1 // Copyright 2011 Google Inc. All Rights Reserved.
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 // -----------------------------------------------------------------------------
8 // Alpha-plane compression.
10 // Author: Skal (pascal.massimino@gmail.com)
15 #include "./vp8enci.h"
16 #include "../utils/filters.h"
17 #include "../utils/quant_levels.h"
18 #include "../webp/format_constants.h"
20 #if defined(__cplusplus) || defined(c_plusplus)
24 // -----------------------------------------------------------------------------
25 // Encodes the given alpha data via specified compression method 'method'.
26 // The pre-processing (quantization) is performed if 'quality' is less than 100.
27 // For such cases, the encoding is lossy. The valid range is [0, 100] for
28 // 'quality' and [0, 1] for 'method':
29 // 'method = 0' - No compression;
30 // 'method = 1' - Use lossless coder on the alpha plane only
31 // 'filter' values [0, 4] correspond to prediction modes none, horizontal,
32 // vertical & gradient filters. The prediction mode 4 will try all the
33 // prediction modes 0 to 3 and pick the best one.
34 // 'effort_level': specifies how much effort must be spent to try and reduce
35 // the compressed output size. In range 0 (quick) to 6 (slow).
37 // 'output' corresponds to the buffer containing compressed alpha data.
38 // This buffer is allocated by this method and caller should call
39 // free(*output) when done.
40 // 'output_size' corresponds to size of this compressed alpha buffer.
42 // Returns 1 on successfully encoding the alpha and
44 // invalid quality or method, or
45 // memory allocation for the compressed data fails.
47 #include "../enc/vp8li.h"
49 static int EncodeLossless(const uint8_t* const data, int width, int height,
50 int effort_level, // in [0..6] range
51 VP8BitWriter* const bw,
52 WebPAuxStats* const stats) {
58 WebPPictureInit(&picture);
59 picture.width = width;
60 picture.height = height;
62 picture.stats = stats;
63 if (!WebPPictureAlloc(&picture)) return 0;
65 // Transfer the alpha values to the green channel.
68 uint32_t* dst = picture.argb;
69 const uint8_t* src = data;
70 for (j = 0; j < picture.height; ++j) {
71 for (i = 0; i < picture.width; ++i) {
72 dst[i] = (src[i] << 8) | 0xff000000u;
75 dst += picture.argb_stride;
79 WebPConfigInit(&config);
81 config.method = effort_level; // impact is very small
82 // Set a moderate default quality setting for alpha.
83 config.quality = 10.f * effort_level;
84 assert(config.quality >= 0 && config.quality <= 100.f);
86 ok = VP8LBitWriterInit(&tmp_bw, (width * height) >> 3);
87 ok = ok && (VP8LEncodeStream(&config, &picture, &tmp_bw) == VP8_ENC_OK);
88 WebPPictureFree(&picture);
90 const uint8_t* const buffer = VP8LBitWriterFinish(&tmp_bw);
91 const size_t buffer_size = VP8LBitWriterNumBytes(&tmp_bw);
92 VP8BitWriterAppend(bw, buffer, buffer_size);
94 VP8LBitWriterDestroy(&tmp_bw);
95 return ok && !bw->error_;
98 // -----------------------------------------------------------------------------
100 // This function always returns an initialized 'bw' object, even upon error.
101 static int EncodeAlphaInternal(const uint8_t* const data, int width, int height,
102 int method, int filter, int reduce_levels,
103 int effort_level, // in [0..6] range
104 uint8_t* const tmp_alpha,
105 VP8BitWriter* const bw,
106 WebPAuxStats* const stats) {
108 const uint8_t* alpha_src;
109 WebPFilterFunc filter_func;
111 size_t expected_size;
112 const size_t data_size = width * height;
114 assert((uint64_t)data_size == (uint64_t)width * height); // as per spec
115 assert(filter >= 0 && filter < WEBP_FILTER_LAST);
116 assert(method >= ALPHA_NO_COMPRESSION);
117 assert(method <= ALPHA_LOSSLESS_COMPRESSION);
118 assert(sizeof(header) == ALPHA_HEADER_LEN);
119 // TODO(skal): have a common function and #define's to validate alpha params.
122 (method == ALPHA_NO_COMPRESSION) ? (ALPHA_HEADER_LEN + data_size)
124 header = method | (filter << 2);
125 if (reduce_levels) header |= ALPHA_PREPROCESSED_LEVELS << 4;
127 VP8BitWriterInit(bw, expected_size);
128 VP8BitWriterAppend(bw, &header, ALPHA_HEADER_LEN);
130 filter_func = WebPFilters[filter];
131 if (filter_func != NULL) {
132 filter_func(data, width, height, width, tmp_alpha);
133 alpha_src = tmp_alpha;
138 if (method == ALPHA_NO_COMPRESSION) {
139 ok = VP8BitWriterAppend(bw, alpha_src, width * height);
140 ok = ok && !bw->error_;
142 ok = EncodeLossless(alpha_src, width, height, effort_level, bw, stats);
143 VP8BitWriterFinish(bw);
148 // -----------------------------------------------------------------------------
150 // TODO(skal): move to dsp/ ?
151 static void CopyPlane(const uint8_t* src, int src_stride,
152 uint8_t* dst, int dst_stride, int width, int height) {
153 while (height-- > 0) {
154 memcpy(dst, src, width);
160 static int GetNumColors(const uint8_t* data, int width, int height,
164 uint8_t color[256] = { 0 };
166 for (j = 0; j < height; ++j) {
168 const uint8_t* const p = data + j * stride;
169 for (i = 0; i < width; ++i) {
173 for (j = 0; j < 256; ++j) {
174 if (color[j] > 0) ++colors;
179 // Given the input 'filter' option, return an OR'd bit-set of filters to try.
180 static uint32_t GetFilterMap(const uint8_t* alpha, int width, int height,
181 int filter, int effort_level) {
182 uint32_t bit_map = 0U;
183 if (filter == WEBP_FILTER_FAST) {
184 // Quick estimate of the best candidate.
185 int try_filter_none = (effort_level > 3);
186 const int kMinColorsForFilterNone = 16;
187 const int kMaxColorsForFilterNone = 192;
188 const int num_colors = GetNumColors(alpha, width, height, width);
189 // For low number of colors, NONE yeilds better compression.
190 filter = (num_colors <= kMinColorsForFilterNone) ? WEBP_FILTER_NONE :
191 EstimateBestFilter(alpha, width, height, width);
192 bit_map |= 1 << filter;
193 // For large number of colors, try FILTER_NONE in addition to the best
195 if (try_filter_none || num_colors > kMaxColorsForFilterNone) {
196 bit_map |= 1 << WEBP_FILTER_NONE;
198 } else if (filter == WEBP_FILTER_NONE) {
199 bit_map = 1 << WEBP_FILTER_NONE;
200 } else { // WEBP_FILTER_BEST
201 bit_map = (1 << WEBP_FILTER_LAST) - 1; // try all.
206 // Small struct to hold the result of a filter mode compression attempt.
213 static void InitFilterTrial(FilterTrial* const score) {
214 score->score = (size_t)~0U;
215 VP8BitWriterInit(&score->bw, 0);
218 static int ApplyFilters(const uint8_t* alpha, int width, int height,
219 uint64_t data_size, int method, int filter,
220 int reduce_levels, int effort_level,
221 uint8_t** const output, size_t* const output_size,
222 WebPAuxStats* const stats) {
224 uint8_t* filtered_alpha = NULL;
225 uint32_t try_map = GetFilterMap(alpha, width, height, filter, effort_level);
227 filtered_alpha = (uint8_t*)malloc(data_size);
228 ok = (filtered_alpha != NULL);
232 InitFilterTrial(&best);
234 for (filter = WEBP_FILTER_NONE; try_map; ++filter, try_map >>= 1) {
237 ok = EncodeAlphaInternal(alpha, width, height, method, filter,
238 reduce_levels, effort_level, filtered_alpha,
241 trial.score = VP8BitWriterSize(&trial.bw);
242 if (trial.score < best.score) {
243 VP8BitWriterWipeOut(&best.bw);
245 if (stats != NULL) best.stats = *stats;
247 VP8BitWriterWipeOut(&trial.bw);
250 VP8BitWriterWipeOut(&trial.bw);
251 VP8BitWriterWipeOut(&best.bw);
258 if (stats != NULL) *stats = best.stats;
259 *output_size = VP8BitWriterSize(&best.bw);
260 *output = VP8BitWriterBuf(&best.bw);
262 free(filtered_alpha);
267 static int EncodeAlpha(VP8Encoder* const enc,
268 int quality, int method, int filter,
270 uint8_t** const output, size_t* const output_size) {
271 const WebPPicture* const pic = enc->pic_;
272 const int width = pic->width;
273 const int height = pic->height;
275 uint8_t* quant_alpha = NULL;
276 const size_t data_size = width * height;
279 const int reduce_levels = (quality < 100);
281 // quick sanity checks
282 assert((uint64_t)data_size == (uint64_t)width * height); // as per spec
283 assert(enc != NULL && pic != NULL && pic->a != NULL);
284 assert(output != NULL && output_size != NULL);
285 assert(width > 0 && height > 0);
286 assert(pic->a_stride >= width);
287 assert(filter >= WEBP_FILTER_NONE && filter <= WEBP_FILTER_FAST);
289 if (quality < 0 || quality > 100) {
293 if (method < ALPHA_NO_COMPRESSION || method > ALPHA_LOSSLESS_COMPRESSION) {
297 quant_alpha = (uint8_t*)malloc(data_size);
298 if (quant_alpha == NULL) {
302 // Extract alpha data (width x height) from raw_data (stride x height).
303 CopyPlane(pic->a, pic->a_stride, quant_alpha, width, width, height);
305 if (reduce_levels) { // No Quantization required for 'quality = 100'.
306 // 16 alpha levels gives quite a low MSE w.r.t original alpha plane hence
307 // mapped to moderate quality 70. Hence Quality:[0, 70] -> Levels:[2, 16]
308 // and Quality:]70, 100] -> Levels:]16, 256].
309 const int alpha_levels = (quality <= 70) ? (2 + quality / 5)
310 : (16 + (quality - 70) * 8);
311 ok = QuantizeLevels(quant_alpha, width, height, alpha_levels, &sse);
315 ok = ApplyFilters(quant_alpha, width, height, data_size, method, filter,
316 reduce_levels, effort_level, output, output_size,
318 if (pic->stats != NULL) { // need stats?
319 pic->stats->coded_size += (int)(*output_size);
328 //------------------------------------------------------------------------------
331 static int CompressAlphaJob(VP8Encoder* const enc, void* dummy) {
332 const WebPConfig* config = enc->config_;
333 uint8_t* alpha_data = NULL;
334 size_t alpha_size = 0;
335 const int effort_level = config->method; // maps to [0..6]
336 const WEBP_FILTER_TYPE filter =
337 (config->alpha_filtering == 0) ? WEBP_FILTER_NONE :
338 (config->alpha_filtering == 1) ? WEBP_FILTER_FAST :
340 if (!EncodeAlpha(enc, config->alpha_quality, config->alpha_compression,
341 filter, effort_level, &alpha_data, &alpha_size)) {
344 if (alpha_size != (uint32_t)alpha_size) { // Sanity check.
348 enc->alpha_data_size_ = (uint32_t)alpha_size;
349 enc->alpha_data_ = alpha_data;
354 void VP8EncInitAlpha(VP8Encoder* const enc) {
355 enc->has_alpha_ = WebPPictureHasTransparency(enc->pic_);
356 enc->alpha_data_ = NULL;
357 enc->alpha_data_size_ = 0;
358 if (enc->thread_level_ > 0) {
359 WebPWorker* const worker = &enc->alpha_worker_;
360 WebPWorkerInit(worker);
362 worker->data2 = NULL;
363 worker->hook = (WebPWorkerHook)CompressAlphaJob;
367 int VP8EncStartAlpha(VP8Encoder* const enc) {
368 if (enc->has_alpha_) {
369 if (enc->thread_level_ > 0) {
370 WebPWorker* const worker = &enc->alpha_worker_;
371 if (!WebPWorkerReset(worker)) { // Makes sure worker is good to go.
374 WebPWorkerLaunch(worker);
377 return CompressAlphaJob(enc, NULL); // just do the job right away
383 int VP8EncFinishAlpha(VP8Encoder* const enc) {
384 if (enc->has_alpha_) {
385 if (enc->thread_level_ > 0) {
386 WebPWorker* const worker = &enc->alpha_worker_;
387 if (!WebPWorkerSync(worker)) return 0; // error
390 return WebPReportProgress(enc->pic_, enc->percent_ + 20, &enc->percent_);
393 int VP8EncDeleteAlpha(VP8Encoder* const enc) {
395 if (enc->thread_level_ > 0) {
396 WebPWorker* const worker = &enc->alpha_worker_;
397 ok = WebPWorkerSync(worker); // finish anything left in flight
398 WebPWorkerEnd(worker); // still need to end the worker, even if !ok
400 free(enc->alpha_data_);
401 enc->alpha_data_ = NULL;
402 enc->alpha_data_size_ = 0;
407 #if defined(__cplusplus) || defined(c_plusplus)