Coverage Report

Created: 2026-10-28 06:18

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
2.13k
{
151
2.13k
  uint32_t uvlc;
152
2.13k
  int32_t svlc;
153
154
2.13k
  pic_parameter_set* pps = ctx->get_pps((int) shdr->slice_pic_parameter_set_id);
155
2.13k
  assert(pps);
156
2.13k
  seq_parameter_set* sps = ctx->get_sps((int) pps->seq_parameter_set_id);
157
2.13k
  assert(sps);
158
159
2.13k
  uvlc = br->get_uvlc();
160
2.13k
  if (uvlc > 7) return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
161
2.10k
  shdr->luma_log2_weight_denom = uvlc;
162
163
2.10k
  if (sps->chroma_format_idc != 0) {
164
2.10k
    svlc = br->get_svlc();
165
2.10k
    svlc += shdr->luma_log2_weight_denom;
166
2.10k
    if (svlc < 0 || svlc > 7) return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
167
2.08k
    shdr->ChromaLog2WeightDenom = svlc;
168
2.08k
  }
169
170
2.08k
  int sumWeightFlags[2]{};
171
172
6.09k
  for (int l = 0; l <= 1; l++)
173
4.10k
    if (l == 0 || (l == 1 && shdr->slice_type == SLICE_TYPE_B)) {
174
3.68k
      int num_ref = (l == 0 ? shdr->num_ref_idx_l0_active - 1 : shdr->num_ref_idx_l1_active - 1);
175
176
11.7k
      for (int i = 0; i <= num_ref; i++) {
177
8.05k
        shdr->luma_weight_flag[l][i] = br->get_bits(1);
178
8.05k
        if (shdr->luma_weight_flag[l][i]) sumWeightFlags[l]++;
179
8.05k
      }
180
181
3.68k
      if (sps->chroma_format_idc != 0) {
182
11.7k
        for (int i = 0; i <= num_ref; i++) {
183
8.05k
          shdr->chroma_weight_flag[l][i] = br->get_bits(1);
184
8.05k
          if (shdr->chroma_weight_flag[l][i]) sumWeightFlags[l] += 2;
185
8.05k
        }
186
3.68k
      }
187
188
11.4k
      for (int i = 0; i <= num_ref; i++) {
189
7.84k
        if (shdr->luma_weight_flag[l][i]) {
190
          // delta_luma_weight
191
192
3.97k
          svlc = br->get_svlc();
193
3.97k
          if (svlc < -128 || svlc > 127) return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
194
195
3.95k
          shdr->LumaWeight[l][i] = (1 << shdr->luma_log2_weight_denom) + svlc;
196
197
          // luma_offset
198
199
3.95k
          svlc = br->get_svlc();
200
3.95k
          if (svlc < -sps->WpOffsetHalfRangeY || svlc > sps->WpOffsetHalfRangeY - 1) return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
201
3.93k
          shdr->luma_offset[l][i] = svlc;
202
3.93k
        }
203
3.87k
        else {
204
3.87k
          shdr->LumaWeight[l][i] = 1 << shdr->luma_log2_weight_denom;
205
3.87k
          shdr->luma_offset[l][i] = 0;
206
3.87k
        }
207
208
7.80k
        if (shdr->chroma_weight_flag[l][i])
209
13.4k
          for (int j = 0; j < 2; j++) {
210
            // delta_chroma_weight
211
212
9.00k
            svlc = br->get_svlc();
213
9.00k
            if (svlc < -128 || svlc > 127) return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
214
215
8.98k
            shdr->ChromaWeight[l][i][j] = (1 << shdr->ChromaLog2WeightDenom) + svlc;
216
217
            // delta_chroma_offset
218
219
8.98k
            svlc = br->get_svlc();
220
8.98k
            if (svlc < -4 * sps->WpOffsetHalfRangeC ||
221
8.98k
                svlc > 4 * sps->WpOffsetHalfRangeC - 1)
222
40
              return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
223
224
8.94k
            svlc = Clip3(-sps->WpOffsetHalfRangeC,
225
8.94k
                         sps->WpOffsetHalfRangeC-1,
226
8.94k
                         (sps->WpOffsetHalfRangeC
227
8.94k
                           +svlc
228
8.94k
                           -((sps->WpOffsetHalfRangeC*shdr->ChromaWeight[l][i][j])
229
8.94k
                             >> shdr->ChromaLog2WeightDenom)));
230
231
8.94k
            shdr->ChromaOffset[l][i][j] = svlc;
232
8.94k
          }
233
3.28k
        else {
234
9.86k
          for (int j = 0; j < 2; j++) {
235
6.57k
            shdr->ChromaWeight[l][i][j] = 1 << shdr->ChromaLog2WeightDenom;
236
6.57k
            shdr->ChromaOffset[l][i][j] = 0;
237
6.57k
          }
238
3.28k
        }
239
7.80k
      }
240
3.68k
    }
241
242
  // check sumWeightFlags against limits (H.265, Section 7.4.7.3)
243
244
1.98k
  if (shdr->slice_type == SLICE_TYPE_P && sumWeightFlags[0] > 24) {
245
4
    return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
246
4
  }
247
248
1.98k
  if (shdr->slice_type == SLICE_TYPE_B && sumWeightFlags[0] + sumWeightFlags[1] > 24) {
249
5
    return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
250
5
  }
251
252
1.97k
  return DE265_OK;
253
1.98k
}
254
255
256
void slice_segment_header::reset()
257
30.0k
{
258
30.0k
  pps = nullptr;
259
260
30.0k
  slice_index = 0;
261
262
30.0k
  first_slice_segment_in_pic_flag = 0;
263
30.0k
  no_output_of_prior_pics_flag = 0;
264
30.0k
  slice_pic_parameter_set_id = 0;
265
30.0k
  dependent_slice_segment_flag = 0;
266
30.0k
  slice_segment_address = 0;
267
268
30.0k
  slice_type = 0;
269
30.0k
  pic_output_flag = 0;
270
30.0k
  colour_plane_id = 0;
271
30.0k
  slice_pic_order_cnt_lsb = 0;
272
30.0k
  short_term_ref_pic_set_sps_flag = 0;
273
30.0k
  slice_ref_pic_set.reset();
274
275
30.0k
  short_term_ref_pic_set_idx = 0;
276
30.0k
  num_long_term_sps = 0;
277
30.0k
  num_long_term_pics = 0;
278
279
509k
  for (int i = 0; i < MAX_NUM_REF_PICS; i++) {
280
479k
    lt_idx_sps[i] = 0;
281
479k
    poc_lsb_lt[i] = 0;
282
479k
    used_by_curr_pic_lt_flag[i] = 0;
283
479k
    delta_poc_msb_present_flag[i] = 0;
284
479k
    delta_poc_msb_cycle_lt[i] = 0;
285
479k
  }
286
287
30.0k
  slice_temporal_mvp_enabled_flag = 0;
288
30.0k
  slice_sao_luma_flag = 0;
289
30.0k
  slice_sao_chroma_flag = 0;
290
291
30.0k
  num_ref_idx_active_override_flag = 0;
292
30.0k
  num_ref_idx_l0_active = 0;
293
30.0k
  num_ref_idx_l1_active = 0;
294
295
30.0k
  ref_pic_list_modification_flag_l0 = 0;
296
30.0k
  ref_pic_list_modification_flag_l1 = 0;
297
509k
  for (int i = 0; i < 16; i++) {
298
479k
    list_entry_l0[i] = 0;
299
479k
    list_entry_l1[i] = 0;
300
479k
  }
301
302
30.0k
  mvd_l1_zero_flag = 0;
303
30.0k
  cabac_init_flag = 0;
304
30.0k
  collocated_from_l0_flag = 0;
305
30.0k
  collocated_ref_idx = 0;
306
307
30.0k
  luma_log2_weight_denom = 0;
308
30.0k
  ChromaLog2WeightDenom = 0;
309
310
89.9k
  for (int i = 0; i < 2; i++)
311
1.01M
    for (int j = 0; j < 16; j++) {
312
958k
      luma_weight_flag[i][j] = 0;
313
958k
      chroma_weight_flag[i][j] = 0;
314
958k
      LumaWeight[i][j] = 0;
315
958k
      luma_offset[i][j] = 0;
316
958k
      ChromaWeight[i][j][0] = ChromaWeight[i][j][1] = 0;
317
958k
      ChromaOffset[i][j][0] = ChromaOffset[i][j][1] = 0;
318
958k
    }
319
320
30.0k
  five_minus_max_num_merge_cand = 0;
321
30.0k
  slice_qp_delta = 0;
322
323
30.0k
  slice_cb_qp_offset = 0;
324
30.0k
  slice_cr_qp_offset = 0;
325
326
30.0k
  cu_chroma_qp_offset_enabled_flag = 0;
327
328
30.0k
  deblocking_filter_override_flag = 0;
329
30.0k
  slice_deblocking_filter_disabled_flag = 0;
330
30.0k
  slice_beta_offset = 0;
331
30.0k
  slice_tc_offset = 0;
332
333
30.0k
  slice_loop_filter_across_slices_enabled_flag = 0;
334
335
30.0k
  num_entry_point_offsets = 0;
336
30.0k
  offset_len = 0;
337
30.0k
  entry_point_offset.clear();
338
339
30.0k
  slice_segment_header_extension_length = 0;
340
341
30.0k
  SliceAddrRS = 0;
342
30.0k
  SliceQPY = 0;
343
344
30.0k
  initType = 0;
345
346
30.0k
  MaxNumMergeCand = 0;
347
30.0k
  CurrRpsIdx = 0;
348
30.0k
  CurrRps.reset();
349
30.0k
  NumPocTotalCurr = 0;
350
351
89.9k
  for (int i = 0; i < 2; i++)
352
1.01M
    for (int j = 0; j < MAX_NUM_REF_PICS; j++) {
353
958k
      RefPicList[i][j] = 0;
354
958k
      RefPicList_POC[i][j] = 0;
355
958k
      RefPicList_PicState[i][j] = 0;
356
958k
      LongTermRefPic[i][j] = 0;
357
958k
    }
358
359
  //context_model ctx_model_storage[CONTEXT_MODEL_TABLE_LENGTH];
360
361
30.0k
  RemoveReferencesList.clear();
362
363
150k
  for (int i = 0; i < 4; i++) {
364
120k
    ctx_model_storage_StatCoeff[i] = 0;
365
120k
  }
366
30.0k
  ctx_model_storage_defined = false;
367
30.0k
}
368
369
370
de265_error slice_segment_header::read(bitreader* br, decoder_context* ctx,
371
                                       bool* continueDecoding)
