1// Copyright 2010 Google Inc. All Rights Reserved.
2//
3// Use of this source code is governed by a BSD-style license
4// that can be found in the COPYING file in the root of the source
5// tree. An additional intellectual property rights grant can be found
6// in the file PATENTS. All contributing project authors may
7// be found in the AUTHORS file in the root of the source tree.
8// -----------------------------------------------------------------------------
9//
10//  Main decoding functions for WebP images.
11//
12// Author: Skal (pascal.massimino@gmail.com)
13
14#ifndef WEBP_WEBP_DECODE_H_
15#define WEBP_WEBP_DECODE_H_
16
17#include "./types.h"
18
19#if defined(__cplusplus) || defined(c_plusplus)
20extern "C" {
21#endif
22
23#define WEBP_DECODER_ABI_VERSION 0x0201    // MAJOR(8b) + MINOR(8b)
24
25// Note: forward declaring enumerations is not allowed in (strict) C and C++,
26// the types are left here for reference.
27// typedef enum VP8StatusCode VP8StatusCode;
28// typedef enum WEBP_CSP_MODE WEBP_CSP_MODE;
29typedef struct WebPRGBABuffer WebPRGBABuffer;
30typedef struct WebPYUVABuffer WebPYUVABuffer;
31typedef struct WebPDecBuffer WebPDecBuffer;
32typedef struct WebPIDecoder WebPIDecoder;
33typedef struct WebPBitstreamFeatures WebPBitstreamFeatures;
34typedef struct WebPDecoderOptions WebPDecoderOptions;
35typedef struct WebPDecoderConfig WebPDecoderConfig;
36
37// Return the decoder's version number, packed in hexadecimal using 8bits for
38// each of major/minor/revision. E.g: v2.5.7 is 0x020507.
39WEBP_EXTERN(int) WebPGetDecoderVersion(void);
40
41// Retrieve basic header information: width, height.
42// This function will also validate the header and return 0 in
43// case of formatting error.
44// Pointers 'width' and 'height' can be passed NULL if deemed irrelevant.
45WEBP_EXTERN(int) WebPGetInfo(const uint8_t* data, size_t data_size,
46                             int* width, int* height);
47
48// Decodes WebP images pointed to by 'data' and returns RGBA samples, along
49// with the dimensions in *width and *height. The ordering of samples in
50// memory is R, G, B, A, R, G, B, A... in scan order (endian-independent).
51// The returned pointer should be deleted calling free().
52// Returns NULL in case of error.
53WEBP_EXTERN(uint8_t*) WebPDecodeRGBA(const uint8_t* data, size_t data_size,
54                                     int* width, int* height);
55
56// Same as WebPDecodeRGBA, but returning A, R, G, B, A, R, G, B... ordered data.
57WEBP_EXTERN(uint8_t*) WebPDecodeARGB(const uint8_t* data, size_t data_size,
58                                     int* width, int* height);
59
60// Same as WebPDecodeRGBA, but returning B, G, R, A, B, G, R, A... ordered data.
61WEBP_EXTERN(uint8_t*) WebPDecodeBGRA(const uint8_t* data, size_t data_size,
62                                     int* width, int* height);
63
64// Same as WebPDecodeRGBA, but returning R, G, B, R, G, B... ordered data.
65// If the bitstream contains transparency, it is ignored.
66WEBP_EXTERN(uint8_t*) WebPDecodeRGB(const uint8_t* data, size_t data_size,
67                                    int* width, int* height);
68
69// Same as WebPDecodeRGB, but returning B, G, R, B, G, R... ordered data.
70WEBP_EXTERN(uint8_t*) WebPDecodeBGR(const uint8_t* data, size_t data_size,
71                                    int* width, int* height);
72
73
74// Decode WebP images pointed to by 'data' to Y'UV format(*). The pointer
75// returned is the Y samples buffer. Upon return, *u and *v will point to
76// the U and V chroma data. These U and V buffers need NOT be free()'d,
77// unlike the returned Y luma one. The dimension of the U and V planes
78// are both (*width + 1) / 2 and (*height + 1)/ 2.
79// Upon return, the Y buffer has a stride returned as '*stride', while U and V
80// have a common stride returned as '*uv_stride'.
81// Return NULL in case of error.
82// (*) Also named Y'CbCr. See: http://en.wikipedia.org/wiki/YCbCr
83WEBP_EXTERN(uint8_t*) WebPDecodeYUV(const uint8_t* data, size_t data_size,
84                                    int* width, int* height,
85                                    uint8_t** u, uint8_t** v,
86                                    int* stride, int* uv_stride);
87
88// These five functions are variants of the above ones, that decode the image
89// directly into a pre-allocated buffer 'output_buffer'. The maximum storage
90// available in this buffer is indicated by 'output_buffer_size'. If this
91// storage is not sufficient (or an error occurred), NULL is returned.
92// Otherwise, output_buffer is returned, for convenience.
93// The parameter 'output_stride' specifies the distance (in bytes)
94// between scanlines. Hence, output_buffer_size is expected to be at least
95// output_stride x picture-height.
96WEBP_EXTERN(uint8_t*) WebPDecodeRGBAInto(
97    const uint8_t* data, size_t data_size,
98    uint8_t* output_buffer, size_t output_buffer_size, int output_stride);
99WEBP_EXTERN(uint8_t*) WebPDecodeARGBInto(
100    const uint8_t* data, size_t data_size,
101    uint8_t* output_buffer, size_t output_buffer_size, int output_stride);
102WEBP_EXTERN(uint8_t*) WebPDecodeBGRAInto(
103    const uint8_t* data, size_t data_size,
104    uint8_t* output_buffer, size_t output_buffer_size, int output_stride);
105
106// RGB and BGR variants. Here too the transparency information, if present,
107// will be dropped and ignored.
108WEBP_EXTERN(uint8_t*) WebPDecodeRGBInto(
109    const uint8_t* data, size_t data_size,
110    uint8_t* output_buffer, size_t output_buffer_size, int output_stride);
111WEBP_EXTERN(uint8_t*) WebPDecodeBGRInto(
112    const uint8_t* data, size_t data_size,
113    uint8_t* output_buffer, size_t output_buffer_size, int output_stride);
114
115// WebPDecodeYUVInto() is a variant of WebPDecodeYUV() that operates directly
116// into pre-allocated luma/chroma plane buffers. This function requires the
117// strides to be passed: one for the luma plane and one for each of the
118// chroma ones. The size of each plane buffer is passed as 'luma_size',
119// 'u_size' and 'v_size' respectively.
120// Pointer to the luma plane ('*luma') is returned or NULL if an error occurred
121// during decoding (or because some buffers were found to be too small).
122WEBP_EXTERN(uint8_t*) WebPDecodeYUVInto(
123    const uint8_t* data, size_t data_size,
124    uint8_t* luma, size_t luma_size, int luma_stride,
125    uint8_t* u, size_t u_size, int u_stride,
126    uint8_t* v, size_t v_size, int v_stride);
127
128//------------------------------------------------------------------------------
129// Output colorspaces and buffer
130
131// Colorspaces
132// Note: the naming describes the byte-ordering of packed samples in memory.
133// For instance, MODE_BGRA relates to samples ordered as B,G,R,A,B,G,R,A,...
134// Non-capital names (e.g.:MODE_Argb) relates to pre-multiplied RGB channels.
135// RGBA-4444 and RGB-565 colorspaces are represented by following byte-order:
136// RGBA-4444: [r3 r2 r1 r0 g3 g2 g1 g0], [b3 b2 b1 b0 a3 a2 a1 a0], ...
137// RGB-565: [r4 r3 r2 r1 r0 g5 g4 g3], [g2 g1 g0 b4 b3 b2 b1 b0], ...
138// In the case WEBP_SWAP_16BITS_CSP is defined, the bytes are swapped for
139// these two modes:
140// RGBA-4444: [b3 b2 b1 b0 a3 a2 a1 a0], [r3 r2 r1 r0 g3 g2 g1 g0], ...
141// RGB-565: [g2 g1 g0 b4 b3 b2 b1 b0], [r4 r3 r2 r1 r0 g5 g4 g3], ...
142
143typedef enum WEBP_CSP_MODE {
144  MODE_RGB = 0, MODE_RGBA = 1,
145  MODE_BGR = 2, MODE_BGRA = 3,
146  MODE_ARGB = 4, MODE_RGBA_4444 = 5,
147  MODE_RGB_565 = 6,
148  // RGB-premultiplied transparent modes (alpha value is preserved)
149  MODE_rgbA = 7,
150  MODE_bgrA = 8,
151  MODE_Argb = 9,
152  MODE_rgbA_4444 = 10,
153  // YUV modes must come after RGB ones.
154  MODE_YUV = 11, MODE_YUVA = 12,  // yuv 4:2:0
155  MODE_LAST = 13
156} WEBP_CSP_MODE;
157
158// Some useful macros:
159static WEBP_INLINE int WebPIsPremultipliedMode(WEBP_CSP_MODE mode) {
160  return (mode == MODE_rgbA || mode == MODE_bgrA || mode == MODE_Argb ||
161          mode == MODE_rgbA_4444);
162}
163
164static WEBP_INLINE int WebPIsAlphaMode(WEBP_CSP_MODE mode) {
165  return (mode == MODE_RGBA || mode == MODE_BGRA || mode == MODE_ARGB ||
166          mode == MODE_RGBA_4444 || mode == MODE_YUVA ||
167          WebPIsPremultipliedMode(mode));
168}
169
170static WEBP_INLINE int WebPIsRGBMode(WEBP_CSP_MODE mode) {
171  return (mode < MODE_YUV);
172}
173
174//------------------------------------------------------------------------------
175// WebPDecBuffer: Generic structure for describing the output sample buffer.
176
177struct WebPRGBABuffer {    // view as RGBA
178  uint8_t* rgba;    // pointer to RGBA samples
179  int stride;       // stride in bytes from one scanline to the next.
180  size_t size;      // total size of the *rgba buffer.
181};
182
183struct WebPYUVABuffer {              // view as YUVA
184  uint8_t* y, *u, *v, *a;     // pointer to luma, chroma U/V, alpha samples
185  int y_stride;               // luma stride
186  int u_stride, v_stride;     // chroma strides
187  int a_stride;               // alpha stride
188  size_t y_size;              // luma plane size
189  size_t u_size, v_size;      // chroma planes size
190  size_t a_size;              // alpha-plane size
191};
192
193// Output buffer
194struct WebPDecBuffer {
195  WEBP_CSP_MODE colorspace;  // Colorspace.
196  int width, height;         // Dimensions.
197  int is_external_memory;    // If true, 'internal_memory' pointer is not used.
198  union {
199    WebPRGBABuffer RGBA;
200    WebPYUVABuffer YUVA;
201  } u;                       // Nameless union of buffer parameters.
202  uint32_t       pad[4];     // padding for later use
203
204  uint8_t* private_memory;   // Internally allocated memory (only when
205                             // is_external_memory is false). Should not be used
206                             // externally, but accessed via the buffer union.
207};
208
209// Internal, version-checked, entry point
210WEBP_EXTERN(int) WebPInitDecBufferInternal(WebPDecBuffer*, int);
211
212// Initialize the structure as empty. Must be called before any other use.
213// Returns false in case of version mismatch
214static WEBP_INLINE int WebPInitDecBuffer(WebPDecBuffer* buffer) {
215  return WebPInitDecBufferInternal(buffer, WEBP_DECODER_ABI_VERSION);
216}
217
218// Free any memory associated with the buffer. Must always be called last.
219// Note: doesn't free the 'buffer' structure itself.
220WEBP_EXTERN(void) WebPFreeDecBuffer(WebPDecBuffer* buffer);
221
222//------------------------------------------------------------------------------
223// Enumeration of the status codes
224
225typedef enum VP8StatusCode {
226  VP8_STATUS_OK = 0,
227  VP8_STATUS_OUT_OF_MEMORY,
228  VP8_STATUS_INVALID_PARAM,
229  VP8_STATUS_BITSTREAM_ERROR,
230  VP8_STATUS_UNSUPPORTED_FEATURE,
231  VP8_STATUS_SUSPENDED,
232  VP8_STATUS_USER_ABORT,
233  VP8_STATUS_NOT_ENOUGH_DATA
234} VP8StatusCode;
235
236//------------------------------------------------------------------------------
237// Incremental decoding
238//
239// This API allows streamlined decoding of partial data.
240// Picture can be incrementally decoded as data become available thanks to the
241// WebPIDecoder object. This object can be left in a SUSPENDED state if the
242// picture is only partially decoded, pending additional input.
243// Code example:
244//
245//   WebPInitDecBuffer(&buffer);
246//   buffer.colorspace = mode;
247//   ...
248//   WebPIDecoder* idec = WebPINewDecoder(&buffer);
249//   while (has_more_data) {
250//     // ... (get additional data)
251//     status = WebPIAppend(idec, new_data, new_data_size);
252//     if (status != VP8_STATUS_SUSPENDED ||
253//       break;
254//     }
255//
256//     // The above call decodes the current available buffer.
257//     // Part of the image can now be refreshed by calling to
258//     // WebPIDecGetRGB()/WebPIDecGetYUVA() etc.
259//   }
260//   WebPIDelete(idec);
261
262// Creates a new incremental decoder with the supplied buffer parameter.
263// This output_buffer can be passed NULL, in which case a default output buffer
264// is used (with MODE_RGB). Otherwise, an internal reference to 'output_buffer'
265// is kept, which means that the lifespan of 'output_buffer' must be larger than
266// that of the returned WebPIDecoder object.
267// The supplied 'output_buffer' content MUST NOT be changed between calls to
268// WebPIAppend() or WebPIUpdate() unless 'output_buffer.is_external_memory' is
269// set to 1. In such a case, it is allowed to modify the pointers, size and
270// stride of output_buffer.u.RGBA or output_buffer.u.YUVA, provided they remain
271// within valid bounds.
272// All other fields of WebPDecBuffer MUST remain constant between calls.
273// Returns NULL if the allocation failed.
274WEBP_EXTERN(WebPIDecoder*) WebPINewDecoder(WebPDecBuffer* output_buffer);
275
276// This function allocates and initializes an incremental-decoder object, which
277// will output the RGB/A samples specified by 'csp' into a preallocated
278// buffer 'output_buffer'. The size of this buffer is at least
279// 'output_buffer_size' and the stride (distance in bytes between two scanlines)
280// is specified by 'output_stride'.
281// Additionally, output_buffer can be passed NULL in which case the output
282// buffer will be allocated automatically when the decoding starts. The
283// colorspace 'csp' is taken into account for allocating this buffer. All other
284// parameters are ignored.
285// Returns NULL if the allocation failed, or if some parameters are invalid.
286WEBP_EXTERN(WebPIDecoder*) WebPINewRGB(
287    WEBP_CSP_MODE csp,
288    uint8_t* output_buffer, size_t output_buffer_size, int output_stride);
289
290// This function allocates and initializes an incremental-decoder object, which
291// will output the raw luma/chroma samples into a preallocated planes if
292// supplied. The luma plane is specified by its pointer 'luma', its size
293// 'luma_size' and its stride 'luma_stride'. Similarly, the chroma-u plane
294// is specified by the 'u', 'u_size' and 'u_stride' parameters, and the chroma-v
295// plane by 'v' and 'v_size'. And same for the alpha-plane. The 'a' pointer
296// can be pass NULL in case one is not interested in the transparency plane.
297// Conversely, 'luma' can be passed NULL if no preallocated planes are supplied.
298// In this case, the output buffer will be automatically allocated (using
299// MODE_YUVA) when decoding starts. All parameters are then ignored.
300// Returns NULL if the allocation failed or if a parameter is invalid.
301WEBP_EXTERN(WebPIDecoder*) WebPINewYUVA(
302    uint8_t* luma, size_t luma_size, int luma_stride,
303    uint8_t* u, size_t u_size, int u_stride,
304    uint8_t* v, size_t v_size, int v_stride,
305    uint8_t* a, size_t a_size, int a_stride);
306
307// Deprecated version of the above, without the alpha plane.
308// Kept for backward compatibility.
309WEBP_EXTERN(WebPIDecoder*) WebPINewYUV(
310    uint8_t* luma, size_t luma_size, int luma_stride,
311    uint8_t* u, size_t u_size, int u_stride,
312    uint8_t* v, size_t v_size, int v_stride);
313
314// Deletes the WebPIDecoder object and associated memory. Must always be called
315// if WebPINewDecoder, WebPINewRGB or WebPINewYUV succeeded.
316WEBP_EXTERN(void) WebPIDelete(WebPIDecoder* idec);
317
318// Copies and decodes the next available data. Returns VP8_STATUS_OK when
319// the image is successfully decoded. Returns VP8_STATUS_SUSPENDED when more
320// data is expected. Returns error in other cases.
321WEBP_EXTERN(VP8StatusCode) WebPIAppend(
322    WebPIDecoder* idec, const uint8_t* data, size_t data_size);
323
324// A variant of the above function to be used when data buffer contains
325// partial data from the beginning. In this case data buffer is not copied
326// to the internal memory.
327// Note that the value of the 'data' pointer can change between calls to
328// WebPIUpdate, for instance when the data buffer is resized to fit larger data.
329WEBP_EXTERN(VP8StatusCode) WebPIUpdate(
330    WebPIDecoder* idec, const uint8_t* data, size_t data_size);
331
332// Returns the RGB/A image decoded so far. Returns NULL if output params
333// are not initialized yet. The RGB/A output type corresponds to the colorspace
334// specified during call to WebPINewDecoder() or WebPINewRGB().
335// *last_y is the index of last decoded row in raster scan order. Some pointers
336// (*last_y, *width etc.) can be NULL if corresponding information is not
337// needed.
338WEBP_EXTERN(uint8_t*) WebPIDecGetRGB(
339    const WebPIDecoder* idec, int* last_y,
340    int* width, int* height, int* stride);
341
342// Same as above function to get a YUVA image. Returns pointer to the luma
343// plane or NULL in case of error. If there is no alpha information
344// the alpha pointer '*a' will be returned NULL.
345WEBP_EXTERN(uint8_t*) WebPIDecGetYUVA(
346    const WebPIDecoder* idec, int* last_y,
347    uint8_t** u, uint8_t** v, uint8_t** a,
348    int* width, int* height, int* stride, int* uv_stride, int* a_stride);
349
350// Deprecated alpha-less version of WebPIDecGetYUVA(): it will ignore the
351// alpha information (if present). Kept for backward compatibility.
352static WEBP_INLINE uint8_t* WebPIDecGetYUV(
353    const WebPIDecoder* idec, int* last_y, uint8_t** u, uint8_t** v,
354    int* width, int* height, int* stride, int* uv_stride) {
355  return WebPIDecGetYUVA(idec, last_y, u, v, NULL, width, height,
356                         stride, uv_stride, NULL);
357}
358
359// Generic call to retrieve information about the displayable area.
360// If non NULL, the left/right/width/height pointers are filled with the visible
361// rectangular area so far.
362// Returns NULL in case the incremental decoder object is in an invalid state.
363// Otherwise returns the pointer to the internal representation. This structure
364// is read-only, tied to WebPIDecoder's lifespan and should not be modified.
365WEBP_EXTERN(const WebPDecBuffer*) WebPIDecodedArea(
366    const WebPIDecoder* idec, int* left, int* top, int* width, int* height);
367
368//------------------------------------------------------------------------------
369// Advanced decoding parametrization
370//
371//  Code sample for using the advanced decoding API
372/*
373     // A) Init a configuration object
374     WebPDecoderConfig config;
375     CHECK(WebPInitDecoderConfig(&config));
376
377     // B) optional: retrieve the bitstream's features.
378     CHECK(WebPGetFeatures(data, data_size, &config.input) == VP8_STATUS_OK);
379
380     // C) Adjust 'config', if needed
381     config.no_fancy_upsampling = 1;
382     config.output.colorspace = MODE_BGRA;
383     // etc.
384
385     // Note that you can also make config.output point to an externally
386     // supplied memory buffer, provided it's big enough to store the decoded
387     // picture. Otherwise, config.output will just be used to allocate memory
388     // and store the decoded picture.
389
390     // D) Decode!
391     CHECK(WebPDecode(data, data_size, &config) == VP8_STATUS_OK);
392
393     // E) Decoded image is now in config.output (and config.output.u.RGBA)
394
395     // F) Reclaim memory allocated in config's object. It's safe to call
396     // this function even if the memory is external and wasn't allocated
397     // by WebPDecode().
398     WebPFreeDecBuffer(&config.output);
399*/
400
401// Features gathered from the bitstream
402struct WebPBitstreamFeatures {
403  int width;          // Width in pixels, as read from the bitstream.
404  int height;         // Height in pixels, as read from the bitstream.
405  int has_alpha;      // True if the bitstream contains an alpha channel.
406  int has_animation;  // True if the bitstream is an animation.
407
408  // Unused for now:
409  int bitstream_version;        // should be 0 for now. TODO(later)
410  int no_incremental_decoding;  // if true, using incremental decoding is not
411                                // recommended.
412  int rotate;                   // TODO(later)
413  int uv_sampling;              // should be 0 for now. TODO(later)
414  uint32_t pad[2];              // padding for later use
415};
416
417// Internal, version-checked, entry point
418WEBP_EXTERN(VP8StatusCode) WebPGetFeaturesInternal(
419    const uint8_t*, size_t, WebPBitstreamFeatures*, int);
420
421// Retrieve features from the bitstream. The *features structure is filled
422// with information gathered from the bitstream.
423// Returns VP8_STATUS_OK when the features are successfully retrieved. Returns
424// VP8_STATUS_NOT_ENOUGH_DATA when more data is needed to retrieve the
425// features from headers. Returns error in other cases.
426static WEBP_INLINE VP8StatusCode WebPGetFeatures(
427    const uint8_t* data, size_t data_size,
428    WebPBitstreamFeatures* features) {
429  return WebPGetFeaturesInternal(data, data_size, features,
430                                 WEBP_DECODER_ABI_VERSION);
431}
432
433// Decoding options
434struct WebPDecoderOptions {
435  int bypass_filtering;               // if true, skip the in-loop filtering
436  int no_fancy_upsampling;            // if true, use faster pointwise upsampler
437  int use_cropping;                   // if true, cropping is applied _first_
438  int crop_left, crop_top;            // top-left position for cropping.
439                                      // Will be snapped to even values.
440  int crop_width, crop_height;        // dimension of the cropping area
441  int use_scaling;                    // if true, scaling is applied _afterward_
442  int scaled_width, scaled_height;    // final resolution
443  int use_threads;                    // if true, use multi-threaded decoding
444
445  // Unused for now:
446  int force_rotation;                 // forced rotation (to be applied _last_)
447  int no_enhancement;                 // if true, discard enhancement layer
448  uint32_t pad[6];                    // padding for later use
449};
450
451// Main object storing the configuration for advanced decoding.
452struct WebPDecoderConfig {
453  WebPBitstreamFeatures input;  // Immutable bitstream features (optional)
454  WebPDecBuffer output;         // Output buffer (can point to external mem)
455  WebPDecoderOptions options;   // Decoding options
456};
457
458// Internal, version-checked, entry point
459WEBP_EXTERN(int) WebPInitDecoderConfigInternal(WebPDecoderConfig*, int);
460
461// Initialize the configuration as empty. This function must always be
462// called first, unless WebPGetFeatures() is to be called.
463// Returns false in case of mismatched version.
464static WEBP_INLINE int WebPInitDecoderConfig(WebPDecoderConfig* config) {
465  return WebPInitDecoderConfigInternal(config, WEBP_DECODER_ABI_VERSION);
466}
467
468// Instantiate a new incremental decoder object with the requested
469// configuration. The bitstream can be passed using 'data' and 'data_size'
470// parameter, in which case the features will be parsed and stored into
471// config->input. Otherwise, 'data' can be NULL and no parsing will occur.
472// Note that 'config' can be NULL too, in which case a default configuration
473// is used.
474// The return WebPIDecoder object must always be deleted calling WebPIDelete().
475// Returns NULL in case of error (and config->status will then reflect
476// the error condition).
477WEBP_EXTERN(WebPIDecoder*) WebPIDecode(const uint8_t* data, size_t data_size,
478                                       WebPDecoderConfig* config);
479
480// Non-incremental version. This version decodes the full data at once, taking
481// 'config' into account. Returns decoding status (which should be VP8_STATUS_OK
482// if the decoding was successful).
483WEBP_EXTERN(VP8StatusCode) WebPDecode(const uint8_t* data, size_t data_size,
484                                      WebPDecoderConfig* config);
485
486#if defined(__cplusplus) || defined(c_plusplus)
487}    // extern "C"
488#endif
489
490#endif  /* WEBP_WEBP_DECODE_H_ */
491