Coverage Report

Created: 2026-09-13 06:32

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