Coverage Report

Created: 2026-10-17 06:52

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/work/libde265/libde265/slice.cc
Line
Count
Source
1
/*
2
 * H.265 video codec.
3
 * Copyright (c) 2013-2014 struktur AG, Dirk Farin <farin@struktur.de>
4
 *
5
 * Authors: struktur AG, Dirk Farin <farin@struktur.de>
6
 *          Min Chen <chenm003@163.com>
7
 *
8
 * This file is part of libde265.
9
 *
10
 * libde265 is free software: you can redistribute it and/or modify
11
 * it under the terms of the GNU Lesser General Public License as
12
 * published by the Free Software Foundation, either version 3 of
13
 * the License, or (at your option) any later version.
14
 *
15
 * libde265 is distributed in the hope that it will be useful,
16
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18
 * GNU Lesser General Public License for more details.
19
 *
20
 * You should have received a copy of the GNU Lesser General Public License
21
 * along with libde265.  If not, see <http://www.gnu.org/licenses/>.
22
 */
23
24
#include "slice.h"
25
#include "motion.h"
26
#include "util.h"
27
#include "scan.h"
28
#include "intrapred.h"
29
#include "transform.h"
30
#include "threads.h"
31
#include "image.h"
32
33
#include <assert.h>
34
#include <string.h>
35
#include <stdlib.h>
36
37
38
#define LOCK de265_mutex_lock(&ctx->thread_pool.mutex)
39
#define UNLOCK de265_mutex_unlock(&ctx->thread_pool.mutex)
40
41
extern bool read_short_term_ref_pic_set(error_queue* errqueue,
42
                                        const seq_parameter_set* sps,
43
                                        bitreader* br,
44
                                        ref_pic_set* out_set,
45
                                        uint32_t idxRps, // index of the set to be read
46
                                        const std::vector<ref_pic_set>& sets,
47
                                        bool sliceRefPicSet);
48
49
50
void read_coding_tree_unit(thread_context* tctx);
51
52
void read_coding_quadtree(thread_context* tctx,
53
                          int xCtb, int yCtb,
54
                          int Log2CtbSizeY,
55
                          int ctDepth);
56
57
/*
58
void decode_inter_block(decoder_context* ctx,thread_context* tctx,
59
                        int xC, int yC, int log2CbSize);
60
*/
61
62
void slice_segment_header::set_defaults()
63
0
{
64
0
  slice_index = 0;
65
66
0
  first_slice_segment_in_pic_flag = 1;
67
0
  no_output_of_prior_pics_flag = 0;
68
0
  slice_pic_parameter_set_id = 0;
69
0
  dependent_slice_segment_flag = 0;
70
0
  slice_segment_address = 0;
71
72
0
  slice_type = SLICE_TYPE_I;
73
0
  pic_output_flag = 1;
74
0
  colour_plane_id = 0;
75
0
  slice_pic_order_cnt_lsb = 0;
76
0
  short_term_ref_pic_set_sps_flag = 1;
77
  // ref_pic_set slice_ref_pic_set;
78
79
0
  short_term_ref_pic_set_idx = 0;
80
0
  num_long_term_sps = 0;
81
0
  num_long_term_pics = 0;
82
83
  //uint8_t lt_idx_sps[MAX_NUM_REF_PICS];
84
  //int     poc_lsb_lt[MAX_NUM_REF_PICS];
85
  //char    used_by_curr_pic_lt_flag[MAX_NUM_REF_PICS];
86
87
  //char delta_poc_msb_present_flag[MAX_NUM_REF_PICS];
88
  //int delta_poc_msb_cycle_lt[MAX_NUM_REF_PICS];
89
90
0
  slice_temporal_mvp_enabled_flag = 0;
91
0
  slice_sao_luma_flag = 0;
92
0
  slice_sao_chroma_flag = 0;
93
94
0
  num_ref_idx_active_override_flag = 0;
95
0
  num_ref_idx_l0_active = 1; // [1;16]
96
0
  num_ref_idx_l1_active = 1; // [1;16]
97
98
0
  ref_pic_list_modification_flag_l0 = 0;
99
0
  ref_pic_list_modification_flag_l1 = 0;
100
  //uint8_t list_entry_l0[16];
101
  //uint8_t list_entry_l1[16];
102
103
0
  mvd_l1_zero_flag = 0;
104
0
  cabac_init_flag = 0;
105
0
  collocated_from_l0_flag = 0;
106
0
  collocated_ref_idx = 0;
107
108
  // --- pred_weight_table ---
109
110
0
  luma_log2_weight_denom = 0; // [0;7]
111
0
  ChromaLog2WeightDenom = 0; // [0;7]
112
113
  // first index is L0/L1
114
  /*
115
  uint8_t luma_weight_flag[2][16];   // bool
116
  uint8_t chroma_weight_flag[2][16]; // bool
117
  int16_t LumaWeight[2][16];
118
  int8_t  luma_offset[2][16];
119
  int16_t ChromaWeight[2][16][2];
120
  int8_t  ChromaOffset[2][16][2];
121
  */
122
123
124
0
  five_minus_max_num_merge_cand = 0;
125
0
  slice_qp_delta = 0;
126
127
0
  slice_cb_qp_offset = 0;
128
0
  slice_cr_qp_offset = 0;
129
130
0
  cu_chroma_qp_offset_enabled_flag = 0;
131
132
0
  deblocking_filter_override_flag = 0;
133
0
  slice_deblocking_filter_disabled_flag = 0;
134
0
  slice_beta_offset = 0; // = pps->beta_offset if undefined
135
0
  slice_tc_offset = 0; // = pps->tc_offset if undefined
136
137
0
  slice_loop_filter_across_slices_enabled_flag = 0;
138
139
0
  num_entry_point_offsets = 0;
140
  //int  offset_len;
141
  //std::vector<int> entry_point_offset;
142
143
0
  slice_segment_header_extension_length = 0;
144
145
0
  SliceAddrRS = slice_segment_address;
146
0
}
147
148
149
de265_error read_pred_weight_table(bitreader* br, slice_segment_header* shdr, decoder_context* ctx)
150
1.16k
{
151
1.16k
  uint32_t uvlc;
152
1.16k
  int32_t svlc;
153
154
1.16k
  pic_parameter_set* pps = ctx->get_pps((int) shdr->slice_pic_parameter_set_id);
155
1.16k
  assert(pps);
156
1.16k
  seq_parameter_set* sps = ctx->get_sps((int) pps->seq_parameter_set_id);
157
1.16k
  assert(sps);
158
159
1.16k
  uvlc = br->get_uvlc();
160
1.16k
  if (uvlc > 7) return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
161
1.15k
  shdr->luma_log2_weight_denom = uvlc;
162
163
1.15k
  if (sps->chroma_format_idc != 0) {
164
1.15k
    svlc = br->get_svlc();
165
1.15k
    svlc += shdr->luma_log2_weight_denom;
166
1.15k
    if (svlc < 0 || svlc > 7) return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
167
1.14k
    shdr->ChromaLog2WeightDenom = svlc;
168
1.14k
  }
169
170
1.14k
  int sumWeightFlags[2]{};
171
172
3.33k
  for (int l = 0; l <= 1; l++)
173
2.25k
    if (l == 0 || (l == 1 && shdr->slice_type == SLICE_TYPE_B)) {
174
2.21k
      int num_ref = (l == 0 ? shdr->num_ref_idx_l0_active - 1 : shdr->num_ref_idx_l1_active - 1);
175
176
6.75k
      for (int i = 0; i <= num_ref; i++) {
177
4.54k
        shdr->luma_weight_flag[l][i] = br->get_bits(1);
178
4.54k
        if (shdr->luma_weight_flag[l][i]) sumWeightFlags[l]++;
179
4.54k
      }
180
181
2.21k
      if (sps->chroma_format_idc != 0) {
182
6.75k
        for (int i = 0; i <= num_ref; i++) {
183
4.54k
          shdr->chroma_weight_flag[l][i] = br->get_bits(1);
184
4.54k
          if (shdr->chroma_weight_flag[l][i]) sumWeightFlags[l] += 2;
185
4.54k
        }
186
2.21k
      }
187
188
6.45k
      for (int i = 0; i <= num_ref; i++) {
189
4.30k
        if (shdr->luma_weight_flag[l][i]) {
190
          // delta_luma_weight
191
192
1.95k
          svlc = br->get_svlc();
193
1.95k
          if (svlc < -128 || svlc > 127) return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
194
195
1.94k
          shdr->LumaWeight[l][i] = (1 << shdr->luma_log2_weight_denom) + svlc;
196
197
          // luma_offset
198
199
1.94k
          svlc = br->get_svlc();
200
1.94k
          if (svlc < -sps->WpOffsetHalfRangeY || svlc > sps->WpOffsetHalfRangeY - 1) return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
201
1.92k
          shdr->luma_offset[l][i] = svlc;
202
1.92k
        }
203
2.35k
        else {
204
2.35k
          shdr->LumaWeight[l][i] = 1 << shdr->luma_log2_weight_denom;
205
2.35k
          shdr->luma_offset[l][i] = 0;
206
2.35k
        }
207
208
4.27k
        if (shdr->chroma_weight_flag[l][i])
209
7.47k
          for (int j = 0; j < 2; j++) {
210
            // delta_chroma_weight
211
212
4.99k
            svlc = br->get_svlc();
213
4.99k
            if (svlc < -128 || svlc > 127) return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
214
215
4.99k
            shdr->ChromaWeight[l][i][j] = (1 << shdr->ChromaLog2WeightDenom) + svlc;
216
217
            // delta_chroma_offset
218
219
4.99k
            svlc = br->get_svlc();
220
4.99k
            if (svlc < -4 * sps->WpOffsetHalfRangeC ||
221
4.99k
                svlc > 4 * sps->WpOffsetHalfRangeC - 1)
222
28
              return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
223
224
4.96k
            svlc = Clip3(-sps->WpOffsetHalfRangeC,
225
4.96k
                         sps->WpOffsetHalfRangeC-1,
226
4.96k
                         (sps->WpOffsetHalfRangeC
227
4.96k
                           +svlc
228
4.96k
                           -((sps->WpOffsetHalfRangeC*shdr->ChromaWeight[l][i][j])
229
4.96k
                             >> shdr->ChromaLog2WeightDenom)));
230
231
4.96k
            shdr->ChromaOffset[l][i][j] = svlc;
232
4.96k
          }
233
1.76k
        else {
234
5.28k
          for (int j = 0; j < 2; j++) {
235
3.52k
            shdr->ChromaWeight[l][i][j] = 1 << shdr->ChromaLog2WeightDenom;
236
3.52k
            shdr->ChromaOffset[l][i][j] = 0;
237
3.52k
          }
238
1.76k
        }
239
4.27k
      }
240
2.21k
    }
241
242
  // check sumWeightFlags against limits (H.265, Section 7.4.7.3)
243
244
1.08k
  if (shdr->slice_type == SLICE_TYPE_P && sumWeightFlags[0] > 24) {
245
1
    return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
246
1
  }
247
248
1.07k
  if (shdr->slice_type == SLICE_TYPE_B && sumWeightFlags[0] + sumWeightFlags[1] > 24) {
249
14
    return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
250
14
  }
251
252
1.06k
  return DE265_OK;
253
1.07k
}
254
255
256
void slice_segment_header::reset()
257
8.94k
{
258
8.94k
  pps = nullptr;
259
260
8.94k
  slice_index = 0;
261
262
8.94k
  first_slice_segment_in_pic_flag = 0;
263
8.94k
  no_output_of_prior_pics_flag = 0;
264
8.94k
  slice_pic_parameter_set_id = 0;
265
8.94k
  dependent_slice_segment_flag = 0;
266
8.94k
  slice_segment_address = 0;
267
268
8.94k
  slice_type = 0;
269
8.94k
  pic_output_flag = 0;
270
8.94k
  colour_plane_id = 0;
271
8.94k
  slice_pic_order_cnt_lsb = 0;
272
8.94k
  short_term_ref_pic_set_sps_flag = 0;
273
8.94k
  slice_ref_pic_set.reset();
274
275
8.94k
  short_term_ref_pic_set_idx = 0;
276
8.94k
  num_long_term_sps = 0;
277
8.94k
  num_long_term_pics = 0;
278
279
152k
  for (int i = 0; i < MAX_NUM_REF_PICS; i++) {
280
143k
    lt_idx_sps[i] = 0;
281
143k
    poc_lsb_lt[i] = 0;
282
143k
    used_by_curr_pic_lt_flag[i] = 0;
283
143k
    delta_poc_msb_present_flag[i] = 0;
284
143k
    delta_poc_msb_cycle_lt[i] = 0;
285
143k
  }
286
287
8.94k
  slice_temporal_mvp_enabled_flag = 0;
288
8.94k
  slice_sao_luma_flag = 0;
289
8.94k
  slice_sao_chroma_flag = 0;
290
291
8.94k
  num_ref_idx_active_override_flag = 0;
292
8.94k
  num_ref_idx_l0_active = 0;
293
8.94k
  num_ref_idx_l1_active = 0;
294
295
8.94k
  ref_pic_list_modification_flag_l0 = 0;
296
8.94k
  ref_pic_list_modification_flag_l1 = 0;
297
152k
  for (int i = 0; i < 16; i++) {
298
143k
    list_entry_l0[i] = 0;
299
143k
    list_entry_l1[i] = 0;
300
143k
  }
301
302
8.94k
  mvd_l1_zero_flag = 0;
303
8.94k
  cabac_init_flag = 0;
304
8.94k
  collocated_from_l0_flag = 0;
305
8.94k
  collocated_ref_idx = 0;
306
307
8.94k
  luma_log2_weight_denom = 0;
308
8.94k
  ChromaLog2WeightDenom = 0;
309
310
26.8k
  for (int i = 0; i < 2; i++)
311
304k
    for (int j = 0; j < 16; j++) {
312
286k
      luma_weight_flag[i][j] = 0;
313
286k
      chroma_weight_flag[i][j] = 0;
314
286k
      LumaWeight[i][j] = 0;
315
286k
      luma_offset[i][j] = 0;
316
286k
      ChromaWeight[i][j][0] = ChromaWeight[i][j][1] = 0;
317
286k
      ChromaOffset[i][j][0] = ChromaOffset[i][j][1] = 0;
318
286k
    }
319
320
8.94k
  five_minus_max_num_merge_cand = 0;
321
8.94k
  slice_qp_delta = 0;
322
323
8.94k
  slice_cb_qp_offset = 0;
324
8.94k
  slice_cr_qp_offset = 0;
325
326
8.94k
  cu_chroma_qp_offset_enabled_flag = 0;
327
328
8.94k
  deblocking_filter_override_flag = 0;
329
8.94k
  slice_deblocking_filter_disabled_flag = 0;
330
8.94k
  slice_beta_offset = 0;
331
8.94k
  slice_tc_offset = 0;
332
333
8.94k
  slice_loop_filter_across_slices_enabled_flag = 0;
334
335
8.94k
  num_entry_point_offsets = 0;
336
8.94k
  offset_len = 0;
337
8.94k
  entry_point_offset.clear();
338
339
8.94k
  slice_segment_header_extension_length = 0;
340
341
8.94k
  SliceAddrRS = 0;
342
8.94k
  SliceQPY = 0;
343
344
8.94k
  initType = 0;
345
346
8.94k
  MaxNumMergeCand = 0;
347
8.94k
  CurrRpsIdx = 0;
348
8.94k
  CurrRps.reset();
349
8.94k
  NumPocTotalCurr = 0;
350
351
26.8k
  for (int i = 0; i < 2; i++)
352
304k
    for (int j = 0; j < MAX_NUM_REF_PICS; j++) {
353
286k
      RefPicList[i][j] = 0;
354
286k
      RefPicList_POC[i][j] = 0;
355
286k
      RefPicList_PicState[i][j] = 0;
356
286k
      LongTermRefPic[i][j] = 0;
357
286k
    }
358
359
  //context_model ctx_model_storage[CONTEXT_MODEL_TABLE_LENGTH];
360
361
8.94k
  RemoveReferencesList.clear();
362
363
44.7k
  for (int i = 0; i < 4; i++) {
364
35.7k
    ctx_model_storage_StatCoeff[i] = 0;
365
35.7k
  }
366
8.94k
  ctx_model_storage_defined = false;
367
8.94k
}
368
369
370
de265_error slice_segment_header::read(bitreader* br, decoder_context* ctx,
371
                                       bool* continueDecoding)
372
4.47k
{
373
4.47k
  *continueDecoding = false;
374
4.47k
  reset();
375
376
4.47k
  uint32_t uvlc;
377
4.47k
  int32_t svlc;
378
379
  // set defaults
380
381
4.47k
  dependent_slice_segment_flag = 0;
382
383
384
  // read bitstream
385
386
4.47k
  first_slice_segment_in_pic_flag = br->get_bits(1);
387
388
4.47k
  if (ctx->get_RapPicFlag()) {
389
    // TODO: is this still correct ? Should we drop RapPicFlag ?
390
4.33k
    no_output_of_prior_pics_flag = br->get_bits(1);
391
4.33k
  }
392
393
4.47k
  if ((uvlc = br->get_uvlc()) == UVLC_ERROR ||
394
4.41k
      uvlc >= DE265_MAX_PPS_SETS) {
395
92
    ctx->add_warning(DE265_WARNING_NONEXISTING_PPS_REFERENCED, false);
396
92
    return DE265_OK;
397
92
  }
398
4.38k
  slice_pic_parameter_set_id = uvlc;
399
400
4.38k
  if (!ctx->has_pps(slice_pic_parameter_set_id)) {
401
560
    ctx->add_warning(DE265_WARNING_NONEXISTING_PPS_REFERENCED, false);
402
560
    return DE265_OK;
403
560
  }
404
405
3.82k
  pps = ctx->get_shared_pps(slice_pic_parameter_set_id);
406
407
3.82k
  const seq_parameter_set* sps = pps->sps.get();
408
3.82k
  if (!sps->sps_read) {
409
0
    ctx->add_warning(DE265_WARNING_NONEXISTING_SPS_REFERENCED, false);
410
0
    *continueDecoding = false;
411
0
    return DE265_OK;
412
0
  }
413
414
3.82k
  if (!first_slice_segment_in_pic_flag) {
415
60
    if (pps->dependent_slice_segments_enabled_flag) {
416
5
      dependent_slice_segment_flag = br->get_bits(1);
417
5
    }
418
55
    else {
419
55
      dependent_slice_segment_flag = 0;
420
55
    }
421
422
60
    uint32_t slice_segment_address = br->get_bits(ceil_log2(sps->PicSizeInCtbsY));
423
424
60
    if (dependent_slice_segment_flag) {
425
2
      if (slice_segment_address == 0) {
426
1
        *continueDecoding = false;
427
1
        ctx->add_warning(DE265_WARNING_DEPENDENT_SLICE_WITH_ADDRESS_ZERO, false);
428
1
        return DE265_OK;
429
1
      }
430
431
1
      if (ctx->previous_slice_header == nullptr) {
432
1
        return DE265_ERROR_NO_INITIAL_SLICE_HEADER;
433
1
      }
434
435
0
      *this = *ctx->previous_slice_header;
436
437
0
      first_slice_segment_in_pic_flag = 0;
438
0
      dependent_slice_segment_flag = 1;
439
0
    }
440
441
58
    this->slice_segment_address = slice_segment_address;
442
58
  }
443
3.76k
  else {
444
3.76k
    dependent_slice_segment_flag = 0;
445
3.76k
    slice_segment_address = 0;
446
3.76k
  }
447
448
3.81k
  if (slice_segment_address >= sps->PicSizeInCtbsY) {
449
1
    ctx->add_warning(DE265_WARNING_SLICE_SEGMENT_ADDRESS_INVALID, false);
450
1
    return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
451
1
  }
452
453
  //printf("SLICE %d (%d)\n",slice_segment_address, sps->PicSizeInCtbsY);
454
455
456
3.81k
  if (!dependent_slice_segment_flag) {
457
6.67k
    for (int i = 0; i < pps->num_extra_slice_header_bits; i++) {
458
      //slice_reserved_undetermined_flag[i]
459
2.86k
      br->skip_bits(1);
460
2.86k
    }
461
462
3.81k
    if ((uvlc = br->get_uvlc()) == UVLC_ERROR ||
463
3.81k
        uvlc > 2) {
464
13
      ctx->add_warning(DE265_WARNING_SLICEHEADER_INVALID, false);
465
13
      *continueDecoding = false;
466
13
      return DE265_OK;
467
13
    }
468
3.80k
    slice_type = uvlc;
469
470
3.80k
    if (pps->output_flag_present_flag) {
471
352
      pic_output_flag = br->get_bits(1);
472
352
    }
473
3.45k
    else {
474
3.45k
      pic_output_flag = 1;
475
3.45k
    }
476
477
3.80k
    if (sps->separate_colour_plane_flag == 1) {
478
0
      colour_plane_id = br->get_bits(2);
479
0
    }
480
481
482
3.80k
    slice_pic_order_cnt_lsb = 0;
483
3.80k
    short_term_ref_pic_set_sps_flag = 0;
484
485
3.80k
    int NumLtPics = 0;
486
487
3.80k
    if (ctx->get_nal_unit_type() != NAL_UNIT_IDR_W_RADL &&
488
2.68k
        ctx->get_nal_unit_type() != NAL_UNIT_IDR_N_LP) {
489
2.51k
      slice_pic_order_cnt_lsb = br->get_bits(sps->log2_max_pic_order_cnt_lsb);
490
2.51k
      short_term_ref_pic_set_sps_flag = br->get_bits(1);
491
492
2.51k
      if (!short_term_ref_pic_set_sps_flag) {
493
2.46k
        read_short_term_ref_pic_set(ctx, sps,
494
2.46k
                                    br, &slice_ref_pic_set,
495
2.46k
                                    sps->num_short_term_ref_pic_sets(),
496
2.46k
                                    sps->ref_pic_sets,
497
2.46k
                                    true);
498
499
2.46k
        CurrRpsIdx = sps->num_short_term_ref_pic_sets();
500
2.46k
        CurrRps = slice_ref_pic_set;
501
2.46k
      }
502
59
      else {
503
59
        int nBits = ceil_log2(sps->num_short_term_ref_pic_sets());
504
59
        if (nBits > 0) short_term_ref_pic_set_idx = br->get_bits(nBits);
505
6
        else short_term_ref_pic_set_idx = 0;
506
507
59
        if (short_term_ref_pic_set_idx >= sps->num_short_term_ref_pic_sets()) {
508
4
          ctx->add_warning(DE265_WARNING_SHORT_TERM_REF_PIC_SET_OUT_OF_RANGE, false);
509
4
          return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
510
4
        }
511
512
55
        CurrRpsIdx = short_term_ref_pic_set_idx;
513
55
        CurrRps = sps->ref_pic_sets[CurrRpsIdx];
514
55
      }
515
516
517
      // --- long-term MC ---
518
519
2.51k
      if (sps->long_term_ref_pics_present_flag) {
520
1.20k
        if (sps->num_long_term_ref_pics_sps > 0) {
521
1.09k
          if ((uvlc = br->get_uvlc()) == UVLC_ERROR ||
522
1.09k
              uvlc > sps->num_long_term_ref_pics_sps) {
523
18
            return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
524
18
          }
525
1.08k
          num_long_term_sps = uvlc;
526
1.08k
        }
527
104
        else {
528
104
          num_long_term_sps = 0;
529
104
        }
530
531
1.18k
        if ((uvlc = br->get_uvlc()) == UVLC_ERROR || uvlc > MAX_NUM_LT_REF_PICS_SPS) {
532
8
          return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
533
8
        }
534
1.17k
        num_long_term_pics = uvlc;
535
536
        // check maximum number of reference frames
537
538
1.17k
        if (num_long_term_sps +
539
1.17k
            num_long_term_pics +
540
1.17k
            CurrRps.NumNegativePics +
541
1.17k
            CurrRps.NumPositivePics
542
1.17k
            > sps->sps_max_dec_pic_buffering[sps->sps_max_sub_layers - 1]) {
543
3
          ctx->add_warning(DE265_WARNING_MAX_NUM_REF_PICS_EXCEEDED, false);
544
3
          *continueDecoding = false;
545
3
          return DE265_OK;
546
3
        }
547
548
3.17k
        for (int i = 0; i < num_long_term_sps + num_long_term_pics; i++) {
549
2.00k
          if (i < num_long_term_sps) {
550
1.52k
            int nBits = ceil_log2(sps->num_long_term_ref_pics_sps);
551
1.52k
            lt_idx_sps[i] = br->get_bits(nBits);
552
553
            // check that the referenced lt-reference really exists
554
555
1.52k
            if (lt_idx_sps[i] >= sps->num_long_term_ref_pics_sps) {
556
1
              ctx->add_warning(DE265_NON_EXISTING_LT_REFERENCE_CANDIDATE_IN_SLICE_HEADER, false);
557
1
              *continueDecoding = false;
558
1
              return DE265_OK;
559
1
            }
560
561
            // delta_poc_msb_present_flag[i] = 0; // TODO ?
562
563
1.52k
            ctx->PocLsbLt[i] = sps->lt_ref_pic_poc_lsb_sps[lt_idx_sps[i]];
564
1.52k
            ctx->UsedByCurrPicLt[i] = sps->used_by_curr_pic_lt_sps_flag[lt_idx_sps[i]];
565
1.52k
          }
566
475
          else {
567
475
            int nBits = sps->log2_max_pic_order_cnt_lsb;
568
475
            poc_lsb_lt[i] = br->get_bits(nBits);
569
475
            used_by_curr_pic_lt_flag[i] = br->get_bits(1);
570
571
475
            ctx->PocLsbLt[i] = poc_lsb_lt[i];
572
475
            ctx->UsedByCurrPicLt[i] = used_by_curr_pic_lt_flag[i];
573
475
          }
574
575
1.99k
          if (ctx->UsedByCurrPicLt[i]) {
576
1.63k
            NumLtPics++;
577
1.63k
          }
578
579
1.99k
          delta_poc_msb_present_flag[i] = br->get_bits(1);
580
1.99k
          if (delta_poc_msb_present_flag[i]) {
581
1.25k
            if ((uvlc = br->get_uvlc()) == UVLC_ERROR) {
582
3
              return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
583
3
            }
584
1.25k
            delta_poc_msb_cycle_lt[i] = uvlc;
585
1.25k
          }
586
745
          else {
587
745
            delta_poc_msb_cycle_lt[i] = 0;
588
745
          }
589
590
1.99k
          if (i == 0 || i == num_long_term_sps) {
591
1.17k
            ctx->DeltaPocMsbCycleLt[i] = delta_poc_msb_cycle_lt[i];
592
1.17k
          }
593
820
          else {
594
820
            if (delta_poc_msb_cycle_lt[i] > UINT32_MAX - ctx->DeltaPocMsbCycleLt[i - 1]) {
595
0
              ctx->add_warning(DE265_WARNING_SLICEHEADER_INVALID, false);
596
0
              return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
597
0
            }
598
820
            ctx->DeltaPocMsbCycleLt[i] = (delta_poc_msb_cycle_lt[i] +
599
820
                                          ctx->DeltaPocMsbCycleLt[i - 1]);
600
820
          }
601
1.99k
        }
602
1.17k
      }
603
1.31k
      else {
604
1.31k
        num_long_term_sps = 0;
605
1.31k
        num_long_term_pics = 0;
606
1.31k
      }
607
608
2.48k
      if (sps->sps_temporal_mvp_enabled_flag) {
609
2.08k
        slice_temporal_mvp_enabled_flag = br->get_bits(1);
610
2.08k
      }
611
397
      else {
612
397
        slice_temporal_mvp_enabled_flag = 0;
613
397
      }
614
2.48k
    }
615
1.28k
    else {
616
1.28k
      slice_pic_order_cnt_lsb = 0;
617
1.28k
      num_long_term_sps = 0;
618
1.28k
      num_long_term_pics = 0;
619
1.28k
    }
620
621
622
    // --- SAO ---
623
624
3.76k
    if (sps->sample_adaptive_offset_enabled_flag) {
625
2.62k
      slice_sao_luma_flag = br->get_bits(1);
626
627
2.62k
      if (sps->ChromaArrayType != CHROMA_MONO) {
628
2.62k
        slice_sao_chroma_flag = br->get_bits(1);
629
2.62k
      }
630
0
      else {
631
0
        slice_sao_chroma_flag = 0;
632
0
      }
633
2.62k
    }
634
1.14k
    else {
635
1.14k
      slice_sao_luma_flag = 0;
636
1.14k
      slice_sao_chroma_flag = 0;
637
1.14k
    }
638
639
3.76k
    num_ref_idx_l0_active = 0;
640
3.76k
    num_ref_idx_l1_active = 0;
641
642
3.76k
    if (slice_type == SLICE_TYPE_P ||
643
3.13k
        slice_type == SLICE_TYPE_B) {
644
2.30k
      num_ref_idx_active_override_flag = br->get_bits(1);
645
2.30k
      if (num_ref_idx_active_override_flag) {
646
1.70k
        if ((uvlc = br->get_uvlc()) == UVLC_ERROR || uvlc > 15) {
647
15
          ctx->add_warning(DE265_WARNING_SLICEHEADER_INVALID, false);
648
15
          return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
649
15
        }
650
1.69k
        num_ref_idx_l0_active = uvlc + 1;
651
652
1.69k
        if (slice_type == SLICE_TYPE_B) {
653
1.21k
          if ((uvlc = br->get_uvlc()) == UVLC_ERROR || uvlc > 15) {
654
22
            ctx->add_warning(DE265_WARNING_SLICEHEADER_INVALID, false);
655
22
            return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
656
22
          }
657
1.19k
          num_ref_idx_l1_active = uvlc + 1;
658
1.19k
        }
659
1.69k
      }
660
599
      else {
661
599
        num_ref_idx_l0_active = pps->num_ref_idx_l0_default_active;
662
599
        num_ref_idx_l1_active = pps->num_ref_idx_l1_default_active;
663
599
      }
664
665
2.26k
      NumPocTotalCurr = CurrRps.NumPocTotalCurr_shortterm_only + NumLtPics;
666
667
2.26k
      if (pps->lists_modification_present_flag && NumPocTotalCurr > 1) {
668
765
        int nBits = ceil_log2(NumPocTotalCurr);
669
670
765
        ref_pic_list_modification_flag_l0 = br->get_bits(1);
671
765
        if (ref_pic_list_modification_flag_l0) {
672
1.39k
          for (int i = 0; i < num_ref_idx_l0_active; i++) {
673
725
            list_entry_l0[i] = br->get_bits(nBits);
674
725
          }
675
673
        }
676
677
765
        if (slice_type == SLICE_TYPE_B) {
678
429
          ref_pic_list_modification_flag_l1 = br->get_bits(1);
679
429
          if (ref_pic_list_modification_flag_l1) {
680
498
            for (int i = 0; i < num_ref_idx_l1_active; i++) {
681
288
              list_entry_l1[i] = br->get_bits(nBits);
682
288
            }
683
210
          }
684
429
        }
685
336
        else {
686
336
          ref_pic_list_modification_flag_l1 = 0;
687
336
        }
688
765
      }
689
1.50k
      else {
690
1.50k
        ref_pic_list_modification_flag_l0 = 0;
691
1.50k
        ref_pic_list_modification_flag_l1 = 0;
692
1.50k
      }
693
694
2.26k
      if (slice_type == SLICE_TYPE_B) {
695
1.63k
        mvd_l1_zero_flag = br->get_bits(1);
696
1.63k
      }
697
698
2.26k
      if (pps->cabac_init_present_flag) {
699
68
        cabac_init_flag = br->get_bits(1);
700
68
      }
701
2.19k
      else {
702
2.19k
        cabac_init_flag = 0;
703
2.19k
      }
704
705
2.26k
      if (slice_temporal_mvp_enabled_flag) {
706
952
        if (slice_type == SLICE_TYPE_B)
707
546
          collocated_from_l0_flag = br->get_bits(1);
708
406
        else
709
406
          collocated_from_l0_flag = 1;
710
711
952
        if ((collocated_from_l0_flag && num_ref_idx_l0_active > 1) ||
712
880
            (!collocated_from_l0_flag && num_ref_idx_l1_active > 1)) {
713
120
          if ((uvlc = br->get_uvlc()) == UVLC_ERROR || uvlc > 15) {
714
13
            ctx->add_warning(DE265_WARNING_SLICEHEADER_INVALID, false);
715
13
            return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
716
13
          }
717
107
          collocated_ref_idx = uvlc;
718
107
        }
719
832
        else {
720
832
          collocated_ref_idx = 0;
721
832
        }
722
723
        // check whether collocated_ref_idx points to a valid index
724
725
939
        if ((collocated_from_l0_flag && collocated_ref_idx >= num_ref_idx_l0_active) ||
726
936
            (!collocated_from_l0_flag && collocated_ref_idx >= num_ref_idx_l1_active)) {
727
6
          ctx->add_warning(DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE, false);
728
6
          return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
729
6
        }
730
939
      }
731
732
733
2.24k
      if ((pps->weighted_pred_flag && slice_type == SLICE_TYPE_P) ||
734
2.19k
          (pps->weighted_bipred_flag && slice_type == SLICE_TYPE_B)) {
735
1.16k
        de265_error err = read_pred_weight_table(br, this, ctx);
736
1.16k
        if (err) {
737
97
          ctx->add_warning(err, false);
738
97
          return err;
739
97
        }
740
1.16k
      }
741
742
2.15k
      if ((uvlc = br->get_uvlc()) == UVLC_ERROR || uvlc > 5) {
743
34
        ctx->add_warning(DE265_WARNING_SLICEHEADER_INVALID, false);
744
34
        return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
745
34
      }
746
747
2.11k
      five_minus_max_num_merge_cand = uvlc;
748
2.11k
      MaxNumMergeCand = 5 - five_minus_max_num_merge_cand;
749
2.11k
    }
750
751
3.58k
    if ((svlc = br->get_svlc()) == SVLC_ERROR) {
752
3
      ctx->add_warning(DE265_WARNING_SLICEHEADER_INVALID, false);
753
3
      return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
754
3
    }
755
756
3.57k
    slice_qp_delta = svlc;
757
    //logtrace(LogSlice,"slice_qp_delta: %d\n",shdr->slice_qp_delta);
758
759
3.57k
    if (pps->pps_slice_chroma_qp_offsets_present_flag) {
760
2.35k
      if ((svlc = br->get_svlc()) == SVLC_ERROR) {
761
4
        ctx->add_warning(DE265_WARNING_SLICEHEADER_INVALID, false);
762
4
        return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
763
4
      }
764
765
2.34k
      slice_cb_qp_offset = svlc;
766
767
2.34k
      if ((svlc = br->get_svlc()) == SVLC_ERROR) {
768
4
        ctx->add_warning(DE265_WARNING_SLICEHEADER_INVALID, false);
769
4
        return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
770
4
      }
771
772
2.34k
      slice_cr_qp_offset = svlc;
773
2.34k
    }
774
1.22k
    else {
775
1.22k
      slice_cb_qp_offset = 0;
776
1.22k
      slice_cr_qp_offset = 0;
777
1.22k
    }
778
779
3.56k
    if (pps->range_extension.chroma_qp_offset_list_enabled_flag) {
780
0
      cu_chroma_qp_offset_enabled_flag = br->get_bits(1);
781
0
    }
782
783
3.56k
    if (pps->deblocking_filter_override_enabled_flag) {
784
162
      deblocking_filter_override_flag = br->get_bits(1);
785
162
    }
786
3.40k
    else {
787
3.40k
      deblocking_filter_override_flag = 0;
788
3.40k
    }
789
790
3.56k
    slice_beta_offset = pps->beta_offset;
791
3.56k
    slice_tc_offset = pps->tc_offset;
792
793
3.56k
    if (deblocking_filter_override_flag) {
794
118
      slice_deblocking_filter_disabled_flag = br->get_bits(1);
795
118
      if (!slice_deblocking_filter_disabled_flag) {
796
        // slice_beta_offset_div2 shall be in [-6, 6] (Sec. 7.4.7.1)
797
98
        if ((svlc = br->get_svlc()) == SVLC_ERROR || svlc < -6 || svlc > 6) {
798
15
          ctx->add_warning(DE265_WARNING_SLICEHEADER_INVALID, false);
799
15
          return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
800
15
        }
801
83
        slice_beta_offset = svlc * 2;
802
803
        // slice_tc_offset_div2 shall be in [-6, 6] (Sec. 7.4.7.1)
804
83
        if ((svlc = br->get_svlc()) == SVLC_ERROR || svlc < -6 || svlc > 6) {
805
14
          ctx->add_warning(DE265_WARNING_SLICEHEADER_INVALID, false);
806
14
          return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
807
14
        }
808
69
        slice_tc_offset = svlc * 2;
809
69
      }
810
118
    }
811
3.45k
    else {
812
3.45k
      slice_deblocking_filter_disabled_flag = pps->pic_disable_deblocking_filter_flag;
813
3.45k
    }
814
815
3.54k
    if (pps->pps_loop_filter_across_slices_enabled_flag &&
816
3.24k
        (slice_sao_luma_flag || slice_sao_chroma_flag ||
817
3.21k
         !slice_deblocking_filter_disabled_flag)) {
818
3.21k
      slice_loop_filter_across_slices_enabled_flag = br->get_bits(1);
819
3.21k
    }
820
323
    else {
821
323
      slice_loop_filter_across_slices_enabled_flag =
822
323
          pps->pps_loop_filter_across_slices_enabled_flag;
823
323
    }
824
3.54k
  }
825
826
3.54k
  if (pps->tiles_enabled_flag || pps->entropy_coding_sync_enabled_flag) {
827
828
    // compute the spec limit for num_entry_point_offsets
829
830
435
    int maxEntryPointOffsets;
831
435
    if (!pps->tiles_enabled_flag && pps->entropy_coding_sync_enabled_flag) {
832
247
      maxEntryPointOffsets = sps->PicHeightInCtbsY - 1;
833
247
    }
834
188
    else if (pps->tiles_enabled_flag && !pps->entropy_coding_sync_enabled_flag) {
835
180
      maxEntryPointOffsets = pps->num_tile_columns * pps->num_tile_rows - 1;
836
180
    }
837
8
    else {
838
8
      maxEntryPointOffsets = pps->num_tile_columns * sps->PicHeightInCtbsY - 1;
839
8
    }
840
841
435
    if ((uvlc = br->get_uvlc()) == UVLC_ERROR ||
842
432
        uvlc > static_cast<uint32_t>(maxEntryPointOffsets)) {
843
16
      ctx->add_warning(DE265_WARNING_SLICEHEADER_INVALID, false);
844
16
      return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
845
16
    }
846
419
    num_entry_point_offsets = uvlc;
847
848
419
    entry_point_offset.resize(num_entry_point_offsets);
849
850
419
    if (num_entry_point_offsets > 0) {
851
230
      if ((uvlc = br->get_uvlc()) == UVLC_ERROR || uvlc > 31) {
852
8
        ctx->add_warning(DE265_WARNING_SLICEHEADER_INVALID, false);
853
8
        return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
854
8
      }
855
222
      offset_len = uvlc + 1;
856
857
2.34k
      for (uint32_t i = 0; i < num_entry_point_offsets; i++) {
858
2.11k
        {
859
2.11k
          uint32_t offset_minus1 = br->get_bits(offset_len);
860
2.11k
          if (offset_minus1 == UINT32_MAX) {
861
0
            ctx->add_warning(DE265_WARNING_SLICEHEADER_INVALID, false);
862
0
            return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
863
0
          }
864
2.11k
          entry_point_offset[i] = offset_minus1 + 1;
865
2.11k
        }
866
867
2.11k
        if (i > 0) {
868
1.89k
          if (entry_point_offset[i] > UINT32_MAX - entry_point_offset[i - 1]) {
869
0
            ctx->add_warning(DE265_WARNING_SLICEHEADER_INVALID, false);
870
0
            return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
871
0
          }
872
1.89k
          entry_point_offset[i] += entry_point_offset[i - 1];
873
1.89k
        }
874
2.11k
      }
875
222
    }
876
419
  }
877
3.10k
  else {
878
3.10k
    num_entry_point_offsets = 0;
879
3.10k
  }
880
881
3.51k
  if (pps->slice_segment_header_extension_present_flag) {
882
2.13k
    if ((uvlc = br->get_uvlc()) == UVLC_ERROR ||
883
2.13k
        uvlc > 1000) {
884
      // TODO: safety check against too large values
885
11
      ctx->add_warning(DE265_WARNING_SLICEHEADER_INVALID, false);
886
11
      return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
887
11
    }
888
2.12k
    slice_segment_header_extension_length = uvlc;
889
890
10.9k
    for (int i = 0; i < slice_segment_header_extension_length; i++) {
891
      //slice_segment_header_extension_data_byte[i]
892
8.82k
      br->get_bits(8);
893
8.82k
    }
894
2.12k
  }
895
896
897
3.50k
  compute_derived_values(pps.get());
898
899
  // SliceQpY shall be in [-QpBdOffsetY, 51] (Sec. 7.4.7.1)
900
3.50k
  if (SliceQPY < -sps->QpBdOffset_Y || SliceQPY > 51) {
901
19
    ctx->add_warning(DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE, false);
902
19
    return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
903
19
  }
904
905
3.48k
  *continueDecoding = true;
906
3.48k
  return DE265_OK;
907
3.50k
}
908
909
910
de265_error slice_segment_header::write(error_queue* errqueue, CABAC_encoder& out,
911
                                        const seq_parameter_set* sps,
912
                                        const pic_parameter_set* pps,
913
                                        uint8_t nal_unit_type)