372
15.0k
{
373
15.0k
  *continueDecoding = false;
374
15.0k
  reset();
375
376
15.0k
  uint32_t uvlc;
377
15.0k
  int32_t svlc;
378
379
  // set defaults
380
381
15.0k
  dependent_slice_segment_flag = 0;
382
383
384
  // read bitstream
385
386
15.0k
  first_slice_segment_in_pic_flag = br->get_bits(1);
387
388
15.0k
  if (ctx->get_RapPicFlag()) {
389
    // TODO: is this still correct ? Should we drop RapPicFlag ?
390
14.5k
    no_output_of_prior_pics_flag = br->get_bits(1);
391
14.5k
  }
392
393
15.0k
  if ((uvlc = br->get_uvlc()) == UVLC_ERROR ||
394
14.9k
      uvlc >= DE265_MAX_PPS_SETS) {
395
63
    ctx->add_warning(DE265_WARNING_NONEXISTING_PPS_REFERENCED, false);
396
63
    return DE265_OK;
397
63
  }
398
14.9k
  slice_pic_parameter_set_id = uvlc;
399
400
14.9k
  if (!ctx->has_pps(slice_pic_parameter_set_id)) {
401
4.55k
    ctx->add_warning(DE265_WARNING_NONEXISTING_PPS_REFERENCED, false);
402
4.55k
    return DE265_OK;
403
4.55k
  }
404
405
10.3k
  pps = ctx->get_shared_pps(slice_pic_parameter_set_id);
406
407
10.3k
  const seq_parameter_set* sps = pps->sps.get();
408
10.3k
  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
10.3k
  if (!first_slice_segment_in_pic_flag) {
415
387
    if (pps->dependent_slice_segments_enabled_flag) {
416
108
      dependent_slice_segment_flag = br->get_bits(1);
417
108
    }
418
279
    else {
419
279
      dependent_slice_segment_flag = 0;
420
279
    }
421
422
387
    uint32_t slice_segment_address = br->get_bits(ceil_log2(sps->PicSizeInCtbsY));
423
424
387
    if (dependent_slice_segment_flag) {
425
100
      if (slice_segment_address == 0) {
426
9
        *continueDecoding = false;
427
9
        ctx->add_warning(DE265_WARNING_DEPENDENT_SLICE_WITH_ADDRESS_ZERO, false);
428
9
        return DE265_OK;
429
9
      }
430
431
91
      if (ctx->previous_slice_header == nullptr) {
432
16
        return DE265_ERROR_NO_INITIAL_SLICE_HEADER;
433
16
      }
434
435
75
      *this = *ctx->previous_slice_header;
436
437
75
      first_slice_segment_in_pic_flag = 0;
438
75
      dependent_slice_segment_flag = 1;
439
75
    }
440
441
362
    this->slice_segment_address = slice_segment_address;
442
362
  }
443
10.0k
  else {
444
10.0k
    dependent_slice_segment_flag = 0;
445
10.0k
    slice_segment_address = 0;
446
10.0k
  }
447
448
10.3k
  if (slice_segment_address >= sps->PicSizeInCtbsY) {
449
10
    ctx->add_warning(DE265_WARNING_SLICE_SEGMENT_ADDRESS_INVALID, false);
450
10
    return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
451
10
  }
452
453
  //printf("SLICE %d (%d)\n",slice_segment_address, sps->PicSizeInCtbsY);
454
455
456
10.3k
  if (!dependent_slice_segment_flag) {
457
25.2k
    for (int i = 0; i < pps->num_extra_slice_header_bits; i++) {
458
      //slice_reserved_undetermined_flag[i]
459
14.9k
      br->skip_bits(1);
460
14.9k
    }
461
462
10.2k
    if ((uvlc = br->get_uvlc()) == UVLC_ERROR ||
463
10.2k
        uvlc > 2) {
464
25
      ctx->add_warning(DE265_WARNING_SLICEHEADER_INVALID, false);
465
25
      *continueDecoding = false;
466
25
      return DE265_OK;
467
25
    }
468
10.2k
    slice_type = uvlc;
469
470
10.2k
    if (pps->output_flag_present_flag) {
471
1.49k
      pic_output_flag = br->get_bits(1);
472
1.49k
    }
473
8.76k
    else {
474
8.76k
      pic_output_flag = 1;
475
8.76k
    }
476
477
10.2k
    if (sps->separate_colour_plane_flag == 1) {
478
0
      colour_plane_id = br->get_bits(2);
479
0
    }
480
481
482
10.2k
    slice_pic_order_cnt_lsb = 0;
483
10.2k
    short_term_ref_pic_set_sps_flag = 0;
484
485
10.2k
    int NumLtPics = 0;
486
487
10.2k
    if (ctx->get_nal_unit_type() != NAL_UNIT_IDR_W_RADL &&
488
9.41k
        ctx->get_nal_unit_type() != NAL_UNIT_IDR_N_LP) {
489
6.00k
      slice_pic_order_cnt_lsb = br->get_bits(sps->log2_max_pic_order_cnt_lsb);
490
6.00k
      short_term_ref_pic_set_sps_flag = br->get_bits(1);
491
492
6.00k
      if (!short_term_ref_pic_set_sps_flag) {
493
5.79k
        read_short_term_ref_pic_set(ctx, sps,
494
5.79k
                                    br, &slice_ref_pic_set,
495
5.79k
                                    sps->num_short_term_ref_pic_sets(),
496
5.79k
                                    sps->ref_pic_sets,
497
5.79k
                                    true);
498
499
5.79k
        CurrRpsIdx = sps->num_short_term_ref_pic_sets();
500
5.79k
        CurrRps = slice_ref_pic_set;
501
5.79k
      }
502
214
      else {
503
214
        int nBits = ceil_log2(sps->num_short_term_ref_pic_sets());
504
214
        if (nBits > 0) short_term_ref_pic_set_idx = br->get_bits(nBits);
505
31
        else short_term_ref_pic_set_idx = 0;
506
507
214
        if (short_term_ref_pic_set_idx >= sps->num_short_term_ref_pic_sets()) {
508
19
          ctx->add_warning(DE265_WARNING_SHORT_TERM_REF_PIC_SET_OUT_OF_RANGE, false);
509
19
          return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
510
19
        }
511
512
195
        CurrRpsIdx = short_term_ref_pic_set_idx;
513
195
        CurrRps = sps->ref_pic_sets[CurrRpsIdx];
514
195
      }
515
516
517
      // --- long-term MC ---
518
519
5.98k
      if (sps->long_term_ref_pics_present_flag) {
520
3.03k
        if (sps->num_long_term_ref_pics_sps > 0) {
521
1.31k
          if ((uvlc = br->get_uvlc()) == UVLC_ERROR ||
522
1.30k
              uvlc > sps->num_long_term_ref_pics_sps) {
523
38
            return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
524
38
          }
525
1.27k
          num_long_term_sps = uvlc;
526
1.27k
        }
527
1.72k
        else {
528
1.72k
          num_long_term_sps = 0;
529
1.72k
        }
530
531
2.99k
        if ((uvlc = br->get_uvlc()) == UVLC_ERROR || uvlc > MAX_NUM_LT_REF_PICS_SPS) {
532
132
          return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
533
132
        }
534
2.86k
        num_long_term_pics = uvlc;
535
536
        // check maximum number of reference frames
537
538
2.86k
        if (num_long_term_sps +
539
2.86k
            num_long_term_pics +
540
2.86k
            CurrRps.NumNegativePics +
541
2.86k
            CurrRps.NumPositivePics
542
2.86k
            > sps->sps_max_dec_pic_buffering[sps->sps_max_sub_layers - 1]) {
543
19
          ctx->add_warning(DE265_WARNING_MAX_NUM_REF_PICS_EXCEEDED, false);
544
19
          *continueDecoding = false;
545
19
          return DE265_OK;
546
19
        }
547
548
8.07k
        for (int i = 0; i < num_long_term_sps + num_long_term_pics; i++) {
549
5.25k
          if (i < num_long_term_sps) {
550
703
            int nBits = ceil_log2(sps->num_long_term_ref_pics_sps);
551
703
            lt_idx_sps[i] = br->get_bits(nBits);
552
553
            // check that the referenced lt-reference really exists
554
555
703
            if (lt_idx_sps[i] >= sps->num_long_term_ref_pics_sps) {
556
11
              ctx->add_warning(DE265_NON_EXISTING_LT_REFERENCE_CANDIDATE_IN_SLICE_HEADER, false);
557
11
              *continueDecoding = false;
558
11
              return DE265_OK;
559
11
            }
560
561
            // delta_poc_msb_present_flag[i] = 0; // TODO ?
562
563
692
            ctx->PocLsbLt[i] = sps->lt_ref_pic_poc_lsb_sps[lt_idx_sps[i]];
564
692
            ctx->UsedByCurrPicLt[i] = sps->used_by_curr_pic_lt_sps_flag[lt_idx_sps[i]];
565
692
          }
566
4.54k
          else {
567
4.54k
            int nBits = sps->log2_max_pic_order_cnt_lsb;
568
4.54k
            poc_lsb_lt[i] = br->get_bits(nBits);
569
4.54k
            used_by_curr_pic_lt_flag[i] = br->get_bits(1);
570
571
4.54k
            ctx->PocLsbLt[i] = poc_lsb_lt[i];
572
4.54k
            ctx->UsedByCurrPicLt[i] = used_by_curr_pic_lt_flag[i];
573
4.54k
          }
574
575
5.24k
          if (ctx->UsedByCurrPicLt[i]) {
576
3.58k
            NumLtPics++;
577
3.58k
          }
578
579
5.24k
          delta_poc_msb_present_flag[i] = br->get_bits(1);
580
5.24k
          if (delta_poc_msb_present_flag[i]) {
581
2.65k
            if ((uvlc = br->get_uvlc()) == UVLC_ERROR) {
582
6
              return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
583
6
            }
584
2.65k
            delta_poc_msb_cycle_lt[i] = uvlc;
585
2.65k
          }
586
2.58k
          else {
587
2.58k
            delta_poc_msb_cycle_lt[i] = 0;
588
2.58k
          }
589
590
5.23k
          if (i == 0 || i == num_long_term_sps) {
591
2.65k
            ctx->DeltaPocMsbCycleLt[i] = delta_poc_msb_cycle_lt[i];
592
2.65k
          }
593
2.57k
          else {
594
2.57k
            if (delta_poc_msb_cycle_lt[i] > UINT32_MAX - ctx->DeltaPocMsbCycleLt[i - 1]) {
595
3
              ctx->add_warning(DE265_WARNING_SLICEHEADER_INVALID, false);
596
3
              return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
597
3
            }
598
2.57k
            ctx->DeltaPocMsbCycleLt[i] = (delta_poc_msb_cycle_lt[i] +
599
2.57k
                                          ctx->DeltaPocMsbCycleLt[i - 1]);
600
2.57k
          }
601
5.23k
        }
602
2.84k
      }
603
2.95k
      else {
604
2.95k
        num_long_term_sps = 0;
605
2.95k
        num_long_term_pics = 0;
606
2.95k
      }
607
608
5.77k
      if (sps->sps_temporal_mvp_enabled_flag) {
609
3.19k
        slice_temporal_mvp_enabled_flag = br->get_bits(1);
610
3.19k
      }
611
2.58k
      else {
612
2.58k
        slice_temporal_mvp_enabled_flag = 0;
613
2.58k
      }
614
5.77k
    }
615
4.25k
    else {
616
4.25k
      slice_pic_order_cnt_lsb = 0;
617
4.25k
      num_long_term_sps = 0;
618
4.25k
      num_long_term_pics = 0;
619
4.25k
    }
620
621
622
    // --- SAO ---
623
624
10.0k
    if (sps->sample_adaptive_offset_enabled_flag) {
625
7.17k
      slice_sao_luma_flag = br->get_bits(1);
626
627
7.18k
      if (sps->ChromaArrayType != CHROMA_MONO) {
628
7.18k
        slice_sao_chroma_flag = br->get_bits(1);
629
7.18k
      }
630
18.4E
      else {
631
18.4E
        slice_sao_chroma_flag = 0;
632
18.4E
      }
633
7.17k
    }
634
2.84k
    else {
635
2.84k
      slice_sao_luma_flag = 0;
636
2.84k
      slice_sao_chroma_flag = 0;
637
2.84k
    }
638
639
10.0k
    num_ref_idx_l0_active = 0;
640
10.0k
    num_ref_idx_l1_active = 0;
641
642
10.0k
    if (slice_type == SLICE_TYPE_P ||
643
8.49k
        slice_type == SLICE_TYPE_B) {
644
4.95k
      num_ref_idx_active_override_flag = br->get_bits(1);
645
4.95k
      if (num_ref_idx_active_override_flag) {
646
3.40k
        if ((uvlc = br->get_uvlc()) == UVLC_ERROR || uvlc > 15) {
647
12
          ctx->add_warning(DE265_WARNING_SLICEHEADER_INVALID, false);
648
12
          return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
649
12
        }
650
3.39k
        num_ref_idx_l0_active = uvlc + 1;
651
652
3.39k
        if (slice_type == SLICE_TYPE_B) {
653
2.47k
          if ((uvlc = br->get_uvlc()) == UVLC_ERROR || uvlc > 15) {
654
13
            ctx->add_warning(DE265_WARNING_SLICEHEADER_INVALID, false);
655
13
            return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
656
13
          }
657
2.46k
          num_ref_idx_l1_active = uvlc + 1;
658
2.46k
        }
659
3.39k
      }
660
1.55k
      else {
661
1.55k
        num_ref_idx_l0_active = pps->num_ref_idx_l0_default_active;
662
1.55k
        num_ref_idx_l1_active = pps->num_ref_idx_l1_default_active;
663
1.55k
      }
664
665
4.92k
      NumPocTotalCurr = CurrRps.NumPocTotalCurr_shortterm_only + NumLtPics;
666
667
4.92k
      if (pps->lists_modification_present_flag && NumPocTotalCurr > 1) {
668
1.31k
        int nBits = ceil_log2(NumPocTotalCurr);
669
670
1.31k
        ref_pic_list_modification_flag_l0 = br->get_bits(1);
671
1.31k
        if (ref_pic_list_modification_flag_l0) {
672
2.61k
          for (int i = 0; i < num_ref_idx_l0_active; i++) {
673
1.67k
            list_entry_l0[i] = br->get_bits(nBits);
674
1.67k
          }
675
936
        }
676
677
1.31k
        if (slice_type == SLICE_TYPE_B) {
678
819
          ref_pic_list_modification_flag_l1 = br->get_bits(1);
679
819
          if (ref_pic_list_modification_flag_l1) {
680
1.24k
            for (int i = 0; i < num_ref_idx_l1_active; i++) {
681
779
              list_entry_l1[i] = br->get_bits(nBits);
682
779
            }
683
461
          }
684
819
        }
685
497
        else {
686
497
          ref_pic_list_modification_flag_l1 = 0;
687
497
        }
688
1.31k
      }
689
3.61k
      else {
690
3.61k
        ref_pic_list_modification_flag_l0 = 0;
691
3.61k
        ref_pic_list_modification_flag_l1 = 0;
692
3.61k
      }
693
694
4.92k
      if (slice_type == SLICE_TYPE_B) {
695
3.39k
        mvd_l1_zero_flag = br->get_bits(1);
696
3.39k
      }
697
698
4.92k
      if (pps->cabac_init_present_flag) {
699
728
        cabac_init_flag = br->get_bits(1);
700
728
      }
701
4.20k
      else {
702
4.20k
        cabac_init_flag = 0;
703
4.20k
      }
704
705
4.92k
      if (slice_temporal_mvp_enabled_flag) {
706
1.61k
        if (slice_type == SLICE_TYPE_B)
707
1.26k
          collocated_from_l0_flag = br->get_bits(1);
708
344
        else
709
344
          collocated_from_l0_flag = 1;
710
711
1.61k
        if ((collocated_from_l0_flag && num_ref_idx_l0_active > 1) ||
712
1.43k
            (!collocated_from_l0_flag && num_ref_idx_l1_active > 1)) {
713
275
          if ((uvlc = br->get_uvlc()) == UVLC_ERROR || uvlc > 15) {
714
17
            ctx->add_warning(DE265_WARNING_SLICEHEADER_INVALID, false);
715
17
            return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
716
17
          }
717
258
          collocated_ref_idx = uvlc;
718
258
        }
719
1.33k
        else {
720
1.33k
          collocated_ref_idx = 0;
721
1.33k
        }
722
723
        // check whether collocated_ref_idx points to a valid index
724
725
1.59k
        if ((collocated_from_l0_flag && collocated_ref_idx >= num_ref_idx_l0_active) ||
726
1.58k
            (!collocated_from_l0_flag && collocated_ref_idx >= num_ref_idx_l1_active)) {
727
21
          ctx->add_warning(DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE, false);
728
21
          return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
729
21
        }
730
1.59k
      }
731
732
733
4.89k
      if ((pps->weighted_pred_flag && slice_type == SLICE_TYPE_P) ||
734
4.41k
          (pps->weighted_bipred_flag && slice_type == SLICE_TYPE_B)) {
735
2.13k
        de265_error err = read_pred_weight_table(br, this, ctx);
736
2.13k
        if (err) {
737
154
          ctx->add_warning(err, false);
738
154
          return err;
739
154
        }
740
2.13k
      }
741
742
4.73k
      if ((uvlc = br->get_uvlc()) == UVLC_ERROR || uvlc > 5) {
743
77
        ctx->add_warning(DE265_WARNING_SLICEHEADER_INVALID, false);
744
77
        return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
745
77
      }
746
747
4.66k
      five_minus_max_num_merge_cand = uvlc;
748
4.66k
      MaxNumMergeCand = 5 - five_minus_max_num_merge_cand;
749
4.66k
    }
750
751
9.73k
    if ((svlc = br->get_svlc()) == SVLC_ERROR) {
752
11
      ctx->add_warning(DE265_WARNING_SLICEHEADER_INVALID, false);
753
11
      return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
754
11
    }
755
756
9.72k
    slice_qp_delta = svlc;
757
    //logtrace(LogSlice,"slice_qp_delta: %d\n",shdr->slice_qp_delta);
758
759
9.72k
    if (pps->pps_slice_chroma_qp_offsets_present_flag) {
760
3.61k
      if ((svlc = br->get_svlc()) == SVLC_ERROR) {
761
6
        ctx->add_warning(DE265_WARNING_SLICEHEADER_INVALID, false);
762
6
        return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
763
6
      }
764
765
3.60k
      slice_cb_qp_offset = svlc;
766
767
3.60k
      if ((svlc = br->get_svlc()) == SVLC_ERROR) {
768
6
        ctx->add_warning(DE265_WARNING_SLICEHEADER_INVALID, false);
769
6
        return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
770
6
      }
771
772
3.60k
      slice_cr_qp_offset = svlc;
773
3.60k
    }
774
6.10k
    else {
775
6.10k
      slice_cb_qp_offset = 0;
776
6.10k
      slice_cr_qp_offset = 0;
777
6.10k
    }
778
779
9.71k
    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
9.71k
    if (pps->deblocking_filter_override_enabled_flag) {
784
753
      deblocking_filter_override_flag = br->get_bits(1);
785
753
    }
786
8.95k
    else {
787
8.95k
      deblocking_filter_override_flag = 0;
788
8.95k
    }
789
790
9.71k
    slice_beta_offset = pps->beta_offset;
791
9.71k
    slice_tc_offset = pps->tc_offset;
792
793
9.71k
    if (deblocking_filter_override_flag) {
794
571
      slice_deblocking_filter_disabled_flag = br->get_bits(1);
795
571
      if (!slice_deblocking_filter_disabled_flag) {
796
        // slice_beta_offset_div2 shall be in [-6, 6] (Sec. 7.4.7.1)
797
349
        if ((svlc = br->get_svlc()) == SVLC_ERROR || svlc < -6 || svlc > 6) {
798
18
          ctx->add_warning(DE265_WARNING_SLICEHEADER_INVALID, false);
799
18
          return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
800
18
        }
801
331
        slice_beta_offset = svlc * 2;
802
803
        // slice_tc_offset_div2 shall be in [-6, 6] (Sec. 7.4.7.1)
804
331
        if ((svlc = br->get_svlc()) == SVLC_ERROR || svlc < -6 || svlc > 6) {
805
32
          ctx->add_warning(DE265_WARNING_SLICEHEADER_INVALID, false);
806
32
          return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
807
32
        }
808
299
        slice_tc_offset = svlc * 2;
809
299
      }
810
571
    }
811
9.14k
    else {
812
9.14k
      slice_deblocking_filter_disabled_flag = pps->pic_disable_deblocking_filter_flag;
813
9.14k
    }
814
815
9.66k
    if (pps->pps_loop_filter_across_slices_enabled_flag &&
816
5.74k
        (slice_sao_luma_flag || slice_sao_chroma_flag ||
817
5.62k
         !slice_deblocking_filter_disabled_flag)) {
818
5.62k
      slice_loop_filter_across_slices_enabled_flag = br->get_bits(1);
819
5.62k
    }
820
4.03k
    else {
821
4.03k
      slice_loop_filter_across_slices_enabled_flag =
822
4.03k
          pps->pps_loop_filter_across_slices_enabled_flag;
823
4.03k
    }
824
9.66k
  }
825
826
9.73k
  if (pps->tiles_enabled_flag || pps->entropy_coding_sync_enabled_flag) {
827
828
    // compute the spec limit for num_entry_point_offsets
829
830
3.90k
    int maxEntryPointOffsets;
831
3.90k
    if (!pps->tiles_enabled_flag && pps->entropy_coding_sync_enabled_flag) {
832
3.06k
      maxEntryPointOffsets = sps->PicHeightInCtbsY - 1;
833
3.06k
    }
834
836
    else if (pps->tiles_enabled_flag && !pps->entropy_coding_sync_enabled_flag) {
835
814
      maxEntryPointOffsets = pps->num_tile_columns * pps->num_tile_rows - 1;
836
814
    }
837
22
    else {
838
22
      maxEntryPointOffsets = pps->num_tile_columns * sps->PicHeightInCtbsY - 1;
839
22
    }
840
841
3.90k
    if ((uvlc = br->get_uvlc()) == UVLC_ERROR ||
842
3.89k
        uvlc > static_cast<uint32_t>(maxEntryPointOffsets)) {
843
136
      ctx->add_warning(DE265_WARNING_SLICEHEADER_INVALID, false);
844
136
      return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
845
136
    }
846
3.76k
    num_entry_point_offsets = uvlc;
847
848
3.76k
    entry_point_offset.resize(num_entry_point_offsets);
849
850
3.76k
    if (num_entry_point_offsets > 0) {
851
2.22k
      if ((uvlc = br->get_uvlc()) == UVLC_ERROR || uvlc > 31) {
852
14
        ctx->add_warning(DE265_WARNING_SLICEHEADER_INVALID, false);
853
14
        return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
854
14
      }
855
2.21k
      offset_len = uvlc + 1;
856
857
29.7k
      for (uint32_t i = 0; i < num_entry_point_offsets; i++) {
858
27.5k
        {
859
27.5k
          uint32_t offset_minus1 = br->get_bits(offset_len);
860
27.5k
          if (offset_minus1 == UINT32_MAX) {
861
2
            ctx->add_warning(DE265_WARNING_SLICEHEADER_INVALID, false);
862
2
            return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
863
2
          }
864
27.5k
          entry_point_offset[i] = offset_minus1 + 1;
865
27.5k
        }
866
867
27.5k
        if (i > 0) {
868
25.3k
          if (entry_point_offset[i] > UINT32_MAX - entry_point_offset[i - 1]) {
869
14
            ctx->add_warning(DE265_WARNING_SLICEHEADER_INVALID, false);
870
14
            return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
871
14
          }
872
25.2k
          entry_point_offset[i] += entry_point_offset[i - 1];
873
25.2k
        }
874
27.5k
      }
875
2.21k
    }
876
3.76k
  }
877
5.83k
  else {
878
5.83k
    num_entry_point_offsets = 0;
879
5.83k
  }
880
881
9.57k
  if (pps->slice_segment_header_extension_present_flag) {
882
4.02k
    if ((uvlc = br->get_uvlc()) == UVLC_ERROR ||
883
4.01k
        uvlc > 1000) {
884
      // TODO: safety check against too large values
885
18
      ctx->add_warning(DE265_WARNING_SLICEHEADER_INVALID, false);
886
18
      return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
887
18
    }
888
4.00k
    slice_segment_header_extension_length = uvlc;
889
890
22.1k
    for (int i = 0; i < slice_segment_header_extension_length; i++) {
891
      //slice_segment_header_extension_data_byte[i]
892
18.1k
      br->get_bits(8);
893
18.1k
    }
894
4.00k
  }
895
896
897
9.55k
  compute_derived_values(pps.get());
898
899
  // SliceQpY shall be in [-QpBdOffsetY, 51] (Sec. 7.4.7.1)
900
9.55k
  if (SliceQPY < -sps->QpBdOffset_Y || SliceQPY > 51) {
901
41
    ctx->add_warning(DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE, false);
902
41
    return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
903
41
  }
904
905
9.51k
  *continueDecoding = true;
906
9.51k
  return DE265_OK;
907
9.55k
}
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
9.55k
{
1273
  // --- init variables ---
1274
1275
9.55k
  SliceQPY = pps->pic_init_qp + slice_qp_delta;
1276
1277
9.55k
  switch (slice_type) {
1278
4.94k
    case SLICE_TYPE_I: initType = 0;
1279
4.94k
      break;
1280
1.38k
    case SLICE_TYPE_P: initType = cabac_init_flag + 1;
1281
1.38k
      break;
1282
3.22k
    case SLICE_TYPE_B: initType = 2 - cabac_init_flag;
1283
3.22k
      break;
1284
9.55k
  }
1285
1286
9.55k
  MaxNumMergeCand = 5 - five_minus_max_num_merge_cand;
1287
9.55k
}
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
9.48k
{
1538
9.48k
  const int QPY = tctx->shdr->SliceQPY;
1539
9.48k
  const int initType = tctx->shdr->initType;
1540
9.48k
  assert(initType >= 0 && initType <= 2);
1541
1542
9.48k
  tctx->ctx_model.init(initType, QPY);
1543
1544
47.4k
  for (int i = 0; i < 4; i++) {
1545
37.9k
    tctx->StatCoeff[i] = 0;
1546
37.9k
  }
1547
9.48k
}
1548
1549
1550
static int decode_transform_skip_flag(thread_context* tctx, int cIdx)
1551
108k
{
1552
108k
  const int context = (cIdx == 0) ? 0 : 1;
1553
1554
108k
  logtrace(LogSlice, "# transform_skip_flag (context=%d)\n", context);
1555
1556
108k
  int bit = tctx->cabac_decoder.decode_bit(
1557
108k
                             &tctx->ctx_model[CONTEXT_MODEL_TRANSFORM_SKIP_FLAG + context]);
1558
1559
108k
  logtrace(LogSymbols, "$1 transform_skip_flag=%d\n", bit);
1560
1561
108k
  return bit;
1562
108k
}
1563
1564
1565
static int decode_sao_merge_flag(thread_context* tctx)
1566
1.39M
{
1567
1.39M
  logtrace(LogSlice, "# sao_merge_left/up_flag\n");
1568
1.39M
  int bit = tctx->cabac_decoder.decode_bit(
1569
1.39M
                             &tctx->ctx_model[CONTEXT_MODEL_SAO_MERGE_FLAG]);
1570
1571
1.39M
  logtrace(LogSymbols, "$1 sao_merge_flag=%d\n", bit);
1572
1573
1.39M
  return bit;
1574
1.39M
}
1575
1576
1577
static uint8_t decode_sao_type_idx(thread_context* tctx)
1578
1.38M
{
1579
1.38M
  logtrace(LogSlice, "# sao_type_idx_luma/chroma\n");
1580
1581
1.38M
  int bit0 = tctx->cabac_decoder.decode_bit(
1582
1.38M
                              &tctx->ctx_model[CONTEXT_MODEL_SAO_TYPE_IDX]);
1583
1584
1.38M
  if (bit0 == 0) {
1585
943k
    logtrace(LogSymbols, "$1 sao_type_idx=%d\n", 0);
1586
943k
    return 0;
1587
943k
  }
1588
437k
  else {
1589
437k
    int bit1 = tctx->cabac_decoder.decode_bypass();
1590
437k
    if (bit1 == 0) {
1591
429k
      logtrace(LogSymbols, "$1 sao_type_idx=%d\n", 1);
1592
429k
      return 1;
1593
429k
    }
1594
8.11k
    else {
1595
8.11k
      logtrace(LogSymbols, "$1 sao_type_idx=%d\n", 2);
1596
8.11k
      return 2;
1597
8.11k
    }
1598
437k
  }
1599
1.38M
}
1600
1601
1602
static uint8_t decode_sao_offset_abs(thread_context* tctx, int bitDepth)
1603
2.61M
{
1604
2.61M
  logtrace(LogSlice, "# sao_offset_abs\n");
1605
2.61M
  int cMax = (1 << (std::min(bitDepth, 10) - 5)) - 1;
1606
2.61M
  assert(cMax >= 7 && cMax<=31);
1607
2.61M
  uint8_t value = static_cast<uint8_t>(tctx->cabac_decoder.decode_TU_bypass( cMax));
1608
2.61M
  logtrace(LogSymbols, "$1 sao_offset_abs=%d\n", value);
1609
2.61M
  return value;
1610
2.61M
}
1611
1612
1613
static int decode_sao_class(thread_context* tctx)
1614
8.12k
{
1615
8.12k
  logtrace(LogSlice, "# sao_class\n");
1616
8.12k
  int value = tctx->cabac_decoder.decode_FL_bypass( 2);
1617
8.12k
  logtrace(LogSymbols, "$1 sao_class=%d\n", value);
1618
8.12k
  return value;
1619
8.12k
}
1620
1621
1622
static int decode_sao_offset_sign(thread_context* tctx)
1623
23.9k
{
1624
23.9k
  logtrace(LogSlice, "# sao_offset_sign\n");
1625
23.9k
  int value = tctx->cabac_decoder.decode_bypass();
1626
23.9k
  logtrace(LogSymbols, "$1 sao_offset_sign=%d\n", value);
1627
23.9k
  return value;
1628
23.9k
}
1629
1630
1631
static int decode_sao_band_position(thread_context* tctx)
1632
640k
{
1633
640k
  logtrace(LogSlice, "# sao_band_position\n");
1634
640k
  int value = tctx->cabac_decoder.decode_FL_bypass( 5);
1635
640k
  logtrace(LogSymbols, "$1 sao_band_position=%d\n", value);
1636
640k
  return value;
1637
640k
}
1638
1639
1640
static int decode_transquant_bypass_flag(thread_context* tctx)
1641
2.82M
{
1642
2.82M
  logtrace(LogSlice, "# cu_transquant_bypass_enable_flag\n");
1643
2.82M
  int value = tctx->cabac_decoder.decode_bit(
1644
2.82M
                               &tctx->ctx_model[CONTEXT_MODEL_CU_TRANSQUANT_BYPASS_FLAG]);
1645
2.82M
  logtrace(LogSymbols, "$1 transquant_bypass_flag=%d\n", value);
1646
2.82M
  return value;
1647
2.82M
}
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
3.12M
{
1656
  // check if neighbors are available
1657
1658
3.12M
  int availableL = check_CTB_available(tctx->img, x0, y0, x0 - 1, y0);
1659
3.12M
  int availableA = check_CTB_available(tctx->img, x0, y0, x0, y0 - 1);
1660
1661
3.12M
  int condL = 0;
1662
3.12M
  int condA = 0;
1663
1664
3.12M
  if (availableL && tctx->img->get_ctDepth(x0 - 1, y0) > ctDepth) condL = 1;
1665
3.12M
  if (availableA && tctx->img->get_ctDepth(x0, y0 - 1) > ctDepth) condA = 1;
1666
1667
3.12M
  int contextOffset = condL + condA;
1668
3.12M
  int context = contextOffset;
1669
1670
  // decode bit
1671
1672
3.12M
  logtrace(LogSlice, "# split_cu_flag context=%d R=%x\n", context, tctx->cabac_decoder.range);
1673
1674
3.12M
  int bit = tctx->cabac_decoder.decode_bit( &tctx->ctx_model[CONTEXT_MODEL_SPLIT_CU_FLAG + context]);
1675
1676
3.12M
  logtrace(LogSlice, "> split_cu_flag R=%x, ctx=%d, bit=%d\n", tctx->cabac_decoder.range, context, bit);
1677
1678
3.12M
  logtrace(LogSymbols, "$1 split_cu_flag=%d\n", bit);
1679
1680
3.12M
  return bit;
1681
3.12M
}
1682
1683
1684
static int decode_cu_skip_flag(thread_context* tctx,
1685
                               int x0, int y0, int ctDepth)
1686
1.84M
{
1687
  // check if neighbors are available
1688
1689
1.84M
  int availableL = check_CTB_available(tctx->img, x0, y0, x0 - 1, y0);
1690
1.84M
  int availableA = check_CTB_available(tctx->img, x0, y0, x0, y0 - 1);
1691
1692
1.84M
  int condL = 0;
1693
1.84M
  int condA = 0;
1694
1695
1.84M
  if (availableL && tctx->img->get_cu_skip_flag(x0 - 1, y0)) condL = 1;
1696
1.84M
  if (availableA && tctx->img->get_cu_skip_flag(x0, y0 - 1)) condA = 1;
1697
1698
1.84M
  int contextOffset = condL + condA;
1699
1.84M
  int context = contextOffset;
1700
1701
  // decode bit
1702
1703
1.84M
  logtrace(LogSlice, "# cu_skip_flag context=%d R=%x\n", context, tctx->cabac_decoder.range);
1704
1705
1.84M
  int bit = tctx->cabac_decoder.decode_bit( &tctx->ctx_model[CONTEXT_MODEL_CU_SKIP_FLAG + context]);
1706
1707
1.84M
  logtrace(LogSlice, "> cu_skip_flag R=%x, ctx=%d, bit=%d\n", tctx->cabac_decoder.range, context, bit);
1708
1709
1.84M
  logtrace(LogSymbols, "$1 cu_skip_flag=%d\n", bit);
1710
1711
1.84M
  return bit;
1712
1.84M
}
1713
1714
1715
static enum PartMode decode_part_mode(thread_context* tctx,
1716
                                      enum PredMode pred_mode, int cLog2CbSize)
