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