914
0
{
915
0
  out.write_bit(first_slice_segment_in_pic_flag);
916
917
0
  if (isRapPic(nal_unit_type)) {
918
    // TODO: is this still correct ? Should we drop RapPicFlag ?
919
0
    out.write_bit(no_output_of_prior_pics_flag);
920
0
  }
921
922
0
  if (slice_pic_parameter_set_id > DE265_MAX_PPS_SETS) {
923
0
    errqueue->add_warning(DE265_WARNING_NONEXISTING_PPS_REFERENCED, false);
924
0
    return DE265_OK;
925
0
  }
926
0
  out.write_uvlc(slice_pic_parameter_set_id);
927
928
0
  if (!first_slice_segment_in_pic_flag) {
929
0
    if (pps->dependent_slice_segments_enabled_flag) {
930
0
      out.write_bit(dependent_slice_segment_flag);
931
0
    }
932
933
0
    out.write_bits(slice_segment_address, ceil_log2(sps->PicSizeInCtbsY));
934
935
0
    if (dependent_slice_segment_flag) {
936
0
      if (slice_segment_address == 0) {
937
0
        errqueue->add_warning(DE265_WARNING_DEPENDENT_SLICE_WITH_ADDRESS_ZERO, false);
938
0
        return DE265_OK;
939
0
      }
940
0
    }
941
0
  }
942
943
0
  if (slice_segment_address > sps->PicSizeInCtbsY) {
944
0
    errqueue->add_warning(DE265_WARNING_SLICE_SEGMENT_ADDRESS_INVALID, false);
945
0
    return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
946
0
  }
947
948
949
0
  if (!dependent_slice_segment_flag) {
950
0
    for (int i = 0; i < pps->num_extra_slice_header_bits; i++) {
951
      //slice_reserved_undetermined_flag[i]
952
0
      out.skip_bits(1);
953
0
    }
954
955
0
    if (slice_type > 2) {
956
0
      errqueue->add_warning(DE265_WARNING_SLICEHEADER_INVALID, false);
957
0
      return DE265_OK;
958
0
    }
959
0
    out.write_uvlc(slice_type);
960
961
0
    if (pps->output_flag_present_flag) {
962
0
      out.write_bit(pic_output_flag);
963
0
    }
964
965
0
    if (sps->separate_colour_plane_flag == 1) {
966
0
      out.write_bits(colour_plane_id, 2);
967
0
    }
968
969
970
0
    int NumLtPics = 0;
971
972
0
    if (nal_unit_type != NAL_UNIT_IDR_W_RADL &&
973
0
        nal_unit_type != NAL_UNIT_IDR_N_LP) {
974
0
      out.write_bits(slice_pic_order_cnt_lsb, sps->log2_max_pic_order_cnt_lsb);
975
0
      out.write_bit(short_term_ref_pic_set_sps_flag);
976
977
0
      if (!short_term_ref_pic_set_sps_flag) {
978
        /* TODO
979
        read_short_term_ref_pic_set(ctx, sps,
980
                                    br, &slice_ref_pic_set,
981
                                    sps->num_short_term_ref_pic_sets,
982
                                    sps->ref_pic_sets,
983
                                    true);
984
        */
985
        //CurrRpsIdx = sps->num_short_term_ref_pic_sets;
986
        //CurrRps    = slice_ref_pic_set;
987
0
      }
988
0
      else {
989
0
        int nBits = ceil_log2(sps->num_short_term_ref_pic_sets());
990
0
        if (nBits > 0) out.write_bits(short_term_ref_pic_set_idx, nBits);
991
0
        else { assert(short_term_ref_pic_set_idx==0); }
992
993
0
        if (short_term_ref_pic_set_idx > sps->num_short_term_ref_pic_sets()) {
994
0
          errqueue->add_warning(DE265_WARNING_SHORT_TERM_REF_PIC_SET_OUT_OF_RANGE, false);
995
0
          return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
996
0
        }
997
998
        //CurrRpsIdx = short_term_ref_pic_set_idx;
999
        //CurrRps    = sps->ref_pic_sets[CurrRpsIdx];
1000
0
      }
1001
1002
1003
      // --- long-term MC ---
1004
1005
0
      if (sps->long_term_ref_pics_present_flag) {
1006
0
        if (sps->num_long_term_ref_pics_sps > 0) {
1007
0
          out.write_uvlc(num_long_term_sps);
1008
0
        }
1009
0
        else {
1010
0
          assert(num_long_term_sps == 0);
1011
0
        }
1012
1013
0
        out.write_uvlc(num_long_term_pics);
1014
1015
1016
        // check maximum number of reference frames
1017
1018
0
        if (num_long_term_sps +
1019
0
            num_long_term_pics +
1020
0
            CurrRps.NumNegativePics +
1021
0
            CurrRps.NumPositivePics
1022
0
            > sps->sps_max_dec_pic_buffering[sps->sps_max_sub_layers - 1]) {
1023
0
          errqueue->add_warning(DE265_WARNING_MAX_NUM_REF_PICS_EXCEEDED, false);
1024
0
          return DE265_OK;
1025
0
        }
1026
1027
0
        for (int i = 0; i < num_long_term_sps + num_long_term_pics; i++) {
1028
0
          if (i < num_long_term_sps) {
1029
0
            int nBits = ceil_log2(sps->num_long_term_ref_pics_sps);
1030
0
            out.write_bits(lt_idx_sps[i], nBits);
1031
1032
            // check that the referenced lt-reference really exists
1033
1034
0
            if (lt_idx_sps[i] >= sps->num_long_term_ref_pics_sps) {
1035
0
              errqueue->add_warning(DE265_NON_EXISTING_LT_REFERENCE_CANDIDATE_IN_SLICE_HEADER, false);
1036
0
              return DE265_OK;
1037
0
            }
1038
1039
            //ctx->PocLsbLt[i] = sps->lt_ref_pic_poc_lsb_sps[ lt_idx_sps[i] ];
1040
            //ctx->UsedByCurrPicLt[i] = sps->used_by_curr_pic_lt_sps_flag[ lt_idx_sps[i] ];
1041
0
          }
1042
0
          else {
1043
0
            int nBits = sps->log2_max_pic_order_cnt_lsb;
1044
0
            out.write_bits(poc_lsb_lt[i], nBits);
1045
0
            out.write_bit(used_by_curr_pic_lt_flag[i]);
1046
1047
            //ctx->PocLsbLt[i] = poc_lsb_lt[i];
1048
            //ctx->UsedByCurrPicLt[i] = used_by_curr_pic_lt_flag[i];
1049
0
          }
1050
1051
          //if (ctx->UsedByCurrPicLt[i]) {
1052
          //NumLtPics++;
1053
          //}
1054
1055
0
          out.write_bit(delta_poc_msb_present_flag[i]);
1056
0
          if (delta_poc_msb_present_flag[i]) {
1057
0
            out.write_uvlc(delta_poc_msb_cycle_lt[i]);
1058
0
          }
1059
0
          else {
1060
0
            assert(delta_poc_msb_cycle_lt[i] == 0);
1061
0
          }
1062
1063
          /*
1064
          if (i==0 || i==num_long_term_sps) {
1065
            ctx->DeltaPocMsbCycleLt[i] = delta_poc_msb_cycle_lt[i];
1066
          }
1067
          else {
1068
            ctx->DeltaPocMsbCycleLt[i] = (delta_poc_msb_cycle_lt[i] +
1069
                                          ctx->DeltaPocMsbCycleLt[i-1]);
1070
          }
1071
          */
1072
0
        }
1073
0
      }
1074
0
      else {
1075
0
        assert(num_long_term_sps == 0);
1076
0
        assert(num_long_term_pics== 0);
1077
0
      }
1078
1079
0
      if (sps->sps_temporal_mvp_enabled_flag) {
1080
0
        out.write_bit(slice_temporal_mvp_enabled_flag);
1081
0
      }
1082
0
      else {
1083
0
        assert(slice_temporal_mvp_enabled_flag == 0);
1084
0
      }
1085
0
    }
1086
0
    else {
1087
0
      assert(slice_pic_order_cnt_lsb == 0);
1088
0
      assert(num_long_term_sps == 0);
1089
0
      assert(num_long_term_pics== 0);
1090
0
    }
1091
1092
1093
    // --- SAO ---
1094
1095
0
    if (sps->sample_adaptive_offset_enabled_flag) {
1096
0
      out.write_bit(slice_sao_luma_flag);
1097
0
      out.write_bit(slice_sao_chroma_flag);
1098
0
    }
1099
0
    else {
1100
0
      assert(slice_sao_luma_flag == 0);
1101
0
      assert(slice_sao_chroma_flag== 0);
1102
0
    }
1103
1104
0
    if (slice_type == SLICE_TYPE_P ||
1105
0
        slice_type == SLICE_TYPE_B) {
1106
0
      out.write_bit(num_ref_idx_active_override_flag);
1107
1108
0
      if (num_ref_idx_active_override_flag) {
1109
0
        out.write_uvlc(num_ref_idx_l0_active);
1110
0
        num_ref_idx_l0_active++;;
1111
1112
0
        if (slice_type == SLICE_TYPE_B) {
1113
0
          out.write_uvlc(num_ref_idx_l1_active);
1114
0
          num_ref_idx_l1_active++;
1115
0
        }
1116
0
      }
1117
0
      else {
1118
0
        assert(num_ref_idx_l0_active == pps->num_ref_idx_l0_default_active);
1119
0
        assert(num_ref_idx_l1_active == pps->num_ref_idx_l1_default_active);
1120
0
      }
1121
1122
0
      NumPocTotalCurr = CurrRps.NumPocTotalCurr_shortterm_only + NumLtPics;
1123
1124
0
      if (pps->lists_modification_present_flag && NumPocTotalCurr > 1) {
1125
0
        int nBits = ceil_log2(NumPocTotalCurr);
1126
1127
0
        out.write_bit(ref_pic_list_modification_flag_l0);
1128
0
        if (ref_pic_list_modification_flag_l0) {
1129
0
          for (int i = 0; i < num_ref_idx_l0_active; i++) {
1130
0
            out.write_bits(list_entry_l0[i], nBits);
1131
0
          }
1132
0
        }
1133
1134
0
        if (slice_type == SLICE_TYPE_B) {
1135
0
          out.write_bit(ref_pic_list_modification_flag_l1);
1136
0
          if (ref_pic_list_modification_flag_l1) {
1137
0
            for (int i = 0; i < num_ref_idx_l1_active; i++) {
1138
0
              out.write_bits(list_entry_l1[i], nBits);
1139
0
            }
1140
0
          }
1141
0
        }
1142
0
        else {
1143
0
          assert(ref_pic_list_modification_flag_l1 == 0);
1144
0
        }
1145
0
      }
1146
0
      else {
1147
0
        assert(ref_pic_list_modification_flag_l0 == 0);
1148
0
        assert(ref_pic_list_modification_flag_l1 == 0);
1149
0
      }
1150
1151
0
      if (slice_type == SLICE_TYPE_B) {
1152
0
        out.write_bit(mvd_l1_zero_flag);
1153
0
      }
1154
1155
0
      if (pps->cabac_init_present_flag) {
1156
0
        out.write_bit(cabac_init_flag);
1157
0
      }
1158
0
      else {
1159
0
        assert(cabac_init_flag == 0);
1160
0
      }
1161
1162
0
      if (slice_temporal_mvp_enabled_flag) {
1163
0
        if (slice_type == SLICE_TYPE_B)
1164
0
          out.write_bit(collocated_from_l0_flag);
1165
0
        else { assert(collocated_from_l0_flag == 1); }
1166
1167
0
        if ((collocated_from_l0_flag && num_ref_idx_l0_active > 1) ||
1168
0
            (!collocated_from_l0_flag && num_ref_idx_l1_active > 1)) {
1169
0
          out.write_uvlc(collocated_ref_idx);
1170
0
        }
1171
0
        else {
1172
0
          assert(collocated_ref_idx == 0);
1173
0
        }
1174
0
      }
1175
1176
0
      if ((pps->weighted_pred_flag && slice_type == SLICE_TYPE_P) ||
1177
0
          (pps->weighted_bipred_flag && slice_type == SLICE_TYPE_B)) {
1178
0
        assert(0);
1179
        /* TODO
1180
        if (read_pred_weight_table(br,this,ctx) != DE265_OK)
1181
          {
1182
      ctx->add_warning(DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE, false);
1183
      return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
1184
          }
1185
        */
1186
0
      }
1187
1188
0
      out.write_uvlc(five_minus_max_num_merge_cand);
1189
      //MaxNumMergeCand = 5-five_minus_max_num_merge_cand;
1190
0
    }
1191
1192
0
    out.write_svlc(slice_qp_delta);
1193
1194
0
    if (pps->pps_slice_chroma_qp_offsets_present_flag) {
1195
0
      out.write_svlc(slice_cb_qp_offset);
1196
0
      out.write_svlc(slice_cr_qp_offset);
1197
0
    }
1198
0
    else {
1199
0
      assert(slice_cb_qp_offset == 0);
1200
0
      assert(slice_cr_qp_offset == 0);
1201
0
    }
1202
1203
0
    if (pps->deblocking_filter_override_enabled_flag) {
1204
0
      out.write_bit(deblocking_filter_override_flag);
1205
0
    }
1206
0
    else {
1207
0
      assert(deblocking_filter_override_flag == 0);
1208
0
    }
1209
1210
    //slice_beta_offset = pps->beta_offset;
1211
    //slice_tc_offset   = pps->tc_offset;
1212
1213
0
    if (deblocking_filter_override_flag) {
1214
0
      out.write_bit(slice_deblocking_filter_disabled_flag);
1215
0
      if (!slice_deblocking_filter_disabled_flag) {
1216
0
        out.write_svlc(slice_beta_offset / 2);
1217
0
        out.write_svlc(slice_tc_offset / 2);
1218
0
      }
1219
0
    }
1220
0
    else {
1221
0
      assert(slice_deblocking_filter_disabled_flag == pps->pic_disable_deblocking_filter_flag);
1222
0
    }
1223
1224
0
    if (pps->pps_loop_filter_across_slices_enabled_flag &&
1225
0
        (slice_sao_luma_flag || slice_sao_chroma_flag ||
1226
0
         !slice_deblocking_filter_disabled_flag)) {
1227
0
      out.write_bit(slice_loop_filter_across_slices_enabled_flag);
1228
0
    }
1229
0
    else {
1230
0
      assert(slice_loop_filter_across_slices_enabled_flag ==
1231
0
             pps->pps_loop_filter_across_slices_enabled_flag);
1232
0
    }
1233
0
  }
1234
1235
0
  if (pps->tiles_enabled_flag || pps->entropy_coding_sync_enabled_flag) {
1236
0
    out.write_uvlc(num_entry_point_offsets);
1237
1238
0
    if (num_entry_point_offsets > 0) {
1239
0
      out.write_uvlc(offset_len - 1);
1240
1241
0
      for (uint32_t i = 0; i < num_entry_point_offsets; i++) {
1242
0
        {
1243
0
          uint32_t prev = 0;
1244
0
          if (i > 0) prev = entry_point_offset[i - 1];
1245
0
          out.write_bits(entry_point_offset[i] - prev - 1, offset_len);
1246
0
        }
1247
0
      }
1248
0
    }
1249
0
  }
1250
0
  else {
1251
0
    assert(num_entry_point_offsets == 0);
1252
0
  }
1253
1254
0
  if (pps->slice_segment_header_extension_present_flag) {
1255
0
    out.write_uvlc(slice_segment_header_extension_length);
1256
0
    if (slice_segment_header_extension_length > 1000) {
1257
      // TODO: safety check against too large values
1258
0
      errqueue->add_warning(DE265_WARNING_SLICEHEADER_INVALID, false);
1259
0
      return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
1260
0
    }
1261
1262
0
    for (int i = 0; i < slice_segment_header_extension_length; i++) {
1263
      //slice_segment_header_extension_data_byte[i]
1264
0
      out.skip_bits(8);
1265
0
    }
1266
0
  }
1267
1268
0
  return DE265_OK;
1269
0
}
1270
1271
void slice_segment_header::compute_derived_values(const pic_parameter_set* pps)
1272
3.50k
{
1273
  // --- init variables ---
1274
1275
3.50k
  SliceQPY = pps->pic_init_qp + slice_qp_delta;
1276
1277
3.50k
  switch (slice_type) {
1278
1.42k
    case SLICE_TYPE_I: initType = 0;
1279
1.42k
      break;
1280
610
    case SLICE_TYPE_P: initType = cabac_init_flag + 1;
1281
610
      break;
1282
1.47k
    case SLICE_TYPE_B: initType = 2 - cabac_init_flag;
1283
1.47k
      break;
1284
3.50k
  }
1285
1286
3.50k
  MaxNumMergeCand = 5 - five_minus_max_num_merge_cand;
1287
3.50k
}
1288
1289
1290
//-----------------------------------------------------------------------
1291
1292
1293
void slice_segment_header::dump_slice_segment_header(const decoder_context* ctx, int fd) const
1294
0
{
1295
0
  FILE* fh;
1296
0
  if (fd == 1) fh = stdout;
1297
0
  else if (fd == 2) fh = stderr;
1298
0
  else { return; }
1299
1300
0
#define LOG0(t) log2fh(fh, t)
1301
0
#define LOG1(t,d) log2fh(fh, t,d)
1302
0
#define LOG2(t,d1,d2) log2fh(fh, t,d1,d2)
1303
0
#define LOG3(t,d1,d2,d3) log2fh(fh, t,d1,d2,d3)
1304
0
#define LOG4(t,d1,d2,d3,d4) log2fh(fh, t,d1,d2,d3,d4)
1305
1306
0
  LOG0("----------------- SLICE -----------------\n");
1307
1308
0
  const pic_parameter_set* pps = ctx->get_pps(slice_pic_parameter_set_id);
1309
0
  if (!pps) {
1310
0
    LOG0("invalid PPS referenced\n");
1311
0
    return;
1312
0
  }
1313
0
  assert(pps->pps_read); // TODO: error handling
1314
1315
0
  const seq_parameter_set* sps = ctx->get_sps((int) pps->seq_parameter_set_id);
1316
0
  if (!sps) {
1317
0
    LOG0("invalid SPS referenced\n");
1318
0
    return;
1319
0
  }
1320
0
  assert(sps->sps_read); // TODO: error handling
1321
1322
1323
0
  LOG1("first_slice_segment_in_pic_flag      : %d\n", first_slice_segment_in_pic_flag);
1324
0
  if (ctx->get_nal_unit_type() >= NAL_UNIT_BLA_W_LP &&
1325
0
      ctx->get_nal_unit_type() <= NAL_UNIT_RESERVED_IRAP_VCL23) {
1326
0
    LOG1("no_output_of_prior_pics_flag         : %d\n", no_output_of_prior_pics_flag);
1327
0
  }
1328
1329
0
  LOG1("slice_pic_parameter_set_id           : %d\n", slice_pic_parameter_set_id);
1330
1331
0
  if (!first_slice_segment_in_pic_flag) {
1332
    //if (pps->dependent_slice_segments_enabled_flag) {
1333
0
    LOG1("dependent_slice_segment_flag         : %d\n", dependent_slice_segment_flag);
1334
    //}
1335
0
    LOG1("slice_segment_address                : %d\n", slice_segment_address);
1336
0
  }
1337
1338
  //if (!dependent_slice_segment_flag)
1339
0
  {
1340
    //for (int i=0; i<pps->num_extra_slice_header_bits; i++) {
1341
    //slice_reserved_flag[i]
1342
1343
0
    LOG1("slice_type                           : %c\n",
1344
0
         slice_type == 0 ? 'B' :
1345
0
         slice_type == 1 ? 'P' : 'I');
1346
1347
0
    if (pps->output_flag_present_flag) {
1348
0
      LOG1("pic_output_flag                      : %d\n", pic_output_flag);
1349
0
    }
1350
1351
0
    if (sps->separate_colour_plane_flag == 1) {
1352
0
      LOG1("colour_plane_id                      : %d\n", colour_plane_id);
1353
0
    }
1354
1355
0
    LOG1("slice_pic_order_cnt_lsb              : %d\n", slice_pic_order_cnt_lsb);
1356
1357
0
    if (ctx->get_nal_unit_type() != NAL_UNIT_IDR_W_RADL &&
1358
0
        ctx->get_nal_unit_type() != NAL_UNIT_IDR_N_LP) {
1359
0
      LOG1("short_term_ref_pic_set_sps_flag      : %d\n", short_term_ref_pic_set_sps_flag);
1360
1361
0
      if (!short_term_ref_pic_set_sps_flag) {
1362
0
        LOG1("ref_pic_set[ %2d ]: ", sps->num_short_term_ref_pic_sets());
1363
0
        dump_compact_short_term_ref_pic_set(&slice_ref_pic_set, 16, fh);
1364
0
      }
1365
0
      else if (sps->num_short_term_ref_pic_sets() > 1) {
1366
0
        LOG1("short_term_ref_pic_set_idx           : %d\n", short_term_ref_pic_set_idx);
1367
0
        dump_compact_short_term_ref_pic_set(&sps->ref_pic_sets[short_term_ref_pic_set_idx], 16, fh);
1368
0
      }
1369
1370
0
      if (sps->long_term_ref_pics_present_flag) {
1371
0
        if (sps->num_long_term_ref_pics_sps > 0) {
1372
0
          LOG1("num_long_term_sps                        : %d\n", num_long_term_sps);
1373
0
        }
1374
1375
0
        LOG1("num_long_term_pics                       : %d\n", num_long_term_pics);
1376
1377
#if 0
1378
        for (int i = 0; i < num_long_term_sps + num_long_term_pics; i++) {
1379
          LOG2("PocLsbLt[%d]            : %d\n", i, ctx->PocLsbLt[i]);
1380
          LOG2("UsedByCurrPicLt[%d]     : %d\n", i, ctx->UsedByCurrPicLt[i]);
1381
          LOG2("DeltaPocMsbCycleLt[%d]  : %d\n", i, ctx->DeltaPocMsbCycleLt[i]);
1382
        }
1383
#endif
1384
0
      }
1385
1386
0
      if (sps->sps_temporal_mvp_enabled_flag) {
1387
0
        LOG1("slice_temporal_mvp_enabled_flag : %d\n", slice_temporal_mvp_enabled_flag);
1388
0
      }
1389
0
    }
1390
1391
1392
0
    if (sps->sample_adaptive_offset_enabled_flag) {
1393
0
      LOG1("slice_sao_luma_flag             : %d\n", slice_sao_luma_flag);
1394
0
      LOG1("slice_sao_chroma_flag           : %d\n", slice_sao_chroma_flag);
1395
0
    }
1396
1397
1398
0
    if (slice_type == SLICE_TYPE_P || slice_type == SLICE_TYPE_B) {
1399
0
      LOG1("num_ref_idx_active_override_flag : %d\n", num_ref_idx_active_override_flag);
1400
1401
0
      LOG2("num_ref_idx_l0_active          : %d %s\n", num_ref_idx_l0_active,
1402
0
           num_ref_idx_active_override_flag ? "" : "(from PPS)");
1403
1404
0
      if (slice_type == SLICE_TYPE_B) {
1405
0
        LOG2("num_ref_idx_l1_active          : %d %s\n", num_ref_idx_l1_active,
1406
0
             num_ref_idx_active_override_flag ? "" : "(from PPS)");
1407
0
      }
1408
1409
0
      if (pps->lists_modification_present_flag && NumPocTotalCurr > 1) {
1410
0
        LOG1("ref_pic_list_modification_flag_l0 : %d\n", ref_pic_list_modification_flag_l0);
1411
0
        if (ref_pic_list_modification_flag_l0) {
1412
0
          for (int i = 0; i < num_ref_idx_l0_active; i++) {
1413
0
            LOG2("  %d: %d\n", i, list_entry_l0[i]);
1414
0
          }
1415
0
        }
1416
1417
0
        LOG1("ref_pic_list_modification_flag_l1 : %d\n", ref_pic_list_modification_flag_l1);
1418
0
        if (ref_pic_list_modification_flag_l1) {
1419
0
          for (int i = 0; i < num_ref_idx_l1_active; i++) {
1420
0
            LOG2("  %d: %d\n", i, list_entry_l1[i]);
1421
0
          }
1422
0
        }
1423
0
      }
1424
1425
0
      if (slice_type == SLICE_TYPE_B) {
1426
0
        LOG1("mvd_l1_zero_flag               : %d\n", mvd_l1_zero_flag);
1427
0
      }
1428
1429
0
      LOG1("cabac_init_flag                : %d\n", cabac_init_flag);
1430
1431
0
      if (slice_temporal_mvp_enabled_flag) {
1432
0
        LOG1("collocated_from_l0_flag        : %d\n", collocated_from_l0_flag);
1433
0
        LOG1("collocated_ref_idx             : %d\n", collocated_ref_idx);
1434
0
      }
1435
1436
0
      if ((pps->weighted_pred_flag && slice_type == SLICE_TYPE_P) ||
1437
0
          (pps->weighted_bipred_flag && slice_type == SLICE_TYPE_B)) {
1438
0
        LOG1("luma_log2_weight_denom         : %d\n", luma_log2_weight_denom);
1439
0
        if (sps->chroma_format_idc != 0) {
1440
0
          LOG1("ChromaLog2WeightDenom          : %d\n", ChromaLog2WeightDenom);
1441
0
        }
1442
1443
0
        for (int l = 0; l <= 1; l++)
1444
0
          if (l == 0 || (l == 1 && slice_type == SLICE_TYPE_B)) {
1445
0
            int num_ref = (l == 0 ? num_ref_idx_l0_active - 1 : num_ref_idx_l1_active - 1);
1446
1447
0
            if (false) {
1448
              // do not show these flags
1449
0
              for (int i = 0; i <= num_ref; i++) {
1450
0
                LOG3("luma_weight_flag_l%d[%d]        : %d\n", l, i, luma_weight_flag[l][i]);
1451
0
              }
1452
1453
0
              if (sps->chroma_format_idc != 0) {
1454
0
                for (int i = 0; i <= num_ref; i++) {
1455
0
                  LOG3("chroma_weight_flag_l%d[%d]      : %d\n", l, i, chroma_weight_flag[l][i]);
1456
0
                }
1457
0
              }
1458
0
            }
1459
1460
0
            for (int i = 0; i <= num_ref; i++) {
1461
0
              LOG3("LumaWeight_L%d[%d]             : %d\n", l, i, LumaWeight[l][i]);
1462
0
              LOG3("luma_offset_l%d[%d]            : %d\n", l, i, luma_offset[l][i]);
1463
1464
0
              for (int j = 0; j < 2; j++) {
1465
0
                LOG4("ChromaWeight_L%d[%d][%d]        : %d\n", l, i, j, ChromaWeight[l][i][j]);
1466
0
                LOG4("ChromaOffset_L%d[%d][%d]        : %d\n", l, i, j, ChromaOffset[l][i][j]);
1467
0
              }
1468
0
            }
1469
0
          }
1470
0
      }
1471
1472
0
      LOG1("five_minus_max_num_merge_cand  : %d\n", five_minus_max_num_merge_cand);
1473
0
    }
1474
1475
1476
0
    LOG1("slice_qp_delta         : %d\n", slice_qp_delta);
1477
0
    if (pps->pps_slice_chroma_qp_offsets_present_flag) {
1478
0
      LOG1("slice_cb_qp_offset     : %d\n", slice_cb_qp_offset);
1479
0
      LOG1("slice_cr_qp_offset     : %d\n", slice_cr_qp_offset);
1480
0
    }
1481
1482
0
    if (pps->deblocking_filter_override_enabled_flag) {
1483
0
      LOG1("deblocking_filter_override_flag : %d\n", deblocking_filter_override_flag);
1484
0
    }
1485
1486
0
    LOG2("slice_deblocking_filter_disabled_flag : %d %s\n",
1487
0
         slice_deblocking_filter_disabled_flag,
1488
0
         (deblocking_filter_override_flag ? "(override)" : "(from pps)"));
1489
1490
0
    if (deblocking_filter_override_flag) {
1491
0
      if (!slice_deblocking_filter_disabled_flag) {
1492
0
        LOG1("slice_beta_offset  : %d\n", slice_beta_offset);
1493
0
        LOG1("slice_tc_offset    : %d\n", slice_tc_offset);
1494
0
      }
1495
0
    }
1496
1497
0
    if (pps->pps_loop_filter_across_slices_enabled_flag &&
1498
0
        (slice_sao_luma_flag || slice_sao_chroma_flag ||
1499
0
         !slice_deblocking_filter_disabled_flag)) {
1500
0
      LOG1("slice_loop_filter_across_slices_enabled_flag : %d\n",
1501
0
           slice_loop_filter_across_slices_enabled_flag);
1502
0
    }
1503
0
  }
1504
1505
0
  if (pps->tiles_enabled_flag || pps->entropy_coding_sync_enabled_flag) {
1506
0
    LOG1("num_entry_point_offsets    : %d\n", num_entry_point_offsets);
1507
1508
0
    if (num_entry_point_offsets > 0) {
1509
0
      LOG1("offset_len                 : %d\n", offset_len);
1510
1511
0
      for (uint32_t i = 0; i < num_entry_point_offsets; i++) {
1512
0
        LOG2("entry point [%i] : %d\n", i, entry_point_offset[i]);
1513
0
      }
1514
0
    }
1515
0
  }
1516
1517
  /*
1518
    if( slice_segment_header_extension_present_flag ) {
1519
    slice_segment_header_extension_length
1520
    for( i = 0; i < slice_segment_header_extension_length; i++)
1521
    slice_segment_header_extension_data_byte[i]
1522
    }
1523
    byte_alignment()
1524
    }
1525
  */
1526
1527
0
#undef LOG0
1528
0
#undef LOG1
1529
0
#undef LOG2
1530
0
#undef LOG3
1531
0
#undef LOG4
1532
  //#endif
1533
0
}
1534
1535
1536
void initialize_CABAC_models(thread_context* tctx)
1537
3.50k
{
1538
3.50k
  const int QPY = tctx->shdr->SliceQPY;
1539
3.50k
  const int initType = tctx->shdr->initType;
1540
3.50k
  assert(initType >= 0 && initType <= 2);
1541
1542
3.50k
  tctx->ctx_model.init(initType, QPY);
1543
1544
17.5k
  for (int i = 0; i < 4; i++) {
1545
14.0k
    tctx->StatCoeff[i] = 0;
1546
14.0k
  }
1547
3.50k
}
1548
1549
1550
static int decode_transform_skip_flag(thread_context* tctx, int cIdx)
1551
56.9k
{
1552
56.9k
  const int context = (cIdx == 0) ? 0 : 1;
1553
1554
56.9k
  logtrace(LogSlice, "# transform_skip_flag (context=%d)\n", context);
1555
1556
56.9k
  int bit = tctx->cabac_decoder.decode_bit(
1557
56.9k
                             &tctx->ctx_model[CONTEXT_MODEL_TRANSFORM_SKIP_FLAG + context]);
1558
1559
56.9k
  logtrace(LogSymbols, "$1 transform_skip_flag=%d\n", bit);
1560
1561
56.9k
  return bit;
1562
56.9k
}
1563
1564
1565
static int decode_sao_merge_flag(thread_context* tctx)
1566
101k
{
1567
101k
  logtrace(LogSlice, "# sao_merge_left/up_flag\n");
1568
101k
  int bit = tctx->cabac_decoder.decode_bit(
1569
101k
                             &tctx->ctx_model[CONTEXT_MODEL_SAO_MERGE_FLAG]);
1570
1571
101k
  logtrace(LogSymbols, "$1 sao_merge_flag=%d\n", bit);
1572
1573
101k
  return bit;
1574
101k
}
1575
1576
1577
static uint8_t decode_sao_type_idx(thread_context* tctx)
1578
90.3k
{
1579
90.3k
  logtrace(LogSlice, "# sao_type_idx_luma/chroma\n");
1580
1581
90.3k
  int bit0 = tctx->cabac_decoder.decode_bit(
1582
90.3k
                              &tctx->ctx_model[CONTEXT_MODEL_SAO_TYPE_IDX]);
1583
1584
90.3k
  if (bit0 == 0) {
1585
63.7k
    logtrace(LogSymbols, "$1 sao_type_idx=%d\n", 0);
1586
63.7k
    return 0;
1587
63.7k
  }
1588
26.6k
  else {
1589
26.6k
    int bit1 = tctx->cabac_decoder.decode_bypass();
1590
26.6k
    if (bit1 == 0) {
1591
24.2k
      logtrace(LogSymbols, "$1 sao_type_idx=%d\n", 1);
1592
24.2k
      return 1;
1593
24.2k
    }
1594
2.40k
    else {
1595
2.40k
      logtrace(LogSymbols, "$1 sao_type_idx=%d\n", 2);
1596
2.40k
      return 2;
1597
2.40k
    }
1598
26.6k
  }
1599
90.3k
}
1600
1601
1602
static uint8_t decode_sao_offset_abs(thread_context* tctx, int bitDepth)
1603
156k
{
1604
156k
  logtrace(LogSlice, "# sao_offset_abs\n");
1605
156k
  int cMax = (1 << (std::min(bitDepth, 10) - 5)) - 1;
1606
156k
  assert(cMax >= 7 && cMax<=31);
1607
156k
  uint8_t value = static_cast<uint8_t>(tctx->cabac_decoder.decode_TU_bypass( cMax));
1608
156k
  logtrace(LogSymbols, "$1 sao_offset_abs=%d\n", value);
1609
156k
  return value;
1610
156k
}
1611
1612
1613
static int decode_sao_class(thread_context* tctx)
1614
2.40k
{
1615
2.40k
  logtrace(LogSlice, "# sao_class\n");
1616
2.40k
  int value = tctx->cabac_decoder.decode_FL_bypass( 2);
1617
2.40k
  logtrace(LogSymbols, "$1 sao_class=%d\n", value);
1618
2.40k
  return value;
1619
2.40k
}
1620
1621
1622
static int decode_sao_offset_sign(thread_context* tctx)
1623
4.63k
{
1624
4.63k
  logtrace(LogSlice, "# sao_offset_sign\n");
1625
4.63k
  int value = tctx->cabac_decoder.decode_bypass();
1626
4.63k
  logtrace(LogSymbols, "$1 sao_offset_sign=%d\n", value);
1627
4.63k
  return value;
1628
4.63k
}
1629
1630
1631
static int decode_sao_band_position(thread_context* tctx)
1632
35.7k
{
1633
35.7k
  logtrace(LogSlice, "# sao_band_position\n");
1634
35.7k
  int value = tctx->cabac_decoder.decode_FL_bypass( 5);
1635
35.7k
  logtrace(LogSymbols, "$1 sao_band_position=%d\n", value);
1636
35.7k
  return value;
1637
35.7k
}
1638
1639
1640
static int decode_transquant_bypass_flag(thread_context* tctx)
1641
1.13M
{
1642
1.13M
  logtrace(LogSlice, "# cu_transquant_bypass_enable_flag\n");
1643
1.13M
  int value = tctx->cabac_decoder.decode_bit(
1644
1.13M
                               &tctx->ctx_model[CONTEXT_MODEL_CU_TRANSQUANT_BYPASS_FLAG]);
1645
1.13M
  logtrace(LogSymbols, "$1 transquant_bypass_flag=%d\n", value);
1646
1.13M
  return value;
1647
1.13M
}
1648
1649
1650
#include <sys/types.h>
1651
#include <signal.h>
1652
1653
static int decode_split_cu_flag(thread_context* tctx,
1654
                                int x0, int y0, int ctDepth)
