Path: blob/master/thirdparty/libwebp/src/enc/alpha_enc.c
9913 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>15#include <string.h>1617#include "src/enc/vp8i_enc.h"18#include "src/dsp/dsp.h"19#include "src/utils/filters_utils.h"20#include "src/utils/quant_levels_utils.h"21#include "src/utils/utils.h"22#include "src/webp/encode.h"23#include "src/webp/format_constants.h"2425// -----------------------------------------------------------------------------26// Encodes the given alpha data via specified compression method 'method'.27// The pre-processing (quantization) is performed if 'quality' is less than 100.28// For such cases, the encoding is lossy. The valid range is [0, 100] for29// 'quality' and [0, 1] for 'method':30// 'method = 0' - No compression;31// 'method = 1' - Use lossless coder on the alpha plane only32// 'filter' values [0, 4] correspond to prediction modes none, horizontal,33// vertical & gradient filters. The prediction mode 4 will try all the34// prediction modes 0 to 3 and pick the best one.35// 'effort_level': specifies how much effort must be spent to try and reduce36// the compressed output size. In range 0 (quick) to 6 (slow).37//38// 'output' corresponds to the buffer containing compressed alpha data.39// This buffer is allocated by this method and caller should call40// WebPSafeFree(*output) when done.41// 'output_size' corresponds to size of this compressed alpha buffer.42//43// Returns 1 on successfully encoding the alpha and44// 0 if either:45// invalid quality or method, or46// memory allocation for the compressed data fails.4748#include "src/enc/vp8li_enc.h"4950static int EncodeLossless(const uint8_t* const data, int width, int height,51int effort_level, // in [0..6] range52int use_quality_100, VP8LBitWriter* const bw,53WebPAuxStats* const stats) {54int ok = 0;55WebPConfig config;56WebPPicture picture;5758if (!WebPPictureInit(&picture)) return 0;59picture.width = width;60picture.height = height;61picture.use_argb = 1;62picture.stats = stats;63if (!WebPPictureAlloc(&picture)) return 0;6465// Transfer the alpha values to the green channel.66WebPDispatchAlphaToGreen(data, width, picture.width, picture.height,67picture.argb, picture.argb_stride);6869if (!WebPConfigInit(&config)) return 0;70config.lossless = 1;71// Enable exact, or it would alter RGB values of transparent alpha, which is72// normally OK but not here since we are not encoding the input image but an73// internal encoding-related image containing necessary exact information in74// RGB channels.75config.exact = 1;76config.method = effort_level; // impact is very small77// Set a low default quality for encoding alpha. Ensure that Alpha quality at78// lower methods (3 and below) is less than the threshold for triggering79// costly 'BackwardReferencesTraceBackwards'.80// If the alpha quality is set to 100 and the method to 6, allow for a high81// lossless quality to trigger the cruncher.82config.quality =83(use_quality_100 && effort_level == 6) ? 100 : 8.f * effort_level;84assert(config.quality >= 0 && config.quality <= 100.f);8586ok = VP8LEncodeStream(&config, &picture, bw);87WebPPictureFree(&picture);88ok = ok && !bw->error_;89if (!ok) {90VP8LBitWriterWipeOut(bw);91return 0;92}93return 1;94}9596// -----------------------------------------------------------------------------9798// Small struct to hold the result of a filter mode compression attempt.99typedef struct {100size_t score;101VP8BitWriter bw;102WebPAuxStats stats;103} FilterTrial;104105// This function always returns an initialized 'bw' object, even upon error.106static int EncodeAlphaInternal(const uint8_t* const data, int width, int height,107int method, int filter, int reduce_levels,108int effort_level, // in [0..6] range109uint8_t* const tmp_alpha,110FilterTrial* result) {111int ok = 0;112const uint8_t* alpha_src;113WebPFilterFunc filter_func;114uint8_t header;115const size_t data_size = width * height;116const uint8_t* output = NULL;117size_t output_size = 0;118VP8LBitWriter tmp_bw;119120assert((uint64_t)data_size == (uint64_t)width * height); // as per spec121assert(filter >= 0 && filter < WEBP_FILTER_LAST);122assert(method >= ALPHA_NO_COMPRESSION);123assert(method <= ALPHA_LOSSLESS_COMPRESSION);124assert(sizeof(header) == ALPHA_HEADER_LEN);125126filter_func = WebPFilters[filter];127if (filter_func != NULL) {128filter_func(data, width, height, width, tmp_alpha);129alpha_src = tmp_alpha;130} else {131alpha_src = data;132}133134if (method != ALPHA_NO_COMPRESSION) {135ok = VP8LBitWriterInit(&tmp_bw, data_size >> 3);136ok = ok && EncodeLossless(alpha_src, width, height, effort_level,137!reduce_levels, &tmp_bw, &result->stats);138if (ok) {139output = VP8LBitWriterFinish(&tmp_bw);140if (tmp_bw.error_) {141VP8LBitWriterWipeOut(&tmp_bw);142memset(&result->bw, 0, sizeof(result->bw));143return 0;144}145output_size = VP8LBitWriterNumBytes(&tmp_bw);146if (output_size > data_size) {147// compressed size is larger than source! Revert to uncompressed mode.148method = ALPHA_NO_COMPRESSION;149VP8LBitWriterWipeOut(&tmp_bw);150}151} else {152VP8LBitWriterWipeOut(&tmp_bw);153memset(&result->bw, 0, sizeof(result->bw));154return 0;155}156}157158if (method == ALPHA_NO_COMPRESSION) {159output = alpha_src;160output_size = data_size;161ok = 1;162}163164// Emit final result.165header = method | (filter << 2);166if (reduce_levels) header |= ALPHA_PREPROCESSED_LEVELS << 4;167168if (!VP8BitWriterInit(&result->bw, ALPHA_HEADER_LEN + output_size)) ok = 0;169ok = ok && VP8BitWriterAppend(&result->bw, &header, ALPHA_HEADER_LEN);170ok = ok && VP8BitWriterAppend(&result->bw, output, output_size);171172if (method != ALPHA_NO_COMPRESSION) {173VP8LBitWriterWipeOut(&tmp_bw);174}175ok = ok && !result->bw.error_;176result->score = VP8BitWriterSize(&result->bw);177return ok;178}179180// -----------------------------------------------------------------------------181182static int GetNumColors(const uint8_t* data, int width, int height,183int stride) {184int j;185int colors = 0;186uint8_t color[256] = { 0 };187188for (j = 0; j < height; ++j) {189int i;190const uint8_t* const p = data + j * stride;191for (i = 0; i < width; ++i) {192color[p[i]] = 1;193}194}195for (j = 0; j < 256; ++j) {196if (color[j] > 0) ++colors;197}198return colors;199}200201#define FILTER_TRY_NONE (1 << WEBP_FILTER_NONE)202#define FILTER_TRY_ALL ((1 << WEBP_FILTER_LAST) - 1)203204// Given the input 'filter' option, return an OR'd bit-set of filters to try.205static uint32_t GetFilterMap(const uint8_t* alpha, int width, int height,206int filter, int effort_level) {207uint32_t bit_map = 0U;208if (filter == WEBP_FILTER_FAST) {209// Quick estimate of the best candidate.210int try_filter_none = (effort_level > 3);211const int kMinColorsForFilterNone = 16;212const int kMaxColorsForFilterNone = 192;213const int num_colors = GetNumColors(alpha, width, height, width);214// For low number of colors, NONE yields better compression.215filter = (num_colors <= kMinColorsForFilterNone)216? WEBP_FILTER_NONE217: WebPEstimateBestFilter(alpha, width, height, width);218bit_map |= 1 << filter;219// For large number of colors, try FILTER_NONE in addition to the best220// filter as well.221if (try_filter_none || num_colors > kMaxColorsForFilterNone) {222bit_map |= FILTER_TRY_NONE;223}224} else if (filter == WEBP_FILTER_NONE) {225bit_map = FILTER_TRY_NONE;226} else { // WEBP_FILTER_BEST -> try all227bit_map = FILTER_TRY_ALL;228}229return bit_map;230}231232static void InitFilterTrial(FilterTrial* const score) {233score->score = (size_t)~0U;234VP8BitWriterInit(&score->bw, 0);235}236237static int ApplyFiltersAndEncode(const uint8_t* alpha, int width, int height,238size_t data_size, int method, int filter,239int reduce_levels, int effort_level,240uint8_t** const output,241size_t* const output_size,242WebPAuxStats* const stats) {243int ok = 1;244FilterTrial best;245uint32_t try_map =246GetFilterMap(alpha, width, height, filter, effort_level);247InitFilterTrial(&best);248249if (try_map != FILTER_TRY_NONE) {250uint8_t* filtered_alpha = (uint8_t*)WebPSafeMalloc(1ULL, data_size);251if (filtered_alpha == NULL) return 0;252253for (filter = WEBP_FILTER_NONE; ok && try_map; ++filter, try_map >>= 1) {254if (try_map & 1) {255FilterTrial trial;256ok = EncodeAlphaInternal(alpha, width, height, method, filter,257reduce_levels, effort_level, filtered_alpha,258&trial);259if (ok && trial.score < best.score) {260VP8BitWriterWipeOut(&best.bw);261best = trial;262} else {263VP8BitWriterWipeOut(&trial.bw);264}265}266}267WebPSafeFree(filtered_alpha);268} else {269ok = EncodeAlphaInternal(alpha, width, height, method, WEBP_FILTER_NONE,270reduce_levels, effort_level, NULL, &best);271}272if (ok) {273#if !defined(WEBP_DISABLE_STATS)274if (stats != NULL) {275stats->lossless_features = best.stats.lossless_features;276stats->histogram_bits = best.stats.histogram_bits;277stats->transform_bits = best.stats.transform_bits;278stats->cross_color_transform_bits = best.stats.cross_color_transform_bits;279stats->cache_bits = best.stats.cache_bits;280stats->palette_size = best.stats.palette_size;281stats->lossless_size = best.stats.lossless_size;282stats->lossless_hdr_size = best.stats.lossless_hdr_size;283stats->lossless_data_size = best.stats.lossless_data_size;284}285#else286(void)stats;287#endif288*output_size = VP8BitWriterSize(&best.bw);289*output = VP8BitWriterBuf(&best.bw);290} else {291VP8BitWriterWipeOut(&best.bw);292}293return ok;294}295296static int EncodeAlpha(VP8Encoder* const enc,297int quality, int method, int filter,298int effort_level,299uint8_t** const output, size_t* const output_size) {300const WebPPicture* const pic = enc->pic_;301const int width = pic->width;302const int height = pic->height;303304uint8_t* quant_alpha = NULL;305const size_t data_size = width * height;306uint64_t sse = 0;307int ok = 1;308const int reduce_levels = (quality < 100);309310// quick correctness checks311assert((uint64_t)data_size == (uint64_t)width * height); // as per spec312assert(enc != NULL && pic != NULL && pic->a != NULL);313assert(output != NULL && output_size != NULL);314assert(width > 0 && height > 0);315assert(pic->a_stride >= width);316assert(filter >= WEBP_FILTER_NONE && filter <= WEBP_FILTER_FAST);317318if (quality < 0 || quality > 100) {319return WebPEncodingSetError(pic, VP8_ENC_ERROR_INVALID_CONFIGURATION);320}321322if (method < ALPHA_NO_COMPRESSION || method > ALPHA_LOSSLESS_COMPRESSION) {323return WebPEncodingSetError(pic, VP8_ENC_ERROR_INVALID_CONFIGURATION);324}325326if (method == ALPHA_NO_COMPRESSION) {327// Don't filter, as filtering will make no impact on compressed size.328filter = WEBP_FILTER_NONE;329}330331quant_alpha = (uint8_t*)WebPSafeMalloc(1ULL, data_size);332if (quant_alpha == NULL) {333return WebPEncodingSetError(pic, VP8_ENC_ERROR_OUT_OF_MEMORY);334}335336// Extract alpha data (width x height) from raw_data (stride x height).337WebPCopyPlane(pic->a, pic->a_stride, quant_alpha, width, width, height);338339if (reduce_levels) { // No Quantization required for 'quality = 100'.340// 16 alpha levels gives quite a low MSE w.r.t original alpha plane hence341// mapped to moderate quality 70. Hence Quality:[0, 70] -> Levels:[2, 16]342// and Quality:]70, 100] -> Levels:]16, 256].343const int alpha_levels = (quality <= 70) ? (2 + quality / 5)344: (16 + (quality - 70) * 8);345ok = QuantizeLevels(quant_alpha, width, height, alpha_levels, &sse);346}347348if (ok) {349VP8FiltersInit();350ok = ApplyFiltersAndEncode(quant_alpha, width, height, data_size, method,351filter, reduce_levels, effort_level, output,352output_size, pic->stats);353if (!ok) {354WebPEncodingSetError(pic, VP8_ENC_ERROR_OUT_OF_MEMORY); // imprecise355}356#if !defined(WEBP_DISABLE_STATS)357if (pic->stats != NULL) { // need stats?358pic->stats->coded_size += (int)(*output_size);359enc->sse_[3] = sse;360}361#endif362}363364WebPSafeFree(quant_alpha);365return ok;366}367368//------------------------------------------------------------------------------369// Main calls370371static int CompressAlphaJob(void* arg1, void* unused) {372VP8Encoder* const enc = (VP8Encoder*)arg1;373const WebPConfig* config = enc->config_;374uint8_t* alpha_data = NULL;375size_t alpha_size = 0;376const int effort_level = config->method; // maps to [0..6]377const WEBP_FILTER_TYPE filter =378(config->alpha_filtering == 0) ? WEBP_FILTER_NONE :379(config->alpha_filtering == 1) ? WEBP_FILTER_FAST :380WEBP_FILTER_BEST;381if (!EncodeAlpha(enc, config->alpha_quality, config->alpha_compression,382filter, effort_level, &alpha_data, &alpha_size)) {383return 0;384}385if (alpha_size != (uint32_t)alpha_size) { // Soundness check.386WebPSafeFree(alpha_data);387return 0;388}389enc->alpha_data_size_ = (uint32_t)alpha_size;390enc->alpha_data_ = alpha_data;391(void)unused;392return 1;393}394395void VP8EncInitAlpha(VP8Encoder* const enc) {396WebPInitAlphaProcessing();397enc->has_alpha_ = WebPPictureHasTransparency(enc->pic_);398enc->alpha_data_ = NULL;399enc->alpha_data_size_ = 0;400if (enc->thread_level_ > 0) {401WebPWorker* const worker = &enc->alpha_worker_;402WebPGetWorkerInterface()->Init(worker);403worker->data1 = enc;404worker->data2 = NULL;405worker->hook = CompressAlphaJob;406}407}408409int VP8EncStartAlpha(VP8Encoder* const enc) {410if (enc->has_alpha_) {411if (enc->thread_level_ > 0) {412WebPWorker* const worker = &enc->alpha_worker_;413// Makes sure worker is good to go.414if (!WebPGetWorkerInterface()->Reset(worker)) {415return WebPEncodingSetError(enc->pic_, VP8_ENC_ERROR_OUT_OF_MEMORY);416}417WebPGetWorkerInterface()->Launch(worker);418return 1;419} else {420return CompressAlphaJob(enc, NULL); // just do the job right away421}422}423return 1;424}425426int VP8EncFinishAlpha(VP8Encoder* const enc) {427if (enc->has_alpha_) {428if (enc->thread_level_ > 0) {429WebPWorker* const worker = &enc->alpha_worker_;430if (!WebPGetWorkerInterface()->Sync(worker)) return 0; // error431}432}433return WebPReportProgress(enc->pic_, enc->percent_ + 20, &enc->percent_);434}435436int VP8EncDeleteAlpha(VP8Encoder* const enc) {437int ok = 1;438if (enc->thread_level_ > 0) {439WebPWorker* const worker = &enc->alpha_worker_;440// finish anything left in flight441ok = WebPGetWorkerInterface()->Sync(worker);442// still need to end the worker, even if !ok443WebPGetWorkerInterface()->End(worker);444}445WebPSafeFree(enc->alpha_data_);446enc->alpha_data_ = NULL;447enc->alpha_data_size_ = 0;448enc->has_alpha_ = 0;449return ok;450}451452453