-
Notifications
You must be signed in to change notification settings - Fork 249
/
mod.rs
2424 lines (2194 loc) · 81.2 KB
/
mod.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, 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.
#![deny(missing_docs)]
/// Color model information
pub mod color;
#[cfg(test)]
mod test;
pub use color::*;
use arrayvec::ArrayVec;
use bitstream_io::*;
use itertools::Itertools;
use num_derive::*;
use rayon::iter::{IntoParallelIterator, ParallelIterator};
use serde_derive::{Deserialize, Serialize};
use crate::context::*;
use crate::context::{FrameBlocks, SuperBlockOffset, TileSuperBlockOffset};
use crate::cpu_features::CpuFeatureLevel;
use crate::dist::get_satd;
use crate::encoder::*;
use crate::frame::*;
use crate::metrics::calculate_frame_psnr;
use crate::partition::*;
use crate::predict::PredictionMode;
use crate::rate::RCState;
use crate::rate::FRAME_NSUBTYPES;
use crate::rate::FRAME_SUBTYPE_I;
use crate::rate::FRAME_SUBTYPE_P;
use crate::rate::FRAME_SUBTYPE_SEF;
use crate::scenechange::SceneChangeDetector;
use crate::stats::EncoderStats;
use crate::tiling::{Area, TileRect, TilingInfo};
use crate::transform::TxSize;
use crate::util::Pixel;
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::sync::Arc;
use std::{cmp, fmt, io};
// We add 1 to rdo_lookahead_frames in a bunch of places.
const MAX_RDO_LOOKAHEAD_FRAMES: usize = usize::max_value() - 1;
// TODO: use the num crate?
/// A rational number.
#[derive(Clone, Copy, Debug)]
#[repr(C)]
pub struct Rational {
/// Numerator.
pub num: u64,
/// Denominator.
pub den: u64,
}
impl Rational {
/// Creates a rational number from the given numerator and denominator.
pub fn new(num: u64, den: u64) -> Self {
Rational { num, den }
}
/// Returns a rational number that is the reciprocal of the given one.
pub fn from_reciprocal(reciprocal: Self) -> Self {
Rational { num: reciprocal.den, den: reciprocal.num }
}
/// Returns the rational number as a floating-point number.
pub fn as_f64(self) -> f64 {
self.num as f64 / self.den as f64
}
}
/// Encoder settings which impact the produced bitstream.
#[derive(Clone, Debug)]
pub struct EncoderConfig {
// output size
/// Width of the frames in pixels.
pub width: usize,
/// Height of the frames in pixels.
pub height: usize,
// data format and ancillary color information
/// Bit depth.
pub bit_depth: usize,
/// Chroma subsampling.
pub chroma_sampling: ChromaSampling,
/// Chroma sample position.
pub chroma_sample_position: ChromaSamplePosition,
/// Pixel value range.
pub pixel_range: PixelRange,
/// Content color description (primaries, transfer characteristics, matrix).
pub color_description: Option<ColorDescription>,
/// HDR mastering display parameters.
pub mastering_display: Option<MasteringDisplay>,
/// HDR content light parameters.
pub content_light: Option<ContentLight>,
/// Still picture mode flag.
pub still_picture: bool,
// encoder configuration
/// Video time base.
pub time_base: Rational,
/// The *minimum* interval between two keyframes
pub min_key_frame_interval: u64,
/// The *maximum* interval between two keyframes
pub max_key_frame_interval: u64,
/// The number of temporal units over which to distribute the reservoir
/// usage.
pub reservoir_frame_delay: Option<i32>,
/// Flag to enable low latency mode.
///
/// In this mode the frame reordering is disabled.
pub low_latency: bool,
/// The base quantizer to use.
pub quantizer: usize,
/// The minimum allowed base quantizer to use in bitrate mode.
pub min_quantizer: u8,
/// The target bitrate for the bitrate mode.
pub bitrate: i32,
/// Metric to tune the quality for.
pub tune: Tune,
/// Number of tiles horizontally. Must be a power of two.
///
/// Overridden by [`tiles`], if present.
///
/// [`tiles`]: #structfield.tiles
pub tile_cols: usize,
/// Number of tiles vertically. Must be a power of two.
///
/// Overridden by [`tiles`], if present.
///
/// [`tiles`]: #structfield.tiles
pub tile_rows: usize,
/// Total number of tiles desired.
///
/// Encoder will try to optimally split to reach this number of tiles,
/// rounded up. Overrides [`tile_cols`] and [`tile_rows`].
///
/// [`tile_cols`]: #structfield.tile_cols
/// [`tile_rows`]: #structfield.tile_rows
pub tiles: usize,
/// Number of frames to read ahead for the RDO lookahead computation.
pub rdo_lookahead_frames: usize,
/// Settings which affect the enconding speed vs. quality trade-off.
pub speed_settings: SpeedSettings,
/// If enabled, computes the PSNR values and stores them in [`Packet`].
///
/// [`Packet`]: struct.Packet.html#structfield.psnr
pub show_psnr: bool,
/// Enables dumping of internal RDO training data.
pub train_rdo: bool,
}
/// Default preset for EncoderConfig: it is a balance between quality and
/// speed. See [`with_speed_preset()`].
///
/// [`with_speed_preset()`]: struct.EncoderConfig.html#method.with_speed_preset
impl Default for EncoderConfig {
fn default() -> Self {
const DEFAULT_SPEED: usize = 5;
Self::with_speed_preset(DEFAULT_SPEED)
}
}
impl EncoderConfig {
/// This is a preset which provides default settings according to a speed
/// value in the specific range 0–10. Each speed value corresponds to a
/// different preset. See [`from_preset()`]. If the input value is greater
/// than 10, it will result in the same settings as 10.
///
/// [`from_preset()`]: struct.SpeedSettings.html#method.from_preset
pub fn with_speed_preset(speed: usize) -> Self {
EncoderConfig {
width: 640,
height: 480,
bit_depth: 8,
chroma_sampling: ChromaSampling::Cs420,
chroma_sample_position: ChromaSamplePosition::Unknown,
pixel_range: Default::default(),
color_description: None,
mastering_display: None,
content_light: None,
still_picture: false,
time_base: Rational { num: 1, den: 30 },
min_key_frame_interval: 12,
max_key_frame_interval: 240,
min_quantizer: 0,
reservoir_frame_delay: None,
low_latency: false,
quantizer: 100,
bitrate: 0,
tune: Tune::default(),
tile_cols: 0,
tile_rows: 0,
tiles: 0,
rdo_lookahead_frames: 40,
speed_settings: SpeedSettings::from_preset(speed),
show_psnr: false,
train_rdo: false,
}
}
/// Sets the minimum and maximum keyframe interval, handling special cases as needed.
pub fn set_key_frame_interval(
&mut self, min_interval: u64, max_interval: u64,
) {
self.min_key_frame_interval = min_interval;
// Map an input value of 0 to an infinite interval
self.max_key_frame_interval =
if max_interval == 0 { std::u64::MAX } else { max_interval };
}
/// Returns the video frame rate computed from [`time_base`].
///
/// [`time_base`]: #structfield.time_base
pub fn frame_rate(&self) -> f64 {
Rational::from_reciprocal(self.time_base).as_f64()
}
}
impl fmt::Display for EncoderConfig {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
let pairs = [
("keyint_min", self.min_key_frame_interval.to_string()),
("keyint_max", self.max_key_frame_interval.to_string()),
("quantizer", self.quantizer.to_string()),
("bitrate", self.bitrate.to_string()),
("min_quantizer", self.min_quantizer.to_string()),
("low_latency", self.low_latency.to_string()),
("tune", self.tune.to_string()),
("tiles", self.tiles.to_string()),
("tile_rows", self.tile_rows.to_string()),
("tile_cols", self.tile_cols.to_string()),
("rdo_lookahead_frames", self.rdo_lookahead_frames.to_string()),
("min_block_size", self.speed_settings.min_block_size.to_string()),
("multiref", self.speed_settings.multiref.to_string()),
("fast_deblock", self.speed_settings.fast_deblock.to_string()),
("reduced_tx_set", self.speed_settings.reduced_tx_set.to_string()),
(
"tx_domain_distortion",
self.speed_settings.tx_domain_distortion.to_string(),
),
("tx_domain_rate", self.speed_settings.tx_domain_rate.to_string()),
("encode_bottomup", self.speed_settings.encode_bottomup.to_string()),
("rdo_tx_decision", self.speed_settings.rdo_tx_decision.to_string()),
("prediction_modes", self.speed_settings.prediction_modes.to_string()),
("include_near_mvs", self.speed_settings.include_near_mvs.to_string()),
(
"no_scene_detection",
self.speed_settings.no_scene_detection.to_string(),
),
("diamond_me", self.speed_settings.diamond_me.to_string()),
("cdef", self.speed_settings.cdef.to_string()),
("quantizer_rdo", self.speed_settings.quantizer_rdo.to_string()),
("use_satd_subpel", self.speed_settings.use_satd_subpel.to_string()),
];
write!(
f,
"{}",
pairs.iter().map(|pair| format!("{}={}", pair.0, pair.1)).join(" ")
)
}
}
/// Contains the speed settings.
#[derive(Clone, Copy, Debug)]
pub struct SpeedSettings {
/// Minimum block size.
///
/// Must be a square block size, so e.g. 8×4 isn't allowed here.
pub min_block_size: BlockSize,
/// Enables inter-frames to have multiple reference frames.
pub multiref: bool,
/// Enables fast deblocking filter.
pub fast_deblock: bool,
/// Enables reduced transform set.
pub reduced_tx_set: bool,
/// Enables using transform-domain distortion instead of pixel-domain.
pub tx_domain_distortion: bool,
/// Enables using transform-domain rate estimation.
pub tx_domain_rate: bool,
/// Enables bottom-up encoding, rather than top-down.
pub encode_bottomup: bool,
/// Enables searching transform size and type with RDO.
pub rdo_tx_decision: bool,
/// Prediction modes to search.
pub prediction_modes: PredictionModesSetting,
/// Enables searching near motion vectors during RDO.
pub include_near_mvs: bool,
/// Disables scene-cut detection.
pub no_scene_detection: bool,
/// Enables diamond motion vector search rather than full search.
pub diamond_me: bool,
/// Enables CDEF.
pub cdef: bool,
/// Enables searching for the optimal segment ID (quantizer delta) with RDO.
///
/// When disabled, the segment ID is chosen heuristically.
pub quantizer_rdo: bool,
/// Use SATD instead of SAD for subpixel search.
pub use_satd_subpel: bool,
}
impl Default for SpeedSettings {
fn default() -> Self {
SpeedSettings {
min_block_size: BlockSize::BLOCK_16X16,
multiref: false,
fast_deblock: false,
reduced_tx_set: false,
tx_domain_distortion: false,
tx_domain_rate: false,
encode_bottomup: false,
rdo_tx_decision: false,
prediction_modes: PredictionModesSetting::Simple,
include_near_mvs: false,
no_scene_detection: false,
diamond_me: false,
cdef: false,
quantizer_rdo: false,
use_satd_subpel: false,
}
}
}
impl SpeedSettings {
/// Set the speed setting according to a numeric speed preset.
///
/// The speed settings vary depending on speed value from 0 to 10.
/// - 10 (fastest): min block size 64x64, reduced TX set, TX domain distortion, fast deblock, no scenechange detection.
/// - 9: min block size 64x64, reduced TX set, TX domain distortion, fast deblock.
/// - 8: min block size 8x8, reduced TX set, TX domain distortion, fast deblock.
/// - 7: min block size 8x8, reduced TX set, TX domain distortion.
/// - 6: min block size 8x8, reduced TX set, TX domain distortion.
/// - 5 (default): min block size 8x8, reduced TX set, TX domain distortion, complex pred modes for keyframes.
/// - 4: min block size 8x8, TX domain distortion, complex pred modes for keyframes.
/// - 3: min block size 8x8, TX domain distortion, complex pred modes for keyframes, RDO TX decision.
/// - 2: min block size 8x8, TX domain distortion, complex pred modes for keyframes, RDO TX decision, include near MVs, quantizer RDO.
/// - 1: min block size 8x8, TX domain distortion, complex pred modes, RDO TX decision, include near MVs, quantizer RDO.
/// - 0 (slowest): min block size 4x4, TX domain distortion, complex pred modes, RDO TX decision, include near MVs, quantizer RDO, bottom-up encoding.
pub fn from_preset(speed: usize) -> Self {
SpeedSettings {
min_block_size: Self::min_block_size_preset(speed),
multiref: Self::multiref_preset(speed),
fast_deblock: Self::fast_deblock_preset(speed),
reduced_tx_set: Self::reduced_tx_set_preset(speed),
tx_domain_distortion: Self::tx_domain_distortion_preset(speed),
tx_domain_rate: Self::tx_domain_rate_preset(speed),
encode_bottomup: Self::encode_bottomup_preset(speed),
rdo_tx_decision: Self::rdo_tx_decision_preset(speed),
prediction_modes: Self::prediction_modes_preset(speed),
include_near_mvs: Self::include_near_mvs_preset(speed),
no_scene_detection: Self::no_scene_detection_preset(speed),
diamond_me: Self::diamond_me_preset(speed),
cdef: Self::cdef_preset(speed),
quantizer_rdo: Self::quantizer_rdo_preset(speed),
use_satd_subpel: Self::use_satd_subpel(speed),
}
}
/// This preset is set this way because 8x8 with reduced TX set is faster but with equivalent
/// or better quality compared to 16x16 or 32x32 (to which reduced TX set does not apply).
fn min_block_size_preset(speed: usize) -> BlockSize {
let min_block_size = if speed == 0 {
BlockSize::BLOCK_4X4
} else if speed <= 8 {
BlockSize::BLOCK_8X8
} else {
BlockSize::BLOCK_64X64
};
// Topdown search checks min_block_size for PARTITION_SPLIT only, so min_block_size must be square.
assert!(min_block_size.is_sqr());
min_block_size
}
/// Multiref is enabled automatically if low_latency is false,
/// but if someone is setting low_latency to true manually,
/// multiref has a large speed penalty with low quality gain.
/// Because low_latency can be set manually, this setting is conservative.
fn multiref_preset(speed: usize) -> bool {
speed <= 1
}
fn fast_deblock_preset(speed: usize) -> bool {
speed >= 8
}
fn reduced_tx_set_preset(speed: usize) -> bool {
speed >= 5
}
/// TX domain distortion is always faster, with no significant quality change
fn tx_domain_distortion_preset(_speed: usize) -> bool {
true
}
fn tx_domain_rate_preset(_speed: usize) -> bool {
false
}
fn encode_bottomup_preset(speed: usize) -> bool {
speed == 0
}
fn rdo_tx_decision_preset(speed: usize) -> bool {
speed <= 3
}
fn prediction_modes_preset(speed: usize) -> PredictionModesSetting {
if speed <= 1 {
PredictionModesSetting::ComplexAll
} else if speed <= 5 {
PredictionModesSetting::ComplexKeyframes
} else {
PredictionModesSetting::Simple
}
}
fn include_near_mvs_preset(speed: usize) -> bool {
speed <= 2
}
fn no_scene_detection_preset(speed: usize) -> bool {
speed == 10
}
/// Currently Diamond ME gives better quality than full search on most videos,
/// in addition to being faster.
// There are a few outliers, such as the Wikipedia test clip.
// TODO: Revisit this setting if full search quality improves in the future.
fn diamond_me_preset(_speed: usize) -> bool {
true
}
fn cdef_preset(_speed: usize) -> bool {
true
}
fn quantizer_rdo_preset(speed: usize) -> bool {
speed <= 2
}
fn use_satd_subpel(speed: usize) -> bool {
speed <= 9
}
}
/// Possible types of a frame.
#[allow(dead_code, non_camel_case_types)]
#[derive(Debug, Eq, PartialEq, Clone, Copy, Serialize, Deserialize)]
#[repr(C)]
pub enum FrameType {
/// Key frame.
KEY,
/// Inter-frame.
INTER,
/// Intra-only frame.
INTRA_ONLY,
/// Switching frame.
SWITCH,
}
impl fmt::Display for FrameType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use self::FrameType::*;
match self {
KEY => write!(f, "Key frame"),
INTER => write!(f, "Inter frame"),
INTRA_ONLY => write!(f, "Intra only frame"),
SWITCH => write!(f, "Switching frame"),
}
}
}
/// Prediction modes to search.
#[derive(Clone, Copy, Debug, PartialOrd, PartialEq, FromPrimitive)]
pub enum PredictionModesSetting {
/// Only simple prediction modes.
Simple,
/// Search all prediction modes on key frames and simple modes on other
/// frames.
ComplexKeyframes,
/// Search all prediction modes on all frames.
ComplexAll,
}
impl fmt::Display for PredictionModesSetting {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(
f,
"{}",
match self {
PredictionModesSetting::Simple => "Simple",
PredictionModesSetting::ComplexKeyframes => "Complex-KFs",
PredictionModesSetting::ComplexAll => "Complex-All",
}
)
}
}
/// Contains the encoder configuration.
#[derive(Clone, Debug, Default)]
pub struct Config {
/// Settings which impact the produced bitstream.
pub enc: EncoderConfig,
/// The number of threads in the threadpool.
pub threads: usize,
}
fn check_tile_log2(n: usize) -> bool {
let tile_log2 = TilingInfo::tile_log2(1, n);
if tile_log2.is_none() {
return false;
}
let tile_log2 = tile_log2.unwrap();
((1 << tile_log2) - n) == 0 || n == 0
}
impl Config {
/// Creates a [`Context`] with this configuration.
///
/// # Examples
///
/// ```
/// use rav1e::prelude::*;
///
/// # fn main() -> Result<(), EncoderStatus> {
/// let cfg = Config::default();
/// let ctx: Context<u8> = cfg.new_context()?;
/// # Ok(())
/// # }
/// ```
///
/// [`Context`]: struct.Context.html
pub fn new_context<T: Pixel>(&self) -> Result<Context<T>, EncoderStatus> {
assert!(
8 * std::mem::size_of::<T>() >= self.enc.bit_depth,
"The Pixel u{} does not match the Config bit_depth {}",
8 * std::mem::size_of::<T>(),
self.enc.bit_depth
);
info!("CPU Feature Level: {}", CpuFeatureLevel::default());
let pool = rayon::ThreadPoolBuilder::new()
.num_threads(self.threads)
.build()
.unwrap();
let mut config = self.enc.clone();
if config.width == 0 || config.height == 0 {
return Err(EncoderStatus::Failure);
}
if config.rdo_lookahead_frames > MAX_RDO_LOOKAHEAD_FRAMES {
return Err(EncoderStatus::Failure);
}
if !check_tile_log2(config.tile_cols) {
return Err(EncoderStatus::Failure);
}
if !check_tile_log2(config.tile_rows) {
return Err(EncoderStatus::Failure);
}
// FIXME: inter unsupported with 4:2:2 and 4:4:4 chroma sampling
let chroma_sampling = config.chroma_sampling;
// FIXME: tx partition for intra not supported for chroma 422
if chroma_sampling == ChromaSampling::Cs422 {
config.speed_settings.rdo_tx_decision = false;
}
let inner = ContextInner::new(&config).ok_or(EncoderStatus::Failure)?;
Ok(Context { is_flushing: false, inner, pool, config })
}
}
/// The set of options that controls frame re-ordering and reference picture
/// selection.
/// The options stored here are invariant over the whole encode.
#[derive(Debug, Clone, Copy)]
pub(crate) struct InterConfig {
/// Whether frame re-ordering is enabled.
reorder: bool,
/// Whether P-frames can use multiple references.
pub(crate) multiref: bool,
/// The depth of the re-ordering pyramid.
/// The current code cannot support values larger than 2.
pub(crate) pyramid_depth: u64,
/// Number of input frames in group.
pub(crate) group_input_len: u64,
/// Number of output frames in group.
/// This includes both hidden frames and "show existing frame" frames.
group_output_len: u64,
}
impl InterConfig {
fn new(enc_config: &EncoderConfig) -> InterConfig {
let reorder = !enc_config.low_latency;
// A group always starts with (group_output_len - group_input_len) hidden
// frames, followed by group_input_len shown frames.
// The shown frames iterate over the input frames in order, with frames
// already encoded as hidden frames now displayed with Show Existing
// Frame.
// For example, for a pyramid depth of 2, the group is as follows:
// |TU |TU |TU |TU
// idx_in_group_output: 0 1 2 3 4 5
// input_frameno: 4 2 1 SEF 3 SEF
// output_frameno: 1 2 3 4 5 6
// level: 0 1 2 1 2 0
// ^^^^^ ^^^^^^^^^^^^^
// hidden shown
// TODO: This only works for pyramid_depth <= 2 --- after that we need
// more hidden frames in the middle of the group.
let pyramid_depth = if reorder { 2 } else { 0 };
let group_input_len = 1 << pyramid_depth;
let group_output_len = group_input_len + pyramid_depth;
InterConfig {
reorder,
multiref: reorder || enc_config.speed_settings.multiref,
pyramid_depth,
group_input_len,
group_output_len,
}
}
/// Get the index of an output frame in its re-ordering group given the output
/// frame number of the frame in the current keyframe gop.
/// When re-ordering is disabled, this always returns 0.
pub(crate) fn get_idx_in_group_output(
&self, output_frameno_in_gop: u64,
) -> u64 {
// The first frame in the GOP should be a keyframe and is not re-ordered,
// so we should not be calling this function on it.
debug_assert!(output_frameno_in_gop > 0);
(output_frameno_in_gop - 1) % self.group_output_len
}
/// Get the order-hint of an output frame given the output frame number of the
/// frame in the current keyframe gop and the index of that output frame
/// in its re-ordering gorup.
pub(crate) fn get_order_hint(
&self, output_frameno_in_gop: u64, idx_in_group_output: u64,
) -> u32 {
// The first frame in the GOP should be a keyframe, but currently this
// function only handles inter frames.
// We could return 0 for keyframes if keyframe support is needed.
debug_assert!(output_frameno_in_gop > 0);
// Which P-frame group in the current gop is this output frame in?
// Subtract 1 because the first frame in the gop is always a keyframe.
let group_idx = (output_frameno_in_gop - 1) / self.group_output_len;
// Get the offset to the corresponding input frame.
// TODO: This only works with pyramid_depth <= 2.
let offset = if idx_in_group_output < self.pyramid_depth {
self.group_input_len >> idx_in_group_output
} else {
idx_in_group_output - self.pyramid_depth + 1
};
// Construct the final order hint relative to the start of the group.
(self.group_input_len * group_idx + offset) as u32
}
/// Get the level of the current frame in the pyramid.
pub(crate) fn get_level(&self, idx_in_group_output: u64) -> u64 {
if !self.reorder {
0
} else if idx_in_group_output < self.pyramid_depth {
// Hidden frames are output first (to be shown in the future).
idx_in_group_output
} else {
// Shown frames
// TODO: This only works with pyramid_depth <= 2.
pos_to_lvl(
idx_in_group_output - self.pyramid_depth + 1,
self.pyramid_depth,
)
}
}
pub(crate) fn get_slot_idx(&self, level: u64, order_hint: u32) -> u32 {
// Frames with level == 0 are stored in slots 0..4, and frames with higher
// values of level in slots 4..8
if level == 0 {
(order_hint >> self.pyramid_depth) & 3
} else {
// This only works with pyramid_depth <= 4.
3 + level as u32
}
}
pub(crate) fn get_show_frame(&self, idx_in_group_output: u64) -> bool {
idx_in_group_output >= self.pyramid_depth
}
pub(crate) fn get_show_existing_frame(
&self, idx_in_group_output: u64,
) -> bool {
// The self.reorder test here is redundant, but short-circuits the rest,
// avoiding a bunch of work when it's false.
self.reorder
&& self.get_show_frame(idx_in_group_output)
&& (idx_in_group_output - self.pyramid_depth + 1).count_ones() == 1
&& idx_in_group_output != self.pyramid_depth
}
pub(crate) fn get_input_frameno(
&self, output_frameno_in_gop: u64, gop_input_frameno_start: u64,
) -> u64 {
if output_frameno_in_gop == 0 {
gop_input_frameno_start
} else {
let idx_in_group_output =
self.get_idx_in_group_output(output_frameno_in_gop);
let order_hint =
self.get_order_hint(output_frameno_in_gop, idx_in_group_output);
gop_input_frameno_start + order_hint as u64
}
}
fn max_reordering_latency(&self) -> u64 {
self.group_input_len
}
pub(crate) fn keyframe_lookahead_distance(&self) -> u64 {
cmp::max(1, self.max_reordering_latency()) + 1
}
}
pub(crate) struct ContextInner<T: Pixel> {
frame_count: u64,
limit: Option<u64>,
inter_cfg: InterConfig,
output_frameno: u64,
frames_processed: u64,
/// Maps *input_frameno* to frames
frame_q: BTreeMap<u64, Option<Arc<Frame<T>>>>, // packet_q: VecDeque<Packet>
/// Maps *output_frameno* to frame data
frame_invariants: BTreeMap<u64, FrameInvariants<T>>,
/// A list of the input_frameno for keyframes in this encode.
/// Needed so that we don't need to keep all of the frame_invariants in
/// memory for the whole life of the encode.
// TODO: Is this needed at all?
keyframes: BTreeSet<u64>,
// TODO: Is this needed at all?
keyframes_forced: BTreeSet<u64>,
/// A storage space for reordered frames.
packet_data: Vec<u8>,
/// Maps `output_frameno` to `gop_output_frameno_start`.
gop_output_frameno_start: BTreeMap<u64, u64>,
/// Maps `output_frameno` to `gop_input_frameno_start`.
pub(crate) gop_input_frameno_start: BTreeMap<u64, u64>,
keyframe_detector: SceneChangeDetector,
pub(crate) config: EncoderConfig,
seq: Sequence,
rc_state: RCState,
maybe_prev_log_base_q: Option<i64>,
/// The next `input_frameno` to be processed by lookahead.
next_lookahead_frame: u64,
/// The next `output_frameno` to be computed by lookahead.
next_lookahead_output_frameno: u64,
}
/// The encoder context.
///
/// Contains the encoding state.
pub struct Context<T: Pixel> {
inner: ContextInner<T>,
config: EncoderConfig,
pool: rayon::ThreadPool,
is_flushing: bool,
}
/// Status that can be returned by [`Context`] functions.
///
/// [`Context`]: struct.Context.html
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum EncoderStatus {
/// The encoder needs more data to produce an output packet.
///
/// May be emitted by [`Context::receive_packet()`] when frame reordering is
/// enabled.
///
/// [`Context::receive_packet()`]: struct.Context.html#method.receive_packet
NeedMoreData,
/// There are enough frames in the queue.
///
/// May be emitted by [`Context::send_frame()`] when trying to send a frame
/// after the encoder has been flushed.
///
/// [`Context::send_frame()`]: struct.Context.html#method.send_frame
EnoughData,
/// The encoder has already produced the number of frames requested.
///
/// May be emitted by [`Context::receive_packet()`] after a flush request had
/// been processed or the frame limit had been reached.
///
/// [`Context::receive_packet()`]: struct.Context.html#method.receive_packet
LimitReached,
/// A frame had been encoded but not emitted yet.
Encoded,
/// Generic fatal error.
Failure,
/// A frame was encoded in the first pass of a 2-pass encode, but its stats
/// data was not retrieved with [`Context::twopass_out()`], or not enough
/// stats data was provided in the second pass of a 2-pass encode to encode
/// the next frame.
///
/// [`Context::twopass_out()`]: struct.Context.html#method.twopass_out
NotReady,
}
/// Represents a packet.
///
/// A packet contains one shown frame together with zero or more additional
/// frames.
#[derive(Debug, PartialEq)]
pub struct Packet<T: Pixel> {
/// The packet data.
pub data: Vec<u8>,
/// The reconstruction of the shown frame.
pub rec: Option<Frame<T>>,
/// The number of the input frame corresponding to the one shown frame in the
/// TU stored in this packet. Since AV1 does not explicitly reorder frames,
/// these will increase sequentially.
// TODO: When we want to add VFR support, we will need a more explicit time
// stamp here.
pub input_frameno: u64,
/// Type of the shown frame.
pub frame_type: FrameType,
/// PSNR for Y, U, and V planes for the shown frame.
pub psnr: Option<(f64, f64, f64)>,
/// QP selected for the frame.
pub qp: u8,
/// Block-level encoding stats for the frame
pub enc_stats: EncoderStats,
}
impl<T: Pixel> fmt::Display for Packet<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"Frame {} - {} - {} bytes",
self.input_frameno,
self.frame_type,
self.data.len()
)
}
}
/// Types which can be converted into frames.
///
/// This trait is used in [`Context::send_frame`] to allow for passing in
/// frames with optional frame parameters and optionally frames wrapped in
/// `Arc` (to allow for zero-copy, since the encoder uses frames in `Arc`
/// internally).
///
/// [`Context::send_frame`]: struct.Context.html#method.send_frame
pub trait IntoFrame<T: Pixel> {
/// Converts the type into a tuple of frame and parameters.
fn into(self) -> (Option<Arc<Frame<T>>>, Option<FrameParameters>);
}
impl<T: Pixel> IntoFrame<T> for Option<Arc<Frame<T>>> {
fn into(self) -> (Option<Arc<Frame<T>>>, Option<FrameParameters>) {
(self, None)
}
}
impl<T: Pixel> IntoFrame<T> for Arc<Frame<T>> {
fn into(self) -> (Option<Arc<Frame<T>>>, Option<FrameParameters>) {
(Some(self), None)
}
}
impl<T: Pixel> IntoFrame<T> for (Arc<Frame<T>>, FrameParameters) {
fn into(self) -> (Option<Arc<Frame<T>>>, Option<FrameParameters>) {
(Some(self.0), Some(self.1))
}
}
impl<T: Pixel> IntoFrame<T> for (Arc<Frame<T>>, Option<FrameParameters>) {
fn into(self) -> (Option<Arc<Frame<T>>>, Option<FrameParameters>) {
(Some(self.0), self.1)
}
}
impl<T: Pixel> IntoFrame<T> for Frame<T> {
fn into(self) -> (Option<Arc<Frame<T>>>, Option<FrameParameters>) {
(Some(Arc::new(self)), None)
}
}
impl<T: Pixel> IntoFrame<T> for (Frame<T>, FrameParameters) {
fn into(self) -> (Option<Arc<Frame<T>>>, Option<FrameParameters>) {
(Some(Arc::new(self.0)), Some(self.1))
}
}
impl<T: Pixel> IntoFrame<T> for (Frame<T>, Option<FrameParameters>) {
fn into(self) -> (Option<Arc<Frame<T>>>, Option<FrameParameters>) {
(Some(Arc::new(self.0)), self.1)
}
}
impl<T: Pixel> Context<T> {
/// Allocates and returns a new frame.
///
/// # Examples
///
/// ```
/// use rav1e::prelude::*;
///
/// # fn main() -> Result<(), EncoderStatus> {
/// let cfg = Config::default();
/// let ctx: Context<u8> = cfg.new_context()?;
/// let frame = ctx.new_frame();
/// # Ok(())
/// # }
/// ```
#[inline]
pub fn new_frame(&self) -> Frame<T> {
Frame::new(
self.config.width,
self.config.height,
self.config.chroma_sampling,
)
}
/// Sends the frame for encoding.
///
/// This method adds the frame into the frame queue and runs the first passes
/// of the look-ahead computation.
///
/// Passing `None` is equivalent to calling [`flush`].
///
/// # Errors
///
/// If this method is called with a frame after the encoder has been flushed,
/// the [`EncoderStatus::EnoughData`] error is returned.
///
/// # Examples
///
/// ```
/// use rav1e::prelude::*;
///
/// # fn main() -> Result<(), EncoderStatus> {
/// let cfg = Config::default();
/// let mut ctx: Context<u8> = cfg.new_context().unwrap();
/// let f1 = ctx.new_frame();
/// let f2 = f1.clone();
/// let info = FrameParameters {
/// frame_type_override: FrameTypeOverride::Key
/// };
///
/// // Send the plain frame data
/// ctx.send_frame(f1)?;
/// // Send the data and the per-frame parameters
/// // In this case the frame is forced to be a keyframe.
/// ctx.send_frame((f2, info))?;
/// // Flush the encoder, it is equivalent to a call to `flush()`
/// ctx.send_frame(None)?;
/// # Ok(())
/// # }
/// ```
///
/// [`flush`]: #method.flush
/// [`EncoderStatus::EnoughData`]: enum.EncoderStatus.html#variant.EnoughData
#[inline]
pub fn send_frame<F>(&mut self, frame: F) -> Result<(), EncoderStatus>
where
F: IntoFrame<T>,
{
let (frame, params) = frame.into();
if frame.is_none() {
if self.is_flushing {
return Ok(());
}
self.inner.limit = Some(self.inner.frame_count);
self.is_flushing = true;
self.inner.compute_lookahead_data();
} else if self.is_flushing {