001/*
002 * $RCSfile: FileCodestreamWriter.java,v $
003 * $Revision: 1.1 $
004 * $Date: 2005/02/11 05:02:02 $
005 * $State: Exp $
006 *
007 * Class:                   FileCodestreamWriter
008 *
009 * Description:             Implementation of the bit stream writer for streams.
010 *
011 *
012 *
013 * COPYRIGHT:
014 *
015 * This software module was originally developed by Raphaël Grosbois and
016 * Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel
017 * Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David
018 * Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research
019 * Centre France S.A) in the course of development of the JPEG2000
020 * standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This
021 * software module is an implementation of a part of the JPEG 2000
022 * Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio
023 * Systems AB and Canon Research Centre France S.A (collectively JJ2000
024 * Partners) agree not to assert against ISO/IEC and users of the JPEG
025 * 2000 Standard (Users) any of their rights under the copyright, not
026 * including other intellectual property rights, for this software module
027 * with respect to the usage by ISO/IEC and Users of this software module
028 * or modifications thereof for use in hardware or software products
029 * claiming conformance to the JPEG 2000 Standard. Those intending to use
030 * this software module in hardware or software products are advised that
031 * their use may infringe existing patents. The original developers of
032 * this software module, JJ2000 Partners and ISO/IEC assume no liability
033 * for use of this software module or modifications thereof. No license
034 * or right to this software module is granted for non JPEG 2000 Standard
035 * conforming products. JJ2000 Partners have full right to use this
036 * software module for his/her own purpose, assign or donate this
037 * software module to any third party and to inhibit third parties from
038 * using this software module for non JPEG 2000 Standard conforming
039 * products. This copyright notice must be included in all copies or
040 * derivative works of this software module.
041 *
042 * Copyright (c) 1999/2000 JJ2000 Partners.
043 * */
044package jj2000.j2k.codestream.writer;
045
046import java.io.BufferedOutputStream;
047import java.io.File;
048import java.io.FileOutputStream;
049import java.io.IOException;
050import java.io.OutputStream;
051
052import jj2000.j2k.codestream.Markers;
053
054/**
055 * This class implements a CodestreamWriter for Java streams. The streams can
056 * be files or network connections, or any other resource that presents itself
057 * as a OutputStream. See the CodestreamWriter abstract class for more details
058 * on the implementation of the CodestreamWriter abstract class.
059 *
060 * <P>Before any packet data is written to the bit stream (even in simulation
061 * mode) the complete header should be written to the HeaderEncoder object
062 * supplied to the constructor, following the procedure explained in the
063 * HeaderEncoder class. Otherwise incorrect estimates are given by
064 * getMaxAvailableBytes() for rate allocation.
065 *
066 * @see CodestreamWriter
067 *
068 * @see HeaderEncoder
069 * */
070public class FileCodestreamWriter extends CodestreamWriter
071    implements Markers {
072
073    /** The upper limit for the value of the Nsop field of the SOP marker */
074    private final static int SOP_MARKER_LIMIT = 65535;
075
076    /** Index of the current tile */
077    private int tileIdx = 0;
078
079    /** The file to write */
080    private OutputStream out;
081
082    /** The number of bytes already written to the bit stream, excluding the
083     * header length, magic number and header length info. */
084    int ndata=0;
085
086    /** The default buffer length, 1024 bytes */
087    public static int DEF_BUF_LEN = 1024;
088
089    /** Array used to store the SOP markers values */
090    byte sopMarker[];
091
092    /** Array used to store the EPH markers values */
093    byte ephMarker[];
094
095    /** The packet index (when start of packet markers i.e. SOP markers) are
096     *  used. */
097    int packetIdx=0;
098
099    /** Offset of end of last packet containing ROI information */
100    private int offLastROIPkt = 0;
101
102    /** Length of last packets containing no ROI information */
103    private int lenLastNoROI = 0;
104
105    /**
106     * Opens the file 'file' for writing the bit stream, using the 'he' header
107     * encoder. The magic number is written to the bit stream. Normally, the
108     * header encoder must be empty (i.e. no data has been written to it
109     * yet). A BufferedOutputStream is used on top of the file to increase
110     * throughput, the length of the buffer is DEF_BUF_LEN.
111     *
112     * @param file The file where to write the bit stream
113     *
114     * @param mb The maximum number of bytes that can be written to the bit
115     * stream.
116     *
117     * @exception IOException If an error occurs while trying to open the file
118     * for writing or while writing the magic number.
119     * */
120    public FileCodestreamWriter(File file, int mb)
121        throws IOException {
122
123        super(mb);
124        out = new BufferedOutputStream(new FileOutputStream(file),DEF_BUF_LEN);
125        initSOP_EPHArrays();
126    }
127
128    /**
129     * Opens the file named 'fname' for writing the bit stream, using the 'he'
130     * header encoder. The magic number is written to the bit
131     * stream. Normally, the header encoder must be empty (i.e. no data has
132     * been written to it yet). A BufferedOutputStream is used on top of the
133     * file to increase throughput, the length of the buffer is DEF_BUF_LEN.
134     *
135     * @param fname The name of file where to write the bit stream
136     *
137     * @param mb The maximum number of bytes that can be written to the bit
138     * stream.
139     *
140     * @param encSpec The encoder's specifications
141     *
142     * @exception IOException If an error occurs while trying to open the file
143     * for writing or while writing the magic number.
144     * */
145    public FileCodestreamWriter(String fname, int mb)
146        throws IOException {
147
148        super(mb);
149        out = new BufferedOutputStream(new FileOutputStream(fname),
150                                       DEF_BUF_LEN);
151        initSOP_EPHArrays();
152    }
153
154    /**
155     * Uses the output stream 'os' for writing the bit stream, using the 'he'
156     * header encoder. The magic number is written to the bit
157     * stream. Normally, the header encoder must be empty (i.e. no data has
158     * been written to it yet). No BufferedOutputStream is used on top of the
159     * output stream 'os'.
160     *
161     * @param os The output stream where to write the bit stream.
162     *
163     * @param mb The maximum number of bytes that can be written to the bit
164     * stream.
165     *
166     * @exception IOException If an error occurs while writing the magic
167     * number to the 'os' output stream.
168     * */
169    public FileCodestreamWriter(OutputStream os, int mb)
170        throws IOException {
171
172        super(mb);
173        out = os;
174        initSOP_EPHArrays();
175    }
176
177    /**
178     * Returns the number of bytes remaining available in the bit stream. This
179     * is the maximum allowed number of bytes minus the number of bytes that
180     * have already been written to the bit stream. If more bytes have been
181     * written to the bit stream than the maximum number of allowed bytes,
182     * then a negative value is returned.
183     *
184     * @return The number of bytes remaining available in the bit stream.
185     * */
186    public final int getMaxAvailableBytes() {
187        return maxBytes-ndata;
188    }
189
190    /**
191     * Returns the current length of the entire bit stream.
192     *
193     * @return the current length of the bit stream
194     * */
195    public int getLength() {
196        if (getMaxAvailableBytes() >= 0) {
197            return ndata;
198        }
199        else {
200            return maxBytes;
201        }
202    }
203
204    /**
205     * Writes a packet head to the bit stream and returns the number of bytes
206     * used by this header. It returns the total number of bytes that the
207     * packet head takes in the bit stream. If in simulation mode then no data
208     * is written to the bit stream but the number of bytes is
209     * calculated. This can be used for iterative rate allocation.
210     *
211     * <P>If the length of the data that is to be written to the bit stream is
212     * more than the space left (as returned by getMaxAvailableBytes()) only
213     * the data that does not exceed the allowed length is written, the rest
214     * is discarded. However the value returned by the method is the total
215     * length of the packet, as if all of it was written to the bit stream.
216     *
217     * <P>If the bit stream header has not been commited yet and 'sim' is
218     * false, then the bit stream header is automatically commited (see
219     * commitBitstreamHeader() method) before writting the packet.
220     *
221     * @param head The packet head data.
222     *
223     * @param hlen The number of bytes in the packet head.
224     *
225     * @param sim Simulation mode flag. If true nothing is written to the bit
226     * stream, but the number of bytes that would be written is returned.
227     *
228     * @param sop Start of packet header marker flag. This flag indicates
229     * whether or not SOP markers should be written. If true, SOP markers
230     * should be written, if false, they should not.
231     *
232     * @param eph End of Packet Header marker flag. This flag indicates
233     * whether or not EPH markers should be written. If true, EPH markers
234     * should be written, if false, they should not.
235     *
236     * @return The number of bytes spent by the packet head.
237     *
238     * @exception IOException If an I/O error occurs while writing to the
239     * output stream.
240     *
241     * @see #commitBitstreamHeader
242     * */
243    public int writePacketHead(byte head[],int hlen,boolean sim,
244                               boolean sop, boolean eph) throws IOException{
245        int len = hlen
246            + (sop?Markers.SOP_LENGTH:0)
247            + (eph?Markers.EPH_LENGTH:0);
248
249        // If not in simulation mode write the data
250        if(!sim){
251            // Write the head bytes
252            if(getMaxAvailableBytes()<len){
253                len = getMaxAvailableBytes();
254            }
255
256            if(len > 0){
257                // Write Start Of Packet header markers if necessary
258                if(sop){
259                    // The first 4 bytes of the array have been filled in the
260                    // classe's constructor.
261                    sopMarker[4] = (byte)(packetIdx>>8);
262                    sopMarker[5] = (byte)(packetIdx);
263                    out.write(sopMarker, 0, Markers.SOP_LENGTH);
264                    packetIdx++;
265                    if(packetIdx>SOP_MARKER_LIMIT){
266                        // Reset SOP value as we have reached its upper limit
267                        packetIdx = 0;
268                    }
269                }
270                out.write(head,0,hlen);
271                // Update data length
272                ndata += len;
273
274                // Write End of Packet Header markers if necessary
275                if(eph){
276                    out.write(ephMarker,0,Markers.EPH_LENGTH);
277                }
278
279                // Deal with ROI Information
280                lenLastNoROI += len;
281            }
282        }
283        return len;
284    }
285
286    /**
287     * Writes a packet body to the bit stream and returns the number of bytes
288     * used by this body .If in simulation mode then no data is written to the
289     * bit stream but the number of bytes is calculated. This can be used for
290     * iterative rate allocation.
291     *
292     * <P>If the length of the data that is to be written to the bit stream is
293     * more than the space left (as returned by getMaxAvailableBytes()) only
294     * the data that does not exceed the allowed length is written, the rest
295     * is discarded. However the value returned by the method is the total
296     * length of the packet body , as if all of it was written to the bit
297     * stream.
298     *
299     * @param body The packet body data.
300     *
301     * @param blen The number of bytes in the packet body.
302     *
303     * @param sim Simulation mode flag. If true nothing is written to the bit
304     * stream, but the number of bytes that would be written is returned.
305     *
306     * @param roiInPkt Whether or not this packet contains ROI information
307     *
308     * @param roiLen Number of byte to read in packet body to get all the ROI
309     * information
310     *
311     * @return The number of bytes spent by the packet body.
312     *
313     * @exception IOException If an I/O error occurs while writing to the
314     * output stream.
315     *
316     * @see #commitBitstreamHeader
317     * */
318    public int writePacketBody(byte body[],int blen,boolean sim,
319                               boolean roiInPkt, int roiLen)
320        throws IOException{
321
322        int len = blen;
323
324        // If not in simulation mode write the data
325        if (!sim) {
326            // Write the body bytes
327            len = blen;
328            if(getMaxAvailableBytes() < len){
329                len = getMaxAvailableBytes();
330            }
331            if(blen > 0){
332                out.write(body,0,len);
333            }
334            // Update data length
335            ndata += len;
336
337            // Deal with ROI information
338            if(roiInPkt) {
339                offLastROIPkt += lenLastNoROI + roiLen;
340                lenLastNoROI = len-roiLen;
341            } else {
342                lenLastNoROI += len;
343            }
344        }
345        return len;
346    }
347
348    /**
349     * Writes the EOC marker and closes the underlying stream.
350     *
351     * @exception IOException If an error occurs while closing the underlying
352     * stream.
353     * */
354    public void close() throws IOException {
355
356        // Write the EOC marker and close the codestream.
357        out.write(EOC>>8);
358        out.write(EOC);
359
360        ndata += 2; // Add two to length of codestream for EOC marker
361
362        out.close();
363    }
364
365    /**
366     * Gives the offset of the end of last packet containing ROI information
367     *
368     * @return End of last ROI packet
369     * */
370    public int getOffLastROIPkt(){
371        return offLastROIPkt;
372    }
373
374    /**
375     * Writes the header data in the codestream and actualize ndata with the
376     * header length. The header is either a MainHeaderEncoder or a
377     * TileHeaderEncoder.
378     *
379     * @param he The current header encoder.
380     *
381     * @exception IOException If an I/O error occurs while writing the data.
382     * */
383    public void commitBitstreamHeader(HeaderEncoder he) throws IOException {
384        // Actualize ndata
385        ndata += he.getLength();
386        he.writeTo(out);         // Write the header
387        // Reset packet index used for SOP markers
388        packetIdx = 0;
389
390        // Deal with ROI information
391        lenLastNoROI += he.getLength();
392    }
393
394    /**
395     * Performs the initialisation of the arrays that are used to store the
396     * values used to write SOP and EPH markers
397     * */
398    private void initSOP_EPHArrays() {
399
400        // Allocate and set first values of SOP marker as they will not be
401        // modified
402        sopMarker = new byte[Markers.SOP_LENGTH];
403        sopMarker[0] = (byte)(Markers.SOP>>8);
404        sopMarker[1] = (byte)Markers.SOP;
405        sopMarker[2] = (byte)0x00;
406        sopMarker[3] = (byte)0x04;
407
408        // Allocate and set values of EPH marker as they will not be
409        // modified
410        ephMarker = new byte[Markers.EPH_LENGTH];
411        ephMarker[0] = (byte)(Markers.EPH>>8);
412        ephMarker[1] = (byte)Markers.EPH;
413    }
414}