1655
549k
{
1656
  // check if neighbors are available
1657
1658
549k
  int availableL = check_CTB_available(tctx->img, x0, y0, x0 - 1, y0);
1659
549k
  int availableA = check_CTB_available(tctx->img, x0, y0, x0, y0 - 1);
1660
1661
549k
  int condL = 0;
1662
549k
  int condA = 0;
1663
1664
549k
  if (availableL && tctx->img->get_ctDepth(x0 - 1, y0) > ctDepth) condL = 1;
1665
549k
  if (availableA && tctx->img->get_ctDepth(x0, y0 - 1) > ctDepth) condA = 1;
1666
1667
549k
  int contextOffset = condL + condA;
1668
549k
  int context = contextOffset;
1669
1670
  // decode bit
1671
1672
549k
  logtrace(LogSlice, "# split_cu_flag context=%d R=%x\n", context, tctx->cabac_decoder.range);
1673
1674
549k
  int bit = tctx->cabac_decoder.decode_bit( &tctx->ctx_model[CONTEXT_MODEL_SPLIT_CU_FLAG + context]);
1675
1676
549k
  logtrace(LogSlice, "> split_cu_flag R=%x, ctx=%d, bit=%d\n", tctx->cabac_decoder.range, context, bit);
1677
1678
549k
  logtrace(LogSymbols, "$1 split_cu_flag=%d\n", bit);
1679
1680
549k
  return bit;
1681
549k
}
1682
1683
1684
static int decode_cu_skip_flag(thread_context* tctx,
1685
                               int x0, int y0, int ctDepth)
1686
805k
{
1687
  // check if neighbors are available
1688
1689
805k
  int availableL = check_CTB_available(tctx->img, x0, y0, x0 - 1, y0);
1690
805k
  int availableA = check_CTB_available(tctx->img, x0, y0, x0, y0 - 1);
1691
1692
805k
  int condL = 0;
1693
805k
  int condA = 0;
1694
1695
805k
  if (availableL && tctx->img->get_cu_skip_flag(x0 - 1, y0)) condL = 1;
1696
805k
  if (availableA && tctx->img->get_cu_skip_flag(x0, y0 - 1)) condA = 1;
1697
1698
805k
  int contextOffset = condL + condA;
1699
805k
  int context = contextOffset;
1700
1701
  // decode bit
1702
1703
805k
  logtrace(LogSlice, "# cu_skip_flag context=%d R=%x\n", context, tctx->cabac_decoder.range);
1704
1705
805k
  int bit = tctx->cabac_decoder.decode_bit( &tctx->ctx_model[CONTEXT_MODEL_CU_SKIP_FLAG + context]);
1706
1707
805k
  logtrace(LogSlice, "> cu_skip_flag R=%x, ctx=%d, bit=%d\n", tctx->cabac_decoder.range, context, bit);
1708
1709
805k
  logtrace(LogSymbols, "$1 cu_skip_flag=%d\n", bit);
1710
1711
805k
  return bit;
1712
805k
}
1713
1714
1715
static enum PartMode decode_part_mode(thread_context* tctx,
1716
                                      enum PredMode pred_mode, int cLog2CbSize)
1717
1.04M
{
1718
1.04M
  de265_image* img = tctx->img;
1719
1720
1.04M
  if (pred_mode == MODE_INTRA) {
1721
684k
    logtrace(LogSlice, "# part_mode (INTRA)\n");
1722
1723
684k
    int bit = tctx->cabac_decoder.decode_bit( &tctx->ctx_model[CONTEXT_MODEL_PART_MODE]);
1724
1725
684k
    logtrace(LogSlice, "> %s\n", bit ? "2Nx2N" : "NxN");
1726
1727
684k
    logtrace(LogSymbols, "$1 part_mode=%d\n", bit ? PART_2Nx2N : PART_NxN);
1728
1729
684k
    return bit ? PART_2Nx2N : PART_NxN;
1730
684k
  }
1731
361k
  else {
1732
361k
    const seq_parameter_set& sps = img->get_sps();
1733
1734
361k
    int bit0 = tctx->cabac_decoder.decode_bit( &tctx->ctx_model[CONTEXT_MODEL_PART_MODE + 0]);
1735
361k
    if (bit0) {
1736
133k
      logtrace(LogSymbols, "$1 part_mode=%d\n", PART_2Nx2N);
1737
133k
      return PART_2Nx2N;
1738
133k
    }
1739
1740
    // CHECK_ME: I optimize code and fix bug here, need more VERIFY!
1741
228k
    int bit1 = tctx->cabac_decoder.decode_bit( &tctx->ctx_model[CONTEXT_MODEL_PART_MODE + 1]);
1742
228k
    if (cLog2CbSize > sps.Log2MinCbSizeY) {
1743
41.2k
      if (!sps.amp_enabled_flag) {
1744
5.64k
        logtrace(LogSymbols, "$1 part_mode=%d\n", bit1 ? PART_2NxN : PART_Nx2N);
1745
5.64k
        return bit1 ? PART_2NxN : PART_Nx2N;
1746
5.64k
      }
1747
35.5k
      else {
1748
35.5k
        int bit3 = tctx->cabac_decoder.decode_bit( &tctx->ctx_model[CONTEXT_MODEL_PART_MODE + 3]);
1749
35.5k
        if (bit3) {
1750
15.0k
          logtrace(LogSymbols, "$1 part_mode=%d\n", bit1 ? PART_2NxN : PART_Nx2N);
1751
15.0k
          return bit1 ? PART_2NxN : PART_Nx2N;
1752
15.0k
        }
1753
1754
20.5k
        int bit4 = tctx->cabac_decoder.decode_bypass();
1755
20.5k
        if (bit1 && bit4) {
1756
1.53k
          logtrace(LogSymbols, "$1 part_mode=%d\n", PART_2NxnD);
1757
1.53k
          return PART_2NxnD;
1758
1.53k
        }
1759
19.0k
        if (bit1 && !bit4) {
1760
9.25k
          logtrace(LogSymbols, "$1 part_mode=%d\n", PART_2NxnU);
1761
9.25k
          return PART_2NxnU;
1762
9.25k
        }
1763
9.76k
        if (!bit1 && !bit4) {
1764
8.43k
          logtrace(LogSymbols, "$1 part_mode=%d\n", PART_nLx2N);
1765
8.43k
          return PART_nLx2N;
1766
8.43k
        }
1767
1.32k
        if (!bit1 && bit4) {
1768
1.32k
          logtrace(LogSymbols, "$1 part_mode=%d\n", PART_nRx2N);
1769
1.32k
          return PART_nRx2N;
1770
1.32k
        }
1771
1.32k
      }
1772
41.2k
    }
1773
187k
    else {
1774
      // TODO, we could save one if here when first decoding the next bin and then
1775
      // checkcLog2CbSize==3 when it is '0'
1776
1777
187k
      if (bit1) {
1778
80.7k
        logtrace(LogSymbols, "$1 part_mode=%d\n", PART_2NxN);
1779
80.7k
        return PART_2NxN;
1780
80.7k
      }
1781
1782
106k
      if (cLog2CbSize == 3) {
1783
106k
        logtrace(LogSymbols, "$1 part_mode=%d\n", PART_Nx2N);
1784
106k
        return PART_Nx2N;
1785
106k
      }
1786
52
      else {
1787
52
        int bit2 = tctx->cabac_decoder.decode_bit( &tctx->ctx_model[CONTEXT_MODEL_PART_MODE + 2]);
1788
52
        logtrace(LogSymbols, "$1 part_mode=%d\n", PART_NxN - bit2);
1789
52
        return (enum PartMode) ((int) PART_NxN - bit2)/*bit2 ? PART_Nx2N : PART_NxN*/;
1790
52
      }
1791
106k
    }
1792
228k
  }
1793
1794
1.04M
  assert(false); // should never be reached
1795
0
  return PART_2Nx2N;
1796
0
}
1797
1798
1799
static inline int decode_prev_intra_luma_pred_flag(thread_context* tctx)
1800
2.30M
{
1801
2.30M
  logtrace(LogSlice, "# prev_intra_luma_pred_flag\n");
1802
2.30M
  int bit = tctx->cabac_decoder.decode_bit( &tctx->ctx_model[CONTEXT_MODEL_PREV_INTRA_LUMA_PRED_FLAG]);
1803
2.30M
  logtrace(LogSymbols, "$1 prev_intra_luma_pred_flag=%d\n", bit);
1804
2.30M
  return bit;
1805
2.30M
}
1806
1807
1808
static inline int decode_mpm_idx(thread_context* tctx)
1809
747k
{
1810
747k
  logtrace(LogSlice, "# mpm_idx (TU:2)\n");
1811
747k
  int mpm = tctx->cabac_decoder.decode_TU_bypass( 2);
1812
747k
  logtrace(LogSlice, "> mpm_idx = %d\n", mpm);
1813
747k
  logtrace(LogSymbols, "$1 mpm_idx=%d\n", mpm);
1814
747k
  return mpm;
1815
747k
}
1816
1817
1818
static inline int decode_rem_intra_luma_pred_mode(thread_context* tctx)
1819
1.56M
{
1820
1.56M
  logtrace(LogSlice, "# rem_intra_luma_pred_mode (5 bits)\n");
1821
1.56M
  int value = tctx->cabac_decoder.decode_FL_bypass( 5);
1822
1.56M
  logtrace(LogSymbols, "$1 rem_intra_luma_pred_mode=%d\n", value);
1823
1.56M
  return value;
1824
1.56M
}
1825
1826
1827
static int decode_intra_chroma_pred_mode(thread_context* tctx)
1828
714k
{
1829
714k
  logtrace(LogSlice, "# intra_chroma_pred_mode\n");
1830
1831
714k
  int prefix = tctx->cabac_decoder.decode_bit( &tctx->ctx_model[CONTEXT_MODEL_INTRA_CHROMA_PRED_MODE]);
1832
1833
714k
  int mode;
1834
714k
  if (prefix == 0) {
1835
371k
    mode = 4;
1836
371k
  }
1837
343k
  else {
1838
343k
    mode = tctx->cabac_decoder.decode_FL_bypass( 2);
1839
343k
  }
1840
1841
714k
  logtrace(LogSlice, "> intra_chroma_pred_mode = %d\n", mode);
1842
714k
  logtrace(LogSymbols, "$1 intra_chroma_pred_mode=%d\n", mode);
1843
1844
714k
  return mode;
1845
714k
}
1846
1847
1848
static int decode_split_transform_flag(thread_context* tctx,
1849
                                       int log2TrafoSize)
1850
162k
{
1851
162k
  logtrace(LogSlice, "# split_transform_flag (log2TrafoSize=%d)\n", log2TrafoSize);
1852
1853
162k
  int context = 5 - log2TrafoSize;
1854
162k
  assert(context >= 0 && context <= 2);
1855
1856
162k
  logtrace(LogSlice, "# context: %d\n", context);
1857
1858
162k
  int bit = tctx->cabac_decoder.decode_bit( &tctx->ctx_model[CONTEXT_MODEL_SPLIT_TRANSFORM_FLAG + context]);
1859
162k
  logtrace(LogSymbols, "$1 split_transform_flag=%d\n", bit);
1860
162k
  return bit;
1861
162k
}
1862
1863
1864
static int decode_cbf_chroma(thread_context* tctx,
1865
                             int trafoDepth)
1866
1.90M
{
1867
1.90M
  logtrace(LogSlice, "# cbf_chroma\n");
1868
1869
1.90M
  int bit = tctx->cabac_decoder.decode_bit( &tctx->ctx_model[CONTEXT_MODEL_CBF_CHROMA + trafoDepth]);
1870
1871
1.90M
  logtrace(LogSymbols, "$1 cbf_chroma=%d\n", bit);
1872
1.90M
  return bit;
1873
1.90M
}
1874
1875
1876
static int decode_cbf_luma(thread_context* tctx,
1877
                           int trafoDepth)
1878
2.91M
{
1879
2.91M
  logtrace(LogSlice, "# cbf_luma\n");
1880
1881
2.91M
  int bit = tctx->cabac_decoder.decode_bit( &tctx->ctx_model[CONTEXT_MODEL_CBF_LUMA + (trafoDepth == 0)]);
1882
1883
2.91M
  logtrace(LogSlice, "> cbf_luma = %d\n", bit);
1884
1885
2.91M
  logtrace(LogSymbols, "$1 cbf_luma=%d\n", bit);
1886
2.91M
  return bit;
1887
2.91M
}
1888
1889
1890
static inline int decode_coded_sub_block_flag(thread_context* tctx,
1891
                                              int cIdx,
1892
                                              uint8_t coded_sub_block_neighbors)
1893
1.27M
{
1894
1.27M
  logtrace(LogSlice, "# coded_sub_block_flag\n");
1895
1896
  // tricky computation of csbfCtx
1897
1.27M
  int csbfCtx = ((coded_sub_block_neighbors & 1) | // right neighbor set  or
1898
1.27M
                 (coded_sub_block_neighbors >> 1)); // bottom neighbor set   -> csbfCtx=1
1899
1900
1.27M
  int ctxIdxInc = csbfCtx;
1901
1.27M
  if (cIdx != 0) {
1902
6.42k
    ctxIdxInc += 2;
1903
6.42k
  }
1904
1905
1.27M
  int bit = tctx->cabac_decoder.decode_bit(
1906
1.27M
                             &tctx->ctx_model[CONTEXT_MODEL_CODED_SUB_BLOCK_FLAG + ctxIdxInc]);
1907
1908
1.27M
  logtrace(LogSymbols, "$1 coded_sub_block_flag=%d\n", bit);
1909
1.27M
  return bit;
1910
1.27M
}
1911
1912
1913
static const uint8_t CABAC_QP_DELTA_ABS_ERROR = 0xFF;
1914
1915
static uint8_t decode_cu_qp_delta_abs(thread_context* tctx)
1916
429k
{
1917
429k
  logtrace(LogSlice, "# cu_qp_delta_abs\n");
1918
1919
429k
  int bit = tctx->cabac_decoder.decode_bit(
1920
429k
                             &tctx->ctx_model[CONTEXT_MODEL_CU_QP_DELTA_ABS + 0]);
1921
429k
  if (bit == 0) {
1922
54.9k
    logtrace(LogSymbols, "$1 cu_qp_delta_abs=%d\n", 0);
1923
54.9k
    return 0;
1924
54.9k
  }
1925
1926
374k
  uint8_t prefix = 1;
1927
1.44M
  for (uint8_t i = 0; i < 4; i++) {
1928
1.18M
    bit = tctx->cabac_decoder.decode_bit(
1929
1.18M
                           &tctx->ctx_model[CONTEXT_MODEL_CU_QP_DELTA_ABS + 1]);
1930
1.18M
    if (bit == 0) { break; }
1931
1.07M
    else { prefix++; }
1932
1.18M
  }
1933
1934
374k
  if (prefix == 5) {
1935
266k
    uint32_t value = tctx->cabac_decoder.decode_EGk_bypass( 0);
1936
266k
    if (value >= 250) { return CABAC_QP_DELTA_ABS_ERROR; }
1937
266k
    logtrace(LogSymbols, "$1 cu_qp_delta_abs=%d\n", value + 5);
1938
266k
    return value + 5;
1939
266k
  }
1940
107k
  else {
1941
107k
    logtrace(LogSymbols, "$1 cu_qp_delta_abs=%d\n", prefix);
1942
107k
    return prefix;
1943
107k
  }
1944
374k
}
1945
1946
1947
static int decode_last_significant_coeff_prefix(thread_context* tctx,
1948
                                                int log2TrafoSize,
1949
                                                int cIdx,
1950
                                                context_model* model)
