1 #ifndef INTERFACES_HEADER_
2 #define INTERFACES_HEADER_
5 #include "matrixUtil.h"
7 /* Forwards for interfaces */
10 struct IColorTransformer
;
11 struct IShapeTransformer
;
12 struct ISquareEncoder
;
14 struct ISquareDomains
;
15 struct IStdEncPredictor
;
18 /** Contains basic types frequently used in modules */
20 typedef double Real
; ///< The floating-point type in which most computations are made
21 typedef float SReal
; ///< The floating-point type for long-term pixel-value storage
23 typedef MatrixSlice
<SReal
> SMatrix
; ///< Used for storing pixel matrices
24 typedef SMatrix::Const CSMatrix
; ///< Used for passing constant pixels
25 typedef std::vector
<SMatrix
> MatrixList
; ///< A list of pixel matrices
27 enum DecodeAct
{ Clear
, Iterate
}; ///< Possible decoding actions
29 struct PlaneBlock
; // declared and described later in the file
31 typedef SummedMatrix
<Real
,SReal
> SummedPixels
;
35 using namespace MTypes
;
40 /** \defgroup interfaces Interfaces for coding modules
43 /** Interface for root modules (with only one implementation MRoot),
44 * all modules are always owned (either directly or indirectly) by one of this type */
45 struct IRoot
: public Interface
<IRoot
> {
46 /** The root can be in any of these modes */
48 Clear
, ///< no action has been done
49 Encode
, ///< contains an encoded image
50 Decode
///< contains an image decoded from a file
53 static const Uint16 Magic
= 65535-4063 /// magic number - integer identifying FIC files
54 , SettingsMagic
= Magic
^12345; ///< magic number - integer identifying settings files
56 /** A status-query method */
57 virtual Mode
getMode() =0;
58 /** Saves current decoding state into a QImage */
59 virtual QImage
toImage() =0;
61 /** Encodes an image - returns false on exception, getMode() have to be to be Clear */
63 ( const QImage
&toEncode
, const UpdateInfo
&updateInfo
=UpdateInfo::none
) =0;
64 /** Performs a decoding action (e.g.\ clearing, multiple iteration) */
65 virtual void decodeAct( DecodeAct action
, int count
=1 ) =0;
67 /** Saves an encoded image into a stream, returns true on success */
68 virtual bool toStream(std::ostream
&file
) =0;
69 /** Loads image from a file - returns true on success (to be run on in Clear state),
70 * can load in bigger size: dimension == orig_dim*2^\p zoom */
71 virtual bool fromStream(std::istream
&file
,int zoom
=0) =0;
73 /** Shorthand: saves an encoded image to a file - returns true on success */
74 bool toFile(const char *fileName
) {
75 std::ofstream
file( fileName
, ios_base::binary
|ios_base::trunc
|ios_base::out
);
76 return toStream(file
);
78 /** Shorthand: loads image from a file - returns true on success, see ::fromStream */
79 bool fromFile(const char *fileName
,int zoom
=0) {
80 std::ifstream
file( fileName
, ios_base::binary
|ios_base::in
);
81 return fromStream(file
,zoom
);
84 /** Saves all settings to a file (incl.\ child modules), returns true on success */
85 bool allSettingsToFile(const char *fileName
);
86 /** Loads all settings from a file (to be run on a shallow module), returns true on success */
87 bool allSettingsFromFile(const char *fileName
);
93 /** Interface for modules deciding how the max.\ SE will depend on block size
94 * (parametrized by quality) */
95 struct IQuality2SE
: public Interface
<IQuality2SE
> {
96 /** Returns maximum SE for a [0,1] quality and range blocks with pixelCount pixels */
97 virtual float rangeSE(float quality
,int pixelCount
) =0;
98 /** Fills an array (until levelEnd) with SE's according to [0,1] quality
99 * : on i-th index for "complete square range blocks" of level i.
100 * Common implementation - uses ::rangeSE method */
101 void regularRangeErrors(float quality
,int levelEnd
,float *squareErrors
);
107 /** Interface for modules performing color transformations,
108 * following modules always work with single-color (greyscale) images */
109 struct IColorTransformer
: public Interface
<IColorTransformer
> {
110 /** Contains some setings for one color plane of an image */
111 struct PlaneSettings
;
113 /** Represents a one-color image, together with some setttings.
114 * In returned instances the pointed-to memory is always owned by this module. */
116 mutable SMatrix pixels
; ///< a matrix of pixels with values in [0,1]
117 const PlaneSettings
*settings
; ///< the settings for the plane
120 /** List of planes (the pointed-to memory is owned by the module) */
121 typedef std::vector
<Plane
> PlaneList
;
123 /** Splits an image into color-planes and adjusts their settings (from \p prototype).
124 * It should call UpdateInfo::incMaxProgress with the total pixel count. */
125 virtual PlaneList
image2planes(const QImage
&toEncode
,const PlaneSettings
&prototype
) =0;
126 /** Merges planes back into a color image (only useful when decoding) */
127 virtual QImage
planes2image() =0;
129 /** Writes any data needed for plane reconstruction to a stream */
130 virtual void writeData(std::ostream
&file
) =0;
131 /** Reads any data needed for plane reconstruction from a stream and creates the plane list */
132 virtual PlaneList
readData( std::istream
&file
, const PlaneSettings
&prototype
) =0;
133 }; // IColorTransformer interface
135 struct IColorTransformer::PlaneSettings
{
136 int width
/// the width of the image (zoomed)
137 , height
/// the height of the image (zoomed)
138 , domainCountLog2
/// 2-logarithm of the maximum domain count
139 , zoom
; ///< the zoom (dimensions multiplied by 2^zoom)
140 SReal quality
; ///< encoding quality for the plane, in [0,1] (higher is better)
141 IQuality2SE
*moduleQ2SE
; ///< pointer to the module computing maximum SE (never owned)
142 const UpdateInfo
&updateInfo
; ///< structure for communication with user
144 /** A simple constructor, only initializes the values from the parameters */
145 PlaneSettings( int width_
, int height_
, int domainCountLog2_
, int zoom_
146 , SReal quality_
=numeric_limits
<SReal
>::quiet_NaN()
147 , IQuality2SE
*moduleQ2SE_
=0, const UpdateInfo
&updateInfo_
=UpdateInfo::none
)
148 : width(width_
), height(height_
)
149 , domainCountLog2(domainCountLog2_
), zoom(zoom_
)
150 , quality(quality_
), moduleQ2SE(moduleQ2SE_
), updateInfo(updateInfo_
) {}
151 }; // PlaneSettings struct
156 /** Interface for modules handling pixel-shape changes
157 * and/or splitting the single-color planes into independently processed parts */
158 struct IShapeTransformer
: public Interface
<IShapeTransformer
> {
159 typedef IColorTransformer::PlaneList PlaneList
;
161 /** Creates jobs from the list of color planes, returns job count */
162 virtual int createJobs(const PlaneList
&planes
) =0;
163 /** Returns the number of jobs */
164 virtual int jobCount() =0;
166 /** Starts encoding a job - thread-safe (for different jobs) */
167 virtual void jobEncode(int jobIndex
) =0;
168 /** Performs a decoding action for a job - thread-safe (for different jobs) */
169 virtual void jobDecodeAct( int jobIndex
, DecodeAct action
, int count
=1 ) =0;
171 /** Writes all settings (shared by all jobs) needed for later reconstruction */
172 virtual void writeSettings(std::ostream
&file
) =0;
173 /** Reads settings (shared by all jobs) needed for reconstruction from a stream -
174 * needs to be done before the job creation */
175 virtual void readSettings(std::istream
&file
) =0;
177 /** Returns the number of phases (progressive encoding), only depends on settings */
178 virtual int phaseCount() =0;
179 /** Writes any data needed for reconstruction of every job, phase parameters
180 * determine the range of saved phases */
181 virtual void writeJobs(std::ostream
&file
,int phaseBegin
,int phaseEnd
) =0;
182 /** Reads all data needed for reconstruction of every job and prepares for encoding,
183 * parameters like ::writeJobs */
184 virtual void readJobs(std::istream
&file
,int phaseBegin
,int phaseEnd
) =0;
186 /** Shortcut - default parameters "phaseBegin=0,phaseEnd=phaseCount()" */
187 void writeJobs(std::ostream
&file
,int phaseBegin
=0)
188 { writeJobs( file
, phaseBegin
, phaseCount() ); }
189 /** Shortcut - default parameters "phaseBegin=0,phaseEnd=phaseCount()" */
190 void readJobs(std::istream
&file
,int phaseBegin
=0)
191 { readJobs( file
, phaseBegin
, phaseCount() ); }
192 }; // IShapeTransformer interface
199 /** Represents a rectangular piece of single-color image to be encoded/decoded.
200 * It is common structure for ISquare{Range,Domain,Encoder}.
201 * Inherits a pixel-matrix, its dimensions and block-summers and adds
202 * pointers to settings and modules handling square ranges, domains and encoding */
203 struct PlaneBlock
: public SummedPixels
{
204 typedef IColorTransformer::PlaneSettings PlaneSettings
;
206 const PlaneSettings
*settings
; ///< the settings for the plane
207 ISquareRanges
*ranges
; ///< module for range blocks generation
208 ISquareDomains
*domains
;///< module for domain blocks generation
209 ISquareEncoder
*encoder
;///< module for encoding (maintaining domain-range mappings)
211 /** A simple integrity test - needs nonzero modules and pixel-matrix */
213 { return this && ranges
&& domains
&& encoder
&& pixels
.isValid(); }
214 }; // PlaneBlock struct
218 /** \addtogroup interfaces
222 /** Interface for modules that control how the image
223 * will be split into rectangular (mostly square) range blocks */
224 struct ISquareRanges
: public Interface
<ISquareRanges
> {
225 /** Structure representing a rectangular range block (usually square) */
227 /** List of range nodes (pointers) */
228 typedef std::vector
<RangeNode
*> RangeList
;
230 /** Starts encoding, calls modules in the passed structure.
231 * It should update UpdateInfo continually by the count of encoded pixels.
232 * \throws std::exception when cancelled via UpdateInfo or on other errors */
233 virtual void encode(const PlaneBlock
&toEncode
) =0;
234 /** Returns a reference to the current range-block list */
235 virtual const RangeList
& getRangeList() const =0;
237 /** Write all settings needed for reconstruction */
238 virtual void writeSettings(std::ostream
&file
) =0;
239 /** Read all settings needed for reconstruction */
240 virtual void readSettings(std::istream
&file
) =0;
242 /** Writes data needed for reconstruction (except for settings) */
243 virtual void writeData(std::ostream
&file
) =0;
244 /** Reads data from a stream and reconstructs the positions of range blocks.
245 * \param file the stream to read from
246 * \param block contains the properties of the block to be reconstructed */
247 virtual void readData_buildRanges( std::istream
&file
, const PlaneBlock
&block
) =0;
248 }; // ISquareRanges interface
250 struct ISquareRanges::RangeNode
: public Block
{
251 /** A common base type for data stored by encoders */
253 float bestSE
; ///< the best square error found until now
256 /// \todo Encoders can store their data here, !not deleted!
257 mutable EncoderData
*encoderData
;
258 /// The smallest integer such that the block fits into square with side of length 2^level
261 /** Checks whether the block has regular shape (dimensions equal to 2^level) */
262 bool isRegular() const
263 { return width()==powers
[level
] && height()==powers
[level
]; }
265 /** Constructor - initializes ::encoderData to zero, to be used by derived classes */
266 RangeNode(const Block
&block
,int level_
)
267 : Block(block
), encoderData(0), level(level_
) {}
270 { delete encoderData
; }
271 }; // ISquareRanges::RangeNode struct
276 /** Interface for modules deciding what will square domain blocks look like */
277 struct ISquareDomains
: public Interface
<ISquareDomains
> {
278 /** Describes one domain pool */
281 typedef std::vector
<Pool
> PoolList
;
283 /** Initializes the pools for given PlaneBlock, assumes settings are OK */
284 virtual void initPools(const PlaneBlock
&planeBlock
) =0;
285 /** Prepares domains in already initialized pools (and fills summers, etc.\ ) */
286 virtual void fillPixelsInPools(PlaneBlock
&planeBlock
) =0;
288 /** Returns a reference to internal list of domain pools */
289 virtual const PoolList
& getPools() const =0;
290 /** Gets densities for all domain pools on a particular level (with size 2^level - zoomed),
291 * returns unzoomed densities */
292 virtual std::vector
<short> getLevelDensities(int level
,int stdDomCountLog2
) =0;
294 /** Writes all settings (data needed for reconstruction that don't depend on the input) */
295 virtual void writeSettings(std::ostream
&file
) =0;
296 /** Reads all settings (like ::writeSettings) */
297 virtual void readSettings(std::istream
&file
) =0;
299 /** Writes all input-dependent data */
300 virtual void writeData(std::ostream
&file
) =0;
301 /** Reads all data, assumes the settings have already been read */
302 virtual void readData(std::istream
&file
) =0;
303 }; // ISquareDomains interface
305 struct ISquareDomains::Pool
: public SummedPixels
{
306 char type
/// The pool-type identifier (like diamond, module-specific)
307 , level
; ///< The count of down-scaling steps (1 for basic domains)
308 float contrFactor
; ///< The contractive factor (0,1) - the quotient of areas
310 /** Constructor allocating the parent SummedPixels with correct dimensions
311 * (increased according to \p zoom) */
312 Pool(short width_
,short height_
,char type_
,char level_
,float cFactor
,short zoom
)
313 : type(type_
), level(level_
), contrFactor(cFactor
)
314 { setSize( lShift(width_
,zoom
), lShift(height_
,zoom
) ); }
320 /** Interface for square encoders - maintaining mappings from square domains to square ranges */
321 struct ISquareEncoder
: public Interface
<ISquareEncoder
> {
322 typedef IColorTransformer::Plane Plane
;
323 typedef ISquareRanges::RangeNode RangeNode
;
325 /** Used by encoders, represents information about a domain pool on a level */
326 struct LevelPoolInfo
{
327 int indexBegin
/// the beginning of domain indices in "this pool" on "this level"
328 , density
; ///< the domain density (step size) in "this pool" on "this level"
330 /** [level][pool] -> LevelPoolInfo (the levels are zoomed). For every used level
331 * contains for all domain pools precomputed densities and the domain-ID boundaries */
332 typedef std::vector
< std::vector
<LevelPoolInfo
> > LevelPoolInfos
;
334 /** Initializes the module for encoding or decoding of a PlaneBlock */
335 virtual void initialize( IRoot::Mode mode
, PlaneBlock
&planeBlock
) =0;
336 /** Finds mapping with the best square error for a range (returns the SE),
337 * data neccessary for decoding are stored in RangeNode.encoderData */
338 virtual float findBestSE(const RangeNode
&range
,bool allowHigherSE
=false) =0;
339 /** Finishes encoding - to be ready for saving or decoding (can do some cleanup) */
340 virtual void finishEncoding() =0;
341 /** Performs a decoding action */
342 virtual void decodeAct( DecodeAct action
, int count
=1 ) =0;
344 /** Write all settings needed for reconstruction (don't depend on encoded thing) */
345 virtual void writeSettings(std::ostream
&file
) =0;
346 /** Read all settings, opposite to ::writeSettings */
347 virtual void readSettings(std::istream
&file
) =0;
349 /** Returns the number of phases (progressive encoding), only depends on settings */
350 virtual int phaseCount() const =0;
351 /** Write one phase of data needed for reconstruction (excluding settings) */
352 virtual void writeData(std::ostream
&file
,int phase
) =0;
353 /** Reads one phase of data needed for recostruction,
354 * assumes the settings have been read previously via ::readSettings */
355 virtual void readData(std::istream
&file
,int phase
) =0;
356 }; // ISquareEncoder interface
361 /** Interface for domain-range mapping predictors for MStandardEncoder */
362 struct IStdEncPredictor
: public Interface
<IStdEncPredictor
> {
363 /** Contains information about one predicted domain block */
365 explicit Prediction( int domainID_
=-1, char rotation_
=-1 )
366 : domainID(domainID_
), rotation(rotation_
) {}
368 int domainID
; ///< domain's identification number
369 char rotation
; ///< the rotation of the domain
371 /** List of predictions (later often reffered to as a chunk) */
372 typedef std::vector
<Prediction
> Predictions
;
374 /** %Interface for objects that predict domains for a concrete range block */
375 class IOneRangePredictor
{
377 /** Virtual destructor needed for safe deletion of derived classes */
378 virtual ~IOneRangePredictor() {}
379 /** Makes several predictions at once, returns \p store reference */
380 virtual Predictions
& getChunk(float maxPredictedSE
,Predictions
&store
) =0;
383 /** Holds plenty precomputed information about the range block to be predicted for */
384 struct NewPredictorData
;
386 /** Creates a predictor (passing the ownership) for a range block */
387 virtual IOneRangePredictor
* newPredictor(const NewPredictorData
&data
) =0;
388 /** Releases common resources (called when encoding is complete) */
389 virtual void cleanUp() =0;
390 }; // IStdEncPredictor interface
392 struct IStdEncPredictor::NewPredictorData
{
393 const ISquareRanges::RangeNode
*rangeBlock
; ///< Pointer to the range block
394 CSMatrix rangePixels
; ///< Pointer to range's pixels
395 const ISquareDomains::PoolList
*pools
; ///< Pointer to the domain pools
396 const ISquareEncoder::LevelPoolInfos::value_type
*poolInfos
;
397 ///< Pointer to LevelPoolInfos for all pools (for this level)
399 bool allowRotations
/// Are rotations allowed?
400 , quantError
/// Should quantization errors be taken into account?
401 , allowInversion
/// Are mappings with negative linear coefficients allowed?
402 , isRegular
; ///< Is this range block regular? (see RangeNode::isRegular)
404 Real maxLinCoeff2
/// The maximum linear coefficient squared (or <0 if none)
405 , bigScaleCoeff
; ///< The coefficient of big-scaling penalization
407 Real rSum
/// The sum of range block's all pixels
408 , r2Sum
/// The sum of squares of range block's pixels
409 , pixCount
/// The number of range block's pixels
410 , rnDev2
/// Precomputed = ( ::pixCount*::r2Sum - sqr(::rSum) )
411 , rnDev
/// Precomputed = sqrt(::rnDev2)
412 , qrAvg
/// The average of range's pixels rounded by the selected quantizer
413 , qrDev
/// ::rnDev rounded by the selected quantizer
414 , qrDev2
; ///< sqr(::qrDev)
417 : rangeBlock(0), rangePixels(), pools(0), poolInfos(0) {}
419 }; // NewPredictorData struct
424 /** Integer sequences (de)coder interface */
425 struct IIntCodec
: public Interface
<IIntCodec
> {
426 /** Sets the number of possible symbols to work with from now on data: [0;possib-1] */
427 virtual void setPossibilities(int possib
) =0;
428 /** Codes data and sends them into a stream */
429 virtual void encode(std::vector
<int> &data
,std::ostream
&file
) =0;
430 /** Reads \c count symbols from \c file, decodes them and fills in \c data */
431 virtual void decode(std::istream
&file
,int count
,std::vector
<int> &data
) =0;
433 /** Write all settings needed (doesn't include possibilities set) */
434 virtual void writeSettings(std::ostream
&file
) =0;
435 /** Read all settings needed (doesn't include possibilities set) */
436 virtual void readSettings(std::istream
&file
) =0;
439 /// @} - interfaces defgroup
441 #endif // INTERFACES_HEADER_