1717
7.53M
{
1718
7.53M
  de265_image* img = tctx->img;
1719
1720
7.53M
  if (pred_mode == MODE_INTRA) {
1721
6.93M
    logtrace(LogSlice, "# part_mode (INTRA)\n");
1722
1723
6.93M
    int bit = tctx->cabac_decoder.decode_bit( &tctx->ctx_model[CONTEXT_MODEL_PART_MODE]);
1724
1725
6.93M
    logtrace(LogSlice, "> %s\n", bit ? "2Nx2N" : "NxN");
1726
1727
6.93M
    logtrace(LogSymbols, "$1 part_mode=%d\n", bit ? PART_2Nx2N : PART_NxN);
1728
1729
6.93M
    return bit ? PART_2Nx2N : PART_NxN;
1730
6.93M
  }
1731
602k
  else {
1732
602k
    const seq_parameter_set& sps = img->get_sps();
1733
1734
602k
    int bit0 = tctx->cabac_decoder.decode_bit( &tctx->ctx_model[CONTEXT_MODEL_PART_MODE + 0]);
1735
602k
    if (bit0) {
1736
315k
      logtrace(LogSymbols, "$1 part_mode=%d\n", PART_2Nx2N);
1737
315k
      return PART_2Nx2N;
1738
315k
    }
1739
1740
    // CHECK_ME: I optimize code and fix bug here, need more VERIFY!
1741
286k
    int bit1 = tctx->cabac_decoder.decode_bit( &tctx->ctx_model[CONTEXT_MODEL_PART_MODE + 1]);
1742
286k
    if (cLog2CbSize > sps.Log2MinCbSizeY) {
1743
67.3k
      if (!sps.amp_enabled_flag) {
1744
20.0k
        logtrace(LogSymbols, "$1 part_mode=%d\n", bit1 ? PART_2NxN : PART_Nx2N);
1745
20.0k
        return bit1 ? PART_2NxN : PART_Nx2N;
1746
20.0k
      }
1747
47.3k
      else {
1748
47.3k
        int bit3 = tctx->cabac_decoder.decode_bit( &tctx->ctx_model[CONTEXT_MODEL_PART_MODE + 3]);
1749
47.3k
        if (bit3) {
1750
20.9k
          logtrace(LogSymbols, "$1 part_mode=%d\n", bit1 ? PART_2NxN : PART_Nx2N);
1751
20.9k
          return bit1 ? PART_2NxN : PART_Nx2N;
1752
20.9k
        }
1753
1754
26.3k
        int bit4 = tctx->cabac_decoder.decode_bypass();
1755
26.3k
        if (bit1 && bit4) {
1756
1.80k
          logtrace(LogSymbols, "$1 part_mode=%d\n", PART_2NxnD);
1757
1.80k
          return PART_2NxnD;
1758
1.80k
        }
1759
24.5k
        if (bit1 && !bit4) {
1760
6.69k
          logtrace(LogSymbols, "$1 part_mode=%d\n", PART_2NxnU);
1761
6.69k
          return PART_2NxnU;
1762
6.69k
        }
1763
17.8k
        if (!bit1 && !bit4) {
1764
15.8k
          logtrace(LogSymbols, "$1 part_mode=%d\n", PART_nLx2N);
1765
15.8k
          return PART_nLx2N;
1766
15.8k
        }
1767
2.02k
        if (!bit1 && bit4) {
1768
2.02k
          logtrace(LogSymbols, "$1 part_mode=%d\n", PART_nRx2N);
1769
2.02k
          return PART_nRx2N;
1770
2.02k
        }
1771
2.02k
      }
1772
67.3k
    }
1773
219k
    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
219k
      if (bit1) {
1778
90.5k
        logtrace(LogSymbols, "$1 part_mode=%d\n", PART_2NxN);
1779
90.5k
        return PART_2NxN;
1780
90.5k
      }
1781
1782
128k
      if (cLog2CbSize == 3) {
1783
127k
        logtrace(LogSymbols, "$1 part_mode=%d\n", PART_Nx2N);
1784
127k
        return PART_Nx2N;
1785
127k
      }
1786
1.54k
      else {
1787
1.54k
        int bit2 = tctx->cabac_decoder.decode_bit( &tctx->ctx_model[CONTEXT_MODEL_PART_MODE + 2]);
1788
1.54k
        logtrace(LogSymbols, "$1 part_mode=%d\n", PART_NxN - bit2);
1789
1.54k
        return (enum PartMode) ((int) PART_NxN - bit2)/*bit2 ? PART_Nx2N : PART_NxN*/;
1790
1.54k
      }
1791
128k
    }
1792
286k
  }
1793
1794
7.53M
  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
26.0M
{
1801
26.0M
  logtrace(LogSlice, "# prev_intra_luma_pred_flag\n");
1802
26.0M
  int bit = tctx->cabac_decoder.decode_bit( &tctx->ctx_model[CONTEXT_MODEL_PREV_INTRA_LUMA_PRED_FLAG]);
1803
26.0M
  logtrace(LogSymbols, "$1 prev_intra_luma_pred_flag=%d\n", bit);
1804
26.0M
  return bit;
1805
26.0M
}
1806
1807
1808
static inline int decode_mpm_idx(thread_context* tctx)
1809
5.63M
{
1810
5.63M
  logtrace(LogSlice, "# mpm_idx (TU:2)\n");
1811
5.63M
  int mpm = tctx->cabac_decoder.decode_TU_bypass( 2);
1812
5.63M
  logtrace(LogSlice, "> mpm_idx = %d\n", mpm);
1813
5.63M
  logtrace(LogSymbols, "$1 mpm_idx=%d\n", mpm);
1814
5.63M
  return mpm;
1815
5.63M
}
1816
1817
1818
static inline int decode_rem_intra_luma_pred_mode(thread_context* tctx)
1819
20.4M
{
1820
20.4M
  logtrace(LogSlice, "# rem_intra_luma_pred_mode (5 bits)\n");
1821
20.4M
  int value = tctx->cabac_decoder.decode_FL_bypass( 5);
1822
20.4M
  logtrace(LogSymbols, "$1 rem_intra_luma_pred_mode=%d\n", value);
1823
20.4M
  return value;
1824
20.4M
}
1825
1826
1827
static int decode_intra_chroma_pred_mode(thread_context* tctx)
1828
7.14M
{
1829
7.14M
  logtrace(LogSlice, "# intra_chroma_pred_mode\n");
1830
1831
7.14M
  int prefix = tctx->cabac_decoder.decode_bit( &tctx->ctx_model[CONTEXT_MODEL_INTRA_CHROMA_PRED_MODE]);
1832
1833
7.14M
  int mode;
1834
7.14M
  if (prefix == 0) {
1835
1.81M
    mode = 4;
1836
1.81M
  }
1837
5.33M
  else {
1838
5.33M
    mode = tctx->cabac_decoder.decode_FL_bypass( 2);
1839
5.33M
  }
1840
1841
7.14M
  logtrace(LogSlice, "> intra_chroma_pred_mode = %d\n", mode);
1842
7.14M
  logtrace(LogSymbols, "$1 intra_chroma_pred_mode=%d\n", mode);
1843
1844
7.14M
  return mode;
1845
7.14M
}
1846
1847
1848
static int decode_split_transform_flag(thread_context* tctx,
1849
                                       int log2TrafoSize)
1850
378k
{
1851
378k
  logtrace(LogSlice, "# split_transform_flag (log2TrafoSize=%d)\n", log2TrafoSize);
1852
1853
378k
  int context = 5 - log2TrafoSize;
1854
378k
  assert(context >= 0 && context <= 2);
1855
1856
378k
  logtrace(LogSlice, "# context: %d\n", context);
1857
1858
378k
  int bit = tctx->cabac_decoder.decode_bit( &tctx->ctx_model[CONTEXT_MODEL_SPLIT_TRANSFORM_FLAG + context]);
1859
378k
  logtrace(LogSymbols, "$1 split_transform_flag=%d\n", bit);
1860
378k
  return bit;
1861
378k
}
1862
1863
1864
static int decode_cbf_chroma(thread_context* tctx,
1865
                             int trafoDepth)
1866
16.0M
{
1867
16.0M
  logtrace(LogSlice, "# cbf_chroma\n");
1868
1869
16.0M
  int bit = tctx->cabac_decoder.decode_bit( &tctx->ctx_model[CONTEXT_MODEL_CBF_CHROMA + trafoDepth]);
1870
1871
16.0M
  logtrace(LogSymbols, "$1 cbf_chroma=%d\n", bit);
1872
16.0M
  return bit;
1873
16.0M
}
1874
1875
1876
static int decode_cbf_luma(thread_context* tctx,
1877
                           int trafoDepth)
1878
25.2M
{
1879
25.2M
  logtrace(LogSlice, "# cbf_luma\n");
1880
1881
25.2M
  int bit = tctx->cabac_decoder.decode_bit( &tctx->ctx_model[CONTEXT_MODEL_CBF_LUMA + (trafoDepth == 0)]);
1882
1883
25.2M
  logtrace(LogSlice, "> cbf_luma = %d\n", bit);
1884
1885
25.2M
  logtrace(LogSymbols, "$1 cbf_luma=%d\n", bit);
1886
25.2M
  return bit;
1887
25.2M
}
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
8.05M
{
1894
8.05M
  logtrace(LogSlice, "# coded_sub_block_flag\n");
1895
1896
  // tricky computation of csbfCtx
1897
8.05M
  int csbfCtx = ((coded_sub_block_neighbors & 1) | // right neighbor set  or
1898
8.05M
                 (coded_sub_block_neighbors >> 1)); // bottom neighbor set   -> csbfCtx=1
1899
1900
8.05M
  int ctxIdxInc = csbfCtx;
1901
8.05M
  if (cIdx != 0) {
1902
36.9k
    ctxIdxInc += 2;
1903
36.9k
  }
1904
1905
8.05M
  int bit = tctx->cabac_decoder.decode_bit(
1906
8.05M
                             &tctx->ctx_model[CONTEXT_MODEL_CODED_SUB_BLOCK_FLAG + ctxIdxInc]);
1907
1908
8.05M
  logtrace(LogSymbols, "$1 coded_sub_block_flag=%d\n", bit);
1909
8.05M
  return bit;
1910
8.05M
}
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
6.11M
{
1917
6.11M
  logtrace(LogSlice, "# cu_qp_delta_abs\n");
1918
1919
6.11M
  int bit = tctx->cabac_decoder.decode_bit(
1920
6.11M
                             &tctx->ctx_model[CONTEXT_MODEL_CU_QP_DELTA_ABS + 0]);
1921
6.11M
  if (bit == 0) {
1922
1.02M
    logtrace(LogSymbols, "$1 cu_qp_delta_abs=%d\n", 0);
1923
1.02M
    return 0;
1924
1.02M
  }
1925
1926
5.09M
  uint8_t prefix = 1;
1927
20.2M
  for (uint8_t i = 0; i < 4; i++) {
1928
16.4M
    bit = tctx->cabac_decoder.decode_bit(
1929
16.4M
                           &tctx->ctx_model[CONTEXT_MODEL_CU_QP_DELTA_ABS + 1]);
1930
16.4M
    if (bit == 0) { break; }
1931
15.1M
    else { prefix++; }
1932
16.4M
  }
1933
1934
5.09M
  if (prefix == 5) {
1935
3.80M
    uint32_t value = tctx->cabac_decoder.decode_EGk_bypass( 0);
1936
3.80M
    if (value >= 250) { return CABAC_QP_DELTA_ABS_ERROR; }
1937
3.80M
    logtrace(LogSymbols, "$1 cu_qp_delta_abs=%d\n", value + 5);
1938
3.80M
    return value + 5;
1939
3.80M
  }
1940
1.29M
  else {
1941
1.29M
    logtrace(LogSymbols, "$1 cu_qp_delta_abs=%d\n", prefix);
1942
1.29M
    return prefix;
1943
1.29M
  }
1944
5.09M
}
1945
1946
1947
static int decode_last_significant_coeff_prefix(thread_context* tctx,
1948
                                                int log2TrafoSize,
1949
                                                int cIdx,
1950
                                                context_model* model)
1951
70.8M
{
1952
70.8M
  logtrace(LogSlice, "# last_significant_coeff_prefix log2TrafoSize:%d cIdx:%d\n", log2TrafoSize, cIdx);
1953
1954
70.8M
  int cMax = (log2TrafoSize << 1) - 1;
1955
1956
70.8M
  int ctxOffset, ctxShift;
1957
70.8M
  if (cIdx == 0) {
1958
48.7M
    ctxOffset = 3 * (log2TrafoSize - 2) + ((log2TrafoSize - 1) >> 2);
1959
48.7M
    ctxShift = (log2TrafoSize + 1) >> 2;
1960
48.7M
  }
1961
22.0M
  else {
1962
22.0M
    ctxOffset = 15;
1963
22.0M
    ctxShift = log2TrafoSize - 2;
1964
22.0M
  }
1965
1966
70.8M
  int binIdx;
1967
70.8M
  int value = cMax;
1968
239M
  for (binIdx = 0; binIdx < cMax; binIdx++) {
1969
193M
    int ctxIdxInc = (binIdx >> ctxShift);
1970
1971
193M
    logtrace(LogSlice, "context: %d+%d\n", ctxOffset, ctxIdxInc);
1972
1973
193M
    int bit = tctx->cabac_decoder.decode_bit( &model[ctxOffset + ctxIdxInc]);
1974
193M
    if (bit == 0) {
1975
24.7M
      value = binIdx;
1976
24.7M
      break;
1977
24.7M
    }
1978
193M
  }
1979
1980
70.8M
  logtrace(LogSlice, "> last_significant_coeff_prefix: %d\n", value);
1981
1982
70.8M
  return value;
1983
70.8M
}
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
3
{
1997
3
  int tableSize = 4 * 4 * (2) + 8 * 8 * (2 * 2 * 4) + 16 * 16 * (2 * 4) + 32 * 32 * (2 * 4);
1998
1999
3
  uint8_t* p = (uint8_t*) malloc(tableSize);
2000
3
  if (p == nullptr) {
2001
0
    return false;
2002
0
  }
2003
2004
3
  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
9
  for (int cIdx = 0; cIdx < 2; cIdx++) {
2012
18
    for (int scanIdx = 0; scanIdx < 2; scanIdx++)
2013
60
      for (int prevCsbf = 0; prevCsbf < 4; prevCsbf++)
2014
48
        ctxIdxLookup[0][cIdx][scanIdx][prevCsbf] = p;
2015
2016
6
    p += 4 * 4;
2017
6
  }
2018
2019
  // 8x8
2020
2021
9
  for (int cIdx = 0; cIdx < 2; cIdx++)
2022
18
    for (int scanIdx = 0; scanIdx < 2; scanIdx++)
2023
60
      for (int prevCsbf = 0; prevCsbf < 4; prevCsbf++) {
2024
48
        ctxIdxLookup[1][cIdx][scanIdx][prevCsbf] = p;
2025
48
        p += 8 * 8;
2026
48
      }
2027
2028
  // 16x16
2029
2030
9
  for (int cIdx = 0; cIdx < 2; cIdx++)
2031
30
    for (int prevCsbf = 0; prevCsbf < 4; prevCsbf++) {
2032
72
      for (int scanIdx = 0; scanIdx < 2; scanIdx++) {
2033
48
        ctxIdxLookup[2][cIdx][scanIdx][prevCsbf] = p;
2034
48
      }
2035
2036
24
      p += 16 * 16;
2037
24
    }
2038
2039
  // 32x32
2040
2041
9
  for (int cIdx = 0; cIdx < 2; cIdx++)
2042
30
    for (int prevCsbf = 0; prevCsbf < 4; prevCsbf++) {
2043
72
      for (int scanIdx = 0; scanIdx < 2; scanIdx++) {
2044
48
        ctxIdxLookup[3][cIdx][scanIdx][prevCsbf] = p;
2045
48
      }
2046
2047
24
      p += 32 * 32;
2048
24
    }
2049
2050
2051
  // --- precompute ctxIdx tables ---
2052
2053
15
  for (int log2w = 2; log2w <= 5; log2w++)
2054
36
    for (int cIdx = 0; cIdx < 2; cIdx++)
2055
72
      for (int scanIdx = 0; scanIdx < 2; scanIdx++)
2056
240
        for (int prevCsbf = 0; prevCsbf < 4; prevCsbf++) {
2057
3.07k
          for (int yC = 0; yC < (1 << log2w); yC++)
2058
68.1k
            for (int xC = 0; xC < (1 << log2w); xC++) {
2059
65.2k
              int w = 1 << log2w;
2060
65.2k
              int sbWidth = w >> 2;
2061
2062
65.2k
              int sigCtx;
2063
2064
              // if log2TrafoSize==2
2065
65.2k
              if (sbWidth == 1) {
2066
768
                sigCtx = ctxIdxMap[(yC << 2) + xC];
2067
768
              }
2068
64.5k
              else if (xC + yC == 0) {
2069
144
                sigCtx = 0;
2070
144
              }
2071
64.3k
              else {
2072
64.3k
                int xS = xC >> 2;
2073
64.3k
                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
64.3k
                int xP = xC & 3;
2081
64.3k
                int yP = yC & 3;
2082
2083
                //logtrace(LogSlice,"posInSubset: %d,%d\n",xP,yP);
2084
                //logtrace(LogSlice,"prevCsbf: %d\n",prevCsbf);
2085
2086
64.3k
                switch (prevCsbf) {
2087
16.0k
                  case 0:
2088
16.0k
                    sigCtx = (xP + yP >= 3) ? 0 : (xP + yP > 0) ? 1 : 2;
2089
16.0k
                    break;
2090
16.0k
                  case 1:
2091
16.0k
                    sigCtx = (yP == 0) ? 2 : (yP == 1) ? 1 : 0;
2092
16.0k
                    break;
2093
16.0k
                  case 2:
2094
16.0k
                    sigCtx = (xP == 0) ? 2 : (xP == 1) ? 1 : 0;
2095
16.0k
                    break;
2096
16.0k
                  default:
2097
16.0k
                    sigCtx = 2;
2098
16.0k
                    break;
2099
64.3k
                }
2100
2101
                //logtrace(LogSlice,"a) sigCtx=%d\n",sigCtx);
2102
2103
64.3k
                if (cIdx == 0) {
2104
32.1k
                  if (xS + yS > 0) sigCtx += 3;
2105
2106
                  //logtrace(LogSlice,"b) sigCtx=%d\n",sigCtx);
2107
2108
                  // if log2TrafoSize==3
2109
32.1k
                  if (sbWidth == 2) {
2110
                    // 8x8 block
2111
1.51k
                    sigCtx += (scanIdx == 0) ? 9 : 15;
2112
1.51k
                  }
2113
30.6k
                  else {
2114
30.6k
                    sigCtx += 21;
2115
30.6k
                  }
2116
2117
                  //logtrace(LogSlice,"c) sigCtx=%d\n",sigCtx);
2118
32.1k
                }
2119
32.1k
                else {
2120
                  // if log2TrafoSize==3
2121
32.1k
                  if (sbWidth == 2) {
2122
                    // 8x8 block
2123
1.51k
                    sigCtx += 9;
2124
1.51k
                  }
2125
30.6k
                  else {
2126
30.6k
                    sigCtx += 12;
2127
30.6k
                  }
2128
32.1k
                }
2129
64.3k
              }
2130
2131
65.2k
              int ctxIdxInc;
2132
65.2k
              if (cIdx == 0) { ctxIdxInc = sigCtx; }
2133
32.6k
              else { ctxIdxInc = 27 + sigCtx; }
2134
2135
65.2k
              if (ctxIdxLookup[log2w - 2][cIdx][scanIdx][prevCsbf][xC + (yC << log2w)] != 0xFF) {
2136
31.3k
                assert(ctxIdxLookup[log2w-2][cIdx][scanIdx][prevCsbf][xC+(yC<<log2w)] == ctxIdxInc);
2137
31.3k
              }
2138
2139
65.2k
              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
65.2k
            }
2144
192
        }
2145
2146
3
  return true;
2147
3
}
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
1
{
2275
1
  free(ctxIdxLookup[0][0][0][0]);
2276
1
  ctxIdxLookup[0][0][0][0] = nullptr;
2277
1
}
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
503M
{
2376
503M
  logtrace(LogSlice, "# significant_coeff_flag\n");
2377
503M
  logtrace(LogSlice, "context: %d\n", ctxIdxInc);
2378
2379
503M
  int bit = tctx->cabac_decoder.decode_bit(
2380
503M
                             &tctx->ctx_model[CONTEXT_MODEL_SIGNIFICANT_COEFF_FLAG + ctxIdxInc]);
2381
2382
503M
  logtrace(LogSymbols, "$1 significant_coeff_flag=%d\n", bit);
2383
2384
503M
  return bit;
2385
503M
}
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
256M
{
2397
256M
  logtrace(LogSlice, "# coeff_abs_level_greater1\n");
2398
2399
256M
  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
256M
           *lastInvocation_greater1Ctx,
2401
256M
           *lastInvocation_coeff_abs_level_greater1_flag,
2402
256M
           *lastInvocation_ctxSet);
2403
2404
256M
  int lastGreater1Ctx;
2405
256M
  int greater1Ctx;
2406
256M
  int ctxSet;
2407
2408
256M
  logtrace(LogSlice, "c1: %d\n", c1);
2409
2410
256M
  if (firstCoeffInSubblock) {
2411
    // block with real DC -> ctx 0
2412
43.6M
    if (i == 0 || cIdx > 0) { ctxSet = 0; }
2413
8.02M
    else { ctxSet = 2; }
2414
2415
43.6M
    if (firstSubblock) { lastGreater1Ctx = 1; }
2416
8.05M
    else { lastGreater1Ctx = lastSubblock_greater1Ctx; }
2417
2418
43.6M
    if (lastGreater1Ctx == 0) { ctxSet++; }
2419
2420
43.6M
    logtrace(LogSlice, "ctxSet: %d\n", ctxSet);
2421
2422
43.6M
    greater1Ctx = 1;
2423
43.6M
  }
2424
212M
  else {
2425
    // !firstCoeffInSubblock
2426
212M
    ctxSet = *lastInvocation_ctxSet;
2427
212M
    logtrace(LogSlice, "ctxSet (old): %d\n", ctxSet);
2428
2429
212M
    greater1Ctx = *lastInvocation_greater1Ctx;
2430
212M
    if (greater1Ctx > 0) {
2431
175M
      int lastGreater1Flag = *lastInvocation_coeff_abs_level_greater1_flag;
2432
175M
      if (lastGreater1Flag == 1) greater1Ctx = 0;
2433
167M
      else {
2434
        /*if (greater1Ctx>0)*/
2435
167M
        greater1Ctx++;
2436
167M
      }
2437
175M
    }
2438
212M
  }
2439
2440
256M
  ctxSet = c1; // use HM algo
2441
2442
256M
  int ctxIdxInc = (ctxSet * 4) + (greater1Ctx >= 3 ? 3 : greater1Ctx);
2443
2444
256M
  if (cIdx > 0) { ctxIdxInc += 16; }
2445
2446
256M
  int bit = tctx->cabac_decoder.decode_bit(
2447
256M
                             &tctx->ctx_model[CONTEXT_MODEL_COEFF_ABS_LEVEL_GREATER1_FLAG + ctxIdxInc]);
2448
2449
256M
  *lastInvocation_greater1Ctx = greater1Ctx;
2450
256M
  *lastInvocation_coeff_abs_level_greater1_flag = bit;
2451
256M
  *lastInvocation_ctxSet = ctxSet;
2452
2453
  //logtrace(LogSymbols,"$1 coeff_abs_level_greater1=%d\n",bit);
2454
2455
256M
  return bit;
2456
256M
}
2457
2458
2459
static int decode_coeff_abs_level_greater2(thread_context* tctx,
2460
                                           int cIdx, // int i,int n,
2461
                                           int ctxSet)
