alpha.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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 "./vp8enci.h"
  16. #include "../utils/filters.h"
  17. #include "../utils/quant_levels.h"
  18. #include "../utils/utils.h"
  19. #include "../webp/format_constants.h"
  20. // -----------------------------------------------------------------------------
  21. // Encodes the given alpha data via specified compression method 'method'.
  22. // The pre-processing (quantization) is performed if 'quality' is less than 100.
  23. // For such cases, the encoding is lossy. The valid range is [0, 100] for
  24. // 'quality' and [0, 1] for 'method':
  25. // 'method = 0' - No compression;
  26. // 'method = 1' - Use lossless coder on the alpha plane only
  27. // 'filter' values [0, 4] correspond to prediction modes none, horizontal,
  28. // vertical & gradient filters. The prediction mode 4 will try all the
  29. // prediction modes 0 to 3 and pick the best one.
  30. // 'effort_level': specifies how much effort must be spent to try and reduce
  31. // the compressed output size. In range 0 (quick) to 6 (slow).
  32. //
  33. // 'output' corresponds to the buffer containing compressed alpha data.
  34. // This buffer is allocated by this method and caller should call
  35. // WebPSafeFree(*output) when done.
  36. // 'output_size' corresponds to size of this compressed alpha buffer.
  37. //
  38. // Returns 1 on successfully encoding the alpha and
  39. // 0 if either:
  40. // invalid quality or method, or
  41. // memory allocation for the compressed data fails.
  42. #include "../enc/vp8li.h"
  43. static int EncodeLossless(const uint8_t* const data, int width, int height,
  44. int effort_level, // in [0..6] range
  45. VP8LBitWriter* const bw,
  46. WebPAuxStats* const stats) {
  47. int ok = 0;
  48. WebPConfig config;
  49. WebPPicture picture;
  50. WebPPictureInit(&picture);
  51. picture.width = width;
  52. picture.height = height;
  53. picture.use_argb = 1;
  54. picture.stats = stats;
  55. if (!WebPPictureAlloc(&picture)) return 0;
  56. // Transfer the alpha values to the green channel.
  57. {
  58. int i, j;
  59. uint32_t* dst = picture.argb;
  60. const uint8_t* src = data;
  61. for (j = 0; j < picture.height; ++j) {
  62. for (i = 0; i < picture.width; ++i) {
  63. dst[i] = src[i] << 8; // we leave A/R/B channels zero'd.
  64. }
  65. src += width;
  66. dst += picture.argb_stride;
  67. }
  68. }
  69. WebPConfigInit(&config);
  70. config.lossless = 1;
  71. config.method = effort_level; // impact is very small
  72. // Set a low default quality for encoding alpha. Ensure that Alpha quality at
  73. // lower methods (3 and below) is less than the threshold for triggering
  74. // costly 'BackwardReferencesTraceBackwards'.
  75. config.quality = 8.f * effort_level;
  76. assert(config.quality >= 0 && config.quality <= 100.f);
  77. ok = (VP8LEncodeStream(&config, &picture, bw) == VP8_ENC_OK);
  78. WebPPictureFree(&picture);
  79. ok = ok && !bw->error_;
  80. if (!ok) {
  81. VP8LBitWriterDestroy(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. // TODO(skal): have a common function and #define's to validate alpha params.
  113. filter_func = WebPFilters[filter];
  114. if (filter_func != NULL) {
  115. filter_func(data, width, height, width, tmp_alpha);
  116. alpha_src = tmp_alpha;
  117. } else {
  118. alpha_src = data;
  119. }
  120. if (method != ALPHA_NO_COMPRESSION) {
  121. ok = VP8LBitWriterInit(&tmp_bw, data_size >> 3);
  122. ok = ok && EncodeLossless(alpha_src, width, height, effort_level,
  123. &tmp_bw, &result->stats);
  124. if (ok) {
  125. output = VP8LBitWriterFinish(&tmp_bw);
  126. output_size = VP8LBitWriterNumBytes(&tmp_bw);
  127. if (output_size > data_size) {
  128. // compressed size is larger than source! Revert to uncompressed mode.
  129. method = ALPHA_NO_COMPRESSION;
  130. VP8LBitWriterDestroy(&tmp_bw);
  131. }
  132. } else {
  133. VP8LBitWriterDestroy(&tmp_bw);
  134. return 0;
  135. }
  136. }
  137. if (method == ALPHA_NO_COMPRESSION) {
  138. output = alpha_src;
  139. output_size = data_size;
  140. ok = 1;
  141. }
  142. // Emit final result.
  143. header = method | (filter << 2);
  144. if (reduce_levels) header |= ALPHA_PREPROCESSED_LEVELS << 4;
  145. VP8BitWriterInit(&result->bw, ALPHA_HEADER_LEN + output_size);
  146. ok = ok && VP8BitWriterAppend(&result->bw, &header, ALPHA_HEADER_LEN);
  147. ok = ok && VP8BitWriterAppend(&result->bw, output, output_size);
  148. if (method != ALPHA_NO_COMPRESSION) {
  149. VP8LBitWriterDestroy(&tmp_bw);
  150. }
  151. ok = ok && !result->bw.error_;
  152. result->score = VP8BitWriterSize(&result->bw);
  153. return ok;
  154. }
  155. // -----------------------------------------------------------------------------
  156. // TODO(skal): move to dsp/ ?
  157. static void CopyPlane(const uint8_t* src, int src_stride,
  158. uint8_t* dst, int dst_stride, int width, int height) {
  159. while (height-- > 0) {
  160. memcpy(dst, src, width);
  161. src += src_stride;
  162. dst += dst_stride;
  163. }
  164. }
  165. static int GetNumColors(const uint8_t* data, int width, int height,
  166. int stride) {
  167. int j;
  168. int colors = 0;
  169. uint8_t color[256] = { 0 };
  170. for (j = 0; j < height; ++j) {
  171. int i;
  172. const uint8_t* const p = data + j * stride;
  173. for (i = 0; i < width; ++i) {
  174. color[p[i]] = 1;
  175. }
  176. }
  177. for (j = 0; j < 256; ++j) {
  178. if (color[j] > 0) ++colors;
  179. }
  180. return colors;
  181. }
  182. #define FILTER_TRY_NONE (1 << WEBP_FILTER_NONE)
  183. #define FILTER_TRY_ALL ((1 << WEBP_FILTER_LAST) - 1)
  184. // Given the input 'filter' option, return an OR'd bit-set of filters to try.
  185. static uint32_t GetFilterMap(const uint8_t* alpha, int width, int height,
  186. int filter, int effort_level) {
  187. uint32_t bit_map = 0U;
  188. if (filter == WEBP_FILTER_FAST) {
  189. // Quick estimate of the best candidate.
  190. int try_filter_none = (effort_level > 3);
  191. const int kMinColorsForFilterNone = 16;
  192. const int kMaxColorsForFilterNone = 192;
  193. const int num_colors = GetNumColors(alpha, width, height, width);
  194. // For low number of colors, NONE yields better compression.
  195. filter = (num_colors <= kMinColorsForFilterNone) ? WEBP_FILTER_NONE :
  196. EstimateBestFilter(alpha, width, height, width);
  197. bit_map |= 1 << filter;
  198. // For large number of colors, try FILTER_NONE in addition to the best
  199. // filter as well.
  200. if (try_filter_none || num_colors > kMaxColorsForFilterNone) {
  201. bit_map |= FILTER_TRY_NONE;
  202. }
  203. } else if (filter == WEBP_FILTER_NONE) {
  204. bit_map = FILTER_TRY_NONE;
  205. } else { // WEBP_FILTER_BEST -> try all
  206. bit_map = FILTER_TRY_ALL;
  207. }
  208. return bit_map;
  209. }
  210. static void InitFilterTrial(FilterTrial* const score) {
  211. score->score = (size_t)~0U;
  212. VP8BitWriterInit(&score->bw, 0);
  213. }
  214. static int ApplyFiltersAndEncode(const uint8_t* alpha, int width, int height,
  215. size_t data_size, int method, int filter,
  216. int reduce_levels, int effort_level,
  217. uint8_t** const output,
  218. size_t* const output_size,
  219. WebPAuxStats* const stats) {
  220. int ok = 1;
  221. FilterTrial best;
  222. uint32_t try_map =
  223. GetFilterMap(alpha, width, height, filter, effort_level);
  224. InitFilterTrial(&best);
  225. if (try_map != FILTER_TRY_NONE) {
  226. uint8_t* filtered_alpha = (uint8_t*)WebPSafeMalloc(1ULL, data_size);
  227. if (filtered_alpha == NULL) return 0;
  228. for (filter = WEBP_FILTER_NONE; ok && try_map; ++filter, try_map >>= 1) {
  229. if (try_map & 1) {
  230. FilterTrial trial;
  231. ok = EncodeAlphaInternal(alpha, width, height, method, filter,
  232. reduce_levels, effort_level, filtered_alpha,
  233. &trial);
  234. if (ok && trial.score < best.score) {
  235. VP8BitWriterWipeOut(&best.bw);
  236. best = trial;
  237. } else {
  238. VP8BitWriterWipeOut(&trial.bw);
  239. }
  240. }
  241. }
  242. WebPSafeFree(filtered_alpha);
  243. } else {
  244. ok = EncodeAlphaInternal(alpha, width, height, method, WEBP_FILTER_NONE,
  245. reduce_levels, effort_level, NULL, &best);
  246. }
  247. if (ok) {
  248. if (stats != NULL) *stats = best.stats;
  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. CopyPlane(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. ok = ApplyFiltersAndEncode(quant_alpha, width, height, data_size, method,
  301. filter, reduce_levels, effort_level, output,
  302. output_size, pic->stats);
  303. if (pic->stats != NULL) { // need stats?
  304. pic->stats->coded_size += (int)(*output_size);
  305. enc->sse_[3] = sse;
  306. }
  307. }
  308. WebPSafeFree(quant_alpha);
  309. return ok;
  310. }
  311. //------------------------------------------------------------------------------
  312. // Main calls
  313. static int CompressAlphaJob(VP8Encoder* const enc, void* dummy) {
  314. const WebPConfig* config = enc->config_;
  315. uint8_t* alpha_data = NULL;
  316. size_t alpha_size = 0;
  317. const int effort_level = config->method; // maps to [0..6]
  318. const WEBP_FILTER_TYPE filter =
  319. (config->alpha_filtering == 0) ? WEBP_FILTER_NONE :
  320. (config->alpha_filtering == 1) ? WEBP_FILTER_FAST :
  321. WEBP_FILTER_BEST;
  322. if (!EncodeAlpha(enc, config->alpha_quality, config->alpha_compression,
  323. filter, effort_level, &alpha_data, &alpha_size)) {
  324. return 0;
  325. }
  326. if (alpha_size != (uint32_t)alpha_size) { // Sanity check.
  327. WebPSafeFree(alpha_data);
  328. return 0;
  329. }
  330. enc->alpha_data_size_ = (uint32_t)alpha_size;
  331. enc->alpha_data_ = alpha_data;
  332. (void)dummy;
  333. return 1;
  334. }
  335. void VP8EncInitAlpha(VP8Encoder* const enc) {
  336. enc->has_alpha_ = WebPPictureHasTransparency(enc->pic_);
  337. enc->alpha_data_ = NULL;
  338. enc->alpha_data_size_ = 0;
  339. if (enc->thread_level_ > 0) {
  340. WebPWorker* const worker = &enc->alpha_worker_;
  341. WebPGetWorkerInterface()->Init(worker);
  342. worker->data1 = enc;
  343. worker->data2 = NULL;
  344. worker->hook = (WebPWorkerHook)CompressAlphaJob;
  345. }
  346. }
  347. int VP8EncStartAlpha(VP8Encoder* const enc) {
  348. if (enc->has_alpha_) {
  349. if (enc->thread_level_ > 0) {
  350. WebPWorker* const worker = &enc->alpha_worker_;
  351. // Makes sure worker is good to go.
  352. if (!WebPGetWorkerInterface()->Reset(worker)) {
  353. return 0;
  354. }
  355. WebPGetWorkerInterface()->Launch(worker);
  356. return 1;
  357. } else {
  358. return CompressAlphaJob(enc, NULL); // just do the job right away
  359. }
  360. }
  361. return 1;
  362. }
  363. int VP8EncFinishAlpha(VP8Encoder* const enc) {
  364. if (enc->has_alpha_) {
  365. if (enc->thread_level_ > 0) {
  366. WebPWorker* const worker = &enc->alpha_worker_;
  367. if (!WebPGetWorkerInterface()->Sync(worker)) return 0; // error
  368. }
  369. }
  370. return WebPReportProgress(enc->pic_, enc->percent_ + 20, &enc->percent_);
  371. }
  372. int VP8EncDeleteAlpha(VP8Encoder* const enc) {
  373. int ok = 1;
  374. if (enc->thread_level_ > 0) {
  375. WebPWorker* const worker = &enc->alpha_worker_;
  376. // finish anything left in flight
  377. ok = WebPGetWorkerInterface()->Sync(worker);
  378. // still need to end the worker, even if !ok
  379. WebPGetWorkerInterface()->End(worker);
  380. }
  381. WebPSafeFree(enc->alpha_data_);
  382. enc->alpha_data_ = NULL;
  383. enc->alpha_data_size_ = 0;
  384. enc->has_alpha_ = 0;
  385. return ok;
  386. }