1951
6.88M
{
1952
6.88M
  logtrace(LogSlice, "# last_significant_coeff_prefix log2TrafoSize:%d cIdx:%d\n", log2TrafoSize, cIdx);
1953
1954
6.88M
  int cMax = (log2TrafoSize << 1) - 1;
1955
1956
6.88M
  int ctxOffset, ctxShift;
1957
6.88M
  if (cIdx == 0) {
1958
4.94M
    ctxOffset = 3 * (log2TrafoSize - 2) + ((log2TrafoSize - 1) >> 2);
1959
4.94M
    ctxShift = (log2TrafoSize + 1) >> 2;
1960
4.94M
  }
1961
1.94M
  else {
1962
1.94M
    ctxOffset = 15;
1963
1.94M
    ctxShift = log2TrafoSize - 2;
1964
1.94M
  }
1965
1966
6.88M
  int binIdx;
1967
6.88M
  int value = cMax;
1968
22.7M
  for (binIdx = 0; binIdx < cMax; binIdx++) {
1969
19.0M
    int ctxIdxInc = (binIdx >> ctxShift);
1970
1971
19.0M
    logtrace(LogSlice, "context: %d+%d\n", ctxOffset, ctxIdxInc);
1972
1973
19.0M
    int bit = tctx->cabac_decoder.decode_bit( &model[ctxOffset + ctxIdxInc]);
1974
19.0M
    if (bit == 0) {
1975
3.16M
      value = binIdx;
1976
3.16M
      break;
1977
3.16M
    }
1978
19.0M
  }
1979
1980
6.88M
  logtrace(LogSlice, "> last_significant_coeff_prefix: %d\n", value);
1981
1982
6.88M
  return value;
1983
6.88M
}
1984
1985
1986
static const uint8_t ctxIdxMap[16] = {
1987
  0, 1, 4, 5,
1988
  2, 3, 4, 5,
1989
  6, 6, 8, 8,
1990
  7, 7, 8, 99
1991
};
1992
1993
uint8_t* ctxIdxLookup[4 /* 4-log2-32 */][2 /* !!cIdx */][2 /* !!scanIdx */][4 /* prevCsbf */];
1994
1995
bool alloc_and_init_significant_coeff_ctxIdx_lookupTable()
1996
2
{
1997
2
  int tableSize = 4 * 4 * (2) + 8 * 8 * (2 * 2 * 4) + 16 * 16 * (2 * 4) + 32 * 32 * (2 * 4);
1998
1999
2
  uint8_t* p = (uint8_t*) malloc(tableSize);
2000
2
  if (p == nullptr) {
2001
0
    return false;
2002
0
  }
2003
2004
2
  memset(p, 0xFF, tableSize); // just for debugging
2005
2006
2007
  // --- Set pointers to memory areas. Note that some parameters share the same memory. ---
2008
2009
  // 4x4
2010
2011
6
  for (int cIdx = 0; cIdx < 2; cIdx++) {
2012
12
    for (int scanIdx = 0; scanIdx < 2; scanIdx++)
2013
40
      for (int prevCsbf = 0; prevCsbf < 4; prevCsbf++)
2014
32
        ctxIdxLookup[0][cIdx][scanIdx][prevCsbf] = p;
2015
2016
4
    p += 4 * 4;
2017
4
  }
2018
2019
  // 8x8
2020
2021
6
  for (int cIdx = 0; cIdx < 2; cIdx++)
2022
12
    for (int scanIdx = 0; scanIdx < 2; scanIdx++)
2023
40
      for (int prevCsbf = 0; prevCsbf < 4; prevCsbf++) {
2024
32
        ctxIdxLookup[1][cIdx][scanIdx][prevCsbf] = p;
2025
32
        p += 8 * 8;
2026
32
      }
2027
2028
  // 16x16
2029
2030
6
  for (int cIdx = 0; cIdx < 2; cIdx++)
2031
20
    for (int prevCsbf = 0; prevCsbf < 4; prevCsbf++) {
2032
48
      for (int scanIdx = 0; scanIdx < 2; scanIdx++) {
2033
32
        ctxIdxLookup[2][cIdx][scanIdx][prevCsbf] = p;
2034
32
      }
2035
2036
16
      p += 16 * 16;
2037
16
    }
2038
2039
  // 32x32
2040
2041
6
  for (int cIdx = 0; cIdx < 2; cIdx++)
2042
20
    for (int prevCsbf = 0; prevCsbf < 4; prevCsbf++) {
2043
48
      for (int scanIdx = 0; scanIdx < 2; scanIdx++) {
2044
32
        ctxIdxLookup[3][cIdx][scanIdx][prevCsbf] = p;
2045
32
      }
2046
2047
16
      p += 32 * 32;
2048
16
    }
2049
2050
2051
  // --- precompute ctxIdx tables ---
2052
2053
10
  for (int log2w = 2; log2w <= 5; log2w++)
2054
24
    for (int cIdx = 0; cIdx < 2; cIdx++)
2055
48
      for (int scanIdx = 0; scanIdx < 2; scanIdx++)
2056
160
        for (int prevCsbf = 0; prevCsbf < 4; prevCsbf++) {
2057
2.04k
          for (int yC = 0; yC < (1 << log2w); yC++)
2058
45.4k
            for (int xC = 0; xC < (1 << log2w); xC++) {
2059
43.5k
              int w = 1 << log2w;
2060
43.5k
              int sbWidth = w >> 2;
2061
2062
43.5k
              int sigCtx;
2063
2064
              // if log2TrafoSize==2
2065
43.5k
              if (sbWidth == 1) {
2066
512
                sigCtx = ctxIdxMap[(yC << 2) + xC];
2067
512
              }
2068
43.0k
              else if (xC + yC == 0) {
2069
96
                sigCtx = 0;
2070
96
              }
2071
42.9k
              else {
2072
42.9k
                int xS = xC >> 2;
2073
42.9k
                int yS = yC >> 2;
2074
                /*
2075
                  int prevCsbf = 0;
2076
2077
                  if (xS < sbWidth-1) { prevCsbf += coded_sub_block_flag[xS+1  +yS*sbWidth];    }
2078
                  if (yS < sbWidth-1) { prevCsbf += coded_sub_block_flag[xS+(1+yS)*sbWidth]<<1; }
2079
                */
2080
42.9k
                int xP = xC & 3;
2081
42.9k
                int yP = yC & 3;
2082
2083
                //logtrace(LogSlice,"posInSubset: %d,%d\n",xP,yP);
2084
                //logtrace(LogSlice,"prevCsbf: %d\n",prevCsbf);
2085
2086
42.9k
                switch (prevCsbf) {
2087
10.7k
                  case 0:
2088
10.7k
                    sigCtx = (xP + yP >= 3) ? 0 : (xP + yP > 0) ? 1 : 2;
2089
10.7k
                    break;
2090
10.7k
                  case 1:
2091
10.7k
                    sigCtx = (yP == 0) ? 2 : (yP == 1) ? 1 : 0;
2092
10.7k
                    break;
2093
10.7k
                  case 2:
2094
10.7k
                    sigCtx = (xP == 0) ? 2 : (xP == 1) ? 1 : 0;
2095
10.7k
                    break;
2096
10.7k
                  default:
2097
10.7k
                    sigCtx = 2;
2098
10.7k
                    break;
2099
42.9k
                }
2100
2101
                //logtrace(LogSlice,"a) sigCtx=%d\n",sigCtx);
2102
2103
42.9k
                if (cIdx == 0) {
2104
21.4k
                  if (xS + yS > 0) sigCtx += 3;
2105
2106
                  //logtrace(LogSlice,"b) sigCtx=%d\n",sigCtx);
2107
2108
                  // if log2TrafoSize==3
2109
21.4k
                  if (sbWidth == 2) {
2110
                    // 8x8 block
2111
1.00k
                    sigCtx += (scanIdx == 0) ? 9 : 15;
2112
1.00k
                  }
2113
20.4k
                  else {
2114
20.4k
                    sigCtx += 21;
2115
20.4k
                  }
2116
2117
                  //logtrace(LogSlice,"c) sigCtx=%d\n",sigCtx);
2118
21.4k
                }
2119
21.4k
                else {
2120
                  // if log2TrafoSize==3
2121
21.4k
                  if (sbWidth == 2) {
2122
                    // 8x8 block
2123
1.00k
                    sigCtx += 9;
2124
1.00k
                  }
2125
20.4k
                  else {
2126
20.4k
                    sigCtx += 12;
2127
20.4k
                  }
2128
21.4k
                }
2129
42.9k
              }
2130
2131
43.5k
              int ctxIdxInc;
2132
43.5k
              if (cIdx == 0) { ctxIdxInc = sigCtx; }
2133
21.7k
              else { ctxIdxInc = 27 + sigCtx; }
2134
2135
43.5k
              if (ctxIdxLookup[log2w - 2][cIdx][scanIdx][prevCsbf][xC + (yC << log2w)] != 0xFF) {
2136
20.9k
                assert(ctxIdxLookup[log2w-2][cIdx][scanIdx][prevCsbf][xC+(yC<<log2w)] == ctxIdxInc);
2137
20.9k
              }
2138
2139
43.5k
              ctxIdxLookup[log2w - 2][cIdx][scanIdx][prevCsbf][xC + (yC << log2w)] = ctxIdxInc;
2140
2141
              //NOTE: when using this option, we have to include all three scanIdx in the table
2142
              //ctxIdxLookup[log2w-2][cIdx][scanIdx][prevCsbf][s] = ctxIdxInc;
2143
43.5k
            }
2144
128
        }
2145
2146
2
  return true;
2147
2
}
2148
2149
2150
bool alloc_and_init_significant_coeff_ctxIdx_lookupTable_OLD()
2151
0
{
2152
0
  int tableSize = 2 * 2 * 4 * (4 * 4 + 8 * 8 + 16 * 16 + 32 * 32);
2153
0
  uint8_t* p = (uint8_t*) malloc(tableSize);
2154
0
  if (p == nullptr) {
2155
0
    return false;
2156
0
  }
2157
2158
0
  for (int log2w = 2; log2w <= 5; log2w++)
2159
0
    for (int cIdx = 0; cIdx < 2; cIdx++)
2160
0
      for (int scanIdx = 0; scanIdx < 2; scanIdx++)
2161
0
        for (int prevCsbf = 0; prevCsbf < 4; prevCsbf++) {
2162
          // assign pointer into reserved memory area
2163
2164
0
          ctxIdxLookup[log2w - 2][cIdx][scanIdx][prevCsbf] = p;
2165
0
          p += (1 << log2w) * (1 << log2w);
2166
2167
0
          const position* ScanOrderSub = get_scan_order(log2w - 2, scanIdx);
2168
0
          const position* ScanOrderPos = get_scan_order(2, scanIdx);
2169
2170
          //for (int yC=0;yC<(1<<log2w);yC++)
2171
          // for (int xC=0;xC<(1<<log2w);xC++)
2172
0
          for (int s = 0; s < (1 << log2w) * (1 << log2w); s++) {
2173
0
            position S = ScanOrderSub[s >> 4];
2174
0
            int x0 = S.x << 2;
2175
0
            int y0 = S.y << 2;
2176
2177
0
            int subX = ScanOrderPos[s & 0xF].x;
2178
0
            int subY = ScanOrderPos[s & 0xF].y;
2179
0
            int xC = x0 + subX;
2180
0
            int yC = y0 + subY;
2181
2182
2183
0
            int w = 1 << log2w;
2184
0
            int sbWidth = w >> 2;
2185
2186
0
            int sigCtx;
2187
2188
            // if log2TrafoSize==2
2189
0
            if (sbWidth == 1) {
2190
0
              sigCtx = ctxIdxMap[(yC << 2) + xC];
2191
0
            }
2192
0
            else if (xC + yC == 0) {
2193
0
              sigCtx = 0;
2194
0
            }
2195
0
            else {
2196
0
              int xS = xC >> 2;
2197
0
              int yS = yC >> 2;
2198
              /*
2199
                int prevCsbf = 0;
2200
2201
                if (xS < sbWidth-1) { prevCsbf += coded_sub_block_flag[xS+1  +yS*sbWidth];    }
2202
                if (yS < sbWidth-1) { prevCsbf += coded_sub_block_flag[xS+(1+yS)*sbWidth]<<1; }
2203
              */
2204
0
              int xP = xC & 3;
2205
0
              int yP = yC & 3;
2206
2207
0
              logtrace(LogSlice, "posInSubset: %d,%d\n", xP, yP);
2208
0
              logtrace(LogSlice, "prevCsbf: %d\n", prevCsbf);
2209
2210
              //printf("%d | %d %d\n",prevCsbf,xP,yP);
2211
2212
0
              switch (prevCsbf) {
2213
0
                case 0:
2214
                  //sigCtx = (xP+yP==0) ? 2 : (xP+yP<3) ? 1 : 0;
2215
0
                  sigCtx = (xP + yP >= 3) ? 0 : (xP + yP > 0) ? 1 : 2;
2216
0
                  break;
2217
0
                case 1:
2218
0
                  sigCtx = (yP == 0) ? 2 : (yP == 1) ? 1 : 0;
2219
0
                  break;
2220
0
                case 2:
2221
0
                  sigCtx = (xP == 0) ? 2 : (xP == 1) ? 1 : 0;
2222
0
                  break;
2223
0
                default:
2224
0
                  sigCtx = 2;
2225
0
                  break;
2226
0
              }
2227
2228
0
              logtrace(LogSlice, "a) sigCtx=%d\n", sigCtx);
2229
2230
0
              if (cIdx == 0) {
2231
0
                if (xS + yS > 0) sigCtx += 3;
2232
2233
0
                logtrace(LogSlice, "b) sigCtx=%d\n", sigCtx);
2234
2235
                // if log2TrafoSize==3
2236
0
                if (sbWidth == 2) {
2237
                  // 8x8 block
2238
0
                  sigCtx += (scanIdx == 0) ? 9 : 15;
2239
0
                }
2240
0
                else {
2241
0
                  sigCtx += 21;
2242
0
                }
2243
2244
0
                logtrace(LogSlice, "c) sigCtx=%d\n", sigCtx);
2245
0
              }
2246
0
              else {
2247
                // if log2TrafoSize==3
2248
0
                if (sbWidth == 2) {
2249
                  // 8x8 block
2250
0
                  sigCtx += 9;
2251
0
                }
2252
0
                else {
2253
0
                  sigCtx += 12;
2254
0
                }
2255
0
              }
2256
0
            }
2257
2258
0
            int ctxIdxInc;
2259
0
            if (cIdx == 0) { ctxIdxInc = sigCtx; }
2260
0
            else { ctxIdxInc = 27 + sigCtx; }
2261
2262
2263
0
            ctxIdxLookup[log2w - 2][cIdx][scanIdx][prevCsbf][xC + (yC << log2w)] = ctxIdxInc;
2264
2265
            //NOTE: when using this option, we have to include all three scanIdx in the table
2266
            //ctxIdxLookup[log2w-2][cIdx][scanIdx][prevCsbf][s] = ctxIdxInc;
2267
0
          }
2268
0
        }
2269
2270
0
  return true;
2271
0
}
2272
2273
void free_significant_coeff_ctxIdx_lookupTable()
2274
0
{
2275
0
  free(ctxIdxLookup[0][0][0][0]);
2276
0
  ctxIdxLookup[0][0][0][0] = nullptr;
2277
0
}
2278
2279
2280
#if 0
2281
static int decode_significant_coeff_flag(thread_context* tctx,
2282
                                         int xC, int yC,
2283
                                         const uint8_t* coded_sub_block_flag,
2284
                                         int sbWidth,
2285
                                         int cIdx,
2286
                                         int scanIdx)
2287
{
2288
  logtrace(LogSlice, "# significant_coeff_flag (xC:%d yC:%d sbWidth:%d cIdx:%d scanIdx:%d)\n",
2289
           xC, yC, sbWidth, cIdx, scanIdx);
2290
2291
  int sigCtx;
2292
2293
  // if log2TrafoSize==2
2294
  if (sbWidth == 1) {
2295
    sigCtx = ctxIdxMap[(yC << 2) + xC];
2296
  }
2297
  else if (xC + yC == 0) {
2298
    sigCtx = 0;
2299
  }
2300
  else {
2301
    int xS = xC >> 2;
2302
    int yS = yC >> 2;
2303
    int prevCsbf = 0;
2304
    if (xS < sbWidth - 1) { prevCsbf += coded_sub_block_flag[xS + 1 + yS * sbWidth]; }
2305
    if (yS < sbWidth - 1) { prevCsbf += coded_sub_block_flag[xS + (1 + yS) * sbWidth] << 1; }
2306
2307
    int xP = xC & 3;
2308
    int yP = yC & 3;
2309
2310
    logtrace(LogSlice, "posInSubset: %d,%d\n", xP, yP);
2311
    logtrace(LogSlice, "prevCsbf: %d\n", prevCsbf);
2312
2313
    //printf("%d | %d %d\n",prevCsbf,xP,yP);
2314
2315
    switch (prevCsbf) {
2316
      case 0:
2317
        //sigCtx = (xP+yP==0) ? 2 : (xP+yP<3) ? 1 : 0;
2318
        sigCtx = (xP + yP >= 3) ? 0 : (xP + yP > 0) ? 1 : 2;
2319
        break;
2320
      case 1:
2321
        sigCtx = (yP == 0) ? 2 : (yP == 1) ? 1 : 0;
2322
        break;
2323
      case 2:
2324
        sigCtx = (xP == 0) ? 2 : (xP == 1) ? 1 : 0;
2325
        break;
2326
      default:
2327
        sigCtx = 2;
2328
        break;
2329
    }
2330
2331
    logtrace(LogSlice, "a) sigCtx=%d\n", sigCtx);
2332
2333
    if (cIdx == 0) {
2334
      if (xS + yS > 0) sigCtx += 3;
2335
2336
      logtrace(LogSlice, "b) sigCtx=%d\n", sigCtx);
2337
2338
      // if log2TrafoSize==3
2339
      if (sbWidth == 2) {
2340
        sigCtx += (scanIdx == 0) ? 9 : 15;
2341
      }
2342
      else {
2343
        sigCtx += 21;
2344
      }
2345
2346
      logtrace(LogSlice, "c) sigCtx=%d\n", sigCtx);
2347
    }
2348
    else {
2349
      // if log2TrafoSize==3
2350
      if (sbWidth == 2) {
2351
        sigCtx += 9;
2352
      }
2353
      else {
2354
        sigCtx += 12;
2355
      }
2356
    }
2357
  }
2358
2359
  int ctxIdxInc;
2360
  if (cIdx == 0) { ctxIdxInc = sigCtx; }
2361
  else { ctxIdxInc = 27 + sigCtx; }
2362
2363
  int context = tctx->shdr->initType * 42 + ctxIdxInc;
2364
  logtrace(LogSlice, "context: %d\n", context);
2365
2366
  int bit = tctx->cabac_decoder.decode_bit(
2367
                             &tctx->ctx_model[CONTEXT_MODEL_SIGNIFICANT_COEFF_FLAG + context]);
2368
  return bit;
2369
}
2370
#endif
2371
2372
2373
static inline int decode_significant_coeff_flag_lookup(thread_context* tctx,
2374
                                                       uint8_t ctxIdxInc)
2375
53.4M
{
2376
53.4M
  logtrace(LogSlice, "# significant_coeff_flag\n");
2377
53.4M
  logtrace(LogSlice, "context: %d\n", ctxIdxInc);
2378
2379
53.4M
  int bit = tctx->cabac_decoder.decode_bit(
2380
53.4M
                             &tctx->ctx_model[CONTEXT_MODEL_SIGNIFICANT_COEFF_FLAG + ctxIdxInc]);
2381
2382
53.4M
  logtrace(LogSymbols, "$1 significant_coeff_flag=%d\n", bit);
2383
2384
53.4M
  return bit;
2385
53.4M
}
2386
2387
2388
static inline int decode_coeff_abs_level_greater1(thread_context* tctx,
2389
                                                  int cIdx, int i,
2390
                                                  bool firstCoeffInSubblock,
2391
                                                  bool firstSubblock,
2392
                                                  int lastSubblock_greater1Ctx,
2393
                                                  int* lastInvocation_greater1Ctx,
2394
                                                  int* lastInvocation_coeff_abs_level_greater1_flag,
2395
                                                  int* lastInvocation_ctxSet, int c1)
2396
25.6M
{
2397
25.6M
  logtrace(LogSlice, "# coeff_abs_level_greater1\n");
2398
2399
25.6M
  logtrace(LogSlice, "  cIdx:%d i:%d firstCoeffInSB:%d firstSB:%d lastSB>1:%d last>1Ctx:%d lastLev>1:%d lastCtxSet:%d\n", cIdx, i, firstCoeffInSubblock, firstSubblock, lastSubblock_greater1Ctx,
2400
25.6M
           *lastInvocation_greater1Ctx,
2401
25.6M
           *lastInvocation_coeff_abs_level_greater1_flag,
2402
25.6M
           *lastInvocation_ctxSet);
2403
2404
25.6M
  int lastGreater1Ctx;
2405
25.6M
  int greater1Ctx;
2406
25.6M
  int ctxSet;
2407
2408
25.6M
  logtrace(LogSlice, "c1: %d\n", c1);
2409
2410
25.6M
  if (firstCoeffInSubblock) {
2411
    // block with real DC -> ctx 0
2412
4.66M
    if (i == 0 || cIdx > 0) { ctxSet = 0; }
2413
1.21M
    else { ctxSet = 2; }
2414
2415
4.66M
    if (firstSubblock) { lastGreater1Ctx = 1; }
2416
1.22M
    else { lastGreater1Ctx = lastSubblock_greater1Ctx; }
2417
2418
4.66M
    if (lastGreater1Ctx == 0) { ctxSet++; }
2419
2420
4.66M
    logtrace(LogSlice, "ctxSet: %d\n", ctxSet);
2421
2422
4.66M
    greater1Ctx = 1;
2423
4.66M
  }
2424
20.9M
  else {
2425
    // !firstCoeffInSubblock
2426
20.9M
    ctxSet = *lastInvocation_ctxSet;
2427
20.9M
    logtrace(LogSlice, "ctxSet (old): %d\n", ctxSet);
2428
2429
20.9M
    greater1Ctx = *lastInvocation_greater1Ctx;
2430
20.9M
    if (greater1Ctx > 0) {
2431
19.0M
      int lastGreater1Flag = *lastInvocation_coeff_abs_level_greater1_flag;
2432
19.0M
      if (lastGreater1Flag == 1) greater1Ctx = 0;
2433
18.6M
      else {
2434
        /*if (greater1Ctx>0)*/
2435
18.6M
        greater1Ctx++;
2436
18.6M
      }
2437
19.0M
    }
2438
20.9M
  }
2439
2440
25.6M
  ctxSet = c1; // use HM algo
2441
2442
25.6M
  int ctxIdxInc = (ctxSet * 4) + (greater1Ctx >= 3 ? 3 : greater1Ctx);
2443
2444
25.6M
  if (cIdx > 0) { ctxIdxInc += 16; }
2445
2446
25.6M
  int bit = tctx->cabac_decoder.decode_bit(
2447
25.6M
                             &tctx->ctx_model[CONTEXT_MODEL_COEFF_ABS_LEVEL_GREATER1_FLAG + ctxIdxInc]);
2448
2449
25.6M
  *lastInvocation_greater1Ctx = greater1Ctx;
2450
25.6M
  *lastInvocation_coeff_abs_level_greater1_flag = bit;
2451
25.6M
  *lastInvocation_ctxSet = ctxSet;
2452
2453
  //logtrace(LogSymbols,"$1 coeff_abs_level_greater1=%d\n",bit);
2454
2455
25.6M
  return bit;
2456
25.6M
}
2457
2458
2459
static int decode_coeff_abs_level_greater2(thread_context* tctx,
2460
                                           int cIdx, // int i,int n,
2461
                                           int ctxSet)
2462
409k
{
2463
409k
  logtrace(LogSlice, "# coeff_abs_level_greater2\n");
2464
2465
409k
  int ctxIdxInc = ctxSet;
2466
2467
409k
  if (cIdx > 0) ctxIdxInc += 4;
2468
2469
409k
  int bit = tctx->cabac_decoder.decode_bit(
2470
409k
                             &tctx->ctx_model[CONTEXT_MODEL_COEFF_ABS_LEVEL_GREATER2_FLAG + ctxIdxInc]);
2471
2472
409k
  logtrace(LogSymbols, "$1 coeff_abs_level_greater2=%d\n", bit);
2473
2474
409k
  return bit;
2475
409k
}
2476
2477
2478
286k
#define MAX_PREFIX (15+3)
2479
2480
// Defensive bounds against non-conforming bitstreams. The spec (eq. 9-25 / 9-23) does
2481
// not impose an explicit upper bound on cRiceParam or StatCoeff in the persistent-rice
2482
// path, but a malformed stream can push them arbitrarily high. We clamp so that the
2483
// signed-int shift expressions in residual_coding stay well-defined:
2484
//   - 3 * (1 << uiGoRiceParam) requires uiGoRiceParam <= 29 (else int32 overflow)
2485
//   - 3 << (StatCoeff/4)       requires StatCoeff/4   <= 29 (same)
2486
7.48k
#define MAX_RICE_PARAM 29
2487
1.38k
#define MAX_STAT_COEFF (4 * MAX_RICE_PARAM + 3)  // 119: largest value with /4 <= 29
2488
2489
static int32_t decode_coeff_abs_level_remaining(thread_context* tctx,
2490
                                                int cRiceParam)
2491
17.3M
{
2492
17.3M
  logtrace(LogSlice, "# decode_coeff_abs_level_remaining\n");
2493
2494
17.3M
  uint32_t prefix = 0;
2495
17.6M
  while (tctx->cabac_decoder.decode_bypass()) {
2496
286k
    prefix++;
2497
286k
    if (prefix > MAX_PREFIX) {
2498
2.02k
      return 0; // TODO: error
2499
2.02k
    }
2500
286k
  }
2501
2502
  // prefix = nb. 1 bits
2503
2504
17.3M
  int32_t value;
2505
2506
17.3M
  if (prefix <= 3) {
2507
    // when code only TR part (level < TRMax)
2508
2509
17.3M
    int codeword = tctx->cabac_decoder.decode_FL_bypass( cRiceParam);
2510
17.3M
    value = (prefix << cRiceParam) + codeword;
2511
17.3M
  }
2512
16.7k
  else {
2513
    // Suffix coded with EGk. Note that the unary part of EGk is already
2514
    // included in the 'prefix' counter above.
2515
2516
16.7k
    int codeword = tctx->cabac_decoder.decode_FL_bypass( prefix - 3 + cRiceParam);
2517
16.7k
    value = (((UINT32_C(1) << (prefix - 3)) + 3 - 1) << cRiceParam) + codeword;
2518
16.7k
  }
2519
2520
17.3M
  logtrace(LogSymbols, "$1 coeff_abs_level_remaining=%d\n", value);
2521
2522
17.3M
  return value;
2523
17.3M
}
2524
2525
2526
static int decode_merge_flag(thread_context* tctx)
2527
589k
{
2528
589k
  logtrace(LogSlice, "# merge_flag\n");
2529
2530
589k
  int bit = tctx->cabac_decoder.decode_bit(
2531
589k
                             &tctx->ctx_model[CONTEXT_MODEL_MERGE_FLAG]);
2532
2533
589k
  logtrace(LogSymbols, "$1 merge_flag=%d\n", bit);
2534
2535
589k
  return bit;
2536
589k
}
2537
2538
2539
static int decode_merge_idx(thread_context* tctx)
2540
719k
{
2541
719k
  logtrace(LogSlice, "# merge_idx\n");
2542
2543
719k
  if (tctx->shdr->MaxNumMergeCand <= 1) {
2544
13.5k
    logtrace(LogSymbols, "$1 merge_idx=%d\n", 0);
2545
13.5k
    return 0;
2546
13.5k
  }
2547
2548
  // TU coding, first bin is CABAC, remaining are bypass.
2549
  // cMax = MaxNumMergeCand-1
2550
2551
706k
  int idx = tctx->cabac_decoder.decode_bit(
2552
706k
                             &tctx->ctx_model[CONTEXT_MODEL_MERGE_IDX]);
2553
2554
706k
  if (idx == 0) {
2555
    // nothing
2556
614k
  }
2557
92.0k
  else {
2558
92.0k
    idx = 1;
2559
2560
108k
    while (idx < tctx->shdr->MaxNumMergeCand - 1) {
2561
96.2k
      if (tctx->cabac_decoder.decode_bypass()) {
2562
16.5k
        idx++;
2563
16.5k
      }
2564
79.6k
      else {
2565
79.6k
        break;
2566
79.6k
      }
2567
96.2k
    }
2568
92.0k
  }
2569
2570
706k
  logtrace(LogSlice, "> merge_idx = %d\n", idx);
2571
706k
  logtrace(LogSymbols, "$1 merge_idx=%d\n", idx);
2572
2573
706k
  return idx;
2574
719k
}
2575
2576
2577
static int decode_pred_mode_flag(thread_context* tctx)
2578
370k
{
2579
370k
  logtrace(LogSlice, "# pred_mode_flag\n");
2580
2581
370k
  int bit = tctx->cabac_decoder.decode_bit(
2582
370k
                             &tctx->ctx_model[CONTEXT_MODEL_PRED_MODE_FLAG]);
2583
2584
370k
  logtrace(LogSymbols, "$1 pred_mode=%d\n", bit);
2585
370k
  return bit;
2586
370k
}
2587
2588
static int decode_mvp_lx_flag(thread_context* tctx)
2589
331k
{
2590
331k
  logtrace(LogSlice, "# mvp_lx_flag\n");
2591
2592
331k
  int bit = tctx->cabac_decoder.decode_bit(
2593
331k
                             &tctx->ctx_model[CONTEXT_MODEL_MVP_LX_FLAG]);
2594
2595
331k
  logtrace(LogSymbols, "$1 mvp_lx_flag=%d\n", bit);
2596
331k
  return bit;
2597
331k
}
2598
2599
static int decode_rqt_root_cbf(thread_context* tctx)
2600
291k
{
2601
291k
  logtrace(LogSlice, "# rqt_root_cbf\n");
2602
2603
291k
  int bit = tctx->cabac_decoder.decode_bit(
2604
291k
                             &tctx->ctx_model[CONTEXT_MODEL_RQT_ROOT_CBF]);
2605
2606
291k
  logtrace(LogSymbols, "$1 rqt_root_cbf=%d\n", bit);
2607
291k
  return bit;
2608
291k
}
2609
2610
static int decode_ref_idx_lX(thread_context* tctx, int numRefIdxLXActive)
2611
331k
{
2612
  // prevent endless loop when 'numRefIdxLXActive' is invalid
2613
331k
  if (numRefIdxLXActive <= 1) {
2614
238k
    return 0;
2615
238k
  }
2616
2617
93.0k
  logtrace(LogSlice, "# ref_idx_lX\n");
2618
2619
93.0k
  int cMax = numRefIdxLXActive - 1;
2620
2621
93.0k
  if (cMax == 0) {
2622
0
    logtrace(LogSlice, "> ref_idx = 0 (cMax==0)\n");
2623
0
    return 0;
2624
0
  } // do check for single reference frame here
2625
2626
93.0k
  int bit = tctx->cabac_decoder.decode_bit(
2627
93.0k
                             &tctx->ctx_model[CONTEXT_MODEL_REF_IDX_LX + 0]);
2628
2629
93.0k
  int idx = 0;
2630
2631
113k
  while (bit) {
2632
27.6k
    idx++;
2633
27.6k
    if (idx == cMax) { break; }
2634
2635
20.0k
    if (idx == 1) {
2636
18.3k
      bit = tctx->cabac_decoder.decode_bit(
2637
18.3k
                             &tctx->ctx_model[CONTEXT_MODEL_REF_IDX_LX + 1]);
2638
18.3k
    }
2639
1.66k
    else {
2640
1.66k
      bit = tctx->cabac_decoder.decode_bypass();
2641
1.66k
    }
2642
20.0k
  }
2643
2644
93.0k
  logtrace(LogSlice, "> ref_idx = %d\n", idx);
2645
2646
93.0k
  logtrace(LogSymbols, "$1 ref_idx_lX=%d\n", idx);
2647
93.0k
  return idx;
2648
93.0k
}
2649
2650
2651
static enum InterPredIdc decode_inter_pred_idc(thread_context* tctx,
2652
                                               int x0, int y0,
2653
                                               int nPbW, int nPbH,
2654
                                               int ctDepth)
2655
243k
{
2656
243k
  logtrace(LogSlice, "# inter_pred_idc\n");
2657
2658
243k
  int value;
2659
2660
243k
  context_model* model = &tctx->ctx_model[CONTEXT_MODEL_INTER_PRED_IDC];
2661
2662
243k
  if (nPbW + nPbH == 12) {
2663
160k
    value = tctx->cabac_decoder.decode_bit(
2664
160k
                             &model[4]);
2665
160k
  }
2666
83.4k
  else {
2667
83.4k
    int bit0 = tctx->cabac_decoder.decode_bit(
2668
83.4k
                                &model[ctDepth]);
2669
83.4k
    if (bit0 == 0) {
2670
56.4k
      value = tctx->cabac_decoder.decode_bit(
2671
56.4k
                               &model[4]);
2672
56.4k
    }
2673
26.9k
    else {
2674
26.9k
      value = 2;
2675
26.9k
    }
2676
83.4k
  }
2677
2678
243k
  logtrace(LogSlice, "> inter_pred_idc = %d (%s)\n", value,
2679
243k
           value == 0 ? "L0" : (value == 1 ? "L1" : "BI"));
2680
2681
243k
  logtrace(LogSymbols, "$1 decode_inter_pred_idx=%d\n", value + 1);
2682
2683
243k
  return (enum InterPredIdc) (value + 1);
2684
243k
}
2685
2686
2687
static int decode_explicit_rdpcm_flag(thread_context* tctx, int cIdx)
2688
6.30k
{
2689
6.30k
  context_model* model = &tctx->ctx_model[CONTEXT_MODEL_RDPCM_FLAG];
2690
6.30k
  int value = tctx->cabac_decoder.decode_bit( &model[cIdx ? 1 : 0]);
2691
6.30k
  return value;
2692
6.30k
}
2693
2694
2695
static int decode_explicit_rdpcm_dir(thread_context* tctx, int cIdx)
2696
4.42k
{
2697
4.42k
  context_model* model = &tctx->ctx_model[CONTEXT_MODEL_RDPCM_DIR];
2698
4.42k
  int value = tctx->cabac_decoder.decode_bit( &model[cIdx ? 1 : 0]);
2699
4.42k
  return value;
2700
4.42k
}
2701
2702
2703
/* Take CtbAddrInTS and compute
2704
   -> CtbAddrInRS, CtbX, CtbY
2705
 */
2706
bool setCtbAddrFromTS(thread_context* tctx)
2707
150k
{
2708
150k
  const seq_parameter_set& sps = tctx->img->get_sps();
2709
2710
150k
  if (tctx->CtbAddrInTS < sps.PicSizeInCtbsY) {
2711
147k
    tctx->CtbAddrInRS = tctx->img->get_pps().scan->CtbAddrTStoRS[tctx->CtbAddrInTS];
2712
2713
147k
    tctx->CtbX = tctx->CtbAddrInRS % sps.PicWidthInCtbsY;
2714
147k
    tctx->CtbY = tctx->CtbAddrInRS / sps.PicWidthInCtbsY;
2715
147k
    return false;
2716
147k
  }
2717
3.07k
  else {
2718
3.07k
    tctx->CtbAddrInRS = sps.PicSizeInCtbsY;
2719
2720
3.07k
    tctx->CtbX = tctx->CtbAddrInRS % sps.PicWidthInCtbsY;
2721
3.07k
    tctx->CtbY = tctx->CtbAddrInRS / sps.PicWidthInCtbsY;
2722
3.07k
    return true;
2723
3.07k
  }
2724
150k
}
2725
2726
// returns true when we reached the end of the image (ctbAddr==picSizeInCtbsY)
2727
bool advanceCtbAddr(thread_context* tctx)
2728
145k
{
2729
145k
  tctx->CtbAddrInTS++;
2730
2731
145k
  return setCtbAddrFromTS(tctx);
2732
145k
}
2733
2734
2735
void read_sao(thread_context* tctx, int xCtb, int yCtb,
2736
              int CtbAddrInSliceSeg)