2462
7.48M
{
2463
7.48M
  logtrace(LogSlice, "# coeff_abs_level_greater2\n");
2464
2465
7.48M
  int ctxIdxInc = ctxSet;
2466
2467
7.48M
  if (cIdx > 0) ctxIdxInc += 4;
2468
2469
7.48M
  int bit = tctx->cabac_decoder.decode_bit(
2470
7.48M
                             &tctx->ctx_model[CONTEXT_MODEL_COEFF_ABS_LEVEL_GREATER2_FLAG + ctxIdxInc]);
2471
2472
7.48M
  logtrace(LogSymbols, "$1 coeff_abs_level_greater2=%d\n", bit);
2473
2474
7.48M
  return bit;
2475
7.48M
}
2476
2477
2478
1.86M
#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
33.6k
#define MAX_RICE_PARAM 29
2487
5.01k
#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
235M
{
2492
235M
  logtrace(LogSlice, "# decode_coeff_abs_level_remaining\n");
2493
2494
235M
  uint32_t prefix = 0;
2495
237M
  while (tctx->cabac_decoder.decode_bypass()) {
2496
1.86M
    prefix++;
2497
1.86M
    if (prefix > MAX_PREFIX) {
2498
9.04k
      return 0; // TODO: error
2499
9.04k
    }
2500
1.86M
  }
2501
2502
  // prefix = nb. 1 bits
2503
2504
235M
  int32_t value;
2505
2506
235M
  if (prefix <= 3) {
2507
    // when code only TR part (level < TRMax)
2508
2509
235M
    int codeword = tctx->cabac_decoder.decode_FL_bypass( cRiceParam);
2510
235M
    value = (prefix << cRiceParam) + codeword;
2511
235M
  }
2512
233k
  else {
2513
    // Suffix coded with EGk. Note that the unary part of EGk is already
2514
    // included in the 'prefix' counter above.
2515
2516
233k
    int codeword = tctx->cabac_decoder.decode_FL_bypass( prefix - 3 + cRiceParam);
2517
233k
    value = (((UINT32_C(1) << (prefix - 3)) + 3 - 1) << cRiceParam) + codeword;
2518
233k
  }
2519
2520
235M
  logtrace(LogSymbols, "$1 coeff_abs_level_remaining=%d\n", value);
2521
2522
235M
  return value;
2523
235M
}
2524
2525
2526
static int decode_merge_flag(thread_context* tctx)
2527
890k
{
2528
890k
  logtrace(LogSlice, "# merge_flag\n");
2529
2530
890k
  int bit = tctx->cabac_decoder.decode_bit(
2531
890k
                             &tctx->ctx_model[CONTEXT_MODEL_MERGE_FLAG]);
2532
2533
890k
  logtrace(LogSymbols, "$1 merge_flag=%d\n", bit);
2534
2535
890k
  return bit;
2536
890k
}
2537
2538
2539
static int decode_merge_idx(thread_context* tctx)
2540
1.63M
{
2541
1.63M
  logtrace(LogSlice, "# merge_idx\n");
2542
2543
1.63M
  if (tctx->shdr->MaxNumMergeCand <= 1) {
2544
181k
    logtrace(LogSymbols, "$1 merge_idx=%d\n", 0);
2545
181k
    return 0;
2546
181k
  }
2547
2548
  // TU coding, first bin is CABAC, remaining are bypass.
2549
  // cMax = MaxNumMergeCand-1
2550
2551
1.44M
  int idx = tctx->cabac_decoder.decode_bit(
2552
1.44M
                             &tctx->ctx_model[CONTEXT_MODEL_MERGE_IDX]);
2553
2554
1.44M
  if (idx == 0) {
2555
    // nothing
2556
1.15M
  }
2557
292k
  else {
2558
292k
    idx = 1;
2559
2560
320k
    while (idx < tctx->shdr->MaxNumMergeCand - 1) {
2561
304k
      if (tctx->cabac_decoder.decode_bypass()) {
2562
27.4k
        idx++;
2563
27.4k
      }
2564
276k
      else {
2565
276k
        break;
2566
276k
      }
2567
304k
    }
2568
292k
  }
2569
2570
1.44M
  logtrace(LogSlice, "> merge_idx = %d\n", idx);
2571
1.44M
  logtrace(LogSymbols, "$1 merge_idx=%d\n", idx);
2572
2573
1.44M
  return idx;
2574
1.63M
}
2575
2576
2577
static int decode_pred_mode_flag(thread_context* tctx)
2578
616k
{
2579
616k
  logtrace(LogSlice, "# pred_mode_flag\n");
2580
2581
616k
  int bit = tctx->cabac_decoder.decode_bit(
2582
616k
                             &tctx->ctx_model[CONTEXT_MODEL_PRED_MODE_FLAG]);
2583
2584
616k
  logtrace(LogSymbols, "$1 pred_mode=%d\n", bit);
2585
616k
  return bit;
2586
616k
}
2587
2588
static int decode_mvp_lx_flag(thread_context* tctx)
2589
576k
{
2590
576k
  logtrace(LogSlice, "# mvp_lx_flag\n");
2591
2592
576k
  int bit = tctx->cabac_decoder.decode_bit(
2593
576k
                             &tctx->ctx_model[CONTEXT_MODEL_MVP_LX_FLAG]);
2594
2595
576k
  logtrace(LogSymbols, "$1 mvp_lx_flag=%d\n", bit);
2596
576k
  return bit;
2597
576k
}
2598
2599
static int decode_rqt_root_cbf(thread_context* tctx)
2600
431k
{
2601
431k
  logtrace(LogSlice, "# rqt_root_cbf\n");
2602
2603
431k
  int bit = tctx->cabac_decoder.decode_bit(
2604
431k
                             &tctx->ctx_model[CONTEXT_MODEL_RQT_ROOT_CBF]);
2605
2606
431k
  logtrace(LogSymbols, "$1 rqt_root_cbf=%d\n", bit);
2607
431k
  return bit;
2608
431k
}
2609
2610
static int decode_ref_idx_lX(thread_context* tctx, int numRefIdxLXActive)
2611
576k
{
2612
  // prevent endless loop when 'numRefIdxLXActive' is invalid
2613
576k
  if (numRefIdxLXActive <= 1) {
2614
464k
    return 0;
2615
464k
  }
2616
2617
111k
  logtrace(LogSlice, "# ref_idx_lX\n");
2618
2619
111k
  int cMax = numRefIdxLXActive - 1;
2620
2621
111k
  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
111k
  int bit = tctx->cabac_decoder.decode_bit(
2627
111k
                             &tctx->ctx_model[CONTEXT_MODEL_REF_IDX_LX + 0]);
2628
2629
111k
  int idx = 0;
2630
2631
132k
  while (bit) {
2632
23.9k
    idx++;
2633
23.9k
    if (idx == cMax) { break; }
2634
2635
21.0k
    if (idx == 1) {
2636
15.4k
      bit = tctx->cabac_decoder.decode_bit(
2637
15.4k
                             &tctx->ctx_model[CONTEXT_MODEL_REF_IDX_LX + 1]);
2638
15.4k
    }
2639
5.64k
    else {
2640
5.64k
      bit = tctx->cabac_decoder.decode_bypass();
2641
5.64k
    }
2642
21.0k
  }
2643
2644
111k
  logtrace(LogSlice, "> ref_idx = %d\n", idx);
2645
2646
111k
  logtrace(LogSymbols, "$1 ref_idx_lX=%d\n", idx);
2647
111k
  return idx;
2648
111k
}
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
399k
{
2656
399k
  logtrace(LogSlice, "# inter_pred_idc\n");
2657
2658
399k
  int value;
2659
2660
399k
  context_model* model = &tctx->ctx_model[CONTEXT_MODEL_INTER_PRED_IDC];
2661
2662
399k
  if (nPbW + nPbH == 12) {
2663
209k
    value = tctx->cabac_decoder.decode_bit(
2664
209k
                             &model[4]);
2665
209k
  }
2666
189k
  else {
2667
189k
    int bit0 = tctx->cabac_decoder.decode_bit(
2668
189k
                                &model[ctDepth]);
2669
189k
    if (bit0 == 0) {
2670
99.9k
      value = tctx->cabac_decoder.decode_bit(
2671
99.9k
                               &model[4]);
2672
99.9k
    }
2673
89.8k
    else {
2674
89.8k
      value = 2;
2675
89.8k
    }
2676
189k
  }
2677
2678
399k
  logtrace(LogSlice, "> inter_pred_idc = %d (%s)\n", value,
2679
399k
           value == 0 ? "L0" : (value == 1 ? "L1" : "BI"));
2680
2681
399k
  logtrace(LogSymbols, "$1 decode_inter_pred_idx=%d\n", value + 1);
2682
2683
399k
  return (enum InterPredIdc) (value + 1);
2684
399k
}
2685
2686
2687
static int decode_explicit_rdpcm_flag(thread_context* tctx, int cIdx)
2688
7.75k
{
2689
7.75k
  context_model* model = &tctx->ctx_model[CONTEXT_MODEL_RDPCM_FLAG];
2690
7.75k
  int value = tctx->cabac_decoder.decode_bit( &model[cIdx ? 1 : 0]);
2691
7.75k
  return value;
2692
7.75k
}
2693
2694
2695
static int decode_explicit_rdpcm_dir(thread_context* tctx, int cIdx)
2696
6.43k
{
2697
6.43k
  context_model* model = &tctx->ctx_model[CONTEXT_MODEL_RDPCM_DIR];
2698
6.43k
  int value = tctx->cabac_decoder.decode_bit( &model[cIdx ? 1 : 0]);
2699
6.43k
  return value;
2700
6.43k
}
2701
2702
2703
/* Take CtbAddrInTS and compute
2704
   -> CtbAddrInRS, CtbX, CtbY
2705
 */
2706
bool setCtbAddrFromTS(thread_context* tctx)
2707
981k
{
2708
981k
  const seq_parameter_set& sps = tctx->img->get_sps();
2709
2710
981k
  if (tctx->CtbAddrInTS < sps.PicSizeInCtbsY) {
2711
973k
    tctx->CtbAddrInRS = tctx->img->get_pps().scan->CtbAddrTStoRS[tctx->CtbAddrInTS];
2712
2713
973k
    tctx->CtbX = tctx->CtbAddrInRS % sps.PicWidthInCtbsY;
2714
973k
    tctx->CtbY = tctx->CtbAddrInRS / sps.PicWidthInCtbsY;
2715
973k
    return false;
2716
973k
  }
2717
7.03k
  else {
2718
7.03k
    tctx->CtbAddrInRS = sps.PicSizeInCtbsY;
2719
2720
7.03k
    tctx->CtbX = tctx->CtbAddrInRS % sps.PicWidthInCtbsY;
2721
7.03k
    tctx->CtbY = tctx->CtbAddrInRS / sps.PicWidthInCtbsY;
2722
7.03k
    return true;
2723
7.03k
  }
2724
981k
}
2725
2726
// returns true when we reached the end of the image (ctbAddr==picSizeInCtbsY)
2727
bool advanceCtbAddr(thread_context* tctx)
2728
945k
{
2729
945k
  tctx->CtbAddrInTS++;
2730
2731
945k
  return setCtbAddrFromTS(tctx);
2732
945k
}
2733
2734
2735
void read_sao(thread_context* tctx, int xCtb, int yCtb,
2736
              int CtbAddrInSliceSeg)
2737
811k
{
2738
811k
  slice_segment_header* shdr = tctx->shdr;
2739
811k
  de265_image* img = tctx->img;
2740
811k
  const seq_parameter_set& sps = img->get_sps();
2741
811k
  const pic_parameter_set& pps = img->get_pps();
2742
2743
811k
  logtrace(LogSlice, "# read_sao(%d,%d)\n", xCtb, yCtb);
2744
2745
811k
  sao_info saoinfo;
2746
811k
  memset(&saoinfo, 0, sizeof(sao_info));
2747
811k
  logtrace(LogSlice, "sizeof saoinfo: %d\n", sizeof(sao_info));
2748
2749
2750
811k
  char sao_merge_left_flag = 0;
2751
811k
  char sao_merge_up_flag = 0;
2752
2753
811k
  if (xCtb > 0) {
2754
    //char leftCtbInSliceSeg = (CtbAddrInSliceSeg>0);
2755
758k
    char leftCtbInSliceSeg = (tctx->CtbAddrInRS > shdr->SliceAddrRS);
2756
758k
    char leftCtbInTile = (pps.scan->TileIdRS[xCtb + yCtb * sps.PicWidthInCtbsY] ==
2757
758k
                          pps.scan->TileIdRS[xCtb - 1 + yCtb * sps.PicWidthInCtbsY]);
2758
2759
758k
    if (leftCtbInSliceSeg && leftCtbInTile) {
2760
758k
      sao_merge_left_flag = decode_sao_merge_flag(tctx);
2761
758k
      logtrace(LogSlice, "sao_merge_left_flag: %d\n", sao_merge_left_flag);
2762
758k
    }
2763
758k
  }
2764
2765
811k
  if (yCtb > 0 && sao_merge_left_flag == 0) {
2766
638k
    logtrace(LogSlice, "CtbAddrInRS:%d PicWidthInCtbsY:%d slice_segment_address:%d\n",
2767
638k
             tctx->CtbAddrInRS,
2768
638k
             sps.PicWidthInCtbsY,
2769
638k
             shdr->slice_segment_address);
2770
638k
    bool upCtbInSliceSeg = (tctx->CtbAddrInRS - sps.PicWidthInCtbsY) >= shdr->SliceAddrRS;
2771
638k
    bool upCtbInTile = (pps.scan->TileIdRS[xCtb + yCtb * sps.PicWidthInCtbsY] ==
2772
638k
                        pps.scan->TileIdRS[xCtb + (yCtb - 1) * sps.PicWidthInCtbsY]);
2773
2774
638k
    if (upCtbInSliceSeg && upCtbInTile) {
2775
635k
      sao_merge_up_flag = decode_sao_merge_flag(tctx);
2776
635k
      logtrace(LogSlice, "sao_merge_up_flag: %d\n", sao_merge_up_flag);
2777
635k
    }
2778
638k
  }
2779
2780
811k
  if (!sao_merge_up_flag && !sao_merge_left_flag) {
2781
708k
    int nChroma = 3;
2782
708k
    if (sps.ChromaArrayType == CHROMA_MONO) nChroma = 1;
2783
2784
2.83M
    for (int cIdx = 0; cIdx < nChroma; cIdx++) {
2785
2.12M
      if ((shdr->slice_sao_luma_flag && cIdx == 0) ||
2786
2.06M
          (shdr->slice_sao_chroma_flag && cIdx > 0)) {
2787
2.06M
        uint8_t SaoTypeIdx = 0;
2788
2789
2.06M
        if (cIdx == 0) {
2790
694k
          uint8_t sao_type_idx_luma = decode_sao_type_idx(tctx);
2791
694k
          logtrace(LogSlice, "sao_type_idx_luma: %d\n", sao_type_idx_luma);
2792
694k
          saoinfo.SaoTypeIdx = SaoTypeIdx = sao_type_idx_luma;
2793
694k
        }
2794
1.37M
        else if (cIdx == 1) {
2795
686k
          uint8_t sao_type_idx_chroma = decode_sao_type_idx(tctx);
2796
686k
          logtrace(LogSlice, "sao_type_idx_chroma: %d\n", sao_type_idx_chroma);
2797
686k
          SaoTypeIdx = sao_type_idx_chroma;
2798
686k
          saoinfo.SaoTypeIdx |= SaoTypeIdx << (2 * 1);
2799
686k
          saoinfo.SaoTypeIdx |= SaoTypeIdx << (2 * 2); // set for both chroma components
2800
686k
        }
2801
685k
        else {
2802
          // SaoTypeIdx = 0
2803
2804
685k
          SaoTypeIdx = (saoinfo.SaoTypeIdx >> (2 * cIdx)) & 0x3;
2805
685k
        }
2806
2807
2.06M
        if (SaoTypeIdx != 0) {
2808
3.26M
          for (int i = 0; i < 4; i++) {
2809
2.61M
            saoinfo.saoOffsetVal[cIdx][i] = decode_sao_offset_abs(tctx, img->get_bit_depth(cIdx));
2810
2.61M
            logtrace(LogSlice, "saoOffsetVal[%d][%d] = %d\n", cIdx, i, saoinfo.saoOffsetVal[cIdx][i]);
2811
2.61M
          }
2812
2813
652k
          int sign[4];
2814
652k
          if (SaoTypeIdx == 1) {
2815
3.20M
            for (int i = 0; i < 4; i++) {
2816
2.56M
              if (saoinfo.saoOffsetVal[cIdx][i] != 0) {
2817
23.9k
                sign[i] = decode_sao_offset_sign(tctx) ? -1 : 1;
2818
23.9k
              }
2819
2.53M
              else {
2820
2.53M
                sign[i] = 0; // not really required, but compiler warns about uninitialized values
2821
2.53M
              }
2822
2.56M
            }
2823
2824
640k
            saoinfo.sao_band_position[cIdx] = decode_sao_band_position(tctx);
2825
640k
          }
2826
12.0k
          else {
2827
12.0k
            uint8_t SaoEoClass = 0;
2828
2829
12.0k
            sign[0] = sign[1] = 1;
2830
12.0k
            sign[2] = sign[3] = -1;
2831
2832
12.0k
            if (cIdx == 0) {
2833
4.23k
              saoinfo.SaoEoClass = SaoEoClass = decode_sao_class(tctx);
2834
4.23k
            }
2835
7.77k
            else if (cIdx == 1) {
2836
3.89k
              SaoEoClass = decode_sao_class(tctx);
2837
3.89k
              saoinfo.SaoEoClass |= SaoEoClass << (2 * 1);
2838
3.89k
              saoinfo.SaoEoClass |= SaoEoClass << (2 * 2);
2839
3.89k
            }
2840
2841
12.0k
            logtrace(LogSlice, "SaoEoClass[%d] = %d\n", cIdx, SaoEoClass);
2842
12.0k
          }
2843
2844
652k
          int log2OffsetScale;
2845
2846
652k
          if (cIdx == 0) {
2847
221k
            log2OffsetScale = pps.range_extension.log2_sao_offset_scale_luma;
2848
221k
          }
2849
431k
          else {
2850
431k
            log2OffsetScale = pps.range_extension.log2_sao_offset_scale_chroma;
2851
431k
          }
2852
2853
3.26M
          for (int i = 0; i < 4; i++) {
2854
2.61M
            saoinfo.saoOffsetVal[cIdx][i] = sign[i] * (saoinfo.saoOffsetVal[cIdx][i] << log2OffsetScale);
2855
2.61M
          }
2856
652k
        }
2857
2.06M
      }
2858
2.12M
    }
2859
2860
708k
    img->set_sao_info(xCtb, yCtb, &saoinfo);
2861
708k
  }
2862
2863
2864
811k
  if (sao_merge_left_flag) {
2865
96.8k
    img->set_sao_info(xCtb, yCtb, img->get_sao_info(xCtb - 1, yCtb));
2866
96.8k
  }
2867
2868
811k
  if (sao_merge_up_flag) {
2869
6.14k
    img->set_sao_info(xCtb, yCtb, img->get_sao_info(xCtb, yCtb - 1));
2870
6.14k
  }
2871
811k
}
2872
2873
2874
void read_coding_tree_unit(thread_context* tctx)
2875
945k
{
2876
945k
  slice_segment_header* shdr = tctx->shdr;
2877
945k
  de265_image* img = tctx->img;
2878
945k
  const seq_parameter_set& sps = img->get_sps();
2879
2880
945k
  int xCtb = (tctx->CtbAddrInRS % sps.PicWidthInCtbsY);
2881
945k
  int yCtb = (tctx->CtbAddrInRS / sps.PicWidthInCtbsY);
2882
945k
  int xCtbPixels = xCtb << sps.Log2CtbSizeY;
2883
945k
  int yCtbPixels = yCtb << sps.Log2CtbSizeY;
2884
2885
945k
  logtrace(LogSlice, "----- decode CTB %d;%d (%d;%d) POC=%d, SliceAddrRS=%d\n",
2886
945k
           xCtbPixels, yCtbPixels, xCtb, yCtb,
2887
945k
           tctx->img->PicOrderCntVal, tctx->shdr->SliceAddrRS);
2888
2889
945k
  img->set_SliceAddrRS(xCtb, yCtb, tctx->shdr->SliceAddrRS);
2890
2891
945k
  img->set_SliceHeaderIndex(xCtbPixels, yCtbPixels, shdr->slice_index);
2892
2893
945k
  int CtbAddrInSliceSeg = tctx->CtbAddrInRS - shdr->slice_segment_address;
2894
2895
945k
  if (shdr->slice_sao_luma_flag || shdr->slice_sao_chroma_flag) {
2896
811k
    read_sao(tctx, xCtb, yCtb, CtbAddrInSliceSeg);
2897
811k
  }
2898
2899
945k
  read_coding_quadtree(tctx, xCtbPixels, yCtbPixels, sps.Log2CtbSizeY, 0);
2900
945k
}
2901
2902
2903
inline static int luma_pos_to_ctbAddrRS(const seq_parameter_set* sps, int x, int y)
2904
46.2M
{
2905
46.2M
  int ctbX = x >> sps->Log2CtbSizeY;
2906
46.2M
  int ctbY = y >> sps->Log2CtbSizeY;
2907
2908
46.2M
  return ctbY * sps->PicWidthInCtbsY + ctbX;
2909
46.2M
}
2910
2911
2912
int check_CTB_available(const de265_image* img,
2913
                        int xC, int yC, int xN, int yN)
