Coverage Report

Created: 2026-09-14 06:49

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/avm/av2/encoder/encoder.h
Line
Count
Source
1
/*
2
 * Copyright (c) 2021, Alliance for Open Media. All rights reserved
3
 *
4
 * This source code is subject to the terms of the BSD 3-Clause Clear License
5
 * and the Alliance for Open Media Patent License 1.0. If the BSD 3-Clause Clear
6
 * License was not distributed with this source code in the LICENSE file, you
7
 * can obtain it at aomedia.org/license/software-license/bsd-3-c-c/.  If the
8
 * Alliance for Open Media Patent License 1.0 was not distributed with this
9
 * source code in the PATENTS file, you can obtain it at
10
 * aomedia.org/license/patent-license/.
11
 */
12
13
/*!\file
14
 * \brief Declares top-level encoder structures and functions.
15
 */
16
#ifndef AVM_AV2_ENCODER_ENCODER_H_
17
#define AVM_AV2_ENCODER_ENCODER_H_
18
19
#include <stdbool.h>
20
#include <stdio.h>
21
22
#include "config/avm_config.h"
23
24
#include "avm/avmcx.h"
25
26
#include "av2/common/alloccommon.h"
27
#include "av2/common/av2_common_int.h"
28
#include "av2/common/blockd.h"
29
#include "av2/common/bru.h"
30
#include "av2/common/entropymode.h"
31
#include "av2/common/enums.h"
32
#include "av2/common/level.h"
33
#include "av2/common/pred_common.h"
34
#include "av2/common/resize.h"
35
#include "av2/common/thread_common.h"
36
#include "av2/common/timing.h"
37
#include "av2/common/gdf.h"
38
#include "av2/encoder/aq_cyclicrefresh.h"
39
#include "av2/encoder/av2_quantize.h"
40
#include "av2/encoder/block.h"
41
#include "av2/encoder/context_tree.h"
42
#include "av2/encoder/encodemb.h"
43
#include "av2/encoder/firstpass.h"
44
#include "av2/encoder/global_motion.h"
45
#include "av2/encoder/lookahead.h"
46
#include "av2/encoder/mcomp.h"
47
#include "av2/encoder/ratectrl.h"
48
#include "av2/encoder/rd.h"
49
#include "av2/encoder/speed_features.h"
50
#include "av2/encoder/tokenize.h"
51
#include "av2/encoder/tpl_model.h"
52
#include "av2/encoder/av2_noise_estimate.h"
53
#include "av2/common/banding_metadata.h"
54
55
#if CONFIG_INTERNAL_STATS
56
#include "avm_dsp/ssim.h"
57
#endif
58
#include "avm_dsp/variance.h"
59
#if CONFIG_DENOISE
60
#include "avm_dsp/noise_model.h"
61
#endif
62
#if CONFIG_TUNE_VMAF
63
#include "av2/encoder/tune_vmaf.h"
64
#endif
65
66
#include "avm/internal/avm_codec_internal.h"
67
#include "avm_util/avm_thread.h"
68
69
#ifdef __cplusplus
70
extern "C" {
71
#endif
72
73
// TODO(yunqing, any): Added suppression tag to quiet Doxygen warnings. Need to
74
// adjust it while we work on documentation.
75
/*!\cond */
76
// Number of frames required to test for scene cut detection
77
#define SCENE_CUT_KEY_TEST_INTERVAL 16
78
79
// Rational number with an int64 numerator
80
// This structure holds a fractional value
81
typedef struct avm_rational64 {
82
  int64_t num;       // fraction numerator
83
  int den;           // fraction denominator
84
} avm_rational64_t;  // alias for struct avm_rational
85
86
enum {
87
  NORMAL = 0,
88
  FOURFIVE = 1,
89
  THREEFIVE = 2,
90
  THREEFOUR = 3,
91
  ONEFOUR = 4,
92
  ONEEIGHT = 5,
93
  ONETWO = 6
94
} UENUM1BYTE(AVM_SCALING);
95
96
enum {
97
  // Good Quality Fast Encoding. The encoder balances quality with the amount of
98
  // time it takes to encode the output. Speed setting controls how fast.
99
  GOOD,
100
  // Realtime Fast Encoding.
101
  REALTIME
102
} UENUM1BYTE(MODE);
103
104
enum {
105
  FRAMEFLAGS_KEY = 1 << 0,
106
  FRAMEFLAGS_INTRAONLY = 1 << 4,
107
  FRAMEFLAGS_SWITCH = 1 << 5,
108
  FRAMEFLAGS_HAS_FILM_GRAIN_PARAMS = 1 << 7,
109
} UENUM1BYTE(FRAMETYPE_FLAGS);
110
111
static INLINE int get_true_pyr_level(int frame_level, int is_key_frame,
112
0
                                     int max_layer_depth, int is_key_overlay) {
113
0
  if (is_key_overlay) return max_layer_depth;
114
0
  if (is_key_frame) {
115
0
    // Keyframe case
116
0
    return 1;
117
0
  } else if (frame_level == MAX_ARF_LAYERS) {
118
0
    // Leaves
119
0
    return max_layer_depth;
120
0
  } else if (frame_level == (MAX_ARF_LAYERS + 1)) {
121
0
    // Altrefs
122
0
    return 1;
123
0
  }
124
0
  return frame_level;
125
0
}
126
127
enum {
128
  NO_AQ = 0,
129
  VARIANCE_AQ = 1,
130
  COMPLEXITY_AQ = 2,
131
  CYCLIC_REFRESH_AQ = 3,
132
  AQ_MODE_COUNT  // This should always be the last member of the enum
133
} UENUM1BYTE(AQ_MODE);
134
enum {
135
  NO_DELTA_Q = 0,
136
  DELTA_Q_OBJECTIVE = 1,   // Modulation to improve objective quality
137
  DELTA_Q_PERCEPTUAL = 2,  // Modulation to improve perceptual quality
138
  DELTA_Q_MODE_COUNT       // This should always be the last member of the enum
139
} UENUM1BYTE(DELTAQ_MODE);
140
141
enum {
142
  RESIZE_NONE = 0,     // No frame resizing allowed.
143
  RESIZE_FIXED = 1,    // All frames are coded at the specified scale.
144
  RESIZE_RANDOM = 2,   // All frames are coded at a random scale.
145
  RESIZE_DYNAMIC = 3,  // Frames coded at lower scale based on rate control.
146
  RESIZE_PATTERN = 4,  // Fixed pattern for resize-mode common test conditions
147
  RESIZE_BRIDGE_FRAME_PATTERN = 5,  // Fixed pattern for Bridge Frame unit test
148
  RESIZE_MODES
149
} UENUM1BYTE(RESIZE_MODE);
150
151
enum {
152
  SS_CFG_SRC = 0,
153
  SS_CFG_LOOKAHEAD = 1,
154
  SS_CFG_FPF = 2,
155
  SS_CFG_TOTAL = 3
156
} UENUM1BYTE(SS_CFG_OFFSET);
157
158
enum {
159
  DISABLE_SCENECUT,        // For LAP, lag_in_frames < 19
160
  ENABLE_SCENECUT_MODE_1,  // For LAP, lag_in_frames >=19 and < 33
161
  ENABLE_SCENECUT_MODE_2   // For twopass and LAP - lag_in_frames >=33
162
} UENUM1BYTE(SCENECUT_MODE);
163
164
#define MAX_VBR_CORPUS_COMPLEXITY 10000
165
166
typedef enum {
167
  COST_UPD_SB,
168
  COST_UPD_SBROW,
169
  COST_UPD_TILE,
170
  COST_UPD_OFF,
171
} COST_UPDATE_TYPE;
172
173
/*!\endcond */
174
175
/*!
176
 * \brief Encoder config related to resize.
177
 */
178
typedef struct {
179
  /*!
180
   * Indicates the frame resize mode to be used by the encoder.
181
   */
182
  RESIZE_MODE resize_mode;
183
  /*!
184
   * Indicates the denominator for resize of inter frames, assuming 8 as the
185
   *  numerator. Its value ranges between 8-16.
186
   */
187
  uint8_t resize_scale_denominator;
188
  /*!
189
   * Indicates the denominator for resize of key frames, assuming 8 as the
190
   * numerator. Its value ranges between 8-16.
191
   */
192
  uint8_t resize_kf_scale_denominator;
193
} ResizeCfg;
194
195
/*!
196
 * \brief Encoder config for coding block partitioning.
197
 */
198
typedef struct {
199
  /*!
200
   * Flag to indicate if ml-based speed-up for partition search should be
201
   * disabled.
202
   */
203
  bool disable_ml_partition_speed_features;
204
  /*!
205
   * Flag to indicate aggressiveness of erp pruning
206
   * */
207
  unsigned int erp_pruning_level;
208
  /*!
209
   * Flag to indicate the use of ml model for erp pruning.
210
   * */
211
  int use_ml_erp_pruning;
212
  /*!
213
   * Flag to indicate if extended partitions are enabled.
214
   * */
215
  unsigned int enable_ext_partitions;
216
  /*!
217
   * Flag to indicate if rectanguar partitions should be enabled.
218
   */
219
  bool enable_rect_partitions;
220
  /*!
221
   * Flag to indicate if 1:2:4:1 / 1:4:2:1 partitions should be enabled.
222
   */
223
  bool enable_uneven_4way_partitions;
224
  /*!
225
   * Flag to indicate if semi-decoupled partitioning should be enabled.
226
   */
227
  bool enable_sdp;
228
  /*!
229
   * Flag to indicate if semi-decoupled partitioning should be enabled for inter
230
   * frames.
231
   */
232
  bool enable_extended_sdp;
233
  /*!
234
   * Indicates the minimum partition size that should be allowed. Both width and
235
   * height of a partition cannot be smaller than the min_partition_size.
236
   */
237
  unsigned int min_partition_size;
238
  /*!
239
   * Indicates the maximum partition size that should be allowed. Both width and
240
   * height of a partition cannot be larger than the max_partition_size.
241
   */
242
  unsigned int max_partition_size;
243
  /*!
244
   * Indicates the maximum aspect ratio of allowed partition block sizes.
245
   */
246
  unsigned int max_partition_aspect_ratio;
247
} PartitionCfg;
248
249
/*!
250
 * \brief Encoder flags for intra prediction.
251
 */
252
typedef struct {
253
  /*!
254
   * Flag to indicate if intra edge filtering process should be enabled.
255
   */
256
  bool enable_intra_edge_filter;
257
  /*!
258
   * Flag to indicate if data-drive intra prediction should be enabled.
259
   */
260
  bool enable_intra_dip;
261
  /*!
262
   * Flag to indicate if smooth intra prediction modes should be enabled.
263
   */
264
  bool enable_smooth_intra;
265
  /*!
266
   * Flag to indicate if PAETH intra prediction mode should be enabled.
267
   */
268
  bool enable_paeth_intra;
269
  /*!
270
   * Flag to indicate if CFL uv intra mode should be enabled.
271
   */
272
  bool enable_cfl_intra;
273
  /*!
274
   * Flag to indicate if MHCCP intra mode should be enabled.
275
   */
276
  bool enable_mhccp;
277
  /*!
278
   * Flag to indicate if delta angles for directional intra prediction should be
279
   * enabled.
280
   */
281
  bool enable_angle_delta;
282
  /*!
283
   * Flag to indicate if multiple reference line selection for intra prediction
284
   * should be enabled.
285
   */
286
  bool enable_mrls;
287
  /*!
288
   * Flag to indicate if forward skip coding is enabled
289
   */
290
  bool enable_fsc;
291
  /*!
292
   * Flag to indicate if the intra IDTX is eanbled
293
   */
294
  bool enable_idtx_intra;
295
  /*!
296
   * Flag to indicate if IBP should be enabled
297
   */
298
  bool enable_ibp;
299
} IntraModeCfg;
300
301
/*!
302
 * \brief Encoder flags for transform sizes and types.
303
 */
304
typedef struct {
305
  /*!
306
   * Flag to disable ml based transform speed features.
307
   */
308
  bool disable_ml_transform_speed_features;
309
  /*!
310
   * Flag to enable txfm partition.
311
   */
312
  bool enable_tx_partition;
313
  /*!
314
   * Flag to indicate if reduced transform block partition set should be
315
   * enabled.
316
   */
317
  bool reduced_tx_part_set;
318
  /*!
319
   * Flag to indicate if flip and identity transform types should be enabled.
320
   */
321
  bool enable_flip_idtx;
322
  /*!
323
   * Flag to indicate whether or not to use a default reduced set for ext-tx
324
   * rather than the potential full set of 16 transforms.
325
   */
326
  uint8_t reduced_tx_type_set;
327
  /*!
328
   * Flag to indicate if transform type for intra blocks should be limited to
329
   * DCT_DCT.
330
   */
331
  bool use_intra_dct_only;
332
  /*!
333
   * Flag to indicate if transform type for inter blocks should be limited to
334
   * DCT_DCT.
335
   */
336
  bool use_inter_dct_only;
337
  /*!
338
   * Flag to indicate if intra blocks should use default transform type
339
   * (mode-dependent) only.
340
   */
341
  bool use_intra_default_tx_only;
342
  /*!
343
   * Flag to indicate if intra secondary transform should be enabled.
344
   */
345
  bool enable_ist;
346
  /*!
347
   * Flag to indicate if inter secondary transform should be enabled.
348
   */
349
  bool enable_inter_ist;
350
  /*!
351
   * Flag to indicate if only dct is applied for chroma residual coding.
352
   */
353
  bool enable_chroma_dctonly;
354
  /*!
355
   * Flag to indicate if inter data-driven transform should be enabled.
356
   */
357
  bool enable_inter_ddt;
358
  /*!
359
   * Flag to indicate if cross chroma component transform is enabled.
360
   */
361
  bool enable_cctx;
362
} TxfmSizeTypeCfg;
363
364
/*!
365
 * \brief Encoder flags for compound prediction modes.
366
 */
367
typedef struct {
368
  /*!
369
   * Flag to indicate if masked (wedge/diff-wtd) compound type should be
370
   * enabled.
371
   */
372
  bool enable_masked_comp;
373
  /*!
374
   * Flag to indicate if smooth interintra mode should be enabled.
375
   */
376
  bool enable_smooth_interintra;
377
  /*!
378
   * Flag to indicate if difference-weighted compound type should be enabled.
379
   */
380
  bool enable_diff_wtd_comp;
381
  /*!
382
   * Flag to indicate if inter-inter wedge compound type should be enabled.
383
   */
384
  bool enable_interinter_wedge;
385
  /*!
386
   * Flag to indicate if inter-intra wedge compound type should be enabled.
387
   */
388
  bool enable_interintra_wedge;
389
} CompoundTypeCfg;
390
391
/*!
392
 * \brief Encoder config related to the coding of key frames.
393
 */
394
typedef struct {
395
  /*!
396
   * Indicates the minimum distance to a key frame.
397
   */
398
  int key_freq_min;
399
400
  /*!
401
   * Indicates the maximum distance to a key frame.
402
   */
403
  int key_freq_max;
404
405
  /*!
406
   * Indicates if temporal filtering should be applied on keyframe.
407
   */
408
  int enable_keyframe_filtering;
409
410
  /*!
411
   * Indicates the number of frames after which a frame may be coded as an
412
   * S-Frame.
413
   */
414
  int sframe_dist;
415
416
  /*!
417
   * Indicates how an S-Frame should be inserted.
418
   * 0: the considered frame will be made into an S-Frame only if it is an
419
   * altref frame. 1: the next altref frame will be made into an S-Frame.
420
   */
421
  int sframe_mode;
422
423
  /*!
424
   * Indicates whether a switch frame is coded as an RAS-Frame.
425
   */
426
  int sframe_type;
427
428
  /*!
429
   * Indicates if encoder should autodetect cut scenes and set the keyframes.
430
   */
431
  bool auto_key;
432
433
  /*!
434
   * Indicates if forward keyframe reference should be enabled.
435
   */
436
  bool fwd_kf_enabled;
437
438
  /*!
439
   * Indicates if S-Frames should be enabled for the sequence.
440
   */
441
  bool enable_sframe;
442
443
  /*!
444
   * Indicates if intra block copy prediction mode should be enabled or not.
445
   */
446
  bool enable_intrabc;
447
448
  /*!
449
   * Indicates if search range extension for intra block copy prediction mode
450
   * should be enabled or not. 0: disable. 1: extend the search range to the
451
   * local area (default). 2: only use the local search range.
452
   */
453
  int enable_intrabc_ext;
454
455
} KeyFrameCfg;
456
457
/*!
458
 * \brief Encoder rate control configuration parameters
459
 */
460
typedef struct {
461
  /*!\cond */
462
  // BUFFERING PARAMETERS
463
  /*!\endcond */
464
  /*!
465
   * Indicates the amount of data that will be buffered by the decoding
466
   * application prior to beginning playback, and is expressed in units of
467
   * time(milliseconds).
468
   */
469
  int64_t starting_buffer_level_ms;
470
  /*!
471
   * Indicates the amount of data that the encoder should try to maintain in the
472
   * decoder's buffer, and is expressed in units of time(milliseconds).
473
   */
474
  int64_t optimal_buffer_level_ms;
475
  /*!
476
   * Indicates the maximum amount of data that may be buffered by the decoding
477
   * application, and is expressed in units of time(milliseconds).
478
   */
479
  int64_t maximum_buffer_size_ms;
480
481
  /*!
482
   * Indicates the bandwidth to be used in bits per second.
483
   */
484
  int64_t target_bandwidth;
485
486
  /*!
487
   * Indicates average complexity of the corpus in single pass vbr based on
488
   * LAP. 0 indicates that corpus complexity vbr mode is disabled.
489
   */
490
  unsigned int vbr_corpus_complexity_lap;
491
  /*!
492
   * Indicates the maximum allowed bitrate for any intra frame as % of bitrate
493
   * target.
494
   */
495
  unsigned int max_intra_bitrate_pct;
496
  /*!
497
   * Indicates the maximum allowed bitrate for any inter frame as % of bitrate
498
   * target.
499
   */
500
  unsigned int max_inter_bitrate_pct;
501
  /*!
502
   * Indicates the percentage of rate boost for golden frame in CBR mode.
503
   */
504
  unsigned int gf_cbr_boost_pct;
505
  /*!
506
   * min_cr / 100 indicates the target minimum compression ratio for each
507
   * frame.
508
   */
509
  unsigned int min_cr;
510
  /*!
511
   * Indicates the frame drop threshold.
512
   */
513
  int drop_frames_water_mark;
514
  /*!
515
   * under_shoot_pct indicates the tolerance of the VBR algorithm to
516
   * undershoot and is used as a trigger threshold for more agressive
517
   * adaptation of Q. It's value can range from 0-100.
518
   */
519
  int under_shoot_pct;
520
  /*!
521
   * over_shoot_pct indicates the tolerance of the VBR algorithm to overshoot
522
   * and is used as a trigger threshold for more agressive adaptation of Q.
523
   * It's value can range from 0-1000.
524
   */
525
  int over_shoot_pct;
526
  /*!
527
   * Indicates the maximum qindex that can be used by the quantizer i.e. the
528
   * worst quality qindex.
529
   */
530
  int worst_allowed_q;
531
  /*!
532
   * Indicates the minimum qindex that can be used by the quantizer i.e. the
533
   * best quality qindex.
534
   */
535
  int best_allowed_q;
536
  /*!
537
   * Indicates the Constant/Constrained Quality level in [0, 255] range.
538
   */
539
  int qp;
540
  /*!
541
   * Indicates if the encoding mode is vbr, cbr, constrained quality or
542
   * constant quality.
543
   */
544
  enum avm_rc_mode mode;
545
  /*!
546
   * Indicates the minimum bitrate to be used for a single frame as a percentage
547
   * of the target bitrate.
548
   */
549
  int vbrmin_section;
550
  /*!
551
   * Indicates the maximum bitrate to be used for a single frame as a percentage
552
   * of the target bitrate.
553
   */
554
  int vbrmax_section;
555
} RateControlCfg;
556
557
/*!\cond */
558
typedef struct {
559
  // Indicates the number of frames lag before encoding is started.
560
  int lag_in_frames;
561
  // Indicates the minimum gf/arf interval to be used.
562
  int min_gf_interval;
563
  // Indicates the maximum gf/arf interval to be used.
564
  int max_gf_interval;
565
  // Indicates the minimum height for GF group pyramid structure to be used.
566
  int gf_min_pyr_height;
567
  // Indicates the maximum height for GF group pyramid structure to be used.
568
  int gf_max_pyr_height;
569
  // Indicates if automatic set and use of altref frames should be enabled.
570
  bool enable_auto_arf;
571
  // Indicates if automatic set and use of (b)ackward (r)ef (f)rames should be
572
  // enabled.
573
  bool enable_auto_brf;
574
} GFConfig;
575
576
typedef struct {
577
  // Indicates the number of tile groups.
578
  unsigned int num_tile_groups;
579
  // Indicates the MTU size for a tile group. If mtu is non-zero,
580
  // num_tile_groups is set to DEFAULT_MAX_NUM_TG.
581
  unsigned int mtu;
582
  // Indicates the number of tile columns in log2.
583
  int tile_columns;
584
  // Indicates the number of tile rows in log2.
585
  int tile_rows;
586
  // Indicates the number of widths in the tile_widths[] array.
587
  int tile_width_count;
588
  // Indicates the number of heights in the tile_heights[] array.
589
  int tile_height_count;
590
  // Indicates the tile widths, and may be empty.
591
  int tile_widths[MAX_TILE_COLS];
592
  // Indicates the tile heights, and may be empty.
593
  int tile_heights[MAX_TILE_ROWS];
594
} TileConfig;
595
596
typedef struct {
597
  // Indicates the width of the input frame.
598
  int width;
599
  // Indicates the height of the input frame.
600
  int height;
601
  // If forced_max_frame_width is non-zero then it is used to force the maximum
602
  // frame width written in write_sequence_header().
603
  int forced_max_frame_width;
604
  // If forced_max_frame_width is non-zero then it is used to force the maximum
605
  // frame height written in write_sequence_header().
606
  int forced_max_frame_height;
607
  // Indicates the frame width after applying both super-resolution and resize
608
  // to the coded frame.
609
  int render_width;
610
  // Indicates the frame height after applying both super-resolution and resize
611
  // to the coded frame.
612
  int render_height;
613
} FrameDimensionCfg;
614
615
typedef struct {
616
  // Bitmask of which motion modes are enabled at the sequence level
617
  int seq_enabled_motion_modes;
618
  int enable_six_param_warp_delta;
619
} MotionModeCfg;
620
621
typedef struct {
622
  // Timing info for each frame.
623
  avm_timing_info_t timing_info;
624
  // Indicates the number of time units of a decoding clock.
625
  uint32_t num_units_in_decoding_tick;
626
  // Indicates if decoder model information is present in the coded sequence
627
  // header.
628
  bool decoder_model_info_present_flag;
629
  // Indicates if display model information is present in the coded sequence
630
  // header.
631
  bool display_model_info_present_flag;
632
  // Indicates if timing info for each frame is present.
633
  bool timing_info_present;
634
} DecoderModelCfg;
635
636
typedef struct {
637
  // Indicates the update frequency for coeff costs.
638
  COST_UPDATE_TYPE coeff;
639
  // Indicates the update frequency for mode costs.
640
  COST_UPDATE_TYPE mode;
641
  // Indicates the update frequency for mv costs.
642
  COST_UPDATE_TYPE mv;
643
} CostUpdateFreq;
644
645
typedef struct {
646
  // Indicates the maximum number of reference frames allowed per frame.
647
  unsigned int max_reference_frames;
648
  // Indicates if the reduced set of references should be enabled.
649
  bool enable_reduced_reference_set;
650
  // Indicates if one-sided compound should be enabled.
651
  bool enable_onesided_comp;
652
  bool explicit_ref_frame_map;
653
  // Indicates if SEFs with the display order hint derivation are added to
654
  // ouptput hidden frames.
655
  bool add_sef_for_hidden_frames;
656
} RefFrameCfg;
657
658
typedef struct {
659
  // Indicates the color space that should be used.
660
  avm_color_primaries_t color_primaries;
661
  // Indicates the characteristics of transfer function to be used.
662
  avm_transfer_characteristics_t transfer_characteristics;
663
  // Indicates the matrix coefficients to be used for the transfer function.
664
  avm_matrix_coefficients_t matrix_coefficients;
665
  // Indicates the chroma 4:2:2 or 4:2:0 sample position info.
666
  avm_chroma_sample_position_t chroma_sample_position;
667
  // Indicates if a limited color range or full color range should be used.
668
  avm_color_range_t color_range;
669
} ColorCfg;
670
671
typedef struct {
672
  // Indicates the LCR OBU (OBU_LAYER_CONFIGURATION_RECORD) is enabled.
673
  bool enable_lcr;
674
  // Indicates the OPS OBU (OBU_OPERATING_POINT_SET) is enabled.
675
  bool enable_ops;
676
  // Indicates the number of OPS OBUs
677
  int num_ops;
678
  // Indicates the Atlas Segment OBU (OBU_ATLAS_SEGMENT) is enabled.
679
  bool enable_atlas;
680
} LayerCfg;
681
682
typedef struct {
683
  // Indicates if extreme motion vector unit test should be enabled or not.
684
  unsigned int motion_vector_unit_test;
685
  // Indicates if superblock multipass unit test should be enabled or not.
686
  unsigned int sb_multipass_unit_test;
687
  // Indicates if subgop unit test is enabled or not.
688
  unsigned int enable_subgop_stats;
689
  // Indicates how many frame-level quantization matrix sets are defined for
690
  // unit test.
691
  uint8_t frame_multi_qmatrix_unit_test;
692
  // Indicates the leaf node frames(LF_UPDATE frames) are set as
693
  // show_existing_frame with derive_order_hint=0 Used only for test purpose.
694
  uint8_t sef_with_order_hint_test;
695
  // Signal multiple sequence header
696
  uint8_t multi_seq_header_test;
697
  // Flag to indicate ref buffer refresh for the multi layers unittests.
698
  int use_buffer_refresh_multi_layers_test;
699
  // Refresh buffer flags for use in the multi layer unittests.
700
  int buffer_refresh_multi_layers_test[REF_FRAMES];
701
  // Changes needed for multi layers tests with nonzero lag.
702
  int multi_layers_lag_test;
703
  // Test-only: defer output of non-KEY/non-S frames to exercise the
704
  // restricted_prediction_switch output ordering path.
705
  int force_deferred_frames_for_ras_test;
706
  // Signal one sequence header for the entire sequence.
707
  uint8_t single_seq_header_for_all_test;
708
  // Insert an s frame for unit test purpose.
709
  int insert_sframe;
710
} UnitTestCfg;
711
712
typedef struct {
713
  // Indicates the file path to the VMAF model.
714
  const char *vmaf_model_path;
715
  // Indicates the path to the film grain parameters.
716
  const char *film_grain_table_filename;
717
  // Indicates the visual tuning metric.
718
  avm_tune_metric tuning;
719
  // Indicates if the current content is screen or default type.
720
  avm_tune_content content;
721
  // Indicates the film grain parameters.
722
  int film_grain_test_vector;
723
  // Indicates FGS block size: 0 - 16x16, 1 - 32x32
724
  int film_grain_block_size;
725
} TuneCfg;
726
727
typedef struct {
728
  // Indicates the framerate of the input video.
729
  double init_framerate;
730
  // Indicates the bit-depth of the input video.
731
  unsigned int input_bit_depth;
732
  // Indicates the maximum number of frames to be encoded.
733
  unsigned int limit;
734
  // Indicates the chrome subsampling x value.
735
  unsigned int chroma_subsampling_x;
736
  // Indicates the chrome subsampling y value.
737
  unsigned int chroma_subsampling_y;
738
} InputCfg;
739
740
typedef struct {
741
  // List of QP offsets for: keyframe, ALTREF, and 3 levels of internal ARFs.
742
  // If any of these values are negative, fixed offsets are disabled.
743
  double fixed_qp_offsets[FIXED_QP_OFFSET_COUNT];
744
  // If the value is 0 (default), encoder may not use fixed QP offsets.
745
  // If the value is 1, encoder will use fixed QP offsets, that are
746
  // either:
747
  // - Given by the user, and stored in 'fixed_qp_offsets' array, OR
748
  // - Picked automatically from qp using a fixed factor.
749
  // If the value is 2, encoder will use fixed QP offsets that are :
750
  // - Derived from qp and has variable factors across Temporal levels as a fn.
751
  // of q-step.
752
  // TODO(krapaka): extend the derivation of factors also based on operating
753
  // configuration such as random access and low-delay.
754
  int use_fixed_qp_offsets;
755
  // It true, the offset factor depends on the QP value
756
  // else fixed value is used.
757
  int q_based_qp_offsets;
758
  // Indicates the minimum flatness of the quantization matrix.
759
  int qm_minlevel;
760
  // Indicates the maximum flatness of the quantization matrix.
761
  int qm_maxlevel;
762
  // Indicates if adaptive quantize_b should be enabled.
763
  int quant_b_adapt;
764
  // Indicates the Adaptive Quantization mode to be used.
765
  AQ_MODE aq_mode;
766
  // Indicates the delta q mode to be used.
767
  DELTAQ_MODE deltaq_mode;
768
  // Indicates if delta quantization should be enabled in chroma planes.
769
  bool enable_chroma_deltaq;
770
  // Indicates if encoding with quantization matrices should be enabled.
771
  bool using_qm;
772
  // Indicates whether user-defined quantization matrices should be used
773
  bool user_defined_qmatrix;
774
  bool is_ra;
775
} QuantizationCfg;
776
777
/*!\endcond */
778
/*!
779
 * \brief Algorithm configuration parameters.
780
 */
781
typedef struct {
782
  /*!
783
   * Indicates the loop filter sharpness.
784
   */
785
  int sharpness;
786
787
  /*!
788
   * Indicates the trellis optimization mode of quantized coefficients.
789
   * 0: disabled
790
   * 1: enabled for all stages
791
   * 2: enabled only for the last encoding pass
792
   * 3: disable trellis for estimate_yrd_for_sb
793
   */
794
  int enable_trellis_quant;
795
796
  /*!
797
   * The maximum number of frames used to create an arf.
798
   */
799
  int arnr_max_frames;
800
801
  /*!
802
   * The temporal filter strength for arf used when creating ARFs.
803
   */
804
  int arnr_strength;
805
806
  /*!
807
   * Indicates the CDF update mode
808
   * 0: no update
809
   * 1: update on every frame(default)
810
   * 2: selectively update
811
   */
812
  uint8_t cdf_update_mode;
813
814
  /*!
815
   * Indicates the cross frame CDF initialization mode
816
   * 0: cross frame initialization disabled
817
   * 1: cross frame initialization enabled
818
   */
819
  uint8_t cross_frame_cdf_init_mode;
820
821
  /*!
822
   * Indicates if RDO based on frame temporal dependency should be enabled.
823
   */
824
  bool enable_tpl_model;
825
826
  /*!
827
   * Indicates if coding of overlay frames for filtered ALTREF frames is
828
   * enabled.
829
   */
830
  bool enable_overlay;
831
} AlgoCfg;
832
/*!\cond */
833
834
typedef struct {
835
  // Indicates the codec bit-depth.
836
  avm_bit_depth_t bit_depth;
837
  // Indicates the superblock size that should be used by the encoder.
838
  avm_superblock_size_t superblock_size;
839
  // Indicates if deblocking should be enabled.
840
  bool enable_deblocking;
841
  // Indicates if CDEF should be enabled.
842
  bool enable_cdef;
843
  // Indicates if GDF should be enabled.
844
  bool enable_gdf;
845
  // Indicates if GDF unit size should match superblock size.
846
  int gdf_unit_matches_sb;
847
  // Indicates if loop restoration filter should be enabled.
848
  bool enable_restoration;
849
  // Indicates if pc_wiener in loop restoration filter should be enabled.
850
  bool enable_pc_wiener;
851
  // Indicates if nonsep wiener in loop restoration filter should be enabled.
852
  bool enable_wiener_nonsep;
853
  // Indicates if ccso should be enabled.
854
  bool enable_ccso;
855
  // Indicates if CCSO unit size should match superblock size.
856
  int ccso_unit_matches_sb;
857
  // Indicates if banding metadata should be enabled.
858
  bool enable_band_metadata;
859
  bool enable_lf_sub_pu;
860
  // Indicates if deblocking on sub block should be enabled.
861
  // Indicates if adaptive MVD resolution should be enabled.
862
  bool enable_adaptive_mvd;
863
864
  // Indicates if flexible MV resolution should be enabled.
865
  bool enable_flex_mvres;
866
867
  // Indicates if joint adaptive downsampling filter should be enabled.
868
  int select_cfl_ds_filter;
869
870
  // Indicates if joint mvd coding should be enabled.
871
  bool enable_joint_mvd;
872
  // Indicates if refineMV mode should be enabled.
873
  bool enable_refinemv;
874
  // Indicates if cfl should be enabled.
875
  bool enable_cfl_intra;
876
  // Indicates if mvd sign derivation should be enabled.
877
  bool enable_mvd_sign_derive;
878
  // enable temporal interpolated prediction
879
  int enable_tip;
880
  // enable RefineMv and OPFL for TIP frame.
881
  int enable_tip_refinemv;
882
  // enable MV trajectory tracking
883
  int enable_mv_traj;
884
  // enable a large motion search window
885
  int enable_high_motion;
886
  // enable block adaptive weighted prediction
887
  int enable_bawp;
888
  // enable compound weighted prediction
889
  int enable_cwp;
890
  // enable implicit masked blending
891
  bool enable_imp_msk_bld;
892
  // When enabled, video mode should be used even for single frame input.
893
  bool force_video_mode;
894
  // When enabled, sets monotonic_output_order_flag=1 in sequence header.
895
  bool monotonic_output_order;
896
  // Indicates if the error resiliency features should be enabled.
897
  bool g_error_resilient_mode;
898
  // Indicates if frame parallel decoding feature should be enabled.
899
  bool frame_parallel_decoding_mode;
900
  // Indicates if the input should be encoded as monochrome.
901
  bool enable_monochrome;
902
  // When enabled, the encoder will use a full header even for still pictures.
903
  // When disabled, a reduced header is used for still pictures.
904
  bool full_still_picture_hdr;
905
  int enable_tcq;
906
  // Indicates if ref_frame_mvs should be enabled at the sequence level.
907
  bool ref_frame_mvs_present;
908
  // Indicates if ref_frame_mvs should be enabled at the frame level.
909
  bool enable_ref_frame_mvs;
910
  // Indicates if 1 reference frame combination is used for temporal mv
911
  // prediction.
912
  int reduced_ref_frame_mvs_mode;
913
  // Indicates if global motion should be enabled.
914
  bool enable_global_motion;
915
  // Indicates if skip mode should be enabled.
916
  bool enable_skip_mode;
917
  // Indicates if palette should be enabled.
918
  bool enable_palette;
919
  unsigned int max_drl_refmvs;
920
  unsigned int max_drl_refbvs;
921
  // Indicates if ref MV Bank should be enabled.
922
  bool enable_refmvbank;
923
  int enable_cropping_window;
924
  int crop_win_left_offset;
925
  int crop_win_right_offset;
926
  int crop_win_top_offset;
927
  int crop_win_bottom_offset;
928
  // Indicates if the reorder of DRL should be enabled.
929
  int enable_drl_reorder;
930
  // Indicates if the CDEF on skip_txfm = 1 blocks should be enabled.
931
  int enable_cdef_on_skip_txfm;
932
  // Indicates if cdf average (frame or tile) should be enabled for
933
  // initialization.
934
  // 0 : disabled
935
  // 1 : enabled
936
  bool enable_avg_cdf;
937
  // Indicates the type of cdf averaging.
938
  // 0 : frame averaging
939
  // 1 : tile averaging
940
  bool avg_cdf_type;
941
  // Indicates if optical flow refinement should be enabled
942
  avm_opfl_refine_type enable_opfl_refine;
943
  // Indicates if BRU is enabled and the mode
944
  unsigned int enable_bru;
945
  bool disable_loopfilters_across_tiles;
946
  // Indicates if parity hiding should be enabled
947
  bool enable_parity_hiding;
948
  bool enable_short_refresh_frame_flags;
949
  bool enable_ext_seg;
950
  int dpb_size;
951
  // Indicates what frame hash metadata to write
952
  unsigned int frame_hash_metadata;
953
954
  // Indicates if the hash values are written for each plane instead of the
955
  // entire frame.
956
  bool frame_hash_per_plane;
957
958
  // Indicates whether to use short metadata OBU format (1) or group format (0)
959
  unsigned int use_short_metadata;
960
961
  unsigned int scan_type_info_present_flag;
962
963
  unsigned int enable_mfh_obu_signaling;
964
  int operating_points_count;
965
966
} ToolCfg;
967
968
#define MAX_SUBGOP_CONFIGS 64
969
#define MAX_SUBGOP_STEPS 64
970
#define MAX_SUBGOP_LENGTH 32
971
972
typedef enum {
973
  FRAME_TYPE_INO_VISIBLE = 'V',
974
  FRAME_TYPE_INO_REPEAT = 'R',
975
  FRAME_TYPE_INO_SHOWEXISTING = 'S',
976
  FRAME_TYPE_OOO_FILTERED = 'F',
977
  FRAME_TYPE_OOO_UNFILTERED = 'U',
978
} FRAME_TYPE_CODE;
979
980
typedef enum {
981
  SUBGOP_IN_GOP_GENERIC = 0,
982
  SUBGOP_IN_GOP_LAST,
983
  SUBGOP_IN_GOP_FIRST,
984
  SUBGOP_IN_GOP_CODES
985
} SUBGOP_IN_GOP_CODE;
986
987
typedef struct {
988
  int8_t disp_frame_idx;
989
  FRAME_TYPE_CODE type_code;
990
  int8_t pyr_level;
991
  int8_t num_references;  // value of -1 indicates unspecified references
992
  int8_t references[INTER_REFS_PER_FRAME];
993
  int8_t refresh;  // value of -1 indicates unspecified refresh
994
                   // value of 0 indicates force no refresh
995
                   // positive value indicates refresh level
996
} SubGOPStepCfg;
997
998
typedef struct {
999
  int8_t num_frames;
1000
  SUBGOP_IN_GOP_CODE subgop_in_gop_code;
1001
  int8_t num_steps;
1002
  SubGOPStepCfg step[MAX_SUBGOP_STEPS];
1003
} SubGOPCfg;
1004
1005
typedef struct {
1006
  bool is_user_specified;
1007
  int frames_to_key;
1008
  int gf_interval;
1009
  int size;
1010
  int num_steps;
1011
  int has_key_overlay;
1012
  SUBGOP_IN_GOP_CODE pos_code;
1013
  SubGOPCfg subgop_cfg;
1014
} SubGOPInfo;
1015
1016
/*!
1017
 * \Holds subgop related info.
1018
 */
1019
typedef struct {
1020
  unsigned char is_filtered[MAX_SUBGOP_STATS_SIZE];
1021
  int pyramid_level[MAX_SUBGOP_STATS_SIZE];
1022
  int ref_frame_pyr_level[MAX_SUBGOP_STATS_SIZE][INTER_REFS_PER_FRAME];
1023
  int ref_frame_disp_order[MAX_SUBGOP_STATS_SIZE][INTER_REFS_PER_FRAME];
1024
  int is_valid_ref_frame[MAX_SUBGOP_STATS_SIZE][INTER_REFS_PER_FRAME];
1025
  int num_references[MAX_SUBGOP_STATS_SIZE];
1026
  unsigned char stat_count;
1027
} SubGOPStatsEnc;
1028
1029
/*!\endcond */
1030
/*!
1031
 * \brief  Data relating to the current GF/ARF group and the
1032
 * individual frames within the group
1033
 */
1034
typedef struct {
1035
  /*!\cond */
1036
  unsigned char is_user_specified;
1037
  unsigned char has_overlay_for_key_frame;
1038
  unsigned char index;
1039
  FRAME_UPDATE_TYPE update_type[MAX_STATIC_GF_GROUP_LENGTH];
1040
  unsigned char arf_src_offset[MAX_STATIC_GF_GROUP_LENGTH];
1041
  // The number of frames displayed so far within the GOP at a given coding
1042
  // frame.
1043
  unsigned char cur_frame_idx[MAX_STATIC_GF_GROUP_LENGTH];
1044
  unsigned char is_filtered[MAX_STATIC_GF_GROUP_LENGTH];
1045
  int layer_depth[MAX_STATIC_GF_GROUP_LENGTH];
1046
  int arf_boost[MAX_STATIC_GF_GROUP_LENGTH];
1047
  int max_layer_depth;
1048
  // Maximum layer depth that is allowed.
1049
  // Two cases:
1050
  // - If positive, out-of-order coding is allowed, and this value impacts both
1051
  //   the coding order and quality assignment of frames.
1052
  // - If zero (special case), all frames are coded in-order, and this value
1053
  //   does NOT impact quality assignment of frames. Instead, quality
1054
  //   assignment depends on other values like gf_cfg->gf_max_pyr_height,
1055
  //   gf_cfg->gf_min_pyr_height, subgop config etc, and the qualities may still
1056
  //   emulate 'layers'.
1057
  int max_layer_depth_allowed;
1058
  // This is currently only populated for AVM_Q mode
1059
  unsigned char q_val[MAX_STATIC_GF_GROUP_LENGTH];
1060
  int bit_allocation[MAX_STATIC_GF_GROUP_LENGTH];
1061
  int arf_index;  // the index in the gf group of ARF, if no arf, then -1
1062
  int size;
1063
  // Current subgop cfg being used, NULL if cfg not specified
1064
  const SubGOPCfg *subgop_cfg;
1065
  // Number of arf updates before a displayeed frame.
1066
  int arf_update_counter;
1067
  /*!\endcond */
1068
} GF_GROUP;
1069
/*!\cond */
1070
1071
typedef struct {
1072
  // Track if the last frame in a GOP has higher quality.
1073
  int arf_gf_boost_lst;
1074
  // Track if the last frame in a GOP is a olk overlay
1075
  int olk_overlay_last;
1076
} GF_STATE;
1077
1078
typedef struct {
1079
  int8_t num_configs;
1080
  SubGOPCfg config[MAX_SUBGOP_CONFIGS];
1081
} SubGOPSetCfg;
1082
1083
/*!\endcond */
1084
/*!
1085
 * \brief Main encoder configuration data structure.
1086
 */
1087
typedef struct AV2EncoderConfig {
1088
  /*!\cond */
1089
  // Configuration related to the input video.
1090
  InputCfg input_cfg;
1091
1092
  // Configuration related to frame-dimensions.
1093
  FrameDimensionCfg frm_dim_cfg;
1094
1095
  /*!\endcond */
1096
  /*!
1097
   * Encoder algorithm configuration.
1098
   */
1099
  AlgoCfg algo_cfg;
1100
1101
  /*!
1102
   * Configuration related to key-frames.
1103
   */
1104
  KeyFrameCfg kf_cfg;
1105
1106
  /*!
1107
   * Rate control configuration
1108
   */
1109
  RateControlCfg rc_cfg;
1110
  /*!\cond */
1111
1112
  // Configuration related to Quantization.
1113
  QuantizationCfg q_cfg;
1114
1115
  // Internal frame size scaling.
1116
  ResizeCfg resize_cfg;
1117
1118
  // SubGOP config.
1119
  const char *subgop_config_str;
1120
1121
  // SubGOP config.
1122
  const char *subgop_config_path;
1123
1124
  // Configuration related to encoder toolsets.
1125
  ToolCfg tool_cfg;
1126
1127
  // Configuration related to Group of frames.
1128
  GFConfig gf_cfg;
1129
1130
  // Tile related configuration parameters.
1131
  TileConfig tile_cfg;
1132
1133
  // Configuration related to Tune.
1134
  TuneCfg tune_cfg;
1135
1136
  // Configuration related to color.
1137
  ColorCfg color_cfg;
1138
1139
  // Configuration related to decoder model.
1140
  DecoderModelCfg dec_model_cfg;
1141
1142
  // Configuration related to reference frames.
1143
  RefFrameCfg ref_frm_cfg;
1144
1145
  // Configuration related to unit tests.
1146
  UnitTestCfg unit_test_cfg;
1147
1148
  // Flags related to motion mode.
1149
  MotionModeCfg motion_mode_cfg;
1150
1151
  // Flags related to intra mode search.
1152
  IntraModeCfg intra_mode_cfg;
1153
1154
  // Flags related to transform size/type.
1155
  TxfmSizeTypeCfg txfm_cfg;
1156
1157
  // Flags related to compound type.
1158
  CompoundTypeCfg comp_type_cfg;
1159
1160
  // Partition related information.
1161
  PartitionCfg part_cfg;
1162
1163
  // Configuration related to frequency of cost update.
1164
  CostUpdateFreq cost_upd_freq;
1165
1166
#if CONFIG_DENOISE
1167
  // Indicates the noise level.
1168
  float noise_level;
1169
  // Indicates the the denoisers block size.
1170
  int noise_block_size;
1171
#endif
1172
1173
  // Bit mask to specify which tier each of the 32 possible operating points
1174
  // conforms to.
1175
  unsigned int tier_mask;
1176
1177
  // Indicates the number of pixels off the edge of a reference frame we're
1178
  // allowed to go when forming an inter prediction.
1179
  int border_in_pixels;
1180
1181
  // Indicates the maximum number of threads that may be used by the encoder.
1182
  int max_threads;
1183
1184
  // Indicates the spped preset to be used.
1185
  int speed;
1186
1187
  // Indicates the target sequence level index for each operating point(OP).
1188
  AV2_LEVEL target_seq_level_idx[MAX_NUM_OPERATING_POINTS];
1189
1190
  // Indicates the bitstream profile to be used.
1191
  BITSTREAM_PROFILE profile;
1192
1193
  /*!\endcond */
1194
  /*!
1195
   * Indicates the current encoder pass :
1196
   * 0 = 1 Pass encode,
1197
   * 1 = First pass of two pass,
1198
   * 2 = Second pass of two pass.
1199
   *
1200
   */
1201
  enum avm_enc_pass pass;
1202
  /*!\cond */
1203
1204
  // Indicates encoding mode. Currently, only GOOD mode is supported.
1205
  MODE mode;
1206
1207
  // Indicates if row-based multi-threading should be enabled or not.
1208
  bool row_mt;
1209
1210
  // Configuration related to layering information.
1211
  LayerCfg layer_cfg;
1212
1213
  // Number of operating points per OPS, in the range 0 to MAX_OPS_COUNT (7).
1214
  int operating_points_count;
1215
1216
  // Enable the low complexity decode mode.
1217
  unsigned int enable_low_complexity_decode;
1218
  /*!\endcond */
1219
} AV2EncoderConfig;
1220
1221
/*!\cond */
1222
0
static INLINE int is_lossless_requested(const RateControlCfg *const rc_cfg) {
1223
0
  return rc_cfg->best_allowed_q == 0 && rc_cfg->worst_allowed_q == 0;
1224
0
}
1225
/*!\endcond */
1226
1227
/*!
1228
 * \brief Encoder-side probabilities for pruning of various AV2 tools
1229
 */
1230
typedef struct {
1231
  /*!
1232
   * warped_probs[i] is the probability of warped motion being the best motion
1233
   * mode for ith frame update type, averaged over past frames. If
1234
   * warped_probs[i] < thresh, then warped motion search is pruned.
1235
   */
1236
  int warped_probs[FRAME_UPDATE_TYPES];
1237
1238
  /*!
1239
   * tx_type_probs[i][j][k] is the probability of kth tx_type being the best
1240
   * for jth transform size and ith frame update type, averaged over past
1241
   * frames. If tx_type_probs[i][j][k] < thresh, then transform search for that
1242
   * type is pruned.
1243
   */
1244
  int tx_type_probs[FRAME_UPDATE_TYPES][TX_SIZES_ALL][TX_TYPES];
1245
} FrameProbInfo;
1246
1247
#if CONFIG_ENTROPY_STATS
1248
typedef struct {
1249
  unsigned int amvd_indices_cnts[CDF_SIZE(MAX_AMVD_INDEX)];  // placeholder
1250
  unsigned int sign_cnts[CDF_SIZE(2)];                       // placeholder
1251
} nmv_component_count;
1252
1253
typedef struct {
1254
  unsigned int joint_shell_set_cnts[CDF_SIZE(2)];
1255
  unsigned int joint_shell_class_0_cnts[NUM_MV_PRECISIONS]
1256
                                       [CDF_SIZE(FIRST_SHELL_CLASS)];
1257
  unsigned int joint_shell_class_1_cnts[NUM_MV_PRECISIONS]
1258
                                       [CDF_SIZE(SECOND_SHELL_CLASS)];
1259
  unsigned int joint_shell_last_two_classes_cnts[CDF_SIZE(2)];  // placeholder
1260
  unsigned int shell_offset_low_class_cnts[2][CDF_SIZE(2)];     // placeholder
1261
  unsigned int shell_offset_class2_cnts[3][CDF_SIZE(2)];  // // placeholder
1262
  unsigned int shell_offset_other_class_cnts[NUM_CTX_CLASS_OFFSETS]
1263
                                            [SHELL_INT_OFFSET_BIT]
1264
                                            [CDF_SIZE(2)];  // placeholder
1265
  unsigned int col_mv_greater_flags_cnts[NUM_CTX_COL_MV_GTX]
1266
                                        [CDF_SIZE(2)];  // placeholder
1267
  unsigned int col_mv_index_cnts[NUM_CTX_COL_MV_INDEX]
1268
                                [CDF_SIZE(2)];         // placeholder
1269
  unsigned int amvd_joints_cnts[CDF_SIZE(MV_JOINTS)];  // placeholder
1270
  nmv_component_count mvd_comp_cnts[2];
1271
} nmv_context_count;
1272
#endif  // CONFIG_ENTROPY_STATS
1273
1274
/*!\cond */
1275
1276
typedef struct FRAME_COUNTS {
1277
// Note: This structure should only contain 'unsigned int' fields, or
1278
// aggregates built solely from 'unsigned int' fields/elements
1279
#if CONFIG_ENTROPY_STATS
1280
  // TODO(urvang, alican): The below are placeholder counters for missing CDF
1281
  // entries for memory optimization code. These are not currently incremented
1282
  // at the encoder to be able to train CDF entries with
1283
  // "avm_entropy_optimizers", these counters will need be incremented properly.
1284
  unsigned int delta_q_cnts[CDF_SIZE(DELTA_Q_PROBS + 1)];   // placeholder
1285
  unsigned int stx_cnts[2][TX_SIZES][CDF_SIZE(STX_TYPES)];  // placeholder
1286
  unsigned int stx_set_cnts[CDF_SIZE(IST_SET_SIZE)];        // placeholder
1287
  unsigned int pb_mv_mpp_flag_cnts[NUM_MV_PREC_MPP_CONTEXT]
1288
                                  [CDF_SIZE(2)];  // placeholder
1289
  unsigned int pb_mv_precision_cnts[MV_PREC_DOWN_CONTEXTS]
1290
                                   [NUM_PB_FLEX_QUALIFIED_MAX_PREC][CDF_SIZE(
1291
                                       FLEX_MV_COSTS_SIZE)];  // placeholder
1292
  unsigned int seg_tree_cnts[CDF_SIZE(MAX_SEGMENTS)];         // placeholder
1293
  unsigned int segment_pred_cnts[SEG_TEMPORAL_PRED_CTXS]
1294
                                [CDF_SIZE(2)];  // placeholder
1295
  unsigned int spatial_pred_seg_tree_cnts[SPATIAL_PREDICTION_PROBS][CDF_SIZE(
1296
      MAX_SEGMENTS)];  // placeholder
1297
1298
  nmv_context_count nmvc_cnts;  // For MVD
1299
  nmv_context_count ndvc_cnts;  // For block vector of IBC mode
1300
1301
  unsigned int y_mode_set_idx[INTRA_MODE_SETS];
1302
  unsigned int y_mode_idx[Y_MODE_CONTEXTS][LUMA_INTRA_MODE_INDEX_COUNT];
1303
  unsigned int y_mode_idx_offset[Y_MODE_CONTEXTS][LUMA_INTRA_MODE_OFFSET_COUNT];
1304
  unsigned int uv_mode[UV_MODE_CONTEXTS][CHROMA_INTRA_MODE_INDEX_COUNT];
1305
  unsigned int cfl_mode[CFL_CONTEXTS][2];
1306
  unsigned int fsc_mode[FSC_MODE_CONTEXTS][FSC_BSIZE_CONTEXTS][FSC_MODES];
1307
  unsigned int mrl_index[MRL_INDEX_CONTEXTS][MRL_LINE_NUMBER];
1308
  unsigned int multi_line_mrl[MRL_INDEX_CONTEXTS][2];
1309
  unsigned int cfl_index[CFL_TYPE_COUNT];
1310
  unsigned int refinemv_flag_cnts[NUM_REFINEMV_CTX]
1311
                                 [REFINEMV_NUM_MODES];  // placeholder
1312
1313
  unsigned int inter_warp_cnts[WARPMV_MODE_CONTEXT][2];  // placeholder
1314
  unsigned int is_warpmv_or_warp_newmv_cnt[2];
1315
1316
  unsigned int cfl_sign[CFL_JOINT_SIGNS];
1317
  unsigned int cfl_alpha[CFL_ALPHA_CONTEXTS][CFL_ALPHABET_SIZE];
1318
1319
  unsigned int identity_row_y_cnts[PALETTE_ROW_FLAG_CONTEXTS]
1320
                                  [3];  // placeholder
1321
  unsigned int identity_row_uv_cnts[PALETTE_ROW_FLAG_CONTEXTS]
1322
                                   [3];    // placeholder
1323
  unsigned int palette_direction_cnts[2];  // placeholder
1324
1325
  unsigned int palette_y_mode[2];
1326
  unsigned int palette_uv_mode[2];
1327
  unsigned int palette_y_size[PALETTE_SIZES];
1328
  unsigned int palette_uv_size[PALETTE_SIZES];
1329
  unsigned int palette_y_color_index[PALETTE_SIZES]
1330
                                    [PALETTE_COLOR_INDEX_CONTEXTS]
1331
                                    [PALETTE_COLORS];
1332
  unsigned int palette_uv_color_index[PALETTE_SIZES]
1333
                                     [PALETTE_COLOR_INDEX_CONTEXTS]
1334
                                     [PALETTE_COLORS];
1335
  unsigned int region_type[INTER_SDP_BSIZE_GROUP][REGION_TYPES];
1336
  unsigned int do_split[PARTITION_STRUCTURE_NUM][PARTITION_CONTEXTS][2];
1337
  unsigned int do_square_split[PARTITION_STRUCTURE_NUM][SQUARE_SPLIT_CONTEXTS]
1338
                              [2];
1339
  unsigned int rect_type[PARTITION_STRUCTURE_NUM][PARTITION_CONTEXTS][2];
1340
  unsigned int do_ext_partition[PARTITION_STRUCTURE_NUM][NUM_RECT_PARTS]
1341
                               [PARTITION_CONTEXTS][2];
1342
  unsigned int do_uneven_4way_partition[PARTITION_STRUCTURE_NUM][NUM_RECT_PARTS]
1343
                                       [PARTITION_CONTEXTS][2];
1344
  unsigned int uneven_4way_partition_type[PARTITION_STRUCTURE_NUM]
1345
                                         [NUM_RECT_PARTS][PARTITION_CONTEXTS]
1346
                                         [NUM_UNEVEN_4WAY_PARTS];
1347
  unsigned int txb_skip[TOKEN_CDF_Q_CTXS][TX_SIZES][TXB_SKIP_CONTEXTS][2];
1348
  unsigned int v_txb_skip[TOKEN_CDF_Q_CTXS][V_TXB_SKIP_CONTEXTS][2];
1349
  unsigned int eob_extra[TOKEN_CDF_Q_CTXS][2];
1350
  unsigned int dc_sign[TOKEN_CDF_Q_CTXS][PLANE_TYPES][DC_SIGN_GROUPS]
1351
                      [DC_SIGN_CONTEXTS][2];
1352
  unsigned int coeff_base_bob_multi[TOKEN_CDF_Q_CTXS][FSC_TX_SIZE_CONTEXTS]
1353
                                   [SIG_COEF_CONTEXTS_BOB][NUM_BASE_LEVELS + 1];
1354
  unsigned int idtx_sign[TOKEN_CDF_Q_CTXS][FSC_TX_SIZE_CONTEXTS]
1355
                        [IDTX_SIGN_CONTEXTS][2];
1356
  unsigned int coeff_lps_skip[FSC_TX_SIZE_CONTEXTS][BR_CDF_SIZE - 1]
1357
                             [IDTX_LEVEL_CONTEXTS][2];
1358
  unsigned int coeff_lps_multi_skip[TOKEN_CDF_Q_CTXS][FSC_TX_SIZE_CONTEXTS]
1359
                                   [IDTX_LEVEL_CONTEXTS][BR_CDF_SIZE];
1360
  unsigned int coeff_base_multi_skip[TOKEN_CDF_Q_CTXS][FSC_TX_SIZE_CONTEXTS]
1361
                                    [IDTX_SIG_COEF_CONTEXTS]
1362
                                    [NUM_BASE_LEVELS + 2];
1363
1364
  unsigned int eob_flag[TX_SIZES][PLANE_TYPES][EOB_COEF_CONTEXTS][2];
1365
  unsigned int eob_multi16[TOKEN_CDF_Q_CTXS][EOB_PLANE_CTXS][EOB_MAX_SYMS - 6];
1366
  unsigned int eob_multi32[TOKEN_CDF_Q_CTXS][EOB_PLANE_CTXS][EOB_MAX_SYMS - 5];
1367
  unsigned int eob_multi64[TOKEN_CDF_Q_CTXS][EOB_PLANE_CTXS][EOB_MAX_SYMS - 4];
1368
  unsigned int eob_multi128[TOKEN_CDF_Q_CTXS][EOB_PLANE_CTXS][EOB_MAX_SYMS - 3];
1369
  unsigned int eob_multi256[TOKEN_CDF_Q_CTXS][EOB_PLANE_CTXS]
1370
                           [EOB_PT_INDEX_COUNT];
1371
  unsigned int eob_multi512[TOKEN_CDF_Q_CTXS][EOB_PLANE_CTXS]
1372
                           [EOB_PT_INDEX_COUNT];
1373
  unsigned int eob_multi1024[TOKEN_CDF_Q_CTXS][EOB_PLANE_CTXS]
1374
                            [EOB_PT_INDEX_COUNT];
1375
1376
  unsigned int coeff_lps_lf[BR_CDF_SIZE - 1][LF_LEVEL_CONTEXTS][2];
1377
  unsigned int coeff_base_lf_multi[TOKEN_CDF_Q_CTXS][TX_SIZES]
1378
                                  [LF_SIG_COEF_CONTEXTS][TCQ_CTXS]
1379
                                  [LF_BASE_SYMBOLS];
1380
  unsigned int coeff_base_lf_eob_multi[TOKEN_CDF_Q_CTXS][TX_SIZES]
1381
                                      [SIG_COEF_CONTEXTS_EOB]
1382
                                      [LF_BASE_SYMBOLS - 1];
1383
  unsigned int coeff_lps_lf_multi[TOKEN_CDF_Q_CTXS][LF_LEVEL_CONTEXTS]
1384
                                 [BR_CDF_SIZE];
1385
  unsigned int coeff_lps_multi[TOKEN_CDF_Q_CTXS][LEVEL_CONTEXTS][BR_CDF_SIZE];
1386
1387
  unsigned int coeff_base_ph_multi[TOKEN_CDF_Q_CTXS][COEFF_BASE_PH_CONTEXTS]
1388
                                  [NUM_BASE_LEVELS + 2];
1389
  unsigned int coeff_lps_ph[BR_CDF_SIZE - 1][COEFF_BR_PH_CONTEXTS][2];
1390
  unsigned int coeff_lps_ph_multi[TOKEN_CDF_Q_CTXS][COEFF_BR_PH_CONTEXTS]
1391
                                 [BR_CDF_SIZE];
1392
  // LF Base, BR UV
1393
  unsigned int coeff_base_lf_multi_uv[TOKEN_CDF_Q_CTXS][LF_SIG_COEF_CONTEXTS_UV]
1394
                                     [LF_BASE_SYMBOLS];
1395
  unsigned int coeff_lps_lf_multi_uv[TOKEN_CDF_Q_CTXS][LF_LEVEL_CONTEXTS_UV]
1396
                                    [BR_CDF_SIZE];
1397
  // HF Base, BR UV
1398
  unsigned int coeff_base_multi_uv[TOKEN_CDF_Q_CTXS][SIG_COEF_CONTEXTS_UV]
1399
                                  [NUM_BASE_LEVELS + 2];
1400
  unsigned int coeff_lps_multi_uv[TOKEN_CDF_Q_CTXS][LEVEL_CONTEXTS_UV]
1401
                                 [BR_CDF_SIZE];
1402
  // LF, HF EOB UV
1403
  unsigned int coeff_base_lf_eob_multi_uv[TOKEN_CDF_Q_CTXS]
1404
                                         [SIG_COEF_CONTEXTS_EOB]
1405
                                         [LF_BASE_SYMBOLS - 1];
1406
  unsigned int coeff_base_eob_multi_uv[TOKEN_CDF_Q_CTXS][SIG_COEF_CONTEXTS_EOB]
1407
                                      [NUM_BASE_LEVELS + 1];
1408
1409
  unsigned int coeff_lps[TX_SIZES][BR_CDF_SIZE - 1][LEVEL_CONTEXTS][2];
1410
  unsigned int coeff_base_multi[TOKEN_CDF_Q_CTXS][TX_SIZES][SIG_COEF_CONTEXTS]
1411
                               [TCQ_CTXS][NUM_BASE_LEVELS + 2];
1412
  unsigned int coeff_base_eob_multi[TOKEN_CDF_Q_CTXS][TX_SIZES]
1413
                                   [SIG_COEF_CONTEXTS_EOB][NUM_BASE_LEVELS + 1];
1414
1415
  unsigned int inter_single_mode[INTER_MODE_CONTEXTS][INTER_SINGLE_MODES];
1416
1417
  unsigned int warp_ref_cnts[3][WARP_REF_CONTEXTS][2];  // placeholder
1418
1419
  unsigned int drl_mode[3][DRL_MODE_CONTEXTS][2];
1420
  unsigned int skip_drl_cnts[3][2];
1421
  unsigned int tip_drl_mode[3][2];
1422
1423
  unsigned int
1424
      jmvd_scale_mode_cnts[JOINT_NEWMV_SCALE_FACTOR_CNT];  // placeholder
1425
  unsigned int
1426
      jmvd_amvd_scale_mode_cnts[JOINT_AMVD_SCALE_FACTOR_CNT];  // placeholder
1427
1428
  unsigned int cwp_idx_cnts[MAX_CWP_CONTEXTS][MAX_CWP_NUM - 1]
1429
                           [2];  // placeholder
1430
  unsigned int use_optflow[INTER_MODE_CONTEXTS][2];
1431
1432
  unsigned int inter_compound_mode_is_joint[NUM_CTX_IS_JOINT]
1433
                                           [NUM_OPTIONS_IS_JOINT];
1434
  unsigned int inter_compound_mode_non_joint_type[NUM_CTX_NON_JOINT_TYPE]
1435
                                                 [NUM_OPTIONS_NON_JOINT_TYPE];
1436
  unsigned int inter_compound_mode_joint_type[NUM_CTX_JOINT_TYPE]
1437
                                             [NUM_OPTIONS_JOINT_TYPE];
1438
1439
  unsigned int
1440
      inter_compound_mode_same_refs_cnt[INTER_MODE_CONTEXTS]
1441
                                       [INTER_COMPOUND_SAME_REFS_TYPES];
1442
  unsigned int amvd_mode[NUM_AMVD_MODES][AMVD_MODE_CONTEXTS][2];
1443
  unsigned int wedge_quad_cnt[WEDGE_QUADS];
1444
  unsigned int wedge_angle_cnt[WEDGE_QUADS][QUAD_WEDGE_ANGLES];
1445
  unsigned int wedge_dist_cnt[NUM_WEDGE_DIST];
1446
  unsigned int wedge_dist2_cnt[NUM_WEDGE_DIST - 1];
1447
  unsigned int interintra[BLOCK_SIZE_GROUPS][2];
1448
  unsigned int interintra_mode[BLOCK_SIZE_GROUPS][INTERINTRA_MODES];
1449
  unsigned int wedge_interintra[2];
1450
  unsigned int compound_type[MASKED_COMPOUND_TYPES];
1451
  unsigned int warp_causal_cnt[WARP_CAUSAL_MODE_CTX][2];
1452
  unsigned int warpmv_with_mvd_flag[CDF_SIZE(2)];
1453
  unsigned int warp_delta_param[2][WARP_DELTA_NUMSYMBOLS_LOW];
1454
  unsigned int warp_delta_param_high[2][WARP_DELTA_NUMSYMBOLS_HIGH];
1455
  unsigned int warp_extend[WARP_EXTEND_CTX][2];
1456
  unsigned int intra_inter[INTRA_INTER_CONTEXTS][2];
1457
  int8_t cwp_idx[MAX_CWP_NUM - 1][2];
1458
  unsigned int bawp[2];
1459
  unsigned int tip_ref[TIP_CONTEXTS][2];
1460
  unsigned int tip_pred_mode_cnt[TIP_PRED_MODES];
1461
  unsigned int comp_inter[COMP_INTER_CONTEXTS][2];
1462
  unsigned int single_ref[REF_CONTEXTS][INTER_REFS_PER_FRAME - 1][2];
1463
  unsigned int comp_ref0[REF_CONTEXTS][INTER_REFS_PER_FRAME - 1][2];
1464
  unsigned int comp_ref1[REF_CONTEXTS][COMPREF_BIT_TYPES]
1465
                        [INTER_REFS_PER_FRAME - 1][2];
1466
  unsigned int intrabc[INTRABC_CONTEXTS][2];
1467
  unsigned int intrabc_mode[2];
1468
  unsigned int intrabc_drl_idx[MAX_REF_BV_STACK_SIZE - 1][2];
1469
  unsigned int morph_pred_count[3][2];
1470
  unsigned int txfm_do_partition[FSC_MODES][2][TXFM_SPLIT_GROUP][2];
1471
  unsigned int txfm_4way_partition_type[FSC_MODES][2]
1472
                                       [TX_PARTITION_TYPE_NUM_VERT_AND_HORZ]
1473
                                       [TX_PARTITION_TYPE_NUM];
1474
  unsigned int
1475
      txfm_2or3_way_partition_type[FSC_MODES][2]
1476
                                  [TX_PARTITION_TYPE_NUM_VERT_OR_HORZ - 1][2];
1477
  unsigned int skip_mode_cnts[SKIP_MODE_CONTEXTS][2];
1478
  unsigned int skip_txfm[SKIP_CONTEXTS][2];
1479
  unsigned int comp_group_idx[COMP_GROUP_IDX_CONTEXTS][2];
1480
  unsigned int delta_q[DELTA_Q_PROBS][2];
1481
  unsigned int switchable_flex_restore_cnts[MAX_LR_FLEX_SWITCHABLE_BITS]
1482
                                           [MAX_MB_PLANE][2];  // placeholder
1483
  unsigned int default_ccso_cnts[3][CCSO_CONTEXT][2];
1484
  unsigned int cdef_strength_index0_cnts[CDEF_STRENGTH_INDEX0_CTX][2];
1485
  unsigned int cdef_cnts[CDEF_STRENGTHS_NUM - 1][CDEF_STRENGTHS_NUM];
1486
  unsigned int inter_tx_type_set[2][EOB_TX_CTXS][EXT_TX_SIZES][2];
1487
  unsigned int inter_tx_type_idx[2][EOB_TX_CTXS][INTER_TX_TYPE_INDEX_COUNT];
1488
  unsigned int inter_tx_type_offset_1[EOB_TX_CTXS][INTER_TX_TYPE_OFFSET1_COUNT];
1489
  unsigned int inter_tx_type_offset_2[EOB_TX_CTXS][INTER_TX_TYPE_OFFSET2_COUNT];
1490
  unsigned int inter_ext_tx[EXT_TX_SETS_INTER][EOB_TX_CTXS][EXT_TX_SIZES]
1491
                           [TX_TYPES];
1492
  unsigned int intra_ext_tx[EXT_TX_SETS_INTRA][EXT_TX_SIZES][TX_TYPES];
1493
  unsigned int tx_ext_32[2][2];
1494
  unsigned int intra_ext_tx_short_side[EXT_TX_SIZES][4];
1495
  unsigned int inter_ext_tx_short_side[EOB_TX_CTXS][EXT_TX_SIZES][4];
1496
  unsigned int cctx_type[CCTX_TYPES];
1497
  unsigned int filter_intra[2];
1498
  unsigned int intra_dip[TOKEN_CDF_Q_CTXS][DIP_CTXS][2];
1499
  unsigned int intra_dip_mode_n6[6];
1500
  unsigned int switchable_restore[RESTORE_SWITCHABLE_TYPES];
1501
  unsigned int wienerns_4part_cnts[WIENERNS_4PART_CTX_MAX]
1502
                                  [CDF_SIZE(4)];  // placeholder
1503
  unsigned int wienerns_length[2];                // placeholder
1504
  unsigned int merged_param_cnts[2];              // placeholder
1505
  unsigned int pc_wiener_restore[2];
1506
  unsigned int wienerns_restore[2];
1507
#endif  // CONFIG_ENTROPY_STATS
1508
  unsigned int switchable_interp[SWITCHABLE_FILTER_CONTEXTS]
1509
                                [SWITCHABLE_FILTERS];
1510
} FRAME_COUNTS;
1511
1512
#define INTER_MODE_RD_DATA_OVERALL_SIZE 6400
1513
1514
typedef struct {
1515
  int ready;
1516
  double a;
1517
  double b;
1518
  double dist_mean;
1519
  double ld_mean;
1520
  double sse_mean;
1521
  double sse_sse_mean;
1522
  double sse_ld_mean;
1523
  int num;
1524
  double dist_sum;
1525
  double ld_sum;
1526
  double sse_sum;
1527
  double sse_sse_sum;
1528
  double sse_ld_sum;
1529
} InterModeRdModel;
1530
1531
typedef struct {
1532
  int idx;
1533
  int64_t rd;
1534
} RdIdxPair;
1535
// TODO(angiebird): This is an estimated size. We still need to figure what is
1536
// the maximum number of modes.
1537
1538
#define MAX_INTER_MODES 1536 * 6
1539
1540
// TODO(any): rename this struct to something else. There is already another
1541
// struct called inter_mode_info, which makes this terribly confusing.
1542
/*!\endcond */
1543
/*!
1544
 * \brief Struct used to hold inter mode data for fast tx search.
1545
 *
1546
 * This struct is used to perform a full transform search only on winning
1547
 * candidates searched with an estimate for transform coding RD.
1548
 */
1549
typedef struct inter_modes_info {
1550
  /*!
1551
   * The number of inter modes for which data was stored in each of the
1552
   * following arrays.
1553
   */
1554
  int num;
1555
  /*!
1556
   * Mode info struct for each of the candidate modes.
1557
   */
1558
  MB_MODE_INFO mbmi_arr[MAX_INTER_MODES];
1559
  /*!
1560
   * The rate for each of the candidate modes.
1561
   */
1562
  int mode_rate_arr[MAX_INTER_MODES];
1563
  /*!
1564
   * The sse of the predictor for each of the candidate modes.
1565
   */
1566
  int64_t sse_arr[MAX_INTER_MODES];
1567
  /*!
1568
   * The estimated rd of the predictor for each of the candidate modes.
1569
   */
1570
  int64_t est_rd_arr[MAX_INTER_MODES];
1571
  /*!
1572
   * The rate and mode index for each of the candidate modes.
1573
   */
1574
  RdIdxPair rd_idx_pair_arr[MAX_INTER_MODES];
1575
} InterModesInfo;
1576
1577
/*!\cond */
1578
typedef struct {
1579
  // This struct is used for computing variance in choose_partitioning(), where
1580
  // the max number of samples within a superblock is 32x32 (with 4x4 avg).
1581
  // uint64_t is used for sum_square_error to prevent overflow in high bitdepth
1582
  // mode.
1583
  uint64_t sum_square_error;
1584
  int32_t sum_error;
1585
  int log2_count;
1586
  int variance;
1587
} VPartVar;
1588
1589
typedef struct {
1590
  VPartVar none;
1591
  VPartVar horz[2];
1592
  VPartVar vert[2];
1593
} VPVariance;
1594
1595
typedef struct {
1596
  VPVariance part_variances;
1597
  VPartVar split[4];
1598
} VP4x4;
1599
1600
typedef struct {
1601
  VPVariance part_variances;
1602
  VP4x4 split[4];
1603
} VP8x8;
1604
1605
typedef struct {
1606
  VPVariance part_variances;
1607
  VP8x8 split[4];
1608
} VP16x16;
1609
1610
typedef struct {
1611
  VPVariance part_variances;
1612
  VP16x16 split[4];
1613
} VP32x32;
1614
1615
typedef struct {
1616
  VPVariance part_variances;
1617
  VP32x32 split[4];
1618
} VP64x64;
1619
1620
typedef struct {
1621
  VPVariance part_variances;
1622
  VP64x64 *split;
1623
} VP128x128;
1624
1625
typedef struct {
1626
  VPVariance part_variances;
1627
  VP128x128 *split;
1628
} VP256x256;
1629
1630
/*!\endcond */
1631
1632
/*!
1633
 * \brief Thresholds for variance based partitioning.
1634
 */
1635
typedef struct {
1636
  /*!
1637
   * If block variance > threshold, then that block is forced to split.
1638
   * thresholds[0] - threshold for 256x256;
1639
   * thresholds[1] - threshold for 128x128;
1640
   * thresholds[2] - threshold for 64x64;
1641
   * thresholds[3] - threshold for 32x32;
1642
   * thresholds[4] - threshold for 16x16;
1643
   * thresholds[5] - threshold for 8x8;
1644
   */
1645
  int64_t thresholds[6];
1646
1647
  /*!
1648
   * MinMax variance threshold for 8x8 sub blocks of a 16x16 block. If actual
1649
   * minmax > threshold_minmax, the 16x16 is forced to split.
1650
   */
1651
  int64_t threshold_minmax;
1652
} VarBasedPartitionInfo;
1653
1654
/*!
1655
 * \brief Encoder parameters for synchronization of row based multi-threading
1656
 */
1657
typedef struct {
1658
#if CONFIG_MULTITHREAD
1659
  /**
1660
   * \name Synchronization objects for top-right dependency.
1661
   */
1662
  /**@{*/
1663
  pthread_mutex_t *mutex_; /*!< Mutex lock object */
1664
  pthread_cond_t *cond_;   /*!< Condition variable */
1665
  /**@}*/
1666
#endif  // CONFIG_MULTITHREAD
1667
  /*!
1668
   * Buffer to store the superblock whose encoding is complete.
1669
   * cur_col[i] stores the number of superblocks which finished encoding in the
1670
   * ith superblock row.
1671
   */
1672
  int *num_finished_cols;
1673
  /*!
1674
   * Number of extra superblocks of the top row to be complete for encoding
1675
   * of the current superblock to start. A value of 1 indicates top-right
1676
   * dependency.
1677
   */
1678
  int sync_range;
1679
  /*!
1680
   * Number of superblock rows.
1681
   */
1682
  int rows;
1683
  /*!
1684
   * The superblock row (in units of MI blocks) to be processed next.
1685
   */
1686
  int next_mi_row;
1687
  /*!
1688
   * Number of threads processing the current tile.
1689
   */
1690
  int num_threads_working;
1691
} AV2EncRowMultiThreadSync;
1692
1693
/*!\cond */
1694
1695
// TODO(jingning) All spatially adaptive variables should go to TileDataEnc.
1696
typedef struct TileDataEnc {
1697
  TileInfo tile_info;
1698
  DECLARE_ALIGNED(16, FRAME_CONTEXT, tctx);
1699
  FRAME_CONTEXT *row_ctx;
1700
  uint8_t allow_update_cdf;
1701
  InterModeRdModel inter_mode_rd_models[BLOCK_SIZES_ALL];
1702
  AV2EncRowMultiThreadSync row_mt_sync;
1703
  MV firstpass_top_mv;
1704
} TileDataEnc;
1705
1706
typedef struct RD_COUNTS {
1707
  int64_t comp_pred_diff[REFERENCE_MODES];
1708
  int compound_ref_used_flag;
1709
  int skip_mode_used_flag;
1710
  int tx_type_used[TX_SIZES_ALL][TX_TYPES];
1711
  int warped_used[2];
1712
} RD_COUNTS;
1713
1714
typedef struct ThreadData {
1715
  MACROBLOCK mb;
1716
  RD_COUNTS rd_counts;
1717
  FRAME_COUNTS *counts;
1718
  PC_TREE_SHARED_BUFFERS shared_coeff_buf;
1719
  SIMPLE_MOTION_DATA_TREE *sms_tree;
1720
  SIMPLE_MOTION_DATA_TREE *sms_root;
1721
  struct SimpleMotionDataBufs *sms_bufs;
1722
  BLOCK_SIZE sb_size;
1723
  uint32_t *hash_value_buffer[2][2];
1724
  PALETTE_BUFFER *palette_buffer;
1725
  CompoundTypeRdBuffers comp_rd_buffer;
1726
  CONV_BUF_TYPE *tmp_conv_dst;
1727
  // Temporary buffers used to store the OPFL MV offsets.
1728
  int *opfl_vxy_bufs;
1729
  // Temporary buffers used to store the OPFL gradient information.
1730
  int16_t *opfl_gxy_bufs;
1731
  // Temporary buffers used to store intermediate prediction data calculated
1732
  // during the OPFL/SMVR.
1733
  uint16_t *opfl_dst_bufs;
1734
  uint16_t *tmp_pred_bufs[2];
1735
  // Buffer used for upsampled prediction.
1736
  uint16_t *upsample_pred;
1737
  int intrabc_used;
1738
  int deltaq_used;
1739
  FRAME_CONTEXT *tctx;
1740
  MB_MODE_INFO_EXT *mbmi_ext;
1741
  // Buffer used to store quantized and dequantized transform coefficients.
1742
  coeff_info *coef_info;
1743
  PICK_MODE_CONTEXT *firstpass_ctx;
1744
  VP128x128 *vt128x128;
1745
  VP64x64 *vt64x64;
1746
#if CONFIG_ML_PART_SPLIT
1747
  void *partition_model;
1748
#endif  // CONFIG_ML_PART_SPLIT
1749
  void *dip_pruning_model;
1750
} ThreadData;
1751
1752
struct EncWorkerData;
1753
1754
/*!\endcond */
1755
1756
/*!
1757
 * \brief Encoder data related to row-based multi-threading
1758
 */
1759
typedef struct {
1760
  /*!
1761
   * Number of tile rows for which row synchronization memory is allocated.
1762
   */
1763
  int allocated_tile_rows;
1764
  /*!
1765
   * Number of tile cols for which row synchronization memory is allocated.
1766
   */
1767
  int allocated_tile_cols;
1768
  /*!
1769
   * Number of rows for which row synchronization memory is allocated
1770
   * per tile. During first-pass/look-ahead stage this equals the
1771
   * maximum number of macroblock rows in a tile. During encode stage,
1772
   * this equals the maximum number of superblock rows in a tile.
1773
   */
1774
  int allocated_rows;
1775
  /*!
1776
   * Number of columns for which entropy context memory is allocated
1777
   * per tile. During encode stage, this equals the maximum number of
1778
   * superblock columns in a tile minus 1. The entropy context memory
1779
   * is not allocated during first-pass/look-ahead stage.
1780
   */
1781
  int allocated_cols;
1782
1783
  /*!
1784
   * thread_id_to_tile_id[i] indicates the tile id assigned to the ith thread.
1785
   */
1786
  int thread_id_to_tile_id[MAX_NUM_THREADS];
1787
1788
  /*!
1789
   * Initialized to false, set to true by the worker thread that encounters an
1790
   * error in order to abort the processing of other worker threads.
1791
   */
1792
  bool row_mt_exit;
1793
1794
#if CONFIG_MULTITHREAD
1795
  /*!
1796
   * Mutex lock used while dispatching jobs.
1797
   */
1798
  pthread_mutex_t *mutex_;
1799
#endif
1800
1801
  /**
1802
   * \name Row synchronization related function pointers.
1803
   */
1804
  /**@{*/
1805
  /*!
1806
   * Reader.
1807
   */
1808
  void (*sync_read_ptr)(AV2EncRowMultiThreadSync *const, int, int);
1809
  /*!
1810
   * Writer.
1811
   */
1812
  void (*sync_write_ptr)(AV2EncRowMultiThreadSync *const, int, int, int);
1813
  /**@}*/
1814
} AV2EncRowMultiThreadInfo;
1815
1816
/*!
1817
 * \brief Encoder parameters related to multi-threading.
1818
 */
1819
typedef struct {
1820
  /*!
1821
   * Number of workers created for multi-threading.
1822
   */
1823
  int num_workers;
1824
1825
  /*!
1826
   * Number of workers created for tpl and tile/row multi-threading of encoder.
1827
   */
1828
  int num_enc_workers;
1829
1830
  /*!
1831
   * Number of workers created for first-pass multi-threading.
1832
   */
1833
  int num_fp_workers;
1834
1835
  /*!
1836
   * Synchronization object used to launch job in the worker thread.
1837
   */
1838
  AVxWorker *workers;
1839
1840
  /*!
1841
   * Data specific to each worker in encoder multi-threading.
1842
   * tile_thr_data[i] stores the worker data of the ith thread.
1843
   */
1844
  struct EncWorkerData *tile_thr_data;
1845
1846
  /*!
1847
   * When set, indicates that row based multi-threading of the encoder is
1848
   * enabled.
1849
   */
1850
  bool row_mt_enabled;
1851
1852
  /*!
1853
   * Encoder row multi-threading data.
1854
   */
1855
  AV2EncRowMultiThreadInfo enc_row_mt;
1856
1857
  /*!
1858
   * Tpl row multi-threading data.
1859
   */
1860
  AV2TplRowMultiThreadInfo tpl_row_mt;
1861
1862
  /*!
1863
   * Loop Filter multi-threading object.
1864
   */
1865
  AV2LfSync lf_row_sync;
1866
1867
  /*!
1868
   * Loop Restoration multi-threading object.
1869
   */
1870
  AV2LrSync lr_row_sync;
1871
1872
  /*!
1873
   * Global Motion multi-threading object.
1874
   */
1875
  AV2GlobalMotionSync gm_sync;
1876
} MultiThreadInfo;
1877
1878
/*!\cond */
1879
1880
typedef struct ActiveMap {
1881
  int enabled;
1882
  int update;
1883
  unsigned char *map;
1884
} ActiveMap;
1885
1886
/*!\endcond */
1887
1888
/*!
1889
 * \brief Encoder info used for decision on forcing integer motion vectors.
1890
 */
1891
typedef struct {
1892
  /*!
1893
   * cs_rate_array[i] is the fraction of blocks in a frame which either match
1894
   * with the collocated block or are smooth, where i is the rate_index.
1895
   */
1896
  double cs_rate_array[32];
1897
  /*!
1898
   * rate_index is used to index cs_rate_array.
1899
   */
1900
  int rate_index;
1901
  /*!
1902
   * rate_size is the total number of entries populated in cs_rate_array.
1903
   */
1904
  int rate_size;
1905
} ForceIntegerMVInfo;
1906
1907
/*!\cond */
1908
1909
#if CONFIG_INTERNAL_STATS
1910
// types of stats
1911
enum {
1912
  STAT_Y,
1913
  STAT_U,
1914
  STAT_V,
1915
  STAT_ALL,
1916
  NUM_STAT_TYPES  // This should always be the last member of the enum
1917
} UENUM1BYTE(StatType);
1918
1919
typedef struct IMAGE_STAT {
1920
  double stat[NUM_STAT_TYPES];
1921
  double worst;
1922
} ImageStat;
1923
#endif  // CONFIG_INTERNAL_STATS
1924
1925
/*!\endcond */
1926
1927
/*!
1928
 * \brief Buffer to store mode information at mi_alloc_bsize (4x4 or 8x8) level
1929
 *
1930
 * This is used for bitstream preparation.
1931
 */
1932
typedef struct {
1933
  /*!
1934
   * frame_base[mi_row * stride + mi_col] stores the mode information of
1935
   * block (mi_row,mi_col).
1936
   */
1937
  MB_MODE_INFO_EXT_FRAME *frame_base;
1938
  /*!
1939
   * Size of frame_base buffer.
1940
   */
1941
  int alloc_size;
1942
  /*!
1943
   * Stride of frame_base buffer.
1944
   */
1945
  int stride;
1946
} MBMIExtFrameBufferInfo;
1947
1948
/*!\cond */
1949
1950
#if CONFIG_COLLECT_PARTITION_STATS == 2
1951
typedef struct FramePartitionTimingStats {
1952
  int partition_decisions[BLOCK_SIZES_ALL][ALL_PARTITION_TYPES];
1953
  int partition_attempts[BLOCK_SIZES_ALL][ALL_PARTITION_TYPES];
1954
  int64_t partition_times[BLOCK_SIZES_ALL][ALL_PARTITION_TYPES];
1955
1956
  int partition_redo;
1957
} FramePartitionTimingStats;
1958
#endif  // CONFIG_COLLECT_PARTITION_STATS == 2
1959
1960
#if CONFIG_COLLECT_COMPONENT_TIMING
1961
#include "avm_ports/avm_timer.h"
1962
// Adjust the following to add new components.
1963
enum {
1964
  encode_frame_to_data_rate_time,
1965
  encode_with_recode_loop_time,
1966
  loop_filter_time,
1967
  cdef_time,
1968
  loop_restoration_time,
1969
  av2_pack_bitstream_final_time,
1970
  av2_encode_frame_time,
1971
  av2_compute_global_motion_time,
1972
  av2_setup_motion_field_time,
1973
  av2_enc_setup_tip_frame_time,
1974
  encode_sb_time,
1975
  rd_pick_partition_time,
1976
  rd_pick_sb_modes_time,
1977
  av2_rd_pick_intra_mode_sb_time,
1978
  av2_rd_pick_inter_mode_sb_time,
1979
  handle_intra_mode_time,
1980
  do_tx_search_time,
1981
  handle_newmv_time,
1982
  compound_type_rd_time,
1983
  interpolation_filter_search_time,
1984
  motion_mode_rd_time,
1985
  kTimingComponents,
1986
} UENUM1BYTE(TIMING_COMPONENT);
1987
1988
static INLINE char const *get_component_name(int index) {
1989
  switch (index) {
1990
    case encode_frame_to_data_rate_time:
1991
      return "encode_frame_to_data_rate_time";
1992
    case encode_with_recode_loop_time: return "encode_with_recode_loop_time";
1993
    case loop_filter_time: return "loop_filter_time";
1994
    case cdef_time: return "cdef_time";
1995
    case loop_restoration_time: return "loop_restoration_time";
1996
    case av2_pack_bitstream_final_time: return "av2_pack_bitstream_final_time";
1997
    case av2_encode_frame_time: return "av2_encode_frame_time";
1998
    case av2_compute_global_motion_time:
1999
      return "av2_compute_global_motion_time";
2000
    case av2_setup_motion_field_time: return "av2_setup_motion_field_time";
2001
    case av2_enc_setup_tip_frame_time: return "av2_enc_setup_tip_frame_time";
2002
    case encode_sb_time: return "encode_sb_time";
2003
    case rd_pick_partition_time: return "rd_pick_partition_time";
2004
    case rd_pick_sb_modes_time: return "rd_pick_sb_modes_time";
2005
    case av2_rd_pick_intra_mode_sb_time:
2006
      return "av2_rd_pick_intra_mode_sb_time";
2007
    case av2_rd_pick_inter_mode_sb_time:
2008
      return "av2_rd_pick_inter_mode_sb_time";
2009
    case handle_intra_mode_time: return "handle_intra_mode_time";
2010
    case do_tx_search_time: return "do_tx_search_time";
2011
    case handle_newmv_time: return "handle_newmv_time";
2012
    case compound_type_rd_time: return "compound_type_rd_time";
2013
    case interpolation_filter_search_time:
2014
      return "interpolation_filter_search_time";
2015
    case motion_mode_rd_time: return "motion_mode_rd_time";
2016
    default: assert(0);
2017
  }
2018
  return "error";
2019
}
2020
#endif
2021
2022
/*!\endcond */
2023
2024
/*!
2025
 * \brief Parameters related to global motion search
2026
 */
2027
typedef struct {
2028
  /*!
2029
   * Flag to indicate if global motion search needs to be rerun.
2030
   */
2031
  bool search_done;
2032
2033
  /*!
2034
   * Array of pointers to the frame buffers holding the reference frames.
2035
   * ref_buf[i] stores the pointer to the reference frame of the ith
2036
   * reference frame type.
2037
   */
2038
  YV12_BUFFER_CONFIG *ref_buf[INTER_REFS_PER_FRAME];
2039
2040
  /*!
2041
   * Holds the number of valid reference frames in past and future directions
2042
   * w.r.t. the current frame. num_ref_filters[i] stores the total number of
2043
   * valid reference frames in 'i' direction.
2044
   */
2045
  int num_ref_frames[MAX_DIRECTIONS];
2046
2047
  /*!
2048
   * Array of structure which stores the valid reference frames in past and
2049
   * future directions and their corresponding distance from the source frame.
2050
   * reference_frames[i][j] holds the jth valid reference frame type in the
2051
   * direction 'i' and its temporal distance from the source frame .
2052
   */
2053
  FrameDistPair reference_frames[MAX_DIRECTIONS][INTER_REFS_PER_FRAME];
2054
2055
  /**
2056
   * \name Dimensions for which segment map is allocated.
2057
   */
2058
  /**@{*/
2059
  int segment_map_w; /*!< segment map width */
2060
  int segment_map_h; /*!< segment map height */
2061
  /**@}*/
2062
2063
  /*!
2064
   * \brief Error ratio for each selected global motion model
2065
   *
2066
   * This is used to help decide which models will actually be used,
2067
   * because that decision has to be deferred until we actually select a
2068
   * base model to use
2069
   */
2070
  double erroradvantage[INTER_REFS_PER_FRAME];
2071
2072
  /**
2073
   * \name Reference path for selected base model
2074
   */
2075
  /**@{*/
2076
  int base_model_our_ref;   /*!< which of our ref frames to copy from */
2077
  int base_model_their_ref; /*!< which model to copy from that frame */
2078
  /**@}*/
2079
} GlobalMotionInfo;
2080
2081
/*!
2082
 * \brief Initial frame dimensions
2083
 *
2084
 * Tracks the frame dimensions using which:
2085
 *  - Frame buffers (like altref and util frame buffers) were allocated
2086
 *  - Motion estimation related initializations were done
2087
 * This structure is helpful to reallocate / reinitialize the above when there
2088
 * is a change in frame dimensions.
2089
 */
2090
typedef struct {
2091
  int width;  /*!< initial width */
2092
  int height; /*!< initial height */
2093
} InitialDimensions;
2094
2095
/*!
2096
 * \brief Flags related to interpolation filter search
2097
 */
2098
typedef struct {
2099
  /*!
2100
   * Stores the default value of skip flag depending on chroma format
2101
   * Set as 1 for monochrome and 3 for other color formats
2102
   */
2103
  int default_interp_skip_flags;
2104
  /*!
2105
   * Filter mask to allow certain interp_filter type.
2106
   */
2107
  uint16_t interp_filter_search_mask;
2108
} InterpSearchFlags;
2109
2110
/*!
2111
 * \brief Parameters for motion vector search process
2112
 */
2113
typedef struct {
2114
  /*!
2115
   * Largest MV component used in a frame.
2116
   * The value from the previous frame is used to set the full pixel search
2117
   * range for the current frame.
2118
   */
2119
  int max_mv_magnitude;
2120
  /*!
2121
   * Parameter indicating initial search window to be used in full-pixel search.
2122
   * Range [0, MAX_MVSEARCH_STEPS-2]. Lower value indicates larger window.
2123
   */
2124
  int mv_step_param;
2125
  /*!
2126
   * Pointer to sub-pixel search function.
2127
   * In encoder: av2_find_best_sub_pixel_tree
2128
   *             av2_find_best_sub_pixel_tree_pruned
2129
   *             av2_find_best_sub_pixel_tree_pruned_more
2130
   *             av2_find_best_sub_pixel_tree_pruned_evenmore
2131
   * In MV unit test: av2_return_max_sub_pixel_mv
2132
   *                  av2_return_min_sub_pixel_mv
2133
   */
2134
  fractional_mv_step_fp *find_fractional_mv_step;
2135
  /*!
2136
   * Search site configuration for full-pel MV search.
2137
   * search_site_cfg[SS_CFG_SRC]: Used in tpl, rd/non-rd inter mode loop, simple
2138
   * motion search. search_site_cfg[SS_CFG_LOOKAHEAD]: Used in intraBC, temporal
2139
   * filter search_site_cfg[SS_CFG_FPF]: Used during first pass and lookahead
2140
   */
2141
  search_site_config search_site_cfg[SS_CFG_TOTAL][NUM_DISTINCT_SEARCH_METHODS];
2142
} MotionVectorSearchParams;
2143
2144
/*!
2145
 * \brief Desired dimensions for an externally triggered resize.
2146
 *
2147
 * When resize is triggered externally, the desired dimensions are stored in
2148
 * this struct until used in the next frame to be coded. These values are
2149
 * effective only for one frame and are reset after they are used.
2150
 */
2151
typedef struct {
2152
  int width;  /*!< Desired resized width */
2153
  int height; /*!< Desired resized height */
2154
} ResizePendingParams;
2155
2156
/*!
2157
 * \brief Refrence frame distance related variables.
2158
 */
2159
typedef struct {
2160
  /*!
2161
   * True relative distance of reference frames w.r.t. the current frame.
2162
   */
2163
  int ref_relative_dist[INTER_REFS_PER_FRAME];
2164
  /*!
2165
   * The nearest reference w.r.t. current frame in the past.
2166
   */
2167
  int8_t nearest_past_ref;
2168
  /*!
2169
   * The nearest reference w.r.t. current frame in the future.
2170
   */
2171
  int8_t nearest_future_ref;
2172
} RefFrameDistanceInfo;
2173
2174
/*!
2175
 * \brief Parameters used for winner mode processing.
2176
 *
2177
 * This is a basic two pass approach: in the first pass, we reduce the number of
2178
 * transform searches based on some thresholds during the rdopt process to find
2179
 * the  "winner mode". In the second pass, we perform a more through tx search
2180
 * on the winner mode.
2181
 * There are some arrays in the struct, and their indices are used in the
2182
 * following manner:
2183
 * Index 0: Default mode evaluation, Winner mode processing is not applicable
2184
 * (Eg : IntraBc).
2185
 * Index 1: Mode evaluation.
2186
 * Index 2: Winner mode evaluation
2187
 * Index 1 and 2 are only used when the respective speed feature is on.
2188
 */
2189
typedef struct {
2190
  /*!
2191
   * Threshold to determine the best number of transform coefficients to keep
2192
   * using trellis optimization.
2193
   * Corresponds to enable_winner_mode_for_coeff_opt speed feature.
2194
   */
2195
  unsigned int coeff_opt_dist_threshold[MODE_EVAL_TYPES];
2196
2197
  /*!
2198
   * Threshold to determine if trellis optimization is to be enabled
2199
   * based on SATD.
2200
   * Corresponds to enable_winner_mode_for_coeff_opt speed feature.
2201
   */
2202
  unsigned int coeff_opt_satd_threshold[MODE_EVAL_TYPES];
2203
2204
  /*!
2205
   * Determines the tx size search method during rdopt.
2206
   * Corresponds to enable_winner_mode_for_tx_size_srch speed feature.
2207
   */
2208
  TX_SIZE_SEARCH_METHOD tx_size_search_methods[MODE_EVAL_TYPES];
2209
2210
  /*!
2211
   * Controls how often we should approximate prediction error with tx
2212
   * coefficients. If it's 0, then never. If 1, then it's during the tx_type
2213
   * search only. If 2, then always.
2214
   * Corresponds to tx_domain_dist_level speed feature.
2215
   */
2216
  unsigned int use_transform_domain_distortion[MODE_EVAL_TYPES];
2217
2218
  /*!
2219
   * Threshold to approximate pixel domain distortion with transform domain
2220
   * distortion. This is only used if use_txform_domain_distortion is on.
2221
   * Corresponds to enable_winner_mode_for_use_tx_domain_dist speed feature.
2222
   */
2223
  unsigned int tx_domain_dist_threshold[MODE_EVAL_TYPES];
2224
2225
  /*!
2226
   * Controls how often we should try to skip the transform process based on
2227
   * result from dct.
2228
   * Corresponds to use_skip_flag_prediction speed feature.
2229
   */
2230
  unsigned int skip_txfm_level[MODE_EVAL_TYPES];
2231
2232
  /*!
2233
   * Predict DC only txfm blocks for default, mode and winner mode evaluation.
2234
   * Index 0: Default mode evaluation, Winner mode processing is not applicable.
2235
   * Index 1: Mode evaluation, Index 2: Winner mode evaluation
2236
   */
2237
  unsigned int predict_dc_level[MODE_EVAL_TYPES];
2238
} WinnerModeParams;
2239
2240
/*!
2241
 * \brief Frame refresh flags set by the external interface.
2242
 *
2243
 * Flags set by external interface to determine which reference buffers are
2244
 * refreshed by this frame. When set, the encoder will update the particular
2245
 * reference frame buffer with the contents of the current frame.
2246
 */
2247
typedef struct {
2248
  bool all_ref_frames; /*!< Refresh all refs */
2249
  /*!
2250
   * Flag indicating if the update of refresh frame flags is pending.
2251
   */
2252
  bool update_pending;
2253
} ExtRefreshFrameFlagsInfo;
2254
2255
/*!
2256
 * \brief Flags signalled by the external interface at frame level.
2257
 */
2258
typedef struct {
2259
  /*!
2260
   * Bit mask to disable certain reference frame types.
2261
   */
2262
  int ref_frame_flags;
2263
2264
  /*!
2265
   * Frame refresh flags set by the external interface.
2266
   */
2267
  ExtRefreshFrameFlagsInfo refresh_frame;
2268
2269
  /*!
2270
   * Flag to enable CDF initialization with cross frame contexts at the
2271
   * beginning of a frame decode.
2272
   */
2273
  bool cross_frame_context;
2274
  /*!
2275
   * Flag to enable temporal MV prediction.
2276
   */
2277
  bool use_ref_frame_mvs;
2278
2279
  /*!
2280
   * Indicates whether the current frame is to be coded as s-frame.
2281
   */
2282
  bool use_s_frame;
2283
2284
  /*!
2285
   * Indicates whether the current frame's primary_ref_frame is set to
2286
   * PRIMARY_REF_NONE.
2287
   */
2288
  bool use_primary_ref_none;
2289
} ExternalFlags;
2290
2291
/*!\cond */
2292
2293
typedef struct {
2294
  // Some misc info
2295
  int high_prec;
2296
  int q;
2297
  int order;
2298
2299
  // MV counters
2300
  int inter_count;
2301
  int intra_count;
2302
  int default_mvs;
2303
  int mv_joint_count[4];
2304
  int last_bit_zero;
2305
  int last_bit_nonzero;
2306
2307
  // Keep track of the rates
2308
  int total_mv_rate;
2309
  int hp_total_mv_rate;
2310
  int lp_total_mv_rate;
2311
2312
  // Texture info
2313
  int horz_text;
2314
  int vert_text;
2315
  int diag_text;
2316
2317
  // precision
2318
  int precision_count[NUM_MV_PRECISIONS];
2319
  // Whether the current struct contains valid data
2320
  int valid;
2321
} MV_STATS;
2322
2323
typedef struct {
2324
  struct loopfilter lf;
2325
  CdefInfo cdef_info;
2326
  YV12_BUFFER_CONFIG copy_buffer;
2327
  RATE_CONTROL rc;
2328
  MV_STATS mv_stats;
2329
  FeatureFlags features;
2330
} CODING_CONTEXT;
2331
2332
typedef struct {
2333
  int frame_width;
2334
  int frame_height;
2335
  int mi_rows;
2336
  int mi_cols;
2337
  int mb_rows;
2338
  int mb_cols;
2339
  int num_mbs;
2340
  avm_bit_depth_t bit_depth;
2341
  int subsampling_x;
2342
  int subsampling_y;
2343
} FRAME_INFO;
2344
2345
/*!\endcond */
2346
2347
/*!
2348
 * \brief Segmentation related information for the current frame.
2349
 */
2350
typedef struct {
2351
  /*!
2352
   * 3-bit number containing the segment affiliation for each 4x4 block in the
2353
   * frame. map[y * stride + x] contains the segment id of the 4x4 block at
2354
   * (x,y) position.
2355
   */
2356
  uint8_t *map;
2357
  /*!
2358
   * Flag to indicate if current frame has lossless segments or not.
2359
   * 1: frame has at least one lossless segment.
2360
   * 0: frame has no lossless segments.
2361
   */
2362
  bool has_lossless_segment;
2363
} EncSegmentationInfo;
2364
2365
/*!
2366
 * \brief Frame time stamps.
2367
 */
2368
typedef struct {
2369
  /*!
2370
   * Start time stamp of the previous frame
2371
   */
2372
  int64_t prev_start_seen;
2373
  /*!
2374
   * End time stamp of the previous frame
2375
   */
2376
  int64_t prev_end_seen;
2377
  /*!
2378
   * Start time stamp of the first frame
2379
   */
2380
  int64_t first_ever;
2381
} TimeStamps;
2382
2383
/*!\cond */
2384
2385
// Define 2 extra indices for 4x64 and 64x4 block sizes, for use with
2386
// `AV2_COMP.fn_ptr` array below. This is because this array may be used for any
2387
// transform or coding block size. So, we need these 2 extra sizes that exist
2388
// for transform blocks, but NOT for coding blocks.
2389
#define BLOCK_4X64 BLOCK_SIZES_ALL
2390
#define BLOCK_64X4 (BLOCK_4X64 + 1)
2391
#define ENCODER_BLOCK_SIZES_ALL (BLOCK_64X4 + 1)
2392
2393
// Used to get block size index for `AV2_COMP.fn_ptr` array.
2394
static const int enc_txsize_to_bsize[TX_SIZES_ALL] = {
2395
  BLOCK_4X4,    // TX_4X4
2396
  BLOCK_8X8,    // TX_8X8
2397
  BLOCK_16X16,  // TX_16X16
2398
  BLOCK_32X32,  // TX_32X32
2399
  BLOCK_64X64,  // TX_64X64
2400
  BLOCK_4X8,    // TX_4X8
2401
  BLOCK_8X4,    // TX_8X4
2402
  BLOCK_8X16,   // TX_8X16
2403
  BLOCK_16X8,   // TX_16X8
2404
  BLOCK_16X32,  // TX_16X32
2405
  BLOCK_32X16,  // TX_32X16
2406
  BLOCK_32X64,  // TX_32X64
2407
  BLOCK_64X32,  // TX_64X32
2408
  BLOCK_4X16,   // TX_4X16
2409
  BLOCK_16X4,   // TX_16X4
2410
  BLOCK_8X32,   // TX_8X32
2411
  BLOCK_32X8,   // TX_32X8
2412
  BLOCK_16X64,  // TX_16X64
2413
  BLOCK_64X16,  // TX_64X16
2414
  BLOCK_4X32,   // TX_4X32
2415
  BLOCK_32X4,   // TX_32X4
2416
  BLOCK_8X64,   // TX_8X64
2417
  BLOCK_64X8,   // TX_64X8
2418
  BLOCK_4X64,   // TX_4X64
2419
  BLOCK_64X4,   // TX_64X4
2420
};
2421
2422
/*!\endcond */
2423
2424
/*!
2425
 * \brief Top level encoder structure.
2426
 */
2427
typedef struct AV2_COMP {
2428
  /*!
2429
   * Quantization and dequantization parameters for internal quantizer setup
2430
   * in the encoder.
2431
   */
2432
  EncQuantDequantParams enc_quant_dequant_params;
2433
2434
  /*!
2435
   * Structure holding thread specific variables.
2436
   */
2437
  ThreadData td;
2438
2439
  /*!
2440
   * Statistics collected at frame level.
2441
   */
2442
  FRAME_COUNTS counts;
2443
2444
  /*!
2445
   * Holds buffer storing mode information at 4x4/8x8 level.
2446
   */
2447
  MBMIExtFrameBufferInfo mbmi_ext_info;
2448
2449
  /*!
2450
   * Buffer holding the transform block related information.
2451
   * coeff_buffer_base[i] stores the transform block related information of the
2452
   * ith superblock in raster scan order.
2453
   */
2454
  CB_COEFF_BUFFER *coeff_buffer_base;
2455
2456
  /*!
2457
   * Structure holding variables common to encoder and decoder.
2458
   */
2459
  AV2_COMMON common;
2460
2461
  /*!
2462
   * Encoder configuration related parameters.
2463
   */
2464
  AV2EncoderConfig oxcf;
2465
2466
  /*!
2467
   * Look-ahead context.
2468
   */
2469
  struct lookahead_ctx *lookahead;
2470
2471
  /*!
2472
   * When set, this flag indicates that the current frame is a forward keyframe.
2473
   */
2474
  int no_show_fwd_kf;
2475
  /*!
2476
   * Indicates an OLK obu is encountered in any layer
2477
   * It is initialized as 0 and set 1 when the first olk is decoded and set 0
2478
   * when the first regular frame or the first CLK after the olk is decoded.
2479
   */
2480
  int olk_encountered;
2481
  /*!
2482
   * If true, the update type is one of overlay updates
2483
   */
2484
  bool update_type_was_overlay;
2485
  /*!
2486
   * If true, the overlay update is for an OLK
2487
   */
2488
  bool is_olk_overlay;
2489
  /*!
2490
   * Stores the trellis optimization type at segment level.
2491
   * optimize_seg_arr[i] stores the trellis opt type for ith segment.
2492
   */
2493
  TRELLIS_OPT_TYPE optimize_seg_arr[MAX_SEGMENTS];
2494
2495
  /*!
2496
   * Pointer to the frame buffer holding the source frame to be used during the
2497
   * current stage of encoding. It can be the raw input, temporally filtered
2498
   * input or scaled input.
2499
   */
2500
  YV12_BUFFER_CONFIG *source;
2501
2502
  /*!
2503
   * Pointer to the frame buffer holding the last raw source frame.
2504
   * NULL for first frame and alt_ref frames.
2505
   */
2506
  YV12_BUFFER_CONFIG *last_source;
2507
2508
  /*!
2509
   * Pointer to the frame buffer holding the unscaled source frame.
2510
   * It can be either the raw input or temporally filtered input.
2511
   */
2512
  YV12_BUFFER_CONFIG *unscaled_source;
2513
2514
  /*!
2515
   * Frame buffer holding the resized source frame.
2516
   */
2517
  YV12_BUFFER_CONFIG scaled_source;
2518
2519
  /*!
2520
   * Pointer to the frame buffer holding the unscaled last source frame.
2521
   */
2522
  YV12_BUFFER_CONFIG *unscaled_last_source;
2523
2524
  /*!
2525
   * Frame buffer holding the resized last source frame.
2526
   */
2527
  YV12_BUFFER_CONFIG scaled_last_source;
2528
2529
  /*!
2530
   * Pointer to the original source frame. This is used to determine if the
2531
   * content is screen.
2532
   */
2533
  YV12_BUFFER_CONFIG *unfiltered_source;
2534
2535
  /*!
2536
   * Parameters related to tpl.
2537
   */
2538
  TplParams tpl_data;
2539
2540
  /*!
2541
   * For a still frame, this flag is set to 1 to skip partition search.
2542
   */
2543
  int partition_search_skippable_frame;
2544
2545
  /*!
2546
   * Variables related to forcing integer mv decisions for the current frame.
2547
   */
2548
  ForceIntegerMVInfo force_intpel_info;
2549
2550
  /*!
2551
   * Pointer to the buffer holding the scaled reference frames.
2552
   * scaled_ref_buf[i] holds the scaled reference frame of type i.
2553
   */
2554
  RefCntBuffer *scaled_ref_buf[INTER_REFS_PER_FRAME];
2555
2556
  /*!
2557
   * Pointer to the buffer holding the last show frame.
2558
   */
2559
  RefCntBuffer *last_show_frame_buf;
2560
2561
  /*!
2562
   * Flags signalled by the external interface at frame level.
2563
   */
2564
  ExternalFlags ext_flags;
2565
2566
  /*!
2567
   * Temporary frame buffer used to store the non-loop filtered reconstructed
2568
   * frame during the search of loop filter level.
2569
   */
2570
  YV12_BUFFER_CONFIG last_frame_uf;
2571
2572
  /*!
2573
   * Temporary frame buffer used to store the loop restored frame during loop
2574
   * restoration search.
2575
   */
2576
  YV12_BUFFER_CONFIG trial_frame_rst;
2577
2578
  /*!
2579
   * Ambient reconstruction err target for force key frames.
2580
   */
2581
  int64_t ambient_err;
2582
2583
  /*!
2584
   * Parameters related to rate distortion optimization.
2585
   */
2586
  RD_OPT rd;
2587
2588
  /*!
2589
   * Parameters related to global motion search.
2590
   */
2591
  GlobalMotionInfo gm_info;
2592
2593
  /*!
2594
   * Parameters related to winner mode processing.
2595
   */
2596
  WinnerModeParams winner_mode_params;
2597
2598
  /*!
2599
   * Frame time stamps.
2600
   */
2601
  TimeStamps time_stamps;
2602
2603
  /*!
2604
   * Rate control related parameters.
2605
   */
2606
  RATE_CONTROL rc;
2607
2608
  /*!
2609
   * Frame rate of the video.
2610
   */
2611
  double framerate;
2612
2613
  /*!
2614
   * Pointer to internal utility functions that manipulate avm_codec_* data
2615
   * structures.
2616
   */
2617
  struct avm_codec_pkt_list *output_pkt_list;
2618
2619
  /*!
2620
   * speed is passed as a per-frame parameter into the encoder.
2621
   */
2622
  int speed;
2623
2624
  /*!
2625
   * sf contains fine-grained config set internally based on speed.
2626
   */
2627
  SPEED_FEATURES sf;
2628
2629
  /*!
2630
   * Parameters for motion vector search process.
2631
   */
2632
  MotionVectorSearchParams mv_search_params;
2633
2634
  /*!
2635
   * When set, indicates that all reference frames are forward references,
2636
   * i.e., all the reference frames are output before the current frame.
2637
   */
2638
  int all_one_sided_refs;
2639
2640
  /*!
2641
   * Segmentation related information for current frame.
2642
   */
2643
  EncSegmentationInfo enc_seg;
2644
2645
  /*!
2646
   * Parameters related to cyclic refresh aq-mode.
2647
   */
2648
  CYCLIC_REFRESH *cyclic_refresh;
2649
  /*!
2650
   * Parameters related to active map. Active maps indicate
2651
   * if there is any activity on a 4x4 block basis.
2652
   */
2653
  ActiveMap active_map;
2654
2655
  /*!
2656
   * Function pointers to variants of sse/sad/variance computation functions.
2657
   * fn_ptr[i] indicates the list of function pointers corresponding to block
2658
   * size i.
2659
   */
2660
  avm_variance_fn_ptr_t fn_ptr[ENCODER_BLOCK_SIZES_ALL];
2661
2662
  /*!
2663
   * Information related to two pass encoding.
2664
   */
2665
  TWO_PASS twopass;
2666
2667
  /*!
2668
   * SubGOP configuration string
2669
   */
2670
  char *subgop_config_str;
2671
2672
  /*!
2673
   * SubGOP configuration file path
2674
   */
2675
  char *subgop_config_path;
2676
2677
  /*!
2678
   * Information related to subGOP configuration if specified.
2679
   */
2680
  SubGOPSetCfg subgop_config_set;
2681
2682
  /*!
2683
   * Information related to a gf group.
2684
   */
2685
  GF_GROUP gf_group;
2686
2687
  /*!
2688
   * Track prior gf group state.
2689
   */
2690
  GF_STATE gf_state;
2691
2692
  /*!
2693
   * Information related to a subgop.
2694
   */
2695
  SubGOPStatsEnc subgop_stats;
2696
2697
  /*!
2698
   * Frame buffer holding the temporally filtered source frame. It can be
2699
   * KEY frame or ARF frame.
2700
   */
2701
  YV12_BUFFER_CONFIG alt_ref_buffer;
2702
2703
#if CONFIG_INTERNAL_STATS
2704
  /*!\cond */
2705
  uint64_t time_receive_data;
2706
  uint64_t time_compress_data;
2707
2708
  int count[2];
2709
  uint64_t total_sq_error[2];
2710
  uint64_t total_samples[2];
2711
  ImageStat psnr[2];
2712
2713
  double total_blockiness;
2714
  double worst_blockiness;
2715
2716
  int bytes;
2717
  double summed_quality;
2718
  double summed_weights;
2719
  unsigned int tot_recode_hits;
2720
  double worst_ssim;
2721
2722
  ImageStat fastssim;
2723
  ImageStat psnrhvs;
2724
2725
  int b_calculate_blockiness;
2726
  int b_calculate_consistency;
2727
2728
  double total_inconsistency;
2729
  double worst_consistency;
2730
  Ssimv *ssim_vars;
2731
  Metrics metrics;
2732
  /*!\endcond */
2733
#endif
2734
2735
  /*!
2736
   * Calculates PSNR on each frame when set to 1 or 2.
2737
   * Uses stream PSNR when set to 2.
2738
   */
2739
  int b_calculate_psnr;
2740
2741
  /*!
2742
   * Prints stats for each frame when set to 1.
2743
   */
2744
  int print_per_frame_stats;
2745
2746
  /*!
2747
   * Prints HLS info for each frame when set to 1.
2748
   */
2749
  int print_per_frame_hls_info;
2750
2751
#if CONFIG_SPEED_STATS
2752
  /*!
2753
   * For debugging: number of transform searches we have performed.
2754
   */
2755
  unsigned int tx_search_count;
2756
#endif  // CONFIG_SPEED_STATS
2757
2758
  /*!
2759
   * When set, indicates that the frame is droppable, i.e., this frame
2760
   * does not update any reference buffers.
2761
   */
2762
  int droppable;
2763
2764
  /*!
2765
   * Stores the frame parameters during encoder initialization.
2766
   */
2767
  FRAME_INFO frame_info;
2768
2769
  /*!
2770
   * Structure to store the dimensions of current frame.
2771
   */
2772
  InitialDimensions initial_dimensions;
2773
2774
  /*!
2775
   * Number of MBs in the full-size frame; to be used to
2776
   * normalize the firstpass stats. This will differ from the
2777
   * number of MBs in the current frame when the frame is
2778
   * scaled.
2779
   */
2780
  int initial_mbs;
2781
2782
  /*!
2783
   * Resize related parameters.
2784
   */
2785
  ResizePendingParams resize_pending_params;
2786
2787
  /*!
2788
   * Pointer to struct holding adaptive data/contexts/models for the tile during
2789
   * encoding.
2790
   */
2791
  TileDataEnc *tile_data;
2792
  /*!
2793
   * Number of tiles for which memory has been allocated for tile_data.
2794
   */
2795
  int allocated_tiles;
2796
2797
  /*!
2798
   * Structure to store the palette token related information.
2799
   */
2800
  TokenInfo token_info;
2801
2802
  /*!
2803
   * Sequence parameters have been transmitted already and locked
2804
   * or not. Once locked av2_change_config cannot change the seq
2805
   * parameters.
2806
   */
2807
  int seq_params_locked;
2808
2809
  /*!
2810
   * VARIANCE_AQ segment map refresh.
2811
   */
2812
  int vaq_refresh;
2813
2814
  /*!
2815
   * Thresholds for variance based partitioning.
2816
   */
2817
  VarBasedPartitionInfo vbp_info;
2818
2819
  /*!
2820
   * Probabilities for pruning of various AV2 tools.
2821
   */
2822
  FrameProbInfo frame_probs;
2823
2824
  /*!
2825
   * Multi-threading parameters.
2826
   */
2827
  MultiThreadInfo mt_info;
2828
  /*!
2829
   * Specifies the frame to be output. It is valid only if show_existing_frame
2830
   * is 1. When show_existing_frame is 0, existing_fb_idx_to_show is set to
2831
   * INVALID_IDX.
2832
   */
2833
  int fb_idx_for_overlay;
2834
  /*!
2835
   * When set, indicates that internal ARFs are enabled.
2836
   */
2837
  int internal_altref_allowed;
2838
2839
  /*!
2840
   * A flag to indicate if intrabc is ever used in current frame.
2841
   */
2842
  int intrabc_used;
2843
2844
  /*!
2845
   * Loop Restoration context.
2846
   */
2847
  AV2LrStruct lr_ctxt;
2848
2849
  /*!
2850
   * Pointer to list of tables with film grain parameters.
2851
   */
2852
  avm_film_grain_table_t *film_grain_table;
2853
2854
#if CONFIG_DENOISE
2855
  /*!
2856
   * Pointer to structure holding the denoised image buffers and the helper
2857
   * noise models.
2858
   */
2859
  struct avm_denoise_and_model_t *denoise_and_model;
2860
#endif
2861
2862
  /*!
2863
   * Flags related to interpolation filter search.
2864
   */
2865
  InterpSearchFlags interp_search_flags;
2866
2867
  /*!
2868
   * Set for screen contents or when screen content tools are enabled.
2869
   */
2870
  int is_screen_content_type;
2871
2872
#if CONFIG_COLLECT_PARTITION_STATS == 2
2873
  /*!
2874
   * Accumulates the partition timing stat over the whole frame.
2875
   */
2876
  FramePartitionTimingStats partition_stats;
2877
#endif  // CONFIG_COLLECT_PARTITION_STATS == 2
2878
2879
#if CONFIG_COLLECT_COMPONENT_TIMING
2880
  /*!
2881
   * component_time[] are initialized to zero while encoder starts.
2882
   */
2883
  uint64_t component_time[kTimingComponents];
2884
  struct avm_usec_timer component_timer[kTimingComponents];
2885
  /*!
2886
   * frame_component_time[] are initialized to zero at beginning of each frame.
2887
   */
2888
  uint64_t frame_component_time[kTimingComponents];
2889
#endif
2890
2891
  /*!
2892
   * Parameters for AV2 bitstream levels.
2893
   */
2894
  AV2LevelParams level_params;
2895
2896
  /*!
2897
   * Whether any no-zero delta_q was actually used.
2898
   */
2899
  int deltaq_used;
2900
2901
  /*!
2902
   * Refrence frame distance related variables.
2903
   */
2904
  RefFrameDistanceInfo ref_frame_dist_info;
2905
2906
  /*!
2907
   * Scaling factors used in the RD multiplier modulation.
2908
   * TODO(sdeng): consider merge the following arrays.
2909
   * tpl_rdmult_scaling_factors is a temporary buffer used to store the
2910
   * intermediate scaling factors which are used in the calculation of
2911
   * tpl_sb_rdmult_scaling_factors. tpl_rdmult_scaling_factors[i] stores the
2912
   * intermediate scaling factor of the ith 16 x 16 block in raster scan order.
2913
   */
2914
  double *tpl_rdmult_scaling_factors;
2915
  /*!
2916
   * tpl_sb_rdmult_scaling_factors[i] stores the RD multiplier scaling factor of
2917
   * the ith 16 x 16 block in raster scan order.
2918
   */
2919
  double *tpl_sb_rdmult_scaling_factors;
2920
  /*!
2921
   * ssim_rdmult_scaling_factors[i] stores the RD multiplier scaling factor of
2922
   * the ith 16 x 16 block in raster scan order. This scaling factor is used for
2923
   * RD multiplier modulation when SSIM tuning is enabled.
2924
   */
2925
  double *ssim_rdmult_scaling_factors;
2926
2927
#if CONFIG_TUNE_VMAF
2928
  /*!
2929
   * Parameters for VMAF tuning.
2930
   */
2931
  TuneVMAFInfo vmaf_info;
2932
#endif
2933
2934
  /*!
2935
   * Flag indicating whether look ahead processing (LAP) is enabled.
2936
   */
2937
  int lap_enabled;
2938
  /*!
2939
   * Indicates whether current processing stage is encode stage or LAP stage.
2940
   */
2941
  COMPRESSOR_STAGE compressor_stage;
2942
2943
  /*!
2944
   * Some motion vector stats from the last encoded frame to help us decide what
2945
   * precision to use to encode the current frame.
2946
   */
2947
  MV_STATS mv_stats;
2948
2949
  /*!
2950
   * Number of tile-groups.
2951
   */
2952
  int num_tg;
2953
2954
  /*!
2955
   * First pass related data.
2956
   */
2957
  FirstPassData firstpass_data;
2958
2959
  /*!
2960
   * Temporal Noise Estimate
2961
   */
2962
  NOISE_ESTIMATE noise_estimate;
2963
2964
  /*!
2965
   * Count on how many consecutive times a block uses small/zeromv for encoding
2966
   * in a scale of 8x8 block.
2967
   */
2968
  uint8_t *consec_zero_mv;
2969
2970
  /*!
2971
   * Number of frames left to be encoded, is 0 if limit is not set.
2972
   */
2973
  int frames_left;
2974
2975
  /*!
2976
   * Indicates if a valid global motion model has been found in the different
2977
   * frame update types of a GF group.
2978
   * valid_gm_model_found[i] indicates if valid global motion model has been
2979
   * found in the frame update type with enum value equal to i
2980
   */
2981
  int valid_gm_model_found[FRAME_UPDATE_TYPES];
2982
2983
  /*!
2984
   *  Should we allocate a downsampling pyramid for each frame buffer?
2985
   *  This is currently only used for global motion
2986
   */
2987
  bool alloc_pyramid;
2988
2989
  /*!
2990
   * Number of pixels that choose palette mode for luma in the
2991
   * fast encoding pass in av2_determine_sc_tools_with_encoding().
2992
   */
2993
  int palette_pixel_num;
2994
  /*!
2995
   * Indicate if the primary reference frame is signaled.
2996
   */
2997
  int signal_primary_ref_frame;
2998
  /*!
2999
   * Record if error_resilience mode is turned on in the encoding. This is used
3000
   * in the primary reference frame decision.
3001
   */
3002
  int error_resilient_frame_seen;
3003
  /*!
3004
   * Record last encoded frame's display order hint.
3005
   */
3006
  int last_encoded_frame_order_hint;
3007
  /*!
3008
   * allocation width
3009
   */
3010
  int alloc_width;
3011
  /*!
3012
   * allocation height
3013
   */
3014
  int alloc_height;
3015
  /*!
3016
   * Record the current multi-frame header parameters
3017
   */
3018
  MultiFrameHeader cur_mfh_params;
3019
  /*!
3020
   * TIP mode selected count for first INTER_REFS_PER_FRAME frames
3021
   * Encoder would use this value to decide if need to enable TIP mode
3022
   * for future frames
3023
   */
3024
  int tip_mode_count[INTER_REFS_PER_FRAME];
3025
  /*!
3026
   * write ci obu
3027
   */
3028
  int write_ci_obu_flag;
3029
  /*!
3030
   * Write the Buffer Removal Timing OBU
3031
   */
3032
  int write_brt_obu;
3033
  /*!
3034
   * list for Layer Config Record (LCR) information
3035
   */
3036
  struct LayerConfigurationRecord lcr_list[MAX_NUM_XLAYERS][MAX_NUM_LCR];
3037
  /*!
3038
   * list for Operating Point Set (OPS) information
3039
   */
3040
  struct OperatingPointSet ops_list[MAX_NUM_XLAYERS][MAX_NUM_OPS_ID];
3041
  /*!
3042
   * list for Atlas information
3043
   */
3044
  struct AtlasSegmentInfo atlas_list[MAX_NUM_XLAYERS][MAX_NUM_ATLAS_SEG_ID];
3045
3046
  /*!
3047
   * determine the mode of the switch frame
3048
   * 0: Switch frame, 1: RAS frame
3049
   */
3050
  int is_ras_frame;
3051
3052
  /*!
3053
   * a list of OBU_QUANTIZATION_MATRIX
3054
   */
3055
3056
  struct qm_obu qmobu_list[NUM_CUSTOM_QMS];
3057
  /*!
3058
   * Intermediate list of quantiztaion matrices for input user defined matrices
3059
   */
3060
  // 15*3*3*64 bytes :
3061
  qm_val_t ***user_defined_qm_list[NUM_CUSTOM_QMS];  //[8x8/8x4,4x8][y/u/v][64]
3062
  /*!
3063
   * number of signalled qm obus
3064
   */
3065
  int total_signalled_qmobu_count;
3066
  /*!
3067
   * indication that an obu is written for a frame during encoding to prevent an
3068
   * qm obu from being written multiple times
3069
   */
3070
  bool obu_is_written;
3071
3072
  /*!
3073
   * Flags to indicate whether user defined qm is used for id, i
3074
   */
3075
  bool use_user_defined_qm[NUM_CUSTOM_QMS];
3076
  /*!
3077
   * list of film grain models
3078
   */
3079
3080
  struct film_grain_model fgm_list[MAX_FGM_NUM];
3081
  /*!
3082
   * number of film grain models written
3083
   */
3084
3085
  int written_fgm_num;
3086
3087
  /*!
3088
   * film grain model counter
3089
   */
3090
  int increase_fgm_counter;
3091
  /*!
3092
   * film grain model for a frame
3093
   */
3094
3095
  struct film_grain_model fgm;
3096
3097
  /*!
3098
   * Index into the film grain random_seed table.
3099
   * Reset to 0 on each keyframe; advanced after every output picture.
3100
   */
3101
  int fgs_seed_idx;
3102
  /*!
3103
   * Previous DOH value.
3104
   * Used for the FGS random seed indexing
3105
   */
3106
  unsigned int fgs_prev_doh;
3107
3108
  /*!
3109
   * Indicates that scan type info is present
3110
   */
3111
3112
  int scan_type_info_present_flag;
3113
3114
  /*!
3115
   * Indicates the level index for the operating points
3116
   */
3117
3118
  AV2_LEVEL level_idx[MAX_NUM_OPERATING_POINTS];
3119
  /*!
3120
   * Indicates the tier information  for the operating points
3121
   */
3122
3123
  uint8_t tier[MAX_NUM_OPERATING_POINTS];  // seq_tier in spec. One bit: 0 or 1.
3124
3125
  /*!
3126
   * Banding hints metadata for the current frame
3127
   */
3128
  avm_banding_hints_metadata_t band_metadata;
3129
  /*!
3130
   * Flag indicating if banding metadata is available for the current frame
3131
   */
3132
  int band_metadata_present;
3133
} AV2_COMP;
3134
3135
/*!
3136
 * \brief Input frames and last input frame
3137
 */
3138
typedef struct EncodeFrameInput {
3139
  /*!\cond */
3140
  YV12_BUFFER_CONFIG *source;
3141
  YV12_BUFFER_CONFIG *last_source;
3142
  YV12_BUFFER_CONFIG *bru_ref_source;
3143
  int64_t ts_duration;
3144
  /*!\endcond */
3145
} EncodeFrameInput;
3146
3147
/*!
3148
 * \brief contains per-frame encoding parameters decided upon by
3149
 * av2_encode_strategy() and passed down to av2_encode().
3150
 */
3151
typedef struct EncodeFrameParams {
3152
  /*!
3153
   * Frame type (eg KF vs inter frame etc)
3154
   */
3155
  FRAME_TYPE frame_type;
3156
3157
  /*!\cond */
3158
  int primary_ref_frame;
3159
  int order_offset;
3160
3161
  /*!\endcond */
3162
  /*!
3163
   * Should the current frame be displayed after being decoded
3164
   */
3165
  int immediate_output_picture;
3166
3167
  /*!\cond */
3168
  int refresh_frame_flags;
3169
  bool frame_params_update_type_was_overlay;
3170
  int fb_idx_for_overlay;
3171
  OBU_TYPE frame_params_obu_type;
3172
  int duplicate_existing_frame;
3173
  /*!\endcond */
3174
  /*!
3175
   *  Bitmask of which reference buffers may be referenced by this frame.
3176
   */
3177
  int ref_frame_flags;
3178
3179
  /*!
3180
   *  Reference buffer assignment for this frame.
3181
   */
3182
  int remapped_ref_idx[INTER_REFS_PER_FRAME];
3183
3184
  /*!
3185
   *  Speed level to use for this frame: Bigger number means faster.
3186
   */
3187
  int speed;
3188
} EncodeFrameParams;
3189
3190
/*!\cond */
3191
3192
// EncodeFrameResults contains information about the result of encoding a
3193
// single frame
3194
typedef struct {
3195
  size_t size;  // Size of resulting bitstream
3196
} EncodeFrameResults;
3197
3198
// Must not be called more than once.
3199
void av2_initialize_enc(void);
3200
3201
struct AV2_COMP *av2_create_compressor(AV2EncoderConfig *oxcf,
3202
                                       BufferPool *const pool,
3203
                                       FIRSTPASS_STATS *frame_stats_buf,
3204
                                       COMPRESSOR_STAGE stage,
3205
                                       int num_lap_buffers,
3206
                                       int lap_lag_in_frames,
3207
                                       STATS_BUFFER_CTX *stats_buf_context);
3208
void av2_remove_compressor(AV2_COMP *cpi);
3209
3210
void av2_change_config(AV2_COMP *cpi, const AV2EncoderConfig *oxcf);
3211
3212
void av2_check_initial_width(AV2_COMP *cpi, int subsampling_x,
3213
                             int subsampling_y);
3214
3215
void av2_validate_crop_window_chroma_alignment(AV2_COMP *cpi, int frame_width,
3216
                                               int frame_height);
3217
3218
void av2_init_seq_coding_tools(AV2_COMP *cpi, SequenceHeader *seq,
3219
                               AV2_COMMON *cm, const AV2EncoderConfig *oxcf);
3220
3221
/*!\endcond */
3222
3223
/*!\brief Obtain the raw frame data
3224
 *
3225
 * \ingroup high_level_algo
3226
 * This function receives the raw frame data from input.
3227
 *
3228
 * \param[in]    cpi            Top-level encoder structure
3229
 * \param[in]    frame_flags    Flags to decide how to encoding the frame
3230
 * \param[in]    sd             Contain raw frame data
3231
 * \param[in]    time_stamp     Time stamp of the frame
3232
 * \param[in]    end_time_stamp End time stamp
3233
 *
3234
 * \return Returns a value to indicate if the frame data is received
3235
 * successfully.
3236
 * \note The caller can assume that a copy of this frame is made and not just a
3237
 * copy of the pointer.
3238
 */
3239
int av2_receive_raw_frame(AV2_COMP *cpi, avm_enc_frame_flags_t frame_flags,
3240
                          YV12_BUFFER_CONFIG *sd, int64_t time_stamp,
3241
                          int64_t end_time_stamp);
3242
3243
/*!\brief Encode a frame
3244
 *
3245
 * \ingroup high_level_algo
3246
 * \callgraph
3247
 * \callergraph
3248
 * This function encodes the raw frame data, and outputs the frame bit stream
3249
 * to the designated buffer. The caller should use the output parameters
3250
 * *time_stamp and *time_end only when this function returns AVM_CODEC_OK.
3251
 *
3252
 * \param[in]    cpi         Top-level encoder structure
3253
 * \param[in]    frame_flags Flags to decide how to encoding the frame
3254
 * \param[in]    size        Bitstream size
3255
 * \param[in]    dest        Bitstream output
3256
 * \param[out]   time_stamp  Time stamp of the frame
3257
 * \param[out]   time_end    Time end
3258
 * \param[in]    flush       Decide to encode one frame or the rest of frames
3259
 * \param[in]    timebase    Time base used
3260
 *
3261
 * \return Returns a value to indicate if the encoding is done successfully.
3262
 * \retval #AVM_CODEC_OK
3263
 * \retval -1
3264
 *     No frame encoded; more input is required.
3265
 * \retval #AVM_CODEC_ERROR
3266
 */
3267
int av2_get_compressed_data(AV2_COMP *cpi, unsigned int *frame_flags,
3268
                            size_t *size, uint8_t *dest, int64_t *time_stamp,
3269
                            int64_t *time_end, int flush,
3270
                            const avm_rational64_t *timebase);
3271
3272
/*!\brief Run 1-pass/2-pass encoding
3273
 *
3274
 * \ingroup high_level_algo
3275
 * \callgraph
3276
 * \callergraph
3277
 */
3278
int av2_encode(AV2_COMP *const cpi, uint8_t *const dest,
3279
               const EncodeFrameInput *const frame_input,
3280
               const EncodeFrameParams *const frame_params,
3281
               EncodeFrameResults *const frame_results,
3282
               int64_t *const time_stamp, int64_t *const time_end);
3283
3284
/*!\cond */
3285
int av2_get_preview_raw_frame(AV2_COMP *cpi, YV12_BUFFER_CONFIG *dest);
3286
3287
int av2_get_last_show_frame(AV2_COMP *cpi, YV12_BUFFER_CONFIG *frame);
3288
3289
avm_codec_err_t av2_copy_new_frame_enc(AV2_COMMON *cm,
3290
                                       YV12_BUFFER_CONFIG *new_frame,
3291
                                       YV12_BUFFER_CONFIG *sd);
3292
3293
int av2_use_as_reference(int *ext_ref_frame_flags, int ref_frame_flags);
3294
3295
int av2_copy_reference_enc(AV2_COMP *cpi, int idx, YV12_BUFFER_CONFIG *sd);
3296
3297
int av2_set_reference_enc(AV2_COMP *cpi, int idx, YV12_BUFFER_CONFIG *sd);
3298
3299
int av2_set_size_literal(AV2_COMP *cpi, int width, int height);
3300
3301
void av2_set_frame_size(AV2_COMP *cpi, int width, int height);
3302
3303
int av2_set_active_map(AV2_COMP *cpi, unsigned char *map, int rows, int cols);
3304
3305
int av2_get_active_map(AV2_COMP *cpi, unsigned char *map, int rows, int cols);
3306
3307
int av2_set_internal_size(AV2EncoderConfig *const oxcf,
3308
                          ResizePendingParams *resize_pending_params,
3309
                          AVM_SCALING horiz_mode, AVM_SCALING vert_mode);
3310
3311
int av2_get_quantizer(struct AV2_COMP *cpi);
3312
3313
// The "sect5" and "annexb" in the function name refer to Section 5 and Annex B
3314
// in the AV2 spec, but AV2 only supports a simplified variant of Annex B.
3315
// TODO(wtc): write OBU sizes to the bitstream in the AV2 bitstream format
3316
// directly and remove this function.
3317
int av2_convert_sect5obus_to_annexb(uint8_t *buffer, size_t *input_size);
3318
3319
void av2_set_downsample_filter_options(AV2_COMP *cpi);
3320
3321
// Set screen content options.
3322
// This function estimates whether to use screen content tools, by counting
3323
// the portion of blocks that have few luma colors.
3324
// Modifies:
3325
//   cpi->commom.allow_screen_content_tools
3326
//   cpi->common.allow_intrabc
3327
// However, the estimation is not accurate and may misclassify videos.
3328
// A slower but more accurate approach that determines whether to use screen
3329
// content tools is employed later. See av2_determine_sc_tools_with_encoding().
3330
void av2_set_screen_content_options(struct AV2_COMP *cpi,
3331
                                    FeatureFlags *features);
3332
3333
// av2 uses 10,000,000 ticks/second as time stamp
3334
0
#define TICKS_PER_SEC 10000000LL
3335
3336
static INLINE int64_t
3337
0
timebase_units_to_ticks(const avm_rational64_t *timestamp_ratio, int64_t n) {
3338
0
  return n * timestamp_ratio->num / timestamp_ratio->den;
3339
0
}
3340
3341
static INLINE int64_t
3342
0
ticks_to_timebase_units(const avm_rational64_t *timestamp_ratio, int64_t n) {
3343
0
  int64_t round = timestamp_ratio->num / 2;
3344
0
  if (round > 0) --round;
3345
0
  return (n * timestamp_ratio->den + round) / timestamp_ratio->num;
3346
0
}
3347
3348
0
static INLINE int frame_is_kf_gf_arf(const AV2_COMP *cpi) {
3349
0
  const GF_GROUP *const gf_group = &cpi->gf_group;
3350
0
  const FRAME_UPDATE_TYPE update_type = gf_group->update_type[gf_group->index];
3351
0
3352
0
  return frame_is_intra_only(&cpi->common) || update_type == ARF_UPDATE ||
3353
0
         update_type == KFFLT_UPDATE || update_type == GF_UPDATE;
3354
0
}
3355
3356
// TODO(huisu@google.com, youzhou@microsoft.com): enable hash-me for HBD.
3357
0
static INLINE int av2_use_hash_me(const AV2_COMP *const cpi) {
3358
0
  if (!cpi->common.features.is_scc_content_by_detector) return 0;
3359
0
  return (cpi->common.features.allow_intrabc) &&
3360
0
         (frame_is_intra_only(&cpi->common) ||
3361
0
          cpi->common.features.allow_local_intrabc);
3362
0
}
3363
3364
static INLINE const YV12_BUFFER_CONFIG *get_ref_frame_yv12_buf_res_indep(
3365
0
    const AV2_COMMON *const cm, MV_REFERENCE_FRAME ref_frame) {
3366
0
  const RefCntBuffer *const buf = get_ref_frame_buf_res_indep(cm, ref_frame);
3367
0
  return buf != NULL ? &buf->buf : NULL;
3368
0
}
3369
3370
static INLINE const YV12_BUFFER_CONFIG *get_ref_frame_yv12_buf(
3371
0
    const AV2_COMMON *const cm, MV_REFERENCE_FRAME ref_frame) {
3372
0
  const RefCntBuffer *const buf = get_ref_frame_buf(cm, ref_frame);
3373
0
  return buf != NULL ? &buf->buf : NULL;
3374
0
}
3375
3376
0
static INLINE void alloc_frame_mvs(AV2_COMMON *const cm, RefCntBuffer *buf) {
3377
0
  assert(buf != NULL);
3378
0
  ensure_mv_buffer(buf, cm);
3379
0
  buf->width = cm->width;
3380
0
  buf->height = cm->height;
3381
0
}
3382
3383
// Get the allocated token size for a tile. It does the same calculation as in
3384
// the frame token allocation.
3385
static INLINE unsigned int allocated_tokens(TileInfo tile, int sb_size_log2,
3386
0
                                            int num_planes) {
3387
0
  int tile_mb_rows = (tile.mi_row_end - tile.mi_row_start + 2) >> 2;
3388
0
  int tile_mb_cols = (tile.mi_col_end - tile.mi_col_start + 2) >> 2;
3389
0
3390
0
  return get_token_alloc(tile_mb_rows, tile_mb_cols, sb_size_log2, num_planes);
3391
0
}
3392
3393
static INLINE void get_start_tok(AV2_COMP *cpi, int tile_row, int tile_col,
3394
                                 int mi_row, TokenExtra **tok, int sb_size_log2,
3395
0
                                 int num_planes) {
3396
0
  AV2_COMMON *const cm = &cpi->common;
3397
0
  const int tile_cols = cm->tiles.cols;
3398
0
  TileDataEnc *this_tile = &cpi->tile_data[tile_row * tile_cols + tile_col];
3399
0
  const TileInfo *const tile_info = &this_tile->tile_info;
3400
0
3401
0
  const int tile_mb_cols =
3402
0
      (tile_info->mi_col_end - tile_info->mi_col_start + 2) >> 2;
3403
0
  const int tile_mb_row = (mi_row - tile_info->mi_row_start + 2) >> 2;
3404
0
3405
0
  *tok = cpi->token_info.tile_tok[tile_row][tile_col] +
3406
0
         get_token_alloc(tile_mb_row, tile_mb_cols, sb_size_log2, num_planes);
3407
0
}
3408
3409
void av2_apply_encoding_flags(AV2_COMP *cpi, avm_enc_frame_flags_t flags);
3410
3411
#define ALT_MIN_LAG 3
3412
0
static INLINE int is_altref_enabled(int lag_in_frames, bool enable_auto_arf) {
3413
0
  return lag_in_frames >= ALT_MIN_LAG && enable_auto_arf;
3414
0
}
3415
3416
// Check if statistics generation stage
3417
0
static INLINE int is_stat_generation_stage(const AV2_COMP *const cpi) {
3418
0
  assert(IMPLIES(cpi->compressor_stage == LAP_STAGE,
3419
0
                 cpi->oxcf.pass == 0 && cpi->lap_enabled));
3420
0
  return (cpi->compressor_stage == LAP_STAGE);
3421
0
}
3422
3423
// Check if statistics consumption stage
3424
0
static INLINE int is_stat_consumption_stage(const AV2_COMP *const cpi) {
3425
0
  return (cpi->compressor_stage == ENCODE_STAGE && cpi->lap_enabled);
3426
0
}
3427
3428
/*!\endcond */
3429
/*!\brief Check if the current stage has statistics
3430
 *
3431
 *\ingroup two_pass_algo
3432
 *
3433
 * \param[in]    cpi     Top - level encoder instance structure
3434
 *
3435
 * \return 0 if no stats for current stage else 1
3436
 */
3437
0
static INLINE int has_no_stats_stage(const AV2_COMP *const cpi) {
3438
0
  assert(IMPLIES(!cpi->lap_enabled, cpi->compressor_stage == ENCODE_STAGE));
3439
0
  return (!cpi->lap_enabled);
3440
0
}
3441
/*!\cond */
3442
3443
// Function return size of frame stats buffer
3444
0
static INLINE int get_stats_buf_size(int num_lap_buffer, int num_lag_buffer) {
3445
0
  /* if lookahead is enabled return num_lap_buffers else num_lag_buffers */
3446
0
  return (num_lap_buffer > 0 ? num_lap_buffer + 1 : num_lag_buffer);
3447
0
}
3448
3449
// TODO(zoeliu): To set up cpi->oxcf.gf_cfg.enable_auto_brf
3450
3451
static INLINE void set_ref_ptrs(const AV2_COMMON *cm, MACROBLOCKD *xd,
3452
                                MV_REFERENCE_FRAME ref0,
3453
0
                                MV_REFERENCE_FRAME ref1) {
3454
0
  xd->block_ref_scale_factors[0] = get_ref_scale_factors_const(
3455
0
      cm, ref0 < INTER_REFS_PER_FRAME || is_tip_ref_frame(ref0) ? ref0 : 0);
3456
0
  xd->block_ref_scale_factors[1] = get_ref_scale_factors_const(
3457
0
      cm, ref1 < INTER_REFS_PER_FRAME || is_tip_ref_frame(ref1) ? ref1 : 0);
3458
0
}
3459
3460
static INLINE const int *cond_cost_list_const(const struct AV2_COMP *cpi,
3461
0
                                              const int *cost_list) {
3462
0
  const int use_cost_list = cpi->sf.mv_sf.subpel_search_method != SUBPEL_TREE &&
3463
0
                            cpi->sf.mv_sf.use_fullpel_costlist;
3464
0
  return use_cost_list ? cost_list : NULL;
3465
0
}
3466
3467
0
static INLINE int *cond_cost_list(const struct AV2_COMP *cpi, int *cost_list) {
3468
0
  const int use_cost_list = cpi->sf.mv_sf.subpel_search_method != SUBPEL_TREE &&
3469
0
                            cpi->sf.mv_sf.use_fullpel_costlist;
3470
0
  return use_cost_list ? cost_list : NULL;
3471
0
}
3472
3473
void av2_new_framerate(AV2_COMP *cpi, double framerate);
3474
3475
// Get index into the 'cpi->mbmi_ext_info.frame_base' array for the given
3476
// 'mi_row' and 'mi_col'.
3477
static INLINE int get_mi_ext_idx(const int mi_row, const int mi_col,
3478
                                 const BLOCK_SIZE mi_alloc_bsize,
3479
0
                                 const int mbmi_ext_stride) {
3480
0
  const int mi_ext_size_1d = mi_size_wide[mi_alloc_bsize];
3481
0
  const int mi_ext_row = mi_row / mi_ext_size_1d;
3482
0
  const int mi_ext_col = mi_col / mi_ext_size_1d;
3483
0
  return mi_ext_row * mbmi_ext_stride + mi_ext_col;
3484
0
}
3485
3486
// Lighter version of set_offsets that only sets the mode info
3487
// pointers.
3488
static INLINE void set_mode_info_offsets(
3489
    const CommonModeInfoParams *const mi_params,
3490
    const MBMIExtFrameBufferInfo *const mbmi_ext_info, MACROBLOCK *const x,
3491
    MACROBLOCKD *const xd, int mi_row, int mi_col, const int mi_width,
3492
0
    const int mi_height) {
3493
0
  const int x_inside_boundary = AVMMIN(mi_width, mi_params->mi_cols - mi_col);
3494
0
  const int y_inside_boundary = AVMMIN(mi_height, mi_params->mi_rows - mi_row);
3495
0
  set_mi_offsets(mi_params, xd, mi_row, mi_col, x_inside_boundary,
3496
0
                 y_inside_boundary);
3497
0
  const int ext_idx = get_mi_ext_idx(mi_row, mi_col, mi_params->mi_alloc_bsize,
3498
0
                                     mbmi_ext_info->stride);
3499
0
  x->mbmi_ext_frame = mbmi_ext_info->frame_base + ext_idx;
3500
0
}
3501
3502
// Check to see if the given partition size is allowed for a specified number
3503
// of mi block rows and columns remaining in the image.
3504
// If not then return the largest allowed partition size
3505
static INLINE BLOCK_SIZE find_partition_size(BLOCK_SIZE bsize, int rows_left,
3506
0
                                             int cols_left, int *bh, int *bw) {
3507
0
  int int_size = (int)bsize;
3508
0
  if (rows_left <= 0 || cols_left <= 0) {
3509
0
    return AVMMIN(bsize, BLOCK_8X8);
3510
0
  } else {
3511
0
    for (; int_size > 0; int_size -= 3) {
3512
0
      *bh = mi_size_high[int_size];
3513
0
      *bw = mi_size_wide[int_size];
3514
0
      if ((*bh <= rows_left) && (*bw <= cols_left)) {
3515
0
        break;
3516
0
      }
3517
0
    }
3518
0
  }
3519
0
  return (BLOCK_SIZE)int_size;
3520
0
}
3521
3522
static INLINE int get_max_allowed_ref_frames(
3523
0
    int selective_ref_frame, unsigned int max_reference_frames) {
3524
0
  const unsigned int max_allowed_refs_for_given_speed =
3525
0
      (selective_ref_frame >= 3) ? INTER_REFS_PER_FRAME - 1
3526
0
                                 : INTER_REFS_PER_FRAME;
3527
0
  return AVMMIN(max_allowed_refs_for_given_speed, max_reference_frames);
3528
0
}
3529
3530
/*!\brief Return whether the current coding block has two separate DRLs,
3531
 * the mdoe info is used as inputs */
3532
static INLINE int has_second_drl_by_mode(const PREDICTION_MODE mode,
3533
0
                                         const MV_REFERENCE_FRAME *ref_frame) {
3534
0
  return (mode == NEAR_NEARMV || mode == NEAR_NEWMV) &&
3535
0
         !is_tip_ref_frame(ref_frame[0]);
3536
0
}
3537
3538
// Enforce the number of references for each arbitrary frame based on user
3539
// options and speed.
3540
static AVM_INLINE void enforce_max_ref_frames(AV2_COMP *cpi,
3541
0
                                              int *ref_frame_flags) {
3542
0
  MV_REFERENCE_FRAME ref_frame;
3543
0
  int total_valid_refs = 0;
3544
0
3545
0
  for (ref_frame = 0; ref_frame < INTER_REFS_PER_FRAME; ++ref_frame) {
3546
0
    if (*ref_frame_flags & (1 << ref_frame)) {
3547
0
      total_valid_refs++;
3548
0
    }
3549
0
  }
3550
0
3551
0
  const int max_allowed_refs =
3552
0
      get_max_allowed_ref_frames(cpi->sf.inter_sf.selective_ref_frame,
3553
0
                                 cpi->oxcf.ref_frm_cfg.max_reference_frames);
3554
0
3555
0
  const int num_refs_to_disable = INTER_REFS_PER_FRAME - max_allowed_refs;
3556
0
  for (int i = 0;
3557
0
       i < num_refs_to_disable && total_valid_refs > max_allowed_refs; ++i) {
3558
0
    const MV_REFERENCE_FRAME ref_frame_to_disable =
3559
0
        INTER_REFS_PER_FRAME - i - 1;
3560
0
3561
0
    if (!(*ref_frame_flags & (1 << ref_frame_to_disable))) {
3562
0
      continue;
3563
0
    }
3564
0
    *ref_frame_flags &= ~(1 << ref_frame_to_disable);
3565
0
    --total_valid_refs;
3566
0
  }
3567
0
}
3568
3569
// Returns a Sequence Header OBU stored in an avm_fixed_buf_t, or NULL upon
3570
// failure. When a non-NULL avm_fixed_buf_t pointer is returned by this
3571
// function, the memory must be freed by the caller. Both the buf member of the
3572
// avm_fixed_buf_t, and the avm_fixed_buf_t pointer itself must be freed. Memory
3573
// returned must be freed via call to free().
3574
//
3575
// Note: The OBU returned is in Low Overhead Bitstream Format. Specifically,
3576
// the obu_has_size_field bit is set, and the buffer contains the obu_size
3577
// field.
3578
avm_fixed_buf_t *av2_get_global_headers(AV2_COMP *cpi);
3579
3580
#define MAX_GFUBOOST_FACTOR 10.0
3581
3582
static INLINE int is_frame_tpl_eligible(const GF_GROUP *const gf_group,
3583
0
                                        uint8_t index) {
3584
0
  const FRAME_UPDATE_TYPE update_type = gf_group->update_type[index];
3585
0
  return update_type == ARF_UPDATE || update_type == GF_UPDATE ||
3586
0
         update_type == KFFLT_UPDATE || update_type == KF_UPDATE;
3587
0
}
3588
3589
static INLINE int is_frame_eligible_for_ref_pruning(const GF_GROUP *gf_group,
3590
                                                    int selective_ref_frame,
3591
                                                    int prune_ref_frames,
3592
0
                                                    int gf_index) {
3593
0
  return (selective_ref_frame > 0) && (prune_ref_frames > 0) &&
3594
0
         !is_frame_tpl_eligible(gf_group, gf_index);
3595
0
}
3596
3597
// Get update type of the current frame.
3598
static INLINE FRAME_UPDATE_TYPE
3599
0
get_frame_update_type(const GF_GROUP *gf_group) {
3600
0
  return gf_group->update_type[gf_group->index];
3601
0
}
3602
3603
0
static INLINE int av2_pixels_to_mi(int pixels) {
3604
0
  return ALIGN_POWER_OF_TWO(pixels, 3) >> MI_SIZE_LOG2;
3605
0
}
3606
3607
0
static AVM_INLINE int is_psnr_calc_enabled(const AV2_COMP *cpi) {
3608
0
  const AV2_COMMON *const cm = &cpi->common;
3609
0
3610
0
  return cpi->b_calculate_psnr >= 1 && !is_stat_generation_stage(cpi) &&
3611
0
         cm->immediate_output_picture;
3612
0
}
3613
3614
#if CONFIG_COLLECT_PARTITION_STATS == 2
3615
static INLINE void av2_print_fr_partition_timing_stats(
3616
    const FramePartitionTimingStats *part_stats, const char *filename) {
3617
  FILE *f = fopen(filename, "w");
3618
  if (!f) {
3619
    return;
3620
  }
3621
3622
  fprintf(f, "bsize,redo,");
3623
  for (int part = 0; part < ALL_PARTITION_TYPES; part++) {
3624
    fprintf(f, "decision_%d,", part);
3625
  }
3626
  for (int part = 0; part < ALL_PARTITION_TYPES; part++) {
3627
    fprintf(f, "attempt_%d,", part);
3628
  }
3629
  for (int part = 0; part < ALL_PARTITION_TYPES; part++) {
3630
    fprintf(f, "time_%d,", part);
3631
  }
3632
  fprintf(f, "\n");
3633
3634
  for (int bsize_idx = 0; bsize_idx < BLOCK_SIZES_ALL; bsize_idx++) {
3635
    fprintf(f, "%d,%d,", bsize_idx, part_stats->partition_redo);
3636
    for (int part = 0; part < ALL_PARTITION_TYPES; part++) {
3637
      fprintf(f, "%d,", part_stats->partition_decisions[bsize_idx][part]);
3638
    }
3639
    for (int part = 0; part < ALL_PARTITION_TYPES; part++) {
3640
      fprintf(f, "%d,", part_stats->partition_attempts[bsize_idx][part]);
3641
    }
3642
    for (int part = 0; part < ALL_PARTITION_TYPES; part++) {
3643
      fprintf(f, "%" PRId64 ",", part_stats->partition_times[bsize_idx][part]);
3644
    }
3645
    fprintf(f, "\n");
3646
  }
3647
  fclose(f);
3648
}
3649
#endif  // CONFIG_COLLECT_PARTITION_STATS == 2
3650
3651
#if CONFIG_COLLECT_COMPONENT_TIMING
3652
static INLINE void start_timing(AV2_COMP *cpi, int component) {
3653
  avm_usec_timer_start(&cpi->component_timer[component]);
3654
}
3655
static INLINE void end_timing(AV2_COMP *cpi, int component) {
3656
  avm_usec_timer_mark(&cpi->component_timer[component]);
3657
  cpi->frame_component_time[component] +=
3658
      avm_usec_timer_elapsed(&cpi->component_timer[component]);
3659
}
3660
3661
static INLINE char const *get_frame_type_enum(int type) {
3662
  switch (type) {
3663
    case 0: return "KEY_FRAME";
3664
    case 1: return "INTER_FRAME";
3665
    case 2: return "INTRA_ONLY_FRAME";
3666
    case 3: return "S_FRAME";
3667
    default: assert(0);
3668
  }
3669
  return "error";
3670
}
3671
#endif
3672
void enc_bru_swap_stage(AV2_COMP *cpi);
3673
void enc_bru_swap_ref(AV2_COMMON *const cm);
3674
3675
0
static INLINE void check_ref_count_status_enc(AV2_COMP *cpi) {
3676
0
  AV2_COMMON *const cm = &cpi->common;
3677
0
  RefCntBuffer *const frame_bufs = cm->buffer_pool->frame_bufs;
3678
0
3679
0
  for (int i = 0; i < FRAME_BUFFERS; ++i) {
3680
0
    int ref_frame_map_cnt = 0, cur_frame_cnt = 0, scaled_ref_cnt = 0;
3681
0
    int calculated_ref_count = 0;
3682
0
    for (int j = 0; j < REF_FRAMES; ++j) {
3683
0
      if (cm->ref_frame_map[j] && cm->ref_frame_map[j] == &frame_bufs[i])
3684
0
        ref_frame_map_cnt++;
3685
0
    }
3686
0
    if (cm->cur_frame && cm->cur_frame == &frame_bufs[i]) cur_frame_cnt++;
3687
0
    for (int j = 0; j < INTER_REFS_PER_FRAME; ++j) {
3688
0
      if (cpi->scaled_ref_buf[j] && cpi->scaled_ref_buf[j] == &frame_bufs[i])
3689
0
        scaled_ref_cnt++;
3690
0
    }
3691
0
    calculated_ref_count = ref_frame_map_cnt + cur_frame_cnt + scaled_ref_cnt;
3692
0
3693
0
    if (frame_bufs[i].ref_count != calculated_ref_count) {
3694
0
      avm_internal_error(&cm->error, AVM_CODEC_MEM_ERROR,
3695
0
                         "The ref_count value is not matched on the encoder");
3696
0
    }
3697
0
  }
3698
0
}
3699
3700
// Returns true if current frame is a shown (visible) keyframe.
3701
static INLINE bool av2_is_shown_keyframe(const AV2_COMP *cpi,
3702
0
                                         FRAME_TYPE frame_type) {
3703
0
  return (frame_type == KEY_FRAME) && !cpi->no_show_fwd_kf;
3704
0
}
3705
3706
/*!\endcond */
3707
3708
#ifdef __cplusplus
3709
}  // extern "C"
3710
#endif
3711
3712
#endif  // AVM_AV2_ENCODER_ENCODER_H_