2737
67.9k
{
2738
67.9k
  slice_segment_header* shdr = tctx->shdr;
2739
67.9k
  de265_image* img = tctx->img;
2740
67.9k
  const seq_parameter_set& sps = img->get_sps();
2741
67.9k
  const pic_parameter_set& pps = img->get_pps();
2742
2743
67.9k
  logtrace(LogSlice, "# read_sao(%d,%d)\n", xCtb, yCtb);
2744
2745
67.9k
  sao_info saoinfo;
2746
67.9k
  memset(&saoinfo, 0, sizeof(sao_info));
2747
67.9k
  logtrace(LogSlice, "sizeof saoinfo: %d\n", sizeof(sao_info));
2748
2749
2750
67.9k
  char sao_merge_left_flag = 0;
2751
67.9k
  char sao_merge_up_flag = 0;
2752
2753
67.9k
  if (xCtb > 0) {
2754
    //char leftCtbInSliceSeg = (CtbAddrInSliceSeg>0);
2755
63.0k
    char leftCtbInSliceSeg = (tctx->CtbAddrInRS > shdr->SliceAddrRS);
2756
63.0k
    char leftCtbInTile = (pps.scan->TileIdRS[xCtb + yCtb * sps.PicWidthInCtbsY] ==
2757
63.0k
                          pps.scan->TileIdRS[xCtb - 1 + yCtb * sps.PicWidthInCtbsY]);
2758
2759
63.0k
    if (leftCtbInSliceSeg && leftCtbInTile) {
2760
62.9k
      sao_merge_left_flag = decode_sao_merge_flag(tctx);
2761
62.9k
      logtrace(LogSlice, "sao_merge_left_flag: %d\n", sao_merge_left_flag);
2762
62.9k
    }
2763
63.0k
  }
2764
2765
67.9k
  if (yCtb > 0 && sao_merge_left_flag == 0) {
2766
39.1k
    logtrace(LogSlice, "CtbAddrInRS:%d PicWidthInCtbsY:%d slice_segment_address:%d\n",
2767
39.1k
             tctx->CtbAddrInRS,
2768
39.1k
             sps.PicWidthInCtbsY,
2769
39.1k
             shdr->slice_segment_address);
2770
39.1k
    bool upCtbInSliceSeg = (tctx->CtbAddrInRS - sps.PicWidthInCtbsY) >= shdr->SliceAddrRS;
2771
39.1k
    bool upCtbInTile = (pps.scan->TileIdRS[xCtb + yCtb * sps.PicWidthInCtbsY] ==
2772
39.1k
                        pps.scan->TileIdRS[xCtb + (yCtb - 1) * sps.PicWidthInCtbsY]);
2773
2774
39.1k
    if (upCtbInSliceSeg && upCtbInTile) {
2775
38.9k
      sao_merge_up_flag = decode_sao_merge_flag(tctx);
2776
38.9k
      logtrace(LogSlice, "sao_merge_up_flag: %d\n", sao_merge_up_flag);
2777
38.9k
    }
2778
39.1k
  }
2779
2780
67.9k
  if (!sao_merge_up_flag && !sao_merge_left_flag) {
2781
59.6k
    int nChroma = 3;
2782
59.6k
    if (sps.ChromaArrayType == CHROMA_MONO) nChroma = 1;
2783
2784
238k
    for (int cIdx = 0; cIdx < nChroma; cIdx++) {
2785
179k
      if ((shdr->slice_sao_luma_flag && cIdx == 0) ||
2786
136k
          (shdr->slice_sao_chroma_flag && cIdx > 0)) {
2787
136k
        uint8_t SaoTypeIdx = 0;
2788
2789
136k
        if (cIdx == 0) {
2790
44.0k
          uint8_t sao_type_idx_luma = decode_sao_type_idx(tctx);
2791
44.0k
          logtrace(LogSlice, "sao_type_idx_luma: %d\n", sao_type_idx_luma);
2792
44.0k
          saoinfo.SaoTypeIdx = SaoTypeIdx = sao_type_idx_luma;
2793
44.0k
        }
2794
92.5k
        else if (cIdx == 1) {
2795
46.2k
          uint8_t sao_type_idx_chroma = decode_sao_type_idx(tctx);
2796
46.2k
          logtrace(LogSlice, "sao_type_idx_chroma: %d\n", sao_type_idx_chroma);
2797
46.2k
          SaoTypeIdx = sao_type_idx_chroma;
2798
46.2k
          saoinfo.SaoTypeIdx |= SaoTypeIdx << (2 * 1);
2799
46.2k
          saoinfo.SaoTypeIdx |= SaoTypeIdx << (2 * 2); // set for both chroma components
2800
46.2k
        }
2801
46.2k
        else {
2802
          // SaoTypeIdx = 0
2803
2804
46.2k
          SaoTypeIdx = (saoinfo.SaoTypeIdx >> (2 * cIdx)) & 0x3;
2805
46.2k
        }
2806
2807
136k
        if (SaoTypeIdx != 0) {
2808
195k
          for (int i = 0; i < 4; i++) {
2809
156k
            saoinfo.saoOffsetVal[cIdx][i] = decode_sao_offset_abs(tctx, img->get_bit_depth(cIdx));
2810
156k
            logtrace(LogSlice, "saoOffsetVal[%d][%d] = %d\n", cIdx, i, saoinfo.saoOffsetVal[cIdx][i]);
2811
156k
          }
2812
2813
39.1k
          int sign[4];
2814
39.1k
          if (SaoTypeIdx == 1) {
2815
178k
            for (int i = 0; i < 4; i++) {
2816
143k
              if (saoinfo.saoOffsetVal[cIdx][i] != 0) {
2817
4.63k
                sign[i] = decode_sao_offset_sign(tctx) ? -1 : 1;
2818
4.63k
              }
2819
138k
              else {
2820
138k
                sign[i] = 0; // not really required, but compiler warns about uninitialized values
2821
138k
              }
2822
143k
            }
2823
2824
35.7k
            saoinfo.sao_band_position[cIdx] = decode_sao_band_position(tctx);
2825
35.7k
          }
2826
3.44k
          else {
2827
3.44k
            uint8_t SaoEoClass = 0;
2828
2829
3.44k
            sign[0] = sign[1] = 1;
2830
3.44k
            sign[2] = sign[3] = -1;
2831
2832
3.44k
            if (cIdx == 0) {
2833
1.35k
              saoinfo.SaoEoClass = SaoEoClass = decode_sao_class(tctx);
2834
1.35k
            }
2835
2.09k
            else if (cIdx == 1) {
2836
1.04k
              SaoEoClass = decode_sao_class(tctx);
2837
1.04k
              saoinfo.SaoEoClass |= SaoEoClass << (2 * 1);
2838
1.04k
              saoinfo.SaoEoClass |= SaoEoClass << (2 * 2);
2839
1.04k
            }
2840
2841
3.44k
            logtrace(LogSlice, "SaoEoClass[%d] = %d\n", cIdx, SaoEoClass);
2842
3.44k
          }
2843
2844
39.1k
          int log2OffsetScale;
2845
2846
39.1k
          if (cIdx == 0) {
2847
14.0k
            log2OffsetScale = pps.range_extension.log2_sao_offset_scale_luma;
2848
14.0k
          }
2849
25.1k
          else {
2850
25.1k
            log2OffsetScale = pps.range_extension.log2_sao_offset_scale_chroma;
2851
25.1k
          }
2852
2853
195k
          for (int i = 0; i < 4; i++) {
2854
156k
            saoinfo.saoOffsetVal[cIdx][i] = sign[i] * (saoinfo.saoOffsetVal[cIdx][i] << log2OffsetScale);
2855
156k
          }
2856
39.1k
        }
2857
136k
      }
2858
179k
    }
2859
2860
59.6k
    img->set_sao_info(xCtb, yCtb, &saoinfo);
2861
59.6k
  }
2862
2863
2864
67.9k
  if (sao_merge_left_flag) {
2865
7.40k
    img->set_sao_info(xCtb, yCtb, img->get_sao_info(xCtb - 1, yCtb));
2866
7.40k
  }
2867
2868
67.9k
  if (sao_merge_up_flag) {
2869
863
    img->set_sao_info(xCtb, yCtb, img->get_sao_info(xCtb, yCtb - 1));
2870
863
  }
2871
67.9k
}
2872
2873
2874
void read_coding_tree_unit(thread_context* tctx)
2875
145k
{
2876
145k
  slice_segment_header* shdr = tctx->shdr;
2877
145k
  de265_image* img = tctx->img;
2878
145k
  const seq_parameter_set& sps = img->get_sps();
2879
2880
145k
  int xCtb = (tctx->CtbAddrInRS % sps.PicWidthInCtbsY);
2881
145k
  int yCtb = (tctx->CtbAddrInRS / sps.PicWidthInCtbsY);
2882
145k
  int xCtbPixels = xCtb << sps.Log2CtbSizeY;
2883
145k
  int yCtbPixels = yCtb << sps.Log2CtbSizeY;
2884
2885
145k
  logtrace(LogSlice, "----- decode CTB %d;%d (%d;%d) POC=%d, SliceAddrRS=%d\n",
2886
145k
           xCtbPixels, yCtbPixels, xCtb, yCtb,
2887
145k
           tctx->img->PicOrderCntVal, tctx->shdr->SliceAddrRS);
2888
2889
145k
  img->set_SliceAddrRS(xCtb, yCtb, tctx->shdr->SliceAddrRS);
2890
2891
145k
  img->set_SliceHeaderIndex(xCtbPixels, yCtbPixels, shdr->slice_index);
2892
2893
145k
  int CtbAddrInSliceSeg = tctx->CtbAddrInRS - shdr->slice_segment_address;
2894
2895
145k
  if (shdr->slice_sao_luma_flag || shdr->slice_sao_chroma_flag) {
2896
67.9k
    read_sao(tctx, xCtb, yCtb, CtbAddrInSliceSeg);
2897
67.9k
  }
2898
2899
145k
  read_coding_quadtree(tctx, xCtbPixels, yCtbPixels, sps.Log2CtbSizeY, 0);
2900
145k
}
2901
2902
2903
inline static int luma_pos_to_ctbAddrRS(const seq_parameter_set* sps, int x, int y)
2904
7.60M
{
2905
7.60M
  int ctbX = x >> sps->Log2CtbSizeY;
2906
7.60M
  int ctbY = y >> sps->Log2CtbSizeY;
2907
2908
7.60M
  return ctbY * sps->PicWidthInCtbsY + ctbX;
2909
7.60M
}
2910
2911
2912
int check_CTB_available(const de265_image* img,
2913
                        int xC, int yC, int xN, int yN)
2914
4.13M
{
2915
  // check whether neighbor is outside of frame
2916
2917
4.13M
  if (xN < 0 || yN < 0) { return 0; }
2918
3.80M
  if (xN >= img->get_sps().pic_width_in_luma_samples) { return 0; }
2919
3.80M
  if (yN >= img->get_sps().pic_height_in_luma_samples) { return 0; }
2920
2921
2922
3.80M
  int current_ctbAddrRS = luma_pos_to_ctbAddrRS(&img->get_sps(), xC, yC);
2923
3.80M
  int neighbor_ctbAddrRS = luma_pos_to_ctbAddrRS(&img->get_sps(), xN, yN);
2924
2925
  // TODO: check if this is correct (6.4.1)
2926
2927
3.80M
  if (img->get_SliceAddrRS_atCtbRS(current_ctbAddrRS) !=
2928
3.80M
      img->get_SliceAddrRS_atCtbRS(neighbor_ctbAddrRS)) {
2929
0
    return 0;
2930
0
  }
2931
2932
  // check if both CTBs are in the same tile.
2933
2934
3.80M
  if (img->get_pps().scan->TileIdRS[current_ctbAddrRS] !=
2935
3.80M
      img->get_pps().scan->TileIdRS[neighbor_ctbAddrRS]) {
2936
2.47k
    return 0;
2937
2.47k
  }
2938
2939
3.79M
  return 1;
2940
3.80M
}
2941
2942
2943
int residual_coding(thread_context* tctx,
2944
                    int x0, int y0, // position of TU in frame
2945
                    int log2TrafoSize,
2946
                    int cIdx)
2947
3.44M
{
2948
3.44M
  logtrace(LogSlice, "- residual_coding x0:%d y0:%d log2TrafoSize:%d cIdx:%d\n", x0, y0, log2TrafoSize, cIdx);
2949
2950
  //slice_segment_header* shdr = tctx->shdr;
2951
2952
3.44M
  de265_image* img = tctx->img;
2953
3.44M
  const seq_parameter_set& sps = img->get_sps();
2954
3.44M
  const pic_parameter_set& pps = img->get_pps();
2955
2956
3.44M
  enum PredMode PredMode = img->get_pred_mode(x0, y0);
2957
2958
3.44M
  if (cIdx == 0) {
2959
2.47M
    img->set_nonzero_coefficient(x0, y0, log2TrafoSize);
2960
2.47M
  }
2961
2962
2963
3.44M
  if (pps.transform_skip_enabled_flag &&
2964
70.0k
      !tctx->cu_transquant_bypass_flag &&
2965
60.5k
      (log2TrafoSize <= pps.Log2MaxTransformSkipSize)) {
2966
56.9k
    tctx->transform_skip_flag[cIdx] = decode_transform_skip_flag(tctx, cIdx);
2967
56.9k
  }
2968
3.38M
  else {
2969
3.38M
    tctx->transform_skip_flag[cIdx] = 0;
2970
3.38M
  }
2971
2972
2973
3.44M
  tctx->explicit_rdpcm_flag = false;
2974
2975
3.44M
  if (PredMode == MODE_INTER && sps.range_extension.explicit_rdpcm_enabled_flag &&
2976
8.18k
      (tctx->transform_skip_flag[cIdx] || tctx->cu_transquant_bypass_flag)) {
2977
6.30k
    tctx->explicit_rdpcm_flag = decode_explicit_rdpcm_flag(tctx, cIdx);
2978
6.30k
    if (tctx->explicit_rdpcm_flag) {
2979
4.42k
      tctx->explicit_rdpcm_dir = decode_explicit_rdpcm_dir(tctx, cIdx);
2980
4.42k
    }
2981
2982
    //printf("EXPLICIT RDPCM %d;%d\n",x0,y0);
2983
6.30k
  }
2984
3.43M
  else {
2985
3.43M
    tctx->explicit_rdpcm_flag = false;
2986
3.43M
  }
2987
2988
2989
  // sbType for persistent_rice_adaptation_enabled_flag
2990
2991
3.44M
  int sbType = (cIdx == 0) ? 2 : 0;
2992
3.44M
  if (tctx->transform_skip_flag[cIdx] || tctx->cu_transquant_bypass_flag) {
2993
474k
    sbType++;
2994
474k
  }
2995
2996
2997
  // --- decode position of last coded coefficient ---
2998
2999
3.44M
  int last_significant_coeff_x_prefix =
3000
3.44M
      decode_last_significant_coeff_prefix(tctx, log2TrafoSize, cIdx,
3001
3.44M
                                           &tctx->ctx_model[CONTEXT_MODEL_LAST_SIGNIFICANT_COEFFICIENT_X_PREFIX]);
3002
3003
3.44M
  int last_significant_coeff_y_prefix =
3004
3.44M
      decode_last_significant_coeff_prefix(tctx, log2TrafoSize, cIdx,
3005
3.44M
                                           &tctx->ctx_model[CONTEXT_MODEL_LAST_SIGNIFICANT_COEFFICIENT_Y_PREFIX]);
3006
3007
3008
  // TODO: we can combine both FL-bypass calls into one, but the gain may be limited...
3009
3010
3.44M
  int LastSignificantCoeffX;
3011
3.44M
  if (last_significant_coeff_x_prefix > 3) {
3012
253k
    int nBits = (last_significant_coeff_x_prefix >> 1) - 1;
3013
253k
    int last_significant_coeff_x_suffix = tctx->cabac_decoder.decode_FL_bypass( nBits);
3014
3015
253k
    LastSignificantCoeffX =
3016
253k
        ((2 + (last_significant_coeff_x_prefix & 1)) << nBits) + last_significant_coeff_x_suffix;
3017
253k
  }
3018
3.19M
  else {
3019
3.19M
    LastSignificantCoeffX = last_significant_coeff_x_prefix;
3020
3.19M
  }
3021
3022
3.44M
  int LastSignificantCoeffY;
3023
3.44M
  if (last_significant_coeff_y_prefix > 3) {
3024
246k
    int nBits = (last_significant_coeff_y_prefix >> 1) - 1;
3025
246k
    int last_significant_coeff_y_suffix = tctx->cabac_decoder.decode_FL_bypass( nBits);
3026
3027
246k
    LastSignificantCoeffY =
3028
246k
        ((2 + (last_significant_coeff_y_prefix & 1)) << nBits) + last_significant_coeff_y_suffix;
3029
246k
  }
3030
3.19M
  else {
3031
3.19M
    LastSignificantCoeffY = last_significant_coeff_y_prefix;
3032
3.19M
  }
3033
3034
3035
  // --- determine scanIdx ---
3036
3037
3.44M
  int scanIdx;
3038
3039
3.44M
  if (PredMode == MODE_INTRA) {
3040
3.23M
    if (cIdx == 0) {
3041
2.27M
      scanIdx = get_intra_scan_idx(log2TrafoSize, img->get_IntraPredMode(x0, y0), cIdx, &sps);
3042
      //printf("luma scan idx=%d <- intra mode=%d\n",scanIdx, img->get_IntraPredMode(x0,y0));
3043
2.27M
    }
3044
961k
    else {
3045
961k
      scanIdx = get_intra_scan_idx(log2TrafoSize, img->get_IntraPredModeC(x0, y0), cIdx, &sps);
3046
      //printf("chroma scan idx=%d <- intra mode=%d chroma:%d trsize:%d\n",scanIdx,
3047
      //       img->get_IntraPredModeC(x0,y0), sps->chroma_format_idc, 1<<log2TrafoSize);
3048
961k
    }
3049
3.23M
  }
3050
207k
  else {
3051
207k
    scanIdx = 0;
3052
207k
  }
3053
3054
3.44M
  if (scanIdx == 2) {
3055
93.6k
    std::swap(LastSignificantCoeffX, LastSignificantCoeffY);
3056
93.6k
  }
3057
3058
3.44M
  logtrace(LogSlice, "LastSignificantCoeff: x=%d;y=%d\n", LastSignificantCoeffX, LastSignificantCoeffY);
3059
3060
3.44M
  const position* ScanOrderSub = get_scan_order(log2TrafoSize - 2, scanIdx);
3061
3.44M
  const position* ScanOrderPos = get_scan_order(2, scanIdx);
3062
3063
3.44M
  logtrace(LogSlice, "ScanOrderPos: ");
3064
58.5M
  for (int n = 0; n < 4 * 4; n++)
3065
55.1M
    logtrace(LogSlice, "*%d,%d ", ScanOrderPos[n].x, ScanOrderPos[n].y);
3066
3.44M
  logtrace(LogSlice, "*\n");
3067
3068
3069
  // --- find last sub block and last scan pos ---
3070
3071
3.44M
  int xC, yC;
3072
3073
3.44M
  scan_position lastScanP = get_scan_position(LastSignificantCoeffX, LastSignificantCoeffY,
3074
3.44M
                                              scanIdx, log2TrafoSize);
3075
3076
3.44M
  int lastScanPos = lastScanP.scanPos;
3077
3.44M
  int lastSubBlock = lastScanP.subBlock;
3078
3079
3080
3.44M
  int sbWidth = 1 << (log2TrafoSize - 2);
3081
3082
3.44M
  uint8_t coded_sub_block_neighbors[32 / 4 * 32 / 4];
3083
3.44M
  memset(coded_sub_block_neighbors, 0, sbWidth * sbWidth);
3084
3085
3.44M
  int c1 = 1;
3086
3.44M
  bool firstSubblock = true; // for coeff_abs_level_greater1_flag context model
3087
3.44M
  int lastSubblock_greater1Ctx = false; /* for coeff_abs_level_greater1_flag context model
3088
                                          (initialization not strictly needed)
3089
                                       */
3090
3091
#ifdef DE265_LOG_TRACE
3092
  int16_t TransCoeffLevel[32 * 32];
3093
  memset(TransCoeffLevel, 0, sizeof(uint16_t) * 32 * 32);
3094
#endif
3095
3096
3.44M
  int CoeffStride = 1 << log2TrafoSize;
3097
3098
3.44M
  int lastInvocation_greater1Ctx = 0;
3099
3.44M
  int lastInvocation_coeff_abs_level_greater1_flag = 0;
3100
3.44M
  int lastInvocation_ctxSet = 0;
3101
3102
3103
  // ----- decode coefficients -----
3104
3105
3.44M
  tctx->nCoeff[cIdx] = 0;
3106
3107
3108
  // i - subblock index
3109
  // n - coefficient index in subblock
3110
3111
8.42M
  for (int i = lastSubBlock; i >= 0; i--) {
3112
4.98M
    position S = ScanOrderSub[i];
3113
4.98M
    int inferSbDcSigCoeffFlag = 0;
3114
3115
4.98M
    logtrace(LogSlice, "sub block scan idx: %d\n", i);
3116
3117
3118
    // --- check whether this sub-block is coded ---
3119
3120
4.98M
    int sub_block_is_coded = 0;
3121
3122
4.98M
    if ((i < lastSubBlock) && (i > 0)) {
3123
1.27M
      sub_block_is_coded = decode_coded_sub_block_flag(tctx, cIdx,
3124
1.27M
                                                       coded_sub_block_neighbors[S.x + S.y * sbWidth]);
3125
1.27M
      inferSbDcSigCoeffFlag = 1;
3126
1.27M
    }
3127
3.71M
    else if (i == 0 || i == lastSubBlock) {
3128
      // first (DC) and last sub-block are always coded
3129
      // - the first will most probably contain coefficients
3130
      // - the last obviously contains the last coded coefficient
3131
3132
3.71M
      sub_block_is_coded = 1;
3133
3.71M
    }
3134
3135
4.98M
    if (sub_block_is_coded) {
3136
4.66M
      if (S.x > 0) coded_sub_block_neighbors[S.x - 1 + S.y * sbWidth] |= 1;
3137
4.66M
      if (S.y > 0) coded_sub_block_neighbors[S.x + (S.y - 1) * sbWidth] |= 2;
3138
4.66M
    }
3139
3140
3141
    // ----- find significant coefficients in this sub-block -----
3142
3143
4.98M
    int16_t coeff_value[16];
3144
4.98M
    int8_t coeff_scan_pos[16];
3145
4.98M
    int8_t coeff_sign[16];
3146
4.98M
    int8_t coeff_has_max_base_level[16];
3147
4.98M
    int nCoefficients = 0;
3148
3149
3150
4.98M
    if (sub_block_is_coded) {
3151
4.66M
      int x0 = S.x << 2;
3152
4.66M
      int y0 = S.y << 2;
3153
3154
4.66M
      int log2w = log2TrafoSize - 2;
3155
4.66M
      int prevCsbf = coded_sub_block_neighbors[S.x + S.y * sbWidth];
3156
4.66M
      uint8_t* ctxIdxMap = ctxIdxLookup[log2w][!!cIdx][!!scanIdx][prevCsbf];
3157
3158
4.66M
      logdebug(LogSlice, "log2w:%d cIdx:%d scanIdx:%d prevCsbf:%d\n",
3159
4.66M
               log2w, cIdx, scanIdx, prevCsbf);
3160
3161
3162
      // set the last coded coefficient in the last subblock
3163
3164
4.66M
      int last_coeff = (i == lastSubBlock) ? lastScanPos - 1 : 15;
3165
3166
4.66M
      if (i == lastSubBlock) {
3167
3.44M
        coeff_value[nCoefficients] = 1;
3168
3.44M
        coeff_has_max_base_level[nCoefficients] = 1;
3169
3.44M
        coeff_scan_pos[nCoefficients] = lastScanPos;
3170
3.44M
        nCoefficients++;
3171
3.44M
      }
3172
3173
3174
      // --- decode all coefficients' significant_coeff flags except for the DC coefficient ---
3175
3176
54.1M
      for (int n = last_coeff; n > 0; n--) {
3177
49.4M
        int subX = ScanOrderPos[n].x;
3178
49.4M
        int subY = ScanOrderPos[n].y;
3179
49.4M
        xC = x0 + subX;
3180
49.4M
        yC = y0 + subY;
3181
3182
3183
        // for all AC coefficients in sub-block, a significant_coeff flag is coded
3184
3185
49.4M
        int ctxInc;
3186
49.4M
        if (sps.range_extension.transform_skip_context_enabled_flag &&
3187
543k
            (tctx->cu_transquant_bypass_flag || tctx->transform_skip_flag[cIdx])) {
3188
346k
          ctxInc = (cIdx == 0) ? 42 : (16 + 27);
3189
346k
        }
3190
49.1M
        else {
3191
49.1M
          ctxInc = ctxIdxMap[xC + (yC << log2TrafoSize)];
3192
49.1M
        }
3193
3194
49.4M
        logtrace(LogSlice, "trafoSize: %d\n", 1 << log2TrafoSize);
3195
3196
49.4M
        int significant_coeff = decode_significant_coeff_flag_lookup(tctx, ctxInc);
3197
3198
49.4M
        if (significant_coeff) {
3199
33.3M
          coeff_value[nCoefficients] = 1;
3200
33.3M
          coeff_has_max_base_level[nCoefficients] = 1;
3201
33.3M
          coeff_scan_pos[nCoefficients] = n;
3202
33.3M
          nCoefficients++;
3203
3204
          // since we have a coefficient in the sub-block,
3205
          // we cannot infer the DC coefficient anymore
3206
33.3M
          inferSbDcSigCoeffFlag = 0;
3207
33.3M
        }
3208
49.4M
      }
3209
3210
3211
      // --- decode DC coefficient significance ---
3212
3213
4.66M
      if (last_coeff >= 0) // last coded coefficient (always set to 1) is not the DC coefficient
3214
4.18M
      {
3215
4.18M
        if (inferSbDcSigCoeffFlag == 0) {
3216
          // if we cannot infert the DC coefficient, it is coded
3217
3218
3.99M
          int ctxInc;
3219
3.99M
          if (sps.range_extension.transform_skip_context_enabled_flag &&
3220
38.5k
              (tctx->cu_transquant_bypass_flag || tctx->transform_skip_flag[cIdx])) {
3221
22.6k
            ctxInc = (cIdx == 0) ? 42 : (16 + 27);
3222
22.6k
          }
3223
3.97M
          else {
3224
3.97M
            ctxInc = ctxIdxMap[x0 + (y0 << log2TrafoSize)];
3225
3.97M
          }
3226
3227
3.99M
          int significant_coeff = decode_significant_coeff_flag_lookup(tctx, ctxInc);
3228
3229
3230
3.99M
          if (significant_coeff) {
3231
3.86M
            coeff_value[nCoefficients] = 1;
3232
3.86M
            coeff_has_max_base_level[nCoefficients] = 1;
3233
3.86M
            coeff_scan_pos[nCoefficients] = 0;
3234
3.86M
            nCoefficients++;
3235
3.86M
          }
3236
3.99M
        }
3237
185k
        else {
3238
          // we can infer that the DC coefficient must be present
3239
185k
          coeff_value[nCoefficients] = 1;
3240
185k
          coeff_has_max_base_level[nCoefficients] = 1;
3241
185k
          coeff_scan_pos[nCoefficients] = 0;
3242
185k
          nCoefficients++;
3243
185k
        }
3244
4.18M
      }
3245
4.66M
    }
3246
3247
3248
    /*
3249
      logtrace(LogSlice,"significant_coeff_flags:\n");
3250
      for (int y=0;y<4;y++) {
3251
      logtrace(LogSlice,"  ");
3252
      for (int x=0;x<4;x++) {
3253
      logtrace(LogSlice,"*%d ",significant_coeff_flag[y][x]);
3254
      }
3255
      logtrace(LogSlice,"*\n");
3256
      }
3257
    */
3258
3259
3260
4.98M
    if (nCoefficients) {
3261
4.66M
      int ctxSet;
3262
4.66M
      if (i == 0 || cIdx > 0) { ctxSet = 0; }
3263
1.21M
      else { ctxSet = 2; }
3264
3265
4.66M
      if (c1 == 0) { ctxSet++; }
3266
4.66M
      c1 = 1;
3267
3268
3269
      /* Whether this sub-block codes any escape data, i.e. any coeff_abs_level_remaining.
3270
         Only used for cabac_bypass_alignment_enabled_flag (see below). */
3271
3272
4.66M
      bool escapeDataPresent = false;
3273
3274
3275
      // --- decode greater-1 flags ---
3276
3277
4.66M
      int newLastGreater1ScanPos = -1;
3278
3279
4.66M
      int lastGreater1Coefficient = std::min(8, nCoefficients);
3280
3281
      // significant coefficients past the first eight carry no greater-1 flag and are escape coded
3282
4.66M
      if (nCoefficients > 8) {
3283
2.23M
        escapeDataPresent = true;
3284
2.23M
      }
3285
30.3M
      for (int c = 0; c < lastGreater1Coefficient; c++) {
3286
25.6M
        int greater1_flag =
3287
25.6M
            decode_coeff_abs_level_greater1(tctx, cIdx, i,
3288
25.6M
                                            c == 0,
3289
25.6M
                                            firstSubblock,
3290
25.6M
                                            lastSubblock_greater1Ctx,
3291
25.6M
                                            &lastInvocation_greater1Ctx,
3292
25.6M
                                            &lastInvocation_coeff_abs_level_greater1_flag,
3293
25.6M
                                            &lastInvocation_ctxSet, ctxSet);
3294
3295
25.6M
        if (greater1_flag) {
3296
2.51M
          coeff_value[c]++;
3297
3298
2.51M
          c1 = 0;
3299
3300
2.51M
          if (newLastGreater1ScanPos == -1) {
3301
409k
            newLastGreater1ScanPos = c;
3302
409k
          }
3303
2.10M
          else {
3304
2.10M
            escapeDataPresent = true;
3305
2.10M
          }
3306
2.51M
        }
3307
23.1M
        else {
3308
23.1M
          coeff_has_max_base_level[c] = 0;
3309
3310
23.1M
          if (c1 < 3 && c1 > 0) {
3311
8.03M
            c1++;
3312
8.03M
          }
3313
23.1M
        }
3314
25.6M
      }
3315
3316
4.66M
      firstSubblock = false;
3317
4.66M
      lastSubblock_greater1Ctx = lastInvocation_greater1Ctx;
3318
3319
3320
      // --- decode greater-2 flag ---
3321
3322
4.66M
      if (newLastGreater1ScanPos != -1) {
3323
409k
        int flag = decode_coeff_abs_level_greater2(tctx, cIdx, lastInvocation_ctxSet);
3324
409k
        coeff_value[newLastGreater1ScanPos] += flag;
3325
409k
        coeff_has_max_base_level[newLastGreater1ScanPos] = flag;
3326
3327
409k
        if (flag) {
3328
47.4k
          escapeDataPresent = true;
3329
47.4k
        }
3330
409k
      }
3331
3332
3333
      // --- decode coefficient signs ---
3334
3335
4.66M
      int signHidden;
3336
3337
3338
4.66M
      IntraPredMode predModeIntra;
3339
4.66M
      if (cIdx == 0) predModeIntra = img->get_IntraPredMode(x0, y0);
3340
980k
      else predModeIntra = img->get_IntraPredModeC(x0, y0);
3341
3342
3343
4.66M
      if (tctx->cu_transquant_bypass_flag ||
3344
3.83M
          (PredMode == MODE_INTRA &&
3345
3.45M
           sps.range_extension.implicit_rdpcm_enabled_flag &&
3346
42.2k
           tctx->transform_skip_flag[cIdx] &&
3347
6.64k
           (predModeIntra == 10 || predModeIntra == 26)) ||
3348
3.83M
          tctx->explicit_rdpcm_flag) {
3349
833k
        signHidden = 0;
3350
833k
      }
3351
3.83M
      else {
3352
3.83M
        signHidden = (coeff_scan_pos[0] - coeff_scan_pos[nCoefficients - 1] > 3);
3353
3.83M
      }
3354
3355
3356
      /* (9.3.4.3.6) Align the CABAC engine before the bypass-coded sign flags and
3357
         remaining levels of a sub-block that carries escape data. No context-coded bin
3358
         follows until the end of the sub-block, so aligning once here covers both. */
3359
3360
4.66M
      if (sps.range_extension.cabac_bypass_alignment_enabled_flag && escapeDataPresent) {
3361
4.51k
        tctx->cabac_decoder.align_bypass();
3362
4.51k
      }
3363
3364
40.8M
      for (int n = 0; n < nCoefficients - 1; n++) {
3365
36.1M
        coeff_sign[n] = tctx->cabac_decoder.decode_bypass();
3366
36.1M
        logtrace(LogSlice, "sign[%d] = %d\n", n, coeff_sign[n]);
3367
36.1M
      }
3368
3369
      // n==nCoefficients-1
3370
4.66M
      if (!pps.sign_data_hiding_flag || !signHidden) {
3371
3.96M
        coeff_sign[nCoefficients - 1] = tctx->cabac_decoder.decode_bypass();
3372
3.96M
        logtrace(LogSlice, "sign[%d] = %d\n", nCoefficients - 1, coeff_sign[nCoefficients - 1]);
3373
3.96M
      }
3374
697k
      else {
3375
697k
        coeff_sign[nCoefficients - 1] = 0;
3376
697k
      }
3377
3378
3379
      // --- decode coefficient value ---
3380
3381
4.66M
      int sumAbsLevel = 0;
3382
4.66M
      int uiGoRiceParam;
3383
3384
4.66M
      if (sps.range_extension.persistent_rice_adaptation_enabled_flag == 0) {
3385
4.61M
        uiGoRiceParam = 0;
3386
4.61M
      }
3387
49.1k
      else {
3388
49.1k
        uiGoRiceParam = tctx->StatCoeff[sbType] / 4;
3389
49.1k
      }
3390
3391
      // printf("initial uiGoRiceParam=%d\n",uiGoRiceParam);
3392
4.66M
      bool firstCoeffWithAbsLevelRemaining = true;
3393
3394
45.5M
      for (int n = 0; n < nCoefficients; n++) {
3395
40.8M
        int16_t baseLevel = coeff_value[n];
3396
3397
40.8M
        int32_t coeff_abs_level_remaining;
3398
3399
        // printf("coeff %d/%d, uiRiceParam: %d\n",n,nCoefficients,uiGoRiceParam);
3400
3401
40.8M
        if (coeff_has_max_base_level[n]) {
3402
17.3M
          coeff_abs_level_remaining =
3403
17.3M
              decode_coeff_abs_level_remaining(tctx, uiGoRiceParam);
3404
3405
17.3M
          if (sps.range_extension.persistent_rice_adaptation_enabled_flag == 0) {
3406
            // (2014.10 / 9-20)
3407
17.2M
            if (baseLevel + coeff_abs_level_remaining > 3 * (1 << uiGoRiceParam)) {
3408
42.0k
              uiGoRiceParam++;
3409
42.0k
              if (uiGoRiceParam > 4) uiGoRiceParam = 4;
3410
42.0k
            }
3411
17.2M
          }
3412
121k
          else {
3413
121k
            if (baseLevel + coeff_abs_level_remaining > 3 * (1 << uiGoRiceParam)) {
3414
6.09k
              uiGoRiceParam++;
3415
6.09k
              if (uiGoRiceParam > MAX_RICE_PARAM) {
3416
0
                uiGoRiceParam = MAX_RICE_PARAM;
3417
0
                tctx->decctx->add_warning(DE265_WARNING_RICE_PARAMETER_OUT_OF_RANGE, true);
3418
0
              }
3419
6.09k
            }
3420
121k
          }
3421
3422
          // persistent_rice_adaptation_enabled_flag
3423
17.3M
          if (sps.range_extension.persistent_rice_adaptation_enabled_flag &&
3424
121k
              firstCoeffWithAbsLevelRemaining) {
3425
21.6k
            if (coeff_abs_level_remaining >= (3 << (tctx->StatCoeff[sbType] / 4))) {
3426
1.38k
              if (tctx->StatCoeff[sbType] < MAX_STAT_COEFF) {
3427
1.38k
                tctx->StatCoeff[sbType]++;
3428
1.38k
              } else {
3429
0
                tctx->decctx->add_warning(DE265_WARNING_RICE_PARAMETER_OUT_OF_RANGE, true);
3430
0
              }
3431
1.38k
            }
3432
20.2k
            else if (2 * coeff_abs_level_remaining < (1 << (tctx->StatCoeff[sbType] / 4)) &&
3433
18.2k
                     tctx->StatCoeff[sbType] > 0) {
3434
641
              tctx->StatCoeff[sbType]--;
3435
641
            }
3436
21.6k
          }
3437
3438
17.3M
          firstCoeffWithAbsLevelRemaining = false;
3439
17.3M
        }
3440
23.4M
        else {
3441
23.4M
          coeff_abs_level_remaining = 0;
3442
23.4M
        }
3443
3444
40.8M
        logtrace(LogSlice, "coeff_abs_level_remaining=%d\n", coeff_abs_level_remaining);
3445
3446
3447
40.8M
        int32_t currCoeff = baseLevel + coeff_abs_level_remaining;
3448
40.8M
        if (coeff_sign[n]) {
3449
331k
          currCoeff = -currCoeff;
3450
331k
        }
3451
3452
40.8M
        if (pps.sign_data_hiding_flag && signHidden) {
3453
6.56M
          sumAbsLevel += currCoeff;
3454
3455
6.56M
          if (n == nCoefficients - 1 && (sumAbsLevel & 1)) {
3456
212k
            currCoeff = -currCoeff;
3457
212k
          }
3458
6.56M
        }
3459
3460
40.8M
        logtrace(LogSlice, "quantized coefficient=%d\n", currCoeff);
3461
3462
#ifdef DE265_LOG_TRACE
3463
        //TransCoeffLevel[yC*CoeffStride + xC] = currCoeff;
3464
#endif
3465
3466
        // put coefficient in list
3467
40.8M
        int p = coeff_scan_pos[n];
3468
40.8M
        xC = (S.x << 2) + ScanOrderPos[p].x;
3469
40.8M
        yC = (S.y << 2) + ScanOrderPos[p].y;
3470
3471
40.8M
        tctx->coeffList[cIdx][tctx->nCoeff[cIdx]] = Clip3(-32768, 32767, currCoeff);
3472
40.8M
        tctx->coeffPos[cIdx][tctx->nCoeff[cIdx]] = xC + yC * CoeffStride;
3473
40.8M
        tctx->nCoeff[cIdx]++;
3474
3475
        //printf("%d ",currCoeff);
3476
40.8M
      } // iterate through coefficients in sub-block
3477
3478
      //printf(" (%d;%d)\n",x0,y0);
3479
4.66M
    } // if nonZero
3480
4.98M
  } // next sub-block
3481
3482
3.44M
  return DE265_OK;
3483
3.44M
}
3484
3485
3486
static void decode_TU(thread_context* tctx,
3487
                      int x0, int y0,
3488
                      int xCUBase, int yCUBase,
3489
                      int nT, int cIdx, enum PredMode cuPredMode, bool cbf)