2914
24.0M
{
2915
  // check whether neighbor is outside of frame
2916
2917
24.0M
  if (xN < 0 || yN < 0) { return 0; }
2918
23.1M
  if (xN >= img->get_sps().pic_width_in_luma_samples) { return 0; }
2919
23.1M
  if (yN >= img->get_sps().pic_height_in_luma_samples) { return 0; }
2920
2921
2922
23.1M
  int current_ctbAddrRS = luma_pos_to_ctbAddrRS(&img->get_sps(), xC, yC);
2923
23.1M
  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
23.1M
  if (img->get_SliceAddrRS_atCtbRS(current_ctbAddrRS) !=
2928
23.1M
      img->get_SliceAddrRS_atCtbRS(neighbor_ctbAddrRS)) {
2929
4.30k
    return 0;
2930
4.30k
  }
2931
2932
  // check if both CTBs are in the same tile.
2933
2934
23.1M
  if (img->get_pps().scan->TileIdRS[current_ctbAddrRS] !=
2935
23.1M
      img->get_pps().scan->TileIdRS[neighbor_ctbAddrRS]) {
2936
9.17k
    return 0;
2937
9.17k
  }
2938
2939
23.1M
  return 1;
2940
23.1M
}
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
35.6M
{
2948
35.6M
  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
35.6M
  de265_image* img = tctx->img;
2953
35.6M
  const seq_parameter_set& sps = img->get_sps();
2954
35.6M
  const pic_parameter_set& pps = img->get_pps();
2955
2956
35.6M
  enum PredMode PredMode = img->get_pred_mode(x0, y0);
2957
2958
35.6M
  if (cIdx == 0) {
2959
24.4M
    img->set_nonzero_coefficient(x0, y0, log2TrafoSize);
2960
24.4M
  }
2961
2962
2963
35.6M
  if (pps.transform_skip_enabled_flag &&
2964
273k
      !tctx->cu_transquant_bypass_flag &&
2965
242k
      (log2TrafoSize <= pps.Log2MaxTransformSkipSize)) {
2966
108k
    tctx->transform_skip_flag[cIdx] = decode_transform_skip_flag(tctx, cIdx);
2967
108k
  }
2968
35.4M
  else {
2969
35.4M
    tctx->transform_skip_flag[cIdx] = 0;
2970
35.4M
  }
2971
2972
2973
35.6M
  tctx->explicit_rdpcm_flag = false;
2974
2975
35.6M
  if (PredMode == MODE_INTER && sps.range_extension.explicit_rdpcm_enabled_flag &&
2976
19.7k
      (tctx->transform_skip_flag[cIdx] || tctx->cu_transquant_bypass_flag)) {
2977
7.75k
    tctx->explicit_rdpcm_flag = decode_explicit_rdpcm_flag(tctx, cIdx);
2978
7.75k
    if (tctx->explicit_rdpcm_flag) {
2979
6.43k
      tctx->explicit_rdpcm_dir = decode_explicit_rdpcm_dir(tctx, cIdx);
2980
6.43k
    }
2981
2982
    //printf("EXPLICIT RDPCM %d;%d\n",x0,y0);
2983
7.75k
  }
2984
35.6M
  else {
2985
35.6M
    tctx->explicit_rdpcm_flag = false;
2986
35.6M
  }
2987
2988
2989
  // sbType for persistent_rice_adaptation_enabled_flag
2990
2991
35.6M
  int sbType = (cIdx == 0) ? 2 : 0;
2992
35.6M
  if (tctx->transform_skip_flag[cIdx] || tctx->cu_transquant_bypass_flag) {
2993
5.43M
    sbType++;
2994
5.43M
  }
2995
2996
2997
  // --- decode position of last coded coefficient ---
2998
2999
35.6M
  int last_significant_coeff_x_prefix =
3000
35.6M
      decode_last_significant_coeff_prefix(tctx, log2TrafoSize, cIdx,
3001
35.6M
                                           &tctx->ctx_model[CONTEXT_MODEL_LAST_SIGNIFICANT_COEFFICIENT_X_PREFIX]);
3002
3003
35.6M
  int last_significant_coeff_y_prefix =
3004
35.6M
      decode_last_significant_coeff_prefix(tctx, log2TrafoSize, cIdx,
3005
35.6M
                                           &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
35.6M
  int LastSignificantCoeffX;
3011
35.6M
  if (last_significant_coeff_x_prefix > 3) {
3012
1.36M
    int nBits = (last_significant_coeff_x_prefix >> 1) - 1;
3013
1.36M
    int last_significant_coeff_x_suffix = tctx->cabac_decoder.decode_FL_bypass( nBits);
3014
3015
1.36M
    LastSignificantCoeffX =
3016
1.36M
        ((2 + (last_significant_coeff_x_prefix & 1)) << nBits) + last_significant_coeff_x_suffix;
3017
1.36M
  }
3018
34.2M
  else {
3019
34.2M
    LastSignificantCoeffX = last_significant_coeff_x_prefix;
3020
34.2M
  }
3021
3022
35.6M
  int LastSignificantCoeffY;
3023
35.6M
  if (last_significant_coeff_y_prefix > 3) {
3024
1.31M
    int nBits = (last_significant_coeff_y_prefix >> 1) - 1;
3025
1.31M
    int last_significant_coeff_y_suffix = tctx->cabac_decoder.decode_FL_bypass( nBits);
3026
3027
1.31M
    LastSignificantCoeffY =
3028
1.31M
        ((2 + (last_significant_coeff_y_prefix & 1)) << nBits) + last_significant_coeff_y_suffix;
3029
1.31M
  }
3030
34.2M
  else {
3031
34.2M
    LastSignificantCoeffY = last_significant_coeff_y_prefix;
3032
34.2M
  }
3033
3034
3035
  // --- determine scanIdx ---
3036
3037
35.6M
  int scanIdx;
3038
3039
35.6M
  if (PredMode == MODE_INTRA) {
3040
35.2M
    if (cIdx == 0) {
3041
24.1M
      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
24.1M
    }
3044
11.1M
    else {
3045
11.1M
      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
11.1M
    }
3049
35.2M
  }
3050
329k
  else {
3051
329k
    scanIdx = 0;
3052
329k
  }
3053
3054
35.6M
  if (scanIdx == 2) {
3055
348k
    std::swap(LastSignificantCoeffX, LastSignificantCoeffY);
3056
348k
  }
3057
3058
35.6M
  logtrace(LogSlice, "LastSignificantCoeff: x=%d;y=%d\n", LastSignificantCoeffX, LastSignificantCoeffY);
3059
3060
35.6M
  const position* ScanOrderSub = get_scan_order(log2TrafoSize - 2, scanIdx);
3061
35.6M
  const position* ScanOrderPos = get_scan_order(2, scanIdx);
3062
3063
35.6M
  logtrace(LogSlice, "ScanOrderPos: ");
3064
605M
  for (int n = 0; n < 4 * 4; n++)
3065
570M
    logtrace(LogSlice, "*%d,%d ", ScanOrderPos[n].x, ScanOrderPos[n].y);
3066
35.6M
  logtrace(LogSlice, "*\n");
3067
3068
3069
  // --- find last sub block and last scan pos ---
3070
3071
35.6M
  int xC, yC;
3072
3073
35.6M
  scan_position lastScanP = get_scan_position(LastSignificantCoeffX, LastSignificantCoeffY,
3074
35.6M
                                              scanIdx, log2TrafoSize);
3075
3076
35.6M
  int lastScanPos = lastScanP.scanPos;
3077
35.6M
  int lastSubBlock = lastScanP.subBlock;
3078
3079
3080
35.6M
  int sbWidth = 1 << (log2TrafoSize - 2);
3081
3082
35.6M
  uint8_t coded_sub_block_neighbors[32 / 4 * 32 / 4];
3083
35.6M
  memset(coded_sub_block_neighbors, 0, sbWidth * sbWidth);
3084
3085
35.6M
  int c1 = 1;
3086
35.6M
  bool firstSubblock = true; // for coeff_abs_level_greater1_flag context model
3087
35.6M
  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
35.6M
  int CoeffStride = 1 << log2TrafoSize;
3097
3098
35.6M
  int lastInvocation_greater1Ctx = 0;
3099
35.6M
  int lastInvocation_coeff_abs_level_greater1_flag = 0;
3100
35.6M
  int lastInvocation_ctxSet = 0;
3101
3102
3103
  // ----- decode coefficients -----
3104
3105
35.6M
  tctx->nCoeff[cIdx] = 0;
3106
3107
3108
  // i - subblock index
3109
  // n - coefficient index in subblock
3110
3111
80.7M
  for (int i = lastSubBlock; i >= 0; i--) {
3112
45.0M
    position S = ScanOrderSub[i];
3113
45.0M
    int inferSbDcSigCoeffFlag = 0;
3114
3115
45.0M
    logtrace(LogSlice, "sub block scan idx: %d\n", i);
3116
3117
3118
    // --- check whether this sub-block is coded ---
3119
3120
45.0M
    int sub_block_is_coded = 0;
3121
3122
45.0M
    if ((i < lastSubBlock) && (i > 0)) {
3123
8.05M
      sub_block_is_coded = decode_coded_sub_block_flag(tctx, cIdx,
3124
8.05M
                                                       coded_sub_block_neighbors[S.x + S.y * sbWidth]);
3125
8.05M
      inferSbDcSigCoeffFlag = 1;
3126
8.05M
    }
3127
37.0M
    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
37.0M
      sub_block_is_coded = 1;
3133
37.0M
    }
3134
3135
45.0M
    if (sub_block_is_coded) {
3136
43.7M
      if (S.x > 0) coded_sub_block_neighbors[S.x - 1 + S.y * sbWidth] |= 1;
3137
43.7M
      if (S.y > 0) coded_sub_block_neighbors[S.x + (S.y - 1) * sbWidth] |= 2;
3138
43.7M
    }
3139
3140
3141
    // ----- find significant coefficients in this sub-block -----
3142
3143
45.0M
    int16_t coeff_value[16];
3144
45.0M
    int8_t coeff_scan_pos[16];
3145
45.0M
    int8_t coeff_sign[16];
3146
45.0M
    int8_t coeff_has_max_base_level[16];
3147
45.0M
    int nCoefficients = 0;
3148
3149
3150
45.0M
    if (sub_block_is_coded) {
3151
43.7M
      int x0 = S.x << 2;
3152
43.7M
      int y0 = S.y << 2;
3153
3154
43.7M
      int log2w = log2TrafoSize - 2;
3155
43.7M
      int prevCsbf = coded_sub_block_neighbors[S.x + S.y * sbWidth];
3156
43.7M
      uint8_t* ctxIdxMap = ctxIdxLookup[log2w][!!cIdx][!!scanIdx][prevCsbf];
3157
3158
43.7M
      logdebug(LogSlice, "log2w:%d cIdx:%d scanIdx:%d prevCsbf:%d\n",
3159
43.7M
               log2w, cIdx, scanIdx, prevCsbf);
3160
3161
3162
      // set the last coded coefficient in the last subblock
3163
3164
43.7M
      int last_coeff = (i == lastSubBlock) ? lastScanPos - 1 : 15;
3165
3166
43.7M
      if (i == lastSubBlock) {
3167
35.6M
        coeff_value[nCoefficients] = 1;
3168
35.6M
        coeff_has_max_base_level[nCoefficients] = 1;
3169
35.6M
        coeff_scan_pos[nCoefficients] = lastScanPos;
3170
35.6M
        nCoefficients++;
3171
35.6M
      }
3172
3173
3174
      // --- decode all coefficients' significant_coeff flags except for the DC coefficient ---
3175
3176
508M
      for (int n = last_coeff; n > 0; n--) {
3177
465M
        int subX = ScanOrderPos[n].x;
3178
465M
        int subY = ScanOrderPos[n].y;
3179
465M
        xC = x0 + subX;
3180
465M
        yC = y0 + subY;
3181
3182
3183
        // for all AC coefficients in sub-block, a significant_coeff flag is coded
3184
3185
465M
        int ctxInc;
3186
465M
        if (sps.range_extension.transform_skip_context_enabled_flag &&
3187
21.4M
            (tctx->cu_transquant_bypass_flag || tctx->transform_skip_flag[cIdx])) {
3188
787k
          ctxInc = (cIdx == 0) ? 42 : (16 + 27);
3189
787k
        }
3190
464M
        else {
3191
464M
          ctxInc = ctxIdxMap[xC + (yC << log2TrafoSize)];
3192
464M
        }
3193
3194
465M
        logtrace(LogSlice, "trafoSize: %d\n", 1 << log2TrafoSize);
3195
3196
465M
        int significant_coeff = decode_significant_coeff_flag_lookup(tctx, ctxInc);
3197
3198
465M
        if (significant_coeff) {
3199
366M
          coeff_value[nCoefficients] = 1;
3200
366M
          coeff_has_max_base_level[nCoefficients] = 1;
3201
366M
          coeff_scan_pos[nCoefficients] = n;
3202
366M
          nCoefficients++;
3203
3204
          // since we have a coefficient in the sub-block,
3205
          // we cannot infer the DC coefficient anymore
3206
366M
          inferSbDcSigCoeffFlag = 0;
3207
366M
        }
3208
465M
      }
3209
3210
3211
      // --- decode DC coefficient significance ---
3212
3213
43.7M
      if (last_coeff >= 0) // last coded coefficient (always set to 1) is not the DC coefficient
3214
41.7M
      {
3215
41.7M
        if (inferSbDcSigCoeffFlag == 0) {
3216
          // if we cannot infert the DC coefficient, it is coded
3217
3218
41.3M
          int ctxInc;
3219
41.3M
          if (sps.range_extension.transform_skip_context_enabled_flag &&
3220
1.69M
              (tctx->cu_transquant_bypass_flag || tctx->transform_skip_flag[cIdx])) {
3221
61.6k
            ctxInc = (cIdx == 0) ? 42 : (16 + 27);
3222
61.6k
          }
3223
41.2M
          else {
3224
41.2M
            ctxInc = ctxIdxMap[x0 + (y0 << log2TrafoSize)];
3225
41.2M
          }
3226
3227
41.3M
          int significant_coeff = decode_significant_coeff_flag_lookup(tctx, ctxInc);
3228
3229
3230
41.3M
          if (significant_coeff) {
3231
40.9M
            coeff_value[nCoefficients] = 1;
3232
40.9M
            coeff_has_max_base_level[nCoefficients] = 1;
3233
40.9M
            coeff_scan_pos[nCoefficients] = 0;
3234
40.9M
            nCoefficients++;
3235
40.9M
          }
3236
41.3M
        }
3237
425k
        else {
3238
          // we can infer that the DC coefficient must be present
3239
425k
          coeff_value[nCoefficients] = 1;
3240
425k
          coeff_has_max_base_level[nCoefficients] = 1;
3241
425k
          coeff_scan_pos[nCoefficients] = 0;
3242
425k
          nCoefficients++;
3243
425k
        }
3244
41.7M
      }
3245
43.7M
    }
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
45.0M
    if (nCoefficients) {
3261
43.6M
      int ctxSet;
3262
43.6M
      if (i == 0 || cIdx > 0) { ctxSet = 0; }
3263
8.02M
      else { ctxSet = 2; }
3264
3265
43.6M
      if (c1 == 0) { ctxSet++; }
3266
43.6M
      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
43.6M
      bool escapeDataPresent = false;
3273
3274
3275
      // --- decode greater-1 flags ---
3276
3277
43.6M
      int newLastGreater1ScanPos = -1;
3278
3279
43.6M
      int lastGreater1Coefficient = std::min(8, nCoefficients);
3280
3281
      // significant coefficients past the first eight carry no greater-1 flag and are escape coded
3282
43.6M
      if (nCoefficients > 8) {
3283
26.6M
        escapeDataPresent = true;
3284
26.6M
      }
3285
300M
      for (int c = 0; c < lastGreater1Coefficient; c++) {
3286
256M
        int greater1_flag =
3287
256M
            decode_coeff_abs_level_greater1(tctx, cIdx, i,
3288
256M
                                            c == 0,
3289
256M
                                            firstSubblock,
3290
256M
                                            lastSubblock_greater1Ctx,
3291
256M
                                            &lastInvocation_greater1Ctx,
3292
256M
                                            &lastInvocation_coeff_abs_level_greater1_flag,
3293
256M
                                            &lastInvocation_ctxSet, ctxSet);
3294
3295
256M
        if (greater1_flag) {
3296
52.6M
          coeff_value[c]++;
3297
3298
52.6M
          c1 = 0;
3299
3300
52.6M
          if (newLastGreater1ScanPos == -1) {
3301
7.48M
            newLastGreater1ScanPos = c;
3302
7.48M
          }
3303
45.1M
          else {
3304
45.1M
            escapeDataPresent = true;
3305
45.1M
          }
3306
52.6M
        }
3307
203M
        else {
3308
203M
          coeff_has_max_base_level[c] = 0;
3309
3310
203M
          if (c1 < 3 && c1 > 0) {
3311
72.1M
            c1++;
3312
72.1M
          }
3313
203M
        }
3314
256M
      }
3315
3316
43.6M
      firstSubblock = false;
3317
43.6M
      lastSubblock_greater1Ctx = lastInvocation_greater1Ctx;
3318
3319
3320
      // --- decode greater-2 flag ---
3321
3322
43.6M
      if (newLastGreater1ScanPos != -1) {
3323
7.49M
        int flag = decode_coeff_abs_level_greater2(tctx, cIdx, lastInvocation_ctxSet);
3324
7.49M
        coeff_value[newLastGreater1ScanPos] += flag;
3325
7.49M
        coeff_has_max_base_level[newLastGreater1ScanPos] = flag;
3326
3327
7.49M
        if (flag) {
3328
1.02M
          escapeDataPresent = true;
3329
1.02M
        }
3330
7.49M
      }
3331
3332
3333
      // --- decode coefficient signs ---
3334
3335
43.6M
      int signHidden;
3336
3337
3338
43.6M
      IntraPredMode predModeIntra;
3339
43.6M
      if (cIdx == 0) predModeIntra = img->get_IntraPredMode(x0, y0);
3340
11.1M
      else predModeIntra = img->get_IntraPredModeC(x0, y0);
3341
3342
3343
43.6M
      if (tctx->cu_transquant_bypass_flag ||
3344
37.5M
          (PredMode == MODE_INTRA &&
3345
36.4M
           sps.range_extension.implicit_rdpcm_enabled_flag &&
3346
3.32M
           tctx->transform_skip_flag[cIdx] &&
3347
19.9k
           (predModeIntra == 10 || predModeIntra == 26)) ||
3348
37.5M
          tctx->explicit_rdpcm_flag) {
3349
6.08M
        signHidden = 0;
3350
6.08M
      }
3351
37.5M
      else {
3352
37.5M
        signHidden = (coeff_scan_pos[0] - coeff_scan_pos[nCoefficients - 1] > 3);
3353
37.5M
      }
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
43.6M
      if (sps.range_extension.cabac_bypass_alignment_enabled_flag && escapeDataPresent) {
3361
66.9k
        tctx->cabac_decoder.align_bypass();
3362
66.9k
      }
3363
3364
447M
      for (int n = 0; n < nCoefficients - 1; n++) {
3365
403M
        coeff_sign[n] = tctx->cabac_decoder.decode_bypass();
3366
403M
        logtrace(LogSlice, "sign[%d] = %d\n", n, coeff_sign[n]);
3367
403M
      }
3368
3369
      // n==nCoefficients-1
3370
43.6M
      if (!pps.sign_data_hiding_flag || !signHidden) {
3371
42.6M
        coeff_sign[nCoefficients - 1] = tctx->cabac_decoder.decode_bypass();
3372
42.6M
        logtrace(LogSlice, "sign[%d] = %d\n", nCoefficients - 1, coeff_sign[nCoefficients - 1]);
3373
42.6M
      }
3374
978k
      else {
3375
978k
        coeff_sign[nCoefficients - 1] = 0;
3376
978k
      }
3377
3378
3379
      // --- decode coefficient value ---
3380
3381
43.6M
      int sumAbsLevel = 0;
3382
43.6M
      int uiGoRiceParam;
3383
3384
43.6M
      if (sps.range_extension.persistent_rice_adaptation_enabled_flag == 0) {
3385
41.9M
        uiGoRiceParam = 0;
3386
41.9M
      }
3387
1.69M
      else {
3388
1.69M
        uiGoRiceParam = tctx->StatCoeff[sbType] / 4;
3389
1.69M
      }
3390
3391
      // printf("initial uiGoRiceParam=%d\n",uiGoRiceParam);
3392
43.6M
      bool firstCoeffWithAbsLevelRemaining = true;
3393
3394
485M
      for (int n = 0; n < nCoefficients; n++) {
3395
441M
        int16_t baseLevel = coeff_value[n];
3396
3397
441M
        int32_t coeff_abs_level_remaining;
3398
3399
        // printf("coeff %d/%d, uiRiceParam: %d\n",n,nCoefficients,uiGoRiceParam);
3400
3401
441M
        if (coeff_has_max_base_level[n]) {
3402
235M
          coeff_abs_level_remaining =
3403
235M
              decode_coeff_abs_level_remaining(tctx, uiGoRiceParam);
3404
3405
235M
          if (sps.range_extension.persistent_rice_adaptation_enabled_flag == 0) {
3406
            // (2014.10 / 9-20)
3407
225M
            if (baseLevel + coeff_abs_level_remaining > 3 * (1 << uiGoRiceParam)) {
3408
261k
              uiGoRiceParam++;
3409
261k
              if (uiGoRiceParam > 4) uiGoRiceParam = 4;
3410
261k
            }
3411
225M
          }
3412
10.2M
          else {
3413
10.2M
            if (baseLevel + coeff_abs_level_remaining > 3 * (1 << uiGoRiceParam)) {
3414
28.6k
              uiGoRiceParam++;
3415
28.6k
              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
28.6k
            }
3420
10.2M
          }
3421
3422
          // persistent_rice_adaptation_enabled_flag
3423
235M
          if (sps.range_extension.persistent_rice_adaptation_enabled_flag &&
3424
10.0M
              firstCoeffWithAbsLevelRemaining) {
3425
1.26M
            if (coeff_abs_level_remaining >= (3 << (tctx->StatCoeff[sbType] / 4))) {
3426
5.01k
              if (tctx->StatCoeff[sbType] < MAX_STAT_COEFF) {
3427
5.01k
                tctx->StatCoeff[sbType]++;
3428
5.01k
              } else {
3429
0
                tctx->decctx->add_warning(DE265_WARNING_RICE_PARAMETER_OUT_OF_RANGE, true);
3430
0
              }
3431
5.01k
            }
3432
1.25M
            else if (2 * coeff_abs_level_remaining < (1 << (tctx->StatCoeff[sbType] / 4)) &&
3433
1.24M
                     tctx->StatCoeff[sbType] > 0) {
3434
3.90k
              tctx->StatCoeff[sbType]--;
3435
3.90k
            }
3436
1.26M
          }
3437
3438
235M
          firstCoeffWithAbsLevelRemaining = false;
3439
235M
        }
3440
206M
        else {
3441
206M
          coeff_abs_level_remaining = 0;
3442
206M
        }
3443
3444
441M
        logtrace(LogSlice, "coeff_abs_level_remaining=%d\n", coeff_abs_level_remaining);
3445
3446
3447
441M
        int32_t currCoeff = baseLevel + coeff_abs_level_remaining;
3448
441M
        if (coeff_sign[n]) {
3449
1.81M
          currCoeff = -currCoeff;
3450
1.81M
        }
3451
3452
441M
        if (pps.sign_data_hiding_flag && signHidden) {
3453
8.55M
          sumAbsLevel += currCoeff;
3454
3455
8.55M
          if (n == nCoefficients - 1 && (sumAbsLevel & 1)) {
3456
82.4k
            currCoeff = -currCoeff;
3457
82.4k
          }
3458
8.55M
        }
3459
3460
441M
        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
441M
        int p = coeff_scan_pos[n];
3468
441M
        xC = (S.x << 2) + ScanOrderPos[p].x;
3469
441M
        yC = (S.y << 2) + ScanOrderPos[p].y;
3470
3471
441M
        tctx->coeffList[cIdx][tctx->nCoeff[cIdx]] = Clip3(-32768, 32767, currCoeff);
3472
441M
        tctx->coeffPos[cIdx][tctx->nCoeff[cIdx]] = xC + yC * CoeffStride;
3473
441M
        tctx->nCoeff[cIdx]++;
3474
3475
        //printf("%d ",currCoeff);
3476
441M
      } // iterate through coefficients in sub-block
3477
3478
      //printf(" (%d;%d)\n",x0,y0);
3479
43.6M
    } // if nonZero
3480
45.0M
  } // next sub-block
3481
3482
35.6M
  return DE265_OK;
3483
35.6M
}
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
41.9M
{
3491
41.9M
  de265_image* img = tctx->img;
3492
41.9M
  const seq_parameter_set& sps = img->get_sps();
3493
3494
41.9M
  int residualDpcm = 0;
3495
3496
41.9M
  if (cuPredMode == MODE_INTRA) // if intra mode
3497
39.5M
  {
3498
39.5M
    enum IntraPredMode intraPredMode;
3499
3500
39.5M
    if (cIdx == 0) {
3501
24.3M
      intraPredMode = img->get_IntraPredMode(x0, y0);
3502
24.3M
    }
3503
15.2M
    else {
3504
15.2M
      const int SubWidthC = sps.SubWidthC;
3505
15.2M
      const int SubHeightC = sps.SubHeightC;
3506
3507
15.2M
      intraPredMode = img->get_IntraPredModeC(x0 * SubWidthC, y0 * SubHeightC);
3508
15.2M
    }
3509
3510
39.5M
    if (intraPredMode < 0 || intraPredMode >= 35) {
3511
      // TODO: ERROR
3512
0
      intraPredMode = INTRA_DC;
3513
0
    }
3514
3515
39.5M
    decode_intra_prediction(img, x0, y0, intraPredMode, nT, cIdx);
3516
3517
3518
39.5M
    residualDpcm = sps.range_extension.implicit_rdpcm_enabled_flag &&
3519
3.11M
                   (tctx->cu_transquant_bypass_flag || tctx->transform_skip_flag[cIdx]) &&
3520
63.9k
                   (intraPredMode == 10 || intraPredMode == 26);
3521
3522
39.5M
    if (residualDpcm && intraPredMode == 26)
3523
2.76k
      residualDpcm = 2;
3524
39.5M
  }
3525
2.35M
  else // INTER
3526
2.35M
  {
3527
2.35M
    if (tctx->explicit_rdpcm_flag) {
3528
15.2k
      residualDpcm = (tctx->explicit_rdpcm_dir ? 2 : 1);
3529
15.2k
    }
3530
2.35M
  }
3531
3532
41.9M
  if (cbf) {
3533
35.5M
    scale_coefficients(tctx, x0, y0, xCUBase, yCUBase, nT, cIdx,
3534
35.5M
                       tctx->transform_skip_flag[cIdx], cuPredMode == MODE_INTRA, residualDpcm);
3535
35.5M
  }
3536
  /*
3537
  else if (!cbf && cIdx==0) {
3538
    memset(tctx->residual_luma,0,32*32*sizeof(int32_t));
3539
  }
3540
  */
3541
6.35M
  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
41.9M
}
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
25.4M
{
3619
25.4M
  logtrace(LogSlice, "- read_transform_unit x0:%d y0:%d xBase:%d yBase:%d nT:%d cbf:%d:%d:%d\n",
3620
25.4M
           x0, y0, xBase, yBase, 1 << log2TrafoSize, cbf_luma, cbf_cb, cbf_cr);
3621
3622
25.4M
  assert(cbf_cb != -1);
3623
25.4M
  assert(cbf_cr != -1);
3624
25.4M
  assert(cbf_luma != -1);
3625
3626
25.4M
  const seq_parameter_set& sps = tctx->img->get_sps();
3627
3628
25.4M
  const int ChromaArrayType = sps.ChromaArrayType;
3629
3630
25.4M
  int log2TrafoSizeC = (ChromaArrayType == CHROMA_444 ? log2TrafoSize : log2TrafoSize - 1);
3631
25.4M
  log2TrafoSizeC = std::max(2, log2TrafoSizeC);
3632
3633
25.4M
  const int cbfLuma = cbf_luma;
3634
25.4M
  const int cbfChroma = cbf_cb | cbf_cr;
3635
3636
25.4M
  tctx->transform_skip_flag[0] = 0;
3637
25.4M
  tctx->transform_skip_flag[1] = 0;
3638
25.4M
  tctx->transform_skip_flag[2] = 0;
3639
3640
25.4M
  tctx->explicit_rdpcm_flag = false;
3641
3642
3643
25.4M
  enum PredMode cuPredMode = tctx->img->get_pred_mode(x0, y0);
3644
3645
25.4M
  if (cbfLuma || cbfChroma) {
3646
24.5M
    bool doDecodeQuantParameters = false;
3647
3648
24.5M
    if (tctx->img->get_pps().cu_qp_delta_enabled_flag &&
3649
24.5M
        !tctx->IsCuQpDeltaCoded) {
3650
6.11M
      uint8_t cu_qp_delta_abs = decode_cu_qp_delta_abs(tctx);
3651
6.11M
      if (cu_qp_delta_abs == CABAC_QP_DELTA_ABS_ERROR) {
3652
170
        tctx->decctx->add_warning(DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE, false);
3653
170
        return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
3654
170
      }
3655
3656
6.11M
      int cu_qp_delta_sign = 0;
3657
6.11M
      if (cu_qp_delta_abs) {
3658
5.09M
        cu_qp_delta_sign = tctx->cabac_decoder.decode_bypass();
3659
5.09M
      }
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
6.11M
      int maxCuQpDeltaAbs = (cu_qp_delta_sign ? 26 : 25) + tctx->img->get_sps().QpBdOffset_Y / 2;
3664
6.11M
      if (cu_qp_delta_abs > maxCuQpDeltaAbs) {
3665
1.92k
        tctx->decctx->add_warning(DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE, false);
3666
1.92k
        return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE;
3667
1.92k
      }
3668
3669
6.11M
      tctx->IsCuQpDeltaCoded = 1;
3670
6.11M
      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
6.11M
      logtrace(LogSlice, "cu_qp_delta_abs = %d\n", cu_qp_delta_abs);
3675
6.11M
      logtrace(LogSlice, "cu_qp_delta_sign = %d\n", cu_qp_delta_sign);
3676
6.11M
      logtrace(LogSlice, "CuQpDelta = %d\n", tctx->CuQpDelta);
3677
3678
6.11M
      doDecodeQuantParameters = true;
3679
      //decode_quantization_parameters(tctx, x0,y0, xCUBase, yCUBase);
3680
6.11M
    }
3681
3682
24.5M
    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
24.5M
    if (doDecodeQuantParameters) {
3715
6.11M
      decode_quantization_parameters(tctx, x0, y0, xCUBase, yCUBase);
3716
6.11M
    }
3717
24.5M
  }
3718
3719
  // position of TU in local CU
3720
  //int xL = x0 - xCUBase;
3721
  //int yL = y0 - yCUBase;
3722
25.4M
  int nT = 1 << log2TrafoSize;
3723
25.4M
  int nTC = 1 << log2TrafoSizeC;
3724
3725
25.4M
  const int SubWidthC = sps.SubWidthC;
3726
25.4M
  const int SubHeightC = sps.SubHeightC;
3727
3728
  // --- luma ---
3729
3730
25.4M
  tctx->ResScaleVal = 0;
3731
3732
25.4M
  int err;
3733
25.4M
  if (cbf_luma) {
3734
24.4M
    if ((err = residual_coding(tctx, x0, y0, log2TrafoSize, 0)) != DE265_OK) return err;
3735
24.4M
  }
3736
3737
25.4M
  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
25.4M
  if (log2TrafoSize > 2 || ChromaArrayType == CHROMA_444) {
3745
    // TODO: cross-component prediction
3746
3747
1.87M
    const bool do_cross_component_prediction =
3748
1.87M
    (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
1.87M
    if (do_cross_component_prediction) {
3753
0
      read_cross_comp_pred(tctx, 0);
3754
0
    }
3755
1.87M
    else {
3756
1.87M
      tctx->ResScaleVal = 0;
3757
1.87M
    } {
3758
1.87M
      if (cbf_cb & 1) {
3759
869k
        if ((err = residual_coding(tctx, x0, y0, log2TrafoSizeC, 1)) != DE265_OK) return err;
3760
869k
      }
3761
3762
1.87M
      if (sps.ChromaArrayType != CHROMA_MONO) {
3763
1.87M
        decode_TU(tctx,
3764
1.87M
                  x0 / SubWidthC, y0 / SubHeightC,
3765
1.87M
                  xCUBase / SubWidthC, yCUBase / SubHeightC, nTC, 1, cuPredMode, cbf_cb & 1);
3766
1.87M
      }
3767
1.87M
    }
3768
3769
    // 4:2:2
3770
1.87M
    if (ChromaArrayType == CHROMA_422) {
3771
262k
      const int yOffset = 1 << log2TrafoSizeC;
3772
3773
262k
      if (cbf_cb & 2) {
3774
62.6k
        if ((err = residual_coding(tctx,
3775
62.6k
                                   x0, y0 + yOffset * SubHeightC,
3776
62.6k
                                   log2TrafoSizeC, 1)) != DE265_OK)
3777
0
          return err;
3778
62.6k
      }
3779
3780
262k
      decode_TU(tctx,
3781
262k
                x0 / SubWidthC, y0 / SubHeightC + yOffset,
3782
262k
                xCUBase / SubWidthC, yCUBase / SubHeightC + yOffset,
3783
262k
                nTC, 1, cuPredMode, cbf_cb & 2);
3784
262k
    }
3785
3786
3787
1.87M
    if (do_cross_component_prediction) {
3788
0
      read_cross_comp_pred(tctx, 1);
3789
0
    }
3790
1.87M
    else {
3791
1.87M
      tctx->ResScaleVal = 0;
3792
1.87M
    } {
3793
1.87M
      if (cbf_cr & 1) {
3794
868k
        if ((err = residual_coding(tctx, x0, y0, log2TrafoSizeC, 2)) != DE265_OK) return err;
3795
868k
      }
3796
3797
1.87M
      if (sps.ChromaArrayType != CHROMA_MONO) {
3798
1.87M
        decode_TU(tctx,
3799
1.87M
                  x0 / SubWidthC, y0 / SubHeightC,
3800
1.87M
                  xCUBase / SubWidthC, yCUBase / SubHeightC,
3801
1.87M
                  nTC, 2, cuPredMode, cbf_cr & 1);
3802
1.87M
      }
3803
1.87M
    }
3804
3805
    // 4:2:2
3806
1.87M
    if (ChromaArrayType == CHROMA_422) {
3807
262k
      const int yOffset = 1 << log2TrafoSizeC;
3808
3809
262k
      if (cbf_cr & 2) {
3810
62.8k
        if ((err = residual_coding(tctx,
3811
62.8k
                                   x0, y0 + yOffset * SubHeightC,
3812
62.8k
                                   log2TrafoSizeC, 2)) != DE265_OK)
3813
0
          return err;
3814
62.8k
      }
3815
3816
262k
      decode_TU(tctx,
3817
262k
                x0 / SubWidthC, y0 / SubHeightC + yOffset,
3818
262k
                xCUBase / SubWidthC, yCUBase / SubHeightC + yOffset,
3819
262k
                nTC, 2, cuPredMode, cbf_cr & 2);
3820
262k
    }
3821
1.87M
  }
3822
23.5M
  else if (blkIdx == 3) {
3823
5.90M
    if (cbf_cb & 1) {
3824
4.49M
      if ((err = residual_coding(tctx, xBase, yBase,
3825
4.49M
                                 log2TrafoSize, 1)) != DE265_OK)
3826
0
        return err;
3827
4.49M
    }
3828
3829
5.91M
    if (sps.ChromaArrayType != CHROMA_MONO) {
3830
5.91M
      decode_TU(tctx,
3831
5.91M
                xBase / SubWidthC, yBase / SubHeightC,
3832
5.91M
                xCUBase / SubWidthC, yCUBase / SubHeightC, nT, 1, cuPredMode, cbf_cb & 1);
3833
5.91M
    }
3834
3835
    // 4:2:2
3836
5.90M
    if (cbf_cb & 2) {
3837
154k
      if ((err = residual_coding(tctx,
3838
154k
                                 xBase, yBase + (1 << log2TrafoSize),
3839
154k
                                 log2TrafoSize, 1)) != DE265_OK)
3840
0
        return err;
3841
154k
    }
3842
3843
5.90M
    if (ChromaArrayType == CHROMA_422) {
3844
213k
      decode_TU(tctx,
3845
213k
                xBase / SubWidthC, yBase / SubHeightC + (1 << log2TrafoSize),
3846
213k
                xCUBase / SubWidthC, yCUBase / SubHeightC, nT, 1, cuPredMode, cbf_cb & 2);
3847
213k
    }
3848
3849
5.90M
    if (cbf_cr & 1) {
3850
4.49M
      if ((err = residual_coding(tctx, xBase, yBase,
3851
4.49M
                                 log2TrafoSize, 2)) != DE265_OK)
3852
0
        return err;
3853
4.49M
    }
3854
3855
5.91M
    if (sps.ChromaArrayType != CHROMA_MONO) {
3856
5.91M
      decode_TU(tctx,
3857
5.91M
                xBase / SubWidthC, yBase / SubHeightC,
3858
5.91M
                xCUBase / SubWidthC, yCUBase / SubHeightC, nT, 2, cuPredMode, cbf_cr & 1);
3859
5.91M
    }
3860
3861
    // 4:2:2
3862
5.90M
    if (cbf_cr & 2) {
3863
154k
      if ((err = residual_coding(tctx,
3864
154k
                                 xBase, yBase + (1 << log2TrafoSizeC),
3865
154k
                                 log2TrafoSize, 2)) != DE265_OK)
3866
0
        return err;
3867
154k
    }
3868
3869
5.90M
    if (ChromaArrayType == CHROMA_422) {
3870
213k
      decode_TU(tctx,
3871
213k
                xBase / SubWidthC, yBase / SubHeightC + (1 << log2TrafoSize),
3872
213k
                xCUBase / SubWidthC, yCUBase / SubHeightC, nT, 2, cuPredMode, cbf_cr & 2);
3873
213k
    }
3874
5.90M
  }
3875
3876
3877
25.4M
  return DE265_OK;
3878
25.4M
}
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
31.4M
{
3909
31.4M
  logtrace(LogSlice, "- read_transform_tree (interleaved) x0:%d y0:%d xBase:%d yBase:%d "
3910
31.4M
           "log2TrafoSize:%d trafoDepth:%d MaxTrafoDepth:%d parent-cbf-cb:%d parent-cbf-cr:%d\n",
3911
31.4M
           x0, y0, xBase, yBase, log2TrafoSize, trafoDepth, MaxTrafoDepth, parent_cbf_cb, parent_cbf_cr);
3912
3913
31.4M
  de265_image* img = tctx->img;
3914
31.4M
  const seq_parameter_set& sps = img->get_sps();
3915
3916
31.4M
  int split_transform_flag;
3917
3918
31.4M
  enum PredMode PredMode = img->get_pred_mode(x0, y0);
3919
31.4M
  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
31.4M
  if (log2TrafoSize <= sps.Log2MaxTrafoSize &&
3928
31.2M
      log2TrafoSize > sps.Log2MinTrafoSize &&
3929
6.94M
      trafoDepth < MaxTrafoDepth &&
3930
6.08M
      !(IntraSplitFlag && trafoDepth == 0)) {
3931
378k
    split_transform_flag = decode_split_transform_flag(tctx, log2TrafoSize);
3932
378k
  }
3933
31.0M
  else {
3934
31.0M
    enum PartMode PartMode = img->get_PartMode(x0, y0);
3935
3936
31.0M
    int interSplitFlag = (sps.max_transform_hierarchy_depth_inter == 0 &&
3937
2.58M
                          trafoDepth == 0 &&
3938
1.05M
                          PredMode == MODE_INTER &&
3939
251k
                          PartMode != PART_2Nx2N);
3940
3941
31.0M
    split_transform_flag = (log2TrafoSize > sps.Log2MaxTrafoSize ||
3942
30.9M
                            (IntraSplitFlag == 1 && trafoDepth == 0) ||
3943
24.5M
                            interSplitFlag == 1)
3944
31.0M
                             ? 1
3945
31.0M
                             : 0;
3946
31.0M
  }
3947
3948
31.4M
  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
637k
    img->decctx->add_warning(DE265_WARNING_INVALID_TU_BLOCK_SPLIT, true);
3954
637k
    split_transform_flag = 0;
3955
637k
  }
3956
3957
31.4M
  if (split_transform_flag) {
3958
5.98M
    logtrace(LogSlice, "set_split_transform_flag(%d,%d, %d)\n", x0, y0, trafoDepth);
3959
5.98M
    img->set_split_transform_flag(x0, y0, trafoDepth);
3960
5.98M
  }
3961
3962
31.4M
  int cbf_cb = -1;
3963
31.4M
  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
31.4M
  if ((log2TrafoSize > 2 && sps.ChromaArrayType != CHROMA_MONO) ||
3970
23.5M
      sps.ChromaArrayType == CHROMA_444) {
3971
    // we do not have to test for trafoDepth==0, because parent_cbf_cb is 1 at depth 0
3972
7.86M
    if (/*trafoDepth==0 ||*/ parent_cbf_cb) {
3973
7.57M
      cbf_cb = decode_cbf_chroma(tctx, trafoDepth);
3974
3975
7.57M
      if (sps.ChromaArrayType == CHROMA_422 && (!split_transform_flag || log2TrafoSize == 3)) {
3976
449k
        cbf_cb |= (decode_cbf_chroma(tctx, trafoDepth) << 1);
3977
449k
      }
3978
7.57M
    }
3979
3980
    // we do not have to test for trafoDepth==0, because parent_cbf_cb is 1 at depth 0
3981
7.86M
    if (/*trafoDepth==0 ||*/ parent_cbf_cr) {
3982
7.57M
      cbf_cr = decode_cbf_chroma(tctx, trafoDepth);
3983
3984
7.57M
      if (sps.ChromaArrayType == CHROMA_422 && (!split_transform_flag || log2TrafoSize == 3)) {
3985
449k
        cbf_cr |= (decode_cbf_chroma(tctx, trafoDepth) << 1);
3986
449k
      }
3987
7.57M
    }
3988
7.86M
  }
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
31.4M
  if (cbf_cb < 0) {
3995
23.8M
    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
23.8M
    if (trafoDepth > 0 && log2TrafoSize == 2) {
4003
23.5M
      cbf_cb = parent_cbf_cb;
4004
23.5M
    }
4005
284k
    else {
4006
284k
      cbf_cb = 0;
4007
284k
    }
4008
23.8M
  }
4009
4010
31.4M
  if (cbf_cr < 0) {
4011
23.8M
    if (trafoDepth > 0 && log2TrafoSize == 2) {
4012
23.5M
      cbf_cr = parent_cbf_cr;
4013
23.5M
    }
4014
283k
    else {
4015
283k
      cbf_cr = 0;
4016
283k
    }
4017
23.8M
  }
4018
4019
31.4M
  if (split_transform_flag) {
4020
5.98M
    int x1 = x0 + (1 << (log2TrafoSize - 1));
4021
5.98M
    int y1 = y0 + (1 << (log2TrafoSize - 1));
4022
4023
5.98M
    logtrace(LogSlice, "transform split.\n");
4024
4025
5.98M
    read_transform_tree(tctx, x0, y0, x0, y0, xCUBase, yCUBase, log2TrafoSize - 1, trafoDepth + 1, 0,
4026
5.98M
                        MaxTrafoDepth, IntraSplitFlag, cuPredMode, cbf_cb, cbf_cr);
4027
5.98M
    read_transform_tree(tctx, x1, y0, x0, y0, xCUBase, yCUBase, log2TrafoSize - 1, trafoDepth + 1, 1,
4028
5.98M
                        MaxTrafoDepth, IntraSplitFlag, cuPredMode, cbf_cb, cbf_cr);
4029
5.98M
    read_transform_tree(tctx, x0, y1, x0, y0, xCUBase, yCUBase, log2TrafoSize - 1, trafoDepth + 1, 2,
4030
5.98M
                        MaxTrafoDepth, IntraSplitFlag, cuPredMode, cbf_cb, cbf_cr);
4031
5.98M
    read_transform_tree(tctx, x1, y1, x0, y0, xCUBase, yCUBase, log2TrafoSize - 1, trafoDepth + 1, 3,
4032
5.98M
                        MaxTrafoDepth, IntraSplitFlag, cuPredMode, cbf_cb, cbf_cr);
4033
5.98M
  }
4034
25.4M
  else {
4035
25.4M
    int cbf_luma;
4036
4037
25.4M
    if (PredMode == MODE_INTRA || trafoDepth != 0 || cbf_cb || cbf_cr) {
4038
25.2M
      cbf_luma = decode_cbf_luma(tctx, trafoDepth);
4039
25.2M
    }
4040
190k
    else {
4041
      /* There cannot be INTER blocks with no residual data.
4042
         That case is already handled with rqt_root_cbf.
4043
      */
4044
4045
190k
      cbf_luma = 1;
4046
190k
    }
4047
4048
25.4M
    logtrace(LogSlice, "call read_transform_unit %d/%d\n", x0, y0);
4049
4050
25.4M
    read_transform_unit(tctx, x0, y0, xBase, yBase, xCUBase, yCUBase, log2TrafoSize, trafoDepth, blkIdx,
4051
25.4M
                        cbf_luma, cbf_cb, cbf_cr);
4052
25.4M
  }
4053
31.4M
}
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
524k
{
4076
524k
  int abs_mvd_greater0_flag[2];
4077
524k
  abs_mvd_greater0_flag[0] = tctx->cabac_decoder.decode_bit(
4078
524k
                                              &tctx->ctx_model[CONTEXT_MODEL_ABS_MVD_GREATER01_FLAG + 0]);
4079
524k
  abs_mvd_greater0_flag[1] = tctx->cabac_decoder.decode_bit(
4080
524k
                                              &tctx->ctx_model[CONTEXT_MODEL_ABS_MVD_GREATER01_FLAG + 0]);
4081
4082
524k
  int abs_mvd_greater1_flag[2];
4083
524k
  if (abs_mvd_greater0_flag[0]) {
4084
402k
    abs_mvd_greater1_flag[0] = tctx->cabac_decoder.decode_bit(
4085
402k
                                                &tctx->ctx_model[CONTEXT_MODEL_ABS_MVD_GREATER01_FLAG + 1]);
4086
402k
  }
4087
121k
  else {
4088
121k
    abs_mvd_greater1_flag[0] = 0;
4089
121k
  }
4090
4091
524k
  if (abs_mvd_greater0_flag[1]) {
4092
403k
    abs_mvd_greater1_flag[1] = tctx->cabac_decoder.decode_bit(
4093
403k
                                                &tctx->ctx_model[CONTEXT_MODEL_ABS_MVD_GREATER01_FLAG + 1]);
4094
403k
  }
4095
121k
  else {
4096
121k
    abs_mvd_greater1_flag[1] = 0;
4097
121k
  }
4098
4099
4100
524k
  int mvd_sign_flag[2];
4101
524k
  int16_t value[2];
4102
4103
1.57M
  for (int c = 0; c < 2; c++) {
4104
1.04M
    if (abs_mvd_greater0_flag[c]) {
4105
805k
      int32_t absMvd;
4106
805k
      if (abs_mvd_greater1_flag[c]) {
4107
147k
        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
147k
        absMvd = static_cast<int32_t>(std::min(abs_mvd_minus2, uint32_t{32768 - 2})) + 2;
4110
147k
      }
4111
658k
      else {
4112
658k
        absMvd = 1;
4113
658k
      }
4114
4115
805k
      mvd_sign_flag[c] = tctx->cabac_decoder.decode_bypass();
4116
805k
      int32_t mvd = mvd_sign_flag[c] ? -absMvd : absMvd;
4117
805k
      value[c] = Clip3(-32768, 32767, mvd);
4118
805k
    }
4119
243k
    else {
4120
243k
      value[c] = 0;
4121
243k
    }
4122
1.04M
  }
4123
4124
524k
  tctx->motion.mvd[refList][0] = value[0];
4125
524k
  tctx->motion.mvd[refList][1] = value[1];
4126
4127
524k
  logtrace(LogSlice, "MVD[%d;%d|%d] = %d;%d\n", x0, y0, refList, value[0], value[1]);
4128
524k
}
4129
4130
4131
void read_prediction_unit_SKIP(thread_context* tctx,
4132
                               int x0, int y0,
4133
                               int nPbW, int nPbH)
