mirror of
https://github.com/storytold/craft-libs.git
synced 2026-12-01 02:36:54 +01:00
* craft-media: shared codec identifiers, one ByteSource, the testkit The types a codec crate needs to describe a file and configure a decoder, ahead of craft-audio: - `Container`, `CodecId`, `PcmFormat` and `CodecParams` (`id.rs`), always built, with optional serde. - `codec_params()` on `isobmff::Track` and `matroska::Track`, both returning `CodecParams` in the same form; `extradata` follows Matroska's `CodecPrivate`. - One `ByteSource` trait (`source.rs`), with `ReadSeekSource`; `isobmff::ByteSource` and `matroska::ByteSource` are that trait. - craft-media-testkit (`publish = false`): the ffmpeg oracle helpers from craft-media's tests, so the codec crates share one copy. The existing tests prove the refactor; the new types have their own. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * craft-media: APV extradata is the bare record; reseek after a poisoned lock An MP4 apvC track gave CodecParams.extradata with the 4-byte FullBox header in front, where Matroska's V_APV CodecPrivate is the bare APVDecoderConfigurationRecord. ApvConfig::record_bytes serializes the record alone and extradata uses it. ReadSeekSource kept its tracked position after recovering a poisoned lock or a failed seek, so a reader moved by a panic was read from the wrong offset with no error. Both now force a seek on the next read. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * craft-media: MP4 codec params per sample description Track::codec_params always described the first stsd entry, while each sample selects its own through description_index. It now describes the first sample's entry; codec_params_for gives the parameters of any entry, and has_mixed_descriptions says whether one set covers every sample. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * craft-media: test file-backed ByteSources; a File read past i64::MAX is an EOF A File and a ReadSeekSource over a file now have the buffer's test: the same bytes at the same offsets, and UnexpectedEof past the end. The test found that a File read at an offset past i64::MAX failed with the OS's InvalidInput instead of the UnexpectedEof the trait promises; it now reports the end of the source like the other implementations. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * craft-media: Matroska codec params match MP4 for ALAC, DNx and Opus Matroska's codec_params gave Unknown for A_ALAC and for DNxHD/DNxHR stored as V_MS/VFW/FOURCC (AVdn, AVdh), where MP4 gives Alac and Dnxhd; ALAC's extradata is the CodecPrivate, the ALACSpecificConfig MP4's alac box holds. Opus now reports 48 kHz from Matroska as from MP4, whatever rate the muxer declared. ReadSeekSource clears the poison when it recovers the lock, so one panicked read costs one recovery instead of a seek on every later read. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * craft-media: MP4 reports the MPEG audio layer the first frame names An MP4 track with MPEG audio reported CodecId::Mp3 whatever the layer, since mp4a + 0x69/0x6B names none (ffmpeg stores MP2 that way), while Matroska reports Mp1/Mp2/Mp3 from its CodecID. open() now reads the frame header of each such entry's first sample and codec_params() reports the layer it names; without a valid header, QuickTime's .mp2 gives Mp2 and anything else Mp3 as before. CodecConfig::Mp3 is unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
160 lines
6.7 KiB
Rust
160 lines
6.7 KiB
Rust
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
|
//! Oracle-test support for the craft-libs media crates (craft-media, craft-audio, and the video
|
|
//! crate to come): ffmpeg/ffprobe discovery, the skip-or-fail rule, and fixture locations.
|
|
//! ffmpeg is used only as an external fixture generator and oracle (never linked). Test support
|
|
//! only: unpublished, and used as a dev-dependency.
|
|
//!
|
|
//! Tool search order: `CRAFT_MEDIA_FFMPEG` / `CRAFT_MEDIA_FFPROBE` (an explicit path; a wrong
|
|
//! path fails the test), then `PATH`, then well-known install directories. A missing tool, a
|
|
//! failed fixture generator or a failed ffprobe run prints `SKIPPED` and the test passes, unless
|
|
//! `CRAFT_MEDIA_REQUIRE_ORACLES=1` is set: then each of these fails the test.
|
|
//! Fixtures are generated into `$CRAFT_MEDIA_FIXTURES_DIR` or `<workspace>/target/fixtures`, one
|
|
//! directory per crate or format, and never committed.
|
|
//!
|
|
//! Failing loudly is what a test helper is for: a wrong `CRAFT_MEDIA_*` setting or an unwritable
|
|
//! fixture directory panics, which fails the test that asked.
|
|
|
|
use std::path::{Path, PathBuf};
|
|
use std::process::Command;
|
|
use std::sync::OnceLock;
|
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
|
|
|
const REQUIRE_ENV: &str = "CRAFT_MEDIA_REQUIRE_ORACLES";
|
|
|
|
const KNOWN_DIRS: &[&str] = &[
|
|
"/opt/homebrew/bin",
|
|
"/usr/local/bin",
|
|
"/usr/bin",
|
|
"/opt/local/bin",
|
|
"/snap/bin",
|
|
r"C:\ffmpeg\bin",
|
|
r"C:\Program Files\ffmpeg\bin",
|
|
r"C:\ProgramData\chocolatey\bin",
|
|
];
|
|
|
|
fn env_var(name: &str) -> String {
|
|
format!("CRAFT_MEDIA_{}", name.to_ascii_uppercase())
|
|
}
|
|
|
|
#[allow(clippy::panic)]
|
|
fn find_tool(name: &str) -> Option<PathBuf> {
|
|
if let Some(e) = std::env::var_os(env_var(name)).filter(|e| !e.is_empty()) {
|
|
let p = PathBuf::from(e);
|
|
assert!(p.is_file(), "{} is set but `{}` is not a file", env_var(name), p.display());
|
|
return Some(p);
|
|
}
|
|
let names = if cfg!(windows) { [format!("{name}.exe"), name.to_string()] } else { [name.to_string(), format!("{name}.exe")] };
|
|
let path_dirs = std::env::var_os("PATH").map(|p| std::env::split_paths(&p).collect::<Vec<_>>()).unwrap_or_default();
|
|
let dirs = path_dirs.into_iter().chain(KNOWN_DIRS.iter().map(PathBuf::from));
|
|
for dir in dirs {
|
|
for n in &names {
|
|
let p = dir.join(n);
|
|
if p.is_file() {
|
|
return Some(p);
|
|
}
|
|
}
|
|
}
|
|
None
|
|
}
|
|
|
|
/// Find a tool silently (cached for the process for ffmpeg and ffprobe).
|
|
pub fn tool(name: &str) -> Option<PathBuf> {
|
|
static FFMPEG: OnceLock<Option<PathBuf>> = OnceLock::new();
|
|
static FFPROBE: OnceLock<Option<PathBuf>> = OnceLock::new();
|
|
match name {
|
|
"ffmpeg" => FFMPEG.get_or_init(|| find_tool("ffmpeg")).clone(),
|
|
"ffprobe" => FFPROBE.get_or_init(|| find_tool("ffprobe")).clone(),
|
|
_ => find_tool(name),
|
|
}
|
|
}
|
|
|
|
pub fn oracles_required() -> bool {
|
|
std::env::var(REQUIRE_ENV).is_ok_and(|v| matches!(v.trim().to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "on"))
|
|
}
|
|
|
|
/// Give up on an oracle check: print `SKIPPED` and return `None`, or fail when oracles are
|
|
/// required.
|
|
pub fn skip<T>(reason: &str) -> Option<T> {
|
|
skip_with(oracles_required(), reason)
|
|
}
|
|
|
|
#[allow(clippy::panic)]
|
|
fn skip_with<T>(required: bool, reason: &str) -> Option<T> {
|
|
assert!(!required, "oracle: {reason}, and {REQUIRE_ENV}=1 forbids skipping oracle tests");
|
|
eprintln!("SKIPPED (oracle): {reason}");
|
|
None
|
|
}
|
|
|
|
/// Run a fixture generator writing `tmp`, then rename it to `out`. A generator that cannot start
|
|
/// or fails skips (see [`skip`]); `required` is explicit so tests can set it without touching
|
|
/// the process environment.
|
|
pub fn run_generator(cmd: &mut Command, tmp: &Path, out: &Path, required: bool) -> Option<PathBuf> {
|
|
let reason = match cmd.output() {
|
|
Ok(o) if o.status.success() => match std::fs::rename(tmp, out) {
|
|
Ok(()) => return Some(out.to_path_buf()),
|
|
Err(e) => format!("could not move {} into place: {e}", tmp.display()),
|
|
},
|
|
Ok(o) => format!("generator failed for {} ({}): {}", out.display(), o.status, String::from_utf8_lossy(&o.stderr).trim()),
|
|
Err(e) => format!("could not start generator for {}: {e}", out.display()),
|
|
};
|
|
let _ = std::fs::remove_file(tmp);
|
|
skip_with(required, &format!("{reason} (encoder unavailable?)"))
|
|
}
|
|
|
|
fn tool_or_skip(name: &str) -> Option<PathBuf> {
|
|
tool(name).or_else(|| skip(&format!("{name} not found (set {} or put {name} on PATH)", env_var(name))))
|
|
}
|
|
|
|
/// ffmpeg, or `None` after printing `SKIPPED` (a failure with `CRAFT_MEDIA_REQUIRE_ORACLES=1`).
|
|
pub fn ffmpeg() -> Option<PathBuf> {
|
|
tool_or_skip("ffmpeg")
|
|
}
|
|
|
|
/// ffprobe, or `None` after printing `SKIPPED` (a failure with `CRAFT_MEDIA_REQUIRE_ORACLES=1`).
|
|
pub fn ffprobe() -> Option<PathBuf> {
|
|
tool_or_skip("ffprobe")
|
|
}
|
|
|
|
/// `$CRAFT_MEDIA_FIXTURES_DIR/<name>` or `<workspace>/target/fixtures/<name>`, created if missing.
|
|
#[allow(clippy::unwrap_used)]
|
|
pub fn fixture_subdir(name: &str) -> PathBuf {
|
|
let d = match std::env::var_os("CRAFT_MEDIA_FIXTURES_DIR").filter(|v| !v.is_empty()) {
|
|
Some(d) => PathBuf::from(d),
|
|
None => {
|
|
let here = Path::new(env!("CARGO_MANIFEST_DIR"));
|
|
let root = here.parent().and_then(Path::parent).unwrap_or(here);
|
|
root.join("target").join("fixtures")
|
|
}
|
|
}
|
|
.join(name);
|
|
std::fs::create_dir_all(&d).unwrap();
|
|
d
|
|
}
|
|
|
|
/// A temporary sibling of `out` that no other thread or process will pick; the extension is kept
|
|
/// because ffmpeg chooses the muxer from it.
|
|
pub fn temp_path(out: &Path) -> PathBuf {
|
|
static N: AtomicUsize = AtomicUsize::new(0);
|
|
let tid = format!("{:?}", std::thread::current().id()).replace(|c: char| !c.is_ascii_alphanumeric(), "");
|
|
let n = N.fetch_add(1, Ordering::Relaxed);
|
|
let stem = out.file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default();
|
|
let name = match out.extension() {
|
|
Some(ext) => format!("{stem}.tmp-{}-{tid}-{n}.{}", std::process::id(), ext.to_string_lossy()),
|
|
None => format!("{stem}.tmp-{}-{tid}-{n}", std::process::id()),
|
|
};
|
|
out.with_file_name(name)
|
|
}
|
|
|
|
/// Run a fixture generator and print `FIXTURE <made|cached|skipped> <name>`.
|
|
pub fn generate_and_report<T>(name: &str, outputs: &[PathBuf], generate: impl FnOnce() -> Option<T>) -> Option<T> {
|
|
let existed = !outputs.is_empty() && outputs.iter().all(|p| std::fs::metadata(p).is_ok_and(|m| m.len() > 0));
|
|
let r = generate();
|
|
let status = match (&r, existed) {
|
|
(None, _) => "skipped",
|
|
(Some(_), true) => "cached",
|
|
(Some(_), false) => "made",
|
|
};
|
|
println!("FIXTURE {status} {name}");
|
|
r
|
|
}
|