LibRaw C++ API[back to Index]

# LibRaw C++ API

Contents

1. LibRaw Objects
2. Returned values
3. Methods Loading Data from a File
   - int LibRaw::open_datastream(LibRaw_abstract_datastream *stream)
   - int LibRaw::open_file(const char *rawfile[,INT64 bigfile_size])
   - int LibRaw::open_buffer(void *buffer, size_t bufsize)
   - int LibRaw::open_bayer(...)
   - int LibRaw::unpack(void)
   - int LibRaw::unpack_thumb(void)
   - int LibRaw::unpack_thumb_ex(int)
4. Auxiliary Functions
   - Library version info
     - const char* LibRaw::version()
     - int LibRaw::versionNumber()
     - bool LIBRAW_CHECK_VERSION(major,minor,patch)
   - List of supported cameras
     - int LibRaw::cameraCount()
     - const char** LibRaw::cameraList()
   - int LibRaw::set_rawspeed_camerafile(char *path_to_cameras_xml)
   - int LibRaw::get_decoder_info(libraw_decoder_info_t *)
   - const char* LibRaw::unpack_function_name()
   - int LibRaw::COLOR()
   - int LibRaw::error_count()
   - void LibRaw::setCancelFlag()
   - void LibRaw::clearCancelFlag()
   - int LibRaw::subtract_black()
   - int LibRaw::adjust_to_raw_inset_crop()
   - Support for Floating Point data
   - Support for YCC formats
   - void LibRaw::recycle_datastream(void)
   - void LibRaw::recycle(void)
   - LibRaw::~LibRaw()
   - const char* LibRaw::strprogress(enum LibRaw_progress code)
   - const char* LibRaw::strerror(int errorcode)
   - Setting Error Notification Functions and other callbacks
     - User callback for progress indication/interruption
     - User callback for exif/makernotes parser routines
     - File Read Error Notifier
5. Data Postprocessing: Emulation of dcraw Behavior
   - Parameter Setting
   - int LibRaw::raw2image
   - void LibRaw::free_image
   - int LibRaw::adjust_sizes_info_only(void)
   - int LibRaw::dcraw_process(void)
6. Data Output to Files: Emulation of dcraw Behavior
   - int LibRaw::dcraw_ppm_tiff_writer(const char *outfile)
   - int LibRaw::dcraw_thumb_writer(const char *thumbfile)
7. Copying unpacked data into memory buffer
   - void get_mem_image_format(int *widthp, int *heightp, int *colorsp, int *bpp)
   - int LibRaw::copy_mem_image(void* scan0, int stride, int bgr)
   - libraw_processed_image_t *dcraw_make_mem_image(int *errorcode)
   - libraw_processed_image_t *dcraw_make_mem_thumb(int *errorcode)
   - void LibRaw::dcraw_clear_mem(libraw_processed_image_t *)
8. Input layer abstraction
   - class LibRaw_abstract_datastream - abstract RAW read interface LibRaw_abstract_datastream class methods
     - Object verification
     - Stream read and positioning
     - Other methods
   - Derived input classes included in LibRaw
     - class LibRaw_file_datastream - file input interface
     - class LibRaw_file_datastream - file input interface for large files
     - class LibRaw_buffer_datastream - input from memory buffer
   - Own datastream derived classes
     - substream field: secondary input stream

## LibRaw Objects

The main LibRaw object (class) is created either without parameters or with flags determining the object behavior.

    #include "libraw/libraw.h"
    ...

       LibRaw ImageProcessor(unsigned int flags=0);
    ...

Flags (several flags are combined via operator |, i.e., bitwise OR):

- LIBRAW_OPTIONS_NO_DATAERR_CALLBACK: do not set the standard file read error handler (standard handler outputs the error report in stderr).

Three groups of methods are used for image processing

- Data loading from the RAW file
- Postprocessing functions emulating the dcraw behavior
- File output functions emulating the dcraw behavior.

