Home | History | Annotate | Download | only in enc
      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 (at) 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 = 5.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 static int EncodeAlphaInternal(const uint8_t* const data, int width, int height,
    101                                int method, int filter, int reduce_levels,
    102                                int effort_level,  // in [0..6] range
    103                                uint8_t* const tmp_alpha,
    104                                VP8BitWriter* const bw,
    105                                WebPAuxStats* const stats) {
    106   int ok = 0;
    107   const uint8_t* alpha_src;
    108   WebPFilterFunc filter_func;
    109   uint8_t header;
    110   size_t expected_size;
    111   const size_t data_size = width * height;
    112 
    113   assert((uint64_t)data_size == (uint64_t)width * height);  // as per spec
    114   assert(filter >= 0 && filter < WEBP_FILTER_LAST);
    115   assert(method >= ALPHA_NO_COMPRESSION);
    116   assert(method <= ALPHA_LOSSLESS_COMPRESSION);
    117   assert(sizeof(header) == ALPHA_HEADER_LEN);
    118   // TODO(skal): have a common function and #define's to validate alpha params.
    119 
    120   expected_size =
    121       (method == ALPHA_NO_COMPRESSION) ? (ALPHA_HEADER_LEN + data_size)
    122                                        : (data_size >> 5);
    123   header = method | (filter << 2);
    124   if (reduce_levels) header |= ALPHA_PREPROCESSED_LEVELS << 4;
    125 
    126   VP8BitWriterInit(bw, expected_size);
    127   VP8BitWriterAppend(bw, &header, ALPHA_HEADER_LEN);
    128 
    129   filter_func = WebPFilters[filter];
    130   if (filter_func) {
    131     filter_func(data, width, height, 1, width, tmp_alpha);
    132     alpha_src = tmp_alpha;
    133   }  else {
    134     alpha_src = data;
    135   }
    136 
    137   if (method == ALPHA_NO_COMPRESSION) {
    138     ok = VP8BitWriterAppend(bw, alpha_src, width * height);
    139     ok = ok && !bw->error_;
    140   } else {
    141     ok = EncodeLossless(alpha_src, width, height, effort_level, bw, stats);
    142     VP8BitWriterFinish(bw);
    143   }
    144   return ok;
    145 }
    146 
    147 // -----------------------------------------------------------------------------
    148 
    149 // TODO(skal): move to dsp/ ?
    150 static void CopyPlane(const uint8_t* src, int src_stride,
    151                       uint8_t* dst, int dst_stride, int width, int height) {
    152   while (height-- > 0) {
    153     memcpy(dst, src, width);
    154     src += src_stride;
    155     dst += dst_stride;
    156   }
    157 }
    158 
    159 static int EncodeAlpha(VP8Encoder* const enc,
    160                        int quality, int method, int filter,
    161                        int effort_level,
    162                        uint8_t** const output, size_t* const output_size) {
    163   const WebPPicture* const pic = enc->pic_;
    164   const int width = pic->width;
    165   const int height = pic->height;
    166 
    167   uint8_t* quant_alpha = NULL;
    168   const size_t data_size = width * height;
    169   uint64_t sse = 0;
    170   int ok = 1;
    171   const int reduce_levels = (quality < 100);
    172 
    173   // quick sanity checks
    174   assert((uint64_t)data_size == (uint64_t)width * height);  // as per spec
    175   assert(enc != NULL && pic != NULL && pic->a != NULL);
    176   assert(output != NULL && output_size != NULL);
    177   assert(width > 0 && height > 0);
    178   assert(pic->a_stride >= width);
    179   assert(filter >= WEBP_FILTER_NONE && filter <= WEBP_FILTER_FAST);
    180 
    181   if (quality < 0 || quality > 100) {
    182     return 0;
    183   }
    184 
    185   if (method < ALPHA_NO_COMPRESSION || method > ALPHA_LOSSLESS_COMPRESSION) {
    186     return 0;
    187   }
    188 
    189   quant_alpha = (uint8_t*)malloc(data_size);
    190   if (quant_alpha == NULL) {
    191     return 0;
    192   }
    193 
    194   // Extract alpha data (width x height) from raw_data (stride x height).
    195   CopyPlane(pic->a, pic->a_stride, quant_alpha, width, width, height);
    196 
    197   if (reduce_levels) {  // No Quantization required for 'quality = 100'.
    198     // 16 alpha levels gives quite a low MSE w.r.t original alpha plane hence
    199     // mapped to moderate quality 70. Hence Quality:[0, 70] -> Levels:[2, 16]
    200     // and Quality:]70, 100] -> Levels:]16, 256].
    201     const int alpha_levels = (quality <= 70) ? (2 + quality / 5)
    202                                              : (16 + (quality - 70) * 8);
    203     ok = QuantizeLevels(quant_alpha, width, height, alpha_levels, &sse);
    204   }
    205 
    206   if (ok) {
    207     VP8BitWriter bw;
    208     int test_filter;
    209     uint8_t* filtered_alpha = NULL;
    210 
    211     // We always test WEBP_FILTER_NONE first.
    212     ok = EncodeAlphaInternal(quant_alpha, width, height,
    213                              method, WEBP_FILTER_NONE, reduce_levels,
    214                              effort_level, NULL, &bw, pic->stats);
    215     if (!ok) {
    216       VP8BitWriterWipeOut(&bw);
    217       goto End;
    218     }
    219 
    220     if (filter == WEBP_FILTER_FAST) {  // Quick estimate of a second candidate?
    221       filter = EstimateBestFilter(quant_alpha, width, height, width);
    222     }
    223     // Stop?
    224     if (filter == WEBP_FILTER_NONE) {
    225       goto Ok;
    226     }
    227 
    228     filtered_alpha = (uint8_t*)malloc(data_size);
    229     ok = (filtered_alpha != NULL);
    230     if (!ok) {
    231       goto End;
    232     }
    233 
    234     // Try the other mode(s).
    235     {
    236       WebPAuxStats best_stats;
    237       size_t best_score = VP8BitWriterSize(&bw);
    238 
    239       memset(&best_stats, 0, sizeof(best_stats));  // prevent spurious warning
    240       if (pic->stats != NULL) best_stats = *pic->stats;
    241       for (test_filter = WEBP_FILTER_HORIZONTAL;
    242            ok && (test_filter <= WEBP_FILTER_GRADIENT);
    243            ++test_filter) {
    244         VP8BitWriter tmp_bw;
    245         if (filter != WEBP_FILTER_BEST && test_filter != filter) {
    246           continue;
    247         }
    248         ok = EncodeAlphaInternal(quant_alpha, width, height,
    249                                  method, test_filter, reduce_levels,
    250                                  effort_level, filtered_alpha, &tmp_bw,
    251                                  pic->stats);
    252         if (ok) {
    253           const size_t score = VP8BitWriterSize(&tmp_bw);
    254           if (score < best_score) {
    255             // swap bitwriter objects.
    256             VP8BitWriter tmp = tmp_bw;
    257             tmp_bw = bw;
    258             bw = tmp;
    259             best_score = score;
    260             if (pic->stats != NULL) best_stats = *pic->stats;
    261           }
    262         } else {
    263           VP8BitWriterWipeOut(&bw);
    264         }
    265         VP8BitWriterWipeOut(&tmp_bw);
    266       }
    267       if (pic->stats != NULL) *pic->stats = best_stats;
    268     }
    269  Ok:
    270     if (ok) {
    271       *output_size = VP8BitWriterSize(&bw);
    272       *output = VP8BitWriterBuf(&bw);
    273       if (pic->stats != NULL) {         // need stats?
    274         pic->stats->coded_size += (int)(*output_size);
    275         enc->sse_[3] = sse;
    276       }
    277     }
    278     free(filtered_alpha);
    279   }
    280  End:
    281   free(quant_alpha);
    282   return ok;
    283 }
    284 
    285 
    286 //------------------------------------------------------------------------------
    287 // Main calls
    288 
    289 static int CompressAlphaJob(VP8Encoder* const enc, void* dummy) {
    290   const WebPConfig* config = enc->config_;
    291   uint8_t* alpha_data = NULL;
    292   size_t alpha_size = 0;
    293   const int effort_level = config->method;  // maps to [0..6]
    294   const WEBP_FILTER_TYPE filter =
    295       (config->alpha_filtering == 0) ? WEBP_FILTER_NONE :
    296       (config->alpha_filtering == 1) ? WEBP_FILTER_FAST :
    297                                        WEBP_FILTER_BEST;
    298   if (!EncodeAlpha(enc, config->alpha_quality, config->alpha_compression,
    299                    filter, effort_level, &alpha_data, &alpha_size)) {
    300     return 0;
    301   }
    302   if (alpha_size != (uint32_t)alpha_size) {  // Sanity check.
    303     free(alpha_data);
    304     return 0;
    305   }
    306   enc->alpha_data_size_ = (uint32_t)alpha_size;
    307   enc->alpha_data_ = alpha_data;
    308   (void)dummy;
    309   return 1;
    310 }
    311 
    312 void VP8EncInitAlpha(VP8Encoder* const enc) {
    313   enc->has_alpha_ = WebPPictureHasTransparency(enc->pic_);
    314   enc->alpha_data_ = NULL;
    315   enc->alpha_data_size_ = 0;
    316   if (enc->thread_level_ > 0) {
    317     WebPWorker* const worker = &enc->alpha_worker_;
    318     WebPWorkerInit(worker);
    319     worker->data1 = enc;
    320     worker->data2 = NULL;
    321     worker->hook = (WebPWorkerHook)CompressAlphaJob;
    322   }
    323 }
    324 
    325 int VP8EncStartAlpha(VP8Encoder* const enc) {
    326   if (enc->has_alpha_) {
    327     if (enc->thread_level_ > 0) {
    328       WebPWorker* const worker = &enc->alpha_worker_;
    329       if (!WebPWorkerReset(worker)) {    // Makes sure worker is good to go.
    330         return 0;
    331       }
    332       WebPWorkerLaunch(worker);
    333       return 1;
    334     } else {
    335       return CompressAlphaJob(enc, NULL);   // just do the job right away
    336     }
    337   }
    338   return 1;
    339 }
    340 
    341 int VP8EncFinishAlpha(VP8Encoder* const enc) {
    342   if (enc->has_alpha_) {
    343     if (enc->thread_level_ > 0) {
    344       WebPWorker* const worker = &enc->alpha_worker_;
    345       if (!WebPWorkerSync(worker)) return 0;  // error
    346     }
    347   }
    348   return WebPReportProgress(enc->pic_, enc->percent_ + 20, &enc->percent_);
    349 }
    350 
    351 int VP8EncDeleteAlpha(VP8Encoder* const enc) {
    352   int ok = 1;
    353   if (enc->thread_level_ > 0) {
    354     WebPWorker* const worker = &enc->alpha_worker_;
    355     ok = WebPWorkerSync(worker);  // finish anything left in flight
    356     WebPWorkerEnd(worker);  // still need to end the worker, even if !ok
    357   }
    358   free(enc->alpha_data_);
    359   enc->alpha_data_ = NULL;
    360   enc->alpha_data_size_ = 0;
    361   enc->has_alpha_ = 0;
    362   return ok;
    363 }
    364 
    365 #if defined(__cplusplus) || defined(c_plusplus)
    366 }    // extern "C"
    367 #endif
    368