forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'simplify/u13' into simplify/w1b

Browse files at this commit

e8adf6d3d8a45c44142575ee5f46594608a00d11Ahmet Kaan GümüşParent: aada96c39a9ee6
Cargo.lockmodified+0 -1
@@ -476,7 +476,6 @@ dependencies = [
476476 name = "ec-dsp"
477477 version = "0.1.0"
478478 dependencies = [
479- "ec-core",
480479 "wide",
481480 ]
482481
crates/ec-core/src/color.rsmodified+2 -758
@@ -1,8 +1,6 @@
11 //! What the numbers in a decoded picture *mean*: which YUV->RGB matrix they
22 //! were coded against, which transfer curve, and whether they span the full byte
3-//! or the limited 16..235 range. Everything here is read off the file; the other
4-//! direction — rewriting samples from one matrix into another — is
5-//! `ec_dsp::remap`.
3+//! or the limited 16..235 range. Everything here is read off the file.
64 //!
75 //! Three tiers, in this order, per field:
86 //!
@@ -26,9 +24,7 @@
2624 //! triplet as a container carries it is [`crate::ColorInfo`]; this module is the
2725 //! meaning behind it.
2826
29-use crate::bitio::BitReader;
3027 use crate::frame::ColorInfo;
31-use crate::registry::CodecId;
3228
3329 /// The YUV->RGB matrix a stream's chroma was coded against. Only the three that
3430 /// exist in practice: SD (BT.601), HD (BT.709) and UHD/HDR (BT.2020
@@ -209,10 +205,7 @@ impl ColorInfo {
209205 Primaries::from_code(u64::from(self.primaries))
210206 }
211207
212- /// This triplet resolved against the `height` heuristic alone. A demuxer
213- /// that also holds parameter sets resolves through all three tiers instead:
214- /// `ColorDescription::resolve(info.tags(), bitstream_tags(codec, sets),
215- /// height)`.
208+ /// This triplet resolved against the `height` heuristic alone.
216209 pub fn describe(self, height: u32) -> ColorDescription {
217210 ColorDescription::resolve(self.tags(), Tags::default(), height)
218211 }
@@ -497,32 +490,6 @@ impl Tags {
497490 }
498491 }
499492
500-/// What the *encoder* wrote into the stream itself, out of the parameter sets a
501-/// demuxer already holds: the SPS VUI for H.264 and HEVC (Annex-B framed) and
502-/// the sequence header OBU for AV1.
503-///
504-/// Empty [`Tags`] for VP9, whose colour space lives in the uncompressed header
505-/// of every frame rather than out of band, for every non-video codec, and for
506-/// anything malformed: this is a middle tier, and the tier below it always has
507-/// an answer.
508-pub fn bitstream_tags(codec: CodecId, sets: &[u8]) -> Tags {
509- match codec {
510- // 7 is an H.264 SPS, 33 an HEVC one (whose NAL header is two bytes and
511- // whose type sits in bits 1..6 of the first).
512- CodecId::H264 => nal_units(sets)
513- .find(|n| n.first().is_some_and(|b| b & 0x1f == 7))
514- .map(|n| h264_sps(&rbsp(&n[1..])))
515- .unwrap_or_default(),
516- CodecId::H265 => nal_units(sets)
517- .find(|n| n.first().is_some_and(|b| (b >> 1) & 0x3f == 33))
518- .filter(|n| n.len() > 2)
519- .map(|n| hevc_sps(&rbsp(&n[2..])))
520- .unwrap_or_default(),
521- CodecId::Av1 => av1_sequence_header(sets),
522- _ => Tags::default(),
523- }
524-}
525-
526493 /// The Annex-B NAL units in `buf`, payloads only: start codes are three or four
527494 /// bytes and both are written in practice.
528495 fn nal_units(buf: &[u8]) -> impl Iterator<Item = &[u8]> {
@@ -564,540 +531,6 @@ fn rbsp(nal: &[u8]) -> Vec<u8> {
564531 out
565532 }
566533
567-/// [`BitReader`] with the contract these parsers want instead of [`Result`]:
568-/// reads past the end return zero and raise [`Bits::overrun`], which every
569-/// parser here checks before it believes anything it read — a truncated
570-/// parameter set must fall to the next tier, not report the colour of whatever
571-/// the zeros decoded to.
572-struct Bits<'a> {
573- inner: BitReader<'a>,
574- over: bool,
575-}
576-
577-impl<'a> Bits<'a> {
578- fn new(buf: &'a [u8]) -> Self {
579- Self {
580- inner: BitReader::new(buf),
581- over: false,
582- }
583- }
584-
585- fn overrun(&self) -> bool {
586- self.over
587- }
588-
589- fn bit(&mut self) -> u32 {
590- match self.inner.read_bit() {
591- Ok(bit) => u32::from(bit),
592- Err(_) => {
593- self.over = true;
594- 0
595- }
596- }
597- }
598-
599- /// `u(n)`, up to 32 bits.
600- fn u(&mut self, n: u32) -> u32 {
601- (0..n).fold(0, |acc, _| (acc << 1) | self.bit())
602- }
603-
604- /// Bits nothing here reads, in one step — profile/tier records and the like,
605- /// which run to 88 bits at a time. A skip past the end consumes what is left
606- /// and says so, so the position stays at the end rather than before it.
607- fn skip(&mut self, n: usize) {
608- if self.inner.skip_bits(n as u64).is_err() {
609- self.over = true;
610- let rest = self.inner.bits_remaining();
611- let _ = self.inner.skip_bits(rest);
612- }
613- }
614-
615- /// `ue(v)`, unsigned exp-Golomb: N leading zeros, a one, then N more bits.
616- /// Capped at 32 leading zeros, which is past any legal value and is what
617- /// keeps a garbage set from spinning here.
618- fn ue(&mut self) -> u32 {
619- let mut zeros = 0;
620- while self.bit() == 0 {
621- zeros += 1;
622- if zeros >= 32 || self.over {
623- self.over = true;
624- return 0;
625- }
626- }
627- ((1u32 << zeros) - 1).wrapping_add(self.u(zeros))
628- }
629-
630- /// `se(v)`, signed exp-Golomb: the unsigned code zig-zagged.
631- fn se(&mut self) -> i32 {
632- let k = self.ue();
633- if k.is_multiple_of(2) {
634- -((k / 2) as i32)
635- } else {
636- k.div_ceil(2) as i32
637- }
638- }
639-}
640-
641-/// H.264 `seq_parameter_set_data` (ITU-T H.264 §7.3.2.1.1) walked as far as the
642-/// VUI's `colour_description` (Annex E, §E.1.1). Everything before it is read
643-/// only to know how many bits it took — which is why the scaling lists matter: a
644-/// High-profile SPS that carries them and is walked as if it did not lands the
645-/// VUI read somewhere in the middle of a coefficient.
646-fn h264_sps(rbsp: &[u8]) -> Tags {
647- let mut b = Bits::new(rbsp);
648- let profile_idc = b.u(8);
649- b.skip(8 + 8); // constraint flags + reserved, level_idc
650- b.ue(); // seq_parameter_set_id
651- // The chroma/depth block exists only in the profiles that can code
652- // something other than 8-bit 4:2:0 (§7.3.2.1.1, the profile_idc list).
653- if matches!(
654- profile_idc,
655- 100 | 110 | 122 | 244 | 44 | 83 | 86 | 118 | 128 | 138 | 139 | 134 | 135
656- ) {
657- let chroma_format_idc = b.ue();
658- if chroma_format_idc == 3 {
659- b.bit(); // separate_colour_plane_flag
660- }
661- b.ue(); // bit_depth_luma_minus8
662- b.ue(); // bit_depth_chroma_minus8
663- b.bit(); // qpprime_y_zero_transform_bypass_flag
664- if b.bit() == 1 {
665- // seq_scaling_matrix_present_flag: 8 lists (12 for 4:4:4), the
666- // first six 16 coefficients long and the rest 64 (§7.3.2.1.1.1).
667- let lists = if chroma_format_idc == 3 { 12 } else { 8 };
668- for i in 0..lists {
669- if b.bit() == 1 {
670- scaling_list(&mut b, if i < 6 { 16 } else { 64 });
671- }
672- }
673- }
674- }
675- b.ue(); // log2_max_frame_num_minus4
676- match b.ue() {
677- // pic_order_cnt_type
678- 0 => {
679- b.ue(); // log2_max_pic_order_cnt_lsb_minus4
680- }
681- 1 => {
682- b.bit(); // delta_pic_order_always_zero_flag
683- b.se(); // offset_for_non_ref_pic
684- b.se(); // offset_for_top_to_bottom_field
685- let cycle = b.ue();
686- if cycle > 255 {
687- return Tags::default();
688- }
689- for _ in 0..cycle {
690- b.se(); // offset_for_ref_frame[i]
691- }
692- }
693- _ => {}
694- }
695- b.ue(); // max_num_ref_frames
696- b.bit(); // gaps_in_frame_num_value_allowed_flag
697- b.ue(); // pic_width_in_mbs_minus1
698- b.ue(); // pic_height_in_map_units_minus1
699- if b.bit() == 0 {
700- b.bit(); // mb_adaptive_frame_field_flag, when !frame_mbs_only_flag
701- }
702- b.bit(); // direct_8x8_inference_flag
703- if b.bit() == 1 {
704- // frame_cropping_flag: four offsets
705- for _ in 0..4 {
706- b.ue();
707- }
708- }
709- if b.bit() == 0 {
710- return Tags::default(); // no VUI at all
711- }
712- vui_colour(&mut b)
713-}
714-
715-/// One H.264 scaling list (§7.3.2.1.1.1): `size` deltas, the run stopping early
716-/// once a `nextScale` of zero says the rest of the list is the default one.
717-fn scaling_list(b: &mut Bits, size: usize) {
718- let mut next = 8;
719- for _ in 0..size {
720- if next != 0 {
721- next = (next + b.se() + 256) % 256;
722- }
723- if b.overrun() {
724- return;
725- }
726- }
727-}
728-
729-/// HEVC `seq_parameter_set_rbsp` (ITU-T H.265 §7.3.2.2.1) to its VUI (§E.2.1).
730-/// The two places bits are easy to lose are the profile/tier record (§7.3.3) and
731-/// the short-term reference picture sets (§7.3.7), both of which are counted
732-/// here rather than read.
733-fn hevc_sps(rbsp: &[u8]) -> Tags {
734- let mut b = Bits::new(rbsp);
735- b.skip(4); // sps_video_parameter_set_id
736- let max_sub_layers_minus1 = b.u(3);
737- b.bit(); // sps_temporal_id_nesting_flag
738- profile_tier_level(&mut b, max_sub_layers_minus1);
739- b.ue(); // sps_seq_parameter_set_id
740- let chroma_format_idc = b.ue();
741- if chroma_format_idc == 3 {
742- b.bit(); // separate_colour_plane_flag
743- }
744- b.ue(); // pic_width_in_luma_samples
745- b.ue(); // pic_height_in_luma_samples
746- if b.bit() == 1 {
747- // conformance_window_flag
748- for _ in 0..4 {
749- b.ue();
750- }
751- }
752- b.ue(); // bit_depth_luma_minus8
753- b.ue(); // bit_depth_chroma_minus8
754- let log2_max_poc_lsb = b.ue() + 4;
755- let ordering_info = b.bit() == 1;
756- let first = if ordering_info {
757- 0
758- } else {
759- max_sub_layers_minus1
760- };
761- for _ in first..=max_sub_layers_minus1 {
762- b.ue(); // sps_max_dec_pic_buffering_minus1
763- b.ue(); // sps_max_num_reorder_pics
764- b.ue(); // sps_max_latency_increase_plus1
765- }
766- for _ in 0..6 {
767- // log2_min_luma_coding_block_size_minus3 through
768- // max_transform_hierarchy_depth_intra: six plain ue(v)s.
769- b.ue();
770- }
771- if b.bit() == 1 && b.bit() == 1 {
772- // scaling_list_enabled_flag && sps_scaling_list_data_present_flag
773- scaling_list_data(&mut b);
774- }
775- b.bit(); // amp_enabled_flag
776- b.bit(); // sample_adaptive_offset_enabled_flag
777- if b.bit() == 1 {
778- // pcm_enabled_flag
779- b.skip(8); // pcm_sample_bit_depth_luma/chroma_minus1
780- b.ue(); // log2_min_pcm_luma_coding_block_size_minus3
781- b.ue(); // log2_diff_max_min_pcm_luma_coding_block_size
782- b.bit(); // pcm_loop_filter_disabled_flag
783- }
784- let sets = b.ue();
785- if sets > 64 || b.overrun() {
786- return Tags::default();
787- }
788- let mut counts = Vec::with_capacity(sets as usize);
789- for i in 0..sets as usize {
790- st_ref_pic_set(&mut b, i, &mut counts);
791- if b.overrun() {
792- return Tags::default();
793- }
794- }
795- if b.bit() == 1 {
796- // long_term_ref_pics_present_flag
797- let lt = b.ue();
798- if lt > 64 {
799- return Tags::default();
800- }
801- for _ in 0..lt {
802- b.skip(log2_max_poc_lsb as usize); // lt_ref_pic_poc_lsb_sps[i]
803- b.bit(); // used_by_curr_pic_lt_sps_flag[i]
804- }
805- }
806- b.bit(); // sps_temporal_mvp_enabled_flag
807- b.bit(); // strong_intra_smoothing_enabled_flag
808- if b.bit() == 0 {
809- return Tags::default(); // no VUI at all
810- }
811- vui_colour(&mut b)
812-}
813-
814-/// `profile_tier_level` (§7.3.3), counted: 2+1+5 bits of general profile, 32
815-/// compatibility flags, 48 bits of source/reserved flags and an 8-bit level,
816-/// then one 88-bit record per sub-layer that declares one.
817-fn profile_tier_level(b: &mut Bits, max_sub_layers_minus1: u32) {
818- b.skip(2 + 1 + 5 + 32 + 48 + 8);
819- let mut present = [(false, false); 8];
820- for slot in present.iter_mut().take(max_sub_layers_minus1 as usize) {
821- *slot = (b.bit() == 1, b.bit() == 1);
822- }
823- if max_sub_layers_minus1 > 0 {
824- // reserved_zero_2bits up to eight sub-layers.
825- b.skip(2 * (8 - max_sub_layers_minus1 as usize));
826- }
827- for &(profile, level) in present.iter().take(max_sub_layers_minus1 as usize) {
828- if profile {
829- b.skip(88);
830- }
831- if level {
832- b.skip(8);
833- }
834- }
835-}
836-
837-/// `scaling_list_data` (§7.3.4): four sizes of six matrices each (the last size
838-/// has two), either predicted from an earlier matrix or written out as deltas.
839-fn scaling_list_data(b: &mut Bits) {
840- for size_id in 0..4 {
841- let step = if size_id == 3 { 3 } else { 1 };
842- for _ in (0..6).step_by(step) {
843- if b.bit() == 0 {
844- b.ue(); // scaling_list_pred_matrix_id_delta
845- continue;
846- }
847- let coefs = 64.min(1 << (4 + (size_id << 1)));
848- if size_id > 1 {
849- b.se(); // scaling_list_dc_coef_minus8
850- }
851- for _ in 0..coefs {
852- b.se(); // scaling_list_delta_coef
853- }
854- if b.overrun() {
855- return;
856- }
857- }
858- }
859-}
860-
861-/// One `st_ref_pic_set` (§7.3.7), kept only for the number of pictures it holds:
862-/// that count is what the *next* set spends a flag per picture on when it
863-/// predicts from this one, so losing it loses the bit position.
864-///
865-/// corner-cut: the predicted case counts flags rather than deriving the POCs
866-/// (§7.4.8, (7-59)..(7-71)), so a set whose `deltaRps` cancels a reference's own
867-/// delta exactly — a picture at POC distance zero, which is the current picture
868-/// and which no encoder emits — would be counted one too high. The upgrade path
869-/// is carrying the `DeltaPocS0/S1` arrays through the loop; the price of being
870-/// wrong is a VUI that reads as garbage and falls to the resolution heuristic,
871-/// not a bad picture.
872-fn st_ref_pic_set(b: &mut Bits, idx: usize, counts: &mut Vec<u32>) {
873- if idx > 0 && b.bit() == 1 {
874- b.bit(); // delta_rps_sign
875- b.ue(); // abs_delta_rps_minus1
876- let mut kept = 0;
877- for _ in 0..=counts[idx - 1] {
878- // used_by_curr_pic_flag, and use_delta_flag only when it is not.
879- let used = b.bit() == 1;
880- kept += u32::from(used || b.bit() == 1);
881- }
882- counts.push(kept);
883- return;
884- }
885- let negative = b.ue();
886- let positive = b.ue();
887- if negative > 64 || positive > 64 {
888- b.over = true;
889- counts.push(0);
890- return;
891- }
892- for _ in 0..negative + positive {
893- b.ue(); // delta_poc_s0/s1_minus1
894- b.bit(); // used_by_curr_pic_s0/s1_flag
895- }
896- counts.push(negative + positive);
897-}
898-
899-/// The head of a VUI, H.264 (§E.1.1) and HEVC (§E.2.1) alike — the two are
900-/// byte-identical up to and including `colour_description`, which is all that is
901-/// read here.
902-fn vui_colour(b: &mut Bits) -> Tags {
903- if b.bit() == 1 {
904- // aspect_ratio_info_present_flag
905- if b.u(8) == 255 {
906- // Extended_SAR: the ratio is written out rather than indexed.
907- b.skip(32);
908- }
909- }
910- if b.bit() == 1 {
911- b.bit(); // overscan_appropriate_flag
912- }
913- if b.bit() == 0 {
914- return Tags::default(); // no video_signal_type at all
915- }
916- b.skip(3); // video_format
917- let full_range = b.bit();
918- if b.bit() == 0 || b.overrun() {
919- // colour_description_present_flag: the range flag still stands on its
920- // own, which is what an untagged-but-full-range stream says.
921- return Tags {
922- full_range: (!b.overrun()).then_some(full_range == 1),
923- ..Tags::default()
924- };
925- }
926- let (primaries, transfer, matrix) = (b.u(8), b.u(8), b.u(8));
927- let _ = primaries;
928- if b.overrun() {
929- return Tags::default();
930- }
931- Tags::from_codes(
932- u64::from(matrix),
933- u64::from(transfer),
934- u64::from(full_range) + 1,
935- )
936-}
937-
938-/// `color_config` out of the sequence header OBU (AV1 §5.5.1, §5.5.2), which is
939-/// what `av1C`/`CodecPrivate` carries and what a demuxer re-injects ahead of
940-/// every keyframe. The whole header before it is counted, and most of it is
941-/// conditional — the operating points and the decoder model in particular.
942-fn av1_sequence_header(obus: &[u8]) -> Tags {
943- let Some(payload) = sequence_header_obu(obus) else {
944- return Tags::default();
945- };
946- let mut b = Bits::new(payload);
947- let seq_profile = b.u(3);
948- b.bit(); // still_picture
949- let reduced = b.bit() == 1;
950- let mut decoder_model = false;
951- if reduced {
952- b.skip(5); // seq_level_idx[0]
953- } else {
954- if b.bit() == 1 {
955- // timing_info: two 32-bit ticks and, if the interval is fixed, a
956- // uvlc() -- the one variable-length code in this header.
957- b.skip(64);
958- if b.bit() == 1 {
959- uvlc(&mut b);
960- }
961- decoder_model = b.bit() == 1;
962- if decoder_model {
963- b.skip(5 + 32 + 5 + 5);
964- }
965- }
966- let initial_display_delay = b.bit() == 1;
967- let operating_points = b.u(5) + 1;
968- for _ in 0..operating_points {
969- b.skip(12); // operating_point_idc[i]
970- let level = b.u(5);
971- if level > 7 {
972- b.bit(); // seq_tier[i]
973- }
974- if decoder_model && b.bit() == 1 {
975- // operating_parameters_info: two delays of the length the
976- // decoder model declared, plus low_delay_mode_flag. The lengths
977- // were skipped above, so a file with a decoder model is where
978- // this walk stops being able to count.
979- return Tags::default();
980- }
981- if initial_display_delay && b.bit() == 1 {
982- b.skip(4); // initial_display_delay_minus_1[i]
983- }
984- }
985- }
986- let width_bits = b.u(4) + 1;
987- let height_bits = b.u(4) + 1;
988- b.skip((width_bits + height_bits) as usize); // max_frame_width/height_minus_1
989- if !reduced && b.bit() == 1 {
990- b.skip(4 + 3); // delta/additional frame id lengths
991- }
992- b.skip(3); // use_128x128_superblock, enable_filter_intra, intra_edge_filter
993- if !reduced {
994- b.skip(4); // enable_interintra_compound .. enable_dual_filter
995- let order_hint = b.bit() == 1;
996- if order_hint {
997- b.skip(2); // enable_jnt_comp, enable_ref_frame_mvs
998- }
999- // seq_choose_screen_content_tools, or the forced value when it is not
1000- // chosen; the integer-mv pair after it exists only when the tools do.
1001- let screen_content = if b.bit() == 1 { 2 } else { b.bit() };
1002- if screen_content > 0 && b.bit() == 0 {
1003- b.bit(); // seq_force_integer_mv
1004- }
1005- if order_hint {
1006- b.skip(3); // order_hint_bits_minus_1
1007- }
1008- }
1009- b.skip(3); // enable_superres, enable_cdef, enable_restoration
1010- av1_color_config(&mut b, seq_profile)
1011-}
1012-
1013-/// The payload of the first sequence header OBU (type 1) in a low-overhead OBU
1014-/// stream (AV1 §5.3.1): a one-byte header, an optional extension byte, and an
1015-/// optional leb128 size.
1016-fn sequence_header_obu(mut buf: &[u8]) -> Option<&[u8]> {
1017- while let Some((&head, rest)) = buf.split_first() {
1018- let kind = (head >> 3) & 0xf;
1019- let mut rest = rest;
1020- if head & 0x4 != 0 {
1021- rest = rest.get(1..)?; // obu_extension_flag: temporal/spatial ids
1022- }
1023- let size = if head & 0x2 != 0 {
1024- let (size, read) = leb128(rest)?;
1025- rest = rest.get(read..)?;
1026- size.min(rest.len())
1027- } else {
1028- rest.len()
1029- };
1030- if kind == 1 {
1031- return rest.get(..size);
1032- }
1033- buf = rest.get(size..)?;
1034- }
1035- None
1036-}
1037-
1038-/// leb128 as AV1 writes it (§4.10.5): seven bits a byte, low group first, the
1039-/// top bit saying another follows.
1040-fn leb128(buf: &[u8]) -> Option<(usize, usize)> {
1041- let mut value = 0usize;
1042- for i in 0..8 {
1043- let &byte = buf.get(i)?;
1044- value |= usize::from(byte & 0x7f) << (i * 7);
1045- if byte & 0x80 == 0 {
1046- return Some((value, i + 1));
1047- }
1048- }
1049- None
1050-}
1051-
1052-/// `uvlc()` (AV1 §4.10.3): leading zeros, then that many bits, biased — the same
1053-/// shape as exp-Golomb with a different bias.
1054-fn uvlc(b: &mut Bits) {
1055- let mut zeros = 0;
1056- while b.bit() == 0 && !b.overrun() {
1057- zeros += 1;
1058- if zeros >= 32 {
1059- b.over = true;
1060- return;
1061- }
1062- }
1063- b.skip(zeros);
1064-}
1065-
1066-/// `color_config` (AV1 §5.5.2). The bit depth and the subsampling are read only
1067-/// as far as they cost bits before `color_range`.
1068-fn av1_color_config(b: &mut Bits, seq_profile: u32) -> Tags {
1069- let high_bitdepth = b.bit() == 1;
1070- if seq_profile == 2 && high_bitdepth {
1071- b.bit(); // twelve_bit
1072- }
1073- let mono_chrome = seq_profile != 1 && b.bit() == 1;
1074- let described = b.bit() == 1;
1075- let (primaries, transfer, matrix) = if described {
1076- (b.u(8), b.u(8), b.u(8))
1077- } else {
1078- (2, 2, 2) // CP/TC/MC_UNSPECIFIED
1079- };
1080- if b.overrun() {
1081- return Tags::default();
1082- }
1083- let full_range = if mono_chrome {
1084- b.bit() == 1
1085- } else if primaries == 1 && transfer == 13 && matrix == 0 {
1086- // sRGB in an identity matrix is full range by definition, and the flag
1087- // is not written.
1088- true
1089- } else {
1090- b.bit() == 1
1091- };
1092- if b.overrun() {
1093- return Tags::default();
1094- }
1095- Tags {
1096- full_range: Some(full_range),
1097- ..Tags::from_codes(u64::from(matrix), u64::from(transfer), 0)
1098- }
1099-}
1100-
1101534 #[cfg(test)]
1102535 mod tests {
1103536 use super::*;
@@ -1255,195 +688,6 @@ mod tests {
1255688 );
1256689 }
1257690
1258- /// The bit reader, against a hand-built pattern: exp-Golomb is where a
1259- /// mis-read shifts everything after it.
1260- #[test]
1261- fn bit_reader_reads_exp_golomb() {
1262- // 1 | 010 | 011 | 00100 : ue = 0, 1, 2, 3
1263- let mut b = Bits::new(&[0b1010_0110, 0b0100_0000]);
1264- assert_eq!((b.ue(), b.ue(), b.ue(), b.ue()), (0, 1, 2, 3));
1265- assert!(!b.overrun());
1266- // se zig-zags: 0, 1, -1, 2
1267- let mut b = Bits::new(&[0b1010_0110, 0b0100_0000]);
1268- assert_eq!((b.se(), b.se(), b.se(), b.se()), (0, 1, -1, 2));
1269- // Past the end reads zero and says so.
1270- let mut b = Bits::new(&[0xff]);
1271- b.skip(8);
1272- assert_eq!(b.u(4), 0);
1273- assert!(b.overrun());
1274- // ...and a skip longer than what is left lands at the end, not before.
1275- let mut b = Bits::new(&[0xff, 0xff]);
1276- b.skip(64);
1277- assert!(b.overrun());
1278- assert_eq!(b.u(1), 0);
1279- }
1280-
1281- /// Emulation prevention: the `03` is syntax-invisible, a third `00` is not.
1282- #[test]
1283- fn rbsp_drops_emulation_bytes() {
1284- assert_eq!(rbsp(&[0, 0, 3, 1, 0, 0, 3, 0]), vec![0, 0, 1, 0, 0, 0]);
1285- assert_eq!(rbsp(&[0, 3, 3]), vec![0, 3, 3]);
1286- }
1287-
1288- /// Bits written out as `'0'`/`'1'`, MSB first, for a hand-built SPS.
1289- fn bits_of(pattern: &str) -> Vec<u8> {
1290- let mut out = Vec::new();
1291- for (i, c) in pattern.chars().filter(|c| !c.is_whitespace()).enumerate() {
1292- if i % 8 == 0 {
1293- out.push(0);
1294- }
1295- if c == '1' {
1296- *out.last_mut().unwrap() |= 0x80 >> (i % 8);
1297- }
1298- }
1299- out
1300- }
1301-
1302- /// A High-profile SPS written by hand, because no encoder in this family
1303- /// writes one with its scaling lists in the *sequence* parameter set (the external encoder
1304- /// puts its quant matrices in the PPS). The lists are what makes this test
1305- /// worth having: read as if they were not there, the VUI lands
1306- /// mid-coefficient and the colour comes out as noise.
1307- #[test]
1308- fn h264_scaling_lists_are_skipped_before_the_vui() {
1309- let sps = concat!(
1310- "01100100", // profile_idc 100 (High)
1311- "00000000", // constraint flags + reserved
1312- "00011110", // level_idc 30
1313- "1", // seq_parameter_set_id ue(0)
1314- "010", // chroma_format_idc ue(1), 4:2:0
1315- "1", // bit_depth_luma_minus8 ue(0)
1316- "1", // bit_depth_chroma_minus8 ue(0)
1317- "0", // qpprime_y_zero_transform_bypass_flag
1318- "1", // seq_scaling_matrix_present_flag
1319- "1", // ...list 0 present
1320- "000010001", // its first delta, se(-8): nextScale hits 0, so the
1321- // remaining 15 coefficients are the default ones and cost no bits
1322- "0000000", // lists 1..7 absent
1323- "1", // log2_max_frame_num_minus4 ue(0)
1324- "1", // pic_order_cnt_type ue(0)
1325- "1", // log2_max_pic_order_cnt_lsb_minus4 ue(0)
1326- "010", // max_num_ref_frames ue(1)
1327- "0", // gaps_in_frame_num_value_allowed_flag
1328- "00000101000", // pic_width_in_mbs_minus1 ue(39), i.e. 640
1329- "000011110", // pic_height_in_map_units_minus1 ue(29), i.e. 480
1330- "1", // frame_mbs_only_flag
1331- "1", // direct_8x8_inference_flag
1332- "0", // frame_cropping_flag
1333- "1", // vui_parameters_present_flag
1334- "0", // aspect_ratio_info_present_flag
1335- "0", // overscan_info_present_flag
1336- "1", // video_signal_type_present_flag
1337- "101", // video_format (unspecified)
1338- "0", // video_full_range_flag
1339- "1", // colour_description_present_flag
1340- "00000001", // colour_primaries 1
1341- "00000001", // transfer_characteristics 1
1342- "00000001", // matrix_coefficients 1 (BT.709)
1343- );
1344- let want = Tags {
1345- matrix: Some(Matrix::Bt709),
1346- transfer: Some(Transfer::Sdr),
1347- full_range: Some(false),
1348- };
1349- assert_eq!(h264_sps(&bits_of(sps)), want);
1350- // ...and through the entry point a demuxer calls, Annex-B framed.
1351- let mut annex_b = vec![0, 0, 0, 1, 0x67];
1352- annex_b.extend_from_slice(&bits_of(sps));
1353- assert_eq!(bitstream_tags(CodecId::H264, &annex_b), want);
1354- // A codec whose colour is not out of band answers nothing at all.
1355- assert_eq!(bitstream_tags(CodecId::Vp9, &annex_b), Tags::default());
1356- assert_eq!(bitstream_tags(CodecId::Aac, &annex_b), Tags::default());
1357- }
1358-
1359- /// The HEVC twin of the test above, and hand-built for the same reason:
1360- /// x265 writes `sps_scaling_list_data_present_flag` only for a *custom*
1361- /// list. Custom lists are not exotic — they are what a psy-tuned anime
1362- /// encode ships — so the branch that counts them has to be measured.
1363- #[test]
1364- fn hevc_scaling_list_data_is_skipped_before_the_vui() {
1365- let mut sps = String::new();
1366- sps.push_str("0000"); // sps_video_parameter_set_id
1367- sps.push_str("000"); // sps_max_sub_layers_minus1: one layer
1368- sps.push('0'); // sps_temporal_id_nesting_flag
1369- sps.push_str(&"0".repeat(96)); // profile_tier_level, general only
1370- sps.push('1'); // sps_seq_parameter_set_id ue(0)
1371- sps.push_str("010"); // chroma_format_idc ue(1), 4:2:0
1372- sps.push_str("0000000001010000001"); // pic_width_in_luma_samples ue(640)
1373- sps.push_str("00000000111100001"); // pic_height_in_luma_samples ue(480)
1374- sps.push('0'); // conformance_window_flag
1375- sps.push_str("11"); // bit_depth_luma/chroma_minus8 ue(0)
1376- sps.push_str("00101"); // log2_max_pic_order_cnt_lsb_minus4 ue(4)
1377- sps.push('1'); // sps_sub_layer_ordering_info_present_flag
1378- sps.push_str("111"); // ...its three ue(0)s, for the one layer
1379- sps.push_str("111111"); // the six coding/transform-block ue(0)s
1380- sps.push_str("11"); // scaling_list_enabled + sps_scaling_list_data_present
1381- // scaling_list_data: the first 4x4 matrix written out (16 se(0) deltas,
1382- // no DC coefficient at this size), every other matrix predicted from an
1383- // earlier one -- 6+6+6+2 matrices in all.
1384- sps.push('1');
1385- sps.push_str(&"1".repeat(16));
1386- sps.push_str(&"01".repeat(5 + 6 + 6 + 2));
1387- sps.push_str("000"); // amp, sample_adaptive_offset, pcm_enabled
1388- sps.push('1'); // num_short_term_ref_pic_sets ue(0)
1389- sps.push('0'); // long_term_ref_pics_present_flag
1390- sps.push_str("00"); // sps_temporal_mvp, strong_intra_smoothing
1391- sps.push('1'); // vui_parameters_present_flag
1392- sps.push_str("00"); // aspect_ratio_info_present, overscan_info_present
1393- sps.push('1'); // video_signal_type_present_flag
1394- sps.push_str("101"); // video_format (unspecified)
1395- sps.push('0'); // video_full_range_flag
1396- sps.push('1'); // colour_description_present_flag
1397- sps.push_str("000000010000000100000001"); // primaries/transfer/matrix 1
1398- let want = Tags {
1399- matrix: Some(Matrix::Bt709),
1400- transfer: Some(Transfer::Sdr),
1401- full_range: Some(false),
1402- };
1403- assert_eq!(hevc_sps(&bits_of(&sps)), want);
1404- let mut annex_b = vec![0, 0, 0, 1, 33 << 1, 1];
1405- annex_b.extend_from_slice(&bits_of(&sps));
1406- assert_eq!(bitstream_tags(CodecId::H265, &annex_b), want);
1407- }
1408-
1409- /// An AV1 sequence header OBU, `reduced_still_picture_header` — the one path
1410- /// whose length does not depend on an operating-point loop — carrying the
1411- /// HDR10 triplet its `color_config` writes.
1412- #[test]
1413- fn av1_sequence_header_reads_its_color_config() {
1414- let header = concat!(
1415- "000", // seq_profile 0
1416- "0", // still_picture
1417- "1", // reduced_still_picture_header
1418- "00000", // seq_level_idx[0]
1419- "0011", // frame_width_bits_minus_1: 4 bits of width
1420- "0011", // frame_height_bits_minus_1: 4 bits of height
1421- "00000000", // max_frame_width/height_minus_1
1422- "000", // use_128x128_superblock, filter_intra, intra_edge_filter
1423- "000", // enable_superres, enable_cdef, enable_restoration
1424- "0", // high_bitdepth
1425- "0", // mono_chrome
1426- "1", // color_description_present_flag
1427- "00001001", // colour_primaries 9
1428- "00010000", // transfer_characteristics 16 (PQ)
1429- "00001001", // matrix_coefficients 9 (BT.2020 NCL)
1430- "0", // color_range: limited
1431- );
1432- // obu_type 1 (sequence header), no extension, no size field.
1433- let mut obu = vec![1 << 3];
1434- obu.extend_from_slice(&bits_of(header));
1435- assert_eq!(
1436- bitstream_tags(CodecId::Av1, &obu),
1437- Tags {
1438- matrix: Some(Matrix::Bt2020Ncl),
1439- transfer: Some(Transfer::Pq),
1440- full_range: Some(false),
1441- }
1442- );
1443- // A truncated header is no answer rather than a wrong one.
1444- assert_eq!(bitstream_tags(CodecId::Av1, &obu[..3]), Tags::default());
1445- }
1446-
1447691 /// The rule an encode declares itself by, and the reason it is the *same*
1448692 /// rule the heuristic reads: a file written here says out loud what a reader
1449693 /// with no tags would have assumed anyway.
crates/ec-core/src/frame.rsmodified+0 -20
@@ -58,20 +58,6 @@ impl PixelFormat {
5858 }
5959 }
6060
61- /// True when chroma lives in its own plane(s) rather than packed with luma.
62- pub fn is_planar(&self) -> bool {
63- self.plane_count() > 1
64- }
65-
66- /// True for the YUV families (planar and semi-planar).
67- pub fn is_yuv(&self) -> bool {
68- use PixelFormat::*;
69- matches!(
70- self,
71- I420 | I422 | I444 | I010 | I210 | I410 | I412 | Nv12 | Nv21 | P010 | P016
72- )
73- }
74-
7561 /// True when the format carries an alpha channel.
7662 pub fn has_alpha(&self) -> bool {
7763 matches!(self, PixelFormat::Rgba8 | PixelFormat::Bgra8)
@@ -311,11 +297,6 @@ impl SampleFormat {
311297 SampleFormat::F64 => 8,
312298 }
313299 }
314-
315- /// True for the float formats.
316- pub fn is_float(&self) -> bool {
317- matches!(self, SampleFormat::F32 | SampleFormat::F64)
318- }
319300 }
320301
321302 /// A named speaker position.
@@ -526,7 +507,6 @@ mod tests {
526507 assert_eq!(PixelFormat::P010.bytes_per_component(), 2);
527508 assert!(PixelFormat::Bgra8.has_alpha());
528509 assert!(!PixelFormat::Nv12.has_alpha());
529- assert!(PixelFormat::Nv12.is_yuv());
530510 }
531511
532512 #[test]
crates/ec-core/src/lib.rsmodified+1 -4
@@ -33,10 +33,7 @@ pub mod registry;
3333 pub mod timebase;
3434
3535 pub use bitio::{BitReader, BitReaderLsb, BitWriter, BitWriterLsb};
36-pub use color::{
37- ColorDescription, ContentLight, MasteringPrimaries, Matrix, Primaries, Tags, Transfer, bitstream_tags,
38- hevc_sei_light,
39-};
36+pub use color::{ColorDescription, ContentLight, MasteringPrimaries, Matrix, Primaries, Tags, Transfer, hevc_sei_light};
4037 pub use error::{Error, Result};
4138 pub use frame::{
4239 AudioFrame, ChannelLayout, ChannelPosition, ColorInfo, Frame, Interlace, PixelFormat, Plane, SampleFormat,
crates/ec-core/src/registry.rsmodified+1 -103
@@ -341,40 +341,6 @@ pub enum Rotation {
341341 }
342342
343343 impl Rotation {
344- /// The rotation an ISO-BMFF `tkhd` display matrix states, from its linear
345- /// 2x2 part read as 16.16 fixed-point `i32`s.
346- ///
347- /// The matrix transforms a point `(x, y)` to `(a*x + c*y, b*x + d*y)`, so
348- /// the columns `(a, b)` and `(c, d)` are the turned axes: a pure rotation
349- /// has both columns the same length (isotropic) and one the other's quarter
350- /// turn (`a == d`, `b == -c`). Anything else is [`Rotation::Other`].
351- ///
352- /// The reading is exact integer arithmetic: the four quarter turns are
353- /// recognised by an axis landing on an axis (`b == 0` or `a == 0`). An
354- /// encoder writes 16.16 quarter turns exactly, so a value within a fraction
355- /// of a degree of one that is not exactly one -- a hand-edited or rescaled
356- /// matrix -- reads as [`Rotation::Other`] rather than being rounded onto a
357- /// turn this decoder would then apply for real.
358- pub fn from_matrix(a: i32, b: i32, c: i32, d: i32) -> Rotation {
359- // A pure rotation: isotropic (a == d, b == -c) with something to turn.
360- // `c.checked_neg()` rather than `-c`: a crafted `tkhd` can carry
361- // `i32::MIN`, whose negation is not representable -- the plain form
362- // panics in a debug build and wraps onto a false quarter turn in a
363- // release one. `checked_neg` is `None` there, so the term falls through
364- // to `Other` below, which is the right reading for it anyway.
365- if a == d && c.checked_neg() == Some(b) && (a != 0 || b != 0) {
366- // `(a, b)` is the turned x-axis; a quarter turn lands it on an axis.
367- return match (a.signum(), b.signum()) {
368- (1, 0) => Rotation::None,
369- (-1, 0) => Rotation::Cw180,
370- (0, 1) => Rotation::Cw90,
371- (0, -1) => Rotation::Cw270,
372- _ => Rotation::Other { a, b, c, d },
373- };
374- }
375- Rotation::Other { a, b, c, d }
376- }
377-
378344 /// Quarter turns clockwise, where the stream is a quarter turn at all --
379345 /// `None` for anything [`Rotation::Other`] carries.
380346 pub fn steps(self) -> Option<u8> {
@@ -665,24 +631,7 @@ mod tests {
665631 }
666632
667633 #[test]
668- fn quarter_turn_matrices_read_as_typed_rotations() {
669- const ONE: i32 = 65_536; // 16.16 unity.
670- let cases = [
671- // A tkhd matrix and the turn it states, in this crate's clockwise
672- // convention. `(0, -1, 1, 0)` is what ffmpeg's
673- // `-display_rotation 90` writes: it asks the picture to be turned
674- // a quarter counter-clockwise here, which is Cw270.
675- ((ONE, 0, 0, ONE), Rotation::None),
676- ((0, -ONE, ONE, 0), Rotation::Cw270),
677- ((-ONE, 0, 0, -ONE), Rotation::Cw180),
678- ((0, ONE, -ONE, 0), Rotation::Cw90),
679- // A scaled identity is still no turn: the reading normalises by the
680- // matrix's own scale, so a differently-scaled copy reads the same.
681- ((2 * ONE, 0, 0, 2 * ONE), Rotation::None),
682- ];
683- for ((a, b, c, d), want) in cases {
684- assert_eq!(Rotation::from_matrix(a, b, c, d), want, "{a} {b} {c} {d}");
685- }
634+ fn quarter_turn_steps_and_axes() {
686635 assert_eq!(Rotation::None.steps(), Some(0));
687636 assert_eq!(Rotation::Cw90.steps(), Some(1));
688637 assert_eq!(Rotation::Cw180.steps(), Some(2));
@@ -692,57 +641,6 @@ mod tests {
692641 assert!(Rotation::None.is_none());
693642 }
694643
695- #[test]
696- fn a_matrix_that_is_not_a_quarter_turn_is_kept_not_rounded() {
697- const ONE: i32 = 65_536;
698- // A 45-degree turn: isotropic and pure, but no axis lands on an axis.
699- assert_eq!(
700- Rotation::from_matrix(46_340, -46_340, 46_340, 46_340),
701- Rotation::Other {
702- a: 46_340,
703- b: -46_340,
704- c: 46_340,
705- d: 46_340,
706- }
707- );
708- // A mirror (negative determinant), a mirror of a quarter turn (b != -c),
709- // a shear (a != d), and the degenerate all-zero matrix: none is a turn.
710- for (a, b, c, d) in [
711- (ONE, 0, 0, -ONE),
712- (0, ONE, ONE, 0),
713- (ONE, 0, ONE, ONE),
714- (0, 0, 0, 0),
715- ] {
716- let got = Rotation::from_matrix(a, b, c, d);
717- assert!(
718- matches!(got, Rotation::Other { .. }),
719- "{a} {b} {c} {d} read as {got:?}"
720- );
721- assert_eq!(got.steps(), None, "Other is not a quarter count");
722- }
723- }
724-
725- #[test]
726- fn a_matrix_term_at_i32_min_is_not_a_quarter_turn() {
727- // A crafted `tkhd` can carry `i32::MIN`, whose negation is not
728- // representable. `from_matrix` must not panic (debug) or wrap onto a
729- // false turn (release) deciding `b == -c`, and such a term is no
730- // quarter turn anyway. `(0, MIN, MIN, 0)` is the load-bearing case: the
731- // wrapping form would read it as `Cw270`.
732- for (a, b, c, d) in [
733- (0, i32::MIN, i32::MIN, 0),
734- (65_536, i32::MIN, i32::MIN, 65_536),
735- (i32::MIN, 0, i32::MIN, i32::MIN),
736- ] {
737- let got = Rotation::from_matrix(a, b, c, d);
738- assert!(
739- matches!(got, Rotation::Other { .. }),
740- "{a} {b} {c} {d} read as {got:?}"
741- );
742- assert_eq!(got.steps(), None, "Other is not a quarter count");
743- }
744- }
745-
746644 #[test]
747645 fn trait_objects_are_send() {
748646 fn assert_send<T: Send + ?Sized>() {}
crates/ec-core/src/timebase.rsmodified+0 -15
@@ -198,19 +198,6 @@ impl Timestamp {
198198 .map(|t| Timestamp::new(t, base))
199199 }
200200
201- /// Advance by `ticks` of this timestamp's own base.
202- pub fn checked_add_ticks(&self, ticks: i64) -> Option<Timestamp> {
203- self.ticks
204- .checked_add(ticks)
205- .map(|t| Timestamp::new(t, self.base))
206- }
207-
208- /// `self - other`, in this timestamp's base, exact.
209- pub fn checked_diff(&self, other: Timestamp) -> Option<i64> {
210- let o = other.checked_rescale(self.base, Rounding::Nearest)?;
211- self.ticks.checked_sub(o.ticks)
212- }
213-
214201 /// Seconds as a float. Display only.
215202 pub fn as_secs_f64(&self) -> f64 {
216203 self.ticks as f64 * self.base.as_secs_f64()
@@ -341,8 +328,6 @@ mod tests {
341328 let a = Timestamp::new(90_000, TimeBase::MPEG_TS); // 1 s
342329 let b = Timestamp::new(1_000, TimeBase::MILLIS); // 1 s
343330 assert_eq!(a, b);
344- assert_eq!(a.checked_diff(b), Some(0));
345- assert_eq!(a.checked_add_ticks(90_000).unwrap().ticks, 180_000);
346331 assert_eq!(a.rescale(TimeBase::MILLIS, Rounding::Nearest).ticks, 1_000);
347332 assert!(Timestamp::new(0, TimeBase::MILLIS) < a);
348333 }
crates/ec-dsp/Cargo.tomlmodified+0 -2
@@ -7,6 +7,4 @@ license.workspace = true
77 authors.workspace = true
88
99 [dependencies]
10-# For the colour matrices `remap` converts between; no other IR is used here.
11-ec-core.workspace = true
1210 wide.workspace = true
crates/ec-dsp/src/lib.rsmodified+1 -7
@@ -26,16 +26,12 @@
2626 //! codec convention (`2/N` on the inverse) and reconstructs exactly under
2727 //! overlap-add with any Princen-Bradley window from [`window`].
2828 //!
29-//! [`remap`] sits beside them for the same reason: it is the pixel arithmetic an
30-//! encode does when a clip's YUV matrix is not the one the output declares, and
31-//! it belongs with the transforms rather than in a container crate.
32-//!
3329 //! Hot loops are vectorised with the `wide` crate through [`Real`]; the scalar
3430 //! and SIMD paths are the same expressions over the same data layout, so
3531 //! neither can drift from the other in correctness.
3632 //!
3733 //! No unsafe, no allocation on the transform path, and no dependencies beyond
38-//! `wide` and the family IR.
34+//! `wide`.
3935
4036 #![forbid(unsafe_code)]
4137 #![warn(missing_docs)]
@@ -43,14 +39,12 @@
4339 pub mod dct;
4440 pub mod fft;
4541 pub mod mdct;
46-pub mod remap;
4742 pub mod rgb;
4843 pub mod window;
4944
5045 pub use dct::{Dct, Dct4};
5146 pub use fft::{Complex, Fft, RealFft};
5247 pub use mdct::Mdct;
53-pub use remap::remap;
5448 pub use window::Window;
5549
5650 use core::fmt::Debug;
crates/ec-dsp/src/mdct.rsmodified+4 -0
@@ -173,6 +173,10 @@ impl<T: Real> Mdct<T> {
173173 }
174174 }
175175
176+}
177+
178+#[cfg(test)]
179+impl<T: Real> Mdct<T> {
176180 /// Runs three overlapped frames of pseudo-random audio through
177181 /// analysis and synthesis with `window` and returns the worst absolute
178182 /// reconstruction error in the fully overlapped region.
crates/ec-dsp/src/remap.rsdeleted+0 -177
@@ -1,177 +0,0 @@
1-//! Rewriting samples coded against one YUV matrix as the same picture coded
2-//! against another — the one colour operation an encode performs when a clip's
3-//! space is not the space the file being written declares.
4-
5-use ec_core::color::Matrix;
6-
7-/// Rewrites planar 4:2:0 samples coded against `from` as the same picture coded
8-/// against `to`, in place. Both spaces here are limited range with the same
9-/// primaries, so this is the matrix and nothing else: no gamut mapping, no range
10-/// scaling, and the 16/128/128 of black lands on itself either way — which is
11-/// what makes a letterboxed bar and a gap's black frame cost nothing.
12-///
13-/// Derived from the two matrices, not tabulated: with R,G,B eliminated between
14-/// them, luma picks up a chroma term and the two chroma planes mix only with
15-/// each other — so chroma never needs the luma plane and is remapped at its own
16-/// resolution, while luma reads the co-sited chroma sample. 8.8 fixed point.
17-///
18-/// A no-op when the two spaces are the same, so the caller may hand any pair;
19-/// BT.2020 is never a target here — an HDR source goes through a tone map, not
20-/// through this.
21-pub fn remap(from: Matrix, to: Matrix, y: &mut [u8], u: &mut [u8], v: &mut [u8], width: usize) {
22- // On normalised samples the two rows are Y' = Y - 0.1182 Cb - 0.2127 Cr,
23- // Cb' = 1.0185 Cb + 0.1146 Cr, Cr' = 0.0751 Cb + 1.0251 Cr; in *code* values
24- // the luma row's chroma terms carry a further 219/224, the ratio of the two
25- // limited-range spans, while the chroma rows' do not (both sides are
26- // chroma). That is the whole difference between these numbers and the
27- // published ones.
28- let coeffs = match (from, to) {
29- (Matrix::Bt601, Matrix::Bt709) => [-30, -53, 261, 29, 19, 262],
30- // ...and its inverse, which round-trips to within a code.
31- (Matrix::Bt709, Matrix::Bt601) => [25, 49, 253, -28, -19, 252],
32- _ => return,
33- };
34- let [yb, yr, ub, ur, vb, vr] = coeffs;
35- let cw = width.div_ceil(2);
36- for (i, y) in y.iter_mut().enumerate() {
37- let (row, col) = (i / width, i % width);
38- let ci = (row / 2) * cw + col / 2;
39- let (d, e) = (u[ci] as i32 - 128, v[ci] as i32 - 128);
40- *y = (*y as i32 + ((yb * d + yr * e + 128) >> 8)).clamp(0, 255) as u8;
41- }
42- for (u, v) in u.iter_mut().zip(v) {
43- let (d, e) = (*u as i32 - 128, *v as i32 - 128);
44- *u = (128 + ((ub * d + ur * e + 128) >> 8)).clamp(0, 255) as u8;
45- *v = (128 + ((vb * d + vr * e + 128) >> 8)).clamp(0, 255) as u8;
46- }
47-}
48-
49-#[cfg(test)]
50-mod tests {
51- use super::*;
52-
53- /// The published luma weights (kr, kb) of each matrix — the numbers the
54- /// fixed-point coefficients above are derived from.
55- fn weights(matrix: Matrix) -> (f64, f64) {
56- match matrix {
57- Matrix::Bt601 => (0.299, 0.114),
58- Matrix::Bt709 => (0.2126, 0.0722),
59- Matrix::Bt2020Ncl => (0.2627, 0.0593),
60- }
61- }
62-
63- /// Limited-range 4:2:0 samples for one colour, in `matrix`, the float way —
64- /// what a correct encoder would have written.
65- fn encode(matrix: Matrix, rgb: [f64; 3]) -> (u8, u8, u8) {
66- let (kr, kb) = weights(matrix);
67- let [r, g, b] = rgb.map(|c| c / 255.0);
68- let luma = kr * r + (1.0 - kr - kb) * g + kb * b;
69- let round = |x: f64| x.round().clamp(0.0, 255.0) as u8;
70- (
71- round(16.0 + 219.0 * luma),
72- round(128.0 + 224.0 * 0.5 * (b - luma) / (1.0 - kb)),
73- round(128.0 + 224.0 * 0.5 * (r - luma) / (1.0 - kr)),
74- )
75- }
76-
77- /// ...and back out of `matrix`, unrounded, which is what a player shows.
78- fn decode(matrix: Matrix, (y, u, v): (u8, u8, u8)) -> [f64; 3] {
79- let (kr, kb) = weights(matrix);
80- let luma = (f64::from(y) - 16.0) / 219.0;
81- let cb = (f64::from(u) - 128.0) / 224.0;
82- let cr = (f64::from(v) - 128.0) / 224.0;
83- let r = luma + 2.0 * (1.0 - kr) * cr;
84- let b = luma + 2.0 * (1.0 - kb) * cb;
85- let g = (luma - kr * r - kb * b) / (1.0 - kr - kb);
86- [r, g, b].map(|c| c * 255.0)
87- }
88-
89- /// One colour as a 2x2 picture — four luma samples over one chroma pair, the
90- /// smallest thing [`remap`] indexes the way it indexes a frame.
91- fn tile((y, u, v): (u8, u8, u8)) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
92- (vec![y; 4], vec![u], vec![v])
93- }
94-
95- /// The claim the whole reconcile rests on: samples coded against one matrix,
96- /// remapped, and then *decoded by the other matrix* are the colour that went
97- /// in — not a second conversion of it. Within a code or two, which is what
98- /// 8-bit 8.8 fixed point can promise.
99- #[test]
100- fn a_remap_is_the_same_colour_read_by_the_other_matrix() {
101- let colours = [
102- [255.0, 0.0, 0.0],
103- [0.0, 255.0, 0.0],
104- [0.0, 0.0, 255.0],
105- [255.0, 255.0, 0.0],
106- [18.0, 200.0, 140.0],
107- [128.0, 128.0, 128.0],
108- [235.0, 210.0, 30.0],
109- ];
110- for (from, to) in [
111- (Matrix::Bt601, Matrix::Bt709),
112- (Matrix::Bt709, Matrix::Bt601),
113- ] {
114- for rgb in colours {
115- let (mut y, mut u, mut v) = tile(encode(from, rgb));
116- remap(from, to, &mut y, &mut u, &mut v, 2);
117- let out = decode(to, (y[0], u[0], v[0]));
118- for (want, got) in rgb.iter().zip(&out) {
119- assert!(
120- (want - got).abs() <= 2.0,
121- "{from:?}->{to:?} {rgb:?} came out {out:?}"
122- );
123- }
124- }
125- }
126- }
127-
128- /// Black, white and neutral grey are the same samples in both matrices, and
129- /// a remap has to leave them alone: those are the letterbox bars, the gap
130- /// frames and every grey in the picture, and a shift there is visible as a
131- /// tint on nothing at all.
132- #[test]
133- fn a_remap_leaves_the_greys_where_they_are() {
134- for (from, to) in [
135- (Matrix::Bt601, Matrix::Bt709),
136- (Matrix::Bt709, Matrix::Bt601),
137- ] {
138- for luma in [16u8, 128, 235] {
139- let (mut y, mut u, mut v) = tile((luma, 128, 128));
140- remap(from, to, &mut y, &mut u, &mut v, 2);
141- assert_eq!((y[0], u[0], v[0]), (luma, 128, 128), "{from:?}->{to:?}");
142- }
143- }
144- }
145-
146- /// The zero-cost path, asserted where it is decided: a clip already in the
147- /// file's own space comes out byte for byte the samples it went in as, so an
148- /// ordinary single-space project is not touched by any of this.
149- #[test]
150- fn a_same_space_remap_touches_nothing() {
151- let mut y: Vec<u8> = (0..64 * 48).map(|i| (i % 256) as u8).collect();
152- let mut u: Vec<u8> = (0..32 * 24).map(|i| (i % 256) as u8).collect();
153- let mut v: Vec<u8> = (0..32 * 24).map(|i| (255 - i % 256) as u8).collect();
154- let (before_y, before_u, before_v) = (y.clone(), u.clone(), v.clone());
155- for matrix in [Matrix::Bt601, Matrix::Bt709, Matrix::Bt2020Ncl] {
156- remap(matrix, matrix, &mut y, &mut u, &mut v, 64);
157- }
158- assert_eq!((y, u, v), (before_y, before_u, before_v));
159- }
160-
161- /// There and back is the picture again: the two directions are one matrix
162- /// and its inverse, not two independent approximations.
163- #[test]
164- fn a_remap_round_trips_within_a_code() {
165- let y: Vec<u8> = (0..64 * 48).map(|i| (16 + i % 220) as u8).collect();
166- let u: Vec<u8> = (0..32 * 24).map(|i| (16 + i % 225) as u8).collect();
167- let v: Vec<u8> = (0..32 * 24).map(|i| (240 - i % 225) as u8).collect();
168- let (mut ry, mut ru, mut rv) = (y.clone(), u.clone(), v.clone());
169- remap(Matrix::Bt601, Matrix::Bt709, &mut ry, &mut ru, &mut rv, 64);
170- remap(Matrix::Bt709, Matrix::Bt601, &mut ry, &mut ru, &mut rv, 64);
171- let worst =
172- |a: &[u8], b: &[u8]| a.iter().zip(b).map(|(x, y)| x.abs_diff(*y)).max().unwrap();
173- assert!(worst(&y, &ry) <= 2, "luma drifted by {}", worst(&y, &ry));
174- assert!(worst(&u, &ru) <= 2, "cb drifted by {}", worst(&u, &ru));
175- assert!(worst(&v, &rv) <= 2, "cr drifted by {}", worst(&v, &rv));
176- }
177-}
crates/ec-dsp/src/window.rsmodified+16 -12
@@ -148,18 +148,6 @@ impl<T: Real> Window<T> {
148148 }
149149 }
150150
151- /// Worst deviation from the Princen-Bradley condition
152- /// `w[n]^2 + w[n + len/2]^2 == 1`, the property MDCT overlap-add needs.
153- pub fn princen_bradley_error(&self) -> f64 {
154- let half = self.samples.len() / 2;
155- (0..half)
156- .map(|n| {
157- let a = self.samples[n].to_f64();
158- let b = self.samples[n + half].to_f64();
159- (a * a + b * b - 1.0).abs()
160- })
161- .fold(0.0, f64::max)
162- }
163151 }
164152
165153 /// Modified Bessel function of the first kind, order zero, by its power
@@ -181,6 +169,22 @@ fn bessel_i0(x: f64) -> f64 {
181169 sum
182170 }
183171
172+#[cfg(test)]
173+impl<T: Real> Window<T> {
174+ /// Worst deviation from the Princen-Bradley condition
175+ /// `w[n]^2 + w[n + len/2]^2 == 1`, the property MDCT overlap-add needs.
176+ pub fn princen_bradley_error(&self) -> f64 {
177+ let half = self.samples.len() / 2;
178+ (0..half)
179+ .map(|n| {
180+ let a = self.samples[n].to_f64();
181+ let b = self.samples[n + half].to_f64();
182+ (a * a + b * b - 1.0).abs()
183+ })
184+ .fold(0.0, f64::max)
185+ }
186+}
187+
184188 #[cfg(test)]
185189 mod tests {
186190 use super::*;