encode.h 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. // Copyright 2011 Google Inc. All Rights Reserved.
  2. //
  3. // This code is licensed under the same terms as WebM:
  4. // Software License Agreement: http://www.webmproject.org/license/software/
  5. // Additional IP Rights Grant: http://www.webmproject.org/license/additional/
  6. // -----------------------------------------------------------------------------
  7. //
  8. // WebP encoder: main interface
  9. //
  10. // Author: Skal (pascal.massimino@gmail.com)
  11. #ifndef WEBP_WEBP_ENCODE_H_
  12. #define WEBP_WEBP_ENCODE_H_
  13. #include "./types.h"
  14. #if defined(__cplusplus) || defined(c_plusplus)
  15. extern "C" {
  16. #endif
  17. #define WEBP_ENCODER_ABI_VERSION 0x0200 // MAJOR(8b) + MINOR(8b)
  18. // Return the encoder's version number, packed in hexadecimal using 8bits for
  19. // each of major/minor/revision. E.g: v2.5.7 is 0x020507.
  20. WEBP_EXTERN(int) WebPGetEncoderVersion(void);
  21. //------------------------------------------------------------------------------
  22. // One-stop-shop call! No questions asked:
  23. // Returns the size of the compressed data (pointed to by *output), or 0 if
  24. // an error occurred. The compressed data must be released by the caller
  25. // using the call 'free(*output)'.
  26. // These functions compress using the lossy format, and the quality_factor
  27. // can go from 0 (smaller output, lower quality) to 100 (best quality,
  28. // larger output).
  29. WEBP_EXTERN(size_t) WebPEncodeRGB(const uint8_t* rgb,
  30. int width, int height, int stride,
  31. float quality_factor, uint8_t** output);
  32. WEBP_EXTERN(size_t) WebPEncodeBGR(const uint8_t* bgr,
  33. int width, int height, int stride,
  34. float quality_factor, uint8_t** output);
  35. WEBP_EXTERN(size_t) WebPEncodeRGBA(const uint8_t* rgba,
  36. int width, int height, int stride,
  37. float quality_factor, uint8_t** output);
  38. WEBP_EXTERN(size_t) WebPEncodeBGRA(const uint8_t* bgra,
  39. int width, int height, int stride,
  40. float quality_factor, uint8_t** output);
  41. // These functions are the equivalent of the above, but compressing in a
  42. // lossless manner. Files are usually larger than lossy format, but will
  43. // not suffer any compression loss.
  44. WEBP_EXTERN(size_t) WebPEncodeLosslessRGB(const uint8_t* rgb,
  45. int width, int height, int stride,
  46. uint8_t** output);
  47. WEBP_EXTERN(size_t) WebPEncodeLosslessBGR(const uint8_t* bgr,
  48. int width, int height, int stride,
  49. uint8_t** output);
  50. WEBP_EXTERN(size_t) WebPEncodeLosslessRGBA(const uint8_t* rgba,
  51. int width, int height, int stride,
  52. uint8_t** output);
  53. WEBP_EXTERN(size_t) WebPEncodeLosslessBGRA(const uint8_t* bgra,
  54. int width, int height, int stride,
  55. uint8_t** output);
  56. //------------------------------------------------------------------------------
  57. // Coding parameters
  58. // Image characteristics hint for the underlying encoder.
  59. typedef enum {
  60. WEBP_HINT_DEFAULT = 0, // default preset.
  61. WEBP_HINT_PICTURE, // digital picture, like portrait, inner shot
  62. WEBP_HINT_PHOTO, // outdoor photograph, with natural lighting
  63. WEBP_HINT_GRAPH, // Discrete tone image (graph, map-tile etc).
  64. WEBP_HINT_LAST
  65. } WebPImageHint;
  66. typedef struct {
  67. int lossless; // Lossless encoding (0=lossy(default), 1=lossless).
  68. float quality; // between 0 (smallest file) and 100 (biggest)
  69. int method; // quality/speed trade-off (0=fast, 6=slower-better)
  70. WebPImageHint image_hint; // Hint for image type (lossless only for now).
  71. // Parameters related to lossy compression only:
  72. int target_size; // if non-zero, set the desired target size in bytes.
  73. // Takes precedence over the 'compression' parameter.
  74. float target_PSNR; // if non-zero, specifies the minimal distortion to
  75. // try to achieve. Takes precedence over target_size.
  76. int segments; // maximum number of segments to use, in [1..4]
  77. int sns_strength; // Spatial Noise Shaping. 0=off, 100=maximum.
  78. int filter_strength; // range: [0 = off .. 100 = strongest]
  79. int filter_sharpness; // range: [0 = off .. 7 = least sharp]
  80. int filter_type; // filtering type: 0 = simple, 1 = strong (only used
  81. // if filter_strength > 0 or autofilter > 0)
  82. int autofilter; // Auto adjust filter's strength [0 = off, 1 = on]
  83. int alpha_compression; // Algorithm for encoding the alpha plane (0 = none,
  84. // 1 = compressed with WebP lossless). Default is 1.
  85. int alpha_filtering; // Predictive filtering method for alpha plane.
  86. // 0: none, 1: fast, 2: best. Default if 1.
  87. int alpha_quality; // Between 0 (smallest size) and 100 (lossless).
  88. // Default is 100.
  89. int pass; // number of entropy-analysis passes (in [1..10]).
  90. int show_compressed; // if true, export the compressed picture back.
  91. // In-loop filtering is not applied.
  92. int preprocessing; // preprocessing filter (0=none, 1=segment-smooth)
  93. int partitions; // log2(number of token partitions) in [0..3]. Default
  94. // is set to 0 for easier progressive decoding.
  95. int partition_limit; // quality degradation allowed to fit the 512k limit
  96. // on prediction modes coding (0: no degradation,
  97. // 100: maximum possible degradation).
  98. uint32_t pad[8]; // padding for later use
  99. } WebPConfig;
  100. // Enumerate some predefined settings for WebPConfig, depending on the type
  101. // of source picture. These presets are used when calling WebPConfigPreset().
  102. typedef enum {
  103. WEBP_PRESET_DEFAULT = 0, // default preset.
  104. WEBP_PRESET_PICTURE, // digital picture, like portrait, inner shot
  105. WEBP_PRESET_PHOTO, // outdoor photograph, with natural lighting
  106. WEBP_PRESET_DRAWING, // hand or line drawing, with high-contrast details
  107. WEBP_PRESET_ICON, // small-sized colorful images
  108. WEBP_PRESET_TEXT // text-like
  109. } WebPPreset;
  110. // Internal, version-checked, entry point
  111. WEBP_EXTERN(int) WebPConfigInitInternal(WebPConfig*, WebPPreset, float, int);
  112. // Should always be called, to initialize a fresh WebPConfig structure before
  113. // modification. Returns false in case of version mismatch. WebPConfigInit()
  114. // must have succeeded before using the 'config' object.
  115. // Note that the default values are lossless=0 and quality=75.
  116. static WEBP_INLINE int WebPConfigInit(WebPConfig* config) {
  117. return WebPConfigInitInternal(config, WEBP_PRESET_DEFAULT, 75.f,
  118. WEBP_ENCODER_ABI_VERSION);
  119. }
  120. // This function will initialize the configuration according to a predefined
  121. // set of parameters (referred to by 'preset') and a given quality factor.
  122. // This function can be called as a replacement to WebPConfigInit(). Will
  123. // return false in case of error.
  124. static WEBP_INLINE int WebPConfigPreset(WebPConfig* config,
  125. WebPPreset preset, float quality) {
  126. return WebPConfigInitInternal(config, preset, quality,
  127. WEBP_ENCODER_ABI_VERSION);
  128. }
  129. // Returns true if 'config' is non-NULL and all configuration parameters are
  130. // within their valid ranges.
  131. WEBP_EXTERN(int) WebPValidateConfig(const WebPConfig* config);
  132. //------------------------------------------------------------------------------
  133. // Input / Output
  134. typedef struct WebPPicture WebPPicture; // main structure for I/O
  135. // Structure for storing auxiliary statistics (mostly for lossy encoding).
  136. typedef struct {
  137. int coded_size; // final size
  138. float PSNR[5]; // peak-signal-to-noise ratio for Y/U/V/All/Alpha
  139. int block_count[3]; // number of intra4/intra16/skipped macroblocks
  140. int header_bytes[2]; // approximate number of bytes spent for header
  141. // and mode-partition #0
  142. int residual_bytes[3][4]; // approximate number of bytes spent for
  143. // DC/AC/uv coefficients for each (0..3) segments.
  144. int segment_size[4]; // number of macroblocks in each segments
  145. int segment_quant[4]; // quantizer values for each segments
  146. int segment_level[4]; // filtering strength for each segments [0..63]
  147. int alpha_data_size; // size of the transparency data
  148. int layer_data_size; // size of the enhancement layer data
  149. // lossless encoder statistics
  150. uint32_t lossless_features; // bit0:predictor bit1:cross-color transform
  151. // bit2:subtract-green bit3:color indexing
  152. int histogram_bits; // number of precision bits of histogram
  153. int transform_bits; // precision bits for transform
  154. int cache_bits; // number of bits for color cache lookup
  155. int palette_size; // number of color in palette, if used
  156. int lossless_size; // final lossless size
  157. uint32_t pad[4]; // padding for later use
  158. } WebPAuxStats;
  159. // Signature for output function. Should return true if writing was successful.
  160. // data/data_size is the segment of data to write, and 'picture' is for
  161. // reference (and so one can make use of picture->custom_ptr).
  162. typedef int (*WebPWriterFunction)(const uint8_t* data, size_t data_size,
  163. const WebPPicture* picture);
  164. // WebPMemoryWrite: a special WebPWriterFunction that writes to memory using
  165. // the following WebPMemoryWriter object (to be set as a custom_ptr).
  166. typedef struct {
  167. uint8_t* mem; // final buffer (of size 'max_size', larger than 'size').
  168. size_t size; // final size
  169. size_t max_size; // total capacity
  170. uint32_t pad[1]; // padding for later use
  171. } WebPMemoryWriter;
  172. // The following must be called first before any use.
  173. WEBP_EXTERN(void) WebPMemoryWriterInit(WebPMemoryWriter* writer);
  174. // The custom writer to be used with WebPMemoryWriter as custom_ptr. Upon
  175. // completion, writer.mem and writer.size will hold the coded data.
  176. WEBP_EXTERN(int) WebPMemoryWrite(const uint8_t* data, size_t data_size,
  177. const WebPPicture* picture);
  178. // Progress hook, called from time to time to report progress. It can return
  179. // false to request an abort of the encoding process, or true otherwise if
  180. // everything is OK.
  181. typedef int (*WebPProgressHook)(int percent, const WebPPicture* picture);
  182. typedef enum {
  183. // chroma sampling
  184. WEBP_YUV420 = 0, // 4:2:0
  185. WEBP_YUV422 = 1, // 4:2:2
  186. WEBP_YUV444 = 2, // 4:4:4
  187. WEBP_YUV400 = 3, // grayscale
  188. WEBP_CSP_UV_MASK = 3, // bit-mask to get the UV sampling factors
  189. // alpha channel variants
  190. WEBP_YUV420A = 4,
  191. WEBP_YUV422A = 5,
  192. WEBP_YUV444A = 6,
  193. WEBP_YUV400A = 7, // grayscale + alpha
  194. WEBP_CSP_ALPHA_BIT = 4 // bit that is set if alpha is present
  195. } WebPEncCSP;
  196. // Encoding error conditions.
  197. typedef enum {
  198. VP8_ENC_OK = 0,
  199. VP8_ENC_ERROR_OUT_OF_MEMORY, // memory error allocating objects
  200. VP8_ENC_ERROR_BITSTREAM_OUT_OF_MEMORY, // memory error while flushing bits
  201. VP8_ENC_ERROR_NULL_PARAMETER, // a pointer parameter is NULL
  202. VP8_ENC_ERROR_INVALID_CONFIGURATION, // configuration is invalid
  203. VP8_ENC_ERROR_BAD_DIMENSION, // picture has invalid width/height
  204. VP8_ENC_ERROR_PARTITION0_OVERFLOW, // partition is bigger than 512k
  205. VP8_ENC_ERROR_PARTITION_OVERFLOW, // partition is bigger than 16M
  206. VP8_ENC_ERROR_BAD_WRITE, // error while flushing bytes
  207. VP8_ENC_ERROR_FILE_TOO_BIG, // file is bigger than 4G
  208. VP8_ENC_ERROR_USER_ABORT, // abort request by user
  209. VP8_ENC_ERROR_LAST // list terminator. always last.
  210. } WebPEncodingError;
  211. // maximum width/height allowed (inclusive), in pixels
  212. #define WEBP_MAX_DIMENSION 16383
  213. // Main exchange structure (input samples, output bytes, statistics)
  214. struct WebPPicture {
  215. // INPUT
  216. //////////////
  217. // Main flag for encoder selecting between ARGB or YUV input.
  218. // It is recommended to use ARGB input (*argb, argb_stride) for lossless
  219. // compression, and YUV input (*y, *u, *v, etc.) for lossy compression
  220. // since these are the respective native colorspace for these formats.
  221. int use_argb;
  222. // YUV input (mostly used for input to lossy compression)
  223. WebPEncCSP colorspace; // colorspace: should be YUV420 for now (=Y'CbCr).
  224. int width, height; // dimensions (less or equal to WEBP_MAX_DIMENSION)
  225. uint8_t *y, *u, *v; // pointers to luma/chroma planes.
  226. int y_stride, uv_stride; // luma/chroma strides.
  227. uint8_t* a; // pointer to the alpha plane
  228. int a_stride; // stride of the alpha plane
  229. uint32_t pad1[2]; // padding for later use
  230. // ARGB input (mostly used for input to lossless compression)
  231. uint32_t* argb; // Pointer to argb (32 bit) plane.
  232. int argb_stride; // This is stride in pixels units, not bytes.
  233. uint32_t pad2[3]; // padding for later use
  234. // OUTPUT
  235. ///////////////
  236. // Byte-emission hook, to store compressed bytes as they are ready.
  237. WebPWriterFunction writer; // can be NULL
  238. void* custom_ptr; // can be used by the writer.
  239. // map for extra information (only for lossy compression mode)
  240. int extra_info_type; // 1: intra type, 2: segment, 3: quant
  241. // 4: intra-16 prediction mode,
  242. // 5: chroma prediction mode,
  243. // 6: bit cost, 7: distortion
  244. uint8_t* extra_info; // if not NULL, points to an array of size
  245. // ((width + 15) / 16) * ((height + 15) / 16) that
  246. // will be filled with a macroblock map, depending
  247. // on extra_info_type.
  248. // STATS AND REPORTS
  249. ///////////////////////////
  250. // Pointer to side statistics (updated only if not NULL)
  251. WebPAuxStats* stats;
  252. // Error code for the latest error encountered during encoding
  253. WebPEncodingError error_code;
  254. // If not NULL, report progress during encoding.
  255. WebPProgressHook progress_hook;
  256. void* user_data; // this field is free to be set to any value and
  257. // used during callbacks (like progress-report e.g.).
  258. uint32_t pad3[3]; // padding for later use
  259. // Unused for now: original samples (for non-YUV420 modes)
  260. uint8_t *u0, *v0;
  261. int uv0_stride;
  262. uint32_t pad4[7]; // padding for later use
  263. // PRIVATE FIELDS
  264. ////////////////////
  265. void* memory_; // row chunk of memory for yuva planes
  266. void* memory_argb_; // and for argb too.
  267. void* pad5[2]; // padding for later use
  268. };
  269. // Internal, version-checked, entry point
  270. WEBP_EXTERN(int) WebPPictureInitInternal(WebPPicture*, int);
  271. // Should always be called, to initialize the structure. Returns false in case
  272. // of version mismatch. WebPPictureInit() must have succeeded before using the
  273. // 'picture' object.
  274. // Note that, by default, use_argb is false and colorspace is WEBP_YUV420.
  275. static WEBP_INLINE int WebPPictureInit(WebPPicture* picture) {
  276. return WebPPictureInitInternal(picture, WEBP_ENCODER_ABI_VERSION);
  277. }
  278. //------------------------------------------------------------------------------
  279. // WebPPicture utils
  280. // Convenience allocation / deallocation based on picture->width/height:
  281. // Allocate y/u/v buffers as per colorspace/width/height specification.
  282. // Note! This function will free the previous buffer if needed.
  283. // Returns false in case of memory error.
  284. WEBP_EXTERN(int) WebPPictureAlloc(WebPPicture* picture);
  285. // Release the memory allocated by WebPPictureAlloc() or WebPPictureImport*().
  286. // Note that this function does _not_ free the memory used by the 'picture'
  287. // object itself.
  288. // Besides memory (which is reclaimed) all other fields of 'picture' are
  289. // preserved.
  290. WEBP_EXTERN(void) WebPPictureFree(WebPPicture* picture);
  291. // Copy the pixels of *src into *dst, using WebPPictureAlloc. Upon return,
  292. // *dst will fully own the copied pixels (this is not a view).
  293. // Returns false in case of memory allocation error.
  294. WEBP_EXTERN(int) WebPPictureCopy(const WebPPicture* src, WebPPicture* dst);
  295. // Compute PSNR or SSIM distortion between two pictures.
  296. // Result is in dB, stores in result[] in the Y/U/V/Alpha/All order.
  297. // Returns false in case of error (pic1 and pic2 don't have same dimension, ...)
  298. // Warning: this function is rather CPU-intensive.
  299. WEBP_EXTERN(int) WebPPictureDistortion(
  300. const WebPPicture* pic1, const WebPPicture* pic2,
  301. int metric_type, // 0 = PSNR, 1 = SSIM
  302. float result[5]);
  303. // self-crops a picture to the rectangle defined by top/left/width/height.
  304. // Returns false in case of memory allocation error, or if the rectangle is
  305. // outside of the source picture.
  306. // The rectangle for the view is defined by the top-left corner pixel
  307. // coordinates (left, top) as well as its width and height. This rectangle
  308. // must be fully be comprised inside the 'src' source picture. If the source
  309. // picture uses the YUV420 colorspace, the top and left coordinates will be
  310. // snapped to even values.
  311. WEBP_EXTERN(int) WebPPictureCrop(WebPPicture* picture,
  312. int left, int top, int width, int height);
  313. // Extracts a view from 'src' picture into 'dst'. The rectangle for the view
  314. // is defined by the top-left corner pixel coordinates (left, top) as well
  315. // as its width and height. This rectangle must be fully be comprised inside
  316. // the 'src' source picture. If the source picture uses the YUV420 colorspace,
  317. // the top and left coordinates will be snapped to even values.
  318. // Picture 'src' must out-live 'dst' picture. Self-extraction of view is allowed
  319. // ('src' equal to 'dst') as a mean of fast-cropping (but note that doing so,
  320. // the original dimension will be lost).
  321. // Returns false in case of memory allocation error or invalid parameters.
  322. WEBP_EXTERN(int) WebPPictureView(const WebPPicture* src,
  323. int left, int top, int width, int height,
  324. WebPPicture* dst);
  325. // Returns true if the 'picture' is actually a view and therefore does
  326. // not own the memory for pixels.
  327. WEBP_EXTERN(int) WebPPictureIsView(const WebPPicture* picture);
  328. // Rescale a picture to new dimension width x height.
  329. // Now gamma correction is applied.
  330. // Returns false in case of error (invalid parameter or insufficient memory).
  331. WEBP_EXTERN(int) WebPPictureRescale(WebPPicture* pic, int width, int height);
  332. // Colorspace conversion function to import RGB samples.
  333. // Previous buffer will be free'd, if any.
  334. // *rgb buffer should have a size of at least height * rgb_stride.
  335. // Returns false in case of memory error.
  336. WEBP_EXTERN(int) WebPPictureImportRGB(
  337. WebPPicture* picture, const uint8_t* rgb, int rgb_stride);
  338. // Same, but for RGBA buffer.
  339. WEBP_EXTERN(int) WebPPictureImportRGBA(
  340. WebPPicture* picture, const uint8_t* rgba, int rgba_stride);
  341. // Same, but for RGBA buffer. Imports the RGB direct from the 32-bit format
  342. // input buffer ignoring the alpha channel. Avoids needing to copy the data
  343. // to a temporary 24-bit RGB buffer to import the RGB only.
  344. WEBP_EXTERN(int) WebPPictureImportRGBX(
  345. WebPPicture* picture, const uint8_t* rgbx, int rgbx_stride);
  346. // Variants of the above, but taking BGR(A|X) input.
  347. WEBP_EXTERN(int) WebPPictureImportBGR(
  348. WebPPicture* picture, const uint8_t* bgr, int bgr_stride);
  349. WEBP_EXTERN(int) WebPPictureImportBGRA(
  350. WebPPicture* picture, const uint8_t* bgra, int bgra_stride);
  351. WEBP_EXTERN(int) WebPPictureImportBGRX(
  352. WebPPicture* picture, const uint8_t* bgrx, int bgrx_stride);
  353. // Converts picture->argb data to the YUVA format specified by 'colorspace'.
  354. // Upon return, picture->use_argb is set to false. The presence of real
  355. // non-opaque transparent values is detected, and 'colorspace' will be
  356. // adjusted accordingly. Note that this method is lossy.
  357. // Returns false in case of error.
  358. WEBP_EXTERN(int) WebPPictureARGBToYUVA(WebPPicture* picture,
  359. WebPEncCSP colorspace);
  360. // Converts picture->yuv to picture->argb and sets picture->use_argb to true.
  361. // The input format must be YUV_420 or YUV_420A.
  362. // Note that the use of this method is discouraged if one has access to the
  363. // raw ARGB samples, since using YUV420 is comparatively lossy. Also, the
  364. // conversion from YUV420 to ARGB incurs a small loss too.
  365. // Returns false in case of error.
  366. WEBP_EXTERN(int) WebPPictureYUVAToARGB(WebPPicture* picture);
  367. // Helper function: given a width x height plane of YUV(A) samples
  368. // (with stride 'stride'), clean-up the YUV samples under fully transparent
  369. // area, to help compressibility (no guarantee, though).
  370. WEBP_EXTERN(void) WebPCleanupTransparentArea(WebPPicture* picture);
  371. // Scan the picture 'picture' for the presence of non fully opaque alpha values.
  372. // Returns true in such case. Otherwise returns false (indicating that the
  373. // alpha plane can be ignored altogether e.g.).
  374. WEBP_EXTERN(int) WebPPictureHasTransparency(const WebPPicture* picture);
  375. //------------------------------------------------------------------------------
  376. // Main call
  377. // Main encoding call, after config and picture have been initialized.
  378. // 'picture' must be less than 16384x16384 in dimension (cf WEBP_MAX_DIMENSION),
  379. // and the 'config' object must be a valid one.
  380. // Returns false in case of error, true otherwise.
  381. // In case of error, picture->error_code is updated accordingly.
  382. // 'picture' can hold the source samples in both YUV(A) or ARGB input, depending
  383. // on the value of 'picture->use_argb'. It is highly recommended to use
  384. // the former for lossy encoding, and the latter for lossless encoding
  385. // (when config.lossless is true). Automatic conversion from one format to
  386. // another is provided but they both incur some loss.
  387. WEBP_EXTERN(int) WebPEncode(const WebPConfig* config, WebPPicture* picture);
  388. //------------------------------------------------------------------------------
  389. #if defined(__cplusplus) || defined(c_plusplus)
  390. } // extern "C"
  391. #endif
  392. #endif /* WEBP_WEBP_ENCODE_H_ */