1use super::{
28 BMODE_CANDIDATES, BlockType, COEFF_BANDS, ENC_BPRED_ORIGIN, ENC_BPRED_STRIDE,
29 IDCT_BASIS_NORM_SQ, IntraBmode, IntraUvMode, IntraYMode, KF_BMODE_BITS, KF_UV_MODE_PROB,
30 KF_YMODE_PATHS, KF_YMODE_PROB, MbAnalysis, MbCoeffs, MbPixels, MbRdCtx, TrellisBlockSpec,
31 TrellisRateTables, TrellisStrength, UV_MODE_PATHS, block_ssd, build_enc_bpred_buffer,
32 forward_dct_4x4, forward_wht_4x4, predict_b4x4, predict_uv8x8, predict_y16x16,
33 reconstruct_block_4x4, rounded_level, transform_chroma_plane_rd, transform_whole_block_luma_rd,
34 treed_bits_cached, trellis_quantize_block,
35};
36use crate::coded_header::TokenProbUpdates;
37use crate::intra_predict::DEFAULT_ABOVE_PIXEL;
38use crate::reconstruct::MbNeighbors;
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
50#[non_exhaustive]
51pub enum EncodeEffort {
52 Fastest,
59 Fast,
63 #[default]
69 Balanced,
70 Thorough,
74}
75
76impl EncodeEffort {
77 pub const fn level(self) -> u8 {
79 match self {
80 EncodeEffort::Fastest => 0,
81 EncodeEffort::Fast => 1,
82 EncodeEffort::Balanced => 2,
83 EncodeEffort::Thorough => 3,
84 }
85 }
86
87 pub const fn from_level(level: u8) -> Self {
90 match level {
91 0 => EncodeEffort::Fastest,
92 1 => EncodeEffort::Fast,
93 2 => EncodeEffort::Balanced,
94 _ => EncodeEffort::Thorough,
95 }
96 }
97
98 pub const fn name(self) -> &'static str {
101 match self {
102 EncodeEffort::Fastest => "fastest",
103 EncodeEffort::Fast => "fast",
104 EncodeEffort::Balanced => "balanced",
105 EncodeEffort::Thorough => "thorough",
106 }
107 }
108
109 pub fn parse(text: &str) -> Option<Self> {
111 match text {
112 "fastest" | "0" => Some(EncodeEffort::Fastest),
113 "fast" | "1" => Some(EncodeEffort::Fast),
114 "balanced" | "2" => Some(EncodeEffort::Balanced),
115 "thorough" | "3" => Some(EncodeEffort::Thorough),
116 _ => None,
117 }
118 }
119
120 pub const ALL: [EncodeEffort; 4] = [
122 EncodeEffort::Fastest,
123 EncodeEffort::Fast,
124 EncodeEffort::Balanced,
125 EncodeEffort::Thorough,
126 ];
127
128 fn model_search(self) -> Option<ModelSearch> {
131 match self {
132 EncodeEffort::Fastest => Some(ModelSearch {
133 bmode_shortlist: 2,
134 whole_modes_by_prediction_error: true,
135 skip_bpred_without_luma_ac: true,
136 trellis: false,
137 }),
138 EncodeEffort::Fast => Some(ModelSearch {
139 bmode_shortlist: 4,
140 whole_modes_by_prediction_error: false,
141 skip_bpred_without_luma_ac: true,
142 trellis: true,
143 }),
144 EncodeEffort::Balanced => Some(ModelSearch {
145 bmode_shortlist: BMODE_CANDIDATES.len(),
146 whole_modes_by_prediction_error: false,
147 skip_bpred_without_luma_ac: false,
148 trellis: true,
149 }),
150 EncodeEffort::Thorough => None,
151 }
152 }
153}
154
155#[derive(Debug, Clone, Copy, PartialEq, Eq)]
166#[non_exhaustive]
167pub struct KeyframeEncodeOptions {
168 pub effort: EncodeEffort,
170 pub threads: usize,
176 pub auto_loop_filter: bool,
181 pub fitted_token_prob_updates: bool,
187 pub token_prob_fit: bool,
194 pub search_token_probs: Option<TokenProbUpdates>,
202 pub sampled_loop_filter: bool,
210}
211
212impl Default for KeyframeEncodeOptions {
213 fn default() -> Self {
214 KeyframeEncodeOptions {
215 effort: EncodeEffort::default(),
216 threads: 0,
217 auto_loop_filter: false,
218 fitted_token_prob_updates: false,
219 token_prob_fit: true,
220 search_token_probs: None,
221 sampled_loop_filter: false,
222 }
223 }
224}
225
226impl KeyframeEncodeOptions {
227 pub fn new() -> Self {
230 Self::default()
231 }
232
233 pub fn exhaustive() -> Self {
238 Self::default()
239 .with_effort(EncodeEffort::Thorough)
240 .with_token_prob_fit(false)
241 }
242
243 #[must_use]
245 pub fn with_effort(mut self, v: EncodeEffort) -> Self {
246 self.effort = v;
247 self
248 }
249
250 #[must_use]
252 pub fn with_threads(mut self, v: usize) -> Self {
253 self.threads = v;
254 self
255 }
256
257 #[must_use]
259 pub fn with_auto_loop_filter(mut self, v: bool) -> Self {
260 self.auto_loop_filter = v;
261 self
262 }
263
264 #[must_use]
266 pub fn with_fitted_token_prob_updates(mut self, v: bool) -> Self {
267 self.fitted_token_prob_updates = v;
268 self
269 }
270
271 #[must_use]
273 pub fn with_token_prob_fit(mut self, v: bool) -> Self {
274 self.token_prob_fit = v;
275 self
276 }
277
278 #[must_use]
280 pub fn with_search_token_probs(mut self, v: Option<TokenProbUpdates>) -> Self {
281 self.search_token_probs = v;
282 self
283 }
284
285 #[must_use]
287 pub fn with_sampled_loop_filter(mut self, v: bool) -> Self {
288 self.sampled_loop_filter = v;
289 self
290 }
291}
292
293#[derive(Debug, Clone)]
297#[non_exhaustive]
298pub struct KeyframeEncoded {
299 pub bytes: Vec<u8>,
301 pub reconstruction: crate::frame::KeyframePlanes,
304 pub token_prob_updates: Option<TokenProbUpdates>,
309 pub loop_filter_level: u8,
311 pub sharpness_level: u8,
313}
314
315#[derive(Clone, Copy)]
317struct ModelSearch {
318 bmode_shortlist: usize,
322 whole_modes_by_prediction_error: bool,
325 skip_bpred_without_luma_ac: bool,
328 trellis: bool,
330}
331
332pub(super) const WEIGHT_SCALE: f64 = 4096.0;
334
335pub(super) static DCT_WEIGHTS: std::sync::LazyLock<[u64; 16]> = std::sync::LazyLock::new(|| {
339 let norms = &*IDCT_BASIS_NORM_SQ;
340 core::array::from_fn(|k| (norms[k] * WEIGHT_SCALE).round() as u64)
341});
342
343pub(super) const Y2_WEIGHTS: [u64; 16] = [(WEIGHT_SCALE / 16.0) as u64; 16];
349
350pub(super) struct BlockModel {
352 pub(super) dist: u64,
355 pub(super) dist_zero: u64,
357 pub(super) rate: f64,
360 pub(super) nonzero: bool,
362}
363
364pub(super) fn model_block_parts(
371 block: &mut [i16; 16],
372 spec: TrellisBlockSpec,
373 weights: &[u64; 16],
374 tables: &TrellisRateTables,
375) -> BlockModel {
376 let first = spec.first_coeff;
377 debug_assert!(first <= 1, "§13.3 blocks start at coefficient 0 or 1");
378 let (dc_q, ac_q) = (spec.dc as u32, spec.ac as u32);
379 let zigzag = &crate::dct_tokens::ZIGZAG;
385 let mut magnitude = [0u32; 16];
386 for (m, &pos) in magnitude.iter_mut().zip(zigzag.iter()) {
387 *m = block[pos].unsigned_abs() as u32;
388 }
389 if first != 0 {
390 magnitude[0] = 0;
391 }
392 let mut thresholds = [ac_q - ac_q / 2; 16];
393 thresholds[0] = dc_q - dc_q / 2;
394 let mut dist_zero = 0u64;
395 let mut any_level = false;
396 for k in 0..16 {
397 let ax = magnitude[k];
398 dist_zero += weights[k] * (ax as u64 * ax as u64);
399 any_level |= ax >= thresholds[k];
400 }
401 let mut ctx3 = spec.entry_ctx3;
402 if !any_level {
403 let rate = tables.eob[spec.plane][COEFF_BANDS[first]][ctx3];
404 *block = [0i16; 16];
405 return BlockModel {
406 dist: dist_zero,
407 dist_zero,
408 rate,
409 nonzero: false,
410 };
411 }
412 let mut levels = [0u32; 16];
413 let mut negative = 0u32;
414 let mut coded = 0u32;
415 let mut dist = 0u64;
416 for k in first..16 {
417 let ax = magnitude[k];
418 let q = if k == 0 { dc_q } else { ac_q };
419 let level = rounded_level(ax, q);
420 let err = (ax as i64 - level as i64 * q as i64).unsigned_abs();
421 dist += weights[k] * err * err;
422 levels[k] = level;
423 negative |= ((block[crate::dct_tokens::ZIGZAG[k]] < 0) as u32) << k;
424 coded |= ((level != 0) as u32) << k;
425 }
426 *block = [0i16; 16];
427 let small = &tables.small[spec.plane];
428 debug_assert!(coded != 0, "a level at or past half a step rounds up");
429 let end = 32 - coded.leading_zeros() as usize;
430
431 let mut rate = 0.0;
432 let mut prev_was_zero = 0usize;
433 for k in first..end {
434 let level = levels[k];
435 let band = COEFF_BANDS[k];
436 rate += if level <= super::TRELLIS_SMALL_LEVEL_MAX as u32 {
437 small[band][ctx3][prev_was_zero][level as usize]
438 } else {
439 TrellisRateTables::level_rate(
440 &small[band],
441 &tables.cat_path[spec.plane][band],
442 ctx3,
443 prev_was_zero == 1,
444 level,
445 )
446 };
447 ctx3 = (level as usize).min(2);
448 prev_was_zero = (level == 0) as usize;
449 let signed = level as i16;
450 block[crate::dct_tokens::ZIGZAG[k]] = if (negative >> k) & 1 != 0 {
451 -signed
452 } else {
453 signed
454 };
455 }
456 if end < 16 {
457 rate += tables.eob[spec.plane][COEFF_BANDS[end]][ctx3];
458 }
459 BlockModel {
460 dist,
461 dist_zero,
462 rate,
463 nonzero: true,
464 }
465}
466
467#[inline]
481pub(super) fn model_block_cost(
482 block: &[i16; 16],
483 spec: TrellisBlockSpec,
484 weights: &[u64; 16],
485 tables: &TrellisRateTables,
486 lambda: f64,
487) -> (f64, bool) {
488 let first = spec.first_coeff;
489 debug_assert!(first <= 1, "§13.3 blocks start at coefficient 0 or 1");
490 let (dc_q, ac_q) = (spec.dc as u32, spec.ac as u32);
491 let mut magnitude = [0u32; 16];
492 for (m, &pos) in magnitude.iter_mut().zip(crate::dct_tokens::ZIGZAG.iter()) {
493 *m = block[pos].unsigned_abs() as u32;
494 }
495 if first != 0 {
496 magnitude[0] = 0;
497 }
498 let mut thresholds = [ac_q - ac_q / 2; 16];
500 thresholds[0] = dc_q - dc_q / 2;
501 let mut dist = 0u64;
502 let mut coded = 0u32;
503 for k in 0..16 {
504 let ax = magnitude[k];
505 dist += weights[k] * (ax as u64 * ax as u64);
506 coded |= ((ax >= thresholds[k]) as u32) << k;
507 }
508 let plane = spec.plane;
509 let eob = &tables.eob[plane];
510 let mut ctx3 = spec.entry_ctx3;
511 if coded == 0 {
512 let rate = eob[COEFF_BANDS[first]][ctx3];
513 return (dist as f64 / WEIGHT_SCALE + lambda * rate, false);
514 }
515 let small = &tables.small[plane];
516 let zero_run = &tables.zero_run[plane];
517 let mut rate = 0.0;
518 let mut pos = first;
519 let mut after_zero = 0usize;
520 let mut pending = coded;
521 while pending != 0 {
522 let k = pending.trailing_zeros() as usize;
523 pending &= pending - 1;
524 if k > pos {
525 rate += small[COEFF_BANDS[pos]][ctx3][after_zero][0];
528 rate += zero_run[k] - zero_run[pos + 1];
529 ctx3 = 0;
530 after_zero = 1;
531 }
532 let ax = magnitude[k];
533 let q = if k == 0 { dc_q } else { ac_q };
534 let level = rounded_level(ax, q);
535 let err = (ax as i64 - level as i64 * q as i64).unsigned_abs();
536 dist -= weights[k] * (ax as u64 * ax as u64 - err * err);
538 let band = COEFF_BANDS[k];
539 rate += if level <= super::TRELLIS_SMALL_LEVEL_MAX as u32 {
540 small[band][ctx3][after_zero][level as usize]
541 } else {
542 TrellisRateTables::level_rate(
543 &small[band],
544 &tables.cat_path[plane][band],
545 ctx3,
546 after_zero == 1,
547 level,
548 )
549 };
550 ctx3 = (level as usize).min(2);
551 after_zero = 0;
552 pos = k + 1;
553 }
554 if pos < 16 {
555 rate += eob[COEFF_BANDS[pos]][ctx3];
556 }
557 (dist as f64 / WEIGHT_SCALE + lambda * rate, true)
558}
559
560#[inline]
563pub(super) fn residual_dct(
564 src: &[u8],
565 pred: &[u8],
566 stride: usize,
567 row: usize,
568 col: usize,
569) -> [i16; 16] {
570 let mut residual = [0i16; 16];
571 for r in 0..4 {
572 let off = (row + r) * stride + col;
573 for c in 0..4 {
574 residual[r * 4 + c] = src[off + c] as i16 - pred[off + c] as i16;
575 }
576 }
577 let mut coeffs = [0i16; 16];
578 forward_dct_4x4(&residual, &mut coeffs);
579 coeffs
580}
581
582fn model_whole_luma(
589 src: &[u8; 256],
590 pred: &[u8; 256],
591 rd: &MbRdCtx,
592 tables: &TrellisRateTables,
593 budget: f64,
594) -> Option<(f64, bool)> {
595 let factors = rd.factors;
596 let dct_weights = &*DCT_WEIGHTS;
597 let mut dcs = [0i16; 16];
598 let mut above = [false; 4];
599 let mut left = [false; 4];
600 let mut cost = 0.0;
601 let mut any_ac = false;
602 for i in 0..4 {
603 for j in 0..4 {
604 let mut coeffs = residual_dct(src, pred, 16, i * 4, j * 4);
605 dcs[i * 4 + j] = coeffs[0];
606 coeffs[0] = 0;
607 let (c, nonzero) = model_block_cost(
608 &coeffs,
609 TrellisBlockSpec {
610 dc: factors.y1_dc,
611 ac: factors.y1_ac,
612 first_coeff: BlockType::YAfterY2.first_coeff(),
613 entry_ctx3: above[j] as usize + left[i] as usize,
614 plane: BlockType::YAfterY2.plane_index(),
615 },
616 dct_weights,
617 tables,
618 rd.lambda,
619 );
620 cost += c;
621 above[j] = nonzero;
622 left[i] = nonzero;
623 any_ac |= nonzero;
624 }
625 if cost >= budget {
626 return None;
627 }
628 }
629 let mut y2 = [0i16; 16];
630 forward_wht_4x4(&dcs, &mut y2);
631 let (c, _) = model_block_cost(
632 &y2,
633 TrellisBlockSpec {
634 dc: factors.y2_dc,
635 ac: factors.y2_ac,
636 first_coeff: BlockType::Y2.first_coeff(),
637 entry_ctx3: 0,
638 plane: BlockType::Y2.plane_index(),
639 },
640 &Y2_WEIGHTS,
641 tables,
642 rd.lambda,
643 );
644 Some((cost + c, any_ac))
645}
646
647fn model_chroma_plane(
649 src: &[u8; 64],
650 pred: &[u8; 64],
651 rd: &MbRdCtx,
652 tables: &TrellisRateTables,
653) -> f64 {
654 let factors = rd.factors;
655 let dct_weights = &*DCT_WEIGHTS;
656 let mut above = [false; 2];
657 let mut left = [false; 2];
658 let mut cost = 0.0;
659 for (i, left_nonzero) in left.iter_mut().enumerate() {
660 for (j, above_nonzero) in above.iter_mut().enumerate() {
661 let coeffs = residual_dct(src, pred, 8, i * 4, j * 4);
662 let (c, nonzero) = model_block_cost(
663 &coeffs,
664 TrellisBlockSpec {
665 dc: factors.uv_dc,
666 ac: factors.uv_ac,
667 first_coeff: BlockType::UV.first_coeff(),
668 entry_ctx3: *above_nonzero as usize + *left_nonzero as usize,
669 plane: BlockType::UV.plane_index(),
670 },
671 dct_weights,
672 tables,
673 rd.lambda,
674 );
675 cost += c;
676 *above_nonzero = nonzero;
677 *left_nonzero = nonzero;
678 }
679 }
680 cost
681}
682
683pub(super) struct BmodeContext {
689 pub(super) above: [IntraBmode; 4],
690 pub(super) left: [IntraBmode; 4],
691}
692
693struct ModelBpred {
695 modes: [IntraBmode; 16],
696 y_coeffs: [[i16; 16]; 16],
697 cost: f64,
698}
699
700fn model_bpred_luma(
710 src: &[u8; 256],
711 neighbors: &MbNeighbors,
712 bmode_ctx: &BmodeContext,
713 rd: &MbRdCtx,
714 tables: &TrellisRateTables,
715 search: ModelSearch,
716 budget: f64,
717) -> Option<ModelBpred> {
718 let factors = rd.factors;
719 let mut buf = build_enc_bpred_buffer(neighbors);
720 let mut modes = [IntraBmode::Dc; 16];
721 let mut y_coeffs = [[0i16; 16]; 16];
722 let mut total = 0.0;
723 let mut tok_above = [false; 4];
724 let mut tok_left = [false; 4];
725 let trellis = search.trellis && rd.trellis_active();
726 let bmode_bits = &*KF_BMODE_BITS;
727 let dct_weights = &*DCT_WEIGHTS;
728
729 for i in 0..4 {
730 for j in 0..4 {
731 let idx = i * 4 + j;
732 let sb_base = ENC_BPRED_ORIGIN + (i * 4) * ENC_BPRED_STRIDE + (j * 4);
733 let above_base = sb_base - ENC_BPRED_STRIDE;
734 let mut above = [0u8; 8];
735 above.copy_from_slice(&buf[above_base..above_base + 8]);
736 let mut left = [0u8; 4];
737 for (r, slot) in left.iter_mut().enumerate() {
738 *slot = buf[sb_base + r * ENC_BPRED_STRIDE - 1];
739 }
740 let corner = buf[above_base - 1];
741 let mut sb_src = [0u8; 16];
742 for r in 0..4 {
743 let off = (i * 4 + r) * 16 + j * 4;
744 sb_src[r * 4..r * 4 + 4].copy_from_slice(&src[off..off + 4]);
745 }
746 let above_mode = if i == 0 {
747 bmode_ctx.above[j]
748 } else {
749 modes[(i - 1) * 4 + j]
750 };
751 let left_mode = if j == 0 {
752 bmode_ctx.left[i]
753 } else {
754 modes[i * 4 + (j - 1)]
755 };
756 let mode_bits = &bmode_bits[above_mode.idx()][left_mode.idx()];
757
758 let mut preds = [[0u8; 16]; 10];
761 let mut mode_cost = [0f64; 10];
762 let mut order = [0usize; 10];
763 let mut rank = [0f64; 10];
764 let shortlisted = search.bmode_shortlist < BMODE_CANDIDATES.len();
765 for (n, &mode) in BMODE_CANDIDATES.iter().enumerate() {
766 predict_b4x4(&mut preds[n], mode, &above, &left, corner);
767 mode_cost[n] = rd.lambda * mode_bits[mode.idx()];
768 order[n] = n;
769 if shortlisted {
770 rank[n] = block_ssd(&preds[n], &sb_src) as f64 + mode_cost[n];
771 }
772 }
773 let considered = if shortlisted {
774 for slot in 0..search.bmode_shortlist {
777 let mut best = slot;
778 for probe in slot + 1..order.len() {
779 if rank[order[probe]] < rank[order[best]] {
780 best = probe;
781 }
782 }
783 order[slot..=best].rotate_right(1);
784 }
785 search.bmode_shortlist
786 } else {
787 order.len()
788 };
789
790 let entry_ctx3 = tok_above[j] as usize + tok_left[i] as usize;
791 let spec = TrellisBlockSpec {
792 dc: factors.y1_dc,
793 ac: factors.y1_ac,
794 first_coeff: BlockType::YNoY2.first_coeff(),
795 entry_ctx3,
796 plane: BlockType::YNoY2.plane_index(),
797 };
798 let mut best_n = order[0];
799 let mut best_cost = f64::INFINITY;
800 let mut best_dct = [0i16; 16];
801 for &n in &order[..considered] {
802 let mut residual = [0i16; 16];
803 for k in 0..16 {
804 residual[k] = sb_src[k] as i16 - preds[n][k] as i16;
805 }
806 let mut dct = [0i16; 16];
807 forward_dct_4x4(&residual, &mut dct);
808 let (c, _) = model_block_cost(&dct, spec, dct_weights, tables, rd.lambda);
809 let cost = c + mode_cost[n];
810 if cost < best_cost {
811 best_cost = cost;
812 best_n = n;
813 best_dct = dct;
814 }
815 }
816
817 if total + best_cost >= budget {
818 return None;
819 }
820 let coeffs = if trellis {
822 let mut c = best_dct;
823 trellis_quantize_block(
824 &mut c,
825 spec,
826 rd.coeff_probs,
827 Some(tables),
828 rd.trellis_lambda(),
829 );
830 c
831 } else {
832 let mut c = best_dct;
833 super::enc_quantize_block_range(&mut c, spec.dc, spec.ac, spec.first_coeff);
834 c
835 };
836 let recon =
837 reconstruct_block_4x4(&preds[best_n], &coeffs, factors.y1_dc, factors.y1_ac);
838 modes[idx] = BMODE_CANDIDATES[best_n];
839 y_coeffs[idx] = coeffs;
840 total += best_cost;
841 let nonzero = coeffs.iter().any(|&v| v != 0);
842 tok_above[j] = nonzero;
843 tok_left[i] = nonzero;
844 for r in 0..4 {
845 let dst = sb_base + r * ENC_BPRED_STRIDE;
846 buf[dst..dst + 4].copy_from_slice(&recon[r * 4..r * 4 + 4]);
847 }
848 }
849 }
850 Some(ModelBpred {
851 modes,
852 y_coeffs,
853 cost: total,
854 })
855}
856
857pub(super) fn analyze_mb_model(
860 pixels: &MbPixels,
861 neighbors: &MbNeighbors,
862 bmode_ctx: &BmodeContext,
863 rd: &MbRdCtx,
864 effort: EncodeEffort,
865) -> MbAnalysis {
866 let search = effort
867 .model_search()
868 .expect("the exhaustive level does not use the model search");
869 let tables = rd
870 .rate_tables
871 .expect("frame drivers attach the per-frame rate tables");
872 let plain = MbRdCtx {
875 factors: rd.factors,
876 coeff_probs: rd.coeff_probs,
877 rate_tables: rd.rate_tables,
878 lambda: rd.lambda,
879 trellis: TrellisStrength::OFF,
880 };
881 let final_rd = if search.trellis { rd } else { &plain };
882 let corner = DEFAULT_ABOVE_PIXEL;
883
884 const Y_MODES: [IntraYMode; 4] = [IntraYMode::Dc, IntraYMode::V, IntraYMode::H, IntraYMode::Tm];
886 let ymode_paths = &*KF_YMODE_PATHS;
887 let y_mode_cost = |mode: IntraYMode| {
888 rd.lambda * treed_bits_cached(ymode_paths, |i| KF_YMODE_PROB[i], mode.leaf())
889 };
890 let mut y_preds = [[0u8; 256]; 4];
891 for (pred, &mode) in y_preds.iter_mut().zip(&Y_MODES) {
892 predict_y16x16(
893 pred,
894 mode,
895 neighbors.y_above.as_ref(),
896 neighbors.y_left.as_ref(),
897 neighbors.y_topleft.unwrap_or(corner),
898 )
899 .expect("whole-block modes only");
900 }
901 let mut whole_n = 0usize;
902 let mut whole_cost = f64::INFINITY;
903 let mut whole_has_ac = false;
904 if search.whole_modes_by_prediction_error {
905 let mut best_key = f64::INFINITY;
906 for (n, &mode) in Y_MODES.iter().enumerate() {
907 let key = block_ssd(&y_preds[n], &pixels.y) as f64 + y_mode_cost(mode);
908 if key < best_key {
909 best_key = key;
910 whole_n = n;
911 }
912 }
913 let (c, has_ac) = model_whole_luma(&pixels.y, &y_preds[whole_n], rd, tables, f64::INFINITY)
914 .expect("no budget");
915 whole_cost = c + y_mode_cost(Y_MODES[whole_n]);
916 whole_has_ac = has_ac;
917 } else {
918 for (n, &mode) in Y_MODES.iter().enumerate() {
919 let signal = y_mode_cost(mode);
922 let Some((c, has_ac)) =
923 model_whole_luma(&pixels.y, &y_preds[n], rd, tables, whole_cost - signal)
924 else {
925 continue;
926 };
927 let cost = c + signal;
928 if cost < whole_cost {
929 whole_cost = cost;
930 whole_n = n;
931 whole_has_ac = has_ac;
932 }
933 }
934 }
935
936 let bpred = if search.skip_bpred_without_luma_ac && !whole_has_ac {
938 None
939 } else {
940 let signal = y_mode_cost(IntraYMode::B);
943 model_bpred_luma(
944 &pixels.y,
945 neighbors,
946 bmode_ctx,
947 final_rd,
948 tables,
949 search,
950 whole_cost - signal,
951 )
952 .filter(|pass| pass.cost + signal < whole_cost)
953 };
954
955 const UV_MODES: [IntraUvMode; 4] = [
957 IntraUvMode::Dc,
958 IntraUvMode::V,
959 IntraUvMode::H,
960 IntraUvMode::Tm,
961 ];
962 let uv_paths = &*UV_MODE_PATHS;
963 let mut uv_n = 0usize;
964 let mut uv_best = f64::INFINITY;
965 let mut u_preds = [[0u8; 64]; 4];
966 let mut v_preds = [[0u8; 64]; 4];
967 for (n, &mode) in UV_MODES.iter().enumerate() {
968 predict_uv8x8(
969 &mut u_preds[n],
970 mode,
971 neighbors.u_above.as_ref(),
972 neighbors.u_left.as_ref(),
973 neighbors.u_topleft.unwrap_or(corner),
974 );
975 predict_uv8x8(
976 &mut v_preds[n],
977 mode,
978 neighbors.v_above.as_ref(),
979 neighbors.v_left.as_ref(),
980 neighbors.v_topleft.unwrap_or(corner),
981 );
982 let mode_cost =
983 rd.lambda * treed_bits_cached(uv_paths, |i| KF_UV_MODE_PROB[i], mode.leaf());
984 let cost = mode_cost
985 + if search.whole_modes_by_prediction_error {
986 (block_ssd(&u_preds[n], &pixels.u) + block_ssd(&v_preds[n], &pixels.v)) as f64
987 } else {
988 let u_cost = model_chroma_plane(&pixels.u, &u_preds[n], rd, tables);
991 if mode_cost + u_cost >= uv_best {
992 continue;
993 }
994 u_cost + model_chroma_plane(&pixels.v, &v_preds[n], rd, tables)
995 };
996 if cost < uv_best {
997 uv_best = cost;
998 uv_n = n;
999 }
1000 }
1001
1002 let mut coeffs = MbCoeffs::default();
1004 let (y_mode, b_modes) = match bpred {
1005 Some(pass) => {
1006 coeffs.y = pass.y_coeffs;
1007 (IntraYMode::B, Some(pass.modes))
1008 }
1009 None => {
1010 let (y, y2) = transform_whole_block_luma_rd(
1011 &pixels.y,
1012 &y_preds[whole_n],
1013 rd.factors,
1014 Some(final_rd),
1015 );
1016 coeffs.y = y;
1017 coeffs.y2 = y2;
1018 (Y_MODES[whole_n], None)
1019 }
1020 };
1021 coeffs.u = transform_chroma_plane_rd(&pixels.u, &u_preds[uv_n], rd.factors, Some(final_rd));
1022 coeffs.v = transform_chroma_plane_rd(&pixels.v, &v_preds[uv_n], rd.factors, Some(final_rd));
1023 MbAnalysis::from_coeffs(coeffs, y_mode, UV_MODES[uv_n], b_modes)
1024}
1025
1026#[cfg(test)]
1027mod tests {
1028 use super::super::enc_quantize_block;
1029 use super::*;
1030
1031 #[test]
1032 fn effort_levels_round_trip() {
1033 for (n, effort) in EncodeEffort::ALL.into_iter().enumerate() {
1034 assert_eq!(effort.level() as usize, n);
1035 assert_eq!(EncodeEffort::from_level(n as u8), effort);
1036 assert_eq!(EncodeEffort::parse(effort.name()), Some(effort));
1037 assert_eq!(EncodeEffort::parse(&n.to_string()), Some(effort));
1038 }
1039 assert_eq!(EncodeEffort::from_level(200), EncodeEffort::Thorough);
1040 assert_eq!(EncodeEffort::default(), EncodeEffort::Balanced);
1041 assert_eq!(EncodeEffort::parse("turbo"), None);
1042 assert!(EncodeEffort::Fastest < EncodeEffort::Thorough);
1043 }
1044
1045 #[test]
1048 fn model_levels_match_plain_rounding() {
1049 let tables = TrellisRateTables::for_probs(&crate::DEFAULT_COEFF_PROBS);
1050 let mut lcg = 0x2468_ACE1u32;
1051 for case in 0..4000 {
1052 let mut block = [0i16; 16];
1053 for c in block.iter_mut() {
1054 lcg = lcg.wrapping_mul(1_103_515_245).wrapping_add(12345);
1055 let span = [3i32, 40, 300, 4000][case % 4];
1056 *c = (((lcg >> 12) as i32).rem_euclid(2 * span + 1) - span) as i16;
1057 }
1058 let (dc, ac) = (
1059 [4i16, 9, 31, 157][case % 4],
1060 [4i16, 12, 37, 157][(case / 4) % 4],
1061 );
1062 for (block_type, first) in [(BlockType::YNoY2, 0usize), (BlockType::YAfterY2, 1)] {
1063 let mut want = block;
1064 if first == 1 {
1065 want[0] = 0;
1066 }
1067 enc_quantize_block(&mut want, dc, ac);
1068 let mut got = block;
1069 let parts = model_block_parts(
1070 &mut got,
1071 TrellisBlockSpec {
1072 dc,
1073 ac,
1074 first_coeff: first,
1075 entry_ctx3: case % 3,
1076 plane: block_type.plane_index(),
1077 },
1078 &DCT_WEIGHTS,
1079 &tables,
1080 );
1081 let (cost, nonzero) = (
1082 parts.dist as f64 / WEIGHT_SCALE + 7.5 * parts.rate,
1083 parts.nonzero,
1084 );
1085 assert_eq!(got, want);
1086 assert_eq!(nonzero, want.iter().any(|&v| v != 0));
1087 assert!(cost.is_finite() && cost >= 0.0);
1088 let (sparse, sparse_nonzero) = model_block_cost(
1090 &block,
1091 TrellisBlockSpec {
1092 dc,
1093 ac,
1094 first_coeff: first,
1095 entry_ctx3: case % 3,
1096 plane: block_type.plane_index(),
1097 },
1098 &DCT_WEIGHTS,
1099 &tables,
1100 7.5,
1101 );
1102 assert_eq!(sparse_nonzero, nonzero);
1103 assert!(
1104 (sparse - cost).abs() <= 1e-9 * cost.max(1.0),
1105 "sparse {sparse} vs reference {cost}"
1106 );
1107 }
1108 }
1109 }
1110}