HDK
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
IMG_File.h
Go to the documentation of this file.
1 /*
2  * PROPRIETARY INFORMATION. This software is proprietary to
3  * Side Effects Software Inc., and is not to be reproduced,
4  * transmitted, or disclosed in any way without written permission.
5  *
6  * NAME: IMG_File.h ( IMG Library, C++)
7  *
8  * COMMENTS:
9  * Generic interface for loading and saving image files.
10  */
11 
12 #pragma once
13 
14 #ifndef __IMG_File__
15 #define __IMG_File__
16 
17 #include "IMG_API.h"
18 #include "IMG_Error.h"
19 #include "IMG_FileParms.h"
20 #include "IMG_FileTypes.h"
21 #include "IMG_Stat.h"
22 #include "IMG_Metadata.h"
23 
24 #include <PXL/PXL_Forward.h>
25 #include <UT/UT_BitArray.h>
26 #include <UT/UT_Functor.h>
27 #include <UT/UT_Matrix4.h>
28 #include <UT/UT_NonCopyable.h>
29 #include <UT/UT_Rect.h>
30 #include <UT/UT_SharedPtr.h>
31 #include <UT/UT_UniquePtr.h>
32 #include <UT/UT_ValArray.h>
33 #include <SYS/SYS_Deprecated.h>
34 #include <SYS/SYS_Types.h>
35 #include <iosfwd>
36 
37 class IMG_File;
38 class IMG_Metadata;
39 class IMG_Format;
40 class IMG_Plane;
42 class PXL_DeepSampleList;
43 class PXL_Raster;
44 class FS_Reader;
45 class FS_Writer;
46 template <typename T> class UT_Array;
47 class UT_IStream;
48 class UT_Options;
49 class UT_String;
50 class UT_StringHolder;
51 class UT_StringRef;
52 class UT_WorkBuffer;
53 
55 
58 
59 /// @brief Generic interface for reading and writing image files.
60 /// This class handles the reading and writing of all image formats that Houdini
61 /// supports. Use the static open() or create() methods to get an IMG_File
62 /// instance to read to or write from. Deleting this instance will close the
63 /// file.
64 class IMG_API IMG_File
65 {
66 public:
67  virtual ~IMG_File();
68  UT_NON_COPYABLE(IMG_File)
69 
70  virtual int64 getMemoryUsage(bool inclusive) const;
71 
72  // The following methods are a public interface which is not dependent on
73  // the format of the image. Users of the library should use these methods
74  // to do the loading and saving of the data.
75 
76  /// @brief Open an image file using a filename
77  /// Open an image file for reading by specifying the filename and path of
78  /// the file. An optional IMG_FileParms class may be passed to convert it
79  /// into a specific image type (8bit, specific resolution, etc). An optional
80  /// format may also be passed, which forces the library to assume the image
81  /// file is of that particular format.
82  /// This method returns a new IMG_File object which you read the image data
83  /// from, or NULL if an error occurred.
84  static IMG_FilePtr open(const char *filename,
85  const IMG_FileParms *options = nullptr,
86  const IMG_Format *fmt = nullptr);
87 
88  /// @brief Open an image file using a filename
89  /// Open an image file for reading by specifying the filename and path of
90  /// the file. A list of formats is also given, allowing the caller
91  /// customization of the types and order of formats.
92  /// An optional IMG_FileParms class may be passed to convert it
93  /// into a specific image type (8bit, specific resolution, etc).
94  /// This method returns a new IMG_File object which you read the image data
95  /// from, or NULL if an error occurred.
96  static IMG_FilePtr open(const char *filename,
97  const UT_Array<const IMG_Format*> &image_formats,
98  const IMG_FileParms *options = nullptr);
99 
100  /// @brief Open an image file from a stream
101  /// Open an image file for reading given a stream. This is useful for
102  /// embedded images in a file. An optional IMG_FileParms class may be
103  /// passed to convert it into a specific image type (8bit, specific
104  /// resolution, etc). An optional format may also be passed, which forces
105  /// the library to assume the image file is of that particular format.
106  /// If 'steal_stream' is true, the image library assumes ownership of the
107  /// stream and closes it when it's finished reading the file. If the stream
108  /// is not seekable (cannot jump around in the file, such as with a pipe),
109  /// set 'streamIsSeekable' to false.
110  /// This method returns a new IMG_File object which you read the image data
111  /// from, or NULL if an error occurred.
112  static IMG_FilePtr open(UT_IStream &is,
113  const IMG_FileParms *options = nullptr,
114  const IMG_Format *fmt=nullptr,
115  int steal_stream = 0,
116  bool streamIsSeekable = true);
117 
118  /// @brief Create a new image file
119  /// Create a new image file with the pathname 'filename' according to the
120  /// parameters specified in 'stat'. You can supply an optional 'options'
121  /// class to translate the image before being written (scale, flip, etc).
122  /// You can also specify an optional 'format' parameter to force the file
123  /// to be written as a specific image format (regardless of the extension
124  /// found in 'filename').
125  /// NULL may be returned if the file could not be created for any reason.
126  static IMG_FilePtr create(const char *filename,
127  const IMG_Stat &stat,
128  const IMG_FileParms *options = nullptr,
129  const IMG_Format *fmt = nullptr);
130 
131 
132  /// @brief Write an image file to an existing stream
133  /// Writes a new image file to the stream 'os' according to the
134  /// parameters specified in 'stat'. You can supply an optional 'options'
135  /// class to translate the image before being written (scale, flip, etc).
136  /// You can also specify an optional 'format' parameter to force the file
137  /// to be written as a specific image format (regardless of the extension
138  /// found in 'filename').
139  /// If 'steal_stream' is true, the image library assumes ownership of the
140  /// stream and closes it when it's finished writing the file. If the stream
141  /// is not seekable (cannot jump around in the file, such as with a pipe),
142  /// set 'streamIsSeekable' to false.
143  /// NULL may be returned if the file could not be created in the stream.
144  static IMG_FilePtr create(std::ostream &os,
145  const IMG_Stat &stat,
146  const IMG_FileParms *options = nullptr,
147  const IMG_Format *fmt = nullptr,
148  int steal_stream = 0,
149  bool streamIsSeekable = true);
150 
151  /// @{
152  /// @brief Writes a PXL_Raster to an image file.
153  /// Convenience method to write an image stored in a PXL_Raster to a disk
154  /// file.
155  static bool saveRasterAsFile(const char *filename,
156  const PXL_Raster *raster,
158  static bool saveRasterAsFile(const char *filename,
159  const PXL_Raster *raster,
160  const IMG_FileParms *fparms = nullptr,
161  const IMG_Format *format = nullptr);
162  /// @}
163 
164  /// @brief Writes PXL_Raster's to image files.
165  /// Convenience method to write images stored in PXL_Raster's to disk
166  /// files. The @c linear_planes parameter specifies a pattern of planes
167  /// which should be written to in linear space.
168  static bool saveRastersAsFiles(const char *filename,
169  const IMG_SaveRastersToFilesParms &parms);
170 
171  /// @brief Copies an existing image file to another image file.
172  /// Convenience method to copy an image file from one file to another.
173  /// The image date may be altered if the formats of the two files are
174  /// not the same (based on filename extension), or if an optional 'options'
175  /// class is passed.
176  static bool copyToFile(const char *sourcename,
177  const char *destname,
178  const IMG_FileParms *options = nullptr);
179 
180  static bool copyToFileFormat(const char *sourcename,
181  const char *formatname,
182  UT_String *destname = nullptr,
183  const IMG_FileParms *options = nullptr);
184 
185  /// @brief Copies an existing image file to a stream
186  /// Convenience method to copy an image file to a stream. The image data
187  /// may be altered if an optional 'options' class is passed, or if the
188  /// optional image 'format' parameter does not match the format of the
189  /// source image file.
190  static bool copyToStream(const char *sourcename,
191  std::ostream &deststream,
192  const IMG_FileParms *options = nullptr,
193  const IMG_Format *format = nullptr);
194 
195  /// Check whether image integrity by reading all scanlines of image
196  static bool checkIntegrity(const char *filename, UT_StringHolder &error);
197 
198  /// Check whether image integrity by reading all scanlines of image.
199  /// @note You cannot have read from the IMG_File, nor will you be able to
200  /// read from the IMG_File after calling this method.
201  ///
202  /// To work properly, there shoud be no filtering on the IMG_File, so it
203  /// should be opened using: @code
204  /// IMG_FileParms parms;
205  /// parms.readAsIs();
206  /// parms.orientImage(IMG_ORIENT_X_NONE, IMG_ORIENT_Y_NONE);
207  /// IMG_FilePtr fp = IMG_File::open(filename, &parms);
208  /// @endcode;
209  static bool checkIntegrity(IMG_File *fp, UT_StringHolder &error);
210 
211  /// Returns the image file extension (including leading ".") that should
212  /// be used when we are automatically saving COP generated texture maps
213  /// to disk as part of a USD export operation.
214  static const char *getAutoTextureSaveFileExtention();
215 
216  virtual const char *className() const { return "IMG_File"; }
217 
218  /// Closes the file. Called by the destructor if needed , so 'delete file'
219  /// will often take the place of this call. However, you won't receive any
220  /// error information in that case, so you can call it directly.
221  int close();
222 
223  /// Returns 1 if we are reading, 0 if writing.
224  int getReadMode() const;
225 
226  /// @{
227  /// Returns the image type of the format we just opened.
228  IMG_ImageType getImageType() const;
229  /// @}
230 
231  /// @{
232  /// Retrieve the file format description of the file. The format contains
233  /// all information that is general to all files of this format type.
234  const IMG_Format *getFormat() const { return myFormat; }
235  void setFormat(const IMG_Format *f) { myFormat = f; }
236  /// @}
237 
238  /// Get the image description of the current image file (resolution, data
239  /// format, etc). The returned class can be queried for all of the current
240  /// image file's statistics.
241  /// @{
242  const IMG_Stat &getStat() const;
243  IMG_Stat &getStat();
244 
245  const IMG_Stat &unfilteredStat() const
246  { return getUnfilteredFile()->myStat; }
247  /// @}
248 
249  /// Get additional image information about the file that is specific
250  /// to a particular format. Some formats do not have additional information.
251  /// The information returned is human-readable in 'text'.
252  virtual void getAdditionalInfo(UT_String &text);
253 
254  /// Returns the option passed through IMG_FileParms. This searches for
255  /// format specific options (i.e. OpenEXR::compression). It's possible to
256  /// override the format name by passing the @c format_override argument.
257  UT_StringHolder getFileOption(const UT_StringRef &name) const;
258 
259  /// Access to the list of file options this file was saved with.
260  /// @{
261  int SYS_DEPRECATED(20.0) getNumOptions() const;
262  UT_StringHolder SYS_DEPRECATED(20.0) getOptionName(int i) const;
263  UT_StringHolder SYS_DEPRECATED(20.0) getOptionValue(int i) const;
264  /// @}
265 
266  /// When reading or writing a file, the metadata will contain all the
267  /// metadata options defined by the file (and values that the user has
268  /// passed through the IMG_FileParms).
269  ///
270  /// When reading a file, the driver will also populate the metadata from
271  /// any data stored in the file.
272  const IMG_Metadata &metadata() const { return unfilteredStat().metadata(); }
273 
274  /// @{
275  /// Iterate over the file's metdata
276  IMG_Metadata::const_iterator beginMetadata() const
277  { return metadata().begin(); }
278  IMG_Metadata::const_iterator endMetadata() const
279  { return metadata().end(); }
280  /// @}
281 
282  /// Search for specific metadata
283  bool findMetadata(const UT_StringRef &name,
284  IMG_MetadataItem &value) const
285  {
286  return unfilteredStat().findMetadata(name, value);
287  }
288 
289  /// @{
290  /// Import metadata
291  bool importMetadata(const UT_StringRef &name, bool &value) const
292  { return unfilteredStat().importMetadata(name, value); }
293  bool importMetadata(const UT_StringRef &name, UT_StringHolder &value) const
294  { return unfilteredStat().importMetadata(name, value); }
295  bool importMetadata(const UT_StringRef &name, int32 &value) const
296  { return unfilteredStat().importMetadata(name, value); }
297  bool importMetadata(const UT_StringRef &name, int64 &value) const
298  { return unfilteredStat().importMetadata(name, value); }
299  bool importMetadata(const UT_StringRef &name, fpreal32 &value) const
300  { return unfilteredStat().importMetadata(name, value); }
301  bool importMetadata(const UT_StringRef &name, fpreal64 &value) const
302  { return unfilteredStat().importMetadata(name, value); }
303  bool importMetadata(const UT_StringRef &name, UT_Matrix4F &m) const
304  { return unfilteredStat().importMetadata(name, m); }
305  bool importMetadata(const UT_StringRef &name, UT_Matrix4D &m) const
306  { return unfilteredStat().importMetadata(name, m); }
307  /// @}
308 
309  /// Convert metadata to a string value. When @c pretty_print is @c true:
310  /// - If there's a menu, the corresponding label will be returned
311  /// - If there's type information, it will be used (i.e. printing a time or
312  /// memory)
313  bool metadataAsString(const UT_StringRef &name,
314  UT_StringHolder &value,
315  bool pretty_print = true) const
316  {
317  return unfilteredStat().metadataAsString(name, value, pretty_print);
318  }
319 
320  /// @brief read a single scanline.
321  /// read() returns a pointer to the scanline data
322  /// in an internal buffer. Do not delete it.
323  const void *read(int scan, const IMG_Plane *from_plane = nullptr);
324 
325  /// @brief Reads the scanline into a buffer that you supply.
326  /// The buffer passed must be big enough to fit the plane passed.
327  /// getStat().bytesPerPlaneScan() will return the proper size.
328  /// Returns 0 on failure.
329  bool readIntoBuffer(int scan, void *buffer,
330  const IMG_Plane *from_plane = nullptr);
331 
332  /// @brief Write a scanline to the file.
333  /// You don't need to write scanlines in order, nor do you need to write
334  /// planes in order; the data may be cached however. Returns 0 if
335  /// there was an error during the write. You should immediately stop
336  /// writing if a failure occurred (many formats will behave unpredictably
337  /// otherwise).
338  bool write(int scan, const void *data,
339  const IMG_Plane *to_plane = nullptr);
340 
341  /// allocates a buffer large enough to hold the biggest plane's scanline
342  /// in the file. Free this buffer with free(). (This will not hold all
343  /// the planes' scanlines, only one at a time!)
344  void * allocScanlineBuffer() const;
345 
346  /// The size in bytes of the buffer allocated for a scanline.
347  exint getScanlineBufferSizeB() const;
348 
349  /// @deprecated
350  /// The following methods read/write a whole raster. Unless the scanline
351  /// increment is passed in, the stat structure will be used to determine the
352  /// scanline size. Beware if you're using translators...
353  /// Use readImages() and writeImages() instead.
354  ///@{
355  bool readImage(void *data, int flip=0, int scaninc=0);
356  /// @deprecated
357  bool writeImage(void *data, int flip=0, int scaninc=0);
358  ///@}
359 
360  // Convenience method to write a single raster to a file.
361  static bool writeImage(const UT_StringRef &filepath,
362  const PXL_Raster &image,
363  const IMG_FileParms *options = nullptr,
364  const IMG_Format *fmt = nullptr);
365 
366  /// @brief Reads all the image data into a list of PXL_Rasters.
367  /// reads the image data into a a series of rasters. The array should be
368  /// empty, as this method creates and fills the rasters for you.
369  bool readImages(UT_Array<UT_UniquePtr<PXL_Raster>> &images,
370  const char *scope = nullptr);
371 
372  /// @{
373  /// @brief Writes all PXL_Rasters to the image format.
374  /// This method takes a raster per IMG_Plane in the stat. The
375  /// data format, color model and res of the raster must match the
376  /// corresponding IMG_Plane. If the format is not a deep raster format,
377  /// not all images may be written.
378  ///
379  /// In H21, the 'freerasters' parameter was removed and it's the
380  /// responsibility of the caller.
381  virtual bool writeImages(const UT_Array<const PXL_Raster *> &imgs);
382  virtual bool writeImages(const UT_Array<UT_UniquePtr<PXL_Raster>> &images);
383  /// @}
384 
385  /// @deprecated
386  /// For image files that contain more than one image, such as a
387  /// movie file, jump to a particular frame in the movie and reset
388  /// for reading the scanlines of the new frame
389  virtual bool jumpToFrame(int frame);
390 
391  /// When writing an image, call if interrupted or you encounter an
392  /// non-image-file error and cannot complete the file write.
393  virtual void abortWrite();
394 
395  ///@{
396  /// orientation of the current file or format. Some formats support multiple
397  /// orientations specified in the image files themselves, others simply
398  /// have a fixed orientation. Call these methods rather than querying the
399  /// orientation from the format, in case the format supports multiple
400  /// orientations.
401  virtual int isTopFirst() const;
402  /// If 0, scanlines are right-to-left. Default is 1 (left-to-right).
403  virtual int isLeftFirst() const;
404  ///@}
405 
406  /// call this if you won't be reading the scanlines in order, or if
407  /// you'll be reading all the scanlines for a single plane first.
408  virtual void randomReadAccessRequired();
409 
410  /// @{
411  /// @private
412  bool randomReadsForced() const { return myForceRandomReads; }
413  /// @}
414 
415  /// @{
416  /// This is a tile interface for reading files. To use it, you must pass an
417  /// IMG_FileParms object to open() with IMG_FileParms::useTileInterface()
418  /// called. Otherwise, this will just return false. The x-y coords of the
419  ///tile is in pixels.
420  virtual bool readTile(const UT_InclusiveRect &tile, void *data,
421  const IMG_Plane *plane=0);
422 
423  /// this is a tile interface for writing files. To use it, you must pass an
424  /// IMG_FileParms object to open() with IMG_FileParms::useTileInterface()
425  /// called. Otherwise, this will just return false. The x-y coords of the
426  ///tile is in pixels.
427  virtual bool writeTile(const UT_InclusiveRect &tile,
428  const void *data,
429  const IMG_Plane *plane=0);
430  /// @}
431 
432  /// When writing an image, the checkpoint() method can be used to
433  /// checkpoint data (see TIFFCheckpointDirectory() for an example).
434  /// Generally, this writes the image data currently passed and this results
435  /// in a usable, partially written file.
436  /// By default, nothing is done.
437  virtual void checkpoint();
438 
439  /// This method converts the "standard" bit depth option to an IMG_DataType.
440  /// This is used by the -b option in mantra as well as many other places.
441  /// When dealing with floating point arguments, there's an optional flag to
442  /// "denormalize" the floating point values when writing. This basically
443  /// removes tiny precision errors. It's up to the user to deal with the
444  /// denormalization.
445  /// - char, byte, 8 = uint8
446  /// - short, 16 = uint16
447  /// - int = uint32
448  /// - FLOAT = fpreal32 (denormalize=true)
449  /// - HALF = fpreal16 (denormalize=true)
450  /// - float, 32 = fpreal32
451  /// - half = fpreal16
452  static IMG_DataType mapStorageOption(const char *option,
453  bool *denormalize_flag = nullptr);
454 
455  /// Turns error reporting on or off. Returns the previous setting.
456  /// Errors are reported to the error manager, which will either show up
457  /// in the node information or the Houdini status bar (if not loaded within
458  /// a node).
459  ///
460  static int doErrors(int newDoErrors);
461  static void imgError(IMG_ErrorCodes code,
462  const char *msg = nullptr);
463  static void imgWarning(IMG_ErrorCodes code,
464  const char *msg = nullptr);
465 
466  bool hasError() const
467  { return getBaseFile() ? (getBaseFile()->hasError() ||
468  myErrorFlag) :myErrorFlag; }
469 
470  /// Returns information about the alpha channel if the IMG_FileParms passed
471  /// to open() had detectAlphaDetails() specified.
472  virtual IMG_FileAlphaInfo getAlphaInfo(float &) const
473  { return IMG_ALPHA_VARYING; }
474 
475  /// returns the raw file at the top of the filter list.
476  IMG_File *getUnfilteredFile();
477  const IMG_File *getUnfilteredFile() const;
478  virtual IMG_File *getBaseFile() const { return 0; }
479 
480  /// Copy the texture image options from another IMG_File
481  bool copyImageTextureOptions(const IMG_File &src,
482  bool clear_existing);
483 
484  /// Some image formats support "texture" options. Formats which do not
485  /// support options should return a NULL pointer.
486  /// This method calls @c getImageTextureOptions() by default
487  virtual UT_SharedPtr<UT_Options> imageTextureOptions() const;
488 
489  /// This method is deprecated. Please implement @c imageTextureOptions()
490  SYS_DEPRECATED(12.0) virtual const UT_Options *getImageTextureOptions() const;
491 
492  /// For image formats which support texture options, this will clear out
493  /// all texture options.
494  virtual void clearImageTextureOptions();
495 
496  /// For image formats which support texture options, merge the UT_Options
497  /// into the current options.
498  virtual bool setImageTextureOptions(const UT_Options &options);
499 
500  /// When being created through a tile device (i.e. rendering, etc.), the
501  /// writer may send additional information to the file writer after the
502  /// image has been created.
503  virtual void setWriteTag(const char *tagname,
504  int num_values,
505  const char *const *values);
506 
507  /// Read the image options (@see getOption()) to extract the world to
508  /// camera transform. If the data isn't available, this method returns
509  /// false. This will likely only work when the image is being created from
510  /// mantra.
511  bool getWorldToCamera(UT_Matrix4D &xform) const;
512 
513  /// Read the image options (@see getOption()) to extract the camera to NDC
514  /// transform. If the data isn't available in the options, this method
515  /// returns false. This will likely only work when the image is being
516  /// created from mantra.
517  /// If the @c fit_z option is true, the near/far range will be set to
518  /// (0,1). This will not be possible if the "camera:clip" setting wasn't
519  /// passed in the options.
520  bool getCameraToNDC(UT_Matrix4D &xform, int xres, int yres, bool
521  fit_z = true) const;
522  /// Read the image options (@see getOption()) to extract the world to NDC
523  /// transform. If the data isn't available in the options, this method
524  /// returns false. This will likely only work when the image is being
525  /// created from mantra.
526  /// If the @c fit_z option is true, the near/far range will be set to
527  /// (0,1). This will not be possible if the "camera:clip" setting wasn't
528  /// passed in the options.
529  bool getWorldToNDC(UT_Matrix4D &xform, int xres, int yres, bool
530  fit_z = true) const;
531 
532 
533  // API for raw deep pixel access. Methods will fail if the image is not
534  // a deep pixel image. The deep pixel functions can be accessed from
535  // multiple threads simultaneously.
536 
537  // Returns the number of deep pixel samples for the given pixel location.
538  // Returns -1 if the sample count cannot be read, or if the image is not
539  // a deep pixel image.
540  virtual int getDeepPixelSamples(int x, int y);
541 
542  // Read the deep pixel samples for the given plane. The size of the data
543  // array should be at least the same size as the number of samples returned
544  // by getDeepPixelSamples multiplied by the component count of the plane
545  // given by IMG_Plane::getComponentCount.
546  // Returns false if the data cannot be read, or if the image is not a deep
547  // pixel image.
548  virtual bool getDeepPixelPlaneData(int x, int y,
549  const IMG_Plane &plane,
550  float *data);
551 
552  // Read the deep pixel samples for all components at a given pixel location.
553  // The length of the pointer array should at least be the same as the
554  // number of samples returned from getDeepPixelSamples(). The size of
555  // each array pointed to should be at least the same size as the number
556  // of components returned from getDeepPixelComponentCount().
557  // Returns false if the data cannot be read, of if the image is not a deep
558  // pixel image.
559  virtual bool getDeepPixelData(int x, int y, float * const *data);
560 
561  /// Read a deep pixel
562  virtual bool readDeepPixelData(int x, int y,
563  PXL_DeepSampleList &pixel);
564 
565  /// @{
566  /// A method to write deep pixel data for all channels, at a given pixel
567  /// location. The function should be given an array of pointers to float
568  /// arrays, where each float array contains the value of all image
569  /// components for a given sample level.
570  ///
571  /// Returns false if the data cannot be written, or if the image is not
572  /// a deep pixel image.
573  virtual bool writeDeepPixelData(int x, int y,
574  const PXL_DeepSampleListPtr &pixel);
575  /// @}
576 
577 
578  /// users of IMG_File can select only certain planes to read using
579  /// IMG_FileParms::selectPlane..(). Call selectPlanesToRead() first,
580  /// usually at the end of open(), and then call isPlaneSelected() to
581  /// determine if the plane was selected for read.
582  /// @{
583  void selectPlanesToRead();
584  bool isPlaneSelected(const IMG_Plane &plane) const;
585  /// @}
586 
587  static void setFileCreateCB(
589  static void setFileHooks(IMG_FileOpenHook openhook,
590  IMG_FileCloseHook closehook);
591  static IMG_FileOpenHook &getOpenHook();
592  static IMG_FileCloseHook &getCloseHook();
593 
594 protected:
595  IMG_File(); /// Only called by format class
596 
597  // If the check_magic flag is 0, then the first 4 bytes of the file have
598  // alread. They are passed in as the magic number for verification.
599  virtual int open();
600  virtual int openPostMagic();
601  virtual int openFile(const char *filename);
602 
603  virtual int readScanline(int scanline, void *data) = 0;
604  virtual const void *readPlaneScanline(int y, const IMG_Plane &pi);
605 
606  // Create an image
607  virtual int createFile(const char *filename,const IMG_Stat &stat);
608  virtual int create(const IMG_Stat &stat);
609 
610  virtual int writeScanline(int scanline, const void *data) = 0;
611  virtual int writePlaneScanline(const void *data, int y,
612  const IMG_Plane &pi);
613 
614  virtual int closeFile() = 0;
615 
616  /// Run after the output stream has been closed.
617  /// Be careful, since some things have been destructed.
618  virtual void postCloseAction();
619 
620  // add any image flips, scales, data translations, etc. Returns the
621  // end of the filter chain.
622  //
623  virtual bool isPassThrough() const { return false; }
624 
625  // if you override this, you must call this class's version.
626  virtual void computeCommonData();
627 
628  void *getScanlineBuffer(int y);
629  void *getPlaneBuffer(int y, const IMG_Plane &pi);
630 
631  virtual void finishedScanline(int scan);
632 
633  static void setOptions(const IMG_FileParms *options,
634  IMG_File *file);
635 
636  /// @{
637  /// Set option to control behaviour of the file. For example, the
638  /// compression level when creating the image.
639  bool setOption(const UT_StringHolder &token, const char *value);
640  bool setOption(const UT_StringHolder &token, fpreal64 val);
641  bool setOption(const UT_StringHolder &token, int64 val);
642  bool setOption(const UT_StringHolder &option, int value)
643  { return setOption(option, (int64)value); }
644 
645  bool addMetadata(const UT_StringHolder &key,
646  const IMG_MetadataItem &item);
647  bool addMetadata(const UT_StringHolder &key,
648  const UT_JSONValue &value,
649  IMG_Metadata::Storage store =
651  IMG_Metadata::TypeInfo type_info =
653  /// @}
654 
655  bool canWriteStatWithoutConversion() const;
656 
657  // Access to input and output streams
658  // peekByte() will peek at the next input byte. -1 returned on EOF
659  // readSomeBytes() will read data into the buffer specified. The number
660  // of bytes actually read is returned.
661  // writeSomeBytes() will write data from the buffer. The number
662  // of bytes actually written is returned.
663  // flushBytes() will flush the output stream
664  // readBytes() is a convenience method when all data needs to be read
665  // writeBytes() is a convenience method when all data needs to be written
666  //
667  int peekByte();
668  int readSomeBytes(void *buffer, int size);
669  int writeSomeBytes(const void *buffer, int size);
670  bool flushBytes();
671 
672  bool readBytes(void *buffer, int size)
673  { return readSomeBytes(buffer, size) == size; }
674  bool writeBytes(const void *buffer, int size)
675  { return writeSomeBytes(buffer, size) == size; }
676 
677 
678  // For the odd format which requires data to be read as ASCII lines, this
679  // method exists.
680  bool readAsciiLine(UT_WorkBuffer &wbuf);
681 
682  // Seeks the stream to the start + offset. Returns true if successful
683  // and false otherwise.
684  bool seekFromBeginning(int64 offset);
685  bool seekFromCurrent(int64 offset);
686  bool seekFromEnd(int64 offset);
687  int64 tellCurrentPosition();
688 
689  // Copies our input stream to the given stream.
690  void copyInputToStream(std::ostream &os);
691 
692  // Deletes our input stream.
693  void deleteStream();
694 
695  /////////////////////////////////////////////////////////////////////////
696  // Do not use these methods. They are for special cases only.
697  UT_IStream *getUTIStream() { return myIStream; }
698  void setIStream(UT_IStream *is) { myIStream = is; }
699  /////////////////////////////////////////////////////////////////////////
700 
701  // Image description.
702  IMG_Stat myStat;
703  bool myReadMode;
704  std::ostream *myOS;
705  int64 myStreamStartPos;
706  int64 myStreamLength;
707  unsigned myCreateIStream:1,
708  myCreateOStream:1,
709  myForceRandomReads:1,
710  myHasRandomReads:1,
711  myFileOpen:1,
712  myErrorFlag:1,
713  myContinueOnErrorFlag:1,
714  myIStreamFromHook:1,
715  myExplicitFormat:1;
716 
717 private:
718  class img_ScanProgress
719  {
720  public:
721  img_ScanProgress()
722  : myNumPlanes(0)
723  {
724  }
725  void init(const IMG_Stat &stat);
726  int64 getMemoryUsage(bool inclusive) const;
727  void processed(int scan, const IMG_Plane *plane);
728  void processAll(int scan);
729  bool isComplete(int scan, const IMG_Plane *plane) const;
730  bool isComplete(int scan) const;
731  int remaining(int scan) const;
732  int numScans() const { return myCounts.entries(); }
733  private:
734  int bitIndex(int scan, int plane) const;
735  private:
736  int myNumPlanes;
737  UT_BitArray myProcessed;
738  UT_ValArray<int> myCounts;
739  };
740 
741  // Initialize tags to default values
742  void initializeTags();
743  void makeScanlineBuffers();
744  void deallocScanlineBuffer(int scan);
745  const void *returnErrorScan(int scan, const IMG_Plane &pi);
746  const char *metadataKey() const;
747 
748  static IMG_FilePtr makeReadFilters(IMG_FilePtr src, const IMG_FileParms &parms);
749  static IMG_FilePtr makeWriteFilters(IMG_FilePtr src, const IMG_FileParms &parms);
750  IMG_File *makeDataConversion(const IMG_FileParms &parms,
751  IMG_File *file);
752  IMG_File *makeFlip(const IMG_FileParms &parms,
753  IMG_File *file);
754 
755  static IMG_FilePtr open(const char *filename,
756  const IMG_FileParms *options,
757  const IMG_Format *fmt,
758  const UT_Array<const IMG_Format*> *image_formats);
759 
760  const IMG_Format *myFormat;
761  void *myScanlineBuffer;
762  int myCurrentImageScanline;
763 
764  img_ScanProgress myScanProgress;
765  UT_ValArray<void *> myImageScanline;
766  UT_BitArray mySelectPlane;
767 
768  UT_UniquePtr<FS_Reader> myReader;
769  UT_UniquePtr<FS_Writer> myWriter;
770  UT_IStream *myIStream;
771 
772  // only IMG_Format can call initializeTags().
773  friend class IMG_Format;
774  friend class IMG_FileFilter;
775  friend class IMG_GZip;
776  friend class IMG_FileBuffer;
777  friend class IMG_MemoryFileBuffer;
778  friend class MV_ReadPRISMS;
779 };
780 
781 /// Auto-scope class mainly to disable file errors temporarily
782 class IMG_API IMG_AutoFileError
783 {
784 public:
785  IMG_AutoFileError(bool report_errors = false)
786  { myReport = IMG_File::doErrors(report_errors?1:0); }
787  ~IMG_AutoFileError()
788  { IMG_File::doErrors(myReport); }
789  UT_NON_COPYABLE(IMG_AutoFileError);
790 private:
791  int myReport = 1;
792 };
793 
794 #endif
795 
Class for reading files.
Definition: FS_Reader.h:33
GT_API const UT_StringHolder filename
IMG_ErrorCodes
Definition: IMG_Error.h:16
int int32
Definition: SYS_Types.h:39
#define SYS_DEPRECATED(__V__)
IMG_ImageType
Type of image we want to create or have opened.
GLsizei const GLfloat * value
Definition: glcorearb.h:824
UT_Functor1< void, UT_IStream * > IMG_FileCloseHook
Definition: IMG_File.h:57
int64 exint
Definition: SYS_Types.h:125
GLenum GLenum GLsizei void * image
Definition: glad.h:5132
GLint y
Definition: glcorearb.h:103
void close() override
Describes the format and layout of a single plane in an image The plane specifies the format and name...
Definition: IMG_Plane.h:48
float fpreal32
Definition: SYS_Types.h:200
GLuint buffer
Definition: glcorearb.h:660
std::unique_ptr< T, Deleter > UT_UniquePtr
A smart pointer for unique ownership of dynamically allocated objects.
Definition: UT_UniquePtr.h:39
< returns > If no error
Definition: snippets.dox:2
double fpreal64
Definition: SYS_Types.h:201
#define IMG_API
Definition: IMG_API.h:10
UT_StringMap< IMG_MetadataItem >::const_iterator const_iterator
Definition: IMG_Metadata.h:334
GLfloat f
Definition: glcorearb.h:1926
GLintptr offset
Definition: glcorearb.h:665
int open(float queuesize) override
const_iterator begin() const
Definition: IMG_Metadata.h:335
std::shared_ptr< T > UT_SharedPtr
Wrapper around std::shared_ptr.
Definition: UT_SharedPtr.h:36
IMG_DataType
Definition: IMG_FileTypes.h:17
GLint GLint GLsizei GLint GLenum format
Definition: glcorearb.h:108
#define UT_NON_COPYABLE(CLASS)
Define deleted copy constructor and assignment operator inside a class.
Class for writing files.
Definition: FS_Writer.h:34
HUSD_API const char * raster()
long long int64
Definition: SYS_Types.h:116
GLuint const GLchar * name
Definition: glcorearb.h:786
GLint GLenum GLint x
Definition: glcorearb.h:409
UT_Functor1< UT_IStream *, const UT_StringRef & > IMG_FileOpenHook
Definition: IMG_File.h:56
ImageBuf OIIO_API flip(const ImageBuf &src, ROI roi={}, int nthreads=0)
IMG_FileAlphaInfo
GLsizeiptr size
Definition: glcorearb.h:664
A map of string to various well defined value types.
Definition: UT_Options.h:84
GA_API const UT_StringHolder parms
GLenum GLsizei GLsizei GLint * values
Definition: glcorearb.h:1602
Base Integer Rectangle class.
__hostdev__ constexpr T pi()
Pi constant taken from Boost to match old behaviour.
Definition: NanoVDB.h:976
File options for manipulating image data on load or save. This class allows you to modify the incomin...
Definition: IMG_FileParms.h:39
GLuint GLfloat * val
Definition: glcorearb.h:1608
Class to store JSON objects as C++ objects.
Definition: UT_JSONValue.h:99
Contains the details of a specific image file, used by IMG_File. This class contains all the high-lev...
Definition: IMG_Stat.h:38
Parameters for the saveRaster[s]AsFile[s]() methods of IMG_File.
Map of metadata items.
Definition: IMG_Metadata.h:217
UT_UniquePtr< IMG_File > IMG_FilePtr
Definition: IMG_File.h:54
Definition: format.h:1821
GLenum src
Definition: glcorearb.h:1793