-
Notifications
You must be signed in to change notification settings - Fork 252
/
encoder.rs
3858 lines (3527 loc) · 115 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-2023, 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 std::collections::VecDeque;
use std::io::Write;
use std::mem::MaybeUninit;
use std::sync::Arc;
use std::{fmt, io, mem};
use arg_enum_proc_macro::ArgEnum;
use arrayvec::*;
use bitstream_io::{BigEndian, BitWrite, BitWriter};
use rayon::iter::*;
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::{
luma_ac, AngleDelta, IntraEdgeFilterParameters, IntraParam, PredictionMode,
};
use crate::quantize::*;
use crate::rate::{
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::*;
#[allow(dead_code)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CDEFSearchMethod {
PickFromQ,
FastSearch,
FullSearch,
}
#[inline(always)]
fn poly2(q: f32, a: f32, b: f32, c: f32, max: i32) -> i32 {
clamp((q * q).mul_add(a, q.mul_add(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: RefMEStats,
pub output_frameno: u64,
pub segmentation: SegmentationState,
}
#[derive(Debug, Clone, Default)]
pub struct ReferenceFramesSet<T: Pixel> {
pub frames: [Option<Arc<ReferenceFrame<T>>>; REF_FRAMES],
pub deblock: [DeblockState; REF_FRAMES],
}
impl<T: Pixel> ReferenceFramesSet<T> {
pub fn new() -> Self {
Self { frames: Default::default(), deblock: Default::default() }
}
}
#[wasm_bindgen]
#[derive(
ArgEnum, Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Default,
)]
#[repr(C)]
pub enum Tune {
Psnr,
#[default]
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,
/// 0 - force off
/// 1 - force on
/// 2 - adaptive
pub force_screen_content_tools: u32,
/// 0 - Not to force. MV can be in 1/4 or 1/8
/// 1 - force to integer
/// 2 - adaptive
pub force_integer_mv: u32,
/// Video is a single frame still picture
pub still_picture: bool,
/// Use reduced header for still picture
pub reduced_still_picture_hdr: bool,
/// enables/disables `filter_intra`
pub enable_filter_intra: bool,
/// enables/disables corner/edge filtering and upsampling
pub enable_intra_edge_filter: bool,
/// enables/disables `interintra_compound`
pub enable_interintra_compound: bool,
/// enables/disables masked compound
pub enable_masked_compound: bool,
/// 0 - disable dual interpolation filter
/// 1 - enable vert/horiz filter selection
pub enable_dual_filter: 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_order_hint: bool,
/// 0 - disable joint compound modes
/// 1 - enable it
pub enable_jnt_comp: bool,
/// 0 - disable ref frame mvs
/// 1 - enable it
pub enable_ref_frame_mvs: bool,
/// 0 - disable warped motion for sequence
/// 1 - enable it for the sequence
pub enable_warped_motion: 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_superres: bool,
/// To turn on/off CDEF
pub enable_cdef: bool,
/// To turn on/off loop restoration
pub enable_restoration: bool,
/// To turn on/off larger-than-superblock loop restoration units
pub enable_large_lru: bool,
/// allow encoder to delay loop filter RDO/coding until after frame reconstruciton is complete
pub enable_delayed_loopfilter_rdo: bool,
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_idx: [u8; MAX_NUM_OPERATING_POINTS],
/// `seq_tier` in the spec. One bit: 0 or 1.
pub tier: [usize; MAX_NUM_OPERATING_POINTS],
pub film_grain_params_present: bool,
pub timing_info_present: bool,
pub tiling: TilingInfo,
pub time_base: Rational,
}
impl Sequence {
/// # Panics
///
/// Panics if the resulting tile sizes would be too large.
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 {
u8::from(config.chroma_sampling == ChromaSampling::Cs444)
};
let operating_point_idc: [u16; MAX_NUM_OPERATING_POINTS] =
[0; MAX_NUM_OPERATING_POINTS];
let level_idx: [u8; MAX_NUM_OPERATING_POINTS] =
if let Some(level_idx) = config.level_idx {
[level_idx; MAX_NUM_OPERATING_POINTS]
} else {
[31; MAX_NUM_OPERATING_POINTS]
};
let tier: [usize; MAX_NUM_OPERATING_POINTS] =
[0; MAX_NUM_OPERATING_POINTS];
// 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_idx,
tier,
film_grain_params_present: config
.film_grain_params
.as_ref()
.map(|entries| !entries.is_empty())
.unwrap_or(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: RefMEStats,
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)),
)
}
/// Similar to [`FrameState::new_with_frame`], but takes an `me_stats`
/// and `rec` to enable reusing the same underlying allocations to create
/// a `FrameState`
///
/// This function primarily exists for [`estimate_inter_costs`], and so
/// it does not create hres or qres versions of `frame` as downscaling is
/// somewhat expensive and are not needed for [`estimate_inter_costs`].
pub fn new_with_frame_and_me_stats_and_rec(
fi: &FrameInvariants<T>, frame: Arc<Frame<T>>, me_stats: RefMEStats,
rec: Arc<Frame<T>>,
) -> Self {
let rs = RestorationState::new(fi, &frame);
let hres = Plane::new(0, 0, 0, 0, 0, 0);
let qres = Plane::new(0, 0, 0, 0, 0, 0);
Self {
sb_size_log2: fi.sb_size_log2(),
input: frame,
input_hres: Arc::new(hres),
input_qres: Arc::new(qres),
rec,
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: me_stats,
enc_stats: Default::default(),
}
}
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(),
}
}
pub fn apply_tile_state_mut<F, R>(&mut self, f: F) -> R
where
F: FnOnce(&mut TileStateMut<'_, T>) -> R,
{
let PlaneConfig { width, height, .. } = self.rec.planes[0].cfg;
let sbo_0 = PlaneSuperBlockOffset(SuperBlockOffset { x: 0, y: 0 });
let frame_me_stats = self.frame_me_stats.clone();
let frame_me_stats = &mut *frame_me_stats.write().expect("poisoned lock");
let ts = &mut TileStateMut::new(
self,
sbo_0,
self.sb_size_log2,
width,
height,
frame_me_stats,
);
f(ts)
}
}
#[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, Default)]
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],
pub threshold: [DistortionScale; 7],
pub min_segment: u8,
pub max_segment: u8,
}
impl SegmentationState {
#[profiling::function]
pub fn update_threshold(&mut self, base_q_idx: u8, bd: usize) {
let base_ac_q = ac_q(base_q_idx, 0, bd).get() as u64;
let real_ac_q = ArrayVec::<_, MAX_SEGMENTS>::from_iter(
self.data[..=self.max_segment as usize].iter().map(|data| {
ac_q(base_q_idx, data[SegLvl::SEG_LVL_ALT_Q as usize] as i8, bd).get()
as u64
}),
);
self.threshold.fill(DistortionScale(0));
for ((q1, q2), threshold) in
real_ac_q.iter().skip(1).zip(&real_ac_q).zip(&mut self.threshold)
{
*threshold = DistortionScale::new(base_ac_q.pow(2), q1 * q2);
}
}
#[cfg(feature = "dump_lookahead_data")]
pub fn dump_threshold(
&self, data_location: std::path::PathBuf, input_frameno: u64,
) {
use byteorder::{NativeEndian, WriteBytesExt};
let file_name = format!("{:010}-thresholds", input_frameno);
let max_segment = self.max_segment;
// dynamic allocation: debugging only
let mut buf = vec![];
buf.write_u64::<NativeEndian>(max_segment as u64).unwrap();
for &v in &self.threshold[..max_segment as usize] {
buf.write_u32::<NativeEndian>(v.0).unwrap();
}
::std::fs::write(data_location.join(file_name).with_extension("bin"), buf)
.unwrap();
}
}
// 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 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: [DistortionScale; 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,
pub enable_segmentation: bool,
pub t35_metadata: Box<[T35]>,
/// Target CPU feature level.
pub cpu_feature_level: crate::cpu_features::CpuFeatureLevel,
// These will be set if this is a coded (non-SEF) frame.
// We do not need them for SEFs.
pub coded_frame_data: Option<CodedFrameData<T>>,
}
/// These frame invariants are only used on coded frames, i.e. non-SEFs.
/// They are stored separately to avoid useless allocations
/// when we do not need them.
///
/// Currently this consists only of lookahaed data.
/// This may change in the future.
#[derive(Debug, Clone)]
pub struct CodedFrameData<T: Pixel> {
/// 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]>,
pub activity_mask: ActivityMask,
/// Combined metric of activity and distortion
pub spatiotemporal_scores: Box<[DistortionScale]>,
}
impl<T: Pixel> CodedFrameData<T> {
pub fn new(fi: &FrameInvariants<T>) -> CodedFrameData<T> {
// Width and height are padded to 8×8 block size.
let w_in_imp_b = fi.w_in_b / 2;
let h_in_imp_b = fi.h_in_b / 2;
CodedFrameData {
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(),
activity_mask: Default::default(),
spatiotemporal_scores: Default::default(),
}
}
// Assumes that we have already computed activity scales and distortion scales
// Returns -0.5 log2(mean(scale))
#[profiling::function]
pub fn compute_spatiotemporal_scores(&mut self) -> i64 {
let mut scores = self
.distortion_scales
.iter()
.zip(self.activity_scales.iter())
.map(|(&d, &a)| d * a)
.collect::<Box<_>>();
let inv_mean = DistortionScale::inv_mean(&scores);
for score in scores.iter_mut() {
*score *= inv_mean;
}
for scale in self.distortion_scales.iter_mut() {
*scale *= inv_mean;
}
self.spatiotemporal_scores = scores;
inv_mean.blog64() >> 1
}
// Assumes that we have already computed distortion_scales
// Returns -0.5 log2(mean(scale))
#[profiling::function]
pub fn compute_temporal_scores(&mut self) -> i64 {
let inv_mean = DistortionScale::inv_mean(&self.distortion_scales);
for scale in self.distortion_scales.iter_mut() {
*scale *= inv_mean;
}
self.spatiotemporal_scores.clone_from(&self.distortion_scales);
inv_mean.blog64() >> 1
}
#[cfg(feature = "dump_lookahead_data")]
pub fn dump_scales(
&self, data_location: std::path::PathBuf, scales: Scales,
input_frameno: u64,
) {
use byteorder::{NativeEndian, WriteBytesExt};
let file_name = format!(
"{:010}-{}",
input_frameno,
match scales {
Scales::ActivityScales => "activity_scales",
Scales::DistortionScales => "distortion_scales",
Scales::SpatiotemporalScales => "spatiotemporal_scales",
}
);
// dynamic allocation: debugging only
let mut buf = vec![];
buf.write_u64::<NativeEndian>(self.w_in_imp_b as u64).unwrap();
buf.write_u64::<NativeEndian>(self.h_in_imp_b as u64).unwrap();
for &v in match scales {
Scales::ActivityScales => &self.activity_scales[..],
Scales::DistortionScales => &self.distortion_scales[..],
Scales::SpatiotemporalScales => &self.spatiotemporal_scores[..],
} {
buf.write_u32::<NativeEndian>(v.0).unwrap();
}
::std::fs::write(data_location.join(file_name).with_extension("bin"), buf)
.unwrap();
}
}
#[cfg(feature = "dump_lookahead_data")]
pub enum Scales {
ActivityScales,
DistortionScales,
SpatiotemporalScales,
}
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)]
/// # Panics
///
/// - If the size of `T` does not match the sequence's bit depth
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.transform.reduced_tx_set;
let use_tx_domain_distortion = config.tune == Tune::Psnr
&& config.speed_settings.transform.tx_domain_distortion;
let use_tx_domain_rate = config.speed_settings.transform.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
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,
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.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: Default::default(),
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,
cpu_feature_level: Default::default(),
enable_segmentation: config.speed_settings.segmentation
!= SegmentationLevel::Disabled,
enable_inter_txfm_split: config
.speed_settings
.transform
.enable_inter_tx_split,
t35_metadata: Box::new([]),
sequence,
config,
coded_frame_data: None,
}
}
pub fn new_key_frame(
config: Arc<EncoderConfig>, sequence: Arc<Sequence>,
gop_input_frameno_start: u64, t35_metadata: Box<[T35]>,
) -> Self {
let tx_mode_select = config.speed_settings.transform.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.coded_frame_data = Some(CodedFrameData::new(&fi));
fi.t35_metadata = t35_metadata;
fi
}
/// Returns the created `FrameInvariants`, or `None` if this should be
/// a placeholder frame.
pub(crate) fn new_inter_frame(
previous_coded_fi: &Self, inter_cfg: &InterConfig,
gop_input_frameno_start: u64, output_frameno_in_gop: u64,
next_keyframe_input_frameno: u64, error_resilient: bool,
t35_metadata: Box<[T35]>,
) -> Option<Self> {
let input_frameno = inter_cfg
.get_input_frameno(output_frameno_in_gop, gop_input_frameno_start);
if input_frameno >= next_keyframe_input_frameno {
// This is an invalid frame. We set it as a placeholder in the FI list.
return None;
}
// We have this special thin clone method to avoid cloning the
// quite large lookahead data for SEFs, when it is not needed.
let mut fi = previous_coded_fi.clone_without_coded_data();
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;
let show_existing_frame =
inter_cfg.get_show_existing_frame(fi.idx_in_group_output);
if !show_existing_frame {
fi.coded_frame_data.clone_from(&previous_coded_fi.coded_frame_data);
}
fi.order_hint =
inter_cfg.get_order_hint(output_frameno_in_gop, fi.idx_in_group_output);
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)
{