-
Notifications
You must be signed in to change notification settings - Fork 252
/
predict.rs
1694 lines (1517 loc) · 49.8 KB
/
predict.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) 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_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(dead_code)]
use std::mem::MaybeUninit;
cfg_if::cfg_if! {
if #[cfg(nasm_x86_64)] {
pub use crate::asm::x86::predict::*;
} else if #[cfg(asm_neon)] {
pub use crate::asm::aarch64::predict::*;
} else {
pub use self::rust::*;
}
}
use aligned_vec::{avec, ABox};
use crate::context::{TileBlockOffset, MAX_SB_SIZE_LOG2, MAX_TX_SIZE};
use crate::cpu_features::CpuFeatureLevel;
use crate::encoder::FrameInvariants;
use crate::frame::*;
use crate::mc::*;
use crate::partition::*;
use crate::tiling::*;
use crate::transform::*;
use crate::util::*;
pub const ANGLE_STEP: i8 = 3;
// TODO: Review the order of this list.
// The order impacts compression efficiency.
pub static RAV1E_INTRA_MODES: &[PredictionMode] = &[
PredictionMode::DC_PRED,
PredictionMode::H_PRED,
PredictionMode::V_PRED,
PredictionMode::SMOOTH_PRED,
PredictionMode::SMOOTH_H_PRED,
PredictionMode::SMOOTH_V_PRED,
PredictionMode::PAETH_PRED,
PredictionMode::D45_PRED,
PredictionMode::D135_PRED,
PredictionMode::D113_PRED,
PredictionMode::D157_PRED,
PredictionMode::D203_PRED,
PredictionMode::D67_PRED,
];
pub static RAV1E_INTER_MODES_MINIMAL: &[PredictionMode] =
&[PredictionMode::NEARESTMV];
pub static RAV1E_INTER_COMPOUND_MODES: &[PredictionMode] = &[
PredictionMode::GLOBAL_GLOBALMV,
PredictionMode::NEAREST_NEARESTMV,
PredictionMode::NEW_NEWMV,
PredictionMode::NEAREST_NEWMV,
PredictionMode::NEW_NEARESTMV,
PredictionMode::NEAR_NEAR0MV,
PredictionMode::NEAR_NEAR1MV,
PredictionMode::NEAR_NEAR2MV,
];
// There are more modes than in the spec because every allowed
// drl index for NEAR modes is considered its own mode.
#[derive(Copy, Clone, Debug, PartialEq, PartialOrd, Eq, Ord, Default)]
pub enum PredictionMode {
#[default]
DC_PRED, // Average of above and left pixels
V_PRED, // Vertical
H_PRED, // Horizontal
D45_PRED, // Directional 45 degree
D135_PRED, // Directional 135 degree
D113_PRED, // Directional 113 degree
D157_PRED, // Directional 157 degree
D203_PRED, // Directional 203 degree
D67_PRED, // Directional 67 degree
SMOOTH_PRED, // Combination of horizontal and vertical interpolation
SMOOTH_V_PRED,
SMOOTH_H_PRED,
PAETH_PRED,
UV_CFL_PRED,
NEARESTMV,
NEAR0MV,
NEAR1MV,
NEAR2MV,
GLOBALMV,
NEWMV,
// Compound ref compound modes
NEAREST_NEARESTMV,
NEAR_NEAR0MV,
NEAR_NEAR1MV,
NEAR_NEAR2MV,
NEAREST_NEWMV,
NEW_NEARESTMV,
NEAR_NEW0MV,
NEAR_NEW1MV,
NEAR_NEW2MV,
NEW_NEAR0MV,
NEW_NEAR1MV,
NEW_NEAR2MV,
GLOBAL_GLOBALMV,
NEW_NEWMV,
}
// This is a higher number than in the spec and cannot be used
// for bitstream writing purposes.
pub const PREDICTION_MODES: usize = 34;
#[derive(Copy, Clone, Debug)]
pub enum PredictionVariant {
NONE,
LEFT,
TOP,
BOTH,
}
impl PredictionVariant {
#[inline]
const fn new(x: usize, y: usize) -> Self {
match (x, y) {
(0, 0) => PredictionVariant::NONE,
(_, 0) => PredictionVariant::LEFT,
(0, _) => PredictionVariant::TOP,
_ => PredictionVariant::BOTH,
}
}
}
pub const fn intra_mode_to_angle(mode: PredictionMode) -> isize {
match mode {
PredictionMode::V_PRED => 90,
PredictionMode::H_PRED => 180,
PredictionMode::D45_PRED => 45,
PredictionMode::D135_PRED => 135,
PredictionMode::D113_PRED => 113,
PredictionMode::D157_PRED => 157,
PredictionMode::D203_PRED => 203,
PredictionMode::D67_PRED => 67,
_ => 0,
}
}
impl PredictionMode {
#[inline]
pub fn is_compound(self) -> bool {
self >= PredictionMode::NEAREST_NEARESTMV
}
#[inline]
pub fn has_nearmv(self) -> bool {
self == PredictionMode::NEAR0MV
|| self == PredictionMode::NEAR1MV
|| self == PredictionMode::NEAR2MV
|| self == PredictionMode::NEAR_NEAR0MV
|| self == PredictionMode::NEAR_NEAR1MV
|| self == PredictionMode::NEAR_NEAR2MV
|| self == PredictionMode::NEAR_NEW0MV
|| self == PredictionMode::NEAR_NEW1MV
|| self == PredictionMode::NEAR_NEW2MV
|| self == PredictionMode::NEW_NEAR0MV
|| self == PredictionMode::NEW_NEAR1MV
|| self == PredictionMode::NEW_NEAR2MV
}
#[inline]
pub fn has_newmv(self) -> bool {
self == PredictionMode::NEWMV
|| self == PredictionMode::NEW_NEWMV
|| self == PredictionMode::NEAREST_NEWMV
|| self == PredictionMode::NEW_NEARESTMV
|| self == PredictionMode::NEAR_NEW0MV
|| self == PredictionMode::NEAR_NEW1MV
|| self == PredictionMode::NEAR_NEW2MV
|| self == PredictionMode::NEW_NEAR0MV
|| self == PredictionMode::NEW_NEAR1MV
|| self == PredictionMode::NEW_NEAR2MV
}
#[inline]
pub fn ref_mv_idx(self) -> usize {
if self == PredictionMode::NEAR0MV
|| self == PredictionMode::NEAR1MV
|| self == PredictionMode::NEAR2MV
{
self as usize - PredictionMode::NEAR0MV as usize + 1
} else if self == PredictionMode::NEAR_NEAR0MV
|| self == PredictionMode::NEAR_NEAR1MV
|| self == PredictionMode::NEAR_NEAR2MV
{
self as usize - PredictionMode::NEAR_NEAR0MV as usize + 1
} else {
1
}
}
/// # Panics
///
/// - If called on an inter `PredictionMode`
pub fn predict_intra<T: Pixel>(
self, tile_rect: TileRect, dst: &mut PlaneRegionMut<'_, T>,
tx_size: TxSize, bit_depth: usize, ac: &[i16], intra_param: IntraParam,
ief_params: Option<IntraEdgeFilterParameters>, edge_buf: &IntraEdge<T>,
cpu: CpuFeatureLevel,
) {
assert!(self.is_intra());
let &Rect { x: frame_x, y: frame_y, .. } = dst.rect();
debug_assert!(frame_x >= 0 && frame_y >= 0);
// x and y are expressed relative to the tile
let x = frame_x as usize - tile_rect.x;
let y = frame_y as usize - tile_rect.y;
let variant = PredictionVariant::new(x, y);
let alpha = match intra_param {
IntraParam::Alpha(val) => val,
_ => 0,
};
let angle_delta = match intra_param {
IntraParam::AngleDelta(val) => val,
_ => 0,
};
let mode = match self {
PredictionMode::PAETH_PRED => match variant {
PredictionVariant::NONE => PredictionMode::DC_PRED,
PredictionVariant::TOP => PredictionMode::V_PRED,
PredictionVariant::LEFT => PredictionMode::H_PRED,
PredictionVariant::BOTH => PredictionMode::PAETH_PRED,
},
PredictionMode::UV_CFL_PRED if alpha == 0 => PredictionMode::DC_PRED,
_ => self,
};
let angle = match mode {
PredictionMode::UV_CFL_PRED => alpha as isize,
_ => intra_mode_to_angle(mode) + (angle_delta * ANGLE_STEP) as isize,
};
dispatch_predict_intra::<T>(
mode, variant, dst, tx_size, bit_depth, ac, angle, ief_params, edge_buf,
cpu,
);
}
#[inline]
pub fn is_intra(self) -> bool {
self < PredictionMode::NEARESTMV
}
#[inline]
pub fn is_cfl(self) -> bool {
self == PredictionMode::UV_CFL_PRED
}
#[inline]
pub fn is_directional(self) -> bool {
self >= PredictionMode::V_PRED && self <= PredictionMode::D67_PRED
}
#[inline(always)]
pub const fn angle_delta_count(self) -> i8 {
match self {
PredictionMode::V_PRED
| PredictionMode::H_PRED
| PredictionMode::D45_PRED
| PredictionMode::D135_PRED
| PredictionMode::D113_PRED
| PredictionMode::D157_PRED
| PredictionMode::D203_PRED
| PredictionMode::D67_PRED => 7,
_ => 1,
}
}
// Used by inter prediction to extract the fractional component of a mv and
// obtain the correct PlaneSlice to operate on.
#[inline]
fn get_mv_params<T: Pixel>(
rec_plane: &Plane<T>, po: PlaneOffset, mv: MotionVector,
) -> (i32, i32, PlaneSlice<T>) {
let &PlaneConfig { xdec, ydec, .. } = &rec_plane.cfg;
let row_offset = mv.row as i32 >> (3 + ydec);
let col_offset = mv.col as i32 >> (3 + xdec);
let row_frac = ((mv.row as i32) << (1 - ydec)) & 0xf;
let col_frac = ((mv.col as i32) << (1 - xdec)) & 0xf;
let qo = PlaneOffset {
x: po.x + col_offset as isize - 3,
y: po.y + row_offset as isize - 3,
};
(row_frac, col_frac, rec_plane.slice(qo).clamp().subslice(3, 3))
}
/// Inter prediction with a single reference (i.e. not compound mode)
///
/// # Panics
///
/// - If called on an intra `PredictionMode`
pub fn predict_inter_single<T: Pixel>(
self, fi: &FrameInvariants<T>, tile_rect: TileRect, p: usize,
po: PlaneOffset, dst: &mut PlaneRegionMut<'_, T>, width: usize,
height: usize, ref_frame: RefType, mv: MotionVector,
) {
assert!(!self.is_intra());
let frame_po = tile_rect.to_frame_plane_offset(po);
let mode = fi.default_filter;
if let Some(ref rec) =
fi.rec_buffer.frames[fi.ref_frames[ref_frame.to_index()] as usize]
{
let (row_frac, col_frac, src) =
PredictionMode::get_mv_params(&rec.frame.planes[p], frame_po, mv);
put_8tap(
dst,
src,
width,
height,
col_frac,
row_frac,
mode,
mode,
fi.sequence.bit_depth,
fi.cpu_feature_level,
);
}
}
/// Inter prediction with two references.
///
/// # Panics
///
/// - If called on an intra `PredictionMode`
pub fn predict_inter_compound<T: Pixel>(
self, fi: &FrameInvariants<T>, tile_rect: TileRect, p: usize,
po: PlaneOffset, dst: &mut PlaneRegionMut<'_, T>, width: usize,
height: usize, ref_frames: [RefType; 2], mvs: [MotionVector; 2],
buffer: &mut InterCompoundBuffers,
) {
assert!(!self.is_intra());
let frame_po = tile_rect.to_frame_plane_offset(po);
let mode = fi.default_filter;
for i in 0..2 {
if let Some(ref rec) =
fi.rec_buffer.frames[fi.ref_frames[ref_frames[i].to_index()] as usize]
{
let (row_frac, col_frac, src) = PredictionMode::get_mv_params(
&rec.frame.planes[p],
frame_po,
mvs[i],
);
prep_8tap(
buffer.get_buffer_mut(i),
src,
width,
height,
col_frac,
row_frac,
mode,
mode,
fi.sequence.bit_depth,
fi.cpu_feature_level,
);
}
}
mc_avg(
dst,
buffer.get_buffer(0),
buffer.get_buffer(1),
width,
height,
fi.sequence.bit_depth,
fi.cpu_feature_level,
);
}
/// Inter prediction that determines whether compound mode is being used based
/// on the second [`RefType`] in [`ref_frames`].
pub fn predict_inter<T: Pixel>(
self, fi: &FrameInvariants<T>, tile_rect: TileRect, p: usize,
po: PlaneOffset, dst: &mut PlaneRegionMut<'_, T>, width: usize,
height: usize, ref_frames: [RefType; 2], mvs: [MotionVector; 2],
compound_buffer: &mut InterCompoundBuffers,
) {
let is_compound = ref_frames[1] != RefType::INTRA_FRAME
&& ref_frames[1] != RefType::NONE_FRAME;
if !is_compound {
self.predict_inter_single(
fi,
tile_rect,
p,
po,
dst,
width,
height,
ref_frames[0],
mvs[0],
)
} else {
self.predict_inter_compound(
fi,
tile_rect,
p,
po,
dst,
width,
height,
ref_frames,
mvs,
compound_buffer,
);
}
}
}
/// A pair of buffers holding the interpolation of two references. Use for
/// compound inter prediction.
#[derive(Debug)]
pub struct InterCompoundBuffers {
data: ABox<[i16]>,
}
impl InterCompoundBuffers {
// Size of one of the two buffers used.
const BUFFER_SIZE: usize = 1 << (2 * MAX_SB_SIZE_LOG2);
/// Get the buffer for eith
#[inline]
fn get_buffer_mut(&mut self, i: usize) -> &mut [i16] {
match i {
0 => &mut self.data[0..Self::BUFFER_SIZE],
1 => &mut self.data[Self::BUFFER_SIZE..2 * Self::BUFFER_SIZE],
_ => panic!(),
}
}
#[inline]
fn get_buffer(&self, i: usize) -> &[i16] {
match i {
0 => &self.data[0..Self::BUFFER_SIZE],
1 => &self.data[Self::BUFFER_SIZE..2 * Self::BUFFER_SIZE],
_ => panic!(),
}
}
}
impl Default for InterCompoundBuffers {
fn default() -> Self {
Self { data: avec![0; 2 * Self::BUFFER_SIZE].into_boxed_slice() }
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd)]
pub enum InterIntraMode {
II_DC_PRED,
II_V_PRED,
II_H_PRED,
II_SMOOTH_PRED,
INTERINTRA_MODES,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd)]
pub enum CompoundType {
COMPOUND_AVERAGE,
COMPOUND_WEDGE,
COMPOUND_DIFFWTD,
COMPOUND_TYPES,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd)]
pub enum MotionMode {
SIMPLE_TRANSLATION,
OBMC_CAUSAL, // 2-sided OBMC
WARPED_CAUSAL, // 2-sided WARPED
MOTION_MODES,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd)]
pub enum PaletteSize {
TWO_COLORS,
THREE_COLORS,
FOUR_COLORS,
FIVE_COLORS,
SIX_COLORS,
SEVEN_COLORS,
EIGHT_COLORS,
PALETTE_SIZES,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd)]
pub enum PaletteColor {
PALETTE_COLOR_ONE,
PALETTE_COLOR_TWO,
PALETTE_COLOR_THREE,
PALETTE_COLOR_FOUR,
PALETTE_COLOR_FIVE,
PALETTE_COLOR_SIX,
PALETTE_COLOR_SEVEN,
PALETTE_COLOR_EIGHT,
PALETTE_COLORS,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd)]
pub enum FilterIntraMode {
FILTER_DC_PRED,
FILTER_V_PRED,
FILTER_H_PRED,
FILTER_D157_PRED,
FILTER_PAETH_PRED,
FILTER_INTRA_MODES,
}
#[derive(Copy, Clone, Debug)]
pub enum IntraParam {
AngleDelta(i8),
Alpha(i16),
None,
}
#[derive(Debug, Clone, Copy, Default)]
pub struct AngleDelta {
pub y: i8,
pub uv: i8,
}
#[derive(Copy, Clone, Default)]
pub struct IntraEdgeFilterParameters {
pub plane: usize,
pub above_ref_frame_types: Option<[RefType; 2]>,
pub left_ref_frame_types: Option<[RefType; 2]>,
pub above_mode: Option<PredictionMode>,
pub left_mode: Option<PredictionMode>,
}
impl IntraEdgeFilterParameters {
pub fn new(
plane: usize, above_ctx: Option<CodedBlockInfo>,
left_ctx: Option<CodedBlockInfo>,
) -> Self {
IntraEdgeFilterParameters {
plane,
above_mode: match above_ctx {
Some(bi) => match plane {
0 => bi.luma_mode,
_ => bi.chroma_mode,
}
.into(),
None => None,
},
left_mode: match left_ctx {
Some(bi) => match plane {
0 => bi.luma_mode,
_ => bi.chroma_mode,
}
.into(),
None => None,
},
above_ref_frame_types: above_ctx.map(|bi| bi.reference_types),
left_ref_frame_types: left_ctx.map(|bi| bi.reference_types),
}
}
/// # Panics
///
/// - If the appropriate ref frame types are not set on `self`
pub fn use_smooth_filter(self) -> bool {
let above_smooth = match self.above_mode {
Some(PredictionMode::SMOOTH_PRED)
| Some(PredictionMode::SMOOTH_V_PRED)
| Some(PredictionMode::SMOOTH_H_PRED) => {
self.plane == 0
|| self.above_ref_frame_types.unwrap()[0] == RefType::INTRA_FRAME
}
_ => false,
};
let left_smooth = match self.left_mode {
Some(PredictionMode::SMOOTH_PRED)
| Some(PredictionMode::SMOOTH_V_PRED)
| Some(PredictionMode::SMOOTH_H_PRED) => {
self.plane == 0
|| self.left_ref_frame_types.unwrap()[0] == RefType::INTRA_FRAME
}
_ => false,
};
above_smooth || left_smooth
}
}
// Weights are quadratic from '1' to '1 / block_size', scaled by 2^sm_weight_log2_scale.
const sm_weight_log2_scale: u8 = 8;
// Smooth predictor weights
#[rustfmt::skip]
static sm_weight_arrays: [u8; 2 * MAX_TX_SIZE] = [
// Unused, because we always offset by bs, which is at least 2.
0, 0,
// bs = 2
255, 128,
// bs = 4
255, 149, 85, 64,
// bs = 8
255, 197, 146, 105, 73, 50, 37, 32,
// bs = 16
255, 225, 196, 170, 145, 123, 102, 84, 68, 54, 43, 33, 26, 20, 17, 16,
// bs = 32
255, 240, 225, 210, 196, 182, 169, 157, 145, 133, 122, 111, 101, 92, 83, 74,
66, 59, 52, 45, 39, 34, 29, 25, 21, 17, 14, 12, 10, 9, 8, 8,
// bs = 64
255, 248, 240, 233, 225, 218, 210, 203, 196, 189, 182, 176, 169, 163, 156,
150, 144, 138, 133, 127, 121, 116, 111, 106, 101, 96, 91, 86, 82, 77, 73, 69,
65, 61, 57, 54, 50, 47, 44, 41, 38, 35, 32, 29, 27, 25, 22, 20, 18, 16, 15,
13, 12, 10, 9, 8, 7, 6, 6, 5, 5, 4, 4, 4,
];
#[inline(always)]
const fn get_scaled_luma_q0(alpha_q3: i16, ac_pred_q3: i16) -> i32 {
let scaled_luma_q6 = (alpha_q3 as i32) * (ac_pred_q3 as i32);
let abs_scaled_luma_q0 = (scaled_luma_q6.abs() + 32) >> 6;
if scaled_luma_q6 < 0 {
-abs_scaled_luma_q0
} else {
abs_scaled_luma_q0
}
}
/// # Returns
///
/// Initialized luma AC coefficients
///
/// # Panics
///
/// - If the block size is invalid for subsampling
///
pub fn luma_ac<'ac, T: Pixel>(
ac: &'ac mut [MaybeUninit<i16>], ts: &mut TileStateMut<'_, T>,
tile_bo: TileBlockOffset, bsize: BlockSize, tx_size: TxSize,
fi: &FrameInvariants<T>,
) -> &'ac mut [i16] {
use crate::context::MI_SIZE_LOG2;
let PlaneConfig { xdec, ydec, .. } = ts.input.planes[1].cfg;
let plane_bsize = bsize.subsampled_size(xdec, ydec).unwrap();
// ensure ac has the right length, so there aren't any uninitialized elements at the end
let ac = &mut ac[..plane_bsize.area()];
let bo = if bsize.is_sub8x8(xdec, ydec) {
let offset = bsize.sub8x8_offset(xdec, ydec);
tile_bo.with_offset(offset.0, offset.1)
} else {
tile_bo
};
let rec = &ts.rec.planes[0];
let luma = &rec.subregion(Area::BlockStartingAt { bo: bo.0 });
let frame_bo = ts.to_frame_block_offset(bo);
let frame_clipped_bw: usize =
((fi.w_in_b - frame_bo.0.x) << MI_SIZE_LOG2).min(bsize.width());
let frame_clipped_bh: usize =
((fi.h_in_b - frame_bo.0.y) << MI_SIZE_LOG2).min(bsize.height());
// Similar to 'MaxLumaW' and 'MaxLumaH' stated in https://aomediacodec.github.io/av1-spec/#transform-block-semantics
let max_luma_w = if bsize.width() > BlockSize::BLOCK_8X8.width() {
let txw_log2 = tx_size.width_log2();
((frame_clipped_bw + (1 << txw_log2) - 1) >> txw_log2) << txw_log2
} else {
bsize.width()
};
let max_luma_h = if bsize.height() > BlockSize::BLOCK_8X8.height() {
let txh_log2 = tx_size.height_log2();
((frame_clipped_bh + (1 << txh_log2) - 1) >> txh_log2) << txh_log2
} else {
bsize.height()
};
let w_pad = (bsize.width() - max_luma_w) >> (2 + xdec);
let h_pad = (bsize.height() - max_luma_h) >> (2 + ydec);
let cpu = fi.cpu_feature_level;
(match (xdec, ydec) {
(0, 0) => pred_cfl_ac::<T, 0, 0>,
(1, 0) => pred_cfl_ac::<T, 1, 0>,
(_, _) => pred_cfl_ac::<T, 1, 1>,
})(ac, luma, plane_bsize, w_pad, h_pad, cpu);
// SAFETY: it relies on individual pred_cfl_ac implementations to initialize the ac
unsafe { slice_assume_init_mut(ac) }
}
pub(crate) mod rust {
use super::*;
use std::mem::size_of;
#[inline(always)]
pub fn dispatch_predict_intra<T: Pixel>(
mode: PredictionMode, variant: PredictionVariant,
dst: &mut PlaneRegionMut<'_, T>, tx_size: TxSize, bit_depth: usize,
ac: &[i16], angle: isize, ief_params: Option<IntraEdgeFilterParameters>,
edge_buf: &IntraEdge<T>, _cpu: CpuFeatureLevel,
) {
let width = tx_size.width();
let height = tx_size.height();
// left pixels are ordered from bottom to top and right-aligned
let (left, top_left, above) = edge_buf.as_slices();
let above_slice = above;
let left_slice = &left[left.len().saturating_sub(height)..];
let left_and_left_below_slice =
&left[left.len().saturating_sub(width + height)..];
match mode {
PredictionMode::DC_PRED => {
(match variant {
PredictionVariant::NONE => pred_dc_128,
PredictionVariant::LEFT => pred_dc_left,
PredictionVariant::TOP => pred_dc_top,
PredictionVariant::BOTH => pred_dc,
})(dst, above_slice, left_slice, width, height, bit_depth)
}
PredictionMode::V_PRED if angle == 90 => {
pred_v(dst, above_slice, width, height)
}
PredictionMode::H_PRED if angle == 180 => {
pred_h(dst, left_slice, width, height)
}
PredictionMode::H_PRED
| PredictionMode::V_PRED
| PredictionMode::D45_PRED
| PredictionMode::D135_PRED
| PredictionMode::D113_PRED
| PredictionMode::D157_PRED
| PredictionMode::D203_PRED
| PredictionMode::D67_PRED => pred_directional(
dst,
above_slice,
left_and_left_below_slice,
top_left,
angle as usize,
width,
height,
bit_depth,
ief_params,
),
PredictionMode::SMOOTH_PRED => {
pred_smooth(dst, above_slice, left_slice, width, height)
}
PredictionMode::SMOOTH_V_PRED => {
pred_smooth_v(dst, above_slice, left_slice, width, height)
}
PredictionMode::SMOOTH_H_PRED => {
pred_smooth_h(dst, above_slice, left_slice, width, height)
}
PredictionMode::PAETH_PRED => {
pred_paeth(dst, above_slice, left_slice, top_left[0], width, height)
}
PredictionMode::UV_CFL_PRED => (match variant {
PredictionVariant::NONE => pred_cfl_128,
PredictionVariant::LEFT => pred_cfl_left,
PredictionVariant::TOP => pred_cfl_top,
PredictionVariant::BOTH => pred_cfl,
})(
dst,
ac,
angle as i16,
above_slice,
left_slice,
width,
height,
bit_depth,
),
_ => unimplemented!(),
}
}
pub(crate) fn pred_dc<T: Pixel>(
output: &mut PlaneRegionMut<'_, T>, above: &[T], left: &[T], width: usize,
height: usize, _bit_depth: usize,
) {
let edges = left[..height].iter().chain(above[..width].iter());
let len = (width + height) as u32;
let avg = (edges.fold(0u32, |acc, &v| {
let v: u32 = v.into();
v + acc
}) + (len >> 1))
/ len;
let avg = T::cast_from(avg);
for line in output.rows_iter_mut().take(height) {
line[..width].fill(avg);
}
}
pub(crate) fn pred_dc_128<T: Pixel>(
output: &mut PlaneRegionMut<'_, T>, _above: &[T], _left: &[T],
width: usize, height: usize, bit_depth: usize,
) {
let v = T::cast_from(128u32 << (bit_depth - 8));
for line in output.rows_iter_mut().take(height) {
line[..width].fill(v);
}
}
pub(crate) fn pred_dc_left<T: Pixel>(
output: &mut PlaneRegionMut<'_, T>, _above: &[T], left: &[T],
width: usize, height: usize, _bit_depth: usize,
) {
let sum = left[..].iter().fold(0u32, |acc, &v| {
let v: u32 = v.into();
v + acc
});
let avg = T::cast_from((sum + (height >> 1) as u32) / height as u32);
for line in output.rows_iter_mut().take(height) {
line[..width].fill(avg);
}
}
pub(crate) fn pred_dc_top<T: Pixel>(
output: &mut PlaneRegionMut<'_, T>, above: &[T], _left: &[T],
width: usize, height: usize, _bit_depth: usize,
) {
let sum = above[..width].iter().fold(0u32, |acc, &v| {
let v: u32 = v.into();
v + acc
});
let avg = T::cast_from((sum + (width >> 1) as u32) / width as u32);
for line in output.rows_iter_mut().take(height) {
line[..width].fill(avg);
}
}
pub(crate) fn pred_h<T: Pixel>(
output: &mut PlaneRegionMut<'_, T>, left: &[T], width: usize,
height: usize,
) {
for (line, l) in output.rows_iter_mut().zip(left[..height].iter().rev()) {
line[..width].fill(*l);
}
}
pub(crate) fn pred_v<T: Pixel>(
output: &mut PlaneRegionMut<'_, T>, above: &[T], width: usize,
height: usize,
) {
for line in output.rows_iter_mut().take(height) {
line[..width].copy_from_slice(&above[..width])
}
}
pub(crate) fn pred_paeth<T: Pixel>(
output: &mut PlaneRegionMut<'_, T>, above: &[T], left: &[T],
above_left: T, width: usize, height: usize,
) {
for r in 0..height {
let row = &mut output[r];
for c in 0..width {
// Top-left pixel is fixed in libaom
let raw_top_left: i32 = above_left.into();
let raw_left: i32 = left[height - 1 - r].into();
let raw_top: i32 = above[c].into();
let p_base = raw_top + raw_left - raw_top_left;
let p_left = (p_base - raw_left).abs();
let p_top = (p_base - raw_top).abs();
let p_top_left = (p_base - raw_top_left).abs();
// Return nearest to base of left, top and top_left
if p_left <= p_top && p_left <= p_top_left {
row[c] = T::cast_from(raw_left);
} else if p_top <= p_top_left {
row[c] = T::cast_from(raw_top);
} else {
row[c] = T::cast_from(raw_top_left);
}
}
}
}
pub(crate) fn pred_smooth<T: Pixel>(
output: &mut PlaneRegionMut<'_, T>, above: &[T], left: &[T], width: usize,
height: usize,
) {
let below_pred = left[0]; // estimated by bottom-left pixel
let right_pred = above[width - 1]; // estimated by top-right pixel
let sm_weights_w = &sm_weight_arrays[width..];
let sm_weights_h = &sm_weight_arrays[height..];
let log2_scale = 1 + sm_weight_log2_scale;
let scale = 1_u16 << sm_weight_log2_scale;
// Weights sanity checks
assert!((sm_weights_w[0] as u16) < scale);
assert!((sm_weights_h[0] as u16) < scale);
assert!((scale - sm_weights_w[width - 1] as u16) < scale);
assert!((scale - sm_weights_h[height - 1] as u16) < scale);
// ensures no overflow when calculating predictor
assert!(log2_scale as usize + size_of::<T>() < 31);
for r in 0..height {
let row = &mut output[r];
for c in 0..width {
let pixels = [above[c], below_pred, left[height - 1 - r], right_pred];
let weights = [
sm_weights_h[r] as u16,
scale - sm_weights_h[r] as u16,
sm_weights_w[c] as u16,
scale - sm_weights_w[c] as u16,
];
assert!(
scale >= (sm_weights_h[r] as u16)
&& scale >= (sm_weights_w[c] as u16)
);
// Sum up weighted pixels
let mut this_pred: u32 = weights
.iter()
.zip(pixels.iter())
.map(|(w, p)| {
let p: u32 = (*p).into();
(*w as u32) * p
})
.sum();
this_pred = (this_pred + (1 << (log2_scale - 1))) >> log2_scale;
row[c] = T::cast_from(this_pred);
}
}
}
pub(crate) fn pred_smooth_h<T: Pixel>(
output: &mut PlaneRegionMut<'_, T>, above: &[T], left: &[T], width: usize,
height: usize,
) {
let right_pred = above[width - 1]; // estimated by top-right pixel
let sm_weights = &sm_weight_arrays[width..];
let log2_scale = sm_weight_log2_scale;
let scale = 1_u16 << sm_weight_log2_scale;
// Weights sanity checks
assert!((sm_weights[0] as u16) < scale);
assert!((scale - sm_weights[width - 1] as u16) < scale);
// ensures no overflow when calculating predictor
assert!(log2_scale as usize + size_of::<T>() < 31);
for r in 0..height {
let row = &mut output[r];
for c in 0..width {
let pixels = [left[height - 1 - r], right_pred];
let weights = [sm_weights[c] as u16, scale - sm_weights[c] as u16];
assert!(scale >= sm_weights[c] as u16);
let mut this_pred: u32 = weights
.iter()
.zip(pixels.iter())
.map(|(w, p)| {
let p: u32 = (*p).into();
(*w as u32) * p
})
.sum();
this_pred = (this_pred + (1 << (log2_scale - 1))) >> log2_scale;
row[c] = T::cast_from(this_pred);
}
}
}
pub(crate) fn pred_smooth_v<T: Pixel>(
output: &mut PlaneRegionMut<'_, T>, above: &[T], left: &[T], width: usize,
height: usize,
) {
let below_pred = left[0]; // estimated by bottom-left pixel
let sm_weights = &sm_weight_arrays[height..];
let log2_scale = sm_weight_log2_scale;
let scale = 1_u16 << sm_weight_log2_scale;
// Weights sanity checks
assert!((sm_weights[0] as u16) < scale);
assert!((scale - sm_weights[height - 1] as u16) < scale);
// ensures no overflow when calculating predictor
assert!(log2_scale as usize + size_of::<T>() < 31);
for r in 0..height {
let row = &mut output[r];
for c in 0..width {
let pixels = [above[c], below_pred];