3490
5.10M
{
3491
5.10M
  de265_image* img = tctx->img;
3492
5.10M
  const seq_parameter_set& sps = img->get_sps();
3493
3494
5.10M
  int residualDpcm = 0;
3495
3496
5.10M
  if (cuPredMode == MODE_INTRA) // if intra mode
3497
3.89M
  {
3498
3.89M
    enum IntraPredMode intraPredMode;
3499
3500
3.89M
    if (cIdx == 0) {
3501
2.39M
      intraPredMode = img->get_IntraPredMode(x0, y0);
3502
2.39M
    }
3503
1.49M
    else {
3504
1.49M
      const int SubWidthC = sps.SubWidthC;
3505
1.49M
      const int SubHeightC = sps.SubHeightC;
3506
3507
1.49M
      intraPredMode = img->get_IntraPredModeC(x0 * SubWidthC, y0 * SubHeightC);
3508
1.49M
    }
3509
3510
3.89M
    if (intraPredMode < 0 || intraPredMode >= 35) {
3511
      // TODO: ERROR
3512
0
      intraPredMode = INTRA_DC;
3513
0
    }
3514
3515
3.89M
    decode_intra_prediction(img, x0, y0, intraPredMode, nT, cIdx);
3516
3517
3518
3.89M
    residualDpcm = sps.range_extension.implicit_rdpcm_enabled_flag &&
3519
84.1k
                   (tctx->cu_transquant_bypass_flag || tctx->transform_skip_flag[cIdx]) &&
3520
45.6k
                   (intraPredMode == 10 || intraPredMode == 26);
3521
3522
3.89M
    if (residualDpcm && intraPredMode == 26)
3523
2.40k
      residualDpcm = 2;
3524
3.89M
  }
3525
1.20M
  else // INTER
3526
1.20M
  {
3527
1.20M
    if (tctx->explicit_rdpcm_flag) {
3528
12.2k
      residualDpcm = (tctx->explicit_rdpcm_dir ? 2 : 1);
3529
12.2k
    }
3530
1.20M
  }
3531
3532
5.10M
  if (cbf) {
3533
3.44M
    scale_coefficients(tctx, x0, y0, xCUBase, yCUBase, nT, cIdx,
3534
3.44M
                       tctx->transform_skip_flag[cIdx], cuPredMode == MODE_INTRA, residualDpcm);
3535
3.44M
  }
3536
  /*
3537
  else if (!cbf && cIdx==0) {
3538
    memset(tctx->residual_luma,0,32*32*sizeof(int32_t));
3539
  }
3540
  */
3541
1.65M
  else if (!cbf && cIdx != 0 && tctx->ResScaleVal) {
3542
    // --- cross-component-prediction when CBF==0 ---
3543
3544
0
    tctx->nCoeff[cIdx] = 0;
3545
0
    residualDpcm = 0;
3546
3547
0
    scale_coefficients(tctx, x0, y0, xCUBase, yCUBase, nT, cIdx,
3548
0
                       tctx->transform_skip_flag[cIdx], cuPredMode == MODE_INTRA, residualDpcm);
3549
0
  }
3550
5.10M
}
3551
3552
3553
static int decode_log2_res_scale_abs_plus1(thread_context* tctx, int cIdxMinus1)
3554
0
{
3555
  //const int context = (cIdx==0) ? 0 : 1;
3556
3557
0
  logtrace(LogSlice, "# log2_res_scale_abs_plus1 (c=%d)\n", cIdxMinus1);
3558
3559
0
  int value = 0;
3560
0
  int cMax = 4;
3561
0
  for (int binIdx = 0; binIdx < cMax; binIdx++) {
3562
0
    int ctxIdxInc = 4 * cIdxMinus1 + binIdx;
3563
3564
0
    int bit = tctx->cabac_decoder.decode_bit(
3565
0
                               &tctx->ctx_model[CONTEXT_MODEL_LOG2_RES_SCALE_ABS_PLUS1 + ctxIdxInc]);
3566
0
    if (!bit) break;
3567
0
    value++;
3568
0
  }
3569
3570
0
  logtrace(LogSymbols, "$1 log2_res_scale_abs_plus1=%d\n", value);
3571
3572
0
  return value;
3573
0
}
3574
3575
3576
static int decode_res_scale_sign_flag(thread_context* tctx, int cIdxMinus1)
3577
0
{
3578
  //const int context = (cIdx==0) ? 0 : 1;
3579
3580
0
  logtrace(LogSlice, "# res_scale_sign_flag (c=%d)\n", cIdxMinus1);
3581
3582
0
  int bit = tctx->cabac_decoder.decode_bit(
3583
0
                             &tctx->ctx_model[CONTEXT_MODEL_RES_SCALE_SIGN_FLAG + cIdxMinus1]);
3584
3585
0
  logtrace(LogSymbols, "$1 res_scale_sign_flag=%d\n", bit);
3586
3587
0
  return bit;
3588
0
}
3589
3590
3591
static void read_cross_comp_pred(thread_context* tctx, int cIdxMinus1)
3592
0
{
3593
0
  int log2_res_scale_abs_plus1 = decode_log2_res_scale_abs_plus1(tctx, cIdxMinus1);
3594
0
  int ResScaleVal;
3595
3596
0
  if (log2_res_scale_abs_plus1 != 0) {
3597
0
    int res_scale_sign_flag = decode_res_scale_sign_flag(tctx, cIdxMinus1);
3598
3599
0
    ResScaleVal = 1 << (log2_res_scale_abs_plus1 - 1);
3600
0
    ResScaleVal *= 1 - 2 * res_scale_sign_flag;
3601
0
  }
3602
0
  else {
3603
0
    ResScaleVal = 0;
3604
0
  }
3605
3606
0
  tctx->ResScaleVal = ResScaleVal;
3607
0
}
3608
3609
3610
int read_transform_unit(thread_context* tctx,
3611
                        int x0, int y0, // position of TU in frame
3612
                        int xBase, int yBase, // position of parent TU in frame
3613
                        int xCUBase, int yCUBase, // position of CU in frame
3614
                        int log2TrafoSize,
3615
                        int trafoDepth,
3616
                        int blkIdx,
3617
                        int cbf_luma, int cbf_cb, int cbf_cr)
3618
3.00M
{
3619
3.00M
  logtrace(LogSlice, "- read_transform_unit x0:%d y0:%d xBase:%d yBase:%d nT:%d cbf:%d:%d:%d\n",
3620
3.00M
           x0, y0, xBase, yBase, 1 << log2TrafoSize, cbf_luma, cbf_cb, cbf_cr);
3621
3622
3.00M
  assert(cbf_cb != -1);
3623
3.00M
  assert(cbf_cr != -1);
3624
3.00M
  assert(cbf_luma != -1);
3625
3626
3.00M
  const seq_parameter_set& sps = tctx->img->get_sps();
3627
3628
3.00M
  const int ChromaArrayType = sps.ChromaArrayType;
3629
3630
3.00M
  int log2TrafoSizeC = (ChromaArrayType == CHROMA_444 ? log2TrafoSize : log2TrafoSize - 1);
3631
3.00M
  log2TrafoSizeC = std::max(2, log2TrafoSizeC);
3632
3633
3.00M
  const int cbfLuma = cbf_luma;
3634
3.00M
  const int cbfChroma = cbf_cb | cbf_cr;
3635
3636
3.00M
  tctx->transform_skip_flag[0] = 0;
3637
3.00M
  tctx->transform_skip_flag[1] = 0;
3638
3.00M
  tctx->transform_skip_flag[2] = 0;
3639
3640
3.00M
  tctx->explicit_rdpcm_flag = false;
3641
3642
3643
3.00M
  enum PredMode cuPredMode = tctx->img->get_pred_mode(x0, y0);
3644
3645
3.00M
  if (cbfLuma || cbfChroma) {
3646
2.51M
    bool doDecodeQuantParameters = false;
3647
3648
2.51M
    if (tctx->img->get_pps().cu_qp_delta_enabled_flag &&
3649
2.49M
        !tctx->IsCuQpDeltaCoded) {
3650
429k
      uint8_t cu_qp_delta_abs = decode_cu_qp_delta_abs(tctx);
3651
429k
      if (cu_qp_delta_abs == CABAC_QP_DELTA_ABS_ERROR) {
3652
27
        tctx->decctx->add_warning(DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE, false);
3653
27
        return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
3654
27
      }
3655
3656
428k
      int cu_qp_delta_sign = 0;
3657
428k
      if (cu_qp_delta_abs) {
3658
373k
        cu_qp_delta_sign = tctx->cabac_decoder.decode_bypass();
3659
373k
      }
3660
3661
      // CuQpDeltaVal shall be in [-(26 + QpBdOffsetY/2), +(25 + QpBdOffsetY/2)] (Sec. 7.4.9.14).
3662
      // Note that the range is asymmetric.
3663
428k
      int maxCuQpDeltaAbs = (cu_qp_delta_sign ? 26 : 25) + tctx->img->get_sps().QpBdOffset_Y / 2;
3664
428k
      if (cu_qp_delta_abs > maxCuQpDeltaAbs) {
3665
248
        tctx->decctx->add_warning(DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE, false);
3666
248
        return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
3667
248
      }
3668
3669
428k
      tctx->IsCuQpDeltaCoded = 1;
3670
428k
      tctx->CuQpDelta = cu_qp_delta_abs * (1 - 2 * cu_qp_delta_sign);
3671
3672
      //printf("read cu_qp_delta (%d;%d) = %d\n",x0,y0,tctx->CuQpDelta);
3673
3674
428k
      logtrace(LogSlice, "cu_qp_delta_abs = %d\n", cu_qp_delta_abs);
3675
428k
      logtrace(LogSlice, "cu_qp_delta_sign = %d\n", cu_qp_delta_sign);
3676
428k
      logtrace(LogSlice, "CuQpDelta = %d\n", tctx->CuQpDelta);
3677
3678
428k
      doDecodeQuantParameters = true;
3679
      //decode_quantization_parameters(tctx, x0,y0, xCUBase, yCUBase);
3680
428k
    }
3681
3682
2.51M
    if (tctx->shdr->cu_chroma_qp_offset_enabled_flag && cbfChroma &&
3683
0
        !tctx->cu_transquant_bypass_flag && !tctx->IsCuChromaQpOffsetCoded) {
3684
0
      logtrace(LogSlice, "# cu_chroma_qp_offset_flag\n");
3685
3686
0
      int cu_chroma_qp_offset_flag = tctx->cabac_decoder.decode_bit(
3687
0
                                                      &tctx->ctx_model[CONTEXT_MODEL_CU_CHROMA_QP_OFFSET_FLAG]);
3688
3689
3690
0
      const pic_parameter_set& pps = tctx->img->get_pps();
3691
3692
0
      int cu_chroma_qp_offset_idx = 0;
3693
0
      if (cu_chroma_qp_offset_flag && pps.range_extension.chroma_qp_offset_list_len > 1) {
3694
0
        cu_chroma_qp_offset_idx = tctx->cabac_decoder.decode_bit(
3695
0
                                                   &tctx->ctx_model[CONTEXT_MODEL_CU_CHROMA_QP_OFFSET_IDX]);
3696
0
      }
3697
3698
0
      tctx->IsCuChromaQpOffsetCoded = 1;
3699
3700
0
      if (cu_chroma_qp_offset_flag) {
3701
0
        tctx->CuQpOffsetCb = pps.range_extension.cb_qp_offset_list[cu_chroma_qp_offset_idx];
3702
0
        tctx->CuQpOffsetCr = pps.range_extension.cr_qp_offset_list[cu_chroma_qp_offset_idx];
3703
0
      }
3704
0
      else {
3705
0
        tctx->CuQpOffsetCb = 0;
3706
0
        tctx->CuQpOffsetCr = 0;
3707
0
      }
3708
3709
0
      doDecodeQuantParameters = true;
3710
      //decode_quantization_parameters(tctx, x0,y0, xCUBase, yCUBase);
3711
0
    }
3712
3713
3714
2.51M
    if (doDecodeQuantParameters) {
3715
428k
      decode_quantization_parameters(tctx, x0, y0, xCUBase, yCUBase);
3716
428k
    }
3717
2.51M
  }
3718
3719
  // position of TU in local CU
3720
  //int xL = x0 - xCUBase;
3721
  //int yL = y0 - yCUBase;
3722
3.00M
  int nT = 1 << log2TrafoSize;
3723
3.00M
  int nTC = 1 << log2TrafoSizeC;
3724
3725
3.00M
  const int SubWidthC = sps.SubWidthC;
3726
3.00M
  const int SubHeightC = sps.SubHeightC;
3727
3728
  // --- luma ---
3729
3730
3.00M
  tctx->ResScaleVal = 0;
3731
3732
3.00M
  int err;
3733
3.00M
  if (cbf_luma) {
3734
2.47M
    if ((err = residual_coding(tctx, x0, y0, log2TrafoSize, 0)) != DE265_OK) return err;
3735
2.47M
  }
3736
3737
3.00M
  decode_TU(tctx, x0, y0, xCUBase, yCUBase, nT, 0, cuPredMode, cbf_luma);
3738
3739
3740
  // --- chroma ---
3741
3742
  //const int yOffset422 = 1<<log2TrafoSizeC;
3743
3744
3.00M
  if (log2TrafoSize > 2 || ChromaArrayType == CHROMA_444) {
3745
    // TODO: cross-component prediction
3746
3747
357k
    const bool do_cross_component_prediction =
3748
357k
    (tctx->img->get_pps().range_extension.cross_component_prediction_enabled_flag &&
3749
0
     cbf_luma &&
3750
0
     (cuPredMode == MODE_INTER || tctx->img->is_IntraPredModeC_Mode4(x0, y0)));
3751
3752
357k
    if (do_cross_component_prediction) {
3753
0
      read_cross_comp_pred(tctx, 0);
3754
0
    }
3755
357k
    else {
3756
357k
      tctx->ResScaleVal = 0;
3757
357k
    } {
3758
357k
      if (cbf_cb & 1) {
3759
83.4k
        if ((err = residual_coding(tctx, x0, y0, log2TrafoSizeC, 1)) != DE265_OK) return err;
3760
83.4k
      }
3761
3762
357k
      if (sps.ChromaArrayType != CHROMA_MONO) {
3763
357k
        decode_TU(tctx,
3764
357k
                  x0 / SubWidthC, y0 / SubHeightC,
3765
357k
                  xCUBase / SubWidthC, yCUBase / SubHeightC, nTC, 1, cuPredMode, cbf_cb & 1);
3766
357k
      }
3767
357k
    }
3768
3769
    // 4:2:2
3770
357k
    if (ChromaArrayType == CHROMA_422) {
3771
19.6k
      const int yOffset = 1 << log2TrafoSizeC;
3772
3773
19.6k
      if (cbf_cb & 2) {
3774
3.83k
        if ((err = residual_coding(tctx,
3775
3.83k
                                   x0, y0 + yOffset * SubHeightC,
3776
3.83k
                                   log2TrafoSizeC, 1)) != DE265_OK)
3777
0
          return err;
3778
3.83k
      }
3779
3780
19.6k
      decode_TU(tctx,
3781
19.6k
                x0 / SubWidthC, y0 / SubHeightC + yOffset,
3782
19.6k
                xCUBase / SubWidthC, yCUBase / SubHeightC + yOffset,
3783
19.6k
                nTC, 1, cuPredMode, cbf_cb & 2);
3784
19.6k
    }
3785
3786
3787
357k
    if (do_cross_component_prediction) {
3788
0
      read_cross_comp_pred(tctx, 1);
3789
0
    }
3790
357k
    else {
3791
357k
      tctx->ResScaleVal = 0;
3792
357k
    } {
3793
357k
      if (cbf_cr & 1) {
3794
83.5k
        if ((err = residual_coding(tctx, x0, y0, log2TrafoSizeC, 2)) != DE265_OK) return err;
3795
83.5k
      }
3796
3797
357k
      if (sps.ChromaArrayType != CHROMA_MONO) {
3798
357k
        decode_TU(tctx,
3799
357k
                  x0 / SubWidthC, y0 / SubHeightC,
3800
357k
                  xCUBase / SubWidthC, yCUBase / SubHeightC,
3801
357k
                  nTC, 2, cuPredMode, cbf_cr & 1);
3802
357k
      }
3803
357k
    }
3804
3805
    // 4:2:2
3806
357k
    if (ChromaArrayType == CHROMA_422) {
3807
19.6k
      const int yOffset = 1 << log2TrafoSizeC;
3808
3809
19.6k
      if (cbf_cr & 2) {
3810
3.78k
        if ((err = residual_coding(tctx,
3811
3.78k
                                   x0, y0 + yOffset * SubHeightC,
3812
3.78k
                                   log2TrafoSizeC, 2)) != DE265_OK)
3813
0
          return err;
3814
3.78k
      }
3815
3816
19.6k
      decode_TU(tctx,
3817
19.6k
                x0 / SubWidthC, y0 / SubHeightC + yOffset,
3818
19.6k
                xCUBase / SubWidthC, yCUBase / SubHeightC + yOffset,
3819
19.6k
                nTC, 2, cuPredMode, cbf_cr & 2);
3820
19.6k
    }
3821
357k
  }
3822
2.64M
  else if (blkIdx == 3) {
3823
661k
    if (cbf_cb & 1) {
3824
398k
      if ((err = residual_coding(tctx, xBase, yBase,
3825
398k
                                 log2TrafoSize, 1)) != DE265_OK)
3826
0
        return err;
3827
398k
    }
3828
3829
661k
    if (sps.ChromaArrayType != CHROMA_MONO) {
3830
661k
      decode_TU(tctx,
3831
661k
                xBase / SubWidthC, yBase / SubHeightC,
3832
661k
                xCUBase / SubWidthC, yCUBase / SubHeightC, nT, 1, cuPredMode, cbf_cb & 1);
3833
661k
    }
3834
3835
    // 4:2:2
3836
661k
    if (cbf_cb & 2) {
3837
878
      if ((err = residual_coding(tctx,
3838
878
                                 xBase, yBase + (1 << log2TrafoSize),
3839
878
                                 log2TrafoSize, 1)) != DE265_OK)
3840
0
        return err;
3841
878
    }
3842
3843
661k
    if (ChromaArrayType == CHROMA_422) {
3844
8.91k
      decode_TU(tctx,
3845
8.91k
                xBase / SubWidthC, yBase / SubHeightC + (1 << log2TrafoSize),
3846
8.91k
                xCUBase / SubWidthC, yCUBase / SubHeightC, nT, 1, cuPredMode, cbf_cb & 2);
3847
8.91k
    }
3848
3849
661k
    if (cbf_cr & 1) {
3850
398k
      if ((err = residual_coding(tctx, xBase, yBase,
3851
398k
                                 log2TrafoSize, 2)) != DE265_OK)
3852
0
        return err;
3853
398k
    }
3854
3855
661k
    if (sps.ChromaArrayType != CHROMA_MONO) {
3856
661k
      decode_TU(tctx,
3857
661k
                xBase / SubWidthC, yBase / SubHeightC,
3858
661k
                xCUBase / SubWidthC, yCUBase / SubHeightC, nT, 2, cuPredMode, cbf_cr & 1);
3859
661k
    }
3860
3861
    // 4:2:2
3862
661k
    if (cbf_cr & 2) {
3863
847
      if ((err = residual_coding(tctx,
3864
847
                                 xBase, yBase + (1 << log2TrafoSizeC),
3865
847
                                 log2TrafoSize, 2)) != DE265_OK)
3866
0
        return err;
3867
847
    }
3868
3869
661k
    if (ChromaArrayType == CHROMA_422) {
3870
8.91k
      decode_TU(tctx,
3871
8.91k
                xBase / SubWidthC, yBase / SubHeightC + (1 << log2TrafoSize),
3872
8.91k
                xCUBase / SubWidthC, yCUBase / SubHeightC, nT, 2, cuPredMode, cbf_cr & 2);
3873
8.91k
    }
3874
661k
  }
3875
3876
3877
3.00M
  return DE265_OK;
3878
3.00M
}
3879
3880
3881
#if 0
3882
static void dump_cbsize(de265_image* img)
3883
{
3884
  int w = img->get_width(0);
3885
  int h = img->get_height(0);
3886
3887
  for (int y = 0; y < h; y += 8) {
3888
    for (int x = 0; x < w; x += 8) {
3889
      printf("%d", img->get_log2CbSize(x, y));
3890
    }
3891
    printf("\n");
3892
  }
3893
}
3894
#endif
3895
3896
3897
void read_transform_tree(thread_context* tctx,
3898
                         int x0, int y0, // position of TU in frame
3899
                         int xBase, int yBase, // position of parent TU in frame
3900
                         int xCUBase, int yCUBase, // position of CU in frame
3901
                         int log2TrafoSize,
3902
                         int trafoDepth,
3903
                         int blkIdx,
3904
                         int MaxTrafoDepth,
3905
                         int IntraSplitFlag,
3906
                         enum PredMode cuPredMode,
3907
                         uint8_t parent_cbf_cb, uint8_t parent_cbf_cr)
