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