4134
1.22M
{
4135
1.22M
  int merge_idx = decode_merge_idx(tctx);
4136
4137
1.22M
  tctx->motion.merge_idx = merge_idx;
4138
1.22M
  tctx->motion.merge_flag = true;
4139
4140
1.22M
  logtrace(LogSlice, "prediction skip 2Nx2N, merge_idx: %d\n", merge_idx);
4141
1.22M
}
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
890k
{
4154
890k
  logtrace(LogSlice, "read_prediction_unit %d;%d %dx%d\n", xC + xB, yC + xB, nPbW, nPbH);
4155
4156
890k
  int x0 = xC + xB;
4157
890k
  int y0 = yC + yB;
4158
4159
890k
  slice_segment_header* shdr = tctx->shdr;
4160
4161
890k
  int merge_flag = decode_merge_flag(tctx);
4162
890k
  tctx->motion.merge_flag = merge_flag;
4163
4164
890k
  if (merge_flag) {
4165
403k
    int merge_idx = decode_merge_idx(tctx);
4166
4167
403k
    logtrace(LogSlice, "prediction unit %d,%d, merge mode, index: %d\n", x0, y0, merge_idx);
4168
4169
403k
    tctx->motion.merge_idx = merge_idx;
4170
403k
  }
4171
486k
  else {
4172
    // no merge flag
4173
486k
    enum InterPredIdc inter_pred_idc;
4174
4175
486k
    if (shdr->slice_type == SLICE_TYPE_B) {
4176
399k
      inter_pred_idc = decode_inter_pred_idc(tctx, x0, y0, nPbW, nPbH, ctDepth);
4177
399k
    }
4178
87.5k
    else {
4179
87.5k
      inter_pred_idc = PRED_L0;
4180
87.5k
    }
4181
4182
486k
    tctx->motion.inter_pred_idc = inter_pred_idc; // set_inter_pred_idc(ctx,x0,y0, inter_pred_idc);
4183
4184
486k
    if (inter_pred_idc != PRED_L1) {
4185
451k
      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
451k
      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
451k
      tctx->motion.refIdx[0] = ref_idx_l0;
4194
4195
451k
      read_mvd_coding(tctx, x0, y0, 0);
4196
4197
451k
      int mvp_l0_flag = decode_mvp_lx_flag(tctx); // l0
4198
451k
      tctx->motion.mvp_l0_flag = mvp_l0_flag;
4199
4200
451k
      logtrace(LogSlice, "prediction unit %d,%d, L0, refIdx=%d mvp_l0_flag:%d\n",
4201
451k
               x0, y0, tctx->motion.refIdx[0], mvp_l0_flag);
4202
451k
    }
4203
4204
486k
    if (inter_pred_idc != PRED_L0) {
4205
124k
      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
124k
      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
124k
      tctx->motion.refIdx[1] = ref_idx_l1;
4214
4215
124k
      if (shdr->mvd_l1_zero_flag &&
4216
80.5k
          inter_pred_idc == PRED_BI) {
4217
51.8k
        tctx->motion.mvd[1][0] = 0;
4218
51.8k
        tctx->motion.mvd[1][1] = 0;
4219
51.8k
      }
4220
72.9k
      else {
4221
72.9k
        read_mvd_coding(tctx, x0, y0, 1);
4222
72.9k
      }
4223
4224
124k
      int mvp_l1_flag = decode_mvp_lx_flag(tctx); // l1
4225
124k
      tctx->motion.mvp_l1_flag = mvp_l1_flag;
4226
4227
124k
      logtrace(LogSlice, "prediction unit %d,%d, L1, refIdx=%d mvp_l1_flag:%d\n",
4228
124k
               x0, y0, tctx->motion.refIdx[1], mvp_l1_flag);
4229
124k
    }
4230
486k
  }
4231
4232
4233
890k
  decode_prediction_unit(tctx->decctx, tctx->shdr, tctx->img, tctx->motion,
4234
890k
                         xC, yC, xB, yB, nCS, nPbW, nPbH, partIdx);
4235
890k
}
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
2.22k
{
4242
2.22k
  const seq_parameter_set& sps = tctx->img->get_sps();
4243
4244
2.22k
  int nPcmBits;
4245
2.22k
  int bitDepth;
4246
4247
2.22k
  int w = 1 << log2CbSize;
4248
2.22k
  int h = 1 << log2CbSize;
4249
4250
2.22k
  if (cIdx > 0) {
4251
1.48k
    w /= sps.SubWidthC;
4252
1.48k
    h /= sps.SubHeightC;
4253
4254
1.48k
    x0 /= sps.SubWidthC;
4255
1.48k
    y0 /= sps.SubHeightC;
4256
4257
1.48k
    nPcmBits = sps.pcm_sample_bit_depth_chroma;
4258
1.48k
    bitDepth = sps.BitDepth_C;
4259
1.48k
  }
4260
743
  else {
4261
743
    nPcmBits = sps.pcm_sample_bit_depth_luma;
4262
743
    bitDepth = sps.BitDepth_Y;
4263
743
  }
4264
4265
2.22k
  pixel_t* ptr;
4266
2.22k
  int stride;
4267
2.22k
  ptr = tctx->img->get_image_plane_at_pos_NEW<pixel_t>(cIdx, x0, y0);
4268
2.22k
  stride = tctx->img->get_image_stride(cIdx);
4269
4270
2.22k
  int shift = bitDepth - nPcmBits;
4271
4272
  // a shift < 0 may result when the SPS sequence header is broken
4273
2.22k
  if (shift < 0) {
4274
0
    shift = 0;
4275
0
  }
4276
4277
17.0k
  for (int y = 0; y < h; y++)
4278
162k
    for (int x = 0; x < w; x++) {
4279
148k
      int value = br.get_bits(nPcmBits);
4280
148k
      ptr[y * stride + x] = value << shift;
4281
148k
    }
4282
2.22k
}
void read_pcm_samples_internal<unsigned short>(thread_context*, int, int, int, int, bitreader&)
Line
Count
Source
4241
1.13k
{
4242
1.13k
  const seq_parameter_set& sps = tctx->img->get_sps();
4243
4244
1.13k
  int nPcmBits;
4245
1.13k
  int bitDepth;
4246
4247
1.13k
  int w = 1 << log2CbSize;
4248
1.13k
  int h = 1 << log2CbSize;
4249
4250
1.13k
  if (cIdx > 0) {
4251
566
    w /= sps.SubWidthC;
4252
566
    h /= sps.SubHeightC;
4253
4254
566
    x0 /= sps.SubWidthC;
4255
566
    y0 /= sps.SubHeightC;
4256
4257
566
    nPcmBits = sps.pcm_sample_bit_depth_chroma;
4258
566
    bitDepth = sps.BitDepth_C;
4259
566
  }
4260
569
  else {
4261
569
    nPcmBits = sps.pcm_sample_bit_depth_luma;
4262
569
    bitDepth = sps.BitDepth_Y;
4263
569
  }
4264
4265
1.13k
  pixel_t* ptr;
4266
1.13k
  int stride;
4267
1.13k
  ptr = tctx->img->get_image_plane_at_pos_NEW<pixel_t>(cIdx, x0, y0);
4268
1.13k
  stride = tctx->img->get_image_stride(cIdx);
4269
4270
1.13k
  int shift = bitDepth - nPcmBits;
4271
4272
  // a shift < 0 may result when the SPS sequence header is broken
4273
1.13k
  if (shift < 0) {
4274
0
    shift = 0;
4275
0
  }
4276
4277
8.94k
  for (int y = 0; y < h; y++)
4278
79.4k
    for (int x = 0; x < w; x++) {
4279
71.6k
      int value = br.get_bits(nPcmBits);
4280
71.6k
      ptr[y * stride + x] = value << shift;
4281
71.6k
    }
4282
1.13k
}
void read_pcm_samples_internal<unsigned char>(thread_context*, int, int, int, int, bitreader&)
Line
Count
Source
4241
1.09k
{
4242
1.09k
  const seq_parameter_set& sps = tctx->img->get_sps();
4243
4244
1.09k
  int nPcmBits;
4245
1.09k
  int bitDepth;
4246
4247
1.09k
  int w = 1 << log2CbSize;
4248
1.09k
  int h = 1 << log2CbSize;
4249
4250
1.09k
  if (cIdx > 0) {
4251
920
    w /= sps.SubWidthC;
4252
920
    h /= sps.SubHeightC;
4253
4254
920
    x0 /= sps.SubWidthC;
4255
920
    y0 /= sps.SubHeightC;
4256
4257
920
    nPcmBits = sps.pcm_sample_bit_depth_chroma;
4258
920
    bitDepth = sps.BitDepth_C;
4259
920
  }
4260
174
  else {
4261
174
    nPcmBits = sps.pcm_sample_bit_depth_luma;
4262
174
    bitDepth = sps.BitDepth_Y;
4263
174
  }
4264
4265
1.09k
  pixel_t* ptr;
4266
1.09k
  int stride;
4267
1.09k
  ptr = tctx->img->get_image_plane_at_pos_NEW<pixel_t>(cIdx, x0, y0);
4268
1.09k
  stride = tctx->img->get_image_stride(cIdx);
4269
4270
1.09k
  int shift = bitDepth - nPcmBits;
4271
4272
  // a shift < 0 may result when the SPS sequence header is broken
4273
1.09k
  if (shift < 0) {
4274
0
    shift = 0;
4275
0
  }
4276
4277
8.11k
  for (int y = 0; y < h; y++)
4278
83.3k
    for (int x = 0; x < w; x++) {
4279
76.3k
      int value = br.get_bits(nPcmBits);
4280
76.3k
      ptr[y * stride + x] = value << shift;
4281
76.3k
    }
4282
1.09k
}
4283
4284
static void read_pcm_samples(thread_context* tctx, int x0, int y0, int log2CbSize)
4285
743
{
4286
743
  bitreader br(tctx->cabac_decoder.bitstream_curr,
4287
743
               tctx->cabac_decoder.bitstream_end - tctx->cabac_decoder.bitstream_curr);
4288
4289
743
  if (tctx->img->high_bit_depth(0)) {
4290
569
    read_pcm_samples_internal<uint16_t>(tctx, x0, y0, log2CbSize, 0, br);
4291
569
  }
4292
174
  else {
4293
174
    read_pcm_samples_internal<uint8_t>(tctx, x0, y0, log2CbSize, 0, br);
4294
174
  }
4295
4296
743
  if (tctx->img->get_sps().ChromaArrayType != CHROMA_MONO) {
4297
743
    if (tctx->img->high_bit_depth(1)) {
4298
283
      read_pcm_samples_internal<uint16_t>(tctx, x0, y0, log2CbSize, 1, br);
4299
283
      read_pcm_samples_internal<uint16_t>(tctx, x0, y0, log2CbSize, 2, br);
4300
283
    }
4301
460
    else {
4302
460
      read_pcm_samples_internal<uint8_t>(tctx, x0, y0, log2CbSize, 1, br);
4303
460
      read_pcm_samples_internal<uint8_t>(tctx, x0, y0, log2CbSize, 2, br);
4304
460
    }
4305
743
  }
4306
4307
743
  br.prepare_for_CABAC();
4308
743
  tctx->cabac_decoder.bitstream_curr = br.data;
4309
743
  tctx->cabac_decoder.init_CABAC();
4310
743
}
4311
4312
4313
int map_chroma_pred_mode(int intra_chroma_pred_mode, int IntraPredMode)
4314
7.14M
{
4315
7.14M
  if (intra_chroma_pred_mode == 4) {
4316
1.81M
    return IntraPredMode;
4317
1.81M
  }
4318
5.33M
  else {
4319
5.33M
    static const enum IntraPredMode IntraPredModeCCand[4] = {
4320
5.33M
      INTRA_PLANAR,
4321
5.33M
      INTRA_ANGULAR_26, // vertical
4322
5.33M
      INTRA_ANGULAR_10, // horizontal
4323
5.33M
      INTRA_DC
4324
5.33M
    };
4325
4326
5.33M
    int IntraPredModeC = IntraPredModeCCand[intra_chroma_pred_mode];
4327
5.33M
    if (IntraPredModeC == IntraPredMode) {
4328
1.39M
      return INTRA_ANGULAR_34;
4329
1.39M
    }
4330
3.93M
    else {
4331
3.93M
      return IntraPredModeC;
4332
3.93M
    }
4333
5.33M
  }
4334
7.14M
}
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
8.98M
{
4347
8.98M
  de265_image* img = tctx->img;
4348
8.98M
  const seq_parameter_set& sps = img->get_sps();
4349
8.98M
  const pic_parameter_set& pps = img->get_pps();
4350
8.98M
  slice_segment_header* shdr = tctx->shdr;
4351
4352
8.98M
  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
8.98M
  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
8.98M
  img->clear_split_transform_flags(x0, y0, log2CbSize);
4364
4365
8.98M
  int nCbS = 1 << log2CbSize; // number of coding block samples
4366
4367
8.98M
  decode_quantization_parameters(tctx, x0, y0, x0, y0);
4368
4369
4370
8.98M
  if (pps.transquant_bypass_enable_flag) {
4371
2.82M
    int transquant_bypass = decode_transquant_bypass_flag(tctx);
4372
4373
2.82M
    tctx->cu_transquant_bypass_flag = transquant_bypass;
4374
4375
2.82M
    if (transquant_bypass) {
4376
1.37M
      img->set_cu_transquant_bypass(x0, y0, log2CbSize);
4377
1.37M
    }
4378
2.82M
  }
4379
6.15M
  else {
4380
6.15M
    tctx->cu_transquant_bypass_flag = 0;
4381
6.15M
  }
4382
4383
8.98M
  uint8_t cu_skip_flag = 0;
4384
8.98M
  if (shdr->slice_type != SLICE_TYPE_I) {
4385
1.84M
    cu_skip_flag = decode_cu_skip_flag(tctx, x0, y0, ctDepth);
4386
1.84M
  }
4387
4388
8.98M
  int IntraSplitFlag = 0;
4389
4390
8.98M
  enum PredMode cuPredMode;
4391
4392
8.98M
  if (cu_skip_flag) {
4393
1.22M
    read_prediction_unit_SKIP(tctx, x0, y0, nCbS, nCbS);
4394
4395
1.22M
    img->set_PartMode(x0, y0, PART_2Nx2N); // need this for deblocking filter
4396
1.22M
    img->set_pred_mode(x0, y0, log2CbSize, MODE_SKIP);
4397
1.22M
    cuPredMode = MODE_SKIP;
4398
4399
1.22M
    logtrace(LogSlice, "CU pred mode: SKIP\n");
4400
4401
4402
    // DECODE
4403
4404
1.22M
    int nCS_L = 1 << log2CbSize;
4405
1.22M
    decode_prediction_unit(tctx->decctx, tctx->shdr, tctx->img, tctx->motion,
4406
1.22M
                           x0, y0, 0, 0, nCS_L, nCS_L, nCS_L, 0);
4407
1.22M
  }
4408
7.75M
  else /* not skipped */ {
4409
7.75M
    if (shdr->slice_type != SLICE_TYPE_I) {
4410
616k
      int pred_mode_flag = decode_pred_mode_flag(tctx);
4411
616k
      cuPredMode = pred_mode_flag ? MODE_INTRA : MODE_INTER;
4412
616k
    }
4413
7.13M
    else {
4414
7.13M
      cuPredMode = MODE_INTRA;
4415
7.13M
    }
4416
4417
7.75M
    img->set_pred_mode(x0, y0, log2CbSize, cuPredMode);
4418
4419
7.75M
    logtrace(LogSlice, "CU pred mode: %s\n", cuPredMode == MODE_INTRA ? "INTRA" : "INTER");
4420
4421
4422
7.75M
    enum PartMode PartMode;
4423
4424
7.75M
    if (cuPredMode != MODE_INTRA ||
4425
7.53M
        log2CbSize == sps.Log2MinCbSizeY) {
4426
7.53M
      PartMode = decode_part_mode(tctx, cuPredMode, log2CbSize);
4427
4428
7.53M
      if (PartMode == PART_NxN && cuPredMode == MODE_INTRA) {
4429
6.34M
        IntraSplitFlag = 1;
4430
6.34M
      }
4431
7.53M
    }
4432
219k
    else {
4433
219k
      PartMode = PART_2Nx2N;
4434
219k
    }
4435
4436
7.75M
    img->set_PartMode(x0, y0, PartMode); // needed for deblocking ?
4437
4438
7.75M
    logtrace(LogSlice, "PartMode: %s\n", part_mode_name(PartMode));
4439
4440
4441
7.75M
    bool pcm_flag = false;
4442
4443
7.75M
    if (cuPredMode == MODE_INTRA) {
4444
7.13M
      if (PartMode == PART_2Nx2N && sps.pcm_enabled_flag &&
4445
202k
          log2CbSize >= sps.Log2MinIpcmCbSizeY &&
4446
201k
          log2CbSize <= sps.Log2MaxIpcmCbSizeY) {
4447
194k
        pcm_flag = tctx->cabac_decoder.decode_term_bit();
4448
194k
      }
4449
4450
7.13M
      if (pcm_flag) {
4451
743
        img->set_pcm_flag(x0, y0, log2CbSize);
4452
4453
743
        read_pcm_samples(tctx, x0, y0, log2CbSize);
4454
743
      }
4455
7.13M
      else {
4456
7.13M
        int pbOffset = (PartMode == PART_NxN) ? (nCbS / 2) : nCbS;
4457
7.13M
        int log2IntraPredSize = (PartMode == PART_NxN) ? (log2CbSize - 1) : log2CbSize;
4458
4459
7.13M
        logtrace(LogSlice, "nCbS:%d pbOffset:%d\n", nCbS, pbOffset);
4460
4461
7.13M
        int prev_intra_luma_pred_flag[4];
4462
4463
7.13M
        int idx = 0;
4464
20.5M
        for (int j = 0; j < nCbS; j += pbOffset)
4465
39.5M
          for (int i = 0; i < nCbS; i += pbOffset) {
4466
26.0M
            prev_intra_luma_pred_flag[idx++] = decode_prev_intra_luma_pred_flag(tctx);
4467
26.0M
          }
4468
4469
7.13M
        int mpm_idx[4], rem_intra_luma_pred_mode[4];
4470
7.13M
        idx = 0;
4471
4472
7.13M
        int availableA0 = check_CTB_available(img, x0, y0, x0 - 1, y0);
4473
7.13M
        int availableB0 = check_CTB_available(img, x0, y0, x0, y0 - 1);
4474
4475
20.5M
        for (int j = 0; j < nCbS; j += pbOffset)
4476
39.4M
          for (int i = 0; i < nCbS; i += pbOffset) {
4477
26.0M
            if (prev_intra_luma_pred_flag[idx]) {
4478
5.63M
              mpm_idx[idx] = decode_mpm_idx(tctx);
4479
5.63M
            }
4480
20.4M
            else {
4481
20.4M
              rem_intra_luma_pred_mode[idx] = decode_rem_intra_luma_pred_mode(tctx);
4482
20.4M
            }
4483
4484
4485
26.0M
            int x = x0 + i;
4486
26.0M
            int y = y0 + j;
4487
4488
            // --- find intra prediction mode ---
4489
4490
26.0M
            int IntraPredMode;
4491
4492
26.0M
            int availableA = availableA0 || (i > 0); // left candidate always available for right blk
4493
26.0M
            int availableB = availableB0 || (j > 0); // top candidate always available for bottom blk
4494
4495
4496
26.0M
            int PUidx = (x >> sps.Log2MinPUSize) + (y >> sps.Log2MinPUSize) * sps.PicWidthInMinPUs;
4497
4498
26.0M
            enum IntraPredMode candModeList[3];
4499
4500
26.0M
            fillIntraPredModeCandidates(candModeList, x, y, PUidx,
4501
26.0M
                                        availableA, availableB, img);
4502
4503
104M
            for (int i = 0; i < 3; i++)
4504
78.4M
              logtrace(LogSlice, "candModeList[%d] = %d\n", i, candModeList[i]);
4505
4506
26.0M
            if (prev_intra_luma_pred_flag[idx] == 1) {
4507
5.64M
              IntraPredMode = candModeList[mpm_idx[idx]];
4508
5.64M
            }
4509
20.4M
            else {
4510
              // sort candModeList
4511
4512
20.4M
              if (candModeList[0] > candModeList[1]) {
4513
3.80M
                std::swap(candModeList[0], candModeList[1]);
4514
3.80M
              }
4515
20.4M
              if (candModeList[0] > candModeList[2]) {
4516
3.33M
                std::swap(candModeList[0], candModeList[2]);
4517
3.33M
              }
4518
20.4M
              if (candModeList[1] > candModeList[2]) {
4519
12.3M
                std::swap(candModeList[1], candModeList[2]);
4520
12.3M
              }
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
20.4M
              IntraPredMode = rem_intra_luma_pred_mode[idx];
4525
82.0M
              for (int n = 0; n <= 2; n++) {
4526
61.5M
                if (IntraPredMode >= candModeList[n]) { IntraPredMode++; }
4527
61.5M
              }
4528
20.4M
            }
4529
4530
26.0M
            logtrace(LogSlice, "IntraPredMode[%d][%d] = %d (log2blk:%d)\n", x, y, IntraPredMode, log2IntraPredSize);
4531
4532
26.0M
            img->set_IntraPredMode(PUidx, log2IntraPredSize,
4533
26.0M
                                   (enum IntraPredMode) IntraPredMode);
4534
4535
26.0M
            idx++;
4536
26.0M
          }
4537
4538
4539
        // set chroma intra prediction mode
4540
4541
7.13M
        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
7.14M
        else if (sps.ChromaArrayType != CHROMA_MONO) {
4565
          // chroma 4:2:0 and 4:2:2
4566
4567
7.14M
          int intra_chroma_pred_mode = decode_intra_chroma_pred_mode(tctx);
4568
7.14M
          int IntraPredMode = img->get_IntraPredMode(x0, y0);
4569
7.14M
          logtrace(LogSlice, "IntraPredMode: %d\n", IntraPredMode);
4570
7.14M
          int IntraPredModeC = map_chroma_pred_mode(intra_chroma_pred_mode, IntraPredMode);
4571
4572
7.14M
          if (sps.ChromaArrayType == CHROMA_422) {
4573
431k
            IntraPredModeC = map_chroma_422[IntraPredModeC];
4574
431k
          }
4575
4576
7.14M
          img->set_IntraPredModeC(x0, y0, log2CbSize,
4577
7.14M
                                  (enum IntraPredMode) IntraPredModeC,
4578
7.14M
                                  intra_chroma_pred_mode == 4);
4579
7.14M
        }
4580
7.13M
      }
4581
7.13M
    }
4582
617k
    else {
4583
      // INTER
4584
617k
      int nCS = 1 << log2CbSize;
4585
4586
617k
      if (PartMode == PART_2Nx2N) {
4587
315k
        read_prediction_unit(tctx, x0, y0, 0, 0, nCbS, nCbS, ctDepth, nCS, 0);
4588
315k
      }
4589
301k
      else if (PartMode == PART_2NxN) {
4590
109k
        read_prediction_unit(tctx, x0, y0, 0, 0, nCbS, nCbS / 2, ctDepth, nCS, 0);
4591
109k
        read_prediction_unit(tctx, x0, y0, 0, nCbS / 2, nCbS, nCbS / 2, ctDepth, nCS, 1);
4592
109k
      }
4593
192k
      else if (PartMode == PART_Nx2N) {
4594
150k
        read_prediction_unit(tctx, x0, y0, 0, 0, nCbS / 2, nCbS, ctDepth, nCS, 0);
4595
150k
        read_prediction_unit(tctx, x0, y0, nCbS / 2, 0, nCbS / 2, nCbS, ctDepth, nCS, 1);
4596
150k
      }
4597
42.3k
      else if (PartMode == PART_2NxnU) {
4598
6.69k
        read_prediction_unit(tctx, x0, y0, 0, 0, nCbS, nCbS / 4, ctDepth, nCS, 0);
4599
6.69k
        read_prediction_unit(tctx, x0, y0, 0, nCbS / 4, nCbS, nCbS * 3 / 4, ctDepth, nCS, 1);
4600
6.69k
      }
4601
35.6k
      else if (PartMode == PART_2NxnD) {
4602
1.80k
        read_prediction_unit(tctx, x0, y0, 0, 0, nCbS, nCbS * 3 / 4, ctDepth, nCS, 0);
4603
1.80k
        read_prediction_unit(tctx, x0, y0, 0, nCbS * 3 / 4, nCbS, nCbS / 4, ctDepth, nCS, 1);
4604
1.80k
      }
4605
33.7k
      else if (PartMode == PART_nLx2N) {
4606
15.8k
        read_prediction_unit(tctx, x0, y0, 0, 0, nCbS / 4, nCbS, ctDepth, nCS, 0);
4607
15.8k
        read_prediction_unit(tctx, x0, y0, nCbS / 4, 0, nCbS * 3 / 4, nCbS, ctDepth, nCS, 1);
4608
15.8k
      }
4609
17.9k
      else if (PartMode == PART_nRx2N) {
4610
2.02k
        read_prediction_unit(tctx, x0, y0, 0, 0, nCbS * 3 / 4, nCbS, ctDepth, nCS, 0);
4611
2.02k
        read_prediction_unit(tctx, x0, y0, nCbS * 3 / 4, 0, nCbS / 4, nCbS, ctDepth, nCS, 1);
4612
2.02k
      }
4613
15.9k
      else if (PartMode == PART_NxN) {
4614
582
        read_prediction_unit(tctx, x0, y0, 0, 0, nCbS / 2, nCbS / 2, ctDepth, nCS, 0);
4615
582
        read_prediction_unit(tctx, x0, y0, nCbS / 2, 0, nCbS / 2, nCbS / 2, ctDepth, nCS, 1);
4616
582
        read_prediction_unit(tctx, x0, y0, 0, nCbS / 2, nCbS / 2, nCbS / 2, ctDepth, nCS, 2);
4617
582
        read_prediction_unit(tctx, x0, y0, nCbS / 2, nCbS / 2, nCbS / 2, nCbS / 2, ctDepth, nCS, 3);
4618
582
      }
4619
15.3k
      else {
4620
15.3k
        assert(0); // undefined PartMode
4621
15.3k
      }
4622
617k
    } // INTER
4623
4624
4625
    // decode residual
4626
4627
7.75M
    if (!pcm_flag) {
4628
      // !pcm
4629
7.75M
      bool rqt_root_cbf;
4630
4631
7.75M
      uint8_t merge_flag = tctx->motion.merge_flag; // !!get_merge_flag(ctx,x0,y0);
4632
4633
7.75M
      if (cuPredMode != MODE_INTRA &&
4634
602k
          !(PartMode == PART_2Nx2N && merge_flag)) {
4635
431k
        rqt_root_cbf = !!decode_rqt_root_cbf(tctx);
4636
431k
      }
4637
7.31M
      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
7.31M
        rqt_root_cbf = true;
4644
7.31M
      }
4645
4646
      //set_rqt_root_cbf(ctx,x0,y0, log2CbSize, rqt_root_cbf);
4647
4648
7.75M
      if (rqt_root_cbf) {
4649
7.55M
        int MaxTrafoDepth;
4650
4651
7.55M
        if (cuPredMode == MODE_INTRA) {
4652
7.14M
          MaxTrafoDepth = sps.max_transform_hierarchy_depth_intra + IntraSplitFlag;
4653
7.14M
        }
4654
407k
        else {
4655
407k
          MaxTrafoDepth = sps.max_transform_hierarchy_depth_inter;
4656
407k
        }
4657
4658
7.55M
        logtrace(LogSlice, "MaxTrafoDepth: %d\n", MaxTrafoDepth);
4659
4660
7.55M
        uint8_t initial_chroma_cbf = 1;
4661
7.55M
        if (sps.ChromaArrayType == CHROMA_MONO) {
4662
0
          initial_chroma_cbf = 0;
4663
0
        }
4664
4665
7.55M
        read_transform_tree(tctx, x0, y0, x0, y0, x0, y0, log2CbSize, 0, 0,
4666
7.55M
                            MaxTrafoDepth, IntraSplitFlag, cuPredMode,
4667
7.55M
                            initial_chroma_cbf, initial_chroma_cbf);
4668
7.55M
      }
4669
7.75M
    } // !pcm
4670
7.73M
  }
