Coverage Report

Created: 2025-07-23 06:39

/src/libwebp/src/dec/frame_dec.c
Line
Count
Source (jump to first uncovered line)
1
// Copyright 2010 Google Inc. All Rights Reserved.
2
//
3
// Use of this source code is governed by a BSD-style license
4
// that can be found in the COPYING file in the root of the source
5
// tree. An additional intellectual property rights grant can be found
6
// in the file PATENTS. All contributing project authors may
7
// be found in the AUTHORS file in the root of the source tree.
8
// -----------------------------------------------------------------------------
9
//
10
// Frame-reconstruction function. Memory allocation.
11
//
12
// Author: Skal (pascal.massimino@gmail.com)
13
14
#include <assert.h>
15
#include <stdlib.h>
16
#include <string.h>
17
18
#include "src/dec/common_dec.h"
19
#include "src/dec/vp8_dec.h"
20
#include "src/dec/vp8i_dec.h"
21
#include "src/dec/webpi_dec.h"
22
#include "src/dsp/dsp.h"
23
#include "src/utils/random_utils.h"
24
#include "src/utils/thread_utils.h"
25
#include "src/utils/utils.h"
26
#include "src/webp/decode.h"
27
#include "src/webp/types.h"
28
29
//------------------------------------------------------------------------------
30
// Main reconstruction function.
31
32
static const uint16_t kScan[16] = {
33
  0 +  0 * BPS,  4 +  0 * BPS, 8 +  0 * BPS, 12 +  0 * BPS,
34
  0 +  4 * BPS,  4 +  4 * BPS, 8 +  4 * BPS, 12 +  4 * BPS,
35
  0 +  8 * BPS,  4 +  8 * BPS, 8 +  8 * BPS, 12 +  8 * BPS,
36
  0 + 12 * BPS,  4 + 12 * BPS, 8 + 12 * BPS, 12 + 12 * BPS
37
};
38
39
1.25M
static int CheckMode(int mb_x, int mb_y, int mode) {
40
1.25M
  if (mode == B_DC_PRED) {
41
734k
    if (mb_x == 0) {
42
235k
      return (mb_y == 0) ? B_DC_PRED_NOTOPLEFT : B_DC_PRED_NOLEFT;
43
498k
    } else {
44
498k
      return (mb_y == 0) ? B_DC_PRED_NOTOP : B_DC_PRED;
45
498k
    }
46
734k
  }
47
516k
  return mode;
48
1.25M
}
49
50
18.4M
static void Copy32b(uint8_t* const dst, const uint8_t* const src) {
51
18.4M
  memcpy(dst, src, 4);
52
18.4M
}
53
54
static WEBP_INLINE void DoTransform(uint32_t bits, const int16_t* const src,
55
8.31M
                                    uint8_t* const dst) {
56
8.31M
  switch (bits >> 30) {
57
1.64M
    case 3:
58
1.64M
      VP8Transform(src, dst, 0);
59
1.64M
      break;
60
606k
    case 2:
61
606k
      VP8TransformAC3(src, dst);
62
606k
      break;
63
1.84M
    case 1:
64
1.84M
      VP8TransformDC(src, dst);
65
1.84M
      break;
66
4.21M
    default:
67
4.21M
      break;
68
8.31M
  }
69
8.31M
}
70
71
static void DoUVTransform(uint32_t bits, const int16_t* const src,
72
1.57M
                          uint8_t* const dst) {
73
1.57M
  if (bits & 0xff) {    // any non-zero coeff at all?
74
559k
    if (bits & 0xaa) {  // any non-zero AC coefficient?
75
357k
      VP8TransformUV(src, dst);   // note we don't use the AC3 variant for U/V
76
357k
    } else {
77
202k
      VP8TransformDCUV(src, dst);
78
202k
    }
79
559k
  }
80
1.57M
}
81
82
static void ReconstructRow(const VP8Decoder* const dec,
83
264k
                           const VP8ThreadContext* ctx) {
84
264k
  int j;
85
264k
  int mb_x;
86
264k
  const int mb_y = ctx->mb_y;
87
264k
  const int cache_id = ctx->id;
88
264k
  uint8_t* const y_dst = dec->yuv_b + Y_OFF;
89
264k
  uint8_t* const u_dst = dec->yuv_b + U_OFF;
90
264k
  uint8_t* const v_dst = dec->yuv_b + V_OFF;
91
92
  // Initialize left-most block.
93
4.48M
  for (j = 0; j < 16; ++j) {
94
4.22M
    y_dst[j * BPS - 1] = 129;
95
4.22M
  }
96
2.37M
  for (j = 0; j < 8; ++j) {
97
2.11M
    u_dst[j * BPS - 1] = 129;
98
2.11M
    v_dst[j * BPS - 1] = 129;
99
2.11M
  }
100
101
  // Init top-left sample on left column too.
102
264k
  if (mb_y > 0) {
103
245k
    y_dst[-1 - BPS] = u_dst[-1 - BPS] = v_dst[-1 - BPS] = 129;
104
245k
  } else {
105
    // we only need to do this init once at block (0,0).
106
    // Afterward, it remains valid for the whole topmost row.
107
18.2k
    memset(y_dst - BPS - 1, 127, 16 + 4 + 1);
108
18.2k
    memset(u_dst - BPS - 1, 127, 8 + 1);
109
18.2k
    memset(v_dst - BPS - 1, 127, 8 + 1);
110
18.2k
  }
111
112
  // Reconstruct one row.
113
1.05M
  for (mb_x = 0; mb_x < dec->mb_w; ++mb_x) {
114
789k
    const VP8MBData* const block = ctx->mb_data + mb_x;
115
116
    // Rotate in the left samples from previously decoded block. We move four
117
    // pixels at a time for alignment reason, and because of in-loop filter.
118
789k
    if (mb_x > 0) {
119
9.46M
      for (j = -1; j < 16; ++j) {
120
8.93M
        Copy32b(&y_dst[j * BPS - 4], &y_dst[j * BPS + 12]);
121
8.93M
      }
122
5.25M
      for (j = -1; j < 8; ++j) {
123
4.73M
        Copy32b(&u_dst[j * BPS - 4], &u_dst[j * BPS + 4]);
124
4.73M
        Copy32b(&v_dst[j * BPS - 4], &v_dst[j * BPS + 4]);
125
4.73M
      }
126
525k
    }
127
789k
    {
128
      // bring top samples into the cache
129
789k
      VP8TopSamples* const top_yuv = dec->yuv_t + mb_x;
130
789k
      const int16_t* const coeffs = block->coeffs;
131
789k
      uint32_t bits = block->non_zero_y;
132
789k
      int n;
133
134
789k
      if (mb_y > 0) {
135
506k
        memcpy(y_dst - BPS, top_yuv[0].y, 16);
136
506k
        memcpy(u_dst - BPS, top_yuv[0].u, 8);
137
506k
        memcpy(v_dst - BPS, top_yuv[0].v, 8);
138
506k
      }
139
140
      // predict and add residuals
141
789k
      if (block->is_i4x4) {   // 4x4
142
328k
        uint32_t* const top_right = (uint32_t*)(y_dst - BPS + 16);
143
144
328k
        if (mb_y > 0) {
145
219k
          if (mb_x >= dec->mb_w - 1) {    // on rightmost border
146
104k
            memset(top_right, top_yuv[0].y[15], sizeof(*top_right));
147
114k
          } else {
148
114k
            memcpy(top_right, top_yuv[1].y, sizeof(*top_right));
149
114k
          }
150
219k
        }
151
        // replicate the top-right pixels below
152
328k
        top_right[BPS] = top_right[2 * BPS] = top_right[3 * BPS] = top_right[0];
153
154
        // predict and add residuals for all 4x4 blocks in turn.
155
5.58M
        for (n = 0; n < 16; ++n, bits <<= 2) {
156
5.25M
          uint8_t* const dst = y_dst + kScan[n];
157
5.25M
          VP8PredLuma4[block->imodes[n]](dst);
158
5.25M
          DoTransform(bits, coeffs + n * 16, dst);
159
5.25M
        }
160
461k
      } else {    // 16x16
161
461k
        const int pred_func = CheckMode(mb_x, mb_y, block->imodes[0]);
162
461k
        VP8PredLuma16[pred_func](y_dst);
163
461k
        if (bits != 0) {
164
3.25M
          for (n = 0; n < 16; ++n, bits <<= 2) {
165
3.06M
            DoTransform(bits, coeffs + n * 16, y_dst + kScan[n]);
166
3.06M
          }
167
191k
        }
168
461k
      }
169
789k
      {
170
        // Chroma
171
789k
        const uint32_t bits_uv = block->non_zero_uv;
172
789k
        const int pred_func = CheckMode(mb_x, mb_y, block->uvmode);
173
789k
        VP8PredChroma8[pred_func](u_dst);
174
789k
        VP8PredChroma8[pred_func](v_dst);
175
789k
        DoUVTransform(bits_uv >> 0, coeffs + 16 * 16, u_dst);
176
789k
        DoUVTransform(bits_uv >> 8, coeffs + 20 * 16, v_dst);
177
789k
      }
178
179
      // stash away top samples for next block
180
789k
      if (mb_y < dec->mb_h - 1) {
181
553k
        memcpy(top_yuv[0].y, y_dst + 15 * BPS, 16);
182
553k
        memcpy(top_yuv[0].u, u_dst +  7 * BPS,  8);
183
553k
        memcpy(top_yuv[0].v, v_dst +  7 * BPS,  8);
184
553k
      }
185
789k
    }
186
    // Transfer reconstructed samples from yuv_b cache to final destination.
187
789k
    {
188
789k
      const int y_offset = cache_id * 16 * dec->cache_y_stride;
189
789k
      const int uv_offset = cache_id * 8 * dec->cache_uv_stride;
190
789k
      uint8_t* const y_out = dec->cache_y + mb_x * 16 + y_offset;
191
789k
      uint8_t* const u_out = dec->cache_u + mb_x * 8 + uv_offset;
192
789k
      uint8_t* const v_out = dec->cache_v + mb_x * 8 + uv_offset;
193
13.4M
      for (j = 0; j < 16; ++j) {
194
12.6M
        memcpy(y_out + j * dec->cache_y_stride, y_dst + j * BPS, 16);
195
12.6M
      }
196
7.10M
      for (j = 0; j < 8; ++j) {
197
6.31M
        memcpy(u_out + j * dec->cache_uv_stride, u_dst + j * BPS, 8);
198
6.31M
        memcpy(v_out + j * dec->cache_uv_stride, v_dst + j * BPS, 8);
199
6.31M
      }
200
789k
    }
201
789k
  }
202
264k
}
203
204
//------------------------------------------------------------------------------
205
// Filtering
206
207
// kFilterExtraRows[] = How many extra lines are needed on the MB boundary
208
// for caching, given a filtering level.
209
// Simple filter:  up to 2 luma samples are read and 1 is written.
210
// Complex filter: up to 4 luma samples are read and 3 are written. Same for
211
//                 U/V, so it's 8 samples total (because of the 2x upsampling).
212
static const uint8_t kFilterExtraRows[3] = { 0, 2, 8 };
213
214
584k
static void DoFilter(const VP8Decoder* const dec, int mb_x, int mb_y) {
215
584k
  const VP8ThreadContext* const ctx = &dec->thread_ctx;
216
584k
  const int cache_id = ctx->id;
217
584k
  const int y_bps = dec->cache_y_stride;
218
584k
  const VP8FInfo* const f_info = ctx->f_info + mb_x;
219
584k
  uint8_t* const y_dst = dec->cache_y + cache_id * 16 * y_bps + mb_x * 16;
220
584k
  const int ilevel = f_info->f_ilevel;
221
584k
  const int limit = f_info->f_limit;
222
584k
  if (limit == 0) {
223
200k
    return;
224
200k
  }
225
383k
  assert(limit >= 3);
226
383k
  if (dec->filter_type == 1) {   // simple
227
249k
    if (mb_x > 0) {
228
164k
      VP8SimpleHFilter16(y_dst, y_bps, limit + 4);
229
164k
    }
230
249k
    if (f_info->f_inner) {
231
185k
      VP8SimpleHFilter16i(y_dst, y_bps, limit);
232
185k
    }
233
249k
    if (mb_y > 0) {
234
153k
      VP8SimpleVFilter16(y_dst, y_bps, limit + 4);
235
153k
    }
236
249k
    if (f_info->f_inner) {
237
185k
      VP8SimpleVFilter16i(y_dst, y_bps, limit);
238
185k
    }
239
249k
  } else {    // complex
240
133k
    const int uv_bps = dec->cache_uv_stride;
241
133k
    uint8_t* const u_dst = dec->cache_u + cache_id * 8 * uv_bps + mb_x * 8;
242
133k
    uint8_t* const v_dst = dec->cache_v + cache_id * 8 * uv_bps + mb_x * 8;
243
133k
    const int hev_thresh = f_info->hev_thresh;
244
133k
    if (mb_x > 0) {
245
76.2k
      VP8HFilter16(y_dst, y_bps, limit + 4, ilevel, hev_thresh);
246
76.2k
      VP8HFilter8(u_dst, v_dst, uv_bps, limit + 4, ilevel, hev_thresh);
247
76.2k
    }
248
133k
    if (f_info->f_inner) {
249
84.8k
      VP8HFilter16i(y_dst, y_bps, limit, ilevel, hev_thresh);
250
84.8k
      VP8HFilter8i(u_dst, v_dst, uv_bps, limit, ilevel, hev_thresh);
251
84.8k
    }
252
133k
    if (mb_y > 0) {
253
81.1k
      VP8VFilter16(y_dst, y_bps, limit + 4, ilevel, hev_thresh);
254
81.1k
      VP8VFilter8(u_dst, v_dst, uv_bps, limit + 4, ilevel, hev_thresh);
255
81.1k
    }
256
133k
    if (f_info->f_inner) {
257
84.8k
      VP8VFilter16i(y_dst, y_bps, limit, ilevel, hev_thresh);
258
84.8k
      VP8VFilter8i(u_dst, v_dst, uv_bps, limit, ilevel, hev_thresh);
259
84.8k
    }
260
133k
  }
261
383k
}
262
263
// Filter the decoded macroblock row (if needed)
264
188k
static void FilterRow(const VP8Decoder* const dec) {
265
188k
  int mb_x;
266
188k
  const int mb_y = dec->thread_ctx.mb_y;
267
188k
  assert(dec->thread_ctx.filter_row);
268
772k
  for (mb_x = dec->tl_mb_x; mb_x < dec->br_mb_x; ++mb_x) {
269
584k
    DoFilter(dec, mb_x, mb_y);
270
584k
  }
271
188k
}
272
273
//------------------------------------------------------------------------------
274
// Precompute the filtering strength for each segment and each i4x4/i16x16 mode.
275
276
22.6k
static void PrecomputeFilterStrengths(VP8Decoder* const dec) {
277
22.6k
  if (dec->filter_type > 0) {
278
16.3k
    int s;
279
16.3k
    const VP8FilterHeader* const hdr = &dec->filter_hdr;
280
81.6k
    for (s = 0; s < NUM_MB_SEGMENTS; ++s) {
281
65.2k
      int i4x4;
282
      // First, compute the initial level
283
65.2k
      int base_level;
284
65.2k
      if (dec->segment_hdr.use_segment) {
285
22.7k
        base_level = dec->segment_hdr.filter_strength[s];
286
22.7k
        if (!dec->segment_hdr.absolute_delta) {
287
3.56k
          base_level += hdr->level;
288
3.56k
        }
289
42.5k
      } else {
290
42.5k
        base_level = hdr->level;
291
42.5k
      }
292
195k
      for (i4x4 = 0; i4x4 <= 1; ++i4x4) {
293
130k
        VP8FInfo* const info = &dec->fstrengths[s][i4x4];
294
130k
        int level = base_level;
295
130k
        if (hdr->use_lf_delta) {
296
22.8k
          level += hdr->ref_lf_delta[0];
297
22.8k
          if (i4x4) {
298
11.4k
            level += hdr->mode_lf_delta[0];
299
11.4k
          }
300
22.8k
        }
301
130k
        level = (level < 0) ? 0 : (level > 63) ? 63 : level;
302
130k
        if (level > 0) {
303
105k
          int ilevel = level;
304
105k
          if (hdr->sharpness > 0) {
305
80.2k
            if (hdr->sharpness > 4) {
306
26.3k
              ilevel >>= 2;
307
53.9k
            } else {
308
53.9k
              ilevel >>= 1;
309
53.9k
            }
310
80.2k
            if (ilevel > 9 - hdr->sharpness) {
311
53.0k
              ilevel = 9 - hdr->sharpness;
312
53.0k
            }
313
80.2k
          }
314
105k
          if (ilevel < 1) ilevel = 1;
315
105k
          info->f_ilevel = ilevel;
316
105k
          info->f_limit = 2 * level + ilevel;
317
105k
          info->hev_thresh = (level >= 40) ? 2 : (level >= 15) ? 1 : 0;
318
105k
        } else {
319
24.6k
          info->f_limit = 0;  // no filtering
320
24.6k
        }
321
130k
        info->f_inner = i4x4;
322
130k
      }
323
65.2k
    }
324
16.3k
  }
325
22.6k
}
326
327
//------------------------------------------------------------------------------
328
// Dithering
329
330
// minimal amp that will provide a non-zero dithering effect
331
36.7k
#define MIN_DITHER_AMP 4
332
333
12.2k
#define DITHER_AMP_TAB_SIZE 12
334
static const uint8_t kQuantToDitherAmp[DITHER_AMP_TAB_SIZE] = {
335
  // roughly, it's dqm->uv_mat[1]
336
  8, 7, 6, 4, 4, 2, 2, 2, 1, 1, 1, 1
337
};
338
339
void VP8InitDithering(const WebPDecoderOptions* const options,
340
22.7k
                      VP8Decoder* const dec) {
341
22.7k
  assert(dec != NULL);
342
22.7k
  if (options != NULL) {
343
15.6k
    const int d = options->dithering_strength;
344
15.6k
    const int max_amp = (1 << VP8_RANDOM_DITHER_FIX) - 1;
345
15.6k
    const int f = (d < 0) ? 0 : (d > 100) ? max_amp : (d * max_amp / 100);
346
15.6k
    if (f > 0) {
347
3.06k
      int s;
348
3.06k
      int all_amp = 0;
349
15.3k
      for (s = 0; s < NUM_MB_SEGMENTS; ++s) {
350
12.2k
        VP8QuantMatrix* const dqm = &dec->dqm[s];
351
12.2k
        if (dqm->uv_quant < DITHER_AMP_TAB_SIZE) {
352
6.24k
          const int idx = (dqm->uv_quant < 0) ? 0 : dqm->uv_quant;
353
6.24k
          dqm->dither = (f * kQuantToDitherAmp[idx]) >> 3;
354
6.24k
        }
355
12.2k
        all_amp |= dqm->dither;
356
12.2k
      }
357
3.06k
      if (all_amp != 0) {
358
1.62k
        VP8InitRandom(&dec->dithering_rg, 1.0f);
359
1.62k
        dec->dither = 1;
360
1.62k
      }
361
3.06k
    }
362
    // potentially allow alpha dithering
363
15.6k
    dec->alpha_dithering = options->alpha_dithering_strength;
364
15.6k
    if (dec->alpha_dithering > 100) {
365
153
      dec->alpha_dithering = 100;
366
15.4k
    } else if (dec->alpha_dithering < 0) {
367
225
      dec->alpha_dithering = 0;
368
225
    }
369
15.6k
  }
370
22.7k
}
371
372
// Convert to range: [-2,2] for dither=50, [-4,4] for dither=100
373
22.0k
static void Dither8x8(VP8Random* const rg, uint8_t* dst, int bps, int amp) {
374
22.0k
  uint8_t dither[64];
375
22.0k
  int i;
376
1.43M
  for (i = 0; i < 8 * 8; ++i) {
377
1.41M
    dither[i] = VP8RandomBits2(rg, VP8_DITHER_AMP_BITS + 1, amp);
378
1.41M
  }
379
22.0k
  VP8DitherCombine8x8(dither, dst, bps);
380
22.0k
}
381
382
21.2k
static void DitherRow(VP8Decoder* const dec) {
383
21.2k
  int mb_x;
384
21.2k
  assert(dec->dither);
385
57.9k
  for (mb_x = dec->tl_mb_x; mb_x < dec->br_mb_x; ++mb_x) {
386
36.7k
    const VP8ThreadContext* const ctx = &dec->thread_ctx;
387
36.7k
    const VP8MBData* const data = ctx->mb_data + mb_x;
388
36.7k
    const int cache_id = ctx->id;
389
36.7k
    const int uv_bps = dec->cache_uv_stride;
390
36.7k
    if (data->dither >= MIN_DITHER_AMP) {
391
11.0k
      uint8_t* const u_dst = dec->cache_u + cache_id * 8 * uv_bps + mb_x * 8;
392
11.0k
      uint8_t* const v_dst = dec->cache_v + cache_id * 8 * uv_bps + mb_x * 8;
393
11.0k
      Dither8x8(&dec->dithering_rg, u_dst, uv_bps, data->dither);
394
11.0k
      Dither8x8(&dec->dithering_rg, v_dst, uv_bps, data->dither);
395
11.0k
    }
396
36.7k
  }
397
21.2k
}
398
399
//------------------------------------------------------------------------------
400
// This function is called after a row of macroblocks is finished decoding.
401
// It also takes into account the following restrictions:
402
//  * In case of in-loop filtering, we must hold off sending some of the bottom
403
//    pixels as they are yet unfiltered. They will be when the next macroblock
404
//    row is decoded. Meanwhile, we must preserve them by rotating them in the
405
//    cache area. This doesn't hold for the very bottom row of the uncropped
406
//    picture of course.
407
//  * we must clip the remaining pixels against the cropping area. The VP8Io
408
//    struct must have the following fields set correctly before calling put():
409
410
528k
#define MACROBLOCK_VPOS(mb_y)  ((mb_y) * 16)    // vertical position of a MB
411
412
// Finalize and transmit a complete row. Return false in case of user-abort.
413
264k
static int FinishRow(void* arg1, void* arg2) {
414
264k
  VP8Decoder* const dec = (VP8Decoder*)arg1;
415
264k
  VP8Io* const io = (VP8Io*)arg2;
416
264k
  int ok = 1;
417
264k
  const VP8ThreadContext* const ctx = &dec->thread_ctx;
418
264k
  const int cache_id = ctx->id;
419
264k
  const int extra_y_rows = kFilterExtraRows[dec->filter_type];
420
264k
  const int ysize = extra_y_rows * dec->cache_y_stride;
421
264k
  const int uvsize = (extra_y_rows / 2) * dec->cache_uv_stride;
422
264k
  const int y_offset = cache_id * 16 * dec->cache_y_stride;
423
264k
  const int uv_offset = cache_id * 8 * dec->cache_uv_stride;
424
264k
  uint8_t* const ydst = dec->cache_y - ysize + y_offset;
425
264k
  uint8_t* const udst = dec->cache_u - uvsize + uv_offset;
426
264k
  uint8_t* const vdst = dec->cache_v - uvsize + uv_offset;
427
264k
  const int mb_y = ctx->mb_y;
428
264k
  const int is_first_row = (mb_y == 0);
429
264k
  const int is_last_row = (mb_y >= dec->br_mb_y - 1);
430
431
264k
  if (dec->mt_method == 2) {
432
462
    ReconstructRow(dec, ctx);
433
462
  }
434
435
264k
  if (ctx->filter_row) {
436
188k
    FilterRow(dec);
437
188k
  }
438
439
264k
  if (dec->dither) {
440
21.2k
    DitherRow(dec);
441
21.2k
  }
442
443
264k
  if (io->put != NULL) {
444
264k
    int y_start = MACROBLOCK_VPOS(mb_y);
445
264k
    int y_end = MACROBLOCK_VPOS(mb_y + 1);
446
264k
    if (!is_first_row) {
447
245k
      y_start -= extra_y_rows;
448
245k
      io->y = ydst;
449
245k
      io->u = udst;
450
245k
      io->v = vdst;
451
245k
    } else {
452
18.2k
      io->y = dec->cache_y + y_offset;
453
18.2k
      io->u = dec->cache_u + uv_offset;
454
18.2k
      io->v = dec->cache_v + uv_offset;
455
18.2k
    }
456
457
264k
    if (!is_last_row) {
458
254k
      y_end -= extra_y_rows;
459
254k
    }
460
264k
    if (y_end > io->crop_bottom) {
461
8.35k
      y_end = io->crop_bottom;    // make sure we don't overflow on last row.
462
8.35k
    }
463
    // If dec->alpha_data is not NULL, we have some alpha plane present.
464
264k
    io->a = NULL;
465
264k
    if (dec->alpha_data != NULL && y_start < y_end) {
466
43.8k
      io->a = VP8DecompressAlphaRows(dec, io, y_start, y_end - y_start);
467
43.8k
      if (io->a == NULL) {
468
0
        return VP8SetError(dec, VP8_STATUS_BITSTREAM_ERROR,
469
0
                           "Could not decode alpha data.");
470
0
      }
471
43.8k
    }
472
264k
    if (y_start < io->crop_top) {
473
9.93k
      const int delta_y = io->crop_top - y_start;
474
9.93k
      y_start = io->crop_top;
475
9.93k
      assert(!(delta_y & 1));
476
9.93k
      io->y += dec->cache_y_stride * delta_y;
477
9.93k
      io->u += dec->cache_uv_stride * (delta_y >> 1);
478
9.93k
      io->v += dec->cache_uv_stride * (delta_y >> 1);
479
9.93k
      if (io->a != NULL) {
480
0
        io->a += io->width * delta_y;
481
0
      }
482
9.93k
    }
483
264k
    if (y_start < y_end) {
484
255k
      io->y += io->crop_left;
485
255k
      io->u += io->crop_left >> 1;
486
255k
      io->v += io->crop_left >> 1;
487
255k
      if (io->a != NULL) {
488
43.8k
        io->a += io->crop_left;
489
43.8k
      }
490
255k
      io->mb_y = y_start - io->crop_top;
491
255k
      io->mb_w = io->crop_right - io->crop_left;
492
255k
      io->mb_h = y_end - y_start;
493
255k
      ok = io->put(io);
494
255k
    }
495
264k
  }
496
  // rotate top samples if needed
497
264k
  if (cache_id + 1 == dec->num_caches) {
498
263k
    if (!is_last_row) {
499
253k
      memcpy(dec->cache_y - ysize, ydst + 16 * dec->cache_y_stride, ysize);
500
253k
      memcpy(dec->cache_u - uvsize, udst + 8 * dec->cache_uv_stride, uvsize);
501
253k
      memcpy(dec->cache_v - uvsize, vdst + 8 * dec->cache_uv_stride, uvsize);
502
253k
    }
503
263k
  }
504
505
264k
  return ok;
506
264k
}
507
508
#undef MACROBLOCK_VPOS
509
510
//------------------------------------------------------------------------------
511
512
264k
int VP8ProcessRow(VP8Decoder* const dec, VP8Io* const io) {
513
264k
  int ok = 1;
514
264k
  VP8ThreadContext* const ctx = &dec->thread_ctx;
515
264k
  const int filter_row =
516
264k
      (dec->filter_type > 0) &&
517
264k
      (dec->mb_y >= dec->tl_mb_y) && (dec->mb_y <= dec->br_mb_y);
518
264k
  if (dec->mt_method == 0) {
519
    // ctx->id and ctx->f_info are already set
520
263k
    ctx->mb_y = dec->mb_y;
521
263k
    ctx->filter_row = filter_row;
522
263k
    ReconstructRow(dec, ctx);
523
263k
    ok = FinishRow(dec, io);
524
263k
  } else {
525
462
    WebPWorker* const worker = &dec->worker;
526
    // Finish previous job *before* updating context
527
462
    ok &= WebPGetWorkerInterface()->Sync(worker);
528
462
    assert(worker->status == OK);
529
462
    if (ok) {   // spawn a new deblocking/output job
530
462
      ctx->io = *io;
531
462
      ctx->id = dec->cache_id;
532
462
      ctx->mb_y = dec->mb_y;
533
462
      ctx->filter_row = filter_row;
534
462
      if (dec->mt_method == 2) {  // swap macroblock data
535
462
        VP8MBData* const tmp = ctx->mb_data;
536
462
        ctx->mb_data = dec->mb_data;
537
462
        dec->mb_data = tmp;
538
462
      } else {
539
        // perform reconstruction directly in main thread
540
0
        ReconstructRow(dec, ctx);
541
0
      }
542
462
      if (filter_row) {            // swap filter info
543
218
        VP8FInfo* const tmp = ctx->f_info;
544
218
        ctx->f_info = dec->f_info;
545
218
        dec->f_info = tmp;
546
218
      }
547
      // (reconstruct)+filter in parallel
548
462
      WebPGetWorkerInterface()->Launch(worker);
549
462
      if (++dec->cache_id == dec->num_caches) {
550
123
        dec->cache_id = 0;
551
123
      }
552
462
    }
553
462
  }
554
264k
  return ok;
555
264k
}
556
557
//------------------------------------------------------------------------------
558
// Finish setting up the decoding parameter once user's setup() is called.
559
560
22.6k
VP8StatusCode VP8EnterCritical(VP8Decoder* const dec, VP8Io* const io) {
561
  // Call setup() first. This may trigger additional decoding features on 'io'.
562
  // Note: Afterward, we must call teardown() no matter what.
563
22.6k
  if (io->setup != NULL && !io->setup(io)) {
564
0
    VP8SetError(dec, VP8_STATUS_USER_ABORT, "Frame setup failed");
565
0
    return dec->status;
566
0
  }
567
568
  // Disable filtering per user request
569
22.6k
  if (io->bypass_filtering) {
570
2.89k
    dec->filter_type = 0;
571
2.89k
  }
572
573
  // Define the area where we can skip in-loop filtering, in case of cropping.
574
  //
575
  // 'Simple' filter reads two luma samples outside of the macroblock
576
  // and filters one. It doesn't filter the chroma samples. Hence, we can
577
  // avoid doing the in-loop filtering before crop_top/crop_left position.
578
  // For the 'Complex' filter, 3 samples are read and up to 3 are filtered.
579
  // Means: there's a dependency chain that goes all the way up to the
580
  // top-left corner of the picture (MB #0). We must filter all the previous
581
  // macroblocks.
582
22.6k
  {
583
22.6k
    const int extra_pixels = kFilterExtraRows[dec->filter_type];
584
22.6k
    if (dec->filter_type == 2) {
585
      // For complex filter, we need to preserve the dependency chain.
586
8.06k
      dec->tl_mb_x = 0;
587
8.06k
      dec->tl_mb_y = 0;
588
14.5k
    } else {
589
      // For simple filter, we can filter only the cropped region.
590
      // We include 'extra_pixels' on the other side of the boundary, since
591
      // vertical or horizontal filtering of the previous macroblock can
592
      // modify some abutting pixels.
593
14.5k
      dec->tl_mb_x = (io->crop_left - extra_pixels) >> 4;
594
14.5k
      dec->tl_mb_y = (io->crop_top - extra_pixels) >> 4;
595
14.5k
      if (dec->tl_mb_x < 0) dec->tl_mb_x = 0;
596
14.5k
      if (dec->tl_mb_y < 0) dec->tl_mb_y = 0;
597
14.5k
    }
598
    // We need some 'extra' pixels on the right/bottom.
599
22.6k
    dec->br_mb_y = (io->crop_bottom + 15 + extra_pixels) >> 4;
600
22.6k
    dec->br_mb_x = (io->crop_right + 15 + extra_pixels) >> 4;
601
22.6k
    if (dec->br_mb_x > dec->mb_w) {
602
4.32k
      dec->br_mb_x = dec->mb_w;
603
4.32k
    }
604
22.6k
    if (dec->br_mb_y > dec->mb_h) {
605
5.12k
      dec->br_mb_y = dec->mb_h;
606
5.12k
    }
607
22.6k
  }
608
22.6k
  PrecomputeFilterStrengths(dec);
609
22.6k
  return VP8_STATUS_OK;
610
22.6k
}
611
612
22.6k
int VP8ExitCritical(VP8Decoder* const dec, VP8Io* const io) {
613
22.6k
  int ok = 1;
614
22.6k
  if (dec->mt_method > 0) {
615
440
    ok = WebPGetWorkerInterface()->Sync(&dec->worker);
616
440
  }
617
618
22.6k
  if (io->teardown != NULL) {
619
22.6k
    io->teardown(io);
620
22.6k
  }
621
22.6k
  return ok;
622
22.6k
}
623
624
//------------------------------------------------------------------------------
625
// For multi-threaded decoding we need to use 3 rows of 16 pixels as delay line.
626
//
627
// Reason is: the deblocking filter cannot deblock the bottom horizontal edges
628
// immediately, and needs to wait for first few rows of the next macroblock to
629
// be decoded. Hence, deblocking is lagging behind by 4 or 8 pixels (depending
630
// on strength).
631
// With two threads, the vertical positions of the rows being decoded are:
632
// Decode:  [ 0..15][16..31][32..47][48..63][64..79][...
633
// Deblock:         [ 0..11][12..27][28..43][44..59][...
634
// If we use two threads and two caches of 16 pixels, the sequence would be:
635
// Decode:  [ 0..15][16..31][ 0..15!!][16..31][ 0..15][...
636
// Deblock:         [ 0..11][12..27!!][-4..11][12..27][...
637
// The problem occurs during row [12..15!!] that both the decoding and
638
// deblocking threads are writing simultaneously.
639
// With 3 cache lines, one get a safe write pattern:
640
// Decode:  [ 0..15][16..31][32..47][ 0..15][16..31][32..47][0..
641
// Deblock:         [ 0..11][12..27][28..43][-4..11][12..27][28...
642
// Note that multi-threaded output _without_ deblocking can make use of two
643
// cache lines of 16 pixels only, since there's no lagging behind. The decoding
644
// and output process have non-concurrent writing:
645
// Decode:  [ 0..15][16..31][ 0..15][16..31][...
646
// io->put:         [ 0..15][16..31][ 0..15][...
647
648
440
#define MT_CACHE_LINES 3
649
22.2k
#define ST_CACHE_LINES 1   // 1 cache row only for single-threaded case
650
651
// Initialize multi/single-thread worker
652
22.6k
static int InitThreadContext(VP8Decoder* const dec) {
653
22.6k
  dec->cache_id = 0;
654
22.6k
  if (dec->mt_method > 0) {
655
440
    WebPWorker* const worker = &dec->worker;
656
440
    if (!WebPGetWorkerInterface()->Reset(worker)) {
657
0
      return VP8SetError(dec, VP8_STATUS_OUT_OF_MEMORY,
658
0
                         "thread initialization failed.");
659
0
    }
660
440
    worker->data1 = dec;
661
440
    worker->data2 = (void*)&dec->thread_ctx.io;
662
440
    worker->hook = FinishRow;
663
440
    dec->num_caches =
664
440
        (dec->filter_type > 0) ? MT_CACHE_LINES : MT_CACHE_LINES - 1;
665
22.2k
  } else {
666
22.2k
    dec->num_caches = ST_CACHE_LINES;
667
22.2k
  }
668
22.6k
  return 1;
669
22.6k
}
670
671
int VP8GetThreadMethod(const WebPDecoderOptions* const options,
672
                       const WebPHeaderStructure* const headers,
673
22.7k
                       int width, int height) {
674
22.7k
  if (options == NULL || options->use_threads == 0) {
675
18.5k
    return 0;
676
18.5k
  }
677
4.14k
  (void)headers;
678
4.14k
  (void)width;
679
4.14k
  (void)height;
680
4.14k
  assert(headers == NULL || !headers->is_lossless);
681
4.14k
#if defined(WEBP_USE_THREAD)
682
4.14k
  if (width >= MIN_WIDTH_FOR_THREADS) return 2;
683
3.70k
#endif
684
3.70k
  return 0;
685
4.14k
}
686
687
#undef MT_CACHE_LINES
688
#undef ST_CACHE_LINES
689
690
//------------------------------------------------------------------------------
691
// Memory setup
692
693
22.6k
static int AllocateMemory(VP8Decoder* const dec) {
694
22.6k
  const int num_caches = dec->num_caches;
695
22.6k
  const int mb_w = dec->mb_w;
696
  // Note: we use 'size_t' when there's no overflow risk, uint64_t otherwise.
697
22.6k
  const size_t intra_pred_mode_size = 4 * mb_w * sizeof(uint8_t);
698
22.6k
  const size_t top_size = sizeof(VP8TopSamples) * mb_w;
699
22.6k
  const size_t mb_info_size = (mb_w + 1) * sizeof(VP8MB);
700
22.6k
  const size_t f_info_size =
701
22.6k
      (dec->filter_type > 0) ?
702
16.3k
          mb_w * (dec->mt_method > 0 ? 2 : 1) * sizeof(VP8FInfo)
703
22.6k
        : 0;
704
22.6k
  const size_t yuv_size = YUV_SIZE * sizeof(*dec->yuv_b);
705
22.6k
  const size_t mb_data_size =
706
22.6k
      (dec->mt_method == 2 ? 2 : 1) * mb_w * sizeof(*dec->mb_data);
707
22.6k
  const size_t cache_height = (16 * num_caches
708
22.6k
                            + kFilterExtraRows[dec->filter_type]) * 3 / 2;
709
22.6k
  const size_t cache_size = top_size * cache_height;
710
  // alpha_size is the only one that scales as width x height.
711
22.6k
  const uint64_t alpha_size = (dec->alpha_data != NULL) ?
712
20.3k
      (uint64_t)dec->pic_hdr.width * dec->pic_hdr.height : 0ULL;
713
22.6k
  const uint64_t needed = (uint64_t)intra_pred_mode_size
714
22.6k
                        + top_size + mb_info_size + f_info_size
715
22.6k
                        + yuv_size + mb_data_size
716
22.6k
                        + cache_size + alpha_size + WEBP_ALIGN_CST;
717
22.6k
  uint8_t* mem;
718
719
22.6k
  if (!CheckSizeOverflow(needed)) return 0;  // check for overflow
720
22.6k
  if (needed > dec->mem_size) {
721
22.6k
    WebPSafeFree(dec->mem);
722
22.6k
    dec->mem_size = 0;
723
22.6k
    dec->mem = WebPSafeMalloc(needed, sizeof(uint8_t));
724
22.6k
    if (dec->mem == NULL) {
725
0
      return VP8SetError(dec, VP8_STATUS_OUT_OF_MEMORY,
726
0
                         "no memory during frame initialization.");
727
0
    }
728
    // down-cast is ok, thanks to WebPSafeMalloc() above.
729
22.6k
    dec->mem_size = (size_t)needed;
730
22.6k
  }
731
732
22.6k
  mem = (uint8_t*)dec->mem;
733
22.6k
  dec->intra_t = mem;
734
22.6k
  mem += intra_pred_mode_size;
735
736
22.6k
  dec->yuv_t = (VP8TopSamples*)mem;
737
22.6k
  mem += top_size;
738
739
22.6k
  dec->mb_info = ((VP8MB*)mem) + 1;
740
22.6k
  mem += mb_info_size;
741
742
22.6k
  dec->f_info = f_info_size ? (VP8FInfo*)mem : NULL;
743
22.6k
  mem += f_info_size;
744
22.6k
  dec->thread_ctx.id = 0;
745
22.6k
  dec->thread_ctx.f_info = dec->f_info;
746
22.6k
  if (dec->filter_type > 0 && dec->mt_method > 0) {
747
    // secondary cache line. The deblocking process need to make use of the
748
    // filtering strength from previous macroblock row, while the new ones
749
    // are being decoded in parallel. We'll just swap the pointers.
750
267
    dec->thread_ctx.f_info += mb_w;
751
267
  }
752
753
22.6k
  mem = (uint8_t*)WEBP_ALIGN(mem);
754
22.6k
  assert((yuv_size & WEBP_ALIGN_CST) == 0);
755
22.6k
  dec->yuv_b = mem;
756
22.6k
  mem += yuv_size;
757
758
22.6k
  dec->mb_data = (VP8MBData*)mem;
759
22.6k
  dec->thread_ctx.mb_data = (VP8MBData*)mem;
760
22.6k
  if (dec->mt_method == 2) {
761
440
    dec->thread_ctx.mb_data += mb_w;
762
440
  }
763
22.6k
  mem += mb_data_size;
764
765
22.6k
  dec->cache_y_stride = 16 * mb_w;
766
22.6k
  dec->cache_uv_stride = 8 * mb_w;
767
22.6k
  {
768
22.6k
    const int extra_rows = kFilterExtraRows[dec->filter_type];
769
22.6k
    const int extra_y = extra_rows * dec->cache_y_stride;
770
22.6k
    const int extra_uv = (extra_rows / 2) * dec->cache_uv_stride;
771
22.6k
    dec->cache_y = mem + extra_y;
772
22.6k
    dec->cache_u = dec->cache_y
773
22.6k
                  + 16 * num_caches * dec->cache_y_stride + extra_uv;
774
22.6k
    dec->cache_v = dec->cache_u
775
22.6k
                  + 8 * num_caches * dec->cache_uv_stride + extra_uv;
776
22.6k
    dec->cache_id = 0;
777
22.6k
  }
778
22.6k
  mem += cache_size;
779
780
  // alpha plane
781
22.6k
  dec->alpha_plane = alpha_size ? mem : NULL;
782
22.6k
  mem += alpha_size;
783
22.6k
  assert(mem <= (uint8_t*)dec->mem + dec->mem_size);
784
785
  // note: left/top-info is initialized once for all.
786
22.6k
  memset(dec->mb_info - 1, 0, mb_info_size);
787
22.6k
  VP8InitScanline(dec);   // initialize left too.
788
789
  // initialize top
790
22.6k
  memset(dec->intra_t, B_DC_PRED, intra_pred_mode_size);
791
792
22.6k
  return 1;
793
22.6k
}
794
795
22.6k
static void InitIo(VP8Decoder* const dec, VP8Io* io) {
796
  // prepare 'io'
797
22.6k
  io->mb_y = 0;
798
22.6k
  io->y = dec->cache_y;
799
22.6k
  io->u = dec->cache_u;
800
22.6k
  io->v = dec->cache_v;
801
22.6k
  io->y_stride = dec->cache_y_stride;
802
22.6k
  io->uv_stride = dec->cache_uv_stride;
803
22.6k
  io->a = NULL;
804
22.6k
}
805
806
22.6k
int VP8InitFrame(VP8Decoder* const dec, VP8Io* const io) {
807
22.6k
  if (!InitThreadContext(dec)) return 0;  // call first. Sets dec->num_caches.
808
22.6k
  if (!AllocateMemory(dec)) return 0;
809
22.6k
  InitIo(dec, io);
810
22.6k
  VP8DspInit();  // Init critical function pointers and look-up tables.
811
22.6k
  return 1;
812
22.6k
}
813
814
//------------------------------------------------------------------------------