New comit of SDL2
[supertux.git] / src / SDL2 / external / libwebp-0.3.0 / src / enc / alpha.c
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 // Alpha-plane compression.
9 //
10 // Author: Skal (pascal.massimino@gmail.com)
11
12 #include <assert.h>
13 #include <stdlib.h>
14
15 #include "./vp8enci.h"
16 #include "../utils/filters.h"
17 #include "../utils/quant_levels.h"
18 #include "../webp/format_constants.h"
19
20 #if defined(__cplusplus) || defined(c_plusplus)
21 extern "C" {
22 #endif
23
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).
36 //
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.
41 //
42 // Returns 1 on successfully encoding the alpha and
43 //         0 if either:
44 //           invalid quality or method, or
45 //           memory allocation for the compressed data fails.
46
47 #include "../enc/vp8li.h"
48
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) {
53   int ok = 0;
54   WebPConfig config;
55   WebPPicture picture;
56   VP8LBitWriter tmp_bw;
57
58   WebPPictureInit(&picture);
59   picture.width = width;
60   picture.height = height;
61   picture.use_argb = 1;
62   picture.stats = stats;
63   if (!WebPPictureAlloc(&picture)) return 0;
64
65   // Transfer the alpha values to the green channel.
66   {
67     int i, j;
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;
73       }
74       src += width;
75       dst += picture.argb_stride;
76     }
77   }
78
79   WebPConfigInit(&config);
80   config.lossless = 1;
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);
85
86   ok = VP8LBitWriterInit(&tmp_bw, (width * height) >> 3);
87   ok = ok && (VP8LEncodeStream(&config, &picture, &tmp_bw) == VP8_ENC_OK);
88   WebPPictureFree(&picture);
89   if (ok) {
90     const uint8_t* const buffer = VP8LBitWriterFinish(&tmp_bw);
91     const size_t buffer_size = VP8LBitWriterNumBytes(&tmp_bw);
92     VP8BitWriterAppend(bw, buffer, buffer_size);
93   }
94   VP8LBitWriterDestroy(&tmp_bw);
95   return ok && !bw->error_;
96 }
97
98 // -----------------------------------------------------------------------------
99
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) {
107   int ok = 0;
108   const uint8_t* alpha_src;
109   WebPFilterFunc filter_func;
110   uint8_t header;
111   size_t expected_size;
112   const size_t data_size = width * height;
113
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.
120
121   expected_size =
122       (method == ALPHA_NO_COMPRESSION) ? (ALPHA_HEADER_LEN + data_size)
123                                        : (data_size >> 5);
124   header = method | (filter << 2);
125   if (reduce_levels) header |= ALPHA_PREPROCESSED_LEVELS << 4;
126
127   VP8BitWriterInit(bw, expected_size);
128   VP8BitWriterAppend(bw, &header, ALPHA_HEADER_LEN);
129
130   filter_func = WebPFilters[filter];
131   if (filter_func != NULL) {
132     filter_func(data, width, height, width, tmp_alpha);
133     alpha_src = tmp_alpha;
134   }  else {
135     alpha_src = data;
136   }
137
138   if (method == ALPHA_NO_COMPRESSION) {
139     ok = VP8BitWriterAppend(bw, alpha_src, width * height);
140     ok = ok && !bw->error_;
141   } else {
142     ok = EncodeLossless(alpha_src, width, height, effort_level, bw, stats);
143     VP8BitWriterFinish(bw);
144   }
145   return ok;
146 }
147
148 // -----------------------------------------------------------------------------
149
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);
155     src += src_stride;
156     dst += dst_stride;
157   }
158 }
159
160 static int GetNumColors(const uint8_t* data, int width, int height,
161                         int stride) {
162   int j;
163   int colors = 0;
164   uint8_t color[256] = { 0 };
165
166   for (j = 0; j < height; ++j) {
167     int i;
168     const uint8_t* const p = data + j * stride;
169     for (i = 0; i < width; ++i) {
170       color[p[i]] = 1;
171     }
172   }
173   for (j = 0; j < 256; ++j) {
174     if (color[j] > 0) ++colors;
175   }
176   return colors;
177 }
178
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
194     // filter as well.
195     if (try_filter_none || num_colors > kMaxColorsForFilterNone) {
196       bit_map |= 1 << WEBP_FILTER_NONE;
197     }
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.
202   }
203   return bit_map;
204 }
205
206 // Small struct to hold the result of a filter mode compression attempt.
207 typedef struct {
208   size_t score;
209   VP8BitWriter bw;
210   WebPAuxStats stats;
211 } FilterTrial;
212
213 static void InitFilterTrial(FilterTrial* const score) {
214   score->score = (size_t)~0U;
215   VP8BitWriterInit(&score->bw, 0);
216 }
217
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) {
223   int ok = 1;
224   uint8_t* filtered_alpha = NULL;
225   uint32_t try_map = GetFilterMap(alpha, width, height, filter, effort_level);
226
227   filtered_alpha = (uint8_t*)malloc(data_size);
228   ok = (filtered_alpha != NULL);
229
230   if (ok) {
231     FilterTrial best;
232     InitFilterTrial(&best);
233
234     for (filter = WEBP_FILTER_NONE; try_map; ++filter, try_map >>= 1) {
235       if (try_map & 1) {
236         FilterTrial trial;
237         ok = EncodeAlphaInternal(alpha, width, height, method, filter,
238                                  reduce_levels, effort_level, filtered_alpha,
239                                  &trial.bw, stats);
240         if (ok) {
241           trial.score = VP8BitWriterSize(&trial.bw);
242           if (trial.score < best.score) {
243             VP8BitWriterWipeOut(&best.bw);
244             best = trial;
245             if (stats != NULL) best.stats = *stats;
246           } else {
247             VP8BitWriterWipeOut(&trial.bw);
248           }
249         } else {
250           VP8BitWriterWipeOut(&trial.bw);
251           VP8BitWriterWipeOut(&best.bw);
252           break;
253         }
254       }
255     }
256
257     if (ok) {
258       if (stats != NULL) *stats = best.stats;
259       *output_size = VP8BitWriterSize(&best.bw);
260       *output = VP8BitWriterBuf(&best.bw);
261     }
262     free(filtered_alpha);
263   }
264   return ok;
265 }
266
267 static int EncodeAlpha(VP8Encoder* const enc,
268                        int quality, int method, int filter,
269                        int effort_level,
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;
274
275   uint8_t* quant_alpha = NULL;
276   const size_t data_size = width * height;
277   uint64_t sse = 0;
278   int ok = 1;
279   const int reduce_levels = (quality < 100);
280
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);
288
289   if (quality < 0 || quality > 100) {
290     return 0;
291   }
292
293   if (method < ALPHA_NO_COMPRESSION || method > ALPHA_LOSSLESS_COMPRESSION) {
294     return 0;
295   }
296
297   quant_alpha = (uint8_t*)malloc(data_size);
298   if (quant_alpha == NULL) {
299     return 0;
300   }
301
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);
304
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);
312   }
313
314   if (ok) {
315     ok = ApplyFilters(quant_alpha, width, height, data_size, method, filter,
316                       reduce_levels, effort_level, output, output_size,
317                       pic->stats);
318     if (pic->stats != NULL) {  // need stats?
319       pic->stats->coded_size += (int)(*output_size);
320       enc->sse_[3] = sse;
321     }
322   }
323
324   free(quant_alpha);
325   return ok;
326 }
327
328 //------------------------------------------------------------------------------
329 // Main calls
330
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 :
339                                        WEBP_FILTER_BEST;
340   if (!EncodeAlpha(enc, config->alpha_quality, config->alpha_compression,
341                    filter, effort_level, &alpha_data, &alpha_size)) {
342     return 0;
343   }
344   if (alpha_size != (uint32_t)alpha_size) {  // Sanity check.
345     free(alpha_data);
346     return 0;
347   }
348   enc->alpha_data_size_ = (uint32_t)alpha_size;
349   enc->alpha_data_ = alpha_data;
350   (void)dummy;
351   return 1;
352 }
353
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);
361     worker->data1 = enc;
362     worker->data2 = NULL;
363     worker->hook = (WebPWorkerHook)CompressAlphaJob;
364   }
365 }
366
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.
372         return 0;
373       }
374       WebPWorkerLaunch(worker);
375       return 1;
376     } else {
377       return CompressAlphaJob(enc, NULL);   // just do the job right away
378     }
379   }
380   return 1;
381 }
382
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
388     }
389   }
390   return WebPReportProgress(enc->pic_, enc->percent_ + 20, &enc->percent_);
391 }
392
393 int VP8EncDeleteAlpha(VP8Encoder* const enc) {
394   int ok = 1;
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
399   }
400   free(enc->alpha_data_);
401   enc->alpha_data_ = NULL;
402   enc->alpha_data_size_ = 0;
403   enc->has_alpha_ = 0;
404   return ok;
405 }
406
407 #if defined(__cplusplus) || defined(c_plusplus)
408 }    // extern "C"
409 #endif