4671
8.98M
}
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
11.7M
{
4682
11.7M
  logtrace(LogSlice, "- read_coding_quadtree %d;%d cbsize:%d depth:%d POC:%d\n", x0, y0, 1 << log2CbSize, ctDepth, tctx->img->PicOrderCntVal);
4683
4684
11.7M
  de265_image* img = tctx->img;
4685
11.7M
  const seq_parameter_set& sps = img->get_sps();
4686
11.7M
  const pic_parameter_set& pps = img->get_pps();
4687
4688
11.7M
  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
11.7M
  if (x0 + (1 << log2CbSize) <= sps.pic_width_in_luma_samples &&
4695
11.7M
      y0 + (1 << log2CbSize) <= sps.pic_height_in_luma_samples &&
4696
11.5M
      log2CbSize > sps.Log2MinCbSizeY) {
4697
3.12M
    split_flag = decode_split_cu_flag(tctx, x0, y0, ctDepth);
4698
3.12M
  }
4699
8.64M
  else {
4700
8.64M
    if (log2CbSize > sps.Log2MinCbSizeY) { split_flag = 1; }
4701
8.43M
    else { split_flag = 0; }
4702
8.64M
  }
4703
4704
4705
11.7M
  if (pps.cu_qp_delta_enabled_flag &&
4706
11.7M
      log2CbSize >= pps.Log2MinCuQpDeltaSize) {
4707
9.00M
    tctx->IsCuQpDeltaCoded = 0;
4708
9.00M
    tctx->CuQpDelta = 0;
4709
9.00M
  }
4710
2.76M
  else {
4711
    // shdr->CuQpDelta = 0; // TODO check: is this the right place to set to default value ?
4712
2.76M
  }
4713
4714
4715
11.7M
  if (tctx->shdr->cu_chroma_qp_offset_enabled_flag &&
4716
0
      log2CbSize >= pps.Log2MinCuChromaQpOffsetSize) {
4717
0
    tctx->IsCuChromaQpOffsetCoded = 0;
4718
0
  }
4719
4720
11.7M
  if (split_flag) {
4721
2.79M
    int x1 = x0 + (1 << (log2CbSize - 1));
4722
2.79M
    int y1 = y0 + (1 << (log2CbSize - 1));
4723
4724
2.79M
    read_coding_quadtree(tctx, x0, y0, log2CbSize - 1, ctDepth + 1);
4725
4726
2.79M
    if (x1 < sps.pic_width_in_luma_samples)
4727
2.75M
      read_coding_quadtree(tctx, x1, y0, log2CbSize - 1, ctDepth + 1);
4728
4729
2.79M
    if (y1 < sps.pic_height_in_luma_samples)
4730
2.66M
      read_coding_quadtree(tctx, x0, y1, log2CbSize - 1, ctDepth + 1);
4731
4732
2.79M
    if (x1 < sps.pic_width_in_luma_samples &&
4733
2.75M
        y1 < sps.pic_height_in_luma_samples)
4734
2.62M
      read_coding_quadtree(tctx, x1, y1, log2CbSize - 1, ctDepth + 1);
4735
2.79M
  }
4736
8.97M
  else {
4737
    // set ctDepth of this CU
4738
4739
8.97M
    img->set_ctDepth(x0, y0, log2CbSize, ctDepth);
4740
4741
8.97M
    read_coding_unit(tctx, x0, y0, log2CbSize, ctDepth);
4742
8.97M
  }
4743
4744
11.7M
  logtrace(LogSlice, "-\n");
4745
11.7M
}
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
35.6k
{
4763
35.6k
  const pic_parameter_set& pps = tctx->img->get_pps();
4764
35.6k
  const seq_parameter_set& sps = tctx->img->get_sps();
4765
4766
35.6k
  const uint16_t ctbW = sps.PicWidthInCtbsY;
4767
35.6k
  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
35.6k
  if ((!first_independent_substream || tctx->CtbY != startCtbY) &&
4774
26.5k
      pps.entropy_coding_sync_enabled_flag &&
4775
26.2k
      tctx->CtbY >= 1 && tctx->CtbX == 0) {
4776
26.2k
    if (sps.PicWidthInCtbsY > 1) {
4777
26.1k
      assert(tctx->CtbY >= 1);
4778
26.1k
      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
26.1k
      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
26.1k
      tctx->ctx_model = tctx->imgunit->ctx_models[(tctx->CtbY - 1)];
4795
26.1k
      tctx->imgunit->ctx_models[(tctx->CtbY - 1)].release(); // not used anymore
4796
4797
      // also restore the StatCoeff[] state for persistent_rice_adaptation
4798
130k
      for (int i = 0; i < 4; i++) {
4799
104k
        tctx->StatCoeff[i] = tctx->imgunit->StatCoeff_models[(tctx->CtbY - 1)][i];
4800
104k
      }
4801
26.1k
    }
4802
2
    else {
4803
2
      tctx->img->wait_for_progress(tctx->task, 0, tctx->CtbY - 1,CTB_PROGRESS_PREFILTER);
4804
2
      initialize_CABAC_models(tctx);
4805
2
    }
4806
26.2k
  }
4807
4808
4809
947k
  do {
4810
947k
    const uint32_t ctbx = tctx->CtbX;
4811
947k
    const uint32_t ctby = tctx->CtbY;
4812
4813
947k
    if (ctbx + ctby * ctbW >= pps.scan->CtbAddrRStoTS.size()) {
4814
0
      return Decode_Error;
4815
0
    }
4816
4817
947k
    if (ctbx >= sps.PicWidthInCtbsY ||
4818
947k
        ctby >= sps.PicHeightInCtbsY) {
4819
0
      return Decode_Error;
4820
0
    }
4821
4822
947k
    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
364k
      tctx->img->wait_for_progress(tctx->task, ctbx + 1, ctby - 1, CTB_PROGRESS_PREFILTER);
4828
364k
    }
4829
4830
    //printf("%p: decode %d;%d\n", tctx, tctx->CtbX,tctx->CtbY);
4831
4832
4833
    // read and decode CTB
4834
4835
947k
    if (tctx->ctx_model.empty() == false) {
4836
2.13k
      return Decode_Error;
4837
2.13k
    }
4838
4839
945k
    read_coding_tree_unit(tctx);
4840
4841
4842
    // save CABAC-model for WPP (except in last CTB row)
4843
4844
945k
    if (pps.entropy_coding_sync_enabled_flag &&
4845
427k
        ctbx == 1 &&
4846
26.4k
        ctby + 1 < sps.PicHeightInCtbsY) {
4847
      // no storage for context table has been allocated
4848
24.9k
      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
24.9k
      tctx->imgunit->ctx_models[ctby] = tctx->ctx_model;
4859
24.9k
      tctx->imgunit->ctx_models[ctby].decouple(); // store an independent copy
4860
4861
      // also save the StatCoeff[] state for persistent_rice_adaptation
4862
124k
      for (int i = 0; i < 4; i++) {
4863
99.8k
        tctx->imgunit->StatCoeff_models[ctby][i] = tctx->StatCoeff[i];
4864
99.8k
      }
4865
24.9k
    }
4866
4867
4868
    // end of slice segment ?
4869
4870
945k
    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
945k
    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
1.11k
      if (pps.dependent_slice_segments_enabled_flag) {
4878
218
        tctx->shdr->ctx_model_storage = tctx->ctx_model;
4879
218
        tctx->shdr->ctx_model_storage.decouple(); // store an independent copy
4880
4881
        // also save the StatCoeff[] state for persistent_rice_adaptation
4882
1.09k
        for (int i = 0; i < 4; i++) {
4883
872
          tctx->shdr->ctx_model_storage_StatCoeff[i] = tctx->StatCoeff[i];
4884
872
        }
4885
4886
218
        tctx->shdr->ctx_model_storage_defined = true;
4887
218
      }
4888
1.11k
    }
