diff --git a/crates/ec-av1/src/cdf.rs b/crates/ec-av1/src/cdf.rs new file mode 100644 index 00000000..6da8d8ca --- /dev/null +++ b/crates/ec-av1/src/cdf.rs @@ -0,0 +1,198 @@ +//! The default CDF tables of spec section 9.4, in the orientation +//! [`crate::msac`] reads: cumulative probabilities scaled to `1 << 15`, with +//! the alphabet's total as the second-to-last entry and the adaptation counter +//! last. +//! +//! Only the syntax elements the tile writer codes today are here; the rest +//! arrive with the syntax that needs them. + +/// `Default_Partition_W64_Cdf` (spec 9.4): the ten partition types of a +/// 64x64 block, indexed by the context the blocks above and left give. +pub const PARTITION_W64: [[u16; 11]; 4] = [ + [ + 20137, 21547, 23078, 29566, 29837, 30261, 30524, 30892, 31724, 32768, 0, + ], + [ + 6732, 7490, 9497, 27944, 28250, 28515, 28969, 29630, 30104, 32768, 0, + ], + [ + 5945, 7663, 8348, 28683, 29117, 29749, 30064, 30298, 32238, 32768, 0, + ], + [ + 870, 1212, 1487, 31198, 31394, 31574, 31743, 31881, 32332, 32768, 0, + ], +]; + +/// `Default_Skip_Cdf` (spec 9.4): indexed by how many of the blocks above +/// and left were skipped. +pub const SKIP: [[u16; 3]; 3] = [[31671, 32768, 0], [16515, 32768, 0], [4576, 32768, 0]]; + +/// `Default_Intra_Frame_Y_Mode_Cdf` (spec 9.4): the thirteen luma intra +/// modes of a key frame, indexed by the mode context of the block above and +/// then of the block to the left. +pub const KF_Y_MODE: [[[u16; 14]; 5]; 5] = [ + [ + [ + 15588, 17027, 19338, 20218, 20682, 21110, 21825, 23244, 24189, 28165, 29093, 30466, + 32768, 0, + ], + [ + 12016, 18066, 19516, 20303, 20719, 21444, 21888, 23032, 24434, 28658, 30172, 31409, + 32768, 0, + ], + [ + 10052, 10771, 22296, 22788, 23055, 23239, 24133, 25620, 26160, 29336, 29929, 31567, + 32768, 0, + ], + [ + 14091, 15406, 16442, 18808, 19136, 19546, 19998, 22096, 24746, 29585, 30958, 32462, + 32768, 0, + ], + [ + 12122, 13265, 15603, 16501, 18609, 20033, 22391, 25583, 26437, 30261, 31073, 32475, + 32768, 0, + ], + ], + [ + [ + 10023, 19585, 20848, 21440, 21832, 22760, 23089, 24023, 25381, 29014, 30482, 31436, + 32768, 0, + ], + [ + 5983, 24099, 24560, 24886, 25066, 25795, 25913, 26423, 27610, 29905, 31276, 31794, + 32768, 0, + ], + [ + 7444, 12781, 20177, 20728, 21077, 21607, 22170, 23405, 24469, 27915, 29090, 30492, + 32768, 0, + ], + [ + 8537, 14689, 15432, 17087, 17408, 18172, 18408, 19825, 24649, 29153, 31096, 32210, + 32768, 0, + ], + [ + 7543, 14231, 15496, 16195, 17905, 20717, 21984, 24516, 26001, 29675, 30981, 31994, + 32768, 0, + ], + ], + [ + [ + 12613, 13591, 21383, 22004, 22312, 22577, 23401, 25055, 25729, 29538, 30305, 32077, + 32768, 0, + ], + [ + 9687, 13470, 18506, 19230, 19604, 20147, 20695, 22062, 23219, 27743, 29211, 30907, + 32768, 0, + ], + [ + 6183, 6505, 26024, 26252, 26366, 26434, 27082, 28354, 28555, 30467, 30794, 32086, + 32768, 0, + ], + [ + 10718, 11734, 14954, 17224, 17565, 17924, 18561, 21523, 23878, 28975, 30287, 32252, + 32768, 0, + ], + [ + 9194, 9858, 16501, 17263, 18424, 19171, 21563, 25961, 26561, 30072, 30737, 32463, + 32768, 0, + ], + ], + [ + [ + 12602, 14399, 15488, 18381, 18778, 19315, 19724, 21419, 25060, 29696, 30917, 32409, + 32768, 0, + ], + [ + 8203, 13821, 14524, 17105, 17439, 18131, 18404, 19468, 25225, 29485, 31158, 32342, + 32768, 0, + ], + [ + 8451, 9731, 15004, 17643, 18012, 18425, 19070, 21538, 24605, 29118, 30078, 32018, + 32768, 0, + ], + [ + 7714, 9048, 9516, 16667, 16817, 16994, 17153, 18767, 26743, 30389, 31536, 32528, 32768, + 0, + ], + [ + 8843, 10280, 11496, 15317, 16652, 17943, 19108, 22718, 25769, 29953, 30983, 32485, + 32768, 0, + ], + ], + [ + [ + 12578, 13671, 15979, 16834, 19075, 20913, 22989, 25449, 26219, 30214, 31150, 32477, + 32768, 0, + ], + [ + 9563, 13626, 15080, 15892, 17756, 20863, 22207, 24236, 25380, 29653, 31143, 32277, + 32768, 0, + ], + [ + 8356, 8901, 17616, 18256, 19350, 20106, 22598, 25947, 26466, 29900, 30523, 32261, + 32768, 0, + ], + [ + 10835, 11815, 13124, 16042, 17018, 18039, 18947, 22753, 24615, 29489, 30883, 32482, + 32768, 0, + ], + [ + 7618, 8288, 9859, 10509, 15386, 18657, 22903, 28776, 29180, 31355, 31802, 32593, 32768, + 0, + ], + ], +]; + +/// `Default_Uv_Mode_Cdf` (spec 9.4) for blocks where chroma from luma is not +/// allowed: the thirteen chroma intra modes, indexed by the luma mode. +pub const UV_MODE_NO_CFL: [[u16; 14]; 13] = [ + [ + 22631, 24152, 25378, 25661, 25986, 26520, 27055, 27923, 28244, 30059, 30941, 31961, 32768, + 0, + ], + [ + 9513, 26881, 26973, 27046, 27118, 27664, 27739, 27824, 28359, 29505, 29800, 31796, 32768, 0, + ], + [ + 9845, 9915, 28663, 28704, 28757, 28780, 29198, 29822, 29854, 30764, 31777, 32029, 32768, 0, + ], + [ + 13639, 13897, 14171, 25331, 25606, 25727, 25953, 27148, 28577, 30612, 31355, 32493, 32768, + 0, + ], + [ + 9764, 9835, 9930, 9954, 25386, 27053, 27958, 28148, 28243, 31101, 31744, 32363, 32768, 0, + ], + [ + 11825, 13589, 13677, 13720, 15048, 29213, 29301, 29458, 29711, 31161, 31441, 32550, 32768, + 0, + ], + [ + 14175, 14399, 16608, 16821, 17718, 17775, 28551, 30200, 30245, 31837, 32342, 32667, 32768, + 0, + ], + [ + 12885, 13038, 14978, 15590, 15673, 15748, 16176, 29128, 29267, 30643, 31961, 32461, 32768, + 0, + ], + [ + 12026, 13661, 13874, 15305, 15490, 15726, 15995, 16273, 28443, 30388, 30767, 32416, 32768, + 0, + ], + [ + 19052, 19840, 20579, 20916, 21150, 21467, 21885, 22719, 23174, 28861, 30379, 32175, 32768, + 0, + ], + [ + 18627, 19649, 20974, 21219, 21492, 21816, 22199, 23119, 23527, 27053, 31397, 32148, 32768, + 0, + ], + [ + 17026, 19004, 19997, 20339, 20586, 21103, 21349, 21907, 22482, 25896, 26541, 31819, 32768, + 0, + ], + [ + 12124, 13759, 14959, 14992, 15007, 15051, 15078, 15166, 15255, 15753, 16039, 16606, 32768, + 0, + ], +]; diff --git a/crates/ec-av1/src/lib.rs b/crates/ec-av1/src/lib.rs index ac4284f0..25983b07 100644 --- a/crates/ec-av1/src/lib.rs +++ b/crates/ec-av1/src/lib.rs @@ -13,7 +13,9 @@ #![warn(missing_docs)] pub mod bits; +pub mod cdf; pub mod frame; pub mod msac; pub mod obu; pub mod sequence; +pub mod tile; diff --git a/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs new file mode 100644 index 00000000..3f9e5f2c --- /dev/null +++ b/crates/ec-av1/src/tile.rs @@ -0,0 +1,223 @@ +//! Tile payload writer (spec 5.11), for the one block coding the encoder can +//! produce today: a key frame whose every superblock is a single 64x64 +//! DC-predicted block with no residual. +//! +//! That frame decodes to a flat mid-grey picture — every sample is the value a +//! DC prediction with no neighbours produces — which is what makes it a usable +//! gate: any desync between this writer and a real decoder shows up as a +//! decode failure or a sample that is not mid-grey, with no metric in the way. +//! It is the skeleton the block modes, transform sizes and coefficients hang +//! off as they arrive. + +use ec_core::{Error, Result}; + +use crate::cdf; +use crate::msac::SymbolEncoder; + +/// `PARTITION_NONE` (spec 6.10.4): the whole block, undivided. +const PARTITION_NONE: usize = 0; +/// `DC_PRED` (spec 6.10.2), as both the luma and the chroma mode. +const DC_PRED: usize = 0; +/// Side of a superblock in 4x4 mode-info units when 128x128 superblocks are off. +const SB_MI: u32 = 16; + +/// Writes the payload of a one-tile key frame in which every superblock is a +/// skipped 64x64 DC-predicted block. +/// +/// `mi_cols` and `mi_rows` are the frame's dimensions in 4x4 mode-info units, +/// as the frame header carries them. +/// +/// # Errors +/// Returns an error when the frame is not a whole number of 64x64 superblocks: +/// a partial superblock forces the partition syntax down the block tree, which +/// this writer does not code yet. +pub fn flat_key_frame_tile(mi_cols: u32, mi_rows: u32) -> Result> { + if mi_cols == 0 + || mi_rows == 0 + || !mi_cols.is_multiple_of(SB_MI) + || !mi_rows.is_multiple_of(SB_MI) + { + return Err(Error::unsupported( + "AV1 tile", + "a flat key frame is written only for frames that are a whole \ + number of 64x64 superblocks", + )); + } + let (sb_cols, sb_rows) = (mi_cols / SB_MI, mi_rows / SB_MI); + + let mut enc = SymbolEncoder::new(); + for r in 0..sb_rows { + for c in 0..sb_cols { + // decode_partition (spec 5.11.4). Every neighbour is a 64x64 block, + // whose stored partition context has a zero bit at this block + // size, so the context is 0 wherever the block sits. + enc.symbol_fixed(PARTITION_NONE, &cdf::PARTITION_W64[0]); + + // intra_frame_mode_info (spec 5.11.16). Segmentation, delta q, + // delta lf, palette, filter intra and intrabc are all off in the + // frame header, and a skipped block codes no CDEF index, so the + // block is three symbols: the skip flag and the two modes. + let skip_ctx = usize::from(r > 0) + usize::from(c > 0); + enc.symbol_fixed(1, &cdf::SKIP[skip_ctx]); + // Both neighbours are DC-predicted, and an unavailable neighbour + // counts as DC too, so both mode contexts are 0. + enc.symbol_fixed(DC_PRED, &cdf::KF_Y_MODE[0][0]); + // Chroma from luma is only offered up to 32x32, so the CFL-free + // table is the one a 64x64 block reads. + enc.symbol_fixed(DC_PRED, &cdf::UV_MODE_NO_CFL[DC_PRED]); + + // read_block_tx_size codes nothing while the frame's tx_mode is + // TX_MODE_LARGEST, and a skipped block has no residual, so the + // block ends here. + } + } + Ok(enc.finish()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::frame::frame_obu; + use crate::obu::temporal_delimiter; + use crate::sequence::sequence_header_obu; + use ec_av1_syntax::sequence::SequenceHeader; + use ec_av1_syntax::{ + FrameHeader, FrameType, LoopFilterParams, PRIMARY_REF_NONE, QuantizationParams, TileInfo, + TxMode, + }; + use std::io::Write; + use std::process::{Command, Stdio}; + + /// A 64x64 sequence with every tool this writer does not code turned off: + /// 64x64 superblocks, no CDEF, no loop restoration, no superres, no filter + /// intra, and no screen content tools (which is what keeps intra block copy + /// and palette out of the block syntax). + fn sequence_64() -> SequenceHeader { + let mut seq = crate::sequence::tests::sample_1080p(); + seq.frame_width_bits = 7; + seq.frame_height_bits = 7; + seq.max_frame_width = 64; + seq.max_frame_height = 64; + seq.use_128x128_superblock = false; + seq.enable_filter_intra = false; + seq.enable_cdef = false; + seq.enable_restoration = false; + seq.enable_superres = false; + seq.seq_force_screen_content_tools = 0; + seq.seq_force_integer_mv = 0; + seq + } + + /// The key frame the tile above belongs to: one tile, quantised so nothing + /// is lossless, one transform size per block, no in-loop filtering, and no + /// CDF adaptation (the writer codes against the defaults). + fn flat_key_frame() -> FrameHeader { + FrameHeader { + frame_type: FrameType::Key, + frame_is_intra: true, + show_frame: true, + error_resilient_mode: true, + disable_cdf_update: true, + allow_screen_content_tools: false, + force_integer_mv: true, + refresh_frame_flags: 0xFF, + primary_ref_frame: PRIMARY_REF_NONE, + frame_width: 64, + frame_height: 64, + upscaled_width: 64, + render_width: 64, + render_height: 64, + mi_cols: 16, + mi_rows: 16, + tile_info: TileInfo { + uniform_spacing: true, + cols: 1, + rows: 1, + cols_log2: 0, + rows_log2: 0, + mi_col_starts: vec![0, 16], + mi_row_starts: vec![0, 16], + context_update_tile_id: 0, + tile_size_bytes: 1, + }, + quantization: QuantizationParams { + base_q_idx: 100, + ..QuantizationParams::default() + }, + loop_filter: LoopFilterParams::default(), + tx_mode: TxMode::Largest, + reduced_tx_set: false, + ..FrameHeader::default() + } + } + + fn have_ffmpeg() -> bool { + Command::new("ffmpeg") + .arg("-version") + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .is_ok_and(|s| s.success()) + } + + /// Decodes an AV1 OBU stream with ffmpeg and hands back the planes. + fn ffmpeg_decode(stream: &[u8], w: usize, h: usize) -> Vec { + let mut child = Command::new("ffmpeg") + .args([ + "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-", + ]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("ffmpeg failed to start"); + child + .stdin + .take() + .expect("ffmpeg stdin") + .write_all(stream) + .expect("writing the stream to ffmpeg"); + let out = child.wait_with_output().expect("ffmpeg failed to run"); + assert!( + out.status.success(), + "ffmpeg refused the stream: {}", + String::from_utf8_lossy(&out.stderr) + ); + assert_eq!( + out.stdout.len(), + w * h * 3 / 2, + "expected one 4:2:0 frame, ffmpeg said: {}", + String::from_utf8_lossy(&out.stderr) + ); + out.stdout + } + + #[test] + fn flat_key_frame_decodes_to_mid_grey() { + if !have_ffmpeg() { + eprintln!("SKIP flat_key_frame_decodes_to_mid_grey: no ffmpeg on PATH"); + return; + } + let seq = sequence_64(); + let header = flat_key_frame(); + let tile = flat_key_frame_tile(header.mi_cols, header.mi_rows).unwrap(); + + let mut stream = temporal_delimiter(); + stream.extend_from_slice(&sequence_header_obu(&seq).unwrap()); + stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap()); + + let planes = ffmpeg_decode(&stream, 64, 64); + // A DC prediction with no neighbour to average is the middle of the + // range, and a skipped block adds no residual, so every sample of every + // plane is 128 — one wrong symbol anywhere in the tile shows up here. + for (i, &s) in planes.iter().enumerate() { + assert_eq!(s, 128, "sample {i} of the decoded frame"); + } + } + + #[test] + fn partial_superblocks_are_refused() { + assert!(flat_key_frame_tile(16, 20).is_err()); + assert!(flat_key_frame_tile(0, 16).is_err()); + } +}