Merge main into feat/import-photocraft

This commit is contained in:
dotCooCoo committed 2026-11-19 19:23:32 -08:00
commit a542423f5e
17 files changed
+2737 -1945

No files matched your search

Generated
+72 -15
View File
@@ -1226,9 +1226,9 @@ dependencies = [
[[package]]
name = "craft-audio"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87"
source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3"
dependencies = [
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87)",
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)",
"thiserror 2.0.21",
]
@@ -1280,6 +1280,14 @@ name = "craft-codepage"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87"
[[package]]
name = "craft-color"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3"
dependencies = [
"serde",
]
[[package]]
name = "craft-doc"
version = "0.1.0"
@@ -1349,6 +1357,17 @@ name = "craft-fonts-build"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87"
[[package]]
name = "craft-frame"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3"
dependencies = [
"craft-color",
"craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)",
"rayon",
"serde",
]
[[package]]
name = "craft-gif"
version = "0.1.0"
@@ -1389,6 +1408,14 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-jsonrpc"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bc186ca719958fcce3b6ee24794277eabed14609#bc186ca719958fcce3b6ee24794277eabed14609"
dependencies = [
"serde_json",
]
[[package]]
name = "craft-lottie"
version = "0.1.0"
@@ -1407,7 +1434,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=30596f73c5ef851ba3dad9
[[package]]
name = "craft-media"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87"
source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3"
dependencies = [
"thiserror 2.0.21",
]
@@ -1429,6 +1456,20 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-media-source"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3"
dependencies = [
"craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)",
"craft-color",
"craft-frame",
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)",
"craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)",
"serde",
"thiserror 2.0.21",
]
[[package]]
name = "craft-mesh"
version = "0.1.0"
@@ -1484,7 +1525,7 @@ dependencies = [
[[package]]
name = "craft-psd"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=fa4741d0bbba8da303dd1bb1a93cbcb78e7747a0#fa4741d0bbba8da303dd1bb1a93cbcb78e7747a0"
source = "git+https://github.com/storytold/craft-libs?rev=08da5e1486ee640de1d2cccd8fe8dd32b1d3b62c#08da5e1486ee640de1d2cccd8fe8dd32b1d3b62c"
dependencies = [
"encoding_rs",
"flate2",
@@ -1520,9 +1561,9 @@ dependencies = [
[[package]]
name = "craft-svg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=77686f24fe8665c21369f1b593f4d65a973e2a45#77686f24fe8665c21369f1b593f4d65a973e2a45"
source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3"
dependencies = [
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=77686f24fe8665c21369f1b593f4d65a973e2a45)",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)",
"flate2",
"kurbo",
"quick-xml 0.41.0",
@@ -1558,6 +1599,15 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-time"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3"
dependencies = [
"serde",
"thiserror 2.0.21",
]
[[package]]
name = "craft-time"
version = "0.1.0"
@@ -1665,9 +1715,10 @@ dependencies = [
[[package]]
name = "craft-video"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87"
source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3"
dependencies = [
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87)",
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)",
"rav1e",
"rayon",
"thiserror 2.0.21",
]
@@ -1695,7 +1746,7 @@ dependencies = [
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=57288edafdc45552e30481cc649021de446abfa0#57288edafdc45552e30481cc649021de446abfa0"
source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3"
dependencies = [
"quick-xml 0.41.0",
"serde",
@@ -1705,7 +1756,7 @@ dependencies = [
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=77686f24fe8665c21369f1b593f4d65a973e2a45#77686f24fe8665c21369f1b593f4d65a973e2a45"
source = "git+https://github.com/storytold/craft-libs?rev=57288edafdc45552e30481cc649021de446abfa0#57288edafdc45552e30481cc649021de446abfa0"
dependencies = [
"quick-xml 0.41.0",
"serde",
@@ -2011,6 +2062,7 @@ dependencies = [
name = "effectcraft-automation"
version = "0.24.1"
dependencies = [
"craft-jsonrpc",
"craft-mime",
"effectcraft-engine",
"effectcraft-host",
@@ -2114,11 +2166,11 @@ dependencies = [
name = "effectcraft-export"
version = "0.24.1"
dependencies = [
"craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87)",
"craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)",
"craft-exr",
"craft-gif",
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87)",
"craft-video 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87)",
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)",
"craft-video 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)",
"effectcraft-color",
"effectcraft-effects",
"effectcraft-keyframe",
@@ -2280,13 +2332,18 @@ name = "effectcraft-media"
version = "0.24.1"
dependencies = [
"craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=30596f73c5ef851ba3dad9cf145669f391e2eb0d)",
"craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87)",
"craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)",
"craft-color",
"craft-doc",
"craft-docpath",
"craft-dpx 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87)",
"craft-exr",
"craft-frame",
"craft-gif",
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87)",
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)",
"craft-media-source",
"craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)",
"craft-video 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)",
"craft-webp",
"effectcraft-color",
"effectcraft-effects",
+11 -6
View File
@@ -15,14 +15,15 @@ craft-timeline = { git = "https://github.com/storytold/craft-libs", rev = "0d6dd
craft-mime = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "808730f49b9637b7909fe2ae56f9d63fdb100cae", version = "=0.1.0", default-features = false, features = ["read"] }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
craft-jsonrpc = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "bc186ca719958fcce3b6ee24794277eabed14609" }
craft-quit = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
craft-ecproj-format = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
craft-dpx = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
craft-ps = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "808730f49b9637b7909fe2ae56f9d63fdb100cae", default-features = false, features = ["read"] }
craft-exr = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3b8e426a260695af840a2cd79a064d40778f939e" }
craft-gif = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "fa4741d0bbba8da303dd1bb1a93cbcb78e7747a0" }
craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "77686f24fe8665c21369f1b593f4d65a973e2a45" }
craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "08da5e1486ee640de1d2cccd8fe8dd32b1d3b62c" }
craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3" }
craft-webp = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
craft-lottie = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" }
craft-mesh = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87", default-features = false, features = ["stl", "obj", "gltf", "fbx"] }
@@ -94,10 +95,14 @@ image = { version = "0.25", default-features = false, features = ["png", "jpeg"]
same-file = "1.0"
tempfile = "3.27"
# codecs + containers shared by the Craft apps (crates/media, crates/export); keep all three on one rev.
craft-media = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87", default-features = false, features = ["isobmff", "matroska"] }
craft-audio = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87", default-features = false, features = ["aac-decode", "aac-encode", "opus-decode", "opus-encode"] }
craft-video = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87", features = ["h264-encode", "prores", "hevc-encode", "vp9-encode", "av1", "threads"] }
# codecs + containers shared by the Craft apps (crates/media, crates/export); keep all in sync.
craft-media = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3", default-features = false, features = ["isobmff", "matroska"] }
craft-media-source = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3" }
craft-frame = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3" }
craft-color = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3" }
craft-time = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3" }
craft-audio = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3", default-features = false, features = ["aac-decode", "aac-encode", "alac-decode", "opus-decode", "opus-encode", "ac3-decode", "mp3-decode", "mpa-decode"] }
craft-video = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3", features = ["h264-decode", "h264-encode", "prores", "hevc-encode", "vp9-encode", "av1", "threads"] }
# footage decoding: FilmCraft's pure-Rust crates, pinned to a revision (plan/adr/0001).
# Only `crates/media`, `crates/export` and `crates/interchange` may depend on these.
+1
View File
@@ -10,6 +10,7 @@ rust-version.workspace = true
workspace = true
[dependencies]
craft-jsonrpc = { workspace = true }
craft-mime = { workspace = true }
effectcraft-engine = { workspace = true }
serde_json = { workspace = true }
+11 -27
View File
@@ -17,7 +17,6 @@ const INSTRUCTIONS: &str = "EffectCraft is an After Effects-class motion graphic
// JSON-RPC error codes.
const PARSE_ERROR: i64 = -32700;
const INVALID_REQUEST: i64 = -32600;
const METHOD_NOT_FOUND: i64 = -32601;
const INVALID_PARAMS: i64 = -32602;
const INTERNAL_ERROR: i64 = -32603;
@@ -61,31 +60,16 @@ impl McpServer {
/// Handle one decoded message (request, notification or batch); `None` when no reply is due.
pub fn handle(&mut self, msg: &Value) -> Option<Value> {
if let Value::Array(batch) = msg {
if batch.is_empty() {
return Some(error(Value::Null, INVALID_REQUEST, "empty batch"));
}
let out: Vec<Value> = batch.iter().filter_map(|m| self.handle(m)).collect();
return (!out.is_empty()).then_some(Value::Array(out));
}
let Some(method) = msg.get("method").and_then(Value::as_str) else {
// A response from the client (we send no requests) or garbage.
return msg
.get("id")
.filter(|_| msg.get("result").is_none() && msg.get("error").is_none())
.map(|id| error(id.clone(), INVALID_REQUEST, "missing `method`"));
};
let Some(id) = msg.get("id").cloned() else {
return None; // notification (notifications/initialized, notifications/cancelled, ...)
};
let params = msg.get("params").cloned().unwrap_or(json!({}));
Some(match self.request(method, &params) {
Ok(mut result) => {
modern_result_fields(method, &params, &mut result);
json!({"jsonrpc": "2.0", "id": id, "result": result})
}
Err((code, m)) => error(id, code, &m),
})
craft_jsonrpc::process_legacy(
msg,
|req| {
let params = req.params.cloned().unwrap_or_else(|| json!({}));
let mut result = self.request(req.method, &params).map_err(|(code, message)| craft_jsonrpc::RpcError::new(code, message))?;
modern_result_fields(req.method, &params, &mut result);
Ok(result)
},
|_| {},
)
}
/// Handle one line of input; `None` when no reply is due.
@@ -304,5 +288,5 @@ pub(crate) fn modern_result_fields(method: &str, params: &Value, result: &mut Va
}
fn error(id: Value, code: i64, message: &str) -> Value {
json!({"jsonrpc": "2.0", "id": id, "error": {"code": code, "message": message}})
craft_jsonrpc::error_response(id, craft_jsonrpc::RpcError::new(code, message))
}
+6 -1
View File
@@ -28,8 +28,13 @@ craft-dpx = { workspace = true }
craft-exr = { workspace = true, features = ["decode"] }
craft-gif = { workspace = true, features = ["frames"] }
craft-webp = { workspace = true, features = ["frames"] }
craft-audio = { workspace = true, features = ["aac-decode"] }
craft-audio = { workspace = true, features = ["aac-decode", "alac-decode", "opus-decode", "ac3-decode", "mp3-decode", "mpa-decode"] }
craft-color = { workspace = true }
craft-frame = { workspace = true }
craft-media = { workspace = true, features = ["mpegts"] }
craft-media-source = { workspace = true }
craft-time = { workspace = true }
craft-video = { workspace = true, features = ["h264-decode", "threads"] }
filmcraft-frame = { workspace = true }
filmcraft-color = { workspace = true }
filmcraft-time = { workspace = true }
+98 -61
View File
@@ -78,15 +78,88 @@ impl AlphaOp {
}
}
/// Borrowed frame view so both `craft_frame::VideoFrame` and `filmcraft_frame::VideoFrame`
/// convert through the same pixel pipeline without copying.
pub(crate) enum PixelsRef<'a> {
Rgba8(&'a [u8]),
RgbaF32(&'a [f32]),
Yuv8 { planes: [&'a [u8]; 3], chroma: Chroma, alpha: Option<&'a [u8]> },
Yuv16 { planes: [&'a [u16]; 3], chroma: Chroma, bits: u32, alpha: Option<&'a [u16]> },
}
pub(crate) struct FrameView<'a> {
pub(crate) width: u32,
pub(crate) height: u32,
pub(crate) data: PixelsRef<'a>,
pub(crate) matrix: Matrix,
pub(crate) range: Range,
}
impl<'a> From<&'a VideoFrame> for FrameView<'a> {
fn from(f: &'a VideoFrame) -> Self {
let data = match &f.data {
PixelData::Rgba8(d) => PixelsRef::Rgba8(d),
PixelData::RgbaF32(d) => PixelsRef::RgbaF32(d),
PixelData::Yuv8 { planes, chroma, alpha } => {
PixelsRef::Yuv8 { planes: [&planes[0], &planes[1], &planes[2]], chroma: *chroma, alpha: alpha.as_deref().map(|a| &a[..]) }
}
PixelData::Yuv16 { planes, chroma, bits, alpha } => {
PixelsRef::Yuv16 { planes: [&planes[0], &planes[1], &planes[2]], chroma: *chroma, bits: *bits, alpha: alpha.as_deref().map(|a| &a[..]) }
}
};
FrameView { width: f.width, height: f.height, data, matrix: f.color.matrix, range: f.color.range }
}
}
impl<'a> From<&'a craft_frame::VideoFrame> for FrameView<'a> {
fn from(f: &'a craft_frame::VideoFrame) -> Self {
let chroma = |c: craft_frame::Chroma| match c {
craft_frame::Chroma::C420 => Chroma::C420,
craft_frame::Chroma::C422 => Chroma::C422,
craft_frame::Chroma::C444 => Chroma::C444,
};
let data = match &f.data {
craft_frame::PixelData::Rgba8(d) => PixelsRef::Rgba8(d),
craft_frame::PixelData::RgbaF32(d) => PixelsRef::RgbaF32(d),
craft_frame::PixelData::Yuv8 { planes, chroma: c, alpha } => {
PixelsRef::Yuv8 { planes: [&planes[0], &planes[1], &planes[2]], chroma: chroma(*c), alpha: alpha.as_deref().map(|a| &a[..]) }
}
craft_frame::PixelData::Yuv16 { planes, chroma: c, bits, alpha } => {
PixelsRef::Yuv16 { planes: [&planes[0], &planes[1], &planes[2]], chroma: chroma(*c), bits: *bits, alpha: alpha.as_deref().map(|a| &a[..]) }
}
};
let matrix = match f.color.matrix {
craft_color::Matrix::Bt601 => Matrix::Bt601,
craft_color::Matrix::Bt709 => Matrix::Bt709,
craft_color::Matrix::Bt2020Ncl => Matrix::Bt2020Ncl,
};
let range = match f.color.range {
craft_color::Range::Limited => Range::Limited,
craft_color::Range::Full => Range::Full,
};
FrameView { width: f.width, height: f.height, data, matrix, range }
}
}
impl<'a> From<&'a crate::stream::DecodedFrame> for FrameView<'a> {
fn from(f: &'a crate::stream::DecodedFrame) -> Self {
match f {
crate::stream::DecodedFrame::Craft(frame) => FrameView::from(&**frame),
crate::stream::DecodedFrame::Film(frame) => FrameView::from(&**frame),
}
}
}
/// Convert a FilmCraft frame to an [`Image`].
#[cfg(test)]
pub(crate) fn frame_to_image(f: &VideoFrame, op: AlphaOp) -> Image {
frame_to_image_in(f, op, Vec::new())
}
/// Convert a FilmCraft frame to an [`Image`], reusing `buf`'s allocation when it is large enough
/// Convert a decoded frame to an [`Image`], reusing `buf`'s allocation when it is large enough
/// (every pixel is overwritten, so a recycled frame's contents do not matter).
pub(crate) fn frame_to_image_in(f: &VideoFrame, op: AlphaOp, mut buf: Vec<Px>) -> Image {
pub(crate) fn frame_to_image_in<'a>(f: impl Into<FrameView<'a>>, op: AlphaOp, mut buf: Vec<Px>) -> Image {
let f = f.into();
let (w, h) = (f.width as usize, f.height as usize);
if buf.len() != w * h {
buf = vec![[0.0; 4]; w * h];
@@ -95,9 +168,9 @@ pub(crate) fn frame_to_image_in(f: &VideoFrame, op: AlphaOp, mut buf: Vec<Px>) -
if w == 0 || h == 0 {
return img;
}
match &f.data {
PixelData::Rgba8(d) => convert_rgba8(&mut img.data, d, w, op, |p| p),
PixelData::RgbaF32(d) => {
match f.data {
PixelsRef::Rgba8(d) => convert_rgba8(&mut img.data, d, w, op, |p| p),
PixelsRef::RgbaF32(d) => {
// linear premultiplied → encoded premultiplied
img.data.par_chunks_mut(w).enumerate().for_each(|(y, row)| {
let src = &d[y * w * 4..(y + 1) * w * 4];
@@ -109,39 +182,15 @@ pub(crate) fn frame_to_image_in(f: &VideoFrame, op: AlphaOp, mut buf: Vec<Px>) -
}
});
}
PixelData::Yuv8 { planes, chroma, alpha } => {
let yuv = Yuv::new(f.color.matrix, f.color.range, 8);
PixelsRef::Yuv8 { planes, chroma, alpha } => {
let yuv = Yuv::new(f.matrix, f.range, 8);
let amax = 255.0;
convert_yuv(
&mut img.data,
YuvSource {
size: (w, h),
chroma: *chroma,
planes: [&planes[0][..], &planes[1][..], &planes[2][..]],
alpha: alpha.as_deref().map(|a| &a[..]),
amax,
},
&yuv,
op,
|p| p,
);
convert_yuv(&mut img.data, YuvSource { size: (w, h), chroma, planes, alpha, amax }, &yuv, op, |p| p);
}
PixelData::Yuv16 { planes, chroma, bits, alpha } => {
let yuv = Yuv::new(f.color.matrix, f.color.range, *bits);
let amax = ((1u32 << *bits) - 1) as f32;
convert_yuv(
&mut img.data,
YuvSource {
size: (w, h),
chroma: *chroma,
planes: [&planes[0][..], &planes[1][..], &planes[2][..]],
alpha: alpha.as_deref().map(|a| &a[..]),
amax,
},
&yuv,
op,
|p| p,
);
PixelsRef::Yuv16 { planes, chroma, bits, alpha } => {
let yuv = Yuv::new(f.matrix, f.range, bits);
let amax = ((1u32 << bits) - 1) as f32;
convert_yuv(&mut img.data, YuvSource { size: (w, h), chroma, planes, alpha, amax }, &yuv, op, |p| p);
}
}
img
@@ -151,26 +200,17 @@ pub(crate) fn frame_to_image_in(f: &VideoFrame, op: AlphaOp, mut buf: Vec<Px>) -
/// ([`effectcraft_raster::quantize_px`]), kept as the 8-bit levels: expanded with
/// [`effectcraft_raster::expand_u8`] it is that quantised image to the bit, in a quarter of
/// the memory. `None` for frames with more than 8 bits (10/12-bit Y'CbCr, float).
pub(crate) fn frame_to_rgba8(f: &VideoFrame, op: AlphaOp) -> Option<Frame8> {
pub(crate) fn frame_to_rgba8<'a>(f: impl Into<FrameView<'a>>, op: AlphaOp) -> Option<Frame8> {
let f = f.into();
let (w, h) = (f.width as usize, f.height as usize);
let mut px = vec![[0u8; 4]; w * h];
if w > 0 && h > 0 {
match &f.data {
PixelData::Rgba8(d) => convert_rgba8(&mut px, d, w, op, quantize_px_u8),
PixelData::Yuv8 { planes, chroma, alpha } => convert_yuv(
&mut px,
YuvSource {
size: (w, h),
chroma: *chroma,
planes: [&planes[0][..], &planes[1][..], &planes[2][..]],
alpha: alpha.as_deref().map(|a| &a[..]),
amax: 255.0,
},
&Yuv::new(f.color.matrix, f.color.range, 8),
op,
quantize_px_u8,
),
PixelData::RgbaF32(_) | PixelData::Yuv16 { .. } => return None,
match f.data {
PixelsRef::Rgba8(d) => convert_rgba8(&mut px, d, w, op, quantize_px_u8),
PixelsRef::Yuv8 { planes, chroma, alpha } => {
convert_yuv(&mut px, YuvSource { size: (w, h), chroma, planes, alpha, amax: 255.0 }, &Yuv::new(f.matrix, f.range, 8), op, quantize_px_u8)
}
PixelsRef::RgbaF32(_) | PixelsRef::Yuv16 { .. } => return None,
}
}
Some(Frame8 { width: f.width, height: f.height, rgba: px.into_flattened() })
@@ -219,18 +259,15 @@ pub(crate) fn turned(img: Image, turn: image::metadata::Orientation) -> Image {
/// pixels get), then resampled the rest of the way. Conversion is linear until it clips, so
/// this is the RGB box filter `resample` starts with, except in blocks where some colours clip.
/// `None` for other frames.
pub(crate) fn frame_to_image_scaled(f: &VideoFrame, w: u32, h: u32) -> Option<Image> {
pub(crate) fn frame_to_image_scaled<'a>(f: impl Into<FrameView<'a>>, w: u32, h: u32) -> Option<Image> {
let f = f.into();
let (fw, fh) = (f.width as usize, f.height as usize);
if w == 0 || h == 0 || fw % 2 != 0 || fh % 2 != 0 || (w as usize).saturating_mul(2) > fw || (h as usize).saturating_mul(2) > fh {
return None;
}
let half = match &f.data {
PixelData::Yuv8 { planes, chroma: Chroma::C420, alpha: None } => {
half_420(fw, fh, [&planes[0][..], &planes[1][..], &planes[2][..]], &Yuv::new(f.color.matrix, f.color.range, 8))?
}
PixelData::Yuv16 { planes, chroma: Chroma::C420, bits, alpha: None } => {
half_420(fw, fh, [&planes[0][..], &planes[1][..], &planes[2][..]], &Yuv::new(f.color.matrix, f.color.range, *bits))?
}
let half = match f.data {
PixelsRef::Yuv8 { planes, chroma: Chroma::C420, alpha: None } => half_420(fw, fh, planes, &Yuv::new(f.matrix, f.range, 8))?,
PixelsRef::Yuv16 { planes, chroma: Chroma::C420, bits, alpha: None } => half_420(fw, fh, planes, &Yuv::new(f.matrix, f.range, bits))?,
_ => return None,
};
Some(if (half.width, half.height) == (w, h) { half } else { effectcraft_raster::resample(&half, w, h) })
+13
View File
@@ -27,6 +27,7 @@ mod exr_read;
mod gif_anim;
mod layered;
mod localize;
mod mp4_h264;
mod pcraft;
pub use layered::vector_doc;
mod pool;
@@ -69,6 +70,18 @@ impl From<filmcraft_media::MediaError> for MediaError {
}
}
impl From<craft_media_source::MediaError> for MediaError {
fn from(e: craft_media_source::MediaError) -> Self {
use craft_media_source::MediaError as C;
match e {
C::Unsupported(s) => MediaError::Unsupported(s),
C::Io(s) | C::Offline(s) => MediaError::Io(s),
C::Cancelled => MediaError::Cancelled,
other => MediaError::Decode(other.to_string()),
}
}
}
/// File extensions recognised as stills.
pub const STILL_EXTENSIONS: &[&str] =
&["png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp", "exr", "tga", "hdr", "psd", "psb", "pcraft", "svg", "pdf", "ai", "eps", "vectorcraft"];
+597
View File
@@ -0,0 +1,597 @@
//! Software MP4/MOV H.264 route backed by `craft-media`, `craft-video`, `craft-audio`, and
//! `craft-media-source`.
//!
//! Preserves sync-sample backward seek, B-frame reordering, cooperative cancellation, VUI +
//! container colour resolution, draft mode for reduced-resolution playback, and bounded worker
//! threads.
use std::sync::{Arc, Mutex};
use craft_audio::{AudioBuffer, TrackDecoder as AudioTrackDecoder};
use craft_color::{ColorInfo, Matrix, Primaries, Range, Transfer};
use craft_frame::{Chroma, PixelData, VideoFrame};
use craft_media::isobmff::{self, Mp4File, Track, TrackKind};
use craft_media::{ByteSource, CodecId};
use craft_media_source::{
AudioStreamInfo, FrameRequest, MAX_AUDIO_STREAMS, MediaError, MediaInfo, MediaKind, MediaSource, Result, SharedBytes, SharedSource, VideoStreamInfo,
};
use craft_time::{FrameRate, Tick};
use craft_video::frame::{ColorFamily, ColorTags, Plane, Samples, Subsampling, VideoFrame as DecodedVideoFrame};
use craft_video::{TrackDecoder, TrackDecoderOptions};
/// Maximum worker threads per `TrackDecoder` instance.
const MAX_WORKERS: usize = 8;
/// Maximum decoded frames retained in the per-source GOP window cache.
const MAX_CACHED_FRAMES: usize = 32;
/// Maximum audio lookahead packets inspected when initializing `craft_audio::TrackDecoder`.
const AUDIO_LOOKAHEAD: usize = 8;
fn worker_cap() -> usize {
std::thread::available_parallelism().map_or(4, |n| n.get()).clamp(1, MAX_WORKERS)
}
/// True when `head` begins with a plausible ISO-BMFF top-level box.
fn looks_like_isobmff(head: &[u8]) -> bool {
if head.len() < 8 {
return false;
}
matches!(&head[4..8], b"ftyp" | b"moov" | b"mdat" | b"free" | b"skip" | b"wide" | b"pnot" | b"uuid")
}
/// Open an in-place MP4/MOV H.264 source via `craft-media` / `craft-video`.
/// Returns `None` when the file is not ISO-BMFF, has no H.264 video track, or has an audio track
/// whose codec is not yet handled by `craft-audio`.
pub(crate) fn open_reader(name: &str, head: &[u8], reader: &SharedBytes) -> Option<Result<SharedSource>> {
if !looks_like_isobmff(head) {
return None;
}
open_byte_source(name, reader.clone())
}
/// Open an in-memory MP4/MOV H.264 source via `craft-media` / `craft-video`.
pub(crate) fn open_bytes(name: &str, bytes: Arc<[u8]>) -> Option<Result<SharedSource>> {
if !looks_like_isobmff(&bytes) {
return None;
}
open_byte_source(name, Arc::new(bytes))
}
fn open_byte_source(name: &str, source: SharedBytes) -> Option<Result<SharedSource>> {
let file = isobmff::open(source.clone()).ok()?;
let video_idx = file.tracks.iter().position(|t| t.kind == TrackKind::Video && !t.samples.is_empty() && !t.entries.is_empty() && t.timescale > 0)?;
let video_track = &file.tracks[video_idx];
let video_params = video_track.codec_params();
if video_params.codec != CodecId::H264 {
return None;
}
// Collect playable audio tracks and ensure `craft-audio` can decode every one of them.
let mut audio_tracks = Vec::new();
let mut audio_infos = Vec::new();
for (idx, track) in file.tracks.iter().enumerate() {
if audio_tracks.len() >= MAX_AUDIO_STREAMS {
break;
}
if track.kind != TrackKind::Audio || track.samples.is_empty() || track.entries.is_empty() || track.timescale == 0 {
continue;
}
let params = track.codec_params();
let mut lookahead = Vec::with_capacity(AUDIO_LOOKAHEAD.min(track.samples.len()));
for s_idx in 0..AUDIO_LOOKAHEAD.min(track.samples.len()) {
let Ok(pkt) = file.read_sample(&*source, idx, s_idx) else {
return None;
};
lookahead.push(pkt);
}
let refs: Vec<&[u8]> = lookahead.iter().map(Vec::as_slice).collect();
let Ok(dec) = AudioTrackDecoder::new(&params, &refs) else {
return None;
};
let native_rate = dec.sample_rate().max(1);
let channels = u32::from(dec.layout().channels()).max(1);
audio_infos.push(AudioStreamInfo {
sample_rate: native_rate,
channels,
codec: params.codec.name().to_string(),
bits_per_sample: params.pcm.map(|p| u32::from(p.bits)),
});
audio_tracks.push(AudioTrackEntry {
track_idx: idx,
native_rate,
state: Mutex::new(AudioTrackState { decoder: dec, next_sample: 0, decoded_pos: 0, buf: Vec::new() }),
});
}
let video_decoder = match TrackDecoder::with_options(&video_params, TrackDecoderOptions { threads: Some(worker_cap()), draft: false }) {
Ok(d) => d,
Err(e) => return Some(Err(MediaError::Decode(e.to_string()))),
};
let container_color = video_track.video().and_then(|v| v.color.as_ref()).map(color_from_isobmff);
let color = container_color.unwrap_or(ColorInfo::REC709);
let (width, height) = video_track
.video()
.map(|v| (u32::from(v.width), u32::from(v.height)))
.filter(|&(w, h)| w > 0 && h > 0)
.unwrap_or((video_track.width, video_track.height));
let par = video_track.video().and_then(|v| v.pixel_aspect).filter(|&(n, d)| n > 0 && d > 0).unwrap_or((1, 1));
let frame_rate = estimate_frame_rate(video_track);
let duration = Tick::from_units(i64::try_from(video_track.duration).unwrap_or(i64::MAX), i64::from(video_track.timescale));
let bitrate = video_track.entries.first().and_then(|e| e.bitrate).map(|b| u64::from(b.avg_bitrate)).filter(|&b| b > 0);
let info = MediaInfo {
name: name.to_string(),
kind: MediaKind::Movie,
duration,
video: Some(VideoStreamInfo {
width,
height,
frame_rate,
par,
codec: "H.264".to_string(),
pixel_format: "yuv420p".to_string(),
color,
has_alpha: false,
bitrate,
hdr: None,
}),
audio_streams: audio_infos,
container: "mp4".to_string(),
start_timecode: None,
file_size: Some(source.len()),
};
Some(Ok(Arc::new(Mp4H264Source {
info,
source,
file,
video_track_idx: video_idx,
container_color,
par,
video: Mutex::new(VideoState { decoder: video_decoder, next_decode_idx: 0, gop_start_idx: 0, flushed: false, decoded: Vec::new() }),
audio_tracks,
})))
}
struct CachedFrame {
pts: i64,
frame: Arc<VideoFrame>,
}
struct VideoState {
decoder: TrackDecoder,
next_decode_idx: usize,
gop_start_idx: usize,
flushed: bool,
decoded: Vec<CachedFrame>,
}
struct AudioTrackState {
decoder: AudioTrackDecoder,
next_sample: usize,
/// Sample index (in native-rate frames) of `buf[0]` relative to track start (0).
decoded_pos: i64,
/// Interleaved or planar? Planar: one `Vec<f32>` per channel.
buf: Vec<Vec<f32>>,
}
struct AudioTrackEntry {
track_idx: usize,
native_rate: u32,
state: Mutex<AudioTrackState>,
}
struct Mp4H264Source {
info: MediaInfo,
source: SharedBytes,
file: Mp4File,
video_track_idx: usize,
container_color: Option<ColorInfo>,
par: (u32, u32),
video: Mutex<VideoState>,
audio_tracks: Vec<AudioTrackEntry>,
}
impl MediaSource for Mp4H264Source {
fn info(&self) -> &MediaInfo {
&self.info
}
fn video_frame(&self, req: FrameRequest) -> Result<Arc<VideoFrame>> {
let track = &self.file.tracks[self.video_track_idx];
let t_track = tick_to_units(req.time, track.timescale);
let target_idx = track.sample_at_presentation_time(t_track).ok_or_else(|| MediaError::Decode("no video samples".into()))?;
let target_pts = track.samples[target_idx].pts;
let mut state = self.video.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(hit) = state.decoded.iter().find(|c| c.pts == target_pts) {
return Ok(hit.frame.clone());
}
let sync_idx = track.sync_sample_before(target_idx);
// Backward seek or jump to a later GOP: reset the decoder to the target sync sample.
if target_idx < state.next_decode_idx || sync_idx > state.gop_start_idx {
state.decoder.reset().map_err(|e| MediaError::Decode(e.to_string()))?;
state.decoded.clear();
state.next_decode_idx = sync_idx;
state.gop_start_idx = sync_idx;
state.flushed = false;
}
let want_draft = req.scale < 0.99;
if state.decoder.draft() != want_draft {
state.decoder.set_draft(want_draft);
}
while !state.decoded.iter().any(|c| c.pts >= target_pts) {
if filmcraft_media::cancel::cancelled() {
return Err(MediaError::Cancelled);
}
if state.next_decode_idx < track.samples.len() {
let idx = state.next_decode_idx;
let sample = track.samples[idx];
let pkt = self.file.read_sample(&*self.source, self.video_track_idx, idx).map_err(|e| MediaError::Io(e.to_string()))?;
let frames = state.decoder.decode(&pkt, sample.pts).map_err(|e| MediaError::Decode(e.to_string()))?;
state.next_decode_idx = idx + 1;
push_decoded(&mut state.decoded, frames, self.container_color, self.par, track.timescale, track.edit_offset)?;
} else if !state.flushed {
let frames = state.decoder.flush().map_err(|e| MediaError::Decode(e.to_string()))?;
state.flushed = true;
push_decoded(&mut state.decoded, frames, self.container_color, self.par, track.timescale, track.edit_offset)?;
break;
} else {
break;
}
}
if let Some(exact) = state.decoded.iter().find(|c| c.pts == target_pts) {
return Ok(exact.frame.clone());
}
// Fallback: latest decoded frame at or before target_pts, or earliest available.
let best = state
.decoded
.iter()
.filter(|c| c.pts <= target_pts)
.max_by_key(|c| c.pts)
.or_else(|| state.decoded.first())
.ok_or_else(|| MediaError::Decode("H.264 decoder produced no frame".into()))?;
Ok(best.frame.clone())
}
fn audio(&self, start: i64, frames: usize, sample_rate: u32) -> Result<AudioBuffer> {
self.audio_stream(0, start, frames, sample_rate)
}
fn audio_stream(&self, stream: usize, start: i64, frames: usize, sample_rate: u32) -> Result<AudioBuffer> {
let entry = self.audio_tracks.get(stream).ok_or(MediaError::NoStream("audio"))?;
if sample_rate == 0 {
return Err(MediaError::Decode("invalid audio sample rate 0".into()));
}
let channels_count = self.info.audio_streams.get(stream).map_or(2, |s| s.channels as usize);
if frames == 0 {
return Ok(AudioBuffer::new(sample_rate, channels_count as u16, 0));
}
let native_rate = entry.native_rate;
let (native_start, native_frames) = if sample_rate == native_rate {
(start, frames)
} else {
let s0 = (i128::from(start) * i128::from(native_rate)) / i128::from(sample_rate);
let len = ((frames as u128 * u128::from(native_rate)).div_ceil(u128::from(sample_rate)) + 2) as usize;
(i64::try_from(s0).unwrap_or(0), len)
};
let track = &self.file.tracks[entry.track_idx];
let mut state = entry.state.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let decoded =
decode_audio_range(&self.file, &*self.source, entry.track_idx, track, native_rate, channels_count, &mut state, native_start, native_frames)?;
if sample_rate == native_rate {
return Ok(AudioBuffer { sample_rate, channels: decoded });
}
let mut resampled = vec![vec![0.0f32; frames]; channels_count];
let ratio = f64::from(native_rate) / f64::from(sample_rate);
for (c, out_ch) in resampled.iter_mut().enumerate() {
let in_ch = &decoded[c];
if in_ch.is_empty() {
continue;
}
for (i, dst) in out_ch.iter_mut().enumerate() {
let pos = i as f64 * ratio;
let idx = pos.floor() as usize;
let frac = (pos - idx as f64) as f32;
let s0 = in_ch.get(idx).copied().unwrap_or(0.0);
let s1 = in_ch.get(idx + 1).copied().unwrap_or(s0);
*dst = s0 + (s1 - s0) * frac;
}
}
Ok(AudioBuffer { sample_rate, channels: resampled })
}
}
#[allow(clippy::too_many_arguments)]
fn decode_audio_range(
file: &Mp4File,
source: &dyn ByteSource,
track_idx: usize,
track: &Track,
native_rate: u32,
channels_count: usize,
state: &mut AudioTrackState,
start: i64,
frames: usize,
) -> Result<Vec<Vec<f32>>> {
let mut out = vec![vec![0.0f32; frames]; channels_count];
let end = start.saturating_add(frames as i64);
if end <= 0 {
return Ok(out);
}
let buf_len = state.buf.first().map_or(0, Vec::len) as i64;
let buf_end = state.decoded_pos.saturating_add(buf_len);
if start < state.decoded_pos || start > buf_end + i64::from(native_rate) * 2 {
// Seek to the sample at or before `start` in track timescale.
let t_track = (i128::from(start.max(0)) * i128::from(track.timescale)) / i128::from(native_rate);
let sample_idx = track.sample_at_presentation_time(i64::try_from(t_track).unwrap_or(0)).unwrap_or(0);
// Back up a few packets for AAC/Opus overlap/preroll.
let seek_idx = sample_idx.saturating_sub(2);
state.decoder.reset();
state.next_sample = seek_idx;
let sample_pts = track.presentation_pts(seek_idx).unwrap_or(0);
state.decoded_pos = i64::try_from((i128::from(sample_pts) * i128::from(native_rate)) / i128::from(track.timescale.max(1))).unwrap_or(0);
for ch in &mut state.buf {
ch.clear();
}
}
if state.buf.len() != channels_count {
state.buf = vec![Vec::new(); channels_count];
}
while state.decoded_pos + state.buf.first().map_or(0, Vec::len) as i64 <= end && state.next_sample < track.samples.len() {
if filmcraft_media::cancel::cancelled() {
return Err(MediaError::Cancelled);
}
let idx = state.next_sample;
let pkt = file.read_sample(source, track_idx, idx).map_err(|e| MediaError::Io(e.to_string()))?;
state.next_sample = idx + 1;
let block = state.decoder.decode(&pkt).map_err(|e| MediaError::Decode(e.to_string()))?;
for (c, ch) in state.buf.iter_mut().enumerate() {
if let Some(src_ch) = block.channels.get(c) {
ch.extend_from_slice(src_ch);
}
}
}
let avail = state.buf.first().map_or(0, Vec::len);
for i in 0..frames {
let pos = start.saturating_add(i as i64);
if pos >= state.decoded_pos {
let off = (pos - state.decoded_pos) as usize;
if off < avail {
for (c, out_ch) in out.iter_mut().enumerate() {
out_ch[i] = state.buf[c][off];
}
}
}
}
// Trim already-consumed audio older than `end` minus a small safety margin.
let drop_to = (end - state.decoded_pos).max(0) as usize;
let trim = drop_to.min(avail);
if trim > 0 {
for ch in &mut state.buf {
ch.drain(..trim);
}
state.decoded_pos = state.decoded_pos.saturating_add(trim as i64);
}
Ok(out)
}
fn push_decoded(
cache: &mut Vec<CachedFrame>,
frames: Vec<DecodedVideoFrame>,
container_color: Option<ColorInfo>,
par: (u32, u32),
timescale: u32,
edit_offset: i64,
) -> Result<()> {
for vf in frames {
let pts = vf.pts.unwrap_or(0);
let frame = Arc::new(to_craft_frame(vf, container_color, par, timescale, edit_offset)?);
cache.push(CachedFrame { pts, frame });
}
if cache.len() > MAX_CACHED_FRAMES {
let excess = cache.len() - MAX_CACHED_FRAMES;
cache.drain(..excess);
}
Ok(())
}
fn to_craft_frame(vf: DecodedVideoFrame, container_color: Option<ColorInfo>, default_par: (u32, u32), timescale: u32, edit_offset: i64) -> Result<VideoFrame> {
let width = vf.width();
let height = vf.height();
let subsampling = vf.subsampling();
let family = vf.family();
let tags = vf.color;
let pts_units = vf.pts.unwrap_or(0).saturating_add(edit_offset);
let pts = Tick::from_units(pts_units, i64::from(timescale.max(1)));
let par = vf.sar.filter(|&(n, d)| n > 0 && d > 0).unwrap_or(default_par);
let color = resolve_color(tags, container_color);
let bit_depth = vf.bit_depth();
let (planes, alpha) = vf.into_planes();
let data = match family {
ColorFamily::YCbCr => {
let chroma = match subsampling {
Subsampling::S420 => Chroma::C420,
Subsampling::S422 => Chroma::C422,
Subsampling::S444 => Chroma::C444,
_ => return Err(MediaError::Unsupported("unsupported YCbCr subsampling".into())),
};
let mut iter = planes.into_iter();
let (Some(y), Some(cb), Some(cr)) = (iter.next(), iter.next(), iter.next()) else {
return Err(MediaError::Decode("missing YUV planes".into()));
};
if bit_depth <= 8 {
let y = Arc::new(plane_u8(y)?);
let cb = Arc::new(plane_u8(cb)?);
let cr = Arc::new(plane_u8(cr)?);
let a = alpha.map(plane_u8).transpose()?.map(Arc::new);
PixelData::Yuv8 { planes: [y, cb, cr], chroma, alpha: a }
} else {
let y = Arc::new(plane_u16(y)?);
let cb = Arc::new(plane_u16(cb)?);
let cr = Arc::new(plane_u16(cr)?);
let a = alpha.map(plane_u16).transpose()?.map(Arc::new);
PixelData::Yuv16 { planes: [y, cb, cr], chroma, bits: u32::from(bit_depth), alpha: a }
}
}
ColorFamily::Rgb | ColorFamily::Gray => return Err(MediaError::Unsupported("non-YCbCr H.264 pixel format".into())),
};
Ok(VideoFrame { width, height, data, color, par, pts })
}
fn plane_u8(p: Plane) -> Result<Vec<u8>> {
let (w, h, stride) = (p.width() as usize, p.height() as usize, p.stride());
match p.into_samples() {
Samples::U8(mut v) => {
if stride == w {
v.truncate(w * h);
return Ok(v);
}
let mut out = Vec::with_capacity(w * h);
for y in 0..h {
let row = y * stride;
out.extend_from_slice(&v[row..row + w]);
}
Ok(out)
}
Samples::U16(_) => Err(MediaError::Decode("expected 8-bit plane".into())),
}
}
fn plane_u16(p: Plane) -> Result<Vec<u16>> {
let (w, h, stride) = (p.width() as usize, p.height() as usize, p.stride());
match p.into_samples() {
Samples::U16(mut v) => {
if stride == w {
v.truncate(w * h);
return Ok(v);
}
let mut out = Vec::with_capacity(w * h);
for y in 0..h {
let row = y * stride;
out.extend_from_slice(&v[row..row + w]);
}
Ok(out)
}
Samples::U8(_) => Err(MediaError::Decode("expected 16-bit plane".into())),
}
}
fn resolve_color(vui: ColorTags, container: Option<ColorInfo>) -> ColorInfo {
let base = container.unwrap_or(ColorInfo::REC709);
let matrix = Matrix::from_code(vui.matrix).unwrap_or(base.matrix);
let transfer = Transfer::from_code(vui.transfer).unwrap_or(base.transfer);
let primaries = primaries_from_code(vui.primaries).unwrap_or(base.primaries);
let range = if vui.full_range { Range::Full } else { base.range };
ColorInfo { matrix, transfer, primaries, range }
}
fn color_from_isobmff(c: &isobmff::ColorInfo) -> ColorInfo {
match c {
isobmff::ColorInfo::Nclx { primaries, transfer, matrix, full_range } => ColorInfo {
matrix: u8::try_from(*matrix).ok().and_then(Matrix::from_code).unwrap_or(Matrix::Bt709),
transfer: u8::try_from(*transfer).ok().and_then(Transfer::from_code).unwrap_or(Transfer::Bt709),
primaries: u8::try_from(*primaries).ok().and_then(primaries_from_code).unwrap_or(Primaries::Bt709),
range: if *full_range { Range::Full } else { Range::Limited },
},
isobmff::ColorInfo::Nclc { primaries, transfer, matrix } => ColorInfo {
matrix: u8::try_from(*matrix).ok().and_then(Matrix::from_code).unwrap_or(Matrix::Bt709),
transfer: u8::try_from(*transfer).ok().and_then(Transfer::from_code).unwrap_or(Transfer::Bt709),
primaries: u8::try_from(*primaries).ok().and_then(primaries_from_code).unwrap_or(Primaries::Bt709),
range: Range::Limited,
},
isobmff::ColorInfo::Icc { .. } => ColorInfo::REC709,
}
}
fn primaries_from_code(c: u8) -> Option<Primaries> {
match c {
1 => Some(Primaries::Bt709),
5 => Some(Primaries::Bt601_625),
6 => Some(Primaries::Bt601_525),
9 => Some(Primaries::Bt2020),
11 | 12 => Some(Primaries::P3D65),
_ => None,
}
}
fn tick_to_units(t: Tick, timescale: u32) -> i64 {
let v = (i128::from(t.0) * i128::from(timescale)) / i128::from(craft_time::TICKS_PER_SECOND);
i64::try_from(v).unwrap_or(if v < 0 { i64::MIN } else { i64::MAX })
}
fn estimate_frame_rate(track: &Track) -> FrameRate {
let ts = i128::from(track.timescale);
if ts <= 0 || track.samples.is_empty() {
return FrameRate::FPS_30;
}
let mut durs: Vec<u32> = track.samples.iter().map(|s| s.duration).filter(|&d| d > 0).collect();
if durs.is_empty() {
return FrameRate::FPS_30;
}
durs.sort_unstable();
let median = durs[durs.len() / 2];
for r in FrameRate::COMMON {
if ts * i128::from(r.den) == i128::from(median) * i128::from(r.num) {
return r;
}
}
let fps = track.timescale as f64 / f64::from(median);
FrameRate::COMMON
.into_iter()
.map(|r| (r, (fps / r.as_f64() - 1.0).abs()))
.filter(|&(_, off)| off <= 0.005)
.min_by(|a, b| a.1.total_cmp(&b.1))
.map(|(r, _)| r)
.unwrap_or_else(|| FrameRate::new(i64::from(track.timescale), i64::from(median)))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn worker_cap_is_bounded() {
let cap = worker_cap();
assert!((1..=MAX_WORKERS).contains(&cap), "cap={cap}");
}
#[test]
fn vui_overrides_container_color_and_falls_back_when_unspecified() {
let container = color_from_isobmff(&isobmff::ColorInfo::Nclx { primaries: 9, transfer: 16, matrix: 9, full_range: false });
assert_eq!(container.primaries, Primaries::Bt2020);
assert_eq!(container.transfer, Transfer::Pq);
assert_eq!(container.matrix, Matrix::Bt2020Ncl);
assert_eq!(container.range, Range::Limited);
// Unspecified VUI (2) falls back to container color.
let resolved = resolve_color(ColorTags::UNSPECIFIED, Some(container));
assert_eq!(resolved, container);
// Explicit VUI overrides container color.
let vui = ColorTags { primaries: 1, transfer: 1, matrix: 1, full_range: true };
let resolved = resolve_color(vui, Some(container));
assert_eq!(resolved.primaries, Primaries::Bt709);
assert_eq!(resolved.transfer, Transfer::Bt709);
assert_eq!(resolved.matrix, Matrix::Bt709);
assert_eq!(resolved.range, Range::Full);
}
}
+21 -17
View File
@@ -12,13 +12,13 @@ use effectcraft_render::disk_cache::Frame8;
use effectcraft_render::reads::{FileStamp, ReadFile, ReadFiles, ReadLog};
use effectcraft_render::{FloatCurve, FootageSource};
use effectcraft_time::{FrameRate, TICKS_PER_SECOND, Tick};
use filmcraft_media::{FrameRequest, SharedSource};
use image::metadata::Orientation;
use crate::convert::{AlphaOp, dynamic_to_image, frame_to_image_in, frame_to_image_scaled, frame_to_rgba8, turned};
use crate::downmix::Order;
use crate::gif_anim::{self, Anim};
use crate::reads;
use crate::stream::MediaSource;
use crate::{MediaError, Result};
/// Default frame-cache budget: 1 GiB of decoded frames.
@@ -560,7 +560,7 @@ type SourceSlot = Arc<OnceLock<(Option<Opened>, ReadFile)>>;
/// audio channels arrive in.
#[derive(Clone)]
struct Opened {
src: SharedSource,
src: MediaSource,
turn: Orientation,
order: Order,
}
@@ -568,7 +568,7 @@ struct Opened {
impl Opened {
/// `src` with what its container says: `header` is an MP4/MOV's ftyp and moov (or the whole
/// file), `file` the file for other containers' AAC configuration.
fn new(src: SharedSource, header: Option<&[u8]>, file: Option<&dyn filmcraft_media::ByteReader>) -> Opened {
fn new(src: MediaSource, header: Option<&[u8]>, file: Option<&dyn filmcraft_media::ByteReader>) -> Opened {
let turn = header.map_or(Orientation::NoTransforms, crate::probe::video_turn);
Opened { order: channel_order(&src, header, file), src, turn }
}
@@ -576,9 +576,11 @@ impl Opened {
/// The order `src`'s audio channels decode in; multichannel AAC's by its configuration, where
/// the container's header shows it ([`crate::aac::config`]).
fn channel_order(src: &SharedSource, header: Option<&[u8]>, file: Option<&dyn filmcraft_media::ByteReader>) -> Order {
match src.info().audio() {
Some(a) if a.codec.contains("AAC") && a.channels > 2 => crate::aac::config(header, file).map_or(Order::Aac, |asc| crate::downmix::aac_order(&asc)),
fn channel_order(src: &MediaSource, header: Option<&[u8]>, file: Option<&dyn filmcraft_media::ByteReader>) -> Order {
match src.primary_audio() {
Some((_, channels, codec)) if codec.contains("AAC") && channels > 2 => {
crate::aac::config(header, file).map_or(Order::Aac, |asc| crate::downmix::aac_order(&asc))
}
_ => Order::Wav,
}
}
@@ -1071,7 +1073,7 @@ impl MediaPool {
let path: Arc<str> = footage.path.as_str().into();
let Opened { src, order, .. } = self.inner.opened(&path).ok_or("the file can't be opened")?;
let s0 = start.to_units_floor(rate as i64);
let native = src.info().audio().map_or(rate, |a| a.sample_rate);
let native = src.primary_audio().map_or(rate, |(sr, _, _)| sr);
// The header's rate scales the samples read: 0xFFFFFFFF Hz made one conform chunk about
// 47 GB (#2141). Real audio is 1–768 kHz.
if native != 0 && !(MIN_SAMPLE_RATE..=MAX_SAMPLE_RATE).contains(&native) {
@@ -1217,7 +1219,7 @@ impl Inner {
let (bytes, read) = self.read_file(path);
let opened = bytes.and_then(|bytes| {
let name = std::path::Path::new(&**path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
let src = filmcraft_codecs::open_bytes(&name, bytes.clone()).map_err(MediaError::from)?;
let src = crate::stream::open_bytes(&name, bytes.clone())?;
Ok(Opened::new(src, Some(&bytes), Some(&filmcraft_media::reader::MemReader(bytes.clone()))))
});
(opened, read)
@@ -1759,18 +1761,20 @@ impl Inner {
}
Some(mt) => {
let Opened { src, turn, .. } = self.opened(path).ok_or_else(|| MediaError::Io(format!("{path}: cannot open")))?;
let vf = src
.video_frame(FrameRequest::full(filmcraft_time::Tick(mt.0)))
.map_err(MediaError::from)
.inspect_err(|e| self.note_problem(path, &footage.codec, e))?;
// A movie shown turned a quarter (a phone held upright): the footage's size and
// the render's are the turned picture's, the decoded frame's are the file's.
let side = |(w, h): (u32, u32)| if crate::probe::swaps_sides(turn) { (h, w) } else { (w, h) };
// A reduced-resolution render's frame, made at its size (a frame of the footage's
// own size only, as the renderer resamples only those).
let (w, h) = side(loc.key.size);
let scale = if w > 0 && footage.width > 0 && footage.height > 0 && (w < footage.width || h < footage.height) {
(w as f32 / footage.width as f32).min(h as f32 / footage.height as f32)
} else {
1.0
};
let vf = src.video_frame(mt, scale).inspect_err(|e| self.note_problem(path, &footage.codec, e))?;
if w > 0
&& (vf.width, vf.height) == side((footage.width, footage.height))
&& (vf.width(), vf.height()) == side((footage.width, footage.height))
&& let Some(img) = frame_to_image_scaled(&vf, w, h)
{
return Ok(f32(turned(img, turn)));
@@ -1781,7 +1785,7 @@ impl Inner {
{
return Ok(Pixels::Q8(Arc::new(f)));
}
let buf = lock(&self.cache).lru.take_spare(vf.width as usize * vf.height as usize);
let buf = lock(&self.cache).lru.take_spare(vf.width() as usize * vf.height() as usize);
Ok(f32(turned(frame_to_image_in(&vf, op, buf), turn)))
}
}
@@ -2005,15 +2009,15 @@ impl FootageSource for MediaPool {
/// `frames` stereo sample frames (interleaved) of `src` from sample `s0` at `rate` Hz, which
/// FilmCraft serves as decoded when it is the source's own rate. Mono is duplicated to both
/// channels, multichannel sources (channels in `order`) are downmixed ([`crate::downmix`]); silence before the start. An error where decoding fails.
fn read_stereo(src: &SharedSource, order: &Order, s0: i64, frames: usize, rate: u32) -> std::result::Result<Vec<f32>, String> {
fn read_stereo(src: &MediaSource, order: &Order, s0: i64, frames: usize, rate: u32) -> std::result::Result<Vec<f32>, String> {
let mut out = vec![0.0; frames * 2];
let skip = usize::try_from(s0.saturating_neg()).unwrap_or(0);
if skip >= frames {
return Ok(out);
}
let buf = src.audio(s0.max(0), frames - skip, rate).map_err(|e| e.to_string())?;
let channels = src.audio(s0.max(0), frames - skip, rate)?;
let Some(dst) = skip.checked_mul(2).and_then(|i| out.get_mut(i..)) else { return Ok(out) };
crate::downmix::downmix_into(&buf.channels, order, dst);
crate::downmix::downmix_into(&channels, order, dst);
Ok(out)
}
+61 -3
View File
@@ -27,7 +27,7 @@ pub fn probe(path: impl AsRef<Path>) -> Result<Footage> {
let path = path.as_ref();
// A movie is read in place (its index), not loaded whole.
if let Some(src) = crate::stream::probe_source(path) {
let mut f = footage_from_info(&path.to_string_lossy(), src?.info());
let mut f = footage_from_source(&path.to_string_lossy(), &src?);
let header = crate::stream::movie_header(path);
let turn = header.as_deref().map_or(Orientation::NoTransforms, video_turn);
turn_footage(&mut f, turn);
@@ -134,8 +134,8 @@ pub fn probe_bytes(path: &str, bytes: Arc<[u8]>) -> Result<Footage> {
let shown = video_shown(&bytes);
// A WAV's cue points and XMP markers become the footage's markers.
let markers = crate::wav_markers::read(&bytes);
let src = filmcraft_codecs::open_bytes(&name, bytes)?;
let mut f = footage_from_info(path, src.info());
let src = crate::stream::open_bytes(&name, bytes)?;
let mut f = footage_from_source(path, &src);
f.markers = markers;
turn_footage(&mut f, turn);
correct_rate(&mut f, rate);
@@ -190,6 +190,64 @@ fn turn_footage(f: &mut Footage, turn: Orientation) {
}
}
pub(crate) fn footage_from_source(path: &str, src: &crate::stream::MediaSource) -> Footage {
match src {
crate::stream::MediaSource::Craft(s) => footage_from_craft_info(path, s.info()),
crate::stream::MediaSource::Film(s) => footage_from_info(path, s.info()),
}
}
pub(crate) fn footage_from_craft_info(path: &str, info: &craft_media_source::MediaInfo) -> Footage {
let v = info.video.as_ref();
let kind = match (info.kind, v) {
(craft_media_source::MediaKind::Still, _) => FootageKind::Still,
(_, Some(_)) => FootageKind::Video,
(_, None) => FootageKind::Audio,
};
let rate = v.map_or(FrameRate::FPS_30, |v| {
if v.frame_rate.num > 0 && v.frame_rate.den > 0 { FrameRate::new(v.frame_rate.num, v.frame_rate.den) } else { FrameRate::FPS_30 }
});
let codec = match (v, info.audio()) {
(Some(v), _) => v.codec.clone(),
(None, Some(a)) => a.codec.clone(),
_ => String::new(),
};
Footage {
path: path.to_string(),
kind,
width: v.map_or(0, |v| v.width),
height: v.map_or(0, |v| v.height),
pixel_aspect: v.map_or(1.0, |v| if v.par.1 > 0 { v.par.0 as f64 / v.par.1 as f64 } else { 1.0 }),
frame_rate: rate,
native_rate: None,
duration: if kind == FootageKind::Still { Tick::ZERO } else { Tick(info.duration.0) },
has_video: v.is_some(),
has_audio: info.has_audio(),
alpha: if v.is_some_and(|v| v.has_alpha) { AlphaMode::Straight } else { AlphaMode::Ignore },
premul_color: [0.0; 3],
loop_count: 1,
codec,
missing: false,
sequence: Vec::new(),
color_profile: v.and_then(|v| profile_of_craft(&v.color)),
file_timecode: v.and(info.start_timecode),
..Default::default()
}
}
fn profile_of_craft(c: &craft_color::ColorInfo) -> Option<effectcraft_project::ColorSpace> {
use craft_color::{Primaries, Transfer};
use effectcraft_project::ColorSpace;
match (c.primaries, c.transfer) {
(Primaries::Bt2020, Transfer::Pq) => Some(ColorSpace::Rec2100Pq),
(Primaries::Bt2020, Transfer::Hlg) => Some(ColorSpace::Rec2100Hlg),
(Primaries::Bt2020, _) => Some(ColorSpace::Rec2020),
(Primaries::P3D65, _) => Some(ColorSpace::DisplayP3),
(_, Transfer::Bt709) => Some(ColorSpace::Rec709),
_ => None,
}
}
pub(crate) fn footage_from_info(path: &str, info: &filmcraft_media::MediaInfo) -> Footage {
let v = info.video.as_ref();
let kind = match (info.kind, v) {
+117 -18
View File
@@ -2,17 +2,83 @@
//!
//! Reading a file whole before opening it made a clip cost its full size in memory (twice while
//! probing: the file's bytes plus the demuxer's copy), so a 45-minute movie took gigabytes just to
//! import. FilmCraft's reader openers (MP4/MOV, Matroska/WebM, MXF, Ogg, MPEG-PS/TS) open from a
//! random-access [`ByteReader`]; [`FileReader`] serves them positional reads from the open file.
//! import. Reader openers (MP4/MOV, Matroska/WebM, MXF, Ogg, MPEG-PS/TS) open from a random-access
//! byte reader; [`FileReader`] serves them positional reads from the open file.
//! Formats decoded in one go (stills, WAV, FLAC, MP3…) still read the whole file, as before.
//! Builds without a native file system (wasm32) keep using in-memory bytes.
use std::path::Path;
use std::sync::Arc;
use effectcraft_render::reads::FileStamp;
use filmcraft_media::SharedSource;
use effectcraft_time::Tick;
use crate::Result;
use crate::{MediaError, Result};
/// A decoded video frame from either `craft-media-source` or `filmcraft-media`.
pub(crate) enum DecodedFrame {
Craft(Arc<craft_frame::VideoFrame>),
Film(Arc<filmcraft_frame::VideoFrame>),
}
impl DecodedFrame {
pub(crate) fn width(&self) -> u32 {
match self {
DecodedFrame::Craft(f) => f.width,
DecodedFrame::Film(f) => f.width,
}
}
pub(crate) fn height(&self) -> u32 {
match self {
DecodedFrame::Craft(f) => f.height,
DecodedFrame::Film(f) => f.height,
}
}
}
/// An opened movie/audio source, routed through `craft-media-source` for migrated formats
/// (currently software MP4/H.264) and `filmcraft-media` for remaining formats.
#[derive(Clone)]
pub(crate) enum MediaSource {
Craft(craft_media_source::SharedSource),
Film(filmcraft_media::SharedSource),
}
impl MediaSource {
pub(crate) fn video_frame(&self, time: Tick, scale: f32) -> Result<DecodedFrame> {
match self {
MediaSource::Craft(s) => {
s.video_frame(craft_media_source::FrameRequest { time: craft_time::Tick(time.0), scale }).map(DecodedFrame::Craft).map_err(MediaError::from)
}
MediaSource::Film(s) => {
s.video_frame(filmcraft_media::FrameRequest { time: filmcraft_time::Tick(time.0), scale }).map(DecodedFrame::Film).map_err(MediaError::from)
}
}
}
pub(crate) fn audio(&self, start: i64, frames: usize, rate: u32) -> std::result::Result<Vec<Vec<f32>>, String> {
match self {
MediaSource::Craft(s) => s.audio(start, frames, rate).map(|b| b.channels).map_err(|e| e.to_string()),
MediaSource::Film(s) => s.audio(start, frames, rate).map(|b| b.channels).map_err(|e| e.to_string()),
}
}
pub(crate) fn primary_audio(&self) -> Option<(u32, u32, String)> {
match self {
MediaSource::Craft(s) => s.info().audio().map(|a| (a.sample_rate, a.channels, a.codec.clone())),
MediaSource::Film(s) => s.info().audio().map(|a| (a.sample_rate, a.channels, a.codec.clone())),
}
}
}
/// Open an in-memory movie/audio source, trying migrated `craft-media-source` routes first.
pub(crate) fn open_bytes(name: &str, bytes: Arc<[u8]>) -> Result<MediaSource> {
if let Some(res) = crate::mp4_h264::open_bytes(name, bytes.clone()) {
return res.map(MediaSource::Craft).map_err(MediaError::from);
}
filmcraft_codecs::open_bytes(name, bytes).map(MediaSource::Film).map_err(MediaError::from)
}
/// A file on disk read in place: it stays open and only the requested ranges are read.
#[cfg(any(unix, windows))]
@@ -40,13 +106,13 @@ impl FileReader {
}
#[cfg(any(unix, windows))]
impl filmcraft_media::ByteReader for FileReader {
fn len(&self) -> u64 {
impl FileReader {
fn len_bytes(&self) -> u64 {
self.len
}
/// Positional reads: threads decoding different parts of the file share no cursor.
fn read_at(&self, offset: u64, buf: &mut [u8]) -> std::io::Result<()> {
fn read_exact_at(&self, offset: u64, buf: &mut [u8]) -> std::io::Result<()> {
#[cfg(unix)]
{
std::os::unix::fs::FileExt::read_exact_at(&self.file, buf, offset)
@@ -70,6 +136,28 @@ impl filmcraft_media::ByteReader for FileReader {
}
}
#[cfg(any(unix, windows))]
impl filmcraft_media::ByteReader for FileReader {
fn len(&self) -> u64 {
self.len_bytes()
}
fn read_at(&self, offset: u64, buf: &mut [u8]) -> std::io::Result<()> {
self.read_exact_at(offset, buf)
}
}
#[cfg(any(unix, windows))]
impl craft_media::ByteSource for FileReader {
fn len(&self) -> u64 {
self.len_bytes()
}
fn read_at(&self, offset: u64, buf: &mut [u8]) -> std::io::Result<()> {
self.read_exact_at(offset, buf)
}
}
#[cfg(any(unix, windows))]
fn name_of(path: &Path) -> String {
path.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default()
@@ -80,17 +168,24 @@ fn name_of(path: &Path) -> String {
/// when the file can't be opened in place (the caller reads it whole, which reports the error).
/// With the file's identity as opened.
#[cfg(any(unix, windows))]
pub(crate) fn open_source(path: &Path) -> Option<(Result<SharedSource>, FileStamp)> {
let reader = FileReader::open(path).ok()?;
pub(crate) fn open_source(path: &Path) -> Option<(Result<MediaSource>, FileStamp)> {
let reader = Arc::new(FileReader::open(path).ok()?);
let stamp = reader.stamp;
let reader: filmcraft_media::SharedReader = std::sync::Arc::new(reader);
let opened = filmcraft_media::reader::open_reader(&name_of(path), reader, &filmcraft_codecs::reader_openers(), &filmcraft_codecs::openers());
Some((opened.map_err(Into::into), stamp))
let name = name_of(path);
let craft_reader: craft_media_source::SharedBytes = reader.clone();
if let Ok(head) = craft_media_source::read_range(&*craft_reader, 0, craft_media_source::HEAD_LEN)
&& let Some(res) = crate::mp4_h264::open_reader(&name, &head, &craft_reader)
{
return Some((res.map(MediaSource::Craft).map_err(MediaError::from), stamp));
}
let fc_reader: filmcraft_media::SharedReader = reader;
let opened = filmcraft_media::reader::open_reader(&name, fc_reader, &filmcraft_codecs::reader_openers(), &filmcraft_codecs::openers());
Some((opened.map(MediaSource::Film).map_err(MediaError::from), stamp))
}
/// Without a native file system there is no in-place source: always `None`.
#[cfg(not(any(unix, windows)))]
pub(crate) fn open_source(_path: &Path) -> Option<(Result<SharedSource>, FileStamp)> {
pub(crate) fn open_source(_path: &Path) -> Option<(Result<MediaSource>, FileStamp)> {
None
}
@@ -160,23 +255,27 @@ pub(crate) fn movie_header(_path: &Path) -> Option<Vec<u8>> {
/// handles and nothing probed before containers (stills, layered and vector documents, 3D models)
/// claims it. `None`: probe the whole file's bytes as before.
#[cfg(any(unix, windows))]
pub(crate) fn probe_source(path: &Path) -> Option<Result<SharedSource>> {
pub(crate) fn probe_source(path: &Path) -> Option<Result<MediaSource>> {
let ext = crate::ext_of(path);
if crate::STILL_EXTENSIONS.contains(&ext.as_str()) || crate::MODEL_EXTENSIONS.contains(&ext.as_str()) {
return None;
}
let reader = FileReader::open(path).ok()?;
let reader: filmcraft_media::SharedReader = std::sync::Arc::new(reader);
let reader = Arc::new(FileReader::open(path).ok()?);
let head = filmcraft_media::reader::read_range(&*reader, 0, filmcraft_media::reader::HEAD_LEN).ok()?;
let name = path.to_string_lossy();
if crate::layered::sniff(&name, &head) || image::guess_format(&head).is_ok() {
return None;
}
let name = name_of(path);
filmcraft_codecs::reader_openers().into_iter().find_map(|open| open(&name, &head, &reader)).map(|r| r.map_err(Into::into))
let craft_reader: craft_media_source::SharedBytes = reader.clone();
if let Some(res) = crate::mp4_h264::open_reader(&name, &head, &craft_reader) {
return Some(res.map(MediaSource::Craft).map_err(MediaError::from));
}
let fc_reader: filmcraft_media::SharedReader = reader;
filmcraft_codecs::reader_openers().into_iter().find_map(|open| open(&name, &head, &fc_reader)).map(|r| r.map(MediaSource::Film).map_err(Into::into))
}
#[cfg(not(any(unix, windows)))]
pub(crate) fn probe_source(_path: &Path) -> Option<Result<SharedSource>> {
pub(crate) fn probe_source(_path: &Path) -> Option<Result<MediaSource>> {
None
}
+71
View File
@@ -1290,3 +1290,74 @@ fn the_h264_fixture_options_fit_the_picked_encoder() {
assert!(options.contains(&"-b:v"), "{enc} gets a bitrate: {options:?}");
}
}
/// #781: software MP4/H.264 route on a B-frame fixture: backward seek across GOPs, cooperative
/// cancellation, VUI/container color resolution, and draft mode for reduced-resolution playback.
#[test]
fn h264_bframe_route_backward_seek_cancel_color_and_draft() {
use std::sync::atomic::AtomicBool;
if h264_encoder() != Some("libx264") {
return;
}
let Some(p) = try_ffmpeg_fixture(
"h264_bframes_bt709.mp4",
&[
"-f",
"lavfi",
"-i",
"testsrc2=size=320x180:rate=24:duration=1",
"-c:v",
"libx264",
"-preset",
"fast",
"-bf",
"2",
"-g",
"12",
"-pix_fmt",
"yuv420p",
"-colorspace",
"bt709",
"-color_primaries",
"bt709",
"-color_trc",
"bt709",
"-color_range",
"tv",
],
) else {
return;
};
let f = probe(&p).expect("probe");
assert_eq!((f.width, f.height), (320, 180));
assert_eq!(f.color_profile, Some(effectcraft_project::ColorSpace::Rec709));
let pool = MediaPool::new();
// Forward decode into second GOP, then backward seek across GOP boundary and within GOP.
let f18 = pool.frame(ItemId(1), &f, t_of(f.frame_rate, 18)).expect("frame 18");
let f13 = pool.frame(ItemId(1), &f, t_of(f.frame_rate, 13)).expect("frame 13");
let f7 = pool.frame(ItemId(1), &f, t_of(f.frame_rate, 7)).expect("frame 7");
let f0 = pool.frame(ItemId(1), &f, t_of(f.frame_rate, 0)).expect("frame 0");
for img in [&f18, &f13, &f7, &f0] {
assert_eq!((img.width, img.height), (320, 180));
}
// Verify backward-seeked frame 7 matches a fresh pool decode of frame 7.
let fresh_f7 = MediaPool::new().frame(ItemId(1), &f, t_of(f.frame_rate, 7)).expect("fresh frame 7");
assert!(psnr(&f7, &fresh_f7) > 55.0, "backward seek frame 7 must match fresh decode");
// Draft mode at reduced resolution.
let draft = pool.frame_at_size(ItemId(1), &f, t_of(f.frame_rate, 5), 160, 90).expect("draft frame");
let full = pool.frame(ItemId(1), &f, t_of(f.frame_rate, 5)).expect("full frame");
assert_eq!((draft.width, draft.height), (160, 90));
assert!(psnr(&draft, &effectcraft_raster::resample(&full, 160, 90)) > 40.0, "draft frame matches resampled full frame");
// Cooperative cancellation.
let off = Arc::new(AtomicBool::new(true));
let mut cancelled = Some(Arc::clone(&f0));
pool.cancellable(&off, &mut || cancelled = pool.frame(ItemId(1), &f, t_of(f.frame_rate, 20)));
assert!(cancelled.is_none(), "cancelled read must not decode");
let on = Arc::new(AtomicBool::new(false));
let mut resumed = None;
pool.cancellable(&on, &mut || resumed = pool.frame(ItemId(1), &f, t_of(f.frame_rate, 20)));
assert_eq!(resumed.map(|i| (i.width, i.height)), Some((320, 180)));
}
+209 -163
View File
@@ -210,15 +210,6 @@ pub(crate) fn put_u32(out: &mut Vec<u8>, v: u32) {
out.extend_from_slice(&v.to_be_bytes());
}
fn put_id(out: &mut Vec<u8>, id: &str) {
if id.len() == 4 {
put_u32(out, 0);
} else {
put_u32(out, id.len() as u32);
}
out.extend_from_slice(id.as_bytes());
}
/// A length-prefixed UTF-16BE string (the length counts code units, including the NUL when
/// `terminated`).
pub(crate) fn put_utf16(out: &mut Vec<u8>, s: &str, terminated: bool) {
@@ -229,163 +220,80 @@ pub(crate) fn put_utf16(out: &mut Vec<u8>, s: &str, terminated: bool) {
}
}
/// A descriptor Unicode string: NUL-terminated.
pub(crate) fn put_unicode(out: &mut Vec<u8>, s: &str) {
put_utf16(out, s, true);
use craft_psd::descriptor::borrowed::{ClassRef, DescriptorView, IdRef, ReferenceRef, ReferencesView, UnicodeRef, ValueRef, ValuesView};
fn borrowed_id(id: &str) -> IdRef<'_> {
match id.as_bytes() {
[a, b, c, d] => IdRef::Code([*a, *b, *c, *d]),
bytes => IdRef::String(bytes),
}
}
fn borrowed_class<'a>(name: &'a str, id: &'a str) -> ClassRef<'a> {
ClassRef { name: UnicodeRef::Text(name, true), id: borrowed_id(id) }
}
fn preserved_class(class: &craft_psd::descriptor::Class) -> ClassRef<'_> {
ClassRef {
name: UnicodeRef::Units(&class.name.0),
id: match &class.class_id {
craft_psd::descriptor::Id::Code(code) => IdRef::Code(*code),
craft_psd::descriptor::Id::Str(bytes) => IdRef::String(bytes),
},
}
}
impl DescriptorView for Descriptor {
fn class(&self) -> ClassRef<'_> {
borrowed_class(&self.class_name, &self.class_id)
}
fn item(&self, index: usize) -> Option<(IdRef<'_>, ValueRef<'_>)> {
self.items.get(index).map(|(k, v)| (borrowed_id(k), borrowed_value(v)))
}
}
impl ValuesView for DValue {
fn value(&self, index: usize) -> Option<ValueRef<'_>> {
match self {
DValue::List(items) => items.get(index).map(borrowed_value),
_ => None,
}
}
}
impl ReferencesView for DValue {
fn reference(&self, index: usize) -> Option<ReferenceRef<'_>> {
let DValue::Reference(items) = self else { return None };
Some(match items.get(index)? {
RefItem::Property(c, k) => ReferenceRef::Property(borrowed_class("", c), borrowed_id(k)),
RefItem::Class(c) => ReferenceRef::Class(borrowed_class("", c)),
RefItem::Enum(c, t, v) => ReferenceRef::Enumerated(borrowed_class("", c), borrowed_id(t), borrowed_id(v)),
RefItem::Offset(c, n) => ReferenceRef::Offset(borrowed_class("", c), *n),
RefItem::Identifier(n) => ReferenceRef::Identifier(borrowed_class("", "null"), *n),
RefItem::Index(n) => ReferenceRef::Index(borrowed_class("", "null"), *n),
RefItem::IdentifierWithClass(c, n) => ReferenceRef::Identifier(preserved_class(c), *n),
RefItem::IndexWithClass(c, n) => ReferenceRef::Index(preserved_class(c), *n),
RefItem::Name(c, n) => ReferenceRef::Name(borrowed_class("", c), UnicodeRef::Text(n, true)),
})
}
}
fn borrowed_value(value: &DValue) -> ValueRef<'_> {
match value {
DValue::Descriptor(d) => ValueRef::Descriptor(d),
DValue::List(_) => ValueRef::List(value),
DValue::ObjectArray(n, d) => ValueRef::ObjectArray(*n, d),
DValue::Double(n) => ValueRef::Double(*n),
DValue::UnitFloat(u, n) => ValueRef::UnitFloat(tag4(u), *n),
DValue::UnitFloats(u, ns) => ValueRef::UnitFloats(tag4(u), ns),
DValue::Text(s) => ValueRef::Text(UnicodeRef::Text(s, true)),
DValue::Enum(t, v) => ValueRef::Enumerated(borrowed_id(t), borrowed_id(v)),
DValue::Integer(n) => ValueRef::Integer(*n),
DValue::LargeInteger(n) => ValueRef::LargeInteger(*n),
DValue::Bool(b) => ValueRef::Boolean(*b),
DValue::Class(n, c) => ValueRef::Class(borrowed_class(n, c)),
DValue::Raw(b) => ValueRef::RawData(b),
DValue::Reference(_) => ValueRef::Reference(value),
}
}
/// Serialise a descriptor (without the version field).
/// Serialise a descriptor (without the version field), appending to out.
pub fn write_descriptor(out: &mut Vec<u8>, d: &Descriptor) {
put_unicode(out, &d.class_name);
put_id(out, &d.class_id);
put_u32(out, d.items.len() as u32);
for (k, v) in &d.items {
put_id(out, k);
write_value(out, v);
}
}
fn write_value(out: &mut Vec<u8>, v: &DValue) {
match v {
DValue::Descriptor(d) => {
out.extend_from_slice(b"Objc");
write_descriptor(out, d);
}
DValue::List(l) => {
out.extend_from_slice(b"VlLs");
put_u32(out, l.len() as u32);
for x in l {
write_value(out, x);
}
}
DValue::ObjectArray(n, d) => {
out.extend_from_slice(b"ObAr");
put_u32(out, *n);
write_descriptor(out, d);
}
DValue::Double(x) => {
out.extend_from_slice(b"doub");
out.extend_from_slice(&x.to_be_bytes());
}
DValue::UnitFloat(u, x) => {
out.extend_from_slice(b"UntF");
out.extend_from_slice(&tag4(u));
out.extend_from_slice(&x.to_be_bytes());
}
DValue::UnitFloats(u, xs) => {
out.extend_from_slice(b"UnFl");
out.extend_from_slice(&tag4(u));
put_u32(out, xs.len() as u32);
for x in xs {
out.extend_from_slice(&x.to_be_bytes());
}
}
DValue::Text(s) => {
out.extend_from_slice(b"TEXT");
put_unicode(out, s);
}
DValue::Enum(t, e) => {
out.extend_from_slice(b"enum");
put_id(out, t);
put_id(out, e);
}
DValue::Integer(i) => {
out.extend_from_slice(b"long");
out.extend_from_slice(&i.to_be_bytes());
}
DValue::LargeInteger(i) => {
out.extend_from_slice(b"comp");
out.extend_from_slice(&i.to_be_bytes());
}
DValue::Bool(b) => {
out.extend_from_slice(b"bool");
out.push(*b as u8);
}
DValue::Class(n, c) => {
out.extend_from_slice(b"type");
put_unicode(out, n);
put_id(out, c);
}
DValue::Raw(b) => {
out.extend_from_slice(b"tdta");
put_u32(out, b.len() as u32);
out.extend_from_slice(b);
}
DValue::Reference(items) => {
out.extend_from_slice(b"obj ");
put_u32(out, items.len() as u32);
for it in items {
match it {
RefItem::Property(c, k) => {
out.extend_from_slice(b"prop");
put_unicode(out, "");
put_id(out, c);
put_id(out, k);
}
RefItem::Class(c) => {
out.extend_from_slice(b"Clss");
put_unicode(out, "");
put_id(out, c);
}
RefItem::Enum(c, t, e) => {
out.extend_from_slice(b"Enmr");
put_unicode(out, "");
put_id(out, c);
put_id(out, t);
put_id(out, e);
}
RefItem::Offset(c, o) => {
out.extend_from_slice(b"rele");
put_unicode(out, "");
put_id(out, c);
out.extend_from_slice(&o.to_be_bytes());
}
RefItem::Identifier(i) => {
// Photoshop stores a class before the id; craft-psd reads it that way.
out.extend_from_slice(b"Idnt");
put_unicode(out, "");
put_id(out, "null");
out.extend_from_slice(&i.to_be_bytes());
}
RefItem::Index(i) => {
out.extend_from_slice(b"indx");
put_unicode(out, "");
put_id(out, "null");
out.extend_from_slice(&i.to_be_bytes());
}
RefItem::IdentifierWithClass(class, id) => {
out.extend_from_slice(b"Idnt");
put_reference_class(out, class);
out.extend_from_slice(&id.to_be_bytes());
}
RefItem::IndexWithClass(class, index) => {
out.extend_from_slice(b"indx");
put_reference_class(out, class);
out.extend_from_slice(&index.to_be_bytes());
}
RefItem::Name(c, n) => {
out.extend_from_slice(b"name");
put_unicode(out, "");
put_id(out, c);
put_unicode(out, n);
}
}
}
}
}
}
fn put_reference_class(out: &mut Vec<u8>, class: &craft_psd::descriptor::Class) {
out.extend_from_slice(&(class.name.0.len() as u32).to_be_bytes());
for unit in &class.name.0 {
out.extend_from_slice(&unit.to_be_bytes());
}
let length = match &class.class_id {
craft_psd::descriptor::Id::Code(_) => 0,
craft_psd::descriptor::Id::Str(bytes) => bytes.len() as u32,
};
out.extend_from_slice(&length.to_be_bytes());
out.extend_from_slice(class.class_id.as_bytes());
craft_psd::descriptor::borrowed::append_descriptor(out, d);
}
fn tag4(s: &str) -> [u8; 4] {
@@ -449,3 +357,141 @@ mod tests {
assert_eq!(back, d);
}
}
#[cfg(test)]
mod writer_wire_tests {
use super::*;
fn hex(s: &str) -> Vec<u8> {
s.split_whitespace().map(|b| u8::from_str_radix(b, 16).unwrap()).collect()
}
fn check(value: DValue, payload: Vec<u8>) {
let d = Descriptor::new("warp").with("time", value);
let mut got = vec![0xaa, 0xbb];
write_descriptor(&mut got, &d);
// Empty name plus one NUL, Code(warp), one item, Code(time).
let mut want = hex("aa bb 00 00 00 01 00 00 00 00 00 00 77 61 72 70 00 00 00 01 00 00 00 00 74 69 6d 65");
want.extend(payload);
assert_eq!(got, want);
}
#[test]
fn all_scalar_wire_tags_keep_raw_bits_ids_and_unicode() {
for (v, bytes) in [
(DValue::Double(f64::from_bits(0x7ff8_1234_5678_9abc)), "64 6f 75 62 7f f8 12 34 56 78 9a bc"),
(DValue::Double(-0.0), "64 6f 75 62 80 00 00 00 00 00 00 00"),
(DValue::UnitFloat("x".into(), f64::INFINITY), "55 6e 74 46 78 20 20 20 7f f0 00 00 00 00 00 00"),
(DValue::UnitFloats("abcde".into(), vec![-0.0, 1.0]), "55 6e 46 6c 61 62 63 64 00 00 00 02 80 00 00 00 00 00 00 00 3f f0 00 00 00 00 00 00"),
(DValue::Text("A\0\0".into()), "54 45 58 54 00 00 00 04 00 41 00 00 00 00 00 00"),
(DValue::Enum("list".into(), "".into()), "65 6e 75 6d 00 00 00 00 6c 69 73 74 00 00 00 00"),
(DValue::Integer(i32::MIN), "6c 6f 6e 67 80 00 00 00"),
(DValue::LargeInteger(i64::MIN), "63 6f 6d 70 80 00 00 00 00 00 00 00"),
(DValue::Bool(true), "62 6f 6f 6c 01"),
(DValue::Class("A".into(), "longer".into()), "74 79 70 65 00 00 00 02 00 41 00 00 00 00 00 06 6c 6f 6e 67 65 72"),
(DValue::Raw(vec![0, 255, 3]), "74 64 74 61 00 00 00 03 00 ff 03"),
] {
check(v, hex(bytes));
}
}
#[test]
fn children_and_object_array_prefix_keep_their_own_counts() {
let empty = Descriptor::new("null");
let body = hex("00 00 00 01 00 00 00 00 00 00 6e 75 6c 6c 00 00 00 00");
let mut object = b"Objc".to_vec();
object.extend(&body);
check(DValue::Descriptor(empty.clone()), object);
let mut array = hex("4f 62 41 72 12 34 56 78");
array.extend(&body);
check(DValue::ObjectArray(0x1234_5678, empty), array);
check(DValue::List(vec![DValue::List(vec![]), DValue::Bool(false)]), hex("56 6c 4c 73 00 00 00 02 56 6c 4c 73 00 00 00 00 62 6f 6f 6c 00"));
}
#[test]
fn reference_variants_preserve_class_encoding_and_signed_fields() {
let class = hex("00 00 00 01 00 00 00 00 00 00 6e 75 6c 6c");
for (r, tag, tail) in [
(RefItem::Property("null".into(), "warp".into()), "prop", hex("00 00 00 00 77 61 72 70")),
(RefItem::Class("null".into()), "Clss", vec![]),
(RefItem::Enum("null".into(), "time".into(), "list".into()), "Enmr", hex("00 00 00 00 74 69 6d 65 00 00 00 00 6c 69 73 74")),
(RefItem::Offset("null".into(), -1), "rele", vec![255; 4]),
(RefItem::Identifier(-1), "Idnt", vec![255; 4]),
(RefItem::Index(-1), "indx", vec![255; 4]),
(RefItem::Name("null".into(), "A\0".into()), "name", hex("00 00 00 03 00 41 00 00 00 00")),
] {
let mut payload = hex("6f 62 6a 20 00 00 00 01");
payload.extend(tag.as_bytes());
payload.extend(&class);
payload.extend(tail);
check(DValue::Reference(vec![r]), payload);
}
let raw = craft_psd::descriptor::Class {
name: craft_psd::descriptor::UnicodeString(vec![0xd800, 0, 0]),
class_id: craft_psd::descriptor::Id::Str(b"warp".to_vec()),
};
for (r, tag) in [(RefItem::IdentifierWithClass(raw.clone(), 7), "Idnt"), (RefItem::IndexWithClass(raw, 7), "indx")] {
let mut payload = hex("6f 62 6a 20 00 00 00 01");
payload.extend(tag.as_bytes());
payload.extend(hex("00 00 00 03 d8 00 00 00 00 00 00 00 00 04 77 61 72 70 00 00 00 07"));
check(DValue::Reference(vec![r]), payload);
}
}
#[test]
fn borrowed_large_payload_and_duplicate_items_remain_in_order() {
let raw = vec![0x65; 1024 * 1024];
let d = Descriptor::new("null").with("same", DValue::Raw(raw)).with("same", DValue::Integer(9));
let Some((_, ValueRef::RawData(bytes))) = d.item(0) else {
panic!("raw");
};
let DValue::Raw(original) = &d.items[0].1 else {
panic!("raw");
};
assert_eq!(bytes.as_ptr(), original.as_ptr());
let mut out = vec![];
write_descriptor(&mut out, &d);
assert_eq!(&out[out.len() - 12..], &hex("73 61 6d 65 6c 6f 6e 67 00 00 00 09"));
}
#[test]
fn unicode_byte_ids_and_split_unit_tags_are_literal() {
check(DValue::Text("\u{1f600}".into()), hex("54 45 58 54 00 00 00 03 d8 3d de 00 00 00"));
check(DValue::UnitFloat("abc\u{e9}".into(), 1.0), hex("55 6e 74 46 61 62 63 c3 3f f0 00 00 00 00 00 00"));
let d = Descriptor::new("\u{e9}\u{e9}").with("\u{1f600}", DValue::Bool(false));
let mut out = vec![0xa5];
write_descriptor(&mut out, &d);
assert_eq!(out, hex("a5 00 00 00 01 00 00 00 00 00 00 c3 a9 c3 a9 00 00 00 01 00 00 00 00 f0 9f 98 80 62 6f 6f 6c 00"));
}
#[test]
fn nonempty_children_resume_each_parent_after_the_child() {
let child = || Descriptor::new("null").with("leaf", DValue::Integer(7)).with("done", DValue::Bool(true));
check(
DValue::List(vec![DValue::Descriptor(child()), DValue::ObjectArray(0x1234_5678, child()), DValue::Bool(false)]),
hex("56 6c 4c 73 00 00 00 03
4f 62 6a 63 00 00 00 01 00 00 00 00 00 00 6e 75 6c 6c 00 00 00 02
00 00 00 00 6c 65 61 66 6c 6f 6e 67 00 00 00 07
00 00 00 00 64 6f 6e 65 62 6f 6f 6c 01
4f 62 41 72 12 34 56 78 00 00 00 01 00 00 00 00 00 00 6e 75 6c 6c 00 00 00 02
00 00 00 00 6c 65 61 66 6c 6f 6e 67 00 00 00 07
00 00 00 00 64 6f 6e 65 62 6f 6f 6c 01
62 6f 6f 6c 00"),
);
}
#[test]
fn large_lists_and_unit_float_slices_are_borrowed() {
let values = DValue::List((0..65536).map(DValue::Integer).collect());
let ValueRef::List(view) = borrowed_value(&values) else { panic!("list") };
assert_eq!(view as *const dyn ValuesView as *const (), &values as *const DValue as *const ());
assert!(matches!(view.value(65535), Some(ValueRef::Integer(65535))));
assert!(view.value(65536).is_none());
let units = DValue::UnitFloats("#Pxl".into(), vec![-0.0; 65536]);
let ValueRef::UnitFloats(_, slice) = borrowed_value(&units) else { panic!("units") };
let DValue::UnitFloats(_, original) = &units else { panic!("units") };
assert_eq!(slice.as_ptr(), original.as_ptr());
let d = Descriptor::new("null").with("list", values).with("unit", units);
let mut out = vec![];
write_descriptor(&mut out, &d);
// Header18 + list key/tag/count16, 65536 scalar tag/value pairs,
// unit key/tag/unit/count20, 65536 raw doubles.
assert_eq!(out.len(), 18 + 16 + 65536 * 8 + 20 + 65536 * 8);
assert_eq!(&out[30..34], &[0, 1, 0, 0]);
assert_eq!(&out[out.len() - 8..], &[128, 0, 0, 0, 0, 0, 0, 0]);
}
}
+1
View File
@@ -2,6 +2,7 @@ use super::write::*;
use super::*;
use crate::pixels::srgb_encode;
mod descriptor_framing;
mod fixed_adjustments;
mod fixed_writers;
mod integration;
+110
View File
@@ -0,0 +1,110 @@
use super::*;
use crate::descriptor::{DValue, Descriptor};
fn hex(s: &str) -> Vec<u8> {
s.split_whitespace().map(|b| u8::from_str_radix(b, 16).unwrap()).collect()
}
fn check(block: ([u8; 4], Vec<u8>), key: [u8; 4], expected: Vec<u8>) {
assert_eq!(block.0, key);
assert_eq!(block.1, expected);
let mut doc = WDoc::new(1, 1);
doc.layers = vec![WLayer::empty("framing", vec![block])];
let bytes = write(&doc);
let file = craft_psd::PsdFile::from_bytes(&bytes).unwrap();
assert_eq!(file.layer_info.as_ref().unwrap().layers[0].block(&key).unwrap().data, expected);
}
#[test]
fn effects_data_keeps_headers_raw_bits_duplicate_keys_and_outer_framing() {
check(effects_block(&Descriptor::new("null")), *b"lfx2", hex("00 00 00 00 00 00 00 10 00 00 00 01 00 00 00 00 00 00 6e 75 6c 6c 00 00 00 00"));
let desc = Descriptor::new("null").with("same", DValue::Double(f64::from_bits(0x7ff8_1234_5678_9abc))).with("same", DValue::Text("\u{1f600}".into()));
check(
effects_block(&desc),
*b"lfx2",
hex("00 00 00 00 00 00 00 10 00 00 00 01 00 00 00 00 00 00 6e 75 6c 6c 00 00 00 02
00 00 00 00 73 61 6d 65 64 6f 75 62 7f f8 12 34 56 78 9a bc
00 00 00 00 73 61 6d 65 54 45 58 54 00 00 00 03 d8 3d de 00 00 00"),
);
}
#[test]
fn solid_color_keeps_rgb_scaling_order_and_nonfinite_policy() {
check(
solid_color_block([0.5, -0.0, f64::INFINITY]),
*b"SoCo",
hex("00 00 00 10 00 00 00 01 00 00 00 00 00 00 6e 75 6c 6c 00 00 00 01
00 00 00 00 43 6c 72 20 4f 62 6a 63
00 00 00 01 00 00 00 00 00 00 52 47 42 43 00 00 00 03
00 00 00 00 52 64 20 20 64 6f 75 62 40 5f e0 00 00 00 00 00
00 00 00 00 47 72 6e 20 64 6f 75 62 80 00 00 00 00 00 00 00
00 00 00 00 42 6c 20 20 64 6f 75 62 7f f0 00 00 00 00 00 00"),
);
}
#[test]
fn smart_object_prefix_keeps_asymmetric_raw_transform_and_optional_warp() {
let quad = [[1.0, -0.0], [2.0, f64::INFINITY], [f64::from_bits(0x7ff8_1234_5678_9abc), -3.0], [4.0, 5.0]];
// Literal descriptor wire fields; no shared writer or parser constructs the oracle.
let transform = hex("56 6c 4c 73 00 00 00 08
64 6f 75 62 3f f0 00 00 00 00 00 00
64 6f 75 62 80 00 00 00 00 00 00 00
64 6f 75 62 40 00 00 00 00 00 00 00
64 6f 75 62 7f f0 00 00 00 00 00 00
64 6f 75 62 7f f8 12 34 56 78 9a bc
64 6f 75 62 c0 08 00 00 00 00 00 00
64 6f 75 62 40 10 00 00 00 00 00 00
64 6f 75 62 40 14 00 00 00 00 00 00");
let mut expected = hex("73 6f 4c 44 00 00 00 04 00 00 00 10
00 00 00 01 00 00 00 00 00 00 6e 75 6c 6c 00 00 00 05
00 00 00 00 49 64 6e 74 54 45 58 54 00 00 00 02 00 75 00 00
00 00 00 06 70 6c 61 63 65 64 54 45 58 54 00 00 00 02 00 75 00 00
00 00 00 00 54 72 6e 66");
expected.extend_from_slice(&transform);
expected.extend(hex("00 00 00 12 6e 6f 6e 41 66 66 69 6e 65 54 72 61 6e 73 66 6f 72 6d"));
expected.extend_from_slice(&transform);
expected.extend(hex("00 00 00 00 53 7a 20 20 4f 62 6a 63
00 00 00 01 00 00 00 00 00 00 50 6e 74 20 00 00 00 02
00 00 00 00 57 64 74 68 64 6f 75 62 40 24 00 00 00 00 00 00
00 00 00 00 48 67 68 74 64 6f 75 62 40 34 00 00 00 00 00 00"));
check(smart_object_block("u", quad, [10.0, 20.0]), *b"SoLd", expected.clone());
// The optional warp is the sixth parent item, not a change to either list count.
expected[29] = 6;
expected.extend(hex("00 00 00 00 77 61 72 70 4f 62 6a 63
00 00 00 01 00 00 00 00 00 00 77 61 72 70 00 00 00 01
00 00 00 00 72 61 77 20 64 6f 75 62 ff f8 12 34 56 78 9a bc"));
let warp = Descriptor::new("warp").with("raw ", DValue::Double(f64::from_bits(0xfff8_1234_5678_9abc)));
check(smart_object_block_warped("u", quad, [10.0, 20.0], Some(warp)), *b"SoLd", expected);
}
#[test]
fn type_layer_framing_keeps_raw_origin_and_distinct_text_policies() {
let block = text_block("A\r\nB\n\u{1f600}", [-0.0, f64::from_bits(0x7ff8_1234_5678_9abc)], "Test", 12.0, [1.0, 0.5, 0.0], 2);
assert_eq!(block.0, *b"TySh");
// Independent header and descriptor-field bytes; CRLF deliberately becomes CRCR.
let prefix = hex("00 01
3f f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 3f f0 00 00 00 00 00 00
80 00 00 00 00 00 00 00 7f f8 12 34 56 78 9a bc
00 32 00 00 00 10
00 00 00 01 00 00 00 00 00 00 54 78 4c 72 00 00 00 04
00 00 00 00 54 78 74 20 54 45 58 54 00 00 00 08 00 41 00 0d 00 0d 00 42 00 0d d8 3d de 00 00 00
00 00 00 0c 74 65 78 74 47 72 69 64 64 69 6e 67
65 6e 75 6d 00 00 00 0c 74 65 78 74 47 72 69 64 64 69 6e 67 00 00 00 00 4e 6f 6e 65
00 00 00 00 4f 72 6e 74 65 6e 75 6d 00 00 00 00 4f 72 6e 74 00 00 00 00 48 72 7a 6e
00 00 00 0a 45 6e 67 69 6e 65 44 61 74 61 74 64 74 61");
assert!(block.1.starts_with(&prefix));
let raw_len = u32::from_be_bytes(block.1[prefix.len()..prefix.len() + 4].try_into().unwrap()) as usize;
let raw_start = prefix.len() + 4;
let raw_end = raw_start + raw_len;
// EngineData is opaque to the framing helper; independently assert its original text,
// including LF rather than the Txt field's CR replacement. This is not an EngineData golden.
let engine = craft_psd::engine_data::parse(&block.1[raw_start..raw_end]).unwrap();
assert_eq!(engine.path(&["EngineDict", "Editor", "Text"]).and_then(craft_psd::engine_data::Value::as_str), Some("A\r\nB\n\u{1f600}\r"));
assert_eq!(
&block.1[raw_end..],
&hex("00 01 00 00 00 10
00 00 00 01 00 00 00 00 00 00 77 61 72 70 00 00 00 01
00 00 00 09 77 61 72 70 53 74 79 6c 65 65 6e 75 6d
00 00 00 09 77 61 72 70 53 74 79 6c 65 00 00 00 08 77 61 72 70 4e 6f 6e 65
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00")
);
let expected_payload = block.1.clone();
check(block, *b"TySh", expected_payload);
}
+7 -24
View File
@@ -10,7 +10,7 @@ use craft_psd::{
BlendMode, BlendingRanges, ChannelData, Compression, GlobalLayerMask, Header, ImageData, LayerFlags, LayerInfoPlacement, MaskData, PsdFile, Version,
};
use crate::descriptor::{self, DValue, Descriptor, put_u16, put_u32, put_utf16};
use crate::descriptor::{DValue, Descriptor, put_u16, put_u32, put_utf16};
use crate::limits::finite_sample;
use crate::{ColorMode, Rect, Section, engine_data};
@@ -383,52 +383,35 @@ pub fn smart_object_block_warped(uuid: &str, quad: [[f64; 2]; 4], size: [f64; 2]
if let Some(w) = warp {
d = d.with("warp", DValue::Descriptor(w));
}
let mut out = b"soLD".to_vec();
put_u32(&mut out, 4);
put_u32(&mut out, 16);
descriptor::write_descriptor(&mut out, &d);
let mut out = vec![];
craft_psd::tagged::append_smart_object_data(&mut out, &d);
(*b"SoLd", out)
}
/// `TySh`: a type layer with one style run; the text origin sits at `origin`.
pub fn text_block(text: &str, origin: [f64; 2], font: &str, size: f64, color: [f64; 3], justification: u8) -> ([u8; 4], Vec<u8>) {
let mut d = vec![];
put_u16(&mut d, 1);
for v in [1.0, 0.0, 0.0, 1.0, origin[0], origin[1]] {
d.extend_from_slice(&f64::to_be_bytes(v));
}
put_u16(&mut d, 50);
put_u32(&mut d, 16);
let desc = Descriptor::new("TxLr")
.with("Txt ", DValue::Text(text.replace('\n', "\r")))
.with("textGridding", DValue::Enum("textGridding".into(), "None".into()))
.with("Ornt", DValue::Enum("Ornt".into(), "Hrzn".into()))
.with("EngineData", DValue::Raw(engine_data::minimal(text, font, size, color, justification)));
descriptor::write_descriptor(&mut d, &desc);
// Warp: version, descriptor version, an empty warp descriptor.
put_u16(&mut d, 1);
put_u32(&mut d, 16);
descriptor::write_descriptor(&mut d, &Descriptor::new("warp").with("warpStyle", DValue::Enum("warpStyle".into(), "warpNone".into())));
for _ in 0..4 {
put_u32(&mut d, 0);
}
let warp = Descriptor::new("warp").with("warpStyle", DValue::Enum("warpStyle".into(), "warpNone".into()));
craft_psd::text::append_type_layer_data_with_zero_bounds(&mut d, &[1.0, 0.0, 0.0, 1.0, origin[0], origin[1]], &desc, &warp);
(*b"TySh", d)
}
/// `lfx2`: layer effects from an effects descriptor (`null` class with `DrSh`, `FrFX`…).
pub fn effects_block(desc: &Descriptor) -> ([u8; 4], Vec<u8>) {
let mut d = vec![];
put_u32(&mut d, 0);
put_u32(&mut d, 16);
descriptor::write_descriptor(&mut d, desc);
craft_psd::tagged::append_layer_effects_data(&mut d, desc);
(*b"lfx2", d)
}
/// `SoCo`: solid colour fill.
pub fn solid_color_block(rgb: [f64; 3]) -> ([u8; 4], Vec<u8>) {
let mut d = vec![];
put_u32(&mut d, 16);
descriptor::write_descriptor(&mut d, &Descriptor::new("null").with("Clr ", DValue::Descriptor(Descriptor::rgb(rgb))));
craft_psd::tagged::append_solid_color_data(&mut d, &Descriptor::new("null").with("Clr ", DValue::Descriptor(Descriptor::rgb(rgb))));
(*b"SoCo", d)
}
+1331 -1610
View File
File diff suppressed because it is too large. Load diff