Path: blob/master/3rdparty/libwebp/src/dec/frame_dec.c
16358 views
// Copyright 2010 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// Frame-reconstruction function. Memory allocation.10//11// Author: Skal ([email protected])1213#include <stdlib.h>14#include "src/dec/vp8i_dec.h"15#include "src/utils/utils.h"1617//------------------------------------------------------------------------------18// Main reconstruction function.1920static const uint16_t kScan[16] = {210 + 0 * BPS, 4 + 0 * BPS, 8 + 0 * BPS, 12 + 0 * BPS,220 + 4 * BPS, 4 + 4 * BPS, 8 + 4 * BPS, 12 + 4 * BPS,230 + 8 * BPS, 4 + 8 * BPS, 8 + 8 * BPS, 12 + 8 * BPS,240 + 12 * BPS, 4 + 12 * BPS, 8 + 12 * BPS, 12 + 12 * BPS25};2627static int CheckMode(int mb_x, int mb_y, int mode) {28if (mode == B_DC_PRED) {29if (mb_x == 0) {30return (mb_y == 0) ? B_DC_PRED_NOTOPLEFT : B_DC_PRED_NOLEFT;31} else {32return (mb_y == 0) ? B_DC_PRED_NOTOP : B_DC_PRED;33}34}35return mode;36}3738static void Copy32b(uint8_t* const dst, const uint8_t* const src) {39memcpy(dst, src, 4);40}4142static WEBP_INLINE void DoTransform(uint32_t bits, const int16_t* const src,43uint8_t* const dst) {44switch (bits >> 30) {45case 3:46VP8Transform(src, dst, 0);47break;48case 2:49VP8TransformAC3(src, dst);50break;51case 1:52VP8TransformDC(src, dst);53break;54default:55break;56}57}5859static void DoUVTransform(uint32_t bits, const int16_t* const src,60uint8_t* const dst) {61if (bits & 0xff) { // any non-zero coeff at all?62if (bits & 0xaa) { // any non-zero AC coefficient?63VP8TransformUV(src, dst); // note we don't use the AC3 variant for U/V64} else {65VP8TransformDCUV(src, dst);66}67}68}6970static void ReconstructRow(const VP8Decoder* const dec,71const VP8ThreadContext* ctx) {72int j;73int mb_x;74const int mb_y = ctx->mb_y_;75const int cache_id = ctx->id_;76uint8_t* const y_dst = dec->yuv_b_ + Y_OFF;77uint8_t* const u_dst = dec->yuv_b_ + U_OFF;78uint8_t* const v_dst = dec->yuv_b_ + V_OFF;7980// Initialize left-most block.81for (j = 0; j < 16; ++j) {82y_dst[j * BPS - 1] = 129;83}84for (j = 0; j < 8; ++j) {85u_dst[j * BPS - 1] = 129;86v_dst[j * BPS - 1] = 129;87}8889// Init top-left sample on left column too.90if (mb_y > 0) {91y_dst[-1 - BPS] = u_dst[-1 - BPS] = v_dst[-1 - BPS] = 129;92} else {93// we only need to do this init once at block (0,0).94// Afterward, it remains valid for the whole topmost row.95memset(y_dst - BPS - 1, 127, 16 + 4 + 1);96memset(u_dst - BPS - 1, 127, 8 + 1);97memset(v_dst - BPS - 1, 127, 8 + 1);98}99100// Reconstruct one row.101for (mb_x = 0; mb_x < dec->mb_w_; ++mb_x) {102const VP8MBData* const block = ctx->mb_data_ + mb_x;103104// Rotate in the left samples from previously decoded block. We move four105// pixels at a time for alignment reason, and because of in-loop filter.106if (mb_x > 0) {107for (j = -1; j < 16; ++j) {108Copy32b(&y_dst[j * BPS - 4], &y_dst[j * BPS + 12]);109}110for (j = -1; j < 8; ++j) {111Copy32b(&u_dst[j * BPS - 4], &u_dst[j * BPS + 4]);112Copy32b(&v_dst[j * BPS - 4], &v_dst[j * BPS + 4]);113}114}115{116// bring top samples into the cache117VP8TopSamples* const top_yuv = dec->yuv_t_ + mb_x;118const int16_t* const coeffs = block->coeffs_;119uint32_t bits = block->non_zero_y_;120int n;121122if (mb_y > 0) {123memcpy(y_dst - BPS, top_yuv[0].y, 16);124memcpy(u_dst - BPS, top_yuv[0].u, 8);125memcpy(v_dst - BPS, top_yuv[0].v, 8);126}127128// predict and add residuals129if (block->is_i4x4_) { // 4x4130uint32_t* const top_right = (uint32_t*)(y_dst - BPS + 16);131132if (mb_y > 0) {133if (mb_x >= dec->mb_w_ - 1) { // on rightmost border134memset(top_right, top_yuv[0].y[15], sizeof(*top_right));135} else {136memcpy(top_right, top_yuv[1].y, sizeof(*top_right));137}138}139// replicate the top-right pixels below140top_right[BPS] = top_right[2 * BPS] = top_right[3 * BPS] = top_right[0];141142// predict and add residuals for all 4x4 blocks in turn.143for (n = 0; n < 16; ++n, bits <<= 2) {144uint8_t* const dst = y_dst + kScan[n];145VP8PredLuma4[block->imodes_[n]](dst);146DoTransform(bits, coeffs + n * 16, dst);147}148} else { // 16x16149const int pred_func = CheckMode(mb_x, mb_y, block->imodes_[0]);150VP8PredLuma16[pred_func](y_dst);151if (bits != 0) {152for (n = 0; n < 16; ++n, bits <<= 2) {153DoTransform(bits, coeffs + n * 16, y_dst + kScan[n]);154}155}156}157{158// Chroma159const uint32_t bits_uv = block->non_zero_uv_;160const int pred_func = CheckMode(mb_x, mb_y, block->uvmode_);161VP8PredChroma8[pred_func](u_dst);162VP8PredChroma8[pred_func](v_dst);163DoUVTransform(bits_uv >> 0, coeffs + 16 * 16, u_dst);164DoUVTransform(bits_uv >> 8, coeffs + 20 * 16, v_dst);165}166167// stash away top samples for next block168if (mb_y < dec->mb_h_ - 1) {169memcpy(top_yuv[0].y, y_dst + 15 * BPS, 16);170memcpy(top_yuv[0].u, u_dst + 7 * BPS, 8);171memcpy(top_yuv[0].v, v_dst + 7 * BPS, 8);172}173}174// Transfer reconstructed samples from yuv_b_ cache to final destination.175{176const int y_offset = cache_id * 16 * dec->cache_y_stride_;177const int uv_offset = cache_id * 8 * dec->cache_uv_stride_;178uint8_t* const y_out = dec->cache_y_ + mb_x * 16 + y_offset;179uint8_t* const u_out = dec->cache_u_ + mb_x * 8 + uv_offset;180uint8_t* const v_out = dec->cache_v_ + mb_x * 8 + uv_offset;181for (j = 0; j < 16; ++j) {182memcpy(y_out + j * dec->cache_y_stride_, y_dst + j * BPS, 16);183}184for (j = 0; j < 8; ++j) {185memcpy(u_out + j * dec->cache_uv_stride_, u_dst + j * BPS, 8);186memcpy(v_out + j * dec->cache_uv_stride_, v_dst + j * BPS, 8);187}188}189}190}191192//------------------------------------------------------------------------------193// Filtering194195// kFilterExtraRows[] = How many extra lines are needed on the MB boundary196// for caching, given a filtering level.197// Simple filter: up to 2 luma samples are read and 1 is written.198// Complex filter: up to 4 luma samples are read and 3 are written. Same for199// U/V, so it's 8 samples total (because of the 2x upsampling).200static const uint8_t kFilterExtraRows[3] = { 0, 2, 8 };201202static void DoFilter(const VP8Decoder* const dec, int mb_x, int mb_y) {203const VP8ThreadContext* const ctx = &dec->thread_ctx_;204const int cache_id = ctx->id_;205const int y_bps = dec->cache_y_stride_;206const VP8FInfo* const f_info = ctx->f_info_ + mb_x;207uint8_t* const y_dst = dec->cache_y_ + cache_id * 16 * y_bps + mb_x * 16;208const int ilevel = f_info->f_ilevel_;209const int limit = f_info->f_limit_;210if (limit == 0) {211return;212}213assert(limit >= 3);214if (dec->filter_type_ == 1) { // simple215if (mb_x > 0) {216VP8SimpleHFilter16(y_dst, y_bps, limit + 4);217}218if (f_info->f_inner_) {219VP8SimpleHFilter16i(y_dst, y_bps, limit);220}221if (mb_y > 0) {222VP8SimpleVFilter16(y_dst, y_bps, limit + 4);223}224if (f_info->f_inner_) {225VP8SimpleVFilter16i(y_dst, y_bps, limit);226}227} else { // complex228const int uv_bps = dec->cache_uv_stride_;229uint8_t* const u_dst = dec->cache_u_ + cache_id * 8 * uv_bps + mb_x * 8;230uint8_t* const v_dst = dec->cache_v_ + cache_id * 8 * uv_bps + mb_x * 8;231const int hev_thresh = f_info->hev_thresh_;232if (mb_x > 0) {233VP8HFilter16(y_dst, y_bps, limit + 4, ilevel, hev_thresh);234VP8HFilter8(u_dst, v_dst, uv_bps, limit + 4, ilevel, hev_thresh);235}236if (f_info->f_inner_) {237VP8HFilter16i(y_dst, y_bps, limit, ilevel, hev_thresh);238VP8HFilter8i(u_dst, v_dst, uv_bps, limit, ilevel, hev_thresh);239}240if (mb_y > 0) {241VP8VFilter16(y_dst, y_bps, limit + 4, ilevel, hev_thresh);242VP8VFilter8(u_dst, v_dst, uv_bps, limit + 4, ilevel, hev_thresh);243}244if (f_info->f_inner_) {245VP8VFilter16i(y_dst, y_bps, limit, ilevel, hev_thresh);246VP8VFilter8i(u_dst, v_dst, uv_bps, limit, ilevel, hev_thresh);247}248}249}250251// Filter the decoded macroblock row (if needed)252static void FilterRow(const VP8Decoder* const dec) {253int mb_x;254const int mb_y = dec->thread_ctx_.mb_y_;255assert(dec->thread_ctx_.filter_row_);256for (mb_x = dec->tl_mb_x_; mb_x < dec->br_mb_x_; ++mb_x) {257DoFilter(dec, mb_x, mb_y);258}259}260261//------------------------------------------------------------------------------262// Precompute the filtering strength for each segment and each i4x4/i16x16 mode.263264static void PrecomputeFilterStrengths(VP8Decoder* const dec) {265if (dec->filter_type_ > 0) {266int s;267const VP8FilterHeader* const hdr = &dec->filter_hdr_;268for (s = 0; s < NUM_MB_SEGMENTS; ++s) {269int i4x4;270// First, compute the initial level271int base_level;272if (dec->segment_hdr_.use_segment_) {273base_level = dec->segment_hdr_.filter_strength_[s];274if (!dec->segment_hdr_.absolute_delta_) {275base_level += hdr->level_;276}277} else {278base_level = hdr->level_;279}280for (i4x4 = 0; i4x4 <= 1; ++i4x4) {281VP8FInfo* const info = &dec->fstrengths_[s][i4x4];282int level = base_level;283if (hdr->use_lf_delta_) {284level += hdr->ref_lf_delta_[0];285if (i4x4) {286level += hdr->mode_lf_delta_[0];287}288}289level = (level < 0) ? 0 : (level > 63) ? 63 : level;290if (level > 0) {291int ilevel = level;292if (hdr->sharpness_ > 0) {293if (hdr->sharpness_ > 4) {294ilevel >>= 2;295} else {296ilevel >>= 1;297}298if (ilevel > 9 - hdr->sharpness_) {299ilevel = 9 - hdr->sharpness_;300}301}302if (ilevel < 1) ilevel = 1;303info->f_ilevel_ = ilevel;304info->f_limit_ = 2 * level + ilevel;305info->hev_thresh_ = (level >= 40) ? 2 : (level >= 15) ? 1 : 0;306} else {307info->f_limit_ = 0; // no filtering308}309info->f_inner_ = i4x4;310}311}312}313}314315//------------------------------------------------------------------------------316// Dithering317318// minimal amp that will provide a non-zero dithering effect319#define MIN_DITHER_AMP 4320321#define DITHER_AMP_TAB_SIZE 12322static const uint8_t kQuantToDitherAmp[DITHER_AMP_TAB_SIZE] = {323// roughly, it's dqm->uv_mat_[1]3248, 7, 6, 4, 4, 2, 2, 2, 1, 1, 1, 1325};326327void VP8InitDithering(const WebPDecoderOptions* const options,328VP8Decoder* const dec) {329assert(dec != NULL);330if (options != NULL) {331const int d = options->dithering_strength;332const int max_amp = (1 << VP8_RANDOM_DITHER_FIX) - 1;333const int f = (d < 0) ? 0 : (d > 100) ? max_amp : (d * max_amp / 100);334if (f > 0) {335int s;336int all_amp = 0;337for (s = 0; s < NUM_MB_SEGMENTS; ++s) {338VP8QuantMatrix* const dqm = &dec->dqm_[s];339if (dqm->uv_quant_ < DITHER_AMP_TAB_SIZE) {340// TODO(skal): should we specially dither more for uv_quant_ < 0?341const int idx = (dqm->uv_quant_ < 0) ? 0 : dqm->uv_quant_;342dqm->dither_ = (f * kQuantToDitherAmp[idx]) >> 3;343}344all_amp |= dqm->dither_;345}346if (all_amp != 0) {347VP8InitRandom(&dec->dithering_rg_, 1.0f);348dec->dither_ = 1;349}350}351// potentially allow alpha dithering352dec->alpha_dithering_ = options->alpha_dithering_strength;353if (dec->alpha_dithering_ > 100) {354dec->alpha_dithering_ = 100;355} else if (dec->alpha_dithering_ < 0) {356dec->alpha_dithering_ = 0;357}358}359}360361// Convert to range: [-2,2] for dither=50, [-4,4] for dither=100362static void Dither8x8(VP8Random* const rg, uint8_t* dst, int bps, int amp) {363uint8_t dither[64];364int i;365for (i = 0; i < 8 * 8; ++i) {366dither[i] = VP8RandomBits2(rg, VP8_DITHER_AMP_BITS + 1, amp);367}368VP8DitherCombine8x8(dither, dst, bps);369}370371static void DitherRow(VP8Decoder* const dec) {372int mb_x;373assert(dec->dither_);374for (mb_x = dec->tl_mb_x_; mb_x < dec->br_mb_x_; ++mb_x) {375const VP8ThreadContext* const ctx = &dec->thread_ctx_;376const VP8MBData* const data = ctx->mb_data_ + mb_x;377const int cache_id = ctx->id_;378const int uv_bps = dec->cache_uv_stride_;379if (data->dither_ >= MIN_DITHER_AMP) {380uint8_t* const u_dst = dec->cache_u_ + cache_id * 8 * uv_bps + mb_x * 8;381uint8_t* const v_dst = dec->cache_v_ + cache_id * 8 * uv_bps + mb_x * 8;382Dither8x8(&dec->dithering_rg_, u_dst, uv_bps, data->dither_);383Dither8x8(&dec->dithering_rg_, v_dst, uv_bps, data->dither_);384}385}386}387388//------------------------------------------------------------------------------389// This function is called after a row of macroblocks is finished decoding.390// It also takes into account the following restrictions:391// * In case of in-loop filtering, we must hold off sending some of the bottom392// pixels as they are yet unfiltered. They will be when the next macroblock393// row is decoded. Meanwhile, we must preserve them by rotating them in the394// cache area. This doesn't hold for the very bottom row of the uncropped395// picture of course.396// * we must clip the remaining pixels against the cropping area. The VP8Io397// struct must have the following fields set correctly before calling put():398399#define MACROBLOCK_VPOS(mb_y) ((mb_y) * 16) // vertical position of a MB400401// Finalize and transmit a complete row. Return false in case of user-abort.402static int FinishRow(void* arg1, void* arg2) {403VP8Decoder* const dec = (VP8Decoder*)arg1;404VP8Io* const io = (VP8Io*)arg2;405int ok = 1;406const VP8ThreadContext* const ctx = &dec->thread_ctx_;407const int cache_id = ctx->id_;408const int extra_y_rows = kFilterExtraRows[dec->filter_type_];409const int ysize = extra_y_rows * dec->cache_y_stride_;410const int uvsize = (extra_y_rows / 2) * dec->cache_uv_stride_;411const int y_offset = cache_id * 16 * dec->cache_y_stride_;412const int uv_offset = cache_id * 8 * dec->cache_uv_stride_;413uint8_t* const ydst = dec->cache_y_ - ysize + y_offset;414uint8_t* const udst = dec->cache_u_ - uvsize + uv_offset;415uint8_t* const vdst = dec->cache_v_ - uvsize + uv_offset;416const int mb_y = ctx->mb_y_;417const int is_first_row = (mb_y == 0);418const int is_last_row = (mb_y >= dec->br_mb_y_ - 1);419420if (dec->mt_method_ == 2) {421ReconstructRow(dec, ctx);422}423424if (ctx->filter_row_) {425FilterRow(dec);426}427428if (dec->dither_) {429DitherRow(dec);430}431432if (io->put != NULL) {433int y_start = MACROBLOCK_VPOS(mb_y);434int y_end = MACROBLOCK_VPOS(mb_y + 1);435if (!is_first_row) {436y_start -= extra_y_rows;437io->y = ydst;438io->u = udst;439io->v = vdst;440} else {441io->y = dec->cache_y_ + y_offset;442io->u = dec->cache_u_ + uv_offset;443io->v = dec->cache_v_ + uv_offset;444}445446if (!is_last_row) {447y_end -= extra_y_rows;448}449if (y_end > io->crop_bottom) {450y_end = io->crop_bottom; // make sure we don't overflow on last row.451}452// If dec->alpha_data_ is not NULL, we have some alpha plane present.453io->a = NULL;454if (dec->alpha_data_ != NULL && y_start < y_end) {455io->a = VP8DecompressAlphaRows(dec, io, y_start, y_end - y_start);456if (io->a == NULL) {457return VP8SetError(dec, VP8_STATUS_BITSTREAM_ERROR,458"Could not decode alpha data.");459}460}461if (y_start < io->crop_top) {462const int delta_y = io->crop_top - y_start;463y_start = io->crop_top;464assert(!(delta_y & 1));465io->y += dec->cache_y_stride_ * delta_y;466io->u += dec->cache_uv_stride_ * (delta_y >> 1);467io->v += dec->cache_uv_stride_ * (delta_y >> 1);468if (io->a != NULL) {469io->a += io->width * delta_y;470}471}472if (y_start < y_end) {473io->y += io->crop_left;474io->u += io->crop_left >> 1;475io->v += io->crop_left >> 1;476if (io->a != NULL) {477io->a += io->crop_left;478}479io->mb_y = y_start - io->crop_top;480io->mb_w = io->crop_right - io->crop_left;481io->mb_h = y_end - y_start;482ok = io->put(io);483}484}485// rotate top samples if needed486if (cache_id + 1 == dec->num_caches_) {487if (!is_last_row) {488memcpy(dec->cache_y_ - ysize, ydst + 16 * dec->cache_y_stride_, ysize);489memcpy(dec->cache_u_ - uvsize, udst + 8 * dec->cache_uv_stride_, uvsize);490memcpy(dec->cache_v_ - uvsize, vdst + 8 * dec->cache_uv_stride_, uvsize);491}492}493494return ok;495}496497#undef MACROBLOCK_VPOS498499//------------------------------------------------------------------------------500501int VP8ProcessRow(VP8Decoder* const dec, VP8Io* const io) {502int ok = 1;503VP8ThreadContext* const ctx = &dec->thread_ctx_;504const int filter_row =505(dec->filter_type_ > 0) &&506(dec->mb_y_ >= dec->tl_mb_y_) && (dec->mb_y_ <= dec->br_mb_y_);507if (dec->mt_method_ == 0) {508// ctx->id_ and ctx->f_info_ are already set509ctx->mb_y_ = dec->mb_y_;510ctx->filter_row_ = filter_row;511ReconstructRow(dec, ctx);512ok = FinishRow(dec, io);513} else {514WebPWorker* const worker = &dec->worker_;515// Finish previous job *before* updating context516ok &= WebPGetWorkerInterface()->Sync(worker);517assert(worker->status_ == OK);518if (ok) { // spawn a new deblocking/output job519ctx->io_ = *io;520ctx->id_ = dec->cache_id_;521ctx->mb_y_ = dec->mb_y_;522ctx->filter_row_ = filter_row;523if (dec->mt_method_ == 2) { // swap macroblock data524VP8MBData* const tmp = ctx->mb_data_;525ctx->mb_data_ = dec->mb_data_;526dec->mb_data_ = tmp;527} else {528// perform reconstruction directly in main thread529ReconstructRow(dec, ctx);530}531if (filter_row) { // swap filter info532VP8FInfo* const tmp = ctx->f_info_;533ctx->f_info_ = dec->f_info_;534dec->f_info_ = tmp;535}536// (reconstruct)+filter in parallel537WebPGetWorkerInterface()->Launch(worker);538if (++dec->cache_id_ == dec->num_caches_) {539dec->cache_id_ = 0;540}541}542}543return ok;544}545546//------------------------------------------------------------------------------547// Finish setting up the decoding parameter once user's setup() is called.548549VP8StatusCode VP8EnterCritical(VP8Decoder* const dec, VP8Io* const io) {550// Call setup() first. This may trigger additional decoding features on 'io'.551// Note: Afterward, we must call teardown() no matter what.552if (io->setup != NULL && !io->setup(io)) {553VP8SetError(dec, VP8_STATUS_USER_ABORT, "Frame setup failed");554return dec->status_;555}556557// Disable filtering per user request558if (io->bypass_filtering) {559dec->filter_type_ = 0;560}561562// Define the area where we can skip in-loop filtering, in case of cropping.563//564// 'Simple' filter reads two luma samples outside of the macroblock565// and filters one. It doesn't filter the chroma samples. Hence, we can566// avoid doing the in-loop filtering before crop_top/crop_left position.567// For the 'Complex' filter, 3 samples are read and up to 3 are filtered.568// Means: there's a dependency chain that goes all the way up to the569// top-left corner of the picture (MB #0). We must filter all the previous570// macroblocks.571{572const int extra_pixels = kFilterExtraRows[dec->filter_type_];573if (dec->filter_type_ == 2) {574// For complex filter, we need to preserve the dependency chain.575dec->tl_mb_x_ = 0;576dec->tl_mb_y_ = 0;577} else {578// For simple filter, we can filter only the cropped region.579// We include 'extra_pixels' on the other side of the boundary, since580// vertical or horizontal filtering of the previous macroblock can581// modify some abutting pixels.582dec->tl_mb_x_ = (io->crop_left - extra_pixels) >> 4;583dec->tl_mb_y_ = (io->crop_top - extra_pixels) >> 4;584if (dec->tl_mb_x_ < 0) dec->tl_mb_x_ = 0;585if (dec->tl_mb_y_ < 0) dec->tl_mb_y_ = 0;586}587// We need some 'extra' pixels on the right/bottom.588dec->br_mb_y_ = (io->crop_bottom + 15 + extra_pixels) >> 4;589dec->br_mb_x_ = (io->crop_right + 15 + extra_pixels) >> 4;590if (dec->br_mb_x_ > dec->mb_w_) {591dec->br_mb_x_ = dec->mb_w_;592}593if (dec->br_mb_y_ > dec->mb_h_) {594dec->br_mb_y_ = dec->mb_h_;595}596}597PrecomputeFilterStrengths(dec);598return VP8_STATUS_OK;599}600601int VP8ExitCritical(VP8Decoder* const dec, VP8Io* const io) {602int ok = 1;603if (dec->mt_method_ > 0) {604ok = WebPGetWorkerInterface()->Sync(&dec->worker_);605}606607if (io->teardown != NULL) {608io->teardown(io);609}610return ok;611}612613//------------------------------------------------------------------------------614// For multi-threaded decoding we need to use 3 rows of 16 pixels as delay line.615//616// Reason is: the deblocking filter cannot deblock the bottom horizontal edges617// immediately, and needs to wait for first few rows of the next macroblock to618// be decoded. Hence, deblocking is lagging behind by 4 or 8 pixels (depending619// on strength).620// With two threads, the vertical positions of the rows being decoded are:621// Decode: [ 0..15][16..31][32..47][48..63][64..79][...622// Deblock: [ 0..11][12..27][28..43][44..59][...623// If we use two threads and two caches of 16 pixels, the sequence would be:624// Decode: [ 0..15][16..31][ 0..15!!][16..31][ 0..15][...625// Deblock: [ 0..11][12..27!!][-4..11][12..27][...626// The problem occurs during row [12..15!!] that both the decoding and627// deblocking threads are writing simultaneously.628// With 3 cache lines, one get a safe write pattern:629// Decode: [ 0..15][16..31][32..47][ 0..15][16..31][32..47][0..630// Deblock: [ 0..11][12..27][28..43][-4..11][12..27][28...631// Note that multi-threaded output _without_ deblocking can make use of two632// cache lines of 16 pixels only, since there's no lagging behind. The decoding633// and output process have non-concurrent writing:634// Decode: [ 0..15][16..31][ 0..15][16..31][...635// io->put: [ 0..15][16..31][ 0..15][...636637#define MT_CACHE_LINES 3638#define ST_CACHE_LINES 1 // 1 cache row only for single-threaded case639640// Initialize multi/single-thread worker641static int InitThreadContext(VP8Decoder* const dec) {642dec->cache_id_ = 0;643if (dec->mt_method_ > 0) {644WebPWorker* const worker = &dec->worker_;645if (!WebPGetWorkerInterface()->Reset(worker)) {646return VP8SetError(dec, VP8_STATUS_OUT_OF_MEMORY,647"thread initialization failed.");648}649worker->data1 = dec;650worker->data2 = (void*)&dec->thread_ctx_.io_;651worker->hook = FinishRow;652dec->num_caches_ =653(dec->filter_type_ > 0) ? MT_CACHE_LINES : MT_CACHE_LINES - 1;654} else {655dec->num_caches_ = ST_CACHE_LINES;656}657return 1;658}659660int VP8GetThreadMethod(const WebPDecoderOptions* const options,661const WebPHeaderStructure* const headers,662int width, int height) {663if (options == NULL || options->use_threads == 0) {664return 0;665}666(void)headers;667(void)width;668(void)height;669assert(headers == NULL || !headers->is_lossless);670#if defined(WEBP_USE_THREAD)671if (width < MIN_WIDTH_FOR_THREADS) return 0;672// TODO(skal): tune the heuristic further673#if 0674if (height < 2 * width) return 2;675#endif676return 2;677#else // !WEBP_USE_THREAD678return 0;679#endif680}681682#undef MT_CACHE_LINES683#undef ST_CACHE_LINES684685//------------------------------------------------------------------------------686// Memory setup687688static int AllocateMemory(VP8Decoder* const dec) {689const int num_caches = dec->num_caches_;690const int mb_w = dec->mb_w_;691// Note: we use 'size_t' when there's no overflow risk, uint64_t otherwise.692const size_t intra_pred_mode_size = 4 * mb_w * sizeof(uint8_t);693const size_t top_size = sizeof(VP8TopSamples) * mb_w;694const size_t mb_info_size = (mb_w + 1) * sizeof(VP8MB);695const size_t f_info_size =696(dec->filter_type_ > 0) ?697mb_w * (dec->mt_method_ > 0 ? 2 : 1) * sizeof(VP8FInfo)698: 0;699const size_t yuv_size = YUV_SIZE * sizeof(*dec->yuv_b_);700const size_t mb_data_size =701(dec->mt_method_ == 2 ? 2 : 1) * mb_w * sizeof(*dec->mb_data_);702const size_t cache_height = (16 * num_caches703+ kFilterExtraRows[dec->filter_type_]) * 3 / 2;704const size_t cache_size = top_size * cache_height;705// alpha_size is the only one that scales as width x height.706const uint64_t alpha_size = (dec->alpha_data_ != NULL) ?707(uint64_t)dec->pic_hdr_.width_ * dec->pic_hdr_.height_ : 0ULL;708const uint64_t needed = (uint64_t)intra_pred_mode_size709+ top_size + mb_info_size + f_info_size710+ yuv_size + mb_data_size711+ cache_size + alpha_size + WEBP_ALIGN_CST;712uint8_t* mem;713714if (needed != (size_t)needed) return 0; // check for overflow715if (needed > dec->mem_size_) {716WebPSafeFree(dec->mem_);717dec->mem_size_ = 0;718dec->mem_ = WebPSafeMalloc(needed, sizeof(uint8_t));719if (dec->mem_ == NULL) {720return VP8SetError(dec, VP8_STATUS_OUT_OF_MEMORY,721"no memory during frame initialization.");722}723// down-cast is ok, thanks to WebPSafeMalloc() above.724dec->mem_size_ = (size_t)needed;725}726727mem = (uint8_t*)dec->mem_;728dec->intra_t_ = mem;729mem += intra_pred_mode_size;730731dec->yuv_t_ = (VP8TopSamples*)mem;732mem += top_size;733734dec->mb_info_ = ((VP8MB*)mem) + 1;735mem += mb_info_size;736737dec->f_info_ = f_info_size ? (VP8FInfo*)mem : NULL;738mem += f_info_size;739dec->thread_ctx_.id_ = 0;740dec->thread_ctx_.f_info_ = dec->f_info_;741if (dec->mt_method_ > 0) {742// secondary cache line. The deblocking process need to make use of the743// filtering strength from previous macroblock row, while the new ones744// are being decoded in parallel. We'll just swap the pointers.745dec->thread_ctx_.f_info_ += mb_w;746}747748mem = (uint8_t*)WEBP_ALIGN(mem);749assert((yuv_size & WEBP_ALIGN_CST) == 0);750dec->yuv_b_ = mem;751mem += yuv_size;752753dec->mb_data_ = (VP8MBData*)mem;754dec->thread_ctx_.mb_data_ = (VP8MBData*)mem;755if (dec->mt_method_ == 2) {756dec->thread_ctx_.mb_data_ += mb_w;757}758mem += mb_data_size;759760dec->cache_y_stride_ = 16 * mb_w;761dec->cache_uv_stride_ = 8 * mb_w;762{763const int extra_rows = kFilterExtraRows[dec->filter_type_];764const int extra_y = extra_rows * dec->cache_y_stride_;765const int extra_uv = (extra_rows / 2) * dec->cache_uv_stride_;766dec->cache_y_ = mem + extra_y;767dec->cache_u_ = dec->cache_y_768+ 16 * num_caches * dec->cache_y_stride_ + extra_uv;769dec->cache_v_ = dec->cache_u_770+ 8 * num_caches * dec->cache_uv_stride_ + extra_uv;771dec->cache_id_ = 0;772}773mem += cache_size;774775// alpha plane776dec->alpha_plane_ = alpha_size ? mem : NULL;777mem += alpha_size;778assert(mem <= (uint8_t*)dec->mem_ + dec->mem_size_);779780// note: left/top-info is initialized once for all.781memset(dec->mb_info_ - 1, 0, mb_info_size);782VP8InitScanline(dec); // initialize left too.783784// initialize top785memset(dec->intra_t_, B_DC_PRED, intra_pred_mode_size);786787return 1;788}789790static void InitIo(VP8Decoder* const dec, VP8Io* io) {791// prepare 'io'792io->mb_y = 0;793io->y = dec->cache_y_;794io->u = dec->cache_u_;795io->v = dec->cache_v_;796io->y_stride = dec->cache_y_stride_;797io->uv_stride = dec->cache_uv_stride_;798io->a = NULL;799}800801int VP8InitFrame(VP8Decoder* const dec, VP8Io* const io) {802if (!InitThreadContext(dec)) return 0; // call first. Sets dec->num_caches_.803if (!AllocateMemory(dec)) return 0;804InitIo(dec, io);805VP8DspInit(); // Init critical function pointers and look-up tables.806return 1;807}808809//------------------------------------------------------------------------------810811812