alpha_enc.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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 "../enc/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. 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. config.quality = 8.f * effort_level;
  72. assert(config.quality >= 0 && config.quality <= 100.f);
  73. // TODO(urvang): Temporary fix to avoid generating images that trigger
  74. // a decoder bug related to alpha with color cache.
  75. // See: https://code.google.com/p/webp/issues/detail?id=239
  76. // Need to re-enable this later.
  77. ok = (VP8LEncodeStream(&config, &picture, bw, 0 /*use_cache*/) == VP8_ENC_OK);
  78. WebPPictureFree(&picture);
  79. ok = ok && !bw->error_;
  80. if (!ok) {
  81. VP8LBitWriterWipeOut(bw);
  82. return 0;
  83. }
  84. return 1;
  85. }
  86. // -----------------------------------------------------------------------------
  87. // Small struct to hold the result of a filter mode compression attempt.
  88. typedef struct {
  89. size_t score;
  90. VP8BitWriter bw;
  91. WebPAuxStats stats;
  92. } FilterTrial;
  93. // This function always returns an initialized 'bw' object, even upon error.
  94. static int EncodeAlphaInternal(const uint8_t* const data, int width, int height,
  95. int method, int filter, int reduce_levels,
  96. int effort_level, // in [0..6] range
  97. uint8_t* const tmp_alpha,
  98. FilterTrial* result) {
  99. int ok = 0;
  100. const uint8_t* alpha_src;
  101. WebPFilterFunc filter_func;
  102. uint8_t header;
  103. const size_t data_size = width * height;
  104. const uint8_t* output = NULL;
  105. size_t output_size = 0;
  106. VP8LBitWriter tmp_bw;
  107. assert((uint64_t)data_size == (uint64_t)width * height); // as per spec
  108. assert(filter >= 0 && filter < WEBP_FILTER_LAST);
  109. assert(method >= ALPHA_NO_COMPRESSION);
  110. assert(method <= ALPHA_LOSSLESS_COMPRESSION);
  111. assert(sizeof(header) == ALPHA_HEADER_LEN);
  112. filter_func = WebPFilters[filter];
  113. if (filter_func != NULL) {
  114. filter_func(data, width, height, width, tmp_alpha);
  115. alpha_src = tmp_alpha;
  116. } else {
  117. alpha_src = data;
  118. }
  119. if (method != ALPHA_NO_COMPRESSION) {
  120. ok = VP8LBitWriterInit(&tmp_bw, data_size >> 3);
  121. ok = ok && EncodeLossless(alpha_src, width, height, effort_level,
  122. &tmp_bw, &result->stats);
  123. if (ok) {
  124. output = VP8LBitWriterFinish(&tmp_bw);
  125. output_size = VP8LBitWriterNumBytes(&tmp_bw);
  126. if (output_size > data_size) {
  127. // compressed size is larger than source! Revert to uncompressed mode.
  128. method = ALPHA_NO_COMPRESSION;
  129. VP8LBitWriterWipeOut(&tmp_bw);
  130. }
  131. } else {
  132. VP8LBitWriterWipeOut(&tmp_bw);
  133. return 0;
  134. }
  135. }
  136. if (method == ALPHA_NO_COMPRESSION) {
  137. output = alpha_src;
  138. output_size = data_size;
  139. ok = 1;
  140. }
  141. // Emit final result.
  142. header = method | (filter << 2);
  143. if (reduce_levels) header |= ALPHA_PREPROCESSED_LEVELS << 4;
  144. VP8BitWriterInit(&result->bw, ALPHA_HEADER_LEN + output_size);
  145. ok = ok && VP8BitWriterAppend(&result->bw, &header, ALPHA_HEADER_LEN);
  146. ok = ok && VP8BitWriterAppend(&result->bw, output, output_size);
  147. if (method != ALPHA_NO_COMPRESSION) {
  148. VP8LBitWriterWipeOut(&tmp_bw);
  149. }
  150. ok = ok && !result->bw.error_;
  151. result->score = VP8BitWriterSize(&result->bw);
  152. return ok;
  153. }
  154. // -----------------------------------------------------------------------------
  155. static int GetNumColors(const uint8_t* data, int width, int height,
  156. int stride) {
  157. int j;
  158. int colors = 0;
  159. uint8_t color[256] = { 0 };
  160. for (j = 0; j < height; ++j) {
  161. int i;
  162. const uint8_t* const p = data + j * stride;
  163. for (i = 0; i < width; ++i) {
  164. color[p[i]] = 1;
  165. }
  166. }
  167. for (j = 0; j < 256; ++j) {
  168. if (color[j] > 0) ++colors;
  169. }
  170. return colors;
  171. }
  172. #define FILTER_TRY_NONE (1 << WEBP_FILTER_NONE)
  173. #define FILTER_TRY_ALL ((1 << WEBP_FILTER_LAST) - 1)
  174. // Given the input 'filter' option, return an OR'd bit-set of filters to try.
  175. static uint32_t GetFilterMap(const uint8_t* alpha, int width, int height,
  176. int filter, int effort_level) {
  177. uint32_t bit_map = 0U;
  178. if (filter == WEBP_FILTER_FAST) {
  179. // Quick estimate of the best candidate.
  180. int try_filter_none = (effort_level > 3);
  181. const int kMinColorsForFilterNone = 16;
  182. const int kMaxColorsForFilterNone = 192;
  183. const int num_colors = GetNumColors(alpha, width, height, width);
  184. // For low number of colors, NONE yields better compression.
  185. filter = (num_colors <= kMinColorsForFilterNone)
  186. ? WEBP_FILTER_NONE
  187. : WebPEstimateBestFilter(alpha, width, height, width);
  188. bit_map |= 1 << filter;
  189. // For large number of colors, try FILTER_NONE in addition to the best
  190. // filter as well.
  191. if (try_filter_none || num_colors > kMaxColorsForFilterNone) {
  192. bit_map |= FILTER_TRY_NONE;
  193. }
  194. } else if (filter == WEBP_FILTER_NONE) {
  195. bit_map = FILTER_TRY_NONE;
  196. } else { // WEBP_FILTER_BEST -> try all
  197. bit_map = FILTER_TRY_ALL;
  198. }
  199. return bit_map;
  200. }
  201. static void InitFilterTrial(FilterTrial* const score) {
  202. score->score = (size_t)~0U;
  203. VP8BitWriterInit(&score->bw, 0);
  204. }
  205. static int ApplyFiltersAndEncode(const uint8_t* alpha, int width, int height,
  206. size_t data_size, int method, int filter,
  207. int reduce_levels, int effort_level,
  208. uint8_t** const output,
  209. size_t* const output_size,
  210. WebPAuxStats* const stats) {
  211. int ok = 1;
  212. FilterTrial best;
  213. uint32_t try_map =
  214. GetFilterMap(alpha, width, height, filter, effort_level);
  215. InitFilterTrial(&best);
  216. if (try_map != FILTER_TRY_NONE) {
  217. uint8_t* filtered_alpha = (uint8_t*)WebPSafeMalloc(1ULL, data_size);
  218. if (filtered_alpha == NULL) return 0;
  219. for (filter = WEBP_FILTER_NONE; ok && try_map; ++filter, try_map >>= 1) {
  220. if (try_map & 1) {
  221. FilterTrial trial;
  222. ok = EncodeAlphaInternal(alpha, width, height, method, filter,
  223. reduce_levels, effort_level, filtered_alpha,
  224. &trial);
  225. if (ok && trial.score < best.score) {
  226. VP8BitWriterWipeOut(&best.bw);
  227. best = trial;
  228. } else {
  229. VP8BitWriterWipeOut(&trial.bw);
  230. }
  231. }
  232. }
  233. WebPSafeFree(filtered_alpha);
  234. } else {
  235. ok = EncodeAlphaInternal(alpha, width, height, method, WEBP_FILTER_NONE,
  236. reduce_levels, effort_level, NULL, &best);
  237. }
  238. if (ok) {
  239. if (stats != NULL) {
  240. stats->lossless_features = best.stats.lossless_features;
  241. stats->histogram_bits = best.stats.histogram_bits;
  242. stats->transform_bits = best.stats.transform_bits;
  243. stats->cache_bits = best.stats.cache_bits;
  244. stats->palette_size = best.stats.palette_size;
  245. stats->lossless_size = best.stats.lossless_size;
  246. stats->lossless_hdr_size = best.stats.lossless_hdr_size;
  247. stats->lossless_data_size = best.stats.lossless_data_size;
  248. }
  249. *output_size = VP8BitWriterSize(&best.bw);
  250. *output = VP8BitWriterBuf(&best.bw);
  251. } else {
  252. VP8BitWriterWipeOut(&best.bw);
  253. }
  254. return ok;
  255. }
  256. static int EncodeAlpha(VP8Encoder* const enc,
  257. int quality, int method, int filter,
  258. int effort_level,
  259. uint8_t** const output, size_t* const output_size) {
  260. const WebPPicture* const pic = enc->pic_;
  261. const int width = pic->width;
  262. const int height = pic->height;
  263. uint8_t* quant_alpha = NULL;
  264. const size_t data_size = width * height;
  265. uint64_t sse = 0;
  266. int ok = 1;
  267. const int reduce_levels = (quality < 100);
  268. // quick sanity checks
  269. assert((uint64_t)data_size == (uint64_t)width * height); // as per spec
  270. assert(enc != NULL && pic != NULL && pic->a != NULL);
  271. assert(output != NULL && output_size != NULL);
  272. assert(width > 0 && height > 0);
  273. assert(pic->a_stride >= width);
  274. assert(filter >= WEBP_FILTER_NONE && filter <= WEBP_FILTER_FAST);
  275. if (quality < 0 || quality > 100) {
  276. return 0;
  277. }
  278. if (method < ALPHA_NO_COMPRESSION || method > ALPHA_LOSSLESS_COMPRESSION) {
  279. return 0;
  280. }
  281. if (method == ALPHA_NO_COMPRESSION) {
  282. // Don't filter, as filtering will make no impact on compressed size.
  283. filter = WEBP_FILTER_NONE;
  284. }
  285. quant_alpha = (uint8_t*)WebPSafeMalloc(1ULL, data_size);
  286. if (quant_alpha == NULL) {
  287. return 0;
  288. }
  289. // Extract alpha data (width x height) from raw_data (stride x height).
  290. WebPCopyPlane(pic->a, pic->a_stride, quant_alpha, width, width, height);
  291. if (reduce_levels) { // No Quantization required for 'quality = 100'.
  292. // 16 alpha levels gives quite a low MSE w.r.t original alpha plane hence
  293. // mapped to moderate quality 70. Hence Quality:[0, 70] -> Levels:[2, 16]
  294. // and Quality:]70, 100] -> Levels:]16, 256].
  295. const int alpha_levels = (quality <= 70) ? (2 + quality / 5)
  296. : (16 + (quality - 70) * 8);
  297. ok = QuantizeLevels(quant_alpha, width, height, alpha_levels, &sse);
  298. }
  299. if (ok) {
  300. VP8FiltersInit();
  301. ok = ApplyFiltersAndEncode(quant_alpha, width, height, data_size, method,
  302. filter, reduce_levels, effort_level, output,
  303. output_size, pic->stats);
  304. if (pic->stats != NULL) { // need stats?
  305. pic->stats->coded_size += (int)(*output_size);
  306. enc->sse_[3] = sse;
  307. }
  308. }
  309. WebPSafeFree(quant_alpha);
  310. return ok;
  311. }
  312. //------------------------------------------------------------------------------
  313. // Main calls
  314. static int CompressAlphaJob(VP8Encoder* const enc, void* dummy) {
  315. const WebPConfig* config = enc->config_;
  316. uint8_t* alpha_data = NULL;
  317. size_t alpha_size = 0;
  318. const int effort_level = config->method; // maps to [0..6]
  319. const WEBP_FILTER_TYPE filter =
  320. (config->alpha_filtering == 0) ? WEBP_FILTER_NONE :
  321. (config->alpha_filtering == 1) ? WEBP_FILTER_FAST :
  322. WEBP_FILTER_BEST;
  323. if (!EncodeAlpha(enc, config->alpha_quality, config->alpha_compression,
  324. filter, effort_level, &alpha_data, &alpha_size)) {
  325. return 0;
  326. }
  327. if (alpha_size != (uint32_t)alpha_size) { // Sanity check.
  328. WebPSafeFree(alpha_data);
  329. return 0;
  330. }
  331. enc->alpha_data_size_ = (uint32_t)alpha_size;
  332. enc->alpha_data_ = alpha_data;
  333. (void)dummy;
  334. return 1;
  335. }
  336. void VP8EncInitAlpha(VP8Encoder* const enc) {
  337. WebPInitAlphaProcessing();
  338. enc->has_alpha_ = WebPPictureHasTransparency(enc->pic_);
  339. enc->alpha_data_ = NULL;
  340. enc->alpha_data_size_ = 0;
  341. if (enc->thread_level_ > 0) {
  342. WebPWorker* const worker = &enc->alpha_worker_;
  343. WebPGetWorkerInterface()->Init(worker);
  344. worker->data1 = enc;
  345. worker->data2 = NULL;
  346. worker->hook = (WebPWorkerHook)CompressAlphaJob;
  347. }
  348. }
  349. int VP8EncStartAlpha(VP8Encoder* const enc) {
  350. if (enc->has_alpha_) {
  351. if (enc->thread_level_ > 0) {
  352. WebPWorker* const worker = &enc->alpha_worker_;
  353. // Makes sure worker is good to go.
  354. if (!WebPGetWorkerInterface()->Reset(worker)) {
  355. return 0;
  356. }
  357. WebPGetWorkerInterface()->Launch(worker);
  358. return 1;
  359. } else {
  360. return CompressAlphaJob(enc, NULL); // just do the job right away
  361. }
  362. }
  363. return 1;
  364. }
  365. int VP8EncFinishAlpha(VP8Encoder* const enc) {
  366. if (enc->has_alpha_) {
  367. if (enc->thread_level_ > 0) {
  368. WebPWorker* const worker = &enc->alpha_worker_;
  369. if (!WebPGetWorkerInterface()->Sync(worker)) return 0; // error
  370. }
  371. }
  372. return WebPReportProgress(enc->pic_, enc->percent_ + 20, &enc->percent_);
  373. }
  374. int VP8EncDeleteAlpha(VP8Encoder* const enc) {
  375. int ok = 1;
  376. if (enc->thread_level_ > 0) {
  377. WebPWorker* const worker = &enc->alpha_worker_;
  378. // finish anything left in flight
  379. ok = WebPGetWorkerInterface()->Sync(worker);
  380. // still need to end the worker, even if !ok
  381. WebPGetWorkerInterface()->End(worker);
  382. }
  383. WebPSafeFree(enc->alpha_data_);
  384. enc->alpha_data_ = NULL;
  385. enc->alpha_data_size_ = 0;
  386. enc->has_alpha_ = 0;
  387. return ok;
  388. }