The results of processing are placed in the imgdata field of type libraw_data_t; the same data set contains fields that control the postprocessing and output.

## Returned Values

All LibRaw API functions return an integer number in accordance with the return code convention. Please read the descriptions of this convention and LibRaw behavior in cases of fatal errors.

## Methods Loading Data from a File

### int LibRaw::open_datastream(LibRaw_abstract_datastream *stream)

Opens a datastream with RAW data, reads metadata (EXIF) from it, and fills the following structures:

- imgdata.idata (libraw_iparams_t),
- imgdata.sizes (libraw_image_sizes_t),
- imgdata.color (libraw_colordata_t),
- imgdata.other (libraw_imgother_t), and
- imgdata.thumbnail (libraw_thumbnail_t).

The function returns an integer number in accordance with the return code convention: positive if any system call has returned an error, negative (from the LibRaw error list) if there has been an error situation within LibRaw.

Before file opening, recycle() is always called; hence, if several images are processed in the batch mode, there is no need to call recycle() at the end of each processing cycle.

Input data: pointer to object, derived from LibRaw_abstract_datastream class. This object should be initialized and ready to read. This object should be destroyed in calling application after use.

### int LibRaw::open_file(const char *filename[,INT64 bigfile_size])

### Win32 only: int LibRaw::open_file(const wchar_t *filename[,INT64 bigfile_size])

Creates an LibRaw_file_datastream object, calls open_datastream(). If succeed, sets internal flag which signals to destroy internal datastream object on recycle(). On failure, just created file_datastream destroyed immediately.

Second optional parameter bigfile_size controls background I/O interface used for file operations. For files smaller than bigfile_size the LibRaw_file_datastream will be used and the LibRaw_bigfile_datastream otherwise.

The function returns an integer number in accordance with the return code convention: positive if any system call has returned an error, negative (from the LibRaw error list) if there has been an error situation within LibRaw.

### int LibRaw::open_buffer(void *buffer, size_t bufsize)

Created an LibRaw_buffer_datastream object, calls open_datastream(). If succeed, sets internal flag which signals to destroy internal datastream object on recycle(). On failure, just created file_datastream destroyed immediately.

The function returns an integer number in accordance with the return code convention: positive if any system call has returned an error, negative (from the LibRaw error list) if there has been an error situation within LibRaw.

### int LibRaw::open_bayer(unsigned char *data, unsigned datalen, ushort _raw_width, ushort _raw_height, ushort _left_margin, ushort _top_margin, ushort _right_margin, ushort _bottom_margin, unsigned char procflags, unsigned char bayer_pattern, unsigned unused_bits, unsigned otherflags, unsigned black_level)

Parameters:

