Added another quality-controller, many small fixes.
[fic.git] / interfaces.h
blob46a36745a5f004650363a15505270ffe7458bba6
1 #ifndef INTERFACES_HEADER_
2 #define INTERFACES_HEADER_
4 #include "modules.h"
5 #include "matrixUtil.h"
7 /* Forwards for interfaces */
8 struct IRoot;
9 struct IQuality2SE;
10 struct IColorTransformer;
11 struct IShapeTransformer;
12 struct ISquareEncoder;
13 struct ISquareRanges;
14 struct ISquareDomains;
15 struct IStdEncPredictor;
16 struct IIntCodec;
18 /** Contains basic types frequently used in modules */
19 namespace MTypes {
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;
33 namespace NOSPACE {
34 using namespace std;
35 using namespace MTypes;
40 /** \defgroup interfaces Interfaces for coding modules
41 * @{ */
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 */
47 enum Mode {
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 */
62 virtual bool encode
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);
88 }; // IRoot interface
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. */
115 struct Plane {
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
195 /// @}
198 namespace MTypes {
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 */
212 bool isReady() const
213 { return this && ranges && domains && encoder && pixels.isValid(); }
214 }; // PlaneBlock struct
218 /** \addtogroup interfaces
219 * @{ */
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) */
226 struct RangeNode;
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 virtual void encode(const PlaneBlock &toEncode) =0;
233 /** Returns a reference to the current range-block list */
234 virtual const RangeList& getRangeList() const =0;
236 /** Write all settings needed for reconstruction */
237 virtual void writeSettings(std::ostream &file) =0;
238 /** Read all settings needed for reconstruction */
239 virtual void readSettings(std::istream &file) =0;
241 /** Writes data needed for reconstruction (except for settings) */
242 virtual void writeData(std::ostream &file) =0;
243 /** Reads data from a stream and reconstructs the positions of range blocks.
244 * \param file the stream to read from
245 * \param block contains the properties of the block to be reconstructed */
246 virtual void readData_buildRanges( std::istream &file, const PlaneBlock &block ) =0;
247 }; // ISquareRanges interface
249 struct ISquareRanges::RangeNode: public Block {
250 /** A common base type for data stored by encoders */
251 struct EncoderData {
252 float bestSE; ///< the best square error found until now
255 /// Encoders can store their data here, !not deleted! (use BulkAllocator)
256 mutable EncoderData *encoderData;
257 /// The smallest integer such that the block fits into square with side of length 2^level
258 int level;
260 /** Checks whether the block has regular shape (dimensions equal to 2^level) */
261 bool isRegular() const
262 { return width()==powers[level] && height()==powers[level]; }
263 protected:
264 /** Constructor - initializes ::encoderData to zero, to be used by derived classes */
265 RangeNode(const Block &block,int level_)
266 : Block(block), encoderData(0), level(level_) {}
267 }; // ISquareRanges::RangeNode struct
272 /** Interface for modules deciding what will square domain blocks look like */
273 struct ISquareDomains: public Interface<ISquareDomains> {
274 /** Describes one domain pool */
275 struct Pool;
276 /** List of pools */
277 typedef std::vector<Pool> PoolList;
279 /** Initializes the pools for given PlaneBlock, assumes settings are OK */
280 virtual void initPools(const PlaneBlock &planeBlock) =0;
281 /** Prepares domains in already initialized pools (and fills summers, etc.\ ) */
282 virtual void fillPixelsInPools(PlaneBlock &planeBlock) =0;
284 /** Returns a reference to internal list of domain pools */
285 virtual const PoolList& getPools() const =0;
286 /** Gets densities for all domain pools on a particular level (with size 2^level - zoomed),
287 * returns unzoomed densities */
288 virtual std::vector<short> getLevelDensities(int level,int stdDomCountLog2) =0;
290 /** Writes all data needed for reconstruction that don't depend on the input (=settings) */
291 virtual void writeSettings(std::ostream &file) =0;
292 /** Reads all settings (like ::writeSettings) */
293 virtual void readSettings(std::istream &file) =0;
295 /** Writes all input-dependent data */
296 virtual void writeData(std::ostream &file) =0;
297 /** Reads all data, assumes the settings have already been read */
298 virtual void readData(std::istream &file) =0;
299 }; // ISquareDomains interface
301 struct ISquareDomains::Pool: public SummedPixels {
302 char type /// The pool-type identifier (like diamond, module-specific)
303 , level; ///< The count of down-scaling steps (1 for basic domains)
304 float contrFactor; ///< The contractive factor (0,1) - the quotient of areas
306 /** Constructor allocating the parent SummedPixels with correct dimensions
307 * (increased according to \p zoom) */
308 Pool(short width_,short height_,char type_,char level_,float cFactor,short zoom)
309 : type(type_), level(level_), contrFactor(cFactor)
310 { setSize( lShift(width_,zoom), lShift(height_,zoom) ); }
316 /** Interface for square encoders - maintaining mappings from square domains to square ranges */
317 struct ISquareEncoder: public Interface<ISquareEncoder> {
318 typedef IColorTransformer::Plane Plane;
319 typedef ISquareRanges::RangeNode RangeNode;
321 /** Used by encoders, represents information about a domain pool on a level */
322 struct LevelPoolInfo {
323 int indexBegin /// the beginning of domain indices in "this pool" on "this level"
324 , density; ///< the domain density (step size) in "this pool" on "this level"
326 /* TODO */
327 typedef std::vector< std::vector<LevelPoolInfo> > LevelPoolInfos;
329 /** Initializes the module for encoding or decoding of a PlaneBlock */
330 virtual void initialize( IRoot::Mode mode, PlaneBlock &planeBlock ) =0;
331 /** Finds mapping with the best square error for a range (returns the SE),
332 * data neccessary for decoding are stored in RangeNode.encoderData */
333 virtual float findBestSE(const RangeNode &range,bool allowHigherSE=false) =0;
334 /** Finishes encoding - to be ready for saving or decoding (can do some cleanup) */
335 virtual void finishEncoding() =0;
336 /** Performs a decoding action */
337 virtual void decodeAct( DecodeAct action, int count=1 ) =0;
339 /** Write all settings needed for reconstruction (don't depend on encoded thing) */
340 virtual void writeSettings(std::ostream &file) =0;
341 /** Read all settings, opposite to ::writeSettings */
342 virtual void readSettings(std::istream &file) =0;
344 /** Returns the number of phases (progressive encoding), only depends on settings */
345 virtual int phaseCount() const =0;
346 /** Write one phase of data needed for reconstruction (excluding settings) */
347 virtual void writeData(std::ostream &file,int phase) =0;
348 /** Reads one phase of data needed for recostruction,
349 * assumes the settings have been read previously via ::readSettings */
350 virtual void readData(std::istream &file,int phase) =0;
351 }; // ISquareEncoder interface
356 /** Interface for domain-range mapping predictors for MStandardEncoder */
357 struct IStdEncPredictor: public Interface<IStdEncPredictor> {
358 /** Contains information about one predicted domain block */
359 struct Prediction {
360 explicit Prediction( int domainID_=-1, char rotation_=-1 )
361 : domainID(domainID_), rotation(rotation_) {}
363 int domainID; ///< domain's identification number
364 char rotation; ///< the rotation of the domain
366 /** List of predictions (later often reffered to as a chunk) */
367 typedef std::vector<Prediction> Predictions;
369 /** %Interface for objects that predict domains for a concrete range block */
370 class IOneRangePredictor {
371 public:
372 /** Virtual destructor needed for safe deletion of derived classes */
373 virtual ~IOneRangePredictor() {}
374 /** Makes several predictions at once, returns \p store reference */
375 virtual Predictions& getChunk(float maxPredictedSE,Predictions &store) =0;
378 /** Holds plenty precomputed information about the range block to be predicted for */
379 struct NewPredictorData;
381 /** Creates a predictor (passing the ownership) for a range block */
382 virtual IOneRangePredictor* newPredictor(const NewPredictorData &data) =0;
383 /** Releases common resources (called when encoding is complete) */
384 virtual void cleanUp() =0;
385 }; // IStdEncPredictor interface
387 struct IStdEncPredictor::NewPredictorData {
388 const ISquareRanges::RangeNode *rangeBlock; ///< Pointer to the range block
389 CSMatrix rangePixels; ///< Pointer to range's pixels
390 const ISquareDomains::PoolList *pools; ///< Pointer to the domain pools
391 const ISquareEncoder::LevelPoolInfos::value_type *poolInfos;
392 ///< Pointer to LevelPoolInfos for all pools (for this level)
394 bool allowRotations /// Are rotations allowed?
395 , quantError /// Should quantization errors be taken into account?
396 , allowInversion /// Are mappings with negative linear coefficients allowed?
397 , isRegular; ///< Is this range block regular? (see RangeNode::isRegular)
399 Real maxLinCoeff2 /// The maximum linear coefficient squared (or <0 if none)
400 , bigScaleCoeff; ///< The coefficient of big-scaling penalization
402 Real rSum /// The sum of range block's all pixels
403 , r2Sum /// The sum of squares of range block's pixels
404 , pixCount /// The number of range block's pixels
405 , rnDev2 /// Precomputed = ( ::pixCount*::r2Sum - sqr(::rSum) )
406 , rnDev /// Precomputed = sqrt(::rnDev2)
407 , qrAvg /// The average of range's pixels rounded by the selected quantizer
408 , qrDev /// ::rnDev rounded by the selected quantizer
409 , qrDev2; ///< sqr(::qrDev)
410 #ifndef NDEBUG
411 NewPredictorData()
412 : rangeBlock(0), rangePixels(), pools(0), poolInfos(0) {}
413 #endif
414 }; // NewPredictorData struct
419 /** Integer sequences (de)coder interface */
420 struct IIntCodec: public Interface<IIntCodec> {
421 /** Sets the number of possible symbols to work with from now on data: [0..possib-1] */
422 virtual void setPossibilities(int possib) =0;
423 /** Codes data and sends them into a stream */
424 virtual void encode(std::vector<int> &data,std::ostream &file) =0;
425 /** Reads \c count symbols from \c file, decodes them and fills in \c data */
426 virtual void decode(std::istream &file,int count,std::vector<int> &data) =0;
428 /** Write all settings needed (doesn't include possibilities set) */
429 virtual void writeSettings(std::ostream &file) =0;
430 /** Read all settings needed (doesn't include possibilities set) */
431 virtual void readSettings(std::istream &file) =0;
434 /// @} - interfaces defgroup
436 #endif // INTERFACES_HEADER_