Path: blob/master/thirdparty/libwebp/src/enc/webp_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// WebP encoder: main entry point10//11// Author: Skal ([email protected])1213#include <assert.h>14#include <stdlib.h>15#include <string.h>16#include <math.h>1718#include "src/enc/cost_enc.h"19#include "src/enc/vp8i_enc.h"20#include "src/enc/vp8li_enc.h"21#include "src/utils/utils.h"2223// #define PRINT_MEMORY_INFO2425#ifdef PRINT_MEMORY_INFO26#include <stdio.h>27#endif2829//------------------------------------------------------------------------------3031int WebPGetEncoderVersion(void) {32return (ENC_MAJ_VERSION << 16) | (ENC_MIN_VERSION << 8) | ENC_REV_VERSION;33}3435//------------------------------------------------------------------------------36// VP8Encoder37//------------------------------------------------------------------------------3839static void ResetSegmentHeader(VP8Encoder* const enc) {40VP8EncSegmentHeader* const hdr = &enc->segment_hdr_;41hdr->num_segments_ = enc->config_->segments;42hdr->update_map_ = (hdr->num_segments_ > 1);43hdr->size_ = 0;44}4546static void ResetFilterHeader(VP8Encoder* const enc) {47VP8EncFilterHeader* const hdr = &enc->filter_hdr_;48hdr->simple_ = 1;49hdr->level_ = 0;50hdr->sharpness_ = 0;51hdr->i4x4_lf_delta_ = 0;52}5354static void ResetBoundaryPredictions(VP8Encoder* const enc) {55// init boundary values once for all56// Note: actually, initializing the preds_[] is only needed for intra4.57int i;58uint8_t* const top = enc->preds_ - enc->preds_w_;59uint8_t* const left = enc->preds_ - 1;60for (i = -1; i < 4 * enc->mb_w_; ++i) {61top[i] = B_DC_PRED;62}63for (i = 0; i < 4 * enc->mb_h_; ++i) {64left[i * enc->preds_w_] = B_DC_PRED;65}66enc->nz_[-1] = 0; // constant67}6869// Mapping from config->method_ to coding tools used.70//-------------------+---+---+---+---+---+---+---+71// Method | 0 | 1 | 2 | 3 |(4)| 5 | 6 |72//-------------------+---+---+---+---+---+---+---+73// fast probe | x | | | x | | | |74//-------------------+---+---+---+---+---+---+---+75// dynamic proba | ~ | x | x | x | x | x | x |76//-------------------+---+---+---+---+---+---+---+77// fast mode analysis|[x]|[x]| | | x | x | x |78//-------------------+---+---+---+---+---+---+---+79// basic rd-opt | | | | x | x | x | x |80//-------------------+---+---+---+---+---+---+---+81// disto-refine i4/16| x | x | x | | | | |82//-------------------+---+---+---+---+---+---+---+83// disto-refine uv | | x | x | | | | |84//-------------------+---+---+---+---+---+---+---+85// rd-opt i4/16 | | | ~ | x | x | x | x |86//-------------------+---+---+---+---+---+---+---+87// token buffer (opt)| | | | x | x | x | x |88//-------------------+---+---+---+---+---+---+---+89// Trellis | | | | | | x |Ful|90//-------------------+---+---+---+---+---+---+---+91// full-SNS | | | | | x | x | x |92//-------------------+---+---+---+---+---+---+---+9394static void MapConfigToTools(VP8Encoder* const enc) {95const WebPConfig* const config = enc->config_;96const int method = config->method;97const int limit = 100 - config->partition_limit;98enc->method_ = method;99enc->rd_opt_level_ = (method >= 6) ? RD_OPT_TRELLIS_ALL100: (method >= 5) ? RD_OPT_TRELLIS101: (method >= 3) ? RD_OPT_BASIC102: RD_OPT_NONE;103enc->max_i4_header_bits_ =104256 * 16 * 16 * // upper bound: up to 16bit per 4x4 block105(limit * limit) / (100 * 100); // ... modulated with a quadratic curve.106107// partition0 = 512k max.108enc->mb_header_limit_ =109(score_t)256 * 510 * 8 * 1024 / (enc->mb_w_ * enc->mb_h_);110111enc->thread_level_ = config->thread_level;112113enc->do_search_ = (config->target_size > 0 || config->target_PSNR > 0);114if (!config->low_memory) {115#if !defined(DISABLE_TOKEN_BUFFER)116enc->use_tokens_ = (enc->rd_opt_level_ >= RD_OPT_BASIC); // need rd stats117#endif118if (enc->use_tokens_) {119enc->num_parts_ = 1; // doesn't work with multi-partition120}121}122}123124// Memory scaling with dimensions:125// memory (bytes) ~= 2.25 * w + 0.0625 * w * h126//127// Typical memory footprint (614x440 picture)128// encoder: 22111129// info: 4368130// preds: 17741131// top samples: 1263132// non-zero: 175133// lf-stats: 0134// total: 45658135// Transient object sizes:136// VP8EncIterator: 3360137// VP8ModeScore: 872138// VP8SegmentInfo: 732139// VP8EncProba: 18352140// LFStats: 2048141// Picture size (yuv): 419328142143static VP8Encoder* InitVP8Encoder(const WebPConfig* const config,144WebPPicture* const picture) {145VP8Encoder* enc;146const int use_filter =147(config->filter_strength > 0) || (config->autofilter > 0);148const int mb_w = (picture->width + 15) >> 4;149const int mb_h = (picture->height + 15) >> 4;150const int preds_w = 4 * mb_w + 1;151const int preds_h = 4 * mb_h + 1;152const size_t preds_size = preds_w * preds_h * sizeof(*enc->preds_);153const int top_stride = mb_w * 16;154const size_t nz_size = (mb_w + 1) * sizeof(*enc->nz_) + WEBP_ALIGN_CST;155const size_t info_size = mb_w * mb_h * sizeof(*enc->mb_info_);156const size_t samples_size =1572 * top_stride * sizeof(*enc->y_top_) // top-luma/u/v158+ WEBP_ALIGN_CST; // align all159const size_t lf_stats_size =160config->autofilter ? sizeof(*enc->lf_stats_) + WEBP_ALIGN_CST : 0;161const size_t top_derr_size =162(config->quality <= ERROR_DIFFUSION_QUALITY || config->pass > 1) ?163mb_w * sizeof(*enc->top_derr_) : 0;164uint8_t* mem;165const uint64_t size = (uint64_t)sizeof(*enc) // main struct166+ WEBP_ALIGN_CST // cache alignment167+ info_size // modes info168+ preds_size // prediction modes169+ samples_size // top/left samples170+ top_derr_size // top diffusion error171+ nz_size // coeff context bits172+ lf_stats_size; // autofilter stats173174#ifdef PRINT_MEMORY_INFO175printf("===================================\n");176printf("Memory used:\n"177" encoder: %ld\n"178" info: %ld\n"179" preds: %ld\n"180" top samples: %ld\n"181" top diffusion: %ld\n"182" non-zero: %ld\n"183" lf-stats: %ld\n"184" total: %ld\n",185sizeof(*enc) + WEBP_ALIGN_CST, info_size,186preds_size, samples_size, top_derr_size, nz_size, lf_stats_size, size);187printf("Transient object sizes:\n"188" VP8EncIterator: %ld\n"189" VP8ModeScore: %ld\n"190" VP8SegmentInfo: %ld\n"191" VP8EncProba: %ld\n"192" LFStats: %ld\n",193sizeof(VP8EncIterator), sizeof(VP8ModeScore),194sizeof(VP8SegmentInfo), sizeof(VP8EncProba),195sizeof(LFStats));196printf("Picture size (yuv): %ld\n",197mb_w * mb_h * 384 * sizeof(uint8_t));198printf("===================================\n");199#endif200mem = (uint8_t*)WebPSafeMalloc(size, sizeof(*mem));201if (mem == NULL) {202WebPEncodingSetError(picture, VP8_ENC_ERROR_OUT_OF_MEMORY);203return NULL;204}205enc = (VP8Encoder*)mem;206mem = (uint8_t*)WEBP_ALIGN(mem + sizeof(*enc));207memset(enc, 0, sizeof(*enc));208enc->num_parts_ = 1 << config->partitions;209enc->mb_w_ = mb_w;210enc->mb_h_ = mb_h;211enc->preds_w_ = preds_w;212enc->mb_info_ = (VP8MBInfo*)mem;213mem += info_size;214enc->preds_ = mem + 1 + enc->preds_w_;215mem += preds_size;216enc->nz_ = 1 + (uint32_t*)WEBP_ALIGN(mem);217mem += nz_size;218enc->lf_stats_ = lf_stats_size ? (LFStats*)WEBP_ALIGN(mem) : NULL;219mem += lf_stats_size;220221// top samples (all 16-aligned)222mem = (uint8_t*)WEBP_ALIGN(mem);223enc->y_top_ = mem;224enc->uv_top_ = enc->y_top_ + top_stride;225mem += 2 * top_stride;226enc->top_derr_ = top_derr_size ? (DError*)mem : NULL;227mem += top_derr_size;228assert(mem <= (uint8_t*)enc + size);229230enc->config_ = config;231enc->profile_ = use_filter ? ((config->filter_type == 1) ? 0 : 1) : 2;232enc->pic_ = picture;233enc->percent_ = 0;234235MapConfigToTools(enc);236VP8EncDspInit();237VP8DefaultProbas(enc);238ResetSegmentHeader(enc);239ResetFilterHeader(enc);240ResetBoundaryPredictions(enc);241VP8EncDspCostInit();242VP8EncInitAlpha(enc);243244// lower quality means smaller output -> we modulate a little the page245// size based on quality. This is just a crude 1rst-order prediction.246{247const float scale = 1.f + config->quality * 5.f / 100.f; // in [1,6]248VP8TBufferInit(&enc->tokens_, (int)(mb_w * mb_h * 4 * scale));249}250return enc;251}252253static int DeleteVP8Encoder(VP8Encoder* enc) {254int ok = 1;255if (enc != NULL) {256ok = VP8EncDeleteAlpha(enc);257VP8TBufferClear(&enc->tokens_);258WebPSafeFree(enc);259}260return ok;261}262263//------------------------------------------------------------------------------264265#if !defined(WEBP_DISABLE_STATS)266static double GetPSNR(uint64_t err, uint64_t size) {267return (err > 0 && size > 0) ? 10. * log10(255. * 255. * size / err) : 99.;268}269270static void FinalizePSNR(const VP8Encoder* const enc) {271WebPAuxStats* stats = enc->pic_->stats;272const uint64_t size = enc->sse_count_;273const uint64_t* const sse = enc->sse_;274stats->PSNR[0] = (float)GetPSNR(sse[0], size);275stats->PSNR[1] = (float)GetPSNR(sse[1], size / 4);276stats->PSNR[2] = (float)GetPSNR(sse[2], size / 4);277stats->PSNR[3] = (float)GetPSNR(sse[0] + sse[1] + sse[2], size * 3 / 2);278stats->PSNR[4] = (float)GetPSNR(sse[3], size);279}280#endif // !defined(WEBP_DISABLE_STATS)281282static void StoreStats(VP8Encoder* const enc) {283#if !defined(WEBP_DISABLE_STATS)284WebPAuxStats* const stats = enc->pic_->stats;285if (stats != NULL) {286int i, s;287for (i = 0; i < NUM_MB_SEGMENTS; ++i) {288stats->segment_level[i] = enc->dqm_[i].fstrength_;289stats->segment_quant[i] = enc->dqm_[i].quant_;290for (s = 0; s <= 2; ++s) {291stats->residual_bytes[s][i] = enc->residual_bytes_[s][i];292}293}294FinalizePSNR(enc);295stats->coded_size = enc->coded_size_;296for (i = 0; i < 3; ++i) {297stats->block_count[i] = enc->block_count_[i];298}299}300#else // defined(WEBP_DISABLE_STATS)301WebPReportProgress(enc->pic_, 100, &enc->percent_); // done!302#endif // !defined(WEBP_DISABLE_STATS)303}304305int WebPEncodingSetError(const WebPPicture* const pic,306WebPEncodingError error) {307assert((int)error < VP8_ENC_ERROR_LAST);308assert((int)error >= VP8_ENC_OK);309// The oldest error reported takes precedence over the new one.310if (pic->error_code == VP8_ENC_OK) {311((WebPPicture*)pic)->error_code = error;312}313return 0;314}315316int WebPReportProgress(const WebPPicture* const pic,317int percent, int* const percent_store) {318if (percent_store != NULL && percent != *percent_store) {319*percent_store = percent;320if (pic->progress_hook && !pic->progress_hook(percent, pic)) {321// user abort requested322return WebPEncodingSetError(pic, VP8_ENC_ERROR_USER_ABORT);323}324}325return 1; // ok326}327//------------------------------------------------------------------------------328329int WebPEncode(const WebPConfig* config, WebPPicture* pic) {330int ok = 0;331if (pic == NULL) return 0;332333pic->error_code = VP8_ENC_OK; // all ok so far334if (config == NULL) { // bad params335return WebPEncodingSetError(pic, VP8_ENC_ERROR_NULL_PARAMETER);336}337if (!WebPValidateConfig(config)) {338return WebPEncodingSetError(pic, VP8_ENC_ERROR_INVALID_CONFIGURATION);339}340if (!WebPValidatePicture(pic)) return 0;341if (pic->width > WEBP_MAX_DIMENSION || pic->height > WEBP_MAX_DIMENSION) {342return WebPEncodingSetError(pic, VP8_ENC_ERROR_BAD_DIMENSION);343}344345if (pic->stats != NULL) memset(pic->stats, 0, sizeof(*pic->stats));346347if (!config->lossless) {348VP8Encoder* enc = NULL;349350if (pic->use_argb || pic->y == NULL || pic->u == NULL || pic->v == NULL) {351// Make sure we have YUVA samples.352if (config->use_sharp_yuv || (config->preprocessing & 4)) {353if (!WebPPictureSharpARGBToYUVA(pic)) {354return 0;355}356} else {357float dithering = 0.f;358if (config->preprocessing & 2) {359const float x = config->quality / 100.f;360const float x2 = x * x;361// slowly decreasing from max dithering at low quality (q->0)362// to 0.5 dithering amplitude at high quality (q->100)363dithering = 1.0f + (0.5f - 1.0f) * x2 * x2;364}365if (!WebPPictureARGBToYUVADithered(pic, WEBP_YUV420, dithering)) {366return 0;367}368}369}370371if (!config->exact) {372WebPCleanupTransparentArea(pic);373}374375enc = InitVP8Encoder(config, pic);376if (enc == NULL) return 0; // pic->error is already set.377// Note: each of the tasks below account for 20% in the progress report.378ok = VP8EncAnalyze(enc);379380// Analysis is done, proceed to actual coding.381ok = ok && VP8EncStartAlpha(enc); // possibly done in parallel382if (!enc->use_tokens_) {383ok = ok && VP8EncLoop(enc);384} else {385ok = ok && VP8EncTokenLoop(enc);386}387ok = ok && VP8EncFinishAlpha(enc);388389ok = ok && VP8EncWrite(enc);390StoreStats(enc);391if (!ok) {392VP8EncFreeBitWriters(enc);393}394ok &= DeleteVP8Encoder(enc); // must always be called, even if !ok395} else {396// Make sure we have ARGB samples.397if (pic->argb == NULL && !WebPPictureYUVAToARGB(pic)) {398return 0;399}400401if (!config->exact) {402WebPReplaceTransparentPixels(pic, 0x000000);403}404405ok = VP8LEncodeImage(config, pic); // Sets pic->error in case of problem.406}407408return ok;409}410411412