-
Notifications
You must be signed in to change notification settings - Fork 252
/
rdo.rs
2750 lines (2499 loc) · 82 KB
/
rdo.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) 2001-2016, Alliance for Open Media. All rights reserved
// Copyright (c) 2017-2022, 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.
#![allow(non_camel_case_types)]
use std::fmt;
use std::mem::MaybeUninit;
use arrayvec::*;
use itertools::izip;
use crate::api::*;
use crate::cdef::*;
use crate::context::*;
use crate::cpu_features::CpuFeatureLevel;
use crate::deblock::*;
use crate::dist::*;
use crate::ec::{Writer, WriterCounter, OD_BITRES};
use crate::encode_block_with_modes;
use crate::encoder::{FrameInvariants, IMPORTANCE_BLOCK_SIZE};
use crate::frame::*;
use crate::header::ReferenceMode;
use crate::lrf::*;
use crate::mc::MotionVector;
use crate::me::estimate_motion;
use crate::me::MVSamplingMode;
use crate::me::MotionSearchResult;
use crate::motion_compensate;
use crate::partition::PartitionType::*;
use crate::partition::RefType::*;
use crate::partition::*;
use crate::predict::{
luma_ac, AngleDelta, IntraEdgeFilterParameters, IntraParam, PredictionMode,
RAV1E_INTER_COMPOUND_MODES, RAV1E_INTER_MODES_MINIMAL, RAV1E_INTRA_MODES,
};
use crate::rdo_tables::*;
use crate::tiling::*;
use crate::transform::{TxSet, TxSize, TxType, RAV1E_TX_TYPES};
use crate::util::{init_slice_repeat_mut, Aligned, Pixel};
use crate::write_tx_blocks;
use crate::write_tx_tree;
use crate::Tune;
use crate::{encode_block_post_cdef, encode_block_pre_cdef};
#[derive(Copy, Clone, PartialEq, Eq)]
pub enum RDOType {
PixelDistRealRate,
TxDistRealRate,
TxDistEstRate,
}
impl RDOType {
#[inline]
pub const fn needs_tx_dist(self) -> bool {
match self {
// Pixel-domain distortion and exact ec rate
RDOType::PixelDistRealRate => false,
// Tx-domain distortion and exact ec rate
RDOType::TxDistRealRate => true,
// Tx-domain distortion and txdist-based rate
RDOType::TxDistEstRate => true,
}
}
#[inline]
pub const fn needs_coeff_rate(self) -> bool {
match self {
RDOType::PixelDistRealRate => true,
RDOType::TxDistRealRate => true,
RDOType::TxDistEstRate => false,
}
}
}
#[derive(Clone)]
pub struct PartitionGroupParameters {
pub rd_cost: f64,
pub part_type: PartitionType,
pub part_modes: ArrayVec<PartitionParameters, 4>,
}
#[derive(Clone, Debug)]
pub struct PartitionParameters {
pub rd_cost: f64,
pub bo: TileBlockOffset,
pub bsize: BlockSize,
pub pred_mode_luma: PredictionMode,
pub pred_mode_chroma: PredictionMode,
pub pred_cfl_params: CFLParams,
pub angle_delta: AngleDelta,
pub ref_frames: [RefType; 2],
pub mvs: [MotionVector; 2],
pub skip: bool,
pub has_coeff: bool,
pub tx_size: TxSize,
pub tx_type: TxType,
pub sidx: u8,
}
impl Default for PartitionParameters {
fn default() -> Self {
PartitionParameters {
rd_cost: f64::MAX,
bo: TileBlockOffset::default(),
bsize: BlockSize::BLOCK_32X32,
pred_mode_luma: PredictionMode::default(),
pred_mode_chroma: PredictionMode::default(),
pred_cfl_params: CFLParams::default(),
angle_delta: AngleDelta::default(),
ref_frames: [RefType::INTRA_FRAME, RefType::NONE_FRAME],
mvs: [MotionVector::default(); 2],
skip: false,
has_coeff: true,
tx_size: TxSize::TX_4X4,
tx_type: TxType::DCT_DCT,
sidx: 0,
}
}
}
pub fn estimate_rate(qindex: u8, ts: TxSize, fast_distortion: u64) -> u64 {
let bs_index = ts as usize;
let q_bin_idx = (qindex as usize) / RDO_QUANT_DIV;
let bin_idx_down =
((fast_distortion) / RATE_EST_BIN_SIZE).min((RDO_NUM_BINS - 2) as u64);
let bin_idx_up = (bin_idx_down + 1).min((RDO_NUM_BINS - 1) as u64);
let x0 = (bin_idx_down * RATE_EST_BIN_SIZE) as i64;
let x1 = (bin_idx_up * RATE_EST_BIN_SIZE) as i64;
let y0 = RDO_RATE_TABLE[q_bin_idx][bs_index][bin_idx_down as usize] as i64;
let y1 = RDO_RATE_TABLE[q_bin_idx][bs_index][bin_idx_up as usize] as i64;
let slope = ((y1 - y0) << 8) / (x1 - x0);
(y0 + (((fast_distortion as i64 - x0) * slope) >> 8)).max(0) as u64
}
#[allow(unused)]
pub fn cdef_dist_wxh<T: Pixel, F: Fn(Area, BlockSize) -> DistortionScale>(
src1: &PlaneRegion<'_, T>, src2: &PlaneRegion<'_, T>, w: usize, h: usize,
bit_depth: usize, compute_bias: F, cpu: CpuFeatureLevel,
) -> Distortion {
debug_assert!(src1.plane_cfg.xdec == 0);
debug_assert!(src1.plane_cfg.ydec == 0);
debug_assert!(src2.plane_cfg.xdec == 0);
debug_assert!(src2.plane_cfg.ydec == 0);
let mut sum = Distortion::zero();
for y in (0..h).step_by(8) {
for x in (0..w).step_by(8) {
let kernel_h = (h - y).min(8);
let kernel_w = (w - x).min(8);
let area = Area::StartingAt { x: x as isize, y: y as isize };
let value = RawDistortion(cdef_dist_kernel(
&src1.subregion(area),
&src2.subregion(area),
kernel_w,
kernel_h,
bit_depth,
cpu,
) as u64);
// cdef is always called on non-subsampled planes, so BLOCK_8X8 is
// correct here.
sum += value * compute_bias(area, BlockSize::BLOCK_8X8);
}
}
sum
}
/// Sum of Squared Error for a wxh block
/// Currently limited to w and h of valid blocks
pub fn sse_wxh<T: Pixel, F: Fn(Area, BlockSize) -> DistortionScale>(
src1: &PlaneRegion<'_, T>, src2: &PlaneRegion<'_, T>, w: usize, h: usize,
compute_bias: F, bit_depth: usize, cpu: CpuFeatureLevel,
) -> Distortion {
// See get_weighted_sse in src/dist.rs.
// Provide a scale to get_weighted_sse for each square region of this size.
const CHUNK_SIZE: usize = IMPORTANCE_BLOCK_SIZE >> 1;
// To bias the distortion correctly, compute it in blocks up to the size
// importance block size in a non-subsampled plane.
let imp_block_w = CHUNK_SIZE << src1.plane_cfg.xdec;
let imp_block_h = CHUNK_SIZE << src1.plane_cfg.ydec;
let imp_bsize = BlockSize::from_width_and_height(imp_block_w, imp_block_h);
let n_imp_blocks_w = (w + CHUNK_SIZE - 1) / CHUNK_SIZE;
let n_imp_blocks_h = (h + CHUNK_SIZE - 1) / CHUNK_SIZE;
// TODO: Copying biases into a buffer is slow. It would be best if biases were
// passed directly. To do this, we would need different versions of the
// weighted sse function for decimated/subsampled data. Also requires
// eliminating use of unbiased sse.
// It should also be noted that the current copy code does not auto-vectorize.
// Copy biases into a buffer.
let mut buf_storage = Aligned::new(
[MaybeUninit::<u32>::uninit(); 128 / CHUNK_SIZE * 128 / CHUNK_SIZE],
);
let buf_stride = n_imp_blocks_w.next_power_of_two();
let buf = init_slice_repeat_mut(
&mut buf_storage.data[..buf_stride * n_imp_blocks_h],
0,
);
for block_y in 0..n_imp_blocks_h {
for block_x in 0..n_imp_blocks_w {
let block = Area::StartingAt {
x: (block_x * CHUNK_SIZE) as isize,
y: (block_y * CHUNK_SIZE) as isize,
};
buf[block_y * buf_stride + block_x] = compute_bias(block, imp_bsize).0;
}
}
Distortion(get_weighted_sse(
src1, src2, buf, buf_stride, w, h, bit_depth, cpu,
))
}
pub const fn clip_visible_bsize(
frame_w: usize, frame_h: usize, bsize: BlockSize, x: usize, y: usize,
) -> (usize, usize) {
let blk_w = bsize.width();
let blk_h = bsize.height();
let visible_w: usize = if x + blk_w <= frame_w {
blk_w
} else if x >= frame_w {
0
} else {
frame_w - x
};
let visible_h: usize = if y + blk_h <= frame_h {
blk_h
} else if y >= frame_h {
0
} else {
frame_h - y
};
(visible_w, visible_h)
}
// Compute the pixel-domain distortion for an encode
fn compute_distortion<T: Pixel>(
fi: &FrameInvariants<T>, ts: &TileStateMut<'_, T>, bsize: BlockSize,
is_chroma_block: bool, tile_bo: TileBlockOffset, luma_only: bool,
) -> ScaledDistortion {
let area = Area::BlockStartingAt { bo: tile_bo.0 };
let input_region = ts.input_tile.planes[0].subregion(area);
let rec_region = ts.rec.planes[0].subregion(area);
// clip a block to have visible pixles only
let frame_bo = ts.to_frame_block_offset(tile_bo);
let (visible_w, visible_h) = clip_visible_bsize(
fi.width,
fi.height,
bsize,
frame_bo.0.x << MI_SIZE_LOG2,
frame_bo.0.y << MI_SIZE_LOG2,
);
if visible_w == 0 || visible_h == 0 {
return ScaledDistortion::zero();
}
let mut distortion = match fi.config.tune {
Tune::Psychovisual => cdef_dist_wxh(
&input_region,
&rec_region,
visible_w,
visible_h,
fi.sequence.bit_depth,
|bias_area, bsize| {
distortion_scale(
fi,
input_region.subregion(bias_area).frame_block_offset(),
bsize,
)
},
fi.cpu_feature_level,
),
Tune::Psnr => sse_wxh(
&input_region,
&rec_region,
visible_w,
visible_h,
|bias_area, bsize| {
distortion_scale(
fi,
input_region.subregion(bias_area).frame_block_offset(),
bsize,
)
},
fi.sequence.bit_depth,
fi.cpu_feature_level,
),
} * fi.dist_scale[0];
if is_chroma_block
&& !luma_only
&& fi.sequence.chroma_sampling != ChromaSampling::Cs400
{
let PlaneConfig { xdec, ydec, .. } = ts.input.planes[1].cfg;
let chroma_w = if bsize.width() >= 8 || xdec == 0 {
(visible_w + xdec) >> xdec
} else {
(4 + visible_w + xdec) >> xdec
};
let chroma_h = if bsize.height() >= 8 || ydec == 0 {
(visible_h + ydec) >> ydec
} else {
(4 + visible_h + ydec) >> ydec
};
for p in 1..3 {
let input_region = ts.input_tile.planes[p].subregion(area);
let rec_region = ts.rec.planes[p].subregion(area);
distortion += sse_wxh(
&input_region,
&rec_region,
chroma_w,
chroma_h,
|bias_area, bsize| {
distortion_scale(
fi,
input_region.subregion(bias_area).frame_block_offset(),
bsize,
)
},
fi.sequence.bit_depth,
fi.cpu_feature_level,
) * fi.dist_scale[p];
}
}
distortion
}
// Compute the transform-domain distortion for an encode
fn compute_tx_distortion<T: Pixel>(
fi: &FrameInvariants<T>, ts: &TileStateMut<'_, T>, bsize: BlockSize,
is_chroma_block: bool, tile_bo: TileBlockOffset, tx_dist: ScaledDistortion,
skip: bool, luma_only: bool,
) -> ScaledDistortion {
assert!(fi.config.tune == Tune::Psnr);
let area = Area::BlockStartingAt { bo: tile_bo.0 };
let input_region = ts.input_tile.planes[0].subregion(area);
let rec_region = ts.rec.planes[0].subregion(area);
let (visible_w, visible_h) = if !skip {
(bsize.width(), bsize.height())
} else {
let frame_bo = ts.to_frame_block_offset(tile_bo);
clip_visible_bsize(
fi.width,
fi.height,
bsize,
frame_bo.0.x << MI_SIZE_LOG2,
frame_bo.0.y << MI_SIZE_LOG2,
)
};
if visible_w == 0 || visible_h == 0 {
return ScaledDistortion::zero();
}
let mut distortion = if skip {
sse_wxh(
&input_region,
&rec_region,
visible_w,
visible_h,
|bias_area, bsize| {
distortion_scale(
fi,
input_region.subregion(bias_area).frame_block_offset(),
bsize,
)
},
fi.sequence.bit_depth,
fi.cpu_feature_level,
) * fi.dist_scale[0]
} else {
tx_dist
};
if is_chroma_block
&& !luma_only
&& skip
&& fi.sequence.chroma_sampling != ChromaSampling::Cs400
{
let PlaneConfig { xdec, ydec, .. } = ts.input.planes[1].cfg;
let chroma_w = if bsize.width() >= 8 || xdec == 0 {
(visible_w + xdec) >> xdec
} else {
(4 + visible_w + xdec) >> xdec
};
let chroma_h = if bsize.height() >= 8 || ydec == 0 {
(visible_h + ydec) >> ydec
} else {
(4 + visible_h + ydec) >> ydec
};
for p in 1..3 {
let input_region = ts.input_tile.planes[p].subregion(area);
let rec_region = ts.rec.planes[p].subregion(area);
distortion += sse_wxh(
&input_region,
&rec_region,
chroma_w,
chroma_h,
|bias_area, bsize| {
distortion_scale(
fi,
input_region.subregion(bias_area).frame_block_offset(),
bsize,
)
},
fi.sequence.bit_depth,
fi.cpu_feature_level,
) * fi.dist_scale[p];
}
}
distortion
}
/// Compute a scaling factor to multiply the distortion of a block by,
/// this factor is determined using temporal RDO.
///
/// # Panics
///
/// - If called with `bsize` of 8x8 or smaller
/// - If the coded frame data doesn't exist on the `FrameInvariants`
pub fn distortion_scale<T: Pixel>(
fi: &FrameInvariants<T>, frame_bo: PlaneBlockOffset, bsize: BlockSize,
) -> DistortionScale {
if !fi.config.temporal_rdo() {
return DistortionScale::default();
}
// EncoderConfig::temporal_rdo() should always return false in situations
// where distortion is computed on > 8x8 blocks, so we should never hit this
// assert.
assert!(bsize <= BlockSize::BLOCK_8X8);
let x = frame_bo.0.x >> IMPORTANCE_BLOCK_TO_BLOCK_SHIFT;
let y = frame_bo.0.y >> IMPORTANCE_BLOCK_TO_BLOCK_SHIFT;
let coded_data = fi.coded_frame_data.as_ref().unwrap();
coded_data.distortion_scales[y * coded_data.w_in_imp_b + x]
}
/// # Panics
///
/// - If the coded frame data doesn't exist on the `FrameInvariants`
pub fn spatiotemporal_scale<T: Pixel>(
fi: &FrameInvariants<T>, frame_bo: PlaneBlockOffset, bsize: BlockSize,
) -> DistortionScale {
if !fi.config.temporal_rdo() && fi.config.tune != Tune::Psychovisual {
return DistortionScale::default();
}
let coded_data = fi.coded_frame_data.as_ref().unwrap();
let x0 = frame_bo.0.x >> IMPORTANCE_BLOCK_TO_BLOCK_SHIFT;
let y0 = frame_bo.0.y >> IMPORTANCE_BLOCK_TO_BLOCK_SHIFT;
let x1 = (x0 + bsize.width_imp_b()).min(coded_data.w_in_imp_b);
let y1 = (y0 + bsize.height_imp_b()).min(coded_data.h_in_imp_b);
let den = (((x1 - x0) * (y1 - y0)) as u64) << DistortionScale::SHIFT;
// calling this on each slice individually improves autovectorization
// compared to using `Iterator::take`
#[inline(always)]
fn take_slice<T>(slice: &[T], n: usize) -> &[T] {
slice.get(..n).unwrap_or(slice)
}
let mut sum = 0;
for y in y0..y1 {
sum += take_slice(
&coded_data.distortion_scales[y * coded_data.w_in_imp_b..][x0..x1],
MAX_SB_IN_IMP_B,
)
.iter()
.zip(
take_slice(
&coded_data.activity_scales[y * coded_data.w_in_imp_b..][x0..x1],
MAX_SB_IN_IMP_B,
)
.iter(),
)
.map(|(d, a)| d.0 as u64 * a.0 as u64)
.sum::<u64>();
}
DistortionScale(((sum + (den >> 1)) / den) as u32)
}
pub fn distortion_scale_for(
propagate_cost: f64, intra_cost: f64,
) -> DistortionScale {
// The mbtree paper \cite{mbtree} uses the following formula:
//
// QP_delta = -strength * log2(1 + (propagate_cost / intra_cost))
//
// Since this is H.264, this corresponds to the following quantizer:
//
// Q' = Q * 2^(QP_delta/6)
//
// Since lambda is proportial to Q^2, this means we want to minimize:
//
// D + lambda' * R
// = D + 2^(QP_delta / 3) * lambda * R
//
// If we want to keep lambda fixed, we can instead scale distortion and
// minimize:
//
// D * scale + lambda * R
//
// where:
//
// scale = 2^(QP_delta / -3)
// = (1 + (propagate_cost / intra_cost))^(strength / 3)
//
// The original paper empirically chooses strength = 2.0, but strength = 1.0
// seems to work best in rav1e currently, this may have something to do with
// the fact that they use 16x16 blocks whereas our "importance blocks" are
// 8x8, but everything should be scale invariant here so that's weird.
//
// @article{mbtree,
// title={A novel macroblock-tree algorithm for high-performance
// optimization of dependent video coding in H.264/AVC},
// author={Garrett-Glaser, Jason},
// journal={Tech. Rep.},
// year={2009},
// url={https://pdfs.semanticscholar.org/032f/1ab7d9db385780a02eb2d579af8303b266d2.pdf}
// }
if intra_cost == 0. {
return DistortionScale::default(); // no scaling
}
let strength = 1.0; // empirical, see comment above
let frac = (intra_cost + propagate_cost) / intra_cost;
frac.powf(strength / 3.0).into()
}
/// Fixed point arithmetic version of distortion scale
#[repr(transparent)]
#[derive(Copy, Clone)]
pub struct DistortionScale(pub u32);
#[repr(transparent)]
pub struct RawDistortion(u64);
#[repr(transparent)]
pub struct Distortion(pub u64);
#[repr(transparent)]
pub struct ScaledDistortion(u64);
impl DistortionScale {
/// Bits past the radix point
const SHIFT: u32 = 14;
/// Number of bits used. Determines the max value.
/// 28 bits is quite excessive.
const BITS: u32 = 28;
/// Maximum internal value
const MAX: u64 = (1 << Self::BITS) - 1;
#[inline]
pub const fn new(num: u64, den: u64) -> Self {
let raw = (num << Self::SHIFT).saturating_add(den / 2) / den;
let mask = (raw <= Self::MAX) as u64;
Self((mask * raw + (1 - mask) * Self::MAX) as u32)
}
pub fn inv_mean(slice: &[Self]) -> Self {
use crate::util::{bexp64, blog32_q11};
let sum = slice.iter().map(|&s| blog32_q11(s.0) as i64).sum::<i64>();
let log_inv_mean_q11 =
(Self::SHIFT << 11) as i64 - sum / slice.len() as i64;
Self(
bexp64((log_inv_mean_q11 + (Self::SHIFT << 11) as i64) << (57 - 11))
.clamp(1, (1 << Self::BITS) - 1) as u32,
)
}
/// Binary logarithm in Q11
#[inline]
pub const fn blog16(self) -> i16 {
use crate::util::blog32_q11;
(blog32_q11(self.0) - ((Self::SHIFT as i32) << 11)) as i16
}
/// Binary logarithm in Q57
#[inline]
pub const fn blog64(self) -> i64 {
use crate::util::{blog64, q57};
blog64(self.0 as i64) - q57(Self::SHIFT as i32)
}
/// Multiply, round and shift
/// Internal implementation, so don't use multiply trait.
#[inline]
pub const fn mul_u64(self, dist: u64) -> u64 {
(self.0 as u64 * dist + (1 << Self::SHIFT >> 1)) >> Self::SHIFT
}
}
impl std::ops::Mul for DistortionScale {
type Output = Self;
/// Multiply, round and shift
#[inline]
fn mul(self, rhs: Self) -> Self {
Self(
(((self.0 as u64 * rhs.0 as u64) + (1 << (Self::SHIFT - 1)))
>> Self::SHIFT)
.clamp(1, (1 << Self::BITS) - 1) as u32,
)
}
}
impl std::ops::MulAssign for DistortionScale {
fn mul_assign(&mut self, rhs: Self) {
*self = *self * rhs;
}
}
// Default value for DistortionScale is a fixed point 1
impl Default for DistortionScale {
#[inline]
fn default() -> Self {
Self(1 << Self::SHIFT)
}
}
impl fmt::Debug for DistortionScale {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", f64::from(*self))
}
}
impl From<f64> for DistortionScale {
#[inline]
fn from(scale: f64) -> Self {
let den = 1 << (Self::SHIFT + 1);
Self::new((scale * den as f64) as u64, den)
}
}
impl From<DistortionScale> for f64 {
#[inline]
fn from(scale: DistortionScale) -> Self {
scale.0 as f64 / (1 << DistortionScale::SHIFT) as f64
}
}
impl RawDistortion {
#[inline]
pub const fn new(dist: u64) -> Self {
Self(dist)
}
}
impl std::ops::Mul<DistortionScale> for RawDistortion {
type Output = Distortion;
#[inline]
fn mul(self, rhs: DistortionScale) -> Distortion {
Distortion(rhs.mul_u64(self.0))
}
}
impl Distortion {
#[inline]
pub const fn zero() -> Self {
Self(0)
}
}
impl std::ops::Mul<DistortionScale> for Distortion {
type Output = ScaledDistortion;
#[inline]
fn mul(self, rhs: DistortionScale) -> ScaledDistortion {
ScaledDistortion(rhs.mul_u64(self.0))
}
}
impl std::ops::AddAssign for Distortion {
#[inline]
fn add_assign(&mut self, other: Self) {
self.0 += other.0;
}
}
impl ScaledDistortion {
#[inline]
pub const fn zero() -> Self {
Self(0)
}
}
impl std::ops::AddAssign for ScaledDistortion {
#[inline]
fn add_assign(&mut self, other: Self) {
self.0 += other.0;
}
}
pub fn compute_rd_cost<T: Pixel>(
fi: &FrameInvariants<T>, rate: u32, distortion: ScaledDistortion,
) -> f64 {
let rate_in_bits = (rate as f64) / ((1 << OD_BITRES) as f64);
fi.lambda.mul_add(rate_in_bits, distortion.0 as f64)
}
pub fn rdo_tx_size_type<T: Pixel>(
fi: &FrameInvariants<T>, ts: &mut TileStateMut<'_, T>,
cw: &mut ContextWriter, bsize: BlockSize, tile_bo: TileBlockOffset,
luma_mode: PredictionMode, ref_frames: [RefType; 2], mvs: [MotionVector; 2],
skip: bool,
) -> (TxSize, TxType) {
let is_inter = !luma_mode.is_intra();
let mut tx_size = max_txsize_rect_lookup[bsize as usize];
if fi.enable_inter_txfm_split && is_inter && !skip {
tx_size = sub_tx_size_map[tx_size as usize]; // Always choose one level split size
}
let mut best_tx_type = TxType::DCT_DCT;
let mut best_tx_size = tx_size;
let mut best_rd = f64::MAX;
let do_rdo_tx_size = fi.tx_mode_select
&& fi.config.speed_settings.transform.rdo_tx_decision
&& !is_inter;
let rdo_tx_depth = if do_rdo_tx_size { 2 } else { 0 };
let mut cw_checkpoint: Option<ContextWriterCheckpoint> = None;
for _ in 0..=rdo_tx_depth {
let tx_set = get_tx_set(tx_size, is_inter, fi.use_reduced_tx_set);
let do_rdo_tx_type = tx_set > TxSet::TX_SET_DCTONLY
&& fi.config.speed_settings.transform.rdo_tx_decision
&& !is_inter
&& !skip;
if !do_rdo_tx_size && !do_rdo_tx_type {
return (best_tx_size, best_tx_type);
};
let tx_types =
if do_rdo_tx_type { RAV1E_TX_TYPES } else { &[TxType::DCT_DCT] };
// Luma plane transform type decision
let (tx_type, rd_cost) = rdo_tx_type_decision(
fi,
ts,
cw,
&mut cw_checkpoint,
luma_mode,
ref_frames,
mvs,
bsize,
tile_bo,
tx_size,
tx_set,
tx_types,
best_rd,
);
if rd_cost < best_rd {
best_tx_size = tx_size;
best_tx_type = tx_type;
best_rd = rd_cost;
}
debug_assert!(tx_size.width_log2() <= bsize.width_log2());
debug_assert!(tx_size.height_log2() <= bsize.height_log2());
debug_assert!(
tx_size.sqr() <= TxSize::TX_32X32 || tx_type == TxType::DCT_DCT
);
let next_tx_size = sub_tx_size_map[tx_size as usize];
if next_tx_size == tx_size {
break;
} else {
tx_size = next_tx_size;
};
}
(best_tx_size, best_tx_type)
}
#[inline]
const fn dmv_in_range(mv: MotionVector, ref_mv: MotionVector) -> bool {
let diff_row = mv.row as i32 - ref_mv.row as i32;
let diff_col = mv.col as i32 - ref_mv.col as i32;
diff_row >= MV_LOW
&& diff_row <= MV_UPP
&& diff_col >= MV_LOW
&& diff_col <= MV_UPP
}
#[inline]
#[profiling::function]
fn luma_chroma_mode_rdo<T: Pixel>(
luma_mode: PredictionMode, fi: &FrameInvariants<T>, bsize: BlockSize,
tile_bo: TileBlockOffset, ts: &mut TileStateMut<'_, T>,
cw: &mut ContextWriter, rdo_type: RDOType,
cw_checkpoint: &ContextWriterCheckpoint, best: &mut PartitionParameters,
mvs: [MotionVector; 2], ref_frames: [RefType; 2],
mode_set_chroma: &[PredictionMode], luma_mode_is_intra: bool,
mode_context: usize, mv_stack: &ArrayVec<CandidateMV, 9>,
angle_delta: AngleDelta,
) {
let PlaneConfig { xdec, ydec, .. } = ts.input.planes[1].cfg;
let is_chroma_block =
has_chroma(tile_bo, bsize, xdec, ydec, fi.sequence.chroma_sampling);
if !luma_mode_is_intra {
let ref_mvs = if mv_stack.is_empty() {
[MotionVector::default(); 2]
} else {
[mv_stack[0].this_mv, mv_stack[0].comp_mv]
};
if (luma_mode == PredictionMode::NEWMV
|| luma_mode == PredictionMode::NEW_NEWMV
|| luma_mode == PredictionMode::NEW_NEARESTMV)
&& !dmv_in_range(mvs[0], ref_mvs[0])
{
return;
}
if (luma_mode == PredictionMode::NEW_NEWMV
|| luma_mode == PredictionMode::NEAREST_NEWMV)
&& !dmv_in_range(mvs[1], ref_mvs[1])
{
return;
}
}
// Find the best chroma prediction mode for the current luma prediction mode
let mut chroma_rdo = |skip: bool| -> bool {
use crate::segmentation::select_segment;
let mut zero_distortion = false;
for sidx in select_segment(fi, ts, tile_bo, bsize, skip) {
cw.bc.blocks.set_segmentation_idx(tile_bo, bsize, sidx);
let (tx_size, tx_type) = rdo_tx_size_type(
fi, ts, cw, bsize, tile_bo, luma_mode, ref_frames, mvs, skip,
);
for &chroma_mode in mode_set_chroma.iter() {
let wr = &mut WriterCounter::new();
let tell = wr.tell_frac();
if bsize >= BlockSize::BLOCK_8X8 && bsize.is_sqr() {
cw.write_partition(
wr,
tile_bo,
PartitionType::PARTITION_NONE,
bsize,
);
}
// TODO(yushin): luma and chroma would have different decision based on chroma format
let need_recon_pixel =
luma_mode_is_intra && tx_size.block_size() != bsize;
encode_block_pre_cdef(&fi.sequence, ts, cw, wr, bsize, tile_bo, skip);
let (has_coeff, tx_dist) = encode_block_post_cdef(
fi,
ts,
cw,
wr,
luma_mode,
chroma_mode,
angle_delta,
ref_frames,
mvs,
bsize,
tile_bo,
skip,
CFLParams::default(),
tx_size,
tx_type,
mode_context,
mv_stack,
rdo_type,
need_recon_pixel,
None,
);
let rate = wr.tell_frac() - tell;
let distortion = if fi.use_tx_domain_distortion && !need_recon_pixel {
compute_tx_distortion(
fi,
ts,
bsize,
is_chroma_block,
tile_bo,
tx_dist,
skip,
false,
)
} else {
compute_distortion(fi, ts, bsize, is_chroma_block, tile_bo, false)
};
let is_zero_dist = distortion.0 == 0;
let rd = compute_rd_cost(fi, rate, distortion);
if rd < best.rd_cost {
//if rd < best.rd_cost || luma_mode == PredictionMode::NEW_NEWMV {
best.rd_cost = rd;
best.pred_mode_luma = luma_mode;
best.pred_mode_chroma = chroma_mode;
best.angle_delta = angle_delta;
best.ref_frames = ref_frames;
best.mvs = mvs;
best.skip = skip;
best.has_coeff = has_coeff;
best.tx_size = tx_size;
best.tx_type = tx_type;
best.sidx = sidx;
zero_distortion = is_zero_dist;
}
cw.rollback(cw_checkpoint);
}
}
zero_distortion
};
// Don't skip when using intra modes
let zero_distortion =
if !luma_mode_is_intra { chroma_rdo(true) } else { false };
// early skip
if !zero_distortion {
chroma_rdo(false);
}
}
/// RDO-based mode decision
///
/// # Panics
///
/// - If the best RD found is negative.
/// This should never happen and indicates a development error.
#[profiling::function]
pub fn rdo_mode_decision<T: Pixel>(
fi: &FrameInvariants<T>, ts: &mut TileStateMut<'_, T>,
cw: &mut ContextWriter, bsize: BlockSize, tile_bo: TileBlockOffset,
inter_cfg: &InterConfig,
) -> PartitionParameters {
let PlaneConfig { xdec, ydec, .. } = ts.input.planes[1].cfg;
let cw_checkpoint = cw.checkpoint(&tile_bo, fi.sequence.chroma_sampling);
let rdo_type = if fi.use_tx_domain_rate {
RDOType::TxDistEstRate
} else if fi.use_tx_domain_distortion {
RDOType::TxDistRealRate
} else {
RDOType::PixelDistRealRate
};
let mut best = if fi.frame_type.has_inter() {
assert!(fi.frame_type != FrameType::KEY);
inter_frame_rdo_mode_decision(
fi,
ts,
cw,
bsize,
tile_bo,
inter_cfg,
&cw_checkpoint,
rdo_type,
)
} else {
PartitionParameters::default()
};
let is_chroma_block =
has_chroma(tile_bo, bsize, xdec, ydec, fi.sequence.chroma_sampling);
if !best.skip {
best = intra_frame_rdo_mode_decision(
fi,
ts,