source: trunk/libdjvu/IW44Image.h @ 206

Last change on this file since 206 was 206, checked in by Eugene Romanenko, 14 years ago

DJVU plugin: djvulibre updated to version 3.5.19

File size: 32.2 KB
Line 
1//C-  -*- C++ -*-
2//C- -------------------------------------------------------------------
3//C- DjVuLibre-3.5
4//C- Copyright (c) 2002  Leon Bottou and Yann Le Cun.
5//C- Copyright (c) 2001  AT&T
6//C-
7//C- This software is subject to, and may be distributed under, the
8//C- GNU General Public License, either Version 2 of the license,
9//C- or (at your option) any later version. The license should have
10//C- accompanied the software or you may obtain a copy of the license
11//C- from the Free Software Foundation at http://www.fsf.org .
12//C-
13//C- This program is distributed in the hope that it will be useful,
14//C- but WITHOUT ANY WARRANTY; without even the implied warranty of
15//C- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16//C- GNU General Public License for more details.
17//C-
18//C- DjVuLibre-3.5 is derived from the DjVu(r) Reference Library from
19//C- Lizardtech Software.  Lizardtech Software has authorized us to
20//C- replace the original DjVu(r) Reference Library notice by the following
21//C- text (see doc/lizard2002.djvu and doc/lizardtech2007.djvu):
22//C-
23//C-  ------------------------------------------------------------------
24//C- | DjVu (r) Reference Library (v. 3.5)
25//C- | Copyright (c) 1999-2001 LizardTech, Inc. All Rights Reserved.
26//C- | The DjVu Reference Library is protected by U.S. Pat. No.
27//C- | 6,058,214 and patents pending.
28//C- |
29//C- | This software is subject to, and may be distributed under, the
30//C- | GNU General Public License, either Version 2 of the license,
31//C- | or (at your option) any later version. The license should have
32//C- | accompanied the software or you may obtain a copy of the license
33//C- | from the Free Software Foundation at http://www.fsf.org .
34//C- |
35//C- | The computer code originally released by LizardTech under this
36//C- | license and unmodified by other parties is deemed "the LIZARDTECH
37//C- | ORIGINAL CODE."  Subject to any third party intellectual property
38//C- | claims, LizardTech grants recipient a worldwide, royalty-free,
39//C- | non-exclusive license to make, use, sell, or otherwise dispose of
40//C- | the LIZARDTECH ORIGINAL CODE or of programs derived from the
41//C- | LIZARDTECH ORIGINAL CODE in compliance with the terms of the GNU
42//C- | General Public License.   This grant only confers the right to
43//C- | infringe patent claims underlying the LIZARDTECH ORIGINAL CODE to
44//C- | the extent such infringement is reasonably necessary to enable
45//C- | recipient to make, have made, practice, sell, or otherwise dispose
46//C- | of the LIZARDTECH ORIGINAL CODE (or portions thereof) and not to
47//C- | any greater extent that may be necessary to utilize further
48//C- | modifications or combinations.
49//C- |
50//C- | The LIZARDTECH ORIGINAL CODE is provided "AS IS" WITHOUT WARRANTY
51//C- | OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
52//C- | TO ANY WARRANTY OF NON-INFRINGEMENT, OR ANY IMPLIED WARRANTY OF
53//C- | MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
54//C- +------------------------------------------------------------------
55//
56// $Id: IW44Image.h,v 1.12 2007/03/25 20:48:32 leonb Exp $
57// $Name: release_3_5_19 $
58
59#ifndef IW44IMAGE_H_
60#define IW44IMAGE_H_
61#ifdef HAVE_CONFIG_H
62#include "config.h"
63#endif
64#if NEED_GNUG_PRAGMAS
65# pragma interface
66#endif
67
68
69/** @name IW44Image.h
70
71    Files #"IW44Image.h"# and #"IW44Image.cpp"# implement the DjVu IW44 wavelet
72    scheme for the compression of gray-level images (see class \Ref{IWBitmap})
73    and color images (see class \Ref{IWPixmap}).  Programs \Ref{c44} and
74    \Ref{d44} demonstrate how to encode and decode IW44 files.
75
76    {\bf IW44 File Structure} --- The IW44 files are structured according to
77    the EA IFF85 specifications (see \Ref{IFFByteStream.h}).  Gray level IW44
78    Images consist of a single #"FORM:BM44"# chunk composed of an arbitrary
79    number of #"BM44"# data chunks.  Color IW44 Images consist of a single
80    #"FORM:PM44"# chunk composed of an arbitrary number of #"PM44"# data
81    chunks.  The successive #"PM44"# or #"BM44"# data chunks contain
82    successive refinements of the encoded image.  Each chunk contains a
83    certain number of ``data slices''.  The first chunk also contains a small
84    image header.  You can use program \Ref{djvuinfo} to display all this
85    structural information:
86    \begin{verbatim}
87    % djvuinfo lag.iw4
88    lag.iw4:
89      FORM:PM44 [62598]
90        PM44 [10807]              #1 - 74 slices - v1.2 (color) - 684x510
91        PM44 [23583]              #2 - 13 slices
92        PM44 [28178]              #3 - 10 slices
93    \end{verbatim}
94
95    {\bf Embedded IW44 Images} --- These IW44 data chunks can also appear within
96    other contexts.  Files representing a DjVu page, for instance, consist of
97    a single #"FORM:DJVU"# composite chunk.  This composite chunk may contain
98    #"BG44"# chunks encoding the background layer and #"FG44"# chunks encoding
99    the foreground color layer.  These #"BG44"# and #"FG44"# chunks are
100    actually regular IW44 data chunks with a different chunk identifier.  This
101    information too can be displayed using program \Ref{djvuinfo}.
102    \begin{verbatim}
103    % djvuinfo graham1.djvu
104    graham1.djvu:
105      FORM:DJVU [32553]
106        INFO [5]            3156x2325, version 17
107        Sjbz [17692]
108        BG44 [2570]         #1 - 74 slices - v1.2 (color) - 1052x775
109        FG44 [1035]         #1 - 100 slices - v1.2 (color) - 263x194
110        BG44 [3048]         #2 - 10 slices
111        BG44 [894]          #3 - 4 slices
112        BG44 [7247]         #4 - 9 slices
113    \end{verbatim}
114
115    {\bf Performance} --- The main design objective for the DjVu wavelets
116    consisted of allowing progressive rendering and smooth scrolling of large
117    images with limited memory requirements.  Decoding functions process the
118    compressed data and update a memory efficient representation of the
119    wavelet coefficients.  Imaging function then can quickly render an
120    arbitrary segment of the image using the available data.  Both process can
121    be carried out in two threads of execution.  This design plays an
122    important role in the DjVu system.  We have investigated various
123    state-of-the-art wavelet compression schemes: although these schemes may
124    achieve slightly smaller file sizes, the decoding functions did not even
125    approach our requirements. 
126
127    The IW44 wavelets satisfy these requirements today. It performs very well
128    for quality settings resulting in high compression ratios.  It should not
129    be used for quasi-lossless compression because certain design choices
130    deliberately sacrifice the IW44 quasi-lossless performance in order to
131    improve the image quality at high compression ratios.
132
133    Little care however has been taken to make the IW44 encoder memory
134    efficient.  This code uses two copies of the wavelet coefficient data
135    structure (one for the raw coefficients, one for the quantized
136    coefficients).  A more sophisticated implementation should considerably
137    reduce the memory requirements.
138
139    {\bf Masking} --- When we create a DjVu image, we often know that certain
140    pixels of the background image are going to be covered by foreground
141    objects like text or drawings.  The DjVu IW44 wavelet decomposition
142    routine can use an optional bilevel image named the mask.  Every non zero
143    pixel in the mask means the value of the corresponding pixel in the
144    background image is irrelevant.  The wavelet decomposition code will
145    replace these masked pixels by a color value whose coding cost is minimal
146    (see \URL{http://www.research.att.com/~leonb/DJVU/mask}).
147
148    {\bf ToDo} --- There are many improvements to be made.  Besides better
149    quantization algorithms (such as trellis quantization and bitrate
150    allocation), we should allow for more wavelet transforms.  These
151    improvements may be implemented in future version, if (and only if) they
152    can meet our decoding constraints.  Future versions will probably split
153    file #"IW44Image.cpp"# which currently contains everything.
154 
155    @memo
156    Wavelet encoded images.
157    @author
158    L\'eon Bottou <leonb@research.att.com>
159
160// From: Leon Bottou, 1/31/2002
161// Lizardtech has split the corresponding cpp file into a decoder and an encoder.
162// Only superficial changes.  The meat is mine.
163
164    @version
165    #$Id: IW44Image.h,v 1.12 2007/03/25 20:48:32 leonb Exp $# */
166//@{
167
168
169#include "GSmartPointer.h"
170#include "ZPCodec.h"
171
172
173#ifdef HAVE_NAMESPACES
174namespace DJVU {
175# ifdef NOT_DEFINED // Just to fool emacs c++ mode
176}
177#endif
178#endif
179
180class GRect;
181class IFFByteStream;
182class ByteStream;
183class GBitmap;
184class GPixmap;
185
186
187
188/** IW44 encoding parameters. 
189    This data structure gathers the quality specification parameters needed
190    for encoding each chunk of an IW44 file.  Chunk data is generated until
191    meeting either the slice target, the size target or the decibel target.  */
192
193struct IWEncoderParms
194{
195  /** Slice target.  Data generation for the current chunk stops if the total
196      number of slices (in this chunk and all the previous chunks) reaches
197      value #slice#.  The default value #0# has a special meaning: data will
198      be generated regardless of the number of slices in the file. */
199  int    slices;
200  /** Size target.  Data generation for the current chunk stops if the total
201      data size (in this chunk and all the previous chunks), expressed in
202      bytes, reaches value #size#.  The default value #0# has a special
203      meaning: data will be generated regardless of the file size. */
204  int    bytes;
205  /** Decibel target.  Data generation for the current chunk stops if the
206      estimated luminance error, expressed in decibels, reaches value
207      #decibel#.  The default value #0# has a special meaning: data will be
208      generated regardless of the estimated luminance error.  Specifying value
209      #0# in fact shortcuts the computation of the estimated luminance error
210      and sensibly speeds up the encoding process.  */
211  float  decibels;
212  /** Constructor. Initializes the structure with the default values. */
213  IWEncoderParms(void);
214};
215
216
217
218/** IW44 encoded gray-level and color images.  This class acts as a base for
219    images represented as a collection of IW44 wavelet coefficients.  The
220    coefficients are stored in a memory efficient data structure.  Member
221    function \Ref{get_bitmap} renders an arbitrary segment of the image into
222    a \Ref{GBitmap}.  Member functions \Ref{decode_iff} and \Ref{encode_iff}
223    read and write DjVu IW44 files (see \Ref{IW44Image.h}).  Both the copy
224    constructor and the copy operator are declared as private members. It is
225    therefore not possible to make multiple copies of instances of this
226    class. */
227
228class IW44Image : public GPEnabled
229{
230public:
231  /** Chrominance processing selector.  The following constants may be used as
232      argument to the following \Ref{IWPixmap} constructor to indicate how the
233      chrominance information should be processed. There are four possible values:
234      \begin{description}
235      \item[CRCBnone:] The wavelet transform will discard the chrominance
236           information and only keep the luminance. The image will show in shades of gray.
237      \item[CRCBhalf:] The wavelet transform will process the chrominance at only
238           half the image resolution. This option creates smaller files but may create
239           artifacts in highly colored images.
240      \item[CRCBnormal:] The wavelet transform will process the chrominance at full
241           resolution. This is the default.
242      \item[CRCBfull:] The wavelet transform will process the chrominance at full
243           resolution. This option also disables the chrominance encoding delay
244           (see \Ref{parm_crcbdelay}) which usually reduces the bitrate associated with the
245           chrominance information.
246      \end{description} */
247  enum CRCBMode { 
248    CRCBnone, 
249    CRCBhalf, 
250    CRCBnormal, 
251    CRCBfull };
252  class Transform;
253  class Map;
254  class Block;
255  class Codec;
256  struct Alloc;
257  struct PrimaryHeader;
258  struct SecondaryHeader;
259  struct TertiaryHeader;
260  enum ImageType {
261    GRAY=false,
262    COLOR=true };
263protected:
264  IW44Image(void);
265public:
266  /** Null constructor.  Constructs an empty IW44Image object. This object does
267      not contain anything meaningful. You must call function \Ref{init},
268      \Ref{decode_iff} or \Ref{decode_chunk} to populate the wavelet
269      coefficient data structure. You may not use \Ref{encode_iff} or
270      \Ref{encode_chunk}. */
271  static GP<IW44Image> create_decode(const ImageType itype=COLOR);
272  /** Null constructor.  Constructs an empty IW44Image object. This object does
273      not contain anything meaningful. You must call function \Ref{init},
274      \Ref{decode_iff} or \Ref{decode_chunk} to populate the wavelet
275      coefficient data structure.  You may then use \Ref{encode_iff}
276      and \Ref{encode_chunk}. */
277  static GP<IW44Image> create_encode(const ImageType itype=COLOR);
278  // virtual destructor
279  virtual ~IW44Image();
280  /** Initializes an IWBitmap with image #bm#.  This constructor
281      performs the wavelet decomposition of image #bm# and records the
282      corresponding wavelet coefficient.  Argument #mask# is an optional
283      bilevel image specifying the masked pixels (see \Ref{IW44Image.h}). */
284  static GP<IW44Image> create_encode(const GBitmap &bm, const GP<GBitmap> mask=0);
285  /** Initializes an IWPixmap with color image #bm#.  This constructor
286      performs the wavelet decomposition of image #bm# and records the
287      corresponding wavelet coefficient.  Argument #mask# is an optional
288      bilevel image specifying the masked pixels (see \Ref{IW44Image.h}).
289      Argument #crcbmode# specifies how the chrominance information should be
290      encoded (see \Ref{CRCBMode}). */
291  static GP<IW44Image> create_encode(const GPixmap &bm, const GP<GBitmap> mask=0, CRCBMode crcbmode=CRCBnormal);
292  // ACCESS
293  /** Returns the width of the IWBitmap image. */
294  int get_width(void) const;
295  /** Returns the height of the IWBitmap image. */
296  int get_height(void) const;
297  /** Reconstructs the complete image.  The reconstructed image
298      is then returned as a GBitmap object. */
299  virtual GP<GBitmap> get_bitmap(void) {return 0;}
300  /** Reconstructs a segment of the image at a given scale.  The subsampling
301      ratio #subsample# must be a power of two between #1# and #32#.  Argument
302      #rect# specifies which segment of the subsampled image should be
303      reconstructed.  The reconstructed image is returned as a GBitmap object
304      whose size is equal to the size of the rectangle #rect#. */
305  virtual GP<GBitmap> get_bitmap(int subsample, const GRect &rect) {return 0;}
306  /** Reconstructs the complete image.  The reconstructed image
307      is then returned as a GPixmap object. */
308  virtual GP<GPixmap> get_pixmap(void) {return 0;}
309  /** Reconstructs a segment of the image at a given scale.  The subsampling
310      ratio #subsample# must be a power of two between #1# and #32#.  Argument
311      #rect# specifies which segment of the subsampled image should be
312      reconstructed.  The reconstructed image is returned as a GPixmap object
313      whose size is equal to the size of the rectangle #rect#. */
314  virtual GP<GPixmap> get_pixmap(int subsample, const GRect &rect) {return 0;}
315  /** Returns the amount of memory used by the wavelet coefficients.  This
316      amount of memory is expressed in bytes. */
317  virtual unsigned int get_memory_usage(void) const = 0;
318  /** Returns the filling ratio of the internal data structure.  Wavelet
319      coefficients are stored in a sparse array.  This function tells what
320      percentage of bins have been effectively allocated. */
321  virtual int get_percent_memory(void) const = 0;
322  // CODER
323  /** Encodes one data chunk into ByteStream #bs#.  Parameter #parms# controls
324      how much data is generated.  The chunk data is written to ByteStream
325      #bs# with no IFF header.  Successive calls to #encode_chunk# encode
326      successive chunks.  You must call #close_codec# after encoding the last
327      chunk of a file. */
328  virtual int  encode_chunk(GP<ByteStream> gbs, const IWEncoderParms &parms);
329  /** Writes a gray level image into DjVu IW44 file.  This function creates a
330      composite chunk (identifier #FORM:BM44# or #FORM:PM44#) composed of
331      #nchunks# chunks (identifier #BM44# or #PM44#).  Data for each chunk is
332      generated with #encode_chunk# using the corresponding parameters in
333      array #parms#. */
334  virtual void encode_iff(IFFByteStream &iff, int nchunks, const IWEncoderParms *parms);
335  // DECODER
336  /** Decodes one data chunk from ByteStream #bs#.  Successive calls to
337      #decode_chunk# decode successive chunks.  You must call #close_codec#
338      after decoding the last chunk of a file.  Note that function
339      #get_bitmap# and #decode_chunk# may be called simultaneously from two
340      execution threads. */
341  virtual int  decode_chunk(GP<ByteStream> gbs) = 0;
342  /** This function enters a composite chunk (identifier #FORM:BM44#, or
343      #FORM:PM44#), and decodes a maximum of #maxchunks# data chunks
344      (identifier #BM44#).  Data for each chunk is processed using the
345      function #decode_chunk#. */
346  virtual void decode_iff(IFFByteStream &iff, int maxchunks=999) = 0;
347  // MISCELLANEOUS
348  /** Resets the encoder/decoder state.  The first call to #decode_chunk# or
349      #encode_chunk# initializes the coder for encoding or decoding.  Function
350      #close_codec# must be called after processing the last chunk in order to
351      reset the coder and release the associated memory. */
352  virtual void close_codec(void) = 0;
353  /** Returns the chunk serial number.  This function returns the serial
354      number of the last chunk encoded with #encode_chunk# or decoded with
355      #decode_chunk#. The first chunk always has serial number #1#. Successive
356      chunks have increasing serial numbers.  Value #0# is returned if this
357      function is called before calling #encode_chunk# or #decode_chunk# or
358      after calling #close_codec#. */
359  virtual int get_serial(void) = 0;
360  /** Sets the chrominance delay parameter.  This function can be called
361      before encoding the first color IW44 data chunk.  Parameter #parm# is an
362      encoding delay which reduces the bitrate associated with the
363      chrominance information. The default chrominance encoding delay is 10. */
364  virtual int  parm_crcbdelay(const int parm) {return parm;}
365  /** Sets the #dbfrac# parameter.  This function can be called before
366      encoding the first IW44 data chunk.  Parameter #frac# modifies the
367      decibel estimation algorithm in such a way that the decibel target only
368      pertains to the average error of the fraction #frac# of the most
369      misrepresented 32x32 pixel blocks.  Setting arguments #frac# to #1.0#
370      restores the normal behavior.  */
371  virtual void parm_dbfrac(float frac) = 0;
372protected:
373  // Parameter
374  float db_frac;
375  // Data
376  Map *ymap, *cbmap, *crmap;
377  int cslice;
378  int cserial;
379  int cbytes;
380private:
381  // Disable assignment semantic
382  IW44Image(const IW44Image &ref);
383  IW44Image& operator=(const IW44Image &ref);
384};
385
386#ifdef IW44IMAGE_IMPLIMENTATION
387
388/*x IW44 encoded gray-level image.  This class provided functions for managing
389    a gray level image represented as a collection of IW44 wavelet
390    coefficients.  The coefficients are stored in a memory efficient data
391    structure.  Member function \Ref{get_bitmap} renders an arbitrary segment
392    of the image into a \Ref{GBitmap}.  Member functions \Ref{decode_iff} and
393    \Ref{encode_iff} read and write DjVu IW44 files (see \Ref{IW44Image.h}).
394    Both the copy constructor and the copy operator are declared as private
395    members. It is therefore not possible to make multiple copies of instances
396    of this class. */
397
398class IWBitmap : public IW44Image
399{
400public:
401  friend class IW44Image;
402  class Encode;
403protected:
404  /*x Null constructor.  Constructs an empty IWBitmap object. This object does
405      not contain anything meaningful. You must call function \Ref{init},
406      \Ref{decode_iff} or \Ref{decode_chunk} to populate the wavelet
407      coefficient data structure. */
408  IWBitmap(void);
409public:
410  //x virtual destructor
411  virtual ~IWBitmap();
412  //x ACCESS
413  /*x Reconstructs the complete image.  The reconstructed image
414      is then returned as a GBitmap object. */
415  virtual GP<GBitmap> get_bitmap(void);
416  /*x Reconstructs a segment of the image at a given scale.  The subsampling
417      ratio #subsample# must be a power of two between #1# and #32#.  Argument
418      #rect# specifies which segment of the subsampled image should be
419      reconstructed.  The reconstructed image is returned as a GBitmap object
420      whose size is equal to the size of the rectangle #rect#. */
421  virtual GP<GBitmap> get_bitmap(int subsample, const GRect &rect);
422  /*x Returns the amount of memory used by the wavelet coefficients.  This
423      amount of memory is expressed in bytes. */
424  virtual unsigned int get_memory_usage(void) const;
425  /*x Returns the filling ratio of the internal data structure.  Wavelet
426      coefficients are stored in a sparse array.  This function tells what
427      percentage of bins have been effectively allocated. */
428  virtual int get_percent_memory(void) const;
429  // DECODER
430  /*x Decodes one data chunk from ByteStream #bs#.  Successive calls to
431      #decode_chunk# decode successive chunks.  You must call #close_codec#
432      after decoding the last chunk of a file.  Note that function
433      #get_bitmap# and #decode_chunk# may be called simultaneously from two
434      execution threads. */
435  virtual int  decode_chunk(GP<ByteStream> gbs);
436  /*x Reads a DjVu IW44 file as a gray level image.  This function enters a
437      composite chunk (identifier #FORM:BM44#), and decodes a maximum of
438      #maxchunks# data chunks (identifier #BM44#).  Data for each chunk is
439      processed using the function #decode_chunk#. */
440  virtual void decode_iff(IFFByteStream &iff, int maxchunks=999);
441  // MISCELLANEOUS
442  /*x Resets the encoder/decoder state.  The first call to #decode_chunk# or
443      #encode_chunk# initializes the coder for encoding or decoding.  Function
444      #close_codec# must be called after processing the last chunk in order to
445      reset the coder and release the associated memory. */
446  virtual void close_codec(void);
447  /*x Returns the chunk serial number.  This function returns the serial
448      number of the last chunk encoded with #encode_chunk# or decoded with
449      #decode_chunk#. The first chunk always has serial number #1#. Successive
450      chunks have increasing serial numbers.  Value #0# is returned if this
451      function is called before calling #encode_chunk# or #decode_chunk# or
452      after calling #close_codec#. */
453  virtual int get_serial(void);
454  /*x Sets the #dbfrac# parameter.  This function can be called before
455      encoding the first IW44 data chunk.  Parameter #frac# modifies the
456      decibel estimation algorithm in such a way that the decibel target only
457      pertains to the average error of the fraction #frac# of the most
458      misrepresented 32x32 pixel blocks.  Setting arguments #frac# to #1.0#
459      restores the normal behavior.  */
460  virtual void parm_dbfrac(float frac);
461private:
462  Codec *ycodec;
463};
464
465
466/*x IW44 encoded color image. This class provided functions for managing a
467    color image represented as a collection of IW44 wavelet coefficients.  The
468    coefficients are stored in a memory efficient data structure.  Member
469    function \Ref{get_pixmap} renders an arbitrary segment of the image into a
470    \Ref{GPixmap}.  Member functions \Ref{decode_iff} and \Ref{encode_iff}
471    read and write DjVu IW44 files (see \Ref{IW44Image.h}).  Both the copy
472    constructor and the copy operator are declared as private members. It is
473    therefore not possible to make multiple copies of instances of this
474    class. */
475
476class IWPixmap : public IW44Image
477{
478public:
479  friend class IW44Image;
480protected:
481  class Encode;
482  /*x Null constructor.  Constructs an empty IWPixmap object. This object does
483      not contain anything meaningful. You must call function \Ref{init},
484      \Ref{decode_iff} or \Ref{decode_chunk} to populate the wavelet
485      coefficient data structure. */
486  IWPixmap(void);
487public:
488  // virtual destructor
489  virtual ~IWPixmap();
490  // ACCESS
491  /*x Reconstructs the complete image.  The reconstructed image
492      is then returned as a GPixmap object. */
493  virtual GP<GPixmap> get_pixmap(void);
494  /*x Reconstructs a segment of the image at a given scale.  The subsampling
495      ratio #subsample# must be a power of two between #1# and #32#.  Argument
496      #rect# specifies which segment of the subsampled image should be
497      reconstructed.  The reconstructed image is returned as a GPixmap object
498      whose size is equal to the size of the rectangle #rect#. */
499  virtual GP<GPixmap> get_pixmap(int subsample, const GRect &rect);
500  /*x Returns the amount of memory used by the wavelet coefficients.  This
501      amount of memory is expressed in bytes. */
502  virtual unsigned int get_memory_usage(void) const;
503  /*x Returns the filling ratio of the internal data structure.  Wavelet
504      coefficients are stored in a sparse array.  This function tells what
505      percentage of bins have been effectively allocated. */
506  virtual int get_percent_memory(void) const;
507  // DECODER
508  /*x Decodes one data chunk from ByteStream #bs#.  Successive calls to
509      #decode_chunk# decode successive chunks.  You must call #close_codec#
510      after decoding the last chunk of a file.  Note that function
511      #get_bitmap# and #decode_chunk# may be called simultaneously from two
512      execution threads. */
513  virtual int  decode_chunk(GP<ByteStream> gbs);
514  /*x Reads a DjVu IW44 file as a color image.  This function enters a
515      composite chunk (identifier #FORM:PM44# or #FORM:BM44#), and decodes a
516      maximum of #maxchunks# data chunks (identifier #PM44# or #BM44#).  Data
517      for each chunk is processed using the function #decode_chunk#. */
518  virtual void decode_iff(IFFByteStream &iff, int maxchunks=999);
519  // MISCELLANEOUS
520  /*x Resets the encoder/decoder state.  The first call to #decode_chunk# or
521      #encode_chunk# initializes the coder for encoding or decoding.  Function
522      #close_codec# must be called after processing the last chunk in order to
523      reset the coder and release the associated memory. */
524  virtual void close_codec(void);
525  /*x Returns the chunk serial number.  This function returns the serial
526      number of the last chunk encoded with #encode_chunk# or decoded with
527      #decode_chunk#. The first chunk always has serial number #1#. Successive
528      chunks have increasing serial numbers.  Value #0# is returned if this
529      function is called before calling #encode_chunk# or #decode_chunk# or
530      after calling #close_codec#. */
531  virtual int  get_serial(void);
532  /*x Sets the chrominance delay parameter.  This function can be called
533      before encoding the first IW44 data chunk.  Parameter #parm# is an
534      encoding delay which reduces the bitrate associated with the
535      chrominance information. The default chrominance encoding delay is 10. */
536  virtual int  parm_crcbdelay(const int parm);
537  /*x Sets the #dbfrac# parameter.  This function can be called before
538      encoding the first IW44 data chunk.  Parameter #frac# modifies the
539      decibel estimation algorithm in such a way that the decibel target only
540      pertains to the average error of the fraction #frac# of the most
541      misrepresented 32x32 pixel blocks.  Setting arguments #frac# to #1.0#
542      restores the normal behavior.  */
543  virtual void parm_dbfrac(float frac);
544protected:
545  // Parameter
546  int   crcb_delay;
547  int   crcb_half;
548  // Data
549private:
550  Codec *ycodec, *cbcodec, *crcodec;
551};
552
553/*x IW44Transform.
554*/
555class IW44Image::Transform
556{
557public:
558  class Decode;
559  class Encode;
560protected:
561  static void filter_begin(int w, int h);
562  static void filter_end(void);
563};
564
565struct GPixel;
566class IW44Image::Transform::Decode : public IW44Image::Transform
567{
568public:
569 // WAVELET TRANSFORM
570  /*x Forward transform. */
571  static void backward(short *p, int w, int h, int rowsize, int begin, int end);
572 
573  // COLOR TRANSFORM
574  /*x Converts YCbCr to RGB. */
575  static void YCbCr_to_RGB(GPixel *p, int w, int h, int rowsize);
576};
577
578//---------------------------------------------------------------
579// *** Class IW44Image::Block [declaration]
580// Represents a block of 32x32 coefficients after zigzagging and scaling
581
582
583class IW44Image::Block // DJVU_CLASS
584{
585public:
586  // creating
587  Block(void);
588  // accessing scaled coefficients
589  short get(int n) const;
590  void  set(int n, int val, IW44Image::Map *map);
591  // converting from liftblock
592  void  read_liftblock(const short *coeff, IW44Image::Map *map);
593  void  write_liftblock(short *coeff, int bmin=0, int bmax=64) const;
594  // sparse array access
595  const short* data(int n) const;
596  short* data(int n, IW44Image::Map *map);
597  void   zero(int n);
598  // sparse representation
599private:
600  short **(pdata[4]);
601};
602
603//---------------------------------------------------------------
604// *** Class IW44Image::Map [declaration]
605// Represents all the blocks of an image
606
607class IW44Image::Map // DJVU_CLASS
608{
609public:
610  class Encode;
611
612  // construction
613  Map(int w, int h);
614  ~Map();
615  // image access
616  void image(signed char *img8, int rowsize, 
617             int pixsep=1, int fast=0);
618  void image(int subsample, const GRect &rect, 
619             signed char *img8, int rowsize, 
620             int pixsep=1, int fast=0);
621  // array of blocks
622  IW44Image::Block *blocks;
623  // geometry
624  int iw, ih;
625  int bw, bh;
626  int nb;
627  // coefficient allocation stuff
628  short *alloc(int n);
629  short **allocp(int n);
630  IW44Image::Alloc *chain;
631  int top;
632  // statistics
633  int get_bucket_count(void) const;
634  unsigned int get_memory_usage(void) const;
635};
636
637//////////////////////////////////////////////////////
638// ENCODING/DECODING WAVELET COEFFICIENTS
639//    USING HIERARCHICAL SET DIFFERENCE
640//////////////////////////////////////////////////////
641
642
643//-----------------------------------------------
644// Class IW44Image::Codec [declaration+implementation]
645// Maintains information shared while encoding or decoding
646
647class IW44Image::Codec
648{
649public:
650  class Decode;
651  class Encode;
652
653protected:
654  // Construction
655  Codec(IW44Image::Map &map);
656public:
657  virtual ~Codec();
658  // Coding
659  int finish_code_slice(ZPCodec &zp);
660  virtual int code_slice(ZPCodec &zp) = 0;
661  // Data
662  IW44Image::Map &map;                  // working map
663  // status
664  int curband;                  // current band
665  int curbit;                   // current bitplane
666  // quantization tables
667  int quant_hi[10];             // quantization for bands 1 to 9
668  int quant_lo[16];             // quantization for band 0.
669  // bucket state
670  char coeffstate[256];
671  char bucketstate[16];
672  enum { ZERO   = 1,            // this coeff never hits this bit
673         ACTIVE = 2,            // this coeff is already active
674         NEW    = 4,            // this coeff is becoming active
675         UNK    = 8 };          // this coeff may become active
676  // coding context
677  BitContext ctxStart [32];
678  BitContext ctxBucket[10][8];
679  BitContext ctxMant;
680  BitContext ctxRoot;
681  // helper
682  int is_null_slice(int bit, int band);
683  int decode_prepare(int fbucket, int nbucket, IW44Image::Block &blk);
684  void decode_buckets(ZPCodec &zp, int bit, int band,
685    IW44Image::Block &blk, int fbucket, int nbucket);
686};
687
688//////////////////////////////////////////////////////
689// DEFINITION OF CHUNK HEADERS
690//////////////////////////////////////////////////////
691
692
693struct IW44Image::PrimaryHeader {
694  unsigned char serial;
695  unsigned char slices;
696  void encode(GP<ByteStream> gbs);
697  void decode(GP<ByteStream> gbs);
698}; 
699
700struct IW44Image::SecondaryHeader {
701  unsigned char major;
702  unsigned char minor;
703  void encode(GP<ByteStream> gbs);
704  void decode(GP<ByteStream> gbs);
705};
706
707struct IW44Image::TertiaryHeader {
708  unsigned char xhi, xlo;
709  unsigned char yhi, ylo;
710  unsigned char crcbdelay;
711  void encode(GP<ByteStream> gbs);
712  void decode(GP<ByteStream> gbs, int major=1, int minor=2);
713};
714
715inline const short* 
716IW44Image::Block::data(int n) const
717{
718  if (! pdata[n>>4])
719    return 0;
720  return pdata[n>>4][n&15];
721}
722
723inline short* 
724IW44Image::Block::data(int n, IW44Image::Map *map)
725{
726  if (! pdata[n>>4])
727    pdata[n>>4] = map->allocp(16);
728  if (! pdata[n>>4][n &15])
729    pdata[n>>4][n &15] = map->alloc(16);
730  return pdata[n>>4][n&15];
731}
732
733inline short 
734IW44Image::Block::get(int n) const
735{
736  int n1 = (n>>4);
737  const short *d = data(n1);
738  if (! d)
739    return 0;
740  return d[n&15];
741}
742
743inline void 
744IW44Image::Block::set(int n, int val, IW44Image::Map *map)
745{
746  int n1 = (n>>4);
747  short* d = data(n1, map);
748  d[n&15] = val;
749}
750
751#endif /* IW44IMAGE_IMPLIMENTATION */
752
753//@}
754
755
756#ifdef HAVE_NAMESPACES
757}
758# ifndef NOT_USING_DJVU_NAMESPACE
759using namespace DJVU;
760# endif
761#endif
762#endif
763
Note: See TracBrowser for help on using the repository browser.