4889
4890
945k
    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
945k
    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
945k
    const int lastCtbY = tctx->CtbY;
4899
4900
945k
    bool endOfPicture = advanceCtbAddr(tctx); // true if we read past the end of the image
4901
4902
945k
    if (endOfPicture &&
4903
7.03k
        end_of_slice_segment_flag == false) {
4904
6.92k
      tctx->decctx->add_warning(DE265_WARNING_CTB_OUTSIDE_IMAGE_AREA, false);
4905
6.92k
      tctx->img->integrity = INTEGRITY_DECODING_ERRORS;
4906
6.92k
      return Decode_Error;
4907
6.92k
    }
4908
4909
4910
938k
    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
1.11k
      return Decode_EndOfSliceSegment;
4923
1.11k
    }
4924
4925
4926
937k
    if (!end_of_slice_segment_flag) {
4927
937k
      bool end_of_sub_stream = false;
4928
937k
      end_of_sub_stream |= (pps.tiles_enabled_flag &&
4929
52.1k
                            pps.scan->TileId[tctx->CtbAddrInTS] != pps.scan->TileId[tctx->CtbAddrInTS - 1]);
4930
937k
      end_of_sub_stream |= (pps.entropy_coding_sync_enabled_flag &&
4931
425k
                            lastCtbY != tctx->CtbY);
4932
4933
937k
      if (end_of_sub_stream) {
4934
25.5k
        int end_of_sub_stream_one_bit = tctx->cabac_decoder.decode_term_bit();
4935
25.5k
        if (!end_of_sub_stream_one_bit) {
4936
23.3k
          tctx->decctx->add_warning(DE265_WARNING_EOSS_BIT_NOT_SET, false);
4937
23.3k
          tctx->img->integrity = INTEGRITY_DECODING_ERRORS;
4938
23.3k
          return Decode_Error;
4939
23.3k
        }
4940
4941
2.13k
        tctx->cabac_decoder.init_CABAC(); // byte alignment
4942
2.13k
        return Decode_EndOfSubstream;
4943
25.5k
      }
4944
937k
    }
4945
937k
  } while (true);
4946
35.6k
}
4947
4948
4949
bool initialize_CABAC_at_slice_segment_start(thread_context* tctx)
4950
9.17k
{
4951
9.17k
  de265_image* img = tctx->img;
4952
9.17k
  const pic_parameter_set& pps = img->get_pps();
4953
9.17k
  const seq_parameter_set& sps = img->get_sps();
4954
9.17k
  slice_segment_header* shdr = tctx->shdr;
4955
4956
9.17k
  if (shdr->dependent_slice_segment_flag) {
4957
62
    int prevCtb = pps.scan->CtbAddrTStoRS[pps.scan->CtbAddrRStoTS[shdr->slice_segment_address] - 1];
4958
4959
62
    uint16_t sliceIdx = img->get_SliceHeaderIndex_atIndex(prevCtb);
4960
62
    if (sliceIdx >= img->slices.size()) {
4961
0
      return false;
4962
0
    }
4963
62
    slice_segment_header* prevCtbHdr = img->slices[sliceIdx];
4964
4965
62
    if (pps.is_tile_start_CTB(shdr->slice_segment_address % sps.PicWidthInCtbsY,
4966
62
                              shdr->slice_segment_address / sps.PicWidthInCtbsY
4967
62
                             )) {
4968
0
      initialize_CABAC_models(tctx);
4969
0
    }
4970
62
    else {
4971
      // wait for previous slice to finish decoding
4972
4973
      //printf("wait for previous slice to finish decoding\n");
4974
4975
4976
62
      slice_unit* prevSliceSegment = tctx->imgunit->get_prev_slice_segment(tctx->sliceunit);
4977
      //assert(prevSliceSegment);
4978
62
      if (prevSliceSegment == nullptr) {
4979
0
        return false;
4980
0
      }
4981
4982
62
      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
62
      if (!prevCtbHdr->ctx_model_storage_defined) {
4993
41
        return false;
4994
41
      }
4995
4996
21
      tctx->ctx_model = prevCtbHdr->ctx_model_storage;
4997
21
      prevCtbHdr->ctx_model_storage.release();
4998
4999
      // also restore the StatCoeff[] state for persistent_rice_adaptation
5000
105
      for (int i = 0; i < 4; i++) {
5001
84
        tctx->StatCoeff[i] = prevCtbHdr->ctx_model_storage_StatCoeff[i];
5002
84
      }
5003
21
    }
5004
62
  }
5005
9.11k
  else {
5006
9.11k
    initialize_CABAC_models(tctx);
5007
9.11k
  }
5008
5009
9.13k
  return true;
5010
9.17k
}
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
1.10k
{
5031
1.10k
  thread_task_slice_segment* data = this;
5032
1.10k
  thread_context* tctx = data->tctx;
5033
1.10k
  de265_image* img = tctx->img;
5034
5035
1.10k
  state = Running;
5036
1.10k
  img->thread_run(this);
5037
5038
1.10k
  setCtbAddrFromTS(tctx);
5039
5040
  //printf("%p: A start decoding at %d/%d\n", tctx, tctx->CtbX,tctx->CtbY);
5041
5042
1.10k
  if (data->firstSliceSubstream) {
5043
735
    bool success = initialize_CABAC_at_slice_segment_start(tctx);
5044
735
    if (!success) {
5045
5
      state = Finished;
5046
5
      tctx->sliceunit->finished_threads.increase_progress(1);
5047
5
      img->thread_finishes(this);
5048
5
      return;
5049
5
    }
5050
735
  }
5051
367
  else {
5052
367
    initialize_CABAC_models(tctx);
5053
367
  }
5054
5055
1.09k
  tctx->cabac_decoder.init_CABAC();
5056
5057
  /*enum DecodeResult result =*/
5058
1.09k
  decode_substream(tctx, false, data->firstSliceSubstream);
5059
5060
1.09k
  state = Finished;
5061
1.09k
  tctx->sliceunit->finished_threads.increase_progress(1);
5062
1.09k
  img->thread_finishes(this);
5063
5064
1.09k
  return; // DE265_OK;
5065
1.10k
}
5066
5067
5068
void thread_task_ctb_row::work()
5069
29.0k
{
5070
29.0k
  thread_task_ctb_row* data = this;
5071
29.0k
  thread_context* tctx = data->tctx;
5072
29.0k
  de265_image* img = tctx->img;
5073
5074
29.0k
  const seq_parameter_set& sps = img->get_sps();
5075
29.0k
  int ctbW = sps.PicWidthInCtbsY;
5076
5077
29.0k
  state = Running;
5078
29.0k
  img->thread_run(this);
5079
5080
29.0k
  setCtbAddrFromTS(tctx);
5081
5082
29.0k
  int ctby = tctx->CtbAddrInRS / ctbW;
5083
29.0k
  int myCtbRow = ctby;
5084
5085
  //printf("start CTB-row decoding at row %d\n", ctby);
5086
5087
29.0k
  if (data->firstSliceSubstream) {
5088
2.87k
    bool success = initialize_CABAC_at_slice_segment_start(tctx);
5089
2.87k
    if (!success) {
5090
      // could not decode this row, mark whole row as finished
5091
127
      for (int x = 0; x < ctbW; x++) {
5092
102
        img->ctb_progress[myCtbRow * ctbW + x].set_progress(CTB_PROGRESS_PREFILTER);
5093
102
      }
5094
5095
25
      state = Finished;
5096
25
      tctx->sliceunit->finished_threads.increase_progress(1);
5097
25
      img->thread_finishes(this);
5098
25
      return;
5099
25
    }
5100
    //initialize_CABAC(tctx);
5101
2.87k
  }
5102
5103
29.0k
  tctx->cabac_decoder.init_CABAC();
5104
5105
29.0k
  bool firstIndependentSubstream =
5106
29.0k
      data->firstSliceSubstream && !tctx->shdr->dependent_slice_segment_flag;
5107
5108
  /*enum DecodeResult result =*/
5109
29.0k
  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
29.0k
  if (tctx->CtbY == myCtbRow) {
5116
2.63k
    int lastCtbX = sps.PicWidthInCtbsY; // assume no tiles when WPP is on
5117
43.0k
    for (int x = tctx->CtbX; x < lastCtbX; x++) {
5118
40.3k
      if (x < sps.PicWidthInCtbsY &&
5119
40.3k
          myCtbRow < sps.PicHeightInCtbsY) {
5120
40.3k
        img->ctb_progress[myCtbRow * ctbW + x].set_progress(CTB_PROGRESS_PREFILTER);
5121
40.3k
      }
5122
40.3k
    }
5123
2.63k
  }
5124
5125
29.0k
  state = Finished;
5126
29.0k
  tctx->sliceunit->finished_threads.increase_progress(1);
5127
29.0k
  img->thread_finishes(this);
5128
29.0k
}
5129
5130
5131
de265_error read_slice_segment_data(thread_context* tctx)
5132
5.56k
{
5133
5.56k
  setCtbAddrFromTS(tctx);
5134
5135
5.56k
  de265_image* img = tctx->img;
5136
5.56k
  const pic_parameter_set& pps = img->get_pps();
5137
  //const seq_parameter_set& sps = img->get_sps();
5138
5.56k
  slice_segment_header* shdr = tctx->shdr;
5139
5140
5.56k
  bool success = initialize_CABAC_at_slice_segment_start(tctx);
5141
5.56k
  if (!success) {
5142
11
    return DE265_ERROR_UNSPECIFIED_DECODING_ERROR;
5143
11
  }
5144
5145
5.55k
  tctx->cabac_decoder.init_CABAC();
5146
5147
  //printf("-----\n");
5148
5149
5.55k
  bool first_slice_substream = !shdr->dependent_slice_segment_flag;
5150
5151
5.55k
  uint32_t substream = 0;
5152
5153
5.55k
  enum DecodeResult result;
5154
5.55k
  do {
5155
    //int ctby = tctx->CtbY;
5156
5157
5158
    // check whether entry_points[] are correct in the bitstream
5159
5160
5.55k
    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
5.55k
    substream++;
5169
5170
5171
5.55k
    result = decode_substream(tctx, false, first_slice_substream);
5172
5173
5174
5.55k
    if (result == Decode_EndOfSliceSegment ||
5175
5.55k
        result == Decode_Error) {
5176
5.55k
      break;
5177
5.55k
    }
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
5.55k
  return DE265_OK;
5187
5.56k
}
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
 */