alpha_enc.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. // Copyright 2011 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. // Alpha-plane compression.
  11. //
  12. // Author: Skal (pascal.massimino@gmail.com)
  13. #include <assert.h>
  14. #include <stdlib.h>
  15. #include "./vp8i_enc.h"
  16. #include "../dsp/dsp.h"
  17. #include "../utils/filters_utils.h"
  18. #include "../utils/quant_levels_utils.h"
  19. #include "../utils/utils.h"
  20. #include "../webp/format_constants.h"
  21. // -----------------------------------------------------------------------------
  22. // Encodes the given alpha data via specified compression method 'method'.
  23. // The pre-processing (quantization) is performed if 'quality' is less than 100.
  24. // For such cases, the encoding is lossy. The valid range is [0, 100] for
  25. // 'quality' and [0, 1] for 'method':
  26. // 'method = 0' - No compression;
  27. // 'method = 1' - Use lossless coder on the alpha plane only
  28. // 'filter' values [0, 4] correspond to prediction modes none, horizontal,
  29. // vertical & gradient filters. The prediction mode 4 will try all the
  30. // prediction modes 0 to 3 and pick the best one.
  31. // 'effort_level': specifies how much effort must be spent to try and reduce
  32. // the compressed output size. In range 0 (quick) to 6 (slow).
  33. //
  34. // 'output' corresponds to the buffer containing compressed alpha data.
  35. // This buffer is allocated by this method and caller should call
  36. // WebPSafeFree(*output) when done.
  37. // 'output_size' corresponds to size of this compressed alpha buffer.
  38. //
  39. // Returns 1 on successfully encoding the alpha and
  40. // 0 if either:
  41. // invalid quality or method, or
  42. // memory allocation for the compressed data fails.
  43. #include "./vp8li_enc.h"
  44. static int EncodeLossless(const uint8_t* const data, int width, int height,
  45. int effort_level, // in [0..6] range
  46. int use_quality_100, VP8LBitWriter* const bw,
  47. WebPAuxStats* const stats) {
  48. int ok = 0;
  49. WebPConfig config;
  50. WebPPicture picture;
  51. WebPPictureInit(&picture);
  52. picture.width = width;
  53. picture.height = height;
  54. picture.use_argb = 1;
  55. picture.stats = stats;
  56. if (!WebPPictureAlloc(&picture)) return 0;
  57. // Transfer the alpha values to the green channel.
  58. WebPDispatchAlphaToGreen(data, width, picture.width, picture.height,
  59. picture.argb, picture.argb_stride);
  60. WebPConfigInit(&config);
  61. config.lossless = 1;
  62. // Enable exact, or it would alter RGB values of transparent alpha, which is
  63. // normally OK but not here since we are not encoding the input image but an
  64. // internal encoding-related image containing necessary exact information in
  65. // RGB channels.
  66. config.exact = 1;
  67. config.method = effort_level; // impact is very small
  68. // Set a low default quality for encoding alpha. Ensure that Alpha quality at
  69. // lower methods (3 and below) is less than the threshold for triggering
  70. // costly 'BackwardReferencesTraceBackwards'.
  71. // If the alpha quality is set to 100 and the method to 6, allow for a high
  72. // lossless quality to trigger the cruncher.
  73. config.quality =
  74. (use_quality_100 && effort_level == 6) ? 100 : 8.f * effort_level;
  75. assert(config.quality >= 0 && config.quality <= 100.f);
  76. // TODO(urvang): Temporary fix to avoid generating images that trigger
  77. // a decoder bug related to alpha with color cache.
  78. // See: https://code.google.com/p/webp/issues/detail?id=239
  79. // Need to re-enable this later.
  80. ok = (VP8LEncodeStream(&config, &picture, bw, 0 /*use_cache*/) == VP8_ENC_OK);
  81. WebPPictureFree(&picture);
  82. ok = ok && !bw->error_;
  83. if (!ok) {
  84. VP8LBitWriterWipeOut(bw);
  85. return 0;
  86. }
  87. return 1;
  88. }
  89. // -----------------------------------------------------------------------------
  90. // Small struct to hold the result of a filter mode compression attempt.
  91. typedef struct {
  92. size_t score;
  93. VP8BitWriter bw;
  94. WebPAuxStats stats;
  95. } FilterTrial;
  96. // This function always returns an initialized 'bw' object, even upon error.
  97. static int EncodeAlphaInternal(const uint8_t* const data, int width, int height,
  98. int method, int filter, int reduce_levels,
  99. int effort_level, // in [0..6] range
  100. uint8_t* const tmp_alpha,
  101. FilterTrial* result) {
  102. int ok = 0;
  103. const uint8_t* alpha_src;
  104. WebPFilterFunc filter_func;
  105. uint8_t header;
  106. const size_t data_size = width * height;
  107. const uint8_t* output = NULL;
  108. size_t output_size = 0;
  109. VP8LBitWriter tmp_bw;
  110. assert((uint64_t)data_size == (uint64_t)width * height); // as per spec
  111. assert(filter >= 0 && filter < WEBP_FILTER_LAST);
  112. assert(method >= ALPHA_NO_COMPRESSION);
  113. assert(method <= ALPHA_LOSSLESS_COMPRESSION);
  114. assert(sizeof(header) == ALPHA_HEADER_LEN);
  115. filter_func = WebPFilters[filter];
  116. if (filter_func != NULL) {
  117. filter_func(data, width, height, width, tmp_alpha);
  118. alpha_src = tmp_alpha;
  119. } else {
  120. alpha_src = data;
  121. }
  122. if (method != ALPHA_NO_COMPRESSION) {
  123. ok = VP8LBitWriterInit(&tmp_bw, data_size >> 3);
  124. ok = ok && EncodeLossless(alpha_src, width, height, effort_level,
  125. !reduce_levels, &tmp_bw, &result->stats);
  126. if (ok) {
  127. output = VP8LBitWriterFinish(&tmp_bw);
  128. output_size = VP8LBitWriterNumBytes(&tmp_bw);
  129. if (output_size > data_size) {
  130. // compressed size is larger than source! Revert to uncompressed mode.
  131. method = ALPHA_NO_COMPRESSION;
  132. VP8LBitWriterWipeOut(&tmp_bw);
  133. }
  134. } else {
  135. VP8LBitWriterWipeOut(&tmp_bw);
  136. return 0;
  137. }
  138. }
  139. if (method == ALPHA_NO_COMPRESSION) {
  140. output = alpha_src;
  141. output_size = data_size;
  142. ok = 1;
  143. }
  144. // Emit final result.
  145. header = method | (filter << 2);
  146. if (reduce_levels) header |= ALPHA_PREPROCESSED_LEVELS << 4;
  147. VP8BitWriterInit(&result->bw, ALPHA_HEADER_LEN + output_size);
  148. ok = ok && VP8BitWriterAppend(&result->bw, &header, ALPHA_HEADER_LEN);
  149. ok = ok && VP8BitWriterAppend(&result->bw, output, output_size);
  150. if (method != ALPHA_NO_COMPRESSION) {
  151. VP8LBitWriterWipeOut(&tmp_bw);
  152. }
  153. ok = ok && !result->bw.error_;
  154. result->score = VP8BitWriterSize(&result->bw);
  155. return ok;
  156. }
  157. // -----------------------------------------------------------------------------
  158. static int GetNumColors(const uint8_t* data, int width, int height,
  159. int stride) {
  160. int j;
  161. int colors = 0;
  162. uint8_t color[256] = { 0 };
  163. for (j = 0; j < height; ++j) {
  164. int i;
  165. const uint8_t* const p = data + j * stride;
  166. for (i = 0; i < width; ++i) {
  167. color[p[i]] = 1;
  168. }
  169. }
  170. for (j = 0; j < 256; ++j) {
  171. if (color[j] > 0) ++colors;
  172. }
  173. return colors;
  174. }
  175. #define FILTER_TRY_NONE (1 << WEBP_FILTER_NONE)
  176. #define FILTER_TRY_ALL ((1 << WEBP_FILTER_LAST) - 1)
  177. // Given the input 'filter' option, return an OR'd bit-set of filters to try.
  178. static uint32_t GetFilterMap(const uint8_t* alpha, int width, int height,
  179. int filter, int effort_level) {
  180. uint32_t bit_map = 0U;
  181. if (filter == WEBP_FILTER_FAST) {
  182. // Quick estimate of the best candidate.
  183. int try_filter_none = (effort_level > 3);
  184. const int kMinColorsForFilterNone = 16;
  185. const int kMaxColorsForFilterNone = 192;
  186. const int num_colors = GetNumColors(alpha, width, height, width);
  187. // For low number of colors, NONE yields better compression.
  188. filter = (num_colors <= kMinColorsForFilterNone)
  189. ? WEBP_FILTER_NONE
  190. : WebPEstimateBestFilter(alpha, width, height, width);
  191. bit_map |= 1 << filter;
  192. // For large number of colors, try FILTER_NONE in addition to the best
  193. // filter as well.
  194. if (try_filter_none || num_colors > kMaxColorsForFilterNone) {
  195. bit_map |= FILTER_TRY_NONE;
  196. }
  197. } else if (filter == WEBP_FILTER_NONE) {
  198. bit_map = FILTER_TRY_NONE;
  199. } else { // WEBP_FILTER_BEST -> try all
  200. bit_map = FILTER_TRY_ALL;
  201. }
  202. return bit_map;
  203. }
  204. static void InitFilterTrial(FilterTrial* const score) {
  205. score->score = (size_t)~0U;
  206. VP8BitWriterInit(&score->bw, 0);
  207. }
  208. static int ApplyFiltersAndEncode(const uint8_t* alpha, int width, int height,
  209. size_t data_size, int method, int filter,
  210. int reduce_levels, int effort_level,
  211. uint8_t** const output,
  212. size_t* const output_size,
  213. WebPAuxStats* const stats) {
  214. int ok = 1;
  215. FilterTrial best;
  216. uint32_t try_map =
  217. GetFilterMap(alpha, width, height, filter, effort_level);
  218. InitFilterTrial(&best);
  219. if (try_map != FILTER_TRY_NONE) {
  220. uint8_t* filtered_alpha = (uint8_t*)WebPSafeMalloc(1ULL, data_size);
  221. if (filtered_alpha == NULL) return 0;
  222. for (filter = WEBP_FILTER_NONE; ok && try_map; ++filter, try_map >>= 1) {
  223. if (try_map & 1) {
  224. FilterTrial trial;
  225. ok = EncodeAlphaInternal(alpha, width, height, method, filter,
  226. reduce_levels, effort_level, filtered_alpha,
  227. &trial);
  228. if (ok && trial.score < best.score) {
  229. VP8BitWriterWipeOut(&best.bw);
  230. best = trial;
  231. } else {
  232. VP8BitWriterWipeOut(&trial.bw);
  233. }
  234. }
  235. }
  236. WebPSafeFree(filtered_alpha);
  237. } else {
  238. ok = EncodeAlphaInternal(alpha, width, height, method, WEBP_FILTER_NONE,
  239. reduce_levels, effort_level, NULL, &best);
  240. }
  241. if (ok) {
  242. #if !defined(WEBP_DISABLE_STATS)
  243. if (stats != NULL) {
  244. stats->lossless_features = best.stats.lossless_features;
  245. stats->histogram_bits = best.stats.histogram_bits;
  246. stats->transform_bits = best.stats.transform_bits;
  247. stats->cache_bits = best.stats.cache_bits;
  248. stats->palette_size = best.stats.palette_size;
  249. stats->lossless_size = best.stats.lossless_size;
  250. stats->lossless_hdr_size = best.stats.lossless_hdr_size;
  251. stats->lossless_data_size = best.stats.lossless_data_size;
  252. }
  253. #else
  254. (void)stats;
  255. #endif
  256. *output_size = VP8BitWriterSize(&best.bw);
  257. *output = VP8BitWriterBuf(&best.bw);
  258. } else {
  259. VP8BitWriterWipeOut(&best.bw);
  260. }
  261. return ok;
  262. }
  263. static int EncodeAlpha(VP8Encoder* const enc,
  264. int quality, int method, int filter,
  265. int effort_level,
  266. uint8_t** const output, size_t* const output_size) {
  267. const WebPPicture* const pic = enc->pic_;
  268. const int width = pic->width;
  269. const int height = pic->height;
  270. uint8_t* quant_alpha = NULL;
  271. const size_t data_size = width * height;
  272. uint64_t sse = 0;
  273. int ok = 1;
  274. const int reduce_levels = (quality < 100);
  275. // quick correctness checks
  276. assert((uint64_t)data_size == (uint64_t)width * height); // as per spec
  277. assert(enc != NULL && pic != NULL && pic->a != NULL);
  278. assert(output != NULL && output_size != NULL);
  279. assert(width > 0 && height > 0);
  280. assert(pic->a_stride >= width);
  281. assert(filter >= WEBP_FILTER_NONE && filter <= WEBP_FILTER_FAST);
  282. if (quality < 0 || quality > 100) {
  283. return 0;
  284. }
  285. if (method < ALPHA_NO_COMPRESSION || method > ALPHA_LOSSLESS_COMPRESSION) {
  286. return 0;
  287. }
  288. if (method == ALPHA_NO_COMPRESSION) {
  289. // Don't filter, as filtering will make no impact on compressed size.
  290. filter = WEBP_FILTER_NONE;
  291. }
  292. quant_alpha = (uint8_t*)WebPSafeMalloc(1ULL, data_size);
  293. if (quant_alpha == NULL) {
  294. return 0;
  295. }
  296. // Extract alpha data (width x height) from raw_data (stride x height).
  297. WebPCopyPlane(pic->a, pic->a_stride, quant_alpha, width, width, height);
  298. if (reduce_levels) { // No Quantization required for 'quality = 100'.
  299. // 16 alpha levels gives quite a low MSE w.r.t original alpha plane hence
  300. // mapped to moderate quality 70. Hence Quality:[0, 70] -> Levels:[2, 16]
  301. // and Quality:]70, 100] -> Levels:]16, 256].
  302. const int alpha_levels = (quality <= 70) ? (2 + quality / 5)
  303. : (16 + (quality - 70) * 8);
  304. ok = QuantizeLevels(quant_alpha, width, height, alpha_levels, &sse);
  305. }
  306. if (ok) {
  307. VP8FiltersInit();
  308. ok = ApplyFiltersAndEncode(quant_alpha, width, height, data_size, method,
  309. filter, reduce_levels, effort_level, output,
  310. output_size, pic->stats);
  311. #if !defined(WEBP_DISABLE_STATS)
  312. if (pic->stats != NULL) { // need stats?
  313. pic->stats->coded_size += (int)(*output_size);
  314. enc->sse_[3] = sse;
  315. }
  316. #endif
  317. }
  318. WebPSafeFree(quant_alpha);
  319. return ok;
  320. }
  321. //------------------------------------------------------------------------------
  322. // Main calls
  323. static int CompressAlphaJob(void* arg1, void* unused) {
  324. VP8Encoder* const enc = (VP8Encoder*)arg1;
  325. const WebPConfig* config = enc->config_;
  326. uint8_t* alpha_data = NULL;
  327. size_t alpha_size = 0;
  328. const int effort_level = config->method; // maps to [0..6]
  329. const WEBP_FILTER_TYPE filter =
  330. (config->alpha_filtering == 0) ? WEBP_FILTER_NONE :
  331. (config->alpha_filtering == 1) ? WEBP_FILTER_FAST :
  332. WEBP_FILTER_BEST;
  333. if (!EncodeAlpha(enc, config->alpha_quality, config->alpha_compression,
  334. filter, effort_level, &alpha_data, &alpha_size)) {
  335. return 0;
  336. }
  337. if (alpha_size != (uint32_t)alpha_size) { // Soundness check.
  338. WebPSafeFree(alpha_data);
  339. return 0;
  340. }
  341. enc->alpha_data_size_ = (uint32_t)alpha_size;
  342. enc->alpha_data_ = alpha_data;
  343. (void)unused;
  344. return 1;
  345. }
  346. void VP8EncInitAlpha(VP8Encoder* const enc) {
  347. WebPInitAlphaProcessing();
  348. enc->has_alpha_ = WebPPictureHasTransparency(enc->pic_);
  349. enc->alpha_data_ = NULL;
  350. enc->alpha_data_size_ = 0;
  351. if (enc->thread_level_ > 0) {
  352. WebPWorker* const worker = &enc->alpha_worker_;
  353. WebPGetWorkerInterface()->Init(worker);
  354. worker->data1 = enc;
  355. worker->data2 = NULL;
  356. worker->hook = CompressAlphaJob;
  357. }
  358. }
  359. int VP8EncStartAlpha(VP8Encoder* const enc) {
  360. if (enc->has_alpha_) {
  361. if (enc->thread_level_ > 0) {
  362. WebPWorker* const worker = &enc->alpha_worker_;
  363. // Makes sure worker is good to go.
  364. if (!WebPGetWorkerInterface()->Reset(worker)) {
  365. return 0;
  366. }
  367. WebPGetWorkerInterface()->Launch(worker);
  368. return 1;
  369. } else {
  370. return CompressAlphaJob(enc, NULL); // just do the job right away
  371. }
  372. }
  373. return 1;
  374. }
  375. int VP8EncFinishAlpha(VP8Encoder* const enc) {
  376. if (enc->has_alpha_) {
  377. if (enc->thread_level_ > 0) {
  378. WebPWorker* const worker = &enc->alpha_worker_;
  379. if (!WebPGetWorkerInterface()->Sync(worker)) return 0; // error
  380. }
  381. }
  382. return WebPReportProgress(enc->pic_, enc->percent_ + 20, &enc->percent_);
  383. }
  384. int VP8EncDeleteAlpha(VP8Encoder* const enc) {
  385. int ok = 1;
  386. if (enc->thread_level_ > 0) {
  387. WebPWorker* const worker = &enc->alpha_worker_;
  388. // finish anything left in flight
  389. ok = WebPGetWorkerInterface()->Sync(worker);
  390. // still need to end the worker, even if !ok
  391. WebPGetWorkerInterface()->End(worker);
  392. }
  393. WebPSafeFree(enc->alpha_data_);
  394. enc->alpha_data_ = NULL;
  395. enc->alpha_data_size_ = 0;
  396. enc->has_alpha_ = 0;
  397. return ok;
  398. }