- data, datalen - buffer passed
- _raw_width/_raw_height/*margin - image size and margins
- procflags:
  - for 10-bit format:
    - 1: "4 pixels in 5 bytes" packing is used
    - 0: "6 pixels in 8 bytes" packing is used
  - for 16-bit format:
    - 1: Big-endian data
- bayer_pattern: one of LIBRAW_OPENBAYER_RGGB,LIBRAW_OPENBAYER_BGGR, LIBRAW_OPENBAYER_GRBG,LIBRAW_OPENBAYER_GBRG
- unused_bits: count of upper zero bits
- otherflags:
  - Bit 1 - filter (average neighbors) for pixels with values of zero
  - Bits 2-4 - the orientation of the image (0=do not rotate, 3=180, 5=90CCW, 6=90CW)
- black_level: file black level (it also may be specified via imgdata.params)

See samples/openbayer_sample.cpp for usage sample (note, this sample is 'sample only', suited for Kodak KAI-0340 sensor, you'll need change open_bayer() params for your data).

### int LibRaw::unpack(void)

Unpacks the RAW files of the image, calculates the black level (not for all formats). The results are placed in imgdata.image.

Data reading is sometimes (not frequently) affected by settings made in imgdata.params (libraw_output_params_t); see API notes for details.

The function returns an integer number in accordance with the return code convention: positive if any system call has returned an error, negative (from the LibRaw error list) if there has been an error situation within LibRaw.

### int LibRaw::unpack_thumb(void)

### int LibRaw::unpack_thumb_ex(int i)

unpack_thumb(): reads (or unpacks) the default (largest) image preview (thumbnail), placing the result into the imgdata.thumbnail.thumb buffer.

unpack_thumb_ex(int i): reads i-th thumbnail (thumbnails list is available in imgdata.thumbs_list structure).

JPEG previews are placed into this buffer without any changes (with the header etc.). Other preview formats are placed into the buffer in the form of the unpacked bitmap image (three components, 8 bits per component).
The thumbnail format is written to the imgdata.thumbnail.tformat field; for the possible values, see description of constants and data structures.

The function returns an integer number in accordance with the return code convention: positive if any system call has returned an error, negative (from the LibRaw error list) if there has been an error situation within LibRaw.

###

## Auxiliary Functions

### Library version check

#### const char* LibRaw::version()

Returns string representation of LibRaw version in MAJOR.MINOR.PATCH-Status format (i.e. 0.6.0-Alpha2 or 0.6.1-Release).

#### int LibRaw::versionNumber()

Returns integer representation of LibRaw version. During LibRaw development, the version number is always increase .

#### bool LIBRAW_CHECK_VERSION(major,minor,patch)

Macro for version check in caller applications. Returns 'true' if current library version is greater or equal to set in macro parameters. This macro executes at runtime (not at compile time) and may be used for checking version of dynamically loaded LibRaw (from DLL/shared library).

### List of supported RAW formats (cameras)

#### int LibRaw::cameraCount()

Returns count of cameras supported.

#### const char** LibRaw::cameraList()

Returns list of supported cameras. Latest item of list is set to NULL (for easy printing).

#### int LibRaw::set_rawspeed_camerafile(char *path_to_cameras_xml)

(Only if LibRaw was built with RawSpeed support).

Loads XML file with RawSpeed camera description data (cameras.xml) specified by path_to_cameras_xml. Returns 0 on success, nonzero on error.

#### int LibRaw::get_decoder_info(libraw_decoder_info_t *)

The function fills libraw_decoder_info_t structure by passed pointer with current raw decoder data.

The function returns an integer number in accordance with the return code convention: positive if any system call has returned an error, negative (from the LibRaw error list) if there has been an error situation within LibRaw.

### const char* LibRaw::unpack_function_name()

Returns function name of file unpacking function. Intended only for LibRaw test suite designers to use in test coverage evaluation.

#### void LibRaw::setCancelFlag()

This call sets internal fast cancel flags. If set, current Raw decoder will be terminated ASAP. This call is useful if you need to cancel all LibRaw decoders in multithreaded program (e.g. for fast program termination or just for cancel current processing).

#### void LibRaw::clearCancelFlag()

This call clears internal fast cancel flags, so (early) terminated LibRaw decoder may work again.

#### int LibRaw::COLOR(int row, int col)

This call returns pixel color (color component number) in bayer pattern at row,col. The returned value is in 0..3 range for 4-component Bayer (RGBG2, CMYG and so on) and in 0..2 range for 3-color data.

Color indexes returned could be used as index in imgdata.idata.cdesc string to get color 'name'.

#### int LibRaw::error_count()

This call returns count of non-fatal data errors (out of range, etc) occurred in unpack() stage.

#### int LibRaw::subtract_black()

This call will subtract black level values from RAW data (for suitable RAW data). colordata.data_maximum and colordata.maximum and black level data (colordata.black and colordata.cblack) will be adjusted too.

This call should be used if you postprocess RAW data by your own code. LibRaw postprocessing functions will call subtract_black() by oneself.

The function returns an integer number in accordance with the return code convention: positive if any system call has returned an error, negative (from the LibRaw error list) if there has been an error situation within LibRaw.

#### int LibRaw::adjust_to_raw_inset_crop(unsigned mask, float maxcrop = 0.55f)

Promotes imgdata.sizes.raw_inset_crops[] values to imgdata.sizes.*margin and imgdata.sizes.width/height fields

Parameters
mask:

- if bit 1 is set: prefer raw_inset_crops[1]
- if bit 0 is set: prefer raw_inset_crops[0]

maxcrop: limits crop to not less than (original width/height)*maxcrop; if raw_inset_crops[i] data results in tighter crop, than this item is ignored.

return value: index in raw_inset_crops[] used increased by one, so

- 0: no changes made
- 1: [0]th data used
- 2: [1]th data used

Note: this call SHOULD be used after LibRaw::unpack(), otherwise black level calculation from masked area may be fooled resulting in wrong black levels.

#### Support for floating point data

Libraw can read floating point DNG files (no other RAW formats may use floating point) with or without conversion to integer data. Floating point values are stored in imgdata.rawdata buffers:

- float * float_image (if not NULL) points to floating point bayer data
- float (*float3_image)[3] (if not NULL) points to floating point 3-channel buffer
- float (*float4_image)[4] (if not NULL) points to floating point 4-channel buffer

Function calls for floating point support:

- int LibRaw::is_floating_point(); function will return 1 if file contains floating point data
- int LibRaw::have_fpdata(); function will return 1 if FP data has read (decoded) into memory and not converted to integer data
- int LibRaw::convertFloatToInt(float dmin=4096.f, float dmax=32767.f, float dtarget = 16383.f) converts floating point data to integer. If data maximum is out of dmin..dmax range, than data scaled to set maximum to dtarget

#### Support for YCC formats (Canon sRAW/mRAW and Nikon Small NEF)

           int LibRaw::is_sraw();
           int LibRaw::is_nikon_sraw();
           int LibRaw::sraw_midpoint()

- is_sraw() call returns nonzero if current image is YCC-based.
- is_nikon_sraw() call returns nonzero for Nikon Small NEF files
- sraw_midpoint() call returns neutral (gray) point for color channels

#### void LibRaw::set_dng_host(void* p)

If LibRaw is compiled with Adobe DNG SDK support and you wish to use this support:

- you need to create own dng_host object
- and pass it to LibRaw object using this function

#### void LibRaw::recycle_datastream(void)

This call closes input datastream with associated data buffer and unblocks opened file.

### void LibRaw::recycle(void)

Frees the allocated data of LibRaw instance, enabling one to process the next file using the same processor. Repeated calls of recycle() are quite possible and do not conflict with anything.

### LibRaw::~LibRaw()

Destructor, which consists in calling recycle().

### const char* LibRaw::strprogress(enum LibRaw_progress code)

Converts progress stage code to description string (in English).

### const char* LibRaw::strerror(int errorcode)

Analog of strerror(3) function: outputs the text descriptions of LibRaw error codes (in English).

### Setting Error Notification Functions

In process of RAW conversion LibRaw can call user-setted callback. This callback can be used for:

- Dynamic status update (progress bar and so on).
- Cancel of processing (for example, user pressed Cancel button).

Also, work of the library may cause two types of exceptional situations that require notification of the calling application:

- Memory shortage
- Data read error.

An application may set its own callbacks that will be called in the cases mentioned above to notify the user (or the calling program).

#### Progress indication/processing termination

            typedef int (*progress_callback)(void *callback_data,enum LibRaw_progress stage, int iteration, int expected);
            void LibRaw::set_progress_handler(progress_callback func,void *callback_data);

LibRaw user can set own callback which will be called 10-50 times during RAW postprocessing by dcraw_process().

This callback may terminate current image processing by returning of non-zero value. In such case all processing will be cancelled immediately and all resources will be returned to system by recycle() call. Current call of dcraw_process() will return error code LIBRAW_CANCELLED_BY_CALLBACK.

Callback parameters:

void *callback_data
  void*-pointer, passed as 2nd argument to set_progress_handler(). This pointer should be used to pass additional data to callback (i.e. thread local data and so on).
enum LibRaw_progress stage
  Current processing stage. This number can be converted to string by call to LibRaw::strprogress. Not all processing stages are covered by callback calls.
int iteration
  Iteration number within current stage (from 0 to expected-1).
int expected
  Expected number of iterations on current stage.

Callback should return value of: 0 for continue processing and non-zero for immediate cancel of processing.

If LibRaw compiled with OpenMP support, iteration parameter may not always increase within one stage. Out of order callback calls are possible.

Callback code sample:

    int my_progress_callback(void *data,enum LibRaw_progress p,int iteration, int expected)
    {
        char *passed_string = (char *data);
        printf("Callback: %s  pass %d of %d, data passed: %s\n",libraw_strprogress(p),iteration,expected,passed_string);
        if(timeout || key_pressed )
            return 1; // cancel processing immediately
        else
            return 0; // can continue
    }

#### User-specified exif tag parser callback

           typedef void (*exif_parser_callback) (void *context, int tag, int type, int len,unsigned int ord, void *ifp);
           void    LibRaw::set_exifparser_handler( exif_parser_callback cb,void *context);

Callback to be called on each parsed EXIF/Makernotes tag with parameters:

- context - pointer to context passed to set_exifparser_handler();
- tag - EXIF/Makernotes tag value
- type - TIFF(EXIF) tag type
- len - tag length
- ord - byte order (II or MM)
- void *ifp - pointer to LibRaw_abstract_datastream, positioned to tag data

#### File Read Error Notifier

            typedef void (*data_callback)(void *callback_data,const char *file, const int offset);
            void LibRaw::set_dataerror_handler(data_callback func, void *callback_data);

The user can define his or her own function to be called in the case of error in the input data. It is a void function receiving two parameters:

- void *callback_data - void*-pointer, passed as 2nd argument to set_progress_handler(). This pointer should be used to pass additional data to callback (i.e. thread local data and so on).
- file is the name of the RAW file whose processing evoked the file read error. This name can be NULL if underlying data input layer does not know the name. So, if calling application sets own callback, this callback should work with NULL file name.
- offset is -1 at end-of-file (if LibRaw expects more data) or a positive number equal to the file position (bytes from file beginning) where the unpacking error occurred.

The callback function is intended for information purposes: it notifies the user or the program code that processing is impossible.

If the user does not set his or her own handler, the standard one (output of error message in stderr) will be used.

One can set the null handler by passing NULL to set_dataerror_handler; then no notifier function will be called. The same effect can be achieved by creating a LibRaw object with the LIBRAW_OPTIONS_NO_DATAERR_CALLBACK flag in the constructor.

In the case of error in the input data, processing of the current file is terminated and a notifier is called; all allocated resources are freed, and recycle() is performed. The current call will return LIBRAW_IO_ERROR.
At an attempt to continue data processing, all subsequent calls will return LIBRAW_OUT_OF_ORDER_CALL. Processing of a new file may be started in the usual way, by calling LibRaw::open_file().

## Data Postprocessing: Emulation of dcraw Behavior

Instead of writing one's own Bayer pattern postprocessing, one can use the dcraw functions, which are called after the calls of open_file() + unpack() /+ unpack_thumb()/

### Parameter Setting

Virtually all parameters that can be set through the dcraw command line are specified by assigning values to fields of the LibRaw::imgdata.params structure. The type of this structure is libraw_output_params_t; all fields are listed and described in sufficient detail in the description of data structures.

### int LibRaw::raw2image

This function allocates buffer for postprocessing (imgdata.image) and fills it with data layout compatible with LibRaw 0.13/0.14 and below. If the buffer is already allocated, it will be free()ed and allocated again.

This function should be called only if your code do postprocessing stage. If you use LibRaw's postprocessing calls (see below) you don't need to call raw2image().

The function returns an integer number in accordance with the return code convention: positive if any system call has returned an error, negative (from the LibRaw error list) if there has been an error situation within LibRaw.

### void LibRaw::free_image

This function releases the imgdata.image buffer allocated by raw2image();

This method should be called if current postprocessing results are not needed by the program (e.g. already copied somewhere), but new postprocessing calls (with another settings) are possible, so it is to early to call recycle().

### int LibRaw::adjust_sizes_info_only(void)

The function calculates the correct size of the output image (imgdata.sizes.iwidth and imgdata.sizes.iheight) for the following cases:

- Files from Fuji cameras (with a 45-degree rotation)
- Files from cameras with non-square pixels
- Images shot by a rotated camera.

In the aforementioned cases, the function changes the fields of the image output size; note that this change cannot be repeated again.

### int LibRaw::dcraw_process(void)

The function emulates the postprocessing capabilities available in dcraw.
Called after calling LibRaw::unpack();

The entire functionality of dcraw (set via the field values in imgdata.params) is supported, except for

- Dark frame subtraction
- Work with bad pixels.

The function is intended solely for demonstration and testing purposes; it is assumed that its source code will be used in most real applications as the reference material concerning the order of RAW data processing.

The function returns an integer number in accordance with the error code convention: positive if any system call has returned an error, negative (from the LibRaw error list) if there has been an error situation within LibRaw.

## Data Output to Files: Emulation of dcraw Behavior

In spite of the abundance of libraries for file output in any formats, LibRaw includes calls that emulate the file output provided by dcraw. This is done primarily for easier verification of library work: the resultant files must be binary identical.

### int LibRaw::dcraw_ppm_tiff_writer(const char *outfile)

The function outputs the postprocessing results to a file in the PPM/PGM or TIFF format (the format is set via imgdata.params.output_tiff). The results are binary identical to those provided by dcraw.

If "-" is passed as outfile, the function will write to standard output (stdout).

The function returns an integer number in accordance with the error code convention: positive if any system call has returned an error, negative (from the LibRaw error list) if there has been an error situation within LibRaw.

### int LibRaw::dcraw_thumb_writer(const char *thumbfile)

Writes the thumbnail to a file in the PPM format for bitmap thumbnails and in the JPEG format for JPEG thumbnails, i.e., in the format completely identical to the results provided by dcraw.

The function returns an integer number in accordance with the error code convention: positive if any system call has returned an error, negative (from the LibRaw error list) if there has been an error situation within LibRaw.

## Copying unpacked data into memory buffer

There is several function calls for store unpacked data into memory buffer (after using dcraw_process() and so on):

- get_mem_image_format - get resulting bitmap size and bit depth.
- copy_mem_image - copy postprocessed data into some memory buffer with different color order and line stride.
- dcraw_make_mem_image - store processed image data into allocated buffer;
- dcraw_make_mem_thumb - store extracted thumbnail into buffer as JPEG-file image (for most cameras) or as RGB-bitmap.

For usage primer see samples/mem_image.c sample.

### void get_mem_image_format(int *widthp, int *heightp, int *colorsp, int *bpp) const - return processing bitmap size

This function returns size of postprocessed image:

- Image width is returned in *widthp;
- Bitmap height is returned in *heightp;
- Image color count is returned in *colorsp;
- Bits per pixel (8 or 16) is returned in *bpp;

### int LibRaw::copy_mem_image(void* scan0, int stride, int bgr) - copies postprocessed bitmap data into buffer

Function parameters:

- void *scan0 - pointer to buffer to copy data to. The buffer should be at least stride*image_height bytes;
- int stride - stride of each other image line (row) in bytes. Usually image_width*(bit_per_pixel/8)*image_colors, but may be more if you wish to align image rows to, for example, 8 or 16 or 32 bytes to make CPU more happy.
- int bgr - pixel copy order. RGB if bgr==0 and BGR otherwise.

The function returns an integer number in accordance with the error code convention: positive if any system call has returned an error, negative (from the LibRaw error list) if there has been an error situation within LibRaw.

### libraw_processed_image_t *dcraw_make_mem_image(int *errorcode=NULL) - store unpacked and processed image into memory buffer as RGB-bitmap

This function allocates memory buffer and stores unpacked-preprocessed image into this buffer. Function returns allocated structure libraw_processed_image_t with filled fields. Always returns data as RGB bitmap (i.e. type field is equal to LIBRAW_IMAGE_BITMAP).

dcraw_process() should be called before dcraw_make_mem_image();

Returns NULL in case of an error. If caller has passed not-NULL value as errorcode parameter, than *errorcode will be set to error code according to error code convention.

NOTE! Memory, allocated for return value will not be fried at destructor or LibRaw::recycle calls. Caller of dcraw_make_mem_image should free this memory by call to LibRaw::dcraw_clear_mem().

### libraw_processed_image_t *dcraw_make_mem_thumb(int *errorcode=NULL) - store unpacked thumbnail into memory buffer

This function allocates memory buffer and stores thumbnail data in it. Function returns allocated structure libraw_processed_image_t with filled fields. For most RAW images allocated structure will contains JPEG image (i.e. type field is equal to LIBRAW_IMAGE_JPEG). For some cameras with RGB-bitmap thumbnail (Kodak SLRs) returned structure contains RGB bitmap (type field is equal to LIBRAW_IMAGE_JPEG, see structure description for details).

unpack_thumb() should be called before dcraw_make_mem_thumb();

Returns NULL in case of an error. If caller has passed not-NULL value as errorcode parameter, than *errorcode will be set to error code according to ñ error code convention.

NOTE! Memory, allocated for return value will not be fried at destructor or LibRaw::recycle calls. Caller of dcraw_make_mem_image should free this memory by call to LibRaw::dcraw_clear_mem().

### void LibRaw::dcraw_clear_mem(libraw_processed_image_t *)

This function will free the memory allocated by dcraw_make_mem_image or dcraw_make_mem_thumb.

This is static class member, so call syntax should be LibRaw::dcraw_clear_mem(...).

This call translates directly to free() system function, but it is better to use dcraw_clear_mem because LibRaw (DLL) may be compiled with memory manager other than in calling application.

## Input layer abstraction

### class LibRaw_abstract_datastream - abstract RAW read interface

LibRaw reads RAW-data by calling (virtual) methods of C++ object derived from LibRaw_abstract_datastream. This C++ class does not implement any read, but defines interface to be called. Call to base class methods always results in error.

#### LibRaw_abstract_datastream class methods

##### Object verification

virtual int valid()
  Checks input datastream validity. Returns 1 on valid stream and 0 if datastream was created on non-valid input parameters (wrong filename for file stream and so on).

##### Stream read and positioning

This group of methods implements file object (FILE*) semantics.

virtual int read(void * ptr,size_t size, size_t nmemb)
  Similar to fread(ptr,size,nmemb,file).
virtual int seek(off_t o, int whence)
  Similar to fseek(file,o,whence).
virtual int tell(
  Similar to ftell(file).
virtual int get_char()
  Similar to getc(file)/fgetc(file).
virtual char* gets(char *s, int n)
  Similar to fgets(s,n,file).
virtual int eof()
  Similar to feof(file).
virtual int scanf_one(const char *fmt, void *val)
  Simplified variant of fscanf(file,fmt,val): format string is always contains one argument to read. So, variable args call is not needed and only one pointer to data passed.
virtual int jpeg_src(void * p);
  Initializes read structures in j_decompress_ptr object passed as *p. This object is used by libjpeg for JPEG data reading from datastream.

  Returns -1 on error and 0 on success.

virtual void * make_jas_stream();
  Creates LibJasper input stream (for JPEG2000 decoding).

  returns NULL on error or data pointer on success.

##### Other methods

This group of methods includes several supplementary calls. These calls are used to temporary switch to another data stream (file and/or memory buffer).

virtual const char* fname()
  Returns name of opened file if datastream object knows it (for example, LibRaw_file_datastream used). Filename used in:
  - error notification callbacks;
  - generation of filename of JPEG-file with metadata when needed (i.e. cameras with 'Diag RAW hack').
virtual int subfile_open(const char *fn)
  This call temporary switches input to file fn. Returns 0 on success and error code on error.
  The function used to read metadata from external JPEG file (on cameras with "Diag RAW hack").
  This call is not implemented for LibRaw_buffer_datastream, so external JPEG processing is not possible when buffer datastream used.
  This function should be implemented in real input class, base class call always return error.
  Working implementation sample can be found in LibRaw_file_datastream implementation in libraw/libraw_datastream.h file.
virtual void subfile_close()
  This call switches input stream from temporary open file back to main data stream.
virtual int tempbuffer_open(void *buf, size_t size)
  This call temporary switches input to LibRaw_buffer_datastream object, created from buf.
  This method is needed for Sony encrypted metadata parser.

  This call implemented in base class (LibRaw_abstract_datastream), there is no need to reimplement in in derived classes.
  Possible activity of temporary datastream requires very accurate programming when implementing datastreams derived from base LibRaw_abstract_datastream. See below for more details.

virtual void tempbuffer_close()
  This call switch input back from temporary datastream to main stream. This call implemented in base LibRaw_abstract_datastream class.

### Derived input classes included in LibRaw

There is three "standard" input classes in LibRaw distribution:

- LibRaw_file_datastream implements input from file (in filesystem).
- LibRaw_bigfile_datastream slower I/O, but files larger than 2Gb are supported.
- LibRaw_buffer_datastream implements input from memory buffer.

LibRaw C++ interface users can implement their own input classes and use them via LibRaw::open_datastream call. Requirements and implementation specifics are described below.

#### class LibRaw_file_datastream - file input interface

This class implements input from file.

Class methods:

LibRaw_file_datastream(const char *fname)
  This constructor creates LibRaw_file_datastream object from file fname.
  Unfortunately, C++ constructor cannot return an error. So if bad filename passed (e.g. nonexistent file) object is created as non-valid (valid() call returns zero).

All other class methods are described above.
This class implements all possible methods, including fname() and subfile_open().

#### class LibRaw_bigfile_datastream - file input interface

This class implements input from file.

Class methods:

LibRaw_bigfile_datastream(const char *fname)
  This constructor creates LibRaw_bigfile_datastream object from file fname.
  Unfortunately, C++ constructor cannot return an error. So if bad filename passed (e.g. nonexistent file) object is created as non-valid (valid() call returns zero).

The difference between file and bigfile datastreams are obvious from class name: bigfile one supports large files (more than 2Gb) on all supported systems. File one uses streambuf interface which is limited to 2Gb on many systems.

All other class methods are described above.
This class implements all possible methods, including fname() and subfile_open().

#### class LibRaw_buffer_datastream - memory buffer input interface

This class implements input from memory buffer.

Class methods:

LibRaw_buffer_datastream(void *buffer, size_t bsize)
  This constructor creates datastream object from buffer with size bsize.
  It is not possibly to verify the pointer passed, so buffer address is checked against 0 and -1 only.

All other class methods are described above.
This class does not implement fname() and subfile_open() calls, so external JPEG metadata parsing is not possible.

### Own datastream derived classes

To create own read interface LibRaw user should implement C++ class derived from LibRaw_abstract_datastream with all read methods.
LibRaw standard implementations may be used as reference. See libraw/libraw_datastream.h file for details (all standard LibRaw input classes are implemented using inline functions only).

[back to Index]