3908
3.70M
{
3909
3.70M
  logtrace(LogSlice, "- read_transform_tree (interleaved) x0:%d y0:%d xBase:%d yBase:%d "
3910
3.70M
           "log2TrafoSize:%d trafoDepth:%d MaxTrafoDepth:%d parent-cbf-cb:%d parent-cbf-cr:%d\n",
3911
3.70M
           x0, y0, xBase, yBase, log2TrafoSize, trafoDepth, MaxTrafoDepth, parent_cbf_cb, parent_cbf_cr);
3912
3913
3.70M
  de265_image* img = tctx->img;
3914
3.70M
  const seq_parameter_set& sps = img->get_sps();
3915
3916
3.70M
  int split_transform_flag;
3917
3918
3.70M
  enum PredMode PredMode = img->get_pred_mode(x0, y0);
3919
3.70M
  assert(PredMode == cuPredMode);
3920
3921
  /*  If TrafoSize is larger than maximum size   -> split automatically
3922
      If TrafoSize is at minimum size            -> do not split
3923
      If maximum transformation depth is reached -> do not split
3924
      If intra-prediction is NxN mode            -> split automatically (only at level 0)
3925
      Otherwise  ->  read split flag
3926
  */
3927
3.70M
  if (log2TrafoSize <= sps.Log2MaxTrafoSize &&
3928
3.62M
      log2TrafoSize > sps.Log2MinTrafoSize &&
3929
972k
      trafoDepth < MaxTrafoDepth &&
3930
686k
      !(IntraSplitFlag && trafoDepth == 0)) {
3931
162k
    split_transform_flag = decode_split_transform_flag(tctx, log2TrafoSize);
3932
162k
  }
3933
3.53M
  else {
3934
3.53M
    enum PartMode PartMode = img->get_PartMode(x0, y0);
3935
3936
3.53M
    int interSplitFlag = (sps.max_transform_hierarchy_depth_inter == 0 &&
3937
1.81M
                          trafoDepth == 0 &&
3938
411k
                          PredMode == MODE_INTER &&
3939
191k
                          PartMode != PART_2Nx2N);
3940
3941
3.53M
    split_transform_flag = (log2TrafoSize > sps.Log2MaxTrafoSize ||
3942
3.46M
                            (IntraSplitFlag == 1 && trafoDepth == 0) ||
3943
2.93M
                            interSplitFlag == 1)
3944
3.53M
                             ? 1
3945
3.53M
                             : 0;
3946
3.53M
  }
3947
3948
3.70M
  if (split_transform_flag && log2TrafoSize <= sps.Log2MinTrafoSize) {
3949
    // TODO: it would be nice to have a flag "ignore_subsequent_errors" since the stream cannot be successfully decoded
3950
    //       after a bitstream error like this. But that would require that the error_queue is independent for each decoding thread
3951
    //       and that the flag is reset at a CABAC synchronization point. An alternative would be to simply stop the decoding this slice
3952
    //       after such an error.
3953
933
    img->decctx->add_warning(DE265_WARNING_INVALID_TU_BLOCK_SPLIT, true);
3954
933
    split_transform_flag = 0;
3955
933
  }
3956
3957
3.70M
  if (split_transform_flag) {
3958
694k
    logtrace(LogSlice, "set_split_transform_flag(%d,%d, %d)\n", x0, y0, trafoDepth);
3959
694k
    img->set_split_transform_flag(x0, y0, trafoDepth);
3960
694k
  }
3961
3962
3.70M
  int cbf_cb = -1;
3963
3.70M
  int cbf_cr = -1;
3964
3965
  // CBF_CB/CR flags are encoded like this:
3966
  // 4:2:0 and 4:4:4 modes: binary flag in bit 0
3967
  // 4:2:2 mode: bit 0: top block, bit 1: bottom block
3968
3969
3.70M
  if ((log2TrafoSize > 2 && sps.ChromaArrayType != CHROMA_MONO) ||
3970
2.64M
      sps.ChromaArrayType == CHROMA_444) {
3971
    // we do not have to test for trafoDepth==0, because parent_cbf_cb is 1 at depth 0
3972
1.05M
    if (/*trafoDepth==0 ||*/ parent_cbf_cb) {
3973
930k
      cbf_cb = decode_cbf_chroma(tctx, trafoDepth);
3974
3975
930k
      if (sps.ChromaArrayType == CHROMA_422 && (!split_transform_flag || log2TrafoSize == 3)) {
3976
23.2k
        cbf_cb |= (decode_cbf_chroma(tctx, trafoDepth) << 1);
3977
23.2k
      }
3978
930k
    }
3979
3980
    // we do not have to test for trafoDepth==0, because parent_cbf_cb is 1 at depth 0
3981
1.05M
    if (/*trafoDepth==0 ||*/ parent_cbf_cr) {
3982
930k
      cbf_cr = decode_cbf_chroma(tctx, trafoDepth);
3983
3984
930k
      if (sps.ChromaArrayType == CHROMA_422 && (!split_transform_flag || log2TrafoSize == 3)) {
3985
23.1k
        cbf_cr |= (decode_cbf_chroma(tctx, trafoDepth) << 1);
3986
23.1k
      }
3987
930k
    }
3988
1.05M
  }
3989
3990
  //printf("CBF: cb:%d cr:%d\n",cbf_cb,cbf_cr);
3991
3992
  // cbf_cr/cbf_cb not present in bitstream -> induce values
3993
3994
3.70M
  if (cbf_cb < 0) {
3995
2.76M
    assert(!(trafoDepth==0 && log2TrafoSize==2));
3996
3997
    /* The standard specifies to check trafoDepth>0 AND log2TrafoSize==2.
3998
       However, I think that trafoDepth>0 is redundant as a CB is always
3999
       at least 8x8 and hence trafoDepth>0.
4000
    */
4001
4002
2.76M
    if (trafoDepth > 0 && log2TrafoSize == 2) {
4003
2.64M
      cbf_cb = parent_cbf_cb;
4004
2.64M
    }
4005
122k
    else {
4006
122k
      cbf_cb = 0;
4007
122k
    }
4008
2.76M
  }
4009
4010
3.70M
  if (cbf_cr < 0) {
4011
2.76M
    if (trafoDepth > 0 && log2TrafoSize == 2) {
4012
2.64M
      cbf_cr = parent_cbf_cr;
4013
2.64M
    }
4014
121k
    else {
4015
121k
      cbf_cr = 0;
4016
121k
    }
4017
2.76M
  }
4018
4019
3.70M
  if (split_transform_flag) {
4020
694k
    int x1 = x0 + (1 << (log2TrafoSize - 1));
4021
694k
    int y1 = y0 + (1 << (log2TrafoSize - 1));
4022
4023
694k
    logtrace(LogSlice, "transform split.\n");
4024
4025
694k
    read_transform_tree(tctx, x0, y0, x0, y0, xCUBase, yCUBase, log2TrafoSize - 1, trafoDepth + 1, 0,
4026
694k
                        MaxTrafoDepth, IntraSplitFlag, cuPredMode, cbf_cb, cbf_cr);
4027
694k
    read_transform_tree(tctx, x1, y0, x0, y0, xCUBase, yCUBase, log2TrafoSize - 1, trafoDepth + 1, 1,
4028
694k
                        MaxTrafoDepth, IntraSplitFlag, cuPredMode, cbf_cb, cbf_cr);
4029
694k
    read_transform_tree(tctx, x0, y1, x0, y0, xCUBase, yCUBase, log2TrafoSize - 1, trafoDepth + 1, 2,
4030
694k
                        MaxTrafoDepth, IntraSplitFlag, cuPredMode, cbf_cb, cbf_cr);
4031
694k
    read_transform_tree(tctx, x1, y1, x0, y0, xCUBase, yCUBase, log2TrafoSize - 1, trafoDepth + 1, 3,
4032
694k
                        MaxTrafoDepth, IntraSplitFlag, cuPredMode, cbf_cb, cbf_cr);
4033
694k
  }
4034
3.00M
  else {
4035
3.00M
    int cbf_luma;
4036
4037
3.00M
    if (PredMode == MODE_INTRA || trafoDepth != 0 || cbf_cb || cbf_cr) {
4038
2.91M
      cbf_luma = decode_cbf_luma(tctx, trafoDepth);
4039
2.91M
    }
4040
93.5k
    else {
4041
      /* There cannot be INTER blocks with no residual data.
4042
         That case is already handled with rqt_root_cbf.
4043
      */
4044
4045
93.5k
      cbf_luma = 1;
4046
93.5k
    }
4047
4048
3.00M
    logtrace(LogSlice, "call read_transform_unit %d/%d\n", x0, y0);
4049
4050
3.00M
    read_transform_unit(tctx, x0, y0, xBase, yBase, xCUBase, yCUBase, log2TrafoSize, trafoDepth, blkIdx,
4051
3.00M
                        cbf_luma, cbf_cb, cbf_cr);
4052
3.00M
  }
4053
3.70M
}
4054
4055
4056
const char* part_mode_name(enum PartMode pm)
4057
0
{
4058
0
  switch (pm) {
4059
0
    case PART_2Nx2N: return "2Nx2N";
4060
0
    case PART_2NxN: return "2NxN";
4061
0
    case PART_Nx2N: return "Nx2N";
4062
0
    case PART_NxN: return "NxN";
4063
0
    case PART_2NxnU: return "2NxnU";
4064
0
    case PART_2NxnD: return "2NxnD";
4065
0
    case PART_nLx2N: return "nLx2N";
4066
0
    case PART_nRx2N: return "nRx2N";
4067
0
  }
4068
4069
0
  return "undefined part mode";
4070
0
}
4071
4072
4073
void read_mvd_coding(thread_context* tctx,
4074
                     int x0, int y0, int refList)
4075
316k
{
4076
316k
  int abs_mvd_greater0_flag[2];
4077
316k
  abs_mvd_greater0_flag[0] = tctx->cabac_decoder.decode_bit(
4078
316k
                                              &tctx->ctx_model[CONTEXT_MODEL_ABS_MVD_GREATER01_FLAG + 0]);
4079
316k
  abs_mvd_greater0_flag[1] = tctx->cabac_decoder.decode_bit(
4080
316k
                                              &tctx->ctx_model[CONTEXT_MODEL_ABS_MVD_GREATER01_FLAG + 0]);
4081
4082
316k
  int abs_mvd_greater1_flag[2];
4083
316k
  if (abs_mvd_greater0_flag[0]) {
4084
214k
    abs_mvd_greater1_flag[0] = tctx->cabac_decoder.decode_bit(
4085
214k
                                                &tctx->ctx_model[CONTEXT_MODEL_ABS_MVD_GREATER01_FLAG + 1]);
4086
214k
  }
4087
101k
  else {
4088
101k
    abs_mvd_greater1_flag[0] = 0;
4089
101k
  }
4090
4091
316k
  if (abs_mvd_greater0_flag[1]) {
4092
214k
    abs_mvd_greater1_flag[1] = tctx->cabac_decoder.decode_bit(
4093
214k
                                                &tctx->ctx_model[CONTEXT_MODEL_ABS_MVD_GREATER01_FLAG + 1]);
4094
214k
  }
4095
102k
  else {
4096
102k
    abs_mvd_greater1_flag[1] = 0;
4097
102k
  }
4098
4099
4100
316k
  int mvd_sign_flag[2];
4101
316k
  int16_t value[2];
4102
4103
950k
  for (int c = 0; c < 2; c++) {
4104
633k
    if (abs_mvd_greater0_flag[c]) {
4105
429k
      int32_t absMvd;
4106
429k
      if (abs_mvd_greater1_flag[c]) {
4107
81.5k
        uint32_t abs_mvd_minus2 = tctx->cabac_decoder.decode_EGk_bypass( 1);
4108
        // MVD is clipped to [-32768, 32767], so cap abs value at 32768
4109
81.5k
        absMvd = static_cast<int32_t>(std::min(abs_mvd_minus2, uint32_t{32768 - 2})) + 2;
4110
81.5k
      }
4111
347k
      else {
4112
347k
        absMvd = 1;
4113
347k
      }
4114
4115
429k
      mvd_sign_flag[c] = tctx->cabac_decoder.decode_bypass();
4116
429k
      int32_t mvd = mvd_sign_flag[c] ? -absMvd : absMvd;
4117
429k
      value[c] = Clip3(-32768, 32767, mvd);
4118
429k
    }
4119
204k
    else {
4120
204k
      value[c] = 0;
4121
204k
    }
4122
633k
  }
4123
4124
316k
  tctx->motion.mvd[refList][0] = value[0];
4125
316k
  tctx->motion.mvd[refList][1] = value[1];
4126
4127
316k
  logtrace(LogSlice, "MVD[%d;%d|%d] = %d;%d\n", x0, y0, refList, value[0], value[1]);
4128
316k
}
4129
4130
4131
void read_prediction_unit_SKIP(thread_context* tctx,
4132
                               int x0, int y0,
4133
                               int nPbW, int nPbH)
4134
435k
{
4135
435k
  int merge_idx = decode_merge_idx(tctx);
4136
4137
435k
  tctx->motion.merge_idx = merge_idx;
4138
435k
  tctx->motion.merge_flag = true;
4139
4140
435k
  logtrace(LogSlice, "prediction skip 2Nx2N, merge_idx: %d\n", merge_idx);
4141
435k
}
4142
4143
4144
/* xC/yC : CB position
4145
   xB/yB : position offset of the PB
4146
   nPbW/nPbH : size of PB
4147
   nCS   : CB size
4148
 */
4149
void read_prediction_unit(thread_context* tctx,
4150
                          int xC, int yC, int xB, int yB,
4151
                          int nPbW, int nPbH,
4152
                          int ctDepth, int nCS, int partIdx)
4153
589k
{
4154
589k
  logtrace(LogSlice, "read_prediction_unit %d;%d %dx%d\n", xC + xB, yC + xB, nPbW, nPbH);
4155
4156
589k
  int x0 = xC + xB;
4157
589k
  int y0 = yC + yB;
4158
4159
589k
  slice_segment_header* shdr = tctx->shdr;
4160
4161
589k
  int merge_flag = decode_merge_flag(tctx);
4162
589k
  tctx->motion.merge_flag = merge_flag;
4163
4164
589k
  if (merge_flag) {
4165
284k
    int merge_idx = decode_merge_idx(tctx);
4166
4167
284k
    logtrace(LogSlice, "prediction unit %d,%d, merge mode, index: %d\n", x0, y0, merge_idx);
4168
4169
284k
    tctx->motion.merge_idx = merge_idx;
4170
284k
  }
4171
304k
  else {
4172
    // no merge flag
4173
304k
    enum InterPredIdc inter_pred_idc;
4174
4175
304k
    if (shdr->slice_type == SLICE_TYPE_B) {
4176
243k
      inter_pred_idc = decode_inter_pred_idc(tctx, x0, y0, nPbW, nPbH, ctDepth);
4177
243k
    }
4178
61.0k
    else {
4179
61.0k
      inter_pred_idc = PRED_L0;
4180
61.0k
    }
4181
4182
304k
    tctx->motion.inter_pred_idc = inter_pred_idc; // set_inter_pred_idc(ctx,x0,y0, inter_pred_idc);
4183
4184
304k
    if (inter_pred_idc != PRED_L1) {
4185
295k
      int ref_idx_l0 = decode_ref_idx_lX(tctx, shdr->num_ref_idx_l0_active);
4186
4187
      // NOTE: case for only one reference frame is handles in decode_ref_idx_lX()
4188
295k
      if (ref_idx_l0 < 0 || ref_idx_l0 >= MAX_NUM_REF_PICS) {
4189
0
        tctx->img->integrity = INTEGRITY_DECODING_ERRORS;
4190
0
        tctx->decctx->add_warning(DE265_WARNING_NONEXISTING_REFERENCE_PICTURE_ACCESSED, false);
4191
0
        return;
4192
0
      }
4193
295k
      tctx->motion.refIdx[0] = ref_idx_l0;
4194
4195
295k
      read_mvd_coding(tctx, x0, y0, 0);
4196
4197
295k
      int mvp_l0_flag = decode_mvp_lx_flag(tctx); // l0
4198
295k
      tctx->motion.mvp_l0_flag = mvp_l0_flag;
4199
4200
295k
      logtrace(LogSlice, "prediction unit %d,%d, L0, refIdx=%d mvp_l0_flag:%d\n",
4201
295k
               x0, y0, tctx->motion.refIdx[0], mvp_l0_flag);
4202
295k
    }
4203
4204
304k
    if (inter_pred_idc != PRED_L0) {
4205
36.4k
      int ref_idx_l1 = decode_ref_idx_lX(tctx, shdr->num_ref_idx_l1_active);
4206
4207
      // NOTE: case for only one reference frame is handles in decode_ref_idx_lX()
4208
36.4k
      if (ref_idx_l1 < 0 || ref_idx_l1 >= MAX_NUM_REF_PICS) {
4209
0
        tctx->img->integrity = INTEGRITY_DECODING_ERRORS;
4210
0
        tctx->decctx->add_warning(DE265_WARNING_NONEXISTING_REFERENCE_PICTURE_ACCESSED, false);
4211
0
        return;
4212
0
      }
4213
36.4k
      tctx->motion.refIdx[1] = ref_idx_l1;
4214
4215
36.4k
      if (shdr->mvd_l1_zero_flag &&
4216
22.9k
          inter_pred_idc == PRED_BI) {
4217
15.0k
        tctx->motion.mvd[1][0] = 0;
4218
15.0k
        tctx->motion.mvd[1][1] = 0;
4219
15.0k
      }
4220
21.3k
      else {
4221
21.3k
        read_mvd_coding(tctx, x0, y0, 1);
4222
21.3k
      }
4223
4224
36.4k
      int mvp_l1_flag = decode_mvp_lx_flag(tctx); // l1
4225
36.4k
      tctx->motion.mvp_l1_flag = mvp_l1_flag;
4226
4227
36.4k
      logtrace(LogSlice, "prediction unit %d,%d, L1, refIdx=%d mvp_l1_flag:%d\n",
4228
36.4k
               x0, y0, tctx->motion.refIdx[1], mvp_l1_flag);
4229
36.4k
    }
4230
304k
  }
4231
4232
4233
589k
  decode_prediction_unit(tctx->decctx, tctx->shdr, tctx->img, tctx->motion,
4234
589k
                         xC, yC, xB, yB, nCS, nPbW, nPbH, partIdx);
4235
589k
}
4236
4237
4238
template<class pixel_t>
4239
void read_pcm_samples_internal(thread_context* tctx, int x0, int y0, int log2CbSize,
4240
                               int cIdx, bitreader& br)
4241
357
{
4242
357
  const seq_parameter_set& sps = tctx->img->get_sps();
4243
4244
357
  int nPcmBits;
4245
357
  int bitDepth;
4246
4247
357
  int w = 1 << log2CbSize;
4248
357
  int h = 1 << log2CbSize;
4249
4250
357
  if (cIdx > 0) {
4251
238
    w /= sps.SubWidthC;
4252
238
    h /= sps.SubHeightC;
4253
4254
238
    x0 /= sps.SubWidthC;
4255
238
    y0 /= sps.SubHeightC;
4256
4257
238
    nPcmBits = sps.pcm_sample_bit_depth_chroma;
4258
238
    bitDepth = sps.BitDepth_C;
4259
238
  }
4260
119
  else {
4261
119
    nPcmBits = sps.pcm_sample_bit_depth_luma;
4262
119
    bitDepth = sps.BitDepth_Y;
4263
119
  }
4264
4265
357
  pixel_t* ptr;
4266
357
  int stride;
4267
357
  ptr = tctx->img->get_image_plane_at_pos_NEW<pixel_t>(cIdx, x0, y0);
4268
357
  stride = tctx->img->get_image_stride(cIdx);
4269
4270
357
  int shift = bitDepth - nPcmBits;
4271
4272
  // a shift < 0 may result when the SPS sequence header is broken
4273
357
  if (shift < 0) {
4274
0
    shift = 0;
4275
0
  }
4276
4277
3.74k
  for (int y = 0; y < h; y++)
4278
49.6k
    for (int x = 0; x < w; x++) {
4279
46.2k
      int value = br.get_bits(nPcmBits);
4280
46.2k
      ptr[y * stride + x] = value << shift;
4281
46.2k
    }
4282
357
}
void read_pcm_samples_internal<unsigned short>(thread_context*, int, int, int, int, bitreader&)
Line
Count
Source
4241
192
{
4242
192
  const seq_parameter_set& sps = tctx->img->get_sps();
4243
4244
192
  int nPcmBits;
4245
192
  int bitDepth;
4246
4247
192
  int w = 1 << log2CbSize;
4248
192
  int h = 1 << log2CbSize;
4249
4250
192
  if (cIdx > 0) {
4251
142
    w /= sps.SubWidthC;
4252
142
    h /= sps.SubHeightC;
4253
4254
142
    x0 /= sps.SubWidthC;
4255
142
    y0 /= sps.SubHeightC;
4256
4257
142
    nPcmBits = sps.pcm_sample_bit_depth_chroma;
4258
142
    bitDepth = sps.BitDepth_C;
4259
142
  }
4260
50
  else {
4261
50
    nPcmBits = sps.pcm_sample_bit_depth_luma;
4262
50
    bitDepth = sps.BitDepth_Y;
4263
50
  }
4264
4265
192
  pixel_t* ptr;
4266
192
  int stride;
4267
192
  ptr = tctx->img->get_image_plane_at_pos_NEW<pixel_t>(cIdx, x0, y0);
4268
192
  stride = tctx->img->get_image_stride(cIdx);
4269
4270
192
  int shift = bitDepth - nPcmBits;
4271
4272
  // a shift < 0 may result when the SPS sequence header is broken
4273
192
  if (shift < 0) {
4274
0
    shift = 0;
4275
0
  }
4276
4277
1.90k
  for (int y = 0; y < h; y++)
4278
24.3k
    for (int x = 0; x < w; x++) {
4279
22.5k
      int value = br.get_bits(nPcmBits);
4280
22.5k
      ptr[y * stride + x] = value << shift;
4281
22.5k
    }
4282
192
}
void read_pcm_samples_internal<unsigned char>(thread_context*, int, int, int, int, bitreader&)
Line
Count
Source
4241
165
{
4242
165
  const seq_parameter_set& sps = tctx->img->get_sps();
4243
4244
165
  int nPcmBits;
4245
165
  int bitDepth;
4246
4247
165
  int w = 1 << log2CbSize;
4248
165
  int h = 1 << log2CbSize;
4249
4250
165
  if (cIdx > 0) {
4251
96
    w /= sps.SubWidthC;
4252
96
    h /= sps.SubHeightC;
4253
4254
96
    x0 /= sps.SubWidthC;
4255
96
    y0 /= sps.SubHeightC;
4256
4257
96
    nPcmBits = sps.pcm_sample_bit_depth_chroma;
4258
96
    bitDepth = sps.BitDepth_C;
4259
96
  }
4260
69
  else {
4261
69
    nPcmBits = sps.pcm_sample_bit_depth_luma;
4262
69
    bitDepth = sps.BitDepth_Y;
4263
69
  }
4264
4265
165
  pixel_t* ptr;
4266
165
  int stride;
4267
165
  ptr = tctx->img->get_image_plane_at_pos_NEW<pixel_t>(cIdx, x0, y0);
4268
165
  stride = tctx->img->get_image_stride(cIdx);
4269
4270
165
  int shift = bitDepth - nPcmBits;
4271
4272
  // a shift < 0 may result when the SPS sequence header is broken
4273
165
  if (shift < 0) {
4274
0
    shift = 0;
4275
0
  }
4276
4277
1.84k
  for (int y = 0; y < h; y++)
4278
25.3k
    for (int x = 0; x < w; x++) {
4279
23.6k
      int value = br.get_bits(nPcmBits);
4280
23.6k
      ptr[y * stride + x] = value << shift;
4281
23.6k
    }
4282
165
}
4283
4284
static void read_pcm_samples(thread_context* tctx, int x0, int y0, int log2CbSize)
4285
119
{
4286
119
  bitreader br(tctx->cabac_decoder.bitstream_curr,
4287
119
               tctx->cabac_decoder.bitstream_end - tctx->cabac_decoder.bitstream_curr);
4288
4289
119
  if (tctx->img->high_bit_depth(0)) {
4290
50
    read_pcm_samples_internal<uint16_t>(tctx, x0, y0, log2CbSize, 0, br);
4291
50
  }
4292
69
  else {
4293
69
    read_pcm_samples_internal<uint8_t>(tctx, x0, y0, log2CbSize, 0, br);
4294
69
  }
4295
4296
119
  if (tctx->img->get_sps().ChromaArrayType != CHROMA_MONO) {
4297
119
    if (tctx->img->high_bit_depth(1)) {
4298
71
      read_pcm_samples_internal<uint16_t>(tctx, x0, y0, log2CbSize, 1, br);
4299
71
      read_pcm_samples_internal<uint16_t>(tctx, x0, y0, log2CbSize, 2, br);
4300
71
    }
4301
48
    else {
4302
48
      read_pcm_samples_internal<uint8_t>(tctx, x0, y0, log2CbSize, 1, br);
4303
48
      read_pcm_samples_internal<uint8_t>(tctx, x0, y0, log2CbSize, 2, br);
4304
48
    }
4305
119
  }
4306
4307
119
  br.prepare_for_CABAC();
4308
119
  tctx->cabac_decoder.bitstream_curr = br.data;
4309
119
  tctx->cabac_decoder.init_CABAC();
4310
119
}
4311
4312
4313
int map_chroma_pred_mode(int intra_chroma_pred_mode, int IntraPredMode)
4314
714k
{
4315
714k
  if (intra_chroma_pred_mode == 4) {
4316
371k
    return IntraPredMode;
4317
371k
  }
4318
343k
  else {
4319
343k
    static const enum IntraPredMode IntraPredModeCCand[4] = {
4320
343k
      INTRA_PLANAR,
4321
343k
      INTRA_ANGULAR_26, // vertical
4322
343k
      INTRA_ANGULAR_10, // horizontal
4323
343k
      INTRA_DC
4324
343k
    };
4325
4326
343k
    int IntraPredModeC = IntraPredModeCCand[intra_chroma_pred_mode];
4327
343k
    if (IntraPredModeC == IntraPredMode) {
4328
37.4k
      return INTRA_ANGULAR_34;
4329
37.4k
    }
4330
305k
    else {
4331
305k
      return IntraPredModeC;
4332
305k
    }
4333
343k
  }
4334
714k
}
4335
4336
// h.265-V2 Table 8-3
4337
static const uint8_t map_chroma_422[35] = {
4338
  0, 1, 2, 2, 2, 2, 3, 5, 7, 8, 10, 12, 13, 15, 17, 18, 19, 20,
4339
  21, 22, 23, 23, 24, 24, 25, 25, 26, 27, 27, 28, 28, 29, 29, 30, 31
4340
};
4341
4342
void read_coding_unit(thread_context* tctx,
4343
                      int x0, int y0, // position of coding unit in frame
4344
                      int log2CbSize,
4345
                      int ctDepth)
4346
1.51M
{
4347
1.51M
  de265_image* img = tctx->img;
4348
1.51M
  const seq_parameter_set& sps = img->get_sps();
4349
1.51M
  const pic_parameter_set& pps = img->get_pps();
4350
1.51M
  slice_segment_header* shdr = tctx->shdr;
4351
4352
1.51M
  logtrace(LogSlice, "- read_coding_unit %d;%d cbsize:%d\n", x0, y0, 1 << log2CbSize);
4353
4354
4355
  //QQprintf("- read_coding_unit %d;%d cbsize:%d\n",x0,y0,1<<log2CbSize);
4356
4357
1.51M
  img->set_log2CbSize(x0, y0, log2CbSize, true);
4358
4359
  /* This is only required on corrupted input streams.
4360
     It may happen that there are several slices in the image that overlap.
4361
     In this case, flags would accumulate from both slices.
4362
  */
4363
1.51M
  img->clear_split_transform_flags(x0, y0, log2CbSize);
4364
4365
1.51M
  int nCbS = 1 << log2CbSize; // number of coding block samples
4366
4367
1.51M
  decode_quantization_parameters(tctx, x0, y0, x0, y0);
4368
4369
4370
1.51M
  if (pps.transquant_bypass_enable_flag) {
4371
1.13M
    int transquant_bypass = decode_transquant_bypass_flag(tctx);
4372
4373
1.13M
    tctx->cu_transquant_bypass_flag = transquant_bypass;
4374
4375
1.13M
    if (transquant_bypass) {
4376
471k
      img->set_cu_transquant_bypass(x0, y0, log2CbSize);
4377
471k
    }
4378
1.13M
  }
4379
372k
  else {
4380
372k
    tctx->cu_transquant_bypass_flag = 0;
4381
372k
  }
4382
4383
1.51M
  uint8_t cu_skip_flag = 0;
4384
1.51M
  if (shdr->slice_type != SLICE_TYPE_I) {
4385
805k
    cu_skip_flag = decode_cu_skip_flag(tctx, x0, y0, ctDepth);
4386
805k
  }
4387
4388
1.51M
  int IntraSplitFlag = 0;
4389
4390
1.51M
  enum PredMode cuPredMode;
4391
4392
1.51M
  if (cu_skip_flag) {
4393
435k
    read_prediction_unit_SKIP(tctx, x0, y0, nCbS, nCbS);
4394
4395
435k
    img->set_PartMode(x0, y0, PART_2Nx2N); // need this for deblocking filter
4396
435k
    img->set_pred_mode(x0, y0, log2CbSize, MODE_SKIP);
4397
435k
    cuPredMode = MODE_SKIP;
4398
4399
435k
    logtrace(LogSlice, "CU pred mode: SKIP\n");
4400
4401
4402
    // DECODE
4403
4404
435k
    int nCS_L = 1 << log2CbSize;
4405
435k
    decode_prediction_unit(tctx->decctx, tctx->shdr, tctx->img, tctx->motion,
4406
435k
                           x0, y0, 0, 0, nCS_L, nCS_L, nCS_L, 0);
4407
435k
  }
4408
1.07M
  else /* not skipped */ {
4409
1.07M
    if (shdr->slice_type != SLICE_TYPE_I) {
4410
370k
      int pred_mode_flag = decode_pred_mode_flag(tctx);
4411
370k
      cuPredMode = pred_mode_flag ? MODE_INTRA : MODE_INTER;
4412
370k
    }
4413
705k
    else {
4414
705k
      cuPredMode = MODE_INTRA;
4415
705k
    }
4416
4417
1.07M
    img->set_pred_mode(x0, y0, log2CbSize, cuPredMode);
4418
4419
1.07M
    logtrace(LogSlice, "CU pred mode: %s\n", cuPredMode == MODE_INTRA ? "INTRA" : "INTER");
4420
4421
4422
1.07M
    enum PartMode PartMode;
4423
4424
1.07M
    if (cuPredMode != MODE_INTRA ||
4425
1.04M
        log2CbSize == sps.Log2MinCbSizeY) {
4426
1.04M
      PartMode = decode_part_mode(tctx, cuPredMode, log2CbSize);
4427
4428
1.04M
      if (PartMode == PART_NxN && cuPredMode == MODE_INTRA) {
4429
531k
        IntraSplitFlag = 1;
4430
531k
      }
4431
1.04M
    }
4432
30.1k
    else {
4433
30.1k
      PartMode = PART_2Nx2N;
4434
30.1k
    }
4435
4436
1.07M
    img->set_PartMode(x0, y0, PartMode); // needed for deblocking ?
4437
4438
1.07M
    logtrace(LogSlice, "PartMode: %s\n", part_mode_name(PartMode));
4439
4440
4441
1.07M
    bool pcm_flag = false;
4442
4443
1.07M
    if (cuPredMode == MODE_INTRA) {
4444
714k
      if (PartMode == PART_2Nx2N && sps.pcm_enabled_flag &&
4445
9.40k
          log2CbSize >= sps.Log2MinIpcmCbSizeY &&
4446
6.16k
          log2CbSize <= sps.Log2MaxIpcmCbSizeY) {
4447
5.41k
        pcm_flag = tctx->cabac_decoder.decode_term_bit();
4448
5.41k
      }
4449
4450
714k
      if (pcm_flag) {
4451
119
        img->set_pcm_flag(x0, y0, log2CbSize);
4452
4453
119
        read_pcm_samples(tctx, x0, y0, log2CbSize);
4454
119
      }
4455
714k
      else {
4456
714k
        int pbOffset = (PartMode == PART_NxN) ? (nCbS / 2) : nCbS;
4457
714k
        int log2IntraPredSize = (PartMode == PART_NxN) ? (log2CbSize - 1) : log2CbSize;
4458
4459
714k
        logtrace(LogSlice, "nCbS:%d pbOffset:%d\n", nCbS, pbOffset);
4460
4461
714k
        int prev_intra_luma_pred_flag[4];
4462
4463
714k
        int idx = 0;
4464
1.96M
        for (int j = 0; j < nCbS; j += pbOffset)
4465
3.55M
          for (int i = 0; i < nCbS; i += pbOffset) {
4466
2.30M
            prev_intra_luma_pred_flag[idx++] = decode_prev_intra_luma_pred_flag(tctx);
4467
2.30M
          }
4468
4469
714k
        int mpm_idx[4], rem_intra_luma_pred_mode[4];
4470
714k
        idx = 0;
4471
4472
714k
        int availableA0 = check_CTB_available(img, x0, y0, x0 - 1, y0);
4473
714k
        int availableB0 = check_CTB_available(img, x0, y0, x0, y0 - 1);
4474
4475
1.96M
        for (int j = 0; j < nCbS; j += pbOffset)
4476
3.55M
          for (int i = 0; i < nCbS; i += pbOffset) {
4477
2.30M
            if (prev_intra_luma_pred_flag[idx]) {
4478
747k
              mpm_idx[idx] = decode_mpm_idx(tctx);
4479
747k
            }
4480
1.56M
            else {
4481
1.56M
              rem_intra_luma_pred_mode[idx] = decode_rem_intra_luma_pred_mode(tctx);
4482
1.56M
            }
4483
4484
4485
2.30M
            int x = x0 + i;
4486
2.30M
            int y = y0 + j;
4487
4488
            // --- find intra prediction mode ---
4489
4490
2.30M
            int IntraPredMode;
4491
4492
2.30M
            int availableA = availableA0 || (i > 0); // left candidate always available for right blk
4493
2.30M
            int availableB = availableB0 || (j > 0); // top candidate always available for bottom blk
4494
4495
4496
2.30M
            int PUidx = (x >> sps.Log2MinPUSize) + (y >> sps.Log2MinPUSize) * sps.PicWidthInMinPUs;
4497
4498
2.30M
            enum IntraPredMode candModeList[3];
4499
4500
2.30M
            fillIntraPredModeCandidates(candModeList, x, y, PUidx,
4501
2.30M
                                        availableA, availableB, img);
4502
4503
9.23M
            for (int i = 0; i < 3; i++)
4504
6.92M
              logtrace(LogSlice, "candModeList[%d] = %d\n", i, candModeList[i]);
4505
4506
2.30M
            if (prev_intra_luma_pred_flag[idx] == 1) {
4507
747k
              IntraPredMode = candModeList[mpm_idx[idx]];
4508
747k
            }
4509
1.56M
            else {
4510
              // sort candModeList
4511
4512
1.56M
              if (candModeList[0] > candModeList[1]) {
4513
260k
                std::swap(candModeList[0], candModeList[1]);
4514
260k
              }
4515
1.56M
              if (candModeList[0] > candModeList[2]) {
4516
258k
                std::swap(candModeList[0], candModeList[2]);
4517
258k
              }
4518
1.56M
              if (candModeList[1] > candModeList[2]) {
4519
970k
                std::swap(candModeList[1], candModeList[2]);
4520
970k
              }
4521
4522
              // skip modes in the list
4523
              // (we have 35 modes. skipping the 3 in the list gives us 32, which can be selected by 5 bits)
4524
1.56M
              IntraPredMode = rem_intra_luma_pred_mode[idx];
4525
6.24M
              for (int n = 0; n <= 2; n++) {
4526
4.68M
                if (IntraPredMode >= candModeList[n]) { IntraPredMode++; }
4527
4.68M
              }
4528
1.56M
            }
4529
4530
2.30M
            logtrace(LogSlice, "IntraPredMode[%d][%d] = %d (log2blk:%d)\n", x, y, IntraPredMode, log2IntraPredSize);
4531
4532
2.30M
            img->set_IntraPredMode(PUidx, log2IntraPredSize,
4533
2.30M
                                   (enum IntraPredMode) IntraPredMode);
4534
4535
2.30M
            idx++;
4536
2.30M
          }
4537
4538
4539
        // set chroma intra prediction mode
4540
4541
714k
        if (sps.ChromaArrayType == CHROMA_444) {
4542
          // chroma 4:4:4
4543
4544
0
          idx = 0;
4545
0
          for (int j = 0; j < nCbS; j += pbOffset)
4546
0
            for (int i = 0; i < nCbS; i += pbOffset) {
4547
0
              int x = x0 + i;
4548
0
              int y = y0 + j;
4549
4550
0
              int intra_chroma_pred_mode = decode_intra_chroma_pred_mode(tctx);
4551
0
              int IntraPredMode = img->get_IntraPredMode(x, y);
4552
4553
0
              int IntraPredModeC = map_chroma_pred_mode(intra_chroma_pred_mode, IntraPredMode);
4554
4555
0
              logtrace(LogSlice, "IntraPredModeC[%d][%d]: %d (blksize:%d)\n", x, y, IntraPredModeC,
4556
0
                       1 << log2IntraPredSize);
4557
4558
0
              img->set_IntraPredModeC(x, y, log2IntraPredSize,
4559
0
                                      (enum IntraPredMode) IntraPredModeC,
4560
0
                                      intra_chroma_pred_mode == 4);
4561
0
              idx++;
4562
0
            }
4563
0
        }
4564
714k
        else if (sps.ChromaArrayType != CHROMA_MONO) {
4565
          // chroma 4:2:0 and 4:2:2
4566
4567
714k
          int intra_chroma_pred_mode = decode_intra_chroma_pred_mode(tctx);
4568
714k
          int IntraPredMode = img->get_IntraPredMode(x0, y0);
4569
714k
          logtrace(LogSlice, "IntraPredMode: %d\n", IntraPredMode);
4570
714k
          int IntraPredModeC = map_chroma_pred_mode(intra_chroma_pred_mode, IntraPredMode);
4571
4572
714k
          if (sps.ChromaArrayType == CHROMA_422) {
4573
11.8k
            IntraPredModeC = map_chroma_422[IntraPredModeC];
4574
11.8k
          }
4575
4576
714k
          img->set_IntraPredModeC(x0, y0, log2CbSize,
4577
714k
                                  (enum IntraPredMode) IntraPredModeC,
4578
714k
                                  intra_chroma_pred_mode == 4);
4579
714k
        }
4580
714k
      }
4581
714k
    }
4582
361k
    else {
4583
      // INTER
4584
361k
      int nCS = 1 << log2CbSize;
4585
4586
361k
      if (PartMode == PART_2Nx2N) {
4587
133k
        read_prediction_unit(tctx, x0, y0, 0, 0, nCbS, nCbS, ctDepth, nCS, 0);
4588
133k
      }
4589
228k
      else if (PartMode == PART_2NxN) {
4590
90.7k
        read_prediction_unit(tctx, x0, y0, 0, 0, nCbS, nCbS / 2, ctDepth, nCS, 0);
4591
90.7k
        read_prediction_unit(tctx, x0, y0, 0, nCbS / 2, nCbS, nCbS / 2, ctDepth, nCS, 1);
4592
90.7k
      }
4593
137k
      else if (PartMode == PART_Nx2N) {
4594
116k
        read_prediction_unit(tctx, x0, y0, 0, 0, nCbS / 2, nCbS, ctDepth, nCS, 0);
4595
116k
        read_prediction_unit(tctx, x0, y0, nCbS / 2, 0, nCbS / 2, nCbS, ctDepth, nCS, 1);
4596
116k
      }
4597
20.5k
      else if (PartMode == PART_2NxnU) {
4598
9.25k
        read_prediction_unit(tctx, x0, y0, 0, 0, nCbS, nCbS / 4, ctDepth, nCS, 0);
4599
9.25k
        read_prediction_unit(tctx, x0, y0, 0, nCbS / 4, nCbS, nCbS * 3 / 4, ctDepth, nCS, 1);
4600
9.25k
      }
4601
11.3k
      else if (PartMode == PART_2NxnD) {
4602
1.53k
        read_prediction_unit(tctx, x0, y0, 0, 0, nCbS, nCbS * 3 / 4, ctDepth, nCS, 0);
4603
1.53k
        read_prediction_unit(tctx, x0, y0, 0, nCbS * 3 / 4, nCbS, nCbS / 4, ctDepth, nCS, 1);
4604
1.53k
      }
4605
9.79k
      else if (PartMode == PART_nLx2N) {
4606
8.43k
        read_prediction_unit(tctx, x0, y0, 0, 0, nCbS / 4, nCbS, ctDepth, nCS, 0);
4607
8.43k
        read_prediction_unit(tctx, x0, y0, nCbS / 4, 0, nCbS * 3 / 4, nCbS, ctDepth, nCS, 1);
4608
8.43k
      }
4609
1.36k
      else if (PartMode == PART_nRx2N) {
4610
1.32k
        read_prediction_unit(tctx, x0, y0, 0, 0, nCbS * 3 / 4, nCbS, ctDepth, nCS, 0);
4611
1.32k
        read_prediction_unit(tctx, x0, y0, nCbS * 3 / 4, 0, nCbS / 4, nCbS, ctDepth, nCS, 1);
4612
1.32k
      }
4613
33
      else if (PartMode == PART_NxN) {
4614
33
        read_prediction_unit(tctx, x0, y0, 0, 0, nCbS / 2, nCbS / 2, ctDepth, nCS, 0);
4615
33
        read_prediction_unit(tctx, x0, y0, nCbS / 2, 0, nCbS / 2, nCbS / 2, ctDepth, nCS, 1);
4616
33
        read_prediction_unit(tctx, x0, y0, 0, nCbS / 2, nCbS / 2, nCbS / 2, ctDepth, nCS, 2);
4617
33
        read_prediction_unit(tctx, x0, y0, nCbS / 2, nCbS / 2, nCbS / 2, nCbS / 2, ctDepth, nCS, 3);
4618
33
      }
4619
0
      else {
4620
0
        assert(0); // undefined PartMode
4621
0
      }
4622
361k
    } // INTER
4623
4624
4625
    // decode residual
4626
4627
1.07M
    if (!pcm_flag) {
4628
      // !pcm
4629
1.07M
      bool rqt_root_cbf;
4630
4631
1.07M
      uint8_t merge_flag = tctx->motion.merge_flag; // !!get_merge_flag(ctx,x0,y0);
4632
4633
1.07M
      if (cuPredMode != MODE_INTRA &&
4634
361k
          !(PartMode == PART_2Nx2N && merge_flag)) {
4635
291k
        rqt_root_cbf = !!decode_rqt_root_cbf(tctx);
4636
291k
      }
4637
784k
      else {
4638
        /* rqt_root_cbf=1 is inferred for Inter blocks with 2Nx2N, merge mode.
4639
           These must be some residual data, because otherwise, the CB could
4640
           also be coded in SKIP mode.
4641
         */
4642
4643
784k
        rqt_root_cbf = true;
4644
784k
      }
4645
4646
      //set_rqt_root_cbf(ctx,x0,y0, log2CbSize, rqt_root_cbf);
4647
4648
1.07M
      if (rqt_root_cbf) {
4649
920k
        int MaxTrafoDepth;
4650
4651
920k
        if (cuPredMode == MODE_INTRA) {
4652
714k
          MaxTrafoDepth = sps.max_transform_hierarchy_depth_intra + IntraSplitFlag;
4653
714k
        }
4654
205k
        else {
4655
205k
          MaxTrafoDepth = sps.max_transform_hierarchy_depth_inter;
4656
205k
        }
4657
4658
920k
        logtrace(LogSlice, "MaxTrafoDepth: %d\n", MaxTrafoDepth);
4659
4660
920k
        uint8_t initial_chroma_cbf = 1;
4661
920k
        if (sps.ChromaArrayType == CHROMA_MONO) {
4662
0
          initial_chroma_cbf = 0;
4663
0
        }
4664
4665
920k
        read_transform_tree(tctx, x0, y0, x0, y0, x0, y0, log2CbSize, 0, 0,
4666
920k
                            MaxTrafoDepth, IntraSplitFlag, cuPredMode,
4667
920k
                            initial_chroma_cbf, initial_chroma_cbf);
4668
920k
      }
4669
1.07M
    } // !pcm
4670
1.07M
  }
4671
1.51M
}
4672
4673
4674
// ------------------------------------------------------------------------------------------
4675
4676
4677
void read_coding_quadtree(thread_context* tctx,
4678
                          int x0, int y0,
4679
                          int log2CbSize,
4680
                          int ctDepth)
