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  static UT_StringHolder guessOCIOColorSpace(const UT_StringHolder &filename,
217  const IMG_Stat &stat);
218 
219  virtual const char *className() const { return "IMG_File"; }
220 
221  /// Closes the file. Called by the destructor if needed , so 'delete file'
222  /// will often take the place of this call. However, you won't receive any
223  /// error information in that case, so you can call it directly.
224  int close();
225 
226  /// Returns 1 if we are reading, 0 if writing.
227  int getReadMode() const;
228 
229  /// @{
230  /// Returns the image type of the format we just opened.
231  IMG_ImageType getImageType() const;
232  /// @}
233 
234  /// @{
235  /// Retrieve the file format description of the file. The format contains
236  /// all information that is general to all files of this format type.
237  const IMG_Format *getFormat() const { return myFormat; }
238  void setFormat(const IMG_Format *f) { myFormat = f; }
239  /// @}
240 
241  /// Get the image description of the current image file (resolution, data
242  /// format, etc). The returned class can be queried for all of the current
243  /// image file's statistics.
244  /// @{
245  const IMG_Stat &getStat() const;
246  IMG_Stat &getStat();
247 
248  const IMG_Stat &unfilteredStat() const
249  { return getUnfilteredFile()->myStat; }
250  /// @}
251 
252  /// Get additional image information about the file that is specific
253  /// to a particular format. Some formats do not have additional information.
254  /// The information returned is human-readable in 'text'.
255  virtual void getAdditionalInfo(UT_String &text);
256 
257  /// Returns the option passed through IMG_FileParms. This searches for
258  /// format specific options (i.e. OpenEXR::compression). It's possible to
259  /// override the format name by passing the @c format_override argument.
260  UT_StringHolder getFileOption(const UT_StringRef &name) const;
261 
262  /// Access to the list of file options this file was saved with.
263  /// @{
264  int SYS_DEPRECATED(20.0) getNumOptions() const;
265  UT_StringHolder SYS_DEPRECATED(20.0) getOptionName(int i) const;
266  UT_StringHolder SYS_DEPRECATED(20.0) getOptionValue(int i) const;
267  /// @}
268 
269  /// When reading or writing a file, the metadata will contain all the
270  /// metadata options defined by the file (and values that the user has
271  /// passed through the IMG_FileParms).
272  ///
273  /// When reading a file, the driver will also populate the metadata from
274  /// any data stored in the file.
275  const IMG_Metadata &metadata() const { return unfilteredStat().metadata(); }
276 
277  /// @{
278  /// Iterate over the file's metdata
279  IMG_Metadata::const_iterator beginMetadata() const
280  { return metadata().begin(); }
281  IMG_Metadata::const_iterator endMetadata() const
282  { return metadata().end(); }
283  /// @}
284 
285  /// Search for specific metadata
286  bool findMetadata(const UT_StringRef &name,
287  IMG_MetadataItem &value) const
288  {
289  return unfilteredStat().findMetadata(name, value);
290  }
291 
292  /// @{
293  /// Import metadata
294  bool importMetadata(const UT_StringRef &name, bool &value) const
295  { return unfilteredStat().importMetadata(name, value); }
296  bool importMetadata(const UT_StringRef &name, UT_StringHolder &value) const
297  { return unfilteredStat().importMetadata(name, value); }
298  bool importMetadata(const UT_StringRef &name, int32 &value) const
299  { return unfilteredStat().importMetadata(name, value); }
300  bool importMetadata(const UT_StringRef &name, int64 &value) const
301  { return unfilteredStat().importMetadata(name, value); }
302  bool importMetadata(const UT_StringRef &name, fpreal32 &value) const
303  { return unfilteredStat().importMetadata(name, value); }
304  bool importMetadata(const UT_StringRef &name, fpreal64 &value) const
305  { return unfilteredStat().importMetadata(name, value); }
306  bool importMetadata(const UT_StringRef &name, UT_Matrix4F &m) const
307  { return unfilteredStat().importMetadata(name, m); }
308  bool importMetadata(const UT_StringRef &name, UT_Matrix4D &m) const
309  { return unfilteredStat().importMetadata(name, m); }
310  /// @}
311 
312  /// Convert metadata to a string value. When @c pretty_print is @c true:
313  /// - If there's a menu, the corresponding label will be returned
314  /// - If there's type information, it will be used (i.e. printing a time or
315  /// memory)
316  bool metadataAsString(const UT_StringRef &name,
317  UT_StringHolder &value,
318  bool pretty_print = true) const
319  {
320  return unfilteredStat().metadataAsString(name, value, pretty_print);
321  }
322 
323  /// @brief read a single scanline.
324  /// read() returns a pointer to the scanline data
325  /// in an internal buffer. Do not delete it.
326  const void *read(int scan, const IMG_Plane *from_plane = nullptr);
327 
328  /// @brief Reads the scanline into a buffer that you supply.
329  /// The buffer passed must be big enough to fit the plane passed.
330  /// getStat().bytesPerPlaneScan() will return the proper size.
331  /// Returns 0 on failure.
332  bool readIntoBuffer(int scan, void *buffer,
333  const IMG_Plane *from_plane = nullptr);
334 
335  /// @brief Write a scanline to the file.
336  /// You don't need to write scanlines in order, nor do you need to write
337  /// planes in order; the data may be cached however. Returns 0 if
338  /// there was an error during the write. You should immediately stop
339  /// writing if a failure occurred (many formats will behave unpredictably
340  /// otherwise).
341  bool write(int scan, const void *data,
342  const IMG_Plane *to_plane = nullptr);
343 
344  /// allocates a buffer large enough to hold the biggest plane's scanline
345  /// in the file. Free this buffer with free(). (This will not hold all
346  /// the planes' scanlines, only one at a time!)
347  void * allocScanlineBuffer() const;
348 
349  /// The size in bytes of the buffer allocated for a scanline.
350  exint getScanlineBufferSizeB() const;
351 
352  /// @deprecated
353  /// The following methods read/write a whole raster. Unless the scanline
354  /// increment is passed in, the stat structure will be used to determine the
355  /// scanline size. Beware if you're using translators...
356  /// Use readImages() and writeImages() instead.
357  ///@{
358  bool readImage(void *data, int flip=0, int scaninc=0);
359  /// @deprecated
360  bool writeImage(void *data, int flip=0, int scaninc=0);
361  ///@}
362 
363  // Convenience method to write a single raster to a file.
364  static bool writeImage(const UT_StringRef &filepath,
365  const PXL_Raster &image,
366  const IMG_FileParms *options = nullptr,
367  const IMG_Format *fmt = nullptr);
368 
369  /// @brief Reads all the image data into a list of PXL_Rasters.
370  /// reads the image data into a a series of rasters. The array should be
371  /// empty, as this method creates and fills the rasters for you.
372  bool readImages(UT_Array<UT_UniquePtr<PXL_Raster>> &images,
373  const char *scope = nullptr);
374 
375  /// @{
376  /// @brief Writes all PXL_Rasters to the image format.
377  /// This method takes a raster per IMG_Plane in the stat. The
378  /// data format, color model and res of the raster must match the
379  /// corresponding IMG_Plane. If the format is not a deep raster format,
380  /// not all images may be written.
381  ///
382  /// In H21, the 'freerasters' parameter was removed and it's the
383  /// responsibility of the caller.
384  virtual bool writeImages(const UT_Array<const PXL_Raster *> &imgs);
385  virtual bool writeImages(const UT_Array<UT_UniquePtr<PXL_Raster>> &images);
386  /// @}
387 
388  /// @deprecated
389  /// For image files that contain more than one image, such as a
390  /// movie file, jump to a particular frame in the movie and reset
391  /// for reading the scanlines of the new frame
392  virtual bool jumpToFrame(int frame);
393 
394  /// When writing an image, call if interrupted or you encounter an
395  /// non-image-file error and cannot complete the file write.
396  virtual void abortWrite();
397 
398  ///@{
399  /// orientation of the current file or format. Some formats support multiple
400  /// orientations specified in the image files themselves, others simply
401  /// have a fixed orientation. Call these methods rather than querying the
402  /// orientation from the format, in case the format supports multiple
403  /// orientations.
404  virtual int isTopFirst() const;
405  /// If 0, scanlines are right-to-left. Default is 1 (left-to-right).
406  virtual int isLeftFirst() const;
407  ///@}
408 
409  /// call this if you won't be reading the scanlines in order, or if
410  /// you'll be reading all the scanlines for a single plane first.
411  virtual void randomReadAccessRequired();
412 
413  /// @{
414  /// @private
415  bool randomReadsForced() const { return myForceRandomReads; }
416  /// @}
417 
418  /// @{
419  /// This is a tile interface for reading files. To use it, you must pass an
420  /// IMG_FileParms object to open() with IMG_FileParms::useTileInterface()
421  /// called. Otherwise, this will just return false. The x-y coords of the
422  ///tile is in pixels.
423  virtual bool readTile(const UT_InclusiveRect &tile, void *data,
424  const IMG_Plane *plane=0);
425 
426  /// this is a tile interface for writing files. To use it, you must pass an
427  /// IMG_FileParms object to open() with IMG_FileParms::useTileInterface()
428  /// called. Otherwise, this will just return false. The x-y coords of the
429  ///tile is in pixels.
430  virtual bool writeTile(const UT_InclusiveRect &tile,
431  const void *data,
432  const IMG_Plane *plane=0);
433  /// @}
434 
435  /// When writing an image, the checkpoint() method can be used to
436  /// checkpoint data (see TIFFCheckpointDirectory() for an example).
437  /// Generally, this writes the image data currently passed and this results
438  /// in a usable, partially written file.
439  /// By default, nothing is done.
440  virtual void checkpoint();
441 
442  /// This method converts the "standard" bit depth option to an IMG_DataType.
443  /// This is used by the -b option in mantra as well as many other places.
444  /// When dealing with floating point arguments, there's an optional flag to
445  /// "denormalize" the floating point values when writing. This basically
446  /// removes tiny precision errors. It's up to the user to deal with the
447  /// denormalization.
448  /// - char, byte, 8 = uint8
449  /// - short, 16 = uint16
450  /// - int = uint32
451  /// - FLOAT = fpreal32 (denormalize=true)
452  /// - HALF = fpreal16 (denormalize=true)
453  /// - float, 32 = fpreal32
454  /// - half = fpreal16
455  static IMG_DataType mapStorageOption(const char *option,
456  bool *denormalize_flag = nullptr);
457 
458  /// Turns error reporting on or off. Returns the previous setting.
459  /// Errors are reported to the error manager, which will either show up
460  /// in the node information or the Houdini status bar (if not loaded within
461  /// a node).
462  ///
463  static int doErrors(int newDoErrors);
464  static void imgError(IMG_ErrorCodes code,
465  const char *msg = nullptr);
466  static void imgWarning(IMG_ErrorCodes code,
467  const char *msg = nullptr);
468 
469  bool hasError() const
470  { return getBaseFile() ? (getBaseFile()->hasError() ||
471  myErrorFlag) :myErrorFlag; }
472 
473  /// Returns information about the alpha channel if the IMG_FileParms passed
474  /// to open() had detectAlphaDetails() specified.
475  virtual IMG_FileAlphaInfo getAlphaInfo(float &) const
476  { return IMG_ALPHA_VARYING; }
477 
478  /// returns the raw file at the top of the filter list.
479  IMG_File *getUnfilteredFile();
480  const IMG_File *getUnfilteredFile() const;
481  virtual IMG_File *getBaseFile() const { return 0; }
482 
483  /// Copy the texture image options from another IMG_File
484  bool copyImageTextureOptions(const IMG_File &src,
485  bool clear_existing);
486 
487  /// Some image formats support "texture" options. Formats which do not
488  /// support options should return a NULL pointer.
489  /// This method calls @c getImageTextureOptions() by default
490  virtual UT_SharedPtr<UT_Options> imageTextureOptions() const;
491 
492  /// This method is deprecated. Please implement @c imageTextureOptions()
493  SYS_DEPRECATED(12.0) virtual const UT_Options *getImageTextureOptions() const;
494 
495  /// For image formats which support texture options, this will clear out
496  /// all texture options.
497  virtual void clearImageTextureOptions();
498 
499  /// For image formats which support texture options, merge the UT_Options
500  /// into the current options.
501  virtual bool setImageTextureOptions(const UT_Options &options);
502 
503  /// When being created through a tile device (i.e. rendering, etc.), the
504  /// writer may send additional information to the file writer after the
505  /// image has been created.
506  virtual void setWriteTag(const char *tagname,
507  int num_values,
508  const char *const *values);
509 
510  /// Read the image options (@see getOption()) to extract the world to
511  /// camera transform. If the data isn't available, this method returns
512  /// false. This will likely only work when the image is being created from
513  /// mantra.
514  bool getWorldToCamera(UT_Matrix4D &xform) const;
515 
516  /// Read the image options (@see getOption()) to extract the camera to NDC
517  /// transform. If the data isn't available in the options, this method
518  /// returns false. This will likely only work when the image is being
519  /// created from mantra.
520  /// If the @c fit_z option is true, the near/far range will be set to
521  /// (0,1). This will not be possible if the "camera:clip" setting wasn't
522  /// passed in the options.
523  bool getCameraToNDC(UT_Matrix4D &xform, int xres, int yres, bool
524  fit_z = true) const;
525  /// Read the image options (@see getOption()) to extract the world to NDC
526  /// transform. If the data isn't available in the options, this method
527  /// returns false. This will likely only work when the image is being
528  /// created from mantra.
529  /// If the @c fit_z option is true, the near/far range will be set to
530  /// (0,1). This will not be possible if the "camera:clip" setting wasn't
531  /// passed in the options.
532  bool getWorldToNDC(UT_Matrix4D &xform, int xres, int yres, bool
533  fit_z = true) const;
534 
535 
536  // API for raw deep pixel access. Methods will fail if the image is not
537  // a deep pixel image. The deep pixel functions can be accessed from
538  // multiple threads simultaneously.
539 
540  // Returns the number of deep pixel samples for the given pixel location.
541  // Returns -1 if the sample count cannot be read, or if the image is not
542  // a deep pixel image.
543  virtual int getDeepPixelSamples(int x, int y);
544 
545  // Read the deep pixel samples for the given plane. The size of the data
546  // array should be at least the same size as the number of samples returned
547  // by getDeepPixelSamples multiplied by the component count of the plane
548  // given by IMG_Plane::getComponentCount.
549  // Returns false if the data cannot be read, or if the image is not a deep
550  // pixel image.
551  virtual bool getDeepPixelPlaneData(int x, int y,
552  const IMG_Plane &plane,
553  float *data);
554 
555  // Read the deep pixel samples for all components at a given pixel location.
556  // The length of the pointer array should at least be the same as the
557  // number of samples returned from getDeepPixelSamples(). The size of
558  // each array pointed to should be at least the same size as the number
559  // of components returned from getDeepPixelComponentCount().
560  // Returns false if the data cannot be read, of if the image is not a deep
561  // pixel image.
562  virtual bool getDeepPixelData(int x, int y, float * const *data);
563 
564  /// Read a deep pixel
565  virtual bool readDeepPixelData(int x, int y,
566  PXL_DeepSampleList &pixel);
567 
568  /// @{
569  /// A method to write deep pixel data for all channels, at a given pixel
570  /// location. The function should be given an array of pointers to float
571  /// arrays, where each float array contains the value of all image
572  /// components for a given sample level.
573  ///
574  /// Returns false if the data cannot be written, or if the image is not
575  /// a deep pixel image.
576  virtual bool writeDeepPixelData(int x, int y,
577  const PXL_DeepSampleListPtr &pixel);
578  /// @}
579 
580 
581  /// users of IMG_File can select only certain planes to read using
582  /// IMG_FileParms::selectPlane..(). Call selectPlanesToRead() first,
583  /// usually at the end of open(), and then call isPlaneSelected() to
584  /// determine if the plane was selected for read.
585  /// @{
586  void selectPlanesToRead();
587  bool isPlaneSelected(const IMG_Plane &plane) const;
588  /// @}
589 
590  static void setFileCreateCB(
592  static void setFileHooks(IMG_FileOpenHook openhook,
593  IMG_FileCloseHook closehook);
594  static IMG_FileOpenHook &getOpenHook();
595  static IMG_FileCloseHook &getCloseHook();
596 
597  bool formatNeedsPremultiplied() const;
598 
599 protected:
600  IMG_File(); /// Only called by format class
601 
602  // If the check_magic flag is 0, then the first 4 bytes of the file have
603  // alread. They are passed in as the magic number for verification.
604  virtual int open();
605  virtual int openPostMagic();
606  virtual int openFile(const char *filename);
607 
608  virtual int readScanline(int scanline, void *data) = 0;
609  virtual const void *readPlaneScanline(int y, const IMG_Plane &pi);
610 
611  // Create an image
612  virtual int createFile(const char *filename,const IMG_Stat &stat);
613  virtual int create(const IMG_Stat &stat);
614 
615  virtual int writeScanline(int scanline, const void *data) = 0;
616  virtual int writePlaneScanline(const void *data, int y,
617  const IMG_Plane &pi);
618 
619  virtual int closeFile() = 0;
620 
621  /// Run after the output stream has been closed.
622  /// Be careful, since some things have been destructed.
623  virtual void postCloseAction();
624 
625  // add any image flips, scales, data translations, etc. Returns the
626  // end of the filter chain.
627  //
628  virtual bool isPassThrough() const { return false; }
629 
630  // if you override this, you must call this class's version.
631  virtual void computeCommonData();
632 
633  void *getScanlineBuffer(int y);
634  void *getPlaneBuffer(int y, const IMG_Plane &pi);
635 
636  virtual void finishedScanline(int scan);
637 
638  static void setOptions(const IMG_FileParms *options,
639  IMG_File *file);
640 
641  /// @{
642  /// Set option to control behaviour of the file. For example, the
643  /// compression level when creating the image.
644  bool setOption(const UT_StringHolder &token, const char *value);
645  bool setOption(const UT_StringHolder &token, fpreal64 val);
646  bool setOption(const UT_StringHolder &token, int64 val);
647  bool setOption(const UT_StringHolder &option, int value)
648  { return setOption(option, (int64)value); }
649 
650  bool addMetadata(const UT_StringHolder &key,
651  const IMG_MetadataItem &item);
652  bool addMetadata(const UT_StringHolder &key,
653  const UT_JSONValue &value,
654  IMG_Metadata::Storage store =
656  IMG_Metadata::TypeInfo type_info =
658  /// @}
659 
660  bool canWriteStatWithoutConversion() const;
661 
662  // Access to input and output streams
663  // peekByte() will peek at the next input byte. -1 returned on EOF
664  // readSomeBytes() will read data into the buffer specified. The number
665  // of bytes actually read is returned.
666  // writeSomeBytes() will write data from the buffer. The number
667  // of bytes actually written is returned.
668  // flushBytes() will flush the output stream
669  // readBytes() is a convenience method when all data needs to be read
670  // writeBytes() is a convenience method when all data needs to be written
671  //
672  int peekByte();
673  int readSomeBytes(void *buffer, int size);
674  int writeSomeBytes(const void *buffer, int size);
675  bool flushBytes();
676 
677  bool readBytes(void *buffer, int size)
678  { return readSomeBytes(buffer, size) == size; }
679  bool writeBytes(const void *buffer, int size)
680  { return writeSomeBytes(buffer, size) == size; }
681 
682 
683  // For the odd format which requires data to be read as ASCII lines, this
684  // method exists.
685  bool readAsciiLine(UT_WorkBuffer &wbuf);
686 
687  // Seeks the stream to the start + offset. Returns true if successful
688  // and false otherwise.
689  bool seekFromBeginning(int64 offset);
690  bool seekFromCurrent(int64 offset);
691  bool seekFromEnd(int64 offset);
692  int64 tellCurrentPosition();
693 
694  // Copies our input stream to the given stream.
695  void copyInputToStream(std::ostream &os);
696 
697  // Deletes our input stream.
698  void deleteStream();
699 
700  /////////////////////////////////////////////////////////////////////////
701  // Do not use these methods. They are for special cases only.
702  UT_IStream *getUTIStream() { return myIStream; }
703  void setIStream(UT_IStream *is) { myIStream = is; }
704  /////////////////////////////////////////////////////////////////////////
705 
706  // Image description.
707  IMG_Stat myStat;
708  bool myReadMode;
709  std::ostream *myOS;
710  int64 myStreamStartPos;
711  int64 myStreamLength;
712  unsigned myCreateIStream:1,
713  myCreateOStream:1,
714  myForceRandomReads:1,
715  myHasRandomReads:1,
716  myFileOpen:1,
717  myErrorFlag:1,
718  myContinueOnErrorFlag:1,
719  myIStreamFromHook:1,
720  myExplicitFormat:1;
721 
722 private:
723  class img_ScanProgress
724  {
725  public:
726  img_ScanProgress()
727  : myNumPlanes(0)
728  {
729  }
730  void init(const IMG_Stat &stat);
731  int64 getMemoryUsage(bool inclusive) const;
732  void processed(int scan, const IMG_Plane *plane);
733  void processAll(int scan);
734  bool isComplete(int scan, const IMG_Plane *plane) const;
735  bool isComplete(int scan) const;
736  int remaining(int scan) const;
737  int numScans() const { return myCounts.entries(); }
738  private:
739  int bitIndex(int scan, int plane) const;
740  private:
741  int myNumPlanes;
742  UT_BitArray myProcessed;
743  UT_ValArray<int> myCounts;
744  };
745 
746  // Initialize tags to default values
747  void initializeTags();
748  void makeScanlineBuffers();
749  void deallocScanlineBuffer(int scan);
750  const void *returnErrorScan(int scan, const IMG_Plane &pi);
751  const char *metadataKey() const;
752 
753  static IMG_FilePtr makeReadFilters(IMG_FilePtr src, const IMG_FileParms &parms);
754  static IMG_FilePtr makeWriteFilters(IMG_FilePtr src, const IMG_FileParms &parms);
755  IMG_File *makeDataConversion(const IMG_FileParms &parms,
756  IMG_File *file);
757  IMG_File *makeFlip(const IMG_FileParms &parms,
758  IMG_File *file);
759 
760  static IMG_FilePtr open(const char *filename,
761  const IMG_FileParms *options,
762  const IMG_Format *fmt,
763  const UT_Array<const IMG_Format*> *image_formats);
764 
765  const IMG_Format *myFormat;
766  void *myScanlineBuffer;
767  int myCurrentImageScanline;
768 
769  img_ScanProgress myScanProgress;
770  UT_ValArray<void *> myImageScanline;
771  UT_BitArray mySelectPlane;
772 
773  UT_UniquePtr<FS_Reader> myReader;
774  UT_UniquePtr<FS_Writer> myWriter;
775  UT_IStream *myIStream;
776 
777  // only IMG_Format can call initializeTags().
778  friend class IMG_Format;
779  friend class IMG_FileFilter;
780  friend class IMG_GZip;
781  friend class IMG_FileBuffer;
782  friend class IMG_MemoryFileBuffer;
783  friend class MV_ReadPRISMS;
784 };
785 
786 /// Auto-scope class mainly to disable file errors temporarily
787 class IMG_API IMG_AutoFileError
788 {
789 public:
790  IMG_AutoFileError(bool report_errors = false)
791  { myReport = IMG_File::doErrors(report_errors?1:0); }
792  ~IMG_AutoFileError()
793  { IMG_File::doErrors(myReport); }
794  UT_NON_COPYABLE(IMG_AutoFileError);
795 private:
796  int myReport = 1;
797 };
798 
799 #endif
800 
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:87
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
GU_API void xform(CE_Context &context, bool recompile, int npts, const cl::Buffer &outPos, const cl::Buffer &inPos, const cl::Buffer &surfacexform, const cl::Buffer *grp=nullptr)
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