From 75d14f2ab2cb39686da722d6f7976ff11eab6af6 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 4 Nov 2026 22:49:27 +0000 Subject: [PATCH 01/11] build: sync Cargo.lock with the image-webp dev-dependency Cargo.lock omitted the dev-dependency image-webp (and its transitive byteorder-lite and quick-error). Without this, cargo build --locked fails in CI. The resolution is additive; no existing package version changed. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Ch6Crfubj3FwdxR7ywn9vT --- Cargo.lock | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index 0bfbbd9..8c25054 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,31 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + +[[package]] +name = "image-webp" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" +dependencies = [ + "byteorder-lite", + "quick-error", +] + +[[package]] +name = "quick-error" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" + [[package]] name = "transcode" version = "0.1.0" +dependencies = [ + "image-webp", +] From c7737bcd13243a144439fa95247d73bfc3c5629b Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 4 Nov 2026 22:53:19 +0000 Subject: [PATCH 02/11] build: crate metadata, MSRV 1.89, and a clippy lint policy - license = MIT (matches LICENSE-MIT; see the README licensing note) - repository, readme, description, keywords, categories - rust-version = 1.89, verified with cargo +1.89.0 build --all-targets - #![forbid(unsafe_code)] on the library crate (the crate has no unsafe) - [lints.clippy]: style, complexity and perf are allowed for now. The crate has about 380 findings there, mostly float-literal precision in DSP tables. Correctness and suspicious lints stay on, so cargo clippy -- -D warnings gates CI. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Ch6Crfubj3FwdxR7ywn9vT --- Cargo.toml | 17 +++++++++++++++++ src/lib.rs | 2 ++ 2 files changed, 19 insertions(+) diff --git a/Cargo.toml b/Cargo.toml index 950bcef..ba64fb1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,6 +7,13 @@ name = "transcode" version = "0.1.0" edition = "2021" +rust-version = "1.89" +license = "MIT" +description = "Pure-Rust, std-only audio, image and video codec crate. Decoders and encoders are from scratch; no ffmpeg, libpng, libjpeg or other C libraries." +repository = "https://github.com/webfold-ai/transcode" +readme = "README.md" +keywords = ["codec", "audio", "image", "video"] +categories = ["multimedia", "multimedia::audio", "multimedia::images", "multimedia::video"] [[bin]] name = "transcode" @@ -18,3 +25,13 @@ opt-level = 3 [dev-dependencies] # Independent WebP decoder, used only to verify the encoder's output in tests. image-webp = "0.2.4" + +[lints.clippy] +# Clippy style/complexity/perf findings are advisory, not blocking. The crate has about +# 380 of them today, mostly `excessive_precision` on DSP float tables and index-based +# loops that mirror the spec text. Fixing them by hand would edit numeric tables, so +# they are tracked as debt instead. Correctness and suspicious lints remain on and are +# denied by `cargo clippy -- -D warnings` in CI. +style = "allow" +complexity = "allow" +perf = "allow" diff --git a/src/lib.rs b/src/lib.rs index b661ec2..783dd2c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -3,6 +3,8 @@ //! → `(samples i32, rate, channels, bps)` for the STT audio front-end). The `transcode` //! binary (`main.rs`) keeps its own module tree; this just makes the codecs reusable. +#![forbid(unsafe_code)] + pub mod aac; pub mod aac_tables; pub mod av1_dct; From 5fa77f0f63dfbf1b3c65695cd8edc17a97ba44b4 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 4 Nov 2026 22:53:36 +0000 Subject: [PATCH 03/11] fix: debug-build overflow panics in AV1 bool decoding; clean up warnings The AV1 range-decoder bool/bit paths (av1_ec.rs) and coefficient context (av1_coef.rs) rely on 32-bit wrap-around: 'r - 2*v' and '(h - k)' are negative in the spec sense and wrap, and the wrapped value is multiplied by 0/1 or clamped with min(). Debug builds panicked with 'attempt to subtract with overflow', so cargo test failed on the two round-trip unit tests. The arithmetic is now spelled with wrapping_* ops. Release builds already wrapped, so their behaviour does not change. Warnings: - src/main.rs used to declare its own copy of the codec modules (mod aac; ...), so most library items looked unused in the binary. It now uses the library. - mp3::read_huffman is private (it was more visible than its Br argument type). - Dead idx store in mp3 Huffman section removed. - jpeg::ycbcr_to_rgb was unused and is removed. - opus.rs carries CELT scaffolding for the unfinished Opus decode path; it is marked #![allow(dead_code)] with a pointer to ROADMAP.md. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Ch6Crfubj3FwdxR7ywn9vT --- src/av1_coef.rs | 8 ++++---- src/av1_ec.rs | 8 ++++++-- src/jpeg.rs | 10 +--------- src/main.rs | 13 +++++-------- src/mp3.rs | 6 +++--- src/opus.rs | 4 ++++ 6 files changed, 23 insertions(+), 26 deletions(-) diff --git a/src/av1_coef.rs b/src/av1_coef.rs index 6a0f42d..7b09183 100644 --- a/src/av1_coef.rs +++ b/src/av1_coef.rs @@ -84,16 +84,16 @@ fn level_byte(tok: u32, is_hi: bool) -> u8 { /// Returns the token ∈ 3..=15. Symmetric (Enc emits hint's tokens, Dec decodes). fn code_hi_tok(c: &mut C, br: &mut [u16], hint: u32) -> u32 { let h = hint.min(15); - let t1 = c.symbol(br, 4, (h - 3).min(3) as usize) as u32; + let t1 = c.symbol(br, 4, h.wrapping_sub(3).min(3) as usize) as u32; let mut tok = 3 + t1; if t1 == 3 { - let t2 = c.symbol(br, 4, (h - 6).min(3) as usize) as u32; + let t2 = c.symbol(br, 4, h.wrapping_sub(6).min(3) as usize) as u32; tok = 6 + t2; if t2 == 3 { - let t3 = c.symbol(br, 4, (h - 9).min(3) as usize) as u32; + let t3 = c.symbol(br, 4, h.wrapping_sub(9).min(3) as usize) as u32; tok = 9 + t3; if t3 == 3 { - let t4 = c.symbol(br, 4, (h - 12).min(3) as usize) as u32; + let t4 = c.symbol(br, 4, h.wrapping_sub(12).min(3) as usize) as u32; tok = 12 + t4; } } diff --git a/src/av1_ec.rs b/src/av1_ec.rs index 2297b17..ef23367 100644 --- a/src/av1_ec.rs +++ b/src/av1_ec.rs @@ -297,7 +297,9 @@ impl<'a> Reader<'a> { let vw = (v as u64) << (EC_WIN_SIZE - 16); let ret = (dif >= vw) as u32; dif -= ret as u64 * vw; - v += ret * (r - 2 * v); + // dav1d relies on 32-bit wrap-around here (`r - 2*v` is negative when v > r/2 and + // ret is 0 or 1); spell the wrap out so debug builds match release. + v = v.wrapping_add(ret.wrapping_mul(r.wrapping_sub(v.wrapping_mul(2)))); self.norm(dif, v); ret == 0 } @@ -330,7 +332,9 @@ impl<'a> Reader<'a> { let vw = (v as u64) << (EC_WIN_SIZE - 16); let ret = (dif >= vw) as u32; dif -= ret as u64 * vw; - v += ret * (r - 2 * v); + // dav1d relies on 32-bit wrap-around here (`r - 2*v` is negative when v > r/2 and + // ret is 0 or 1); spell the wrap out so debug builds match release. + v = v.wrapping_add(ret.wrapping_mul(r.wrapping_sub(v.wrapping_mul(2)))); self.norm(dif, v); (ret == 0) as u32 } diff --git a/src/jpeg.rs b/src/jpeg.rs index 973310d..72fe87f 100644 --- a/src/jpeg.rs +++ b/src/jpeg.rs @@ -448,14 +448,6 @@ fn clamp_u8(v: f32) -> u8 { } } -#[inline] -fn ycbcr_to_rgb(y: f32, cb: f32, cr: f32) -> (u8, u8, u8) { - let r = y + 1.402 * (cr - 128.0); - let g = y - 0.344136 * (cb - 128.0) - 0.714136 * (cr - 128.0); - let b = y + 1.772 * (cb - 128.0); - (clamp_u8(r), clamp_u8(g), clamp_u8(b)) -} - #[inline] fn rgb_to_ycbcr(r: f32, g: f32, b: f32) -> (f32, f32, f32) { let y = 0.299 * r + 0.587 * g + 0.114 * b; @@ -1192,7 +1184,7 @@ mod writer_bench { let bytewise = || { let mut buf = Vec::new(); let mut acc = 0u32; let mut nbits = 0u32; - let mut put = |buf: &mut Vec, acc: &mut u32, nbits: &mut u32, code: u32, len: u32| { + let put = |buf: &mut Vec, acc: &mut u32, nbits: &mut u32, code: u32, len: u32| { *acc |= code << (32 - *nbits - len); *nbits += len; while *nbits >= 8 { let b=(*acc>>24)as u8; buf.push(b); if b==0xFF{buf.push(0);} *acc<<=8; *nbits-=8; } }; diff --git a/src/main.rs b/src/main.rs index c9376ea..8d3521c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -14,16 +14,13 @@ // applicative of proof/IIRFilterCollapse.lean) summed in i64. // ═══════════════════════════════════════════════════════════════════════════ +#![forbid(unsafe_code)] + use std::f64::consts::PI; -mod aac; -mod aac_tables; -mod codec; -mod flac; -mod mp3; -mod mp3_tables; -mod opus; -mod opus_tables; +// The codec modules come from the library crate (src/lib.rs). Declaring them here as +// `mod aac;` etc. compiled a second copy into the binary, where most items looked unused. +use transcode::{aac, codec, flac, mp3, opus}; const FS: f64 = 2_147_483_648.0; // 2^31, canonical full scale diff --git a/src/mp3.rs b/src/mp3.rs index b734556..2e313cf 100644 --- a/src/mp3.rs +++ b/src/mp3.rs @@ -338,7 +338,7 @@ pub fn reservoir_check(data: &[u8]) -> Result { /// Read one Huffman codeword from `br` against (codes, lens), returning the /// entry index. Prefix-free, so accumulate bits until a (length, code) matches. -/ -pub fn read_huffman(br: &mut Br, codes: &[u32], lens: &[u8]) -> Option { +fn read_huffman(br: &mut Br, codes: &[u32], lens: &[u8]) -> Option { if codes.is_empty() { return None; } @@ -582,12 +582,12 @@ fn decode_is(br: &mut Br, g: &Granule, sfb: &[usize; 23], boundary: usize) -> [i let i2 = (g.region0_count as usize + g.region1_count as usize + 2).min(22); (sfb[i1].min(bvl), sfb[i2].min(bvl)) }; - let mut idx = 0usize; + let mut idx: usize; for (s, e, ts) in [(0usize, r1, g.table_select[0]), (r1, r2, g.table_select[1]), (r2, bvl, g.table_select[2])] { if s >= e { continue; } let (codes, lens, wrap) = crate::mp3_tables::table(ts as usize); let lin = crate::mp3_tables::LINBITS[ts as usize & 31]; - if codes.is_empty() || wrap == 0 { idx = e; continue; } + if codes.is_empty() || wrap == 0 { continue; } idx = s; while idx < e { let hi = match read_huffman(br, codes, lens) { Some(v) => v as u32, None => return is }; diff --git a/src/opus.rs b/src/opus.rs index d98818d..cad8014 100644 --- a/src/opus.rs +++ b/src/opus.rs @@ -13,6 +13,10 @@ // ─── Ogg container ──────────────────────────────────────────────────────────── +// Opus decode -> PCM is partial (ROADMAP.md). The CELT synthesis helpers below are +// scaffolding that is not wired up yet, so they are allowed to be unused for now. +#![allow(dead_code)] + /// One reassembled Opus packet (the bytes after Ogg framing). pub struct OggPacket { pub data: Vec, From b2dd3c56d8a44a40d591c0afe019a6cd47cb99d6 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 4 Nov 2026 22:58:32 +0000 Subject: [PATCH 04/11] docs: rewrite README and add community, security and OpenSSF documentation - README: rewritten to match the code. The old text described a PDF image decoder that does not exist here and paths that are not in the tree. The status table is taken from ROADMAP.md and the source. A patents and licensing section is first, marked as an open decision. - CONTRIBUTING, CODE_OF_CONDUCT (Contributor Covenant 2.1), SECURITY (GitHub private reporting; no email address), CONTRIBUTORS (human names from git history), CHANGELOG (Keep a Changelog). - docs/OPENSSF.md: Scorecard mapping, Best Practices status, and open human items. Placeholder owners, the license question, the patent review, the conduct contact, repository visibility and the ruleset are all open. - docs/SUPPLY-CHAIN.md: pins with verified commit SHAs, verification commands. - docs/RELEASING.md: maintainer steps. - PR and issue templates. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Ch6Crfubj3FwdxR7ywn9vT --- .github/ISSUE_TEMPLATE/bug_report.md | 21 ++ .github/ISSUE_TEMPLATE/config.yml | 5 + .github/ISSUE_TEMPLATE/feature_request.md | 13 ++ .github/PULL_REQUEST_TEMPLATE.md | 19 ++ CHANGELOG.md | 23 +++ CODE_OF_CONDUCT.md | 56 ++++++ CONTRIBUTING.md | 70 +++++++ CONTRIBUTORS.md | 11 ++ README.md | 222 ++++++++++------------ SECURITY.md | 49 +++++ docs/OPENSSF.md | 93 +++++++++ docs/RELEASING.md | 38 ++++ docs/SUPPLY-CHAIN.md | 99 ++++++++++ 13 files changed, 594 insertions(+), 125 deletions(-) create mode 100644 .github/ISSUE_TEMPLATE/bug_report.md create mode 100644 .github/ISSUE_TEMPLATE/config.yml create mode 100644 .github/ISSUE_TEMPLATE/feature_request.md create mode 100644 .github/PULL_REQUEST_TEMPLATE.md create mode 100644 CHANGELOG.md create mode 100644 CODE_OF_CONDUCT.md create mode 100644 CONTRIBUTING.md create mode 100644 CONTRIBUTORS.md create mode 100644 SECURITY.md create mode 100644 docs/OPENSSF.md create mode 100644 docs/RELEASING.md create mode 100644 docs/SUPPLY-CHAIN.md diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..a6ff330 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,21 @@ +--- +name: Bug report +about: Something produces the wrong output, panics or fails to build +labels: bug +--- + +**What happened** + +**What you expected** + +**Reproduction** + +A minimal command, code snippet or input file. For decoder problems, attach the input bytes or +a generator script. + +**Environment** + +- transcode version or commit: +- Rust version (`rustc --version`): +- OS and architecture: +- ffmpeg present? (only for ffmpeg-backed tests): diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..a839df4 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: true +contact_links: + - name: Report a security vulnerability + url: https://github.com/webfold-ai/transcode/security/advisories/new + about: Please use private reporting for vulnerabilities. Do not open a public issue. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..7c04c68 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,13 @@ +--- +name: Feature request +about: Propose a codec, container or API change +labels: enhancement +--- + +**Problem or use case** + +**Proposed change** + +**Alternatives considered** + +**Patent or licensing status of the format, if known** diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..34ade5d --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,19 @@ +## Summary + + + +## Output compatibility + + + +## Checks + +- [ ] `cargo fmt --all -- --check` +- [ ] `cargo test --locked` +- [ ] `cargo clippy --locked --all-targets -- -D warnings` +- [ ] New or changed decoder paths are covered by a test or a fuzz input +- [ ] No `unsafe` added, and no new runtime dependency (or one is justified below) + +## Notes for reviewers + + diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..fb27682 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,23 @@ +# Changelog + +All notable changes to this project are documented here. The format follows +[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project uses +[Semantic Versioning](https://semver.org/) once it reaches 1.0. + +## [Unreleased] + +### Changed + +- The binary uses the library's codec modules instead of compiling its own copies. +- `Cargo.toml` records the license, repository, readme and keywords, and sets `rust-version = 1.89`. +- The library and binary are built with `#![forbid(unsafe_code)]`. + +### Fixed + +- Debug builds no longer panic on the AV1 boolean and coefficient decoding paths. Release + output is unchanged. +- `Cargo.lock` now includes the `image-webp` dev-dependency, so `--locked` builds succeed. + +## [0.1.0] + +First version recorded in this repository. Contains the codecs listed in the README's status table. diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..dc10d09 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,56 @@ +# Contributor Covenant Code of Conduct + +## Our pledge + +We as members, contributors and maintainers pledge to make participation in this project a +harassment-free experience for everyone, regardless of age, body size, visible or invisible +disability, ethnicity, sex characteristics, gender identity and expression, level of experience, +education, socio-economic status, nationality, personal appearance, race, religion, or sexual +identity and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive +and healthy community. + +## Our standards + +Examples of behaviour that contributes to a positive environment: + +- Demonstrating empathy and kindness toward other people. +- Being respectful of differing opinions, viewpoints and experiences. +- Giving and gracefully accepting constructive feedback. +- Accepting responsibility, apologising to those affected by our mistakes, and learning from them. +- Focusing on what is best for the community as a whole. + +Examples of unacceptable behaviour: + +- The use of sexualised language or imagery, and sexual attention or advances of any kind. +- Trolling, insulting or derogatory comments, and personal or political attacks. +- Public or private harassment. +- Publishing others' private information, such as a physical or email address, without their + explicit permission. +- Other conduct which could reasonably be considered inappropriate in a professional setting. + +## Enforcement responsibilities + +Project maintainers are responsible for clarifying and enforcing these standards. They may remove, +edit or reject comments, commits, code, issues and other contributions that do not align with +this Code of Conduct, and may temporarily or permanently ban contributors for behaviour they +judge to be inappropriate, threatening, offensive or harmful. + +## Scope + +This Code of Conduct applies within project spaces and when an individual represents the project +in public spaces. + +## Enforcement + +Report instances of abusive, harassing or otherwise unacceptable behaviour to the project maintainers. +Until a dedicated contact is set up, use GitHub's private reporting for this repository +(**https://github.com/webfold-ai/transcode/security/advisories/new**) and state in the report that it +concerns conduct. All complaints are reviewed promptly and fairly, and the reporter's privacy and +security are respected. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org), +version 2.1, available at https://www.contributor-covenant.org/version/2/1/code_of_conduct.html. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..c4d8f4f --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,70 @@ +# Contributing to transcode + +Thanks for looking at transcode. It is a from-scratch codec crate with no runtime +dependencies, so changes are checked closely for correctness and for the bit-exact +behaviour the tests depend on. + +## Before you start + +- Read [README.md](README.md), especially the patents and licensing section. +- Check [ROADMAP.md](ROADMAP.md) for what is planned and what is intentionally unfinished. +- For anything larger than a bug fix, open an issue first so the approach can be agreed. + +## Development setup + +```sh +cargo build --locked --all-targets +cargo test --locked +cargo fmt --all -- --check +cargo clippy --locked --all-targets -- -D warnings +``` + +Install ffmpeg as well if you want the ffmpeg-backed tests to run rather than print `SKIP`. + +Supply-chain checks, which CI also runs: + +```sh +cargo deny check advisories bans licenses sources +cargo audit +``` + +Fuzzing needs nightly and cargo-fuzz: + +```sh +cargo +nightly fuzz run fuzz_png --fuzz-dir fuzz -- -max_total_time=60 +``` + +## What a good change looks like + +- **Keep the output bit-exact.** Changes to a codec must not alter the bytes it produces unless + that is the point of the change. If the output changes, say so in the pull request and update + the test that pins it. +- **Add a test that fails before your change.** For a decoder, add a regression input to the + fuzz corpus or a unit test, and include the input bytes or a generator. +- **No `unsafe`.** The crate is built with `#![forbid(unsafe_code)]`. +- **No new runtime dependencies** without an issue first. Dev-dependencies need the same + review because they enter `Cargo.lock`. +- **Codecs need evidence.** A new encoder or decoder should come with an external check + (for example an ffmpeg round-trip) where one exists, and a note on its patent status. + +## Commits and pull requests + +- Keep commits focused. Separate formatting-only commits from behaviour changes. +- Describe the change and why it is correct. Mention any output-format change. +- Fill in the pull request template. +- A maintainer reviews every change. Automated tooling does not approve or merge. + +## Reporting bugs and security issues + +- Ordinary bugs: open an issue with the bug report template. +- Security issues, including a decoder that panics, hangs or allocates without bound on + crafted input: do **not** open a public issue. Follow [SECURITY.md](SECURITY.md). + +## Code of conduct + +Participation is governed by [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md). + +## License + +By contributing you agree that your contribution is licensed under the same terms as the +project (MIT; see [LICENSE-MIT](LICENSE-MIT)). diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md new file mode 100644 index 0000000..65af5eb --- /dev/null +++ b/CONTRIBUTORS.md @@ -0,0 +1,11 @@ +# Contributors + +People who have contributed code or documentation to transcode. Names are taken from the git +history. Automated or agent-authored commits are not listed here. + +- Clay Townsend +- Clay + +The git history contains commits under both "Clay Townsend" and "Clay". They are listed +separately until a maintainer confirms that they are the same person. Add yourself in your first +pull request. diff --git a/README.md b/README.md index 8060c26..7acc071 100644 --- a/README.md +++ b/README.md @@ -1,152 +1,124 @@ # transcode -![transcode social preview](assets/social-card.png) +[![CI](https://github.com/webfold-ai/transcode/actions/workflows/ci.yml/badge.svg)](https://github.com/webfold-ai/transcode/actions/workflows/ci.yml) +[![OpenSSF Scorecard](https://api.scorecard.dev/projects/github.com/webfold-ai/transcode/badge)](https://scorecard.dev/viewer/?uri=github.com/webfold-ai/transcode) + +Pure-Rust audio, image and video codecs, written from scratch. The library uses only `std`: +no ffmpeg, libpng, libjpeg, zlib or other C libraries at runtime. + +**Status: 0.1.0, pre-release.** Some formats are complete in both directions and others are +partial or encode-only. The per-format table below and [ROADMAP.md](ROADMAP.md) are the +authoritative status. Nothing here is a claim of conformance with a specification beyond what +the tests check. + +## Patents and licensing: open decision + +**This section must be read before the crate is distributed.** It is not resolved. + +- Several formats in this crate are covered by patents in some jurisdictions. H.264 and AAC are + the main examples, and both are licensed through patent pools. MP3 patents have largely + expired, but the position varies by country. The MP4, MKV and HEIF writers carry H.264 here, so the same + questions apply to their output. Container licensing has not been reviewed. +- AV1 is described by its licensors as royalty-free under published terms. That is not the same + as a statement that no patent applies. +- Nothing in this repository is a patent search, a licensing opinion, or a grant of patent + rights. Do not describe the crate as patent-free. +- Maintainers need to decide, with counsel, whether and how these codecs are published. That + decision is tracked as an open item in [docs/OPENSSF.md](docs/OPENSSF.md). + +## What works today + +Status is taken from [ROADMAP.md](ROADMAP.md) and the source. "Encode" means the crate's own +encoder. Round-trip and external-decoder checks are listed in the Verification section. + +| Format | Decode | Encode | Notes | +|---|:--:|:--:|---| +| PNG | RGBA8 | RGBA8 | 8-bit, non-interlaced only (`src/png.rs`) | +| JPEG | Baseline | Baseline | Sequential Huffman only. Progressive files return an error (`src/jpeg.rs`) | +| WebP | - | Lossless (VP8L) | Encoder output has no predictive transforms or colour cache, so files are large (`src/webp.rs`) | +| RIFF WAV | yes | yes | CLI path; 8/16/24/32-bit integer and 32-bit float (ROADMAP.md) | +| FLAC | yes | yes | Standard `.flac` output (ROADMAP.md) | +| SLAC | yes | yes | This crate's own lossless container (ROADMAP.md) | +| MP3 (Layer III) | yes | no | Decode to PCM; no encoder planned (ROADMAP.md) | +| AAC-LC (ADTS) | yes | yes | MDCT, Huffman, closed-form rate control (ROADMAP.md) | +| Opus | partial | no | Ogg demux, OpusHead and TOC parsing. No packet-to-PCM decode yet (ROADMAP.md) | +| H.264 | no | intra and P-skip | Annex-B output. Used by the MP4, MKV and HEIF muxers (`src/h264.rs`) | +| AV1 | no | keyframes | Experimental. Covers synthetic 64x64 keyframes (`src/av1_frame.rs`) | +| MP4, MKV, HEIF, Motion-JPEG AVI | no | muxers | Container writers only (`src/mp4.rs`, `src/mkv.rs`, `src/heif.rs`, `src/mjpeg.rs`) | + +Other modules: `preview` renders a decoded RGBA image as a grayscale text preview +(`src/preview.rs`). + +## Build and test -**Zero-dependency PDF image decoder.** Extract and decode image streams from PDF files. -Pure Rust, std only — no libc, no ffmpeg, no C libraries. - -Used by [pdffold](https://github.com/Ptyktos/pdffold) for image extraction during -PDF-to-markdown conversion. Sovereign from-scratch JPEG and PNG codecs handle the -image formats embedded in PDF content streams. - -## Quick start - -```toml -[dependencies] -transcode = "0.1" -``` - -```bash +```sh cargo build --release +cargo test --locked ``` -Decode images from a PDF via the CLI: +Some integration tests use ffmpeg as an external decoder, so their output is checked against an +independent implementation. They print `SKIP` and pass when ffmpeg is not installed. CI installs +ffmpeg, so those checks always run there. The H.264 size report is `#[ignore]`d; run it with +`cargo test --release --test h264_bitexact -- --ignored --nocapture report_sizes`. -```bash -# Extract + decode all JPEG and PNG image streams to RGBA -transcode extract in.pdf --out-dir ./frames - -# Pipe raw image stream bytes from a PDF object -cat obj-stream.bin | transcode decode --fmt auto > decoded.rgba -``` - -## Features - -- **JPEG decode** — baseline sequential DCT, Huffman entropy coding (no arithmetic, - no progressive). Grayscale + YCbCr with arbitrary sampling factors (4:2:0, 4:2:2, - 4:4:4), restart markers. Output is canonical 8-bit RGBA. -- **PNG decode** — all color types (grayscale, RGB, palette, gray+alpha, RGBA), - 8-bit depth, non-interlaced. Full DEFLATE inflate (stored / fixed-Huffman / - dynamic-Huffman) + zlib wrapper + scanline filters. -- **Zero dependencies** — from-scratch implementations of JPEG DCT/Huffman, PNG - DEFLATE/CRC-32/Adler-32. No libpng, libjpeg, zlib, or system libraries. -- **Container probes** — parse stream headers without full decode (dimensions, - color type, compression params). -- **RGBA canonical output** — both codecs produce the same `Image` struct (`Vec` - RGBA pixels, width, height), so downstream consumers handle one format. - -## How it works - -PDF files embed image streams as compressed object data, typically JPEG DCT or PNG -deflate. transcode provides the decode engines for both formats: - -- **JPEG path:** Parse SOI–EOI markers, extract quantization + Huffman tables, - decode MCU blocks via separable DCT, upsample chroma components to full - resolution, output RGBA. -- **PNG path:** Parse chunk stream (IHDR → IDAT → IEND), inflate DEFLATE-compressed - scanline data (dynamic or fixed Huffman), reverse the per-scanline filter (none, - sub, up, average, Paeth), assemble RGBA pixels. - -Both codecs are standalone implementations — no wrappers around system libraries, -no FFI, no `build.rs` probes. The JPEG decoder uses a clean direct separable float -DCT (AAN/FFT fast path available as a drop-in); the PNG decoder includes a complete -DEFLATE inflate with LZ77 hash-chain match finding. - -``` -PDF object ──▶ JPEG marker scan ──▶ Huffman decode ──▶ iDCT ──▶ RGBA pixels - or - ▶ PNG chunk parse ──▶ DEFLATE inflate ──▶ unfilter ──▶ RGBA pixels -``` +Minimum supported Rust version: **1.89** (`rust-version` in `Cargo.toml`, checked in CI). -## Library API +## Library use ```rust -// Decode JPEG bytes → RGBA image -let img = transcode::jpeg::decode(&bytes)?; +use transcode::{flac, png}; -// Decode PNG bytes → RGBA image -let img = transcode::png::decode(&bytes)?; +let image = png::decode(&bytes)?; // image.width, image.height, image.pixels (RGBA8) +let (samples, rate, channels, _bps) = flac::decode(&bytes)?; +let png_bytes = png::encode(width, height, &rgba_pixels, true)?; ``` -Both return `Image { width: u32, height: u32, pixels: Vec }` where `pixels` -is RGBA8, row-major, `width * height * 4` bytes. +Decoders return `Result<_, String>`. The design goal is that they never panic on malformed +input; the fuzz targets in `fuzz/` exist to test that goal, and it is not yet proven. The public +modules are listed in `src/lib.rs`. -## Related Projects (Ptyktos ecosystem) +## Command line -- **[pdffold](https://github.com/Ptyktos/pdffold)** — PDF-to-markdown using transcode - for image stream extraction -- **[swarm](https://github.com/TWN-Systems/swarm)** — swarm prediction via - stationary-phase collapse -- **[talon](https://github.com/TWN-Systems/talon)** — mail-security adapter on the - same collapse engine -- **[cerealize](https://github.com/TWN-Systems/collapse_wire)** — zero-dependency - Rust serialization via the x=B/U Null residual -- **Sanguine** — the Lean proof corpus; the fixed-point kernels in this crate derive - from `proof/PolyphaseCollapse.lean` and `proof/IIRFilterCollapse.lean` - -Also from the fold-family: **[chunkfold](https://github.com/Ptyktos/chunkfold)**, -**[textfold](https://github.com/Ptyktos/textfold)**, -**[webfold](https://github.com/Ptyktos/webfold)**, -**[sdirstat](https://github.com/Ptyktos/sdirstat)**. - -## License - -MIT - -Sovereign, ffmpeg-free audio + image codec crate — pure Rust, zero -non-Ptyktos dependencies. - -## What it is +```sh +transcode in.wav out.wav --rate 8000 --bits 16 --channels 1 # resample / depth / channels +transcode --selftest # resampler, depth and channel-mixing checks +transcode --codec-selftest # SLAC lossless round-trip +transcode --bench 10 # time each operation on a synthetic signal +``` -transcode is the Ptyktos fold-extracted codec layer. PNG, JPEG, AAC, AV1, -H.264, FLAC, MP3, MP4, HEIF, WEBP, NIfTI, HDF5 — all decoded and encoded -without leaving the ptyktos substrate (no ffmpeg, no libpng, no libjpeg). +`src/main.rs` also has flags for individual codec stages (`--from-flac`, `--to-aac`, +`--from-mp3`, `--png-to-mp4`, and others). Most are self-tests for one stage of one codec. -Lives on the ptyktos substrate because Ptyktos's image + audio pipelines -(`memoryfold`, the audio-folders, the `glossa` localization engine, the -peregrine-ng extraction service) all want to handle media without -shipping ffmpeg. +## Verification -## What lives here +- Unit tests in `src/` cover the entropy coders, transforms and container writers. +- Integration tests in `tests/` check AV1 and H.264 output against ffmpeg (`tests/av1_*.rs`, + `tests/h264_bitexact.rs`). +- `fuzz/` contains one libFuzzer target per decoder that accepts untrusted bytes: PNG, JPEG, + FLAC, SLAC, MP3, AAC and Opus. They run for 180 seconds per target on pull requests and daily in + CI. No long-running campaign has been completed yet. +- Clippy correctness and suspicious lints are denied in CI. Style, complexity and perf lints are + allowed for now; see the `[lints.clippy]` note in `Cargo.toml`. +- `cargo deny` and `cargo audit` run in CI against `Cargo.lock`. -| Surface | Path | -|---|---| -| Crate | `src/lib.rs` | -| PNG decoder/encoder | `src/codec/png/` | -| JPEG decoder/encoder | `src/codec/jpeg/` | -| AAC decoder/encoder | `src/codec/aac/` | -| AV1 decoder/encoder | `src/codec/av1/` | -| H.264 decoder/encoder | `src/codec/h264/` | -| MP4 muxer | `src/mp4/` | +Performance numbers are in [BENCHMARKS.md](BENCHMARKS.md). They come from one machine and mostly +from a synthetic tone. Read that file before quoting any number. -## Build +## Security -```sh -cargo build --release -``` +- The crate forbids `unsafe` code: `#![forbid(unsafe_code)]` is set on the library and the binary. +- The library has no runtime dependencies. +- Please report vulnerabilities privately, as described in [SECURITY.md](SECURITY.md). -## See also +## Contributing -- [`Ptyktos/sangsec`](https://github.com/Ptyktos/sangsec) — uses transcode - for embedded-image inspection in agent tool calls -- [`Ptyktos/glossa`](https://github.com/Ptyktos/glossa) — uses transcode - for localization-asset hashing +See [CONTRIBUTING.md](CONTRIBUTING.md). Contributions that add a codec need test vectors, +an external-decoder check where one exists, and a note on patent status for review. ## License -SPDX: `MIT OR Apache-2.0`. Ptyktos substrate (fold-extracted). +MIT. See [LICENSE-MIT](LICENSE-MIT). -The full Ptyktos substrate (PNG, JPEG, AAC, AV1, H.264, FLAC, MP3, -MP4, HEIF, WEBP, NIfTI, HDF5) is built and consumed by Ptyktos itself -via fold extraction; transcode exposes the image + audio halves as the -pde-aligned public surface. +The repository contains only the MIT license text. An earlier version of this README also said +"MIT OR Apache-2.0"; that is not reflected in the repository and is part of the open licensing +decision above. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..c8882d1 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,49 @@ +# Security policy + +## Supported versions + +| Version | Supported | +|---|---| +| 0.1.x (current development line) | Yes | +| Anything older | No | + +transcode has not had a public release yet. Until one exists, only the default branch is +supported. + +## Reporting a vulnerability + +Please report security issues privately, using GitHub's private vulnerability reporting: + +**https://github.com/webfold-ai/transcode/security/advisories/new** + +Do not open a public issue, pull request or discussion for a suspected vulnerability. + +Include, where you can: + +- the affected version or commit, +- a minimal input (a byte file, or a generator script) that reproduces the problem, +- the observed behaviour (panic message, hang, memory growth, wrong output) and the expected behaviour. + +## Scope + +In scope: + +- Panics, out-of-bounds access, unbounded allocation, or non-terminating loops in any decoder + or parser that accepts untrusted bytes (PNG, JPEG, FLAC, SLAC, MP3, AAC, Opus demux/parse, + and the container readers that are used on input). +- Incorrect output that could be used to mislead a consumer, for example a decoder that accepts + a malformed stream as valid and returns different content from the reference decoder. +- Problems in the release process or in the supply-chain configuration described in + [docs/SUPPLY-CHAIN.md](docs/SUPPLY-CHAIN.md). + +Out of scope: + +- Speed and output-quality issues that do not affect safety. +- Missing features listed in [ROADMAP.md](ROADMAP.md) (for example, Opus packet-to-PCM decode). +- Patent or licensing questions. These are not security issues; see the README. + +## What to expect + +We aim to acknowledge a report within 7 days and to give a first assessment within 14 days. +This is a small project, so those targets are best effort. We will keep you informed, credit you +in the advisory if you want, and coordinate disclosure with you. diff --git a/docs/OPENSSF.md b/docs/OPENSSF.md new file mode 100644 index 0000000..0672075 --- /dev/null +++ b/docs/OPENSSF.md @@ -0,0 +1,93 @@ +# OpenSSF posture + +This page records how transcode maps to the OpenSSF Scorecard checks and the Best Practices +badge, what is already in the repository, and what still needs a human. Status words are used +strictly: **In repo** means a file or setting exists in this repository. **Verified** means it was +checked by running it. **Human** means someone with access has to act. Nothing here is a claim +that a score has been earned. + +## Scorecard checks + +| Check | What closes it | Status | +|---|---|---| +| Pinned-Dependencies | Every `uses:` is a full commit SHA. Tags are verified with `git ls-remote` (see docs/SUPPLY-CHAIN.md). `cargo` dependencies are pinned by `Cargo.lock`. | In repo; Verified for the SHAs listed in SUPPLY-CHAIN.md | +| SAST | `codeql.yml` (Rust, `security-extended`) and `cargo clippy -D warnings` in CI | In repo | +| Fuzzing | `fuzz/` with seven libFuzzer targets (`libfuzzer_sys` marker) and `fuzz.yml` (pull requests and daily) | In repo; targets compile on stable (`cargo check`). No long campaign run yet | +| Signed-Releases | `release.yml`: cosign keyless signatures (`.sig`, `.cert`), SLSA provenance (`.intoto.jsonl`) | In repo; not yet exercised by a real tag | +| Packaging | Not applicable yet. The crate sets no `publish` flag. Release assets are GitHub release tarballs, not a package registry | Human (decide whether to publish to crates.io) | +| Branch-Protection | Ruleset (see below) | Human. Not applied | +| CI-Tests | `ci.yml` runs build, tests (with ffmpeg), fmt and clippy on every pull request | In repo | +| Dependency-Update-Tool | `dependabot.yml` for cargo and github-actions, weekly | In repo | +| Token-Permissions | Read-only top-level `permissions` in every workflow; write only per job | In repo | +| Security-Policy | `SECURITY.md` | In repo | +| License | `LICENSE-MIT` matches `license = "MIT"` in Cargo.toml | In repo; licensing decision open (see the README) | +| Binary-Artifacts | No binaries are committed. The crate has no build scripts. | Verified by inspection | +| Dangerous-Workflow | No `pull_request_target`; untrusted input is not interpolated into `run:` steps | In repo | +| Vulnerabilities | `cargo audit` and `cargo deny` in `supply-chain.yml`. Last local run: no advisories | In repo; Verified locally | +| Maintained | Time-gated. The project must have commits over 90 days | Time | +| Code-Review | Requires human approvals on each change through the ruleset | Human | +| Contributors | Requires contributors from more than one organisation. Not claimed | Human | +| CII-Best-Practices | See the next section | Human | +| Webhooks | Not applicable: no webhook-driven service | Not applicable | + +## Best Practices badge (bestpractices.dev) + +Registration needs an OAuth login, which cannot be done from this repository. No badge ID has +been created or recorded here. + +| Area | Status | +|---|---| +| Basics: FLOSS license, documented project, public repository | License in repo. The repository is **private** today; it must be public before the badge is meaningful. **Human** | +| Change control: version control, unique version per release | In repo (git, Cargo version, tags via release workflow) | +| Reporting: bug reports and vulnerability reports | `SECURITY.md`, issue templates. Response targets are proposed, not yet agreed. **Human** | +| Quality: build, automated tests, warnings policy | CI and `-D warnings` for correctness and suspicious lints | +| Security: secure design, no unsafe, dependency checks | `#![forbid(unsafe_code)]`; cargo-audit and cargo-deny in CI. Fuzzing exists but has not run for a sustained period | +| Analysis: static analysis | Clippy and CodeQL in CI | + +## Open items + +1. **CODEOWNERS placeholders.** `.github/CODEOWNERS` lists `@OWNER-1 @OWNER-2`. These are not real + accounts. Replace them with two or more human maintainers before the code-owner rule is + enabled. Do not use bot accounts. **Human** +2. **Licensing.** Cargo.toml and `LICENSE-MIT` say MIT. An earlier README said `MIT OR Apache-2.0`. + Decide, and if dual licensing is wanted, add `LICENSE-APACHE` and change Cargo.toml. **Human** +3. **Patents.** The H.264, AAC and MP3 coverage described in the README needs a legal review + before publication. **Human** +4. **Code of conduct contact.** No dedicated contact exists yet. CODE_OF_CONDUCT.md routes reports + through private reporting for now. **Human** +5. **Visibility.** The repository is private. Scorecard publishing, the badges and + dependency-review on private repositories (which needs GitHub Advanced Security) depend on this. + **Human** +6. **Ruleset.** Default-branch protection is not applied. The caretaker ruleset requires two + approvals, code-owner review and the `Rust checks` status check. Apply it only after the + CODEOWNERS placeholders are resolved. **Human** +7. **Fuzz campaigns.** Targets compile. A sustained campaign has not been run. The first CI + fuzz run may find real panics; those are bugs to fix, not to suppress. **Human review of + results** + +## Caretaker + +`caretaker-ossf` holds the fleet template set this repository follows +(`ptyktos/caretaker`, `caretaker-ossf/templates/`). The `caretakerctl ossf` commands are not run +for this repository yet: + +```sh +# Render the template set offline and inspect the result. +caretakerctl ossf render --repo-path webfold-ai/transcode --crate-name transcode \ + --import-entry transcode::png::decode --code-owners '@owner-one @owner-two' --out /tmp/transcode-ossf + +# Measure compliance (read-only). Needs the GitHub token in CARETAKER_GITHUB_TOKEN. +caretakerctl ossf report --repos webfold-ai/transcode + +# Open the compliance change. Use --skip-ruleset until the owners are real and the change is merged. +caretakerctl ossf apply --repo webfold-ai/transcode --crate-name transcode \ + --import-entry transcode::png::decode --code-owners '@owner-one @owner-two' --skip-ruleset +``` + +These are the commands documented in `caretaker/docs/ossf-scorecard.md`. This repository +diverges from the template set on purpose: its fuzz targets are per decoder (not the HTTP +service pair), it has no container job, and its release job builds the `transcode` CLI. Do not let +`apply` overwrite those files without review. The caretakerctl binary could not be built in the +session that produced this change, because the caretaker workspace depends on private git +repositories. The template files were rendered with a Python script that follows the same +substitutions and invariants. diff --git a/docs/RELEASING.md b/docs/RELEASING.md new file mode 100644 index 0000000..f4d336d --- /dev/null +++ b/docs/RELEASING.md @@ -0,0 +1,38 @@ +# Releasing + +Only maintainers cut releases. The `release.yml` workflow does the build, signing and +attestation; the maintainer's job is to choose the version, make sure `main` is green, and push the +tag. + +## Steps + +1. **Pick the version.** Follow Semantic Versioning. While the major version is 0, a minor bump may + break compatibility. +2. **Update the version and changelog.** Set `version` in `Cargo.toml` and move the `[Unreleased]` + entries in `CHANGELOG.md` under a new heading with today's date. +3. **Check the release locally.** + ```sh + cargo fmt --all -- --check + cargo test --locked --release + cargo clippy --locked --all-targets -- -D warnings + cargo deny check advisories bans licenses sources + cargo audit + ``` +4. **Merge the release pull request** after review. Confirm that the `Rust checks`, `MSRV 1.89` + and supply-chain jobs passed on the merge commit. +5. **Tag the merge commit.** + ```sh + git tag -a v0.1.0 -m "transcode v0.1.0" + git push origin v0.1.0 + ``` + The tag must equal `v` plus the `version` in `Cargo.toml`. The workflow fails otherwise. +6. **Check the workflow run.** The release workflow runs the tests, builds, signs and attests. Its + assets appear on the GitHub release page. Verify them with the commands in + [SUPPLY-CHAIN.md](SUPPLY-CHAIN.md#release-provenance). + +## Rules + +- Never create a tag from a fork or a branch other than the default branch. +- Do not edit a published release. If it is wrong, publish a new version. +- Recommended: resolve the patent and licensing questions in the README before releasing binaries + that contain codecs. Those binaries are the first thing a public release distributes. diff --git a/docs/SUPPLY-CHAIN.md b/docs/SUPPLY-CHAIN.md new file mode 100644 index 0000000..8779191 --- /dev/null +++ b/docs/SUPPLY-CHAIN.md @@ -0,0 +1,99 @@ +# Supply chain + +How transcode's dependencies, build inputs, CI and release artifacts are controlled, and how to +check them. + +## Dependencies + +- **Runtime:** none. The library and the binary use only `std`. +- **Dev-dependencies:** `image-webp` (MIT OR Apache-2.0), used only in tests to check the WebP + encoder's output with an independent decoder. It and its transitive crates appear in + `Cargo.lock`. +- **Fuzz crate:** `fuzz/` is a separate workspace with its own `Cargo.lock`. It depends on + `libfuzzer-sys` and on the library by path. It is not built by the root workspace. +- **Lock file:** `Cargo.lock` is committed. CI builds with `--locked`, so a dependency change that + is not reflected in the lock file fails the build. + +## Policy checks (run in CI, and locally) + +| Tool | Command | What it checks | +|---|---|---| +| cargo-audit | `cargo audit --deny warnings` | RustSec advisories against `Cargo.lock` | +| cargo-deny | `cargo deny check advisories bans licenses sources` | advisories, duplicate or wildcard versions, license allow-list, and that every source is crates.io | +| cargo-cyclonedx | `cargo cyclonedx --format json --override-filename transcode.sbom` | a CycloneDX SBOM, uploaded as a CI artifact for 90 days | + +`deny.toml` allows only the MIT and Apache-2.0 licenses and no git sources. Any new git or +unknown-registry source is denied until a reviewed exception is added to that file. + +The `supply-chain.yml` workflow also writes a small JSON evidence record +(`ptyktos.supply_chain.audit`) with the result of each job, in the same format caretaker expects. + +## Pinned build inputs + +- **GitHub Actions:** every `uses:` line is pinned to a full commit SHA, with the tag in a comment. + Dependabot (`.github/dependabot.yml`) proposes updates to these pins weekly. +- **Rust toolchain:** `dtolnay/rust-toolchain` is pinned to a commit. The toolchain version itself is + set per job (`stable`, `nightly`, or `1.89.0` for MSRV). +- **Tool installs in CI:** `cargo install --locked` for cargo-audit, cargo-deny (version 0.19.4) + and cargo-cyclonedx, and cargo-fuzz. + +### Verifying the pins + +Resolve a tag to its commit before pinning, and use the peeled `^{}` line for annotated tags: + +```sh +git ls-remote --tags https://github.com/actions/checkout 'refs/tags/v7.0.1*' +``` + +Pins in use on 2026-11-04 (resolved with `git ls-remote` at that date): + +| Action | Tag | Commit | +|---|---|---| +| actions/checkout | v7.0.1 | 3d3c42e5aac5ba805825da76410c181273ba90b1 | +| actions/upload-artifact | v7.0.1 | 043fb46d1a93c77aae656e7c1c64a875d1fc6a0a | +| github/codeql-action | v4.38.2 | 2892aa5e19bbd11bc0cff5427e3b750a04d9e3c2 | +| actions/attest-build-provenance | v4.2.2 | 4d101475d8b20a2381f78447822ac1eab6504dd8 | +| sigstore/cosign-installer | v4.1.2 | 6f9f17788090df1f26f669e9d70d6ae9567deba6 | +| ossf/scorecard-action | v2.5.0 | fa7117db83c52d787ae5a89f350999701505d78e | +| actions/dependency-review-action | v4.9.0 | 2031cfc080254a8a887f58cffee85186f0e49e48 | +| dtolnay/rust-toolchain | master (not a release tag) | 683b588c487a69d01f6c6ddf40f036ff682cc2c8 | + +`dtolnay/rust-toolchain` has no release tags, so it is pinned to the `master` commit that was +current when the pin was set. Update it on the same schedule as the others. + +## Release provenance + +Releases are produced only by `release.yml`, which runs when a `v*` tag is pushed. A release +contains: + +- `transcode-vX.Y.Z-linux-x86_64.tar.gz`, the CLI binary with `LICENSE-MIT` and `README.md`, +- `SHA256SUMS`, with a sha256 for the tarball, +- `.sig` and `.cert` files from cosign keyless signing (identity: the release workflow at the tag), +- `.intoto.jsonl`, the SLSA build-provenance attestation. + +How to verify a downloaded release (replace `v0.1.0` with the version you downloaded): + +```sh +sha256sum -c SHA256SUMS + +cosign verify-blob \ + --certificate transcode-v0.1.0-linux-x86_64.tar.gz.cert \ + --signature transcode-v0.1.0-linux-x86_64.tar.gz.sig \ + --certificate-identity-regexp '^https://github.com/webfold-ai/transcode/\.github/workflows/release\.yml@refs/tags/v0\.1\.0$' \ + --certificate-oidc-issuer https://token.actions.githubusercontent.com \ + transcode-v0.1.0-linux-x86_64.tar.gz + +gh attestation verify transcode-v0.1.0-linux-x86_64.tar.gz --repo webfold-ai/transcode +``` + +Those commands are written from the workflow and have not yet been run against a published +release, because no release exists yet. + +## Known gaps + +- The release is Linux x86_64 only. +- The Rust toolchain used to build a release is whatever `dtolnay` installs for `1.89.0`, which is + not itself pinned by hash. +- `cargo install` of the audit tools compiles them in CI on every run. That is slow but reproducible + from the lock file of each tool. +- No crates.io publication is configured. Nothing is uploaded to a registry. From 8a51e7fc8db3c1db10c5b5ad0d71a11c05f89381 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 4 Nov 2026 22:58:32 +0000 Subject: [PATCH 05/11] ci: add CI, supply-chain, scorecard, fuzz and release workflows - ci.yml: job 'Rust checks' (fmt, build, test with ffmpeg installed, clippy -D warnings) and an MSRV 1.89 build job. - codeql.yml (Rust), scorecard.yml, dependency-review.yml. - supply-chain.yml: cargo-audit, cargo-deny, CycloneDX SBOM, evidence record. - fuzz.yml: matrix over seven libFuzzer targets; crash inputs kept on failure. - release.yml: tag-gated; runs tests, checks the tag against Cargo.toml, builds the CLI, signs with cosign, attests SLSA provenance. No container job, since the crate has no Dockerfile. - Every uses: line is pinned to a full commit SHA. Actions were verified with git ls-remote (peeled commits where annotated). - dependabot.yml for cargo and github-actions. - CODEOWNERS uses @OWNER-1 @OWNER-2 placeholders. Replace them with real maintainers before enabling the code-owner rule. - fuzz/: cargo-fuzz crate with targets for PNG, JPEG, FLAC, SLAC, MP3, AAC and Opus. The crate has its own workspace and lock file. - deny.toml: MIT and Apache-2.0 only, crates.io sources only, no git sources. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Ch6Crfubj3FwdxR7ywn9vT --- .github/CODEOWNERS | 4 + .github/dependabot.yml | 15 ++++ .github/workflows/ci.yml | 54 +++++++++++ .github/workflows/codeql.yml | 47 ++++++++++ .github/workflows/dependency-review.yml | 25 ++++++ .github/workflows/fuzz.yml | 51 +++++++++++ .github/workflows/release.yml | 93 +++++++++++++++++++ .github/workflows/scorecard.yml | 45 ++++++++++ .github/workflows/supply-chain.yml | 114 ++++++++++++++++++++++++ deny.toml | 42 +++++++++ fuzz/.gitignore | 4 + fuzz/Cargo.lock | 94 +++++++++++++++++++ fuzz/Cargo.toml | 67 ++++++++++++++ fuzz/fuzz_targets/fuzz_aac.rs | 9 ++ fuzz/fuzz_targets/fuzz_flac.rs | 8 ++ fuzz/fuzz_targets/fuzz_jpeg.rs | 8 ++ fuzz/fuzz_targets/fuzz_mp3.rs | 9 ++ fuzz/fuzz_targets/fuzz_opus.rs | 15 ++++ fuzz/fuzz_targets/fuzz_png.rs | 8 ++ fuzz/fuzz_targets/fuzz_slac.rs | 8 ++ 20 files changed, 720 insertions(+) create mode 100644 .github/CODEOWNERS create mode 100644 .github/dependabot.yml create mode 100644 .github/workflows/ci.yml create mode 100644 .github/workflows/codeql.yml create mode 100644 .github/workflows/dependency-review.yml create mode 100644 .github/workflows/fuzz.yml create mode 100644 .github/workflows/release.yml create mode 100644 .github/workflows/scorecard.yml create mode 100644 .github/workflows/supply-chain.yml create mode 100644 deny.toml create mode 100644 fuzz/.gitignore create mode 100644 fuzz/Cargo.lock create mode 100644 fuzz/Cargo.toml create mode 100644 fuzz/fuzz_targets/fuzz_aac.rs create mode 100644 fuzz/fuzz_targets/fuzz_flac.rs create mode 100644 fuzz/fuzz_targets/fuzz_jpeg.rs create mode 100644 fuzz/fuzz_targets/fuzz_mp3.rs create mode 100644 fuzz/fuzz_targets/fuzz_opus.rs create mode 100644 fuzz/fuzz_targets/fuzz_png.rs create mode 100644 fuzz/fuzz_targets/fuzz_slac.rs diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000..406a748 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1,4 @@ +# Code ownership for the required code-owner review on the default-branch +# ruleset. Two or more owners so an authoring owner is never locked out +# of merging their own change. +* @OWNER-1 @OWNER-2 diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..df265c6 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,15 @@ +version: 2 +updates: + - package-ecosystem: cargo + directory: "/" + schedule: + interval: weekly + open-pull-requests-limit: 10 + groups: + rust-dependencies: + patterns: ["*"] + - package-ecosystem: github-actions + directory: "/" + schedule: + interval: weekly + open-pull-requests-limit: 10 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..217232f --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,54 @@ +name: CI + +on: + pull_request: + push: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +jobs: + rust: + # This job name is the required status check ("Rust checks") in the + # default-branch ruleset. Renaming it requires updating the ruleset too. + name: Rust checks + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + # Several integration tests use ffmpeg as an external decoder oracle. They skip + # when ffmpeg is absent, so install it explicitly to make the job meaningful. + - name: Install ffmpeg (test oracle) + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends ffmpeg + ffmpeg -version | head -n 1 + - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master as of 2026-11-04 + with: + toolchain: stable + components: rustfmt, clippy + - name: Check formatting + run: cargo fmt --all -- --check + - name: Build + run: cargo build --locked --all-targets + - name: Test + run: cargo test --locked --no-fail-fast + - name: Clippy + run: cargo clippy --locked --all-targets -- -D warnings + + msrv: + name: MSRV 1.89 + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master as of 2026-11-04 + with: + toolchain: "1.89.0" + # Build only. The MSRV job does not run tests, so it is not a full test gate on 1.89. + - name: Build on the minimum supported Rust version + run: cargo build --locked --all-targets diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml new file mode 100644 index 0000000..4b95f4f --- /dev/null +++ b/.github/workflows/codeql.yml @@ -0,0 +1,47 @@ +name: CodeQL + +# Static analysis for the Scorecard SAST check. Runs on pull requests that touch Rust +# sources, on pushes to main, and weekly as a backstop. + +on: + pull_request: + paths: + - "src/**" + - "tests/**" + - "fuzz/**" + - "Cargo.toml" + - "Cargo.lock" + - ".github/workflows/codeql.yml" + push: + branches: [main] + schedule: + - cron: "23 2 * * 3" + workflow_dispatch: + +permissions: + contents: read + +jobs: + analyze: + name: CodeQL (Rust) + runs-on: ubuntu-latest + permissions: + contents: read + security-events: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master as of 2026-11-04 + with: + toolchain: stable + - name: Initialize CodeQL + uses: github/codeql-action/init@2892aa5e19bbd11bc0cff5427e3b750a04d9e3c2 # v4.38.2 + with: + languages: rust + build-mode: none + queries: security-extended + - name: Perform CodeQL analysis + uses: github/codeql-action/analyze@2892aa5e19bbd11bc0cff5427e3b750a04d9e3c2 # v4.38.2 + with: + category: "/language:rust" diff --git a/.github/workflows/dependency-review.yml b/.github/workflows/dependency-review.yml new file mode 100644 index 0000000..b931faf --- /dev/null +++ b/.github/workflows/dependency-review.yml @@ -0,0 +1,25 @@ +name: Dependency review + +# Fails a pull request that adds a dependency with a known high-severity vulnerability. +# GitHub's dependency graph must be enabled for the repository. For private repositories +# this also requires GitHub Advanced Security. + +on: + pull_request: + +permissions: + contents: read + +jobs: + dependency-review: + name: Dependency review + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Review dependency changes + uses: actions/dependency-review-action@2031cfc080254a8a887f58cffee85186f0e49e48 # v4.9.0 + with: + fail-on-severity: high diff --git a/.github/workflows/fuzz.yml b/.github/workflows/fuzz.yml new file mode 100644 index 0000000..3b24aae --- /dev/null +++ b/.github/workflows/fuzz.yml @@ -0,0 +1,51 @@ +name: Fuzz + +# cargo-fuzz (libFuzzer) runs every decoder target that accepts untrusted bytes. +# Short runs on pull requests that touch code, and a longer scheduled run every day, +# so the Scorecard Fuzzing check sees continuous fuzzing. + +on: + pull_request: + paths: + - "src/**" + - "tests/**" + - "fuzz/**" + - "Cargo.toml" + - "Cargo.lock" + - ".github/workflows/fuzz.yml" + push: + branches: [main] + schedule: + - cron: "17 5 * * *" + workflow_dispatch: + +permissions: + contents: read + +jobs: + fuzz: + name: cargo-fuzz (${{ matrix.target }}) + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + target: [fuzz_png, fuzz_jpeg, fuzz_flac, fuzz_slac, fuzz_mp3, fuzz_aac, fuzz_opus] + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master as of 2026-11-04 + with: + toolchain: nightly + - name: Install cargo-fuzz + run: cargo install --locked cargo-fuzz + - name: Run ${{ matrix.target }} + run: cargo +nightly fuzz run ${{ matrix.target }} --fuzz-dir fuzz -- -max_total_time=180 -rss_limit_mb=4096 + - name: Keep crash inputs + if: failure() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: fuzz-artifacts-${{ matrix.target }} + path: fuzz/artifacts/${{ matrix.target }} + retention-days: 30 + if-no-files-found: ignore diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..65a5478 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,93 @@ +name: Release + +# Runs only for version tags (v*). A tag is created by a maintainer; this workflow never +# creates tags itself. It builds the transcode CLI for Linux x86_64, signs the artifact +# with Sigstore (keyless, via GitHub OIDC), and attaches SLSA build provenance. + +on: + push: + tags: + - "v*" + +permissions: + contents: read + +jobs: + release: + name: Build and publish release assets + runs-on: ubuntu-latest + permissions: + contents: write + id-token: write # cosign keyless signing and artifact attestations + attestations: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master as of 2026-11-04 + with: + toolchain: "1.89.0" + - name: Install ffmpeg (test oracle) + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends ffmpeg + - name: Test before packaging + run: cargo test --locked --release --no-fail-fast + - name: Check tag matches package version + env: + TAG_NAME: ${{ github.ref_name }} + run: | + PACKAGE_VERSION=$(sed -n 's/^version = "\([^"]*\)"$/\1/p' Cargo.toml | head -n 1) + test "v${PACKAGE_VERSION}" = "${TAG_NAME}" + - name: Build + run: cargo build --release --locked --bin transcode + - name: Package assets + env: + TAG_NAME: ${{ github.ref_name }} + run: | + mkdir -p dist + cp target/release/transcode dist/transcode-linux-x86_64 + cp LICENSE-MIT README.md dist/ + tar -czf "dist/transcode-${TAG_NAME}-linux-x86_64.tar.gz" -C dist transcode-linux-x86_64 LICENSE-MIT README.md + (cd dist && sha256sum "transcode-${TAG_NAME}-linux-x86_64.tar.gz" > SHA256SUMS) + - name: Install cosign + uses: sigstore/cosign-installer@6f9f17788090df1f26f669e9d70d6ae9567deba6 # v4.1.2 + - name: Sign release artifacts (keyless Sigstore) + env: + TAG_NAME: ${{ github.ref_name }} + run: | + cd dist + for f in "transcode-${TAG_NAME}-linux-x86_64.tar.gz" SHA256SUMS; do + cosign sign-blob --yes \ + --certificate-oidc-issuer "https://token.actions.githubusercontent.com" \ + --certificate-identity-regexp \ + "^https://github.com/webfold-ai/transcode/\.github/workflows/release\.yml@refs/tags/${TAG_NAME//./\\.}$" \ + --output-signature "${f}.sig" \ + --output-certificate "${f}.cert" \ + "$f" + done + - name: Generate SLSA build provenance + id: attest + uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2 + with: + subject-path: "dist/transcode-*-linux-x86_64.tar.gz" + - name: Attach provenance bundle to the release assets + env: + BUNDLE_B64: ${{ steps.attest.outputs.bundle }} + TAG_NAME: ${{ github.ref_name }} + run: | + cd dist + echo "$BUNDLE_B64" | base64 -d > "transcode-${TAG_NAME}-linux-x86_64.tar.gz.intoto.jsonl" + - name: Create GitHub release + env: + GH_TOKEN: ${{ github.token }} + TAG_NAME: ${{ github.ref_name }} + run: | + cd dist + gh release create "$TAG_NAME" \ + "transcode-${TAG_NAME}-linux-x86_64.tar.gz" \ + "transcode-${TAG_NAME}-linux-x86_64.tar.gz.sig" \ + "transcode-${TAG_NAME}-linux-x86_64.tar.gz.cert" \ + "transcode-${TAG_NAME}-linux-x86_64.tar.gz.intoto.jsonl" \ + SHA256SUMS SHA256SUMS.sig SHA256SUMS.cert \ + --generate-notes diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml new file mode 100644 index 0000000..ed5b8c0 --- /dev/null +++ b/.github/workflows/scorecard.yml @@ -0,0 +1,45 @@ +name: Scorecard + +# OpenSSF Scorecard. Results are published so the README badge and the scorecard.dev +# page stay current. Requires the repository to be public for publishing to work. + +on: + branch_protection_rule: + schedule: + - cron: "20 7 * * 1" + push: + branches: [main] + workflow_dispatch: + +# Scorecard recommends read-all at the top level, and grants write only per job. +permissions: read-all + +jobs: + analysis: + name: Scorecard analysis + runs-on: ubuntu-latest + permissions: + contents: read + actions: read + security-events: write + id-token: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Run analysis + uses: ossf/scorecard-action@fa7117db83c52d787ae5a89f350999701505d78e # v2.5.0 + with: + results_file: results.sarif + results_format: sarif + publish_results: true + - name: Upload artifact + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: scorecard-sarif + path: results.sarif + retention-days: 5 + - name: Upload to code scanning + uses: github/codeql-action/upload-sarif@2892aa5e19bbd11bc0cff5427e3b750a04d9e3c2 # v4.38.2 + with: + sarif_file: results.sarif diff --git a/.github/workflows/supply-chain.yml b/.github/workflows/supply-chain.yml new file mode 100644 index 0000000..3f876bd --- /dev/null +++ b/.github/workflows/supply-chain.yml @@ -0,0 +1,114 @@ +name: Supply chain + +# RustSec advisories, dependency policy, and a CycloneDX SBOM. Scheduled daily so new +# advisories surface even when no code changes. + +on: + pull_request: + paths: + - "**/*.toml" + - "**/*.lock" + - "src/**" + - "tests/**" + - "deny.toml" + - ".github/workflows/supply-chain.yml" + push: + branches: [main] + schedule: + - cron: "13 6 * * *" + workflow_dispatch: + +permissions: + contents: read + +jobs: + audit: + name: RustSec audit + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master as of 2026-11-04 + with: + toolchain: stable + - name: Install cargo-audit + run: cargo install --locked cargo-audit + - name: Audit Cargo.lock + run: cargo audit --deny warnings + + deny: + name: Dependency policy + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master as of 2026-11-04 + with: + toolchain: stable + - name: Install cargo-deny + run: cargo install --locked cargo-deny --version 0.19.4 + - name: Check advisories, bans, licenses, sources + run: cargo deny check advisories bans licenses sources + + sbom: + name: CycloneDX SBOM + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master as of 2026-11-04 + with: + toolchain: stable + - name: Install cargo-cyclonedx + run: cargo install --locked cargo-cyclonedx + - name: Generate SBOM + run: cargo cyclonedx --format json --override-filename transcode.sbom + - name: Upload SBOM + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: transcode-cyclonedx-sbom + path: transcode.sbom.json + retention-days: 90 + + evidence: + name: Supply-chain evidence record + if: always() + needs: [audit, deny, sbom] + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Write evidence record + env: + AUDIT_RESULT: ${{ needs.audit.result }} + DENY_RESULT: ${{ needs.deny.result }} + SBOM_RESULT: ${{ needs.sbom.result }} + REPOSITORY: ${{ github.repository }} + run: | + mkdir -p evidence + python3 - <<'PY' + import json, os + from datetime import datetime, timezone + payload = { + "event": "ptyktos.supply_chain.audit", + "ts": datetime.now(timezone.utc).isoformat(), + "repo": os.environ["REPOSITORY"], + "audit": os.environ["AUDIT_RESULT"], + "deny": os.environ["DENY_RESULT"], + "sbom": os.environ["SBOM_RESULT"], + "sbom_path": "transcode.sbom.json", + } + with open("evidence/supply-chain.json", "w") as f: + json.dump(payload, f, indent=2) + f.write("\n") + PY + - name: Upload evidence record + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: supply-chain-evidence + path: evidence/supply-chain.json + retention-days: 90 diff --git a/deny.toml b/deny.toml new file mode 100644 index 0000000..54a377b --- /dev/null +++ b/deny.toml @@ -0,0 +1,42 @@ +# cargo-deny policy for transcode. +# +# Run from the repository root: +# cargo deny check advisories bans licenses sources +# +# transcode has no git dependencies. Anything added from a git or unknown registry +# source is denied on purpose; add an explicit, reviewed exception here if one is +# ever needed. + +[graph] +all-features = true + +[advisories] +version = 2 +yanked = "deny" +ignore = [] + +[licenses] +version = 2 +confidence-threshold = 0.9 +allow = [ + "MIT", + "Apache-2.0", +] + +[licenses.private] +ignore = false +registries = [] + +[bans] +multiple-versions = "warn" +wildcards = "deny" +highlight = "all" +deny = [] +skip = [] +skip-tree = [] + +[sources] +unknown-registry = "deny" +unknown-git = "deny" +allow-registry = ["https://github.com/rust-lang/crates.io-index"] +allow-git = [] diff --git a/fuzz/.gitignore b/fuzz/.gitignore new file mode 100644 index 0000000..1a45eee --- /dev/null +++ b/fuzz/.gitignore @@ -0,0 +1,4 @@ +target +corpus +artifacts +coverage diff --git a/fuzz/Cargo.lock b/fuzz/Cargo.lock new file mode 100644 index 0000000..ccabd48 --- /dev/null +++ b/fuzz/Cargo.lock @@ -0,0 +1,94 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "arbitrary" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed" + +[[package]] +name = "cc" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "375989decec1a0fa424442bed520fa12ede43a48475ce8c7417d2c69b32b5f6b" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom", + "libc", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libfuzzer-sys" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9fd2f41a1cba099f79a0b6b6c35656cf7c03351a7bae8ff0f28f25270f929d2" +dependencies = [ + "arbitrary", + "cc", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "transcode" +version = "0.1.0" + +[[package]] +name = "transcode-fuzz" +version = "0.0.0" +dependencies = [ + "libfuzzer-sys", + "transcode", +] diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml new file mode 100644 index 0000000..e3a4d43 --- /dev/null +++ b/fuzz/Cargo.toml @@ -0,0 +1,67 @@ +[package] +name = "transcode-fuzz" +version = "0.0.0" +edition = "2021" +publish = false + +[package.metadata] +cargo-fuzz = true + +[dependencies] +libfuzzer-sys = "0.4" + +[dependencies.transcode] +path = ".." + +# Standalone workspace so the fuzz crate does not join the transcode package's workspace. +[workspace] +members = ["."] + +[[bin]] +name = "fuzz_png" +path = "fuzz_targets/fuzz_png.rs" +test = false +doc = false +bench = false + +[[bin]] +name = "fuzz_jpeg" +path = "fuzz_targets/fuzz_jpeg.rs" +test = false +doc = false +bench = false + +[[bin]] +name = "fuzz_flac" +path = "fuzz_targets/fuzz_flac.rs" +test = false +doc = false +bench = false + +[[bin]] +name = "fuzz_slac" +path = "fuzz_targets/fuzz_slac.rs" +test = false +doc = false +bench = false + +[[bin]] +name = "fuzz_mp3" +path = "fuzz_targets/fuzz_mp3.rs" +test = false +doc = false +bench = false + +[[bin]] +name = "fuzz_aac" +path = "fuzz_targets/fuzz_aac.rs" +test = false +doc = false +bench = false + +[[bin]] +name = "fuzz_opus" +path = "fuzz_targets/fuzz_opus.rs" +test = false +doc = false +bench = false diff --git a/fuzz/fuzz_targets/fuzz_aac.rs b/fuzz/fuzz_targets/fuzz_aac.rs new file mode 100644 index 0000000..5b23c86 --- /dev/null +++ b/fuzz/fuzz_targets/fuzz_aac.rs @@ -0,0 +1,9 @@ +//! Untrusted input: ADTS/AAC-LC parsing and full PCM decode. +#![no_main] + +use libfuzzer_sys::fuzz_target; + +fuzz_target!(|data: &[u8]| { + let _ = transcode::aac::parse(data); + let _ = transcode::aac::decode_pcm(data); +}); diff --git a/fuzz/fuzz_targets/fuzz_flac.rs b/fuzz/fuzz_targets/fuzz_flac.rs new file mode 100644 index 0000000..0ddb467 --- /dev/null +++ b/fuzz/fuzz_targets/fuzz_flac.rs @@ -0,0 +1,8 @@ +//! Untrusted input: any bytes are handed to the FLAC decoder. +#![no_main] + +use libfuzzer_sys::fuzz_target; + +fuzz_target!(|data: &[u8]| { + let _ = transcode::flac::decode(data); +}); diff --git a/fuzz/fuzz_targets/fuzz_jpeg.rs b/fuzz/fuzz_targets/fuzz_jpeg.rs new file mode 100644 index 0000000..b04d448 --- /dev/null +++ b/fuzz/fuzz_targets/fuzz_jpeg.rs @@ -0,0 +1,8 @@ +//! Untrusted input: any bytes are handed to the baseline JPEG decoder. +#![no_main] + +use libfuzzer_sys::fuzz_target; + +fuzz_target!(|data: &[u8]| { + let _ = transcode::jpeg::decode(data); +}); diff --git a/fuzz/fuzz_targets/fuzz_mp3.rs b/fuzz/fuzz_targets/fuzz_mp3.rs new file mode 100644 index 0000000..7343321 --- /dev/null +++ b/fuzz/fuzz_targets/fuzz_mp3.rs @@ -0,0 +1,9 @@ +//! Untrusted input: MPEG Layer III parsing and full PCM decode. +#![no_main] + +use libfuzzer_sys::fuzz_target; + +fuzz_target!(|data: &[u8]| { + let _ = transcode::mp3::parse(data); + let _ = transcode::mp3::decode_pcm(data); +}); diff --git a/fuzz/fuzz_targets/fuzz_opus.rs b/fuzz/fuzz_targets/fuzz_opus.rs new file mode 100644 index 0000000..7661f07 --- /dev/null +++ b/fuzz/fuzz_targets/fuzz_opus.rs @@ -0,0 +1,15 @@ +//! Untrusted input: Ogg demux, OpusHead parse and TOC parse. Full Opus decode is not implemented yet (ROADMAP.md), so it is not fuzzed here. +#![no_main] + +use libfuzzer_sys::fuzz_target; + +fuzz_target!(|data: &[u8]| { + let _ = transcode::opus::parse(data); + if let Ok(packets) = transcode::opus::demux_ogg(data) { + for p in packets.iter().take(64) { + if let Some(&toc) = p.data.first() { + let _ = transcode::opus::parse_toc(toc); + } + } + } +}); diff --git a/fuzz/fuzz_targets/fuzz_png.rs b/fuzz/fuzz_targets/fuzz_png.rs new file mode 100644 index 0000000..aa6e43b --- /dev/null +++ b/fuzz/fuzz_targets/fuzz_png.rs @@ -0,0 +1,8 @@ +//! Untrusted input: any bytes are handed to the PNG decoder. It must return Ok or Err and never panic, overflow or hang. +#![no_main] + +use libfuzzer_sys::fuzz_target; + +fuzz_target!(|data: &[u8]| { + let _ = transcode::png::decode(data); +}); diff --git a/fuzz/fuzz_targets/fuzz_slac.rs b/fuzz/fuzz_targets/fuzz_slac.rs new file mode 100644 index 0000000..d1c4cb4 --- /dev/null +++ b/fuzz/fuzz_targets/fuzz_slac.rs @@ -0,0 +1,8 @@ +//! Untrusted input: any bytes are handed to the SLAC (lossless container) decoder. +#![no_main] + +use libfuzzer_sys::fuzz_target; + +fuzz_target!(|data: &[u8]| { + let _ = transcode::codec::decode(data); +}); From 4099b916436456eb92f0ba170118a89bb8fb6cc6 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 4 Nov 2026 23:01:19 +0000 Subject: [PATCH 06/11] fix(release): sign with cosign bundles and copy the attestation by bundle-path - cosign sign-blob --bundle writes one .sigstore.json per asset. The previous --output-signature/--output-certificate flags are verify-blob options and do not belong on sign-blob, and the identity check moves to the verify command. - The provenance bundle is taken from the attest step's bundle-path output and copied as the .intoto.jsonl asset, instead of base64-decoding an output. - Release assets now list the two .sigstore.json bundles in place of the .sig and .cert pairs. SUPPLY-CHAIN.md's verification command is updated to --bundle with the identity and issuer checks. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Ch6Crfubj3FwdxR7ywn9vT --- .github/workflows/release.yml | 27 ++++++++++----------------- docs/OPENSSF.md | 2 +- docs/SUPPLY-CHAIN.md | 6 +++--- 3 files changed, 14 insertions(+), 21 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 65a5478..7b9e20b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -52,32 +52,26 @@ jobs: (cd dist && sha256sum "transcode-${TAG_NAME}-linux-x86_64.tar.gz" > SHA256SUMS) - name: Install cosign uses: sigstore/cosign-installer@6f9f17788090df1f26f669e9d70d6ae9567deba6 # v4.1.2 - - name: Sign release artifacts (keyless Sigstore) - env: - TAG_NAME: ${{ github.ref_name }} + - name: Sign release artifacts (keyless Sigstore bundles) run: | cd dist for f in "transcode-${TAG_NAME}-linux-x86_64.tar.gz" SHA256SUMS; do - cosign sign-blob --yes \ - --certificate-oidc-issuer "https://token.actions.githubusercontent.com" \ - --certificate-identity-regexp \ - "^https://github.com/webfold-ai/transcode/\.github/workflows/release\.yml@refs/tags/${TAG_NAME//./\\.}$" \ - --output-signature "${f}.sig" \ - --output-certificate "${f}.cert" \ - "$f" + cosign sign-blob --yes --bundle "${f}.sigstore.json" "$f" done + env: + TAG_NAME: ${{ github.ref_name }} - name: Generate SLSA build provenance id: attest uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2 with: subject-path: "dist/transcode-*-linux-x86_64.tar.gz" - - name: Attach provenance bundle to the release assets + - name: Copy provenance bundle to the release assets env: - BUNDLE_B64: ${{ steps.attest.outputs.bundle }} + BUNDLE_PATH: ${{ steps.attest.outputs.bundle-path }} TAG_NAME: ${{ github.ref_name }} run: | - cd dist - echo "$BUNDLE_B64" | base64 -d > "transcode-${TAG_NAME}-linux-x86_64.tar.gz.intoto.jsonl" + test -s "$BUNDLE_PATH" + cp "$BUNDLE_PATH" "dist/transcode-${TAG_NAME}-linux-x86_64.tar.gz.intoto.jsonl" - name: Create GitHub release env: GH_TOKEN: ${{ github.token }} @@ -86,8 +80,7 @@ jobs: cd dist gh release create "$TAG_NAME" \ "transcode-${TAG_NAME}-linux-x86_64.tar.gz" \ - "transcode-${TAG_NAME}-linux-x86_64.tar.gz.sig" \ - "transcode-${TAG_NAME}-linux-x86_64.tar.gz.cert" \ + "transcode-${TAG_NAME}-linux-x86_64.tar.gz.sigstore.json" \ "transcode-${TAG_NAME}-linux-x86_64.tar.gz.intoto.jsonl" \ - SHA256SUMS SHA256SUMS.sig SHA256SUMS.cert \ + SHA256SUMS SHA256SUMS.sigstore.json \ --generate-notes diff --git a/docs/OPENSSF.md b/docs/OPENSSF.md index 0672075..c852138 100644 --- a/docs/OPENSSF.md +++ b/docs/OPENSSF.md @@ -13,7 +13,7 @@ that a score has been earned. | Pinned-Dependencies | Every `uses:` is a full commit SHA. Tags are verified with `git ls-remote` (see docs/SUPPLY-CHAIN.md). `cargo` dependencies are pinned by `Cargo.lock`. | In repo; Verified for the SHAs listed in SUPPLY-CHAIN.md | | SAST | `codeql.yml` (Rust, `security-extended`) and `cargo clippy -D warnings` in CI | In repo | | Fuzzing | `fuzz/` with seven libFuzzer targets (`libfuzzer_sys` marker) and `fuzz.yml` (pull requests and daily) | In repo; targets compile on stable (`cargo check`). No long campaign run yet | -| Signed-Releases | `release.yml`: cosign keyless signatures (`.sig`, `.cert`), SLSA provenance (`.intoto.jsonl`) | In repo; not yet exercised by a real tag | +| Signed-Releases | `release.yml`: cosign keyless signing bundles (`.sigstore.json`), SLSA provenance (`.intoto.jsonl`) | In repo; not yet exercised by a real tag | | Packaging | Not applicable yet. The crate sets no `publish` flag. Release assets are GitHub release tarballs, not a package registry | Human (decide whether to publish to crates.io) | | Branch-Protection | Ruleset (see below) | Human. Not applied | | CI-Tests | `ci.yml` runs build, tests (with ffmpeg), fmt and clippy on every pull request | In repo | diff --git a/docs/SUPPLY-CHAIN.md b/docs/SUPPLY-CHAIN.md index 8779191..afdf745 100644 --- a/docs/SUPPLY-CHAIN.md +++ b/docs/SUPPLY-CHAIN.md @@ -68,7 +68,8 @@ contains: - `transcode-vX.Y.Z-linux-x86_64.tar.gz`, the CLI binary with `LICENSE-MIT` and `README.md`, - `SHA256SUMS`, with a sha256 for the tarball, -- `.sig` and `.cert` files from cosign keyless signing (identity: the release workflow at the tag), +- `.sigstore.json` bundles from cosign keyless signing (one each for the tarball and `SHA256SUMS`), + containing the signature, the certificate and the transparency-log proof, - `.intoto.jsonl`, the SLSA build-provenance attestation. How to verify a downloaded release (replace `v0.1.0` with the version you downloaded): @@ -77,8 +78,7 @@ How to verify a downloaded release (replace `v0.1.0` with the version you downlo sha256sum -c SHA256SUMS cosign verify-blob \ - --certificate transcode-v0.1.0-linux-x86_64.tar.gz.cert \ - --signature transcode-v0.1.0-linux-x86_64.tar.gz.sig \ + --bundle transcode-v0.1.0-linux-x86_64.tar.gz.sigstore.json \ --certificate-identity-regexp '^https://github.com/webfold-ai/transcode/\.github/workflows/release\.yml@refs/tags/v0\.1\.0$' \ --certificate-oidc-issuer https://token.actions.githubusercontent.com \ transcode-v0.1.0-linux-x86_64.tar.gz From 2cd5f4bf790b96ae8518d8fcf59950a5b3067f56 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 4 Nov 2026 23:13:31 +0000 Subject: [PATCH 07/11] style: apply rustfmt to the whole crate The crate was never run through rustfmt: cargo fmt --check reported about 700 hunks. This commit is formatting only. Tests and clippy are unchanged. The next commit's diff can be read without this noise by ignoring whitespace-only changes (git log -p --ignore-all-space). Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Ch6Crfubj3FwdxR7ywn9vT --- src/aac.rs | 286 ++++++++++++++---- src/aac_tables.rs | 430 ++++++++++++-------------- src/av1_coef.rs | 87 ++++-- src/av1_coef_tables.rs | 144 ++++++++- src/av1_dct.rs | 10 +- src/av1_ec.rs | 33 +- src/av1_frame.rs | 46 ++- src/av1_intra.rs | 47 ++- src/av1_obu.rs | 45 ++- src/codec.rs | 55 +++- src/flac.rs | 243 ++++++++++++--- src/h264.rs | 30 +- src/h264_i4x4.rs | 191 +++++++++--- src/h264_inter.rs | 19 +- src/h264_intra.rs | 597 ++++++++++++++++++++++++++++-------- src/h264bits.rs | 12 +- src/heif.rs | 31 +- src/jpeg.rs | 292 +++++++++++++----- src/lib.rs | 14 +- src/main.rs | 468 ++++++++++++++++++++++------ src/mp3.rs | 501 +++++++++++++++++++++++------- src/mp3_tables.rs | 653 ++++++++++++++++++++++++++++++++-------- src/mp4.rs | 16 +- src/opus.rs | 551 ++++++++++++++++++++++++++++----- src/opus_tables.rs | 334 +++++++++++++------- src/png.rs | 29 +- src/webp.rs | 24 +- tests/av1_coeff.rs | 85 +++++- tests/av1_decode.rs | 34 ++- tests/av1_gencoef.rs | 122 ++++++-- tests/av1_msac_trace.rs | 85 ++++-- tests/h264_bitexact.rs | 69 +++-- 32 files changed, 4258 insertions(+), 1325 deletions(-) diff --git a/src/aac.rs b/src/aac.rs index 0ebd6c0..b0013cf 100644 --- a/src/aac.rs +++ b/src/aac.rs @@ -16,8 +16,9 @@ use crate::aac_tables; /// ISO sampling-frequency table (index → Hz), 14496-3 Table 1.16. -pub const SAMPLE_RATES: [u32; 13] = - [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350]; +pub const SAMPLE_RATES: [u32; 13] = [ + 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350, +]; /// channel_configuration → channel count (0 = defined by PCE; we treat as 0). pub const CHANNEL_CONFIG: [u16; 8] = [0, 1, 2, 3, 4, 5, 6, 8]; @@ -42,7 +43,11 @@ impl<'a> Bits<'a> { for _ in 0..n { let byte = self.pos >> 3; let bit = 7 - (self.pos & 7); - let b = if byte < self.data.len() { (self.data[byte] >> bit) & 1 } else { 0 }; + let b = if byte < self.data.len() { + (self.data[byte] >> bit) & 1 + } else { + 0 + }; v = (v << 1) | b as u32; self.pos += 1; } @@ -63,14 +68,14 @@ impl<'a> Bits<'a> { #[derive(Clone, Copy, Debug)] pub struct AdtsHeader { - pub mpeg4: bool, // ID bit: false = MPEG-4, true = MPEG-2 + pub mpeg4: bool, // ID bit: false = MPEG-4, true = MPEG-2 pub protection_absent: bool, - pub profile: u8, // object_type - 1 (LC = 1) + pub profile: u8, // object_type - 1 (LC = 1) pub sf_index: u8, pub channel_config: u8, - pub frame_length: usize, // total frame incl. header, bytes - pub num_blocks: u8, // raw_data_blocks in frame - 1 - pub header_len: usize, // 7 (no CRC) or 9 (CRC) + pub frame_length: usize, // total frame incl. header, bytes + pub num_blocks: u8, // raw_data_blocks in frame - 1 + pub header_len: usize, // 7 (no CRC) or 9 (CRC) } /// Parse an ADTS header at byte offset `o`. Returns None if no valid syncword. @@ -250,7 +255,11 @@ pub fn huffman_selftest() -> i32 { " cb{cb:<2} {:>3} symbols, max {} bits {}", codes.len(), lens.iter().max().unwrap(), - if bad == 0 { "[ok]".to_string() } else { format!("[{bad} BAD]") } + if bad == 0 { + "[ok]".to_string() + } else { + format!("[{bad} BAD]") + } ); } let (sfc, sfl) = (&aac_tables::SF_CODES, &aac_tables::SF_BITS); @@ -263,7 +272,11 @@ pub fn huffman_selftest() -> i32 { " sf {:>3} symbols, max {} bits {}", sfc.len(), sfl.iter().max().unwrap(), - if bad == 0 { "[ok]".to_string() } else { format!("[{bad} BAD]") } + if bad == 0 { + "[ok]".to_string() + } else { + format!("[{bad} BAD]") + } ); if fails == 0 { println!("aac huffman: all {total} codewords round-trip (valid prefix codes)"); @@ -292,8 +305,8 @@ pub struct Ics { pub max_sfb: usize, pub num_windows: usize, pub num_window_groups: usize, - pub group_len: Vec, // windows per group - pub swb_offset: Vec, // sfb boundaries within one window + pub group_len: Vec, // windows per group + pub swb_offset: Vec, // sfb boundaries within one window pub num_swb: usize, } @@ -324,7 +337,11 @@ fn decode_ics_info(b: &mut Bits, sr: usize) -> Result { b.bit(); // ics_reserved_bit let window_sequence = b.bits(2); let window_shape = b.bit(); - let mut ics = Ics { window_sequence, window_shape, ..Default::default() }; + let mut ics = Ics { + window_sequence, + window_shape, + ..Default::default() + }; if window_sequence == EIGHT_SHORT { ics.max_sfb = b.bits(4) as usize; let sfg = b.bits(7); @@ -361,7 +378,11 @@ fn decode_ics_info(b: &mut Bits, sr: usize) -> Result { } fn decode_section(b: &mut Bits, ics: &Ics) -> Vec { - let bits_incr = if ics.window_sequence == EIGHT_SHORT { 3 } else { 5 }; + let bits_incr = if ics.window_sequence == EIGHT_SHORT { + 3 + } else { + 5 + }; let esc = (1u32 << bits_incr) - 1; let mut cb = vec![0u8; ics.num_window_groups * ics.max_sfb]; for g in 0..ics.num_window_groups { @@ -390,7 +411,12 @@ fn decode_section(b: &mut Bits, ics: &Ics) -> Vec { cb } -fn decode_scalefactors(b: &mut Bits, ics: &Ics, cb: &[u8], global_gain: u32) -> Result, String> { +fn decode_scalefactors( + b: &mut Bits, + ics: &Ics, + cb: &[u8], + global_gain: u32, +) -> Result, String> { let mut sf = vec![0i32; ics.num_window_groups * ics.max_sfb]; let mut off_sf = global_gain as i32; let mut off_is = 0i32; @@ -535,7 +561,9 @@ fn decode_tns(b: &mut Bits, ics: &Ics) -> Tns { } else { (2, 6, 5) }; - let mut tns = Tns { filt: vec![Vec::new(); ics.num_windows] }; + let mut tns = Tns { + filt: vec![Vec::new(); ics.num_windows], + }; for w in 0..ics.num_windows { let n_filt = b.bits(nf_bits); if n_filt > 0 { @@ -544,7 +572,11 @@ fn decode_tns(b: &mut Bits, ics: &Ics) -> Tns { for _ in 0..n_filt { let length = b.bits(len_bits) as usize; let order = b.bits(ord_bits) as usize; - let mut f = TnsFilter { length, order, ..Default::default() }; + let mut f = TnsFilter { + length, + order, + ..Default::default() + }; if order > 0 { f.direction = b.bit() == 1; let coef_compress = b.bit(); @@ -554,7 +586,11 @@ fn decode_tns(b: &mut Bits, ics: &Ics) -> Tns { let iqfac_m = ((1i32 << (coef_res_bits - 1)) as f64 + 0.5) / (PI / 2.0); for _ in 0..order { let raw = b.bits(coef_bits) as i32; - let c = if raw >= (1 << (coef_bits - 1)) { raw - (1 << coef_bits) } else { raw }; + let c = if raw >= (1 << (coef_bits - 1)) { + raw - (1 << coef_bits) + } else { + raw + }; let p = (c as f64 / if c >= 0 { iqfac } else { iqfac_m }).sin(); f.parcor.push(p); } @@ -596,9 +632,16 @@ fn apply_tns(spec: &mut [f64], ics: &Ics, tns: &Tns) { if size == 0 { continue; } - let woff = if ics.window_sequence == EIGHT_SHORT { w * 128 } else { 0 }; - let (mut p, inc): (isize, isize) = - if f.direction { ((woff + end - 1) as isize, -1) } else { ((woff + start) as isize, 1) }; + let woff = if ics.window_sequence == EIGHT_SHORT { + w * 128 + } else { + 0 + }; + let (mut p, inc): (isize, isize) = if f.direction { + ((woff + end - 1) as isize, -1) + } else { + ((woff + start) as isize, 1) + }; for m in 0..size { let lim = m.min(order); let mut acc = spec[p as usize]; @@ -644,7 +687,11 @@ fn parse_ics(b: &mut Bits, sr: usize, common: Option<&Ics>, dbg: bool) -> Result if dbg { eprintln!(" after pulse @bit {}", b.pos); } - let tns = if b.bit() == 1 { decode_tns(b, &ics) } else { Tns::default() }; + let tns = if b.bit() == 1 { + decode_tns(b, &ics) + } else { + Tns::default() + }; if dbg { eprintln!(" after tns @bit {}", b.pos); } @@ -655,12 +702,24 @@ fn parse_ics(b: &mut Bits, sr: usize, common: Option<&Ics>, dbg: bool) -> Result if dbg { eprintln!(" after spectral @bit {} ncoef={}", b.pos, coef.len()); } - Ok(Channel { ics, global_gain, cb, sf, coef, tns }) + Ok(Channel { + ics, + global_gain, + cb, + sf, + coef, + tns, + }) } /// Parse one raw_data_block: the element sequence terminated by ID_END. /// `ms` collects (num_groups, max_sfb, ms_used bits) per CPE for stereo. -fn parse_raw_data_block(b: &mut Bits, sr: usize, ms: &mut Vec>, dbg: bool) -> Result, String> { +fn parse_raw_data_block( + b: &mut Bits, + sr: usize, + ms: &mut Vec>, + dbg: bool, +) -> Result, String> { let mut chans = Vec::new(); loop { let id = b.bits(3); @@ -787,7 +846,9 @@ pub fn align_check(data: &[u8]) -> Result { } else { format!("; first mismatch — {first_err}") }; - Ok(format!("{aligned}/{frames} frames byte-exact aligned ({errs} mismatched){tail}")) + Ok(format!( + "{aligned}/{frames} frames byte-exact aligned ({errs} mismatched){tail}" + )) } /// Count feature usage across the stream (to characterize decode residuals). @@ -842,7 +903,12 @@ pub fn debug_frame(data: &[u8]) -> Result { let mut b = Bits::at(data, h.header_len * 8); let mut ms = Vec::new(); let r = parse_raw_data_block(&mut b, h.sf_index as usize, &mut ms, true); - Ok(format!("result={:?} ended @bit {} (want {})", r.map(|c| c.len()), b.pos, frame_end)) + Ok(format!( + "result={:?} ended @bit {} (want {})", + r.map(|c| c.len()), + b.pos, + frame_end + )) } // ═══════════════════════════════════════════════════════════════════════════ @@ -902,7 +968,9 @@ pub fn kbd_window(n: usize, alpha: f64) -> Vec { /// Sine window of length `n`: W[k] = sin( π/N (k + 1/2) ). pub fn sine_window(n: usize) -> Vec { - (0..n).map(|k| (PI / n as f64 * (k as f64 + 0.5)).sin()).collect() + (0..n) + .map(|k| (PI / n as f64 * (k as f64 + 0.5)).sin()) + .collect() } /// In-place radix-2 FFT, positive sign, no normalization: @@ -975,7 +1043,10 @@ fn mdct_twiddles(n: usize) -> &'static Twiddles { use std::collections::HashMap; use std::sync::{Mutex, OnceLock}; static CACHE: OnceLock>> = OnceLock::new(); - let mut map = CACHE.get_or_init(|| Mutex::new(HashMap::new())).lock().unwrap(); + let mut map = CACHE + .get_or_init(|| Mutex::new(HashMap::new())) + .lock() + .unwrap(); if let Some(t) = map.get(&n) { return t; } @@ -1003,7 +1074,14 @@ fn mdct_twiddles(n: usize) -> &'static Twiddles { p_im[nn] = i; } let leaked: &'static Twiddles = Box::leak(Box::new(Twiddles { - b_re, b_im, a_re, a_im, p_re, p_im, wp_re, wp_im, + b_re, + b_im, + a_re, + a_im, + p_re, + p_im, + wp_re, + wp_im, })); map.insert(n, leaked); leaked @@ -1021,7 +1099,9 @@ fn fast_imdct_core(spec: &[f64]) -> Vec { yi[k] = spec[k] * tw.b_im[k]; } fft_pos(&mut yr, &mut yi); - (0..n).map(|nn| tw.a_re[nn] * yr[nn] - tw.a_im[nn] * yi[nn]).collect() + (0..n) + .map(|nn| tw.a_re[nn] * yr[nn] - tw.a_im[nn] * yi[nn]) + .collect() } /// Forward MDCT cosine sum (length N → M), canonical phase, via one N-point FFT. @@ -1035,7 +1115,9 @@ fn fast_mdct_core(time: &[f64]) -> Vec { zi[nn] = time[nn] * tw.p_im[nn]; } fft_pos(&mut zr, &mut zi); - (0..m).map(|k| tw.wp_re[k] * zr[k] - tw.wp_im[k] * zi[k]).collect() + (0..m) + .map(|k| tw.wp_re[k] * zr[k] - tw.wp_im[k] * zi[k]) + .collect() } #[inline] @@ -1111,7 +1193,11 @@ pub fn mdct_probe() -> i32 { ((n / 2 + 1) as f64 / 2.0, "(N/2+1)/2=same"), ((n as f64) / 2.0 + 0.5, "N/2+0.5"), ]; - let candidates_scale = [(2.0 / n as f64, "2/N"), (2.0 / half as f64, "2/L=4/N"), (1.0 / half as f64, "1/L")]; + let candidates_scale = [ + (2.0 / n as f64, "2/N"), + (2.0 / half as f64, "2/L=4/N"), + (1.0 / half as f64, "1/L"), + ]; for (n0, n0name) in candidates_n0 { for (scale, sname) in candidates_scale { let mut recon = vec![0.0f64; total]; @@ -1125,7 +1211,9 @@ pub fn mdct_probe() -> i32 { } h += half; } - let err = (n..total - n).map(|i| (recon[i] - sig[i]).abs()).fold(0.0, f64::max); + let err = (n..total - n) + .map(|i| (recon[i] - sig[i]).abs()) + .fold(0.0, f64::max); let db = 20.0 * err.max(1e-300).log10(); println!(" n0={n0name:<14} scale={sname:<8} → {db:>8.1} dB"); } @@ -1156,7 +1244,11 @@ pub fn fft_check() -> i32 { let mut di = 0.0f64; for nn in 0..n { let a = nn as f64 + n0; - let naive: f64 = spec.iter().enumerate().map(|(k, &s)| s * (PI / m as f64 * a * (k as f64 + 0.5)).cos()).sum(); + let naive: f64 = spec + .iter() + .enumerate() + .map(|(k, &s)| s * (PI / m as f64 * a * (k as f64 + 0.5)).cos()) + .sum(); di = di.max((fast[nn] - naive).abs()); } // MDCT: fast core vs direct cosine sum @@ -1164,12 +1256,20 @@ pub fn fft_check() -> i32 { let fastf = fast_mdct_core(&time); let mut df = 0.0f64; for k in 0..m { - let naive: f64 = time.iter().enumerate().map(|(nn, &t)| t * (PI / m as f64 * (nn as f64 + n0) * (k as f64 + 0.5)).cos()).sum(); + let naive: f64 = time + .iter() + .enumerate() + .map(|(nn, &t)| t * (PI / m as f64 * (nn as f64 + n0) * (k as f64 + 0.5)).cos()) + .sum(); df = df.max((fastf[k] - naive).abs()); } worst = worst.max(di).max(df); let to_db = |e: f64| 20.0 * e.max(1e-300).log10(); - println!(" N={n:<5} IMDCT err {di:.2e} ({:>7.1} dB) MDCT err {df:.2e} ({:>7.1} dB)", to_db(di), to_db(df)); + println!( + " N={n:<5} IMDCT err {di:.2e} ({:>7.1} dB) MDCT err {df:.2e} ({:>7.1} dB)", + to_db(di), + to_db(df) + ); } if worst < 1e-6 { println!("aac FFT cores: match direct cosine sum (worst {worst:.2e}) [ok]"); @@ -1186,7 +1286,9 @@ pub fn imdct_bench() -> i32 { use std::time::Instant; let spec: Vec = (0..1024).map(|k| (k as f64 * 0.0173).sin()).collect(); // warm - for _ in 0..1000 { let _ = fast_imdct_core(&spec); } + for _ in 0..1000 { + let _ = fast_imdct_core(&spec); + } let iters = 100_000usize; let t0 = Instant::now(); let mut sink = 0.0f64; @@ -1197,13 +1299,15 @@ pub fn imdct_bench() -> i32 { let dt = t0.elapsed().as_secs_f64(); let us = dt * 1e6 / iters as f64; let mhz = (1024.0 / us) as i64; // Msamp/s of spec consumed - // For 10s @16k decode budget context (1024-hop): 160000/1024 ≈ 156 frames. + // For 10s @16k decode budget context (1024-hop): 160000/1024 ≈ 156 frames. let frames_10s = 156.0; let imdct_share_ms = us * frames_10s / 1000.0; println!("fast_imdct_core(spec[1024]): {us:.2} µs/call ({mhz} Msamp/s) [sink={sink:.3e}]"); println!("for 10s @16k mono (156 long frames): IMDCT alone = {imdct_share_ms:.2} ms"); - println!("(compare to measured full decode 26.89 ms → IMDCT is ~{:.0}% of decode)", - 100.0 * imdct_share_ms / 26.89); + println!( + "(compare to measured full decode 26.89 ms → IMDCT is ~{:.0}% of decode)", + 100.0 * imdct_share_ms / 26.89 + ); 0 } @@ -1290,7 +1394,11 @@ fn dequant_table() -> &'static [f64; 8192] { #[inline] fn dequant(q: i32) -> f64 { let a = dequant_table()[(q.unsigned_abs() as usize).min(8191)]; - if q < 0 { -a } else { a } + if q < 0 { + -a + } else { + a + } } /// Precomputed analysis windows (sine + KBD, long + short). @@ -1319,7 +1427,10 @@ struct ChanState { } impl Default for ChanState { fn default() -> Self { - ChanState { overlap: [0.0; 1024], prev_kbd: false } + ChanState { + overlap: [0.0; 1024], + prev_kbd: false, + } } } @@ -1341,7 +1452,11 @@ fn reconstruct(ch: &Channel) -> Vec { let gain = 2f64.powf(0.25 * (sf - 100) as f64); let off = ics.swb_offset[s]; for w in 0..ics.group_len[g] { - let base = if ics.window_sequence == EIGHT_SHORT { (win_start + w) * 128 } else { 0 }; + let base = if ics.window_sequence == EIGHT_SHORT { + (win_start + w) * 128 + } else { + 0 + }; for k in 0..width { let q = ch.coef[ci]; ci += 1; @@ -1369,7 +1484,11 @@ fn apply_ms(ics: &Ics, ms_used: &[bool], spectra: &mut [Vec]) { let off = ics.swb_offset[s]; let width = ics.swb_offset[s + 1] - off; for w in 0..ics.group_len[g] { - let base = if ics.window_sequence == EIGHT_SHORT { (win_start + w) * 128 } else { 0 }; + let base = if ics.window_sequence == EIGHT_SHORT { + (win_start + w) * 128 + } else { + 0 + }; for k in 0..width { let p = base + off + k; let (m, sd) = (s0[p], s1[p]); @@ -1384,10 +1503,26 @@ fn apply_ms(ics: &Ics, ms_used: &[bool], spectra: &mut [Vec]) { /// Build the 2048-point synthesis window for a long-type block, honouring the /// window_sequence transitions (START/STOP) and per-half window shape. fn make_long_window(ws: u32, prev_kbd: bool, curr_kbd: bool, dsp: &Dsp) -> Vec { - let ll = if prev_kbd { &dsp.kbd_long } else { &dsp.sine_long }; - let lr = if curr_kbd { &dsp.kbd_long } else { &dsp.sine_long }; - let sl = if prev_kbd { &dsp.kbd_short } else { &dsp.sine_short }; - let sr = if curr_kbd { &dsp.kbd_short } else { &dsp.sine_short }; + let ll = if prev_kbd { + &dsp.kbd_long + } else { + &dsp.sine_long + }; + let lr = if curr_kbd { + &dsp.kbd_long + } else { + &dsp.sine_long + }; + let sl = if prev_kbd { + &dsp.kbd_short + } else { + &dsp.sine_short + }; + let sr = if curr_kbd { + &dsp.kbd_short + } else { + &dsp.sine_short + }; let mut w = vec![0f64; 2048]; match ws { EIGHT_SHORT => {} // handled separately @@ -1422,7 +1557,11 @@ fn make_long_window(ws: u32, prev_kbd: bool, curr_kbd: bool, dsp: &Dsp) -> Vec Vec { let mut buf = vec![0f64; 2048]; if ws == EIGHT_SHORT { - let sw = if curr_kbd { &dsp.kbd_short } else { &dsp.sine_short }; + let sw = if curr_kbd { + &dsp.kbd_short + } else { + &dsp.sine_short + }; for i in 0..8 { let t = imdct(&spec[i * 128..i * 128 + 128]); for j in 0..256 { @@ -1483,7 +1622,10 @@ pub fn synth_pr_test() -> i32 { sigp += (g * sig[i]).powi(2); } let db = 10.0 * (err / sigp).max(1e-300).log10(); - println!("decode-path gain G={g:.4} (1/G={:.4}) residual={db:.1} dB", 1.0 / g); + println!( + "decode-path gain G={g:.4} (1/G={:.4}) residual={db:.1} dB", + 1.0 / g + ); if db < -60.0 { println!("OLA reconstructs cleanly; divide synth by G to match unity"); 0 @@ -1563,7 +1705,10 @@ struct BitWriter { } impl BitWriter { fn new() -> Self { - BitWriter { buf: Vec::new(), nbits: 0 } + BitWriter { + buf: Vec::new(), + nbits: 0, + } } fn write(&mut self, n: u32, val: u32) { for k in (0..n).rev() { @@ -1600,18 +1745,28 @@ fn quant(x: f64, sf: i32) -> i32 { let g = 2f64.powf(-0.25 * (sf - 100) as f64); let m = ((x.abs() * g).powf(0.75) + 0.4054) as i32; let q = m.min(8191); - if x < 0.0 { -q } else { q } + if x < 0.0 { + -q + } else { + q + } } /// Codebook index for a `dim`-value tuple (signed cbs use values; unsigned use /// magnitudes; cb11 clamps magnitude to 16 = ESC flag). fn cb_index(cb: usize, t: &[i32]) -> usize { match cb { - 1 | 2 => t.iter().fold(0, |a, &v| a * 3 + (v.clamp(-1, 1) + 1) as usize), - 3 | 4 => t.iter().fold(0, |a, &v| a * 3 + (v.unsigned_abs() as usize).min(2)), + 1 | 2 => t + .iter() + .fold(0, |a, &v| a * 3 + (v.clamp(-1, 1) + 1) as usize), + 3 | 4 => t + .iter() + .fold(0, |a, &v| a * 3 + (v.unsigned_abs() as usize).min(2)), 5 | 6 => (t[0].clamp(-4, 4) + 4) as usize * 9 + (t[1].clamp(-4, 4) + 4) as usize, 7 | 8 => (t[0].unsigned_abs() as usize).min(7) * 8 + (t[1].unsigned_abs() as usize).min(7), - 9 | 10 => (t[0].unsigned_abs() as usize).min(12) * 13 + (t[1].unsigned_abs() as usize).min(12), + 9 | 10 => { + (t[0].unsigned_abs() as usize).min(12) * 13 + (t[1].unsigned_abs() as usize).min(12) + } 11 => (t[0].unsigned_abs() as usize).min(16) * 17 + (t[1].unsigned_abs() as usize).min(16), _ => 0, } @@ -1742,13 +1897,13 @@ fn build_ics(spec: &[f64], swb: &[usize], sf: i32) -> BitWriter { } let mut w = BitWriter::new(); w.write(8, sf as u32 & 0xFF); // global_gain - // ics_info (ONLY_LONG, sine window) + // ics_info (ONLY_LONG, sine window) w.write(1, 0); // ics_reserved_bit w.write(2, 0); // window_sequence = ONLY_LONG w.write(1, 0); // window_shape = sine w.write(6, max_sfb as u32); w.write(1, 0); // predictor_data_present - // section_data: runs of equal codebook + // section_data: runs of equal codebook let mut s = 0; while s < max_sfb { let c = cbs[s]; @@ -1774,7 +1929,7 @@ fn build_ics(spec: &[f64], swb: &[usize], sf: i32) -> BitWriter { w.write(1, 0); // pulse_data_present w.write(1, 0); // tns_data_present w.write(1, 0); // gain_control_data_present - // spectral_data + // spectral_data for s in 0..max_sfb { let c = cbs[s] as usize; if c == 0 || c >= 12 { @@ -1831,7 +1986,10 @@ fn encode_channel(spec: &[f64], swb: &[usize], target_bits: usize) -> BitWriter return ics0; // finest allowed sf already fits — nothing to coarsen } let n_coef = swb[swb.len() - 1]; - let n_nz = spec[..n_coef].iter().filter(|&&x| quant(x, sf_min) != 0).count(); + let n_nz = spec[..n_coef] + .iter() + .filter(|&&x| quant(x, sf_min) != 0) + .count(); let slope = (0.1875 * n_nz as f64).max(1e-6); // bits shed per +1 in sf let step = ((ics0.len_bits() - target_bits) as f64 / slope).ceil() as i32; let sf = (sf_min + step).clamp(sf_min, 255); @@ -1885,7 +2043,10 @@ pub fn encode_roundtrip_test() -> i32 { } } } - println!("aac encode round-trip (1 kHz tone @128k): correlation={best:.4} ({} B)", aac.len()); + println!( + "aac encode round-trip (1 kHz tone @128k): correlation={best:.4} ({} B)", + aac.len() + ); if best > 0.99 { println!(" encoder OK"); 0 @@ -1898,7 +2059,10 @@ pub fn encode_roundtrip_test() -> i32 { /// Encode interleaved 16-bit PCM to an ADTS AAC-LC stream at ~`bitrate_kbps`. pub fn encode_pcm(samples: &[i16], rate: u32, channels: u16, bitrate_kbps: u32) -> Vec { let sr_index = SAMPLE_RATES.iter().position(|&r| r == rate).unwrap_or(4); - let swb: Vec = aac_tables::swb_offset_long(sr_index).iter().map(|&x| x as usize).collect(); + let swb: Vec = aac_tables::swb_offset_long(sr_index) + .iter() + .map(|&x| x as usize) + .collect(); let nch = channels.max(1) as usize; let n_in = samples.len() / nch; let awin = sine_window(2048); diff --git a/src/aac_tables.rs b/src/aac_tables.rs index 742be7a..dc1b11c 100644 --- a/src/aac_tables.rs +++ b/src/aac_tables.rs @@ -9,341 +9,289 @@ // ═══════════════════════════════════════════════════════════════════════════ pub const CODES1: [u16; 81] = [ - 0x7f8, 0x1f1, 0x7fd, 0x3f5, 0x068, 0x3f0, 0x7f7, 0x1ec, 0x7f5, 0x3f1, 0x072, 0x3f4, - 0x074, 0x011, 0x076, 0x1eb, 0x06c, 0x3f6, 0x7fc, 0x1e1, 0x7f1, 0x1f0, 0x061, 0x1f6, - 0x7f2, 0x1ea, 0x7fb, 0x1f2, 0x069, 0x1ed, 0x077, 0x017, 0x06f, 0x1e6, 0x064, 0x1e5, - 0x067, 0x015, 0x062, 0x012, 0x000, 0x014, 0x065, 0x016, 0x06d, 0x1e9, 0x063, 0x1e4, - 0x06b, 0x013, 0x071, 0x1e3, 0x070, 0x1f3, 0x7fe, 0x1e7, 0x7f3, 0x1ef, 0x060, 0x1ee, - 0x7f0, 0x1e2, 0x7fa, 0x3f3, 0x06a, 0x1e8, 0x075, 0x010, 0x073, 0x1f4, 0x06e, 0x3f7, - 0x7f6, 0x1e0, 0x7f9, 0x3f2, 0x066, 0x1f5, 0x7ff, 0x1f7, 0x7f4, + 0x7f8, 0x1f1, 0x7fd, 0x3f5, 0x068, 0x3f0, 0x7f7, 0x1ec, 0x7f5, 0x3f1, 0x072, 0x3f4, 0x074, + 0x011, 0x076, 0x1eb, 0x06c, 0x3f6, 0x7fc, 0x1e1, 0x7f1, 0x1f0, 0x061, 0x1f6, 0x7f2, 0x1ea, + 0x7fb, 0x1f2, 0x069, 0x1ed, 0x077, 0x017, 0x06f, 0x1e6, 0x064, 0x1e5, 0x067, 0x015, 0x062, + 0x012, 0x000, 0x014, 0x065, 0x016, 0x06d, 0x1e9, 0x063, 0x1e4, 0x06b, 0x013, 0x071, 0x1e3, + 0x070, 0x1f3, 0x7fe, 0x1e7, 0x7f3, 0x1ef, 0x060, 0x1ee, 0x7f0, 0x1e2, 0x7fa, 0x3f3, 0x06a, + 0x1e8, 0x075, 0x010, 0x073, 0x1f4, 0x06e, 0x3f7, 0x7f6, 0x1e0, 0x7f9, 0x3f2, 0x066, 0x1f5, + 0x7ff, 0x1f7, 0x7f4, ]; pub const BITS1: [u8; 81] = [ - 11, 9, 11, 10, 7, 10, 11, 9, 11, 10, 7, 10, 7, 5, 7, 9, - 7, 10, 11, 9, 11, 9, 7, 9, 11, 9, 11, 9, 7, 9, 7, 5, - 7, 9, 7, 9, 7, 5, 7, 5, 1, 5, 7, 5, 7, 9, 7, 9, - 7, 5, 7, 9, 7, 9, 11, 9, 11, 9, 7, 9, 11, 9, 11, 10, - 7, 9, 7, 5, 7, 9, 7, 10, 11, 9, 11, 10, 7, 9, 11, 9, - 11, + 11, 9, 11, 10, 7, 10, 11, 9, 11, 10, 7, 10, 7, 5, 7, 9, 7, 10, 11, 9, 11, 9, 7, 9, 11, 9, 11, + 9, 7, 9, 7, 5, 7, 9, 7, 9, 7, 5, 7, 5, 1, 5, 7, 5, 7, 9, 7, 9, 7, 5, 7, 9, 7, 9, 11, 9, 11, 9, + 7, 9, 11, 9, 11, 10, 7, 9, 7, 5, 7, 9, 7, 10, 11, 9, 11, 10, 7, 9, 11, 9, 11, ]; pub const CODES2: [u16; 81] = [ - 0x1f3, 0x06f, 0x1fd, 0x0eb, 0x023, 0x0ea, 0x1f7, 0x0e8, 0x1fa, 0x0f2, 0x02d, 0x070, - 0x020, 0x006, 0x02b, 0x06e, 0x028, 0x0e9, 0x1f9, 0x066, 0x0f8, 0x0e7, 0x01b, 0x0f1, - 0x1f4, 0x06b, 0x1f5, 0x0ec, 0x02a, 0x06c, 0x02c, 0x00a, 0x027, 0x067, 0x01a, 0x0f5, - 0x024, 0x008, 0x01f, 0x009, 0x000, 0x007, 0x01d, 0x00b, 0x030, 0x0ef, 0x01c, 0x064, - 0x01e, 0x00c, 0x029, 0x0f3, 0x02f, 0x0f0, 0x1fc, 0x071, 0x1f2, 0x0f4, 0x021, 0x0e6, - 0x0f7, 0x068, 0x1f8, 0x0ee, 0x022, 0x065, 0x031, 0x002, 0x026, 0x0ed, 0x025, 0x06a, - 0x1fb, 0x072, 0x1fe, 0x069, 0x02e, 0x0f6, 0x1ff, 0x06d, 0x1f6, + 0x1f3, 0x06f, 0x1fd, 0x0eb, 0x023, 0x0ea, 0x1f7, 0x0e8, 0x1fa, 0x0f2, 0x02d, 0x070, 0x020, + 0x006, 0x02b, 0x06e, 0x028, 0x0e9, 0x1f9, 0x066, 0x0f8, 0x0e7, 0x01b, 0x0f1, 0x1f4, 0x06b, + 0x1f5, 0x0ec, 0x02a, 0x06c, 0x02c, 0x00a, 0x027, 0x067, 0x01a, 0x0f5, 0x024, 0x008, 0x01f, + 0x009, 0x000, 0x007, 0x01d, 0x00b, 0x030, 0x0ef, 0x01c, 0x064, 0x01e, 0x00c, 0x029, 0x0f3, + 0x02f, 0x0f0, 0x1fc, 0x071, 0x1f2, 0x0f4, 0x021, 0x0e6, 0x0f7, 0x068, 0x1f8, 0x0ee, 0x022, + 0x065, 0x031, 0x002, 0x026, 0x0ed, 0x025, 0x06a, 0x1fb, 0x072, 0x1fe, 0x069, 0x02e, 0x0f6, + 0x1ff, 0x06d, 0x1f6, ]; pub const BITS2: [u8; 81] = [ - 9, 7, 9, 8, 6, 8, 9, 8, 9, 8, 6, 7, 6, 5, 6, 7, - 6, 8, 9, 7, 8, 8, 6, 8, 9, 7, 9, 8, 6, 7, 6, 5, - 6, 7, 6, 8, 6, 5, 6, 5, 3, 5, 6, 5, 6, 8, 6, 7, - 6, 5, 6, 8, 6, 8, 9, 7, 9, 8, 6, 8, 8, 7, 9, 8, - 6, 7, 6, 4, 6, 8, 6, 7, 9, 7, 9, 7, 6, 8, 9, 7, - 9, + 9, 7, 9, 8, 6, 8, 9, 8, 9, 8, 6, 7, 6, 5, 6, 7, 6, 8, 9, 7, 8, 8, 6, 8, 9, 7, 9, 8, 6, 7, 6, 5, + 6, 7, 6, 8, 6, 5, 6, 5, 3, 5, 6, 5, 6, 8, 6, 7, 6, 5, 6, 8, 6, 8, 9, 7, 9, 8, 6, 8, 8, 7, 9, 8, + 6, 7, 6, 4, 6, 8, 6, 7, 9, 7, 9, 7, 6, 8, 9, 7, 9, ]; pub const CODES3: [u16; 81] = [ - 0x000, 0x009, 0x0ef, 0x00b, 0x019, 0x0f0, 0x1eb, 0x1e6, 0x3f2, 0x00a, 0x035, 0x1ef, - 0x034, 0x037, 0x1e9, 0x1ed, 0x1e7, 0x3f3, 0x1ee, 0x3ed, 0x1ffa, 0x1ec, 0x1f2, 0x7f9, - 0x7f8, 0x3f8, 0xff8, 0x008, 0x038, 0x3f6, 0x036, 0x075, 0x3f1, 0x3eb, 0x3ec, 0xff4, - 0x018, 0x076, 0x7f4, 0x039, 0x074, 0x3ef, 0x1f3, 0x1f4, 0x7f6, 0x1e8, 0x3ea, 0x1ffc, - 0x0f2, 0x1f1, 0xffb, 0x3f5, 0x7f3, 0xffc, 0x0ee, 0x3f7, 0x7ffe, 0x1f0, 0x7f5, 0x7ffd, - 0x1ffb, 0x3ffa, 0xffff, 0x0f1, 0x3f0, 0x3ffc, 0x1ea, 0x3ee, 0x3ffb, 0xff6, 0xffa, 0x7ffc, - 0x7f2, 0xff5, 0xfffe, 0x3f4, 0x7f7, 0x7ffb, 0xff7, 0xff9, 0x7ffa, + 0x000, 0x009, 0x0ef, 0x00b, 0x019, 0x0f0, 0x1eb, 0x1e6, 0x3f2, 0x00a, 0x035, 0x1ef, 0x034, + 0x037, 0x1e9, 0x1ed, 0x1e7, 0x3f3, 0x1ee, 0x3ed, 0x1ffa, 0x1ec, 0x1f2, 0x7f9, 0x7f8, 0x3f8, + 0xff8, 0x008, 0x038, 0x3f6, 0x036, 0x075, 0x3f1, 0x3eb, 0x3ec, 0xff4, 0x018, 0x076, 0x7f4, + 0x039, 0x074, 0x3ef, 0x1f3, 0x1f4, 0x7f6, 0x1e8, 0x3ea, 0x1ffc, 0x0f2, 0x1f1, 0xffb, 0x3f5, + 0x7f3, 0xffc, 0x0ee, 0x3f7, 0x7ffe, 0x1f0, 0x7f5, 0x7ffd, 0x1ffb, 0x3ffa, 0xffff, 0x0f1, 0x3f0, + 0x3ffc, 0x1ea, 0x3ee, 0x3ffb, 0xff6, 0xffa, 0x7ffc, 0x7f2, 0xff5, 0xfffe, 0x3f4, 0x7f7, 0x7ffb, + 0xff7, 0xff9, 0x7ffa, ]; pub const BITS3: [u8; 81] = [ - 1, 4, 8, 4, 5, 8, 9, 9, 10, 4, 6, 9, 6, 6, 9, 9, - 9, 10, 9, 10, 13, 9, 9, 11, 11, 10, 12, 4, 6, 10, 6, 7, - 10, 10, 10, 12, 5, 7, 11, 6, 7, 10, 9, 9, 11, 9, 10, 13, - 8, 9, 12, 10, 11, 12, 8, 10, 15, 9, 11, 15, 13, 14, 16, 8, - 10, 14, 9, 10, 14, 12, 12, 15, 11, 12, 16, 10, 11, 15, 12, 12, + 1, 4, 8, 4, 5, 8, 9, 9, 10, 4, 6, 9, 6, 6, 9, 9, 9, 10, 9, 10, 13, 9, 9, 11, 11, 10, 12, 4, 6, + 10, 6, 7, 10, 10, 10, 12, 5, 7, 11, 6, 7, 10, 9, 9, 11, 9, 10, 13, 8, 9, 12, 10, 11, 12, 8, 10, + 15, 9, 11, 15, 13, 14, 16, 8, 10, 14, 9, 10, 14, 12, 12, 15, 11, 12, 16, 10, 11, 15, 12, 12, 15, ]; pub const CODES4: [u16; 81] = [ - 0x007, 0x016, 0x0f6, 0x018, 0x008, 0x0ef, 0x1ef, 0x0f3, 0x7f8, 0x019, 0x017, 0x0ed, - 0x015, 0x001, 0x0e2, 0x0f0, 0x070, 0x3f0, 0x1ee, 0x0f1, 0x7fa, 0x0ee, 0x0e4, 0x3f2, - 0x7f6, 0x3ef, 0x7fd, 0x005, 0x014, 0x0f2, 0x009, 0x004, 0x0e5, 0x0f4, 0x0e8, 0x3f4, - 0x006, 0x002, 0x0e7, 0x003, 0x000, 0x06b, 0x0e3, 0x069, 0x1f3, 0x0eb, 0x0e6, 0x3f6, - 0x06e, 0x06a, 0x1f4, 0x3ec, 0x1f0, 0x3f9, 0x0f5, 0x0ec, 0x7fb, 0x0ea, 0x06f, 0x3f7, - 0x7f9, 0x3f3, 0xfff, 0x0e9, 0x06d, 0x3f8, 0x06c, 0x068, 0x1f5, 0x3ee, 0x1f2, 0x7f4, - 0x7f7, 0x3f1, 0xffe, 0x3ed, 0x1f1, 0x7f5, 0x7fe, 0x3f5, 0x7fc, + 0x007, 0x016, 0x0f6, 0x018, 0x008, 0x0ef, 0x1ef, 0x0f3, 0x7f8, 0x019, 0x017, 0x0ed, 0x015, + 0x001, 0x0e2, 0x0f0, 0x070, 0x3f0, 0x1ee, 0x0f1, 0x7fa, 0x0ee, 0x0e4, 0x3f2, 0x7f6, 0x3ef, + 0x7fd, 0x005, 0x014, 0x0f2, 0x009, 0x004, 0x0e5, 0x0f4, 0x0e8, 0x3f4, 0x006, 0x002, 0x0e7, + 0x003, 0x000, 0x06b, 0x0e3, 0x069, 0x1f3, 0x0eb, 0x0e6, 0x3f6, 0x06e, 0x06a, 0x1f4, 0x3ec, + 0x1f0, 0x3f9, 0x0f5, 0x0ec, 0x7fb, 0x0ea, 0x06f, 0x3f7, 0x7f9, 0x3f3, 0xfff, 0x0e9, 0x06d, + 0x3f8, 0x06c, 0x068, 0x1f5, 0x3ee, 0x1f2, 0x7f4, 0x7f7, 0x3f1, 0xffe, 0x3ed, 0x1f1, 0x7f5, + 0x7fe, 0x3f5, 0x7fc, ]; pub const BITS4: [u8; 81] = [ - 4, 5, 8, 5, 4, 8, 9, 8, 11, 5, 5, 8, 5, 4, 8, 8, - 7, 10, 9, 8, 11, 8, 8, 10, 11, 10, 11, 4, 5, 8, 4, 4, - 8, 8, 8, 10, 4, 4, 8, 4, 4, 7, 8, 7, 9, 8, 8, 10, - 7, 7, 9, 10, 9, 10, 8, 8, 11, 8, 7, 10, 11, 10, 12, 8, - 7, 10, 7, 7, 9, 10, 9, 11, 11, 10, 12, 10, 9, 11, 11, 10, - 11, + 4, 5, 8, 5, 4, 8, 9, 8, 11, 5, 5, 8, 5, 4, 8, 8, 7, 10, 9, 8, 11, 8, 8, 10, 11, 10, 11, 4, 5, + 8, 4, 4, 8, 8, 8, 10, 4, 4, 8, 4, 4, 7, 8, 7, 9, 8, 8, 10, 7, 7, 9, 10, 9, 10, 8, 8, 11, 8, 7, + 10, 11, 10, 12, 8, 7, 10, 7, 7, 9, 10, 9, 11, 11, 10, 12, 10, 9, 11, 11, 10, 11, ]; pub const CODES5: [u16; 81] = [ - 0x1fff, 0xff7, 0x7f4, 0x7e8, 0x3f1, 0x7ee, 0x7f9, 0xff8, 0x1ffd, 0xffd, 0x7f1, 0x3e8, - 0x1e8, 0x0f0, 0x1ec, 0x3ee, 0x7f2, 0xffa, 0xff4, 0x3ef, 0x1f2, 0x0e8, 0x070, 0x0ec, - 0x1f0, 0x3ea, 0x7f3, 0x7eb, 0x1eb, 0x0ea, 0x01a, 0x008, 0x019, 0x0ee, 0x1ef, 0x7ed, - 0x3f0, 0x0f2, 0x073, 0x00b, 0x000, 0x00a, 0x071, 0x0f3, 0x7e9, 0x7ef, 0x1ee, 0x0ef, - 0x018, 0x009, 0x01b, 0x0eb, 0x1e9, 0x7ec, 0x7f6, 0x3eb, 0x1f3, 0x0ed, 0x072, 0x0e9, - 0x1f1, 0x3ed, 0x7f7, 0xff6, 0x7f0, 0x3e9, 0x1ed, 0x0f1, 0x1ea, 0x3ec, 0x7f8, 0xff9, - 0x1ffc, 0xffc, 0xff5, 0x7ea, 0x3f3, 0x3f2, 0x7f5, 0xffb, 0x1ffe, + 0x1fff, 0xff7, 0x7f4, 0x7e8, 0x3f1, 0x7ee, 0x7f9, 0xff8, 0x1ffd, 0xffd, 0x7f1, 0x3e8, 0x1e8, + 0x0f0, 0x1ec, 0x3ee, 0x7f2, 0xffa, 0xff4, 0x3ef, 0x1f2, 0x0e8, 0x070, 0x0ec, 0x1f0, 0x3ea, + 0x7f3, 0x7eb, 0x1eb, 0x0ea, 0x01a, 0x008, 0x019, 0x0ee, 0x1ef, 0x7ed, 0x3f0, 0x0f2, 0x073, + 0x00b, 0x000, 0x00a, 0x071, 0x0f3, 0x7e9, 0x7ef, 0x1ee, 0x0ef, 0x018, 0x009, 0x01b, 0x0eb, + 0x1e9, 0x7ec, 0x7f6, 0x3eb, 0x1f3, 0x0ed, 0x072, 0x0e9, 0x1f1, 0x3ed, 0x7f7, 0xff6, 0x7f0, + 0x3e9, 0x1ed, 0x0f1, 0x1ea, 0x3ec, 0x7f8, 0xff9, 0x1ffc, 0xffc, 0xff5, 0x7ea, 0x3f3, 0x3f2, + 0x7f5, 0xffb, 0x1ffe, ]; pub const BITS5: [u8; 81] = [ - 13, 12, 11, 11, 10, 11, 11, 12, 13, 12, 11, 10, 9, 8, 9, 10, - 11, 12, 12, 10, 9, 8, 7, 8, 9, 10, 11, 11, 9, 8, 5, 4, - 5, 8, 9, 11, 10, 8, 7, 4, 1, 4, 7, 8, 11, 11, 9, 8, - 5, 4, 5, 8, 9, 11, 11, 10, 9, 8, 7, 8, 9, 10, 11, 12, - 11, 10, 9, 8, 9, 10, 11, 12, 13, 12, 12, 11, 10, 10, 11, 12, - 13, + 13, 12, 11, 11, 10, 11, 11, 12, 13, 12, 11, 10, 9, 8, 9, 10, 11, 12, 12, 10, 9, 8, 7, 8, 9, 10, + 11, 11, 9, 8, 5, 4, 5, 8, 9, 11, 10, 8, 7, 4, 1, 4, 7, 8, 11, 11, 9, 8, 5, 4, 5, 8, 9, 11, 11, + 10, 9, 8, 7, 8, 9, 10, 11, 12, 11, 10, 9, 8, 9, 10, 11, 12, 13, 12, 12, 11, 10, 10, 11, 12, 13, ]; pub const CODES6: [u16; 81] = [ - 0x7fe, 0x3fd, 0x1f1, 0x1eb, 0x1f4, 0x1ea, 0x1f0, 0x3fc, 0x7fd, 0x3f6, 0x1e5, 0x0ea, - 0x06c, 0x071, 0x068, 0x0f0, 0x1e6, 0x3f7, 0x1f3, 0x0ef, 0x032, 0x027, 0x028, 0x026, - 0x031, 0x0eb, 0x1f7, 0x1e8, 0x06f, 0x02e, 0x008, 0x004, 0x006, 0x029, 0x06b, 0x1ee, - 0x1ef, 0x072, 0x02d, 0x002, 0x000, 0x003, 0x02f, 0x073, 0x1fa, 0x1e7, 0x06e, 0x02b, - 0x007, 0x001, 0x005, 0x02c, 0x06d, 0x1ec, 0x1f9, 0x0ee, 0x030, 0x024, 0x02a, 0x025, - 0x033, 0x0ec, 0x1f2, 0x3f8, 0x1e4, 0x0ed, 0x06a, 0x070, 0x069, 0x074, 0x0f1, 0x3fa, - 0x7ff, 0x3f9, 0x1f6, 0x1ed, 0x1f8, 0x1e9, 0x1f5, 0x3fb, 0x7fc, + 0x7fe, 0x3fd, 0x1f1, 0x1eb, 0x1f4, 0x1ea, 0x1f0, 0x3fc, 0x7fd, 0x3f6, 0x1e5, 0x0ea, 0x06c, + 0x071, 0x068, 0x0f0, 0x1e6, 0x3f7, 0x1f3, 0x0ef, 0x032, 0x027, 0x028, 0x026, 0x031, 0x0eb, + 0x1f7, 0x1e8, 0x06f, 0x02e, 0x008, 0x004, 0x006, 0x029, 0x06b, 0x1ee, 0x1ef, 0x072, 0x02d, + 0x002, 0x000, 0x003, 0x02f, 0x073, 0x1fa, 0x1e7, 0x06e, 0x02b, 0x007, 0x001, 0x005, 0x02c, + 0x06d, 0x1ec, 0x1f9, 0x0ee, 0x030, 0x024, 0x02a, 0x025, 0x033, 0x0ec, 0x1f2, 0x3f8, 0x1e4, + 0x0ed, 0x06a, 0x070, 0x069, 0x074, 0x0f1, 0x3fa, 0x7ff, 0x3f9, 0x1f6, 0x1ed, 0x1f8, 0x1e9, + 0x1f5, 0x3fb, 0x7fc, ]; pub const BITS6: [u8; 81] = [ - 11, 10, 9, 9, 9, 9, 9, 10, 11, 10, 9, 8, 7, 7, 7, 8, - 9, 10, 9, 8, 6, 6, 6, 6, 6, 8, 9, 9, 7, 6, 4, 4, - 4, 6, 7, 9, 9, 7, 6, 4, 4, 4, 6, 7, 9, 9, 7, 6, - 4, 4, 4, 6, 7, 9, 9, 8, 6, 6, 6, 6, 6, 8, 9, 10, - 9, 8, 7, 7, 7, 7, 8, 10, 11, 10, 9, 9, 9, 9, 9, 10, - 11, + 11, 10, 9, 9, 9, 9, 9, 10, 11, 10, 9, 8, 7, 7, 7, 8, 9, 10, 9, 8, 6, 6, 6, 6, 6, 8, 9, 9, 7, 6, + 4, 4, 4, 6, 7, 9, 9, 7, 6, 4, 4, 4, 6, 7, 9, 9, 7, 6, 4, 4, 4, 6, 7, 9, 9, 8, 6, 6, 6, 6, 6, 8, + 9, 10, 9, 8, 7, 7, 7, 7, 8, 10, 11, 10, 9, 9, 9, 9, 9, 10, 11, ]; pub const CODES7: [u16; 64] = [ - 0x000, 0x005, 0x037, 0x074, 0x0f2, 0x1eb, 0x3ed, 0x7f7, 0x004, 0x00c, 0x035, 0x071, - 0x0ec, 0x0ee, 0x1ee, 0x1f5, 0x036, 0x034, 0x072, 0x0ea, 0x0f1, 0x1e9, 0x1f3, 0x3f5, - 0x073, 0x070, 0x0eb, 0x0f0, 0x1f1, 0x1f0, 0x3ec, 0x3fa, 0x0f3, 0x0ed, 0x1e8, 0x1ef, - 0x3ef, 0x3f1, 0x3f9, 0x7fb, 0x1ed, 0x0ef, 0x1ea, 0x1f2, 0x3f3, 0x3f8, 0x7f9, 0x7fc, - 0x3ee, 0x1ec, 0x1f4, 0x3f4, 0x3f7, 0x7f8, 0xffd, 0xffe, 0x7f6, 0x3f0, 0x3f2, 0x3f6, - 0x7fa, 0x7fd, 0xffc, 0xfff, + 0x000, 0x005, 0x037, 0x074, 0x0f2, 0x1eb, 0x3ed, 0x7f7, 0x004, 0x00c, 0x035, 0x071, 0x0ec, + 0x0ee, 0x1ee, 0x1f5, 0x036, 0x034, 0x072, 0x0ea, 0x0f1, 0x1e9, 0x1f3, 0x3f5, 0x073, 0x070, + 0x0eb, 0x0f0, 0x1f1, 0x1f0, 0x3ec, 0x3fa, 0x0f3, 0x0ed, 0x1e8, 0x1ef, 0x3ef, 0x3f1, 0x3f9, + 0x7fb, 0x1ed, 0x0ef, 0x1ea, 0x1f2, 0x3f3, 0x3f8, 0x7f9, 0x7fc, 0x3ee, 0x1ec, 0x1f4, 0x3f4, + 0x3f7, 0x7f8, 0xffd, 0xffe, 0x7f6, 0x3f0, 0x3f2, 0x3f6, 0x7fa, 0x7fd, 0xffc, 0xfff, ]; pub const BITS7: [u8; 64] = [ - 1, 3, 6, 7, 8, 9, 10, 11, 3, 4, 6, 7, 8, 8, 9, 9, - 6, 6, 7, 8, 8, 9, 9, 10, 7, 7, 8, 8, 9, 9, 10, 10, - 8, 8, 9, 9, 10, 10, 10, 11, 9, 8, 9, 9, 10, 10, 11, 11, - 10, 9, 9, 10, 10, 11, 12, 12, 11, 10, 10, 10, 11, 11, 12, 12, + 1, 3, 6, 7, 8, 9, 10, 11, 3, 4, 6, 7, 8, 8, 9, 9, 6, 6, 7, 8, 8, 9, 9, 10, 7, 7, 8, 8, 9, 9, + 10, 10, 8, 8, 9, 9, 10, 10, 10, 11, 9, 8, 9, 9, 10, 10, 11, 11, 10, 9, 9, 10, 10, 11, 12, 12, + 11, 10, 10, 10, 11, 11, 12, 12, ]; pub const CODES8: [u16; 64] = [ - 0x00e, 0x005, 0x010, 0x030, 0x06f, 0x0f1, 0x1fa, 0x3fe, 0x003, 0x000, 0x004, 0x012, - 0x02c, 0x06a, 0x075, 0x0f8, 0x00f, 0x002, 0x006, 0x014, 0x02e, 0x069, 0x072, 0x0f5, - 0x02f, 0x011, 0x013, 0x02a, 0x032, 0x06c, 0x0ec, 0x0fa, 0x071, 0x02b, 0x02d, 0x031, - 0x06d, 0x070, 0x0f2, 0x1f9, 0x0ef, 0x068, 0x033, 0x06b, 0x06e, 0x0ee, 0x0f9, 0x3fc, - 0x1f8, 0x074, 0x073, 0x0ed, 0x0f0, 0x0f6, 0x1f6, 0x1fd, 0x3fd, 0x0f3, 0x0f4, 0x0f7, - 0x1f7, 0x1fb, 0x1fc, 0x3ff, + 0x00e, 0x005, 0x010, 0x030, 0x06f, 0x0f1, 0x1fa, 0x3fe, 0x003, 0x000, 0x004, 0x012, 0x02c, + 0x06a, 0x075, 0x0f8, 0x00f, 0x002, 0x006, 0x014, 0x02e, 0x069, 0x072, 0x0f5, 0x02f, 0x011, + 0x013, 0x02a, 0x032, 0x06c, 0x0ec, 0x0fa, 0x071, 0x02b, 0x02d, 0x031, 0x06d, 0x070, 0x0f2, + 0x1f9, 0x0ef, 0x068, 0x033, 0x06b, 0x06e, 0x0ee, 0x0f9, 0x3fc, 0x1f8, 0x074, 0x073, 0x0ed, + 0x0f0, 0x0f6, 0x1f6, 0x1fd, 0x3fd, 0x0f3, 0x0f4, 0x0f7, 0x1f7, 0x1fb, 0x1fc, 0x3ff, ]; pub const BITS8: [u8; 64] = [ - 5, 4, 5, 6, 7, 8, 9, 10, 4, 3, 4, 5, 6, 7, 7, 8, - 5, 4, 4, 5, 6, 7, 7, 8, 6, 5, 5, 6, 6, 7, 8, 8, - 7, 6, 6, 6, 7, 7, 8, 9, 8, 7, 6, 7, 7, 8, 8, 10, - 9, 7, 7, 8, 8, 8, 9, 9, 10, 8, 8, 8, 9, 9, 9, 10, + 5, 4, 5, 6, 7, 8, 9, 10, 4, 3, 4, 5, 6, 7, 7, 8, 5, 4, 4, 5, 6, 7, 7, 8, 6, 5, 5, 6, 6, 7, 8, + 8, 7, 6, 6, 6, 7, 7, 8, 9, 8, 7, 6, 7, 7, 8, 8, 10, 9, 7, 7, 8, 8, 8, 9, 9, 10, 8, 8, 8, 9, 9, + 9, 10, ]; pub const CODES9: [u16; 169] = [ - 0x000, 0x005, 0x037, 0x0e7, 0x1de, 0x3ce, 0x3d9, 0x7c8, 0x7cd, 0xfc8, 0xfdd, 0x1fe4, - 0x1fec, 0x004, 0x00c, 0x035, 0x072, 0x0ea, 0x0ed, 0x1e2, 0x3d1, 0x3d3, 0x3e0, 0x7d8, - 0xfcf, 0xfd5, 0x036, 0x034, 0x071, 0x0e8, 0x0ec, 0x1e1, 0x3cf, 0x3dd, 0x3db, 0x7d0, - 0xfc7, 0xfd4, 0xfe4, 0x0e6, 0x070, 0x0e9, 0x1dd, 0x1e3, 0x3d2, 0x3dc, 0x7cc, 0x7ca, - 0x7de, 0xfd8, 0xfea, 0x1fdb, 0x1df, 0x0eb, 0x1dc, 0x1e6, 0x3d5, 0x3de, 0x7cb, 0x7dd, - 0x7dc, 0xfcd, 0xfe2, 0xfe7, 0x1fe1, 0x3d0, 0x1e0, 0x1e4, 0x3d6, 0x7c5, 0x7d1, 0x7db, - 0xfd2, 0x7e0, 0xfd9, 0xfeb, 0x1fe3, 0x1fe9, 0x7c4, 0x1e5, 0x3d7, 0x7c6, 0x7cf, 0x7da, - 0xfcb, 0xfda, 0xfe3, 0xfe9, 0x1fe6, 0x1ff3, 0x1ff7, 0x7d3, 0x3d8, 0x3e1, 0x7d4, 0x7d9, - 0xfd3, 0xfde, 0x1fdd, 0x1fd9, 0x1fe2, 0x1fea, 0x1ff1, 0x1ff6, 0x7d2, 0x3d4, 0x3da, 0x7c7, - 0x7d7, 0x7e2, 0xfce, 0xfdb, 0x1fd8, 0x1fee, 0x3ff0, 0x1ff4, 0x3ff2, 0x7e1, 0x3df, 0x7c9, - 0x7d6, 0xfca, 0xfd0, 0xfe5, 0xfe6, 0x1feb, 0x1fef, 0x3ff3, 0x3ff4, 0x3ff5, 0xfe0, 0x7ce, - 0x7d5, 0xfc6, 0xfd1, 0xfe1, 0x1fe0, 0x1fe8, 0x1ff0, 0x3ff1, 0x3ff8, 0x3ff6, 0x7ffc, 0xfe8, - 0x7df, 0xfc9, 0xfd7, 0xfdc, 0x1fdc, 0x1fdf, 0x1fed, 0x1ff5, 0x3ff9, 0x3ffb, 0x7ffd, 0x7ffe, - 0x1fe7, 0xfcc, 0xfd6, 0xfdf, 0x1fde, 0x1fda, 0x1fe5, 0x1ff2, 0x3ffa, 0x3ff7, 0x3ffc, 0x3ffd, - 0x7fff, + 0x000, 0x005, 0x037, 0x0e7, 0x1de, 0x3ce, 0x3d9, 0x7c8, 0x7cd, 0xfc8, 0xfdd, 0x1fe4, 0x1fec, + 0x004, 0x00c, 0x035, 0x072, 0x0ea, 0x0ed, 0x1e2, 0x3d1, 0x3d3, 0x3e0, 0x7d8, 0xfcf, 0xfd5, + 0x036, 0x034, 0x071, 0x0e8, 0x0ec, 0x1e1, 0x3cf, 0x3dd, 0x3db, 0x7d0, 0xfc7, 0xfd4, 0xfe4, + 0x0e6, 0x070, 0x0e9, 0x1dd, 0x1e3, 0x3d2, 0x3dc, 0x7cc, 0x7ca, 0x7de, 0xfd8, 0xfea, 0x1fdb, + 0x1df, 0x0eb, 0x1dc, 0x1e6, 0x3d5, 0x3de, 0x7cb, 0x7dd, 0x7dc, 0xfcd, 0xfe2, 0xfe7, 0x1fe1, + 0x3d0, 0x1e0, 0x1e4, 0x3d6, 0x7c5, 0x7d1, 0x7db, 0xfd2, 0x7e0, 0xfd9, 0xfeb, 0x1fe3, 0x1fe9, + 0x7c4, 0x1e5, 0x3d7, 0x7c6, 0x7cf, 0x7da, 0xfcb, 0xfda, 0xfe3, 0xfe9, 0x1fe6, 0x1ff3, 0x1ff7, + 0x7d3, 0x3d8, 0x3e1, 0x7d4, 0x7d9, 0xfd3, 0xfde, 0x1fdd, 0x1fd9, 0x1fe2, 0x1fea, 0x1ff1, + 0x1ff6, 0x7d2, 0x3d4, 0x3da, 0x7c7, 0x7d7, 0x7e2, 0xfce, 0xfdb, 0x1fd8, 0x1fee, 0x3ff0, 0x1ff4, + 0x3ff2, 0x7e1, 0x3df, 0x7c9, 0x7d6, 0xfca, 0xfd0, 0xfe5, 0xfe6, 0x1feb, 0x1fef, 0x3ff3, 0x3ff4, + 0x3ff5, 0xfe0, 0x7ce, 0x7d5, 0xfc6, 0xfd1, 0xfe1, 0x1fe0, 0x1fe8, 0x1ff0, 0x3ff1, 0x3ff8, + 0x3ff6, 0x7ffc, 0xfe8, 0x7df, 0xfc9, 0xfd7, 0xfdc, 0x1fdc, 0x1fdf, 0x1fed, 0x1ff5, 0x3ff9, + 0x3ffb, 0x7ffd, 0x7ffe, 0x1fe7, 0xfcc, 0xfd6, 0xfdf, 0x1fde, 0x1fda, 0x1fe5, 0x1ff2, 0x3ffa, + 0x3ff7, 0x3ffc, 0x3ffd, 0x7fff, ]; pub const BITS9: [u8; 169] = [ - 1, 3, 6, 8, 9, 10, 10, 11, 11, 12, 12, 13, 13, 3, 4, 6, - 7, 8, 8, 9, 10, 10, 10, 11, 12, 12, 6, 6, 7, 8, 8, 9, - 10, 10, 10, 11, 12, 12, 12, 8, 7, 8, 9, 9, 10, 10, 11, 11, - 11, 12, 12, 13, 9, 8, 9, 9, 10, 10, 11, 11, 11, 12, 12, 12, - 13, 10, 9, 9, 10, 11, 11, 11, 12, 11, 12, 12, 13, 13, 11, 9, - 10, 11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 11, 10, 10, 11, 11, - 12, 12, 13, 13, 13, 13, 13, 13, 11, 10, 10, 11, 11, 11, 12, 12, - 13, 13, 14, 13, 14, 11, 10, 11, 11, 12, 12, 12, 12, 13, 13, 14, - 14, 14, 12, 11, 11, 12, 12, 12, 13, 13, 13, 14, 14, 14, 15, 12, - 11, 12, 12, 12, 13, 13, 13, 13, 14, 14, 15, 15, 13, 12, 12, 12, - 13, 13, 13, 13, 14, 14, 14, 14, 15, + 1, 3, 6, 8, 9, 10, 10, 11, 11, 12, 12, 13, 13, 3, 4, 6, 7, 8, 8, 9, 10, 10, 10, 11, 12, 12, 6, + 6, 7, 8, 8, 9, 10, 10, 10, 11, 12, 12, 12, 8, 7, 8, 9, 9, 10, 10, 11, 11, 11, 12, 12, 13, 9, 8, + 9, 9, 10, 10, 11, 11, 11, 12, 12, 12, 13, 10, 9, 9, 10, 11, 11, 11, 12, 11, 12, 12, 13, 13, 11, + 9, 10, 11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 11, 10, 10, 11, 11, 12, 12, 13, 13, 13, 13, 13, + 13, 11, 10, 10, 11, 11, 11, 12, 12, 13, 13, 14, 13, 14, 11, 10, 11, 11, 12, 12, 12, 12, 13, 13, + 14, 14, 14, 12, 11, 11, 12, 12, 12, 13, 13, 13, 14, 14, 14, 15, 12, 11, 12, 12, 12, 13, 13, 13, + 13, 14, 14, 15, 15, 13, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, ]; pub const CODES10: [u16; 169] = [ - 0x022, 0x008, 0x01d, 0x026, 0x05f, 0x0d3, 0x1cf, 0x3d0, 0x3d7, 0x3ed, 0x7f0, 0x7f6, - 0xffd, 0x007, 0x000, 0x001, 0x009, 0x020, 0x054, 0x060, 0x0d5, 0x0dc, 0x1d4, 0x3cd, - 0x3de, 0x7e7, 0x01c, 0x002, 0x006, 0x00c, 0x01e, 0x028, 0x05b, 0x0cd, 0x0d9, 0x1ce, - 0x1dc, 0x3d9, 0x3f1, 0x025, 0x00b, 0x00a, 0x00d, 0x024, 0x057, 0x061, 0x0cc, 0x0dd, - 0x1cc, 0x1de, 0x3d3, 0x3e7, 0x05d, 0x021, 0x01f, 0x023, 0x027, 0x059, 0x064, 0x0d8, - 0x0df, 0x1d2, 0x1e2, 0x3dd, 0x3ee, 0x0d1, 0x055, 0x029, 0x056, 0x058, 0x062, 0x0ce, - 0x0e0, 0x0e2, 0x1da, 0x3d4, 0x3e3, 0x7eb, 0x1c9, 0x05e, 0x05a, 0x05c, 0x063, 0x0ca, - 0x0da, 0x1c7, 0x1ca, 0x1e0, 0x3db, 0x3e8, 0x7ec, 0x1e3, 0x0d2, 0x0cb, 0x0d0, 0x0d7, - 0x0db, 0x1c6, 0x1d5, 0x1d8, 0x3ca, 0x3da, 0x7ea, 0x7f1, 0x1e1, 0x0d4, 0x0cf, 0x0d6, - 0x0de, 0x0e1, 0x1d0, 0x1d6, 0x3d1, 0x3d5, 0x3f2, 0x7ee, 0x7fb, 0x3e9, 0x1cd, 0x1c8, - 0x1cb, 0x1d1, 0x1d7, 0x1df, 0x3cf, 0x3e0, 0x3ef, 0x7e6, 0x7f8, 0xffa, 0x3eb, 0x1dd, - 0x1d3, 0x1d9, 0x1db, 0x3d2, 0x3cc, 0x3dc, 0x3ea, 0x7ed, 0x7f3, 0x7f9, 0xff9, 0x7f2, - 0x3ce, 0x1e4, 0x3cb, 0x3d8, 0x3d6, 0x3e2, 0x3e5, 0x7e8, 0x7f4, 0x7f5, 0x7f7, 0xffb, - 0x7fa, 0x3ec, 0x3df, 0x3e1, 0x3e4, 0x3e6, 0x3f0, 0x7e9, 0x7ef, 0xff8, 0xffe, 0xffc, - 0xfff, + 0x022, 0x008, 0x01d, 0x026, 0x05f, 0x0d3, 0x1cf, 0x3d0, 0x3d7, 0x3ed, 0x7f0, 0x7f6, 0xffd, + 0x007, 0x000, 0x001, 0x009, 0x020, 0x054, 0x060, 0x0d5, 0x0dc, 0x1d4, 0x3cd, 0x3de, 0x7e7, + 0x01c, 0x002, 0x006, 0x00c, 0x01e, 0x028, 0x05b, 0x0cd, 0x0d9, 0x1ce, 0x1dc, 0x3d9, 0x3f1, + 0x025, 0x00b, 0x00a, 0x00d, 0x024, 0x057, 0x061, 0x0cc, 0x0dd, 0x1cc, 0x1de, 0x3d3, 0x3e7, + 0x05d, 0x021, 0x01f, 0x023, 0x027, 0x059, 0x064, 0x0d8, 0x0df, 0x1d2, 0x1e2, 0x3dd, 0x3ee, + 0x0d1, 0x055, 0x029, 0x056, 0x058, 0x062, 0x0ce, 0x0e0, 0x0e2, 0x1da, 0x3d4, 0x3e3, 0x7eb, + 0x1c9, 0x05e, 0x05a, 0x05c, 0x063, 0x0ca, 0x0da, 0x1c7, 0x1ca, 0x1e0, 0x3db, 0x3e8, 0x7ec, + 0x1e3, 0x0d2, 0x0cb, 0x0d0, 0x0d7, 0x0db, 0x1c6, 0x1d5, 0x1d8, 0x3ca, 0x3da, 0x7ea, 0x7f1, + 0x1e1, 0x0d4, 0x0cf, 0x0d6, 0x0de, 0x0e1, 0x1d0, 0x1d6, 0x3d1, 0x3d5, 0x3f2, 0x7ee, 0x7fb, + 0x3e9, 0x1cd, 0x1c8, 0x1cb, 0x1d1, 0x1d7, 0x1df, 0x3cf, 0x3e0, 0x3ef, 0x7e6, 0x7f8, 0xffa, + 0x3eb, 0x1dd, 0x1d3, 0x1d9, 0x1db, 0x3d2, 0x3cc, 0x3dc, 0x3ea, 0x7ed, 0x7f3, 0x7f9, 0xff9, + 0x7f2, 0x3ce, 0x1e4, 0x3cb, 0x3d8, 0x3d6, 0x3e2, 0x3e5, 0x7e8, 0x7f4, 0x7f5, 0x7f7, 0xffb, + 0x7fa, 0x3ec, 0x3df, 0x3e1, 0x3e4, 0x3e6, 0x3f0, 0x7e9, 0x7ef, 0xff8, 0xffe, 0xffc, 0xfff, ]; pub const BITS10: [u8; 169] = [ - 6, 5, 6, 6, 7, 8, 9, 10, 10, 10, 11, 11, 12, 5, 4, 4, - 5, 6, 7, 7, 8, 8, 9, 10, 10, 11, 6, 4, 5, 5, 6, 6, - 7, 8, 8, 9, 9, 10, 10, 6, 5, 5, 5, 6, 7, 7, 8, 8, - 9, 9, 10, 10, 7, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 10, - 10, 8, 7, 6, 7, 7, 7, 8, 8, 8, 9, 10, 10, 11, 9, 7, - 7, 7, 7, 8, 8, 9, 9, 9, 10, 10, 11, 9, 8, 8, 8, 8, - 8, 9, 9, 9, 10, 10, 11, 11, 9, 8, 8, 8, 8, 8, 9, 9, - 10, 10, 10, 11, 11, 10, 9, 9, 9, 9, 9, 9, 10, 10, 10, 11, - 11, 12, 10, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 12, 11, - 10, 9, 10, 10, 10, 10, 10, 11, 11, 11, 11, 12, 11, 10, 10, 10, - 10, 10, 10, 11, 11, 12, 12, 12, 12, + 6, 5, 6, 6, 7, 8, 9, 10, 10, 10, 11, 11, 12, 5, 4, 4, 5, 6, 7, 7, 8, 8, 9, 10, 10, 11, 6, 4, 5, + 5, 6, 6, 7, 8, 8, 9, 9, 10, 10, 6, 5, 5, 5, 6, 7, 7, 8, 8, 9, 9, 10, 10, 7, 6, 6, 6, 6, 7, 7, + 8, 8, 9, 9, 10, 10, 8, 7, 6, 7, 7, 7, 8, 8, 8, 9, 10, 10, 11, 9, 7, 7, 7, 7, 8, 8, 9, 9, 9, 10, + 10, 11, 9, 8, 8, 8, 8, 8, 9, 9, 9, 10, 10, 11, 11, 9, 8, 8, 8, 8, 8, 9, 9, 10, 10, 10, 11, 11, + 10, 9, 9, 9, 9, 9, 9, 10, 10, 10, 11, 11, 12, 10, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 12, + 11, 10, 9, 10, 10, 10, 10, 10, 11, 11, 11, 11, 12, 11, 10, 10, 10, 10, 10, 10, 11, 11, 12, 12, + 12, 12, ]; pub const CODES11: [u16; 289] = [ - 0x000, 0x006, 0x019, 0x03d, 0x09c, 0x0c6, 0x1a7, 0x390, 0x3c2, 0x3df, 0x7e6, 0x7f3, - 0xffb, 0x7ec, 0xffa, 0xffe, 0x38e, 0x005, 0x001, 0x008, 0x014, 0x037, 0x042, 0x092, - 0x0af, 0x191, 0x1a5, 0x1b5, 0x39e, 0x3c0, 0x3a2, 0x3cd, 0x7d6, 0x0ae, 0x017, 0x007, - 0x009, 0x018, 0x039, 0x040, 0x08e, 0x0a3, 0x0b8, 0x199, 0x1ac, 0x1c1, 0x3b1, 0x396, - 0x3be, 0x3ca, 0x09d, 0x03c, 0x015, 0x016, 0x01a, 0x03b, 0x044, 0x091, 0x0a5, 0x0be, - 0x196, 0x1ae, 0x1b9, 0x3a1, 0x391, 0x3a5, 0x3d5, 0x094, 0x09a, 0x036, 0x038, 0x03a, - 0x041, 0x08c, 0x09b, 0x0b0, 0x0c3, 0x19e, 0x1ab, 0x1bc, 0x39f, 0x38f, 0x3a9, 0x3cf, - 0x093, 0x0bf, 0x03e, 0x03f, 0x043, 0x045, 0x09e, 0x0a7, 0x0b9, 0x194, 0x1a2, 0x1ba, - 0x1c3, 0x3a6, 0x3a7, 0x3bb, 0x3d4, 0x09f, 0x1a0, 0x08f, 0x08d, 0x090, 0x098, 0x0a6, - 0x0b6, 0x0c4, 0x19f, 0x1af, 0x1bf, 0x399, 0x3bf, 0x3b4, 0x3c9, 0x3e7, 0x0a8, 0x1b6, - 0x0ab, 0x0a4, 0x0aa, 0x0b2, 0x0c2, 0x0c5, 0x198, 0x1a4, 0x1b8, 0x38c, 0x3a4, 0x3c4, - 0x3c6, 0x3dd, 0x3e8, 0x0ad, 0x3af, 0x192, 0x0bd, 0x0bc, 0x18e, 0x197, 0x19a, 0x1a3, - 0x1b1, 0x38d, 0x398, 0x3b7, 0x3d3, 0x3d1, 0x3db, 0x7dd, 0x0b4, 0x3de, 0x1a9, 0x19b, - 0x19c, 0x1a1, 0x1aa, 0x1ad, 0x1b3, 0x38b, 0x3b2, 0x3b8, 0x3ce, 0x3e1, 0x3e0, 0x7d2, - 0x7e5, 0x0b7, 0x7e3, 0x1bb, 0x1a8, 0x1a6, 0x1b0, 0x1b2, 0x1b7, 0x39b, 0x39a, 0x3ba, - 0x3b5, 0x3d6, 0x7d7, 0x3e4, 0x7d8, 0x7ea, 0x0ba, 0x7e8, 0x3a0, 0x1bd, 0x1b4, 0x38a, - 0x1c4, 0x392, 0x3aa, 0x3b0, 0x3bc, 0x3d7, 0x7d4, 0x7dc, 0x7db, 0x7d5, 0x7f0, 0x0c1, - 0x7fb, 0x3c8, 0x3a3, 0x395, 0x39d, 0x3ac, 0x3ae, 0x3c5, 0x3d8, 0x3e2, 0x3e6, 0x7e4, - 0x7e7, 0x7e0, 0x7e9, 0x7f7, 0x190, 0x7f2, 0x393, 0x1be, 0x1c0, 0x394, 0x397, 0x3ad, - 0x3c3, 0x3c1, 0x3d2, 0x7da, 0x7d9, 0x7df, 0x7eb, 0x7f4, 0x7fa, 0x195, 0x7f8, 0x3bd, - 0x39c, 0x3ab, 0x3a8, 0x3b3, 0x3b9, 0x3d0, 0x3e3, 0x3e5, 0x7e2, 0x7de, 0x7ed, 0x7f1, - 0x7f9, 0x7fc, 0x193, 0xffd, 0x3dc, 0x3b6, 0x3c7, 0x3cc, 0x3cb, 0x3d9, 0x3da, 0x7d3, - 0x7e1, 0x7ee, 0x7ef, 0x7f5, 0x7f6, 0xffc, 0xfff, 0x19d, 0x1c2, 0x0b5, 0x0a1, 0x096, - 0x097, 0x095, 0x099, 0x0a0, 0x0a2, 0x0ac, 0x0a9, 0x0b1, 0x0b3, 0x0bb, 0x0c0, 0x18f, - 0x004, + 0x000, 0x006, 0x019, 0x03d, 0x09c, 0x0c6, 0x1a7, 0x390, 0x3c2, 0x3df, 0x7e6, 0x7f3, 0xffb, + 0x7ec, 0xffa, 0xffe, 0x38e, 0x005, 0x001, 0x008, 0x014, 0x037, 0x042, 0x092, 0x0af, 0x191, + 0x1a5, 0x1b5, 0x39e, 0x3c0, 0x3a2, 0x3cd, 0x7d6, 0x0ae, 0x017, 0x007, 0x009, 0x018, 0x039, + 0x040, 0x08e, 0x0a3, 0x0b8, 0x199, 0x1ac, 0x1c1, 0x3b1, 0x396, 0x3be, 0x3ca, 0x09d, 0x03c, + 0x015, 0x016, 0x01a, 0x03b, 0x044, 0x091, 0x0a5, 0x0be, 0x196, 0x1ae, 0x1b9, 0x3a1, 0x391, + 0x3a5, 0x3d5, 0x094, 0x09a, 0x036, 0x038, 0x03a, 0x041, 0x08c, 0x09b, 0x0b0, 0x0c3, 0x19e, + 0x1ab, 0x1bc, 0x39f, 0x38f, 0x3a9, 0x3cf, 0x093, 0x0bf, 0x03e, 0x03f, 0x043, 0x045, 0x09e, + 0x0a7, 0x0b9, 0x194, 0x1a2, 0x1ba, 0x1c3, 0x3a6, 0x3a7, 0x3bb, 0x3d4, 0x09f, 0x1a0, 0x08f, + 0x08d, 0x090, 0x098, 0x0a6, 0x0b6, 0x0c4, 0x19f, 0x1af, 0x1bf, 0x399, 0x3bf, 0x3b4, 0x3c9, + 0x3e7, 0x0a8, 0x1b6, 0x0ab, 0x0a4, 0x0aa, 0x0b2, 0x0c2, 0x0c5, 0x198, 0x1a4, 0x1b8, 0x38c, + 0x3a4, 0x3c4, 0x3c6, 0x3dd, 0x3e8, 0x0ad, 0x3af, 0x192, 0x0bd, 0x0bc, 0x18e, 0x197, 0x19a, + 0x1a3, 0x1b1, 0x38d, 0x398, 0x3b7, 0x3d3, 0x3d1, 0x3db, 0x7dd, 0x0b4, 0x3de, 0x1a9, 0x19b, + 0x19c, 0x1a1, 0x1aa, 0x1ad, 0x1b3, 0x38b, 0x3b2, 0x3b8, 0x3ce, 0x3e1, 0x3e0, 0x7d2, 0x7e5, + 0x0b7, 0x7e3, 0x1bb, 0x1a8, 0x1a6, 0x1b0, 0x1b2, 0x1b7, 0x39b, 0x39a, 0x3ba, 0x3b5, 0x3d6, + 0x7d7, 0x3e4, 0x7d8, 0x7ea, 0x0ba, 0x7e8, 0x3a0, 0x1bd, 0x1b4, 0x38a, 0x1c4, 0x392, 0x3aa, + 0x3b0, 0x3bc, 0x3d7, 0x7d4, 0x7dc, 0x7db, 0x7d5, 0x7f0, 0x0c1, 0x7fb, 0x3c8, 0x3a3, 0x395, + 0x39d, 0x3ac, 0x3ae, 0x3c5, 0x3d8, 0x3e2, 0x3e6, 0x7e4, 0x7e7, 0x7e0, 0x7e9, 0x7f7, 0x190, + 0x7f2, 0x393, 0x1be, 0x1c0, 0x394, 0x397, 0x3ad, 0x3c3, 0x3c1, 0x3d2, 0x7da, 0x7d9, 0x7df, + 0x7eb, 0x7f4, 0x7fa, 0x195, 0x7f8, 0x3bd, 0x39c, 0x3ab, 0x3a8, 0x3b3, 0x3b9, 0x3d0, 0x3e3, + 0x3e5, 0x7e2, 0x7de, 0x7ed, 0x7f1, 0x7f9, 0x7fc, 0x193, 0xffd, 0x3dc, 0x3b6, 0x3c7, 0x3cc, + 0x3cb, 0x3d9, 0x3da, 0x7d3, 0x7e1, 0x7ee, 0x7ef, 0x7f5, 0x7f6, 0xffc, 0xfff, 0x19d, 0x1c2, + 0x0b5, 0x0a1, 0x096, 0x097, 0x095, 0x099, 0x0a0, 0x0a2, 0x0ac, 0x0a9, 0x0b1, 0x0b3, 0x0bb, + 0x0c0, 0x18f, 0x004, ]; pub const BITS11: [u8; 289] = [ - 4, 5, 6, 7, 8, 8, 9, 10, 10, 10, 11, 11, 12, 11, 12, 12, - 10, 5, 4, 5, 6, 7, 7, 8, 8, 9, 9, 9, 10, 10, 10, 10, - 11, 8, 6, 5, 5, 6, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, - 10, 10, 8, 7, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 10, - 10, 10, 10, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, - 10, 10, 10, 10, 8, 8, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, - 9, 10, 10, 10, 10, 8, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, - 9, 10, 10, 10, 10, 10, 8, 9, 8, 8, 8, 8, 8, 8, 9, 9, - 9, 10, 10, 10, 10, 10, 10, 8, 10, 9, 8, 8, 9, 9, 9, 9, - 9, 10, 10, 10, 10, 10, 10, 11, 8, 10, 9, 9, 9, 9, 9, 9, - 9, 10, 10, 10, 10, 10, 10, 11, 11, 8, 11, 9, 9, 9, 9, 9, - 9, 10, 10, 10, 10, 10, 11, 10, 11, 11, 8, 11, 10, 9, 9, 10, - 9, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 8, 11, 10, 10, 10, - 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 9, 11, 10, 9, - 9, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 9, 11, 10, - 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 9, 12, - 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 12, 12, 9, - 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, - 5, + 4, 5, 6, 7, 8, 8, 9, 10, 10, 10, 11, 11, 12, 11, 12, 12, 10, 5, 4, 5, 6, 7, 7, 8, 8, 9, 9, 9, + 10, 10, 10, 10, 11, 8, 6, 5, 5, 6, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 8, 7, 6, 6, 6, 7, 7, + 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 8, 8, + 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 8, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 10, 10, + 10, 10, 10, 8, 9, 8, 8, 8, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 10, 10, 8, 10, 9, 8, 8, 9, 9, 9, + 9, 9, 10, 10, 10, 10, 10, 10, 11, 8, 10, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 11, 11, + 8, 11, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 11, 10, 11, 11, 8, 11, 10, 9, 9, 10, 9, 10, 10, + 10, 10, 10, 11, 11, 11, 11, 11, 8, 11, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, + 11, 9, 11, 10, 9, 9, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 9, 11, 10, 10, 10, 10, 10, + 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 9, 12, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, + 11, 12, 12, 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 5, ]; pub const SF_CODES: [u32; 121] = [ - 0x3ffe8, 0x3ffe6, 0x3ffe7, 0x3ffe5, 0x7fff5, 0x7fff1, 0x7ffed, 0x7fff6, 0x7ffee, 0x7ffef, 0x7fff0, 0x7fffc, - 0x7fffd, 0x7ffff, 0x7fffe, 0x7fff7, 0x7fff8, 0x7fffb, 0x7fff9, 0x3ffe4, 0x7fffa, 0x3ffe3, 0x1ffef, 0x1fff0, - 0xfff5, 0x1ffee, 0xfff2, 0xfff3, 0xfff4, 0xfff1, 0x7ff6, 0x7ff7, 0x3ff9, 0x3ff5, 0x3ff7, 0x3ff3, - 0x3ff6, 0x3ff2, 0x1ff7, 0x1ff5, 0xff9, 0xff7, 0xff6, 0x7f9, 0xff4, 0x7f8, 0x3f9, 0x3f7, - 0x3f5, 0x1f8, 0x1f7, 0x0fa, 0x0f8, 0x0f6, 0x079, 0x03a, 0x038, 0x01a, 0x00b, 0x004, - 0x000, 0x00a, 0x00c, 0x01b, 0x039, 0x03b, 0x078, 0x07a, 0x0f7, 0x0f9, 0x1f6, 0x1f9, - 0x3f4, 0x3f6, 0x3f8, 0x7f5, 0x7f4, 0x7f6, 0x7f7, 0xff5, 0xff8, 0x1ff4, 0x1ff6, 0x1ff8, - 0x3ff8, 0x3ff4, 0xfff0, 0x7ff4, 0xfff6, 0x7ff5, 0x3ffe2, 0x7ffd9, 0x7ffda, 0x7ffdb, 0x7ffdc, 0x7ffdd, - 0x7ffde, 0x7ffd8, 0x7ffd2, 0x7ffd3, 0x7ffd4, 0x7ffd5, 0x7ffd6, 0x7fff2, 0x7ffdf, 0x7ffe7, 0x7ffe8, 0x7ffe9, - 0x7ffea, 0x7ffeb, 0x7ffe6, 0x7ffe0, 0x7ffe1, 0x7ffe2, 0x7ffe3, 0x7ffe4, 0x7ffe5, 0x7ffd7, 0x7ffec, 0x7fff4, - 0x7fff3, + 0x3ffe8, 0x3ffe6, 0x3ffe7, 0x3ffe5, 0x7fff5, 0x7fff1, 0x7ffed, 0x7fff6, 0x7ffee, 0x7ffef, + 0x7fff0, 0x7fffc, 0x7fffd, 0x7ffff, 0x7fffe, 0x7fff7, 0x7fff8, 0x7fffb, 0x7fff9, 0x3ffe4, + 0x7fffa, 0x3ffe3, 0x1ffef, 0x1fff0, 0xfff5, 0x1ffee, 0xfff2, 0xfff3, 0xfff4, 0xfff1, 0x7ff6, + 0x7ff7, 0x3ff9, 0x3ff5, 0x3ff7, 0x3ff3, 0x3ff6, 0x3ff2, 0x1ff7, 0x1ff5, 0xff9, 0xff7, 0xff6, + 0x7f9, 0xff4, 0x7f8, 0x3f9, 0x3f7, 0x3f5, 0x1f8, 0x1f7, 0x0fa, 0x0f8, 0x0f6, 0x079, 0x03a, + 0x038, 0x01a, 0x00b, 0x004, 0x000, 0x00a, 0x00c, 0x01b, 0x039, 0x03b, 0x078, 0x07a, 0x0f7, + 0x0f9, 0x1f6, 0x1f9, 0x3f4, 0x3f6, 0x3f8, 0x7f5, 0x7f4, 0x7f6, 0x7f7, 0xff5, 0xff8, 0x1ff4, + 0x1ff6, 0x1ff8, 0x3ff8, 0x3ff4, 0xfff0, 0x7ff4, 0xfff6, 0x7ff5, 0x3ffe2, 0x7ffd9, 0x7ffda, + 0x7ffdb, 0x7ffdc, 0x7ffdd, 0x7ffde, 0x7ffd8, 0x7ffd2, 0x7ffd3, 0x7ffd4, 0x7ffd5, 0x7ffd6, + 0x7fff2, 0x7ffdf, 0x7ffe7, 0x7ffe8, 0x7ffe9, 0x7ffea, 0x7ffeb, 0x7ffe6, 0x7ffe0, 0x7ffe1, + 0x7ffe2, 0x7ffe3, 0x7ffe4, 0x7ffe5, 0x7ffd7, 0x7ffec, 0x7fff4, 0x7fff3, ]; pub const SF_BITS: [u8; 121] = [ - 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, - 19, 19, 19, 18, 19, 18, 17, 17, 16, 17, 16, 16, 16, 16, 15, 15, - 14, 14, 14, 14, 14, 14, 13, 13, 12, 12, 12, 11, 12, 11, 10, 10, - 10, 9, 9, 8, 8, 8, 7, 6, 6, 5, 4, 3, 1, 4, 4, 5, - 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 10, 11, 11, 11, 11, 12, - 12, 13, 13, 13, 14, 14, 16, 15, 16, 15, 18, 19, 19, 19, 19, 19, - 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, - 19, 19, 19, 19, 19, 19, 19, 19, 19, + 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 18, 19, 18, 17, 17, + 16, 17, 16, 16, 16, 16, 15, 15, 14, 14, 14, 14, 14, 14, 13, 13, 12, 12, 12, 11, 12, 11, 10, 10, + 10, 9, 9, 8, 8, 8, 7, 6, 6, 5, 4, 3, 1, 4, 4, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 10, 11, 11, + 11, 11, 12, 12, 13, 13, 13, 14, 14, 16, 15, 16, 15, 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, + 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, ]; pub const SWB_LONG_96: [u16; 42] = [ - 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, - 72, 80, 88, 96, 108, 120, 132, 144, 156, 172, 188, 212, 240, 276, 320, 384, - 448, 512, 576, 640, 704, 768, 832, 896, 960, 1024, + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 96, 108, 120, 132, + 144, 156, 172, 188, 212, 240, 276, 320, 384, 448, 512, 576, 640, 704, 768, 832, 896, 960, 1024, ]; pub const SWB_LONG_64: [u16; 48] = [ - 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, - 72, 80, 88, 100, 112, 124, 140, 156, 172, 192, 216, 240, 268, 304, 344, 384, - 424, 464, 504, 544, 584, 624, 664, 704, 744, 784, 824, 864, 904, 944, 984, 1024, + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 100, 112, 124, 140, + 156, 172, 192, 216, 240, 268, 304, 344, 384, 424, 464, 504, 544, 584, 624, 664, 704, 744, 784, + 824, 864, 904, 944, 984, 1024, ]; pub const SWB_LONG_48: [u16; 50] = [ - 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, - 88, 96, 108, 120, 132, 144, 160, 176, 196, 216, 240, 264, 292, 320, 352, 384, - 416, 448, 480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800, 832, 864, 896, - 928, 1024, + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 88, 96, 108, 120, 132, 144, 160, + 176, 196, 216, 240, 264, 292, 320, 352, 384, 416, 448, 480, 512, 544, 576, 608, 640, 672, 704, + 736, 768, 800, 832, 864, 896, 928, 1024, ]; pub const SWB_LONG_32: [u16; 52] = [ - 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, - 88, 96, 108, 120, 132, 144, 160, 176, 196, 216, 240, 264, 292, 320, 352, 384, - 416, 448, 480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800, 832, 864, 896, - 928, 960, 992, 1024, + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 88, 96, 108, 120, 132, 144, 160, + 176, 196, 216, 240, 264, 292, 320, 352, 384, 416, 448, 480, 512, 544, 576, 608, 640, 672, 704, + 736, 768, 800, 832, 864, 896, 928, 960, 992, 1024, ]; pub const SWB_LONG_24: [u16; 48] = [ - 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 52, 60, 68, 76, - 84, 92, 100, 108, 116, 124, 136, 148, 160, 172, 188, 204, 220, 240, 260, 284, - 308, 336, 364, 396, 432, 468, 508, 552, 600, 652, 704, 768, 832, 896, 960, 1024, + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 52, 60, 68, 76, 84, 92, 100, 108, 116, 124, 136, + 148, 160, 172, 188, 204, 220, 240, 260, 284, 308, 336, 364, 396, 432, 468, 508, 552, 600, 652, + 704, 768, 832, 896, 960, 1024, ]; pub const SWB_LONG_16: [u16; 44] = [ - 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 100, 112, 124, 136, - 148, 160, 172, 184, 196, 212, 228, 244, 260, 280, 300, 320, 344, 368, 396, 424, - 456, 492, 532, 572, 616, 664, 716, 772, 832, 896, 960, 1024, + 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 100, 112, 124, 136, 148, 160, 172, 184, 196, 212, + 228, 244, 260, 280, 300, 320, 344, 368, 396, 424, 456, 492, 532, 572, 616, 664, 716, 772, 832, + 896, 960, 1024, ]; pub const SWB_LONG_8: [u16; 41] = [ - 0, 12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144, 156, 172, 188, - 204, 220, 236, 252, 268, 288, 308, 328, 348, 372, 396, 420, 448, 476, 508, 544, - 580, 620, 664, 712, 764, 820, 880, 944, 1024, + 0, 12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144, 156, 172, 188, 204, 220, 236, 252, 268, + 288, 308, 328, 348, 372, 396, 420, 448, 476, 508, 544, 580, 620, 664, 712, 764, 820, 880, 944, + 1024, ]; -pub const SWB_SHORT_96: [u16; 13] = [ - 0, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 92, 128, -]; +pub const SWB_SHORT_96: [u16; 13] = [0, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 92, 128]; -pub const SWB_SHORT_48: [u16; 15] = [ - 0, 4, 8, 12, 16, 20, 28, 36, 44, 56, 68, 80, 96, 112, 128, -]; +pub const SWB_SHORT_48: [u16; 15] = [0, 4, 8, 12, 16, 20, 28, 36, 44, 56, 68, 80, 96, 112, 128]; pub const SWB_SHORT_24: [u16; 16] = [ 0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 64, 76, 92, 108, 128, diff --git a/src/av1_coef.rs b/src/av1_coef.rs index 7b09183..fba8e42 100644 --- a/src/av1_coef.rs +++ b/src/av1_coef.rs @@ -27,8 +27,9 @@ fn bcdf(arg: u16) -> [u16; 2] { [32768 - arg, 0] } -const EOB_BIN_1024_L: [u16; 10] = - [6698, 8334, 11961, 15762, 20186, 23862, 27434, 29326, 31082, 32050]; +const EOB_BIN_1024_L: [u16; 10] = [ + 6698, 8334, 11961, 15762, 20186, 23862, 27434, 29326, 31082, 32050, +]; // EOB_HI_BIT_64 (= eob_hi_bit[4][0]) comes from av1_coef_tables (the correct // TX_64X64 context; an earlier hardcode used [0][0] and desynced — caught by // the dav1d symbol trace). @@ -73,11 +74,23 @@ fn lo_ctx_2d(levels: &[u8], rc: usize, x: usize, y: usize) -> (usize, u32) { let hi_mag = mag; mag += l(2) + l(2 * STRIDE); let offset = LO_CTX_OFFSETS_2D[y.min(4)][x.min(4)] as usize; - (offset + if mag > 512 { 4 } else { ((mag + 64) >> 7) as usize }, hi_mag) + ( + offset + + if mag > 512 { + 4 + } else { + ((mag + 64) >> 7) as usize + }, + hi_mag, + ) } fn level_byte(tok: u32, is_hi: bool) -> u8 { - if is_hi { (tok + 0xc0) as u8 } else { (tok.wrapping_mul(0x41)) as u8 } + if is_hi { + (tok + 0xc0) as u8 + } else { + (tok.wrapping_mul(0x41)) as u8 + } } /// hi_tok (br_tok): base-3 with 3=continue. `hint` = full |level| on encode. @@ -170,13 +183,21 @@ fn code_block(c: &mut C, cdf: &mut CoefCdf, coeffs: &mut [i32]) -> boo if eob == 0 { // dc-only: DC via eob_base_tok[0] let h = coeffs[0].unsigned_abs(); - let et = c.symbol(&mut cdf.eob_base_tok[0], 3, h.min(3).saturating_sub(1) as usize); + let et = c.symbol( + &mut cdf.eob_base_tok[0], + 3, + h.min(3).saturating_sub(1) as usize, + ); let mut tok = et as u32 + 1; if et == 2 { tok = code_hi_tok(c, &mut cdf.br_tok[0], h); } let sign = c.bool_adapt(&mut cdf.dc_sign, coeffs[0] < 0); - let full = if tok == 15 { 15 + code_golomb(c, h.saturating_sub(15)) } else { tok }; + let full = if tok == 15 { + 15 + code_golomb(c, h.saturating_sub(15)) + } else { + tok + }; coeffs[0] = if sign { -(full as i32) } else { full as i32 }; return true; } @@ -186,7 +207,11 @@ fn code_block(c: &mut C, cdf: &mut CoefCdf, coeffs: &mut [i32]) -> boo let (xe, ye) = (rc_e >> SHIFT, rc_e & MASK); let eob_ctx = 1 + (eob > (2 << 6)) as usize + (eob > (4 << 6)) as usize; let he = coeffs[rc_e].unsigned_abs(); - let et = c.symbol(&mut cdf.eob_base_tok[eob_ctx], 3, he.min(3).saturating_sub(1) as usize); + let et = c.symbol( + &mut cdf.eob_base_tok[eob_ctx], + 3, + he.min(3).saturating_sub(1) as usize, + ); let tok_e = if et == 2 { let hctx = if (xe | ye) > 1 { 14 } else { 7 }; let t = code_hi_tok(c, &mut cdf.br_tok[hctx], he); @@ -210,7 +235,12 @@ fn code_block(c: &mut C, cdf: &mut CoefCdf, coeffs: &mut [i32]) -> boo let (_, hi_mag) = lo_ctx_2d(&levels, rc, x, y); let mag = hi_mag & 63; let yy = (y | x) as u32; - let hctx = (if yy > 1 { 14 } else { 7 }) + if mag > 12 { 6 } else { ((mag + 1) >> 1) as usize }; + let hctx = (if yy > 1 { 14 } else { 7 }) + + if mag > 12 { + 6 + } else { + ((mag + 1) >> 1) as usize + }; let t = code_hi_tok(c, &mut cdf.br_tok[hctx], h); levels[rc] = level_byte(t, true); t @@ -226,7 +256,11 @@ fn code_block(c: &mut C, cdf: &mut CoefCdf, coeffs: &mut [i32]) -> boo let base = c.symbol(&mut cdf.base_tok[0], 4, h0.min(3) as usize) as u32; let tok0 = if base == 3 { let mag = (levels[STRIDE] as u32 + levels[1] as u32 + levels[STRIDE + 1] as u32) & 63; - let hctx = if mag > 12 { 6 } else { ((mag + 1) >> 1) as usize }; + let hctx = if mag > 12 { + 6 + } else { + ((mag + 1) >> 1) as usize + }; code_hi_tok(c, &mut cdf.br_tok[hctx], h0) } else { base @@ -235,14 +269,26 @@ fn code_block(c: &mut C, cdf: &mut CoefCdf, coeffs: &mut [i32]) -> boo // ── signs + golomb: dc_sign (+dc golomb), then AC signs (increasing scan) ── let dsign = c.bool_adapt(&mut cdf.dc_sign, coeffs[0] < 0); - let dc_full = if tok0 == 15 { 15 + code_golomb(c, h0.saturating_sub(15)) } else { tok0 }; - coeffs[0] = if dsign { -(dc_full as i32) } else { dc_full as i32 }; + let dc_full = if tok0 == 15 { + 15 + code_golomb(c, h0.saturating_sub(15)) + } else { + tok0 + }; + coeffs[0] = if dsign { + -(dc_full as i32) + } else { + dc_full as i32 + }; for i in 1..=eob { let rc = SCAN_32X32[i] as usize; let t = tok_at[rc]; if t != 0 { let sign = c.bit((coeffs[rc] < 0) as u32) == 1; - let full = if t == 15 { 15 + code_golomb(c, coeffs[rc].unsigned_abs().saturating_sub(15)) } else { t }; + let full = if t == 15 { + 15 + code_golomb(c, coeffs[rc].unsigned_abs().saturating_sub(15)) + } else { + t + }; coeffs[rc] = if sign { -(full as i32) } else { full as i32 }; } } @@ -275,12 +321,12 @@ mod tests { #[test] fn coeff_block_roundtrips() { let cases: &[&[(usize, i32)]] = &[ - &[], // empty (all_zero) - &[(0, 1)], // DC only, +1 - &[(0, -7)], // DC only, -7 (hi_tok) - &[(0, 2), (32, 1), (1, 3)], // DC + 2 AC (scan 0,1,2) - &[(0, 40)], // DC golomb (level>15) - &[(0, -3), (32, -20), (1, 2), (2, 9)], // mixed signs + golomb AC + &[], // empty (all_zero) + &[(0, 1)], // DC only, +1 + &[(0, -7)], // DC only, -7 (hi_tok) + &[(0, 2), (32, 1), (1, 3)], // DC + 2 AC (scan 0,1,2) + &[(0, 40)], // DC golomb (level>15) + &[(0, -3), (32, -20), (1, 2), (2, 9)], // mixed signs + golomb AC &[(0, 1), (1, 1), (2, 1), (33, 1), (64, 1), (96, 1)], // a run of AC ]; for (ci, case) in cases.iter().enumerate() { @@ -298,7 +344,10 @@ mod tests { let mut out = vec![0i32; 1024]; decode_block_2d(&mut r, &mut dec_cdf, &mut out); assert_eq!(out, coeffs, "case {ci} round-trip mismatch"); - assert_eq!(enc_cdf.base_tok, dec_cdf.base_tok, "case {ci} CDF adaptation diverged"); + assert_eq!( + enc_cdf.base_tok, dec_cdf.base_tok, + "case {ci} CDF adaptation diverged" + ); } } } diff --git a/src/av1_coef_tables.rs b/src/av1_coef_tables.rs index cbb4627..082aa5a 100644 --- a/src/av1_coef_tables.rs +++ b/src/av1_coef_tables.rs @@ -1,9 +1,141 @@ // AUTO-GENERATED from dav1d cdf.c (qctx=3) + scan.c. AV1 coefficient // coding tables for TX_64X64 luma (tx_ctx=4 / clamped 3), 2D class. // Values are dav1d cumulative args; the coder converts to icdf (32768-x). -pub const SCAN_32X32: [u16; 1024] = [0, 32, 1, 2, 33, 64, 96, 65, 34, 3, 4, 35, 66, 97, 128, 160, 129, 98, 67, 36, 5, 6, 37, 68, 99, 130, 161, 192, 224, 193, 162, 131, 100, 69, 38, 7, 8, 39, 70, 101, 132, 163, 194, 225, 256, 288, 257, 226, 195, 164, 133, 102, 71, 40, 9, 10, 41, 72, 103, 134, 165, 196, 227, 258, 289, 320, 352, 321, 290, 259, 228, 197, 166, 135, 104, 73, 42, 11, 12, 43, 74, 105, 136, 167, 198, 229, 260, 291, 322, 353, 384, 416, 385, 354, 323, 292, 261, 230, 199, 168, 137, 106, 75, 44, 13, 14, 45, 76, 107, 138, 169, 200, 231, 262, 293, 324, 355, 386, 417, 448, 480, 449, 418, 387, 356, 325, 294, 263, 232, 201, 170, 139, 108, 77, 46, 15, 16, 47, 78, 109, 140, 171, 202, 233, 264, 295, 326, 357, 388, 419, 450, 481, 512, 544, 513, 482, 451, 420, 389, 358, 327, 296, 265, 234, 203, 172, 141, 110, 79, 48, 17, 18, 49, 80, 111, 142, 173, 204, 235, 266, 297, 328, 359, 390, 421, 452, 483, 514, 545, 576, 608, 577, 546, 515, 484, 453, 422, 391, 360, 329, 298, 267, 236, 205, 174, 143, 112, 81, 50, 19, 20, 51, 82, 113, 144, 175, 206, 237, 268, 299, 330, 361, 392, 423, 454, 485, 516, 547, 578, 609, 640, 672, 641, 610, 579, 548, 517, 486, 455, 424, 393, 362, 331, 300, 269, 238, 207, 176, 145, 114, 83, 52, 21, 22, 53, 84, 115, 146, 177, 208, 239, 270, 301, 332, 363, 394, 425, 456, 487, 518, 549, 580, 611, 642, 673, 704, 736, 705, 674, 643, 612, 581, 550, 519, 488, 457, 426, 395, 364, 333, 302, 271, 240, 209, 178, 147, 116, 85, 54, 23, 24, 55, 86, 117, 148, 179, 210, 241, 272, 303, 334, 365, 396, 427, 458, 489, 520, 551, 582, 613, 644, 675, 706, 737, 768, 800, 769, 738, 707, 676, 645, 614, 583, 552, 521, 490, 459, 428, 397, 366, 335, 304, 273, 242, 211, 180, 149, 118, 87, 56, 25, 26, 57, 88, 119, 150, 181, 212, 243, 274, 305, 336, 367, 398, 429, 460, 491, 522, 553, 584, 615, 646, 677, 708, 739, 770, 801, 832, 864, 833, 802, 771, 740, 709, 678, 647, 616, 585, 554, 523, 492, 461, 430, 399, 368, 337, 306, 275, 244, 213, 182, 151, 120, 89, 58, 27, 28, 59, 90, 121, 152, 183, 214, 245, 276, 307, 338, 369, 400, 431, 462, 493, 524, 555, 586, 617, 648, 679, 710, 741, 772, 803, 834, 865, 896, 928, 897, 866, 835, 804, 773, 742, 711, 680, 649, 618, 587, 556, 525, 494, 463, 432, 401, 370, 339, 308, 277, 246, 215, 184, 153, 122, 91, 60, 29, 30, 61, 92, 123, 154, 185, 216, 247, 278, 309, 340, 371, 402, 433, 464, 495, 526, 557, 588, 619, 650, 681, 712, 743, 774, 805, 836, 867, 898, 929, 960, 992, 961, 930, 899, 868, 837, 806, 775, 744, 713, 682, 651, 620, 589, 558, 527, 496, 465, 434, 403, 372, 341, 310, 279, 248, 217, 186, 155, 124, 93, 62, 31, 63, 94, 125, 156, 187, 218, 249, 280, 311, 342, 373, 404, 435, 466, 497, 528, 559, 590, 621, 652, 683, 714, 745, 776, 807, 838, 869, 900, 931, 962, 993, 994, 963, 932, 901, 870, 839, 808, 777, 746, 715, 684, 653, 622, 591, 560, 529, 498, 467, 436, 405, 374, 343, 312, 281, 250, 219, 188, 157, 126, 95, 127, 158, 189, 220, 251, 282, 313, 344, 375, 406, 437, 468, 499, 530, 561, 592, 623, 654, 685, 716, 747, 778, 809, 840, 871, 902, 933, 964, 995, 996, 965, 934, 903, 872, 841, 810, 779, 748, 717, 686, 655, 624, 593, 562, 531, 500, 469, 438, 407, 376, 345, 314, 283, 252, 221, 190, 159, 191, 222, 253, 284, 315, 346, 377, 408, 439, 470, 501, 532, 563, 594, 625, 656, 687, 718, 749, 780, 811, 842, 873, 904, 935, 966, 997, 998, 967, 936, 905, 874, 843, 812, 781, 750, 719, 688, 657, 626, 595, 564, 533, 502, 471, 440, 409, 378, 347, 316, 285, 254, 223, 255, 286, 317, 348, 379, 410, 441, 472, 503, 534, 565, 596, 627, 658, 689, 720, 751, 782, 813, 844, 875, 906, 937, 968, 999, 1000, 969, 938, 907, 876, 845, 814, 783, 752, 721, 690, 659, 628, 597, 566, 535, 504, 473, 442, 411, 380, 349, 318, 287, 319, 350, 381, 412, 443, 474, 505, 536, 567, 598, 629, 660, 691, 722, 753, 784, 815, 846, 877, 908, 939, 970, 1001, 1002, 971, 940, 909, 878, 847, 816, 785, 754, 723, 692, 661, 630, 599, 568, 537, 506, 475, 444, 413, 382, 351, 383, 414, 445, 476, 507, 538, 569, 600, 631, 662, 693, 724, 755, 786, 817, 848, 879, 910, 941, 972, 1003, 1004, 973, 942, 911, 880, 849, 818, 787, 756, 725, 694, 663, 632, 601, 570, 539, 508, 477, 446, 415, 447, 478, 509, 540, 571, 602, 633, 664, 695, 726, 757, 788, 819, 850, 881, 912, 943, 974, 1005, 1006, 975, 944, 913, 882, 851, 820, 789, 758, 727, 696, 665, 634, 603, 572, 541, 510, 479, 511, 542, 573, 604, 635, 666, 697, 728, 759, 790, 821, 852, 883, 914, 945, 976, 1007, 1008, 977, 946, 915, 884, 853, 822, 791, 760, 729, 698, 667, 636, 605, 574, 543, 575, 606, 637, 668, 699, 730, 761, 792, 823, 854, 885, 916, 947, 978, 1009, 1010, 979, 948, 917, 886, 855, 824, 793, 762, 731, 700, 669, 638, 607, 639, 670, 701, 732, 763, 794, 825, 856, 887, 918, 949, 980, 1011, 1012, 981, 950, 919, 888, 857, 826, 795, 764, 733, 702, 671, 703, 734, 765, 796, 827, 858, 889, 920, 951, 982, 1013, 1014, 983, 952, 921, 890, 859, 828, 797, 766, 735, 767, 798, 829, 860, 891, 922, 953, 984, 1015, 1016, 985, 954, 923, 892, 861, 830, 799, 831, 862, 893, 924, 955, 986, 1017, 1018, 987, 956, 925, 894, 863, 895, 926, 957, 988, 1019, 1020, 989, 958, 927, 959, 990, 1021, 1022, 991, 1023]; -pub const BASE_TOK_64: [[u16;3]; 41] = [[4137, 10847, 15682], [17824, 27001, 30058], [10204, 22796, 28291], [6076, 15935, 22125], [3852, 10937, 16816], [2252, 6324, 10131], [25840, 32016, 32662], [15109, 28268, 31531], [9385, 22231, 28340], [6082, 16672, 23479], [3318, 9427, 14681], [30594, 32574, 32718], [16836, 29552, 31859], [9556, 22542, 28356], [6305, 16725, 23540], [3376, 9895, 15184], [29383, 32617, 32745], [18891, 30809, 32401], [11688, 25942, 30687], [7468, 19469, 26651], [3909, 11358, 17012], [31564, 32736, 32748], [20906, 31611, 32600], [13191, 27621, 31537], [8768, 22029, 28676], [5079, 14109, 20906], [8192, 16384, 24576], [8192, 16384, 24576], [8192, 16384, 24576], [8192, 16384, 24576], [8192, 16384, 24576], [8192, 16384, 24576], [8192, 16384, 24576], [8192, 16384, 24576], [8192, 16384, 24576], [8192, 16384, 24576], [8192, 16384, 24576], [8192, 16384, 24576], [8192, 16384, 24576], [8192, 16384, 24576], [8192, 16384, 24576]]; -pub const BR_TOK_64: [[u16;3]; 21] = [[12162, 18785, 22648], [12749, 19697, 23806], [8580, 15297, 20346], [6169, 11749, 16543], [4836, 9391, 13448], [3821, 7711, 11613], [2228, 4601, 7070], [16319, 24725, 28280], [15698, 23277, 27168], [12726, 20368, 25047], [9912, 17015, 21976], [7888, 14220, 19179], [6777, 12284, 17018], [4492, 8590, 12252], [23249, 28904, 30947], [21050, 27908, 30512], [17440, 25340, 28949], [14059, 22018, 26541], [11288, 18903, 23898], [9411, 16342, 21428], [6278, 11588, 15944]]; -pub const EOB_BASE_TOK_64: [[u16;2]; 4] = [[12358, 24977], [31331, 32385], [32634, 32756], [30411, 32548]]; -pub const EOB_HI_BIT_64: [u16; 9] = [26064, 22098, 19613, 20525, 17595, 16618, 20497, 18989, 15513]; -pub const LO_CTX_OFFSETS_2D: [[u8;5];5] = [[0,1,6,6,21],[1,6,6,21,21],[6,6,21,21,21],[6,21,21,21,21],[21,21,21,21,21]]; +pub const SCAN_32X32: [u16; 1024] = [ + 0, 32, 1, 2, 33, 64, 96, 65, 34, 3, 4, 35, 66, 97, 128, 160, 129, 98, 67, 36, 5, 6, 37, 68, 99, + 130, 161, 192, 224, 193, 162, 131, 100, 69, 38, 7, 8, 39, 70, 101, 132, 163, 194, 225, 256, + 288, 257, 226, 195, 164, 133, 102, 71, 40, 9, 10, 41, 72, 103, 134, 165, 196, 227, 258, 289, + 320, 352, 321, 290, 259, 228, 197, 166, 135, 104, 73, 42, 11, 12, 43, 74, 105, 136, 167, 198, + 229, 260, 291, 322, 353, 384, 416, 385, 354, 323, 292, 261, 230, 199, 168, 137, 106, 75, 44, + 13, 14, 45, 76, 107, 138, 169, 200, 231, 262, 293, 324, 355, 386, 417, 448, 480, 449, 418, 387, + 356, 325, 294, 263, 232, 201, 170, 139, 108, 77, 46, 15, 16, 47, 78, 109, 140, 171, 202, 233, + 264, 295, 326, 357, 388, 419, 450, 481, 512, 544, 513, 482, 451, 420, 389, 358, 327, 296, 265, + 234, 203, 172, 141, 110, 79, 48, 17, 18, 49, 80, 111, 142, 173, 204, 235, 266, 297, 328, 359, + 390, 421, 452, 483, 514, 545, 576, 608, 577, 546, 515, 484, 453, 422, 391, 360, 329, 298, 267, + 236, 205, 174, 143, 112, 81, 50, 19, 20, 51, 82, 113, 144, 175, 206, 237, 268, 299, 330, 361, + 392, 423, 454, 485, 516, 547, 578, 609, 640, 672, 641, 610, 579, 548, 517, 486, 455, 424, 393, + 362, 331, 300, 269, 238, 207, 176, 145, 114, 83, 52, 21, 22, 53, 84, 115, 146, 177, 208, 239, + 270, 301, 332, 363, 394, 425, 456, 487, 518, 549, 580, 611, 642, 673, 704, 736, 705, 674, 643, + 612, 581, 550, 519, 488, 457, 426, 395, 364, 333, 302, 271, 240, 209, 178, 147, 116, 85, 54, + 23, 24, 55, 86, 117, 148, 179, 210, 241, 272, 303, 334, 365, 396, 427, 458, 489, 520, 551, 582, + 613, 644, 675, 706, 737, 768, 800, 769, 738, 707, 676, 645, 614, 583, 552, 521, 490, 459, 428, + 397, 366, 335, 304, 273, 242, 211, 180, 149, 118, 87, 56, 25, 26, 57, 88, 119, 150, 181, 212, + 243, 274, 305, 336, 367, 398, 429, 460, 491, 522, 553, 584, 615, 646, 677, 708, 739, 770, 801, + 832, 864, 833, 802, 771, 740, 709, 678, 647, 616, 585, 554, 523, 492, 461, 430, 399, 368, 337, + 306, 275, 244, 213, 182, 151, 120, 89, 58, 27, 28, 59, 90, 121, 152, 183, 214, 245, 276, 307, + 338, 369, 400, 431, 462, 493, 524, 555, 586, 617, 648, 679, 710, 741, 772, 803, 834, 865, 896, + 928, 897, 866, 835, 804, 773, 742, 711, 680, 649, 618, 587, 556, 525, 494, 463, 432, 401, 370, + 339, 308, 277, 246, 215, 184, 153, 122, 91, 60, 29, 30, 61, 92, 123, 154, 185, 216, 247, 278, + 309, 340, 371, 402, 433, 464, 495, 526, 557, 588, 619, 650, 681, 712, 743, 774, 805, 836, 867, + 898, 929, 960, 992, 961, 930, 899, 868, 837, 806, 775, 744, 713, 682, 651, 620, 589, 558, 527, + 496, 465, 434, 403, 372, 341, 310, 279, 248, 217, 186, 155, 124, 93, 62, 31, 63, 94, 125, 156, + 187, 218, 249, 280, 311, 342, 373, 404, 435, 466, 497, 528, 559, 590, 621, 652, 683, 714, 745, + 776, 807, 838, 869, 900, 931, 962, 993, 994, 963, 932, 901, 870, 839, 808, 777, 746, 715, 684, + 653, 622, 591, 560, 529, 498, 467, 436, 405, 374, 343, 312, 281, 250, 219, 188, 157, 126, 95, + 127, 158, 189, 220, 251, 282, 313, 344, 375, 406, 437, 468, 499, 530, 561, 592, 623, 654, 685, + 716, 747, 778, 809, 840, 871, 902, 933, 964, 995, 996, 965, 934, 903, 872, 841, 810, 779, 748, + 717, 686, 655, 624, 593, 562, 531, 500, 469, 438, 407, 376, 345, 314, 283, 252, 221, 190, 159, + 191, 222, 253, 284, 315, 346, 377, 408, 439, 470, 501, 532, 563, 594, 625, 656, 687, 718, 749, + 780, 811, 842, 873, 904, 935, 966, 997, 998, 967, 936, 905, 874, 843, 812, 781, 750, 719, 688, + 657, 626, 595, 564, 533, 502, 471, 440, 409, 378, 347, 316, 285, 254, 223, 255, 286, 317, 348, + 379, 410, 441, 472, 503, 534, 565, 596, 627, 658, 689, 720, 751, 782, 813, 844, 875, 906, 937, + 968, 999, 1000, 969, 938, 907, 876, 845, 814, 783, 752, 721, 690, 659, 628, 597, 566, 535, 504, + 473, 442, 411, 380, 349, 318, 287, 319, 350, 381, 412, 443, 474, 505, 536, 567, 598, 629, 660, + 691, 722, 753, 784, 815, 846, 877, 908, 939, 970, 1001, 1002, 971, 940, 909, 878, 847, 816, + 785, 754, 723, 692, 661, 630, 599, 568, 537, 506, 475, 444, 413, 382, 351, 383, 414, 445, 476, + 507, 538, 569, 600, 631, 662, 693, 724, 755, 786, 817, 848, 879, 910, 941, 972, 1003, 1004, + 973, 942, 911, 880, 849, 818, 787, 756, 725, 694, 663, 632, 601, 570, 539, 508, 477, 446, 415, + 447, 478, 509, 540, 571, 602, 633, 664, 695, 726, 757, 788, 819, 850, 881, 912, 943, 974, 1005, + 1006, 975, 944, 913, 882, 851, 820, 789, 758, 727, 696, 665, 634, 603, 572, 541, 510, 479, 511, + 542, 573, 604, 635, 666, 697, 728, 759, 790, 821, 852, 883, 914, 945, 976, 1007, 1008, 977, + 946, 915, 884, 853, 822, 791, 760, 729, 698, 667, 636, 605, 574, 543, 575, 606, 637, 668, 699, + 730, 761, 792, 823, 854, 885, 916, 947, 978, 1009, 1010, 979, 948, 917, 886, 855, 824, 793, + 762, 731, 700, 669, 638, 607, 639, 670, 701, 732, 763, 794, 825, 856, 887, 918, 949, 980, 1011, + 1012, 981, 950, 919, 888, 857, 826, 795, 764, 733, 702, 671, 703, 734, 765, 796, 827, 858, 889, + 920, 951, 982, 1013, 1014, 983, 952, 921, 890, 859, 828, 797, 766, 735, 767, 798, 829, 860, + 891, 922, 953, 984, 1015, 1016, 985, 954, 923, 892, 861, 830, 799, 831, 862, 893, 924, 955, + 986, 1017, 1018, 987, 956, 925, 894, 863, 895, 926, 957, 988, 1019, 1020, 989, 958, 927, 959, + 990, 1021, 1022, 991, 1023, +]; +pub const BASE_TOK_64: [[u16; 3]; 41] = [ + [4137, 10847, 15682], + [17824, 27001, 30058], + [10204, 22796, 28291], + [6076, 15935, 22125], + [3852, 10937, 16816], + [2252, 6324, 10131], + [25840, 32016, 32662], + [15109, 28268, 31531], + [9385, 22231, 28340], + [6082, 16672, 23479], + [3318, 9427, 14681], + [30594, 32574, 32718], + [16836, 29552, 31859], + [9556, 22542, 28356], + [6305, 16725, 23540], + [3376, 9895, 15184], + [29383, 32617, 32745], + [18891, 30809, 32401], + [11688, 25942, 30687], + [7468, 19469, 26651], + [3909, 11358, 17012], + [31564, 32736, 32748], + [20906, 31611, 32600], + [13191, 27621, 31537], + [8768, 22029, 28676], + [5079, 14109, 20906], + [8192, 16384, 24576], + [8192, 16384, 24576], + [8192, 16384, 24576], + [8192, 16384, 24576], + [8192, 16384, 24576], + [8192, 16384, 24576], + [8192, 16384, 24576], + [8192, 16384, 24576], + [8192, 16384, 24576], + [8192, 16384, 24576], + [8192, 16384, 24576], + [8192, 16384, 24576], + [8192, 16384, 24576], + [8192, 16384, 24576], + [8192, 16384, 24576], +]; +pub const BR_TOK_64: [[u16; 3]; 21] = [ + [12162, 18785, 22648], + [12749, 19697, 23806], + [8580, 15297, 20346], + [6169, 11749, 16543], + [4836, 9391, 13448], + [3821, 7711, 11613], + [2228, 4601, 7070], + [16319, 24725, 28280], + [15698, 23277, 27168], + [12726, 20368, 25047], + [9912, 17015, 21976], + [7888, 14220, 19179], + [6777, 12284, 17018], + [4492, 8590, 12252], + [23249, 28904, 30947], + [21050, 27908, 30512], + [17440, 25340, 28949], + [14059, 22018, 26541], + [11288, 18903, 23898], + [9411, 16342, 21428], + [6278, 11588, 15944], +]; +pub const EOB_BASE_TOK_64: [[u16; 2]; 4] = [ + [12358, 24977], + [31331, 32385], + [32634, 32756], + [30411, 32548], +]; +pub const EOB_HI_BIT_64: [u16; 9] = [ + 26064, 22098, 19613, 20525, 17595, 16618, 20497, 18989, 15513, +]; +pub const LO_CTX_OFFSETS_2D: [[u8; 5]; 5] = [ + [0, 1, 6, 6, 21], + [1, 6, 6, 21, 21], + [6, 6, 21, 21, 21], + [6, 21, 21, 21, 21], + [21, 21, 21, 21, 21], +]; diff --git a/src/av1_dct.rs b/src/av1_dct.rs index 4fe6fcd..1c82c01 100644 --- a/src/av1_dct.rs +++ b/src/av1_dct.rs @@ -191,8 +191,14 @@ mod tests { let d = Dct::new(n); let flat = vec![100i64; n]; let f = d.forward(&flat); - assert!(f[1..].iter().all(|&c| c.abs() <= 1), "AC of flat input not ~0: {f:?}"); + assert!( + f[1..].iter().all(|&c| c.abs() <= 1), + "AC of flat input not ~0: {f:?}" + ); let r = d.inverse(&f); - assert!(r.iter().all(|&v| (v - 100).abs() <= 2), "flat not recovered: {r:?}"); + assert!( + r.iter().all(|&v| (v - 100).abs() <= 2), + "flat not recovered: {r:?}" + ); } } diff --git a/src/av1_ec.rs b/src/av1_ec.rs index ef23367..b9e48a4 100644 --- a/src/av1_ec.rs +++ b/src/av1_ec.rs @@ -83,7 +83,12 @@ impl Default for Writer { impl Writer { pub fn new() -> Self { - Writer { low: 0, rng: 0x8000, cnt: -9, precarry: Vec::new() } + Writer { + low: 0, + rng: 0x8000, + cnt: -9, + precarry: Vec::new(), + } } /// Range split from the icdf boundaries `fl` (high) and `fh` (low) with @@ -229,7 +234,13 @@ pub struct Reader<'a> { impl<'a> Reader<'a> { pub fn new(data: &'a [u8]) -> Self { - let mut r = Reader { dif: 0, rng: 0x8000, cnt: -15, data, pos: 0 }; + let mut r = Reader { + dif: 0, + rng: 0x8000, + cnt: -15, + data, + pos: 0, + }; r.refill(); r } @@ -432,7 +443,9 @@ mod tests { let mut w = Writer::new(); let mut enc_cdfs: std::collections::HashMap> = Default::default(); for &(nsymbs, s) in &plan { - let cdf = enc_cdfs.entry(nsymbs).or_insert_with(|| uniform_cdf(nsymbs)); + let cdf = enc_cdfs + .entry(nsymbs) + .or_insert_with(|| uniform_cdf(nsymbs)); w.symbol(s, cdf, nsymbs); } let bytes = w.finish(); @@ -440,14 +453,19 @@ mod tests { let mut r = Reader::new(&bytes); let mut dec_cdfs: std::collections::HashMap> = Default::default(); for (i, &(nsymbs, s)) in plan.iter().enumerate() { - let cdf = dec_cdfs.entry(nsymbs).or_insert_with(|| uniform_cdf(nsymbs)); + let cdf = dec_cdfs + .entry(nsymbs) + .or_insert_with(|| uniform_cdf(nsymbs)); let got = r.symbol(cdf, nsymbs); assert_eq!(got, s, "symbol {i} mismatch (nsymbs={nsymbs})"); } assert_eq!(enc_cdfs, dec_cdfs, "CDF adaptation diverged enc vs dec"); let bits = bytes.len() as f64 * 8.0 / n as f64; - eprintln!("AV1 od_ec⇄msac: {n} symbols → {} bytes ({bits:.2} bits/sym)", bytes.len()); + eprintln!( + "AV1 od_ec⇄msac: {n} symbols → {} bytes ({bits:.2} bits/sym)", + bytes.len() + ); } #[test] @@ -471,7 +489,10 @@ mod tests { } let bps = bytes.len() as f64 * 8.0 / bits.len() as f64; eprintln!("AV1 bool coder: 90/10 skew → {bps:.3} bits/sym (entropy ≈ 0.47)"); - assert!(bps < 0.7, "skewed bool stream should compress below 0.7 bits/sym, got {bps}"); + assert!( + bps < 0.7, + "skewed bool stream should compress below 0.7 bits/sym, got {bps}" + ); } #[test] diff --git a/src/av1_frame.rs b/src/av1_frame.rs index 74be286..3d28019 100644 --- a/src/av1_frame.rs +++ b/src/av1_frame.rs @@ -19,16 +19,21 @@ // ═══════════════════════════════════════════════════════════════════════════ use crate::av1_ec::Writer; -use crate::av1_obu::{sequence_header_obu, temporal_delimiter, wrap_obu, write_frame_header, OBU_FRAME}; +use crate::av1_obu::{ + sequence_header_obu, temporal_delimiter, wrap_obu, write_frame_header, OBU_FRAME, +}; use crate::h264bits::BitWriter; // dav1d default-CDF cumulative args (src/cdf.c). icdf[i] = 32768 − arg[i]. -const PARTITION_64_CTX0: [u16; 9] = - [20137, 21547, 23078, 29566, 29837, 30261, 30524, 30892, 31724]; // 10 symbols -const KF_YMODE_00: [u16; 12] = - [15588, 17027, 19338, 20218, 20682, 21110, 21825, 23244, 24189, 28165, 29093, 30466]; // 13 -const UV_MODE_DC: [u16; 12] = - [22631, 24152, 25378, 25661, 25986, 26520, 27055, 27923, 28244, 30059, 30941, 31961]; // 13 +const PARTITION_64_CTX0: [u16; 9] = [ + 20137, 21547, 23078, 29566, 29837, 30261, 30524, 30892, 31724, +]; // 10 symbols +const KF_YMODE_00: [u16; 12] = [ + 15588, 17027, 19338, 20218, 20682, 21110, 21825, 23244, 24189, 28165, 29093, 30466, +]; // 13 +const UV_MODE_DC: [u16; 12] = [ + 22631, 24152, 25378, 25661, 25986, 26520, 27055, 27923, 28244, 30059, 30941, 31961, +]; // 13 // Coefficient-skip (all_zero / txb_skip) defaults, coef.skip[qctx=3][tx_ctx][ctx] // (dav1d cdf.c). Stored 2-entry [icdf, count] for the adaptive bool. @@ -81,8 +86,9 @@ fn encode_tile_flat_dc() -> Vec { // Coefficient CDFs for the nonzero luma-DC path (dav1d cdf.c, qctx=3), // all verified bit-for-bit against dav1d's per-symbol rng trace. -const EOB_BIN_1024_L: [u16; 10] = - [6698, 8334, 11961, 15762, 20186, 23862, 27434, 29326, 31082, 32050]; // [chroma=0] +const EOB_BIN_1024_L: [u16; 10] = [ + 6698, 8334, 11961, 15762, 20186, 23862, 27434, 29326, 31082, 32050, +]; // [chroma=0] const EOB_BASE_TOK_64: [u16; 2] = [12358, 24977]; // eob_base_tok[ctx=4][0][0] const BR_TOK_64: [u16; 3] = [12162, 18785, 22648]; // br_tok[imin(ctx,3)=3][0][0] const DC_SIGN_L: u16 = 16000; // dc_sign[chroma=0][ctx=0] @@ -137,7 +143,7 @@ fn encode_tile_dc(dc_tok: u32, dc_sign: bool) -> Vec { w.symbol(0, &mut ym, 13); // y_mode = DC let mut uv = cdf(&UV_MODE_DC); w.symbol(0, &mut uv, 13); // uv_mode = DC - // luma residual: all_zero = 0 (has the DC coeff) + // luma residual: all_zero = 0 (has the DC coeff) let mut luma_az = bcdf(COEF_SKIP_TX64_C0); w.bool_adapt(false, &mut luma_az); // eob_pt = 0 (dc-only) @@ -189,7 +195,7 @@ fn encode_tile_dc_ac(dc_lvl: u32, dc_neg: bool, ac_lvl: u32, ac_neg: bool) -> Ve w.bool_adapt(false, &mut az); // all_zero = 0 let mut eb = cdf(&EOB_BIN_1024_L); w.symbol(1, &mut eb, 11); // eob_pt = 1 - // eob coeff (scan[1]) via eob_base_tok[ctx=1]; tok = ac_lvl (≤2 ⇒ no hi) + // eob coeff (scan[1]) via eob_base_tok[ctx=1]; tok = ac_lvl (≤2 ⇒ no hi) let mut et = cdf(&EOB_BASE_TOK_64_C1); w.symbol((ac_lvl - 1) as usize, &mut et, 3); // DC (scan[0]) via base_tok[ctx=0]; tok = dc_lvl (≤2 ⇒ no hi) @@ -271,9 +277,21 @@ mod tests { let s = encode_flat_keyframe_64(); assert_eq!(s.len(), 21); assert_eq!(&s[0..2], &[0x12, 0x00], "temporal delimiter"); - assert_eq!(&s[2..10], &[0x0a, 0x06, 0x18, 0x15, 0x7f, 0xfd, 0xa0, 0x08], "seq header"); + assert_eq!( + &s[2..10], + &[0x0a, 0x06, 0x18, 0x15, 0x7f, 0xfd, 0xa0, 0x08], + "seq header" + ); assert_eq!(&s[10..12], &[0x32, 0x09], "OBU_FRAME header + size"); - assert_eq!(&s[12..19], &[0x18, 0x00, 0x00, 0x00, 0x50, 0x00, 0x00], "frame header"); - assert_eq!(&s[19..21], &[0x31, 0x80], "tile (skip=0, all-zero residual)"); + assert_eq!( + &s[12..19], + &[0x18, 0x00, 0x00, 0x00, 0x50, 0x00, 0x00], + "frame header" + ); + assert_eq!( + &s[19..21], + &[0x31, 0x80], + "tile (skip=0, all-zero residual)" + ); } } diff --git a/src/av1_intra.rs b/src/av1_intra.rs index 14a5207..638814a 100644 --- a/src/av1_intra.rs +++ b/src/av1_intra.rs @@ -35,7 +35,9 @@ fn sm_weights(n: usize) -> &'static [u8] { match n { 4 => &[255, 149, 85, 64], 8 => &[255, 197, 146, 105, 73, 50, 37, 32], - 16 => &[255, 225, 196, 170, 145, 123, 102, 84, 68, 54, 43, 33, 26, 20, 17, 16], + 16 => &[ + 255, 225, 196, 170, 145, 123, 102, 84, 68, 54, 43, 33, 26, 20, 17, 16, + ], 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, @@ -133,9 +135,21 @@ pub fn predict(mode: Mode, n: usize, top: &[u8], left: &[u8], topleft: u8) -> Ve /// Pick the intra mode minimising the sum of absolute residual (SAD) against /// the actual block, and return `(mode, residual)`. This is the encoder's /// per-block decision; residual is `block[i] - pred[i]` as i16. -pub fn choose_mode(n: usize, block: &[u8], top: &[u8], left: &[u8], topleft: u8) -> (Mode, Vec) { +pub fn choose_mode( + n: usize, + block: &[u8], + top: &[u8], + left: &[u8], + topleft: u8, +) -> (Mode, Vec) { const MODES: [Mode; 7] = [ - Mode::Dc, Mode::Vert, Mode::Horz, Mode::Paeth, Mode::Smooth, Mode::SmoothV, Mode::SmoothH, + Mode::Dc, + Mode::Vert, + Mode::Horz, + Mode::Paeth, + Mode::Smooth, + Mode::SmoothV, + Mode::SmoothH, ]; let mut best_mode = Mode::Dc; let mut best_sad = u64::MAX; @@ -171,7 +185,15 @@ mod tests { for &n in &[4usize, 8, 16, 32] { let top = vec![120u8; n]; let left = vec![120u8; n]; - for m in [Mode::Dc, Mode::Vert, Mode::Horz, Mode::Paeth, Mode::Smooth, Mode::SmoothV, Mode::SmoothH] { + for m in [ + Mode::Dc, + Mode::Vert, + Mode::Horz, + Mode::Paeth, + Mode::Smooth, + Mode::SmoothV, + Mode::SmoothH, + ] { let p = predict(m, n, &top, &left, 120); assert!( p.iter().all(|&v| (v as i32 - 120).abs() <= 1), @@ -233,14 +255,25 @@ mod tests { } let (mode, resid) = choose_mode(n, &block, &top, &left, top[0]); let energy: i64 = resid.iter().map(|&r| (r as i64).abs()).sum(); - assert_eq!(mode, Mode::Vert, "should pick vertical for a vertical block"); - assert_eq!(energy, 0, "vertical block must have zero residual under Vert"); + assert_eq!( + mode, + Mode::Vert, + "should pick vertical for a vertical block" + ); + assert_eq!( + energy, 0, + "vertical block must have zero residual under Vert" + ); } #[test] fn smooth_weights_present_for_all_sizes() { for &n in &[4usize, 8, 16, 32] { - assert_eq!(sm_weights(n).len(), n, "smooth weights wrong length for {n}"); + assert_eq!( + sm_weights(n).len(), + n, + "smooth weights wrong length for {n}" + ); } } } diff --git a/src/av1_obu.rs b/src/av1_obu.rs index f55fa24..6430d96 100644 --- a/src/av1_obu.rs +++ b/src/av1_obu.rs @@ -74,7 +74,7 @@ pub fn sequence_header_obu(w: u32, h: u32) -> Vec { bw.put_bits(0, 3); // seq_profile = 0 bw.put_flag(true); // still_picture = 1 bw.put_flag(true); // reduced_still_picture_header = 1 - // reduced path: operating_points_cnt=1, idc=0, tier=0, no decoder model + // reduced path: operating_points_cnt=1, idc=0, tier=0, no decoder model bw.put_bits(0, 5); // seq_level_idx[0] = 0 let wb = size_bits(w - 1); // frame_width_bits = ceil bits of (w-1) @@ -83,12 +83,12 @@ pub fn sequence_header_obu(w: u32, h: u32) -> Vec { bw.put_bits(hb - 1, 4); // frame_height_bits_minus_1 bw.put_bits(w - 1, wb); // max_frame_width_minus_1 bw.put_bits(h - 1, hb); // max_frame_height_minus_1 - // reduced: frame_id_numbers_present_flag = 0 (not coded) + // reduced: frame_id_numbers_present_flag = 0 (not coded) bw.put_flag(false); // use_128x128_superblock = 0 (64×64 SB) bw.put_flag(true); // enable_filter_intra = 1 bw.put_flag(true); // enable_intra_edge_filter = 1 - // reduced: all inter enable_* flags absent / 0 + // reduced: all inter enable_* flags absent / 0 bw.put_flag(false); // enable_superres = 0 bw.put_flag(true); // enable_cdef = 1 @@ -99,7 +99,7 @@ pub fn sequence_header_obu(w: u32, h: u32) -> Vec { bw.put_flag(false); // mono_chrome = 0 (profile 0) bw.put_flag(false); // color_description_present_flag = 0 bw.put_flag(false); // color_range = 0 (studio) - // profile 0 ⇒ subsampling_x = subsampling_y = 1 (4:2:0), not coded + // profile 0 ⇒ subsampling_x = subsampling_y = 1 (4:2:0), not coded bw.put_bits(0, 2); // chroma_sample_position = CSP_UNKNOWN bw.put_flag(false); // separate_uv_delta_q = 0 @@ -120,10 +120,10 @@ pub fn write_frame_header(bw: &mut BitWriter, _w: u32, _h: u32, base_q_idx: u8) // (reduced) frame_type=KEY_FRAME, show_frame=1, error_resilient_mode=1 — none coded bw.put_flag(false); // disable_cdf_update = 0 bw.put_flag(false); // allow_screen_content_tools = 0 - // frame_size_override=0 (reduced), order_hint absent, refresh=allFrames — none coded - // frame_size(): override 0 + superres disabled → no bits + // frame_size_override=0 (reduced), order_hint absent, refresh=allFrames — none coded + // frame_size(): override 0 + superres disabled → no bits bw.put_flag(false); // render_and_frame_size_different = 0 - // allow_intrabc absent (screen_content_tools=0); disable_frame_end_update_cdf=1 (reduced) + // allow_intrabc absent (screen_content_tools=0); disable_frame_end_update_cdf=1 (reduced) // tile_info() — single 64×64 tile for a ≤64×64 frame bw.put_flag(true); // uniform_tile_spacing_flag = 1 (no increments: maxLog2Tiles=0) @@ -144,7 +144,7 @@ pub fn write_frame_header(bw: &mut BitWriter, _w: u32, _h: u32, base_q_idx: u8) // loop_filter_params() (not CodedLossless, not intrabc ⇒ coded) — levels 0 = off bw.put_bits(0, 6); // loop_filter_level[0] = 0 bw.put_bits(0, 6); // loop_filter_level[1] = 0 - // level[0]||level[1] == 0 ⇒ level[2],[3] not coded + // level[0]||level[1] == 0 ⇒ level[2],[3] not coded bw.put_bits(0, 3); // loop_filter_sharpness = 0 bw.put_flag(true); // loop_filter_delta_enabled = 1 (matches libaom; harmless at level 0) bw.put_flag(false); // loop_filter_delta_update = 0 @@ -160,9 +160,9 @@ pub fn write_frame_header(bw: &mut BitWriter, _w: u32, _h: u32, base_q_idx: u8) // lr_params() — enable_restoration=0 ⇒ nothing // read_tx_mode() bw.put_flag(false); // tx_mode_select = 0 → TX_MODE_LARGEST - // frame_reference_mode / skip_mode_params — intra, nothing + // frame_reference_mode / skip_mode_params — intra, nothing bw.put_flag(false); // reduced_tx_set = 0 - // global_motion / film_grain — nothing + // global_motion / film_grain — nothing } /// The byte-aligned frame header (for verification / standalone inspection). @@ -183,7 +183,18 @@ mod tests { #[test] fn uleb128_roundtrip() { - let cases = [0u64, 1, 127, 128, 255, 256, 16383, 16384, 1 << 20, u32::MAX as u64]; + let cases = [ + 0u64, + 1, + 127, + 128, + 255, + 256, + 16383, + 16384, + 1 << 20, + u32::MAX as u64, + ]; for &v in &cases { let e = uleb128(v); // decode @@ -212,7 +223,11 @@ mod tests { // -frames:v 1 -c:v libaom-av1 -still-picture 1 ref.obu // First OBUs: 12 00 | 0a 06 18 15 7f fd a0 08 let expected = vec![0x0a, 0x06, 0x18, 0x15, 0x7f, 0xfd, 0xa0, 0x08]; - assert_eq!(sequence_header_obu(64, 64), expected, "seq header must match libaom byte-for-byte"); + assert_eq!( + sequence_header_obu(64, 64), + expected, + "seq header must match libaom byte-for-byte" + ); } #[test] @@ -220,7 +235,11 @@ mod tests { // Reference: bytes 0..7 of the OBU_FRAME payload from the same libaom // still-picture (after `32 09`): 18 00 00 00 50 00 00, then tile data. let expected = vec![0x18, 0x00, 0x00, 0x00, 0x50, 0x00, 0x00]; - assert_eq!(frame_header_bytes(64, 64, 128), expected, "frame header must match libaom"); + assert_eq!( + frame_header_bytes(64, 64, 128), + expected, + "frame header must match libaom" + ); } #[test] diff --git a/src/codec.rs b/src/codec.rs index af16697..85c6108 100644 --- a/src/codec.rs +++ b/src/codec.rs @@ -24,7 +24,11 @@ struct BitWriter { } impl BitWriter { fn new() -> Self { - BitWriter { buf: Vec::new(), cur: 0, nbits: 0 } + BitWriter { + buf: Vec::new(), + cur: 0, + nbits: 0, + } } fn bit(&mut self, b: u32) { self.cur = (self.cur << 1) | ((b & 1) as u8); @@ -116,7 +120,11 @@ fn choose_k(u: &[u64]) -> u32 { return 0; } let mean = (u.iter().map(|&x| x as u128).sum::() / u.len() as u128) as u64; - let k = if mean == 0 { 0 } else { 63 - mean.leading_zeros() }; + let k = if mean == 0 { + 0 + } else { + 63 - mean.leading_zeros() + }; k.min(30) } @@ -180,7 +188,11 @@ fn decode_residuals(br: &mut BitReader, n: usize) -> Vec { let psize = n / parts; let mut out = Vec::with_capacity(n); for p in 0..parts { - let cnt = if p == parts - 1 { n - psize * (parts - 1) } else { psize }; + let cnt = if p == parts - 1 { + n - psize * (parts - 1) + } else { + psize + }; let k = br.bits(5) as u32; for _ in 0..cnt { out.push(rice_decode(br, k)); @@ -197,7 +209,11 @@ fn autocorr(x: &[i32], lag: usize) -> Vec { .iter() .enumerate() .map(|(i, &xi)| { - let t = if half > 0.0 { (i as f64 - half) / half } else { 0.0 }; + let t = if half > 0.0 { + (i as f64 - half) / half + } else { + 0.0 + }; xi as f64 * (1.0 - t * t) }) .collect(); @@ -269,10 +285,19 @@ fn encode_block(bw: &mut BitWriter, x: &[i32]) { // tiny block → order-1 delta fallback (lpc_closed_form, a = 1) bw.bits(0, 6); let mut prev = 0i64; - let u: Vec = x.iter().map(|&xi| { let e = xi as i64 - prev; prev = xi as i64; zigzag(e) }).collect(); + let u: Vec = x + .iter() + .map(|&xi| { + let e = xi as i64 - prev; + prev = xi as i64; + zigzag(e) + }) + .collect(); let k = choose_k(&u); bw.bits(k as u64, 5); - for uu in u { rice_encode(bw, uu, k); } + for uu in u { + rice_encode(bw, uu, k); + } return; } let order = max_o; // = LPC_ORDER (12) for normal blocks; closed-form Levinson @@ -291,7 +316,9 @@ fn encode_block(bw: &mut BitWriter, x: &[i32]) { x[nn] as i64 } else { let mut p = 0i64; - for i in 0..order { p += q[i] as i64 * x[nn - 1 - i] as i64; } + for i in 0..order { + p += q[i] as i64 * x[nn - 1 - i] as i64; + } x[nn] as i64 - (p >> shift) }; zigzag(e) @@ -306,7 +333,12 @@ fn decode_block(br: &mut BitReader, bs: usize) -> Vec { let k = br.bits(5) as u32; let mut prev = 0i64; let mut out = Vec::with_capacity(bs); - for _ in 0..bs { let e = unzigzag(rice_decode(br, k)); let x = prev + e; out.push(x as i32); prev = x; } + for _ in 0..bs { + let e = unzigzag(rice_decode(br, k)); + let x = prev + e; + out.push(x as i32); + prev = x; + } return out; } let shift = br.bits(4) as i64; @@ -319,7 +351,9 @@ fn decode_block(br: &mut BitReader, bs: usize) -> Vec { out.push(e as i32); } else { let mut p = 0i64; - for i in 0..order { p += q[i] * out[nn - 1 - i] as i64; } + for i in 0..order { + p += q[i] * out[nn - 1 - i] as i64; + } out.push(((p >> shift) + e) as i32); // lpc_closed_form, order p } } @@ -402,7 +436,8 @@ pub fn selftest() -> i32 { for i in 0..n { for c in 0..ch { let t = i as f64 / 16000.0; - let v = 8000.0 * (2.0 * std::f64::consts::PI * (300.0 + 120.0 * c as f64) * t).sin(); + let v = + 8000.0 * (2.0 * std::f64::consts::PI * (300.0 + 120.0 * c as f64) * t).sin(); samples.push((v as i32) << 16); // canonical full-scale (16-bit source) } } diff --git a/src/flac.rs b/src/flac.rs index 38e5a75..17c6d04 100644 --- a/src/flac.rs +++ b/src/flac.rs @@ -13,7 +13,11 @@ fn crc8(d: &[u8]) -> u8 { for &b in d { c ^= b; for _ in 0..8 { - c = if c & 0x80 != 0 { (c << 1) ^ 0x07 } else { c << 1 }; + c = if c & 0x80 != 0 { + (c << 1) ^ 0x07 + } else { + c << 1 + }; } } c @@ -23,7 +27,11 @@ fn crc16(d: &[u8]) -> u16 { for &b in d { c ^= (b as u16) << 8; for _ in 0..8 { - c = if c & 0x8000 != 0 { (c << 1) ^ 0x8005 } else { c << 1 }; + c = if c & 0x8000 != 0 { + (c << 1) ^ 0x8005 + } else { + c << 1 + }; } } c @@ -37,7 +45,11 @@ struct W { } impl W { fn new() -> Self { - W { buf: Vec::new(), acc: 0, n: 0 } + W { + buf: Vec::new(), + acc: 0, + n: 0, + } } fn bits(&mut self, v: u64, nb: u32) { for i in (0..nb).rev() { @@ -63,8 +75,19 @@ fn write_utf8(w: &mut W, val: u64) { w.bits(val, 8); return; } - let nb = if val < 0x800 { 2 } else if val < 0x10000 { 3 } else if val < 0x200000 { 4 } - else if val < 0x4000000 { 5 } else if val < 0x80000000 { 6 } else { 7u32 }; + let nb = if val < 0x800 { + 2 + } else if val < 0x10000 { + 3 + } else if val < 0x200000 { + 4 + } else if val < 0x4000000 { + 5 + } else if val < 0x80000000 { + 6 + } else { + 7u32 + }; let lead = ((0xFFu32 << (8 - nb)) & 0xFF) as u64 | (val >> (6 * (nb - 1))); w.bits(lead, 8); for i in (0..nb - 1).rev() { @@ -90,8 +113,16 @@ fn choose_k(res: &[i64]) -> u32 { if res.is_empty() { return 0; } - let mean = res.iter().map(|&r| ((r << 1) ^ (r >> 63)) as u128).sum::() / res.len() as u128; - let k = if mean == 0 { 0 } else { 63 - (mean as u64).leading_zeros() }; + let mean = res + .iter() + .map(|&r| ((r << 1) ^ (r >> 63)) as u128) + .sum::() + / res.len() as u128; + let k = if mean == 0 { + 0 + } else { + 63 - (mean as u64).leading_zeros() + }; k.min(30) } @@ -125,11 +156,21 @@ fn write_residual(w: &mut W, res: &[i64]) { fn autocorr(x: &[i64], lag: usize) -> Vec { let n = x.len(); let half = (n as f64 - 1.0) / 2.0; - let w: Vec = x.iter().enumerate().map(|(i, &v)| { - let t = if half > 0.0 { (i as f64 - half) / half } else { 0.0 }; - v as f64 * (1.0 - t * t) - }).collect(); - (0..=lag).map(|k| (k..n).map(|i| w[i] * w[i - k]).sum()).collect() + let w: Vec = x + .iter() + .enumerate() + .map(|(i, &v)| { + let t = if half > 0.0 { + (i as f64 - half) / half + } else { + 0.0 + }; + v as f64 * (1.0 - t * t) + }) + .collect(); + (0..=lag) + .map(|k| (k..n).map(|i| w[i] * w[i - k]).sum()) + .collect() } fn levinson(r: &[f64], order: usize) -> Vec { @@ -140,14 +181,20 @@ fn levinson(r: &[f64], order: usize) -> Vec { } for i in 0..order { let mut acc = r[i + 1]; - for j in 0..i { acc -= a[j] * r[i - j]; } + for j in 0..i { + acc -= a[j] * r[i - j]; + } let k = acc / e; let mut na = a.clone(); na[i] = k; - for j in 0..i { na[j] = a[j] - k * a[i - 1 - j]; } + for j in 0..i { + na[j] = a[j] - k * a[i - 1 - j]; + } a = na; e *= 1.0 - k * k; - if e <= 0.0 { break; } + if e <= 0.0 { + break; + } } a } @@ -177,7 +224,11 @@ fn write_lpc(w: &mut W, x: &[i64], bps: u32, order: usize) { w.bits(0, 1); w.bits(0b100000 | (order - 1) as u64, 6); // LPC subframe, order w.bits(0, 1); // no wasted bits - let mask = if bps >= 64 { u64::MAX } else { (1u64 << bps) - 1 }; + let mask = if bps >= 64 { + u64::MAX + } else { + (1u64 << bps) - 1 + }; for &s in &x[..order] { w.bits((s as u64) & mask, bps); } @@ -187,11 +238,15 @@ fn write_lpc(w: &mut W, x: &[i64], bps: u32, order: usize) { for &qc in &q { w.bits((qc as u64) & cmask, LPC_PREC); } - let res: Vec = (order..x.len()).map(|n| { - let mut p = 0i64; - for j in 0..order { p += q[j] as i64 * x[n - 1 - j]; } - x[n] - (p >> shift) - }).collect(); + let res: Vec = (order..x.len()) + .map(|n| { + let mut p = 0i64; + for j in 0..order { + p += q[j] as i64 * x[n - 1 - j]; + } + x[n] - (p >> shift) + }) + .collect(); write_residual(w, &res); } @@ -200,14 +255,24 @@ fn write_fixed(w: &mut W, x: &[i64], bps: u32) { let mut best = 0usize; let mut best_sum = u128::MAX; for o in 0..=4.min(x.len().saturating_sub(1)) { - let s: u128 = residual_fixed(x, o).iter().map(|&r| r.unsigned_abs() as u128).sum(); - if s < best_sum { best_sum = s; best = o; } + let s: u128 = residual_fixed(x, o) + .iter() + .map(|&r| r.unsigned_abs() as u128) + .sum(); + if s < best_sum { + best_sum = s; + best = o; + } } let order = best; w.bits(0, 1); w.bits(0b001000 | order as u64, 6); w.bits(0, 1); - let mask = if bps >= 64 { u64::MAX } else { (1u64 << bps) - 1 }; + let mask = if bps >= 64 { + u64::MAX + } else { + (1u64 << bps) - 1 + }; for &s in &x[..order] { w.bits((s as u64) & mask, bps); } @@ -216,7 +281,11 @@ fn write_fixed(w: &mut W, x: &[i64], bps: u32) { /// Pick subframe type: CONSTANT for flat blocks, LPC for normal, FIXED for tiny. -/ fn write_subframe(w: &mut W, x: &[i64], bps: u32) { - let mask = if bps >= 64 { u64::MAX } else { (1u64 << bps) - 1 }; + let mask = if bps >= 64 { + u64::MAX + } else { + (1u64 << bps) - 1 + }; if x.iter().all(|&v| v == x[0]) { w.bits(0, 1); w.bits(0, 6); // CONSTANT @@ -331,36 +400,55 @@ impl<'a> R<'a> { fn bit(&mut self) -> u64 { let (byte, off) = (self.pos / 8, 7 - (self.pos % 8)); self.pos += 1; - if byte < self.d.len() { ((self.d[byte] >> off) & 1) as u64 } else { 0 } + if byte < self.d.len() { + ((self.d[byte] >> off) & 1) as u64 + } else { + 0 + } } fn bits(&mut self, n: u32) -> u64 { let mut v = 0u64; - for _ in 0..n { v = (v << 1) | self.bit(); } + for _ in 0..n { + v = (v << 1) | self.bit(); + } v } fn sbits(&mut self, n: u32) -> i64 { - if n == 0 { return 0; } + if n == 0 { + return 0; + } let v = self.bits(n); let sh = 64 - n; ((v << sh) as i64) >> sh } fn unary(&mut self) -> u32 { let mut q = 0u32; - while self.bit() == 0 { q += 1; } + while self.bit() == 0 { + q += 1; + } q } fn align(&mut self) { - if self.pos % 8 != 0 { self.pos += 8 - (self.pos % 8); } + if self.pos % 8 != 0 { + self.pos += 8 - (self.pos % 8); + } } } fn read_utf8(r: &mut R) { let b0 = r.bits(8); - if b0 < 0x80 { return; } + if b0 < 0x80 { + return; + } let mut nc = 0u32; let mut m = 0x40u64; - while b0 & m != 0 { nc += 1; m >>= 1; } - for _ in 0..nc { r.bits(8); } + while b0 & m != 0 { + nc += 1; + m >>= 1; + } + for _ in 0..nc { + r.bits(8); + } } fn decode_residual(r: &mut R, blocksize: usize, order: usize) -> Vec { @@ -370,12 +458,18 @@ fn decode_residual(r: &mut R, blocksize: usize, order: usize) -> Vec { let parts = 1usize << po; let mut res = Vec::with_capacity(blocksize - order); for p in 0..parts { - let cnt = if p == 0 { (blocksize >> po) - order } else { blocksize >> po }; + let cnt = if p == 0 { + (blocksize >> po) - order + } else { + blocksize >> po + }; let k = r.bits(pbits) as u32; let escape = (pbits == 4 && k == 0xF) || (pbits == 5 && k == 0x1F); if escape { let bw = r.bits(5) as u32; - for _ in 0..cnt { res.push(r.sbits(bw)); } + for _ in 0..cnt { + res.push(r.sbits(bw)); + } } else { for _ in 0..cnt { let q = r.unary(); @@ -423,7 +517,9 @@ fn decode_subframe(r: &mut R, blocksize: usize, bps: u32) -> Vec { for i in 0..res.len() { let n = order + i; let mut p = 0i64; - for j in 0..order { p += coeffs[j] * s[n - 1 - j]; } + for j in 0..order { + p += coeffs[j] * s[n - 1 - j]; + } s.push(res[i] + (p >> shift)); } s @@ -431,7 +527,9 @@ fn decode_subframe(r: &mut R, blocksize: usize, bps: u32) -> Vec { vec![0i64; blocksize] }; if wasted > 0 { - for v in s.iter_mut() { *v <<= wasted; } + for v in s.iter_mut() { + *v <<= wasted; + } } s } @@ -450,14 +548,19 @@ pub fn decode(data: &[u8]) -> Result<(Vec, u32, u16, u32), String> { let len = r.bits(24) as usize; let blk_start = r.pos; if btype == 0 { - r.bits(16); r.bits(16); r.bits(24); r.bits(24); // block/frame sizes + r.bits(16); + r.bits(16); + r.bits(24); + r.bits(24); // block/frame sizes rate = r.bits(20) as u32; channels = (r.bits(3) + 1) as u16; bps = (r.bits(5) + 1) as u32; total = r.bits(36); } r.pos = blk_start + len * 8; // skip to end of metadata block - if last == 1 { break; } + if last == 1 { + break; + } } if rate == 0 || channels == 0 { return Err("missing STREAMINFO".into()); @@ -467,7 +570,9 @@ pub fn decode(data: &[u8]) -> Result<(Vec, u32, u16, u32), String> { let mut got = 0u64; while got < total { // frame header - if r.bits(14) != 0b11111111111110 { return Err(format!("lost sync at sample {got}")); } + if r.bits(14) != 0b11111111111110 { + return Err(format!("lost sync at sample {got}")); + } r.bits(1); // reserved r.bits(1); // blocking strategy let bsc = r.bits(4); @@ -484,23 +589,53 @@ pub fn decode(data: &[u8]) -> Result<(Vec, u32, u16, u32), String> { 8..=15 => 256usize << (bsc - 8), _ => return Err("bad blocksize code".into()), }; - match src { 12 => { r.bits(8); } 13 | 14 => { r.bits(16); } _ => {} } + match src { + 12 => { + r.bits(8); + } + 13 | 14 => { + r.bits(16); + } + _ => {} + } r.bits(8); // CRC-8 (header is byte-aligned here) - // subframes (decorrelation modes give the "side" channel +1 bit) - let nsub = if cassign < 8 { (cassign + 1) as usize } else { 2 }; + // subframes (decorrelation modes give the "side" channel +1 bit) + let nsub = if cassign < 8 { + (cassign + 1) as usize + } else { + 2 + }; let mut sub: Vec> = Vec::with_capacity(nsub); for c in 0..nsub { let side_bonus = match cassign { - 0b1000 => if c == 1 { 1 } else { 0 }, // left/side - 0b1001 => if c == 0 { 1 } else { 0 }, // side/right - 0b1010 => if c == 1 { 1 } else { 0 }, // mid/side + 0b1000 => { + if c == 1 { + 1 + } else { + 0 + } + } // left/side + 0b1001 => { + if c == 0 { + 1 + } else { + 0 + } + } // side/right + 0b1010 => { + if c == 1 { + 1 + } else { + 0 + } + } // mid/side _ => 0, }; sub.push(decode_subframe(&mut r, bs, bps + side_bonus)); } r.align(); r.bits(16); // CRC-16 - // channel decorrelation → independent L/R + // channel decorrelation → independent L/R let frame: Vec> = match cassign { 0b1000 => { let (l, s) = (&sub[0], &sub[1]); @@ -512,8 +647,18 @@ pub fn decode(data: &[u8]) -> Result<(Vec, u32, u16, u32), String> { } 0b1010 => { let (m, s) = (&sub[0], &sub[1]); - let l: Vec = (0..bs).map(|i| { let m2 = (m[i] << 1) | (s[i] & 1); (m2 + s[i]) >> 1 }).collect(); - let rr: Vec = (0..bs).map(|i| { let m2 = (m[i] << 1) | (s[i] & 1); (m2 - s[i]) >> 1 }).collect(); + let l: Vec = (0..bs) + .map(|i| { + let m2 = (m[i] << 1) | (s[i] & 1); + (m2 + s[i]) >> 1 + }) + .collect(); + let rr: Vec = (0..bs) + .map(|i| { + let m2 = (m[i] << 1) | (s[i] & 1); + (m2 - s[i]) >> 1 + }) + .collect(); vec![l, rr] } _ => sub, diff --git a/src/h264.rs b/src/h264.rs index 573364b..76e401a 100644 --- a/src/h264.rs +++ b/src/h264.rs @@ -37,7 +37,11 @@ struct BitWriter { impl BitWriter { fn new() -> Self { - BitWriter { buf: Vec::new(), cur: 0, nbits: 0 } + BitWriter { + buf: Vec::new(), + cur: 0, + nbits: 0, + } } fn put_bit(&mut self, b: u32) { self.cur = (self.cur << 1) | ((b & 1) as u8); @@ -60,7 +64,7 @@ impl BitWriter { fn ue(&mut self, v: u32) { let code = v + 1; let nbits = 32 - code.leading_zeros(); // # of significant bits - // (nbits - 1) leading zeros, then `code` in nbits bits + // (nbits - 1) leading zeros, then `code` in nbits bits for _ in 0..(nbits - 1) { self.put_bit(0); } @@ -219,7 +223,7 @@ fn build_sps(width: u32, height: u32) -> Vec { w.put_bits(0, 8); // constraint_set flags + reserved w.put_bits(30, 8); // level_idc = 3.0 w.ue(0); // seq_parameter_set_id - // (baseline: no chroma_format_idc / bit_depth fields) + // (baseline: no chroma_format_idc / bit_depth fields) w.ue(0); // log2_max_frame_num_minus4 → frame_num is 4 bits w.ue(0); // pic_order_cnt_type = 0 w.ue(0); // log2_max_pic_order_cnt_lsb_minus4 → poc_lsb is 4 bits @@ -229,7 +233,7 @@ fn build_sps(width: u32, height: u32) -> Vec { w.ue(mbh - 1); // pic_height_in_map_units_minus1 w.put_flag(true); // frame_mbs_only_flag w.put_flag(false); // direct_8x8_inference_flag - // frame cropping for non-multiple-of-16 dimensions (4:2:0 → CropUnit 2×2) + // frame cropping for non-multiple-of-16 dimensions (4:2:0 → CropUnit 2×2) let crop_r = (mbw * 16 - width) / 2; let crop_b = (mbh * 16 - height) / 2; if crop_r != 0 || crop_b != 0 { @@ -328,7 +332,7 @@ fn build_idr_slice(width: u32, height: u32, rgba: &[u8], idr_id: u32) -> Vec bw.put_bits(0, 4); // frame_num (4 bits; IDR → 0) bw.ue(idr_id); // idr_pic_id bw.put_bits(0, 4); // pic_order_cnt_lsb (4 bits) - // dec_ref_pic_marking (IDR): no_output_of_prior_pics_flag, long_term_reference_flag + // dec_ref_pic_marking (IDR): no_output_of_prior_pics_flag, long_term_reference_flag bw.put_flag(false); bw.put_flag(false); bw.se(0); // slice_qp_delta (QP=26; irrelevant for I_PCM) @@ -338,7 +342,7 @@ fn build_idr_slice(width: u32, height: u32, rgba: &[u8], idr_id: u32) -> Vec for mbx in 0..mbw { bw.ue(25); // mb_type = I_PCM bw.align_zero(); // pcm_alignment_zero_bit(s) - // luma 16×16 + // luma 16×16 for j in 0..16 { for i in 0..16 { bw.put_byte(yp[(mby * 16 + j) * pw + (mbx * 16 + i)]); @@ -373,11 +377,7 @@ pub fn encode_frame(width: u32, height: u32, rgba: &[u8]) -> Result, Str /// Encode a sequence of RGBA8 frames as a **compressed** intra-only (all-IDR) /// H.264 Annex-B stream at [`DEFAULT_QP`], using the adaptive per-MB /// I_16x16/I_4x4 encoder. `frames[i]` is `width*height*4` bytes. -pub fn encode_sequence( - frames: &[Vec], - width: u32, - height: u32, -) -> Result, String> { +pub fn encode_sequence(frames: &[Vec], width: u32, height: u32) -> Result, String> { encode_sequence_qp(frames, width, height, DEFAULT_QP) } @@ -391,7 +391,8 @@ pub fn encode_sequence_qp( if width == 0 || height == 0 { return Err("H264: zero dimension".into()); } - crate::h264_intra::encode_sequence_adaptive_with_recon(frames, width, height, qp).map(|(s, _)| s) + crate::h264_intra::encode_sequence_adaptive_with_recon(frames, width, height, qp) + .map(|(s, _)| s) } /// Lossless I_PCM Annex-B stream (every MB stored raw). Exactly reconstructs @@ -448,10 +449,7 @@ mod tests { let frame = vec![128u8; (w * h * 4) as usize]; let stream = encode_frame(w, h, &frame).expect("encode"); // count start codes 00 00 00 01 - let starts = stream - .windows(4) - .filter(|x| *x == [0, 0, 0, 1]) - .count(); + let starts = stream.windows(4).filter(|x| *x == [0, 0, 0, 1]).count(); assert_eq!(starts, 3, "expected SPS+PPS+IDR start codes"); // first NAL after start code is SPS (type 7) assert_eq!(stream[4] & 0x1F, 7); diff --git a/src/h264_i4x4.rs b/src/h264_i4x4.rs index d89a115..31f0f50 100644 --- a/src/h264_i4x4.rs +++ b/src/h264_i4x4.rs @@ -97,15 +97,24 @@ pub fn predict4(mode: u8, n: &Neighbours) -> Option<[i32; 16]> { let (l0, l1, l2, l3) = (l[0], l[1], l[2], l[3]); set(&mut p, 0, 3, (l3 + 2 * l2 + l1 + 2) >> 2); let a = (l2 + 2 * l1 + l0 + 2) >> 2; - set(&mut p, 0, 2, a); set(&mut p, 1, 3, a); + set(&mut p, 0, 2, a); + set(&mut p, 1, 3, a); let b = (l1 + 2 * l0 + tl + 2) >> 2; - set(&mut p, 0, 1, b); set(&mut p, 1, 2, b); set(&mut p, 2, 3, b); + set(&mut p, 0, 1, b); + set(&mut p, 1, 2, b); + set(&mut p, 2, 3, b); let c = (l0 + 2 * tl + t0 + 2) >> 2; - set(&mut p, 0, 0, c); set(&mut p, 1, 1, c); set(&mut p, 2, 2, c); set(&mut p, 3, 3, c); + set(&mut p, 0, 0, c); + set(&mut p, 1, 1, c); + set(&mut p, 2, 2, c); + set(&mut p, 3, 3, c); let d = (tl + 2 * t0 + t1 + 2) >> 2; - set(&mut p, 1, 0, d); set(&mut p, 2, 1, d); set(&mut p, 3, 2, d); + set(&mut p, 1, 0, d); + set(&mut p, 2, 1, d); + set(&mut p, 3, 2, d); let e = (t0 + 2 * t1 + t2 + 2) >> 2; - set(&mut p, 2, 0, e); set(&mut p, 3, 1, e); + set(&mut p, 2, 0, e); + set(&mut p, 3, 1, e); set(&mut p, 3, 0, (t1 + 2 * t2 + t3 + 2) >> 2); } 5 => { @@ -116,18 +125,24 @@ pub fn predict4(mode: u8, n: &Neighbours) -> Option<[i32; 16]> { let (t0, t1, t2, t3) = (t[0], t[1], t[2], t[3]); let (l0, l1, l2) = (l[0], l[1], l[2]); let a = (tl + t0 + 1) >> 1; - set(&mut p, 0, 0, a); set(&mut p, 1, 2, a); + set(&mut p, 0, 0, a); + set(&mut p, 1, 2, a); let b = (t0 + t1 + 1) >> 1; - set(&mut p, 1, 0, b); set(&mut p, 2, 2, b); + set(&mut p, 1, 0, b); + set(&mut p, 2, 2, b); let c = (t1 + t2 + 1) >> 1; - set(&mut p, 2, 0, c); set(&mut p, 3, 2, c); + set(&mut p, 2, 0, c); + set(&mut p, 3, 2, c); set(&mut p, 3, 0, (t2 + t3 + 1) >> 1); let d = (l0 + 2 * tl + t0 + 2) >> 2; - set(&mut p, 0, 1, d); set(&mut p, 1, 3, d); + set(&mut p, 0, 1, d); + set(&mut p, 1, 3, d); let e = (tl + 2 * t0 + t1 + 2) >> 2; - set(&mut p, 1, 1, e); set(&mut p, 2, 3, e); + set(&mut p, 1, 1, e); + set(&mut p, 2, 3, e); let f = (t0 + 2 * t1 + t2 + 2) >> 2; - set(&mut p, 2, 1, f); set(&mut p, 3, 3, f); + set(&mut p, 2, 1, f); + set(&mut p, 3, 3, f); set(&mut p, 3, 1, (t1 + 2 * t2 + t3 + 2) >> 2); set(&mut p, 0, 2, (tl + 2 * l0 + l1 + 2) >> 2); set(&mut p, 0, 3, (l0 + 2 * l1 + l2 + 2) >> 2); @@ -140,19 +155,25 @@ pub fn predict4(mode: u8, n: &Neighbours) -> Option<[i32; 16]> { let (t0, t1, t2) = (t[0], t[1], t[2]); let (l0, l1, l2, l3) = (l[0], l[1], l[2], l[3]); let a = (tl + l0 + 1) >> 1; - set(&mut p, 0, 0, a); set(&mut p, 2, 1, a); + set(&mut p, 0, 0, a); + set(&mut p, 2, 1, a); let b = (l0 + 2 * tl + t0 + 2) >> 2; - set(&mut p, 1, 0, b); set(&mut p, 3, 1, b); + set(&mut p, 1, 0, b); + set(&mut p, 3, 1, b); set(&mut p, 2, 0, (tl + 2 * t0 + t1 + 2) >> 2); set(&mut p, 3, 0, (t0 + 2 * t1 + t2 + 2) >> 2); let c = (l0 + l1 + 1) >> 1; - set(&mut p, 0, 1, c); set(&mut p, 2, 2, c); + set(&mut p, 0, 1, c); + set(&mut p, 2, 2, c); let d = (tl + 2 * l0 + l1 + 2) >> 2; - set(&mut p, 1, 1, d); set(&mut p, 3, 2, d); + set(&mut p, 1, 1, d); + set(&mut p, 3, 2, d); let e = (l1 + l2 + 1) >> 1; - set(&mut p, 0, 2, e); set(&mut p, 2, 3, e); + set(&mut p, 0, 2, e); + set(&mut p, 2, 3, e); let f = (l0 + 2 * l1 + l2 + 2) >> 2; - set(&mut p, 1, 2, f); set(&mut p, 3, 3, f); + set(&mut p, 1, 2, f); + set(&mut p, 3, 3, f); set(&mut p, 0, 3, (l2 + l3 + 1) >> 1); set(&mut p, 1, 3, (l1 + 2 * l2 + l3 + 2) >> 2); } @@ -165,19 +186,25 @@ pub fn predict4(mode: u8, n: &Neighbours) -> Option<[i32; 16]> { let (t4, t5, t6) = (t[4], t[5], t[6]); set(&mut p, 0, 0, (t0 + t1 + 1) >> 1); let a = (t1 + t2 + 1) >> 1; - set(&mut p, 1, 0, a); set(&mut p, 0, 2, a); + set(&mut p, 1, 0, a); + set(&mut p, 0, 2, a); let b = (t2 + t3 + 1) >> 1; - set(&mut p, 2, 0, b); set(&mut p, 1, 2, b); + set(&mut p, 2, 0, b); + set(&mut p, 1, 2, b); let c = (t3 + t4 + 1) >> 1; - set(&mut p, 3, 0, c); set(&mut p, 2, 2, c); + set(&mut p, 3, 0, c); + set(&mut p, 2, 2, c); set(&mut p, 3, 2, (t4 + t5 + 1) >> 1); set(&mut p, 0, 1, (t0 + 2 * t1 + t2 + 2) >> 2); let d = (t1 + 2 * t2 + t3 + 2) >> 2; - set(&mut p, 1, 1, d); set(&mut p, 0, 3, d); + set(&mut p, 1, 1, d); + set(&mut p, 0, 3, d); let e = (t2 + 2 * t3 + t4 + 2) >> 2; - set(&mut p, 2, 1, e); set(&mut p, 1, 3, e); + set(&mut p, 2, 1, e); + set(&mut p, 1, 3, e); let f = (t3 + 2 * t4 + t5 + 2) >> 2; - set(&mut p, 3, 1, f); set(&mut p, 2, 3, f); + set(&mut p, 3, 1, f); + set(&mut p, 2, 3, f); set(&mut p, 3, 3, (t4 + 2 * t5 + t6 + 2) >> 2); } 8 => { @@ -189,13 +216,17 @@ pub fn predict4(mode: u8, n: &Neighbours) -> Option<[i32; 16]> { set(&mut p, 0, 0, (l0 + l1 + 1) >> 1); set(&mut p, 1, 0, (l0 + 2 * l1 + l2 + 2) >> 2); let a = (l1 + l2 + 1) >> 1; - set(&mut p, 2, 0, a); set(&mut p, 0, 1, a); + set(&mut p, 2, 0, a); + set(&mut p, 0, 1, a); let b = (l1 + 2 * l2 + l3 + 2) >> 2; - set(&mut p, 3, 0, b); set(&mut p, 1, 1, b); + set(&mut p, 3, 0, b); + set(&mut p, 1, 1, b); let c = (l2 + l3 + 1) >> 1; - set(&mut p, 2, 1, c); set(&mut p, 0, 2, c); + set(&mut p, 2, 1, c); + set(&mut p, 0, 2, c); let d = (l2 + 2 * l3 + l3 + 2) >> 2; - set(&mut p, 3, 1, d); set(&mut p, 1, 2, d); + set(&mut p, 3, 1, d); + set(&mut p, 1, 2, d); for &(x, y) in &[(3, 2), (1, 3), (0, 3), (2, 2), (2, 3), (3, 3)] { set(&mut p, x, y, l3); } @@ -232,7 +263,14 @@ mod tests { use super::*; fn nb(left: [i32; 4], top: [i32; 8], tl: i32) -> Neighbours { - Neighbours { left, top, tl, avail_l: true, avail_t: true, avail_tr: true } + Neighbours { + left, + top, + tl, + avail_l: true, + avail_t: true, + avail_tr: true, + } } #[test] @@ -284,7 +322,14 @@ mod tests { #[test] fn dc_availability() { // DC works with no neighbours (→128); directional modes return None. - let none = Neighbours { left: [0; 4], top: [0; 8], tl: 0, avail_l: false, avail_t: false, avail_tr: false }; + let none = Neighbours { + left: [0; 4], + top: [0; 8], + tl: 0, + avail_l: false, + avail_t: false, + avail_tr: false, + }; assert!(predict4(2, &none).is_some()); assert_eq!(predict4(2, &none).unwrap()[0], 128); assert!(predict4(0, &none).is_none()); @@ -303,11 +348,19 @@ use crate::h264_intra::{fwd_core, inv_core, pos_class, MF, V}; /// decoded (replicate top[3]); the rest are interior and always available. /// (Derived from §6.4.11.4 + the Inverse4x4LumaBlockScan, §8.3.1.) #[derive(Clone, Copy)] -enum TrGate { Top, TopRight, Always, Never } +enum TrGate { + Top, + TopRight, + Always, + Never, +} const TR_GATE: [TrGate; 16] = { use TrGate::*; // blk: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 - [Top, Top, Always, Never, Top, TopRight, Always, Never, Always, Always, Always, Never, Always, Never, Always, Never] + [ + Top, Top, Always, Never, Top, TopRight, Always, Never, Always, Always, Always, Never, + Always, Never, Always, Never, + ] }; /// Gather the neighbour samples for the 4×4 block `blk` (scan index) at MB-pixel @@ -315,8 +368,16 @@ const TR_GATE: [TrGate; 16] = { /// samples are replicated from top[3], matching the H.264 reference decoders. #[allow(clippy::too_many_arguments)] fn gather( - rec: &[u8], pw: usize, px: usize, py: usize, ux: usize, uy: usize, blk: usize, - avail_l_mb: bool, avail_t_mb: bool, avail_tr_mb: bool, + rec: &[u8], + pw: usize, + px: usize, + py: usize, + ux: usize, + uy: usize, + blk: usize, + avail_l_mb: bool, + avail_t_mb: bool, + avail_tr_mb: bool, ) -> Neighbours { let avail_l = ux > 0 || avail_l_mb; let avail_t = uy > 0 || avail_t_mb; @@ -340,13 +401,24 @@ fn gather( } for i in 0..4 { let tx = px + 4 + i; - top[4 + i] = if avail_tr && tx < pw { rec[(py - 1) * pw + tx] as i32 } else { top[3] }; + top[4 + i] = if avail_tr && tx < pw { + rec[(py - 1) * pw + tx] as i32 + } else { + top[3] + }; } } if avail_l && avail_t { tl = rec[(py - 1) * pw + (px - 1)] as i32; } - Neighbours { left, top, tl, avail_l, avail_t, avail_tr } + Neighbours { + left, + top, + tl, + avail_l, + avail_t, + avail_tr, + } } pub struct I4x4Luma { @@ -364,21 +436,44 @@ pub struct I4x4Luma { /// path in h264_intra.rs exactly. #[allow(clippy::too_many_arguments)] pub fn encode_luma_i4x4( - src: &[u8], rec: &mut [u8], pw: usize, _ph: usize, - mbx: usize, mby: usize, qp: i32, blk_xy: &[(usize, usize); 16], - avail_l_mb: bool, avail_t_mb: bool, avail_tr_mb: bool, + src: &[u8], + rec: &mut [u8], + pw: usize, + _ph: usize, + mbx: usize, + mby: usize, + qp: i32, + blk_xy: &[(usize, usize); 16], + avail_l_mb: bool, + avail_t_mb: bool, + avail_tr_mb: bool, ) -> I4x4Luma { let qbits = 15 + qp / 6; let shift = qp / 6; let rem = (qp % 6) as usize; let f = (1i64 << qbits) / 3; - let mut out = I4x4Luma { coeffs: [[0; 16]; 16], modes: [2; 16], any_nonzero: false }; + let mut out = I4x4Luma { + coeffs: [[0; 16]; 16], + modes: [2; 16], + any_nonzero: false, + }; let mb_x0 = mbx * 16; for blk in 0..16 { let (bx, by) = blk_xy[blk]; let px = mb_x0 + bx; let py = mby * 16 + by; - let n = gather(rec, pw, px, py, bx / 4, by / 4, blk, avail_l_mb, avail_t_mb, avail_tr_mb); + let n = gather( + rec, + pw, + px, + py, + bx / 4, + by / 4, + blk, + avail_l_mb, + avail_t_mb, + avail_tr_mb, + ); let mut best_mode = 2u8; let mut best_pred = [0i32; 16]; let mut best_sad = u64::MAX; @@ -391,13 +486,18 @@ pub fn encode_luma_i4x4( sad += (s - pp[yy * 4 + xx]).unsigned_abs() as u64; } } - if sad < best_sad { best_sad = sad; best_mode = m; best_pred = pp; } + if sad < best_sad { + best_sad = sad; + best_mode = m; + best_pred = pp; + } } } let mut resid = [0i32; 16]; for yy in 0..4 { for xx in 0..4 { - resid[yy * 4 + xx] = src[(py + yy) * pw + (px + xx)] as i32 - best_pred[yy * 4 + xx]; + resid[yy * 4 + xx] = + src[(py + yy) * pw + (px + xx)] as i32 - best_pred[yy * 4 + xx]; } } let wq = fwd_core(&resid); @@ -408,7 +508,9 @@ pub fn encode_luma_i4x4( let mf = MF[rem][cl] as i64; let zz = ((wq[i].abs() as i64 * mf + f) >> qbits) as i32; z[i] = if wq[i] < 0 { -zz } else { zz }; - if z[i] != 0 { out.any_nonzero = true; } + if z[i] != 0 { + out.any_nonzero = true; + } let vv = V[rem][cl]; deq[i] = if shift >= 4 { (z[i] * vv) << shift @@ -419,7 +521,8 @@ pub fn encode_luma_i4x4( let sp = inv_core(&deq); for yy in 0..4 { for xx in 0..4 { - rec[(py + yy) * pw + (px + xx)] = (best_pred[yy * 4 + xx] + sp[yy * 4 + xx]).clamp(0, 255) as u8; + rec[(py + yy) * pw + (px + xx)] = + (best_pred[yy * 4 + xx] + sp[yy * 4 + xx]).clamp(0, 255) as u8; } } out.coeffs[blk] = z; diff --git a/src/h264_inter.rs b/src/h264_inter.rs index 6f81f23..65e59b6 100644 --- a/src/h264_inter.rs +++ b/src/h264_inter.rs @@ -151,11 +151,15 @@ mod tests { assert_eq!(nals, 10, "expected SPS+PPS+IDR+7P start codes, got {nals}"); // a static clip (1 IDR + 7 skip P-slices) must be far smaller than the // same 8 frames coded as independent IDRs (all visibly different). - let diff_frames: Vec> = - (0..8).map(|t| frame(w as usize, h as usize, t * 50)).collect(); + let diff_frames: Vec> = (0..8) + .map(|t| frame(w as usize, h as usize, t * 50)) + .collect(); let idr_only = encode_ipppp(&diff_frames, w, h, 28, 2).expect("all-idr"); let idr_nals = idr_only.windows(4).filter(|x| *x == [0, 0, 0, 1]).count(); - assert_eq!(idr_nals, 10, "all-different frames should be 8 IDRs (+SPS+PPS)"); + assert_eq!( + idr_nals, 10, + "all-different frames should be 8 IDRs (+SPS+PPS)" + ); assert!( stream.len() * 3 < idr_only.len(), "skip stream {} should be ≪ all-IDR {}", @@ -168,10 +172,15 @@ mod tests { fn changed_frames_rekey() { let (w, h) = (32u32, 32u32); // each frame visibly different → every frame should re-key (IDR) - let frames: Vec> = (0..4).map(|t| frame(w as usize, h as usize, t * 60)).collect(); + let frames: Vec> = (0..4) + .map(|t| frame(w as usize, h as usize, t * 60)) + .collect(); let stream = encode_ipppp(&frames, w, h, 28, 2).expect("encode"); // SPS+PPS + 4 IDR = 6 start codes let nals = stream.windows(4).filter(|x| *x == [0, 0, 0, 1]).count(); - assert_eq!(nals, 6, "all-different frames should produce 4 IDRs (+SPS+PPS)"); + assert_eq!( + nals, 6, + "all-different frames should produce 4 IDRs (+SPS+PPS)" + ); } } diff --git a/src/h264_intra.rs b/src/h264_intra.rs index 293184f..c62fc8c 100644 --- a/src/h264_intra.rs +++ b/src/h264_intra.rs @@ -28,10 +28,22 @@ use crate::h264bits::{build_pps, build_sps, emit_nal, rgb_to_ycbcr601_limited}; // luma4x4BlkIdx → (x,y) pixel offset within the 16×16 MB (H.264 Z-order). const BLK_XY: [(usize, usize); 16] = [ - (0, 0), (4, 0), (0, 4), (4, 4), - (8, 0), (12, 0), (8, 4), (12, 4), - (0, 8), (4, 8), (0, 12), (4, 12), - (8, 8), (12, 8), (8, 12), (12, 12), + (0, 0), + (4, 0), + (0, 4), + (4, 4), + (8, 0), + (12, 0), + (8, 4), + (12, 4), + (0, 8), + (4, 8), + (0, 12), + (4, 12), + (8, 8), + (12, 8), + (8, 12), + (12, 12), ]; // zig-zag scan for a 4×4 block (frequency order used by CAVLC). @@ -244,7 +256,11 @@ impl<'a> Cavlc<'a> { let mut suffix_length: u32 = if tc > 10 && t1 < 3 { 1 } else { 0 }; for j in t1..tc { let level = nz[tc - 1 - j].1; - let mut level_code: i32 = if level > 0 { (level << 1) - 2 } else { (-level << 1) - 1 }; + let mut level_code: i32 = if level > 0 { + (level << 1) - 2 + } else { + (-level << 1) - 1 + }; if j == t1 && t1 < 3 { level_code -= 2; } @@ -263,7 +279,8 @@ impl<'a> Cavlc<'a> { let prefix = lc >> suffix_length; if prefix < 15 { self.put_level_prefix(prefix); - self.bw.put_bits(lc & ((1 << suffix_length) - 1), suffix_length); + self.bw + .put_bits(lc & ((1 << suffix_length) - 1), suffix_length); } else { self.put_level_prefix(15); let escape = lc - (15u32 << suffix_length); @@ -325,7 +342,12 @@ impl<'a> Cavlc<'a> { } /// Encode a sequence of RGBA8 frames as intra-only (all-IDR) compressed H.264. -pub fn encode_sequence(frames: &[Vec], width: u32, height: u32, qp: i32) -> Result, String> { +pub fn encode_sequence( + frames: &[Vec], + width: u32, + height: u32, + qp: i32, +) -> Result, String> { if frames.is_empty() { return Err("H264-intra: no frames".into()); } @@ -370,7 +392,13 @@ pub fn encode_sequence_with_recon( Ok((out, recons)) } -fn encode_idr_intra(width: u32, height: u32, rgba: &[u8], qp: i32, idr: u32) -> Result, String> { +fn encode_idr_intra( + width: u32, + height: u32, + rgba: &[u8], + qp: i32, + idr: u32, +) -> Result, String> { Ok(encode_idr_intra_recon(width, height, rgba, qp, idr)?.0) } @@ -507,11 +535,30 @@ fn encode_idr_i4x4_recon( } // chroma (shared path) — always coded, so CBPChroma ≥ 1 let cm = encode_chroma_mb( - &src_cb, &src_cr, &mut rec_cb, &mut rec_cr, cw, mbx, mby, qp, avail_l, avail_t, + &src_cb, + &src_cr, + &mut rec_cb, + &mut rec_cr, + cw, + mbx, + mby, + qp, + avail_l, + avail_t, ); emit_mb_i4x4( - &mut bw, &luma, cbp_luma, &cm, &mut nz_luma, lw4, &mut mode_grid, - &mut nz_cb, &mut nz_cr, cw4, mbx, mby, + &mut bw, + &luma, + cbp_luma, + &cm, + &mut nz_luma, + lw4, + &mut mode_grid, + &mut nz_cb, + &mut nz_cr, + cw4, + mbx, + mby, ); } } @@ -540,7 +587,14 @@ fn encode_idr_i4x4_recon( /// macroblock — the distortion term `D` of the free energy. `rec` is indexed by /// the padded stride `pw`; `recon` (when Some) overrides `rec` with a private /// 16×16 candidate buffer (raster within the MB). -fn ssd_luma_mb(rec: &[u8], recon: Option<&[u8; 256]>, src: &[u8], pw: usize, mbx: usize, mby: usize) -> u64 { +fn ssd_luma_mb( + rec: &[u8], + recon: Option<&[u8; 256]>, + src: &[u8], + pw: usize, + mbx: usize, + mby: usize, +) -> u64 { let mut s = 0u64; for yy in 0..16 { for xx in 0..16 { @@ -593,7 +647,13 @@ pub fn encode_sequence_adaptive_with_recon( /// Encode one IDR frame with the adaptive per-MB type decision, returning just /// the slice RBSP (no NAL framing). Used by the MP4 muxer track builder. -pub fn encode_idr_adaptive(width: u32, height: u32, rgba: &[u8], qp: i32, idr: u32) -> Result, String> { +pub fn encode_idr_adaptive( + width: u32, + height: u32, + rgba: &[u8], + qp: i32, + idr: u32, +) -> Result, String> { Ok(encode_idr_adaptive_recon(width, height, rgba, qp, idr)?.0) } @@ -686,7 +746,16 @@ fn encode_idr_adaptive_recon( // Chroma is identical for both luma types (independent of luma) — // compute and commit once; it adds an equal constant to both costs. let cm = encode_chroma_mb( - &src_cb, &src_cr, &mut rec_cb, &mut rec_cr, cw, mbx, mby, qp, avail_l, avail_t, + &src_cb, + &src_cr, + &mut rec_cb, + &mut rec_cr, + cw, + mbx, + mby, + qp, + avail_l, + avail_t, ); // ── candidate A: I_4x4 (writes its reconstruction into rec_y) ── @@ -701,14 +770,34 @@ fn encode_idr_adaptive_recon( } let d4 = ssd_luma_mb(&rec_y, None, &src_y, pw, mbx, mby); let r4 = trial_rate_i4x4( - &i4, cbp_luma4, &cm, &mut nz_luma, lw4, &mut mode_grid, &mut nz_cb, &mut nz_cr, cw4, mbx, mby, + &i4, + cbp_luma4, + &cm, + &mut nz_luma, + lw4, + &mut mode_grid, + &mut nz_cb, + &mut nz_cr, + cw4, + mbx, + mby, ); // ── candidate B: I_16x16 (private recon; reads only out-of-MB // neighbours, so I_4x4's interior writes don't perturb it) ── let i16 = encode_luma_i16(&src_y, &rec_y, pw, mbx, mby, qp, avail_l, avail_t); let d16 = ssd_luma_mb(&rec_y, Some(&i16.recon), &src_y, pw, mbx, mby); - let r16 = trial_rate_i16(&i16, &cm, &mut nz_luma, lw4, &mut nz_cb, &mut nz_cr, cw4, mbx, mby); + let r16 = trial_rate_i16( + &i16, + &cm, + &mut nz_luma, + lw4, + &mut nz_cb, + &mut nz_cr, + cw4, + mbx, + mby, + ); // ── free-energy collapse: P(type) = δ(type − argmin F) ── let f4 = d4 as f64 + lambda * r4 as f64; @@ -720,7 +809,18 @@ fn encode_idr_adaptive_recon( rec_y[(mby * 16 + yy) * pw + (mbx * 16 + xx)] = i16.recon[yy * 16 + xx]; } } - emit_mb_i16(&mut bw, &i16, &cm, &mut nz_luma, lw4, &mut nz_cb, &mut nz_cr, cw4, mbx, mby); + emit_mb_i16( + &mut bw, + &i16, + &cm, + &mut nz_luma, + lw4, + &mut nz_cb, + &mut nz_cr, + cw4, + mbx, + mby, + ); // an I_16x16 MB contributes DC (mode 2) to neighbours' MPM for fy in mby * 4..mby * 4 + 4 { for fx in mbx * 4..mbx * 4 + 4 { @@ -730,8 +830,18 @@ fn encode_idr_adaptive_recon( } else { // rec_y already holds the I_4x4 reconstruction emit_mb_i4x4( - &mut bw, &i4, cbp_luma4, &cm, &mut nz_luma, lw4, &mut mode_grid, - &mut nz_cb, &mut nz_cr, cw4, mbx, mby, + &mut bw, + &i4, + cbp_luma4, + &cm, + &mut nz_luma, + lw4, + &mut mode_grid, + &mut nz_cb, + &mut nz_cr, + cw4, + mbx, + mby, ); } } @@ -762,16 +872,26 @@ fn encode_idr_adaptive_recon( /// read live from the committed grids, which is correct. #[allow(clippy::too_many_arguments)] fn trial_rate_i4x4( - luma: &crate::h264_i4x4::I4x4Luma, cbp_luma: u32, cm: &ChromaMb, - nz_luma: &mut [i32], lw4: usize, mode_grid: &mut [i32], nz_cb: &mut [i32], nz_cr: &mut [i32], - cw4: usize, mbx: usize, mby: usize, + luma: &crate::h264_i4x4::I4x4Luma, + cbp_luma: u32, + cm: &ChromaMb, + nz_luma: &mut [i32], + lw4: usize, + mode_grid: &mut [i32], + nz_cb: &mut [i32], + nz_cr: &mut [i32], + cw4: usize, + mbx: usize, + mby: usize, ) -> usize { let sl = snap_rect(nz_luma, lw4, mbx * 4, mby * 4, 4, 4); let sm = snap_rect(mode_grid, lw4, mbx * 4, mby * 4, 4, 4); let sb = snap_rect(nz_cb, cw4, mbx * 2, mby * 2, 2, 2); let sr = snap_rect(nz_cr, cw4, mbx * 2, mby * 2, 2, 2); let mut tb = BitWriter::new(); - emit_mb_i4x4(&mut tb, luma, cbp_luma, cm, nz_luma, lw4, mode_grid, nz_cb, nz_cr, cw4, mbx, mby); + emit_mb_i4x4( + &mut tb, luma, cbp_luma, cm, nz_luma, lw4, mode_grid, nz_cb, nz_cr, cw4, mbx, mby, + ); let bits = tb.bit_len(); restore_rect(nz_luma, lw4, mbx * 4, mby * 4, 4, 4, &sl); restore_rect(mode_grid, lw4, mbx * 4, mby * 4, 4, 4, &sm); @@ -784,8 +904,15 @@ fn trial_rate_i4x4( /// [`trial_rate_i4x4`]; I_16x16 does not touch the mode grid. #[allow(clippy::too_many_arguments)] fn trial_rate_i16( - i16: &I16Luma, cm: &ChromaMb, - nz_luma: &mut [i32], lw4: usize, nz_cb: &mut [i32], nz_cr: &mut [i32], cw4: usize, mbx: usize, mby: usize, + i16: &I16Luma, + cm: &ChromaMb, + nz_luma: &mut [i32], + lw4: usize, + nz_cb: &mut [i32], + nz_cr: &mut [i32], + cw4: usize, + mbx: usize, + mby: usize, ) -> usize { let sl = snap_rect(nz_luma, lw4, mbx * 4, mby * 4, 4, 4); let sb = snap_rect(nz_cb, cw4, mbx * 2, mby * 2, 2, 2); @@ -868,7 +995,7 @@ pub(crate) fn encode_idr_intra_recon( let lw4 = pw / 4; let lh4 = ph / 4; let mut nz_luma = vec![-1i32; lw4 * lh4]; // -1 = not yet coded - // chroma 4×4 TotalCoeff grids (cw/4 × ch/4) for chroma-AC nC context, per plane + // chroma 4×4 TotalCoeff grids (cw/4 × ch/4) for chroma-AC nC context, per plane let cw4 = cw / 4; let ch4 = ch / 4; let mut nz_cb = vec![-1i32; cw4 * ch4]; @@ -885,9 +1012,9 @@ pub(crate) fn encode_idr_intra_recon( bw.put_flag(false); // no_output_of_prior_pics bw.put_flag(false); // long_term_reference bw.se(qp - 26); // slice_qp_delta → SliceQP = qp - // deblocking_filter_control_present is set in the PPS, so signal it here. - // disable_deblocking_filter_idc = 1 → decoder skips the in-loop deblocking - // filter, so its reconstruction matches our (non-deblocked) recon bit-exact. + // deblocking_filter_control_present is set in the PPS, so signal it here. + // disable_deblocking_filter_idc = 1 → decoder skips the in-loop deblocking + // filter, so its reconstruction matches our (non-deblocked) recon bit-exact. bw.ue(1); // disable_deblocking_filter_idc = 1 for mby in 0..mbh { @@ -902,9 +1029,29 @@ pub(crate) fn encode_idr_intra_recon( } } let cm = encode_chroma_mb( - &src_cb, &src_cr, &mut rec_cb, &mut rec_cr, cw, mbx, mby, qp, avail_l, avail_t, + &src_cb, + &src_cr, + &mut rec_cb, + &mut rec_cr, + cw, + mbx, + mby, + qp, + avail_l, + avail_t, + ); + emit_mb_i16( + &mut bw, + &i16, + &cm, + &mut nz_luma, + lw4, + &mut nz_cb, + &mut nz_cr, + cw4, + mbx, + mby, ); - emit_mb_i16(&mut bw, &i16, &cm, &mut nz_luma, lw4, &mut nz_cb, &mut nz_cr, cw4, mbx, mby); } } bw.trailing_bits(); @@ -967,7 +1114,10 @@ fn encode_chroma_mb( [(Vec::new(), [[0; 16]; 4]), (Vec::new(), [[0; 16]; 4])]; let mut recon: [[u8; 64]; 2] = [[0u8; 64]; 2]; let mut cbp_chroma_ac = false; - for (pi, (src, pred)) in [(&src_cb, &pred_cb), (&src_cr, &pred_cr)].into_iter().enumerate() { + for (pi, (src, pred)) in [(&src_cb, &pred_cb), (&src_cr, &pred_cr)] + .into_iter() + .enumerate() + { let mut dc_vals = [0i32; 4]; // raster order of the 4 sub-blocks' W[0] let mut wblk: [[i32; 16]; 4] = [[0; 16]; 4]; for sb in 0..4 { @@ -1037,7 +1187,8 @@ fn encode_chroma_mb( let p = pred[sb] as i32; for yy in 0..4 { for xx in 0..4 { - recon[pi][(by + yy) * 8 + (bx + xx)] = (p + sp[yy * 4 + xx]).clamp(0, 255) as u8; + recon[pi][(by + yy) * 8 + (bx + xx)] = + (p + sp[yy * 4 + xx]).clamp(0, 255) as u8; } } ac_z[sb] = z; @@ -1056,7 +1207,10 @@ fn encode_chroma_mb( } } } - ChromaMb { planes, cbp_chroma_ac } + ChromaMb { + planes, + cbp_chroma_ac, + } } /// One I_16x16 luma candidate: the 16×16 reconstruction (raster within the MB), @@ -1064,9 +1218,9 @@ fn encode_chroma_mb( struct I16Luma { recon: [u8; 256], mode: u8, - dc_z: [i32; 16], // Hadamard-DC levels (raster blk grid) - ac_z: [[i32; 16]; 16], // per-block AC levels (raster within block) - cbp_luma_flag: u32, // 1 if any AC coeff nonzero + dc_z: [i32; 16], // Hadamard-DC levels (raster blk grid) + ac_z: [[i32; 16]; 16], // per-block AC levels (raster within block) + cbp_luma_flag: u32, // 1 if any AC coeff nonzero } /// Compute the I_16x16 luma candidate for one MB: SAD-pick the prediction mode @@ -1076,8 +1230,14 @@ struct I16Luma { /// reconstruction only if this candidate wins the per-MB free-energy decision. #[allow(clippy::needless_range_loop)] fn encode_luma_i16( - src_y: &[u8], rec_y: &[u8], pw: usize, mbx: usize, mby: usize, qp: i32, - avail_l: bool, avail_t: bool, + src_y: &[u8], + rec_y: &[u8], + pw: usize, + mbx: usize, + mby: usize, + qp: i32, + avail_l: bool, + avail_t: bool, ) -> I16Luma { let mut mode = 2u8; let mut pred16 = [0i32; 256]; @@ -1179,16 +1339,29 @@ fn encode_luma_i16( } } } - I16Luma { recon, mode, dc_z, ac_z, cbp_luma_flag: if cbp_luma_nonzero { 1 } else { 0 } } + I16Luma { + recon, + mode, + dc_z, + ac_z, + cbp_luma_flag: if cbp_luma_nonzero { 1 } else { 0 }, + } } /// Emit one I_16x16 macroblock (header + residual) into `bw`, updating the nC /// TotalCoeff grids. Shared by the I_16x16-only path and the adaptive path. #[allow(clippy::too_many_arguments)] fn emit_mb_i16( - bw: &mut BitWriter, i16: &I16Luma, cm: &ChromaMb, - nz_luma: &mut [i32], lw4: usize, nz_cb: &mut [i32], nz_cr: &mut [i32], cw4: usize, - mbx: usize, mby: usize, + bw: &mut BitWriter, + i16: &I16Luma, + cm: &ChromaMb, + nz_luma: &mut [i32], + lw4: usize, + nz_cb: &mut [i32], + nz_cr: &mut [i32], + cw4: usize, + mbx: usize, + mby: usize, ) { let cbp_chroma: u32 = if cm.cbp_chroma_ac { 2 } else { 1 }; let mb_type = 1 + i16.mode as u32 + 4 * cbp_chroma + 12 * i16.cbp_luma_flag; @@ -1218,9 +1391,18 @@ fn emit_mb_i16( /// residual) into `bw`, updating the nC grids and the frame-wide `mode_grid`. #[allow(clippy::too_many_arguments)] fn emit_mb_i4x4( - bw: &mut BitWriter, luma: &crate::h264_i4x4::I4x4Luma, cbp_luma: u32, cm: &ChromaMb, - nz_luma: &mut [i32], lw4: usize, mode_grid: &mut [i32], - nz_cb: &mut [i32], nz_cr: &mut [i32], cw4: usize, mbx: usize, mby: usize, + bw: &mut BitWriter, + luma: &crate::h264_i4x4::I4x4Luma, + cbp_luma: u32, + cm: &ChromaMb, + nz_luma: &mut [i32], + lw4: usize, + mode_grid: &mut [i32], + nz_cb: &mut [i32], + nz_cr: &mut [i32], + cw4: usize, + mbx: usize, + mby: usize, ) { let cbp_chroma: u32 = if cm.cbp_chroma_ac { 2 } else { 1 }; let cbp = cbp_luma | (cbp_chroma << 4); @@ -1239,7 +1421,11 @@ fn emit_mb_i4x4( bw.put_flag(true); } else { bw.put_flag(false); - let rem = if actual < pred_mode { actual } else { actual - 1 }; + let rem = if actual < pred_mode { + actual + } else { + actual - 1 + }; bw.put_bits(rem as u32, 3); } mode_grid[fy * lw4 + fx] = actual; @@ -1272,8 +1458,14 @@ fn emit_mb_i4x4( /// types. Updates the chroma nC grids. #[allow(clippy::too_many_arguments)] fn emit_chroma_residual( - cav: &mut Cavlc, cm: &ChromaMb, cbp_chroma: u32, - nz_cb: &mut [i32], nz_cr: &mut [i32], cw4: usize, mbx: usize, mby: usize, + cav: &mut Cavlc, + cm: &ChromaMb, + cbp_chroma: u32, + nz_cb: &mut [i32], + nz_cr: &mut [i32], + cw4: usize, + mbx: usize, + mby: usize, ) { for pi in 0..2 { cav.block(&cm.planes[pi].0, -1); @@ -1283,8 +1475,11 @@ fn emit_chroma_residual( let grid: &mut [i32] = if pi == 0 { nz_cb } else { nz_cr }; for sb in 0..4 { let nc = chroma_ac_nc(grid, cw4, mbx, mby, sb); - let ac_scan: Vec = - ZZ4.iter().skip(1).map(|&i| cm.planes[pi].1[sb][i]).collect(); + let ac_scan: Vec = ZZ4 + .iter() + .skip(1) + .map(|&i| cm.planes[pi].1[sb][i]) + .collect(); let tc = cav.block(&ac_scan, nc); set_chroma_ac_nz(grid, cw4, mbx, mby, sb, tc as i32); } @@ -1309,7 +1504,15 @@ fn snap_rect(grid: &[i32], w: usize, x0: usize, y0: usize, bw: usize, bh: usize) } out } -fn restore_rect(grid: &mut [i32], w: usize, x0: usize, y0: usize, bw: usize, bh: usize, saved: &[i32]) { +fn restore_rect( + grid: &mut [i32], + w: usize, + x0: usize, + y0: usize, + bw: usize, + bh: usize, + saved: &[i32], +) { let mut k = 0; for gy in y0..y0 + bh { for gx in x0..x0 + bw { @@ -1328,7 +1531,15 @@ fn rdo_lambda(qp: i32) -> f64 { // ── I_16x16 luma prediction (H.264 8.3.3): modes 0=V 1=H 2=DC 3=Plane ── // Produces a full 16×16 prediction from reconstructed left/top neighbours. // Returns None if the chosen mode's required neighbours are unavailable. -fn intra16_pred(rec: &[u8], pw: usize, mbx: usize, mby: usize, mode: u8, al: bool, at: bool) -> Option<[i32; 256]> { +fn intra16_pred( + rec: &[u8], + pw: usize, + mbx: usize, + mby: usize, + mode: u8, + al: bool, + at: bool, +) -> Option<[i32; 256]> { let x0 = mbx * 16; let y0 = mby * 16; let top = |i: usize| rec[(y0 - 1) * pw + (x0 + i)] as i32; @@ -1489,8 +1700,16 @@ fn c_shift(x: i64, s: i32) -> i64 { fn chroma_ac_nc(grid: &[i32], cw4: usize, mbx: usize, mby: usize, sb: usize) -> i32 { let gx = mbx * 2 + (sb % 2); let gy = mby * 2 + (sb / 2); - let left = if gx > 0 { grid[gy * cw4 + (gx - 1)] } else { -1 }; - let top = if gy > 0 { grid[(gy - 1) * cw4 + gx] } else { -1 }; + let left = if gx > 0 { + grid[gy * cw4 + (gx - 1)] + } else { + -1 + }; + let top = if gy > 0 { + grid[(gy - 1) * cw4 + gx] + } else { + -1 + }; match (left >= 0, top >= 0) { (true, true) => (left + top + 1) >> 1, (true, false) => left, @@ -1544,9 +1763,7 @@ mod roundtrip_tests { let qbits = 15 + qp / 6; let f = (1i64 << qbits) / 3; // a non-trivial residual (values a real intra residual might have) - let resid: [i32; 16] = [ - 12, -5, 3, 1, -8, 7, -2, 0, 4, -3, 6, -1, 2, 0, -4, 5, - ]; + let resid: [i32; 16] = [12, -5, 3, 1, -8, 7, -2, 0, 4, -3, 6, -1, 2, 0, -4, 5]; let w = fwd_core(&resid); // forward quant (all positions, class-dependent) let mut z = [0i32; 16]; @@ -1576,7 +1793,10 @@ mod roundtrip_tests { eprintln!("residual: {:?}", resid); eprintln!("recon: {:?}", back); eprintln!("max abs error at QP{qp}: {maxerr}"); - assert!(maxerr <= 3, "core transform round-trip error {maxerr} too large (QP{qp})"); + assert!( + maxerr <= 3, + "core transform round-trip error {maxerr} too large (QP{qp})" + ); } } @@ -1625,75 +1845,185 @@ mod dc_roundtrip { eprintln!("dc_vals: {:?}", dc_vals); eprintln!("dc_recon: {:?}", dc_recon); eprintln!("DC max abs error at QP{qp}: {maxerr} (should be ~quant step, not ~values)"); - assert!(maxerr < 100, "DC Hadamard round-trip error {maxerr} — scaling bug"); + assert!( + maxerr < 100, + "DC Hadamard round-trip error {maxerr} — scaling bug" + ); } } #[cfg(test)] mod cavlc_fuzz { use super::*; - struct Br<'a> { d: &'a [u8], pos: usize } + struct Br<'a> { + d: &'a [u8], + pos: usize, + } impl<'a> Br<'a> { - fn bit(&mut self) -> u32 { let b=(self.d[self.pos/8]>>(7-(self.pos%8)))&1; self.pos+=1; b as u32 } - fn bits(&mut self, n: u32) -> u32 { let mut v=0; for _ in 0..n { v=(v<<1)|self.bit(); } v } + fn bit(&mut self) -> u32 { + let b = (self.d[self.pos / 8] >> (7 - (self.pos % 8))) & 1; + self.pos += 1; + b as u32 + } + fn bits(&mut self, n: u32) -> u32 { + let mut v = 0; + for _ in 0..n { + v = (v << 1) | self.bit(); + } + v + } } - fn vlc(br:&mut Br, t:&[(u8,u16)])->usize{ - let mut code=0u32; let mut len=0u8; - for _ in 0..16 { code=(code<<1)|br.bit(); len+=1; - for (s,&(l,c)) in t.iter().enumerate(){ if l!=0 && l==len && c as u32==code {return s;} } } + fn vlc(br: &mut Br, t: &[(u8, u16)]) -> usize { + let mut code = 0u32; + let mut len = 0u8; + for _ in 0..16 { + code = (code << 1) | br.bit(); + len += 1; + for (s, &(l, c)) in t.iter().enumerate() { + if l != 0 && l == len && c as u32 == code { + return s; + } + } + } panic!("vlc decode fail"); } - fn dec(bytes:&[u8], nc:i32, max:usize)->Vec{ - let mut br=Br{d:bytes,pos:0}; - let (mut tc, mut t1)=(0usize,0usize); - { let mut code=0u32; let mut len=0u8; 'o: for _ in 0..16 { code=(code<<1)|br.bit(); len+=1; - for c in 0..=16usize { for o in 0..=c.min(3) { - if nc<0 && c>4 {continue} - let (l,cc)=coeff_token(c,o,nc); - if l==len as u32 && cc==code { tc=c; t1=o; break 'o; } } } } } - if tc==0 { return vec![0;max]; } - let mut lv=vec![0i32;tc]; - for j in 0..t1 { lv[j]= if br.bit()==1 {-1}else{1}; } - let mut sl:u32= if tc>10 && t1<3 {1}else{0}; + fn dec(bytes: &[u8], nc: i32, max: usize) -> Vec { + let mut br = Br { d: bytes, pos: 0 }; + let (mut tc, mut t1) = (0usize, 0usize); + { + let mut code = 0u32; + let mut len = 0u8; + 'o: for _ in 0..16 { + code = (code << 1) | br.bit(); + len += 1; + for c in 0..=16usize { + for o in 0..=c.min(3) { + if nc < 0 && c > 4 { + continue; + } + let (l, cc) = coeff_token(c, o, nc); + if l == len as u32 && cc == code { + tc = c; + t1 = o; + break 'o; + } + } + } + } + } + if tc == 0 { + return vec![0; max]; + } + let mut lv = vec![0i32; tc]; + for j in 0..t1 { + lv[j] = if br.bit() == 1 { -1 } else { 1 }; + } + let mut sl: u32 = if tc > 10 && t1 < 3 { 1 } else { 0 }; for j in t1..tc { - let mut lp=0u32; while br.bit()==0 {lp+=1;} + let mut lp = 0u32; + while br.bit() == 0 { + lp += 1; + } let mut code; - if sl==0 { if lp<14 {code=lp as i32;} else if lp==14 {code=14+br.bits(4)as i32;} else {code=30+br.bits(12)as i32;} } - else { code=((lp<>1} else {-((code+1)>>1)}; - if sl==0 {sl=1;} - if lv[j].unsigned_abs() > (3u32<<(sl-1)) && sl<6 { sl+=1; } - } - let tz= if tc=(0..=(max-tc)).map(|z|{let (l,c)= if max==4 {total_zeros_chroma_dc(tc,z as i32)} else {total_zeros_4x4(tc,z as i32)}; (l as u8,c as u16)}).collect(); - vlc(&mut br,&tbl) as i32 } else {0}; - let mut zl=tz; let mut runs=vec![0i32;tc]; - for j in 0..tc-1 { if zl<=0 {break;} - let tbl:Vec<(u8,u16)>=(0..=zl).map(|r|{let (l,c)=run_before(r,zl); (l as u8,c as u16)}).collect(); - runs[j]=vlc(&mut br,&tbl) as i32; zl-=runs[j]; } - runs[tc-1]=zl; - let mut pos=vec![0i32;tc]; let mut acc=0i32; - for i in (0..tc).rev(){ acc+=runs[i]+1; pos[i]=acc-1; } - let mut out=vec![0i32;max]; - for i in 0..tc { out[pos[i] as usize]=lv[i]; } + if sl == 0 { + if lp < 14 { + code = lp as i32; + } else if lp == 14 { + code = 14 + br.bits(4) as i32; + } else { + code = 30 + br.bits(12) as i32; + } + } else { + code = ((lp << sl) | br.bits(sl)) as i32; + } + if j == t1 && t1 < 3 { + code += 2; + } + lv[j] = if code % 2 == 0 { + (code + 2) >> 1 + } else { + -((code + 1) >> 1) + }; + if sl == 0 { + sl = 1; + } + if lv[j].unsigned_abs() > (3u32 << (sl - 1)) && sl < 6 { + sl += 1; + } + } + let tz = if tc < max { + let tbl: Vec<(u8, u16)> = (0..=(max - tc)) + .map(|z| { + let (l, c) = if max == 4 { + total_zeros_chroma_dc(tc, z as i32) + } else { + total_zeros_4x4(tc, z as i32) + }; + (l as u8, c as u16) + }) + .collect(); + vlc(&mut br, &tbl) as i32 + } else { + 0 + }; + let mut zl = tz; + let mut runs = vec![0i32; tc]; + for j in 0..tc - 1 { + if zl <= 0 { + break; + } + let tbl: Vec<(u8, u16)> = (0..=zl) + .map(|r| { + let (l, c) = run_before(r, zl); + (l as u8, c as u16) + }) + .collect(); + runs[j] = vlc(&mut br, &tbl) as i32; + zl -= runs[j]; + } + runs[tc - 1] = zl; + let mut pos = vec![0i32; tc]; + let mut acc = 0i32; + for i in (0..tc).rev() { + acc += runs[i] + 1; + pos[i] = acc - 1; + } + let mut out = vec![0i32; max]; + for i in 0..tc { + out[pos[i] as usize] = lv[i]; + } out } #[test] fn block_roundtrips() { - let mut st=0xBADC0FFEu64; - let mut rng=|| { st=st.wrapping_mul(6364136223846793005).wrapping_add(1); (st>>33) as u32 }; + let mut st = 0xBADC0FFEu64; + let mut rng = || { + st = st.wrapping_mul(6364136223846793005).wrapping_add(1); + (st >> 33) as u32 + }; for trial in 0..200000u32 { - let max= match trial%3 {0=>4,1=>15,_=>16}; - let nc= (rng()%9) as i32; - let mut coeffs=vec![0i32;max]; - let k=(rng() as usize)%(max+1); - for _ in 0..k { let p=(rng() as usize)%max; let m=1+(rng()%15) as i32; coeffs[p]= if rng()&1==1 {m}else{-m}; } - let mut bw=BitWriter::new(); - { let mut c=Cavlc{bw:&mut bw}; c.block(&coeffs,nc); } - bw.put_bit(1); bw.align_zero(); - let got=dec(&bw.into_rbsp(),nc,max); - assert_eq!(got,coeffs,"trial {trial} nc={nc} max={max}"); + let max = match trial % 3 { + 0 => 4, + 1 => 15, + _ => 16, + }; + let nc = (rng() % 9) as i32; + let mut coeffs = vec![0i32; max]; + let k = (rng() as usize) % (max + 1); + for _ in 0..k { + let p = (rng() as usize) % max; + let m = 1 + (rng() % 15) as i32; + coeffs[p] = if rng() & 1 == 1 { m } else { -m }; + } + let mut bw = BitWriter::new(); + { + let mut c = Cavlc { bw: &mut bw }; + c.block(&coeffs, nc); + } + bw.put_bit(1); + bw.align_zero(); + let got = dec(&bw.into_rbsp(), nc, max); + assert_eq!(got, coeffs, "trial {trial} nc={nc} max={max}"); } } } @@ -1701,26 +2031,43 @@ mod cavlc_fuzz { #[cfg(test)] mod chroma_dc_unit { use super::*; - fn shift(x: i64, s: i32) -> i64 { if s <= 0 { x << (-s) } else { (x + (1 << (s - 1))) >> s } } - fn chroma_dc_qdq(dc: [i32;4], qpc: i32) -> [i32;4] { - let rem=(qpc%6) as usize; - let q4mf=shift(MF[rem][0] as i64, qpc/6 - 1); - let mf=q4mf>>1; let bias=((1i64<<15)/q4mf)<<1; - let had=hadamard2(&dc); - let mut z=[0i32;4]; - for i in 0..4 { let d=had[i] as i64; let q=((bias+d.abs())*mf)>>16; z[i]= if d<0 {-(q as i32)} else {q as i32}; } - let deq=hadamard2(&z); - let dmf=(V[rem][0] as i64)<<(qpc/6); - let mut r=[0i32;4]; for i in 0..4 { r[i]=((deq[i] as i64*dmf)>>5) as i32; } + fn shift(x: i64, s: i32) -> i64 { + if s <= 0 { + x << (-s) + } else { + (x + (1 << (s - 1))) >> s + } + } + fn chroma_dc_qdq(dc: [i32; 4], qpc: i32) -> [i32; 4] { + let rem = (qpc % 6) as usize; + let q4mf = shift(MF[rem][0] as i64, qpc / 6 - 1); + let mf = q4mf >> 1; + let bias = ((1i64 << 15) / q4mf) << 1; + let had = hadamard2(&dc); + let mut z = [0i32; 4]; + for i in 0..4 { + let d = had[i] as i64; + let q = ((bias + d.abs()) * mf) >> 16; + z[i] = if d < 0 { -(q as i32) } else { q as i32 }; + } + let deq = hadamard2(&z); + let dmf = (V[rem][0] as i64) << (qpc / 6); + let mut r = [0i32; 4]; + for i in 0..4 { + r[i] = ((deq[i] as i64 * dmf) >> 5) as i32; + } r } #[test] fn matches_x264_golden() { // hand-traced verbatim from x264 encoder/macroblock.c at qpc=6 - assert_eq!(chroma_dc_qdq([120,-80,40,-16], 6), [28,-20,10,-4]); + assert_eq!(chroma_dc_qdq([120, -80, 40, -16], 6), [28, -20, 10, -4]); // flat DC in → uniform DC out (inverse Hadamard of a single DC coeff) - let r = chroma_dc_qdq([100,100,100,100], 6); - assert!(r.iter().all(|&v| (v - r[0]).abs() <= 1), "flat in → flat out, got {r:?}"); + let r = chroma_dc_qdq([100, 100, 100, 100], 6); + assert!( + r.iter().all(|&v| (v - r[0]).abs() <= 1), + "flat in → flat out, got {r:?}" + ); assert!(r[0] > 0); } } diff --git a/src/h264bits.rs b/src/h264bits.rs index b91a442..b886b87 100644 --- a/src/h264bits.rs +++ b/src/h264bits.rs @@ -15,7 +15,11 @@ pub struct BitWriter { impl BitWriter { pub fn new() -> Self { - BitWriter { buf: Vec::new(), cur: 0, nbits: 0 } + BitWriter { + buf: Vec::new(), + cur: 0, + nbits: 0, + } } pub fn put_bit(&mut self, b: u32) { self.cur = (self.cur << 1) | ((b & 1) as u8); @@ -43,7 +47,11 @@ impl BitWriter { self.put_bits(code, nbits); } pub fn se(&mut self, v: i32) { - let mapped = if v <= 0 { (-2 * v) as u32 } else { (2 * v - 1) as u32 }; + let mapped = if v <= 0 { + (-2 * v) as u32 + } else { + (2 * v - 1) as u32 + }; self.ue(mapped); } pub fn byte_aligned(&self) -> bool { diff --git a/src/heif.rs b/src/heif.rs index f50cb90..48cf34d 100644 --- a/src/heif.rs +++ b/src/heif.rs @@ -241,8 +241,25 @@ mod tests { assert!(tags.iter().any(|t| t == b"mdat")); // required HEIF item-structure boxes present somewhere let find = |n: &[u8]| heif.windows(n.len()).any(|w| w == n); - for need in [&b"mif1"[..], b"hdlr", b"pict", b"pitm", b"iinf", b"infe", b"avc1", b"avcC", b"ispe", b"iprp", b"ipma", b"iloc"] { - assert!(find(need), "missing required HEIF box/marker {:?}", std::str::from_utf8(need).unwrap()); + for need in [ + &b"mif1"[..], + b"hdlr", + b"pict", + b"pitm", + b"iinf", + b"infe", + b"avc1", + b"avcC", + b"ispe", + b"iprp", + b"ipma", + b"iloc", + ] { + assert!( + find(need), + "missing required HEIF box/marker {:?}", + std::str::from_utf8(need).unwrap() + ); } // it must NOT claim the heic brand (we have no HEVC) assert!(!find(b"heic"), "must not claim heic brand without HEVC"); @@ -272,8 +289,14 @@ mod tests { heif[mdat_payload + 2], heif[mdat_payload + 3], ]) as usize; - assert!(nal_len > 0 && mdat_payload + 4 + nal_len <= heif.len(), "mdat extent sane"); + assert!( + nal_len > 0 && mdat_payload + 4 + nal_len <= heif.len(), + "mdat extent sane" + ); let nal_type = heif[mdat_payload + 4] & 0x1F; - assert_eq!(nal_type, 5, "first item NAL should be an IDR slice (type 5)"); + assert_eq!( + nal_type, 5, + "first item NAL should be an IDR slice (type 5)" + ); } } diff --git a/src/jpeg.rs b/src/jpeg.rs index 72fe87f..1f2ce86 100644 --- a/src/jpeg.rs +++ b/src/jpeg.rs @@ -115,7 +115,16 @@ fn fdct8x8(block: &[f32; 64], basis: &[[f32; 8]; 8]) -> [f32; 64] { // column pass: out[u][v] = Σ_y b[u][y]·tmp[y][v] let mut out = [0.0f32; 64]; for v in 0..8 { - let c = [tmp[v], tmp[8 + v], tmp[16 + v], tmp[24 + v], tmp[32 + v], tmp[40 + v], tmp[48 + v], tmp[56 + v]]; + let c = [ + tmp[v], + tmp[8 + v], + tmp[16 + v], + tmp[24 + v], + tmp[32 + v], + tmp[40 + v], + tmp[48 + v], + tmp[56 + v], + ]; let s = [c[0] + c[7], c[1] + c[6], c[2] + c[5], c[3] + c[4]]; let d = [c[0] - c[7], c[1] - c[6], c[2] - c[5], c[3] - c[4]]; for u in (0..8).step_by(2) { @@ -135,10 +144,21 @@ fn idct8x8(coef: &[f32; 64], basis: &[[f32; 8]; 8]) -> [f32; 64] { let mut tmp = [0.0f32; 64]; // tmp[y][v] = Σ_u b[u][y]·coef[u][v] (split by parity of u) for v in 0..8 { - let c = [coef[v], coef[8 + v], coef[16 + v], coef[24 + v], coef[32 + v], coef[40 + v], coef[48 + v], coef[56 + v]]; + let c = [ + coef[v], + coef[8 + v], + coef[16 + v], + coef[24 + v], + coef[32 + v], + coef[40 + v], + coef[48 + v], + coef[56 + v], + ]; for y in 0..4 { - let e = basis[0][y] * c[0] + basis[2][y] * c[2] + basis[4][y] * c[4] + basis[6][y] * c[6]; - let o = basis[1][y] * c[1] + basis[3][y] * c[3] + basis[5][y] * c[5] + basis[7][y] * c[7]; + let e = + basis[0][y] * c[0] + basis[2][y] * c[2] + basis[4][y] * c[4] + basis[6][y] * c[6]; + let o = + basis[1][y] * c[1] + basis[3][y] * c[3] + basis[5][y] * c[5] + basis[7][y] * c[7]; tmp[y * 8 + v] = e + o; tmp[(7 - y) * 8 + v] = e - o; } @@ -148,8 +168,10 @@ fn idct8x8(coef: &[f32; 64], basis: &[[f32; 8]; 8]) -> [f32; 64] { for y in 0..8 { let r = &tmp[y * 8..y * 8 + 8]; for x in 0..4 { - let e = basis[0][x] * r[0] + basis[2][x] * r[2] + basis[4][x] * r[4] + basis[6][x] * r[6]; - let o = basis[1][x] * r[1] + basis[3][x] * r[3] + basis[5][x] * r[5] + basis[7][x] * r[7]; + let e = + basis[0][x] * r[0] + basis[2][x] * r[2] + basis[4][x] * r[4] + basis[6][x] * r[6]; + let o = + basis[1][x] * r[1] + basis[3][x] * r[3] + basis[5][x] * r[5] + basis[7][x] * r[7]; out[y * 8 + x] = e + o; out[y * 8 + (7 - x)] = e - o; } @@ -200,7 +222,8 @@ impl HuffDec { let sym = *vals.get(k + j).unwrap_or(&0) as u16; let entry = ((l as u16) << 8) | sym; let base = c << shift; - for p in base..(base + (1 << shift)).min(fast.len()) { // bound malformed codes + for p in base..(base + (1 << shift)).min(fast.len()) { + // bound malformed codes fast[p] = entry; } } @@ -213,7 +236,13 @@ impl HuffDec { } code <<= 1; } - HuffDec { mincode, maxcode, valptr, vals: vals.to_vec(), fast } + HuffDec { + mincode, + maxcode, + valptr, + vals: vals.to_vec(), + fast, + } } } @@ -259,7 +288,14 @@ struct JpegBitReader<'a> { impl<'a> JpegBitReader<'a> { fn new(data: &'a [u8], pos: usize) -> Self { - JpegBitReader { data, pos, acc: 0, nbits: 0, hit_marker: false, marker: 0 } + JpegBitReader { + data, + pos, + acc: 0, + nbits: 0, + hit_marker: false, + marker: 0, + } } fn fill(&mut self) { // 64-bit accumulator, MSB-first (next bit at bit 63). Bulk-load 4 @@ -388,7 +424,11 @@ struct JpegBitWriter { impl JpegBitWriter { fn new() -> Self { - JpegBitWriter { buf: Vec::new(), acc: 0, nbits: 0 } + JpegBitWriter { + buf: Vec::new(), + acc: 0, + nbits: 0, + } } fn put_bits(&mut self, code: u32, len: u32) { // place `code` just below the filled region of the 64-bit accumulator @@ -465,9 +505,9 @@ struct Component { id: u8, h: u8, v: u8, - tq: u8, // quant table selector - td: u8, // DC huff selector - ta: u8, // AC huff selector + tq: u8, // quant table selector + td: u8, // DC huff selector + ta: u8, // AC huff selector // full-resolution plane (filled after upsampling); during scan, blocks // are written into a per-component grid sized to its own sampling. plane: Vec, @@ -514,13 +554,19 @@ pub fn decode(data: &[u8]) -> Result { // Anti-bomb (the streaming-law bound): a JPEG cannot decode more 8×8 blocks than its // entropy stream has bytes (≥ ~1 byte/MCU). Reject attacker-inflated dimensions in // O(1) — a compare, never an allocation sized by the declared (untrusted) header. - if width == 0 || height == 0 { return Err("JPEG: zero dimension".into()); } + if width == 0 || height == 0 { + return Err("JPEG: zero dimension".into()); + } // Two bounds, both O(1): (1) a generous data-relative check (a JPEG block needs // entropy; ≥ ~1 byte per 16 blocks rejects truncated bombs) and (2) the absolute 100MP // backstop (≤ 400 MiB RGBA) — no real document image approaches either. let blocks = (width / 8 + 1) as u64 * (height / 8 + 1) as u64; - if blocks > data.len() as u64 * 16 { return Err("JPEG: dimensions exceed data".into()); } - if (width as u64) * (height as u64) > 100_000_000 { return Err("JPEG: exceeds 100MP".into()); } + if blocks > data.len() as u64 * 16 { + return Err("JPEG: dimensions exceed data".into()); + } + if (width as u64) * (height as u64) > 100_000_000 { + return Err("JPEG: exceeds 100MP".into()); + } let nc = data[p + 7] as usize; comps.clear(); for i in 0..nc { @@ -543,12 +589,16 @@ pub fn decode(data: &[u8]) -> Result { let len = u16::from_be_bytes([data[p], data[p + 1]]) as usize; let mut q = p + 2; let end = p + len; - if end > data.len() { return Err("JPEG: truncated DHT".into()); } // bound the segment + if end > data.len() { + return Err("JPEG: truncated DHT".into()); + } // bound the segment while q < end { let tc_th = data[q]; let class = tc_th >> 4; let id = (tc_th & 0x0F) as usize; - if id >= 4 { return Err("JPEG: bad Huffman table id".into()); } // index is 0..3 + if id >= 4 { + return Err("JPEG: bad Huffman table id".into()); + } // index is 0..3 q += 1; let mut bits = [0u8; 16]; let mut total = 0usize; @@ -557,7 +607,9 @@ pub fn decode(data: &[u8]) -> Result { total += *b as usize; q += 1; } - if q + total > data.len() { return Err("JPEG: truncated DHT values".into()); } + if q + total > data.len() { + return Err("JPEG: truncated DHT values".into()); + } let vals = data[q..q + total].to_vec(); q += total; let h = HuffDec::build(&bits, &vals); @@ -574,12 +626,16 @@ pub fn decode(data: &[u8]) -> Result { let len = u16::from_be_bytes([data[p], data[p + 1]]) as usize; let mut q = p + 2; let end = p + len; - if end > data.len() { return Err("JPEG: truncated DQT".into()); } // bound the segment + if end > data.len() { + return Err("JPEG: truncated DQT".into()); + } // bound the segment while q < end { let pq_tq = data[q]; let prec = pq_tq >> 4; let id = (pq_tq & 0x0F) as usize; - if id >= 4 { return Err("JPEG: bad quant table id".into()); } // index is 0..3 + if id >= 4 { + return Err("JPEG: bad quant table id".into()); + } // index is 0..3 q += 1; let mut table = [0u16; 64]; for k in 0..64 { @@ -615,17 +671,28 @@ pub fn decode(data: &[u8]) -> Result { p += len; // entropy-coded data begins at p return decode_scan( - data, p, width, height, &mut comps, &qtables, &dc_huff, &ac_huff, - restart_interval, adobe, &basis, + data, + p, + width, + height, + &mut comps, + &qtables, + &dc_huff, + &ac_huff, + restart_interval, + adobe, + &basis, ); } - 0xD8 => {} // SOI (shouldn't recur) - 0x01 | 0xD0..=0xD7 => {} // TEM / stray RST + 0xD8 => {} // SOI (shouldn't recur) + 0x01 | 0xD0..=0xD7 => {} // TEM / stray RST 0xEE => { // APP14 Adobe: the transform byte (0 = CMYK/RGB, 1 = YCbCr, 2 = YCCK) — needed to // colour-convert 4-component (CMYK) JPEGs, which Adobe also stores inverted. let len = u16::from_be_bytes([data[p], data[p + 1]]) as usize; - if len >= 14 && &data[p + 2..p + 7] == b"Adobe" { adobe = Some(data[p + 13]); } + if len >= 14 && &data[p + 2..p + 7] == b"Adobe" { + adobe = Some(data[p + 13]); + } p += len; } _ => { @@ -676,9 +743,13 @@ fn decode_scan( } } for (ci, c) in comps.iter_mut().enumerate() { - let dch = dc_huff.get(c.td as usize).and_then(|x| x.as_ref()) + let dch = dc_huff + .get(c.td as usize) + .and_then(|x| x.as_ref()) .ok_or("JPEG: missing DC table")?; - let ach = ac_huff.get(c.ta as usize).and_then(|x| x.as_ref()) + let ach = ac_huff + .get(c.ta as usize) + .and_then(|x| x.as_ref()) .ok_or("JPEG: missing AC table")?; let qt = qtables.get(c.tq as usize).ok_or("JPEG: missing Q table")?; for by in 0..c.v as usize { @@ -752,8 +823,12 @@ fn decode_scan( } if ncomp == 1 { let c = &comps[0]; - let sxm: Vec = (0..width).map(|x| (x * c.h as usize / hmax).min(c.bw - 1)).collect(); - let sym: Vec = (0..height).map(|y| (y * c.v as usize / vmax).min(c.bh - 1)).collect(); + let sxm: Vec = (0..width) + .map(|x| (x * c.h as usize / hmax).min(c.bw - 1)) + .collect(); + let sym: Vec = (0..height) + .map(|y| (y * c.v as usize / vmax).min(c.bh - 1)) + .collect(); for y in 0..height { let row = sym[y] * c.bw; for x in 0..width { @@ -770,10 +845,14 @@ fn decode_scan( // white-minus-ink); for transform==2 the first three are YCCK (YCbCr of the CMY). Recover // (R,G,B) from the first three, then multiply by K — RGB = C'·K'/255 — the libjpeg path. let sxm = |c: &Component| -> Vec { - (0..width).map(|x| (x * c.h as usize / hmax).min(c.bw - 1)).collect() + (0..width) + .map(|x| (x * c.h as usize / hmax).min(c.bw - 1)) + .collect() }; let sym = |c: &Component| -> Vec { - (0..height).map(|y| (y * c.v as usize / vmax).min(c.bh - 1)).collect() + (0..height) + .map(|y| (y * c.v as usize / vmax).min(c.bh - 1)) + .collect() }; let maps: Vec<(Vec, Vec)> = comps.iter().map(|c| (sxm(c), sym(c))).collect(); let ycck = adobe == Some(2); @@ -787,9 +866,11 @@ fn decode_scan( // For YCCK the first three YCbCr→RGB *to CMY directly*; for plain CMYK they are CMY. // Final RGB = (255 − CMY)·K/255 (K = the stored 4th channel, Adobe convention). let (cy, mg, ye) = if ycck { - (cl(c0 + cr_r[c2 as usize]), - cl(c0 - cb_g[c1 as usize] - cr_g[c2 as usize]), - cl(c0 + cb_b[c1 as usize])) + ( + cl(c0 + cr_r[c2 as usize]), + cl(c0 - cb_g[c1 as usize] - cr_g[c2 as usize]), + cl(c0 + cb_b[c1 as usize]), + ) } else { (c0 as u8, c1 as u8, c2 as u8) }; @@ -803,10 +884,14 @@ fn decode_scan( } else { let (cy, ccb, ccr) = (&comps[0], &comps[1], &comps[2]); let sxm = |c: &Component| -> Vec { - (0..width).map(|x| (x * c.h as usize / hmax).min(c.bw - 1)).collect() + (0..width) + .map(|x| (x * c.h as usize / hmax).min(c.bw - 1)) + .collect() }; let sym = |c: &Component| -> Vec { - (0..height).map(|y| (y * c.v as usize / vmax).min(c.bh - 1)).collect() + (0..height) + .map(|y| (y * c.v as usize / vmax).min(c.bh - 1)) + .collect() }; let (yxm, yym) = (sxm(cy), sym(cy)); let (bxm, bym) = (sxm(ccb), sym(ccb)); @@ -826,7 +911,11 @@ fn decode_scan( } } - Ok(Image { width: width as u32, height: height as u32, pixels }) + Ok(Image { + width: width as u32, + height: height as u32, + pixels, + }) } // ───────────────────────────────────────────────────────────────────────── @@ -894,7 +983,7 @@ pub fn encode(width: u32, height: u32, pixels: &[u8], quality: u32) -> Result 0 { - let v = if diff < 0 { (diff - 1) & ((1 << s) - 1) } else { diff } as u32; + let v = if diff < 0 { + (diff - 1) & ((1 << s) - 1) + } else { + diff + } as u32; bw.put_bits(v, s); } // AC in zigzag order @@ -1029,7 +1122,11 @@ fn encode_block( let s = magnitude_category(coef); let rs = ((run << 4) | s) as usize; bw.put_bits(ach.codes[rs], ach.sizes[rs] as u32); - let v = if coef < 0 { (coef - 1) & ((1 << s) - 1) } else { coef } as u32; + let v = if coef < 0 { + (coef - 1) & ((1 << s) - 1) + } else { + coef + } as u32; bw.put_bits(v, s); run = 0; } @@ -1113,7 +1210,11 @@ mod huff_bench { for _ in 0..nsym { st = st.wrapping_mul(1664525).wrapping_add(1013904223); // realistic skew: ~80% of symbols are the short-code (low-index) ones - let sym = if (st >> 8) % 100 < 80 { (st >> 16) as usize % 12 } else { (st >> 16) as usize % 162 }; + let sym = if (st >> 8) % 100 < 80 { + (st >> 16) as usize % 12 + } else { + (st >> 16) as usize % 162 + }; let s = AC_LUMA_VALS[sym] as usize; bw.put_bits(enc.codes[s], enc.sizes[s] as u32); } @@ -1123,7 +1224,9 @@ mod huff_bench { let run_fast = || { let mut br = JpegBitReader::new(&data, 0); let mut acc = 0u32; - for _ in 0..nsym { acc = acc.wrapping_add(br.decode_huff(&h).unwrap() as u32); } + for _ in 0..nsym { + acc = acc.wrapping_add(br.decode_huff(&h).unwrap() as u32); + } acc }; // slow-only decoder (the old per-bit walk) @@ -1144,16 +1247,38 @@ mod huff_bench { } acc }; - assert_eq!(run_fast(), run_slow(), "fast and slow must decode identically"); + assert_eq!( + run_fast(), + run_slow(), + "fast and slow must decode identically" + ); let (mut fmin, mut smin) = (1e9f64, 1e9f64); for _ in 0..20 { - let t = Instant::now(); std::hint::black_box(run_slow()); let e = t.elapsed().as_secs_f64(); if e < smin { smin = e; } - let t = Instant::now(); std::hint::black_box(run_fast()); let e = t.elapsed().as_secs_f64(); if e < fmin { fmin = e; } + let t = Instant::now(); + std::hint::black_box(run_slow()); + let e = t.elapsed().as_secs_f64(); + if e < smin { + smin = e; + } + let t = Instant::now(); + std::hint::black_box(run_fast()); + let e = t.elapsed().as_secs_f64(); + if e < fmin { + fmin = e; + } } eprintln!("Huffman decode {nsym} symbols (min of 20, interleaved):"); - eprintln!(" per-bit (old): {:.3} ms {:.1} Msym/s", smin*1e3, nsym as f64/1e6/smin); - eprintln!(" fast table: {:.3} ms {:.1} Msym/s", fmin*1e3, nsym as f64/1e6/fmin); - eprintln!(" speedup: {:.2}x", smin/fmin); + eprintln!( + " per-bit (old): {:.3} ms {:.1} Msym/s", + smin * 1e3, + nsym as f64 / 1e6 / smin + ); + eprintln!( + " fast table: {:.3} ms {:.1} Msym/s", + fmin * 1e3, + nsym as f64 / 1e6 / fmin + ); + eprintln!(" speedup: {:.2}x", smin / fmin); } } @@ -1167,40 +1292,73 @@ mod writer_bench { fn bulk_vs_bytewise() { // deterministic (code,len) stream resembling JPEG entropy let mut st = 0x2468u32; - let syms: Vec<(u32, u32)> = (0..300_000).map(|_| { - st = st.wrapping_mul(1103515245).wrapping_add(12345); - let len = 2 + (st >> 28) % 11; // 2..12 bits - let code = (st >> 8) & ((1 << len) - 1); - (code, len) - }).collect(); + let syms: Vec<(u32, u32)> = (0..300_000) + .map(|_| { + st = st.wrapping_mul(1103515245).wrapping_add(12345); + let len = 2 + (st >> 28) % 11; // 2..12 bits + let code = (st >> 8) & ((1 << len) - 1); + (code, len) + }) + .collect(); let bulk = || { let mut w = JpegBitWriter::new(); - for &(c, l) in &syms { w.put_bits(c, l); } + for &(c, l) in &syms { + w.put_bits(c, l); + } w.flush(); w.buf }; // byte-at-a-time reference (the old writer) let bytewise = || { let mut buf = Vec::new(); - let mut acc = 0u32; let mut nbits = 0u32; + let mut acc = 0u32; + let mut nbits = 0u32; let put = |buf: &mut Vec, acc: &mut u32, nbits: &mut u32, code: u32, len: u32| { - *acc |= code << (32 - *nbits - len); *nbits += len; - while *nbits >= 8 { let b=(*acc>>24)as u8; buf.push(b); if b==0xFF{buf.push(0);} *acc<<=8; *nbits-=8; } + *acc |= code << (32 - *nbits - len); + *nbits += len; + while *nbits >= 8 { + let b = (*acc >> 24) as u8; + buf.push(b); + if b == 0xFF { + buf.push(0); + } + *acc <<= 8; + *nbits -= 8; + } }; - for &(c, l) in &syms { put(&mut buf, &mut acc, &mut nbits, c, l); } - if nbits % 8 != 0 { let p=8-nbits%8; put(&mut buf,&mut acc,&mut nbits,(1< i32 { Fmt::I16 => (i16::from_le_bytes([b[i], b[i + 1]]) as i32) << 16, Fmt::I24 => { let raw = (b[i] as i32) | ((b[i + 1] as i32) << 8) | ((b[i + 2] as i32) << 16); - let signed = if raw & 0x80_0000 != 0 { raw | !0xFF_FFFF } else { raw }; // sign-extend 24→32 + let signed = if raw & 0x80_0000 != 0 { + raw | !0xFF_FFFF + } else { + raw + }; // sign-extend 24→32 signed << 8 } Fmt::I32 => i32::from_le_bytes([b[i], b[i + 1], b[i + 2], b[i + 3]]), @@ -191,7 +195,12 @@ fn read_wav(path: &str) -> Result { samples.push(to_canon(fmt, &b, i)); i += bp; } - Ok(Wav { sample_rate: rate, channels, fmt, samples }) + Ok(Wav { + sample_rate: rate, + channels, + fmt, + samples, + }) } fn write_wav(path: &str, w: &Wav) -> Result<(), String> { @@ -237,7 +246,11 @@ fn design_lowpass(l: usize, m: usize) -> Vec { let mut taps = Vec::with_capacity(len); for n in 0..len { let t = n as f64 - center; - let sinc = if t == 0.0 { 2.0 * fc } else { (2.0 * PI * fc * t).sin() / (PI * t) }; + let sinc = if t == 0.0 { + 2.0 * fc + } else { + (2.0 * PI * fc * t).sin() / (PI * t) + }; let win = 0.5 - 0.5 * (2.0 * PI * n as f64 / (len - 1) as f64).cos(); let h = sinc * win * (l as f64); // DC gain L → unity per polyphase taps.push((h * (1i64 << Q) as f64).round() as i32); @@ -248,7 +261,11 @@ fn design_lowpass(l: usize, m: usize) -> Vec { // ─── polyphase rational resampler (fixed-point, canonical i32) ──────────────── fn gcd(a: u32, b: u32) -> u32 { - if b == 0 { a } else { gcd(b, a % b) } + if b == 0 { + a + } else { + gcd(b, a % b) + } } fn resample_channel(x: &[i32], l: usize, m: usize, taps: &[i32]) -> Vec { @@ -308,7 +325,10 @@ fn transcode(w: &Wav, rate: u32, out_ch: u16, out_fmt: Fmt) -> Wav { let g = gcd(rate, w.sample_rate); let (l, m) = ((rate / g) as usize, (w.sample_rate / g) as usize); let taps = design_lowpass(l, m); - chans = chans.iter().map(|c| resample_channel(c, l, m, &taps)).collect(); + chans = chans + .iter() + .map(|c| resample_channel(c, l, m, &taps)) + .collect(); } // channel remap @@ -329,7 +349,12 @@ fn transcode(w: &Wav, rate: u32, out_ch: u16, out_fmt: Fmt) -> Wav { vec![chans[0].clone(); want] }; - Wav { sample_rate: rate, channels: out_ch, fmt: out_fmt, samples: interleave(&chans) } + Wav { + sample_rate: rate, + channels: out_ch, + fmt: out_fmt, + samples: interleave(&chans), + } } // ─── synth + measurement (self-test) ────────────────────────────────────────── @@ -341,7 +366,12 @@ fn synth_sine(rate: u32, freq: f64, secs: f64, amp_frac: f64) -> Wav { let t = i as f64 / rate as f64; samples.push((amp_frac * FS * (2.0 * PI * freq * t).sin()) as i32); } - Wav { sample_rate: rate, channels: 1, fmt: Fmt::I16, samples } + Wav { + sample_rate: rate, + channels: 1, + fmt: Fmt::I16, + samples, + } } fn goertzel(x: &[i32], rate: u32, freq: f64) -> f64 { @@ -367,15 +397,29 @@ fn selftest() -> i32 { let sig = goertzel(&out.samples, fout, 1000.0); let noise = goertzel(&out.samples, fout, 5000.0).max(1e-9); let ok = (out.samples.len() as isize - exp as isize).abs() <= 2 && sig > 10.0 * noise; - if !ok { fails += 1; } - println!(" {fin:>5}->{fout:<5} out={:<6}(exp {exp}) 1k/5k ratio={:>7.0} [{}]", - out.samples.len(), sig / noise, if ok { "ok" } else { "FAIL" }); + if !ok { + fails += 1; + } + println!( + " {fin:>5}->{fout:<5} out={:<6}(exp {exp}) 1k/5k ratio={:>7.0} [{}]", + out.samples.len(), + sig / noise, + if ok { "ok" } else { "FAIL" } + ); } println!("bit-depth round-trips (write → read, expect near-identity):"); let base = synth_sine(16000, 1000.0, 0.1, 0.4); for &fmt in &[Fmt::U8, Fmt::I16, Fmt::I24, Fmt::I32, Fmt::F32] { - let path = format!("/tmp/_tc_rt_{}.wav", fmt.label().replace(' ', "_").replace('-', "")); - let w = Wav { sample_rate: 16000, channels: 1, fmt, samples: base.samples.clone() }; + let path = format!( + "/tmp/_tc_rt_{}.wav", + fmt.label().replace(' ', "_").replace('-', "") + ); + let w = Wav { + sample_rate: 16000, + channels: 1, + fmt, + samples: base.samples.clone(), + }; write_wav(&path, &w).unwrap(); let back = read_wav(&path).unwrap(); // tolerance = the depth's quantisation step in canonical units @@ -386,25 +430,53 @@ fn selftest() -> i32 { Fmt::F32 => 1 << 8, // f32 has a 23-bit mantissa → ~2^8 step at full scale Fmt::I32 => 2, }; - let maxerr = base.samples.iter().zip(&back.samples) - .map(|(a, b)| (*a as i64 - *b as i64).abs()).max().unwrap_or(0); + let maxerr = base + .samples + .iter() + .zip(&back.samples) + .map(|(a, b)| (*a as i64 - *b as i64).abs()) + .max() + .unwrap_or(0); let ok = back.fmt == fmt && back.samples.len() == base.samples.len() && maxerr <= tol; - if !ok { fails += 1; } - println!(" {:<13} maxerr={maxerr:>11} (tol {tol:>11}) [{}]", fmt.label(), if ok { "ok" } else { "FAIL" }); + if !ok { + fails += 1; + } + println!( + " {:<13} maxerr={maxerr:>11} (tol {tol:>11}) [{}]", + fmt.label(), + if ok { "ok" } else { "FAIL" } + ); } println!("channel remap:"); - let st = Wav { sample_rate: 16000, channels: 2, fmt: Fmt::I16, - samples: vec![100 << 16, 300 << 16, 100 << 16, 300 << 16] }; // L=100 R=300 + let st = Wav { + sample_rate: 16000, + channels: 2, + fmt: Fmt::I16, + samples: vec![100 << 16, 300 << 16, 100 << 16, 300 << 16], + }; // L=100 R=300 let mono = transcode(&st, 16000, 1, Fmt::I16); let mono_ok = mono.channels == 1 && mono.samples == vec![200 << 16, 200 << 16]; // avg let up = transcode(&mono, 16000, 2, Fmt::I16); let up_ok = up.channels == 2 && up.samples == vec![200 << 16, 200 << 16, 200 << 16, 200 << 16]; - if !mono_ok { fails += 1; } - if !up_ok { fails += 1; } - println!(" stereo->mono avg [{}] mono->stereo dup [{}]", - if mono_ok { "ok" } else { "FAIL" }, if up_ok { "ok" } else { "FAIL" }); + if !mono_ok { + fails += 1; + } + if !up_ok { + fails += 1; + } + println!( + " stereo->mono avg [{}] mono->stereo dup [{}]", + if mono_ok { "ok" } else { "FAIL" }, + if up_ok { "ok" } else { "FAIL" } + ); - if fails == 0 { println!("\nselftest: all passed"); 0 } else { println!("\nselftest: {fails} FAILED"); 1 } + if fails == 0 { + println!("\nselftest: all passed"); + 0 + } else { + println!("\nselftest: {fails} FAILED"); + 1 + } } // ─── benchmark: throughput + compression ratio (std-only, reproducible) ──────── @@ -416,7 +488,10 @@ fn bench(secs: f64) -> i32 { let n = src.samples.len(); let audio_s = n as f64 / rate as f64; let raw_bytes = n * bytes_per(Fmt::I16); - println!("bench: {audio_s:.1}s mono @ {rate} Hz = {n} samples ({} KiB raw i16)", raw_bytes / 1024); + println!( + "bench: {audio_s:.1}s mono @ {rate} Hz = {n} samples ({} KiB raw i16)", + raw_bytes / 1024 + ); println!(" synthetic 440 Hz tone — compression ratios are best-case (pure tone);"); println!(" throughput is representative. real speech/music ratios will be lower.\n"); @@ -428,7 +503,10 @@ fn bench(secs: f64) -> i32 { let ratio = raw_bytes as f64 / b as f64; println!(" {label:<20} {:>8.2} ms {xrt:>8.0}x realtime {msps:>6.1} Msamp/s ratio {ratio:>5.2}x ({} KiB)", elapsed * 1e3, b / 1024); } - None => println!(" {label:<20} {:>8.2} ms {xrt:>8.0}x realtime {msps:>6.1} Msamp/s", elapsed * 1e3), + None => println!( + " {label:<20} {:>8.2} ms {xrt:>8.0}x realtime {msps:>6.1} Msamp/s", + elapsed * 1e3 + ), } }; @@ -439,7 +517,11 @@ fn bench(secs: f64) -> i32 { let native_i32: Vec = src.samples.iter().map(|&v| v >> 16).collect(); let t = Instant::now(); let flac_bytes = flac::encode(&native_i32, rate, 1, 16); - report("FLAC encode", t.elapsed().as_secs_f64(), Some(flac_bytes.len())); + report( + "FLAC encode", + t.elapsed().as_secs_f64(), + Some(flac_bytes.len()), + ); let t = Instant::now(); match flac::decode(&flac_bytes) { Ok(_) => report("FLAC decode", t.elapsed().as_secs_f64(), None), @@ -449,7 +531,11 @@ fn bench(secs: f64) -> i32 { let pcm_i16: Vec = src.samples.iter().map(|&v| (v >> 16) as i16).collect(); let t = Instant::now(); let aac_bytes = aac::encode_pcm(&pcm_i16, rate, 1, 128); - report("AAC-LC encode 128k", t.elapsed().as_secs_f64(), Some(aac_bytes.len())); + report( + "AAC-LC encode 128k", + t.elapsed().as_secs_f64(), + Some(aac_bytes.len()), + ); let t = Instant::now(); match aac::decode_pcm(&aac_bytes) { Ok(_) => report("AAC-LC decode", t.elapsed().as_secs_f64(), None), @@ -458,14 +544,20 @@ fn bench(secs: f64) -> i32 { let t = Instant::now(); let slac_bytes = codec::encode(&src.samples, rate, 1, Fmt::I16.code(), Fmt::I16.shift()); - report("SLAC encode", t.elapsed().as_secs_f64(), Some(slac_bytes.len())); + report( + "SLAC encode", + t.elapsed().as_secs_f64(), + Some(slac_bytes.len()), + ); let t = Instant::now(); match codec::decode(&slac_bytes) { Ok(_) => report("SLAC decode", t.elapsed().as_secs_f64(), None), Err(e) => println!(" SLAC decode FAILED: {e}"), } - println!("\n(MP3 + Opus decode need a real encoded file — this crate ships no MP3/Opus encoder.)"); + println!( + "\n(MP3 + Opus decode need a real encoded file — this crate ships no MP3/Opus encoder.)" + ); 0 } @@ -505,7 +597,11 @@ fn main() { let raw = (img.width * img.height * 3) as usize; println!( "{}x{} → {} : {} bytes (qp={}, {:.1}x vs raw RGB)", - img.width, img.height, args[3], mp4.len(), qp, + img.width, + img.height, + args[3], + mp4.len(), + qp, raw as f64 / mp4.len() as f64, ); } @@ -557,7 +653,13 @@ fn main() { }); println!( "{} frames {}x{} @ {}fps → {} : {} bytes (qp={})", - frames.len(), w, h, fps, args[3], mp4.len(), qp, + frames.len(), + w, + h, + fps, + args[3], + mp4.len(), + qp, ); } Err(e) => { @@ -571,9 +673,20 @@ fn main() { match mp3::decode_pcm(&std::fs::read(&args[2]).unwrap_or_default()) { Ok((s, rate, ch)) => { let samples: Vec = s.iter().map(|&v| (v as i32) << 16).collect(); - let w = Wav { sample_rate: rate, channels: ch, fmt: Fmt::I16, samples }; + let w = Wav { + sample_rate: rate, + channels: ch, + fmt: Fmt::I16, + samples, + }; write_wav(&args[3], &w).ok(); - println!("decoded {} samples @ {} Hz, {} ch → {}", s.len(), rate, ch, args[3]); + println!( + "decoded {} samples @ {} Hz, {} ch → {}", + s.len(), + rate, + ch, + args[3] + ); } Err(e) => eprintln!("error: {e}"), } @@ -648,7 +761,10 @@ fn main() { args[2], i.channels, i.input_rate, i.pre_skip, i.audio_packets, i.samples, dur ); } - Err(e) => { eprintln!("error: {e}"); std::process::exit(1); } + Err(e) => { + eprintln!("error: {e}"); + std::process::exit(1); + } } return; } @@ -656,17 +772,39 @@ fn main() { // WAV → ADTS AAC-LC. Optional 5th arg = bitrate kbps (default 128). let w = match read_wav(&args[2]) { Ok(w) => w, - Err(e) => { eprintln!("error: {e}"); std::process::exit(1); } + Err(e) => { + eprintln!("error: {e}"); + std::process::exit(1); + } + }; + let kbps: u32 = if args.len() == 5 { + args[4].parse().unwrap_or(128) + } else { + 128 }; - let kbps: u32 = if args.len() == 5 { args[4].parse().unwrap_or(128) } else { 128 }; let pcm: Vec = w.samples.iter().map(|&v| (v >> 16) as i16).collect(); let bytes = aac::encode_pcm(&pcm, w.sample_rate, w.channels, kbps); let raw = w.samples.len() * 2; - let ratio = if bytes.is_empty() { 0.0 } else { raw as f64 / bytes.len() as f64 }; + let ratio = if bytes.is_empty() { + 0.0 + } else { + raw as f64 / bytes.len() as f64 + }; match std::fs::write(&args[3], &bytes) { - Ok(()) => println!("AAC {} → {} : {} Hz, {} ch, {} kbps, {} B → {} B ({ratio:.2}x)", - args[2], args[3], w.sample_rate, w.channels, kbps, raw, bytes.len()), - Err(e) => { eprintln!("error: {e}"); std::process::exit(1); } + Ok(()) => println!( + "AAC {} → {} : {} Hz, {} ch, {} kbps, {} B → {} B ({ratio:.2}x)", + args[2], + args[3], + w.sample_rate, + w.channels, + kbps, + raw, + bytes.len() + ), + Err(e) => { + eprintln!("error: {e}"); + std::process::exit(1); + } } return; } @@ -674,9 +812,20 @@ fn main() { match aac::decode_pcm(&std::fs::read(&args[2]).unwrap_or_default()) { Ok((s, rate, ch)) => { let samples: Vec = s.iter().map(|&v| (v as i32) << 16).collect(); - let w = Wav { sample_rate: rate, channels: ch, fmt: Fmt::I16, samples }; + let w = Wav { + sample_rate: rate, + channels: ch, + fmt: Fmt::I16, + samples, + }; write_wav(&args[3], &w).ok(); - println!("decoded {} samples @ {} Hz, {} ch → {}", s.len(), rate, ch, args[3]); + println!( + "decoded {} samples @ {} Hz, {} ch → {}", + s.len(), + rate, + ch, + args[3] + ); } Err(e) => eprintln!("error: {e}"), } @@ -706,24 +855,38 @@ fn main() { if args.len() == 3 && args[1] == "--aac-info" { let bytes = match std::fs::read(&args[2]) { Ok(b) => b, - Err(e) => { eprintln!("read {}: {e}", args[2]); std::process::exit(1); } + Err(e) => { + eprintln!("read {}: {e}", args[2]); + std::process::exit(1); + } }; match aac::parse(&bytes) { Ok(i) => { let dur = i.samples as f64 / i.samplerate as f64; - println!("{}: AAC profile {} (1=LC), {} Hz, {} ch, {} frames, {} samples/ch, {:.3}s", - args[2], i.profile, i.samplerate, i.channels, i.frames, i.samples, dur); + println!( + "{}: AAC profile {} (1=LC), {} Hz, {} ch, {} frames, {} samples/ch, {:.3}s", + args[2], i.profile, i.samplerate, i.channels, i.frames, i.samples, dur + ); + } + Err(e) => { + eprintln!("error: {e}"); + std::process::exit(1); } - Err(e) => { eprintln!("error: {e}"); std::process::exit(1); } } return; } if args.len() == 3 && args[1] == "--mp3-requant" { - match mp3::requant_check(&std::fs::read(&args[2]).unwrap_or_default()) { Ok(s)=>println!("{s}"), Err(e)=>eprintln!("error: {e}") } + match mp3::requant_check(&std::fs::read(&args[2]).unwrap_or_default()) { + Ok(s) => println!("{s}"), + Err(e) => eprintln!("error: {e}"), + } return; } if args.len() == 3 && args[1] == "--mp3-spectral" { - match mp3::spectral_check(&std::fs::read(&args[2]).unwrap_or_default()) { Ok(s)=>println!("{s}"), Err(e)=>eprintln!("error: {e}") } + match mp3::spectral_check(&std::fs::read(&args[2]).unwrap_or_default()) { + Ok(s) => println!("{s}"), + Err(e) => eprintln!("error: {e}"), + } return; } if args.len() == 2 && args[1] == "--mp3-fb-test" { @@ -738,16 +901,30 @@ fn main() { if args.len() == 3 && args[1] == "--mp3-info" { let bytes = match std::fs::read(&args[2]) { Ok(b) => b, - Err(e) => { eprintln!("read {}: {e}", args[2]); std::process::exit(1); } + Err(e) => { + eprintln!("read {}: {e}", args[2]); + std::process::exit(1); + } }; match mp3::parse(&bytes) { Ok(i) => { let dur = i.samples as f64 / i.samplerate as f64; - println!("{}: MPEG{} Layer III, {} Hz, {} ch, {} frames, {} samples, {:.2}s, {}{} kbps", + println!( + "{}: MPEG{} Layer III, {} Hz, {} ch, {} frames, {} samples, {:.2}s, {}{} kbps", args[2], - match i.version { mp3::Version::Mpeg1 => "1", mp3::Version::Mpeg2 => "2", mp3::Version::Mpeg25 => "2.5" }, - i.samplerate, i.channels, i.frames, i.samples, dur, - if i.vbr { "VBR ~" } else { "" }, i.bitrate_kbps_first); + match i.version { + mp3::Version::Mpeg1 => "1", + mp3::Version::Mpeg2 => "2", + mp3::Version::Mpeg25 => "2.5", + }, + i.samplerate, + i.channels, + i.frames, + i.samples, + dur, + if i.vbr { "VBR ~" } else { "" }, + i.bitrate_kbps_first + ); match mp3::sideinfo_stats(&bytes) { Ok(s) => println!(" {s}"), Err(e) => eprintln!(" side-info: {e}"), @@ -757,7 +934,10 @@ fn main() { Err(e) => eprintln!(" reservoir: {e}"), } } - Err(e) => { eprintln!("error: {e}"); std::process::exit(1); } + Err(e) => { + eprintln!("error: {e}"); + std::process::exit(1); + } } return; } @@ -765,20 +945,42 @@ fn main() { // real .flac → WAV let bytes = match std::fs::read(&args[2]) { Ok(b) => b, - Err(e) => { eprintln!("read {}: {e}", args[2]); std::process::exit(1); } + Err(e) => { + eprintln!("read {}: {e}", args[2]); + std::process::exit(1); + } }; match flac::decode(&bytes) { Ok((native, rate, channels, bps)) => { let shift = 32 - bps; let samples: Vec = native.iter().map(|&v| v << shift).collect(); - let fmt = match bps { 8 => Fmt::U8, 24 => Fmt::I24, 32 => Fmt::I32, _ => Fmt::I16 }; - let w = Wav { sample_rate: rate, channels, fmt, samples }; + let fmt = match bps { + 8 => Fmt::U8, + 24 => Fmt::I24, + 32 => Fmt::I32, + _ => Fmt::I16, + }; + let w = Wav { + sample_rate: rate, + channels, + fmt, + samples, + }; match write_wav(&args[3], &w) { - Ok(()) => println!("FLAC {} → {} : {} Hz, {} ch, {}-bit", args[2], args[3], rate, channels, bps), - Err(e) => { eprintln!("error: {e}"); std::process::exit(1); } + Ok(()) => println!( + "FLAC {} → {} : {} Hz, {} ch, {}-bit", + args[2], args[3], rate, channels, bps + ), + Err(e) => { + eprintln!("error: {e}"); + std::process::exit(1); + } } } - Err(e) => { eprintln!("decode error: {e}"); std::process::exit(1); } + Err(e) => { + eprintln!("decode error: {e}"); + std::process::exit(1); + } } return; } @@ -786,18 +988,36 @@ fn main() { // WAV → real .flac (decodable by any FLAC decoder) let w = match read_wav(&args[2]) { Ok(w) => w, - Err(e) => { eprintln!("error: {e}"); std::process::exit(1); } + Err(e) => { + eprintln!("error: {e}"); + std::process::exit(1); + } }; let sh = w.fmt.shift(); let native: Vec = w.samples.iter().map(|&v| v >> sh).collect(); let bps = 32 - sh; let bytes = flac::encode(&native, w.sample_rate, w.channels, bps); let raw = w.samples.len() * bytes_per(w.fmt); - let ratio = if bytes.is_empty() { 0.0 } else { raw as f64 / bytes.len() as f64 }; + let ratio = if bytes.is_empty() { + 0.0 + } else { + raw as f64 / bytes.len() as f64 + }; match std::fs::write(&args[3], &bytes) { - Ok(()) => println!("FLAC {} → {} : {} Hz, {} ch, {}-bit, {} B → {} B ({ratio:.2}x)", - args[2], args[3], w.sample_rate, w.channels, bps, raw, bytes.len()), - Err(e) => { eprintln!("error: {e}"); std::process::exit(1); } + Ok(()) => println!( + "FLAC {} → {} : {} Hz, {} ch, {}-bit, {} B → {} B ({ratio:.2}x)", + args[2], + args[3], + w.sample_rate, + w.channels, + bps, + raw, + bytes.len() + ), + Err(e) => { + eprintln!("error: {e}"); + std::process::exit(1); + } } return; } @@ -805,15 +1025,38 @@ fn main() { // WAV → SLAC (lossless) let w = match read_wav(&args[2]) { Ok(w) => w, - Err(e) => { eprintln!("error: {e}"); std::process::exit(1); } + Err(e) => { + eprintln!("error: {e}"); + std::process::exit(1); + } }; - let bytes = codec::encode(&w.samples, w.sample_rate, w.channels, w.fmt.code(), w.fmt.shift()); + let bytes = codec::encode( + &w.samples, + w.sample_rate, + w.channels, + w.fmt.code(), + w.fmt.shift(), + ); let raw = w.samples.len() * bytes_per(w.fmt); - let ratio = if bytes.is_empty() { 0.0 } else { raw as f64 / bytes.len() as f64 }; + let ratio = if bytes.is_empty() { + 0.0 + } else { + raw as f64 / bytes.len() as f64 + }; match std::fs::write(&args[3], &bytes) { - Ok(()) => println!("encoded {} → {} : {} ch, {}, {} B → {} B ({ratio:.2}x)", - args[2], args[3], w.channels, w.fmt.label(), raw, bytes.len()), - Err(e) => { eprintln!("error: {e}"); std::process::exit(1); } + Ok(()) => println!( + "encoded {} → {} : {} ch, {}, {} B → {} B ({ratio:.2}x)", + args[2], + args[3], + w.channels, + w.fmt.label(), + raw, + bytes.len() + ), + Err(e) => { + eprintln!("error: {e}"); + std::process::exit(1); + } } return; } @@ -821,18 +1064,39 @@ fn main() { // SLAC → WAV let bytes = match std::fs::read(&args[2]) { Ok(b) => b, - Err(e) => { eprintln!("read {}: {e}", args[2]); std::process::exit(1); } + Err(e) => { + eprintln!("read {}: {e}", args[2]); + std::process::exit(1); + } }; match codec::decode(&bytes) { Ok((samples, rate, channels, fmt_code)) => { let fmt = Fmt::from_code(fmt_code).unwrap_or(Fmt::I16); - let w = Wav { sample_rate: rate, channels, fmt, samples }; + let w = Wav { + sample_rate: rate, + channels, + fmt, + samples, + }; match write_wav(&args[3], &w) { - Ok(()) => println!("decoded {} → {} : {} Hz, {} ch, {}", args[2], args[3], rate, channels, fmt.label()), - Err(e) => { eprintln!("error: {e}"); std::process::exit(1); } + Ok(()) => println!( + "decoded {} → {} : {} Hz, {} ch, {}", + args[2], + args[3], + rate, + channels, + fmt.label() + ), + Err(e) => { + eprintln!("error: {e}"); + std::process::exit(1); + } } } - Err(e) => { eprintln!("decode error: {e}"); std::process::exit(1); } + Err(e) => { + eprintln!("decode error: {e}"); + std::process::exit(1); + } } return; } @@ -843,7 +1107,10 @@ fn main() { let w = synth_sine(rate, freq, secs, 0.4); match write_wav(&args[2], &w) { Ok(()) => println!("gen {} : {rate} Hz, {freq} Hz tone, {secs}s", args[2]), - Err(e) => { eprintln!("error: {e}"); std::process::exit(1); } + Err(e) => { + eprintln!("error: {e}"); + std::process::exit(1); + } } return; } @@ -856,26 +1123,57 @@ fn main() { let (inp, outp) = (args[1].clone(), args[2].clone()); let w = match read_wav(&inp) { Ok(w) => w, - Err(e) => { eprintln!("error: {e}"); std::process::exit(1); } + Err(e) => { + eprintln!("error: {e}"); + std::process::exit(1); + } }; let (mut rate, mut bits, mut chans) = (w.sample_rate, w.fmt, w.channels); let mut i = 3; while i < args.len() { match args[i].as_str() { - "--rate" if i + 1 < args.len() => { rate = args[i + 1].parse().unwrap_or(rate); i += 2; } + "--rate" if i + 1 < args.len() => { + rate = args[i + 1].parse().unwrap_or(rate); + i += 2; + } "--bits" if i + 1 < args.len() => { - match Fmt::parse(&args[i + 1]) { Some(f) => bits = f, None => { eprintln!("bad --bits {}", args[i + 1]); std::process::exit(2); } } + match Fmt::parse(&args[i + 1]) { + Some(f) => bits = f, + None => { + eprintln!("bad --bits {}", args[i + 1]); + std::process::exit(2); + } + } i += 2; } - "--channels" if i + 1 < args.len() => { chans = args[i + 1].parse().unwrap_or(chans); i += 2; } - other => { eprintln!("unknown arg: {other}"); std::process::exit(2); } + "--channels" if i + 1 < args.len() => { + chans = args[i + 1].parse().unwrap_or(chans); + i += 2; + } + other => { + eprintln!("unknown arg: {other}"); + std::process::exit(2); + } } } - println!("in : {} Hz, {} ch, {}", w.sample_rate, w.channels, w.fmt.label()); + println!( + "in : {} Hz, {} ch, {}", + w.sample_rate, + w.channels, + w.fmt.label() + ); let out = transcode(&w, rate, chans, bits); - println!("out: {} Hz, {} ch, {}", out.sample_rate, out.channels, out.fmt.label()); + println!( + "out: {} Hz, {} ch, {}", + out.sample_rate, + out.channels, + out.fmt.label() + ); match write_wav(&outp, &out) { Ok(()) => println!("wrote {outp}"), - Err(e) => { eprintln!("error: {e}"); std::process::exit(1); } + Err(e) => { + eprintln!("error: {e}"); + std::process::exit(1); + } } } diff --git a/src/mp3.rs b/src/mp3.rs index 2e313cf..6274fb7 100644 --- a/src/mp3.rs +++ b/src/mp3.rs @@ -26,8 +26,12 @@ pub struct Mp3Info { } // Layer III bitrate tables (kbps), indexed by the 4-bit bitrate index. -const BR_MPEG1: [u32; 16] = [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 0]; -const BR_MPEG2: [u32; 16] = [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0]; +const BR_MPEG1: [u32; 16] = [ + 0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 0, +]; +const BR_MPEG2: [u32; 16] = [ + 0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0, +]; const SR_MPEG1: [u32; 3] = [44100, 48000, 32000]; const SR_MPEG2: [u32; 3] = [22050, 24000, 16000]; const SR_MPEG25: [u32; 3] = [11025, 12000, 8000]; @@ -107,7 +111,11 @@ pub fn parse(data: &[u8]) -> Result { let first = parse_header(data, p).ok_or("no MPEG Layer III frame found")?; let (version, layer) = { let h = u32::from_be_bytes([data[p], data[p + 1], data[p + 2], data[p + 3]]); - let v = match (h >> 19) & 0b11 { 0b00 => Version::Mpeg25, 0b10 => Version::Mpeg2, _ => Version::Mpeg1 }; + let v = match (h >> 19) & 0b11 { + 0b00 => Version::Mpeg25, + 0b10 => Version::Mpeg2, + _ => Version::Mpeg1, + }; (v, 3u8) }; let (samplerate, channels, br0) = (first.2, first.3, first.4); @@ -141,7 +149,16 @@ pub fn parse(data: &[u8]) -> Result { } } } - Ok(Mp3Info { version, layer, samplerate, channels, frames, samples, bitrate_kbps_first: br0, vbr }) + Ok(Mp3Info { + version, + layer, + samplerate, + channels, + frames, + samples, + bitrate_kbps_first: br0, + vbr, + }) } // ─── step 1: side-info parsing + bit-reservoir accounting (MPEG-1) ──────────── @@ -158,7 +175,11 @@ impl<'a> Br<'a> { let mut v = 0u32; for _ in 0..n { let (byte, off) = (self.pos / 8, 7 - (self.pos % 8)); - let bit = if byte < self.d.len() { (self.d[byte] >> off) & 1 } else { 0 }; + let bit = if byte < self.d.len() { + (self.d[byte] >> off) & 1 + } else { + 0 + }; v = (v << 1) | bit as u32; self.pos += 1; } @@ -186,7 +207,7 @@ pub struct Granule { pub struct SideInfo { pub main_data_begin: u32, - pub scfsi: Vec, // [channel] 4-bit scale-factor selection info + pub scfsi: Vec, // [channel] 4-bit scale-factor selection info pub granules: Vec>, // [granule][channel] } @@ -216,7 +237,11 @@ pub fn parse_side_info(b: &[u8], nch: usize) -> SideInfo { g.subblock_gain[i] = r.bits(3); } // region counts implied for short blocks - g.region0_count = if g.block_type == 2 && !g.mixed_block { 8 } else { 7 }; + g.region0_count = if g.block_type == 2 && !g.mixed_block { + 8 + } else { + 7 + }; g.region1_count = 36; } else { for i in 0..3 { @@ -230,7 +255,11 @@ pub fn parse_side_info(b: &[u8], nch: usize) -> SideInfo { g.count1table_select = r.bits(1) == 1; } } - SideInfo { main_data_begin, scfsi, granules } + SideInfo { + main_data_begin, + scfsi, + granules, + } } /// Walk all frames, parse each side-info block, and report aggregate stats + @@ -318,8 +347,15 @@ pub fn reservoir_check(data: &[u8]) -> Result { if md_start < md_end { reservoir.extend_from_slice(&data[md_start..md_end]); } - let total_bits: u64 = si.granules.iter().flatten().map(|g| g.part2_3_length as u64).sum(); - if frame_main_start >= 0 && (frame_main_start as u64) * 8 + total_bits > (reservoir.len() as u64) * 8 { + let total_bits: u64 = si + .granules + .iter() + .flatten() + .map(|g| g.part2_3_length as u64) + .sum(); + if frame_main_start >= 0 + && (frame_main_start as u64) * 8 + total_bits > (reservoir.len() as u64) * 8 + { overflow += 1; } frames += 1; @@ -394,16 +430,34 @@ pub fn huffman_selftest() -> i32 { let (c, l) = crate::mp3_tables::quad_table(q); check(c, l); } - println!("huffman round-trip: {} entries, {} failures [{}]", total, fails, if fails == 0 { "ok" } else { "FAIL" }); - if fails == 0 { 0 } else { 1 } + println!( + "huffman round-trip: {} entries, {} failures [{}]", + total, + fails, + if fails == 0 { "ok" } else { "FAIL" } + ); + if fails == 0 { + 0 + } else { + 1 + } } // ─── step 3b: scalefactor bit accounting + spectral (part3) decode ──────────── // Long-block scalefactor-band boundaries (sample indices), MPEG-1, per samplerate. -const SFB_44100: [usize; 23] = [0,4,8,12,16,20,24,30,36,44,52,62,74,90,110,134,162,196,238,288,342,418,576]; -const SFB_48000: [usize; 23] = [0,4,8,12,16,20,24,30,36,42,50,60,72,88,106,128,156,190,230,276,330,384,576]; -const SFB_32000: [usize; 23] = [0,4,8,12,16,20,24,30,36,44,54,66,82,102,126,156,194,240,296,364,448,550,576]; +const SFB_44100: [usize; 23] = [ + 0, 4, 8, 12, 16, 20, 24, 30, 36, 44, 52, 62, 74, 90, 110, 134, 162, 196, 238, 288, 342, 418, + 576, +]; +const SFB_48000: [usize; 23] = [ + 0, 4, 8, 12, 16, 20, 24, 30, 36, 42, 50, 60, 72, 88, 106, 128, 156, 190, 230, 276, 330, 384, + 576, +]; +const SFB_32000: [usize; 23] = [ + 0, 4, 8, 12, 16, 20, 24, 30, 36, 44, 54, 66, 82, 102, 126, 156, 194, 240, 296, 364, 448, 550, + 576, +]; fn sfb_long(samplerate: u32) -> &'static [usize; 23] { match samplerate { @@ -415,23 +469,50 @@ fn sfb_long(samplerate: u32) -> &'static [usize; 23] { // scalefac_compress → (slen1, slen2) const SLEN: [(u32, u32); 16] = [ - (0,0),(0,1),(0,2),(0,3),(3,0),(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3),(4,2),(4,3), + (0, 0), + (0, 1), + (0, 2), + (0, 3), + (3, 0), + (1, 1), + (1, 2), + (1, 3), + (2, 1), + (2, 2), + (2, 3), + (3, 1), + (3, 2), + (3, 3), + (4, 2), + (4, 3), ]; /// Exact number of part2 (scalefactor) bits for a granule. -/ fn part2_bits(g: &Granule, gr: usize, scfsi: u32) -> u32 { let (s1, s2) = SLEN[g.scalefac_compress as usize & 15]; if g.block_type == 2 { - if g.mixed_block { 17 * s1 + 18 * s2 } else { 18 * s1 + 18 * s2 } + if g.mixed_block { + 17 * s1 + 18 * s2 + } else { + 18 * s1 + 18 * s2 + } } else if gr == 0 { 11 * s1 + 10 * s2 } else { // scfsi groups (gr1): bit3=sfb0-5, bit2=sfb6-10, bit1=sfb11-15, bit0=sfb16-20 let mut b = 0; - if scfsi & 0b1000 == 0 { b += 6 * s1; } - if scfsi & 0b0100 == 0 { b += 5 * s1; } - if scfsi & 0b0010 == 0 { b += 5 * s2; } - if scfsi & 0b0001 == 0 { b += 5 * s2; } + if scfsi & 0b1000 == 0 { + b += 6 * s1; + } + if scfsi & 0b0100 == 0 { + b += 5 * s1; + } + if scfsi & 0b0010 == 0 { + b += 5 * s2; + } + if scfsi & 0b0001 == 0 { + b += 5 * s2; + } b } } @@ -448,7 +529,11 @@ fn decode_part3(br: &mut Br, g: &Granule, sfb: &[usize; 23], boundary: usize) -> let i2 = (g.region0_count as usize + g.region1_count as usize + 2).min(22); (sfb[i1].min(bvl), sfb[i2].min(bvl)) }; - for (s, e, ts) in [(0usize, r1, g.table_select[0]), (r1, r2, g.table_select[1]), (r2, bvl, g.table_select[2])] { + for (s, e, ts) in [ + (0usize, r1, g.table_select[0]), + (r1, r2, g.table_select[1]), + (r2, bvl, g.table_select[2]), + ] { if s >= e { continue; } @@ -459,13 +544,24 @@ fn decode_part3(br: &mut Br, g: &Granule, sfb: &[usize; 23], boundary: usize) -> } let mut i = s; while i < e { - let idx = match read_huffman(br, codes, lens) { Some(v) => v as u32, None => return false }; + let idx = match read_huffman(br, codes, lens) { + Some(v) => v as u32, + None => return false, + }; let mut x = idx / wrap as u32; let mut y = idx % wrap as u32; - if x == 15 && lin > 0 { x += br.bits(lin); } - if x > 0 { br.bits(1); } - if y == 15 && lin > 0 { y += br.bits(lin); } - if y > 0 { br.bits(1); } + if x == 15 && lin > 0 { + x += br.bits(lin); + } + if x > 0 { + br.bits(1); + } + if y == 15 && lin > 0 { + y += br.bits(lin); + } + if y > 0 { + br.bits(1); + } i += 2; } } @@ -473,9 +569,14 @@ fn decode_part3(br: &mut Br, g: &Granule, sfb: &[usize; 23], boundary: usize) -> let (qc, ql) = crate::mp3_tables::quad_table(g.count1table_select as u8); let mut idx = bvl; while br.pos < boundary && idx < 576 { - let qi = match read_huffman(br, qc, ql) { Some(v) => v as u32, None => return false }; + let qi = match read_huffman(br, qc, ql) { + Some(v) => v as u32, + None => return false, + }; for b in 0..4 { - if (qi >> (3 - b)) & 1 == 1 { br.bits(1); } + if (qi >> (3 - b)) & 1 == 1 { + br.bits(1); + } } idx += 4; } @@ -492,23 +593,34 @@ pub fn spectral_check(data: &[u8]) -> Result { let sfb = sfb_long(info.samplerate); // pass 1: build reservoir + record per-frame (main_start, side_info) let mut p = 0usize; - if data.len() > 10 && &data[0..3] == b"ID3" { p = 10 + syncsafe(&data[6..10]); } + if data.len() > 10 && &data[0..3] == b"ID3" { + p = 10 + syncsafe(&data[6..10]); + } let mut reservoir: Vec = Vec::new(); let mut frames: Vec<(usize, SideInfo)> = Vec::new(); while let Some((len, _, sr, ch, _)) = parse_header(data, p) { - if sr != info.samplerate || ch != info.channels { p += 1; continue; } + if sr != info.samplerate || ch != info.channels { + p += 1; + continue; + } let h = u32::from_be_bytes([data[p], data[p + 1], data[p + 2], data[p + 3]]); let crc = if (h >> 16) & 1 == 0 { 2 } else { 0 }; let si_start = p + 4 + crc; - if si_start + si_bytes > data.len() { break; } + if si_start + si_bytes > data.len() { + break; + } let si = parse_side_info(&data[si_start..si_start + si_bytes], nch); let start = reservoir.len() as isize - si.main_data_begin as isize; let md_end = (p + len).min(data.len()); if si_start + si_bytes < md_end { reservoir.extend_from_slice(&data[si_start + si_bytes..md_end]); } - if start >= 0 { frames.push((start as usize, si)); } - if p + len + 4 > data.len() { break; } + if start >= 0 { + frames.push((start as usize, si)); + } + if p + len + 4 > data.len() { + break; + } p += len; } // pass 2: decode each granule's part3, check bit landing @@ -520,10 +632,15 @@ pub fn spectral_check(data: &[u8]) -> Result { for gr in 0..2 { for ch in 0..nch { let g = &si.granules[gr][ch]; - if g.part2_3_length == 0 { gpos += 0; continue; } + if g.part2_3_length == 0 { + gpos += 0; + continue; + } let start = gpos; let boundary = start + g.part2_3_length as usize; - if boundary > reservoir.len() * 8 { continue; } + if boundary > reservoir.len() * 8 { + continue; + } let p2 = part2_bits(g, gr, si.scfsi[ch]) as usize; let mut br = Br::new(&reservoir); br.pos = start + p2; @@ -542,7 +659,9 @@ pub fn spectral_check(data: &[u8]) -> Result { ); } } - if dev.abs() > maxdev.abs() { maxdev = dev; } + if dev.abs() > maxdev.abs() { + maxdev = dev; + } gpos = boundary; } } @@ -583,22 +702,43 @@ fn decode_is(br: &mut Br, g: &Granule, sfb: &[usize; 23], boundary: usize) -> [i (sfb[i1].min(bvl), sfb[i2].min(bvl)) }; let mut idx: usize; - for (s, e, ts) in [(0usize, r1, g.table_select[0]), (r1, r2, g.table_select[1]), (r2, bvl, g.table_select[2])] { - if s >= e { continue; } + for (s, e, ts) in [ + (0usize, r1, g.table_select[0]), + (r1, r2, g.table_select[1]), + (r2, bvl, g.table_select[2]), + ] { + if s >= e { + continue; + } let (codes, lens, wrap) = crate::mp3_tables::table(ts as usize); let lin = crate::mp3_tables::LINBITS[ts as usize & 31]; - if codes.is_empty() || wrap == 0 { continue; } + if codes.is_empty() || wrap == 0 { + continue; + } idx = s; while idx < e { - let hi = match read_huffman(br, codes, lens) { Some(v) => v as u32, None => return is }; + let hi = match read_huffman(br, codes, lens) { + Some(v) => v as u32, + None => return is, + }; let mut x = (hi / wrap as u32) as i32; let mut y = (hi % wrap as u32) as i32; - if x == 15 && lin > 0 { x += br.bits(lin) as i32; } - if x != 0 && br.bits(1) == 1 { x = -x; } - if y == 15 && lin > 0 { y += br.bits(lin) as i32; } - if y != 0 && br.bits(1) == 1 { y = -y; } + if x == 15 && lin > 0 { + x += br.bits(lin) as i32; + } + if x != 0 && br.bits(1) == 1 { + x = -x; + } + if y == 15 && lin > 0 { + y += br.bits(lin) as i32; + } + if y != 0 && br.bits(1) == 1 { + y = -y; + } is[idx] = x; - if idx + 1 < 576 { is[idx + 1] = y; } + if idx + 1 < 576 { + is[idx + 1] = y; + } idx += 2; } } @@ -606,7 +746,10 @@ fn decode_is(br: &mut Br, g: &Granule, sfb: &[usize; 23], boundary: usize) -> [i let (qc, ql) = crate::mp3_tables::quad_table(g.count1table_select as u8); idx = bvl; while br.pos < boundary && idx + 4 <= 576 { - let qi = match read_huffman(br, qc, ql) { Some(v) => v as u32, None => return is }; + let qi = match read_huffman(br, qc, ql) { + Some(v) => v as u32, + None => return is, + }; for b in 0..4 { if (qi >> (3 - b)) & 1 == 1 { let v = if br.bits(1) == 1 { -1 } else { 1 }; @@ -622,7 +765,9 @@ fn decode_is(br: &mut Br, g: &Granule, sfb: &[usize; 23], boundary: usize) -> [i /// xr = sign(is)·|is|^(4/3) · 2^(0.25·(global_gain−210)) · 2^(−mult·scalefac[sfb]) /// with mult = scalefac_scale ? 1 : 0.5, plus the preflag pretab. -/ fn requantize_long(is: &[i32; 576], sf: &[u32; 21], g: &Granule, sfb: &[usize; 23]) -> [f64; 576] { - const PRETAB: [u32; 22] = [0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,2,2,3,3,3,2,0]; + const PRETAB: [u32; 22] = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 3, 3, 3, 2, 0, + ]; let mult = if g.scalefac_scale { 1.0 } else { 0.5 }; let gain = 0.25 * (g.global_gain as f64 - 210.0); let mut xr = [0.0f64; 576]; @@ -648,25 +793,42 @@ pub fn requant_check(data: &[u8]) -> Result { let si_bytes = if nch == 1 { 17 } else { 32 }; let sfb = sfb_long(info.samplerate); let mut p = 0usize; - if data.len() > 10 && &data[0..3] == b"ID3" { p = 10 + syncsafe(&data[6..10]); } + if data.len() > 10 && &data[0..3] == b"ID3" { + p = 10 + syncsafe(&data[6..10]); + } let mut reservoir: Vec = Vec::new(); let mut first: Option<(usize, SideInfo)> = None; let mut nlong = 0u64; while let Some((len, _, sr, ch, _)) = parse_header(data, p) { - if sr != info.samplerate || ch != info.channels { p += 1; continue; } - let h = u32::from_be_bytes([data[p], data[p+1], data[p+2], data[p+3]]); + if sr != info.samplerate || ch != info.channels { + p += 1; + continue; + } + let h = u32::from_be_bytes([data[p], data[p + 1], data[p + 2], data[p + 3]]); let crc = if (h >> 16) & 1 == 0 { 2 } else { 0 }; let si_start = p + 4 + crc; - if si_start + si_bytes > data.len() { break; } + if si_start + si_bytes > data.len() { + break; + } let si = parse_side_info(&data[si_start..si_start + si_bytes], nch); let start = reservoir.len() as isize - si.main_data_begin as isize; let md_end = (p + len).min(data.len()); - if si_start + si_bytes < md_end { reservoir.extend_from_slice(&data[si_start + si_bytes..md_end]); } - if first.is_none() && start >= 0 && si.granules[0][0].block_type != 2 && si.granules[0][0].big_values > 30 { + if si_start + si_bytes < md_end { + reservoir.extend_from_slice(&data[si_start + si_bytes..md_end]); + } + if first.is_none() + && start >= 0 + && si.granules[0][0].block_type != 2 + && si.granules[0][0].big_values > 30 + { first = Some((start as usize, si.clone_min())); } - if si.granules[0][0].block_type != 2 { nlong += 1; } - if p + len + 4 > data.len() { break; } + if si.granules[0][0].block_type != 2 { + nlong += 1; + } + if p + len + 4 > data.len() { + break; + } p += len; } let (mstart, si) = first.ok_or("no long-block granule found")?; @@ -689,7 +851,11 @@ pub fn requant_check(data: &[u8]) -> Result { impl SideInfo { fn clone_min(&self) -> SideInfo { - SideInfo { main_data_begin: self.main_data_begin, scfsi: self.scfsi.clone(), granules: self.granules.clone() } + SideInfo { + main_data_begin: self.main_data_begin, + scfsi: self.scfsi.clone(), + granules: self.granules.clone(), + } } } @@ -705,30 +871,36 @@ struct ChanState { } impl ChanState { fn new() -> Self { - ChanState { overlap: [[0.0; 18]; 32], v: [0.0; 1024], prev_sf: [0; 21] } + ChanState { + overlap: [[0.0; 18]; 32], + v: [0.0; 1024], + prev_sf: [0; 21], + } } } /// Precomputed cosine matrices (computed once, not tabled). struct Dsp { - imdct: [[f32; 18]; 36], // imdct[i][k] = cos(PI/72 * (2i+1+18)(2k+1)) - imdct6: [[f32; 6]; 12], // 6-point IMDCT for short blocks - win_long: [f32; 36], // sin window (block_type 0) - win_short: [f32; 12], // sin window for short blocks - nmat: Vec, // 64x32 synthesis matrixing cos + imdct: [[f32; 18]; 36], // imdct[i][k] = cos(PI/72 * (2i+1+18)(2k+1)) + imdct6: [[f32; 6]; 12], // 6-point IMDCT for short blocks + win_long: [f32; 36], // sin window (block_type 0) + win_short: [f32; 12], // sin window for short blocks + nmat: Vec, // 64x32 synthesis matrixing cos } impl Dsp { fn new() -> Self { let mut imdct = [[0.0f32; 18]; 36]; for i in 0..36 { for k in 0..18 { - imdct[i][k] = ((PI / 72.0) * ((2 * i + 1 + 18) as f64) * ((2 * k + 1) as f64)).cos() as f32; + imdct[i][k] = + ((PI / 72.0) * ((2 * i + 1 + 18) as f64) * ((2 * k + 1) as f64)).cos() as f32; } } let mut imdct6 = [[0.0f32; 6]; 12]; for i in 0..12 { for k in 0..6 { - imdct6[i][k] = ((PI / 24.0) * ((2 * i + 1 + 6) as f64) * ((2 * k + 1) as f64)).cos() as f32; + imdct6[i][k] = + ((PI / 24.0) * ((2 * i + 1 + 6) as f64) * ((2 * k + 1) as f64)).cos() as f32; } } let mut win_long = [0.0f32; 36]; @@ -742,16 +914,27 @@ impl Dsp { let mut nmat = vec![0.0f32; 64 * 32]; for i in 0..64 { for k in 0..32 { - nmat[i * 32 + k] = ((PI / 64.0) * ((2 * k + 1) as f64) * ((i + 16) as f64)).cos() as f32; + nmat[i * 32 + k] = + ((PI / 64.0) * ((2 * k + 1) as f64) * ((i + 16) as f64)).cos() as f32; } } - Dsp { imdct, imdct6, win_long, win_short, nmat } + Dsp { + imdct, + imdct6, + win_long, + win_short, + nmat, + } } } fn alias_reduce(xr: &mut [f32; 576]) { - const CS: [f32; 8] = [0.857493, 0.881742, 0.949629, 0.983315, 0.995518, 0.999161, 0.999899, 0.999993]; - const CA: [f32; 8] = [-0.514496, -0.471732, -0.313377, -0.181913, -0.094574, -0.040966, -0.014199, -0.003700]; + const CS: [f32; 8] = [ + 0.857493, 0.881742, 0.949629, 0.983315, 0.995518, 0.999161, 0.999899, 0.999993, + ]; + const CA: [f32; 8] = [ + -0.514496, -0.471732, -0.313377, -0.181913, -0.094574, -0.040966, -0.014199, -0.003700, + ]; for sb in 1..32 { let base = sb * 18; for i in 0..8 { @@ -829,7 +1012,10 @@ fn synth_granule(st: &mut ChanState, dsp: &Dsp, mut xr: [f32; 576], short: bool) } if sb & 1 == 1 { let mut i = 1; - while i < 18 { o[i] = -o[i]; i += 2; } + while i < 18 { + o[i] = -o[i]; + i += 2; + } } sub[sb] = o; } @@ -837,22 +1023,41 @@ fn synth_granule(st: &mut ChanState, dsp: &Dsp, mut xr: [f32; 576], short: bool) let mut tmp = [0.0f32; 32]; for ts in 0..18 { let mut s = [0.0f32; 32]; - for sb in 0..32 { s[sb] = sub[sb][ts]; } + for sb in 0..32 { + s[sb] = sub[sb][ts]; + } synth_step(st, dsp, &s, &mut tmp); - for j in 0..32 { pcm[ts * 32 + j] = tmp[j]; } + for j in 0..32 { + pcm[ts * 32 + j] = tmp[j]; + } } pcm } -fn read_scalefac(br: &mut Br, g: &Granule, gr: usize, scfsi: u32, prev: &mut [u32; 21]) -> [u32; 21] { +fn read_scalefac( + br: &mut Br, + g: &Granule, + gr: usize, + scfsi: u32, + prev: &mut [u32; 21], +) -> [u32; 21] { let (s1, s2) = SLEN[g.scalefac_compress as usize & 15]; let mut sf = [0u32; 21]; - let groups = [(0usize, 6, s1, 0b1000u32), (6, 11, s1, 0b0100), (11, 16, s2, 0b0010), (16, 21, s2, 0b0001)]; + let groups = [ + (0usize, 6, s1, 0b1000u32), + (6, 11, s1, 0b0100), + (11, 16, s2, 0b0010), + (16, 21, s2, 0b0001), + ]; for (lo, hi, slen, bit) in groups { if gr == 1 && scfsi & bit != 0 { - for i in lo..hi { sf[i] = prev[i]; } + for i in lo..hi { + sf[i] = prev[i]; + } } else { - for i in lo..hi { sf[i] = if slen > 0 { br.bits(slen) } else { 0 }; } + for i in lo..hi { + sf[i] = if slen > 0 { br.bits(slen) } else { 0 }; + } } } *prev = sf; @@ -863,28 +1068,43 @@ fn read_scalefac(br: &mut Br, g: &Granule, gr: usize, scfsi: u32, prev: &mut [u3 /// now). Returns (samples i16, samplerate). First-cut, validated by SNR. -/ pub fn decode_pcm_mono(data: &[u8]) -> Result<(Vec, u32), String> { let info = parse(data)?; - if info.channels != 1 { return Err("mono-only decode (first cut)".into()); } + if info.channels != 1 { + return Err("mono-only decode (first cut)".into()); + } let si_bytes = 17; let sfb = sfb_long(info.samplerate); let sfb_s = sfb_short(info.samplerate); let dsp = Dsp::new(); // build reservoir + per-frame side info let mut p = 0usize; - if data.len() > 10 && &data[0..3] == b"ID3" { p = 10 + syncsafe(&data[6..10]); } + if data.len() > 10 && &data[0..3] == b"ID3" { + p = 10 + syncsafe(&data[6..10]); + } let mut res: Vec = Vec::new(); let mut frames: Vec<(usize, SideInfo)> = Vec::new(); while let Some((len, _, sr, ch, _)) = parse_header(data, p) { - if sr != info.samplerate || ch != 1 { p += 1; continue; } - let h = u32::from_be_bytes([data[p], data[p+1], data[p+2], data[p+3]]); + if sr != info.samplerate || ch != 1 { + p += 1; + continue; + } + let h = u32::from_be_bytes([data[p], data[p + 1], data[p + 2], data[p + 3]]); let crc = if (h >> 16) & 1 == 0 { 2 } else { 0 }; let si_start = p + 4 + crc; - if si_start + si_bytes > data.len() { break; } + if si_start + si_bytes > data.len() { + break; + } let si = parse_side_info(&data[si_start..si_start + si_bytes], 1); let start = res.len() as isize - si.main_data_begin as isize; let md_end = (p + len).min(data.len()); - if si_start + si_bytes < md_end { res.extend_from_slice(&data[si_start + si_bytes..md_end]); } - if start >= 0 { frames.push((start as usize, si)); } - if p + len + 4 > data.len() { break; } + if si_start + si_bytes < md_end { + res.extend_from_slice(&data[si_start + si_bytes..md_end]); + } + if start >= 0 { + frames.push((start as usize, si)); + } + if p + len + 4 > data.len() { + break; + } p += len; } let mut st = ChanState::new(); @@ -896,7 +1116,9 @@ pub fn decode_pcm_mono(data: &[u8]) -> Result<(Vec, u32), String> { let g = &si.granules[gr][0]; let start = br.pos; let boundary = start + g.part2_3_length as usize; - if boundary > res.len() * 8 { return Err("reservoir underrun".into()); } + if boundary > res.len() * 8 { + return Err("reservoir underrun".into()); + } let short = g.block_type == 2; let xr = if short { let sf = read_scalefac_short(&mut br, g); @@ -910,7 +1132,9 @@ pub fn decode_pcm_mono(data: &[u8]) -> Result<(Vec, u32), String> { br.pos = boundary; let xr64 = requantize_long(&is, &sf, g, sfb); let mut xr = [0.0f32; 576]; - for i in 0..576 { xr[i] = xr64[i] as f32; } + for i in 0..576 { + xr[i] = xr64[i] as f32; + } xr }; let gp = synth_granule(&mut st, &dsp, xr, short); @@ -929,7 +1153,9 @@ pub fn decode_pcm_mono(data: &[u8]) -> Result<(Vec, u32), String> { pub fn imdct_tdac_test() -> i32 { let dsp = Dsp::new(); let n = 18 * 12; - let x: Vec = (0..n).map(|i| ((i as f64 * 0.31).sin() + 0.5 * (i as f64 * 0.07).cos()) as f32).collect(); + let x: Vec = (0..n) + .map(|i| ((i as f64 * 0.31).sin() + 0.5 * (i as f64 * 0.07).cos()) as f32) + .collect(); for &scale in &[1.0f64, 2.0 / 18.0, 1.0 / 9.0, 1.0 / 18.0, 2.0 / 36.0] { let mut recon = vec![0f32; n]; let mut overlap = [0f32; 18]; @@ -942,13 +1168,17 @@ pub fn imdct_tdac_test() -> i32 { let mut coef = [0f32; 18]; for k in 0..18 { let mut a = 0.0f32; - for nn in 0..36 { a += z[nn] * dsp.imdct[nn][k]; } + for nn in 0..36 { + a += z[nn] * dsp.imdct[nn][k]; + } coef[k] = a; } let mut y = [0f32; 36]; for nn in 0..36 { let mut a = 0.0f32; - for k in 0..18 { a += coef[k] * dsp.imdct[nn][k]; } + for k in 0..18 { + a += coef[k] * dsp.imdct[nn][k]; + } y[nn] = a * scale as f32 * dsp.win_long[nn]; } for i in 0..18 { @@ -961,7 +1191,11 @@ pub fn imdct_tdac_test() -> i32 { num += (x[i] as f64).powi(2); err += ((x[i] - recon[i]) as f64).powi(2); } - let snr = if err > 0.0 { 10.0 * (num / err).log10() } else { 999.0 }; + let snr = if err > 0.0 { + 10.0 * (num / err).log10() + } else { + 999.0 + }; println!(" 18-pt scale={scale:.5} reconstruction SNR = {snr:.1} dB"); } // 6-point IMDCT (short blocks): 12-sample frames, hop 6, scale 2/6 @@ -974,16 +1208,40 @@ pub fn imdct_tdac_test() -> i32 { for f in 0..(m / 6 - 1) { let s = f * 6; let mut z = [0f32; 12]; - for i in 0..12 { z[i] = if s + i < m { xs[s + i] } else { 0.0 } * dsp.win_short[i]; } + for i in 0..12 { + z[i] = if s + i < m { xs[s + i] } else { 0.0 } * dsp.win_short[i]; + } let mut coef = [0f32; 6]; - for k in 0..6 { let mut a = 0.0f32; for nn in 0..12 { a += z[nn] * dsp.imdct6[nn][k]; } coef[k] = a; } + for k in 0..6 { + let mut a = 0.0f32; + for nn in 0..12 { + a += z[nn] * dsp.imdct6[nn][k]; + } + coef[k] = a; + } let mut y = [0f32; 12]; - for nn in 0..12 { let mut a = 0.0f32; for k in 0..6 { a += coef[k] * dsp.imdct6[nn][k]; } y[nn] = a * scale * dsp.win_short[nn]; } - for i in 0..6 { recon[s + i] = y[i] + ov[i]; ov[i] = y[6 + i]; } + for nn in 0..12 { + let mut a = 0.0f32; + for k in 0..6 { + a += coef[k] * dsp.imdct6[nn][k]; + } + y[nn] = a * scale * dsp.win_short[nn]; + } + for i in 0..6 { + recon[s + i] = y[i] + ov[i]; + ov[i] = y[6 + i]; + } } let (mut num, mut err) = (0f64, 0f64); - for i in 18..(m - 18) { num += (xs[i] as f64).powi(2); err += ((xs[i] - recon[i]) as f64).powi(2); } - let snr = if err > 0.0 { 10.0 * (num / err).log10() } else { 999.0 }; + for i in 18..(m - 18) { + num += (xs[i] as f64).powi(2); + err += ((xs[i] - recon[i]) as f64).powi(2); + } + let snr = if err > 0.0 { + 10.0 * (num / err).log10() + } else { + 999.0 + }; println!(" 6-pt scale={scale:.5} reconstruction SNR = {snr:.1} dB"); } 0 @@ -1000,7 +1258,8 @@ pub fn filterbank_test() -> i32 { let (mut s1, mut s2) = (0.0f64, 0.0f64); for &v in x { let s0 = v as f64 + c * s1 - s2; - s2 = s1; s1 = s0; + s2 = s1; + s1 = s0; } ((s1 * s1 + s2 * s2 - c * s1 * s2).sqrt()) / x.len() as f64 }; @@ -1010,7 +1269,9 @@ pub fn filterbank_test() -> i32 { let mut tmp = [0.0f32; 32]; for step in 0..20 { let mut s = [0.0f32; 32]; - if step == 0 { s[sb] = 1.0; } // impulse in this subband + if step == 0 { + s[sb] = 1.0; + } // impulse in this subband synth_step(&mut st, &dsp, &s, &mut tmp); out.extend_from_slice(&tmp); } @@ -1058,7 +1319,12 @@ fn read_scalefac_short(br: &mut Br, g: &Granule) -> [[u32; 13]; 3] { } /// Requantize short-block spectral values (stored sfb-window order). -/ -fn requantize_short(is: &[i32; 576], sf: &[[u32; 13]; 3], g: &Granule, sfb_s: &[usize; 14]) -> [f64; 576] { +fn requantize_short( + is: &[i32; 576], + sf: &[[u32; 13]; 3], + g: &Granule, + sfb_s: &[usize; 14], +) -> [f64; 576] { let mult = if g.scalefac_scale { 1.0 } else { 0.5 }; let gain = 0.25 * (g.global_gain as f64 - 210.0); let mut xr = [0.0f64; 576]; @@ -1069,7 +1335,9 @@ fn requantize_short(is: &[i32; 576], sf: &[[u32; 13]; 3], g: &Granule, sfb_s: &[ let exp = gain - 2.0 * g.subblock_gain[win] as f64 - mult * sf[win][sfb.min(11)] as f64; let scale = exp.exp2(); for _ in 0..width { - if idx >= 576 { break; } + if idx >= 576 { + break; + } let v = is[idx]; if v != 0 { xr[idx] = v.signum() as f64 * (v.unsigned_abs() as f64).powf(4.0 / 3.0) * scale; @@ -1112,24 +1380,37 @@ pub fn decode_pcm(data: &[u8]) -> Result<(Vec, u32, u16), String> { let sfb_s = sfb_short(info.samplerate); let dsp = Dsp::new(); let mut p = 0usize; - if data.len() > 10 && &data[0..3] == b"ID3" { p = 10 + syncsafe(&data[6..10]); } + if data.len() > 10 && &data[0..3] == b"ID3" { + p = 10 + syncsafe(&data[6..10]); + } let mut res: Vec = Vec::new(); let mut frames: Vec<(usize, SideInfo, bool)> = Vec::new(); // (main_start, side_info, ms_on) while let Some((len, _, sr, ch, _)) = parse_header(data, p) { - if sr != info.samplerate || ch != info.channels { p += 1; continue; } + if sr != info.samplerate || ch != info.channels { + p += 1; + continue; + } let h = u32::from_be_bytes([data[p], data[p + 1], data[p + 2], data[p + 3]]); let mode = (h >> 6) & 0b11; let mode_ext = (h >> 4) & 0b11; let ms_on = mode == 0b01 && (mode_ext & 0b10) != 0; let crc = if (h >> 16) & 1 == 0 { 2 } else { 0 }; let si_start = p + 4 + crc; - if si_start + si_bytes > data.len() { break; } + if si_start + si_bytes > data.len() { + break; + } let si = parse_side_info(&data[si_start..si_start + si_bytes], nch); let start = res.len() as isize - si.main_data_begin as isize; let md_end = (p + len).min(data.len()); - if si_start + si_bytes < md_end { res.extend_from_slice(&data[si_start + si_bytes..md_end]); } - if start >= 0 { frames.push((start as usize, si, ms_on)); } - if p + len + 4 > data.len() { break; } + if si_start + si_bytes < md_end { + res.extend_from_slice(&data[si_start + si_bytes..md_end]); + } + if start >= 0 { + frames.push((start as usize, si, ms_on)); + } + if p + len + 4 > data.len() { + break; + } p += len; } let mut states: Vec = (0..nch).map(|_| ChanState::new()).collect(); @@ -1144,7 +1425,9 @@ pub fn decode_pcm(data: &[u8]) -> Result<(Vec, u32, u16), String> { for ch in 0..nch { let g = &si.granules[gr][ch]; let boundary = br.pos + g.part2_3_length as usize; - if boundary > res.len() * 8 { return Err("reservoir underrun".into()); } + if boundary > res.len() * 8 { + return Err("reservoir underrun".into()); + } shortc[ch] = g.block_type == 2; if shortc[ch] { let sfs = read_scalefac_short(&mut br, g); @@ -1158,7 +1441,9 @@ pub fn decode_pcm(data: &[u8]) -> Result<(Vec, u32, u16), String> { let is = decode_is(&mut br, g, sfb, boundary); br.pos = boundary; let xr64 = requantize_long(&is, &sf, g, sfb); - for i in 0..576 { xrc[ch][i] = xr64[i] as f32; } + for i in 0..576 { + xrc[ch][i] = xr64[i] as f32; + } } } if nch == 2 && *ms { diff --git a/src/mp3_tables.rs b/src/mp3_tables.rs index 7b23d13..6c64627 100644 --- a/src/mp3_tables.rs +++ b/src/mp3_tables.rs @@ -10,7 +10,7 @@ // ═══════════════════════════════════════════════════════════════════════════ #![allow(dead_code)] -const MPEG_CODES_0: [u32; 0] = [ ]; +const MPEG_CODES_0: [u32; 0] = []; #[rustfmt::skip] const MPEG_BITS_0: [u8; 0] = [ ]; @@ -493,14 +493,13 @@ const MPEG_QUADS_BITS_A: [u8; 16] = [1, 4, 4, 5, 4, 6, 5, 6, 4, 5, 5, 6, 5, 6, 6 const MPEG_QUADS_CODES_B: [u32; 16] = [15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]; const MPEG_QUADS_BITS_B: [u8; 16] = [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]; - /// y-dimension (`wrap`) per codebook 0..=17 (0 = empty/unused). -/ pub const WRAP: [u16; 18] = [0, 2, 3, 3, 0, 4, 4, 6, 6, 6, 8, 8, 8, 16, 0, 16, 16, 16]; /// linbits per `table_select` 0..=31 (ISO Table B.7). -/ pub const LINBITS: [u32; 32] = [ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 1, 2, 3, 4, 6, 8, 10, 13, 4, 5, 6, 7, 8, 9, 11, 13, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 8, 10, 13, 4, 5, 6, 7, 8, 9, 11, + 13, ]; /// (codes, lens, wrap) for a `table_select` 0..=31. Empty tables → (&[], &[], 0). @@ -534,137 +533,525 @@ pub fn table(table_select: usize) -> (&'static [u32], &'static [u8], u16) { /// count1 quad table A/B (codes, lens). -/ pub fn quad_table(sel: u8) -> (&'static [u32], &'static [u8]) { - if sel == 0 { (&MPEG_QUADS_CODES_A, &MPEG_QUADS_BITS_A) } else { (&MPEG_QUADS_CODES_B, &MPEG_QUADS_BITS_B) } + if sel == 0 { + (&MPEG_QUADS_CODES_A, &MPEG_QUADS_BITS_A) + } else { + (&MPEG_QUADS_CODES_B, &MPEG_QUADS_BITS_B) + } } // ── Synthesis filterbank window D[512] — ISO/IEC 11172-3 Table 3-B.3 (facts) ── pub const SYNTHESIS_D: [f32; 512] = [ - 0.000000000, -0.000015259, -0.000015259, -0.000015259, - -0.000015259, -0.000015259, -0.000015259, -0.000030518, - -0.000030518, -0.000030518, -0.000030518, -0.000045776, - -0.000045776, -0.000061035, -0.000061035, -0.000076294, - -0.000076294, -0.000091553, -0.000106812, -0.000106812, - -0.000122070, -0.000137329, -0.000152588, -0.000167847, - -0.000198364, -0.000213623, -0.000244141, -0.000259399, - -0.000289917, -0.000320435, -0.000366211, -0.000396729, - -0.000442505, -0.000473022, -0.000534058, -0.000579834, - -0.000625610, -0.000686646, -0.000747681, -0.000808716, - -0.000885010, -0.000961304, -0.001037598, -0.001113892, - -0.001205444, -0.001296997, -0.001388550, -0.001480103, - -0.001586914, -0.001693726, -0.001785278, -0.001907349, - -0.002014160, -0.002120972, -0.002243042, -0.002349854, - -0.002456665, -0.002578735, -0.002685547, -0.002792358, - -0.002899170, -0.002990723, -0.003082275, -0.003173828, - 0.003250122, 0.003326416, 0.003387451, 0.003433228, - 0.003463745, 0.003479004, 0.003479004, 0.003463745, - 0.003417969, 0.003372192, 0.003280640, 0.003173828, - 0.003051758, 0.002883911, 0.002700806, 0.002487183, - 0.002227783, 0.001937866, 0.001617432, 0.001266479, - 0.000869751, 0.000442505, -0.000030518, -0.000549316, - -0.001098633, -0.001693726, -0.002334595, -0.003005981, - -0.003723145, -0.004486084, -0.005294800, -0.006118774, - -0.007003784, -0.007919312, -0.008865356, -0.009841919, - -0.010848999, -0.011886597, -0.012939453, -0.014022827, - -0.015121460, -0.016235352, -0.017349243, -0.018463135, - -0.019577026, -0.020690918, -0.021789551, -0.022857666, - -0.023910522, -0.024932861, -0.025909424, -0.026840210, - -0.027725220, -0.028533936, -0.029281616, -0.029937744, - -0.030532837, -0.031005859, -0.031387329, -0.031661987, - -0.031814575, -0.031845093, -0.031738281, -0.031478882, - 0.031082153, 0.030517578, 0.029785156, 0.028884888, - 0.027801514, 0.026535034, 0.025085449, 0.023422241, - 0.021575928, 0.019531250, 0.017257690, 0.014801025, - 0.012115479, 0.009231567, 0.006134033, 0.002822876, - -0.000686646, -0.004394531, -0.008316040, -0.012420654, - -0.016708374, -0.021179199, -0.025817871, -0.030609131, - -0.035552979, -0.040634155, -0.045837402, -0.051132202, - -0.056533813, -0.061996460, -0.067520142, -0.073059082, - -0.078628540, -0.084182739, -0.089706421, -0.095169067, - -0.100540161, -0.105819702, -0.110946655, -0.115921021, - -0.120697021, -0.125259399, -0.129562378, -0.133590698, - -0.137298584, -0.140670776, -0.143676758, -0.146255493, - -0.148422241, -0.150115967, -0.151306152, -0.151962280, - -0.152069092, -0.151596069, -0.150497437, -0.148773193, - -0.146362305, -0.143264771, -0.139450073, -0.134887695, - -0.129577637, -0.123474121, -0.116577148, -0.108856201, - 0.100311279, 0.090927124, 0.080688477, 0.069595337, - 0.057617187, 0.044784546, 0.031082153, 0.016510010, - 0.001068115, -0.015228271, -0.032379150, -0.050354004, - -0.069168091, -0.088775635, -0.109161377, -0.130310059, - -0.152206421, -0.174789429, -0.198059082, -0.221984863, - -0.246505737, -0.271591187, -0.297210693, -0.323318481, - -0.349868774, -0.376800537, -0.404083252, -0.431655884, - -0.459472656, -0.487472534, -0.515609741, -0.543823242, - -0.572036743, -0.600219727, -0.628295898, -0.656219482, - -0.683914185, -0.711318970, -0.738372803, -0.765029907, - -0.791213989, -0.816864014, -0.841949463, -0.866363525, - -0.890090942, -0.913055420, -0.935195923, -0.956481934, - -0.976852417, -0.996246338, -1.014617920, -1.031936646, - -1.048156738, -1.063217163, -1.077117920, -1.089782715, - -1.101211548, -1.111373901, -1.120223999, -1.127746582, - -1.133926392, -1.138763428, -1.142211914, -1.144287109, - 1.144989014, 1.144287109, 1.142211914, 1.138763428, - 1.133926392, 1.127746582, 1.120223999, 1.111373901, - 1.101211548, 1.089782715, 1.077117920, 1.063217163, - 1.048156738, 1.031936646, 1.014617920, 0.996246338, - 0.976852417, 0.956481934, 0.935195923, 0.913055420, - 0.890090942, 0.866363525, 0.841949463, 0.816864014, - 0.791213989, 0.765029907, 0.738372803, 0.711318970, - 0.683914185, 0.656219482, 0.628295898, 0.600219727, - 0.572036743, 0.543823242, 0.515609741, 0.487472534, - 0.459472656, 0.431655884, 0.404083252, 0.376800537, - 0.349868774, 0.323318481, 0.297210693, 0.271591187, - 0.246505737, 0.221984863, 0.198059082, 0.174789429, - 0.152206421, 0.130310059, 0.109161377, 0.088775635, - 0.069168091, 0.050354004, 0.032379150, 0.015228271, - -0.001068115, -0.016510010, -0.031082153, -0.044784546, - -0.057617187, -0.069595337, -0.080688477, -0.090927124, - 0.100311279, 0.108856201, 0.116577148, 0.123474121, - 0.129577637, 0.134887695, 0.139450073, 0.143264771, - 0.146362305, 0.148773193, 0.150497437, 0.151596069, - 0.152069092, 0.151962280, 0.151306152, 0.150115967, - 0.148422241, 0.146255493, 0.143676758, 0.140670776, - 0.137298584, 0.133590698, 0.129562378, 0.125259399, - 0.120697021, 0.115921021, 0.110946655, 0.105819702, - 0.100540161, 0.095169067, 0.089706421, 0.084182739, - 0.078628540, 0.073059082, 0.067520142, 0.061996460, - 0.056533813, 0.051132202, 0.045837402, 0.040634155, - 0.035552979, 0.030609131, 0.025817871, 0.021179199, - 0.016708374, 0.012420654, 0.008316040, 0.004394531, - 0.000686646, -0.002822876, -0.006134033, -0.009231567, - -0.012115479, -0.014801025, -0.017257690, -0.019531250, - -0.021575928, -0.023422241, -0.025085449, -0.026535034, - -0.027801514, -0.028884888, -0.029785156, -0.030517578, - 0.031082153, 0.031478882, 0.031738281, 0.031845093, - 0.031814575, 0.031661987, 0.031387329, 0.031005859, - 0.030532837, 0.029937744, 0.029281616, 0.028533936, - 0.027725220, 0.026840210, 0.025909424, 0.024932861, - 0.023910522, 0.022857666, 0.021789551, 0.020690918, - 0.019577026, 0.018463135, 0.017349243, 0.016235352, - 0.015121460, 0.014022827, 0.012939453, 0.011886597, - 0.010848999, 0.009841919, 0.008865356, 0.007919312, - 0.007003784, 0.006118774, 0.005294800, 0.004486084, - 0.003723145, 0.003005981, 0.002334595, 0.001693726, - 0.001098633, 0.000549316, 0.000030518, -0.000442505, - -0.000869751, -0.001266479, -0.001617432, -0.001937866, - -0.002227783, -0.002487183, -0.002700806, -0.002883911, - -0.003051758, -0.003173828, -0.003280640, -0.003372192, - -0.003417969, -0.003463745, -0.003479004, -0.003479004, - -0.003463745, -0.003433228, -0.003387451, -0.003326416, - 0.003250122, 0.003173828, 0.003082275, 0.002990723, - 0.002899170, 0.002792358, 0.002685547, 0.002578735, - 0.002456665, 0.002349854, 0.002243042, 0.002120972, - 0.002014160, 0.001907349, 0.001785278, 0.001693726, - 0.001586914, 0.001480103, 0.001388550, 0.001296997, - 0.001205444, 0.001113892, 0.001037598, 0.000961304, - 0.000885010, 0.000808716, 0.000747681, 0.000686646, - 0.000625610, 0.000579834, 0.000534058, 0.000473022, - 0.000442505, 0.000396729, 0.000366211, 0.000320435, - 0.000289917, 0.000259399, 0.000244141, 0.000213623, - 0.000198364, 0.000167847, 0.000152588, 0.000137329, - 0.000122070, 0.000106812, 0.000106812, 0.000091553, - 0.000076294, 0.000076294, 0.000061035, 0.000061035, - 0.000045776, 0.000045776, 0.000030518, 0.000030518, - 0.000030518, 0.000030518, 0.000015259, 0.000015259, - 0.000015259, 0.000015259, 0.000015259, 0.000015259, + 0.000000000, + -0.000015259, + -0.000015259, + -0.000015259, + -0.000015259, + -0.000015259, + -0.000015259, + -0.000030518, + -0.000030518, + -0.000030518, + -0.000030518, + -0.000045776, + -0.000045776, + -0.000061035, + -0.000061035, + -0.000076294, + -0.000076294, + -0.000091553, + -0.000106812, + -0.000106812, + -0.000122070, + -0.000137329, + -0.000152588, + -0.000167847, + -0.000198364, + -0.000213623, + -0.000244141, + -0.000259399, + -0.000289917, + -0.000320435, + -0.000366211, + -0.000396729, + -0.000442505, + -0.000473022, + -0.000534058, + -0.000579834, + -0.000625610, + -0.000686646, + -0.000747681, + -0.000808716, + -0.000885010, + -0.000961304, + -0.001037598, + -0.001113892, + -0.001205444, + -0.001296997, + -0.001388550, + -0.001480103, + -0.001586914, + -0.001693726, + -0.001785278, + -0.001907349, + -0.002014160, + -0.002120972, + -0.002243042, + -0.002349854, + -0.002456665, + -0.002578735, + -0.002685547, + -0.002792358, + -0.002899170, + -0.002990723, + -0.003082275, + -0.003173828, + 0.003250122, + 0.003326416, + 0.003387451, + 0.003433228, + 0.003463745, + 0.003479004, + 0.003479004, + 0.003463745, + 0.003417969, + 0.003372192, + 0.003280640, + 0.003173828, + 0.003051758, + 0.002883911, + 0.002700806, + 0.002487183, + 0.002227783, + 0.001937866, + 0.001617432, + 0.001266479, + 0.000869751, + 0.000442505, + -0.000030518, + -0.000549316, + -0.001098633, + -0.001693726, + -0.002334595, + -0.003005981, + -0.003723145, + -0.004486084, + -0.005294800, + -0.006118774, + -0.007003784, + -0.007919312, + -0.008865356, + -0.009841919, + -0.010848999, + -0.011886597, + -0.012939453, + -0.014022827, + -0.015121460, + -0.016235352, + -0.017349243, + -0.018463135, + -0.019577026, + -0.020690918, + -0.021789551, + -0.022857666, + -0.023910522, + -0.024932861, + -0.025909424, + -0.026840210, + -0.027725220, + -0.028533936, + -0.029281616, + -0.029937744, + -0.030532837, + -0.031005859, + -0.031387329, + -0.031661987, + -0.031814575, + -0.031845093, + -0.031738281, + -0.031478882, + 0.031082153, + 0.030517578, + 0.029785156, + 0.028884888, + 0.027801514, + 0.026535034, + 0.025085449, + 0.023422241, + 0.021575928, + 0.019531250, + 0.017257690, + 0.014801025, + 0.012115479, + 0.009231567, + 0.006134033, + 0.002822876, + -0.000686646, + -0.004394531, + -0.008316040, + -0.012420654, + -0.016708374, + -0.021179199, + -0.025817871, + -0.030609131, + -0.035552979, + -0.040634155, + -0.045837402, + -0.051132202, + -0.056533813, + -0.061996460, + -0.067520142, + -0.073059082, + -0.078628540, + -0.084182739, + -0.089706421, + -0.095169067, + -0.100540161, + -0.105819702, + -0.110946655, + -0.115921021, + -0.120697021, + -0.125259399, + -0.129562378, + -0.133590698, + -0.137298584, + -0.140670776, + -0.143676758, + -0.146255493, + -0.148422241, + -0.150115967, + -0.151306152, + -0.151962280, + -0.152069092, + -0.151596069, + -0.150497437, + -0.148773193, + -0.146362305, + -0.143264771, + -0.139450073, + -0.134887695, + -0.129577637, + -0.123474121, + -0.116577148, + -0.108856201, + 0.100311279, + 0.090927124, + 0.080688477, + 0.069595337, + 0.057617187, + 0.044784546, + 0.031082153, + 0.016510010, + 0.001068115, + -0.015228271, + -0.032379150, + -0.050354004, + -0.069168091, + -0.088775635, + -0.109161377, + -0.130310059, + -0.152206421, + -0.174789429, + -0.198059082, + -0.221984863, + -0.246505737, + -0.271591187, + -0.297210693, + -0.323318481, + -0.349868774, + -0.376800537, + -0.404083252, + -0.431655884, + -0.459472656, + -0.487472534, + -0.515609741, + -0.543823242, + -0.572036743, + -0.600219727, + -0.628295898, + -0.656219482, + -0.683914185, + -0.711318970, + -0.738372803, + -0.765029907, + -0.791213989, + -0.816864014, + -0.841949463, + -0.866363525, + -0.890090942, + -0.913055420, + -0.935195923, + -0.956481934, + -0.976852417, + -0.996246338, + -1.014617920, + -1.031936646, + -1.048156738, + -1.063217163, + -1.077117920, + -1.089782715, + -1.101211548, + -1.111373901, + -1.120223999, + -1.127746582, + -1.133926392, + -1.138763428, + -1.142211914, + -1.144287109, + 1.144989014, + 1.144287109, + 1.142211914, + 1.138763428, + 1.133926392, + 1.127746582, + 1.120223999, + 1.111373901, + 1.101211548, + 1.089782715, + 1.077117920, + 1.063217163, + 1.048156738, + 1.031936646, + 1.014617920, + 0.996246338, + 0.976852417, + 0.956481934, + 0.935195923, + 0.913055420, + 0.890090942, + 0.866363525, + 0.841949463, + 0.816864014, + 0.791213989, + 0.765029907, + 0.738372803, + 0.711318970, + 0.683914185, + 0.656219482, + 0.628295898, + 0.600219727, + 0.572036743, + 0.543823242, + 0.515609741, + 0.487472534, + 0.459472656, + 0.431655884, + 0.404083252, + 0.376800537, + 0.349868774, + 0.323318481, + 0.297210693, + 0.271591187, + 0.246505737, + 0.221984863, + 0.198059082, + 0.174789429, + 0.152206421, + 0.130310059, + 0.109161377, + 0.088775635, + 0.069168091, + 0.050354004, + 0.032379150, + 0.015228271, + -0.001068115, + -0.016510010, + -0.031082153, + -0.044784546, + -0.057617187, + -0.069595337, + -0.080688477, + -0.090927124, + 0.100311279, + 0.108856201, + 0.116577148, + 0.123474121, + 0.129577637, + 0.134887695, + 0.139450073, + 0.143264771, + 0.146362305, + 0.148773193, + 0.150497437, + 0.151596069, + 0.152069092, + 0.151962280, + 0.151306152, + 0.150115967, + 0.148422241, + 0.146255493, + 0.143676758, + 0.140670776, + 0.137298584, + 0.133590698, + 0.129562378, + 0.125259399, + 0.120697021, + 0.115921021, + 0.110946655, + 0.105819702, + 0.100540161, + 0.095169067, + 0.089706421, + 0.084182739, + 0.078628540, + 0.073059082, + 0.067520142, + 0.061996460, + 0.056533813, + 0.051132202, + 0.045837402, + 0.040634155, + 0.035552979, + 0.030609131, + 0.025817871, + 0.021179199, + 0.016708374, + 0.012420654, + 0.008316040, + 0.004394531, + 0.000686646, + -0.002822876, + -0.006134033, + -0.009231567, + -0.012115479, + -0.014801025, + -0.017257690, + -0.019531250, + -0.021575928, + -0.023422241, + -0.025085449, + -0.026535034, + -0.027801514, + -0.028884888, + -0.029785156, + -0.030517578, + 0.031082153, + 0.031478882, + 0.031738281, + 0.031845093, + 0.031814575, + 0.031661987, + 0.031387329, + 0.031005859, + 0.030532837, + 0.029937744, + 0.029281616, + 0.028533936, + 0.027725220, + 0.026840210, + 0.025909424, + 0.024932861, + 0.023910522, + 0.022857666, + 0.021789551, + 0.020690918, + 0.019577026, + 0.018463135, + 0.017349243, + 0.016235352, + 0.015121460, + 0.014022827, + 0.012939453, + 0.011886597, + 0.010848999, + 0.009841919, + 0.008865356, + 0.007919312, + 0.007003784, + 0.006118774, + 0.005294800, + 0.004486084, + 0.003723145, + 0.003005981, + 0.002334595, + 0.001693726, + 0.001098633, + 0.000549316, + 0.000030518, + -0.000442505, + -0.000869751, + -0.001266479, + -0.001617432, + -0.001937866, + -0.002227783, + -0.002487183, + -0.002700806, + -0.002883911, + -0.003051758, + -0.003173828, + -0.003280640, + -0.003372192, + -0.003417969, + -0.003463745, + -0.003479004, + -0.003479004, + -0.003463745, + -0.003433228, + -0.003387451, + -0.003326416, + 0.003250122, + 0.003173828, + 0.003082275, + 0.002990723, + 0.002899170, + 0.002792358, + 0.002685547, + 0.002578735, + 0.002456665, + 0.002349854, + 0.002243042, + 0.002120972, + 0.002014160, + 0.001907349, + 0.001785278, + 0.001693726, + 0.001586914, + 0.001480103, + 0.001388550, + 0.001296997, + 0.001205444, + 0.001113892, + 0.001037598, + 0.000961304, + 0.000885010, + 0.000808716, + 0.000747681, + 0.000686646, + 0.000625610, + 0.000579834, + 0.000534058, + 0.000473022, + 0.000442505, + 0.000396729, + 0.000366211, + 0.000320435, + 0.000289917, + 0.000259399, + 0.000244141, + 0.000213623, + 0.000198364, + 0.000167847, + 0.000152588, + 0.000137329, + 0.000122070, + 0.000106812, + 0.000106812, + 0.000091553, + 0.000076294, + 0.000076294, + 0.000061035, + 0.000061035, + 0.000045776, + 0.000045776, + 0.000030518, + 0.000030518, + 0.000030518, + 0.000030518, + 0.000015259, + 0.000015259, + 0.000015259, + 0.000015259, + 0.000015259, + 0.000015259, ]; diff --git a/src/mp4.rs b/src/mp4.rs index 2ee6294..ec3e348 100644 --- a/src/mp4.rs +++ b/src/mp4.rs @@ -340,10 +340,8 @@ fn assemble( u16be(&mut tkhd_rest, 0); // alternate_group u16be(&mut tkhd_rest, 0); // volume (0 for video) u16be(&mut tkhd_rest, 0); // reserved - // unity transformation matrix - for &v in &[ - 0x0001_0000u32, 0, 0, 0, 0x0001_0000, 0, 0, 0, 0x4000_0000, - ] { + // unity transformation matrix + for &v in &[0x0001_0000u32, 0, 0, 0, 0x0001_0000, 0, 0, 0, 0x4000_0000] { u32be(&mut tkhd_rest, v); } u32be(&mut tkhd_rest, width << 16); // width (16.16 fixed) @@ -367,9 +365,7 @@ fn assemble( for _ in 0..2 { u32be(&mut mvhd_rest, 0); // reserved[2] } - for &v in &[ - 0x0001_0000u32, 0, 0, 0, 0x0001_0000, 0, 0, 0, 0x4000_0000, - ] { + for &v in &[0x0001_0000u32, 0, 0, 0, 0x0001_0000, 0, 0, 0, 0x4000_0000] { u32be(&mut mvhd_rest, v); } for _ in 0..6 { @@ -478,7 +474,11 @@ mod tests { assert!(p + size <= data.len(), "box {:?} overruns file", tag); p += size; } - assert_eq!(p, data.len(), "top-level boxes do not tile the file exactly"); + assert_eq!( + p, + data.len(), + "top-level boxes do not tile the file exactly" + ); tags } diff --git a/src/opus.rs b/src/opus.rs index cad8014..25ee903 100644 --- a/src/opus.rs +++ b/src/opus.rs @@ -38,7 +38,16 @@ fn rd_u32le(b: &[u8], o: usize) -> u32 { u32::from_le_bytes([b[o], b[o + 1], b[o + 2], b[o + 3]]) } fn rd_i64le(b: &[u8], o: usize) -> i64 { - i64::from_le_bytes([b[o], b[o + 1], b[o + 2], b[o + 3], b[o + 4], b[o + 5], b[o + 6], b[o + 7]]) + i64::from_le_bytes([ + b[o], + b[o + 1], + b[o + 2], + b[o + 3], + b[o + 4], + b[o + 5], + b[o + 6], + b[o + 7], + ]) } /// Demux an Ogg stream into Opus packets (segment reassembly across pages). @@ -67,7 +76,10 @@ pub fn demux_ogg(data: &[u8]) -> Result, String> { body += l; if lace < 255 { // a lacing value < 255 terminates a packet - packets.push(OggPacket { data: std::mem::take(&mut cur), granule }); + packets.push(OggPacket { + data: std::mem::take(&mut cur), + granule, + }); } } o = body; @@ -234,7 +246,11 @@ impl<'a> RangeDecoder<'a> { pub fn update(&mut self, fl: u32, fh: u32, ft: u32) { let s = self.ext * (ft - fh); self.val -= s; - self.rng = if fl > 0 { self.ext * (fh - fl) } else { self.rng - s }; + self.rng = if fl > 0 { + self.ext * (fh - fl) + } else { + self.rng - s + }; self.normalize(); } pub fn dec_bit_logp(&mut self, logp: u32) -> u32 { @@ -573,7 +589,12 @@ pub fn range_selftest() -> i32 { } idx += 1; } - println!("opus range coder: {} symbols round-trip in {} bytes [{}]", prog.len(), bytes.len(), if ok { "ok" } else { "FAIL" }); + println!( + "opus range coder: {} symbols round-trip in {} bytes [{}]", + prog.len(), + bytes.len(), + if ok { "ok" } else { "FAIL" } + ); if ok { 0 } else { @@ -594,7 +615,7 @@ pub enum Mode { #[derive(Debug, Clone, Copy)] pub struct Toc { pub mode: Mode, - pub bandwidth_hz: u32, // 4000/6000/8000/12000/20000 + pub bandwidth_hz: u32, // 4000/6000/8000/12000/20000 pub frame_size_samples: u32, // @48kHz pub stereo: bool, pub frame_count: u8, @@ -605,14 +626,38 @@ fn config_table(config: u8) -> (Mode, u32, u32) { // frame size in samples @48k: 2.5ms=120, 5=240, 10=480, 20=960, 40=1920, 60=2880 let (m, bw, fs) = match config { 0..=3 => (Mode::Silk, 4000, [480, 960, 1920, 2880][config as usize]), - 4..=7 => (Mode::Silk, 6000, [480, 960, 1920, 2880][(config - 4) as usize]), - 8..=11 => (Mode::Silk, 8000, [480, 960, 1920, 2880][(config - 8) as usize]), + 4..=7 => ( + Mode::Silk, + 6000, + [480, 960, 1920, 2880][(config - 4) as usize], + ), + 8..=11 => ( + Mode::Silk, + 8000, + [480, 960, 1920, 2880][(config - 8) as usize], + ), 12..=13 => (Mode::Hybrid, 12000, [480, 960][(config - 12) as usize]), 14..=15 => (Mode::Hybrid, 20000, [480, 960][(config - 14) as usize]), - 16..=19 => (Mode::Celt, 4000, [120, 240, 480, 960][(config - 16) as usize]), - 20..=23 => (Mode::Celt, 8000, [120, 240, 480, 960][(config - 20) as usize]), - 24..=27 => (Mode::Celt, 12000, [120, 240, 480, 960][(config - 24) as usize]), - _ => (Mode::Celt, 20000, [120, 240, 480, 960][(config - 28) as usize]), + 16..=19 => ( + Mode::Celt, + 4000, + [120, 240, 480, 960][(config - 16) as usize], + ), + 20..=23 => ( + Mode::Celt, + 8000, + [120, 240, 480, 960][(config - 20) as usize], + ), + 24..=27 => ( + Mode::Celt, + 12000, + [120, 240, 480, 960][(config - 24) as usize], + ), + _ => ( + Mode::Celt, + 20000, + [120, 240, 480, 960][(config - 28) as usize], + ), }; (m, bw, fs) } @@ -622,7 +667,13 @@ pub fn parse_toc(toc: u8) -> Toc { let stereo = (toc >> 2) & 1 == 1; let frame_count = toc & 3; let (mode, bandwidth_hz, frame_size_samples) = config_table(config); - Toc { mode, bandwidth_hz, frame_size_samples, stereo, frame_count } + Toc { + mode, + bandwidth_hz, + frame_size_samples, + stereo, + frame_count, + } } /// Summarize the per-packet TOC distribution across the stream. @@ -772,7 +823,11 @@ pub fn laplace_selftest() -> i32 { break; } } - println!("opus laplace coder: {} energy symbols round-trip [{}]", params.len(), if ok { "ok" } else { "FAIL" }); + println!( + "opus laplace coder: {} energy symbols round-trip [{}]", + params.len(), + if ok { "ok" } else { "FAIL" } + ); if ok { 0 } else { @@ -790,12 +845,27 @@ use crate::opus_tables; /// unquant_coarse_energy: decode band energies into `old_e` (log2-energy units). pub fn unquant_coarse_energy( - d: &mut RangeDecoder, start: usize, end: usize, old_e: &mut [f64], - intra: bool, c_ch: usize, lm: usize, nb: usize, budget: i32, + d: &mut RangeDecoder, + start: usize, + end: usize, + old_e: &mut [f64], + intra: bool, + c_ch: usize, + lm: usize, + nb: usize, + budget: i32, ) { let pm = &opus_tables::E_PROB_MODEL[lm][if intra { 1 } else { 0 }]; - let coef = if intra { 0.0 } else { opus_tables::PRED_COEF[lm] }; - let beta = if intra { opus_tables::BETA_INTRA } else { opus_tables::BETA_COEF[lm] }; + let coef = if intra { + 0.0 + } else { + opus_tables::PRED_COEF[lm] + }; + let beta = if intra { + opus_tables::BETA_INTRA + } else { + opus_tables::BETA_COEF[lm] + }; let mut prev = [0.0f64; 2]; for i in start..end { for c in 0..c_ch { @@ -824,12 +894,28 @@ pub fn unquant_coarse_energy( /// identically to the decoder. (Round-trip path; omits the decay/lfe quality /// heuristics, which only nudge qi — the decoder recovers whatever qi was coded.) pub fn quant_coarse_energy( - enc: &mut RangeEncoder, start: usize, end: usize, e: &[f64], old_e: &mut [f64], - intra: bool, c_ch: usize, lm: usize, nb: usize, budget: i32, + enc: &mut RangeEncoder, + start: usize, + end: usize, + e: &[f64], + old_e: &mut [f64], + intra: bool, + c_ch: usize, + lm: usize, + nb: usize, + budget: i32, ) { let pm = &opus_tables::E_PROB_MODEL[lm][if intra { 1 } else { 0 }]; - let coef = if intra { 0.0 } else { opus_tables::PRED_COEF[lm] }; - let beta = if intra { opus_tables::BETA_INTRA } else { opus_tables::BETA_COEF[lm] }; + let coef = if intra { + 0.0 + } else { + opus_tables::PRED_COEF[lm] + }; + let beta = if intra { + opus_tables::BETA_INTRA + } else { + opus_tables::BETA_COEF[lm] + }; let mut prev = [0.0f64; 2]; for i in start..end { for c in 0..c_ch { @@ -883,13 +969,34 @@ pub fn coarse_energy_selftest() -> i32 { let mut enc = RangeEncoder::with_capacity(1 << 14); let budget = (enc.buf_len() * 8) as i32; enc.enc_bit_logp(intra as u32, 3); // intra flag (as in celt) - quant_coarse_energy(&mut enc, 0, nb, &e, &mut oe_enc, intra, c_ch, lm, nb, budget); + quant_coarse_energy( + &mut enc, + 0, + nb, + &e, + &mut oe_enc, + intra, + c_ch, + lm, + nb, + budget, + ); let bytes = enc.done(); let mut oe_dec = vec![0.0f64; nb * c_ch]; let mut dec = RangeDecoder::new(&bytes); let dbudget = (bytes.len() * 8) as i32; let intra_dec = dec.dec_bit_logp(3) == 1; - unquant_coarse_energy(&mut dec, 0, nb, &mut oe_dec, intra_dec, c_ch, lm, nb, dbudget); + unquant_coarse_energy( + &mut dec, + 0, + nb, + &mut oe_dec, + intra_dec, + c_ch, + lm, + nb, + dbudget, + ); cases += 1; if intra_dec != intra || oe_enc != oe_dec { fails += 1; @@ -898,7 +1005,10 @@ pub fn coarse_energy_selftest() -> i32 { } } } - println!("opus coarse energy: {cases} cases (LM×intra×C) round-trip [{}]", if fails == 0 { "ok" } else { "FAIL" }); + println!( + "opus coarse energy: {cases} cases (LM×intra×C) round-trip [{}]", + if fails == 0 { "ok" } else { "FAIL" } + ); if fails == 0 { 0 } else { @@ -1038,8 +1148,21 @@ pub fn pvq_selftest() -> i32 { }; // (N,K) pairs spanning small/large dims & pulse counts (min(N,K) ≤ 14, as CELT guarantees) let cases = [ - (2usize, 1usize), (2, 5), (3, 1), (3, 8), (4, 2), (4, 10), (8, 1), (8, 6), - (16, 3), (16, 8), (12, 12), (44, 2), (88, 3), (176, 1), (176, 4), + (2usize, 1usize), + (2, 5), + (3, 1), + (3, 8), + (4, 2), + (4, 10), + (8, 1), + (8, 6), + (16, 3), + (16, 8), + (12, 12), + (44, 2), + (88, 3), + (176, 1), + (176, 4), ]; let mut fails = 0; let mut total = 0; @@ -1052,7 +1175,11 @@ pub fn pvq_selftest() -> i32 { counts[(rnd() as usize) % n] += 1; } for i in 0..n { - y[i] = if rnd() & 1 == 1 { -counts[i] } else { counts[i] }; + y[i] = if rnd() & 1 == 1 { + -counts[i] + } else { + counts[i] + }; } let mut enc = RangeEncoder::with_capacity(256); encode_pulses(&y, n, k, &mut enc); @@ -1068,7 +1195,11 @@ pub fn pvq_selftest() -> i32 { } } } - println!("opus PVQ (cwrs): {total} pulse vectors round-trip across {} (N,K) configs [{}]", cases.len(), if fails == 0 { "ok" } else { "FAIL" }); + println!( + "opus PVQ (cwrs): {total} pulse vectors round-trip across {} (N,K) configs [{}]", + cases.len(), + if fails == 0 { "ok" } else { "FAIL" } + ); if fails == 0 { 0 } else { @@ -1082,8 +1213,13 @@ pub fn pvq_selftest() -> i32 { /// unquant_fine_energy: add the fine-quant offset to each band's energy. pub fn unquant_fine_energy( - dec: &mut RangeDecoder, start: usize, end: usize, old_e: &mut [f64], - fine: &[i32], c_ch: usize, nb: usize, + dec: &mut RangeDecoder, + start: usize, + end: usize, + old_e: &mut [f64], + fine: &[i32], + c_ch: usize, + nb: usize, ) { for i in start..end { if fine[i] <= 0 { @@ -1099,8 +1235,14 @@ pub fn unquant_fine_energy( /// quant_fine_energy: encode the residual error to `fine[i]` bits per band. pub fn quant_fine_energy( - enc: &mut RangeEncoder, start: usize, end: usize, old_e: &mut [f64], err: &[f64], - fine: &[i32], c_ch: usize, nb: usize, + enc: &mut RangeEncoder, + start: usize, + end: usize, + old_e: &mut [f64], + err: &[f64], + fine: &[i32], + c_ch: usize, + nb: usize, ) { for i in start..end { if fine[i] <= 0 { @@ -1133,8 +1275,12 @@ pub fn fine_energy_selftest() -> i32 { for f in fine.iter_mut() { *f = (rnd() % 9) as i32; // 0..8 bits } - let base: Vec = (0..nb * c_ch).map(|_| (rnd() % 1000) as f64 / 10.0).collect(); - let err: Vec = (0..nb * c_ch).map(|_| (rnd() % 1000) as f64 / 1000.0 - 0.5).collect(); + let base: Vec = (0..nb * c_ch) + .map(|_| (rnd() % 1000) as f64 / 10.0) + .collect(); + let err: Vec = (0..nb * c_ch) + .map(|_| (rnd() % 1000) as f64 / 1000.0 - 0.5) + .collect(); let mut oe_enc = base.clone(); let mut enc = RangeEncoder::with_capacity(1 << 12); quant_fine_energy(&mut enc, 0, nb, &mut oe_enc, &err, &fine, c_ch, nb); @@ -1146,7 +1292,10 @@ pub fn fine_energy_selftest() -> i32 { fails += 1; } } - println!("opus fine energy: mono+stereo round-trip [{}]", if fails == 0 { "ok" } else { "FAIL" }); + println!( + "opus fine energy: mono+stereo round-trip [{}]", + if fails == 0 { "ok" } else { "FAIL" } + ); if fails == 0 { 0 } else { @@ -1164,7 +1313,11 @@ const LOG_MAX_PSEUDO: usize = 6; const NB_EBANDS: usize = 21; fn get_pulses(i: i32) -> i32 { - if i < 8 { i } else { (8 + (i & 7)) << ((i >> 3) - 1) } + if i < 8 { + i + } else { + (8 + (i & 7)) << ((i >> 3) - 1) + } } /// Largest pulse count whose cached cost ≤ `bits` (8th-bit units), per band/LM. @@ -1184,7 +1337,12 @@ pub fn bits2pulses(band: usize, lm: i32, bits: i32) -> i32 { lo = mid; } } - if b - (if lo == 0 { -1 } else { cache[lo as usize] as i32 }) <= cache[hi as usize] as i32 - b { + if b - (if lo == 0 { + -1 + } else { + cache[lo as usize] as i32 + }) <= cache[hi as usize] as i32 - b + { lo } else { hi @@ -1206,7 +1364,11 @@ pub fn alloc_cache_selftest() -> i32 { let mut fails = 0; let mut total = 0; // also sanity-check get_pulses monotonic + known values - let gp_ok = get_pulses(0) == 0 && get_pulses(7) == 7 && get_pulses(8) == 8 && get_pulses(9) == 9 && get_pulses(16) == 16; + let gp_ok = get_pulses(0) == 0 + && get_pulses(7) == 7 + && get_pulses(8) == 8 + && get_pulses(9) == 9 + && get_pulses(16) == 16; for lm in 0..4 { for band in 0..NB_EBANDS { let off = opus_tables::CACHE_INDEX50[(lm + 1) as usize * NB_EBANDS + band]; @@ -1256,8 +1418,9 @@ const MAX_FINE_BITS: i32 = 8; const SPREAD_ICDF: [u8; 4] = [25, 23, 2, 0]; const TAPSET_ICDF: [u8; 3] = [2, 1, 0]; const TRIM_ICDF: [u8; 11] = [126, 124, 119, 109, 87, 41, 19, 9, 4, 2, 0]; -const LOG2_FRAC_TABLE: [u8; 24] = - [0, 8, 13, 16, 19, 21, 23, 24, 26, 27, 28, 29, 30, 31, 32, 32, 33, 34, 34, 35, 36, 36, 37, 37]; +const LOG2_FRAC_TABLE: [u8; 24] = [ + 0, 8, 13, 16, 19, 21, 23, 24, 26, 27, 28, 29, 30, 31, 32, 32, 33, 34, 34, 35, 36, 36, 37, 37, +]; const TF_SELECT_TABLE: [[i8; 8]; 4] = [ [0, -1, 0, -1, 0, -1, 0, -1], [0, -1, 0, -2, 1, 0, 1, -1], @@ -1273,11 +1436,23 @@ fn eb(i: usize) -> i32 { fn init_caps(cap: &mut [i32], lm: i32, c_ch: i32, nb: usize) { for i in 0..nb { let n = (eb(i + 1) - eb(i)) << lm; - cap[i] = (opus_tables::CACHE_CAPS50[(nb as i32 * (2 * lm + c_ch - 1) + i as i32) as usize] as i32 + 64) * c_ch * n >> 2; - } -} - -fn tf_decode(start: usize, end: usize, is_transient: bool, tf_res: &mut [i32], lm: i32, dec: &mut RangeDecoder) { + cap[i] = (opus_tables::CACHE_CAPS50[(nb as i32 * (2 * lm + c_ch - 1) + i as i32) as usize] + as i32 + + 64) + * c_ch + * n + >> 2; + } +} + +fn tf_decode( + start: usize, + end: usize, + is_transient: bool, + tf_res: &mut [i32], + lm: i32, + dec: &mut RangeDecoder, +) { let mut budget = (dec.storage * 8) as i32; let mut tell = dec.tell(); let mut logp = if is_transient { 2 } else { 4 }; @@ -1309,10 +1484,26 @@ fn tf_decode(start: usize, end: usize, is_transient: bool, tf_res: &mut [i32], l #[allow(clippy::too_many_arguments)] fn interp_bits2pulses( - start: usize, end: usize, skip_start: usize, bits1: &[i32], bits2: &[i32], thresh: &[i32], cap: &[i32], - mut total: i32, balance: &mut i32, skip_rsv: i32, intensity: &mut i32, mut intensity_rsv: i32, - dual_stereo: &mut i32, mut dual_stereo_rsv: i32, pulses: &mut [i32], ebits: &mut [i32], - fine_priority: &mut [i32], c_ch: i32, lm: i32, dec: &mut RangeDecoder, + start: usize, + end: usize, + skip_start: usize, + bits1: &[i32], + bits2: &[i32], + thresh: &[i32], + cap: &[i32], + mut total: i32, + balance: &mut i32, + skip_rsv: i32, + intensity: &mut i32, + mut intensity_rsv: i32, + dual_stereo: &mut i32, + mut dual_stereo_rsv: i32, + pulses: &mut [i32], + ebits: &mut [i32], + fine_priority: &mut [i32], + c_ch: i32, + lm: i32, + dec: &mut RangeDecoder, ) -> usize { let alloc_floor = c_ch << BITRES; let stereo = (c_ch > 1) as i32; @@ -1392,7 +1583,11 @@ fn interp_bits2pulses( total += dual_stereo_rsv; dual_stereo_rsv = 0; } - *dual_stereo = if dual_stereo_rsv > 0 { dec.dec_bit_logp(1) as i32 } else { 0 }; + *dual_stereo = if dual_stereo_rsv > 0 { + dec.dec_bit_logp(1) as i32 + } else { + 0 + }; let mut left = total - psum; let perc = left / (eb(coded_bands as usize) - eb(start)); left -= (eb(coded_bands as usize) - eb(start)) * perc; @@ -1412,7 +1607,12 @@ fn interp_bits2pulses( if n > 1 { let mut excess = (bit - cap[j]).max(0); pulses[j] = bit - excess; - let den = c_ch * n + if c_ch == 2 && n > 2 && *dual_stereo == 0 && (j as i32) < *intensity { 1 } else { 0 }; + let den = c_ch * n + + if c_ch == 2 && n > 2 && *dual_stereo == 0 && (j as i32) < *intensity { + 1 + } else { + 0 + }; let nclogn = den * (opus_tables::LOGN400[j] as i32 + logm); let mut offset = (nclogn >> 1) - den * FINE_OFFSET; if n == 2 { @@ -1459,9 +1659,21 @@ fn interp_bits2pulses( #[allow(clippy::too_many_arguments)] fn compute_allocation( - start: usize, end: usize, offsets: &[i32], cap: &[i32], alloc_trim: i32, intensity: &mut i32, - dual_stereo: &mut i32, mut total: i32, balance: &mut i32, pulses: &mut [i32], ebits: &mut [i32], - fine_priority: &mut [i32], c_ch: i32, lm: i32, dec: &mut RangeDecoder, + start: usize, + end: usize, + offsets: &[i32], + cap: &[i32], + alloc_trim: i32, + intensity: &mut i32, + dual_stereo: &mut i32, + mut total: i32, + balance: &mut i32, + pulses: &mut [i32], + ebits: &mut [i32], + fine_priority: &mut [i32], + c_ch: i32, + lm: i32, + dec: &mut RangeDecoder, ) -> usize { total = total.max(0); let len = NB_EBANDS; @@ -1483,7 +1695,12 @@ fn compute_allocation( let mut trim_offset = vec![0i32; len]; for j in start..end { thresh[j] = ((c_ch) << BITRES).max((3 * (eb(j + 1) - eb(j)) << lm << BITRES) >> 4); - trim_offset[j] = c_ch * (eb(j + 1) - eb(j)) * (alloc_trim - 5 - lm) * (end as i32 - j as i32 - 1) * (1 << (lm + BITRES)) >> 6; + trim_offset[j] = c_ch + * (eb(j + 1) - eb(j)) + * (alloc_trim - 5 - lm) + * (end as i32 - j as i32 - 1) + * (1 << (lm + BITRES)) + >> 6; if (eb(j + 1) - eb(j)) << lm == 1 { trim_offset[j] -= c_ch << BITRES; } @@ -1525,7 +1742,11 @@ fn compute_allocation( for j in start..end { let n = eb(j + 1) - eb(j); let mut b1 = c_ch * n * (av[lo as usize][j] as i32) << lm >> 2; - let mut b2 = if hi >= nb_alloc { cap[j] } else { c_ch * n * (av[hi as usize][j] as i32) << lm >> 2 }; + let mut b2 = if hi >= nb_alloc { + cap[j] + } else { + c_ch * n * (av[hi as usize][j] as i32) << lm >> 2 + }; if b1 > 0 { b1 = 0.max(b1 + trim_offset[j]); } @@ -1544,8 +1765,26 @@ fn compute_allocation( bits2[j] = b2; } interp_bits2pulses( - start, end, skip_start, &bits1, &bits2, &thresh, cap, total, balance, skip_rsv, intensity, - intensity_rsv, dual_stereo, dual_stereo_rsv, pulses, ebits, fine_priority, c_ch, lm, dec, + start, + end, + skip_start, + &bits1, + &bits2, + &thresh, + cap, + total, + balance, + skip_rsv, + intensity, + intensity_rsv, + dual_stereo, + dual_stereo_rsv, + pulses, + ebits, + fine_priority, + c_ch, + lm, + dec, ) } @@ -1593,15 +1832,37 @@ pub fn celt_alloc_demo(data: &[u8]) -> Result { } } tell = dec.tell(); - let is_transient = if lm > 0 && tell + 3 <= total_bits { dec.dec_bit_logp(3) != 0 } else { false }; + let is_transient = if lm > 0 && tell + 3 <= total_bits { + dec.dec_bit_logp(3) != 0 + } else { + false + }; tell = dec.tell(); - let intra = if tell + 3 <= total_bits { dec.dec_bit_logp(3) != 0 } else { false }; + let intra = if tell + 3 <= total_bits { + dec.dec_bit_logp(3) != 0 + } else { + false + }; let mut old_e = vec![0f64; nb * c_ch as usize]; - unquant_coarse_energy(&mut dec, start, end, &mut old_e, intra, c_ch as usize, lm as usize, nb, total_bits); + unquant_coarse_energy( + &mut dec, + start, + end, + &mut old_e, + intra, + c_ch as usize, + lm as usize, + nb, + total_bits, + ); let mut tf_res = vec![0i32; nb]; tf_decode(start, end, is_transient, &mut tf_res, lm, &mut dec); tell = dec.tell(); - let _spread = if tell + 4 <= total_bits { dec.dec_icdf(&SPREAD_ICDF, 5) } else { 2 }; + let _spread = if tell + 4 <= total_bits { + dec.dec_icdf(&SPREAD_ICDF, 5) + } else { + 2 + }; let mut cap = vec![0i32; nb]; init_caps(&mut cap, lm, c_ch, nb); let mut offsets = vec![0i32; nb]; @@ -1628,17 +1889,38 @@ pub fn celt_alloc_demo(data: &[u8]) -> Result { dynalloc_logp = 2.max(dynalloc_logp - 1); } } - let alloc_trim = if tellf + (6 << BITRES) <= total_bits { dec.dec_icdf(&TRIM_ICDF, 7) as i32 } else { 5 }; + let alloc_trim = if tellf + (6 << BITRES) <= total_bits { + dec.dec_icdf(&TRIM_ICDF, 7) as i32 + } else { + 5 + }; let mut bits = (len * 8 << BITRES) - dec.tell_frac() as i32 - 1; - let anti_collapse_rsv = if is_transient && lm >= 2 && bits >= ((lm + 2) << BITRES) { 1 << BITRES } else { 0 }; + let anti_collapse_rsv = if is_transient && lm >= 2 && bits >= ((lm + 2) << BITRES) { + 1 << BITRES + } else { + 0 + }; bits -= anti_collapse_rsv; let mut pulses = vec![0i32; nb]; let mut fine = vec![0i32; nb]; let mut fine_pri = vec![0i32; nb]; let (mut intensity, mut dual_stereo, mut balance) = (0i32, 0i32, 0i32); let coded = compute_allocation( - start, end, &offsets, &cap, alloc_trim, &mut intensity, &mut dual_stereo, bits, &mut balance, - &mut pulses, &mut fine, &mut fine_pri, c_ch, lm, &mut dec, + start, + end, + &offsets, + &cap, + alloc_trim, + &mut intensity, + &mut dual_stereo, + bits, + &mut balance, + &mut pulses, + &mut fine, + &mut fine_pri, + c_ch, + lm, + &mut dec, ); unquant_fine_energy(&mut dec, start, end, &mut old_e, &fine, c_ch as usize, nb); let after = dec.tell_frac() as i32; @@ -1728,7 +2010,15 @@ fn extract_collapse_mask(iy: &[i32], n: usize, b: usize) -> u32 { } /// alg_unquant: decode a unit-norm PVQ shape into X (length N, K pulses). -pub fn alg_unquant(x: &mut [f64], n: usize, k: usize, spread: i32, b: usize, dec: &mut RangeDecoder, gain: f64) -> u32 { +pub fn alg_unquant( + x: &mut [f64], + n: usize, + k: usize, + spread: i32, + b: usize, + dec: &mut RangeDecoder, + gain: f64, +) -> u32 { let mut iy = vec![0i32; n]; let ryy = pvq_decode_into(&mut iy, n, k, dec); let g = gain / (ryy as f64).sqrt(); @@ -1759,18 +2049,34 @@ pub fn exp_rotation_selftest() -> i32 { }; let mut worst = 0.0f64; let mut cases = 0; - for &(n, k, b) in &[(16usize, 3usize, 1usize), (32, 5, 1), (32, 4, 2), (64, 8, 4), (24, 2, 1), (48, 6, 2)] { + for &(n, k, b) in &[ + (16usize, 3usize, 1usize), + (32, 5, 1), + (32, 4, 2), + (64, 8, 4), + (24, 2, 1), + (48, 6, 2), + ] { for spread in 1..=3 { - let orig: Vec = (0..n).map(|_| (rnd() % 2000) as f64 / 1000.0 - 1.0).collect(); + let orig: Vec = (0..n) + .map(|_| (rnd() % 2000) as f64 / 1000.0 - 1.0) + .collect(); let mut x = orig.clone(); exp_rotation(&mut x, n, 1, b, k, spread); exp_rotation(&mut x, n, -1, b, k, spread); - let err = orig.iter().zip(&x).map(|(a, b)| (a - b).abs()).fold(0.0, f64::max); + let err = orig + .iter() + .zip(&x) + .map(|(a, b)| (a - b).abs()) + .fold(0.0, f64::max); worst = worst.max(err); cases += 1; } } - println!("opus exp_rotation: {cases} cases, max round-trip err = {worst:.2e} [{}]", if worst < 1e-9 { "ok" } else { "FAIL" }); + println!( + "opus exp_rotation: {cases} cases, max round-trip err = {worst:.2e} [{}]", + if worst < 1e-9 { "ok" } else { "FAIL" } + ); if worst < 1e-9 { 0 } else { @@ -1843,7 +2149,11 @@ fn compute_qn(n: i32, b: i32, offset: i32, pulse_cap: i32, stereo: bool) -> i32 /// Triangular-pdf encode of itheta given qn (the mono long-block case). fn theta_encode(enc: &mut RangeEncoder, itheta: i32, qn: i32) { let ft = ((qn >> 1) + 1) * ((qn >> 1) + 1); - let fs = if itheta <= qn >> 1 { itheta + 1 } else { qn + 1 - itheta }; + let fs = if itheta <= qn >> 1 { + itheta + 1 + } else { + qn + 1 - itheta + }; let fl = if itheta <= qn >> 1 { itheta * (itheta + 1) >> 1 } else { @@ -1894,7 +2204,11 @@ pub fn theta_selftest() -> i32 { } // isqrt is the helper the triangular decode depends on (floor sqrt). let h_ok = isqrt32(100) == 10 && isqrt32(99) == 9 && isqrt32(0) == 0 && isqrt32(1) == 1; - println!("opus theta coding: {total} (qn,itheta) round-trip [{}]{}", if fails == 0 { "ok" } else { "FAIL" }, if h_ok { "" } else { " (isqrt BAD)" }); + println!( + "opus theta coding: {total} (qn,itheta) round-trip [{}]{}", + if fails == 0 { "ok" } else { "FAIL" }, + if h_ok { "" } else { " (isqrt BAD)" } + ); if fails == 0 && h_ok { 0 } else { @@ -1991,7 +2305,16 @@ struct CeltCtx { /// compute_theta (mono decode path). `n` is the post-split half-size. Returns /// (imid, iside, delta, itheta, qalloc); subtracts qalloc from `b`, updates fill. -fn compute_theta_mono(ctx: &mut CeltCtx, dec: &mut RangeDecoder, n: i32, b: &mut i32, big_b: i32, b0: i32, lm: i32, fill: &mut u32) -> (i32, i32, i32, i32, i32) { +fn compute_theta_mono( + ctx: &mut CeltCtx, + dec: &mut RangeDecoder, + n: i32, + b: &mut i32, + big_b: i32, + b0: i32, + lm: i32, + fill: &mut u32, +) -> (i32, i32, i32, i32, i32) { let pulse_cap = opus_tables::LOGN400[ctx.i] as i32 + lm * (1 << BITRES); let offset = (pulse_cap >> 1) - QTHETA_OFFSET; let qn = compute_qn(n, *b, offset, pulse_cap, false); @@ -2028,12 +2351,25 @@ fn compute_theta_mono(ctx: &mut CeltCtx, dec: &mut RangeDecoder, n: i32, b: &mut /// quant_partition (mono decode, resynth). Operates on x in place (len n). #[allow(clippy::too_many_arguments)] -fn quant_partition(ctx: &mut CeltCtx, dec: &mut RangeDecoder, x: &mut [f64], n: i32, mut b: i32, big_b: i32, lowband: Option<&[f64]>, lm: i32, gain: f64, mut fill: u32) -> u32 { +fn quant_partition( + ctx: &mut CeltCtx, + dec: &mut RangeDecoder, + x: &mut [f64], + n: i32, + mut b: i32, + big_b: i32, + lowband: Option<&[f64]>, + lm: i32, + gain: f64, + mut fill: u32, +) -> u32 { let idx = opus_tables::CACHE_INDEX50[((lm + 1) * NB_EBANDS as i32 + ctx.i as i32) as usize]; let cache_thresh = if idx < 0 { i32::MAX } else { - opus_tables::CACHE_BITS50[idx as usize + opus_tables::CACHE_BITS50[idx as usize] as usize] as i32 + 12 + opus_tables::CACHE_BITS50[idx as usize + opus_tables::CACHE_BITS50[idx as usize] as usize] + as i32 + + 12 }; if lm != -1 && b > cache_thresh && n > 2 { let nh = (n >> 1) as usize; @@ -2061,7 +2397,10 @@ fn quant_partition(ctx: &mut CeltCtx, dec: &mut RangeDecoder, x: &mut [f64], n: delta = 16384; } else { iside = bitexact_cos(16384 - itheta); - delta = frac_mul16(((n >> 1) - 1) << 7, bitexact_log2tan(iside, bitexact_cos(itheta))); + delta = frac_mul16( + ((n >> 1) - 1) << 7, + bitexact_log2tan(iside, bitexact_cos(itheta)), + ); } let mid = imid as f64 / 32768.0; let side = iside as f64 / 32768.0; @@ -2085,19 +2424,63 @@ fn quant_partition(ctx: &mut CeltCtx, dec: &mut RangeDecoder, x: &mut [f64], n: let mut cm; let rebal = ctx.remaining_bits; if mbits >= sbits { - cm = quant_partition(ctx, dec, xl, n >> 1, mbits, big_b2, ll, lm2, gain * mid, fill); + cm = quant_partition( + ctx, + dec, + xl, + n >> 1, + mbits, + big_b2, + ll, + lm2, + gain * mid, + fill, + ); let reb = mbits - (rebal - ctx.remaining_bits); if reb > 3 << BITRES && itheta != 0 { sbits += reb - (3 << BITRES); } - cm |= quant_partition(ctx, dec, xr, n >> 1, sbits, big_b2, lr, lm2, gain * side, fill >> big_b2) << (b0 >> 1); + cm |= quant_partition( + ctx, + dec, + xr, + n >> 1, + sbits, + big_b2, + lr, + lm2, + gain * side, + fill >> big_b2, + ) << (b0 >> 1); } else { - cm = quant_partition(ctx, dec, xr, n >> 1, sbits, big_b2, lr, lm2, gain * side, fill >> big_b2) << (b0 >> 1); + cm = quant_partition( + ctx, + dec, + xr, + n >> 1, + sbits, + big_b2, + lr, + lm2, + gain * side, + fill >> big_b2, + ) << (b0 >> 1); let reb = sbits - (rebal - ctx.remaining_bits); if reb > 3 << BITRES && itheta != 16384 { mbits += reb - (3 << BITRES); } - cm |= quant_partition(ctx, dec, xl, n >> 1, mbits, big_b2, ll, lm2, gain * mid, fill); + cm |= quant_partition( + ctx, + dec, + xl, + n >> 1, + mbits, + big_b2, + ll, + lm2, + gain * mid, + fill, + ); } let _ = &mut mbits; cm @@ -2137,7 +2520,11 @@ fn quant_partition(ctx: &mut CeltCtx, dec: &mut RangeDecoder, x: &mut [f64], n: Some(lb) => { for j in 0..nu { ctx.seed = lcg_rand(ctx.seed); - let tmp = if ctx.seed & 0x8000 != 0 { 1.0 / 256.0 } else { -1.0 / 256.0 }; + let tmp = if ctx.seed & 0x8000 != 0 { + 1.0 / 256.0 + } else { + -1.0 / 256.0 + }; x[j] = lb[j] + tmp; } renormalise_vector(&mut x[..nu], gain); diff --git a/src/opus_tables.rs b/src/opus_tables.rs index 965baef..fac4739 100644 --- a/src/opus_tables.rs +++ b/src/opus_tables.rs @@ -5,138 +5,258 @@ // ═══════════════════════════════════════════════════════════════════════════ /// CELT critical-band boundaries in 2.5ms (120-bin) MDCT units; 21 bands. -pub const EBAND5MS: [u16; 22] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 34, 40, 48, 60, 78, 100]; +pub const EBAND5MS: [u16; 22] = [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 34, 40, 48, 60, 78, 100, +]; /// Coarse-energy probability model [LM][intra][2*band] (Laplace fs<<7, decay<<6). pub const E_PROB_MODEL: [[[u8; 42]; 2]; 4] = [ [ - [72, 127, 65, 129, 66, 128, 65, 128, 64, 128, 62, 128, 64, 128, 64, 128, 92, 78, 92, 79, 92, 78, 90, 79, 116, 41, 115, 40, 114, 40, 132, 26, 132, 26, 145, 17, 161, 12, 176, 10, 177, 11], - [24, 179, 48, 138, 54, 135, 54, 132, 53, 134, 56, 133, 55, 132, 55, 132, 61, 114, 70, 96, 74, 88, 75, 88, 87, 74, 89, 66, 91, 67, 100, 59, 108, 50, 120, 40, 122, 37, 97, 43, 78, 50], + [ + 72, 127, 65, 129, 66, 128, 65, 128, 64, 128, 62, 128, 64, 128, 64, 128, 92, 78, 92, 79, + 92, 78, 90, 79, 116, 41, 115, 40, 114, 40, 132, 26, 132, 26, 145, 17, 161, 12, 176, 10, + 177, 11, + ], + [ + 24, 179, 48, 138, 54, 135, 54, 132, 53, 134, 56, 133, 55, 132, 55, 132, 61, 114, 70, + 96, 74, 88, 75, 88, 87, 74, 89, 66, 91, 67, 100, 59, 108, 50, 120, 40, 122, 37, 97, 43, + 78, 50, + ], ], [ - [83, 78, 84, 81, 88, 75, 86, 74, 87, 71, 90, 73, 93, 74, 93, 74, 109, 40, 114, 36, 117, 34, 117, 34, 143, 17, 145, 18, 146, 19, 162, 12, 165, 10, 178, 7, 189, 6, 190, 8, 177, 9], - [23, 178, 54, 115, 63, 102, 66, 98, 69, 99, 74, 89, 71, 91, 73, 91, 78, 89, 86, 80, 92, 66, 93, 64, 102, 59, 103, 60, 104, 60, 117, 52, 123, 44, 138, 35, 133, 31, 97, 38, 77, 45], + [ + 83, 78, 84, 81, 88, 75, 86, 74, 87, 71, 90, 73, 93, 74, 93, 74, 109, 40, 114, 36, 117, + 34, 117, 34, 143, 17, 145, 18, 146, 19, 162, 12, 165, 10, 178, 7, 189, 6, 190, 8, 177, + 9, + ], + [ + 23, 178, 54, 115, 63, 102, 66, 98, 69, 99, 74, 89, 71, 91, 73, 91, 78, 89, 86, 80, 92, + 66, 93, 64, 102, 59, 103, 60, 104, 60, 117, 52, 123, 44, 138, 35, 133, 31, 97, 38, 77, + 45, + ], ], [ - [61, 90, 93, 60, 105, 42, 107, 41, 110, 45, 116, 38, 113, 38, 112, 38, 124, 26, 132, 27, 136, 19, 140, 20, 155, 14, 159, 16, 158, 18, 170, 13, 177, 10, 187, 8, 192, 6, 175, 9, 159, 10], - [21, 178, 59, 110, 71, 86, 75, 85, 84, 83, 91, 66, 88, 73, 87, 72, 92, 75, 98, 72, 105, 58, 107, 54, 115, 52, 114, 55, 112, 56, 129, 51, 132, 40, 150, 33, 140, 29, 98, 35, 77, 42], + [ + 61, 90, 93, 60, 105, 42, 107, 41, 110, 45, 116, 38, 113, 38, 112, 38, 124, 26, 132, 27, + 136, 19, 140, 20, 155, 14, 159, 16, 158, 18, 170, 13, 177, 10, 187, 8, 192, 6, 175, 9, + 159, 10, + ], + [ + 21, 178, 59, 110, 71, 86, 75, 85, 84, 83, 91, 66, 88, 73, 87, 72, 92, 75, 98, 72, 105, + 58, 107, 54, 115, 52, 114, 55, 112, 56, 129, 51, 132, 40, 150, 33, 140, 29, 98, 35, 77, + 42, + ], ], [ - [42, 121, 96, 66, 108, 43, 111, 40, 117, 44, 123, 32, 120, 36, 119, 33, 127, 33, 134, 34, 139, 21, 147, 23, 152, 20, 158, 25, 154, 26, 166, 21, 173, 16, 184, 13, 184, 10, 150, 13, 139, 15], - [22, 178, 63, 114, 74, 82, 84, 83, 92, 82, 103, 62, 96, 72, 96, 67, 101, 73, 107, 72, 113, 55, 118, 52, 125, 52, 118, 52, 117, 55, 135, 49, 137, 39, 157, 32, 145, 29, 97, 33, 77, 40], + [ + 42, 121, 96, 66, 108, 43, 111, 40, 117, 44, 123, 32, 120, 36, 119, 33, 127, 33, 134, + 34, 139, 21, 147, 23, 152, 20, 158, 25, 154, 26, 166, 21, 173, 16, 184, 13, 184, 10, + 150, 13, 139, 15, + ], + [ + 22, 178, 63, 114, 74, 82, 84, 83, 92, 82, 103, 62, 96, 72, 96, 67, 101, 73, 107, 72, + 113, 55, 118, 52, 125, 52, 118, 52, 117, 55, 135, 49, 137, 39, 157, 32, 145, 29, 97, + 33, 77, 40, + ], ], ]; /// Bit-allocation quality grid, 11 rows × 21 bands (RFC band_allocation). pub const BAND_ALLOCATION: [[u8; 21]; 11] = [ - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [90, 80, 75, 69, 63, 56, 49, 40, 34, 29, 20, 18, 10, 0, 0, 0, 0, 0, 0, 0, 0], - [110, 100, 90, 84, 78, 71, 65, 58, 51, 45, 39, 32, 26, 20, 12, 0, 0, 0, 0, 0, 0], - [118, 110, 103, 93, 86, 80, 75, 70, 65, 59, 53, 47, 40, 31, 23, 15, 4, 0, 0, 0, 0], - [126, 119, 112, 104, 95, 89, 83, 78, 72, 66, 60, 54, 47, 39, 32, 25, 17, 12, 1, 0, 0], - [134, 127, 120, 114, 103, 97, 91, 85, 78, 72, 66, 60, 54, 47, 41, 35, 29, 23, 16, 10, 1], - [144, 137, 130, 124, 113, 107, 101, 95, 88, 82, 76, 70, 64, 57, 51, 45, 39, 33, 26, 15, 1], - [152, 145, 138, 132, 123, 117, 111, 105, 98, 92, 86, 80, 74, 67, 61, 55, 49, 43, 36, 20, 1], - [162, 155, 148, 142, 133, 127, 121, 115, 108, 102, 96, 90, 84, 77, 71, 65, 59, 53, 46, 30, 1], - [172, 165, 158, 152, 143, 137, 131, 125, 118, 112, 106, 100, 94, 87, 81, 75, 69, 63, 56, 45, 20], - [200, 200, 200, 200, 200, 200, 200, 200, 198, 193, 188, 183, 178, 173, 168, 163, 158, 153, 148, 129, 104], + [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + ], + [ + 90, 80, 75, 69, 63, 56, 49, 40, 34, 29, 20, 18, 10, 0, 0, 0, 0, 0, 0, 0, 0, + ], + [ + 110, 100, 90, 84, 78, 71, 65, 58, 51, 45, 39, 32, 26, 20, 12, 0, 0, 0, 0, 0, 0, + ], + [ + 118, 110, 103, 93, 86, 80, 75, 70, 65, 59, 53, 47, 40, 31, 23, 15, 4, 0, 0, 0, 0, + ], + [ + 126, 119, 112, 104, 95, 89, 83, 78, 72, 66, 60, 54, 47, 39, 32, 25, 17, 12, 1, 0, 0, + ], + [ + 134, 127, 120, 114, 103, 97, 91, 85, 78, 72, 66, 60, 54, 47, 41, 35, 29, 23, 16, 10, 1, + ], + [ + 144, 137, 130, 124, 113, 107, 101, 95, 88, 82, 76, 70, 64, 57, 51, 45, 39, 33, 26, 15, 1, + ], + [ + 152, 145, 138, 132, 123, 117, 111, 105, 98, 92, 86, 80, 74, 67, 61, 55, 49, 43, 36, 20, 1, + ], + [ + 162, 155, 148, 142, 133, 127, 121, 115, 108, 102, 96, 90, 84, 77, 71, 65, 59, 53, 46, 30, 1, + ], + [ + 172, 165, 158, 152, 143, 137, 131, 125, 118, 112, 106, 100, 94, 87, 81, 75, 69, 63, 56, 45, + 20, + ], + [ + 200, 200, 200, 200, 200, 200, 200, 200, 198, 193, 188, 183, 178, 173, 168, 163, 158, 153, + 148, 129, 104, + ], ]; /// logN (log2 of band width in Q-units), per band. -pub const LOGN400: [i16; 21] = [0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 16, 16, 16, 21, 21, 24, 29, 34, 36]; +pub const LOGN400: [i16; 21] = [ + 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 16, 16, 16, 21, 21, 24, 29, 34, 36, +]; /// Coarse-energy prediction coefficients (Q15) per LM and beta. -pub const PRED_COEF: [f64; 4] = [29440.0/32768.0, 26112.0/32768.0, 21248.0/32768.0, 16384.0/32768.0]; -pub const BETA_COEF: [f64; 4] = [30147.0/32768.0, 22282.0/32768.0, 12124.0/32768.0, 6554.0/32768.0]; -pub const BETA_INTRA: f64 = 4915.0/32768.0; +pub const PRED_COEF: [f64; 4] = [ + 29440.0 / 32768.0, + 26112.0 / 32768.0, + 21248.0 / 32768.0, + 16384.0 / 32768.0, +]; +pub const BETA_COEF: [f64; 4] = [ + 30147.0 / 32768.0, + 22282.0 / 32768.0, + 12124.0 / 32768.0, + 6554.0 / 32768.0, +]; +pub const BETA_INTRA: f64 = 4915.0 / 32768.0; pub const SMALL_ENERGY_ICDF: [u8; 3] = [2, 1, 0]; /// CELT PVQ combinatorial table U(n,k) (RFC 6716 / libopus, default build). pub const PVQ_U_DATA: [u32; 1272] = [ - 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, - 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, - 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, - 97, 99, 101, 103, 105, 107, 109, 111, 113, 115, 117, 119, 121, 123, 125, 127, - 129, 131, 133, 135, 137, 139, 141, 143, 145, 147, 149, 151, 153, 155, 157, 159, - 161, 163, 165, 167, 169, 171, 173, 175, 177, 179, 181, 183, 185, 187, 189, 191, - 193, 195, 197, 199, 201, 203, 205, 207, 209, 211, 213, 215, 217, 219, 221, 223, - 225, 227, 229, 231, 233, 235, 237, 239, 241, 243, 245, 247, 249, 251, 253, 255, - 257, 259, 261, 263, 265, 267, 269, 271, 273, 275, 277, 279, 281, 283, 285, 287, - 289, 291, 293, 295, 297, 299, 301, 303, 305, 307, 309, 311, 313, 315, 317, 319, - 321, 323, 325, 327, 329, 331, 333, 335, 337, 339, 341, 343, 345, 347, 349, 351, - 13, 25, 41, 61, 85, 113, 145, 181, 221, 265, 313, 365, 421, 481, 545, 613, - 685, 761, 841, 925, 1013, 1105, 1201, 1301, 1405, 1513, 1625, 1741, 1861, 1985, 2113, 2245, - 2381, 2521, 2665, 2813, 2965, 3121, 3281, 3445, 3613, 3785, 3961, 4141, 4325, 4513, 4705, 4901, - 5101, 5305, 5513, 5725, 5941, 6161, 6385, 6613, 6845, 7081, 7321, 7565, 7813, 8065, 8321, 8581, - 8845, 9113, 9385, 9661, 9941, 10225, 10513, 10805, 11101, 11401, 11705, 12013, 12325, 12641, 12961, 13285, - 13613, 13945, 14281, 14621, 14965, 15313, 15665, 16021, 16381, 16745, 17113, 17485, 17861, 18241, 18625, 19013, - 19405, 19801, 20201, 20605, 21013, 21425, 21841, 22261, 22685, 23113, 23545, 23981, 24421, 24865, 25313, 25765, - 26221, 26681, 27145, 27613, 28085, 28561, 29041, 29525, 30013, 30505, 31001, 31501, 32005, 32513, 33025, 33541, - 34061, 34585, 35113, 35645, 36181, 36721, 37265, 37813, 38365, 38921, 39481, 40045, 40613, 41185, 41761, 42341, - 42925, 43513, 44105, 44701, 45301, 45905, 46513, 47125, 47741, 48361, 48985, 49613, 50245, 50881, 51521, 52165, - 52813, 53465, 54121, 54781, 55445, 56113, 56785, 57461, 58141, 58825, 59513, 60205, 60901, 61601, 63, 129, - 231, 377, 575, 833, 1159, 1561, 2047, 2625, 3303, 4089, 4991, 6017, 7175, 8473, 9919, 11521, - 13287, 15225, 17343, 19649, 22151, 24857, 27775, 30913, 34279, 37881, 41727, 45825, 50183, 54809, 59711, 64897, - 70375, 76153, 82239, 88641, 95367, 102425, 109823, 117569, 125671, 134137, 142975, 152193, 161799, 171801, 182207, 193025, - 204263, 215929, 228031, 240577, 253575, 267033, 280959, 295361, 310247, 325625, 341503, 357889, 374791, 392217, 410175, 428673, - 447719, 467321, 487487, 508225, 529543, 551449, 573951, 597057, 620775, 645113, 670079, 695681, 721927, 748825, 776383, 804609, - 833511, 863097, 893375, 924353, 956039, 988441, 1021567, 1055425, 1090023, 1125369, 1161471, 1198337, 1235975, 1274393, 1313599, 1353601, - 1394407, 1436025, 1478463, 1521729, 1565831, 1610777, 1656575, 1703233, 1750759, 1799161, 1848447, 1898625, 1949703, 2001689, 2054591, 2108417, - 2163175, 2218873, 2275519, 2333121, 2391687, 2451225, 2511743, 2573249, 2635751, 2699257, 2763775, 2829313, 2895879, 2963481, 3032127, 3101825, - 3172583, 3244409, 3317311, 3391297, 3466375, 3542553, 3619839, 3698241, 3777767, 3858425, 3940223, 4023169, 4107271, 4192537, 4278975, 4366593, - 4455399, 4545401, 4636607, 4729025, 4822663, 4917529, 5013631, 5110977, 5209575, 5309433, 5410559, 5512961, 5616647, 5721625, 5827903, 5935489, - 6044391, 6154617, 6266175, 6379073, 6493319, 6608921, 6725887, 6844225, 6963943, 7085049, 7207551, 321, 681, 1289, 2241, 3649, - 5641, 8361, 11969, 16641, 22569, 29961, 39041, 50049, 63241, 78889, 97281, 118721, 143529, 172041, 204609, 241601, - 283401, 330409, 383041, 441729, 506921, 579081, 658689, 746241, 842249, 947241, 1061761, 1186369, 1321641, 1468169, 1626561, 1797441, - 1981449, 2179241, 2391489, 2618881, 2862121, 3121929, 3399041, 3694209, 4008201, 4341801, 4695809, 5071041, 5468329, 5888521, 6332481, 6801089, - 7295241, 7815849, 8363841, 8940161, 9545769, 10181641, 10848769, 11548161, 12280841, 13047849, 13850241, 14689089, 15565481, 16480521, 17435329, 18431041, - 19468809, 20549801, 21675201, 22846209, 24064041, 25329929, 26645121, 28010881, 29428489, 30899241, 32424449, 34005441, 35643561, 37340169, 39096641, 40914369, - 42794761, 44739241, 46749249, 48826241, 50971689, 53187081, 55473921, 57833729, 60268041, 62778409, 65366401, 68033601, 70781609, 73612041, 76526529, 79526721, - 82614281, 85790889, 89058241, 92418049, 95872041, 99421961, 103069569, 106816641, 110664969, 114616361, 118672641, 122835649, 127107241, 131489289, 135983681, 140592321, - 145317129, 150160041, 155123009, 160208001, 165417001, 170752009, 176215041, 181808129, 187533321, 193392681, 199388289, 205522241, 211796649, 218213641, 224775361, 231483969, - 238341641, 245350569, 252512961, 259831041, 267307049, 274943241, 282741889, 290705281, 298835721, 307135529, 315607041, 324252609, 333074601, 342075401, 351257409, 360623041, - 370174729, 379914921, 389846081, 399970689, 410291241, 420810249, 431530241, 442453761, 453583369, 464921641, 476471169, 488234561, 500214441, 512413449, 524834241, 537479489, - 550351881, 563454121, 576788929, 590359041, 604167209, 618216201, 632508801, 1683, 3653, 7183, 13073, 22363, 36365, 56695, 85305, 124515, - 177045, 246047, 335137, 448427, 590557, 766727, 982729, 1244979, 1560549, 1937199, 2383409, 2908411, 3522221, 4235671, 5060441, 6009091, - 7095093, 8332863, 9737793, 11326283, 13115773, 15124775, 17372905, 19880915, 22670725, 25765455, 29189457, 32968347, 37129037, 41699767, 46710137, 52191139, - 58175189, 64696159, 71789409, 79491819, 87841821, 96879431, 106646281, 117185651, 128542501, 140763503, 153897073, 167993403, 183104493, 199284183, 216588185, 235074115, - 254801525, 275831935, 298228865, 322057867, 347386557, 374284647, 402823977, 433078547, 465124549, 499040399, 534906769, 572806619, 612825229, 655050231, 699571641, 746481891, - 795875861, 847850911, 902506913, 959946283, 1020274013, 1083597703, 1150027593, 1219676595, 1292660325, 1369097135, 1449108145, 1532817275, 1620351277, 1711839767, 1807415257, 1907213187, - 2011371957, 2120032959, 8989, 19825, 40081, 75517, 134245, 227305, 369305, 579125, 880685, 1303777, 1884961, 2668525, 3707509, 5064793, - 6814249, 9041957, 11847485, 15345233, 19665841, 24957661, 31388293, 39146185, 48442297, 59511829, 72616013, 88043969, 106114625, 127178701, 151620757, 179861305, - 212358985, 249612805, 292164445, 340600625, 395555537, 457713341, 527810725, 606639529, 695049433, 793950709, 904317037, 1027188385, 1163673953, 1314955181, 1482288821, 1667010073, - 1870535785, 2094367717, 48639, 108545, 224143, 433905, 795455, 1392065, 2340495, 3800305, 5984767, 9173505, 13726991, 20103025, 28875327, 40754369, - 56610575, 77500017, 104692735, 139703809, 184327311, 240673265, 311207743, 398796225, 506750351, 638878193, 799538175, 993696769, 1226990095, 1505789553, 1837271615, 2229491905, - 265729, 598417, 1256465, 2485825, 4673345, 8405905, 14546705, 24331777, 39490049, 62390545, 96220561, 145198913, 214828609, 312193553, 446304145, 628496897, - 872893441, 1196924561, 1621925137, 2173806145, 1462563, 3317445, 7059735, 14218905, 27298155, 50250765, 89129247, 152951073, 254831667, 413442773, 654862247, 1014889769, - 1541911931, 2300409629, 3375210671, 8097453, 18474633, 39753273, 81270333, 158819253, 298199265, 540279585, 948062325, 1616336765, 45046719, 103274625, 224298231, 464387817, + 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, + 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, + 99, 101, 103, 105, 107, 109, 111, 113, 115, 117, 119, 121, 123, 125, 127, 129, 131, 133, 135, + 137, 139, 141, 143, 145, 147, 149, 151, 153, 155, 157, 159, 161, 163, 165, 167, 169, 171, 173, + 175, 177, 179, 181, 183, 185, 187, 189, 191, 193, 195, 197, 199, 201, 203, 205, 207, 209, 211, + 213, 215, 217, 219, 221, 223, 225, 227, 229, 231, 233, 235, 237, 239, 241, 243, 245, 247, 249, + 251, 253, 255, 257, 259, 261, 263, 265, 267, 269, 271, 273, 275, 277, 279, 281, 283, 285, 287, + 289, 291, 293, 295, 297, 299, 301, 303, 305, 307, 309, 311, 313, 315, 317, 319, 321, 323, 325, + 327, 329, 331, 333, 335, 337, 339, 341, 343, 345, 347, 349, 351, 13, 25, 41, 61, 85, 113, 145, + 181, 221, 265, 313, 365, 421, 481, 545, 613, 685, 761, 841, 925, 1013, 1105, 1201, 1301, 1405, + 1513, 1625, 1741, 1861, 1985, 2113, 2245, 2381, 2521, 2665, 2813, 2965, 3121, 3281, 3445, 3613, + 3785, 3961, 4141, 4325, 4513, 4705, 4901, 5101, 5305, 5513, 5725, 5941, 6161, 6385, 6613, 6845, + 7081, 7321, 7565, 7813, 8065, 8321, 8581, 8845, 9113, 9385, 9661, 9941, 10225, 10513, 10805, + 11101, 11401, 11705, 12013, 12325, 12641, 12961, 13285, 13613, 13945, 14281, 14621, 14965, + 15313, 15665, 16021, 16381, 16745, 17113, 17485, 17861, 18241, 18625, 19013, 19405, 19801, + 20201, 20605, 21013, 21425, 21841, 22261, 22685, 23113, 23545, 23981, 24421, 24865, 25313, + 25765, 26221, 26681, 27145, 27613, 28085, 28561, 29041, 29525, 30013, 30505, 31001, 31501, + 32005, 32513, 33025, 33541, 34061, 34585, 35113, 35645, 36181, 36721, 37265, 37813, 38365, + 38921, 39481, 40045, 40613, 41185, 41761, 42341, 42925, 43513, 44105, 44701, 45301, 45905, + 46513, 47125, 47741, 48361, 48985, 49613, 50245, 50881, 51521, 52165, 52813, 53465, 54121, + 54781, 55445, 56113, 56785, 57461, 58141, 58825, 59513, 60205, 60901, 61601, 63, 129, 231, 377, + 575, 833, 1159, 1561, 2047, 2625, 3303, 4089, 4991, 6017, 7175, 8473, 9919, 11521, 13287, + 15225, 17343, 19649, 22151, 24857, 27775, 30913, 34279, 37881, 41727, 45825, 50183, 54809, + 59711, 64897, 70375, 76153, 82239, 88641, 95367, 102425, 109823, 117569, 125671, 134137, + 142975, 152193, 161799, 171801, 182207, 193025, 204263, 215929, 228031, 240577, 253575, 267033, + 280959, 295361, 310247, 325625, 341503, 357889, 374791, 392217, 410175, 428673, 447719, 467321, + 487487, 508225, 529543, 551449, 573951, 597057, 620775, 645113, 670079, 695681, 721927, 748825, + 776383, 804609, 833511, 863097, 893375, 924353, 956039, 988441, 1021567, 1055425, 1090023, + 1125369, 1161471, 1198337, 1235975, 1274393, 1313599, 1353601, 1394407, 1436025, 1478463, + 1521729, 1565831, 1610777, 1656575, 1703233, 1750759, 1799161, 1848447, 1898625, 1949703, + 2001689, 2054591, 2108417, 2163175, 2218873, 2275519, 2333121, 2391687, 2451225, 2511743, + 2573249, 2635751, 2699257, 2763775, 2829313, 2895879, 2963481, 3032127, 3101825, 3172583, + 3244409, 3317311, 3391297, 3466375, 3542553, 3619839, 3698241, 3777767, 3858425, 3940223, + 4023169, 4107271, 4192537, 4278975, 4366593, 4455399, 4545401, 4636607, 4729025, 4822663, + 4917529, 5013631, 5110977, 5209575, 5309433, 5410559, 5512961, 5616647, 5721625, 5827903, + 5935489, 6044391, 6154617, 6266175, 6379073, 6493319, 6608921, 6725887, 6844225, 6963943, + 7085049, 7207551, 321, 681, 1289, 2241, 3649, 5641, 8361, 11969, 16641, 22569, 29961, 39041, + 50049, 63241, 78889, 97281, 118721, 143529, 172041, 204609, 241601, 283401, 330409, 383041, + 441729, 506921, 579081, 658689, 746241, 842249, 947241, 1061761, 1186369, 1321641, 1468169, + 1626561, 1797441, 1981449, 2179241, 2391489, 2618881, 2862121, 3121929, 3399041, 3694209, + 4008201, 4341801, 4695809, 5071041, 5468329, 5888521, 6332481, 6801089, 7295241, 7815849, + 8363841, 8940161, 9545769, 10181641, 10848769, 11548161, 12280841, 13047849, 13850241, + 14689089, 15565481, 16480521, 17435329, 18431041, 19468809, 20549801, 21675201, 22846209, + 24064041, 25329929, 26645121, 28010881, 29428489, 30899241, 32424449, 34005441, 35643561, + 37340169, 39096641, 40914369, 42794761, 44739241, 46749249, 48826241, 50971689, 53187081, + 55473921, 57833729, 60268041, 62778409, 65366401, 68033601, 70781609, 73612041, 76526529, + 79526721, 82614281, 85790889, 89058241, 92418049, 95872041, 99421961, 103069569, 106816641, + 110664969, 114616361, 118672641, 122835649, 127107241, 131489289, 135983681, 140592321, + 145317129, 150160041, 155123009, 160208001, 165417001, 170752009, 176215041, 181808129, + 187533321, 193392681, 199388289, 205522241, 211796649, 218213641, 224775361, 231483969, + 238341641, 245350569, 252512961, 259831041, 267307049, 274943241, 282741889, 290705281, + 298835721, 307135529, 315607041, 324252609, 333074601, 342075401, 351257409, 360623041, + 370174729, 379914921, 389846081, 399970689, 410291241, 420810249, 431530241, 442453761, + 453583369, 464921641, 476471169, 488234561, 500214441, 512413449, 524834241, 537479489, + 550351881, 563454121, 576788929, 590359041, 604167209, 618216201, 632508801, 1683, 3653, 7183, + 13073, 22363, 36365, 56695, 85305, 124515, 177045, 246047, 335137, 448427, 590557, 766727, + 982729, 1244979, 1560549, 1937199, 2383409, 2908411, 3522221, 4235671, 5060441, 6009091, + 7095093, 8332863, 9737793, 11326283, 13115773, 15124775, 17372905, 19880915, 22670725, + 25765455, 29189457, 32968347, 37129037, 41699767, 46710137, 52191139, 58175189, 64696159, + 71789409, 79491819, 87841821, 96879431, 106646281, 117185651, 128542501, 140763503, 153897073, + 167993403, 183104493, 199284183, 216588185, 235074115, 254801525, 275831935, 298228865, + 322057867, 347386557, 374284647, 402823977, 433078547, 465124549, 499040399, 534906769, + 572806619, 612825229, 655050231, 699571641, 746481891, 795875861, 847850911, 902506913, + 959946283, 1020274013, 1083597703, 1150027593, 1219676595, 1292660325, 1369097135, 1449108145, + 1532817275, 1620351277, 1711839767, 1807415257, 1907213187, 2011371957, 2120032959, 8989, + 19825, 40081, 75517, 134245, 227305, 369305, 579125, 880685, 1303777, 1884961, 2668525, + 3707509, 5064793, 6814249, 9041957, 11847485, 15345233, 19665841, 24957661, 31388293, 39146185, + 48442297, 59511829, 72616013, 88043969, 106114625, 127178701, 151620757, 179861305, 212358985, + 249612805, 292164445, 340600625, 395555537, 457713341, 527810725, 606639529, 695049433, + 793950709, 904317037, 1027188385, 1163673953, 1314955181, 1482288821, 1667010073, 1870535785, + 2094367717, 48639, 108545, 224143, 433905, 795455, 1392065, 2340495, 3800305, 5984767, 9173505, + 13726991, 20103025, 28875327, 40754369, 56610575, 77500017, 104692735, 139703809, 184327311, + 240673265, 311207743, 398796225, 506750351, 638878193, 799538175, 993696769, 1226990095, + 1505789553, 1837271615, 2229491905, 265729, 598417, 1256465, 2485825, 4673345, 8405905, + 14546705, 24331777, 39490049, 62390545, 96220561, 145198913, 214828609, 312193553, 446304145, + 628496897, 872893441, 1196924561, 1621925137, 2173806145, 1462563, 3317445, 7059735, 14218905, + 27298155, 50250765, 89129247, 152951073, 254831667, 413442773, 654862247, 1014889769, + 1541911931, 2300409629, 3375210671, 8097453, 18474633, 39753273, 81270333, 158819253, + 298199265, 540279585, 948062325, 1616336765, 45046719, 103274625, 224298231, 464387817, 921406335, 1759885185, 3248227095, 251595969, 579168825, 1267854873, 2653649025, 1409933619, ]; -pub const PVQ_U_ROW: [usize; 15] = [0, 176, 351, 525, 698, 870, 1041, 1131, 1178, 1207, 1226, 1240, 1248, 1254, 1257]; +pub const PVQ_U_ROW: [usize; 15] = [ + 0, 176, 351, 525, 698, 870, 1041, 1131, 1178, 1207, 1226, 1240, 1248, 1254, 1257, +]; /// CELT pulse-cache for bit allocation (RFC 6716 / libopus, 2.5ms base mode). -pub const CACHE_INDEX50: [i16; 105] = [-1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0, 0, 41, 41, 41, 82, 82, 123, 164, 200, 222, 0, 0, 0, 0, 0, 0, 0, 0, 41, 41, 41, 41, 123, 123, 123, 164, 164, 240, 266, 283, 295, 41, 41, 41, 41, 41, 41, 41, 41, 123, 123, 123, 123, 240, 240, 240, 266, 266, 305, 318, 328, 336, 123, 123, 123, 123, 123, 123, 123, 123, 240, 240, 240, 240, 305, 305, 305, 318, 318, 343, 351, 358, 364, 240, 240, 240, 240, 240, 240, 240, 240, 305, 305, 305, 305, 343, 343, 343, 351, 351, 370, 376, 382, 387]; -pub const CACHE_BITS50: [u8; 392] = [40, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 40, 15, 23, 28, 31, 34, 36, 38, 39, 41, 42, 43, 44, 45, 46, 47, 47, 49, 50, 51, 52, 53, 54, 55, 55, 57, 58, 59, 60, 61, 62, 63, 63, 65, 66, 67, 68, 69, 70, 71, 71, 40, 20, 33, 41, 48, 53, 57, 61, 64, 66, 69, 71, 73, 75, 76, 78, 80, 82, 85, 87, 89, 91, 92, 94, 96, 98, 101, 103, 105, 107, 108, 110, 112, 114, 117, 119, 121, 123, 124, 126, 128, 40, 23, 39, 51, 60, 67, 73, 79, 83, 87, 91, 94, 97, 100, 102, 105, 107, 111, 115, 118, 121, 124, 126, 129, 131, 135, 139, 142, 145, 148, 150, 153, 155, 159, 163, 166, 169, 172, 174, 177, 179, 35, 28, 49, 65, 78, 89, 99, 107, 114, 120, 126, 132, 136, 141, 145, 149, 153, 159, 165, 171, 176, 180, 185, 189, 192, 199, 205, 211, 216, 220, 225, 229, 232, 239, 245, 251, 21, 33, 58, 79, 97, 112, 125, 137, 148, 157, 166, 174, 182, 189, 195, 201, 207, 217, 227, 235, 243, 251, 17, 35, 63, 86, 106, 123, 139, 152, 165, 177, 187, 197, 206, 214, 222, 230, 237, 250, 25, 31, 55, 75, 91, 105, 117, 128, 138, 146, 154, 161, 168, 174, 180, 185, 190, 200, 208, 215, 222, 229, 235, 240, 245, 255, 16, 36, 65, 89, 110, 128, 144, 159, 173, 185, 196, 207, 217, 226, 234, 242, 250, 11, 41, 74, 103, 128, 151, 172, 191, 209, 225, 241, 255, 9, 43, 79, 110, 138, 163, 186, 207, 227, 246, 12, 39, 71, 99, 123, 144, 164, 182, 198, 214, 228, 241, 253, 9, 44, 81, 113, 142, 168, 192, 214, 235, 255, 7, 49, 90, 127, 160, 191, 220, 247, 6, 51, 95, 134, 170, 203, 234, 7, 47, 87, 123, 155, 184, 212, 237, 6, 52, 97, 137, 174, 208, 240, 5, 57, 106, 151, 192, 231, 5, 59, 111, 158, 202, 243, 5, 55, 103, 147, 187, 224, 5, 60, 113, 161, 206, 248, 4, 65, 122, 175, 224, 4, 67, 127, 182, 234]; -pub const CACHE_CAPS50: [u8; 168] = [224, 224, 224, 224, 224, 224, 224, 224, 160, 160, 160, 160, 185, 185, 185, 178, 178, 168, 134, 61, 37, 224, 224, 224, 224, 224, 224, 224, 224, 240, 240, 240, 240, 207, 207, 207, 198, 198, 183, 144, 66, 40, 160, 160, 160, 160, 160, 160, 160, 160, 185, 185, 185, 185, 193, 193, 193, 183, 183, 172, 138, 64, 38, 240, 240, 240, 240, 240, 240, 240, 240, 207, 207, 207, 207, 204, 204, 204, 193, 193, 180, 143, 66, 40, 185, 185, 185, 185, 185, 185, 185, 185, 193, 193, 193, 193, 193, 193, 193, 183, 183, 172, 138, 65, 39, 207, 207, 207, 207, 207, 207, 207, 207, 204, 204, 204, 204, 201, 201, 201, 188, 188, 176, 141, 66, 40, 193, 193, 193, 193, 193, 193, 193, 193, 193, 193, 193, 193, 194, 194, 194, 184, 184, 173, 139, 65, 39, 204, 204, 204, 204, 204, 204, 204, 204, 201, 201, 201, 201, 198, 198, 198, 187, 187, 175, 140, 66, 40]; +pub const CACHE_INDEX50: [i16; 105] = [ + -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0, 0, 41, 41, 41, 82, 82, 123, 164, 200, 222, 0, 0, 0, 0, + 0, 0, 0, 0, 41, 41, 41, 41, 123, 123, 123, 164, 164, 240, 266, 283, 295, 41, 41, 41, 41, 41, + 41, 41, 41, 123, 123, 123, 123, 240, 240, 240, 266, 266, 305, 318, 328, 336, 123, 123, 123, + 123, 123, 123, 123, 123, 240, 240, 240, 240, 305, 305, 305, 318, 318, 343, 351, 358, 364, 240, + 240, 240, 240, 240, 240, 240, 240, 305, 305, 305, 305, 343, 343, 343, 351, 351, 370, 376, 382, + 387, +]; +pub const CACHE_BITS50: [u8; 392] = [ + 40, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 40, 15, 23, 28, 31, 34, 36, 38, 39, 41, 42, 43, 44, 45, 46, 47, + 47, 49, 50, 51, 52, 53, 54, 55, 55, 57, 58, 59, 60, 61, 62, 63, 63, 65, 66, 67, 68, 69, 70, 71, + 71, 40, 20, 33, 41, 48, 53, 57, 61, 64, 66, 69, 71, 73, 75, 76, 78, 80, 82, 85, 87, 89, 91, 92, + 94, 96, 98, 101, 103, 105, 107, 108, 110, 112, 114, 117, 119, 121, 123, 124, 126, 128, 40, 23, + 39, 51, 60, 67, 73, 79, 83, 87, 91, 94, 97, 100, 102, 105, 107, 111, 115, 118, 121, 124, 126, + 129, 131, 135, 139, 142, 145, 148, 150, 153, 155, 159, 163, 166, 169, 172, 174, 177, 179, 35, + 28, 49, 65, 78, 89, 99, 107, 114, 120, 126, 132, 136, 141, 145, 149, 153, 159, 165, 171, 176, + 180, 185, 189, 192, 199, 205, 211, 216, 220, 225, 229, 232, 239, 245, 251, 21, 33, 58, 79, 97, + 112, 125, 137, 148, 157, 166, 174, 182, 189, 195, 201, 207, 217, 227, 235, 243, 251, 17, 35, + 63, 86, 106, 123, 139, 152, 165, 177, 187, 197, 206, 214, 222, 230, 237, 250, 25, 31, 55, 75, + 91, 105, 117, 128, 138, 146, 154, 161, 168, 174, 180, 185, 190, 200, 208, 215, 222, 229, 235, + 240, 245, 255, 16, 36, 65, 89, 110, 128, 144, 159, 173, 185, 196, 207, 217, 226, 234, 242, 250, + 11, 41, 74, 103, 128, 151, 172, 191, 209, 225, 241, 255, 9, 43, 79, 110, 138, 163, 186, 207, + 227, 246, 12, 39, 71, 99, 123, 144, 164, 182, 198, 214, 228, 241, 253, 9, 44, 81, 113, 142, + 168, 192, 214, 235, 255, 7, 49, 90, 127, 160, 191, 220, 247, 6, 51, 95, 134, 170, 203, 234, 7, + 47, 87, 123, 155, 184, 212, 237, 6, 52, 97, 137, 174, 208, 240, 5, 57, 106, 151, 192, 231, 5, + 59, 111, 158, 202, 243, 5, 55, 103, 147, 187, 224, 5, 60, 113, 161, 206, 248, 4, 65, 122, 175, + 224, 4, 67, 127, 182, 234, +]; +pub const CACHE_CAPS50: [u8; 168] = [ + 224, 224, 224, 224, 224, 224, 224, 224, 160, 160, 160, 160, 185, 185, 185, 178, 178, 168, 134, + 61, 37, 224, 224, 224, 224, 224, 224, 224, 224, 240, 240, 240, 240, 207, 207, 207, 198, 198, + 183, 144, 66, 40, 160, 160, 160, 160, 160, 160, 160, 160, 185, 185, 185, 185, 193, 193, 193, + 183, 183, 172, 138, 64, 38, 240, 240, 240, 240, 240, 240, 240, 240, 207, 207, 207, 207, 204, + 204, 204, 193, 193, 180, 143, 66, 40, 185, 185, 185, 185, 185, 185, 185, 185, 193, 193, 193, + 193, 193, 193, 193, 183, 183, 172, 138, 65, 39, 207, 207, 207, 207, 207, 207, 207, 207, 204, + 204, 204, 204, 201, 201, 201, 188, 188, 176, 141, 66, 40, 193, 193, 193, 193, 193, 193, 193, + 193, 193, 193, 193, 193, 194, 194, 194, 184, 184, 173, 139, 65, 39, 204, 204, 204, 204, 204, + 204, 204, 204, 201, 201, 201, 201, 198, 198, 198, 187, 187, 175, 140, 66, 40, +]; diff --git a/src/png.rs b/src/png.rs index 822dd4b..7b3f0f8 100644 --- a/src/png.rs +++ b/src/png.rs @@ -40,7 +40,11 @@ fn crc32_table() -> [u32; 256] { let mut c = n as u32; let mut k = 0; while k < 8 { - c = if c & 1 != 0 { 0xEDB8_8320 ^ (c >> 1) } else { c >> 1 }; + c = if c & 1 != 0 { + 0xEDB8_8320 ^ (c >> 1) + } else { + c >> 1 + }; k += 1; } t[n] = c; @@ -91,7 +95,12 @@ struct BitReader<'a> { impl<'a> BitReader<'a> { fn new(data: &'a [u8]) -> Self { - BitReader { data, pos: 0, acc: 0, nbits: 0 } + BitReader { + data, + pos: 0, + acc: 0, + nbits: 0, + } } /// Read `n` bits, LSB-first (DEFLATE convention). `n` ≤ 16 in practice. fn bits(&mut self, n: u32) -> Result { @@ -358,7 +367,11 @@ struct BitWriter { impl BitWriter { fn new() -> Self { - BitWriter { buf: Vec::new(), acc: 0, nbits: 0 } + BitWriter { + buf: Vec::new(), + acc: 0, + nbits: 0, + } } /// Write `n` bits LSB-first. fn bits(&mut self, val: u32, n: u32) { @@ -786,7 +799,11 @@ pub fn decode(data: &[u8]) -> Result { } } - Ok(Image { width, height, pixels }) + Ok(Image { + width, + height, + pixels, + }) } // ───────────────────────────────────────────────────────────────────────── @@ -906,7 +923,9 @@ mod tests { #[test] fn zlib_roundtrips_itself() { - let data: Vec = (0..20000u32).map(|i| ((i * 7 + i / 13) % 256) as u8).collect(); + let data: Vec = (0..20000u32) + .map(|i| ((i * 7 + i / 13) % 256) as u8) + .collect(); let z = zlib_compress(&data); let back = zlib_decompress(&z).expect("zlib roundtrip"); assert_eq!(back, data); diff --git a/src/webp.rs b/src/webp.rs index 6298b1f..9483125 100644 --- a/src/webp.rs +++ b/src/webp.rs @@ -10,11 +10,16 @@ /// Encode `pixels` (RGBA8, row-major, `width * height * 4` bytes) as a lossless WebP file. pub fn encode(width: u32, height: u32, pixels: &[u8]) -> Result, String> { if width == 0 || height == 0 || width > 16_384 || height > 16_384 { - return Err(format!("webp: dimensions {width}x{height} out of range (1..=16384)")); + return Err(format!( + "webp: dimensions {width}x{height} out of range (1..=16384)" + )); } let expected = width as usize * height as usize * 4; if pixels.len() != expected { - return Err(format!("webp: expected {expected} RGBA bytes, got {}", pixels.len())); + return Err(format!( + "webp: expected {expected} RGBA bytes, got {}", + pixels.len() + )); } let mut bits = BitWriter::default(); @@ -57,7 +62,9 @@ fn write_flat_literal_code(bits: &mut BitWriter, alphabet: usize) { bits.put(0, 1); // Code-length code: only symbols 0 and 8 are used, each with length 1. The order table // below is fixed by the spec; symbol 8 sits at index 11, so 12 entries are sent. - const ORDER: [usize; 19] = [17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]; + const ORDER: [usize; 19] = [ + 17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + ]; let needed = ORDER.iter().position(|&s| s == 8).map_or(0, |p| p + 1); bits.put((needed - 4) as u32, 4); for &sym in ORDER.iter().take(needed) { @@ -137,7 +144,16 @@ mod tests { #[test] fn round_trips_every_pixel_exactly() { let (w, h) = (5u32, 3u32); - let pixels: Vec = (0..w * h).flat_map(|i| [(i * 37) as u8, (i * 91) as u8, (i * 13) as u8, (255 - i) as u8]).collect(); + let pixels: Vec = (0..w * h) + .flat_map(|i| { + [ + (i * 37) as u8, + (i * 91) as u8, + (i * 13) as u8, + (255 - i) as u8, + ] + }) + .collect(); let webp = encode(w, h, &pixels).expect("encode"); assert_eq!(&webp[0..4], b"RIFF"); assert_eq!(&webp[8..12], b"WEBP"); diff --git a/tests/av1_coeff.rs b/tests/av1_coeff.rs index 6dce87c..c4ec656 100644 --- a/tests/av1_coeff.rs +++ b/tests/av1_coeff.rs @@ -6,15 +6,34 @@ // ═══════════════════════════════════════════════════════════════════════════ use std::process::Command; fn ffmpeg() -> bool { - Command::new("ffmpeg").arg("-version").stdout(std::process::Stdio::null()) - .stderr(std::process::Stdio::null()).status().map(|s| s.success()).unwrap_or(false) + Command::new("ffmpeg") + .arg("-version") + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .status() + .map(|s| s.success()) + .unwrap_or(false) } fn decode_y(stream: &[u8], tag: &str) -> Vec { let dir = env!("CARGO_TARGET_TMPDIR"); let (o, y) = (format!("{dir}/c_{tag}.obu"), format!("{dir}/c_{tag}.yuv")); std::fs::write(&o, stream).unwrap(); - let st = Command::new("ffmpeg").args(["-hide_banner","-v","error","-y","-i",&o, - "-f","rawvideo","-pix_fmt","yuv420p",&y]).status().unwrap(); + let st = Command::new("ffmpeg") + .args([ + "-hide_banner", + "-v", + "error", + "-y", + "-i", + &o, + "-f", + "rawvideo", + "-pix_fmt", + "yuv420p", + &y, + ]) + .status() + .unwrap(); assert!(st.success(), "ffmpeg failed to decode {tag}"); std::fs::read(&y).unwrap()[..4096].to_vec() } @@ -23,34 +42,72 @@ fn decode_y(stream: &[u8], tag: &str) -> Vec { fn dc_tile_reproduces_libaom_byte_exact() { // The (7, negative) coeff is exactly what libaom emitted for its grey still. let s = transcode::av1_frame::encode_dc_keyframe_64(7, true); - assert_eq!(&s[19..], &[0x09, 0xac], "DC tile must reproduce libaom's `09 ac`"); + assert_eq!( + &s[19..], + &[0x09, 0xac], + "DC tile must reproduce libaom's `09 ac`" + ); } #[test] fn dc_coeff_decodes_to_offset_grey() { - if !ffmpeg() { eprintln!("SKIP: no ffmpeg"); return; } + if !ffmpeg() { + eprintln!("SKIP: no ffmpeg"); + return; + } // ±7 ⇒ symmetric ±2 around mid-grey (sign controls direction). let neg = decode_y(&transcode::av1_frame::encode_dc_keyframe_64(7, true), "n7"); - assert!(neg.iter().all(|&p| p == 126), "neg DC: expected uniform 126, got {:?}", &neg[..4]); + assert!( + neg.iter().all(|&p| p == 126), + "neg DC: expected uniform 126, got {:?}", + &neg[..4] + ); let pos = decode_y(&transcode::av1_frame::encode_dc_keyframe_64(7, false), "p7"); - assert!(pos.iter().all(|&p| p == 130), "pos DC: expected uniform 130, got {:?}", &pos[..4]); + assert!( + pos.iter().all(|&p| p == 130), + "pos DC: expected uniform 130, got {:?}", + &pos[..4] + ); // every level in the clean (pre-saturation) range decodes to a uniform frame for tok in [1u32, 3, 7, 14, 20, 40] { - let y = decode_y(&transcode::av1_frame::encode_dc_keyframe_64(tok, false), &format!("s{tok}")); + let y = decode_y( + &transcode::av1_frame::encode_dc_keyframe_64(tok, false), + &format!("s{tok}"), + ); let set: std::collections::HashSet<_> = y.iter().collect(); - assert_eq!(set.len(), 1, "dc_tok={tok}: frame must be uniform, got {} values", set.len()); + assert_eq!( + set.len(), + 1, + "dc_tok={tok}: frame must be uniform, got {} values", + set.len() + ); } } #[test] fn ac_coeff_decodes_nonuniform() { - if !ffmpeg() { eprintln!("SKIP: no ffmpeg"); return; } + if !ffmpeg() { + eprintln!("SKIP: no ffmpeg"); + return; + } // DC + one vertical-AC coeff ⇒ the decoded luma must NOT be flat. - let y = decode_y(&transcode::av1_frame::encode_ac_keyframe_64(1, false, 1, false), "ac11"); + let y = decode_y( + &transcode::av1_frame::encode_ac_keyframe_64(1, false, 1, false), + "ac11", + ); let distinct: std::collections::HashSet<_> = y.iter().collect(); - assert!(distinct.len() >= 2, "AC coeff must produce spatial variation, got {} value(s)", distinct.len()); + assert!( + distinct.len() >= 2, + "AC coeff must produce spatial variation, got {} value(s)", + distinct.len() + ); // a few level/sign variants must all decode without error - for (d, dn, a, an) in [(1u32,false,1u32,false),(2,true,1,false),(1,false,2,true),(2,true,2,true)] { + for (d, dn, a, an) in [ + (1u32, false, 1u32, false), + (2, true, 1, false), + (1, false, 2, true), + (2, true, 2, true), + ] { let s = transcode::av1_frame::encode_ac_keyframe_64(d, dn, a, an); let _ = decode_y(&s, &format!("ac{d}{}{a}{}", dn as u8, an as u8)); // asserts ffmpeg success inside } diff --git a/tests/av1_decode.rs b/tests/av1_decode.rs index 9b4c52f..3225b48 100644 --- a/tests/av1_decode.rs +++ b/tests/av1_decode.rs @@ -6,9 +6,13 @@ use std::process::Command; fn ffmpeg_available() -> bool { - Command::new("ffmpeg").arg("-version") - .stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()) - .status().map(|s| s.success()).unwrap_or(false) + Command::new("ffmpeg") + .arg("-version") + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .status() + .map(|s| s.success()) + .unwrap_or(false) } #[test] @@ -25,9 +29,21 @@ fn flat_keyframe_decodes_in_ffmpeg() { // decode to planar yuv420p let st = Command::new("ffmpeg") - .args(["-hide_banner", "-v", "error", "-y", "-i", &obu, - "-f", "rawvideo", "-pix_fmt", "yuv420p", &yuv]) - .status().expect("spawn ffmpeg"); + .args([ + "-hide_banner", + "-v", + "error", + "-y", + "-i", + &obu, + "-f", + "rawvideo", + "-pix_fmt", + "yuv420p", + &yuv, + ]) + .status() + .expect("spawn ffmpeg"); assert!(st.success(), "ffmpeg failed to decode our AV1 stream"); let d = std::fs::read(&yuv).expect("read yuv"); @@ -35,7 +51,11 @@ fn flat_keyframe_decodes_in_ffmpeg() { assert_eq!(d.len(), 64 * 64 + 2 * 32 * 32, "decoded frame size"); let (y, u, v) = (&d[..4096], &d[4096..5120], &d[5120..]); // flat DC prediction, no residual ⇒ every sample is mid-grey 128 - assert!(y.iter().all(|&p| p == 128), "Y not uniform 128: {:?}", &y[..8]); + assert!( + y.iter().all(|&p| p == 128), + "Y not uniform 128: {:?}", + &y[..8] + ); assert!(u.iter().all(|&p| p == 128), "U not uniform 128"); assert!(v.iter().all(|&p| p == 128), "V not uniform 128"); } diff --git a/tests/av1_gencoef.rs b/tests/av1_gencoef.rs index 32779a5..6bf27e7 100644 --- a/tests/av1_gencoef.rs +++ b/tests/av1_gencoef.rs @@ -2,43 +2,99 @@ // unified grammar (encode_block_2d), then dav1d must decode them. Confirms the // grammar ≡ dav1d (round-trip already proves Enc≡Dec). use std::process::Command; +use transcode::av1_coef::{encode_block_2d, CoefCdf}; use transcode::av1_ec::Writer; -use transcode::av1_coef::{CoefCdf, encode_block_2d}; -use transcode::av1_obu::{sequence_header_obu, temporal_delimiter, wrap_obu, write_frame_header, OBU_FRAME}; +use transcode::av1_obu::{ + sequence_header_obu, temporal_delimiter, wrap_obu, write_frame_header, OBU_FRAME, +}; use transcode::h264bits::BitWriter; -fn cdf(a:&[u16])->Vec{let mut v:Vec=a.iter().map(|&x|32768-x).collect();v.push(0);v.push(0);v} -fn bcdf(a:u16)->[u16;2]{[32768-a,0]} -fn ffmpeg()->bool{Command::new("ffmpeg").arg("-version").stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()).status().map(|s|s.success()).unwrap_or(false)} +fn cdf(a: &[u16]) -> Vec { + let mut v: Vec = a.iter().map(|&x| 32768 - x).collect(); + v.push(0); + v.push(0); + v +} +fn bcdf(a: u16) -> [u16; 2] { + [32768 - a, 0] +} +fn ffmpeg() -> bool { + Command::new("ffmpeg") + .arg("-version") + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .status() + .map(|s| s.success()) + .unwrap_or(false) +} -fn build(coeffs:&[i32])->Vec{ - let part=[20137u16,21547,23078,29566,29837,30261,30524,30892,31724]; - let ym=[15588u16,17027,19338,20218,20682,21110,21825,23244,24189,28165,29093,30466]; - let uv=[22631u16,24152,25378,25661,25986,26520,27055,27923,28244,30059,30941,31961]; - let mut w=Writer::new(); - let mut c=cdf(&part); w.symbol(0,&mut c,10); - let mut s=bcdf(31671); w.bool_adapt(false,&mut s); - let mut c=cdf(&ym); w.symbol(0,&mut c,13); - let mut c=cdf(&uv); w.symbol(0,&mut c,13); - let mut cc=CoefCdf::new(); encode_block_2d(&mut w,&mut cc,coeffs); - let mut cz=bcdf(4656); w.bool_adapt(true,&mut cz); w.bool_adapt(true,&mut cz); - let tile=w.finish(); - let mut out=temporal_delimiter(); out.extend_from_slice(&sequence_header_obu(64,64)); - let mut fh=BitWriter::new(); write_frame_header(&mut fh,64,64,128); fh.align_zero(); - let mut pl=fh.into_rbsp(); pl.extend_from_slice(&tile); - out.extend_from_slice(&wrap_obu(OBU_FRAME,&pl)); out +fn build(coeffs: &[i32]) -> Vec { + let part = [ + 20137u16, 21547, 23078, 29566, 29837, 30261, 30524, 30892, 31724, + ]; + let ym = [ + 15588u16, 17027, 19338, 20218, 20682, 21110, 21825, 23244, 24189, 28165, 29093, 30466, + ]; + let uv = [ + 22631u16, 24152, 25378, 25661, 25986, 26520, 27055, 27923, 28244, 30059, 30941, 31961, + ]; + let mut w = Writer::new(); + let mut c = cdf(&part); + w.symbol(0, &mut c, 10); + let mut s = bcdf(31671); + w.bool_adapt(false, &mut s); + let mut c = cdf(&ym); + w.symbol(0, &mut c, 13); + let mut c = cdf(&uv); + w.symbol(0, &mut c, 13); + let mut cc = CoefCdf::new(); + encode_block_2d(&mut w, &mut cc, coeffs); + let mut cz = bcdf(4656); + w.bool_adapt(true, &mut cz); + w.bool_adapt(true, &mut cz); + let tile = w.finish(); + let mut out = temporal_delimiter(); + out.extend_from_slice(&sequence_header_obu(64, 64)); + let mut fh = BitWriter::new(); + write_frame_header(&mut fh, 64, 64, 128); + fh.align_zero(); + let mut pl = fh.into_rbsp(); + pl.extend_from_slice(&tile); + out.extend_from_slice(&wrap_obu(OBU_FRAME, &pl)); + out } #[test] -fn gencoef_decodes_in_ffmpeg(){ - if !ffmpeg(){eprintln!("SKIP");return;} - let mut coeffs=vec![0i32;1024]; coeffs[0]=2; coeffs[32]=1; coeffs[1]=3; - let s=build(&coeffs); - let dir=env!("CARGO_TARGET_TMPDIR"); - std::fs::write(format!("{dir}/gc.obu"),&s).unwrap(); - let st=Command::new("ffmpeg").args(["-hide_banner","-v","error","-y","-i",&format!("{dir}/gc.obu"),"-f","rawvideo","-pix_fmt","yuv420p",&format!("{dir}/gc.yuv")]).status().unwrap(); - assert!(st.success(),"ffmpeg failed to decode multi-coeff frame"); - let d=std::fs::read(format!("{dir}/gc.yuv")).unwrap(); - let y=&d[..4096]; - let distinct:std::collections::HashSet<_>=y.iter().collect(); +fn gencoef_decodes_in_ffmpeg() { + if !ffmpeg() { + eprintln!("SKIP"); + return; + } + let mut coeffs = vec![0i32; 1024]; + coeffs[0] = 2; + coeffs[32] = 1; + coeffs[1] = 3; + let s = build(&coeffs); + let dir = env!("CARGO_TARGET_TMPDIR"); + std::fs::write(format!("{dir}/gc.obu"), &s).unwrap(); + let st = Command::new("ffmpeg") + .args([ + "-hide_banner", + "-v", + "error", + "-y", + "-i", + &format!("{dir}/gc.obu"), + "-f", + "rawvideo", + "-pix_fmt", + "yuv420p", + &format!("{dir}/gc.yuv"), + ]) + .status() + .unwrap(); + assert!(st.success(), "ffmpeg failed to decode multi-coeff frame"); + let d = std::fs::read(format!("{dir}/gc.yuv")).unwrap(); + let y = &d[..4096]; + let distinct: std::collections::HashSet<_> = y.iter().collect(); eprintln!("Y distinct={} sample={:?}", distinct.len(), &y[..8]); - assert!(distinct.len()>=2,"multi-coeff residual must be non-flat"); + assert!(distinct.len() >= 2, "multi-coeff residual must be non-flat"); } diff --git a/tests/av1_msac_trace.rs b/tests/av1_msac_trace.rs index 4d16f28..a608b84 100644 --- a/tests/av1_msac_trace.rs +++ b/tests/av1_msac_trace.rs @@ -6,31 +6,70 @@ // (all_zero, eob, eob_base_tok, hi_tok/br_tok, dc_sign) to dav1d bit-for-bit. // ═══════════════════════════════════════════════════════════════════════════ use transcode::av1_ec::Reader; -fn cdf(a: &[u16]) -> Vec { let mut v: Vec=a.iter().map(|&x|32768-x).collect(); v.push(0); v.push(0); v } -fn bcdf(a: u16) -> [u16;2] { [32768-a, 0] } +fn cdf(a: &[u16]) -> Vec { + let mut v: Vec = a.iter().map(|&x| 32768 - x).collect(); + v.push(0); + v.push(0); + v +} +fn bcdf(a: u16) -> [u16; 2] { + [32768 - a, 0] +} #[test] fn reader_matches_dav1d_rng_trace() { // dav1d default CDFs (qctx=3), from src/cdf.c. - let part=[20137u16,21547,23078,29566,29837,30261,30524,30892,31724]; - let ym=[15588u16,17027,19338,20218,20682,21110,21825,23244,24189,28165,29093,30466]; - let uv=[22631u16,24152,25378,25661,25986,26520,27055,27923,28244,30059,30941,31961]; - let eob=[6698u16,8334,11961,15762,20186,23862,27434,29326,31082,32050]; - let eobtok=[12358u16,24977]; // eob_base_tok[4][0][0] - let brtok=[12162u16,18785,22648]; // br_tok[3][0][0] (TX_64X64 → imin(ctx,3)=3) - let mut r=Reader::new(&[0x09u8,0xac]); - macro_rules! ck { ($name:expr,$want:expr) => { assert_eq!(r.rng(), $want, "rng diverged at {}", $name); } } - let mut c=cdf(&part); assert_eq!(r.symbol(&mut c,10),0); ck!("partition",40248); - let mut s=bcdf(31671); assert!(!r.bool_adapt(&mut s)); ck!("skip",38910); - let mut c=cdf(&ym); assert_eq!(r.symbol(&mut c,13),0); ck!("ymode",37256); - let mut c=cdf(&uv); assert_eq!(r.symbol(&mut c,13),0); ck!("uvmode",51506); - let mut lz=bcdf(31539); assert!(!r.bool_adapt(&mut lz)); ck!("all_zero",49593); - let mut c=cdf(&eob); assert_eq!(r.symbol(&mut c,11),0); ck!("eob_pt",41112); - let mut c=cdf(&eobtok); assert_eq!(r.symbol(&mut c,3),2); ck!("dc_lo",38736); - let mut br=cdf(&brtok); - assert_eq!(r.symbol(&mut br,4),3); assert_eq!(r.symbol(&mut br,4),1); ck!("dc_hi(=7)",37216); - let mut ds=bcdf(16000); assert!(r.bool_adapt(&mut ds)); ck!("dc_sign",37998); - let mut cz=bcdf(4656); - assert!(r.bool_adapt(&mut cz)); ck!("U_az",64980); - assert!(r.bool_adapt(&mut cz)); ck!("V_az",56043); + let part = [ + 20137u16, 21547, 23078, 29566, 29837, 30261, 30524, 30892, 31724, + ]; + let ym = [ + 15588u16, 17027, 19338, 20218, 20682, 21110, 21825, 23244, 24189, 28165, 29093, 30466, + ]; + let uv = [ + 22631u16, 24152, 25378, 25661, 25986, 26520, 27055, 27923, 28244, 30059, 30941, 31961, + ]; + let eob = [ + 6698u16, 8334, 11961, 15762, 20186, 23862, 27434, 29326, 31082, 32050, + ]; + let eobtok = [12358u16, 24977]; // eob_base_tok[4][0][0] + let brtok = [12162u16, 18785, 22648]; // br_tok[3][0][0] (TX_64X64 → imin(ctx,3)=3) + let mut r = Reader::new(&[0x09u8, 0xac]); + macro_rules! ck { + ($name:expr,$want:expr) => { + assert_eq!(r.rng(), $want, "rng diverged at {}", $name); + }; + } + let mut c = cdf(&part); + assert_eq!(r.symbol(&mut c, 10), 0); + ck!("partition", 40248); + let mut s = bcdf(31671); + assert!(!r.bool_adapt(&mut s)); + ck!("skip", 38910); + let mut c = cdf(&ym); + assert_eq!(r.symbol(&mut c, 13), 0); + ck!("ymode", 37256); + let mut c = cdf(&uv); + assert_eq!(r.symbol(&mut c, 13), 0); + ck!("uvmode", 51506); + let mut lz = bcdf(31539); + assert!(!r.bool_adapt(&mut lz)); + ck!("all_zero", 49593); + let mut c = cdf(&eob); + assert_eq!(r.symbol(&mut c, 11), 0); + ck!("eob_pt", 41112); + let mut c = cdf(&eobtok); + assert_eq!(r.symbol(&mut c, 3), 2); + ck!("dc_lo", 38736); + let mut br = cdf(&brtok); + assert_eq!(r.symbol(&mut br, 4), 3); + assert_eq!(r.symbol(&mut br, 4), 1); + ck!("dc_hi(=7)", 37216); + let mut ds = bcdf(16000); + assert!(r.bool_adapt(&mut ds)); + ck!("dc_sign", 37998); + let mut cz = bcdf(4656); + assert!(r.bool_adapt(&mut cz)); + ck!("U_az", 64980); + assert!(r.bool_adapt(&mut cz)); + ck!("V_az", 56043); } diff --git a/tests/h264_bitexact.rs b/tests/h264_bitexact.rs index 4e4322f..09416d1 100644 --- a/tests/h264_bitexact.rs +++ b/tests/h264_bitexact.rs @@ -93,11 +93,7 @@ fn ffmpeg_decode_yuv420p(stream: &[u8], tag: &str) -> Vec { // Compare ffmpeg's decoded yuv420p against the encoder's reconstruction, // frame by frame, byte-exact. -fn assert_bitexact( - decoded: &[u8], - recons: &[(Vec, Vec, Vec)], - label: &str, -) { +fn assert_bitexact(decoded: &[u8], recons: &[(Vec, Vec, Vec)], label: &str) { let (w, h) = (W as usize, H as usize); let ysz = w * h; let csz = (w / 2) * (h / 2); @@ -118,8 +114,11 @@ fn assert_bitexact( [("Y", (dy, ry)), ("Cb", (dcb, rcb)), ("Cr", (dcr, rcr))].into_iter() { assert_eq!(dec.len(), ours.len(), "{label} f{f} {plane}: size mismatch"); - if let Some((idx, (&a, &b))) = - dec.iter().zip(ours.iter()).enumerate().find(|(_, (a, b))| a != b) + if let Some((idx, (&a, &b))) = dec + .iter() + .zip(ours.iter()) + .enumerate() + .find(|(_, (a, b))| a != b) { let ndiff = dec.iter().zip(ours.iter()).filter(|(a, b)| a != b).count(); panic!( @@ -161,7 +160,10 @@ fn i4x4_decodes_bitexact_in_ffmpeg() { eprintln!("SKIP: ffmpeg not available — cannot run the decode oracle"); return; } - run_path("i4x4", transcode::h264_intra::encode_sequence_i4x4_with_recon); + run_path( + "i4x4", + transcode::h264_intra::encode_sequence_i4x4_with_recon, + ); } #[test] @@ -172,7 +174,10 @@ fn adaptive_decodes_bitexact_in_ffmpeg() { } // The per-MB free-energy decision mixes I_16x16 and I_4x4 MBs in one slice; // ffmpeg must still reconstruct every MB exactly. - run_path("adaptive", transcode::h264_intra::encode_sequence_adaptive_with_recon); + run_path( + "adaptive", + transcode::h264_intra::encode_sequence_adaptive_with_recon, + ); } #[test] @@ -191,25 +196,49 @@ fn mp4_product_path_decodes_in_ffmpeg() { std::fs::write(&path, &mp4).expect("write mp4"); // demux + decode with no errors let dec = Command::new("ffmpeg") - .args(["-hide_banner", "-v", "error", "-i", &path, "-f", "null", "-"]) + .args([ + "-hide_banner", + "-v", + "error", + "-i", + &path, + "-f", + "null", + "-", + ]) .status() .expect("spawn ffmpeg"); assert!(dec.success(), "ffmpeg failed to decode the muxed MP4"); // ffprobe: it really is H.264 at W×H let probe = Command::new("ffprobe") .args([ - "-hide_banner", "-v", "error", "-select_streams", "v:0", - "-show_entries", "stream=codec_name,width,height", - "-of", "csv=p=0", &path, + "-hide_banner", + "-v", + "error", + "-select_streams", + "v:0", + "-show_entries", + "stream=codec_name,width,height", + "-of", + "csv=p=0", + &path, ]) .output() .expect("spawn ffprobe"); let s = String::from_utf8_lossy(&probe.stdout); assert!(s.contains("h264"), "not an h264 track: {s}"); - assert!(s.contains(&W.to_string()) && s.contains(&H.to_string()), "wrong dims: {s}"); + assert!( + s.contains(&W.to_string()) && s.contains(&H.to_string()), + "wrong dims: {s}" + ); // the compressed MP4 must be far smaller than raw I_PCM (≈ YUV420 raw size) let ipcm_floor = (W * H * 3 / 2) as usize; - assert!(mp4.len() < ipcm_floor, "not compressed: {} >= {}", mp4.len(), ipcm_floor); + assert!( + mp4.len() < ipcm_floor, + "not compressed: {} >= {}", + mp4.len(), + ipcm_floor + ); } // `cargo test --release --test h264_bitexact -- --ignored --nocapture report_sizes` @@ -226,9 +255,13 @@ fn report_sizes() { let frames = vec![pattern(kind)]; println!("\n[{kind}]"); for qp in [18i32, 26, 34, 40] { - let (s16, _) = transcode::h264_intra::encode_sequence_with_recon(&frames, W, H, qp).unwrap(); - let (s4, _) = transcode::h264_intra::encode_sequence_i4x4_with_recon(&frames, W, H, qp).unwrap(); - let (sa, _) = transcode::h264_intra::encode_sequence_adaptive_with_recon(&frames, W, H, qp).unwrap(); + let (s16, _) = + transcode::h264_intra::encode_sequence_with_recon(&frames, W, H, qp).unwrap(); + let (s4, _) = + transcode::h264_intra::encode_sequence_i4x4_with_recon(&frames, W, H, qp).unwrap(); + let (sa, _) = + transcode::h264_intra::encode_sequence_adaptive_with_recon(&frames, W, H, qp) + .unwrap(); let best = s16.len().min(s4.len()); println!( " qp{qp:>2}: i16={:>5}B i4x4={:>5}B adaptive={:>5}B (vs best-fixed {:+.0}%)", From 23713d108488bd8e8b66aa8476664a537dce6f60 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 4 Nov 2026 23:27:01 +0000 Subject: [PATCH 08/11] docs: standards and licensing table; owners and security contacts - docs/STANDARDS.md: for each format the crate decodes or encodes, the specification, its body, and the licensing and patent position as understood. Each row is marked unverified: the standards hosts did not resolve from the session that wrote it, so each row links its primary source for review. Open standard is stated as not the same as royalty-free. - README: a standards and licensing section linking the table, and a note that this is a codec implementation, not a certified or licensed product. - CODEOWNERS: @twn-lloyd @yokoszn replace the placeholders. - SECURITY.md: security@twn.systems added alongside private reporting. - CODE_OF_CONDUCT.md: hello@twn.systems as the enforcement contact. - docs/OPENSSF.md: CODEOWNERS and contact items marked resolved; the patent item now points at docs/STANDARDS.md. No codec, fuzz or manifest change. Licence unchanged (MIT). Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Ch6Crfubj3FwdxR7ywn9vT --- .github/CODEOWNERS | 2 +- CODE_OF_CONDUCT.md | 6 ++--- README.md | 20 +++++++++++++++ SECURITY.md | 3 ++- docs/OPENSSF.md | 14 +++++----- docs/STANDARDS.md | 64 ++++++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 97 insertions(+), 12 deletions(-) create mode 100644 docs/STANDARDS.md diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 406a748..36a120e 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -1,4 +1,4 @@ # Code ownership for the required code-owner review on the default-branch # ruleset. Two or more owners so an authoring owner is never locked out # of merging their own change. -* @OWNER-1 @OWNER-2 +* @twn-lloyd @yokoszn diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index dc10d09..77c211e 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -45,9 +45,9 @@ in public spaces. ## Enforcement Report instances of abusive, harassing or otherwise unacceptable behaviour to the project maintainers. -Until a dedicated contact is set up, use GitHub's private reporting for this repository -(**https://github.com/webfold-ai/transcode/security/advisories/new**) and state in the report that it -concerns conduct. All complaints are reviewed promptly and fairly, and the reporter's privacy and +Report conduct concerns to **hello@twn.systems**, or through GitHub's private reporting for this +repository (**https://github.com/webfold-ai/transcode/security/advisories/new**) and state in the +report that it concerns conduct. All complaints are reviewed promptly and fairly, and the reporter's privacy and security are respected. ## Attribution diff --git a/README.md b/README.md index 7acc071..8f66b88 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,26 @@ encoder. Round-trip and external-decoder checks are listed in the Verification s Other modules: `preview` renders a decoded RGBA image as a grayscale text preview (`src/preview.rs`). +## Standards and licensing + +Each format above follows a published specification, listed with its standards body in +[docs/STANDARDS.md](docs/STANDARDS.md). The table there gives the licensing and patent position as +understood for each one, with a link to check it. + +- **Described as royalty-free by their publishers:** PNG (W3C), FLAC (Xiph), Opus (IETF RFC 6716), + AV1 (AOMedia royalty-free patent licence), WebP (Google royalty-free patent licence). +- **Patent-pool or unclear:** H.264 and AAC (patent pools; royalties can apply), MP3 (core patents + understood to have expired, but the position varies by country), and JPEG (baseline understood + to be royalty-free; to be confirmed). +- **Containers:** the MP4, Matroska and HEIF writers carry H.264 here, so the H.264 position applies + to their output. The Motion-JPEG AVI writer is not an ISO standard and was not reviewed. + +An open standard is not automatically royalty-free. The publication status of each row has not +been checked against its primary source yet; see the "Verified" column in docs/STANDARDS.md. + +This crate is a codec implementation. It is not certified against any conformance suite and is +not a licensed product from any codec vendor. + ## Build and test ```sh diff --git a/SECURITY.md b/SECURITY.md index c8882d1..36f20a0 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -16,7 +16,8 @@ Please report security issues privately, using GitHub's private vulnerability re **https://github.com/webfold-ai/transcode/security/advisories/new** -Do not open a public issue, pull request or discussion for a suspected vulnerability. +You can also email **security@twn.systems**. Do not open a public issue, pull request or +discussion for a suspected vulnerability. Include, where you can: diff --git a/docs/OPENSSF.md b/docs/OPENSSF.md index c852138..8b6ae68 100644 --- a/docs/OPENSSF.md +++ b/docs/OPENSSF.md @@ -46,15 +46,15 @@ been created or recorded here. ## Open items -1. **CODEOWNERS placeholders.** `.github/CODEOWNERS` lists `@OWNER-1 @OWNER-2`. These are not real - accounts. Replace them with two or more human maintainers before the code-owner rule is - enabled. Do not use bot accounts. **Human** +1. **CODEOWNERS.** Resolved. `.github/CODEOWNERS` lists `@twn-lloyd @yokoszn`, two human owners, + as the owners instructed. The ruleset still needs applying (item 6). No bot accounts are listed. 2. **Licensing.** Cargo.toml and `LICENSE-MIT` say MIT. An earlier README said `MIT OR Apache-2.0`. Decide, and if dual licensing is wanted, add `LICENSE-APACHE` and change Cargo.toml. **Human** -3. **Patents.** The H.264, AAC and MP3 coverage described in the README needs a legal review - before publication. **Human** -4. **Code of conduct contact.** No dedicated contact exists yet. CODE_OF_CONDUCT.md routes reports - through private reporting for now. **Human** +3. **Patents and standards.** The per-format position is in docs/STANDARDS.md. Every row is still + unverified against its primary source, and H.264, AAC, MP3 and the containers that carry them + need counsel's review before publication. **Human** +4. **Contacts.** Resolved. SECURITY.md lists security@twn.systems and CODE_OF_CONDUCT.md lists + hello@twn.systems, alongside GitHub private reporting. 5. **Visibility.** The repository is private. Scorecard publishing, the badges and dependency-review on private repositories (which needs GitHub Advanced Security) depend on this. **Human** diff --git a/docs/STANDARDS.md b/docs/STANDARDS.md new file mode 100644 index 0000000..f53d266 --- /dev/null +++ b/docs/STANDARDS.md @@ -0,0 +1,64 @@ +# Standards and licensing + +This page lists, for each format this crate decodes or encodes, the specification it follows, who +publishes that specification, and what is understood about its licensing and patent position. +It is written so a maintainer or a counsel can check each row quickly. + +## Read this first + +- **An open standard is not the same as a royalty-free one.** A specification can be published + for free and still be covered by patents that need a licence. Several formats below are in that + position. +- **This is a codec implementation, not a certified or licensed product.** Nothing here is + conformance-certified, and no codec vendor has licensed this code. The crate writes and reads + bytes; whether using those bytes needs a patent licence is a separate question. +- **Nothing here is legal advice.** Each row must be reviewed by counsel before the crate is + published or used commercially. See the decision list at the end. + +## Verification status + +**The rows below were not verified against their primary sources in the session that wrote this +page.** Outbound DNS to the standards hosts (`www.w3.org`, `xiph.org`, `www.rfc-editor.org`, +`aomedia.org`, `developers.google.com`, `www.itu.int`, `via-la.com`, `www.matroska.org`) failed +from that environment. Each row gives the URL to check. Mark a row "verified" only after its +source has been read. + +## Formats + +| Format | Crate module(s) | Specification and body | Licensing and patent position (as understood) | Verified | +|---|---|---|---|---| +| PNG, RGBA8, non-interlaced | `src/png.rs` | PNG Specification, Third Edition. W3C Recommendation, identified as ISO/IEC 15948 | Published by the W3C under its Patent Policy, which provides royalty-free licensing. Source: https://www.w3.org/TR/png-3/ | No | +| JPEG, baseline sequential | `src/jpeg.rs`, `src/mjpeg.rs` | ITU-T T.81, equivalent to ISO/IEC 10918-1. ITU-T and ISO/IEC JPEG committee | The specification is freely downloadable. Baseline JPEG is widely treated as royalty-free, and the main early patent claims are understood to have expired. Confirm with counsel. Source: https://www.itu.int/rec/T-REC-T.81 | No | +| WebP, VP8L lossless | `src/webp.rs` | WebP Lossless Bitstream Specification. Google | Google states a royalty-free patent licence for WebP. The reference library, libwebp, is BSD-3-Clause. Source: https://developers.google.com/speed/webp/docs/webp-lossless-bitstream-specification and https://developers.google.com/speed/webp/faq | No | +| RIFF WAVE, PCM | `src/main.rs`, `src/codec.rs` (CLI path) | RIFF/WAVE, as documented by Microsoft and IBM in the Multimedia Programming Interface and Data Specifications 1.0 (1991). No standards body | Not reviewed. The format is old and widely implemented; no licence requirement has been identified, but that has not been checked. | No | +| FLAC | `src/flac.rs` | FLAC format specification. Xiph.Org Foundation | Documented by Xiph as free to use with no royalties; the reference implementation is BSD-licensed. Source: https://xiph.org/flac/format.html | No | +| SLAC | `src/codec.rs` | This crate's own container. No external specification | Covered by this crate's licence. Nothing external to license. | Not applicable | +| MP3, Layer III decode | `src/mp3.rs` | ISO/IEC 11172-3 (MPEG-1 audio), ISO/IEC 13818-3 (MPEG-2 audio) | The core MP3 patents are understood to have expired in most jurisdictions, but the position varies by country, so this is not a clean grant. Confirm with counsel. Source: https://www.iso.org/standard/22412.html | No | +| AAC-LC in ADTS, encode and decode | `src/aac.rs`, `src/aac_tables.rs` | ISO/IEC 13818-7 (MPEG-2 AAC), ISO/IEC 14496-3 (MPEG-4 Audio) | Patents are licensed through the Via LA AAC patent pool. Royalties can apply. Source: https://via-la.com/licensing-programs/aac/ | No | +| Opus, Ogg demux and TOC parsing | `src/opus.rs`, `src/opus_tables.rs` | RFC 6716 (Opus codec), RFC 7845 (Ogg encapsulation). IETF | Opus is documented in the RFCs as royalty-free, with IPR declarations in the RFC record. Packet-to-PCM decode is not implemented. Sources: https://www.rfc-editor.org/rfc/rfc6716 and https://www.rfc-editor.org/rfc/rfc7845 | No | +| H.264 (AVC), Annex B, intra and P-skip encode | `src/h264.rs`, `src/h264_intra.rs`, `src/h264_inter.rs`, `src/h264_i4x4.rs`, `src/h264bits.rs`, `src/h264_cavlc_tables.rs` | ITU-T H.264, equivalent to ISO/IEC 14496-10 | Patents are licensed through the Via LA AVC patent pool. Royalties apply above the pool's thresholds, with stated exceptions. **This is the highest-risk row in this crate.** Source: https://via-la.com/licensing-programs/avc/ and https://www.itu.int/rec/T-REC-H.264 | No | +| AV1, keyframe OBU encode | `src/av1_obu.rs`, `src/av1_frame.rs`, `src/av1_intra.rs`, `src/av1_coef.rs`, `src/av1_coef_tables.rs`, `src/av1_ec.rs`, `src/av1_dct.rs` | AV1 Bitstream and Decoding Process Specification. Alliance for Open Media (AOMedia) | AOMedia publishes a royalty-free patent licence for AV1. Its terms include a termination condition if a licensee sues over AV1. A royalty-free licence is not a statement that no patent applies. Source: https://aomedia.org/license/patent-license/ | No | +| MP4 writer | `src/mp4.rs` | ISO/IEC 14496-12 (ISO base media file format), ISO/IEC 14496-14 (MP4 file format) | Container only. Not reviewed. The writer carries H.264 by default, so the H.264 row applies to its output. | No | +| Matroska (MKV) writer | `src/mkv.rs` | Matroska specification. matroska.org | Container only. The licence of the published specification was not verified. The writer carries H.264, so the H.264 row applies to its output. Source: https://www.matroska.org/technical/specs/index.html | No | +| HEIF writer | `src/heif.rs` | ISO/IEC 23008-12 (HEIF). ISO/IEC | Container only. The image coding here is H.264, so the H.264 row applies to its output. Not reviewed beyond that. | No | +| Motion JPEG in AVI | `src/mjpeg.rs` | RIFF AVI, as documented by Microsoft. Frames are JPEG (ITU-T T.81) | AVI is not an ISO standard and its licence was not reviewed. The JPEG frames follow the JPEG row. | No | + +Two formats named in the repository description are **not implemented** in this source tree: +NIfTI and HDF5. This page does not cover them. Do not cite them as supported. + +## What the MIT licence covers + +The crate's own code is licensed under the MIT licence (`LICENSE-MIT`, `license = "MIT"` in +`Cargo.toml`). That licence covers this code only. It grants no rights under any patent that +applies to a format above. A dual `MIT OR Apache-2.0` licence has been discussed but is not in the +repository; that is an owners' decision. + +## Decisions for the owners + +1. **Patent review (H.264, AAC, and the MP4, MKV and HEIF writers that carry H.264).** Counsel must + review each row before the crate is published. Until then the README must not describe the + crate as patent-free. +2. **MP3 and JPEG.** Confirm the expiry dates and jurisdictions with counsel. +3. **Verification of every row.** Read each primary source above and mark the "Verified" column. +4. **Licence.** MIT only, or dual MIT and Apache-2.0 with a `LICENSE-APACHE` file. +5. **Publication.** Whether to publish any encoder that writes H.264 or AAC at all. From 70bd63dae6cd132eac67a658df5e80ba1362e1b5 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 5 Nov 2026 00:02:37 +0000 Subject: [PATCH 09/11] decoders: reject the four inputs found by fuzzing - jpeg: a marker's length field and the APP14 Adobe segment must lie inside the input. Previously the APP14 transform byte was read past the end of a 97-byte input. - flac: the metadata loop stops when the reader is past the end of the input. Past the end the bit reader returns zeros, so the last-block flag never set and the loop never ended. - codec (SLAC): the per-channel capacity is capped at what the input can hold (8 samples per byte). A header frame count of about 4 billion made Vec::with_capacity request about 17 GB before any data was read. Capacity only; valid output is unchanged. - aac: a fill element whose escape byte is zero is rejected instead of underflowing the count. tests/fuzz_regressions.rs embeds each crash input and runs the decoder on a worker thread with a deadline, so a panic, a hang or an abort fails the test. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Ch6Crfubj3FwdxR7ywn9vT --- src/aac.rs | 6 ++++- src/codec.rs | 5 +++- src/flac.rs | 3 +++ src/jpeg.rs | 6 +++++ tests/fuzz_regressions.rs | 50 +++++++++++++++++++++++++++++++++++++++ 5 files changed, 68 insertions(+), 2 deletions(-) create mode 100644 tests/fuzz_regressions.rs diff --git a/src/aac.rs b/src/aac.rs index b0013cf..25bfeda 100644 --- a/src/aac.rs +++ b/src/aac.rs @@ -778,7 +778,11 @@ fn parse_raw_data_block( // fill_element let mut cnt = b.bits(4); if cnt == 15 { - cnt += b.bits(8) - 1; + let esc = b.bits(8); + if esc == 0 { + return Err("AAC: fill element escape of zero".into()); + } + cnt += esc - 1; } for _ in 0..cnt { b.bits(8); diff --git a/src/codec.rs b/src/codec.rs index 85c6108..d32e9f2 100644 --- a/src/codec.rs +++ b/src/codec.rs @@ -406,7 +406,10 @@ pub fn decode(data: &[u8]) -> Result<(Vec, u32, u16, u8), String> { let ch = channels.max(1) as usize; let mut br = BitReader::new(&data[16..]); - let mut chans: Vec> = vec![Vec::with_capacity(frames); ch]; + // Capacity only: a header frame count larger than the input can hold must not drive an + // allocation. The vectors still grow on demand, so valid output is unchanged. + let cap = frames.min(data.len().saturating_mul(8)); + let mut chans: Vec> = vec![Vec::with_capacity(cap); ch]; let mut got = 0; while got < frames { if br.bits(8) != SYNC { diff --git a/src/flac.rs b/src/flac.rs index 17c6d04..8db1f6c 100644 --- a/src/flac.rs +++ b/src/flac.rs @@ -561,6 +561,9 @@ pub fn decode(data: &[u8]) -> Result<(Vec, u32, u16, u32), String> { if last == 1 { break; } + if r.pos > data.len() * 8 { + return Err("FLAC: truncated metadata".into()); + } } if rate == 0 || channels == 0 { return Err("missing STREAMINFO".into()); diff --git a/src/jpeg.rs b/src/jpeg.rs index 1f2ce86..1dbc399 100644 --- a/src/jpeg.rs +++ b/src/jpeg.rs @@ -540,6 +540,9 @@ pub fn decode(data: &[u8]) -> Result { } let marker = data[p + 1]; p += 2; + if p + 2 > data.len() { + return Err("JPEG: truncated marker".into()); + } match marker { 0xD9 => return Err("JPEG: EOI before scan".into()), 0xC0 | 0xC1 => { @@ -690,6 +693,9 @@ pub fn decode(data: &[u8]) -> Result { // APP14 Adobe: the transform byte (0 = CMYK/RGB, 1 = YCbCr, 2 = YCCK) — needed to // colour-convert 4-component (CMYK) JPEGs, which Adobe also stores inverted. let len = u16::from_be_bytes([data[p], data[p + 1]]) as usize; + if p + len > data.len() { + return Err("JPEG: truncated APP14".into()); + } if len >= 14 && &data[p + 2..p + 7] == b"Adobe" { adobe = Some(data[p + 13]); } diff --git a/tests/fuzz_regressions.rs b/tests/fuzz_regressions.rs new file mode 100644 index 0000000..63fd754 --- /dev/null +++ b/tests/fuzz_regressions.rs @@ -0,0 +1,50 @@ +//! Regression tests for the crash, hang and allocation inputs found by the libFuzzer targets. +//! +//! Each input is embedded here so the test does not depend on the gitignored `fuzz/artifacts` +//! directory. Every decoder runs on a worker thread with a deadline: a panic, a hang, or a return +//! after the deadline fails the test. Each input is malformed, so the decoder must return `Err`. + +use std::sync::mpsc; +use std::time::Duration; + +const JPEG_APP14_OOB: &[u8] = &[0xff, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0x0a, 0x49, 0x69, 0x24, 0xff, 0xff, 0x0a]; // 97 bytes, from crash-e157e4d4c381d64c80bc211e28654473028053b5 +const FLAC_METADATA_HANG: &[u8] = &[0x66, 0x4c, 0x61, 0x43, 0x58, 0xb3, 0x58, 0x58, 0x58, 0xb3, 0x0a, 0xb3, 0x0a, 0xb3]; // 14 bytes, from timeout-cfba99684dabd48ecfd12ae5a292121b2b7e0c71 +const SLAC_HUGE_ALLOC: &[u8] = &[0x53, 0x4c, 0x41, 0x31, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0x31, 0xff, 0xff, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0x31]; // 32 bytes, from crash-e9befc0703434daad291ffb90c40106fadec97cd +const AAC_FILL_UNDERFLOW: &[u8] = &[0xff, 0xff, 0xd3, 0x04, 0x01, 0x01, 0xde, 0xde, 0x00, 0x01, 0x01, 0x00, 0x32, 0xde, 0x07, 0x2d, 0x0a, 0x31, 0x00]; // 19 bytes, from crash-a1369e35ba1d55c4c5f404b7745ce080d1d0855b + +/// Run `f` on a worker thread. Fail if it panics or does not return within the deadline. +fn bounded(name: &str, f: impl FnOnce() -> T + Send + 'static) -> T { + let (tx, rx) = mpsc::channel(); + std::thread::spawn(move || { + let _ = tx.send(f()); + }); + match rx.recv_timeout(Duration::from_secs(10)) { + Ok(v) => v, + Err(mpsc::RecvTimeoutError::Disconnected) => panic!("{name}: decoder panicked"), + Err(mpsc::RecvTimeoutError::Timeout) => panic!("{name}: decoder did not return within 10s"), + } +} + +#[test] +fn jpeg_app14_segment_past_end_is_rejected() { + let r = bounded("jpeg", || transcode::jpeg::decode(JPEG_APP14_OOB).map(|_| ())); + assert!(r.is_err(), "expected Err, got {r:?}"); +} + +#[test] +fn flac_unterminated_metadata_is_rejected() { + let r = bounded("flac", || transcode::flac::decode(FLAC_METADATA_HANG).map(|_| ())); + assert!(r.is_err(), "expected Err, got {r:?}"); +} + +#[test] +fn slac_frame_count_does_not_drive_allocation() { + let r = bounded("slac", || transcode::codec::decode(SLAC_HUGE_ALLOC).map(|_| ())); + assert!(r.is_err(), "expected Err, got {r:?}"); +} + +#[test] +fn aac_fill_element_zero_escape_is_rejected() { + let r = bounded("aac", || transcode::aac::decode_pcm(AAC_FILL_UNDERFLOW).map(|_| ())); + assert!(r.is_err(), "expected Err, got {r:?}"); +} From bd9cb777d5a6195bd16156802d71157f67e94530 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 5 Nov 2026 00:17:19 +0000 Subject: [PATCH 10/11] decoders: close the crash, hang and over-allocation paths found by fuzzing Each fix rejects malformed input with an error. Valid input is unchanged. - flac: a unary code read past the end of the input never terminated (the bit reader yields zeros). The loop now stops at the end of the input. - flac: the metadata loop stops when past the end of the input. - flac: a subframe whose wasted-bits count reaches the sample width is an error (it underflowed the width). decode_subframe now returns a Result. - flac: a frame whose channel count differs from STREAMINFO is an error. - slac: each channel block checks the input is not exhausted first. A header with 49163 channels walked frames and blocks long after the input ended. - slac: the per-channel capacity is capped at what the input can hold. - jpeg: every length-bearing marker's segment must lie inside the input before its fields are read. DQT, DHT and DRI bound their reads against the segment or the input. SOF needs seven bytes, SOS needs its component list to fit. - jpeg: a scan header with no component count byte is an error. - jpeg: a scan before any frame header (zero components) is an error. - aac: a fill element whose escape byte is zero is an error, not an underflow. tests/fuzz_regressions.rs embeds each crash, hang or allocation input and runs the decoder on a worker thread with a deadline. A panic, a hang or an abort fails the test. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Ch6Crfubj3FwdxR7ywn9vT --- LICENSE-MIT | 21 ------ src/codec.rs | 5 ++ src/flac.rs | 23 ++++-- src/jpeg.rs | 34 ++++++++- tests/fuzz_regressions.rs | 147 +++++++++++++++++++++++++++++++++++--- 5 files changed, 196 insertions(+), 34 deletions(-) delete mode 100644 LICENSE-MIT diff --git a/LICENSE-MIT b/LICENSE-MIT deleted file mode 100644 index 9fd24a1..0000000 --- a/LICENSE-MIT +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2026 Ptyktos - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/src/codec.rs b/src/codec.rs index d32e9f2..184452d 100644 --- a/src/codec.rs +++ b/src/codec.rs @@ -420,6 +420,11 @@ pub fn decode(data: &[u8]) -> Result<(Vec, u32, u16, u8), String> { return Err("bad blocksize".into()); } for c in 0..ch { + // Every block consumes at least one bit per sample, so a block that starts at the end of + // the input is truncated. Stop before decoding it; valid streams never hit this. + if br.pos >= br.buf.len() * 8 { + return Err("SLAC: truncated frame".into()); + } chans[c].extend_from_slice(&decode_block(&mut br, bs)); } got += bs; diff --git a/src/flac.rs b/src/flac.rs index 8db1f6c..2988833 100644 --- a/src/flac.rs +++ b/src/flac.rs @@ -423,7 +423,12 @@ impl<'a> R<'a> { } fn unary(&mut self) -> u32 { let mut q = 0u32; + // Past the end of the input the reader yields zeros forever. Stop once the read position + // is past the end, so a truncated stream cannot loop; the caller's sync checks reject it. while self.bit() == 0 { + if self.pos > self.d.len() * 8 { + break; + } q += 1; } q @@ -482,10 +487,17 @@ fn decode_residual(r: &mut R, blocksize: usize, order: usize) -> Vec { res } -fn decode_subframe(r: &mut R, blocksize: usize, bps: u32) -> Vec { +fn decode_subframe(r: &mut R, blocksize: usize, bps: u32) -> Result, String> { let _pad = r.bit(); let typ = r.bits(6); - let wasted = if r.bit() == 1 { r.unary() + 1 } else { 0 }; + let wasted = if r.bit() == 1 { + r.unary().saturating_add(1) + } else { + 0 + }; + if wasted >= bps { + return Err("FLAC: wasted bits exceed sample width".into()); + } let b = bps - wasted; let mut s: Vec = if typ == 0 { vec![r.sbits(b); blocksize] @@ -531,7 +543,7 @@ fn decode_subframe(r: &mut R, blocksize: usize, bps: u32) -> Vec { *v <<= wasted; } } - s + Ok(s) } /// Decode a real FLAC stream → (native samples interleaved, rate, channels, bps). @@ -634,7 +646,7 @@ pub fn decode(data: &[u8]) -> Result<(Vec, u32, u16, u32), String> { } // mid/side _ => 0, }; - sub.push(decode_subframe(&mut r, bs, bps + side_bonus)); + sub.push(decode_subframe(&mut r, bs, bps + side_bonus)?); } r.align(); r.bits(16); // CRC-16 @@ -666,6 +678,9 @@ pub fn decode(data: &[u8]) -> Result<(Vec, u32, u16, u32), String> { } _ => sub, }; + if frame.len() != ch { + return Err("FLAC: frame channel count differs from STREAMINFO".into()); + } for c in 0..ch { chans[c].extend_from_slice(&frame[c]); } diff --git a/src/jpeg.rs b/src/jpeg.rs index 1dbc399..28548e3 100644 --- a/src/jpeg.rs +++ b/src/jpeg.rs @@ -543,11 +543,22 @@ pub fn decode(data: &[u8]) -> Result { if p + 2 > data.len() { return Err("JPEG: truncated marker".into()); } + // Every marker except the standalone ones carries a 2-byte length that counts itself. + // The segment must have room for that length and lie inside the input before any field is read. + if !matches!(marker, 0x01 | 0xD0..=0xD9) { + let seg = u16::from_be_bytes([data[p], data[p + 1]]) as usize; + if seg < 2 || p + seg > data.len() { + return Err("JPEG: segment length outside the input".into()); + } + } match marker { 0xD9 => return Err("JPEG: EOI before scan".into()), 0xC0 | 0xC1 => { // SOF0 baseline / SOF1 extended sequential (treat same) let len = u16::from_be_bytes([data[p], data[p + 1]]) as usize; + if len < 7 { + return Err("JPEG: frame header too short".into()); + } let prec = data[p + 2]; if prec != 8 { return Err("JPEG: only 8-bit precision".into()); @@ -603,6 +614,9 @@ pub fn decode(data: &[u8]) -> Result { return Err("JPEG: bad Huffman table id".into()); } // index is 0..3 q += 1; + if q + 16 > end { + return Err("JPEG: truncated DHT counts".into()); + } let mut bits = [0u8; 16]; let mut total = 0usize; for b in &mut bits { @@ -642,6 +656,10 @@ pub fn decode(data: &[u8]) -> Result { q += 1; let mut table = [0u16; 64]; for k in 0..64 { + let need = if prec == 0 { 1 } else { 2 }; + if q + need > end { + return Err("JPEG: truncated DQT".into()); + } if prec == 0 { table[ZIGZAG[k]] = data[q] as u16; q += 1; @@ -656,13 +674,22 @@ pub fn decode(data: &[u8]) -> Result { } 0xDD => { // DRI + if p + 4 > data.len() { + return Err("JPEG: truncated restart interval".into()); + } restart_interval = u16::from_be_bytes([data[p + 2], data[p + 3]]) as usize; p += 4; } 0xDA => { // SOS let len = u16::from_be_bytes([data[p], data[p + 1]]) as usize; - let ns = data[p + 2] as usize; + let ns = *data + .get(p + 2) + .ok_or_else(|| "JPEG: truncated scan header".to_string())? + as usize; + if 3 + 2 * ns > len { + return Err("JPEG: scan header too short for its component count".into()); + } for i in 0..ns { let cs = data[p + 3 + i * 2]; let tdta = data[p + 4 + i * 2]; @@ -724,6 +751,11 @@ fn decode_scan( adobe: Option, basis: &[[f32; 8]; 8], ) -> Result { + // Only the grey (1), YCbCr (3) and CMYK (4) paths exist. Any other count, including a scan + // before any frame header, would index past the component list. + if !matches!(comps.len(), 1 | 3 | 4) { + return Err("JPEG: unsupported component count".into()); + } let hmax = comps.iter().map(|c| c.h).max().unwrap_or(1) as usize; let vmax = comps.iter().map(|c| c.v).max().unwrap_or(1) as usize; let mcus_x = (width + 8 * hmax - 1) / (8 * hmax); diff --git a/tests/fuzz_regressions.rs b/tests/fuzz_regressions.rs index 63fd754..12f3a25 100644 --- a/tests/fuzz_regressions.rs +++ b/tests/fuzz_regressions.rs @@ -7,10 +7,26 @@ use std::sync::mpsc; use std::time::Duration; -const JPEG_APP14_OOB: &[u8] = &[0xff, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0x0a, 0x49, 0x69, 0x24, 0xff, 0xff, 0x0a]; // 97 bytes, from crash-e157e4d4c381d64c80bc211e28654473028053b5 -const FLAC_METADATA_HANG: &[u8] = &[0x66, 0x4c, 0x61, 0x43, 0x58, 0xb3, 0x58, 0x58, 0x58, 0xb3, 0x0a, 0xb3, 0x0a, 0xb3]; // 14 bytes, from timeout-cfba99684dabd48ecfd12ae5a292121b2b7e0c71 -const SLAC_HUGE_ALLOC: &[u8] = &[0x53, 0x4c, 0x41, 0x31, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0x31, 0xff, 0xff, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0x31]; // 32 bytes, from crash-e9befc0703434daad291ffb90c40106fadec97cd -const AAC_FILL_UNDERFLOW: &[u8] = &[0xff, 0xff, 0xd3, 0x04, 0x01, 0x01, 0xde, 0xde, 0x00, 0x01, 0x01, 0x00, 0x32, 0xde, 0x07, 0x2d, 0x0a, 0x31, 0x00]; // 19 bytes, from crash-a1369e35ba1d55c4c5f404b7745ce080d1d0855b +const JPEG_APP14_OOB: &[u8] = &[ + 0xff, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, + 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, + 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, + 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, + 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, + 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0x0a, 0x49, 0x69, 0x24, 0xff, 0xff, + 0x0a, +]; // 97 bytes, from crash-e157e4d4c381d64c80bc211e28654473028053b5 +const FLAC_METADATA_HANG: &[u8] = &[ + 0x66, 0x4c, 0x61, 0x43, 0x58, 0xb3, 0x58, 0x58, 0x58, 0xb3, 0x0a, 0xb3, 0x0a, 0xb3, +]; // 14 bytes, from timeout-cfba99684dabd48ecfd12ae5a292121b2b7e0c71 +const SLAC_HUGE_ALLOC: &[u8] = &[ + 0x53, 0x4c, 0x41, 0x31, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, + 0x31, 0xff, 0xff, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0x31, +]; // 32 bytes, from crash-e9befc0703434daad291ffb90c40106fadec97cd +const AAC_FILL_UNDERFLOW: &[u8] = &[ + 0xff, 0xff, 0xd3, 0x04, 0x01, 0x01, 0xde, 0xde, 0x00, 0x01, 0x01, 0x00, 0x32, 0xde, 0x07, 0x2d, + 0x0a, 0x31, 0x00, +]; // 19 bytes, from crash-a1369e35ba1d55c4c5f404b7745ce080d1d0855b /// Run `f` on a worker thread. Fail if it panics or does not return within the deadline. fn bounded(name: &str, f: impl FnOnce() -> T + Send + 'static) -> T { @@ -25,26 +41,141 @@ fn bounded(name: &str, f: impl FnOnce() -> T + Send + 'static } } +// jpeg: a scan that starts before any frame header (zero components) indexed past the component list. +const JPEG_SCAN_BEFORE_FRAME: &[u8] = &[ + 0xff, 0xd8, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, + 0xff, 0xda, 0x29, 0x00, 0x00, 0xff, +]; // 22 bytes + +// jpeg: a SOS header whose component count runs past its segment; the marker walker read past the end. +const JPEG_SOS_COMPONENTS_PAST_SEGMENT: &[u8] = &[ + 0xff, 0xd8, 0xff, 0x01, 0xff, 0xd8, 0x40, 0x00, 0x00, 0x29, 0xff, 0xda, 0xff, 0x01, 0x40, 0x00, + 0x00, 0x29, 0xff, 0x01, 0x40, 0x00, 0x00, +]; // 23 bytes + // flac: a subframe whose wasted-bits count is at least the sample width underflowed the width. +const FLAC_WASTED_BITS_OVERFLOW: &[u8] = &[ + 0x66, 0x4c, 0x61, 0x43, 0x00, 0x00, 0x00, 0x00, 0xb4, 0x00, 0x00, 0x00, 0xff, 0xfb, 0xbc, 0xf1, + 0xf5, 0xf5, 0x00, 0x00, 0xb9, 0x61, 0x43, 0x00, 0x00, 0x00, 0x00, 0xb4, 0x00, 0x00, 0x00, 0xff, + 0x1f, 0xe0, 0xbc, 0xf1, 0xf5, 0xf7, +]; // 38 bytes + +#[test] +fn jpeg_scan_header_past_its_segment_is_rejected() { + let r = bounded("jpeg-sos", || { + transcode::jpeg::decode(JPEG_SOS_COMPONENTS_PAST_SEGMENT).map(|_| ()) + }); + assert!(r.is_err(), "expected Err, got {r:?}"); +} + +#[test] +fn flac_wasted_bits_at_sample_width_is_rejected() { + let r = bounded("flac-wasted", || { + transcode::flac::decode(FLAC_WASTED_BITS_OVERFLOW).map(|_| ()) + }); + assert!(r.is_err(), "expected Err, got {r:?}"); +} + +// jpeg: a SOS segment of length 2 at the end of the input; reading the component count went one byte past it. +const JPEG_SOS_AT_END: &[u8] = &[0xff, 0xd8, 0xff, 0xda, 0x00, 0x02]; // 6 bytes + // flac: a frame whose channel count differs from STREAMINFO indexed past its channel list. +const FLAC_FRAME_CHANNEL_MISMATCH: &[u8] = &[ + 0x66, 0x4c, 0x61, 0x43, 0x00, 0x00, 0x00, 0x00, 0xb4, 0x00, 0x00, 0x00, 0xff, 0xfb, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, + 0xb4, 0x00, 0x00, 0x00, 0xff, 0xfb, 0x1f, 0xe0, 0xbc, 0xf1, 0xf5, 0xf7, +]; // 156 bytes + +#[test] +fn jpeg_sos_at_end_of_input_is_rejected() { + let r = bounded("jpeg-sos-end", || { + transcode::jpeg::decode(JPEG_SOS_AT_END).map(|_| ()) + }); + assert!(r.is_err(), "expected Err, got {r:?}"); +} + +#[test] +fn flac_frame_channel_mismatch_is_rejected() { + let r = bounded("flac-channels", || { + transcode::flac::decode(FLAC_FRAME_CHANNEL_MISMATCH).map(|_| ()) + }); + assert!(r.is_err(), "expected Err, got {r:?}"); +} + +#[test] +fn jpeg_scan_before_frame_header_is_rejected() { + let r = bounded("jpeg-scan", || { + transcode::jpeg::decode(JPEG_SCAN_BEFORE_FRAME).map(|_| ()) + }); + assert!(r.is_err(), "expected Err, got {r:?}"); +} + #[test] fn jpeg_app14_segment_past_end_is_rejected() { - let r = bounded("jpeg", || transcode::jpeg::decode(JPEG_APP14_OOB).map(|_| ())); + let r = bounded("jpeg", || { + transcode::jpeg::decode(JPEG_APP14_OOB).map(|_| ()) + }); assert!(r.is_err(), "expected Err, got {r:?}"); } +// flac: a unary code read past the end of the input never terminated (the bit reader yields zeros). +const FLAC_UNARY_PAST_END_A: &[u8] = &[ + 0x66, 0x4c, 0x61, 0x43, 0x00, 0x00, 0x00, 0x00, 0xb4, 0x00, 0x00, 0x00, 0xff, 0xfb, 0x66, 0x4c, + 0x61, 0x43, 0xbc, 0xf1, 0xf5, 0xf7, +]; // 22 bytes +const FLAC_UNARY_PAST_END_B: &[u8] = &[ + 0x66, 0x4c, 0x61, 0x43, 0x58, 0xb3, 0x58, 0x58, 0x58, 0xb3, 0x0a, 0xb3, 0x0a, 0xb3, +]; // 14 bytes + +#[test] +fn flac_unary_past_end_is_rejected() { + for (name, data) in [("a", FLAC_UNARY_PAST_END_A), ("b", FLAC_UNARY_PAST_END_B)] { + let r = bounded("flac-unary", move || { + transcode::flac::decode(data).map(|_| ()) + }); + assert!(r.is_err(), "input {name}: expected Err, got {r:?}"); + } +} + #[test] fn flac_unterminated_metadata_is_rejected() { - let r = bounded("flac", || transcode::flac::decode(FLAC_METADATA_HANG).map(|_| ())); + let r = bounded("flac", || { + transcode::flac::decode(FLAC_METADATA_HANG).map(|_| ()) + }); + assert!(r.is_err(), "expected Err, got {r:?}"); +} + +// slac: 49163 channels from the header; decoding walked frames and blocks long after the input ended. +const SLAC_TRUNCATED_CHANNELS: &[u8] = &[ + 0x53, 0x4c, 0x41, 0x31, 0xff, 0xff, 0xff, 0x00, 0x0b, 0xc0, 0xc0, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, + 0xaa, 0xaa, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, +]; // 25 bytes + +#[test] +fn slac_truncated_channel_blocks_are_rejected() { + let r = bounded("slac-channels", || { + transcode::codec::decode(SLAC_TRUNCATED_CHANNELS).map(|_| ()) + }); assert!(r.is_err(), "expected Err, got {r:?}"); } #[test] fn slac_frame_count_does_not_drive_allocation() { - let r = bounded("slac", || transcode::codec::decode(SLAC_HUGE_ALLOC).map(|_| ())); + let r = bounded("slac", || { + transcode::codec::decode(SLAC_HUGE_ALLOC).map(|_| ()) + }); assert!(r.is_err(), "expected Err, got {r:?}"); } #[test] fn aac_fill_element_zero_escape_is_rejected() { - let r = bounded("aac", || transcode::aac::decode_pcm(AAC_FILL_UNDERFLOW).map(|_| ())); + let r = bounded("aac", || { + transcode::aac::decode_pcm(AAC_FILL_UNDERFLOW).map(|_| ()) + }); assert!(r.is_err(), "expected Err, got {r:?}"); } From e376d5f8e1c94578aa08e39b518feb7210c32302 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 5 Nov 2026 00:17:38 +0000 Subject: [PATCH 11/11] licence: Apache-2.0; Unreleased changelog entries - LICENSE is the Apache License, Version 2.0. LICENSE-MIT is removed. - Cargo.toml: license = "Apache-2.0". The version stays 0.1.0. - README, STANDARDS, OPENSSF, SUPPLY-CHAIN and CONTRIBUTING now state Apache-2.0. The release workflow packages LICENSE. - CHANGELOG: Unreleased lists the licence change and the decoder hardening. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Ch6Crfubj3FwdxR7ywn9vT --- .github/workflows/release.yml | 4 +- CHANGELOG.md | 6 + CONTRIBUTING.md | 2 +- Cargo.toml | 2 +- LICENSE | 201 ++++++++++++++++++++++++++++++++++ README.md | 7 +- docs/OPENSSF.md | 6 +- docs/STANDARDS.md | 12 +- docs/SUPPLY-CHAIN.md | 2 +- 9 files changed, 222 insertions(+), 20 deletions(-) create mode 100644 LICENSE diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 7b9e20b..28eec64 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -47,8 +47,8 @@ jobs: run: | mkdir -p dist cp target/release/transcode dist/transcode-linux-x86_64 - cp LICENSE-MIT README.md dist/ - tar -czf "dist/transcode-${TAG_NAME}-linux-x86_64.tar.gz" -C dist transcode-linux-x86_64 LICENSE-MIT README.md + cp LICENSE README.md dist/ + tar -czf "dist/transcode-${TAG_NAME}-linux-x86_64.tar.gz" -C dist transcode-linux-x86_64 LICENSE README.md (cd dist && sha256sum "transcode-${TAG_NAME}-linux-x86_64.tar.gz" > SHA256SUMS) - name: Install cosign uses: sigstore/cosign-installer@6f9f17788090df1f26f669e9d70d6ae9567deba6 # v4.1.2 diff --git a/CHANGELOG.md b/CHANGELOG.md index fb27682..a0a7427 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,8 @@ All notable changes to this project are documented here. The format follows ### Changed +- Licensed under the Apache License, Version 2.0 (`LICENSE`). The MIT licence text and the + `LICENSE-MIT` file are removed. - The binary uses the library's codec modules instead of compiling its own copies. - `Cargo.toml` records the license, repository, readme and keywords, and sets `rust-version = 1.89`. - The library and binary are built with `#![forbid(unsafe_code)]`. @@ -16,6 +18,10 @@ All notable changes to this project are documented here. The format follows - Debug builds no longer panic on the AV1 boolean and coefficient decoding paths. Release output is unchanged. +- Malformed input can no longer make the decoders panic, hang or over-allocate. Four cases found + by fuzzing are fixed: a JPEG APP14 segment read past the end of the input, a FLAC metadata loop + that never ended on truncated input, a SLAC header frame count that requested about 17 GB, and an + AAC fill element with a zero escape byte that underflowed. - `Cargo.lock` now includes the `image-webp` dev-dependency, so `--locked` builds succeed. ## [0.1.0] diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c4d8f4f..4669513 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -67,4 +67,4 @@ Participation is governed by [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md). ## License By contributing you agree that your contribution is licensed under the same terms as the -project (MIT; see [LICENSE-MIT](LICENSE-MIT)). +project (Apache-2.0; see [LICENSE](LICENSE)). diff --git a/Cargo.toml b/Cargo.toml index ba64fb1..c385b12 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,7 +8,7 @@ name = "transcode" version = "0.1.0" edition = "2021" rust-version = "1.89" -license = "MIT" +license = "Apache-2.0" description = "Pure-Rust, std-only audio, image and video codec crate. Decoders and encoders are from scratch; no ffmpeg, libpng, libjpeg or other C libraries." repository = "https://github.com/webfold-ai/transcode" readme = "README.md" diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md index 8f66b88..0bdc9ac 100644 --- a/README.md +++ b/README.md @@ -137,8 +137,7 @@ an external-decoder check where one exists, and a note on patent status for revi ## License -MIT. See [LICENSE-MIT](LICENSE-MIT). +Apache License, Version 2.0. See [LICENSE](LICENSE). -The repository contains only the MIT license text. An earlier version of this README also said -"MIT OR Apache-2.0"; that is not reflected in the repository and is part of the open licensing -decision above. +The licence covers this code only. It grants no rights under any patent that applies to a format +this crate decodes or encodes; see the patent note above. diff --git a/docs/OPENSSF.md b/docs/OPENSSF.md index 8b6ae68..01653f6 100644 --- a/docs/OPENSSF.md +++ b/docs/OPENSSF.md @@ -20,7 +20,7 @@ that a score has been earned. | Dependency-Update-Tool | `dependabot.yml` for cargo and github-actions, weekly | In repo | | Token-Permissions | Read-only top-level `permissions` in every workflow; write only per job | In repo | | Security-Policy | `SECURITY.md` | In repo | -| License | `LICENSE-MIT` matches `license = "MIT"` in Cargo.toml | In repo; licensing decision open (see the README) | +| License | `LICENSE` (Apache-2.0) matches `license = "Apache-2.0"` in Cargo.toml | In repo | | Binary-Artifacts | No binaries are committed. The crate has no build scripts. | Verified by inspection | | Dangerous-Workflow | No `pull_request_target`; untrusted input is not interpolated into `run:` steps | In repo | | Vulnerabilities | `cargo audit` and `cargo deny` in `supply-chain.yml`. Last local run: no advisories | In repo; Verified locally | @@ -48,9 +48,7 @@ been created or recorded here. 1. **CODEOWNERS.** Resolved. `.github/CODEOWNERS` lists `@twn-lloyd @yokoszn`, two human owners, as the owners instructed. The ruleset still needs applying (item 6). No bot accounts are listed. -2. **Licensing.** Cargo.toml and `LICENSE-MIT` say MIT. An earlier README said `MIT OR Apache-2.0`. - Decide, and if dual licensing is wanted, add `LICENSE-APACHE` and change Cargo.toml. **Human** -3. **Patents and standards.** The per-format position is in docs/STANDARDS.md. Every row is still +2. **Patents and standards.** The per-format position is in docs/STANDARDS.md. Every row is still unverified against its primary source, and H.264, AAC, MP3 and the containers that carry them need counsel's review before publication. **Human** 4. **Contacts.** Resolved. SECURITY.md lists security@twn.systems and CODE_OF_CONDUCT.md lists diff --git a/docs/STANDARDS.md b/docs/STANDARDS.md index f53d266..e3d5e4c 100644 --- a/docs/STANDARDS.md +++ b/docs/STANDARDS.md @@ -46,12 +46,11 @@ source has been read. Two formats named in the repository description are **not implemented** in this source tree: NIfTI and HDF5. This page does not cover them. Do not cite them as supported. -## What the MIT licence covers +## What the licence covers -The crate's own code is licensed under the MIT licence (`LICENSE-MIT`, `license = "MIT"` in -`Cargo.toml`). That licence covers this code only. It grants no rights under any patent that -applies to a format above. A dual `MIT OR Apache-2.0` licence has been discussed but is not in the -repository; that is an owners' decision. +The crate's own code is licensed under the Apache License, Version 2.0 (`LICENSE`, +`license = "Apache-2.0"` in `Cargo.toml`). That licence covers this code only. It grants no rights +under any patent that applies to a format above. ## Decisions for the owners @@ -60,5 +59,4 @@ repository; that is an owners' decision. crate as patent-free. 2. **MP3 and JPEG.** Confirm the expiry dates and jurisdictions with counsel. 3. **Verification of every row.** Read each primary source above and mark the "Verified" column. -4. **Licence.** MIT only, or dual MIT and Apache-2.0 with a `LICENSE-APACHE` file. -5. **Publication.** Whether to publish any encoder that writes H.264 or AAC at all. +4. **Publication.** Whether to publish any encoder that writes H.264 or AAC at all. diff --git a/docs/SUPPLY-CHAIN.md b/docs/SUPPLY-CHAIN.md index afdf745..7934cad 100644 --- a/docs/SUPPLY-CHAIN.md +++ b/docs/SUPPLY-CHAIN.md @@ -66,7 +66,7 @@ current when the pin was set. Update it on the same schedule as the others. Releases are produced only by `release.yml`, which runs when a `v*` tag is pushed. A release contains: -- `transcode-vX.Y.Z-linux-x86_64.tar.gz`, the CLI binary with `LICENSE-MIT` and `README.md`, +- `transcode-vX.Y.Z-linux-x86_64.tar.gz`, the CLI binary with `LICENSE` and `README.md`, - `SHA256SUMS`, with a sha256 for the tarball, - `.sigstore.json` bundles from cosign keyless signing (one each for the tarball and `SHA256SUMS`), containing the signature, the certificate and the transparency-log proof,