4681
2.04M
{
4682
2.04M
  logtrace(LogSlice, "- read_coding_quadtree %d;%d cbsize:%d depth:%d POC:%d\n", x0, y0, 1 << log2CbSize, ctDepth, tctx->img->PicOrderCntVal);
4683
4684
2.04M
  de265_image* img = tctx->img;
4685
2.04M
  const seq_parameter_set& sps = img->get_sps();
4686
2.04M
  const pic_parameter_set& pps = img->get_pps();
4687
4688
2.04M
  int split_flag;
4689
4690
  // We only send a split flag if CU is larger than minimum size and
4691
  // completely contained within the image area.
4692
  // If it is partly outside the image area and not at minimum size,
4693
  // it is split. If already at minimum size, it is not split further.
4694
2.04M
  if (x0 + (1 << log2CbSize) <= sps.pic_width_in_luma_samples &&
4695
2.04M
      y0 + (1 << log2CbSize) <= sps.pic_height_in_luma_samples &&
4696
1.89M
      log2CbSize > sps.Log2MinCbSizeY) {
4697
549k
    split_flag = decode_split_cu_flag(tctx, x0, y0, ctDepth);
4698
549k
  }
4699
1.49M
  else {
4700
1.49M
    if (log2CbSize > sps.Log2MinCbSizeY) { split_flag = 1; }
4701
1.34M
    else { split_flag = 0; }
4702
1.49M
  }
4703
4704
4705
2.04M
  if (pps.cu_qp_delta_enabled_flag &&
4706
2.03M
      log2CbSize >= pps.Log2MinCuQpDeltaSize) {
4707
779k
    tctx->IsCuQpDeltaCoded = 0;
4708
779k
    tctx->CuQpDelta = 0;
4709
779k
  }
4710
1.26M
  else {
4711
    // shdr->CuQpDelta = 0; // TODO check: is this the right place to set to default value ?
4712
1.26M
  }
4713
4714
4715
2.04M
  if (tctx->shdr->cu_chroma_qp_offset_enabled_flag &&
4716
0
      log2CbSize >= pps.Log2MinCuChromaQpOffsetSize) {
4717
0
    tctx->IsCuChromaQpOffsetCoded = 0;
4718
0
  }
4719
4720
2.04M
  if (split_flag) {
4721
537k
    int x1 = x0 + (1 << (log2CbSize - 1));
4722
537k
    int y1 = y0 + (1 << (log2CbSize - 1));
4723
4724
537k
    read_coding_quadtree(tctx, x0, y0, log2CbSize - 1, ctDepth + 1);
4725
4726
537k
    if (x1 < sps.pic_width_in_luma_samples)
4727
534k
      read_coding_quadtree(tctx, x1, y0, log2CbSize - 1, ctDepth + 1);
4728
4729
537k
    if (y1 < sps.pic_height_in_luma_samples)
4730
416k
      read_coding_quadtree(tctx, x0, y1, log2CbSize - 1, ctDepth + 1);
4731
4732
537k
    if (x1 < sps.pic_width_in_luma_samples &&
4733
534k
        y1 < sps.pic_height_in_luma_samples)
4734
414k
      read_coding_quadtree(tctx, x1, y1, log2CbSize - 1, ctDepth + 1);
4735
537k
  }
4736
1.51M
  else {
4737
    // set ctDepth of this CU
4738
4739
1.51M
    img->set_ctDepth(x0, y0, log2CbSize, ctDepth);
4740
4741
1.51M
    read_coding_unit(tctx, x0, y0, log2CbSize, ctDepth);
4742
1.51M
  }
4743
4744
2.04M
  logtrace(LogSlice, "-\n");
4745
2.04M
}
4746
4747
4748
// ---------------------------------------------------------------------------
4749
4750
enum DecodeResult
4751
{
4752
  Decode_EndOfSliceSegment,
4753
  Decode_EndOfSubstream,
4754
  Decode_Error
4755
};
4756
4757
/* Decode CTBs until the end of sub-stream, the end-of-slice, or some error occurs.
4758
 */
4759
enum DecodeResult decode_substream(thread_context* tctx,
4760
                                   bool block_wpp, // block on WPP dependencies
4761
                                   bool first_independent_substream)
4762
5.30k
{
4763
5.30k
  const pic_parameter_set& pps = tctx->img->get_pps();
4764
5.30k
  const seq_parameter_set& sps = tctx->img->get_sps();
4765
4766
5.30k
  const uint16_t ctbW = sps.PicWidthInCtbsY;
4767
5.30k
  const uint16_t startCtbY = tctx->CtbY;
4768
4769
  //printf("start decoding substream at %d;%d\n",tctx->CtbX,tctx->CtbY);
4770
4771
  // in WPP mode: initialize CABAC model with stored model from row above
4772
4773
5.30k
  if ((!first_independent_substream || tctx->CtbY != startCtbY) &&
4774
1.92k
      pps.entropy_coding_sync_enabled_flag &&
4775
1.81k
      tctx->CtbY >= 1 && tctx->CtbX == 0) {
4776
1.81k
    if (sps.PicWidthInCtbsY > 1) {
4777
1.80k
      assert(tctx->CtbY >= 1);
4778
1.80k
      if (static_cast<size_t>(tctx->CtbY - 1) >= tctx->imgunit->ctx_models.size()) {
4779
0
        return Decode_Error;
4780
0
      }
4781
4782
      //printf("CTX wait on %d/%d\n",1,tctx->CtbY-1);
4783
4784
      // we have to wait until the context model data is there
4785
1.80k
      tctx->img->wait_for_progress(tctx->task, 1, tctx->CtbY - 1,CTB_PROGRESS_PREFILTER);
4786
4787
      // Copy the CABAC model (and StatCoeff state) saved by the row above.
4788
      // No lock is needed: the producer stores into ctx_models[CtbY-1] before
4789
      // it signals the progress of CTB (1, CtbY-1), and the acquire load in
4790
      // wait_for_progress() above pairs with that release store. The slot has
4791
      // exactly one producer and one consumer, and after the copy/release
4792
      // below nobody touches it again. See image_unit::ctx_models for why a
4793
      // consumer can never skip this wait.
4794
1.80k
      tctx->ctx_model = tctx->imgunit->ctx_models[(tctx->CtbY - 1)];
4795
1.80k
      tctx->imgunit->ctx_models[(tctx->CtbY - 1)].release(); // not used anymore
4796
4797
      // also restore the StatCoeff[] state for persistent_rice_adaptation
4798
9.03k
      for (int i = 0; i < 4; i++) {
4799
7.22k
        tctx->StatCoeff[i] = tctx->imgunit->StatCoeff_models[(tctx->CtbY - 1)][i];
4800
7.22k
      }
4801
1.80k
    }
4802
4
    else {
4803
4
      tctx->img->wait_for_progress(tctx->task, 0, tctx->CtbY - 1,CTB_PROGRESS_PREFILTER);
4804
4
      initialize_CABAC_models(tctx);
4805
4
    }
4806
1.81k
  }
4807
4808
4809
145k
  do {
4810
145k
    const uint32_t ctbx = tctx->CtbX;
4811
145k
    const uint32_t ctby = tctx->CtbY;
4812
4813
145k
    if (ctbx + ctby * ctbW >= pps.scan->CtbAddrRStoTS.size()) {
4814
0
      return Decode_Error;
4815
0
    }
4816
4817
145k
    if (ctbx >= sps.PicWidthInCtbsY ||
4818
145k
        ctby >= sps.PicHeightInCtbsY) {
4819
0
      return Decode_Error;
4820
0
    }
4821
4822
145k
    if (block_wpp && ctby > 0 && ctbx + 1 < ctbW) {
4823
      // TODO: if we are in tiles mode and at the right border, do not wait for x+1,y-1
4824
4825
      //printf("wait on %d/%d (%d)\n",ctbx+1,ctby-1, ctbx+1+(ctby-1)*sps->PicWidthInCtbsY);
4826
4827
21.1k
      tctx->img->wait_for_progress(tctx->task, ctbx + 1, ctby - 1, CTB_PROGRESS_PREFILTER);
4828
21.1k
    }
4829
4830
    //printf("%p: decode %d;%d\n", tctx, tctx->CtbX,tctx->CtbY);
4831
4832
4833
    // read and decode CTB
4834
4835
145k
    if (tctx->ctx_model.empty() == false) {
4836
422
      return Decode_Error;
4837
422
    }
4838
4839
145k
    read_coding_tree_unit(tctx);
4840
4841
4842
    // save CABAC-model for WPP (except in last CTB row)
4843
4844
145k
    if (pps.entropy_coding_sync_enabled_flag &&
4845
25.4k
        ctbx == 1 &&
4846
1.54k
        ctby + 1 < sps.PicHeightInCtbsY) {
4847
      // no storage for context table has been allocated
4848
1.43k
      if (tctx->imgunit->ctx_models.size() <= ctby) {
4849
0
        return Decode_Error;
4850
0
      }
4851
4852
      // Store an independent copy of the CABAC model (and StatCoeff state) for
4853
      // the row below to pick up. This store must stay ahead of the
4854
      // set_progress(CTB_PROGRESS_PREFILTER) for this CTB further down: that
4855
      // release store publishes the slot to the consumer row task, which waits
4856
      // for CTB (1, ctby) with an acquire load before reading it. No lock is
4857
      // needed, see image_unit::ctx_models.
4858
1.43k
      tctx->imgunit->ctx_models[ctby] = tctx->ctx_model;
4859
1.43k
      tctx->imgunit->ctx_models[ctby].decouple(); // store an independent copy
4860
4861
      // also save the StatCoeff[] state for persistent_rice_adaptation
4862
7.16k
      for (int i = 0; i < 4; i++) {
4863
5.72k
        tctx->imgunit->StatCoeff_models[ctby][i] = tctx->StatCoeff[i];
4864
5.72k
      }
4865
1.43k
    }
4866
4867
4868
    // end of slice segment ?
4869
4870
145k
    int end_of_slice_segment_flag = tctx->cabac_decoder.decode_term_bit();
4871
    //printf("end-of-slice flag: %d\n", end_of_slice_segment_flag);
4872
4873
145k
    if (end_of_slice_segment_flag) {
4874
      // at the end of the slice segment, we store the CABAC model if we need it
4875
      // because a dependent slice may follow
4876
4877
321
      if (pps.dependent_slice_segments_enabled_flag) {
4878
50
        tctx->shdr->ctx_model_storage = tctx->ctx_model;
4879
50
        tctx->shdr->ctx_model_storage.decouple(); // store an independent copy
4880
4881
        // also save the StatCoeff[] state for persistent_rice_adaptation
4882
250
        for (int i = 0; i < 4; i++) {
4883
200
          tctx->shdr->ctx_model_storage_StatCoeff[i] = tctx->StatCoeff[i];
4884
200
        }
4885
4886
50
        tctx->shdr->ctx_model_storage_defined = true;
4887
50
      }
4888
321
    }
4889
4890
145k
    tctx->img->ctb_progress[ctbx + ctby * ctbW].set_progress(CTB_PROGRESS_PREFILTER);
4891
4892
    //printf("%p: decoded %d|%d\n",tctx, ctby,ctbx);
4893
4894
4895
145k
    logtrace(LogSlice, "read CTB %d -> end=%d\n", tctx->CtbAddrInRS, end_of_slice_segment_flag);
4896
    //printf("read CTB %d -> end=%d\n", tctx->CtbAddrInRS, end_of_slice_segment_flag);
4897
4898
145k
    const int lastCtbY = tctx->CtbY;
4899
4900
145k
    bool endOfPicture = advanceCtbAddr(tctx); // true if we read past the end of the image
4901
4902
145k
    if (endOfPicture &&
4903
3.07k
        end_of_slice_segment_flag == false) {
4904
3.01k
      tctx->decctx->add_warning(DE265_WARNING_CTB_OUTSIDE_IMAGE_AREA, false);
4905
3.01k
      tctx->img->integrity = INTEGRITY_DECODING_ERRORS;
4906
3.01k
      return Decode_Error;
4907
3.01k
    }
4908
4909
4910
142k
    if (end_of_slice_segment_flag) {
4911
      /* corrupted inputs may send the end_of_slice_segment_flag even if not all
4912
         CTBs in a row have been coded. Hence, we mark all of them as finished.
4913
       */
4914
4915
      /*
4916
      for (int x = ctbx+1 ; x<sps->PicWidthInCtbsY; x++) {
4917
        printf("mark skipped %d;%d\n",ctbx,ctby);
4918
        tctx->img->ctb_progress[ctbx+ctby*ctbW].set_progress(CTB_PROGRESS_PREFILTER);
4919
      }
4920
      */
4921
4922
321
      return Decode_EndOfSliceSegment;
4923
321
    }
4924
4925
4926
142k
    if (!end_of_slice_segment_flag) {
4927
142k
      bool end_of_sub_stream = false;
4928
142k
      end_of_sub_stream |= (pps.tiles_enabled_flag &&
4929
4.99k
                            pps.scan->TileId[tctx->CtbAddrInTS] != pps.scan->TileId[tctx->CtbAddrInTS - 1]);
4930
142k
      end_of_sub_stream |= (pps.entropy_coding_sync_enabled_flag &&
4931
25.2k
                            lastCtbY != tctx->CtbY);
4932
4933
142k
      if (end_of_sub_stream) {
4934
1.55k
        int end_of_sub_stream_one_bit = tctx->cabac_decoder.decode_term_bit();
4935
1.55k
        if (!end_of_sub_stream_one_bit) {
4936
1.44k
          tctx->decctx->add_warning(DE265_WARNING_EOSS_BIT_NOT_SET, false);
4937
1.44k
          tctx->img->integrity = INTEGRITY_DECODING_ERRORS;
4938
1.44k
          return Decode_Error;
4939
1.44k
        }
4940
4941
105
        tctx->cabac_decoder.init_CABAC(); // byte alignment
4942
105
        return Decode_EndOfSubstream;
4943
1.55k
      }
4944
142k
    }
4945
142k
  } while (true);
4946
5.30k
}
4947
4948
4949
bool initialize_CABAC_at_slice_segment_start(thread_context* tctx)
4950
3.38k
{
4951
3.38k
  de265_image* img = tctx->img;
4952
3.38k
  const pic_parameter_set& pps = img->get_pps();
4953
3.38k
  const seq_parameter_set& sps = img->get_sps();
4954
3.38k
  slice_segment_header* shdr = tctx->shdr;
4955
4956
3.38k
  if (shdr->dependent_slice_segment_flag) {
4957
0
    int prevCtb = pps.scan->CtbAddrTStoRS[pps.scan->CtbAddrRStoTS[shdr->slice_segment_address] - 1];
4958
4959
0
    uint16_t sliceIdx = img->get_SliceHeaderIndex_atIndex(prevCtb);
4960
0
    if (sliceIdx >= img->slices.size()) {
4961
0
      return false;
4962
0
    }
4963
0
    slice_segment_header* prevCtbHdr = img->slices[sliceIdx];
4964
4965
0
    if (pps.is_tile_start_CTB(shdr->slice_segment_address % sps.PicWidthInCtbsY,
4966
0
                              shdr->slice_segment_address / sps.PicWidthInCtbsY
4967
0
                             )) {
4968
0
      initialize_CABAC_models(tctx);
4969
0
    }
4970
0
    else {
4971
      // wait for previous slice to finish decoding
4972
4973
      //printf("wait for previous slice to finish decoding\n");
4974
4975
4976
0
      slice_unit* prevSliceSegment = tctx->imgunit->get_prev_slice_segment(tctx->sliceunit);
4977
      //assert(prevSliceSegment);
4978
0
      if (prevSliceSegment == nullptr) {
4979
0
        return false;
4980
0
      }
4981
4982
0
      prevSliceSegment->finished_threads.wait_for_progress(prevSliceSegment->nThreads);
4983
4984
4985
      /*
4986
      printf("wait for %d,%d (init)\n",
4987
             prevCtb / sps->PicWidthInCtbsY,
4988
             prevCtb % sps->PicWidthInCtbsY);
4989
      tctx->img->wait_for_progress(tctx->task, prevCtb, CTB_PROGRESS_PREFILTER);
4990
      */
4991
4992
0
      if (!prevCtbHdr->ctx_model_storage_defined) {
4993
0
        return false;
4994
0
      }
4995
4996
0
      tctx->ctx_model = prevCtbHdr->ctx_model_storage;
4997
0
      prevCtbHdr->ctx_model_storage.release();
4998
4999
      // also restore the StatCoeff[] state for persistent_rice_adaptation
5000
0
      for (int i = 0; i < 4; i++) {
5001
0
        tctx->StatCoeff[i] = prevCtbHdr->ctx_model_storage_StatCoeff[i];
5002
0
      }
5003
0
    }
5004
0
  }
5005
3.38k
  else {
5006
3.38k
    initialize_CABAC_models(tctx);
5007
3.38k
  }
5008
5009
3.38k
  return true;
5010
3.38k
}
5011
5012
5013
std::string thread_task_ctb_row::name() const
5014
0
{
5015
0
  char buf[100];
5016
0
  sprintf(buf, "ctb-row-%d", debug_startCtbRow);
5017
0
  return buf;
5018
0
}
5019
5020
5021
std::string thread_task_slice_segment::name() const
5022
0
{
5023
0
  char buf[100];
5024
0
  sprintf(buf, "slice-segment-%d;%d", debug_startCtbX, debug_startCtbY);
5025
0
  return buf;
5026
0
}
5027
5028
5029
void thread_task_slice_segment::work()
5030
285
{
5031
285
  thread_task_slice_segment* data = this;
5032
285
  thread_context* tctx = data->tctx;
5033
285
  de265_image* img = tctx->img;
5034
5035
285
  state = Running;
5036
285
  img->thread_run(this);
5037
5038
285
  setCtbAddrFromTS(tctx);
5039
5040
  //printf("%p: A start decoding at %d/%d\n", tctx, tctx->CtbX,tctx->CtbY);
5041
5042
285
  if (data->firstSliceSubstream) {
5043
170
    bool success = initialize_CABAC_at_slice_segment_start(tctx);
5044
170
    if (!success) {
5045
0
      state = Finished;
5046
0
      tctx->sliceunit->finished_threads.increase_progress(1);
5047
0
      img->thread_finishes(this);
5048
0
      return;
5049
0
    }
5050
170
  }
5051
115
  else {
5052
115
    initialize_CABAC_models(tctx);
5053
115
  }
5054
5055
285
  tctx->cabac_decoder.init_CABAC();
5056
5057
  /*enum DecodeResult result =*/
5058
285
  decode_substream(tctx, false, data->firstSliceSubstream);
5059
5060
285
  state = Finished;
5061
285
  tctx->sliceunit->finished_threads.increase_progress(1);
5062
285
  img->thread_finishes(this);
5063
5064
285
  return; // DE265_OK;
5065
285
}
5066
5067
5068
void thread_task_ctb_row::work()
5069
2.02k
{
5070
2.02k
  thread_task_ctb_row* data = this;
5071
2.02k
  thread_context* tctx = data->tctx;
5072
2.02k
  de265_image* img = tctx->img;
5073
5074
2.02k
  const seq_parameter_set& sps = img->get_sps();
5075
2.02k
  int ctbW = sps.PicWidthInCtbsY;
5076
5077
2.02k
  state = Running;
5078
2.02k
  img->thread_run(this);
5079
5080
2.02k
  setCtbAddrFromTS(tctx);
5081
5082
2.02k
  int ctby = tctx->CtbAddrInRS / ctbW;
5083
2.02k
  int myCtbRow = ctby;
5084
5085
  //printf("start CTB-row decoding at row %d\n", ctby);
5086
5087
2.02k
  if (data->firstSliceSubstream) {
5088
216
    bool success = initialize_CABAC_at_slice_segment_start(tctx);
5089
216
    if (!success) {
5090
      // could not decode this row, mark whole row as finished
5091
0
      for (int x = 0; x < ctbW; x++) {
5092
0
        img->ctb_progress[myCtbRow * ctbW + x].set_progress(CTB_PROGRESS_PREFILTER);
5093
0
      }
5094
5095
0
      state = Finished;
5096
0
      tctx->sliceunit->finished_threads.increase_progress(1);
5097
0
      img->thread_finishes(this);
5098
0
      return;
5099
0
    }
5100
    //initialize_CABAC(tctx);
5101
216
  }
5102
5103
2.02k
  tctx->cabac_decoder.init_CABAC();
5104
5105
2.02k
  bool firstIndependentSubstream =
5106
2.02k
      data->firstSliceSubstream && !tctx->shdr->dependent_slice_segment_flag;
5107
5108
  /*enum DecodeResult result =*/
5109
2.02k
  decode_substream(tctx, true, firstIndependentSubstream);
5110
5111
  // mark progress on remaining CTBs in row (in case of decoder error and early termination)
5112
5113
  // TODO: what about slices that end properly in the middle of a CTB row?
5114
5115
2.02k
  if (tctx->CtbY == myCtbRow) {
5116
490
    int lastCtbX = sps.PicWidthInCtbsY; // assume no tiles when WPP is on
5117
8.03k
    for (int x = tctx->CtbX; x < lastCtbX; x++) {
5118
7.54k
      if (x < sps.PicWidthInCtbsY &&
5119
7.54k
          myCtbRow < sps.PicHeightInCtbsY) {
5120
7.54k
        img->ctb_progress[myCtbRow * ctbW + x].set_progress(CTB_PROGRESS_PREFILTER);
5121
7.54k
      }
5122
7.54k
    }
5123
490
  }
5124
5125
2.02k
  state = Finished;
5126
2.02k
  tctx->sliceunit->finished_threads.increase_progress(1);
5127
2.02k
  img->thread_finishes(this);
5128
2.02k
}
5129
5130
5131
de265_error read_slice_segment_data(thread_context* tctx)
5132
2.99k
{
5133
2.99k
  setCtbAddrFromTS(tctx);
5134
5135
2.99k
  de265_image* img = tctx->img;
5136
2.99k
  const pic_parameter_set& pps = img->get_pps();
5137
  //const seq_parameter_set& sps = img->get_sps();
5138
2.99k
  slice_segment_header* shdr = tctx->shdr;
5139
5140
2.99k
  bool success = initialize_CABAC_at_slice_segment_start(tctx);
5141
2.99k
  if (!success) {
5142
0
    return DE265_ERROR_UNSPECIFIED_DECODING_ERROR;
5143
0
  }
5144
5145
2.99k
  tctx->cabac_decoder.init_CABAC();
5146
5147
  //printf("-----\n");
5148
5149
2.99k
  bool first_slice_substream = !shdr->dependent_slice_segment_flag;
5150
5151
2.99k
  uint32_t substream = 0;
5152
5153
2.99k
  enum DecodeResult result;
5154
2.99k
  do {
5155
    //int ctby = tctx->CtbY;
5156
5157
5158
    // check whether entry_points[] are correct in the bitstream
5159
5160
2.99k
    if (substream > 0) {
5161
0
      if (substream - 1 >= tctx->shdr->entry_point_offset.size() ||
5162
0
          tctx->cabac_decoder.bitstream_curr - tctx->cabac_decoder.bitstream_start - 2 /* -2 because of CABAC init */
5163
0
          != tctx->shdr->entry_point_offset[substream - 1]) {
5164
0
        tctx->decctx->add_warning(DE265_WARNING_INCORRECT_ENTRY_POINT_OFFSET, true);
5165
0
      }
5166
0
    }
5167
5168
2.99k
    substream++;
5169
5170
5171
2.99k
    result = decode_substream(tctx, false, first_slice_substream);
5172
5173
5174
2.99k
    if (result == Decode_EndOfSliceSegment ||
5175
2.99k
        result == Decode_Error) {
5176
2.99k
      break;
5177
2.99k
    }
5178
5179
0
    first_slice_substream = false;
5180
5181
0
    if (pps.tiles_enabled_flag) {
5182
0
      initialize_CABAC_models(tctx);
5183
0
    }
5184
0
  } while (true);
5185
5186
2.99k
  return DE265_OK;
5187
2.99k
}
5188
5189
5190
/* TODO:
5191
   When a task wants to block, but is the first in the list of pending tasks,
5192
   do some error concealment instead of blocking, since it will never be deblocked.
5193
   This will only happen in the case of input error.
5194
 */