Path: blob/master/thirdparty/libwebp/src/dec/frame_dec.c
9912 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) {340const int idx = (dqm->uv_quant_ < 0) ? 0 : dqm->uv_quant_;341dqm->dither_ = (f * kQuantToDitherAmp[idx]) >> 3;342}343all_amp |= dqm->dither_;344}345if (all_amp != 0) {346VP8InitRandom(&dec->dithering_rg_, 1.0f);347dec->dither_ = 1;348}349}350// potentially allow alpha dithering351dec->alpha_dithering_ = options->alpha_dithering_strength;352if (dec->alpha_dithering_ > 100) {353dec->alpha_dithering_ = 100;354} else if (dec->alpha_dithering_ < 0) {355dec->alpha_dithering_ = 0;356}357}358}359360// Convert to range: [-2,2] for dither=50, [-4,4] for dither=100361static void Dither8x8(VP8Random* const rg, uint8_t* dst, int bps, int amp) {362uint8_t dither[64];363int i;364for (i = 0; i < 8 * 8; ++i) {365dither[i] = VP8RandomBits2(rg, VP8_DITHER_AMP_BITS + 1, amp);366}367VP8DitherCombine8x8(dither, dst, bps);368}369370static void DitherRow(VP8Decoder* const dec) {371int mb_x;372assert(dec->dither_);373for (mb_x = dec->tl_mb_x_; mb_x < dec->br_mb_x_; ++mb_x) {374const VP8ThreadContext* const ctx = &dec->thread_ctx_;375const VP8MBData* const data = ctx->mb_data_ + mb_x;376const int cache_id = ctx->id_;377const int uv_bps = dec->cache_uv_stride_;378if (data->dither_ >= MIN_DITHER_AMP) {379uint8_t* const u_dst = dec->cache_u_ + cache_id * 8 * uv_bps + mb_x * 8;380uint8_t* const v_dst = dec->cache_v_ + cache_id * 8 * uv_bps + mb_x * 8;381Dither8x8(&dec->dithering_rg_, u_dst, uv_bps, data->dither_);382Dither8x8(&dec->dithering_rg_, v_dst, uv_bps, data->dither_);383}384}385}386387//------------------------------------------------------------------------------388// This function is called after a row of macroblocks is finished decoding.389// It also takes into account the following restrictions:390// * In case of in-loop filtering, we must hold off sending some of the bottom391// pixels as they are yet unfiltered. They will be when the next macroblock392// row is decoded. Meanwhile, we must preserve them by rotating them in the393// cache area. This doesn't hold for the very bottom row of the uncropped394// picture of course.395// * we must clip the remaining pixels against the cropping area. The VP8Io396// struct must have the following fields set correctly before calling put():397398#define MACROBLOCK_VPOS(mb_y) ((mb_y) * 16) // vertical position of a MB399400// Finalize and transmit a complete row. Return false in case of user-abort.401static int FinishRow(void* arg1, void* arg2) {402VP8Decoder* const dec = (VP8Decoder*)arg1;403VP8Io* const io = (VP8Io*)arg2;404int ok = 1;405const VP8ThreadContext* const ctx = &dec->thread_ctx_;406const int cache_id = ctx->id_;407const int extra_y_rows = kFilterExtraRows[dec->filter_type_];408const int ysize = extra_y_rows * dec->cache_y_stride_;409const int uvsize = (extra_y_rows / 2) * dec->cache_uv_stride_;410const int y_offset = cache_id * 16 * dec->cache_y_stride_;411const int uv_offset = cache_id * 8 * dec->cache_uv_stride_;412uint8_t* const ydst = dec->cache_y_ - ysize + y_offset;413uint8_t* const udst = dec->cache_u_ - uvsize + uv_offset;414uint8_t* const vdst = dec->cache_v_ - uvsize + uv_offset;415const int mb_y = ctx->mb_y_;416const int is_first_row = (mb_y == 0);417const int is_last_row = (mb_y >= dec->br_mb_y_ - 1);418419if (dec->mt_method_ == 2) {420ReconstructRow(dec, ctx);421}422423if (ctx->filter_row_) {424FilterRow(dec);425}426427if (dec->dither_) {428DitherRow(dec);429}430431if (io->put != NULL) {432int y_start = MACROBLOCK_VPOS(mb_y);433int y_end = MACROBLOCK_VPOS(mb_y + 1);434if (!is_first_row) {435y_start -= extra_y_rows;436io->y = ydst;437io->u = udst;438io->v = vdst;439} else {440io->y = dec->cache_y_ + y_offset;441io->u = dec->cache_u_ + uv_offset;442io->v = dec->cache_v_ + uv_offset;443}444445if (!is_last_row) {446y_end -= extra_y_rows;447}448if (y_end > io->crop_bottom) {449y_end = io->crop_bottom; // make sure we don't overflow on last row.450}451// If dec->alpha_data_ is not NULL, we have some alpha plane present.452io->a = NULL;453if (dec->alpha_data_ != NULL && y_start < y_end) {454io->a = VP8DecompressAlphaRows(dec, io, y_start, y_end - y_start);455if (io->a == NULL) {456return VP8SetError(dec, VP8_STATUS_BITSTREAM_ERROR,457"Could not decode alpha data.");458}459}460if (y_start < io->crop_top) {461const int delta_y = io->crop_top - y_start;462y_start = io->crop_top;463assert(!(delta_y & 1));464io->y += dec->cache_y_stride_ * delta_y;465io->u += dec->cache_uv_stride_ * (delta_y >> 1);466io->v += dec->cache_uv_stride_ * (delta_y >> 1);467if (io->a != NULL) {468io->a += io->width * delta_y;469}470}471if (y_start < y_end) {472io->y += io->crop_left;473io->u += io->crop_left >> 1;474io->v += io->crop_left >> 1;475if (io->a != NULL) {476io->a += io->crop_left;477}478io->mb_y = y_start - io->crop_top;479io->mb_w = io->crop_right - io->crop_left;480io->mb_h = y_end - y_start;481ok = io->put(io);482}483}484// rotate top samples if needed485if (cache_id + 1 == dec->num_caches_) {486if (!is_last_row) {487memcpy(dec->cache_y_ - ysize, ydst + 16 * dec->cache_y_stride_, ysize);488memcpy(dec->cache_u_ - uvsize, udst + 8 * dec->cache_uv_stride_, uvsize);489memcpy(dec->cache_v_ - uvsize, vdst + 8 * dec->cache_uv_stride_, uvsize);490}491}492493return ok;494}495496#undef MACROBLOCK_VPOS497498//------------------------------------------------------------------------------499500int VP8ProcessRow(VP8Decoder* const dec, VP8Io* const io) {501int ok = 1;502VP8ThreadContext* const ctx = &dec->thread_ctx_;503const int filter_row =504(dec->filter_type_ > 0) &&505(dec->mb_y_ >= dec->tl_mb_y_) && (dec->mb_y_ <= dec->br_mb_y_);506if (dec->mt_method_ == 0) {507// ctx->id_ and ctx->f_info_ are already set508ctx->mb_y_ = dec->mb_y_;509ctx->filter_row_ = filter_row;510ReconstructRow(dec, ctx);511ok = FinishRow(dec, io);512} else {513WebPWorker* const worker = &dec->worker_;514// Finish previous job *before* updating context515ok &= WebPGetWorkerInterface()->Sync(worker);516assert(worker->status_ == OK);517if (ok) { // spawn a new deblocking/output job518ctx->io_ = *io;519ctx->id_ = dec->cache_id_;520ctx->mb_y_ = dec->mb_y_;521ctx->filter_row_ = filter_row;522if (dec->mt_method_ == 2) { // swap macroblock data523VP8MBData* const tmp = ctx->mb_data_;524ctx->mb_data_ = dec->mb_data_;525dec->mb_data_ = tmp;526} else {527// perform reconstruction directly in main thread528ReconstructRow(dec, ctx);529}530if (filter_row) { // swap filter info531VP8FInfo* const tmp = ctx->f_info_;532ctx->f_info_ = dec->f_info_;533dec->f_info_ = tmp;534}535// (reconstruct)+filter in parallel536WebPGetWorkerInterface()->Launch(worker);537if (++dec->cache_id_ == dec->num_caches_) {538dec->cache_id_ = 0;539}540}541}542return ok;543}544545//------------------------------------------------------------------------------546// Finish setting up the decoding parameter once user's setup() is called.547548VP8StatusCode VP8EnterCritical(VP8Decoder* const dec, VP8Io* const io) {549// Call setup() first. This may trigger additional decoding features on 'io'.550// Note: Afterward, we must call teardown() no matter what.551if (io->setup != NULL && !io->setup(io)) {552VP8SetError(dec, VP8_STATUS_USER_ABORT, "Frame setup failed");553return dec->status_;554}555556// Disable filtering per user request557if (io->bypass_filtering) {558dec->filter_type_ = 0;559}560561// Define the area where we can skip in-loop filtering, in case of cropping.562//563// 'Simple' filter reads two luma samples outside of the macroblock564// and filters one. It doesn't filter the chroma samples. Hence, we can565// avoid doing the in-loop filtering before crop_top/crop_left position.566// For the 'Complex' filter, 3 samples are read and up to 3 are filtered.567// Means: there's a dependency chain that goes all the way up to the568// top-left corner of the picture (MB #0). We must filter all the previous569// macroblocks.570{571const int extra_pixels = kFilterExtraRows[dec->filter_type_];572if (dec->filter_type_ == 2) {573// For complex filter, we need to preserve the dependency chain.574dec->tl_mb_x_ = 0;575dec->tl_mb_y_ = 0;576} else {577// For simple filter, we can filter only the cropped region.578// We include 'extra_pixels' on the other side of the boundary, since579// vertical or horizontal filtering of the previous macroblock can580// modify some abutting pixels.581dec->tl_mb_x_ = (io->crop_left - extra_pixels) >> 4;582dec->tl_mb_y_ = (io->crop_top - extra_pixels) >> 4;583if (dec->tl_mb_x_ < 0) dec->tl_mb_x_ = 0;584if (dec->tl_mb_y_ < 0) dec->tl_mb_y_ = 0;585}586// We need some 'extra' pixels on the right/bottom.587dec->br_mb_y_ = (io->crop_bottom + 15 + extra_pixels) >> 4;588dec->br_mb_x_ = (io->crop_right + 15 + extra_pixels) >> 4;589if (dec->br_mb_x_ > dec->mb_w_) {590dec->br_mb_x_ = dec->mb_w_;591}592if (dec->br_mb_y_ > dec->mb_h_) {593dec->br_mb_y_ = dec->mb_h_;594}595}596PrecomputeFilterStrengths(dec);597return VP8_STATUS_OK;598}599600int VP8ExitCritical(VP8Decoder* const dec, VP8Io* const io) {601int ok = 1;602if (dec->mt_method_ > 0) {603ok = WebPGetWorkerInterface()->Sync(&dec->worker_);604}605606if (io->teardown != NULL) {607io->teardown(io);608}609return ok;610}611612//------------------------------------------------------------------------------613// For multi-threaded decoding we need to use 3 rows of 16 pixels as delay line.614//615// Reason is: the deblocking filter cannot deblock the bottom horizontal edges616// immediately, and needs to wait for first few rows of the next macroblock to617// be decoded. Hence, deblocking is lagging behind by 4 or 8 pixels (depending618// on strength).619// With two threads, the vertical positions of the rows being decoded are:620// Decode: [ 0..15][16..31][32..47][48..63][64..79][...621// Deblock: [ 0..11][12..27][28..43][44..59][...622// If we use two threads and two caches of 16 pixels, the sequence would be:623// Decode: [ 0..15][16..31][ 0..15!!][16..31][ 0..15][...624// Deblock: [ 0..11][12..27!!][-4..11][12..27][...625// The problem occurs during row [12..15!!] that both the decoding and626// deblocking threads are writing simultaneously.627// With 3 cache lines, one get a safe write pattern:628// Decode: [ 0..15][16..31][32..47][ 0..15][16..31][32..47][0..629// Deblock: [ 0..11][12..27][28..43][-4..11][12..27][28...630// Note that multi-threaded output _without_ deblocking can make use of two631// cache lines of 16 pixels only, since there's no lagging behind. The decoding632// and output process have non-concurrent writing:633// Decode: [ 0..15][16..31][ 0..15][16..31][...634// io->put: [ 0..15][16..31][ 0..15][...635636#define MT_CACHE_LINES 3637#define ST_CACHE_LINES 1 // 1 cache row only for single-threaded case638639// Initialize multi/single-thread worker640static int InitThreadContext(VP8Decoder* const dec) {641dec->cache_id_ = 0;642if (dec->mt_method_ > 0) {643WebPWorker* const worker = &dec->worker_;644if (!WebPGetWorkerInterface()->Reset(worker)) {645return VP8SetError(dec, VP8_STATUS_OUT_OF_MEMORY,646"thread initialization failed.");647}648worker->data1 = dec;649worker->data2 = (void*)&dec->thread_ctx_.io_;650worker->hook = FinishRow;651dec->num_caches_ =652(dec->filter_type_ > 0) ? MT_CACHE_LINES : MT_CACHE_LINES - 1;653} else {654dec->num_caches_ = ST_CACHE_LINES;655}656return 1;657}658659int VP8GetThreadMethod(const WebPDecoderOptions* const options,660const WebPHeaderStructure* const headers,661int width, int height) {662if (options == NULL || options->use_threads == 0) {663return 0;664}665(void)headers;666(void)width;667(void)height;668assert(headers == NULL || !headers->is_lossless);669#if defined(WEBP_USE_THREAD)670if (width >= MIN_WIDTH_FOR_THREADS) return 2;671#endif672return 0;673}674675#undef MT_CACHE_LINES676#undef ST_CACHE_LINES677678//------------------------------------------------------------------------------679// Memory setup680681static int AllocateMemory(VP8Decoder* const dec) {682const int num_caches = dec->num_caches_;683const int mb_w = dec->mb_w_;684// Note: we use 'size_t' when there's no overflow risk, uint64_t otherwise.685const size_t intra_pred_mode_size = 4 * mb_w * sizeof(uint8_t);686const size_t top_size = sizeof(VP8TopSamples) * mb_w;687const size_t mb_info_size = (mb_w + 1) * sizeof(VP8MB);688const size_t f_info_size =689(dec->filter_type_ > 0) ?690mb_w * (dec->mt_method_ > 0 ? 2 : 1) * sizeof(VP8FInfo)691: 0;692const size_t yuv_size = YUV_SIZE * sizeof(*dec->yuv_b_);693const size_t mb_data_size =694(dec->mt_method_ == 2 ? 2 : 1) * mb_w * sizeof(*dec->mb_data_);695const size_t cache_height = (16 * num_caches696+ kFilterExtraRows[dec->filter_type_]) * 3 / 2;697const size_t cache_size = top_size * cache_height;698// alpha_size is the only one that scales as width x height.699const uint64_t alpha_size = (dec->alpha_data_ != NULL) ?700(uint64_t)dec->pic_hdr_.width_ * dec->pic_hdr_.height_ : 0ULL;701const uint64_t needed = (uint64_t)intra_pred_mode_size702+ top_size + mb_info_size + f_info_size703+ yuv_size + mb_data_size704+ cache_size + alpha_size + WEBP_ALIGN_CST;705uint8_t* mem;706707if (!CheckSizeOverflow(needed)) return 0; // check for overflow708if (needed > dec->mem_size_) {709WebPSafeFree(dec->mem_);710dec->mem_size_ = 0;711dec->mem_ = WebPSafeMalloc(needed, sizeof(uint8_t));712if (dec->mem_ == NULL) {713return VP8SetError(dec, VP8_STATUS_OUT_OF_MEMORY,714"no memory during frame initialization.");715}716// down-cast is ok, thanks to WebPSafeMalloc() above.717dec->mem_size_ = (size_t)needed;718}719720mem = (uint8_t*)dec->mem_;721dec->intra_t_ = mem;722mem += intra_pred_mode_size;723724dec->yuv_t_ = (VP8TopSamples*)mem;725mem += top_size;726727dec->mb_info_ = ((VP8MB*)mem) + 1;728mem += mb_info_size;729730dec->f_info_ = f_info_size ? (VP8FInfo*)mem : NULL;731mem += f_info_size;732dec->thread_ctx_.id_ = 0;733dec->thread_ctx_.f_info_ = dec->f_info_;734if (dec->filter_type_ > 0 && dec->mt_method_ > 0) {735// secondary cache line. The deblocking process need to make use of the736// filtering strength from previous macroblock row, while the new ones737// are being decoded in parallel. We'll just swap the pointers.738dec->thread_ctx_.f_info_ += mb_w;739}740741mem = (uint8_t*)WEBP_ALIGN(mem);742assert((yuv_size & WEBP_ALIGN_CST) == 0);743dec->yuv_b_ = mem;744mem += yuv_size;745746dec->mb_data_ = (VP8MBData*)mem;747dec->thread_ctx_.mb_data_ = (VP8MBData*)mem;748if (dec->mt_method_ == 2) {749dec->thread_ctx_.mb_data_ += mb_w;750}751mem += mb_data_size;752753dec->cache_y_stride_ = 16 * mb_w;754dec->cache_uv_stride_ = 8 * mb_w;755{756const int extra_rows = kFilterExtraRows[dec->filter_type_];757const int extra_y = extra_rows * dec->cache_y_stride_;758const int extra_uv = (extra_rows / 2) * dec->cache_uv_stride_;759dec->cache_y_ = mem + extra_y;760dec->cache_u_ = dec->cache_y_761+ 16 * num_caches * dec->cache_y_stride_ + extra_uv;762dec->cache_v_ = dec->cache_u_763+ 8 * num_caches * dec->cache_uv_stride_ + extra_uv;764dec->cache_id_ = 0;765}766mem += cache_size;767768// alpha plane769dec->alpha_plane_ = alpha_size ? mem : NULL;770mem += alpha_size;771assert(mem <= (uint8_t*)dec->mem_ + dec->mem_size_);772773// note: left/top-info is initialized once for all.774memset(dec->mb_info_ - 1, 0, mb_info_size);775VP8InitScanline(dec); // initialize left too.776777// initialize top778memset(dec->intra_t_, B_DC_PRED, intra_pred_mode_size);779780return 1;781}782783static void InitIo(VP8Decoder* const dec, VP8Io* io) {784// prepare 'io'785io->mb_y = 0;786io->y = dec->cache_y_;787io->u = dec->cache_u_;788io->v = dec->cache_v_;789io->y_stride = dec->cache_y_stride_;790io->uv_stride = dec->cache_uv_stride_;791io->a = NULL;792}793794int VP8InitFrame(VP8Decoder* const dec, VP8Io* const io) {795if (!InitThreadContext(dec)) return 0; // call first. Sets dec->num_caches_.796if (!AllocateMemory(dec)) return 0;797InitIo(dec, io);798VP8DspInit(); // Init critical function pointers and look-up tables.799return 1;800}801802//------------------------------------------------------------------------------803804805