Path: blob/master/3rdparty/libwebp/src/enc/alpha_enc.c
16345 views
// Copyright 2011 Google Inc. All Rights Reserved.1//2// Use of this source code is governed by a BSD-style license3// that can be found in the COPYING file in the root of the source4// tree. An additional intellectual property rights grant can be found5// in the file PATENTS. All contributing project authors may6// be found in the AUTHORS file in the root of the source tree.7// -----------------------------------------------------------------------------8//9// Alpha-plane compression.10//11// Author: Skal ([email protected])1213#include <assert.h>14#include <stdlib.h>1516#include "src/enc/vp8i_enc.h"17#include "src/dsp/dsp.h"18#include "src/utils/filters_utils.h"19#include "src/utils/quant_levels_utils.h"20#include "src/utils/utils.h"21#include "src/webp/format_constants.h"2223// -----------------------------------------------------------------------------24// Encodes the given alpha data via specified compression method 'method'.25// The pre-processing (quantization) is performed if 'quality' is less than 100.26// For such cases, the encoding is lossy. The valid range is [0, 100] for27// 'quality' and [0, 1] for 'method':28// 'method = 0' - No compression;29// 'method = 1' - Use lossless coder on the alpha plane only30// 'filter' values [0, 4] correspond to prediction modes none, horizontal,31// vertical & gradient filters. The prediction mode 4 will try all the32// prediction modes 0 to 3 and pick the best one.33// 'effort_level': specifies how much effort must be spent to try and reduce34// the compressed output size. In range 0 (quick) to 6 (slow).35//36// 'output' corresponds to the buffer containing compressed alpha data.37// This buffer is allocated by this method and caller should call38// WebPSafeFree(*output) when done.39// 'output_size' corresponds to size of this compressed alpha buffer.40//41// Returns 1 on successfully encoding the alpha and42// 0 if either:43// invalid quality or method, or44// memory allocation for the compressed data fails.4546#include "src/enc/vp8li_enc.h"4748static int EncodeLossless(const uint8_t* const data, int width, int height,49int effort_level, // in [0..6] range50int use_quality_100, VP8LBitWriter* const bw,51WebPAuxStats* const stats) {52int ok = 0;53WebPConfig config;54WebPPicture picture;5556WebPPictureInit(&picture);57picture.width = width;58picture.height = height;59picture.use_argb = 1;60picture.stats = stats;61if (!WebPPictureAlloc(&picture)) return 0;6263// Transfer the alpha values to the green channel.64WebPDispatchAlphaToGreen(data, width, picture.width, picture.height,65picture.argb, picture.argb_stride);6667WebPConfigInit(&config);68config.lossless = 1;69// Enable exact, or it would alter RGB values of transparent alpha, which is70// normally OK but not here since we are not encoding the input image but an71// internal encoding-related image containing necessary exact information in72// RGB channels.73config.exact = 1;74config.method = effort_level; // impact is very small75// Set a low default quality for encoding alpha. Ensure that Alpha quality at76// lower methods (3 and below) is less than the threshold for triggering77// costly 'BackwardReferencesTraceBackwards'.78// If the alpha quality is set to 100 and the method to 6, allow for a high79// lossless quality to trigger the cruncher.80config.quality =81(use_quality_100 && effort_level == 6) ? 100 : 8.f * effort_level;82assert(config.quality >= 0 && config.quality <= 100.f);8384// TODO(urvang): Temporary fix to avoid generating images that trigger85// a decoder bug related to alpha with color cache.86// See: https://code.google.com/p/webp/issues/detail?id=23987// Need to re-enable this later.88ok = (VP8LEncodeStream(&config, &picture, bw, 0 /*use_cache*/) == VP8_ENC_OK);89WebPPictureFree(&picture);90ok = ok && !bw->error_;91if (!ok) {92VP8LBitWriterWipeOut(bw);93return 0;94}95return 1;96}9798// -----------------------------------------------------------------------------99100// Small struct to hold the result of a filter mode compression attempt.101typedef struct {102size_t score;103VP8BitWriter bw;104WebPAuxStats stats;105} FilterTrial;106107// This function always returns an initialized 'bw' object, even upon error.108static int EncodeAlphaInternal(const uint8_t* const data, int width, int height,109int method, int filter, int reduce_levels,110int effort_level, // in [0..6] range111uint8_t* const tmp_alpha,112FilterTrial* result) {113int ok = 0;114const uint8_t* alpha_src;115WebPFilterFunc filter_func;116uint8_t header;117const size_t data_size = width * height;118const uint8_t* output = NULL;119size_t output_size = 0;120VP8LBitWriter tmp_bw;121122assert((uint64_t)data_size == (uint64_t)width * height); // as per spec123assert(filter >= 0 && filter < WEBP_FILTER_LAST);124assert(method >= ALPHA_NO_COMPRESSION);125assert(method <= ALPHA_LOSSLESS_COMPRESSION);126assert(sizeof(header) == ALPHA_HEADER_LEN);127128filter_func = WebPFilters[filter];129if (filter_func != NULL) {130filter_func(data, width, height, width, tmp_alpha);131alpha_src = tmp_alpha;132} else {133alpha_src = data;134}135136if (method != ALPHA_NO_COMPRESSION) {137ok = VP8LBitWriterInit(&tmp_bw, data_size >> 3);138ok = ok && EncodeLossless(alpha_src, width, height, effort_level,139!reduce_levels, &tmp_bw, &result->stats);140if (ok) {141output = VP8LBitWriterFinish(&tmp_bw);142output_size = VP8LBitWriterNumBytes(&tmp_bw);143if (output_size > data_size) {144// compressed size is larger than source! Revert to uncompressed mode.145method = ALPHA_NO_COMPRESSION;146VP8LBitWriterWipeOut(&tmp_bw);147}148} else {149VP8LBitWriterWipeOut(&tmp_bw);150return 0;151}152}153154if (method == ALPHA_NO_COMPRESSION) {155output = alpha_src;156output_size = data_size;157ok = 1;158}159160// Emit final result.161header = method | (filter << 2);162if (reduce_levels) header |= ALPHA_PREPROCESSED_LEVELS << 4;163164VP8BitWriterInit(&result->bw, ALPHA_HEADER_LEN + output_size);165ok = ok && VP8BitWriterAppend(&result->bw, &header, ALPHA_HEADER_LEN);166ok = ok && VP8BitWriterAppend(&result->bw, output, output_size);167168if (method != ALPHA_NO_COMPRESSION) {169VP8LBitWriterWipeOut(&tmp_bw);170}171ok = ok && !result->bw.error_;172result->score = VP8BitWriterSize(&result->bw);173return ok;174}175176// -----------------------------------------------------------------------------177178static int GetNumColors(const uint8_t* data, int width, int height,179int stride) {180int j;181int colors = 0;182uint8_t color[256] = { 0 };183184for (j = 0; j < height; ++j) {185int i;186const uint8_t* const p = data + j * stride;187for (i = 0; i < width; ++i) {188color[p[i]] = 1;189}190}191for (j = 0; j < 256; ++j) {192if (color[j] > 0) ++colors;193}194return colors;195}196197#define FILTER_TRY_NONE (1 << WEBP_FILTER_NONE)198#define FILTER_TRY_ALL ((1 << WEBP_FILTER_LAST) - 1)199200// Given the input 'filter' option, return an OR'd bit-set of filters to try.201static uint32_t GetFilterMap(const uint8_t* alpha, int width, int height,202int filter, int effort_level) {203uint32_t bit_map = 0U;204if (filter == WEBP_FILTER_FAST) {205// Quick estimate of the best candidate.206int try_filter_none = (effort_level > 3);207const int kMinColorsForFilterNone = 16;208const int kMaxColorsForFilterNone = 192;209const int num_colors = GetNumColors(alpha, width, height, width);210// For low number of colors, NONE yields better compression.211filter = (num_colors <= kMinColorsForFilterNone)212? WEBP_FILTER_NONE213: WebPEstimateBestFilter(alpha, width, height, width);214bit_map |= 1 << filter;215// For large number of colors, try FILTER_NONE in addition to the best216// filter as well.217if (try_filter_none || num_colors > kMaxColorsForFilterNone) {218bit_map |= FILTER_TRY_NONE;219}220} else if (filter == WEBP_FILTER_NONE) {221bit_map = FILTER_TRY_NONE;222} else { // WEBP_FILTER_BEST -> try all223bit_map = FILTER_TRY_ALL;224}225return bit_map;226}227228static void InitFilterTrial(FilterTrial* const score) {229score->score = (size_t)~0U;230VP8BitWriterInit(&score->bw, 0);231}232233static int ApplyFiltersAndEncode(const uint8_t* alpha, int width, int height,234size_t data_size, int method, int filter,235int reduce_levels, int effort_level,236uint8_t** const output,237size_t* const output_size,238WebPAuxStats* const stats) {239int ok = 1;240FilterTrial best;241uint32_t try_map =242GetFilterMap(alpha, width, height, filter, effort_level);243InitFilterTrial(&best);244245if (try_map != FILTER_TRY_NONE) {246uint8_t* filtered_alpha = (uint8_t*)WebPSafeMalloc(1ULL, data_size);247if (filtered_alpha == NULL) return 0;248249for (filter = WEBP_FILTER_NONE; ok && try_map; ++filter, try_map >>= 1) {250if (try_map & 1) {251FilterTrial trial;252ok = EncodeAlphaInternal(alpha, width, height, method, filter,253reduce_levels, effort_level, filtered_alpha,254&trial);255if (ok && trial.score < best.score) {256VP8BitWriterWipeOut(&best.bw);257best = trial;258} else {259VP8BitWriterWipeOut(&trial.bw);260}261}262}263WebPSafeFree(filtered_alpha);264} else {265ok = EncodeAlphaInternal(alpha, width, height, method, WEBP_FILTER_NONE,266reduce_levels, effort_level, NULL, &best);267}268if (ok) {269#if !defined(WEBP_DISABLE_STATS)270if (stats != NULL) {271stats->lossless_features = best.stats.lossless_features;272stats->histogram_bits = best.stats.histogram_bits;273stats->transform_bits = best.stats.transform_bits;274stats->cache_bits = best.stats.cache_bits;275stats->palette_size = best.stats.palette_size;276stats->lossless_size = best.stats.lossless_size;277stats->lossless_hdr_size = best.stats.lossless_hdr_size;278stats->lossless_data_size = best.stats.lossless_data_size;279}280#else281(void)stats;282#endif283*output_size = VP8BitWriterSize(&best.bw);284*output = VP8BitWriterBuf(&best.bw);285} else {286VP8BitWriterWipeOut(&best.bw);287}288return ok;289}290291static int EncodeAlpha(VP8Encoder* const enc,292int quality, int method, int filter,293int effort_level,294uint8_t** const output, size_t* const output_size) {295const WebPPicture* const pic = enc->pic_;296const int width = pic->width;297const int height = pic->height;298299uint8_t* quant_alpha = NULL;300const size_t data_size = width * height;301uint64_t sse = 0;302int ok = 1;303const int reduce_levels = (quality < 100);304305// quick sanity checks306assert((uint64_t)data_size == (uint64_t)width * height); // as per spec307assert(enc != NULL && pic != NULL && pic->a != NULL);308assert(output != NULL && output_size != NULL);309assert(width > 0 && height > 0);310assert(pic->a_stride >= width);311assert(filter >= WEBP_FILTER_NONE && filter <= WEBP_FILTER_FAST);312313if (quality < 0 || quality > 100) {314return 0;315}316317if (method < ALPHA_NO_COMPRESSION || method > ALPHA_LOSSLESS_COMPRESSION) {318return 0;319}320321if (method == ALPHA_NO_COMPRESSION) {322// Don't filter, as filtering will make no impact on compressed size.323filter = WEBP_FILTER_NONE;324}325326quant_alpha = (uint8_t*)WebPSafeMalloc(1ULL, data_size);327if (quant_alpha == NULL) {328return 0;329}330331// Extract alpha data (width x height) from raw_data (stride x height).332WebPCopyPlane(pic->a, pic->a_stride, quant_alpha, width, width, height);333334if (reduce_levels) { // No Quantization required for 'quality = 100'.335// 16 alpha levels gives quite a low MSE w.r.t original alpha plane hence336// mapped to moderate quality 70. Hence Quality:[0, 70] -> Levels:[2, 16]337// and Quality:]70, 100] -> Levels:]16, 256].338const int alpha_levels = (quality <= 70) ? (2 + quality / 5)339: (16 + (quality - 70) * 8);340ok = QuantizeLevels(quant_alpha, width, height, alpha_levels, &sse);341}342343if (ok) {344VP8FiltersInit();345ok = ApplyFiltersAndEncode(quant_alpha, width, height, data_size, method,346filter, reduce_levels, effort_level, output,347output_size, pic->stats);348#if !defined(WEBP_DISABLE_STATS)349if (pic->stats != NULL) { // need stats?350pic->stats->coded_size += (int)(*output_size);351enc->sse_[3] = sse;352}353#endif354}355356WebPSafeFree(quant_alpha);357return ok;358}359360//------------------------------------------------------------------------------361// Main calls362363static int CompressAlphaJob(void* arg1, void* dummy) {364VP8Encoder* const enc = (VP8Encoder*)arg1;365const WebPConfig* config = enc->config_;366uint8_t* alpha_data = NULL;367size_t alpha_size = 0;368const int effort_level = config->method; // maps to [0..6]369const WEBP_FILTER_TYPE filter =370(config->alpha_filtering == 0) ? WEBP_FILTER_NONE :371(config->alpha_filtering == 1) ? WEBP_FILTER_FAST :372WEBP_FILTER_BEST;373if (!EncodeAlpha(enc, config->alpha_quality, config->alpha_compression,374filter, effort_level, &alpha_data, &alpha_size)) {375return 0;376}377if (alpha_size != (uint32_t)alpha_size) { // Sanity check.378WebPSafeFree(alpha_data);379return 0;380}381enc->alpha_data_size_ = (uint32_t)alpha_size;382enc->alpha_data_ = alpha_data;383(void)dummy;384return 1;385}386387void VP8EncInitAlpha(VP8Encoder* const enc) {388WebPInitAlphaProcessing();389enc->has_alpha_ = WebPPictureHasTransparency(enc->pic_);390enc->alpha_data_ = NULL;391enc->alpha_data_size_ = 0;392if (enc->thread_level_ > 0) {393WebPWorker* const worker = &enc->alpha_worker_;394WebPGetWorkerInterface()->Init(worker);395worker->data1 = enc;396worker->data2 = NULL;397worker->hook = CompressAlphaJob;398}399}400401int VP8EncStartAlpha(VP8Encoder* const enc) {402if (enc->has_alpha_) {403if (enc->thread_level_ > 0) {404WebPWorker* const worker = &enc->alpha_worker_;405// Makes sure worker is good to go.406if (!WebPGetWorkerInterface()->Reset(worker)) {407return 0;408}409WebPGetWorkerInterface()->Launch(worker);410return 1;411} else {412return CompressAlphaJob(enc, NULL); // just do the job right away413}414}415return 1;416}417418int VP8EncFinishAlpha(VP8Encoder* const enc) {419if (enc->has_alpha_) {420if (enc->thread_level_ > 0) {421WebPWorker* const worker = &enc->alpha_worker_;422if (!WebPGetWorkerInterface()->Sync(worker)) return 0; // error423}424}425return WebPReportProgress(enc->pic_, enc->percent_ + 20, &enc->percent_);426}427428int VP8EncDeleteAlpha(VP8Encoder* const enc) {429int ok = 1;430if (enc->thread_level_ > 0) {431WebPWorker* const worker = &enc->alpha_worker_;432// finish anything left in flight433ok = WebPGetWorkerInterface()->Sync(worker);434// still need to end the worker, even if !ok435WebPGetWorkerInterface()->End(worker);436}437WebPSafeFree(enc->alpha_data_);438enc->alpha_data_ = NULL;439enc->alpha_data_size_ = 0;440enc->has_alpha_ = 0;441return ok;442}443444445