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,
157  const IMG_SaveRastersToFilesParms &parms);
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  /// if 'freerasters' is true, it will free the rasters for you.
379  bool writeImages(const UT_Array<const PXL_Raster *> &imgs);
380  bool writeImages(UT_Array<UT_UniquePtr<PXL_Raster>> &images,
381  bool freerasters = false);
382  /// @}
383 
384  /// @deprecated
385  /// For image files that contain more than one image, such as a
386  /// movie file, jump to a particular frame in the movie and reset
387  /// for reading the scanlines of the new frame
388  virtual bool jumpToFrame(int frame);
389 
390  /// When writing an image, call if interrupted or you encounter an
391  /// non-image-file error and cannot complete the file write.
392  virtual void abortWrite();
393 
394  ///@{
395  /// orientation of the current file or format. Some formats support multiple
396  /// orientations specified in the image files themselves, others simply
397  /// have a fixed orientation. Call these methods rather than querying the
398  /// orientation from the format, in case the format supports multiple
399  /// orientations.
400  virtual int isTopFirst() const;
401  /// If 0, scanlines are right-to-left. Default is 1 (left-to-right).
402  virtual int isLeftFirst() const;
403  ///@}
404 
405  /// call this if you won't be reading the scanlines in order, or if
406  /// you'll be reading all the scanlines for a single plane first.
407  virtual void randomReadAccessRequired();
408 
409  /// @{
410  /// @private
411  bool randomReadsForced() const { return myForceRandomReads; }
412  /// @}
413 
414  /// @{
415  /// This is a tile interface for reading files. To use it, you must pass an
416  /// IMG_FileParms object to open() with IMG_FileParms::useTileInterface()
417  /// called. Otherwise, this will just return false. The x-y coords of the
418  ///tile is in pixels.
419  virtual bool readTile(const UT_InclusiveRect &tile, void *data,
420  const IMG_Plane *plane=0);
421 
422  /// this is a tile interface for writing files. To use it, you must pass an
423  /// IMG_FileParms object to open() with IMG_FileParms::useTileInterface()
424  /// called. Otherwise, this will just return false. The x-y coords of the
425  ///tile is in pixels.
426  virtual bool writeTile(const UT_InclusiveRect &tile,
427  const void *data,
428  const IMG_Plane *plane=0);
429  /// @}
430 
431  /// When writing an image, the checkpoint() method can be used to
432  /// checkpoint data (see TIFFCheckpointDirectory() for an example).
433  /// Generally, this writes the image data currently passed and this results
434  /// in a usable, partially written file.
435  /// By default, nothing is done.
436  virtual void checkpoint();
437 
438  /// This method converts the "standard" bit depth option to an IMG_DataType.
439  /// This is used by the -b option in mantra as well as many other places.
440  /// When dealing with floating point arguments, there's an optional flag to
441  /// "denormalize" the floating point values when writing. This basically
442  /// removes tiny precision errors. It's up to the user to deal with the
443  /// denormalization.
444  /// - char, byte, 8 = uint8
445  /// - short, 16 = uint16
446  /// - int = uint32
447  /// - FLOAT = fpreal32 (denormalize=true)
448  /// - HALF = fpreal16 (denormalize=true)
449  /// - float, 32 = fpreal32
450  /// - half = fpreal16
451  static IMG_DataType mapStorageOption(const char *option,
452  bool *denormalize_flag = nullptr);
453 
454  /// Turns error reporting on or off. Returns the previous setting.
455  /// Errors are reported to the error manager, which will either show up
456  /// in the node information or the Houdini status bar (if not loaded within
457  /// a node).
458  ///
459  static int doErrors(int newDoErrors);
460  static void imgError(IMG_ErrorCodes code,
461  const char *msg = nullptr);
462  static void imgWarning(IMG_ErrorCodes code,
463  const char *msg = nullptr);
464 
465  bool hasError() const
466  { return getBaseFile() ? (getBaseFile()->hasError() ||
467  myErrorFlag) :myErrorFlag; }
468 
469  /// Returns information about the alpha channel if the IMG_FileParms passed
470  /// to open() had detectAlphaDetails() specified.
471  virtual IMG_FileAlphaInfo getAlphaInfo(float &) const
472  { return IMG_ALPHA_VARYING; }
473 
474  /// returns the raw file at the top of the filter stack.
475  IMG_File *getUnfilteredFile();
476  const IMG_File *getUnfilteredFile() const;
477  virtual IMG_File *getBaseFile() const { return 0; }
478 
479  /// Copy the texture image options from another IMG_File
480  bool copyImageTextureOptions(const IMG_File &src,
481  bool clear_existing);
482 
483  /// Some image formats support "texture" options. Formats which do not
484  /// support options should return a NULL pointer.
485  /// This method calls @c getImageTextureOptions() by default
486  virtual UT_SharedPtr<UT_Options> imageTextureOptions() const;
487 
488  /// This method is deprecated. Please implement @c imageTextureOptions()
489  SYS_DEPRECATED(12.0) virtual const UT_Options *getImageTextureOptions() const;
490 
491  /// For image formats which support texture options, this will clear out
492  /// all texture options.
493  virtual void clearImageTextureOptions();
494 
495  /// For image formats which support texture options, merge the UT_Options
496  /// into the current options.
497  virtual bool setImageTextureOptions(const UT_Options &options);
498 
499  /// When being created through a tile device (i.e. rendering, etc.), the
500  /// writer may send additional information to the file writer after the
501  /// image has been created.
502  virtual void setWriteTag(const char *tagname,
503  int num_values,
504  const char *const *values);
505 
506  /// Read the image options (@see getOption()) to extract the world to
507  /// camera transform. If the data isn't available, this method returns
508  /// false. This will likely only work when the image is being created from
509  /// mantra.
510  bool getWorldToCamera(UT_Matrix4D &xform) const;
511 
512  /// Read the image options (@see getOption()) to extract the camera to NDC
513  /// transform. If the data isn't available in the options, this method
514  /// returns false. This will likely only work when the image is being
515  /// created from mantra.
516  /// If the @c fit_z option is true, the near/far range will be set to
517  /// (0,1). This will not be possible if the "camera:clip" setting wasn't
518  /// passed in the options.
519  bool getCameraToNDC(UT_Matrix4D &xform, int xres, int yres, bool
520  fit_z = true) const;
521  /// Read the image options (@see getOption()) to extract the world to NDC
522  /// transform. If the data isn't available in the options, this method
523  /// returns false. This will likely only work when the image is being
524  /// created from mantra.
525  /// If the @c fit_z option is true, the near/far range will be set to
526  /// (0,1). This will not be possible if the "camera:clip" setting wasn't
527  /// passed in the options.
528  bool getWorldToNDC(UT_Matrix4D &xform, int xres, int yres, bool
529  fit_z = true) const;
530 
531 
532  // API for raw deep pixel access. Methods will fail if the image is not
533  // a deep pixel image. The deep pixel functions can be accessed from
534  // multiple threads simultaneously.
535 
536  // Returns the number of deep pixel samples for the given pixel location.
537  // Returns -1 if the sample count cannot be read, or if the image is not
538  // a deep pixel image.
539  virtual int getDeepPixelSamples(int x, int y);
540 
541  // Read the deep pixel samples for the given plane. The size of the data
542  // array should be at least the same size as the number of samples returned
543  // by getDeepPixelSamples multiplied by the component count of the plane
544  // given by IMG_Plane::getComponentCount.
545  // Returns false if the data cannot be read, or if the image is not a deep
546  // pixel image.
547  virtual bool getDeepPixelPlaneData(int x, int y,
548  const IMG_Plane &plane,
549  float *data);
550 
551  // Read the deep pixel samples for all components at a given pixel location.
552  // The length of the pointer array should at least be the same as the
553  // number of samples returned from getDeepPixelSamples(). The size of
554  // each array pointed to should be at least the same size as the number
555  // of components returned from getDeepPixelComponentCount().
556  // Returns false if the data cannot be read, of if the image is not a deep
557  // pixel image.
558  virtual bool getDeepPixelData(int x, int y, float * const *data);
559 
560  /// Read a deep pixel
561  virtual bool readDeepPixelData(int x, int y,
562  PXL_DeepSampleList &pixel);
563 
564  /// @{
565  /// A method to write deep pixel data for all channels, at a given pixel
566  /// location. The function should be given an array of pointers to float
567  /// arrays, where each float array contains the value of all image
568  /// components for a given sample level.
569  ///
570  /// Returns false if the data cannot be written, or if the image is not
571  /// a deep pixel image.
572  virtual bool writeDeepPixelData(int x, int y,
573  const PXL_DeepSampleListPtr &pixel);
574  /// @}
575 
576 
577  /// users of IMG_File can select only certain planes to read using
578  /// IMG_FileParms::selectPlane..(). Call selectPlanesToRead() first,
579  /// usually at the end of open(), and then call isPlaneSelected() to
580  /// determine if the plane was selected for read.
581  /// @{
582  void selectPlanesToRead();
583  bool isPlaneSelected(const IMG_Plane &plane) const;
584  /// @}
585 
586  static void setFileCreateCB(
588  static void setFileHooks(IMG_FileOpenHook openhook,
589  IMG_FileCloseHook closehook);
590  static IMG_FileOpenHook &getOpenHook();
591  static IMG_FileCloseHook &getCloseHook();
592 
593 protected:
594  IMG_File(); /// Only called by format class
595 
596  // If the check_magic flag is 0, then the first 4 bytes of the file have
597  // alread. They are passed in as the magic number for verification.
598  virtual int open();
599  virtual int openPostMagic();
600  virtual int openFile(const char *filename);
601 
602  virtual int readScanline(int scanline, void *data) = 0;
603  virtual const void *readPlaneScanline(int y, const IMG_Plane &pi);
604 
605  // Create an image
606  virtual int createFile(const char *filename,const IMG_Stat &stat);
607  virtual int create(const IMG_Stat &stat);
608 
609  virtual int writeScanline(int scanline, const void *data) = 0;
610  virtual int writePlaneScanline(const void *data, int y,
611  const IMG_Plane &pi);
612 
613  virtual int closeFile() = 0;
614 
615  /// Run after the output stream has been closed.
616  /// Be careful, since some things have been destructed.
617  virtual void postCloseAction();
618 
619  // add any image flips, scales, data translations, etc. Returns the
620  // end of the filter chain.
621  //
622  virtual bool isPassThrough() const { return false; }
623 
624  // if you override this, you must call this class's version.
625  virtual void computeCommonData();
626 
627  void *getScanlineBuffer(int y);
628  void *getPlaneBuffer(int y, const IMG_Plane &pi);
629 
630  virtual void finishedScanline(int scan);
631 
632  static void setOptions(const IMG_FileParms *options,
633  IMG_File *file);
634 
635  /// @{
636  /// Set option to control behaviour of the file. For example, the
637  /// compression level when creating the image.
638  bool setOption(const UT_StringHolder &token, const char *value);
639  bool setOption(const UT_StringHolder &token, fpreal64 val);
640  bool setOption(const UT_StringHolder &token, int64 val);
641  bool setOption(const UT_StringHolder &option, int value)
642  { return setOption(option, (int64)value); }
643 
644  bool addMetadata(const UT_StringHolder &key,
645  const IMG_MetadataItem &item);
646  bool addMetadata(const UT_StringHolder &key,
647  const UT_JSONValue &value,
648  IMG_Metadata::Storage store =
650  IMG_Metadata::TypeInfo type_info =
652  /// @}
653 
654  bool canWriteStatWithoutConversion() const;
655 
656  // Access to input and output streams
657  // peekByte() will peek at the next input byte. -1 returned on EOF
658  // readSomeBytes() will read data into the buffer specified. The number
659  // of bytes actually read is returned.
660  // writeSomeBytes() will write data from the buffer. The number
661  // of bytes actually written is returned.
662  // flushBytes() will flush the output stream
663  // readBytes() is a convenience method when all data needs to be read
664  // writeBytes() is a convenience method when all data needs to be written
665  //
666  int peekByte();
667  int readSomeBytes(void *buffer, int size);
668  int writeSomeBytes(const void *buffer, int size);
669  bool flushBytes();
670 
671  bool readBytes(void *buffer, int size)
672  { return readSomeBytes(buffer, size) == size; }
673  bool writeBytes(const void *buffer, int size)
674  { return writeSomeBytes(buffer, size) == size; }
675 
676 
677  // For the odd format which requires data to be read as ASCII lines, this
678  // method exists.
679  bool readAsciiLine(UT_WorkBuffer &wbuf);
680 
681  // Seeks the stream to the start + offset. Returns true if successful
682  // and false otherwise.
683  bool seekFromBeginning(int64 offset);
684  bool seekFromCurrent(int64 offset);
685  bool seekFromEnd(int64 offset);
686  int64 tellCurrentPosition();
687 
688  // Copies our input stream to the given stream.
689  void copyInputToStream(std::ostream &os);
690 
691  // Deletes our input stream.
692  void deleteStream();
693 
694  /////////////////////////////////////////////////////////////////////////
695  // Do not use these methods. They are for special cases only.
696  UT_IStream *getUTIStream() { return myIStream; }
697  void setIStream(UT_IStream *is) { myIStream = is; }
698  /////////////////////////////////////////////////////////////////////////
699 
700  // Image description.
701  IMG_Stat myStat;
702  bool myReadMode;
703  std::ostream *myOS;
704  int64 myStreamStartPos;
705  int64 myStreamLength;
706  unsigned myCreateIStream:1,
707  myCreateOStream:1,
708  myForceRandomReads:1,
709  myHasRandomReads:1,
710  myFileOpen:1,
711  myErrorFlag:1,
712  myContinueOnErrorFlag:1,
713  myIStreamFromHook:1,
714  myExplicitFormat:1;
715 
716 private:
717  class img_ScanProgress
718  {
719  public:
720  img_ScanProgress()
721  : myNumPlanes(0)
722  {
723  }
724  void init(const IMG_Stat &stat);
725  int64 getMemoryUsage(bool inclusive) const;
726  void processed(int scan, const IMG_Plane *plane);
727  void processAll(int scan);
728  bool isComplete(int scan, const IMG_Plane *plane) const;
729  bool isComplete(int scan) const;
730  int remaining(int scan) const;
731  int numScans() const { return myCounts.entries(); }
732  private:
733  int bitIndex(int scan, int plane) const;
734  private:
735  int myNumPlanes;
736  UT_BitArray myProcessed;
737  UT_ValArray<int> myCounts;
738  };
739 
740  // Initialize tags to default values
741  void initializeTags();
742  void makeScanlineBuffers();
743  void deallocScanlineBuffer(int scan);
744  const void *returnErrorScan(int scan, const IMG_Plane &pi);
745  const char *metadataKey() const;
746 
747  static IMG_FilePtr makeReadFilters(IMG_FilePtr src, const IMG_FileParms &parms);
748  static IMG_FilePtr makeWriteFilters(IMG_FilePtr src, const IMG_FileParms &parms);
749  IMG_File *makeDataConversion(const IMG_FileParms &parms,
750  IMG_File *file);
751  IMG_File *makeFlip(const IMG_FileParms &parms,
752  IMG_File *file);
753 
754  static IMG_FilePtr open(const char *filename,
755  const IMG_FileParms *options,
756  const IMG_Format *fmt,
757  const UT_Array<const IMG_Format*> *image_formats);
758 
759  const IMG_Format *myFormat;
760  void *myScanlineBuffer;
761  int myCurrentImageScanline;
762 
763  img_ScanProgress myScanProgress;
764  UT_ValArray<void *> myImageScanline;
765  UT_BitArray mySelectPlane;
766 
767  UT_UniquePtr<FS_Reader> myReader;
768  UT_UniquePtr<FS_Writer> myWriter;
769  UT_IStream *myIStream;
770 
771  // only IMG_Format can call initializeTags().
772  friend class IMG_Format;
773  friend class IMG_FileFilter;
774  friend class IMG_GZip;
775  friend class IMG_FileBuffer;
776  friend class IMG_MemoryFileBuffer;
777  friend class MV_ReadPRISMS;
778 };
779 
780 /// Auto-scope class mainly to disable file errors temporarily
781 class IMG_API IMG_AutoFileError
782 {
783 public:
784  IMG_AutoFileError(bool report_errors = false)
785  { myReport = IMG_File::doErrors(report_errors?1:0); }
786  ~IMG_AutoFileError()
787  { IMG_File::doErrors(myReport); }
788  UT_NON_COPYABLE(IMG_AutoFileError);
789 private:
790  int myReport = 1;
791 };
792 
793 #endif
794 
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.
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
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:325
GLfloat f
Definition: glcorearb.h:1926
GLintptr offset
Definition: glcorearb.h:665
Definition: core.h:760
int open(float queuesize) override
const_iterator begin() const
Definition: IMG_Metadata.h:326
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:32
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
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:38
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:208
Definition: core.h:1131
UT_UniquePtr< IMG_File > IMG_FilePtr
Definition: IMG_File.h:54
Definition: format.h:895
GLenum src
Definition: glcorearb.h:1793