Coverage Report

Created: 2026-10-27 06:57

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