-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencoder.rs
3573 lines (3263 loc) · 107 KB
/
encoder.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2018-2020, The rav1e contributors. All rights reserved
//
// This source code is subject to the terms of the BSD 2 Clause License and
// the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
// was not distributed with this source code in the LICENSE file, you can
// obtain it at www.aomedia.org/license/software. If the Alliance for Open
// Media Patent License 1.0 was not distributed with this source code in the
// PATENTS file, you can obtain it at www.aomedia.org/license/patent.
use crate::activity::*;
use crate::api::*;
use crate::cdef::*;
use crate::context::*;
use crate::deblock::*;
use crate::ec::*;
use crate::frame::*;
use crate::header::*;
use crate::lrf::*;
use crate::mc::{FilterMode, MotionVector};
use crate::me::*;
use crate::partition::PartitionType::*;
use crate::partition::RefType::*;
use crate::partition::*;
use crate::predict::{
AngleDelta, IntraEdgeFilterParameters, IntraParam, PredictionMode,
};
use crate::quantize::*;
use crate::rate::{
bexp64, q57, QuantizerParameters, FRAME_SUBTYPE_I, FRAME_SUBTYPE_P, QSCALE,
};
use crate::rdo::*;
use crate::segmentation::*;
use crate::serialize::{Deserialize, Serialize};
use crate::stats::EncoderStats;
use crate::tiling::*;
use crate::transform::*;
use crate::util::*;
use crate::wasm_bindgen::*;
use crate::hidden_info::HiddenInformationContainer;
use arg_enum_proc_macro::ArgEnum;
use arrayvec::*;
use bitstream_io::{BigEndian, BitWrite, BitWriter};
use std::collections::VecDeque;
use std::io::Write;
use std::mem::MaybeUninit;
use std::sync::Arc;
use std::{fmt, io, mem};
use rust_hawktracer::*;
#[allow(dead_code)]
#[derive(Debug, Clone, PartialEq)]
pub enum CDEFSearchMethod {
PickFromQ,
FastSearch,
FullSearch,
}
#[inline(always)]
fn poly2(q: f32, a: f32, b: f32, c: f32, max: i32) -> i32 {
clamp((q * q * a + q * b + c).round() as i32, 0, max)
}
pub static TEMPORAL_DELIMITER: [u8; 2] = [0x12, 0x00];
const MAX_NUM_TEMPORAL_LAYERS: usize = 8;
const MAX_NUM_SPATIAL_LAYERS: usize = 4;
const MAX_NUM_OPERATING_POINTS: usize =
MAX_NUM_TEMPORAL_LAYERS * MAX_NUM_SPATIAL_LAYERS;
/// Size of blocks for the importance computation, in pixels.
pub const IMPORTANCE_BLOCK_SIZE: usize =
1 << (IMPORTANCE_BLOCK_TO_BLOCK_SHIFT + BLOCK_TO_PLANE_SHIFT);
#[derive(Debug, Clone)]
pub struct ReferenceFrame<T: Pixel> {
pub order_hint: u32,
pub width: u32,
pub height: u32,
pub render_width: u32,
pub render_height: u32,
pub frame: Arc<Frame<T>>,
pub input_hres: Arc<Plane<T>>,
pub input_qres: Arc<Plane<T>>,
pub cdfs: CDFContext,
pub frame_me_stats: Arc<[FrameMEStats; REF_FRAMES as usize]>,
pub output_frameno: u64,
pub segmentation: SegmentationState,
}
#[derive(Debug, Clone, Default)]
pub struct ReferenceFramesSet<T: Pixel> {
pub frames: [Option<Arc<ReferenceFrame<T>>>; REF_FRAMES as usize],
pub deblock: [DeblockState; REF_FRAMES as usize],
}
impl<T: Pixel> ReferenceFramesSet<T> {
pub fn new() -> Self {
Self { frames: Default::default(), deblock: Default::default() }
}
}
#[wasm_bindgen]
#[derive(ArgEnum, Copy, Clone, Debug, PartialEq, Serialize, Deserialize)]
#[repr(C)]
pub enum Tune {
Psnr,
Psychovisual,
}
impl Default for Tune {
fn default() -> Self {
Tune::Psychovisual
}
}
const FRAME_ID_LENGTH: u32 = 15;
const DELTA_FRAME_ID_LENGTH: u32 = 14;
#[derive(Copy, Clone, Debug)]
pub struct Sequence {
// OBU Sequence header of AV1
pub profile: u8,
pub num_bits_width: u32,
pub num_bits_height: u32,
pub bit_depth: usize,
pub chroma_sampling: ChromaSampling,
pub chroma_sample_position: ChromaSamplePosition,
pub pixel_range: PixelRange,
pub color_description: Option<ColorDescription>,
pub mastering_display: Option<MasteringDisplay>,
pub content_light: Option<ContentLight>,
pub max_frame_width: u32,
pub max_frame_height: u32,
pub frame_id_numbers_present_flag: bool,
pub frame_id_length: u32,
pub delta_frame_id_length: u32,
pub use_128x128_superblock: bool,
pub order_hint_bits_minus_1: u32,
pub force_screen_content_tools: u32, // 0 - force off
// 1 - force on
// 2 - adaptive
pub force_integer_mv: u32, // 0 - Not to force. MV can be in 1/4 or 1/8
// 1 - force to integer
// 2 - adaptive
pub still_picture: bool, // Video is a single frame still picture
pub reduced_still_picture_hdr: bool, // Use reduced header for still picture
pub enable_filter_intra: bool, // enables/disables filter_intra
pub enable_intra_edge_filter: bool, // enables/disables corner/edge filtering and upsampling
pub enable_interintra_compound: bool, // enables/disables interintra_compound
pub enable_masked_compound: bool, // enables/disables masked compound
pub enable_dual_filter: bool, // 0 - disable dual interpolation filter
// 1 - enable vert/horiz filter selection
pub enable_order_hint: bool, // 0 - disable order hint, and related tools
// jnt_comp, ref_frame_mvs, frame_sign_bias
// if 0, enable_jnt_comp and
// enable_ref_frame_mvs must be set zs 0.
pub enable_jnt_comp: bool, // 0 - disable joint compound modes
// 1 - enable it
pub enable_ref_frame_mvs: bool, // 0 - disable ref frame mvs
// 1 - enable it
pub enable_warped_motion: bool, // 0 - disable warped motion for sequence
// 1 - enable it for the sequence
pub enable_superres: bool, // 0 - Disable superres for the sequence, and disable
// transmitting per-frame superres enabled flag.
// 1 - Enable superres for the sequence, and also
// enable per-frame flag to denote if superres is
// enabled for that frame.
pub enable_cdef: bool, // To turn on/off CDEF
pub enable_restoration: bool, // To turn on/off loop restoration
pub enable_large_lru: bool, // To turn on/off larger-than-superblock loop restoration units
pub enable_delayed_loopfilter_rdo: bool, // allow encoder to delay loop filter RDO/coding until after frame reconstruciton is complete
pub operating_points_cnt_minus_1: usize,
pub operating_point_idc: [u16; MAX_NUM_OPERATING_POINTS],
pub display_model_info_present_flag: bool,
pub decoder_model_info_present_flag: bool,
pub level: [[usize; 2]; MAX_NUM_OPERATING_POINTS], // minor, major
pub tier: [usize; MAX_NUM_OPERATING_POINTS], // seq_tier in the spec. One bit: 0
// or 1.
pub film_grain_params_present: bool,
pub timing_info_present: bool,
pub tiling: TilingInfo,
pub time_base: Rational,
}
impl Sequence {
pub fn new(config: &EncoderConfig) -> Sequence {
let width_bits = 32 - (config.width as u32).leading_zeros();
let height_bits = 32 - (config.height as u32).leading_zeros();
assert!(width_bits <= 16);
assert!(height_bits <= 16);
let profile = if config.bit_depth == 12
|| config.chroma_sampling == ChromaSampling::Cs422
{
2
} else if config.chroma_sampling == ChromaSampling::Cs444 {
1
} else {
0
};
let mut operating_point_idc: [u16; MAX_NUM_OPERATING_POINTS] =
[0; MAX_NUM_OPERATING_POINTS];
let mut level: [[usize; 2]; MAX_NUM_OPERATING_POINTS] =
[[1, 2]; MAX_NUM_OPERATING_POINTS];
let mut tier: [usize; MAX_NUM_OPERATING_POINTS] =
[0; MAX_NUM_OPERATING_POINTS];
for i in 0..MAX_NUM_OPERATING_POINTS {
operating_point_idc[i] = 0;
level[i][0] = 1; // minor
level[i][1] = 2; // major
tier[i] = 0;
}
// Restoration filters are not useful for very small frame sizes,
// so disable them in that case.
let enable_restoration_filters = config.width >= 32 && config.height >= 32;
let use_128x128_superblock = false;
let frame_rate = config.frame_rate();
let sb_size_log2 = Self::sb_size_log2(use_128x128_superblock);
let mut tiling = TilingInfo::from_target_tiles(
sb_size_log2,
config.width,
config.height,
frame_rate,
TilingInfo::tile_log2(1, config.tile_cols).unwrap(),
TilingInfo::tile_log2(1, config.tile_rows).unwrap(),
config.chroma_sampling == ChromaSampling::Cs422,
);
if config.tiles > 0 {
let mut tile_rows_log2 = 0;
let mut tile_cols_log2 = 0;
while (tile_rows_log2 < tiling.max_tile_rows_log2)
|| (tile_cols_log2 < tiling.max_tile_cols_log2)
{
tiling = TilingInfo::from_target_tiles(
sb_size_log2,
config.width,
config.height,
frame_rate,
tile_cols_log2,
tile_rows_log2,
config.chroma_sampling == ChromaSampling::Cs422,
);
if tiling.rows * tiling.cols >= config.tiles {
break;
};
if ((tiling.tile_height_sb >= tiling.tile_width_sb)
&& (tiling.tile_rows_log2 < tiling.max_tile_rows_log2))
|| (tile_cols_log2 >= tiling.max_tile_cols_log2)
{
tile_rows_log2 += 1;
} else {
tile_cols_log2 += 1;
}
}
}
Sequence {
tiling,
profile,
num_bits_width: width_bits,
num_bits_height: height_bits,
bit_depth: config.bit_depth,
chroma_sampling: config.chroma_sampling,
chroma_sample_position: config.chroma_sample_position,
pixel_range: config.pixel_range,
color_description: config.color_description,
mastering_display: config.mastering_display,
content_light: config.content_light,
max_frame_width: config.width as u32,
max_frame_height: config.height as u32,
frame_id_numbers_present_flag: false,
frame_id_length: FRAME_ID_LENGTH,
delta_frame_id_length: DELTA_FRAME_ID_LENGTH,
use_128x128_superblock,
order_hint_bits_minus_1: 5,
force_screen_content_tools: if config.still_picture { 2 } else { 0 },
force_integer_mv: 2,
still_picture: config.still_picture,
reduced_still_picture_hdr: config.still_picture,
enable_filter_intra: false,
enable_intra_edge_filter: true,
enable_interintra_compound: false,
enable_masked_compound: false,
enable_dual_filter: false,
enable_order_hint: !config.still_picture,
enable_jnt_comp: false,
enable_ref_frame_mvs: false,
enable_warped_motion: false,
enable_superres: false,
enable_cdef: config.speed_settings.cdef && enable_restoration_filters,
enable_restoration: config.speed_settings.lrf
&& enable_restoration_filters,
enable_large_lru: true,
enable_delayed_loopfilter_rdo: true,
operating_points_cnt_minus_1: 0,
operating_point_idc,
display_model_info_present_flag: false,
decoder_model_info_present_flag: false,
level,
tier,
film_grain_params_present: false,
timing_info_present: config.enable_timing_info,
time_base: config.time_base,
}
}
pub const fn get_relative_dist(&self, a: u32, b: u32) -> i32 {
let diff = a as i32 - b as i32;
let m = 1 << self.order_hint_bits_minus_1;
(diff & (m - 1)) - (diff & m)
}
pub fn get_skip_mode_allowed<T: Pixel>(
&self, fi: &FrameInvariants<T>, inter_cfg: &InterConfig,
reference_select: bool,
) -> bool {
if fi.intra_only || !reference_select || !self.enable_order_hint {
return false;
}
let mut forward_idx: isize = -1;
let mut backward_idx: isize = -1;
let mut forward_hint = 0;
let mut backward_hint = 0;
for i in inter_cfg.allowed_ref_frames().iter().map(|rf| rf.to_index()) {
if let Some(ref rec) = fi.rec_buffer.frames[fi.ref_frames[i] as usize] {
let ref_hint = rec.order_hint;
if self.get_relative_dist(ref_hint, fi.order_hint) < 0 {
if forward_idx < 0
|| self.get_relative_dist(ref_hint, forward_hint) > 0
{
forward_idx = i as isize;
forward_hint = ref_hint;
}
} else if self.get_relative_dist(ref_hint, fi.order_hint) > 0
&& (backward_idx < 0
|| self.get_relative_dist(ref_hint, backward_hint) > 0)
{
backward_idx = i as isize;
backward_hint = ref_hint;
}
}
}
if forward_idx < 0 {
false
} else if backward_idx >= 0 {
// set skip_mode_frame
true
} else {
let mut second_forward_idx: isize = -1;
let mut second_forward_hint = 0;
for i in inter_cfg.allowed_ref_frames().iter().map(|rf| rf.to_index()) {
if let Some(ref rec) = fi.rec_buffer.frames[fi.ref_frames[i] as usize]
{
let ref_hint = rec.order_hint;
if self.get_relative_dist(ref_hint, forward_hint) < 0
&& (second_forward_idx < 0
|| self.get_relative_dist(ref_hint, second_forward_hint) > 0)
{
second_forward_idx = i as isize;
second_forward_hint = ref_hint;
}
}
}
// TODO: Set skip_mode_frame, when second_forward_idx is not less than 0.
second_forward_idx >= 0
}
}
#[inline(always)]
const fn sb_size_log2(use_128x128_superblock: bool) -> usize {
6 + (use_128x128_superblock as usize)
}
}
#[derive(Debug, Clone)]
pub struct FrameState<T: Pixel> {
pub sb_size_log2: usize,
pub input: Arc<Frame<T>>,
pub input_hres: Arc<Plane<T>>, // half-resolution version of input luma
pub input_qres: Arc<Plane<T>>, // quarter-resolution version of input luma
pub rec: Arc<Frame<T>>,
pub cdfs: CDFContext,
pub context_update_tile_id: usize, // tile id used for the CDFontext
pub max_tile_size_bytes: u32,
pub deblock: DeblockState,
pub segmentation: SegmentationState,
pub restoration: RestorationState,
// Because we only reference these within a tile context,
// these are stored per-tile for easier access.
pub frame_me_stats: Arc<[FrameMEStats; REF_FRAMES as usize]>,
pub enc_stats: EncoderStats,
}
impl<T: Pixel> FrameState<T> {
pub fn new(fi: &FrameInvariants<T>) -> Self {
// TODO(negge): Use fi.cfg.chroma_sampling when we store VideoDetails in FrameInvariants
FrameState::new_with_frame(
fi,
Arc::new(Frame::new(fi.width, fi.height, fi.sequence.chroma_sampling)),
)
}
pub fn new_with_frame(
fi: &FrameInvariants<T>, frame: Arc<Frame<T>>,
) -> Self {
let rs = RestorationState::new(fi, &frame);
let luma_width = frame.planes[0].cfg.width;
let luma_height = frame.planes[0].cfg.height;
let hres = frame.planes[0].downsampled(fi.width, fi.height);
let qres = hres.downsampled(fi.width, fi.height);
Self {
sb_size_log2: fi.sb_size_log2(),
input: frame,
input_hres: Arc::new(hres),
input_qres: Arc::new(qres),
rec: Arc::new(Frame::new(
luma_width,
luma_height,
fi.sequence.chroma_sampling,
)),
cdfs: CDFContext::new(0),
context_update_tile_id: 0,
max_tile_size_bytes: 0,
deblock: Default::default(),
segmentation: Default::default(),
restoration: rs,
frame_me_stats: FrameMEStats::new_arc_array(fi.w_in_b, fi.h_in_b),
enc_stats: Default::default(),
}
}
#[inline(always)]
pub fn as_tile_state_mut(&mut self) -> TileStateMut<'_, T> {
let PlaneConfig { width, height, .. } = self.rec.planes[0].cfg;
let sbo_0 = PlaneSuperBlockOffset(SuperBlockOffset { x: 0, y: 0 });
TileStateMut::new(self, sbo_0, self.sb_size_log2, width, height)
}
}
#[derive(Copy, Clone, Debug)]
pub struct DeblockState {
pub levels: [u8; MAX_PLANES + 1], // Y vertical edges, Y horizontal, U, V
pub sharpness: u8,
pub deltas_enabled: bool,
pub delta_updates_enabled: bool,
pub ref_deltas: [i8; REF_FRAMES],
pub mode_deltas: [i8; 2],
pub block_deltas_enabled: bool,
pub block_delta_shift: u8,
pub block_delta_multi: bool,
}
impl Default for DeblockState {
fn default() -> Self {
DeblockState {
levels: [8, 8, 4, 4],
sharpness: 0,
deltas_enabled: false, // requires delta_q_enabled
delta_updates_enabled: false,
ref_deltas: [1, 0, 0, 0, 0, -1, -1, -1],
mode_deltas: [0, 0],
block_deltas_enabled: false,
block_delta_shift: 0,
block_delta_multi: false,
}
}
}
#[derive(Copy, Clone, Debug)]
pub struct SegmentationState {
pub enabled: bool,
pub update_data: bool,
pub update_map: bool,
pub preskip: bool,
pub last_active_segid: u8,
pub features: [[bool; SegLvl::SEG_LVL_MAX as usize]; 8],
pub data: [[i16; SegLvl::SEG_LVL_MAX as usize]; 8],
}
impl Default for SegmentationState {
fn default() -> Self {
SegmentationState {
enabled: false,
update_data: false,
update_map: false,
preskip: false,
last_active_segid: 0,
features: [[false; SegLvl::SEG_LVL_MAX as usize]; 8],
data: [[0; SegLvl::SEG_LVL_MAX as usize]; 8],
}
}
}
// Frame Invariants are invariant inside a frame
#[allow(dead_code)]
#[derive(Debug, Clone)]
pub struct FrameInvariants<T: Pixel> {
pub sequence: Arc<Sequence>,
pub config: Arc<EncoderConfig>,
pub width: usize,
pub height: usize,
pub render_width: u32,
pub render_height: u32,
pub frame_size_override_flag: bool,
pub render_and_frame_size_different: bool,
pub sb_width: usize,
pub sb_height: usize,
pub w_in_b: usize,
pub h_in_b: usize,
pub input_frameno: u64,
pub order_hint: u32,
pub show_frame: bool,
pub showable_frame: bool,
pub error_resilient: bool,
pub intra_only: bool,
pub allow_high_precision_mv: bool,
pub frame_type: FrameType,
pub show_existing_frame: bool,
pub frame_to_show_map_idx: u32,
pub use_reduced_tx_set: bool,
pub reference_mode: ReferenceMode,
pub use_prev_frame_mvs: bool,
pub partition_range: PartitionRange,
pub globalmv_transformation_type: [GlobalMVMode; INTER_REFS_PER_FRAME],
pub num_tg: usize,
pub large_scale_tile: bool,
pub disable_cdf_update: bool,
pub allow_screen_content_tools: u32,
pub force_integer_mv: u32,
pub primary_ref_frame: u32,
pub refresh_frame_flags: u32, // a bitmask that specifies which
// reference frame slots will be updated with the current frame
// after it is decoded.
pub allow_intrabc: bool,
pub use_ref_frame_mvs: bool,
pub is_filter_switchable: bool,
pub is_motion_mode_switchable: bool,
pub disable_frame_end_update_cdf: bool,
pub allow_warped_motion: bool,
pub cdef_search_method: CDEFSearchMethod,
pub cdef_damping: u8,
pub cdef_bits: u8,
pub cdef_y_strengths: [u8; 8],
pub cdef_uv_strengths: [u8; 8],
pub delta_q_present: bool,
pub ref_frames: [u8; INTER_REFS_PER_FRAME],
pub ref_frame_sign_bias: [bool; INTER_REFS_PER_FRAME],
pub rec_buffer: ReferenceFramesSet<T>,
pub base_q_idx: u8,
pub dc_delta_q: [i8; 3],
pub ac_delta_q: [i8; 3],
pub lambda: f64,
pub me_lambda: f64,
pub dist_scale: [f64; 3],
pub me_range_scale: u8,
pub use_tx_domain_distortion: bool,
pub use_tx_domain_rate: bool,
pub idx_in_group_output: u64,
pub pyramid_level: u64,
pub enable_early_exit: bool,
pub tx_mode_select: bool,
pub enable_inter_txfm_split: bool,
pub default_filter: FilterMode,
/// If true, this `FrameInvariants` corresponds to an invalid frame and
/// should be ignored. Invalid frames occur when a subgop is prematurely
/// ended, for example, by a key frame or the end of the video.
pub invalid: bool,
/// Motion vectors to the _original_ reference frames (not reconstructed).
/// Used for lookahead purposes.
pub lookahead_me_stats: Arc<[FrameMEStats; REF_FRAMES as usize]>,
/// The lookahead version of `rec_buffer`, used for storing and propagating
/// the original reference frames (rather than reconstructed ones). The
/// lookahead uses both `rec_buffer` and `lookahead_rec_buffer`, where
/// `rec_buffer` contains the current frame's reference frames and
/// `lookahead_rec_buffer` contains the next frame's reference frames.
pub lookahead_rec_buffer: ReferenceFramesSet<T>,
/// Frame width in importance blocks.
pub w_in_imp_b: usize,
/// Frame height in importance blocks.
pub h_in_imp_b: usize,
/// Intra prediction cost estimations for each importance block.
pub lookahead_intra_costs: Box<[u32]>,
/// Future importance values for each importance block. That is, a value
/// indicating how much future frames depend on the block (for example, via
/// inter-prediction).
pub block_importances: Box<[f32]>,
/// Pre-computed distortion_scale.
pub distortion_scales: Box<[DistortionScale]>,
/// Pre-computed activity_scale.
pub activity_scales: Box<[DistortionScale]>,
/// Target CPU feature level.
pub cpu_feature_level: crate::cpu_features::CpuFeatureLevel,
pub activity_mask: ActivityMask,
pub enable_segmentation: bool,
}
pub(crate) const fn pos_to_lvl(pos: u64, pyramid_depth: u64) -> u64 {
// Derive level within pyramid for a frame with a given coding order position
// For example, with a pyramid of depth 2, the 2 least significant bits of the
// position determine the level:
// 00 -> 0
// 01 -> 2
// 10 -> 1
// 11 -> 2
pyramid_depth - (pos | (1 << pyramid_depth)).trailing_zeros() as u64
}
impl<T: Pixel> FrameInvariants<T> {
#[allow(clippy::erasing_op, clippy::identity_op)]
pub fn new(config: Arc<EncoderConfig>, sequence: Arc<Sequence>) -> Self {
assert!(
sequence.bit_depth <= mem::size_of::<T>() * 8,
"bit depth cannot fit into u8"
);
let (width, height) = (config.width, config.height);
let frame_size_override_flag = width as u32 != sequence.max_frame_width
|| height as u32 != sequence.max_frame_height;
let (render_width, render_height) = config.render_size();
let render_and_frame_size_different =
render_width != width || render_height != height;
let use_reduced_tx_set = config.speed_settings.reduced_tx_set;
let use_tx_domain_distortion =
config.tune == Tune::Psnr && config.speed_settings.tx_domain_distortion;
let use_tx_domain_rate = config.speed_settings.tx_domain_rate;
let w_in_b = 2 * config.width.align_power_of_two_and_shift(3); // MiCols, ((width+7)/8)<<3 >> MI_SIZE_LOG2
let h_in_b = 2 * config.height.align_power_of_two_and_shift(3); // MiRows, ((height+7)/8)<<3 >> MI_SIZE_LOG2
// Width and height are padded to 8×8 block size.
let w_in_imp_b = w_in_b / 2;
let h_in_imp_b = h_in_b / 2;
Self {
width,
height,
render_width: render_width as u32,
render_height: render_height as u32,
frame_size_override_flag,
render_and_frame_size_different,
sb_width: width.align_power_of_two_and_shift(6),
sb_height: height.align_power_of_two_and_shift(6),
w_in_b,
h_in_b,
input_frameno: 0,
order_hint: 0,
show_frame: true,
showable_frame: !sequence.reduced_still_picture_hdr,
error_resilient: false,
intra_only: true,
allow_high_precision_mv: false,
frame_type: FrameType::KEY,
show_existing_frame: false,
frame_to_show_map_idx: 0,
use_reduced_tx_set,
reference_mode: ReferenceMode::SINGLE,
use_prev_frame_mvs: false,
partition_range: config.speed_settings.partition_range,
globalmv_transformation_type: [GlobalMVMode::IDENTITY;
INTER_REFS_PER_FRAME],
num_tg: 1,
large_scale_tile: false,
disable_cdf_update: false,
allow_screen_content_tools: sequence.force_screen_content_tools,
force_integer_mv: 1,
primary_ref_frame: PRIMARY_REF_NONE,
refresh_frame_flags: ALL_REF_FRAMES_MASK,
allow_intrabc: false,
use_ref_frame_mvs: false,
is_filter_switchable: false,
is_motion_mode_switchable: false, // 0: only the SIMPLE motion mode will be used.
disable_frame_end_update_cdf: sequence.reduced_still_picture_hdr,
allow_warped_motion: false,
cdef_search_method: CDEFSearchMethod::PickFromQ,
cdef_damping: 3,
cdef_bits: 0,
cdef_y_strengths: [
0 * 4 + 0,
1 * 4 + 0,
2 * 4 + 1,
3 * 4 + 1,
5 * 4 + 2,
7 * 4 + 3,
10 * 4 + 3,
13 * 4 + 3,
],
cdef_uv_strengths: [
0 * 4 + 0,
1 * 4 + 0,
2 * 4 + 1,
3 * 4 + 1,
5 * 4 + 2,
7 * 4 + 3,
10 * 4 + 3,
13 * 4 + 3,
],
delta_q_present: false,
ref_frames: [0; INTER_REFS_PER_FRAME],
ref_frame_sign_bias: [false; INTER_REFS_PER_FRAME],
rec_buffer: ReferenceFramesSet::new(),
base_q_idx: config.quantizer as u8,
dc_delta_q: [0; 3],
ac_delta_q: [0; 3],
lambda: 0.0,
dist_scale: [1.0; 3],
me_lambda: 0.0,
me_range_scale: 1,
use_tx_domain_distortion,
use_tx_domain_rate,
idx_in_group_output: 0,
pyramid_level: 0,
enable_early_exit: true,
tx_mode_select: false,
default_filter: FilterMode::REGULAR,
invalid: false,
lookahead_me_stats: FrameMEStats::new_arc_array(w_in_b, h_in_b),
lookahead_rec_buffer: ReferenceFramesSet::new(),
w_in_imp_b,
h_in_imp_b,
// This is never used before it is assigned
lookahead_intra_costs: Box::new([]),
// dynamic allocation: once per frame
block_importances: vec![0.; w_in_imp_b * h_in_imp_b].into_boxed_slice(),
distortion_scales: vec![
DistortionScale::default();
w_in_imp_b * h_in_imp_b
]
.into_boxed_slice(),
activity_scales: vec![
DistortionScale::default();
w_in_imp_b * h_in_imp_b
]
.into_boxed_slice(),
cpu_feature_level: Default::default(),
activity_mask: Default::default(),
enable_segmentation: config.speed_settings.segmentation
!= SegmentationLevel::Disabled,
enable_inter_txfm_split: config.speed_settings.enable_inter_tx_split,
sequence,
config,
}
}
pub fn new_key_frame(
config: Arc<EncoderConfig>, sequence: Arc<Sequence>,
gop_input_frameno_start: u64,
) -> Self {
let tx_mode_select = config.speed_settings.rdo_tx_decision;
let mut fi = Self::new(config, sequence);
fi.input_frameno = gop_input_frameno_start;
fi.tx_mode_select = tx_mode_select;
fi
}
/// Returns the created FrameInvariants along with a bool indicating success.
/// This interface provides simpler usage, because we always need the produced
/// FrameInvariants regardless of success or failure.
pub(crate) fn new_inter_frame(
previous_fi: &Self, inter_cfg: &InterConfig, gop_input_frameno_start: u64,
output_frameno_in_gop: u64, next_keyframe_input_frameno: u64,
error_resilient: bool,
) -> Self {
let mut fi = previous_fi.clone();
fi.intra_only = false;
fi.force_integer_mv = 0; // note: should be 1 if fi.intra_only is true
fi.idx_in_group_output =
inter_cfg.get_idx_in_group_output(output_frameno_in_gop);
fi.tx_mode_select = fi.enable_inter_txfm_split;
fi.order_hint =
inter_cfg.get_order_hint(output_frameno_in_gop, fi.idx_in_group_output);
let input_frameno = inter_cfg
.get_input_frameno(output_frameno_in_gop, gop_input_frameno_start);
if input_frameno >= next_keyframe_input_frameno {
fi.frame_type = FrameType::INTER;
fi.show_existing_frame = false;
fi.show_frame = false;
fi.invalid = true;
return fi;
} else {
fi.invalid = false;
}
fi.pyramid_level = inter_cfg.get_level(fi.idx_in_group_output);
fi.frame_type = if (inter_cfg.switch_frame_interval > 0)
&& (output_frameno_in_gop % inter_cfg.switch_frame_interval == 0)
&& (fi.pyramid_level == 0)
{
FrameType::SWITCH
} else {
FrameType::INTER
};
fi.error_resilient =
if fi.frame_type == FrameType::SWITCH { true } else { error_resilient };
fi.frame_size_override_flag = if fi.frame_type == FrameType::SWITCH {
true
} else if fi.sequence.reduced_still_picture_hdr {
false
} else if fi.frame_type == FrameType::INTER
&& !fi.error_resilient
&& fi.render_and_frame_size_different
{
// force frame_size_with_refs() code path if render size != frame size
true
} else {
fi.width as u32 != fi.sequence.max_frame_width
|| fi.height as u32 != fi.sequence.max_frame_height
};
// this is the slot that the current frame is going to be saved into
let slot_idx = inter_cfg.get_slot_idx(fi.pyramid_level, fi.order_hint);
fi.show_frame = inter_cfg.get_show_frame(fi.idx_in_group_output);
fi.show_existing_frame =
inter_cfg.get_show_existing_frame(fi.idx_in_group_output);
fi.frame_to_show_map_idx = slot_idx;
fi.refresh_frame_flags = if fi.frame_type == FrameType::SWITCH {
ALL_REF_FRAMES_MASK
} else if fi.show_existing_frame {
0
} else {
1 << slot_idx
};
let second_ref_frame =
if fi.idx_in_group_output == 0 { LAST2_FRAME } else { ALTREF_FRAME };
let ref_in_previous_group = LAST3_FRAME;
// reuse probability estimates from previous frames only in top level frames
fi.primary_ref_frame = if fi.error_resilient || (fi.pyramid_level > 2) {
PRIMARY_REF_NONE
} else {
(ref_in_previous_group.to_index()) as u32
};
if fi.pyramid_level == 0 {
// level 0 has no forward references
// default to last P frame
fi.ref_frames = [
// calculations done relative to the slot_idx for this frame.
// the last four frames can be found by subtracting from the current slot_idx
// add 4 to prevent underflow
// TODO: maybe use order_hint here like in get_slot_idx?
// this is the previous P frame
(slot_idx + 4 - 1) as u8 % 4
; INTER_REFS_PER_FRAME];
if inter_cfg.multiref {
// use the second-previous p frame as a second reference frame
fi.ref_frames[second_ref_frame.to_index()] =
(slot_idx + 4 - 2) as u8 % 4;
}
} else {
debug_assert!(inter_cfg.multiref);
// fill in defaults
// default to backwards reference in lower level
fi.ref_frames = [{
let oh = fi.order_hint
- (inter_cfg.group_input_len as u32 >> fi.pyramid_level);
let lvl1 = pos_to_lvl(oh as u64, inter_cfg.pyramid_depth);
if lvl1 == 0 {
((oh >> inter_cfg.pyramid_depth) % 4) as u8
} else {
3 + lvl1 as u8
}
}; INTER_REFS_PER_FRAME];
// use forward reference in lower level as a second reference frame
fi.ref_frames[second_ref_frame.to_index()] = {
let oh = fi.order_hint
+ (inter_cfg.group_input_len as u32 >> fi.pyramid_level);
let lvl2 = pos_to_lvl(oh as u64, inter_cfg.pyramid_depth);
if lvl2 == 0 {
((oh >> inter_cfg.pyramid_depth) % 4) as u8
} else {
3 + lvl2 as u8
}
};
// use a reference to the previous frame in the same level
// (horizontally) as a third reference
fi.ref_frames[ref_in_previous_group.to_index()] = slot_idx as u8;
}
fi.set_ref_frame_sign_bias();
fi.reference_mode = if inter_cfg.multiref && fi.idx_in_group_output != 0 {
ReferenceMode::SELECT
} else {
ReferenceMode::SINGLE
};
fi.input_frameno = input_frameno;
fi.me_range_scale = (inter_cfg.group_input_len >> fi.pyramid_level) as u8;
fi
}
pub fn set_ref_frame_sign_bias(&mut self) {
for i in 0..INTER_REFS_PER_FRAME {
self.ref_frame_sign_bias[i] = if !self.sequence.enable_order_hint {
false
} else if let Some(ref rec) =
self.rec_buffer.frames[self.ref_frames[i] as usize]
{
let hint = rec.order_hint;
self.sequence.get_relative_dist(hint, self.order_hint) > 0
} else {
false
};
}
}
pub fn get_frame_subtype(&self) -> usize {
if self.frame_type == FrameType::KEY {
FRAME_SUBTYPE_I
} else {
FRAME_SUBTYPE_P + (self.pyramid_level as usize)
}
}
fn pick_strength_from_q(&mut self, qps: &QuantizerParameters) {
self.cdef_damping = 3 + (self.base_q_idx >> 6);
let q = bexp64(qps.log_target_q as i64 + q57(QSCALE)) as f32;
/* These coefficients were trained on libaom. */
let (y_f1, y_f2, uv_f1, uv_f2) = if !self.intra_only {
(
poly2(q, -0.0000023593946_f32, 0.0068615186_f32, 0.02709886_f32, 15),
poly2(q, -0.00000057629734_f32, 0.0013993345_f32, 0.03831067_f32, 3),
poly2(q, -0.0000007095069_f32, 0.0034628846_f32, 0.00887099_f32, 15),
poly2(q, 0.00000023874085_f32, 0.00028223585_f32, 0.05576307_f32, 3),
)
} else {
(
poly2(q, 0.0000033731974_f32, 0.008070594_f32, 0.0187634_f32, 15),
poly2(q, 0.0000029167343_f32, 0.0027798624_f32, 0.0079405_f32, 3),
poly2(q, -0.0000130790995_f32, 0.012892405_f32, -0.00748388_f32, 15),
poly2(q, 0.0000032651783_f32, 0.00035520183_f32, 0.00228092_f32, 3),
)
};
self.cdef_y_strengths[0] = (y_f1 * CDEF_SEC_STRENGTHS as i32 + y_f2) as u8;
self.cdef_uv_strengths[0] =
(uv_f1 * CDEF_SEC_STRENGTHS as i32 + uv_f2) as u8;
}
pub fn set_quantizers(&mut self, qps: &QuantizerParameters) {
self.base_q_idx = qps.ac_qi[0];
let base_q_idx = self.base_q_idx as i32;
for pi in 0..3 {
self.dc_delta_q[pi] = (qps.dc_qi[pi] as i32 - base_q_idx) as i8;
self.ac_delta_q[pi] = (qps.ac_qi[pi] as i32 - base_q_idx) as i8;
}
self.lambda =
qps.lambda * ((1 << (2 * (self.sequence.bit_depth - 8))) as f64);
self.me_lambda = self.lambda.sqrt();
self.dist_scale = qps.dist_scale;
match self.cdef_search_method {
CDEFSearchMethod::PickFromQ => {
self.pick_strength_from_q(qps);
}
// TODO: implement FastSearch and FullSearch
_ => unreachable!(),
}
}
#[inline(always)]
pub fn sb_size_log2(&self) -> usize {
self.sequence.tiling.sb_size_log2
}
}
impl<T: Pixel> fmt::Display for FrameInvariants<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Input Frame {} - {}", self.input_frameno, self.frame_type)
}
}
pub fn write_temporal_delimiter(packet: &mut dyn io::Write) -> io::Result<()> {