Merge upstream/main into cache-defaults-3298

This commit is contained in:
vangel76 committed 2026-11-12 12:36:34 +01:00
commit dcd46af227
155 files changed
+6214 -17309

No files matched your search

+2
View File
@@ -133,7 +133,9 @@ configuration from these Apache-2.0 projects:
| Asset | Author | Source | Licence |
|---|---|---|---|
| `crates/engine/src/tests/fixtures/analysed-0.24.ecproj` | arnav-hiwarkar | Original work, synthetic project keyed by EffectCraft 0.24.1 | MIT OR Apache-2.0 |
| `crates/engine/src/tests/fixtures/object-matte-0.22.ecproj` | lisn0 | Original work, synthetic project saved by EffectCraft 0.22.0 | MIT OR Apache-2.0 |
| `crates/engine/src/tests/fixtures/tracked-0.22.ecproj` | arnav-hiwarkar | Original work, synthetic project saved by EffectCraft 0.22.0 | MIT OR Apache-2.0 |
## First-party brand marks
Generated
+48 -54
View File
@@ -1089,15 +1089,24 @@ dependencies = [
"libc",
]
[[package]]
name = "craft-audio"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4#e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4"
dependencies = [
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4)",
"thiserror 2.0.21",
]
[[package]]
name = "craft-docpath"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545#e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545"
source = "git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4#e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4"
[[package]]
name = "craft-ecproj-format"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ca1b5e2edb8568335c6c14f390307bd5beae8238#ca1b5e2edb8568335c6c14f390307bd5beae8238"
source = "git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4#e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4"
dependencies = [
"serde",
"serde_json",
@@ -1107,12 +1116,12 @@ dependencies = [
[[package]]
name = "craft-fonts-build"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545#e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545"
source = "git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4#e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4"
[[package]]
name = "craft-i18n"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545#e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545"
source = "git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4#e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4"
dependencies = [
"fixed_decimal",
"icu_decimal",
@@ -1132,6 +1141,14 @@ dependencies = [
"writeable",
]
[[package]]
name = "craft-media"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4#e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4"
dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-media"
version = "0.1.0"
@@ -1143,7 +1160,7 @@ dependencies = [
[[package]]
name = "craft-pdf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545#e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545"
source = "git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4#e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4"
dependencies = [
"hayro-syntax",
"thiserror 2.0.21",
@@ -1152,7 +1169,7 @@ dependencies = [
[[package]]
name = "craft-quit"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545#e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545"
source = "git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4#e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4"
dependencies = [
"dispatch2",
"egui",
@@ -1163,7 +1180,7 @@ dependencies = [
[[package]]
name = "craft-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545#e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545"
source = "git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4#e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4"
dependencies = [
"craft-fonts-build",
"craft-i18n",
@@ -1184,7 +1201,7 @@ dependencies = [
[[package]]
name = "craft-update"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
source = "git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4#e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4"
dependencies = [
"chrono",
"dunce",
@@ -1208,6 +1225,16 @@ dependencies = [
"zip 9.1.3",
]
[[package]]
name = "craft-video"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4#e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4"
dependencies = [
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4)",
"rayon",
"thiserror 2.0.21",
]
[[package]]
name = "crc32fast"
version = "1.5.2"
@@ -1475,14 +1502,6 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "effectcraft-av1enc"
version = "0.24.1"
dependencies = [
"filmcraft-av1",
"tempfile",
]
[[package]]
name = "effectcraft-cli"
version = "0.24.1"
@@ -1572,10 +1591,11 @@ dependencies = [
name = "effectcraft-export"
version = "0.24.1"
dependencies = [
"effectcraft-av1enc",
"craft-audio",
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4)",
"craft-video",
"effectcraft-color",
"effectcraft-effects",
"effectcraft-hevcenc",
"effectcraft-keyframe",
"effectcraft-media",
"effectcraft-opusenc",
@@ -1583,13 +1603,9 @@ dependencies = [
"effectcraft-raster",
"effectcraft-render",
"effectcraft-time",
"effectcraft-vp9enc",
"exr",
"filmcraft-aac",
"filmcraft-h264enc",
"filmcraft-isobmff",
"filmcraft-opus",
"filmcraft-prores",
"filmcraft-av1",
"filmcraft-hevc",
"filmcraft-vp9",
"gif",
"image",
@@ -1659,13 +1675,6 @@ dependencies = [
"serde_json",
]
[[package]]
name = "effectcraft-hevcenc"
version = "0.24.1"
dependencies = [
"filmcraft-hevc",
]
[[package]]
name = "effectcraft-host"
version = "0.24.1"
@@ -1746,7 +1755,9 @@ dependencies = [
name = "effectcraft-media"
version = "0.24.1"
dependencies = [
"craft-audio",
"craft-docpath",
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4)",
"effectcraft-color",
"effectcraft-effects",
"effectcraft-model",
@@ -1758,12 +1769,9 @@ dependencies = [
"effectcraft-svg",
"effectcraft-time",
"exr",
"filmcraft-aac",
"filmcraft-codecs",
"filmcraft-color",
"filmcraft-frame",
"filmcraft-isobmff",
"filmcraft-matroska",
"filmcraft-media",
"filmcraft-mpegts",
"filmcraft-time",
@@ -1794,7 +1802,7 @@ dependencies = [
name = "effectcraft-opusenc"
version = "0.24.1"
dependencies = [
"filmcraft-opus",
"craft-audio",
]
[[package]]
@@ -2020,10 +2028,6 @@ dependencies = [
"web-time",
]
[[package]]
name = "effectcraft-vp9enc"
version = "0.24.1"
[[package]]
name = "effectcraft-web"
version = "0.24.1"
@@ -2491,7 +2495,7 @@ name = "filmcraft-bitstream"
version = "0.12.0"
source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5"
dependencies = [
"craft-media",
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f0ad6c1e1d297908915f4be315b0fcfc9be7b5d4)",
]
[[package]]
@@ -2592,16 +2596,6 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "filmcraft-h264enc"
version = "0.12.0"
source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5"
dependencies = [
"filmcraft-bitstream",
"rayon",
"thiserror 2.0.21",
]
[[package]]
name = "filmcraft-hevc"
version = "0.12.0"
@@ -2634,7 +2628,7 @@ name = "filmcraft-isobmff"
version = "0.12.0"
source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5"
dependencies = [
"craft-media",
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f0ad6c1e1d297908915f4be315b0fcfc9be7b5d4)",
]
[[package]]
@@ -2642,7 +2636,7 @@ name = "filmcraft-matroska"
version = "0.12.0"
source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5"
dependencies = [
"craft-media",
"craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f0ad6c1e1d297908915f4be315b0fcfc9be7b5d4)",
]
[[package]]
@@ -3331,7 +3325,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
[[package]]
name = "hayro-jbig2"
version = "0.3.0"
source = "git+https://github.com/storytold/craft-libs?rev=e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545#e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545"
source = "git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4#e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4"
dependencies = [
"hayro-ccitt",
]
@@ -3345,7 +3339,7 @@ checksum = "c75ab947623ef4ccaa7acf0579edf7cbb5a73838e3839a7be73335e522f433a1"
[[package]]
name = "hayro-syntax"
version = "0.7.2"
source = "git+https://github.com/storytold/craft-libs?rev=e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545#e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545"
source = "git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4#e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4"
dependencies = [
"hayro-jbig2",
"hayro-jpeg2000",
+21 -42
View File
@@ -11,12 +11,12 @@ rust-version = "1.95"
repository = "https://github.com/storytold/effectcraft"
[workspace.dependencies]
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545", version = "=0.1.0", default-features = false, features = ["read"] }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" }
craft-quit = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" }
craft-ecproj-format = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "ca1b5e2edb8568335c6c14f390307bd5beae8238" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4", version = "=0.1.0", default-features = false, features = ["read"] }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4" }
craft-quit = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4" }
craft-ecproj-format = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4" }
# craft-update: app-specific pretend versions apply to startup and manual checks.
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4", features = ["egui"] }
# internal
effectcraft-time = { path = "crates/time" }
effectcraft-geom = { path = "crates/geom" }
@@ -41,7 +41,6 @@ effectcraft-interchange = { path = "crates/interchange" }
effectcraft-pdf = { path = "crates/pdf" }
effectcraft-psd = { path = "crates/psd" }
effectcraft-aep = { path = "crates/aep" }
effectcraft-vp9enc = { path = "crates/vp9enc" }
effectcraft-svg = { path = "crates/svg" }
effectcraft-engine = { path = "crates/engine" }
effectcraft-host = { path = "crates/host" }
@@ -49,8 +48,6 @@ effectcraft-ui-egui = { path = "crates/ui-egui" }
effectcraft-automation = { path = "crates/automation" }
effectcraft-opusenc = { path = "crates/opusenc" }
effectcraft-script = { path = "crates/script" }
effectcraft-hevcenc = { path = "crates/hevcenc" }
effectcraft-av1enc = { path = "crates/av1enc" }
effectcraft-plugin = { path = "crates/plugin" }
effectcraft-helper-host = { path = "crates/helper-host" }
@@ -84,25 +81,23 @@ image = { version = "0.25", default-features = false, features = ["png", "jpeg"]
same-file = "1.0"
tempfile = "3.27"
# media codecs + containers: FilmCraft's pure-Rust crates, pinned to a revision (plan/adr/0001).
# 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 = "e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4", default-features = false, features = ["isobmff", "matroska"] }
craft-audio = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4", default-features = false, features = ["aac-decode", "aac-encode", "opus-decode"] }
craft-video = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4", features = ["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.
filmcraft-codecs = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" }
filmcraft-media = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" }
filmcraft-frame = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" }
filmcraft-color = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" }
filmcraft-time = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" }
# encoders + muxer (crates/export)
filmcraft-h264enc = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" }
filmcraft-prores = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" }
filmcraft-aac = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" }
filmcraft-isobmff = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" }
# container headers read for AAC channel layouts (crates/media)
filmcraft-matroska = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" }
# MPEG TS / PS headers read for AAC channel layouts (crates/media); craft-media has no MPEG TS reader
filmcraft-mpegts = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" }
# decoder used as the round-trip oracle of effectcraft-opusenc (crates/export dev-dependency)
filmcraft-opus = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" }
# decoders used as the round-trip oracles of craft-video's VP9, HEVC and AV1 encoders (crates/export
# dev-dependencies only); craft-video has no decoder for them
filmcraft-vp9 = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" }
# decoders used as the round-trip oracles of effectcraft-hevcenc / effectcraft-av1enc (dev-dependencies only)
filmcraft-hevc = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" }
filmcraft-av1 = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" }
# timeline interchange (EDL, FCP7 XML, FCPXML, OTIO) for Premiere Pro interop (crates/interchange only)
@@ -119,7 +114,7 @@ half = "2.7"
# ui
# Shared frontend components; keep this dependency above the engine boundary.
# Shared UI and the complete egui family select reviewed immutable commits below.
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545", features = ["serde"] }
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4", features = ["serde"] }
# `default_fonts` and `monochrome_emoji_fonts` are explicit: the app's `FontDefinitions::default()`
# and its `✔`/`▣` chrome glyphs need both, and kittest's own dev-dependencies do not propagate.
egui = { version = "0.37", default-features = false, features = ["default_fonts", "monochrome_emoji_fonts"] }
@@ -139,11 +134,6 @@ sys-locale = "0.3"
# filmcraft-frame = { path = "../filmcraft/crates/frame" }
# filmcraft-color = { path = "../filmcraft/crates/color" }
# filmcraft-time = { path = "../filmcraft/crates/time" }
# filmcraft-h264enc = { path = "../filmcraft/crates/h264enc" }
# filmcraft-prores = { path = "../filmcraft/crates/prores" }
# filmcraft-aac = { path = "../filmcraft/crates/aac" }
# filmcraft-isobmff = { path = "../filmcraft/crates/isobmff" }
# filmcraft-matroska = { path = "../filmcraft/crates/matroska" }
# filmcraft-mpegts = { path = "../filmcraft/crates/mpegts" }
[workspace.lints.rust]
@@ -202,50 +192,39 @@ opt-level = 3
[profile.dev.package.effectcraft-export]
opt-level = 3
[profile.dev.package.effectcraft-vp9enc]
# craft-libs codec hot loops.
[profile.dev.package.craft-video]
opt-level = 3
[profile.dev.package.effectcraft-hevcenc]
[profile.dev.package.craft-audio]
opt-level = 3
[profile.dev.package.effectcraft-av1enc]
[profile.dev.package.craft-media]
opt-level = 3
# FilmCraft codec hot loops (same settings as FilmCraft's own workspace).
[profile.dev.package.filmcraft-h264]
opt-level = 3
[profile.dev.package.filmcraft-h264enc]
opt-level = 3
[profile.dev.package.filmcraft-hevc]
opt-level = 3
[profile.dev.package.filmcraft-vp9]
opt-level = 3
[profile.dev.package.filmcraft-prores]
opt-level = 3
[profile.dev.package.filmcraft-dnx]
opt-level = 3
[profile.dev.package.filmcraft-av1]
opt-level = 3
[profile.dev.package.filmcraft-aac]
opt-level = 3
[profile.dev.package.filmcraft-opus]
opt-level = 3
[profile.release]
lto = "thin"
codegen-units = 1
[patch.crates-io]
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545", version = "=0.7.2" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545", version = "=0.3.0" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4", version = "=0.7.2" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4", version = "=0.3.0" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
+1 -1
View File
@@ -156,7 +156,7 @@ MP4, **WebM** (VP9 with inter frames and alpha, or AV1; Opus audio), PNG, JPEG,
rendering with 3:2 pulldown, effect/solo/guide/depth overrides, crop, region of interest and
resize, Render Settings and Output Module templates with defaults, post-render actions, storage
overflow and render logs. The same queue runs from the command line. Every encoder is pure
Rust (FilmCraft's H.264, ProRes and AAC; EffectCraft's own VP9, AV1, HEVC and Opus); there is no
Rust (craft-libs' H.264, ProRes, HEVC, VP9, AV1 and AAC; EffectCraft's own Opus); there is no
FFmpeg inside.
**Lottie** goes both ways: File ▸ Export ▸ Lottie JSON… writes a composition (precomps, shape,
+1 -1
View File
@@ -44,7 +44,7 @@ pub use camera::{CameraPosition, DEFAULT_CAMERA_ZOOM};
pub use chunk::{AepFile, Body, Chunk, LIST, NESTED_IDS, Walk};
pub use effects::{DefinitionSource, Effect, EffectDefinitions, EffectParam, LayerRef, ParamKind, ParamValue};
pub use error::AepError;
pub use footage::{Footage, SequenceInfo};
pub use footage::{Footage, PsdLayer, SequenceInfo};
pub use header::{BlendMode, CompHeader, LayerHeader, LayerType, LightType, Quality, Rational, Renderer};
pub use keys::{ExpressionFlags, Interpolation, KeyEase, KeyframeKind, SpatialKey};
pub use masks::{Mask, MaskAtom, MaskMode, PathVertex, ShapePath};
+95 -2
View File
@@ -1,7 +1,7 @@
//! Item ids and labels, footage items (solids and files), precomp linkage, and the name and size
//! of a layer's source.
use crate::container::bytes::{be_f32, be_f64, be_u32, cstr, le_u32, text};
use crate::container::bytes::{be_f32, be_f64, be_i32, be_u32, cstr, le_u32, text, until_nul};
use crate::container::chunk::Chunk;
use crate::container::header::Rational;
use crate::container::typed::{Item, ItemKind, Layer, Project};
@@ -45,6 +45,59 @@ pub struct Footage {
/// True when the alias points at a folder (`"target_is_folder":true`): an image sequence is ONE
/// item whose alias is its folder and whose `opti` holds the first file name.
pub is_sequence: bool,
/// The one layer of a Photoshop file the item shows; `None` for the merged image and for
/// any other footage.
pub psd_layer: Option<PsdLayer>,
}
/// One layer of a Photoshop file shown by a footage item, from its `opti` (tag `8BPS`,
/// docs/aep-format.md 3.3): the layer record's index as a big-endian `i32` at byte 14 (-1 for the
/// merged image), the document's sides as little-endian `u32` at 32 and 36, its bounds top, left,
/// bottom, right as little-endian `i32` at 78, 82, 86 and 90, and its name (UTF-8, NUL
/// terminated) from byte 344.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PsdLayer {
/// The layer record's position in the file (bottom of the stack = 0).
pub index: u32,
pub name: String,
/// Top, left, bottom, right in document pixels; all 0 for a layer without pixels (an
/// adjustment layer).
pub bounds: [i32; 4],
/// The document's two sides (bytes 32 and 36; which one is the width is not sampled: the one
/// file read has a square document). 0 when not stored.
pub document: [u32; 2],
}
/// Most bytes of a Photoshop layer name read.
const MAX_NAME: usize = 1024;
impl PsdLayer {
/// The bounds' width and height; `None` when they are empty.
pub fn size(&self) -> Option<(u32, u32)> {
let [top, left, bottom, right] = self.bounds;
let w = u32::try_from(i64::from(right) - i64::from(left)).ok().filter(|w| *w > 0)?;
let h = u32::try_from(i64::from(bottom) - i64::from(top)).ok().filter(|h| *h > 0)?;
Some((w, h))
}
/// Whether the document is `size` big, its sides in either order.
pub fn document_is(&self, size: (u32, u32)) -> bool {
let [a, b] = self.document;
a > 0 && b > 0 && ((a, b) == size || (b, a) == size)
}
/// The layer an `opti` names; `None` for another tag, the merged image or a cut record.
fn read(opti: &[u8]) -> Option<Self> {
if opti.get(..4) != Some(&b"8BPS"[..]) {
return None;
}
let index = u32::try_from(be_i32(opti, 14)?).ok()?;
let le_i32 = |at| le_u32(opti, at).map(|v| i32::from_le_bytes(v.to_le_bytes()));
// (After Effects writes 602 bytes; a longer hostile name is cut.)
let name = opti.get(344..).map(|b| text(until_nul(b.get(..MAX_NAME).unwrap_or(b)))).unwrap_or_default();
let document = [le_u32(opti, 32).unwrap_or(0), le_u32(opti, 36).unwrap_or(0)];
Some(Self { index, name, bounds: [le_i32(78)?, le_i32(82)?, le_i32(86)?, le_i32(90)?], document })
}
}
impl Footage {
@@ -330,6 +383,7 @@ impl<'f, 'a> Item<'f, 'a> {
file_size: be_u32(sspc, 208).unwrap_or(0),
audio_sample_rate: be_f64(sspc, 160).filter(|r| r.is_finite() && *r > 0.0),
is_sequence,
psd_layer: PsdLayer::read(opti),
})
}
@@ -370,7 +424,46 @@ impl<'f, 'a> Project<'f, 'a> {
#[cfg(test)]
mod tests {
use super::json_string;
use super::{PsdLayer, json_string};
/// A 602-byte Photoshop `opti` naming layer `index` with `bounds` and `name`.
fn opti(index: i32, bounds: [i32; 4], name: &[u8]) -> Vec<u8> {
let mut b = vec![0u8; 602];
b[..4].copy_from_slice(b"8BPS");
b[14..18].copy_from_slice(&index.to_be_bytes());
for (i, v) in bounds.iter().enumerate() {
b[78 + 4 * i..82 + 4 * i].copy_from_slice(&v.to_le_bytes());
}
b[344..344 + name.len()].copy_from_slice(name);
b
}
#[test]
fn a_photoshop_layer_reads_its_index_bounds_and_name() {
let l = PsdLayer::read(&opti(7, [749, 800, 764, 848], "tést".as_bytes())).unwrap();
assert_eq!((l.index, l.name.as_str(), l.bounds, l.size()), (7, "tést", [749, 800, 764, 848], Some((48, 15))));
// The merged image, another tag, a cut record: no layer.
assert_eq!(PsdLayer::read(&opti(-1, [0; 4], b"x")), None);
let mut other = opti(1, [0; 4], b"x");
other[..4].copy_from_slice(b"Soli");
assert_eq!(PsdLayer::read(&other), None);
assert_eq!(PsdLayer::read(&opti(1, [0; 4], b"x")[..80]), None);
// A cut name, and no name at all.
assert_eq!(PsdLayer::read(&opti(1, [0; 4], b"x")[..345]).unwrap().name, "x");
assert_eq!(PsdLayer::read(&opti(1, [0; 4], b"x")[..300]).unwrap().name, "");
// A layer without pixels has no size; extreme bounds do not overflow.
assert_eq!(PsdLayer::read(&opti(2, [0; 4], b"")).unwrap().size(), None);
assert_eq!(PsdLayer::read(&opti(2, [i32::MIN, i32::MIN, i32::MAX, i32::MAX], b"")).unwrap().size(), Some((u32::MAX, u32::MAX)));
assert_eq!(PsdLayer::read(&opti(2, [i32::MAX, 0, i32::MIN, 1], b"")).unwrap().size(), None);
// The document's size, its sides in either order; none when not stored.
let mut doc = opti(0, [0, 0, 1000, 800], b"");
doc[32..36].copy_from_slice(&800u32.to_le_bytes());
doc[36..40].copy_from_slice(&1000u32.to_le_bytes());
let l = PsdLayer::read(&doc).unwrap();
assert_eq!(l.document, [800, 1000]);
assert!(l.document_is((800, 1000)) && l.document_is((1000, 800)) && !l.document_is((800, 800)));
assert!(!PsdLayer::read(&opti(0, [0; 4], b"")).unwrap().document_is((0, 0)));
}
#[test]
fn reads_a_string_with_escapes() {
+3 -1
View File
@@ -14,7 +14,8 @@
//! missing-footage placeholders). `docs/aep-import.md` has the full list.
//!
//! What does not arrive is **reported**, never dropped silently: [`ImportReport`] counts other
//! effects (by match name) and unimported effect parameters, unusable masks, layer style
//! effects (by match name; they arrive as placeholders that render nothing, with their parameters
//! for expressions) and unimported effect parameters, unusable masks, layer style
//! features, text layer features, shape items, unsupported blend modes and transform
//! properties, simplified keyframes and unreadable data per [`LossCategory`]. By default the import
//! is refused when anything would be lost ([`ImportOptions::allow_losses`] lifts that); a refusal
@@ -30,6 +31,7 @@ mod effects;
mod lumetri;
mod markers;
mod masks;
mod placeholder;
mod props;
mod puppet;
mod report;
+42 -2
View File
@@ -12,7 +12,8 @@ use effectcraft_color::{BlendMode, Label};
use effectcraft_keyframe::Value;
use effectcraft_project::build::{self, Ids};
use effectcraft_project::{
AutoOrient, Comp, Footage, FootageKind, ItemId, ItemKind, Layer, LayerId, LayerSource, LightKind, MatteKind, Project, Quality, Solid, TrackMatte,
AutoOrient, Comp, Footage, FootageKind, ItemId, ItemKind, Layer, LayerId, LayerSource, LightKind, MatteKind, Project, Quality, Solid, SourceLayer,
TrackMatte,
};
use effectcraft_time::Tick;
@@ -216,7 +217,17 @@ fn import_footage(project: &mut Project, cx: &mut Ctx<'_>, item: &AepItem<'_, '_
let aep_id = item.id();
// An item without a stored name shows its file's name, a sequence `shot_[0101-0103].exr`
// (126, 603-607).
let name = if name.is_empty() { default_footage_name(item, &f).unwrap_or_else(|| "Footage".to_string()) } else { name };
// One layer of a Photoshop file is `<layer>/<file>`, as EffectCraft's own Photoshop import
// names it (#3087).
let name = if name.is_empty() {
let file = default_footage_name(item, &f).unwrap_or_else(|| "Footage".to_string());
match &f.psd_layer {
Some(l) if !l.name.is_empty() => format!("{}/{file}", l.name),
_ => file,
}
} else {
name
};
if f.is_solid {
// A null object's placeholder solid is not an item here.
if aep_id.is_some_and(|i| null_only.contains(&i)) {
@@ -299,6 +310,7 @@ fn import_footage(project: &mut Project, cx: &mut Ctx<'_>, item: &AepItem<'_, '_
missing: !present,
placed_page,
sequence,
layer: source_layer(&f, &name, &mut cx.col),
..Footage::default()
};
// The native frame rate and the stored duration of sequences and clips (352, 603, 606).
@@ -338,6 +350,34 @@ fn is_placed_page_path(path: &str) -> bool {
matches!(ext.as_deref(), Some("pdf" | "ai"))
}
/// The Photoshop layer a footage item shows (#3087): at its own bounds when the item is as big
/// as they are (Retain Layer Sizes), else on the document. A layer without pixels (an adjustment
/// layer) keeps the merged image and is reported. So is a layer as big as the document but not at
/// its corner (the item's size fits both framings; its bounds are used), and an item as big as
/// neither (the document is used).
fn source_layer(f: &crate::Footage, name: &str, col: &mut Collector) -> Option<SourceLayer> {
let l = f.psd_layer.as_ref()?;
let Some(size) = l.size() else {
col.lose(LossCategory::UnsupportedItems, format!("footage '{name}': a Photoshop layer without pixels (an adjustment layer), the merged image used"));
return None;
};
let layer_size = size == (f.width, f.height);
if !layer_size && l.document.iter().all(|side| *side > 0) && !l.document_is((f.width, f.height)) {
col.lose(
LossCategory::UnsupportedItems,
format!("footage '{name}': {} x {} is neither the Photoshop layer's size nor the document's, shown on the document", f.width, f.height),
);
}
let [top, left, ..] = l.bounds;
if layer_size && (top, left) != (0, 0) && l.document_is(size) {
col.lose(
LossCategory::UnsupportedItems,
format!("footage '{name}': a Photoshop layer as big as the document but at ({left}, {top}), shown at its own bounds (Retain Layer Sizes assumed)"),
);
}
Some(SourceLayer { index: l.index, name: l.name.clone(), layer_size, ..SourceLayer::default() })
}
/// The name After Effects shows for a footage item that stores none: the file's name, or for a
/// sequence the name with the frame range (`shot_[0101-0103].exr`).
fn default_footage_name(item: &AepItem<'_, '_>, f: &crate::Footage) -> Option<String> {
+55 -38
View File
@@ -1,7 +1,8 @@
//! Effects: a table maps an After Effects effect (its match name) and its parameters (by their
//! index in `parT`) to an EffectCraft effect, a parameter id and a unit conversion. Effects and
//! parameters outside the table are reported in [`LossCategory::Effects`] by match name, never
//! dropped silently.
//! index in `parT`) to an EffectCraft effect, a parameter id and a unit conversion. Parameters
//! outside the table are reported in [`LossCategory::Effects`] by match name, never dropped
//! silently. An effect outside it arrives as a placeholder holding its parameters (`placeholder.rs`)
//! and is reported too.
//!
//! Every conversion is backed by the corpus (`docs/aep-format.md` 3.7, cases 356-450, 511-516):
//!
@@ -82,44 +83,37 @@ pub(crate) fn import_effects<'f, 'a>(
continue;
}
let shown = fx.display_name().unwrap_or_else(|| fx.match_name().to_string());
let Some(map) = EFFECTS.iter().find(|m| m.match_name == fx.match_name()) else {
col.lose_unmapped_effect(fx.match_name(), format!("{}: '{}' has the effect '{shown}' ({})", cx.comp, cx.layer, fx.match_name()));
continue;
};
let Some(spec) = effectcraft_effects::find(map.effect) else {
col.lose_unmapped_effect(fx.match_name(), format!("{}: '{}' has the effect '{shown}' ({})", cx.comp, cx.layer, fx.match_name()));
continue;
};
let found = EFFECTS.iter().find(|m| m.match_name == fx.match_name()).and_then(|m| Some((m, effectcraft_effects::find(m.effect)?)));
let lost = format!("{}: '{}' has the effect '{shown}' ({})", cx.comp, cx.layer, fx.match_name());
if defs.source(&fx) == DefinitionSource::Missing {
col.lose(
LossCategory::Effects,
format!("{}: '{}' has the effect '{shown}' ({}) without readable parameter definitions, not imported", cx.comp, cx.layer, fx.match_name()),
);
match found {
Some(_) => col.lose(LossCategory::Effects, format!("{lost} without readable parameter definitions, not imported")),
None => col.lose_unmapped_effect(fx.match_name(), lost),
}
continue;
}
let size = [f64::from(cx.size.0), f64::from(cx.size.1)];
let mut group = effectcraft_effects::instantiate(spec, ids, &shown, size);
match fx.enabled() {
Some(on) => group.enabled = on,
None => col.lose(LossCategory::DamagedData, format!("{}: '{}': the fx switch of '{shown}' is unreadable, imported switched on", cx.comp, cx.layer)),
if found.is_none() && col.placeholder_cost >= crate::import::placeholder::MAX_COST {
// The import's placeholder budget is spent: the definitions (shared by many instances)
// are not read again. Named like any effect without a counterpart, in a group of its
// own (with the kept instances it would read as kept).
let key = format!("{} (not kept)", fx.match_name());
col.lose_unmapped_effect(&key, format!("{lost}, not kept (past the import's placeholder parameters)"));
continue;
}
let params = defs.params(&fx);
// Borrowed definitions (another instance's or the project copy) may not name every value
// record this instance has: such a record has nothing to import into, so it is reported.
if params.first().is_some_and(|p| p.borrowed_definition) {
let defined: std::collections::HashSet<&str> = params.iter().map(|p| p.match_name.as_str()).collect();
for name in fx.value_record_names().iter().filter(|n| !defined.contains(n.as_str())) {
col.lose(
LossCategory::Effects,
format!(
"{}: '{}' effect '{shown}' ({}): the value record {name} has no parameter definition, not imported",
cx.comp,
cx.layer,
fx.match_name()
),
);
}
}
report_records_without_definition(&fx, &params, cx, &shown, col);
let Some((map, spec)) = found else {
// No counterpart: kept as a placeholder that renders nothing, for expressions (#3087).
let mut group = crate::import::placeholder::placeholder(&fx, &params, cx, &shown, ids, refs, col);
set_enabled(&fx, &mut group, cx, &shown, col);
col.lose_unmapped_effect(fx.match_name(), format!("{lost}, kept without rendering"));
col.imported.placeholder_effects = col.imported.placeholder_effects.saturating_add(1);
target.children.push(Node::Group(group));
continue;
};
let size = [f64::from(cx.size.0), f64::from(cx.size.1)];
let mut group = effectcraft_effects::instantiate(spec, ids, &shown, size);
set_enabled(&fx, &mut group, cx, &shown, col);
if map.extra == Extra::Lumetri {
crate::import::lumetri::import_lumetri(&fx, &params, cx, &shown, ParamOut { group: &mut group, refs: &mut *refs, col: &mut *col });
} else if map.extra == Extra::Cryptomatte {
@@ -143,6 +137,29 @@ pub(crate) fn import_effects<'f, 'a>(
}
}
/// The effect's fx switch.
fn set_enabled(fx: &AepEffect<'_, '_>, group: &mut PropGroup, cx: &LayerCtx<'_>, shown: &str, col: &mut Collector) {
match fx.enabled() {
Some(on) => group.enabled = on,
None => col.lose(LossCategory::DamagedData, format!("{}: '{}': the fx switch of '{shown}' is unreadable, imported switched on", cx.comp, cx.layer)),
}
}
/// Borrowed definitions (another instance's or the project copy) may not name every value record
/// this instance has: such a record has nothing to import into, so it is reported.
fn report_records_without_definition(fx: &AepEffect<'_, '_>, params: &[EffectParam<'_, '_>], cx: &LayerCtx<'_>, shown: &str, col: &mut Collector) {
if !params.first().is_some_and(|p| p.borrowed_definition) {
return;
}
let defined: std::collections::HashSet<&str> = params.iter().map(|p| p.match_name.as_str()).collect();
for name in fx.value_record_names().iter().filter(|n| !defined.contains(n.as_str())) {
col.lose(
LossCategory::Effects,
format!("{}: '{}' effect '{shown}' ({}): the value record {name} has no parameter definition, not imported", cx.comp, cx.layer, fx.match_name()),
);
}
}
/// Parameters that never carry a value to import.
pub(crate) fn carries_nothing(p: &EffectParam<'_, '_>) -> bool {
matches!(p.kind, ParamKind::Button | ParamKind::NoData | ParamKind::GroupStart | ParamKind::GroupEnd) || (p.index == 0 && p.kind == ParamKind::Layer)
@@ -373,7 +390,7 @@ fn report_beyond_limit<'v>(limit: Option<(f64, f64)>, values: impl Iterator<Item
/// A layer parameter: None stays unset, the owning layer is itself (`own`) or unset, another layer
/// is resolved by [`resolve_layer_refs`] once the composition's layers exist.
/// `names` is `(here, label)`, the effect and the parameter for the report.
fn import_layer_ref(p: &EffectParam<'_, '_>, target: &str, own: bool, cx: &LayerCtx<'_>, names: (&str, &str), out: ParamOut<'_>) {
pub(crate) fn import_layer_ref(p: &EffectParam<'_, '_>, target: &str, own: bool, cx: &LayerCtx<'_>, names: (&str, &str), out: ParamOut<'_>) {
let (here, label) = names;
let ParamOut { group, refs, col } = out;
// After Effects hands the named layer's source to the effect, without its masks and effects
@@ -813,7 +830,7 @@ fn px(v: f64) -> String {
/// A decoded value in EffectCraft's units, `None` when it does not fit the kind or is not a valid
/// number.
fn convert(value: ParamValue, kind: Kind) -> Option<Value> {
pub(crate) fn convert(value: ParamValue, kind: Kind) -> Option<Value> {
let raw = match (value, kind) {
// The reader gives colours as ARGB fractions; `Kind` takes the stored 0..255.
(ParamValue::Argb(c), Kind::EffectColor) => c.map(|x| x * 255.0).to_vec(),
+218
View File
@@ -0,0 +1,218 @@
//! Placeholders: an effect with no EffectCraft counterpart (a third-party plug-in, a pseudo effect
//! of expression controls) arrives as an effect group that renders nothing, as a missing plug-in
//! does. Its effect id is the After Effects match name, so Find Missing Effects lists it. It holds
//! the effect's parameters, flat and named as in After Effects, each with its value, keys and
//! expression, so expressions that read them (`effect("Settings")("Speed")`) keep working. It is
//! still reported, once per match name.
//!
//! The values keep After Effects' units, the ones its expressions read: sliders and angles as
//! stored, points in layer pixels, colours RGBA 0..1, checkboxes on / off, popups as EffectCraft's
//! 0-based items over the file's items in order (expressions read them 1-based, as After Effects
//! does). Layer parameters name their layer (their keys and expression are reported). Paths and
//! arbitrary data are not kept (reported when they hold something).
//!
//! The parameters placeholders walk, kept or not, and their popup items (by name length) are
//! bounded per import ([`MAX_COST`]): definitions can be shared by many instances, so a small file
//! could otherwise ask for very many properties. Once
//! the budget is spent, later effects without a counterpart are reported without a placeholder.
use effectcraft_keyframe::Value;
use effectcraft_project::build::Ids;
use effectcraft_project::{GroupKind, Node, ParamUi, PropGroup, Property};
use crate::import::effects::{LayerCtx, ParamOut, PendingLayerRef, carries_nothing, convert, import_layer_ref, param_label};
use crate::import::props::{Kind, import_expression, import_keys};
use crate::import::report::{Collector, LossCategory};
use crate::{Effect as AepEffect, EffectParam, ParamKind, ParamValue};
/// Most placeholder parameters (kept or not) and popup items one import walks.
pub(crate) const MAX_COST: usize = 200_000;
/// Most items read from one placeholder popup.
const MAX_POPUP_ITEMS: usize = 1024;
/// A popup item costs one more for each of these bytes in its name, so the names kept stay
/// bounded too.
const NAME_BYTES: usize = 16;
/// The placeholder of `fx`, with `params` (its parameter definitions) as properties.
pub(crate) fn placeholder(
fx: &AepEffect<'_, '_>,
params: &[EffectParam<'_, '_>],
cx: &LayerCtx<'_>,
shown: &str,
ids: &mut Ids<'_>,
refs: &mut Vec<PendingLayerRef>,
col: &mut Collector,
) -> PropGroup {
// The effect id is the match name; the group's match id is one segment of a property path
// (a pseudo effect's `Pseudo/0.25` would be cut apart), so match paths find its parameters.
let mut group = ids.group(&segment(fx.match_name()), shown);
group.kind = GroupKind::Effect { effect: fx.match_name().to_string() };
let here = format!("{}: '{}' effect '{shown}' ({})", cx.comp, cx.layer, fx.match_name());
for p in params {
// Every parameter walked counts, kept or not: a definition shared by many instances is
// otherwise walked again for each one.
if carries_nothing(p) {
col.placeholder_cost = col.placeholder_cost.saturating_add(1).min(MAX_COST);
continue;
}
if col.placeholder_cost >= MAX_COST {
col.lose(LossCategory::Effects, format!("{here}: parameters past the import's {MAX_COST} placeholder parameters not kept"));
break;
}
let label = param_label(p);
let Some((kind, ui, default)) = shape(p, cx.size) else {
col.placeholder_cost = col.placeholder_cost.saturating_add(1);
if p.stored().is_some() {
col.lose(LossCategory::Effects, format!("{here}: parameter {label} not kept (type {:?})", p.kind));
}
continue;
};
let (items, names) = match &ui {
ParamUi::Popup { options } => (options.len(), options.iter().map(|o| 1 + o.len() / NAME_BYTES).fold(0, usize::saturating_add)),
_ => (0, 0),
};
if p.kind == ParamKind::Popup && popup_len(p).is_some_and(|n| n > items) {
col.lose(LossCategory::Effects, format!("{here}: parameter {label}: the items past the first {MAX_POPUP_ITEMS} not kept"));
}
let cost = col.placeholder_cost.saturating_add(names).saturating_add(1);
if cost > MAX_COST {
// The budget is spent: nothing more is built, here or in later effects (definitions
// shared by many instances would otherwise still be walked item by item).
col.lose(
LossCategory::Effects,
format!("{here}: parameter {label} and the ones after it not kept (past the import's {MAX_COST} placeholder parameters)"),
);
col.placeholder_cost = MAX_COST;
break;
}
col.placeholder_cost = cost;
let mut prop = Property::new(ids.alloc(), &param_id(p), p.name.trim(), default).with_ui(ui);
prop.spatial = p.kind == ParamKind::Point;
prop.hold_only = matches!(p.kind, ParamKind::Checkbox | ParamKind::Popup | ParamKind::Layer);
match kind {
Some(kind) => {
fill(p, &mut prop, kind, cx, (&here, &label), col);
group.children.push(Node::Prop(prop));
}
// A layer parameter: the layer it names (set once every layer exists, by its uid).
None => {
let id = format!("@{}", prop.uid);
group.children.push(Node::Prop(prop));
import_layer_ref(p, &id, true, cx, (&here, &label), ParamOut { group: &mut group, refs: &mut *refs, col: &mut *col });
}
}
}
group
}
/// How parameter `p` is held on a layer `size` big: its unit conversion (`None` for a layer
/// parameter), its control and its value until one is read. `None` for a type that is not kept.
fn shape(p: &EffectParam<'_, '_>, size: (u32, u32)) -> Option<(Option<Kind>, ParamUi, Value)> {
let (kind, ui, default) = match p.kind {
ParamKind::IntSlider | ParamKind::FixedSlider | ParamKind::FloatSlider => (Kind::EffectNumber(1.0), slider_ui(p), Value::Scalar(0.0)),
ParamKind::Angle => (Kind::EffectNumber(1.0), ParamUi::Angle, Value::Scalar(0.0)),
ParamKind::Checkbox => (Kind::EffectBool, ParamUi::Checkbox, Value::Bool(false)),
ParamKind::Color => (Kind::EffectColor, ParamUi::Color, Value::Color([0.0, 0.0, 0.0, 1.0])),
ParamKind::Point => (Kind::EffectPoint(f64::from(size.0), f64::from(size.1)), ParamUi::Point, Value::Vec2([0.0, 0.0])),
ParamKind::Layer => return Some((None, ParamUi::Layer, Value::Layer(None))),
ParamKind::Popup => {
// The file's items, separators (`(-`) included: After Effects counts them.
let options: Vec<String> = match &p.items {
Some(items) => items.iter().take(MAX_POPUP_ITEMS).cloned().collect(),
None => (1..=popup_len(p)?.min(MAX_POPUP_ITEMS)).map(|i| format!("Item {i}")).collect(),
};
let n = u32::try_from(options.len()).ok().filter(|n| *n > 0)?;
(Kind::EffectPopup(n), ParamUi::Popup { options }, Value::Enum(0))
}
_ => return None,
};
Some((Some(kind), ui, default))
}
/// A slider's control: a float slider's valid range and drag range when they are ranges (only a
/// float slider's are decoded), else a plain number.
fn slider_ui(p: &EffectParam<'_, '_>) -> ParamUi {
match (p.valid_min(), p.valid_max(), p.slider_range()) {
(Some(min), Some(max), Some((smin, smax))) if [min, max, smin, smax].iter().all(|v| v.is_finite()) && min <= max && smin <= smax => {
ParamUi::Slider { min, max, slider_min: smin.clamp(min, max), slider_max: smax.clamp(min, max), decimals: 2 }
}
_ => ParamUi::Number,
}
}
/// How many items a popup has: the file's names, else the count in its definition.
fn popup_len(p: &EffectParam<'_, '_>) -> Option<usize> {
p.items.as_ref().map(Vec::len).or_else(|| p.popup_item_count().map(usize::from))
}
/// The property id of `p`: its match name when that is one segment of a property path (a
/// third-party effect's `CC Cylinder-0003`), else `param<index>` (a pseudo effect's
/// `Pseudo/0.25-0001`: `/` and `.` separate path segments). Expressions also find it by its name.
fn param_id(p: &EffectParam<'_, '_>) -> String {
if !p.match_name.is_empty() && p.match_name.chars().all(plain) { p.match_name.clone() } else { format!("param{}", p.index) }
}
/// Whether `c` can stand in one segment of a property path (`/`, `.`, `#` and `@` mean more).
fn plain(c: char) -> bool {
c.is_alphanumeric() || matches!(c, ' ' | '-' | '_')
}
/// `name` as one segment of a property path: other characters become `_` (`Pseudo/0.25` is
/// `Pseudo_0_25`).
fn segment(name: &str) -> String {
name.chars().map(|c| if plain(c) { c } else { '_' }).collect()
}
/// Sets `prop` from `p`: its expression, then its keys or its value (the record, else the `pard`
/// default). `names` is `(here, label)` for the report.
fn fill(p: &EffectParam<'_, '_>, prop: &mut Property, kind: Kind, cx: &LayerCtx<'_>, names: (&str, &str), col: &mut Collector) {
let (here, label) = names;
if let Some(stored) = p.stored() {
import_expression(&stored, prop, col);
}
if p.is_animated() {
let Some(stored) = p.stored() else { return };
if kind == Kind::EffectBool {
// Keys on a checkbox are not sampled by the corpus.
col.lose(LossCategory::Effects, format!("{here}: the keyframes of parameter {label} are not kept (not decoded)"));
return;
}
let before = prop.keys.len();
import_keys(&stored, kind, cx.layer, &p.match_name, cx.tm, prop, col);
if prop.keys.len() == before {
col.lose(LossCategory::DamagedData, format!("{here}: parameter {label} has no readable keyframe"));
}
return;
}
let value = match (p.stored(), p.recorded_value()) {
(Some(_), Some(v)) => v,
(Some(_), None) => {
col.lose(LossCategory::DamagedData, format!("{here}: parameter {label} holds an unreadable value"));
return;
}
// A borrowed popup's default slot holds another copy's selection (docs/aep-format.md 3.7).
(None, _) if p.kind == ParamKind::Popup && p.borrowed_definition => {
col.lose(LossCategory::Effects, format!("{here}: parameter {label}: the default item is not known (shared definition), the first item used"));
return;
}
// A popup's default slot can hold 0, no item (After Effects' save of a project it opened).
(None, _) => match p.pard_default() {
Some(ParamValue::Index(0)) => {
col.lose(LossCategory::Effects, format!("{here}: parameter {label}: the default item is not stored, the first item used"));
return;
}
Some(v) => v,
None => return,
},
};
match (convert(value, kind), value) {
(Some(v), _) => prop.value = v,
// An item of the file that is past the ones kept (reported with the cut): the first item.
(None, ParamValue::Index(i)) if usize::try_from(i).is_ok_and(|i| i > MAX_POPUP_ITEMS && popup_len(p).is_some_and(|n| i <= n)) => {
col.lose(LossCategory::Effects, format!("{here}: parameter {label}: item {i} is past the items kept, the first item used"));
}
(None, _) => col.lose(LossCategory::DamagedData, format!("{here}: parameter {label} holds a value that is not valid ({value:?})")),
}
}
+9 -1
View File
@@ -56,7 +56,8 @@ pub enum LossCategory {
/// Layers that could not be imported for another reason (unknown layer type, missing or
/// unsupported source, precomposition loop).
UnsupportedLayers,
/// Project items of a kind that is not imported.
/// Project items of a kind that is not imported, and items made from a Photoshop layer
/// without pixels (they show the merged image).
UnsupportedItems,
/// Data that could not be read (damaged headers, unreadable keyframes).
DamagedData,
@@ -160,6 +161,10 @@ pub struct Imported {
/// in [`LossCategory::Effects`]).
#[serde(default)]
pub effects: usize,
/// Effects with no counterpart, kept as placeholders that render nothing (their parameters,
/// for expressions; each is also in [`LossCategory::Effects`]).
#[serde(default)]
pub placeholder_effects: usize,
/// Layer styles (Drop Shadow, Stroke, ...), one per style on a layer.
#[serde(default)]
pub layer_styles: usize,
@@ -277,6 +282,9 @@ pub(crate) struct Collector {
/// many instances there were. They get a line each in [`Collector::finish`], so one that
/// comes after the example lines are used up is still named (#3365).
unmapped_effects: BTreeMap<String, (String, usize)>,
/// The properties and popup items the placeholders of this import hold so far (at most
/// `placeholder::MAX_COST`).
pub placeholder_cost: usize,
}
/// How many different unmapped effects get a line of their own (a file names at most this many).
+4 -4
View File
@@ -20,8 +20,8 @@ pub use container::{
GradientType, HueSaturationData, Interpolation, Item, ItemKind, Justification, KernRun, KeyEase, KeyLayout, KeyList, Keyframe, KeyframeKind, LIST, Layer,
LayerHeader, LayerRef, LayerType, LevelsData, LightType, Limits, ListHeader, Marker, Mask, MaskAtom, MaskMode, MatteMode, MeshData, NESTED_IDS,
Orientation, OrientationKey, ParagraphRun, ParamKind, ParamValue, PathVertex, PolystarType, Project, ProjectSettings, PropEntry, PropGroup, PropNode,
Property, Quality, Rational, Renderer, SequenceInfo, ShapeDetail, ShapeGroup, ShapeItem, ShapePath, SpatialKey, Stroke, StrokeCap, StrokeJoin, StyleRun,
TextBox, TextDocument, TextValue, TimeBase, TimeDisplay, TimeRemap, TimeRemapKey, TrackMatte, Tracked, Transform, ValueSource, Walk, WorkingSpace,
curve_lut, effect_map, identifier_channel_type, is_aepx, parse, parse_any, parse_text_dict, parse_with_limits, read_aepx, read_aepx_with_limits, style_map,
write, write_to,
Property, PsdLayer, Quality, Rational, Renderer, SequenceInfo, ShapeDetail, ShapeGroup, ShapeItem, ShapePath, SpatialKey, Stroke, StrokeCap, StrokeJoin,
StyleRun, TextBox, TextDocument, TextValue, TimeBase, TimeDisplay, TimeRemap, TimeRemapKey, TrackMatte, Tracked, Transform, ValueSource, Walk,
WorkingSpace, curve_lut, effect_map, identifier_channel_type, is_aepx, parse, parse_any, parse_text_dict, parse_with_limits, read_aepx,
read_aepx_with_limits, style_map, write, write_to,
};
@@ -720,6 +720,7 @@ fn extreme_values_in_the_batch_3_fields() {
file_size: 0,
audio_sample_rate: None,
is_sequence: true,
psd_layer: None,
};
for (num, den, rate) in [(3i64, 30i64, 30u32), (3, 0, 30), (-3, 30, 30), (i64::MAX, 1, u32::MAX), (i64::MIN, -1, u32::MAX), (1, i64::MAX, 1), (0, 1, 0)] {
let f = Footage { duration: Some(Rational { num, den }), native_frame_rate: rate, ..base.clone() };
+1
View File
@@ -22,6 +22,7 @@ mod lumetri;
mod markers;
mod masks;
mod mattes;
mod placeholders;
mod puppet;
mod resaved_defaults;
mod robustness;
+10 -5
View File
@@ -10,7 +10,7 @@
use effectcraft_aep::import::{ImportOptions, ImportResult, LossCategory, import};
use effectcraft_aep::{Body, Chunk, ParamKind, ParamValue, Project as AepProject, parse, write};
use effectcraft_keyframe::Value;
use effectcraft_project::{Project, PropGroup};
use effectcraft_project::{GroupKind, Project, PropGroup};
const SYNTHETIC: &[u8] = include_bytes!("../../fixtures/synthetic.aep");
@@ -274,10 +274,15 @@ pub fn import_bytes(bytes: &[u8], effect: &str) -> (Option<PropGroup>, ImportRes
let mut project = Project::default();
let none = |_: &str| false;
let r = import(&mut project, bytes, &ImportOptions { allow_losses: true, ..ImportOptions::new(&none) }).unwrap();
let g = project
.comps()
.flat_map(|(_, c)| c.layers.iter())
.find_map(|l| l.props.sub("effects").and_then(|fx| fx.children.iter().filter_map(|n| n.as_group()).find(|g| g.match_id == effect).cloned()));
let g = project.comps().flat_map(|(_, c)| c.layers.iter()).find_map(|l| {
l.props.sub("effects").and_then(|fx| {
fx.children
.iter()
.filter_map(|n| n.as_group())
.find(|g| g.match_id == effect || matches!(&g.kind, GroupKind::Effect { effect: e } if e == effect))
.cloned()
})
});
(g, r)
}
+315
View File
@@ -0,0 +1,315 @@
//! #3087: an effect with no EffectCraft counterpart (a third-party plug-in, a pseudo effect of
//! expression controls) arrives as a placeholder holding its parameters, so expressions that read
//! them keep working; it renders nothing and is still reported. Each effect is built into
//! `synthetic.aep` (`fx_inject`) in place of its Glow, on the 8 x 8 sequence layer.
use crate::import::fx_inject::{Default, Fx, bytes_with, import_bytes, losses, other, popup, run, slider, v};
use effectcraft_aep::import::LossCategory;
use effectcraft_aep::{Body, Chunk, ParamKind as K, parse, write};
use effectcraft_keyframe::Value;
use effectcraft_project::{GroupKind, ParamUi, PropGroup};
/// A third-party effect with one parameter of each kept kind, inside a twirl-down group.
fn third_party(values: Vec<(usize, f64)>, keys: Vec<(usize, Vec<(i32, f64)>)>) -> Fx {
Fx {
match_name: "CC Cylinder",
name: "CC Cylinder",
defs: vec![
other(K::GroupStart, "Light", Default::None),
slider(K::FloatSlider, "Radius (%)", 30.0, (0.0, 30000.0)),
other(K::GroupEnd, "", Default::None),
other(K::Angle, "Rotation X", Default::Number(12.5)),
other(K::Checkbox, "Wire", Default::Number(1.0)),
other(K::Color, "Light Color", Default::Color([255, 51, 102, 204])),
other(K::Point, "Position", Default::Point(0.25, 0.5)),
popup("Render", 1, &["Full", "(-", "Outside", "Inside"]),
slider(K::IntSlider, "Count", 3.0, (0.0, 50.0)),
],
values,
data: vec![],
keys,
}
}
fn placeholder_of(fx: &Fx) -> (PropGroup, effectcraft_aep::import::ImportResult) {
let (g, r) = run(fx, fx.match_name);
(g.expect("the placeholder"), r)
}
#[test]
fn an_effect_without_a_counterpart_is_kept_with_its_values() {
// Radius 37.5 and Render "Outside" (3: the separator counts) stored, the rest at defaults.
let (g, r) = placeholder_of(&third_party(vec![(2, 37.5), (8, 3.0)], vec![]));
assert_eq!(g.kind, GroupKind::Effect { effect: "CC Cylinder".into() });
assert_eq!(g.name, "CC Cylinder");
let names: Vec<(&str, &str)> = g.props().map(|p| (p.match_id.as_str(), p.name.as_str())).collect();
assert_eq!(
names,
[
("CC Cylinder-0002", "Radius (%)"),
("CC Cylinder-0004", "Rotation X"),
("CC Cylinder-0005", "Wire"),
("CC Cylinder-0006", "Light Color"),
("CC Cylinder-0007", "Position"),
("CC Cylinder-0008", "Render"),
("CC Cylinder-0009", "Count"),
],
"flat, in order, without the group markers"
);
assert_eq!(v(&g, "CC Cylinder-0002"), Value::Scalar(37.5));
assert_eq!(v(&g, "CC Cylinder-0004"), Value::Scalar(12.5));
assert_eq!(v(&g, "CC Cylinder-0005"), Value::Bool(true));
let Value::Color(c) = v(&g, "CC Cylinder-0006") else { panic!("a colour") };
assert!(c.iter().zip([0.2, 0.4, 0.8, 1.0]).all(|(a, b)| (a - b).abs() < 1e-6), "{c:?}");
assert_eq!(v(&g, "CC Cylinder-0007"), Value::Vec2([2.0, 4.0]), "layer pixels");
assert_eq!(v(&g, "CC Cylinder-0008"), Value::Enum(2), "item 3 of 4, 0-based");
assert_eq!(v(&g, "CC Cylinder-0009"), Value::Scalar(3.0));
let render = g.prop("CC Cylinder-0008").unwrap();
assert_eq!(render.ui, ParamUi::Popup { options: ["Full", "(-", "Outside", "Inside"].map(String::from).to_vec() });
// Still reported, once, and counted apart from the imported effects.
let found = losses(&r, LossCategory::Effects, "CC Cylinder");
assert!(found.len() == 1 && found[0].ends_with("has the effect 'CC Cylinder' (CC Cylinder), kept without rendering"), "{found:?}");
assert_eq!((r.report.imported.placeholder_effects, r.report.imported.effects), (1, 1), "the placeholder and the Levels");
}
#[test]
fn keys_and_expressions_of_a_placeholder_are_kept() {
let fx = third_party(vec![(4, 12.5)], vec![(2, vec![(0, 10.0), (25, 20.0)])]);
let bytes = with_expression(&bytes_with(&fx), "CC Cylinder-0004", "time * 90");
let (g, _) = import_bytes(&bytes, "CC Cylinder");
let g = g.unwrap();
let radius = g.prop("CC Cylinder-0002").unwrap();
assert_eq!(radius.keys.iter().map(|k| k.value.clone()).collect::<Vec<_>>(), [Value::Scalar(10.0), Value::Scalar(20.0)]);
let angle = g.prop("CC Cylinder-0004").unwrap();
assert_eq!(angle.expr.as_ref().map(|e| (e.text.as_str(), e.enabled)), Some(("time * 90", true)));
}
/// A pseudo effect's parameter match names (`Pseudo/0.25-0001`) are no property path segment:
/// its parameters are `param<index>`, found by their names.
#[test]
fn a_pseudo_effect_is_kept_with_its_parameter_names() {
let fx = Fx {
match_name: "Pseudo/0.25",
name: "Settings",
defs: vec![slider(K::FloatSlider, "Speed", 1.0, (0.0, 100.0)), popup("Mode", 2, &["A", "B"])],
values: vec![(1, 4.0)],
data: vec![],
keys: vec![],
};
let (g, r) = placeholder_of(&fx);
assert_eq!(g.prop("param1").map(|p| (p.name.as_str(), p.value.clone())), Some(("Speed", Value::Scalar(4.0))));
assert_eq!(g.prop("param2").map(|p| (p.name.as_str(), p.value.clone())), Some(("Mode", Value::Enum(1))));
assert_eq!(losses(&r, LossCategory::Effects, "Pseudo/0.25").len(), 1);
// The effect id stays the match name (Find Missing Effects, expressions); the group's match id
// is one path segment, so a match path (keyframe paste, pick whip) finds its parameters again.
assert_eq!(g.kind, GroupKind::Effect { effect: "Pseudo/0.25".into() });
let speed = g.prop("param1").map(|p| p.uid);
let layer = PropGroup::new(0, "layer", "Layer").with(PropGroup::new(0, "effects", "Effects").with(g));
let path = speed.and_then(|u| layer.match_path_of(u));
assert_eq!(path.as_deref().and_then(|p| layer.prop(p)).map(|p| p.name.as_str()), Some("Speed"), "{path:?}");
}
/// A float slider keeps its valid range and slider range, so Effect Controls drags and clamps it
/// as After Effects does; a range that is not a range stays a plain number.
#[test]
fn a_float_slider_keeps_its_range() {
let fx = Fx {
match_name: "Pseudo/r",
name: "Rig",
defs: vec![slider(K::FloatSlider, "Speed", 1.0, (-10.0, 100.0)), slider(K::FloatSlider, "Odd", 1.0, (5.0, 1.0))],
values: vec![],
data: vec![],
keys: vec![],
};
let (g, _) = placeholder_of(&fx);
let ui = |id: &str| g.prop(id).map(|p| p.ui.clone());
assert_eq!(ui("param1"), Some(ParamUi::Slider { min: -10.0, max: 100.0, slider_min: -10.0, slider_max: 100.0, decimals: 2 }));
assert_eq!(ui("param2"), Some(ParamUi::Number));
}
/// A popup whose definition is borrowed (the project copy) and has no value record: its default
/// slot holds another copy's selection, so the first item is used and that is reported.
#[test]
fn a_borrowed_popup_without_a_record_takes_the_first_item_and_is_reported() {
let bytes = without_instance_definitions(&bytes_with(&third_party(vec![], vec![])));
let (g, r) = import_bytes(&bytes, "CC Cylinder");
assert_eq!(v(&g.unwrap(), "CC Cylinder-0008"), Value::Enum(0));
let found = losses(&r, LossCategory::Effects, "CC Cylinder");
assert!(found.iter().any(|d| d.contains("Render") && d.contains("default item is not known")), "{found:?}");
}
/// A popup default slot of 0 (no item; After Effects' save of a project it opened) takes the first
/// item and is reported, not read as damaged data.
#[test]
fn a_popup_default_of_no_item_takes_the_first_item() {
let fx = Fx { match_name: "Some Fx", name: "Some", defs: vec![popup("Mode", 0, &["A", "B"])], values: vec![], data: vec![], keys: vec![] };
let (g, r) = placeholder_of(&fx);
assert_eq!(v(&g, "Some Fx-0001"), Value::Enum(0));
let found = losses(&r, LossCategory::Effects, "Some Fx");
assert!(found.iter().any(|d| d.contains("default item is not stored")), "{found:?}");
assert!(losses(&r, LossCategory::DamagedData, "Some Fx").is_empty());
}
/// A popup past the 1024 items kept: the cut is reported, and a selection among the cut items
/// takes the first item and is reported as such, not as damaged data.
#[test]
fn a_popup_past_the_items_kept_is_reported() {
let items: &'static [&'static str] = Box::leak((0..1100).map(|i| &*Box::leak(format!("I{i}").into_boxed_str())).collect::<Vec<_>>().into_boxed_slice());
let fx = Fx { match_name: "Long Fx", name: "Long", defs: vec![popup("Pick", 1, items)], values: vec![(1, 1050.0)], data: vec![], keys: vec![] };
let (g, r) = placeholder_of(&fx);
let pick = g.prop("Long Fx-0001").unwrap();
assert_eq!(pick.value, Value::Enum(0));
assert!(matches!(&pick.ui, ParamUi::Popup { options } if options.len() == 1024));
let found = losses(&r, LossCategory::Effects, "Long Fx");
assert!(found.iter().any(|d| d.contains("past the first 1024")), "{found:?}");
assert!(found.iter().any(|d| d.contains("item 1050 is past the items kept")), "{found:?}");
assert!(losses(&r, LossCategory::DamagedData, "Long Fx").is_empty());
}
/// Many large popups stay within the import's budget: what is beyond is reported, not kept.
#[test]
fn a_hostile_placeholder_stays_bounded() {
let items: &'static [&'static str] = Box::leak((0..1000).map(|i| &*Box::leak(format!("I{i}").into_boxed_str())).collect::<Vec<_>>().into_boxed_slice());
let fx = Fx { match_name: "Big Fx", name: "Big", defs: (0..300).map(|_| popup("P", 1, items)).collect(), values: vec![], data: vec![], keys: vec![] };
let (g, r) = placeholder_of(&fx);
let kept = g.props().count();
assert!(kept > 0 && kept < 300, "{kept}");
assert!(g.props().map(|p| if let ParamUi::Popup { options } = &p.ui { options.len() + 1 } else { 1 }).sum::<usize>() <= 200_000);
assert!(losses(&r, LossCategory::Effects, "Big Fx").iter().any(|d| d.contains("placeholder parameters")));
}
/// Two instances of an effect whose parameters fill the import's budget: the first keeps what fits
/// and stops at the first parameter past it; the second is reported without a placeholder (its
/// shared definitions are not read again).
#[test]
fn an_effect_past_the_spent_budget_gets_no_placeholder() {
let items: &'static [&'static str] = Box::leak((0..1000).map(|i| &*Box::leak(format!("I{i}").into_boxed_str())).collect::<Vec<_>>().into_boxed_slice());
let fx = Fx { match_name: "Big Fx", name: "Big", defs: (0..300).map(|_| popup("P", 1, items)).collect(), values: vec![], data: vec![], keys: vec![] };
let bytes = twice(&bytes_with(&fx), "Big Fx");
let mut project = effectcraft_project::Project::default();
let none = |_: &str| false;
let r = effectcraft_aep::import::import(
&mut project,
&bytes,
&effectcraft_aep::import::ImportOptions { allow_losses: true, ..effectcraft_aep::import::ImportOptions::new(&none) },
)
.unwrap();
let placeholders: Vec<usize> = project
.comps()
.flat_map(|(_, c)| c.layers.iter())
.filter_map(|l| l.props.sub("effects"))
.flat_map(|fx| fx.children.iter().filter_map(|n| n.as_group()).filter(|g| g.match_id == "Big Fx").map(|g| g.props().count()).collect::<Vec<_>>())
.collect();
// 199 popups of 1000 items (1001 each) fit in 200 000; the 200th stops the first instance.
assert_eq!(placeholders, [199]);
let found = losses(&r, LossCategory::Effects, "Big Fx");
assert_eq!(found.iter().filter(|d| d.contains("and the ones after it not kept")).count(), 1, "{found:?}");
assert!(found.iter().any(|d| d.contains("not kept (past the import's placeholder parameters)")), "{found:?}");
assert!(found.iter().any(|d| d.contains("kept without rendering") && !d.contains("more like it")), "the kept instance alone: {found:?}");
}
/// Parameters a placeholder does not keep (markers, arbitrary data) still spend the budget: a
/// definition of very many of them, shared by many instances, is not walked again for each one.
#[test]
fn parameters_not_kept_still_spend_the_budget() {
let defs = (0..200_000).map(|i| other(if i % 2 == 0 { K::NoData } else { K::ArbitraryData }, "X", Default::None)).collect();
let fx = Fx { match_name: "Odd Fx", name: "Odd", defs, values: vec![], data: vec![], keys: vec![] };
let (_, r) = import_bytes(&twice(&bytes_with(&fx), "Odd Fx"), "Odd Fx");
let found = losses(&r, LossCategory::Effects, "Odd Fx");
assert!(found.iter().any(|d| d.contains("not kept (past the import's placeholder parameters)")), "{found:?}");
}
/// Long popup item names spend the budget by their length, so the names kept stay bounded.
#[test]
fn long_popup_item_names_spend_the_budget() {
let long = "x".repeat(1600);
let items: &'static [&'static str] =
Box::leak((0..1024).map(|i| &*Box::leak(format!("{long}{i}").into_boxed_str())).collect::<Vec<_>>().into_boxed_slice());
let fx = Fx { match_name: "Long Fx", name: "Long", defs: vec![popup("A", 1, items), popup("B", 1, items)], values: vec![], data: vec![], keys: vec![] };
let (g, r) = placeholder_of(&fx);
assert_eq!(g.props().count(), 1);
assert!(losses(&r, LossCategory::Effects, "Long Fx").iter().any(|d| d.contains("placeholder parameters")));
}
/// `bytes` with the layer's instance of `match_name` (its `tdmn` and `sspc`) repeated after it.
fn twice(bytes: &[u8], match_name: &str) -> Vec<u8> {
let mut file = parse(bytes).unwrap();
let mut done = 0;
edit(&mut file.chunks, false, &mut |c, in_project_copy| {
let Body::List { children, .. } = &mut c.body else { return };
if in_project_copy {
return;
}
let Some(at) = children.iter().position(|k| k.is(b"tdmn") && k.bytes().is_some_and(|b| b.split(|x| *x == 0).next() == Some(match_name.as_bytes())))
else {
return;
};
let pair: Vec<Chunk<'_>> = children[at..at + 2].to_vec();
children.splice(at + 2..at + 2, pair);
done += 1;
});
assert_eq!(done, 1, "one instance");
write(&file).unwrap()
}
/// `bytes` with the expression `text` on the parameter record `param` (enabled: `tdb4` byte 120
/// 1, docs/aep-format.md 3.6).
fn with_expression(bytes: &[u8], param: &str, text: &str) -> Vec<u8> {
let mut file = parse(bytes).unwrap();
let mut done = 0;
edit(&mut file.chunks, false, &mut |c, _| {
let Body::List { children, .. } = &mut c.body else { return };
let Some(at) = children.iter().position(|k| k.is(b"tdmn") && k.bytes().is_some_and(|b| b.split(|x| *x == 0).next() == Some(param.as_bytes()))) else {
return;
};
let Some(Body::List { children: record, .. }) = children.get_mut(at + 1).map(|k| &mut k.body) else { return };
for k in record.iter_mut().filter(|k| k.is(b"tdb4")) {
if let Body::Data(d) = &mut k.body
&& let Some(b) = d.to_mut().get_mut(120)
{
*b = 1;
}
}
record.push(Chunk::data(*b"Utf8", text.as_bytes().to_vec()));
done += 1;
});
assert!(done >= 1);
write(&file).unwrap()
}
/// `bytes` with the layer's instance of `CC Cylinder` stripped of its own definitions (an empty
/// `parT`): it borrows the project copy's (`EfdG`).
fn without_instance_definitions(bytes: &[u8]) -> Vec<u8> {
let mut file = parse(bytes).unwrap();
let mut done = 0;
edit(&mut file.chunks, false, &mut |c, in_project_copy| {
let Body::List { children, .. } = &mut c.body else { return };
if in_project_copy {
return;
}
let Some(at) = children.iter().position(|k| k.is(b"tdmn") && k.bytes().is_some_and(|b| b.split(|x| *x == 0).next() == Some(&b"CC Cylinder"[..])))
else {
return;
};
let Some(sspc) = children.get_mut(at + 1).filter(|k| k.is_list(b"sspc")) else { return };
for k in sspc.children_mut() {
if let Body::List { list_type, children } = &mut k.body
&& list_type == b"parT"
{
children.clear();
done += 1;
}
}
});
assert_eq!(done, 1, "one instance");
write(&file).unwrap()
}
/// Calls `f` on every chunk with whether it is inside the project's effect definitions (`EfdG`).
fn edit(chunks: &mut [Chunk<'_>], in_efdg: bool, f: &mut dyn FnMut(&mut Chunk<'_>, bool)) {
for c in chunks {
let inside = in_efdg || c.is_list(b"EfdG");
f(c, inside);
edit(c.children_mut(), inside, f);
}
}
+86
View File
@@ -843,6 +843,92 @@ fn a_default_state_colour_record_holds_the_value() {
assert_ne!(colour(&default_state), colour(&unchanged), "the recorded colour, not the default");
}
/// The project with its png item made one layer of a Photoshop file `art.psd`: the `opti` of
/// docs/aep-format.md 3.3 (tag `8BPS`, the layer index at 14, a 1000 x 1000 document at 32 and 36,
/// its bounds at 78-94, its name at 344) and the item `size` big.
fn as_psd_layer(index: i32, bounds: [i32; 4], name: &str, size: (u32, u32)) -> Vec<u8> {
let mut opti = vec![0u8; 602];
opti[..4].copy_from_slice(b"8BPS");
opti[14..18].copy_from_slice(&index.to_be_bytes());
opti[32..36].copy_from_slice(&1000u32.to_le_bytes());
opti[36..40].copy_from_slice(&1000u32.to_le_bytes());
for (i, v) in bounds.iter().enumerate() {
opti[78 + 4 * i..82 + 4 * i].copy_from_slice(&v.to_le_bytes());
}
opti[344..344 + name.len()].copy_from_slice(name.as_bytes());
let alias = br#"{"fullpath":"C:\\x\\art.psd","platform":1,"target_is_folder":false}"#.to_vec();
mutate(&mut |c| {
if !c.is_list(b"Pin ") {
return;
}
let Body::List { children, .. } = &mut c.body else { return };
if !children.iter().any(|k| k.is(b"opti") && k.bytes().is_some_and(|d| d.get(..4) == Some(&b"png!"[..]))) {
return;
}
// No sequence naming between the alias and the `opti`.
children.retain(|k| k.is(b"sspc") || k.is(b"opti") || k.is_list(b"Als2"));
for k in children.iter_mut() {
if k.is(b"opti") {
k.body = Body::Data(opti.clone().into());
} else if k.is(b"sspc") {
set_data(k, 30, &size.0.to_be_bytes());
set_data(k, 34, &size.1.to_be_bytes());
}
}
visit(children, &mut |k| {
if k.is(b"alas") {
k.body = Body::Data(alias.clone().into());
}
});
})
}
/// #3087: an item made from one layer of a Photoshop file shows that layer, named
/// `<layer>/<file>`; it showed the whole document, named after the file. Item as big as the layer:
/// Retain Layer Sizes; as big as the document: the layer on the document.
#[test]
fn a_photoshop_layer_item_shows_its_layer() {
for (size, layer_size) in [((48, 15), true), ((1000, 1000), false)] {
let (p, r) = run(&as_psd_layer(7, [749, 800, 764, 848], "Tëst", size), true);
r.unwrap();
let (name, f) = p.items.values().find_map(|i| if let ItemKind::Footage(f) = &i.kind { Some((i.name.clone(), f.clone())) } else { None }).unwrap();
assert_eq!(name, "Tëst/art.psd");
let l = f.layer.expect("the layer");
assert_eq!((l.index, l.name.as_str(), l.layer_size, (f.width, f.height)), (7, "Tëst", layer_size, size));
}
}
/// A layer as big as the document but off its corner fits both framings: shown at its own bounds
/// and reported. One at the corner, or bigger than the document, reads one way and is not. An item
/// as big as neither is shown on the document and reported.
#[test]
fn a_photoshop_layer_as_big_as_the_document_off_its_corner_is_reported() {
let framing = |bounds, size| {
let (p, r) = run(&as_psd_layer(3, bounds, "Moved", size), true);
let found = losses(&r.unwrap(), LossCategory::UnsupportedItems);
let said = |what: &str| found.iter().any(|d| d.contains("'Moved/art.psd'") && d.contains(what));
(the_footage(&p).layer.map(|l| l.layer_size), said("as big as the document"), said("neither the Photoshop layer's size"))
};
assert_eq!(framing([5, 10, 1005, 1010], (1000, 1000)), (Some(true), true, false));
assert_eq!(framing([0, 0, 1000, 1000], (1000, 1000)), (Some(true), false, false));
assert_eq!(framing([9, -346, 1083, 1086], (1432, 1074)), (Some(true), false, false));
assert_eq!(framing([749, 800, 764, 848], (1000, 1000)), (Some(false), false, false));
// An item as big as neither the layer nor the document: shown on the document, reported.
assert_eq!(framing([5, 10, 1005, 1010], (800, 800)), (Some(false), false, true));
}
/// #3087: a Photoshop layer without pixels (an adjustment layer) keeps the merged image and is
/// reported; the merged image itself (index -1) is no layer.
#[test]
fn a_photoshop_layer_without_pixels_keeps_the_merged_image() {
let (p, r) = run(&as_psd_layer(4, [0; 4], "Levels 1", (1000, 1000)), true);
let found = losses(&r.unwrap(), LossCategory::UnsupportedItems);
assert!(found.iter().any(|d| d.contains("'Levels 1/art.psd'") && d.contains("without pixels")), "{found:?}");
assert_eq!(the_footage(&p).layer, None);
let (p, _) = run(&as_psd_layer(-1, [0; 4], "", (1000, 1000)), true);
assert_eq!(the_footage(&p).layer, None);
}
/// #3087: an expression on Orientation arrives with the stored value, as on any property; it was
/// dropped together with the value and reported as "not decoded".
#[test]
+16 -2
View File
@@ -65,6 +65,8 @@ const REFUSED: &[&str] = &[
"file.revealInFinder",
"layer.openSource",
"help.revealLogFile",
// Hands the footage file to the platform's default application.
"edit.editOriginal",
"file.autoSave",
// The Plug-in Library downloads code, installs it to load at start-up and reads `file://` catalogs.
"library.refresh",
@@ -73,6 +75,10 @@ const REFUSED: &[&str] = &[
"library.uninstall",
"library.loadInstalled",
"library.preview",
// Watch Folder renders the projects it finds to the outputs they name and writes status
// files into the watched folder: neither is a path the agent gives, so neither is checked.
"file.watchFolder",
"file.watchFolder.poll",
];
/// Most numbered folders `check_render_folder` inspects for one output; more are refused.
@@ -91,7 +97,6 @@ const READS: &[(&str, &[&str])] = &[
("file.replaceFootage", &["path"]),
("file.relinkFootage", &["folder"]),
("file.setProxy", &["path"]),
("file.watchFolder", &["folder"]),
("anim.applyPreset", &["path"]),
("anim.applyRecentPreset", &["path"]),
("keys.rpfCameraImport", &["path"]),
@@ -105,7 +110,6 @@ const READS: &[(&str, &[&str])] = &[
// unchecked.
("essential.templateInfo", &["path"]),
("file.importProject", &["path"]),
("file.watchFolder.poll", &["folder"]),
("footage.relink", &["path"]),
("layer.newModel", &["path"]),
("mediaBrowser.fileInfo", &["path"]),
@@ -817,6 +821,16 @@ mod tests {
assert!(read(&footage(&inside)).1.is_complete());
}
#[test]
fn watch_folder_and_edit_original_are_refused_while_confined() {
let dir = std::env::temp_dir();
let c = Confinement::new(std::slice::from_ref(&dir), std::slice::from_ref(&dir)).unwrap();
for id in ["file.watchFolder", "file.watchFolder.poll", "edit.editOriginal"] {
let e = c.check_command(id, &serde_json::json!({"folder": dir.to_string_lossy()})).unwrap_err().to_string();
assert!(e.contains("not available while file access is confined"), "{id}: {e}");
}
}
#[test]
fn relative_and_outside_paths_of_newly_listed_commands_are_refused() {
let base = std::env::temp_dir().join(format!("ec-confine-1243-{}", std::process::id()));
-16
View File
@@ -1,16 +0,0 @@
[package]
name = "effectcraft-av1enc"
description = "Clean-room pure-Rust AV1 encoder (Main profile, key and inter frames) for MP4/WebM export, from the AV1 Bitstream & Decoding Process Specification"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
[lints]
workspace = true
[dependencies]
[dev-dependencies]
tempfile = { workspace = true }
filmcraft-av1 = { workspace = true }
-76
View File
@@ -1,76 +0,0 @@
# effectcraft-av1enc
Clean-room, pure-Rust AV1 encoder for EffectCraft's MP4 / WebM export (layer L0, `std` only,
no `unsafe`, builds for `wasm32-unknown-unknown`).
Output is decoded **bit-exactly** by libdav1d (`ffmpeg -c:v libdav1d`, checked in
`tests/it/ffmpeg_oracle.rs` when ffmpeg is installed) and by FilmCraft's spec-derived
`filmcraft-av1` decoder (`tests/it/roundtrip.rs`): every decoded frame equals the encoder's own
reconstruction, so prediction never drifts.
## What is implemented
- **Stream**: Main profile (`seq_profile` 0), 4:2:0, 8 or 10 bit, BT.709 colour description,
limited or full range. Sequence header with one operating point; `seq_level_idx` given or the
lowest Annex A level whose MaxPicSize / MaxH/VSize / MaxDisplayRate (and, in bitrate mode, Main
tier MaxBitrate) fit. Order hints, film grain, superres, CDEF, loop restoration, intra edge
filter, filter intra, inter-intra, masked / distance compound, warped motion and dual filter
are disabled in the sequence header.
- **Packets**: one temporal unit per frame as stored in MP4 / Matroska samples: OBUs with size
fields, no temporal delimiter; key frames start with the sequence header OBU, followed by one
`OBU_FRAME` (frame header + tile group). Every frame is shown, in input order.
`Encoder::av1c()` returns the `AV1CodecConfigurationRecord` (also the WebM `CodecPrivate`).
- **Frames**: a `KEY_FRAME` every `keyint` frames, `INTER_FRAME`s otherwise. Inter frames use
slot 0 (the previous reconstruction) for all seven references and refresh slot 0 only, so
`LAST_FRAME` is always the previous frame. CDFs adapt per symbol and are saved at the end of
every frame; inter frames load them from `LAST_FRAME` (`primary_ref_frame` = 0). One tile,
`TX_MODE_LARGEST`, `reduced_tx_set`, no segmentation, no delta q / lf.
- **Deblocking**: the normative loop filter (7.14) runs on the reconstruction; the frame level
(the same for both luma directions and both chroma planes, no deltas, sharpness 0) is searched
per frame for the lowest luma error.
- **Tiles**: the multi-symbol arithmetic encoder is the exact inverse of the spec's symbol
decoder (8.2), including the exit process padding; CDF adaptation as in 8.2.6.
- **Partitions**: 64x64 superblocks, `PARTITION_NONE` / `PARTITION_SPLIT` down to 8x8 chosen by
a rate-distortion cost (SSE + λ·estimated bits); blocks crossing the frame edge are split as
the syntax requires. 64x64 blocks are only used as inter skip blocks.
- **Intra**: DC, V, H, Paeth, smooth, smooth-V, smooth-H for luma and chroma,
ranked by SATD with a rate-distortion choice among the best three; the spec's edge preparation
and above-right / below-left availability.
- **Inter**: single reference (`LAST_FRAME`), `NEWMV` / `NEARESTMV` / `NEARMV` / `GLOBALMV`
chosen from the spec's motion vector prediction stack (7.10.2, mirrored exactly); motion search
from neighbour / co-located / parent candidates, a whole-sample diamond search and half- then
quarter-sample refinement (`allow_high_precision_mv` = 0); the normative 8-tap `EIGHTTAP`
prediction for luma and chroma; skip blocks; per-block intra / inter choice.
- **Residual**: one transform per plane and block (4x4 ... 32x32): for intra luma `DCT_DCT` or
the mode's preferred `ADST` combination (rate-distortion choice over the two best modes), the
mode-dependent type for intra chroma, `DCT_DCT` for inter blocks; dead-zone quantisation with the
spec's `Dc_Qlookup` / `Ac_Qlookup`; the normative dequantisation and inverse transforms in the
reconstruction loop; full coefficient coding (all_zero, tx type, eob_pt, eob_extra,
coeff_base_eob, coeff_base, coeff_br, dc_sign, Golomb) with the exact contexts.
- **Rate control**: `ConstantQ(base_q_idx)`; `Bitrate { kbps }` adapts `base_q_idx` per frame
towards the average target (key frames get a lower quantizer and a larger share of the budget of
their group of `keyint` frames, the inter frames the rest; the first key frame is searched in a
few passes, a later key frame that misses its budget by more than 19 % is coded again; the
deviation from the budget is paid back over 16 frames).
## Limits
- One tile: width and height up to 4096 and at most 2304 superblocks (4096x2304 samples).
- No CDEF or loop restoration, no compound prediction, no rectangular or 4xN blocks, no
directional intra modes other than V / H, no CfL or palette, no transform-size splits, so
compression is below mature encoders.
- 4:2:0 only (Main profile), no 12 bit.
## Specification and provenance
Implemented from the **AV1 Bitstream & Decoding Process Specification, version 1.0.0 with
Errata 1** (AOMediaCodec, 2019; the edition FilmCraft's decoder follows) and the **AV1 Codec
ISO Media File Format Binding** (v1.2.0) for `av1C`.
The constant tables (default CDFs, scan orders, quantizer lookup tables, interpolation filter
taps, smooth weights, block / transform size tables, ...) and the decoder-side processes the
encoder must reproduce exactly (inverse transforms, intra and inter prediction rounding, context
derivations, motion vector prediction) are mirrored from FilmCraft's first-party, spec-derived
`filmcraft-av1` decoder (MIT OR Apache-2.0), which is also the round-trip oracle. No source of
libaom, dav1d, rav1e, SVT-AV1, ffmpeg or any other third-party encoder or decoder was consulted;
ffmpeg / libdav1d is used only as an external test oracle.
-87
View File
@@ -1,87 +0,0 @@
//! MSB-first bit writer for the OBU headers (spec 4.10 `f(n)` descriptors) and `leb128()`.
#[derive(Default)]
pub(crate) struct BitWriter {
pub buf: Vec<u8>,
nbits: usize,
}
impl BitWriter {
pub fn new() -> Self {
BitWriter::default()
}
/// `f(n)`: writes the low `n` bits of `v`, most significant first.
pub fn f(&mut self, n: u32, v: u32) {
for i in (0..n).rev() {
self.bit((v >> i) & 1 != 0);
}
}
pub fn bit(&mut self, b: bool) {
if self.nbits.is_multiple_of(8) {
self.buf.push(0);
}
if b {
let last = self.buf.len() - 1;
self.buf[last] |= 0x80 >> (self.nbits % 8);
}
self.nbits += 1;
}
/// `byte_alignment()`: zero bits up to the next byte boundary.
pub fn byte_align(&mut self) {
while !self.nbits.is_multiple_of(8) {
self.bit(false);
}
}
/// `trailing_bits()`: a one bit followed by zero bits up to the byte boundary.
pub fn trailing_bits(&mut self) {
self.bit(true);
self.byte_align();
}
pub fn into_bytes(self) -> Vec<u8> {
self.buf
}
}
/// `leb128()` encoding of an OBU size.
pub(crate) fn leb128(mut v: usize, out: &mut Vec<u8>) {
loop {
let mut b = (v & 0x7f) as u8;
v >>= 7;
if v != 0 {
b |= 0x80;
}
out.push(b);
if v == 0 {
break;
}
}
}
/// An OBU with `obu_has_size_field` = 1 and no extension header.
pub(crate) fn obu(obu_type: u8, payload: &[u8], out: &mut Vec<u8>) {
out.push((obu_type << 3) | 0x02);
leb128(payload.len(), out);
out.extend_from_slice(payload);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bits_and_leb128() {
let mut w = BitWriter::new();
w.f(3, 0b101);
w.f(6, 0b110011);
w.trailing_bits();
assert_eq!(w.into_bytes(), vec![0b1011_1001, 0b1100_0000]);
let mut v = Vec::new();
leb128(300, &mut v);
assert_eq!(v, vec![0xAC, 0x02]);
}
}
-172
View File
@@ -1,172 +0,0 @@
//! The adaptive CDFs this encoder codes with (the subset of spec 6.8.2 init_non_coeff_cdfs /
//! init_coeff_cdfs that its syntax uses). Layout as in filmcraft-av1: each innermost array
//! holds N cumulative values (the last is 32768) plus the adaptation counter.
use crate::tables::{
DEFAULT_ANGLE_DELTA_CDF, DEFAULT_COEFF_BASE_CDF, DEFAULT_COEFF_BASE_EOB_CDF, DEFAULT_COEFF_BR_CDF, DEFAULT_DC_SIGN_CDF, DEFAULT_DRL_MODE_CDF,
DEFAULT_EOB_EXTRA_CDF, DEFAULT_EOB_PT_16_CDF, DEFAULT_EOB_PT_32_CDF, DEFAULT_EOB_PT_64_CDF, DEFAULT_EOB_PT_128_CDF, DEFAULT_EOB_PT_256_CDF,
DEFAULT_EOB_PT_512_CDF, DEFAULT_EOB_PT_1024_CDF, DEFAULT_INTER_TX_TYPE_SET3_CDF, DEFAULT_INTRA_TX_TYPE_SET2_CDF, DEFAULT_IS_INTER_CDF, DEFAULT_MV_BIT_CDF,
DEFAULT_MV_CLASS_CDF, DEFAULT_MV_CLASS0_BIT_CDF, DEFAULT_MV_CLASS0_FR_CDF, DEFAULT_MV_FR_CDF, DEFAULT_MV_JOINT_CDF, DEFAULT_MV_SIGN_CDF,
DEFAULT_NEW_MV_CDF, DEFAULT_PARTITION_W8_CDF, DEFAULT_PARTITION_W16_CDF, DEFAULT_PARTITION_W32_CDF, DEFAULT_PARTITION_W64_CDF, DEFAULT_REF_MV_CDF,
DEFAULT_SINGLE_REF_CDF, DEFAULT_SKIP_CDF, DEFAULT_TXB_SKIP_CDF, DEFAULT_UV_MODE_CFL_ALLOWED_CDF, DEFAULT_UV_MODE_CFL_NOT_ALLOWED_CDF, DEFAULT_Y_MODE_CDF,
DEFAULT_ZERO_MV_CDF,
};
#[derive(Clone)]
pub(crate) struct Cdfs {
pub y_mode: [[u16; 14]; 4],
pub uv_mode_cfl_not_allowed: [[u16; 14]; 13],
pub uv_mode_cfl_allowed: [[u16; 15]; 13],
pub angle_delta: [[u16; 8]; 8],
pub partition_w8: [[u16; 5]; 4],
pub partition_w16: [[u16; 11]; 4],
pub partition_w32: [[u16; 11]; 4],
pub partition_w64: [[u16; 11]; 4],
pub skip: [[u16; 3]; 3],
pub is_inter: [[u16; 3]; 4],
pub single_ref: [[[u16; 3]; 6]; 3],
pub new_mv: [[u16; 3]; 6],
pub zero_mv: [[u16; 3]; 2],
pub ref_mv: [[u16; 3]; 6],
pub drl_mode: [[u16; 3]; 3],
pub mv_joint: [u16; 5],
pub mv_class: [[u16; 12]; 2],
pub mv_class0_bit: [[u16; 3]; 2],
pub mv_fr: [[u16; 5]; 2],
pub mv_class0_fr: [[[u16; 5]; 2]; 2],
pub mv_sign: [[u16; 3]; 2],
pub mv_bit: [[[u16; 3]; 10]; 2],
pub intra_tx_type_set2: [[[u16; 6]; 13]; 3],
pub inter_tx_type_set3: [[u16; 3]; 4],
pub txb_skip: [[[u16; 3]; 13]; 5],
pub eob_pt_16: [[[u16; 6]; 2]; 2],
pub eob_pt_32: [[[u16; 7]; 2]; 2],
pub eob_pt_64: [[[u16; 8]; 2]; 2],
pub eob_pt_128: [[[u16; 9]; 2]; 2],
pub eob_pt_256: [[[u16; 10]; 2]; 2],
pub eob_pt_512: [[u16; 11]; 2],
pub eob_pt_1024: [[u16; 12]; 2],
pub eob_extra: [[[[u16; 3]; 9]; 2]; 5],
pub dc_sign: [[[u16; 3]; 3]; 2],
pub coeff_base_eob: [[[[u16; 4]; 4]; 2]; 5],
pub coeff_base: [[[[u16; 5]; 42]; 2]; 5],
pub coeff_br: [[[[u16; 5]; 21]; 2]; 5],
}
impl Cdfs {
/// init_non_coeff_cdfs( ) followed by init_coeff_cdfs( ) for `base_q_idx`.
pub fn new(base_q_idx: u32) -> Box<Cdfs> {
let idx = match base_q_idx {
0..=20 => 0,
21..=60 => 1,
61..=120 => 2,
_ => 3,
};
Box::new(Cdfs {
y_mode: DEFAULT_Y_MODE_CDF,
uv_mode_cfl_not_allowed: DEFAULT_UV_MODE_CFL_NOT_ALLOWED_CDF,
uv_mode_cfl_allowed: DEFAULT_UV_MODE_CFL_ALLOWED_CDF,
angle_delta: DEFAULT_ANGLE_DELTA_CDF,
partition_w8: DEFAULT_PARTITION_W8_CDF,
partition_w16: DEFAULT_PARTITION_W16_CDF,
partition_w32: DEFAULT_PARTITION_W32_CDF,
partition_w64: DEFAULT_PARTITION_W64_CDF,
skip: DEFAULT_SKIP_CDF,
is_inter: DEFAULT_IS_INTER_CDF,
single_ref: DEFAULT_SINGLE_REF_CDF,
new_mv: DEFAULT_NEW_MV_CDF,
zero_mv: DEFAULT_ZERO_MV_CDF,
ref_mv: DEFAULT_REF_MV_CDF,
drl_mode: DEFAULT_DRL_MODE_CDF,
mv_joint: DEFAULT_MV_JOINT_CDF,
mv_class: DEFAULT_MV_CLASS_CDF,
mv_class0_bit: [DEFAULT_MV_CLASS0_BIT_CDF; 2],
mv_fr: DEFAULT_MV_FR_CDF,
mv_class0_fr: DEFAULT_MV_CLASS0_FR_CDF,
mv_sign: [DEFAULT_MV_SIGN_CDF; 2],
mv_bit: [DEFAULT_MV_BIT_CDF; 2],
intra_tx_type_set2: DEFAULT_INTRA_TX_TYPE_SET2_CDF,
inter_tx_type_set3: DEFAULT_INTER_TX_TYPE_SET3_CDF,
txb_skip: DEFAULT_TXB_SKIP_CDF[idx],
eob_pt_16: DEFAULT_EOB_PT_16_CDF[idx],
eob_pt_32: DEFAULT_EOB_PT_32_CDF[idx],
eob_pt_64: DEFAULT_EOB_PT_64_CDF[idx],
eob_pt_128: DEFAULT_EOB_PT_128_CDF[idx],
eob_pt_256: DEFAULT_EOB_PT_256_CDF[idx],
eob_pt_512: DEFAULT_EOB_PT_512_CDF[idx],
eob_pt_1024: DEFAULT_EOB_PT_1024_CDF[idx],
eob_extra: DEFAULT_EOB_EXTRA_CDF[idx],
dc_sign: DEFAULT_DC_SIGN_CDF[idx],
coeff_base_eob: DEFAULT_COEFF_BASE_EOB_CDF[idx],
coeff_base: DEFAULT_COEFF_BASE_CDF[idx],
coeff_br: DEFAULT_COEFF_BR_CDF[idx],
})
}
}
impl Cdfs {
/// The counter reset of load_cdfs( ): the last entry of every CDF array is set to 0.
pub fn clear_counts(&mut self) {
macro_rules! clr {
($($f:ident),*) => { $( self.$f.clear_count(); )* };
}
clr!(
y_mode,
uv_mode_cfl_not_allowed,
uv_mode_cfl_allowed,
angle_delta,
partition_w8,
partition_w16,
partition_w32,
partition_w64,
skip,
is_inter,
single_ref,
new_mv,
zero_mv,
ref_mv,
drl_mode,
mv_joint,
mv_class,
mv_class0_bit,
mv_fr,
mv_class0_fr,
mv_sign,
mv_bit,
intra_tx_type_set2,
inter_tx_type_set3,
txb_skip,
eob_pt_16,
eob_pt_32,
eob_pt_64,
eob_pt_128,
eob_pt_256,
eob_pt_512,
eob_pt_1024,
eob_extra,
dc_sign,
coeff_base_eob,
coeff_base,
coeff_br
);
}
}
/// Zeroes the adaptation counter (last element) of every innermost CDF array.
trait ClearCount {
fn clear_count(&mut self);
}
impl<const N: usize> ClearCount for [u16; N] {
fn clear_count(&mut self) {
self[N - 1] = 0;
}
}
impl<T: ClearCount, const M: usize> ClearCount for [T; M] {
fn clear_count(&mut self) {
for e in self.iter_mut() {
e.clear_count();
}
}
}
File diff suppressed because it is too large. Load diff
-670
View File
@@ -1,670 +0,0 @@
//! Clean-room pure-Rust AV1 encoder (Main profile, 4:2:0, 8 and 10 bit), implemented from the
//! AV1 Bitstream & Decoding Process Specification v1.0.0 with Errata 1.
//!
//! Key frames and single-reference inter frames (LAST_FRAME = the previous frame), 64x64
//! superblocks split down to 8x8 by rate-distortion decisions, intra modes DC / V / H / Paeth /
//! smooth, full-sample motion search with the spec's motion vector prediction, DCT / ADST
//! transforms up to 32x32, one tile per frame, in-loop filters off. See the crate README.
//!
//! The public API below is the contract `crates/export` codes against; keep it stable.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
mod bitw;
mod cdf;
mod decide;
mod loopfilter;
mod pred;
mod symbol;
mod tables;
mod transform;
mod writer;
use bitw::{BitWriter, obu};
use decide::{Decider, FrameGeom, RefFrame};
use loopfilter::{LfInfo, loop_filter};
use pred::Plane;
use tables::AC_QLOOKUP;
use writer::TileWriter;
/// Rate control.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RateControl {
/// Constant quantizer index (`base_q_idx`, 1–255; lower is better).
ConstantQ(u8),
/// Average bitrate target in kbit/s (frame-level quantizer adaptation).
Bitrate { kbps: u32 },
}
/// Encoder settings. Main profile (seq_profile 0), 4:2:0.
#[derive(Clone, Debug, PartialEq)]
pub struct EncoderConfig {
pub width: u32,
pub height: u32,
pub fps_num: u32,
pub fps_den: u32,
/// 8 or 10.
pub bit_depth: u8,
/// `seq_level_idx` (e.g. 8 = level 4.0); `None` picks the lowest level that fits.
pub level_idx: Option<u8>,
pub rate: RateControl,
/// Frames between key frames (1 = all key frames).
pub keyint: u32,
/// BT.709 limited range is signalled unless this is set.
pub full_range: bool,
/// The colour description of `color_config` (ITU-T H.273 code points); BT.709 by default.
pub color_primaries: u8,
pub transfer_characteristics: u8,
pub matrix_coefficients: u8,
}
impl EncoderConfig {
pub fn new(width: u32, height: u32, fps_num: u32, fps_den: u32) -> Self {
EncoderConfig {
width,
height,
fps_num,
fps_den,
bit_depth: 8,
level_idx: None,
rate: RateControl::ConstantQ(100),
keyint: 60,
full_range: false,
color_primaries: 1,
transfer_characteristics: 1,
matrix_coefficients: 1,
}
}
}
/// One input picture, 4:2:0, samples at the configured bit depth.
#[derive(Clone, Copy, Debug)]
pub struct Frame<'a> {
pub y: &'a [u16],
pub u: &'a [u16],
pub v: &'a [u16],
pub y_stride: usize,
pub uv_stride: usize,
}
/// One temporal unit as stored in MP4 / WebM samples: OBUs with `obu_has_size_field` = 1 and
/// no temporal delimiter (key frames start with the sequence header OBU).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Packet {
pub data: Vec<u8>,
pub keyframe: bool,
}
#[derive(Debug, PartialEq, Eq)]
pub enum Error {
InvalidConfig(String),
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Error::InvalidConfig(s) => write!(f, "invalid AV1 encoder config: {s}"),
}
}
}
impl std::error::Error for Error {}
const OBU_SEQUENCE_HEADER: u8 = 1;
const OBU_FRAME: u8 = 6;
/// Annex A level limits: (seq_level_idx, MaxPicSize, MaxHSize, MaxVSize, MaxDisplayRate,
/// MaxBitrate (Main tier, Mbit/s)).
const LEVELS: [(u8, u64, u32, u32, u64, u64); 14] = [
(0, 147_456, 2048, 1152, 4_423_680, 1_500_000),
(1, 278_784, 2816, 1584, 8_363_520, 3_000_000),
(4, 665_856, 4352, 2448, 19_975_680, 6_000_000),
(5, 1_065_024, 5504, 3096, 31_950_720, 10_000_000),
(8, 2_359_296, 6144, 3456, 70_778_880, 12_000_000),
(9, 2_359_296, 6144, 3456, 141_557_760, 20_000_000),
(12, 8_912_896, 8192, 4352, 267_386_880, 30_000_000),
(13, 8_912_896, 8192, 4352, 534_773_760, 40_000_000),
(14, 8_912_896, 8192, 4352, 1_069_547_520, 60_000_000),
(15, 8_912_896, 8192, 4352, 1_069_547_520, 60_000_000),
(16, 35_651_584, 16384, 8704, 1_069_547_520, 60_000_000),
(17, 35_651_584, 16384, 8704, 2_139_095_040, 100_000_000),
(18, 35_651_584, 16384, 8704, 4_278_190_080, 160_000_000),
(19, 35_651_584, 16384, 8704, 4_278_190_080, 160_000_000),
];
/// The lowest level whose limits fit the stream (31 = no level limits when none does).
fn pick_level(cfg: &EncoderConfig) -> u8 {
let pic = cfg.width as u64 * cfg.height as u64;
let rate = pic * cfg.fps_num as u64 / cfg.fps_den.max(1) as u64;
let bitrate = match cfg.rate {
RateControl::Bitrate { kbps } => kbps as u64 * 1000,
RateControl::ConstantQ(_) => 0,
};
for &(idx, max_pic, max_h, max_v, max_rate, max_br) in LEVELS.iter() {
if pic <= max_pic && cfg.width <= max_h && cfg.height <= max_v && rate <= max_rate && bitrate <= max_br {
return idx;
}
}
31
}
/// Frame-level rate control state for `RateControl::Bitrate`.
struct RateState {
/// Bits per frame at the target rate.
frame_bits: f64,
/// Quantizer index for inter frames (continuous).
q: f64,
/// Key frame quantizer index minus the inter frame one.
key_off: f64,
/// Quantizer index steps per halving of the frame size, measured from consecutive inter
/// frames (the size/quantizer curve is much steeper than the default on noisy content).
slope: f64,
/// Quantizer index and size (in bits) of the previous inter frame.
prev_inter: Option<(f64, f64)>,
/// Accumulated (spent - budget) bits.
debt: f64,
}
/// Quantizer index steps per halving of the frame size before any measurement.
const RC_SLOPE: f64 = 28.0;
/// Fraction of the quantizer step the size error asks for that is applied per frame.
const RC_GAIN: f64 = 0.8;
/// Frames over which an accumulated deviation from the budget is paid back.
const RC_PAYBACK: f64 = 16.0;
impl RateState {
/// The nominal bit budget and the starting quantizer index of a key or inter frame. A key
/// frame gets a larger share, and the inter frames of the group get the rest, so that a whole
/// group of `keyint` frames adds up to `keyint * frame_bits`.
fn frame_budget(&self, keyint: u32, key: bool) -> (f64, f64) {
let keyint = keyint.max(1) as f64;
let boost = (1.0 + (keyint.clamp(1.0, 60.0) - 1.0).sqrt() * 0.75).min(0.5 * keyint + 0.5);
if key {
(self.frame_bits * boost, (self.q + self.key_off).clamp(1.0, 255.0))
} else if keyint > 1.0 {
(self.frame_bits * (keyint - boost) / (keyint - 1.0), self.q)
} else {
(self.frame_bits, self.q)
}
}
/// Adapts the quantizers to the size of the frame just coded at `q_used` against `target`.
fn update(&mut self, key: bool, first: bool, q_used: f64, bits: f64, target: f64) {
let err = (bits / target).log2().clamp(-1.5, 1.5);
if first && key {
// four passes ran: the key frame quantizer is known, the inter one follows from the offset
self.q = (q_used - self.key_off).clamp(1.0, 255.0);
} else if key {
self.key_off = q_used - self.q + RC_GAIN * self.slope * err;
} else {
if let Some((pq, pbits)) = self.prev_inter {
let (dq, dr) = (q_used - pq, (pbits / bits).log2());
if dq.abs() >= 3.0 && dr.abs() >= 0.15 && dq * dr > 0.0 {
self.slope = (0.6 * self.slope + 0.4 * (dq / dr)).clamp(3.0, 45.0);
}
}
self.prev_inter = Some((q_used, bits));
self.q = (q_used + RC_GAIN * self.slope * err).clamp(1.0, 255.0);
}
}
}
/// Most passes on the first frame, and how far from the target (octaves, 3 %) its size may be
/// before it is accepted.
const RC_FIRST_PASSES: usize = 4;
const RC_FIRST_TOLERANCE: f64 = 0.04;
/// Quantizer index steps per halving of the size, for the first correction of the first frame
/// (the starting quantizer comes from the bits per sample; the first pass shows how far off it
/// is, and from there on the passes are placed by `next_probe_q`).
const RC_FIRST_SLOPE: f64 = 30.0;
/// The same for a key frame after the first: coded again when its size is more than 0.25 octaves
/// (19 %) off the target.
const RC_KEY_PASSES: usize = 3;
const RC_KEY_TOLERANCE: f64 = 0.25;
/// Octaves of frame size per octave of quantizer step assumed for the first correction of a frame.
const RC_PROBE_SLOPE: f64 = 1.0;
/// Largest change of the quantizer step (octaves) between two passes on one frame.
const RC_PROBE_MAX_STEP: f64 = 2.0;
/// The quantizer index whose step size is closest to `2^x`.
fn q_for_step(bit_depth: u8, x: f64) -> u8 {
let table = &AC_QLOOKUP[((bit_depth - 8) / 2) as usize];
let mut best = 1;
for q in 1..=255usize {
if ((table[q] as f64).log2() - x).abs() < ((table[best] as f64).log2() - x).abs() {
best = q;
}
}
best as u8
}
/// The next quantizer to try for a frame, from the `(quantizer, log2(size / target))`
/// pairs coded so far. The size follows the quantizer step (not the index, which is linear in the
/// step only below about 60) in a near log-log line: false position between the closest pair of
/// passes that enclose the target, otherwise a step from the latest one with the slope of the
/// last two. `None` when no untried quantizer lies between the enclosing passes.
fn next_probe_q(bit_depth: u8, tried: &[(u8, f64)]) -> Option<u8> {
let table = &AC_QLOOKUP[((bit_depth - 8) / 2) as usize];
let x = |q: u8| (table[q as usize] as f64).log2();
let over = tried.iter().filter(|t| t.1 > 0.0).max_by_key(|t| t.0);
let under = tried.iter().filter(|t| t.1 <= 0.0).min_by_key(|t| t.0);
if let (Some(&(q_lo, e_lo)), Some(&(q_hi, e_hi))) = (over, under) {
if q_hi - q_lo < 2 {
return None;
}
let next = x(q_lo) + (x(q_hi) - x(q_lo)) * e_lo / (e_lo - e_hi);
return Some(q_for_step(bit_depth, next).clamp(q_lo + 1, q_hi - 1));
}
let &(q, err) = tried.last()?;
let mut slope = RC_PROBE_SLOPE;
if let [.., (q0, e0), (q1, e1)] = tried
&& (x(*q1) - x(*q0)).abs() > 0.05
&& (e0 - e1) / (x(*q1) - x(*q0)) > 0.0
{
slope = ((e0 - e1) / (x(*q1) - x(*q0))).clamp(0.25, 3.0);
}
Some(q_for_step(bit_depth, x(q) + (err / slope).clamp(-RC_PROBE_MAX_STEP, RC_PROBE_MAX_STEP)))
}
/// AV1 encoder. Frames come out in input order (no hidden/reordered frames).
pub struct Encoder {
cfg: EncoderConfig,
geom: FrameGeom,
level: u8,
seq_obu: Vec<u8>,
frame_num: u64,
refr: Option<RefFrame>,
rc: Option<RateState>,
}
impl Encoder {
pub fn new(cfg: EncoderConfig) -> Result<Encoder, Error> {
if cfg.width == 0 || cfg.height == 0 {
return Err(Error::InvalidConfig("empty frame".into()));
}
if cfg.width > 4096 || cfg.height > 4096 {
return Err(Error::InvalidConfig(format!("{}x{} exceeds the single-tile limit (4096 samples per side)", cfg.width, cfg.height)));
}
if cfg.bit_depth != 8 && cfg.bit_depth != 10 {
return Err(Error::InvalidConfig(format!("bit depth {} (8 or 10 supported)", cfg.bit_depth)));
}
if cfg.fps_num == 0 || cfg.fps_den == 0 {
return Err(Error::InvalidConfig("frame rate".into()));
}
let geom = FrameGeom::new(cfg.width as usize, cfg.height as usize);
if geom.sb_cols * geom.sb_rows > 2304 {
return Err(Error::InvalidConfig(format!("{}x{} exceeds the single-tile area limit (MAX_TILE_AREA)", cfg.width, cfg.height)));
}
if let RateControl::Bitrate { kbps } = cfg.rate
&& kbps == 0
{
return Err(Error::InvalidConfig("zero bitrate".into()));
}
let level = cfg.level_idx.unwrap_or_else(|| pick_level(&cfg));
if level > 31 {
return Err(Error::InvalidConfig(format!("seq_level_idx {level}")));
}
let rc = match cfg.rate {
RateControl::ConstantQ(_) => None,
RateControl::Bitrate { kbps } => {
let frame_bits = kbps as f64 * 1000.0 * cfg.fps_den as f64 / cfg.fps_num as f64;
// initial guess from the bits per sample
let bpp = frame_bits / (cfg.width as f64 * cfg.height as f64);
let q = (110.0 - 40.0 * (bpp / 0.1).log2()).clamp(20.0, 230.0);
Some(RateState { frame_bits, q, key_off: -24.0, slope: RC_SLOPE, prev_inter: None, debt: 0.0 })
}
};
let mut enc = Encoder { cfg, geom, level, seq_obu: Vec::new(), frame_num: 0, refr: None, rc };
let payload = enc.sequence_header_payload();
obu(OBU_SEQUENCE_HEADER, &payload, &mut enc.seq_obu);
Ok(enc)
}
pub fn config(&self) -> &EncoderConfig {
&self.cfg
}
/// The sequence header OBU (with size field).
pub fn sequence_header_obu(&self) -> Vec<u8> {
self.seq_obu.clone()
}
/// AV1CodecConfigurationRecord (`av1C` payload, also the WebM CodecPrivate).
pub fn av1c(&self) -> Vec<u8> {
let high = (self.cfg.bit_depth > 8) as u8;
let mut v = vec![
0x81, // marker (1), version (1)
self.level & 0x1f, // seq_profile 0, seq_level_idx_0
(high << 6) | (1 << 3) | (1 << 2), // tier 0, high_bitdepth, twelve_bit 0, mono 0, ss_x 1, ss_y 1, csp 0
0, // no initial_presentation_delay
];
v.extend_from_slice(&self.seq_obu);
v
}
/// sequence_header_obu( ) payload (5.5) including trailing bits.
fn sequence_header_payload(&self) -> Vec<u8> {
let c = &self.cfg;
let mut w = BitWriter::new();
w.f(3, 0); // seq_profile
w.f(1, 0); // still_picture
w.f(1, 0); // reduced_still_picture_header
w.f(1, 0); // timing_info_present_flag
w.f(1, 0); // initial_display_delay_present_flag
w.f(5, 0); // operating_points_cnt_minus_1
w.f(12, 0); // operating_point_idc[ 0 ]
w.f(5, self.level as u32); // seq_level_idx[ 0 ]
if self.level > 7 {
w.f(1, 0); // seq_tier[ 0 ]
}
let wbits = 32 - (c.width - 1).max(1).leading_zeros();
let hbits = 32 - (c.height - 1).max(1).leading_zeros();
w.f(4, wbits - 1);
w.f(4, hbits - 1);
w.f(wbits, c.width - 1);
w.f(hbits, c.height - 1);
w.f(1, 0); // frame_id_numbers_present_flag
w.f(1, 0); // use_128x128_superblock
w.f(1, 0); // enable_filter_intra
w.f(1, 0); // enable_intra_edge_filter
w.f(1, 0); // enable_interintra_compound
w.f(1, 0); // enable_masked_compound
w.f(1, 0); // enable_warped_motion
w.f(1, 0); // enable_dual_filter
w.f(1, 0); // enable_order_hint
w.f(1, 0); // seq_choose_screen_content_tools
w.f(1, 0); // seq_force_screen_content_tools
w.f(1, 0); // enable_superres
w.f(1, 0); // enable_cdef
w.f(1, 0); // enable_restoration
// color_config( )
w.f(1, (c.bit_depth > 8) as u32); // high_bitdepth
w.f(1, 0); // mono_chrome
w.f(1, 1); // color_description_present_flag
w.f(8, c.color_primaries as u32); // color_primaries
w.f(8, c.transfer_characteristics as u32); // transfer_characteristics
w.f(8, c.matrix_coefficients as u32); // matrix_coefficients
w.f(1, c.full_range as u32); // color_range
w.f(2, 0); // chroma_sample_position: unknown
w.f(1, 0); // separate_uv_delta_q
w.f(1, 0); // film_grain_params_present
w.trailing_bits();
w.into_bytes()
}
/// uncompressed_header( ) (5.9) for a shown KEY_FRAME or an INTER_FRAME referencing slot 0.
fn frame_header(&self, w: &mut BitWriter, key: bool, qidx: u8, lf_level: u32) {
w.f(1, 0); // show_existing_frame
w.f(2, if key { 0 } else { 1 }); // frame_type
w.f(1, 1); // show_frame
if !key {
w.f(1, 0); // error_resilient_mode
}
w.f(1, 0); // disable_cdf_update
w.f(1, 0); // frame_size_override_flag
if !key {
w.f(3, 0); // primary_ref_frame: LAST_FRAME's saved CDFs
w.f(8, 1); // refresh_frame_flags: slot 0 becomes LAST for the next frame
for _ in 0..7 {
w.f(3, 0); // ref_frame_idx[ i ]
}
w.f(1, 0); // render_and_frame_size_different
w.f(1, 0); // allow_high_precision_mv
w.f(1, 0); // is_filter_switchable
w.f(2, 0); // interpolation_filter = EIGHTTAP
w.f(1, 0); // is_motion_mode_switchable
} else {
w.f(1, 0); // render_and_frame_size_different
}
w.f(1, 0); // disable_frame_end_update_cdf
// tile_info( ): uniform spacing, one tile
let g = &self.geom;
let tile_log2 = |blk: usize, target: usize| {
let mut k = 0;
while (blk << k) < target {
k += 1;
}
k
};
w.f(1, 1); // uniform_tile_spacing_flag
if tile_log2(1, g.sb_cols.min(64)) > 0 {
w.f(1, 0); // increment_tile_cols_log2
}
if tile_log2(1, g.sb_rows.min(64)) > 0 {
w.f(1, 0); // increment_tile_rows_log2
}
// quantization_params( )
w.f(8, qidx as u32);
w.f(1, 0); // DeltaQYDc
w.f(1, 0); // DeltaQUDc
w.f(1, 0); // DeltaQUAc
w.f(1, 0); // using_qmatrix
w.f(1, 0); // segmentation_enabled
w.f(1, 0); // delta_q_present (base_q_idx > 0)
// loop_filter_params( ): the same level for every plane and direction
w.f(6, lf_level);
w.f(6, lf_level);
if lf_level != 0 {
w.f(6, lf_level);
w.f(6, lf_level);
}
w.f(3, 0); // loop_filter_sharpness
w.f(1, 0); // loop_filter_delta_enabled
w.f(1, 0); // tx_mode_select (TX_MODE_LARGEST)
if !key {
w.f(1, 0); // reference_select
}
w.f(1, 1); // reduced_tx_set
if !key {
for _ in 0..7 {
w.f(1, 0); // is_global
}
}
}
/// Copies a picture into superblock-padded planes (edge replication).
fn load_source(&self, frame: &Frame) -> [Plane; 3] {
let maxv = (1u16 << self.cfg.bit_depth) - 1;
std::array::from_fn(|p| {
let (vw, vh) = self.geom.visible(p);
let (pw, ph) = self.geom.padded(p);
let (data, stride) = match p {
0 => (frame.y, frame.y_stride),
1 => (frame.u, frame.uv_stride),
_ => (frame.v, frame.uv_stride),
};
assert!(stride >= vw && data.len() >= stride * (vh - 1) + vw, "plane {p} is too small for {vw}x{vh}");
let mut pl = Plane::new(pw, ph);
for y in 0..ph {
let sy = y.min(vh - 1);
let src = &data[sy * stride..sy * stride + vw];
let row = &mut pl.data[y * pw..y * pw + pw];
for (x, d) in row.iter_mut().enumerate() {
*d = src[x.min(vw - 1)].min(maxv);
}
}
pl
})
}
/// Codes one frame at `qidx`; returns the frame OBU and the reconstruction.
fn encode_frame(&self, src: &[Plane; 3], key: bool, qidx: u8) -> (Vec<u8>, RefFrame) {
let g = &self.geom;
let refr = if key { None } else { self.refr.as_ref() };
let mut dec = Decider::new(g, self.cfg.bit_depth as u32, qidx, key, src, refr);
let mut tw = TileWriter::new(g, key, qidx, refr.map(|r| &*r.cdfs));
for sbr in 0..g.sb_rows {
tw.start_sb_row();
for sbc in 0..g.sb_cols {
let node = dec.superblock(sbr * 16, sbc * 16);
tw.superblock(sbr * 16, sbc * 16, &node);
}
}
let lf_level = self.pick_filter_level(&dec.rec, &tw.lf_info(), src, qidx);
loop_filter(&mut dec.rec, &tw.lf_info(), [lf_level; 4], self.cfg.bit_depth as u32, false, 1);
let (tile, cdfs) = tw.finish();
let mut w = BitWriter::new();
self.frame_header(&mut w, key, qidx, lf_level);
w.byte_align();
// tile_group_obu( ): a single tile, no tile_start_and_end_present_flag
let mut payload = w.into_bytes();
payload.extend_from_slice(&tile);
let mut out = Vec::with_capacity(payload.len() + 8);
obu(OBU_FRAME, &payload, &mut out);
let rf = RefFrame { planes: dec.rec, mvs: dec.mvs, lf_level, cdfs };
(out, rf)
}
/// The loop filter level minimising the luma error (searched around a guess from the
/// quantizer, on the luma of a subset of the superblock rows).
fn pick_filter_level(&self, rec: &[Plane; 3], info: &LfInfo, src: &[Plane; 3], qidx: u8) -> u32 {
let (w, h) = (self.geom.width, self.geom.height);
let sb_row_step = if self.geom.sb_rows >= 9 { 3 } else { 1 };
let sse = |pl: &Plane| -> u64 {
let mut s = 0u64;
for y in 0..h {
if !(y >> 6).is_multiple_of(sb_row_step) {
continue;
}
for (a, b) in pl.row(y)[..w].iter().zip(&src[0].row(y)[..w]) {
let d = *a as i64 - *b as i64;
s += (d * d) as u64;
}
}
s
};
let bd = self.cfg.bit_depth as u32;
let mut cache: Vec<(u32, u64)> = vec![(0, sse(&rec[0]))];
// one working copy of the luma plane for all candidate levels
let mut planes = [rec[0].clone(), Plane::new(0, 0), Plane::new(0, 0)];
let mut eval = |lvl: u32| -> u64 {
if let Some(&(_, e)) = cache.iter().find(|(l, _)| *l == lvl) {
return e;
}
planes[0].data.copy_from_slice(&rec[0].data);
loop_filter(&mut planes, info, [lvl; 4], bd, true, sb_row_step);
let e = sse(&planes[0]);
cache.push((lvl, e));
e
};
let guess = ((qidx as u32 * 3) / 16).clamp(2, 50);
let mut best = (0u32, eval(0));
let mut step = (guess / 2).max(1);
let mut center = guess;
let e = eval(center);
if e < best.1 {
best = (center, e);
}
while step >= 2 {
for lvl in [center.saturating_sub(step), (center + step).min(63)] {
let e = eval(lvl);
if e < best.1 {
best = (lvl, e);
}
}
center = best.0.max(1);
step /= 2;
}
best.0
}
/// Encodes one frame.
pub fn encode(&mut self, frame: &Frame) -> Packet {
let key = self.frame_num.is_multiple_of(self.cfg.keyint.max(1) as u64);
let src = self.load_source(frame);
let (frame_obu, rf) = match self.cfg.rate {
RateControl::ConstantQ(q) => self.encode_frame(&src, key, q.max(1)),
RateControl::Bitrate { .. } => match self.rc.take() {
Some(mut rc) => {
let out = self.encode_rate_controlled(&src, key, &mut rc);
self.rc = Some(rc);
out
}
// The state is created with the encoder for bitrate mode; without it, encode at a
// middle quantizer rather than fail.
None => self.encode_frame(&src, key, 128),
},
};
self.refr = Some(rf);
self.frame_num += 1;
let mut data = Vec::with_capacity(frame_obu.len() + self.seq_obu.len());
if key {
data.extend_from_slice(&self.seq_obu);
}
data.extend_from_slice(&frame_obu);
Packet { data, keyframe: key }
}
fn encode_rate_controlled(&mut self, src: &[Plane; 3], key: bool, rc: &mut RateState) -> (Vec<u8>, RefFrame) {
let first = self.frame_num == 0;
let (budget, q_start) = rc.frame_budget(self.cfg.keyint, key);
// pay back the accumulated deviation over the next RC_PAYBACK frames
let target = (budget - rc.debt / RC_PAYBACK).clamp(budget * 0.35, budget * 2.0);
let mut q = q_start;
let mut best: Option<(Vec<u8>, RefFrame, f64, f64)> = None;
// The first frame is coded up to four times to find its quantizer (it fixes the
// quantizers of everything after it), a later key frame up to three times (it is a large
// part of the budget of its group). A frame is coded again only while its size is far from
// the target and an untried quantizer is left to try; other frames are coded once.
let (max_passes, tolerance) = if first {
(RC_FIRST_PASSES, RC_FIRST_TOLERANCE)
} else if key {
(RC_KEY_PASSES, RC_KEY_TOLERANCE)
} else {
(1, 0.0)
};
let mut tried: Vec<(u8, f64)> = Vec::new();
for _ in 0..max_passes {
let qi = q.round().clamp(1.0, 255.0) as u8;
if tried.iter().any(|t| t.0 == qi) {
break;
}
let (obu, rf) = self.encode_frame(src, key, qi);
let bits = obu.len() as f64 * 8.0;
let err = (bits / target).log2();
tried.push((qi, err));
if best.as_ref().is_none_or(|b| err.abs() < (b.2 / target).log2().abs()) {
best = Some((obu, rf, bits, qi as f64));
}
if err.abs() <= tolerance {
break;
}
let next = if first && tried.len() == 1 {
Some((q + RC_FIRST_SLOPE * err).clamp(1.0, 255.0))
} else {
next_probe_q(self.cfg.bit_depth, &tried).map(f64::from)
};
match next {
Some(next) => q = next,
None => break,
}
}
// At least one pass ran, so `best` is set.
let Some((obu, rf, bits, q_used)) = best else { return self.encode_frame(src, key, q.round().clamp(1.0, 255.0) as u8) };
rc.debt += bits - budget;
rc.update(key, first, q_used, bits, target);
(obu, rf)
}
/// The loop filter level of the last encoded frame. For tests.
#[doc(hidden)]
pub fn last_loop_filter_level(&self) -> Option<u32> {
self.refr.as_ref().map(|r| r.lf_level)
}
/// The reconstruction of the last encoded frame (visible area, planes Y, U, V), equal to
/// what a decoder outputs. For tests.
#[doc(hidden)]
pub fn last_reconstruction(&self) -> Option<[Vec<u16>; 3]> {
let rf = self.refr.as_ref()?;
Some(std::array::from_fn(|p| {
let (vw, vh) = self.geom.visible(p);
let pl = &rf.planes[p];
let mut v = Vec::with_capacity(vw * vh);
for y in 0..vh {
v.extend_from_slice(&pl.row(y)[..vw]);
}
v
}))
}
}
-209
View File
@@ -1,209 +0,0 @@
//! Deblocking loop filter (spec 7.14), mirrored from the decoder process so that the encoder's
//! references equal a decoder's. Segmentation and loop filter deltas are off and the sharpness
//! is 0 in the frames this encoder writes.
use crate::pred::Plane;
use crate::tables::{MAX_LOOP_FILTER, NUM_4X4_BLOCKS_HIGH, NUM_4X4_BLOCKS_WIDE, SUBSAMPLED_SIZE, TX_HEIGHT, TX_WIDTH};
/// Mode info the loop filter reads (per 4x4 luma unit, row stride `mi_cols`), and the
/// transform size per 4x4 unit of each plane (`LoopfilterTxSizes`, row stride `mi_cols + 32`).
pub(crate) struct LfInfo<'a> {
pub mi_cols: usize,
pub mi_rows: usize,
pub width: usize,
pub height: usize,
pub mi_size: &'a [u8],
pub skip: &'a [bool],
pub is_inter: &'a [bool],
pub tx: [&'a [u8]; 3],
}
/// Applies the loop filter with `loop_filter_level[ 0..4 ]` to `planes`. For level search
/// (`luma_only`), only plane 0 and only every `sb_row_step`-th superblock row are filtered.
pub(crate) fn loop_filter(planes: &mut [Plane; 3], info: &LfInfo, level: [u32; 4], bit_depth: u32, luma_only: bool, sb_row_step: usize) {
if level[0] == 0 && level[1] == 0 {
return;
}
let nplanes = if luma_only { 1 } else { 3 };
for (plane, pl) in planes.iter_mut().enumerate().take(nplanes) {
if plane > 0 && level[1 + plane] == 0 {
continue;
}
for pass in 0..2 {
let step = if plane == 0 { 1 } else { 2 };
let mut row = 0;
while row < info.mi_rows {
if !(row >> 4).is_multiple_of(sb_row_step) {
row += step;
continue;
}
let mut col = 0;
while col < info.mi_cols {
edge(pl, info, level, bit_depth, plane, pass, (row, col));
col += step;
}
row += step;
}
}
}
}
fn edge(pl: &mut Plane, info: &LfInfo, level: [u32; 4], bd: u32, plane: usize, pass: usize, position: (usize, usize)) {
let (row, col) = position;
let s = (plane > 0) as usize;
let (dx, dy) = if pass == 0 { (1usize, 0usize) } else { (0, 1) };
let x = col * 4;
let y = row * 4;
let row = row | s;
let col = col | s;
let on_screen = !(x >= info.width || y >= info.height || (pass == 0 && x == 0) || (pass == 1 && y == 0));
if !on_screen {
return;
}
let xp = x >> s;
let yp = y >> s;
let prev_row = row - (dy << s);
let prev_col = col - (dx << s);
let i = row * info.mi_cols + col;
let mi_size = info.mi_size[i] as usize;
let tx_stride = info.mi_cols + 32;
let tx_sz = info.tx[plane][(row >> s) * tx_stride + (col >> s)] as usize;
let plane_size = SUBSAMPLED_SIZE[mi_size][s][s] as usize;
let skip = info.skip[i];
let is_intra = !info.is_inter[i];
let prev_tx_sz = info.tx[plane][(prev_row >> s) * tx_stride + (prev_col >> s)] as usize;
let is_block_edge = if pass == 0 {
xp.is_multiple_of(4 * NUM_4X4_BLOCKS_WIDE[plane_size] as usize)
} else {
yp.is_multiple_of(4 * NUM_4X4_BLOCKS_HIGH[plane_size] as usize)
};
let is_tx_edge = if pass == 0 { xp.is_multiple_of(TX_WIDTH[tx_sz] as usize) } else { yp.is_multiple_of(TX_HEIGHT[tx_sz] as usize) };
let apply_filter = is_tx_edge && (is_block_edge || !skip || is_intra);
let base_size = if pass == 0 { TX_WIDTH[prev_tx_sz].min(TX_WIDTH[tx_sz]) } else { TX_HEIGHT[prev_tx_sz].min(TX_HEIGHT[tx_sz]) } as usize;
let filter_size = if plane == 0 { 16.min(base_size) } else { 8.min(base_size) };
// 7.14.4 with no deltas, segmentation or sharpness: the same strength for every block
let lvl = level[if plane == 0 { pass } else { plane + 1 }].min(MAX_LOOP_FILTER as u32) as i32;
if !apply_filter || lvl == 0 {
return;
}
let limit = lvl.max(1);
let blimit = 2 * (lvl + 2) + limit;
let thresh = lvl >> 4;
let strength = FilterStrength { limit, blimit, thresh };
for k in 0..4 {
sample_filter(pl, (xp + dy * k, yp + dx * k), plane, &strength, (dx as isize, dy as isize), filter_size, bd);
}
}
/// Thresholds derived from the loop-filter level (spec 7.14.4).
struct FilterStrength {
limit: i32,
blimit: i32,
thresh: i32,
}
#[inline]
fn sample_filter(pl: &mut Plane, position: (usize, usize), plane: usize, strength: &FilterStrength, direction: (isize, isize), filter_size: usize, bd: u32) {
let (x, y) = position;
let (dx, dy) = direction;
let FilterStrength { limit, blimit, thresh } = *strength;
let stride = pl.stride as isize;
let step = dy * stride + dx;
let base = y as isize * stride + x as isize;
let reach: isize = if filter_size >= 16 { 7 } else { 4 };
let mut v = [0i32; 16];
for k in -reach..reach {
v[(k + 8) as usize] = pl.data[(base + k * step) as usize] as i32;
}
let at = |k: isize| -> i32 { v[(k + 8) as usize] };
let (q0, q1, q2, q3) = (at(0), at(1), at(2), at(3));
let (p0, p1, p2, p3) = (at(-1), at(-2), at(-3), at(-4));
let d = &mut pl.data;
let sh = bd - 8;
let thresh_bd = thresh << sh;
let hev = (p1 - p0).abs() > thresh_bd || (q1 - q0).abs() > thresh_bd;
let filter_len = if filter_size == 4 {
4
} else if plane != 0 {
6
} else if filter_size == 8 {
8
} else {
16
};
let limit_bd = limit << sh;
let blimit_bd = blimit << sh;
let mut mask = (p1 - p0).abs() > limit_bd || (q1 - q0).abs() > limit_bd || (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 > blimit_bd;
if filter_len >= 6 {
mask |= (p2 - p1).abs() > limit_bd || (q2 - q1).abs() > limit_bd;
}
if filter_len >= 8 {
mask |= (p3 - p2).abs() > limit_bd || (q3 - q2).abs() > limit_bd;
}
if mask {
return;
}
let t_bd = 1 << sh;
let flat = if filter_size >= 8 {
let mut m = (p1 - p0).abs() > t_bd || (q1 - q0).abs() > t_bd || (p2 - p0).abs() > t_bd || (q2 - q0).abs() > t_bd;
if filter_len >= 8 {
m |= (p3 - p0).abs() > t_bd || (q3 - q0).abs() > t_bd;
}
!m
} else {
false
};
let flat2 = if filter_size >= 16 {
let (q4, q5, q6, p4, p5, p6) = (at(4), at(5), at(6), at(-5), at(-6), at(-7));
!((p6 - p0).abs() > t_bd
|| (q6 - q0).abs() > t_bd
|| (p5 - p0).abs() > t_bd
|| (q5 - q0).abs() > t_bd
|| (p4 - p0).abs() > t_bd
|| (q4 - q0).abs() > t_bd)
} else {
false
};
if filter_size == 4 || !flat {
// narrow filter (7.14.6.3)
let half = 1i32 << (bd - 1);
let c = |v: i32| v.clamp(-half, half - 1);
let off = 0x80 << sh;
let (ps1, ps0, qs0, qs1) = (p1 - off, p0 - off, q0 - off, q1 - off);
let mut filter = if hev { c(ps1 - qs1) } else { 0 };
filter = c(filter + 3 * (qs0 - ps0));
let filter1 = c(filter + 4) >> 3;
let filter2 = c(filter + 3) >> 3;
d[base as usize] = (c(qs0 - filter1) + off) as u16;
d[(base - step) as usize] = (c(ps0 + filter2) + off) as u16;
if !hev {
let f = (filter1 + 1) >> 1;
d[(base + step) as usize] = (c(qs1 - f) + off) as u16;
d[(base - 2 * step) as usize] = (c(ps1 + f) + off) as u16;
}
} else {
// wide filter (7.14.6.4)
let log2 = if filter_size == 8 || !flat2 { 3 } else { 4 };
let n: isize = if log2 == 4 {
6
} else if plane == 0 {
3
} else {
2
};
let n2: isize = if log2 == 3 && plane == 0 { 0 } else { 1 };
let mut f = [0i32; 12];
for i in -n..n {
let mut t = 0;
for j in -n..=n {
let p = (i + j).clamp(-(n + 1), n);
let tap = if j.abs() <= n2 { 2 } else { 1 };
t += at(p) * tap;
}
f[(i + n) as usize] = (t + (1 << (log2 - 1))) >> log2;
}
for i in -n..n {
d[(base + i * step) as usize] = f[(i + n) as usize] as u16;
}
}
}
-445
View File
@@ -1,445 +0,0 @@
//! Prediction processes, mirrored from the spec (7.11.2 intra prediction for the non-directional
//! modes plus V_PRED / H_PRED without edge filtering, 7.11.3 block inter prediction without
//! reference scaling) so that the encoder predicts exactly like a decoder.
use crate::tables::{
DC_PRED, EIGHTTAP, H_PRED, PAETH_PRED, SM_WEIGHTS_TX_4X4, SM_WEIGHTS_TX_8X8, SM_WEIGHTS_TX_16X16, SM_WEIGHTS_TX_32X32, SMOOTH_H_PRED, SMOOTH_PRED,
SMOOTH_V_PRED, SUBPEL_FILTERS, V_PRED,
};
use crate::transform::round2;
/// A plane buffer (padded to whole superblocks).
#[derive(Clone)]
pub(crate) struct Plane {
pub data: Vec<u16>,
pub stride: usize,
}
impl Plane {
pub fn new(w: usize, h: usize) -> Plane {
Plane { data: vec![0; w * h], stride: w }
}
#[inline(always)]
pub fn at(&self, x: usize, y: usize) -> u16 {
self.data[y * self.stride + x]
}
#[inline(always)]
pub fn row(&self, y: usize) -> &[u16] {
&self.data[y * self.stride..(y + 1) * self.stride]
}
}
/// The intra modes this encoder uses (values are the spec's y / uv mode numbers).
pub(crate) const INTRA_MODES_USED: [usize; 7] = [DC_PRED, V_PRED, H_PRED, PAETH_PRED, SMOOTH_PRED, SMOOTH_V_PRED, SMOOTH_H_PRED];
/// Inputs of the intra prediction process.
pub(crate) struct IntraEdge {
pub x: usize,
pub y: usize,
pub have_left: bool,
pub have_above: bool,
pub have_above_right: bool,
pub have_below_left: bool,
pub log2: u32,
/// ((MiCols * MI_SIZE) >> subX) - 1 and the same for rows.
pub max_x: i32,
pub max_y: i32,
pub bit_depth: u32,
}
/// Edge samples: `above[0..2n]`, `left[0..2n]` and the top-left corner.
pub(crate) struct Edges {
above: [i32; 64],
left: [i32; 64],
corner: i32,
}
pub(crate) fn edges(pl: &Plane, e: &IntraEdge) -> Edges {
let w = 1usize << e.log2;
let h = w;
let bd = e.bit_depth;
let (x, y) = (e.x, e.y);
let n = w + h;
let mut above = [0i32; 64];
let mut left = [0i32; 64];
if !e.have_above && e.have_left {
let v = pl.at(x - 1, y) as i32;
above[..n].iter_mut().for_each(|a| *a = v);
} else if !e.have_above && !e.have_left {
let v = (1 << (bd - 1)) - 1;
above[..n].iter_mut().for_each(|a| *a = v);
} else {
let above_limit = e.max_x.min(x as i32 + if e.have_above_right { 2 * w as i32 } else { w as i32 } - 1);
let row = pl.row(y - 1);
for (i, a) in above[..n].iter_mut().enumerate() {
*a = row[above_limit.min(x as i32 + i as i32) as usize] as i32;
}
}
if !e.have_left && e.have_above {
let v = pl.at(x, y - 1) as i32;
left[..n].iter_mut().for_each(|a| *a = v);
} else if !e.have_left && !e.have_above {
let v = (1 << (bd - 1)) + 1;
left[..n].iter_mut().for_each(|a| *a = v);
} else {
let left_limit = e.max_y.min(y as i32 + if e.have_below_left { 2 * h as i32 } else { h as i32 } - 1);
for (i, l) in left[..n].iter_mut().enumerate() {
*l = pl.at(x - 1, left_limit.min(y as i32 + i as i32) as usize) as i32;
}
}
let corner = if e.have_above && e.have_left {
pl.at(x - 1, y - 1) as i32
} else if e.have_above {
pl.at(x, y - 1) as i32
} else if e.have_left {
pl.at(x - 1, y) as i32
} else {
1 << (bd - 1)
};
Edges { above, left, corner }
}
fn sm_weights(log2: u32) -> &'static [u8] {
match log2 {
2 => &SM_WEIGHTS_TX_4X4,
3 => &SM_WEIGHTS_TX_8X8,
4 => &SM_WEIGHTS_TX_16X16,
_ => &SM_WEIGHTS_TX_32X32,
}
}
/// Predicts a square `2^log2` block with `mode` into `pred` (row stride = block width).
pub(crate) fn predict_intra(ed: &Edges, e: &IntraEdge, mode: usize, pred: &mut [u16]) {
let log2 = e.log2;
let w = 1usize << log2;
let h = w;
let bd = e.bit_depth;
let (above, left) = (&ed.above, &ed.left);
match mode {
DC_PRED => {
let v = if e.have_left && e.have_above {
let sum: i32 = left[..h].iter().sum::<i32>() + above[..w].iter().sum::<i32>() + ((w + h) >> 1) as i32;
sum / (w + h) as i32
} else if e.have_left {
(left[..h].iter().sum::<i32>() + (h >> 1) as i32) >> log2
} else if e.have_above {
(above[..w].iter().sum::<i32>() + (w >> 1) as i32) >> log2
} else {
1 << (bd - 1)
};
let v = v.clamp(0, (1 << bd) - 1) as u16;
pred[..w * h].iter_mut().for_each(|p| *p = v);
}
V_PRED => {
for i in 0..h {
for j in 0..w {
pred[i * w + j] = above[j] as u16;
}
}
}
H_PRED => {
for i in 0..h {
pred[i * w..i * w + w].iter_mut().for_each(|p| *p = left[i] as u16);
}
}
PAETH_PRED => {
let tl = ed.corner;
for i in 0..h {
for j in 0..w {
let a = above[j];
let l = left[i];
let base = a + l - tl;
let p_left = (base - l).abs();
let p_top = (base - a).abs();
let p_tl = (base - tl).abs();
pred[i * w + j] = if p_left <= p_top && p_left <= p_tl {
l as u16
} else if p_top <= p_tl {
a as u16
} else {
tl as u16
};
}
}
}
_ => {
let wx = sm_weights(log2);
let wy = wx;
for i in 0..h {
for j in 0..w {
let v = if mode == SMOOTH_PRED {
let s = wy[i] as i32 * above[j] + (256 - wy[i] as i32) * left[h - 1] + wx[j] as i32 * left[i] + (256 - wx[j] as i32) * above[w - 1];
round2(s, 9)
} else if mode == SMOOTH_V_PRED {
round2(wy[i] as i32 * above[j] + (256 - wy[i] as i32) * left[h - 1], 8)
} else {
round2(wx[j] as i32 * left[i] + (256 - wx[j] as i32) * above[w - 1], 8)
};
pred[i * w + j] = v as u16;
}
}
}
}
}
/// Block inter prediction (7.11.3.3 motion vector scaling without scaling, 7.11.3.4 block
/// inter prediction with the EIGHTTAP filter, single reference so InterRound1 = 11 and the
/// final rounding is the identity) of the `w x h` block at plane position (x, y) displaced by
/// `mv` (1/8 luma sample units, [row, col]). `last_x` / `last_y` are the largest sample
/// coordinates of the reference plane; the result goes to `pred` (row stride `w`).
pub(crate) struct InterBlock {
pub last_x: i32,
pub last_y: i32,
pub x: usize,
pub y: usize,
pub width: usize,
pub height: usize,
pub mv: [i32; 2],
pub subsampling: usize,
pub bit_depth: u32,
}
pub(crate) fn predict_inter(refp: &Plane, block: &InterBlock, pred: &mut [u16]) {
let InterBlock { last_x, last_y, x, y, width: w, height: h, mv, subsampling: ss, bit_depth } = *block;
// positions in 1/16 sample units ((startX >> 6) & 15 is the filter phase)
let px = ((x as i32) << 4) + ((2 * mv[1]) >> ss);
let py = ((y as i32) << 4) + ((2 * mv[0]) >> ss);
let (fx, fy) = ((px & 15) as usize, (py & 15) as usize);
let (ix, iy) = (px >> 4, py >> 4);
let max = (1i32 << bit_depth) - 1;
if fx == 0 && fy == 0 {
// the filters' phase-0 kernel is a unit impulse: a clamped copy
for r in 0..h {
let ry = (iy + r as i32).clamp(0, last_y) as usize;
let row = refp.row(ry);
let out = &mut pred[r * w..r * w + w];
let x0 = ix;
if x0 >= 0 && x0 + w as i32 - 1 <= last_x {
out.copy_from_slice(&row[x0 as usize..x0 as usize + w]);
} else {
for (c, o) in out.iter_mut().enumerate() {
*o = row[(x0 + c as i32).clamp(0, last_x) as usize];
}
}
}
return;
}
let filt_h = if w <= 4 { 4 } else { EIGHTTAP };
let filt_v = if h <= 4 { 4 } else { EIGHTTAP };
let kh = &SUBPEL_FILTERS[filt_h][fx];
let kv = &SUBPEL_FILTERS[filt_v][fy];
let bx = ix - 3;
let x_inside = bx >= 0 && bx + w as i32 + 7 <= last_x + 1;
// horizontal pass of one reference row into `out` (Round2( sum, InterRound0 = 3 ))
let hfilter = |ry: usize, out: &mut [i32]| {
let row = refp.row(ry);
if x_inside {
let seg = &row[bx as usize..bx as usize + w + 7];
for (c, o) in out.iter_mut().enumerate() {
let mut s = 0i32;
for t in 0..8 {
s += kh[t] as i32 * seg[c + t] as i32;
}
*o = round2(s, 3);
}
} else {
for (c, o) in out.iter_mut().enumerate() {
let mut s = 0i32;
for t in 0..8 {
s += kh[t] as i32 * row[(bx + c as i32 + t as i32).clamp(0, last_x) as usize] as i32;
}
*o = round2(s, 3);
}
}
};
let mut inter = [0i32; (64 + 7) * 64];
if fy == 0 {
// the vertical kernel is 128 at the centre: Round2( 128 * v, 11 ) = Round2( v, 4 )
for r in 0..h {
let ry = (iy + r as i32).clamp(0, last_y) as usize;
hfilter(ry, &mut inter[..w]);
for (p, &v) in pred[r * w..r * w + w].iter_mut().zip(&inter[..w]) {
*p = round2(v, 4).clamp(0, max) as u16;
}
}
return;
}
if fx == 0 {
// the horizontal pass is exactly 16 * sample: Round2( 16 * sum, 11 ) = Round2( sum, 7 )
for r in 0..h {
let rows: [&[u16]; 8] = std::array::from_fn(|t| refp.row((iy + r as i32 + t as i32 - 3).clamp(0, last_y) as usize));
for c in 0..w {
let xx = if x_inside { (ix + c as i32) as usize } else { (ix + c as i32).clamp(0, last_x) as usize };
let mut s = 0i32;
for t in 0..8 {
s += kv[t] as i32 * rows[t][xx] as i32;
}
pred[r * w + c] = round2(s, 7).clamp(0, max) as u16;
}
}
return;
}
let inter_h = h + 7;
for r in 0..inter_h {
let ry = (iy + r as i32 - 3).clamp(0, last_y) as usize;
hfilter(ry, &mut inter[r * w..r * w + w]);
}
for r in 0..h {
for c in 0..w {
let mut s = 0i32;
for t in 0..8 {
s += kv[t] as i32 * inter[(r + t) * w + c];
}
pred[r * w + c] = round2(s, 11).clamp(0, max) as u16;
}
}
}
/// The visible `w x h` area of a reference plane interpolated at the sub-sample phase
/// (`fx`, `fy`) (1/16 units) with the EIGHTTAP filter, as `predict_inter` computes it for
/// blocks wider and taller than 4. The reference for `half_planes`, which the encoder uses.
#[cfg(test)]
pub(crate) fn subpel_plane(refp: &Plane, w: usize, h: usize, fx: usize, fy: usize, bit_depth: u32) -> Vec<u16> {
let kh = &SUBPEL_FILTERS[EIGHTTAP][fx];
let kv = &SUBPEL_FILTERS[EIGHTTAP][fy];
let max = (1i32 << bit_depth) - 1;
let (lx, ly) = (w as i32 - 1, h as i32 - 1);
let mut inter = vec![0i32; w * h];
for y in 0..h {
let row = refp.row(y);
for x in 0..w {
let mut s = 0i32;
for t in 0..8 {
s += kh[t] as i32 * row[(x as i32 + t as i32 - 3).clamp(0, lx) as usize] as i32;
}
inter[y * w + x] = round2(s, 3);
}
}
let mut out = vec![0u16; w * h];
for y in 0..h {
for x in 0..w {
let mut s = 0i32;
for t in 0..8 {
s += kv[t] as i32 * inter[(y as i32 + t as i32 - 3).clamp(0, ly) as usize * w + x];
}
out[y * w + x] = round2(s, 11).clamp(0, max) as u16;
}
}
out
}
/// The three half-sample planes (8, 0), (0, 8), (8, 8) of `subpel_plane` in one pass: the
/// horizontal half-sample pass is shared by (8, 0) and (8, 8), and the phase-0 kernels reduce to
/// exact shifts (Round2( 128 * v, 11 ) = Round2( v, 4 ), Round2( 16 * s, 11 ) = Round2( s, 7 )),
/// so the result equals three `subpel_plane` calls bit for bit.
pub(crate) fn half_planes(refp: &Plane, w: usize, h: usize, bit_depth: u32) -> [Vec<u16>; 3] {
let k = &SUBPEL_FILTERS[EIGHTTAP][8];
let max = (1i32 << bit_depth) - 1;
let (lx, ly) = (w as i32 - 1, h as i32 - 1);
// horizontal pass at phase 8: Round2( sum, 3 )
let mut hp = vec![0i32; w * h];
for y in 0..h {
let row = &refp.row(y)[..w];
let out = &mut hp[y * w..y * w + w];
let tap = |x: i32| -> i32 {
let mut s = 0i32;
for t in 0..8 {
s += k[t] as i32 * row[(x + t as i32 - 3).clamp(0, lx) as usize] as i32;
}
round2(s, 3)
};
if w >= 8 {
for x in 0..3 {
out[x] = tap(x as i32);
}
for (x, o) in out.iter_mut().enumerate().take(w - 4).skip(3) {
let seg = &row[x - 3..x + 5];
let mut s = 0i32;
for t in 0..8 {
s += k[t] as i32 * seg[t] as i32;
}
*o = round2(s, 3);
}
for x in w - 4..w {
out[x] = tap(x as i32);
}
} else {
for (x, o) in out.iter_mut().enumerate() {
*o = tap(x as i32);
}
}
}
let p80: Vec<u16> = hp.iter().map(|&v| round2(v, 4).clamp(0, max) as u16).collect();
let mut p08 = vec![0u16; w * h];
let mut p88 = vec![0u16; w * h];
for y in 0..h {
let rows: [usize; 8] = std::array::from_fn(|t| (y as i32 + t as i32 - 3).clamp(0, ly) as usize);
let (o08, o88) = (&mut p08[y * w..y * w + w], &mut p88[y * w..y * w + w]);
for x in 0..w {
let (mut a, mut b) = (0i32, 0i32);
for t in 0..8 {
a += k[t] as i32 * refp.data[rows[t] * refp.stride + x] as i32;
b += k[t] as i32 * hp[rows[t] * w + x];
}
o08[x] = round2(a, 7).clamp(0, max) as u16;
o88[x] = round2(b, 11).clamp(0, max) as u16;
}
}
[p80, p08, p88]
}
#[cfg(test)]
mod tests {
use super::*;
/// Whole-plane interpolation equals block inter prediction at the same phase.
#[test]
fn subpel_plane_matches_block_prediction() {
let (w, h) = (37, 29);
let mut p = Plane::new(64, 64);
for (i, v) in p.data.iter_mut().enumerate() {
*v = ((i * 7919) % 256) as u16;
}
for (fx, fy) in [(8, 0), (0, 8), (8, 8), (4, 12)] {
let plane = subpel_plane(&p, w, h, fx, fy, 8);
for (bx, by) in [(0i32, 0i32), (8, 8), (24, 16), (-5, 20), (30, -3)] {
let mut pred = vec![0u16; 64];
let mv = [by * 8 + fy as i32 / 2, bx * 8 + fx as i32 / 2];
predict_inter(
&p,
&InterBlock { last_x: w as i32 - 1, last_y: h as i32 - 1, x: 0, y: 0, width: 8, height: 8, mv, subsampling: 0, bit_depth: 8 },
&mut pred,
);
for r in 0..8 {
for c in 0..8 {
let (x, y) = ((bx + c).clamp(0, w as i32 - 1), (by + r).clamp(0, h as i32 - 1));
if bx + c == x && by + r == y {
assert_eq!(pred[(r * 8 + c) as usize], plane[y as usize * w + x as usize], "phase ({fx}, {fy}) at ({}, {})", bx + c, by + r);
}
}
}
}
}
}
#[test]
fn half_planes_match_subpel_plane() {
for (w, h) in [(37usize, 29usize), (5, 3), (1, 1), (64, 64)] {
let mut p = Plane::new(64, 64);
for (i, v) in p.data.iter_mut().enumerate() {
*v = ((i * 7919) % 1024) as u16;
}
let hp = half_planes(&p, w, h, 10);
for (i, (fx, fy)) in [(8, 0), (0, 8), (8, 8)].into_iter().enumerate() {
assert_eq!(hp[i], subpel_plane(&p, w, h, fx, fy, 10), "{w}x{h} phase ({fx}, {fy})");
}
}
}
#[test]
fn phase_zero_filters_are_impulses() {
for f in SUBPEL_FILTERS.iter() {
assert_eq!(f[0], [0, 0, 0, 128, 0, 0, 0, 0]);
}
}
}
-267
View File
@@ -1,267 +0,0 @@
//! Multi-symbol arithmetic encoder: the exact inverse of the symbol decoder of spec 8.2.
//!
//! The decoder keeps `SymbolValue`, the bitwise complement of a 15-bit window into the tile data
//! minus the lower bounds of the symbols decoded so far, and selects symbol `k` when
//! `cur(k) <= SymbolValue < cur(k - 1)` with
//! `cur(k) = ((SymbolRange >> 8) * ((32768 - cdf[k]) >> 6) >> 1) + 4 * (N - k - 1)` and
//! `cur(-1) = SymbolRange`. The encoder therefore runs an ordinary carry-propagating range
//! coder over the complemented bit stream: coding symbol `k` adds `cur(k)` to `low` and sets the
//! range to `cur(k - 1) - cur(k)`; both are renormalised exactly like the decoder's range.
//!
//! At the end (spec 8.2.4 exit process) the decoder has consumed `S` renormalisation bits plus a
//! 15-bit window, and the bits from position `S` on must be a one followed by zeros. In the
//! complemented domain that window is `0b011_1111_1111_1111`, so the encoder picks the `S`-bit
//! prefix `D` with `D * 2^15 + 2^14 - 1` inside `[low, low + range)`, i.e.
//! `D = (low + 2^14) >> 15`, and writes `!D`, a one bit and zero padding.
pub(crate) struct SymbolWriter {
/// Low end of the interval, holding `15 + cnt` bits not yet moved to `out` (plus carries).
low: u64,
rng: u32,
cnt: u32,
out: Vec<u8>,
pub disable_update: bool,
}
impl SymbolWriter {
pub fn new(disable_update: bool) -> Self {
SymbolWriter { low: 0, rng: 1 << 15, cnt: 0, out: Vec::with_capacity(1 << 16), disable_update }
}
/// Adds `k` to the bytes already output (carry propagation).
fn carry(&mut self, mut k: u64) {
let mut i = self.out.len();
while k != 0 {
i -= 1;
let t = self.out[i] as u64 + k;
self.out[i] = t as u8;
k = t >> 8;
}
}
#[inline(always)]
fn encode(&mut self, cdf: &[u16], n: usize, s: usize) {
let r8 = self.rng >> 8;
let cur = |k: usize| -> u32 { ((r8 * ((32768 - cdf[k] as u32) >> 6)) >> 1) + 4 * (n - k - 1) as u32 };
let hi = if s == 0 { self.rng } else { cur(s - 1) };
let lo = cur(s);
debug_assert!(hi > lo, "symbol {s} has an empty interval");
self.low += lo as u64;
self.rng = hi - lo;
let d = 15 - (31 - self.rng.leading_zeros());
if d == 0 {
return;
}
self.rng <<= d;
self.low <<= d;
self.cnt += d;
while self.cnt >= 8 {
let sh = 15 + self.cnt - 8;
let c = self.low >> sh;
self.low &= (1u64 << sh) - 1;
self.cnt -= 8;
self.carry(c >> 8);
self.out.push((c & 0xff) as u8);
}
}
/// Codes `s` with the adaptive CDF `cdf` (N values plus the adaptation counter).
#[inline]
pub fn symbol(&mut self, s: usize, cdf: &mut [u16]) {
let n = cdf.len() - 1;
debug_assert!(s < n);
self.encode(cdf, n, s);
if !self.disable_update {
update_cdf(cdf, n, s);
}
}
/// Codes `s` with a CDF that is not adapted.
pub fn symbol_fixed(&mut self, s: usize, cdf: &[u16]) {
let n = cdf.len() - 1;
self.encode(cdf, n, s);
}
/// `read_bool()` counterpart.
pub fn bool(&mut self, b: bool) {
self.encode(&[1 << 14, 1 << 15, 0], 2, b as usize);
}
/// `L(n)` counterpart (most significant bit first).
#[cfg(test)]
pub fn literal(&mut self, n: u32, v: u32) {
for i in (0..n).rev() {
self.bool((v >> i) & 1 != 0);
}
}
/// Finishes the tile: returns its bytes (with the trailing one bit and zero padding).
pub fn finish(mut self) -> Vec<u8> {
let low = self.low + (1 << 14);
let mut tail = low >> 15;
self.carry(tail >> self.cnt);
tail &= (1u64 << self.cnt) - 1;
let mut bytes: Vec<u8> = self.out.iter().map(|b| !b).collect();
let n = self.cnt + 1; // 1..=8 bits: !tail then the trailing one bit
let v = (((!tail) & ((1u64 << self.cnt) - 1)) << 1) | 1;
bytes.push((v << (8 - n)) as u8);
bytes
}
}
/// CDF adaptation (spec 8.2.6, as in the decoder).
#[inline(always)]
pub(crate) fn update_cdf(cdf: &mut [u16], n: usize, symbol: usize) {
let count = cdf[n];
let rate = 3 + (count > 15) as u32 + (count > 31) as u32 + (31 - (n as u32).leading_zeros()).min(2);
let mut tmp = 0u32;
for i in 0..n - 1 {
if i == symbol {
tmp = 1 << 15;
}
let c = cdf[i] as u32;
if tmp < c {
cdf[i] = (c - ((c - tmp) >> rate)) as u16;
} else {
cdf[i] = (c + ((tmp - c) >> rate)) as u16;
}
}
cdf[n] += (count < 32) as u16;
}
#[cfg(test)]
mod tests {
use super::*;
/// The spec's symbol decoder (8.2.2 - 8.2.4), for checking the encoder.
struct Dec<'a> {
data: &'a [u8],
pos: usize,
value: u32,
range: u32,
max_bits: i64,
}
impl<'a> Dec<'a> {
fn new(data: &'a [u8]) -> Self {
let mut d = Dec { data, pos: 0, value: 0, range: 1 << 15, max_bits: 8 * data.len() as i64 - 15 };
let nb = (data.len() * 8).min(15) as u32;
let buf = d.bits(nb);
d.value = ((1 << 15) - 1) ^ (buf << (15 - nb));
d
}
fn bits(&mut self, n: u32) -> u32 {
let mut x = 0;
for _ in 0..n {
let b = if self.pos < self.data.len() * 8 { (self.data[self.pos >> 3] >> (7 - (self.pos & 7))) & 1 } else { 0 };
self.pos += 1;
x = (x << 1) | b as u32;
}
x
}
fn symbol(&mut self, cdf: &mut [u16], adapt: bool) -> usize {
let n = cdf.len() - 1;
let mut cur = self.range;
let mut s = 0;
let mut prev;
loop {
prev = cur;
let f = (1u32 << 15) - cdf[s] as u32;
cur = (((self.range >> 8) * (f >> 6)) >> 1) + 4 * (n - s - 1) as u32;
if self.value >= cur {
break;
}
s += 1;
}
self.range = prev - cur;
self.value -= cur;
let b = 15 - (31 - self.range.leading_zeros());
if b > 0 {
self.range <<= b;
let nb = (b as i64).min(self.max_bits.max(0)) as u32;
let nd = self.bits(nb) << (b - nb);
self.value = nd ^ (((self.value + 1) << b) - 1);
self.max_bits -= b as i64;
}
if adapt {
update_cdf(cdf, n, s);
}
s
}
/// Position of the trailing one bit (8.2.4).
fn trailing_position(&self) -> i64 {
let consumed = (self.pos as i64).min(self.data.len() as i64 * 8);
consumed - (15i64).min(self.max_bits + 15)
}
}
#[test]
fn bools_only() {
for len in 1..200 {
let bits: Vec<bool> = (0..len).map(|i| (i * 7 + len) % 3 == 0).collect();
let mut w = SymbolWriter::new(false);
for &b in &bits {
w.bool(b);
}
let data = w.finish();
let mut d = Dec::new(&data);
for (i, &b) in bits.iter().enumerate() {
assert_eq!(d.symbol(&mut [1 << 14, 1 << 15, 0], false) == 1, b, "len {len} bit {i} data {data:?}");
}
}
}
#[test]
fn round_trip_random_symbols() {
let mut seed = 0x1234_5678u32;
let mut rnd = || {
seed ^= seed << 13;
seed ^= seed >> 17;
seed ^= seed << 5;
seed
};
for trial in 0..300 {
let count = 1 + (rnd() % 3000) as usize;
let mut cdfs_e = vec![[4096u16, 11264, 19328, 32768, 0]; 4];
let mut cdfs_d = cdfs_e.clone();
let mut syms = Vec::new();
let mut w = SymbolWriter::new(false);
for _ in 0..count {
let kind = rnd() % 3;
let ctx = (rnd() % 4) as usize;
// skewed symbols so that the range also gets small
let s = if rnd() % 4 == 0 { (rnd() % 4) as usize } else { 0 };
match kind {
0 => w.symbol(s, &mut cdfs_e[ctx]),
1 => w.bool(s & 1 == 1),
_ => w.literal(5, s as u32 * 7),
}
syms.push((kind, ctx, s));
}
let data = w.finish();
let mut d = Dec::new(&data);
for (idx, &(kind, ctx, s)) in syms.iter().enumerate() {
let got = match kind {
0 => d.symbol(&mut cdfs_d[ctx], true),
1 => d.symbol(&mut [1 << 14, 1 << 15, 0], false),
_ => {
let mut v = 0;
for _ in 0..5 {
v = (v << 1) | d.symbol(&mut [1 << 14, 1 << 15, 0], false);
}
v / 7
}
};
let want = if kind == 1 { s & 1 } else { s };
assert_eq!(got, want, "trial {trial} idx {idx} kind {kind} of {}", syms.len());
}
let tp = d.trailing_position();
assert!(tp >= 0 && (tp as usize) < data.len() * 8, "trial {trial}: trailing bit position {tp}");
let tp = tp as usize;
assert_eq!((data[tp >> 3] >> (7 - (tp & 7))) & 1, 1, "trial {trial}: trailing one bit");
for p in tp + 1..data.len() * 8 {
assert_eq!((data[p >> 3] >> (7 - (p & 7))) & 1, 0, "trial {trial}: padding");
}
}
}
}
File diff suppressed because it is too large. Load diff
-575
View File
@@ -1,575 +0,0 @@
//! Transforms. The inverse transforms are the normative ones of spec 7.13 (mirrored from
//! filmcraft-av1, so that the encoder reconstructs exactly like a decoder); the forward
//! transforms are floating-point matrices scaled to match them (not normative).
use std::sync::OnceLock;
use crate::tables::{ADST_ADST, ADST_DCT, COS128_LOOKUP, DCT_ADST, DCT_DCT, TRANSFORM_ROW_SHIFT, TX_WIDTH_LOG2};
#[inline(always)]
fn round2_64(x: i64, n: u32) -> i32 {
if n == 0 { x as i32 } else { ((x + (1i64 << (n - 1))) >> n) as i32 }
}
#[inline(always)]
pub(crate) fn round2(x: i32, n: u32) -> i32 {
if n == 0 { x } else { (x + (1 << (n - 1))) >> n }
}
#[inline(always)]
fn cos128(angle: i32) -> i64 {
let a = (angle & 255) as usize;
(match a {
0..=64 => COS128_LOOKUP[a] as i32,
65..=128 => -(COS128_LOOKUP[128 - a] as i32),
129..=192 => -(COS128_LOOKUP[a - 128] as i32),
_ => COS128_LOOKUP[256 - a] as i32,
}) as i64
}
#[inline(always)]
fn sin128(angle: i32) -> i64 {
cos128(angle - 64)
}
#[inline(always)]
fn brev(num_bits: u32, x: usize) -> usize {
let mut t = 0;
for i in 0..num_bits {
let bit = (x >> i) & 1;
t += bit << (num_bits - 1 - i);
}
t
}
#[inline(always)]
fn bf(t: &mut [i32], a: usize, b: usize, angle: i32, flip: bool) {
let x = t[a] as i64 * cos128(angle) - t[b] as i64 * sin128(angle);
let y = t[a] as i64 * sin128(angle) + t[b] as i64 * cos128(angle);
t[a] = round2_64(x, 12);
t[b] = round2_64(y, 12);
if flip {
t.swap(a, b);
}
}
#[inline(always)]
fn hd(t: &mut [i32], a: usize, b: usize, flip: bool, r: u32) {
let (a, b) = if flip { (b, a) } else { (a, b) };
let x = t[a];
let y = t[b];
let lo = -(1i32 << (r - 1));
let hi = (1i32 << (r - 1)) - 1;
t[a] = (x + y).clamp(lo, hi);
t[b] = (x - y).clamp(lo, hi);
}
/// Inverse DCT of length 2^N, N = 2..=5 (7.13.2.3), in place. `N` is a const generic so that the
/// bit-reversal permutations and loop bounds fold at compile time.
#[inline(always)]
fn inverse_dct_n<const N: u32>(t: &mut [i32], r: u32) {
let n = N;
let len = 1usize << n;
let mut copy = [0i32; 32];
copy[..len].copy_from_slice(&t[..len]);
for i in 0..len {
t[i] = copy[brev(n, i)];
}
inverse_dct_initial_stages(t, n, r);
inverse_dct_final_stages(t, n, r);
}
/// Rotate the high-frequency branches before the four-point core.
#[inline(always)]
fn inverse_dct_initial_stages(t: &mut [i32], n: u32, r: u32) {
if n >= 5 {
for i in 0..8 {
bf(t, 16 + i, 31 - i, 6 + ((brev(3, 7 - i) as i32) << 3), false);
}
}
if n >= 4 {
for i in 0..4 {
bf(t, 8 + i, 15 - i, 12 + ((brev(2, 3 - i) as i32) << 4), false);
}
}
if n >= 5 {
for i in 0..8 {
hd(t, 16 + 2 * i, 17 + 2 * i, i & 1 == 1, r);
}
}
if n >= 3 {
for i in 0..2 {
bf(t, 4 + i, 7 - i, 56 - 32 * i as i32, false);
}
}
if n >= 4 {
for i in 0..4 {
hd(t, 8 + 2 * i, 9 + 2 * i, i & 1 == 1, r);
}
}
if n >= 5 {
for i in 0..2 {
for j in 0..2 {
bf(t, 30 - 4 * i - j, 17 + 4 * i + j, 24 + ((j as i32) << 6) + (((1 - i) as i32) << 5), true);
}
}
}
}
/// Evaluate the four-point core and merge progressively larger branches.
#[inline(always)]
fn inverse_dct_final_stages(t: &mut [i32], n: u32, r: u32) {
for i in 0..2 {
bf(t, 2 * i, 2 * i + 1, 32 + 16 * i as i32, i == 0);
}
if n >= 3 {
for i in 0..2 {
hd(t, 4 + 2 * i, 5 + 2 * i, i == 1, r);
}
}
if n >= 4 {
for i in 0..2 {
bf(t, 14 - i, 9 + i, 48 + 64 * i as i32, true);
}
}
if n >= 5 {
for i in 0..4 {
for j in 0..2 {
hd(t, 16 + 4 * i + j, 19 + 4 * i - j, i & 1 == 1, r);
}
}
}
for i in 0..2 {
hd(t, i, 3 - i, false, r);
}
if n >= 3 {
bf(t, 6, 5, 32, true);
}
if n >= 4 {
for i in 0..2 {
for j in 0..2 {
hd(t, 8 + 4 * i + j, 11 + 4 * i - j, i == 1, r);
}
}
}
if n >= 5 {
for i in 0..4 {
bf(t, 29 - i, 18 + i, 48 + (i as i32 >> 1) * 64, true);
}
}
if n >= 3 {
for i in 0..4 {
hd(t, i, 7 - i, false, r);
}
}
if n >= 4 {
for i in 0..2 {
bf(t, 13 - i, 10 + i, 32, true);
}
}
if n >= 5 {
for i in 0..2 {
for j in 0..4 {
hd(t, 16 + i * 8 + j, 23 + i * 8 - j, i == 1, r);
}
}
}
if n >= 4 {
for i in 0..8 {
hd(t, i, 15 - i, false, r);
}
}
if n >= 5 {
for i in 0..4 {
bf(t, 27 - i, 20 + i, 32, true);
}
}
if n >= 5 {
for i in 0..16 {
hd(t, i, 31 - i, false, r);
}
}
}
const SINPI_1_9: i64 = 1321;
const SINPI_2_9: i64 = 2482;
const SINPI_3_9: i64 = 3344;
const SINPI_4_9: i64 = 3803;
#[inline(always)]
fn inverse_adst4(t: &mut [i32]) {
let (t0, t1, t2, t3) = (t[0] as i64, t[1] as i64, t[2] as i64, t[3] as i64);
let mut s = [SINPI_1_9 * t0, SINPI_2_9 * t0, SINPI_3_9 * t1, SINPI_4_9 * t2, SINPI_1_9 * t2, SINPI_2_9 * t3, SINPI_4_9 * t3];
let a7 = t0 - t2;
let b7 = a7 + t3;
s[0] += s[3];
s[1] -= s[4];
s[3] = s[2];
s[2] = SINPI_3_9 * b7;
s[0] += s[5];
s[1] -= s[6];
let x = [s[0] + s[3], s[1] + s[3], s[2], s[0] + s[1] - s[3]];
for i in 0..4 {
t[i] = round2_64(x[i], 12);
}
}
#[inline(always)]
fn adst_in_permute<const N: u32>(t: &mut [i32]) {
let n = N;
let n0 = 1usize << n;
let mut copy = [0i32; 16];
copy[..n0].copy_from_slice(&t[..n0]);
for i in 0..n0 {
let idx = if i & 1 == 1 { i - 1 } else { n0 - i - 1 };
t[i] = copy[idx];
}
}
#[inline(always)]
fn adst_out_permute<const N: u32>(t: &mut [i32]) {
let n = N;
let n0 = 1usize << n;
let mut copy = [0i32; 16];
copy[..n0].copy_from_slice(&t[..n0]);
for i in 0..n0 {
let a = (i >> 3) & 1;
let b = ((i >> 2) & 1) ^ ((i >> 3) & 1);
let c = ((i >> 1) & 1) ^ ((i >> 2) & 1);
let d = (i & 1) ^ ((i >> 1) & 1);
let idx = ((d << 3) | (c << 2) | (b << 1) | a) >> (4 - n);
t[i] = if i & 1 == 1 { -copy[idx] } else { copy[idx] };
}
}
#[inline(always)]
fn inverse_adst8(t: &mut [i32], r: u32) {
adst_in_permute::<3>(t);
for i in 0..4 {
bf(t, 2 * i, 2 * i + 1, 60 - 16 * i as i32, true);
}
for i in 0..4 {
hd(t, i, 4 + i, false, r);
}
for i in 0..2 {
bf(t, 4 + 3 * i, 5 + i, 48 - 32 * i as i32, true);
}
for i in 0..2 {
for j in 0..2 {
hd(t, 4 * j + i, 2 + 4 * j + i, false, r);
}
}
for i in 0..2 {
bf(t, 2 + 4 * i, 3 + 4 * i, 32, true);
}
adst_out_permute::<3>(t);
}
#[inline(always)]
fn inverse_adst16(t: &mut [i32], r: u32) {
adst_in_permute::<4>(t);
for i in 0..8 {
bf(t, 2 * i, 2 * i + 1, 62 - 8 * i as i32, true);
}
for i in 0..8 {
hd(t, i, 8 + i, false, r);
}
for i in 0..2 {
bf(t, 8 + 2 * i, 9 + 2 * i, 56 - 32 * i as i32, true);
bf(t, 13 + 2 * i, 12 + 2 * i, 8 + 32 * i as i32, true);
}
for i in 0..4 {
for j in 0..2 {
hd(t, 8 * j + i, 4 + 8 * j + i, false, r);
}
}
for i in 0..2 {
for j in 0..2 {
bf(t, 4 + 8 * j + 3 * i, 5 + 8 * j + i, 48 - 32 * i as i32, true);
}
}
for i in 0..2 {
for j in 0..4 {
hd(t, 4 * j + i, 2 + 4 * j + i, false, r);
}
}
for i in 0..4 {
bf(t, 2 + 4 * i, 3 + 4 * i, 32, true);
}
adst_out_permute::<4>(t);
}
/// 1-D transform kind.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum Kind {
Dct,
Adst,
}
/// (vertical / column kind, horizontal / row kind) of a transform type.
pub(crate) fn kinds(tx_type: usize) -> (Kind, Kind) {
match tx_type {
DCT_DCT => (Kind::Dct, Kind::Dct),
ADST_DCT => (Kind::Adst, Kind::Dct),
DCT_ADST => (Kind::Dct, Kind::Adst),
ADST_ADST => (Kind::Adst, Kind::Adst),
// The encoder only chooses the four types above.
_ => {
debug_assert!(false, "unsupported transform type {tx_type}");
(Kind::Dct, Kind::Dct)
}
}
}
#[inline(always)]
fn inverse_dct(t: &mut [i32], n: u32, r: u32) {
match n {
2 => inverse_dct_n::<2>(t, r),
3 => inverse_dct_n::<3>(t, r),
4 => inverse_dct_n::<4>(t, r),
_ => inverse_dct_n::<5>(t, r),
}
}
#[inline(always)]
fn inverse_1d(t: &mut [i32], kind: Kind, n: u32, r: u32) {
match kind {
Kind::Dct => inverse_dct(t, n, r),
Kind::Adst => match n {
2 => inverse_adst4(t),
3 => inverse_adst8(t, r),
_ => inverse_adst16(t, r),
},
}
}
/// 2-D inverse transform (7.13.3) of a square `n x n` block (n = 4..=32) of dequantised
/// coefficients (row stride `n`) into `residual` (row stride `n`).
pub(crate) fn inverse_2d(dequant: &[i32], residual: &mut [i32], tx_sz: usize, tx_type: usize, bit_depth: u32) {
match TX_WIDTH_LOG2[tx_sz] {
2 => inverse_2d_n::<2>(dequant, residual, tx_sz, tx_type, bit_depth),
3 => inverse_2d_n::<3>(dequant, residual, tx_sz, tx_type, bit_depth),
4 => inverse_2d_n::<4>(dequant, residual, tx_sz, tx_type, bit_depth),
_ => inverse_2d_n::<5>(dequant, residual, tx_sz, tx_type, bit_depth),
}
}
/// `inverse_2d` for a block of width `1 << LOG2`.
fn inverse_2d_n<const LOG2: u32>(dequant: &[i32], residual: &mut [i32], tx_sz: usize, tx_type: usize, bit_depth: u32) {
let log2 = LOG2;
let n = 1usize << log2;
let row_shift = TRANSFORM_ROW_SHIFT[tx_sz] as u32;
let row_clamp = bit_depth + 8;
let col_clamp = (bit_depth + 6).max(16);
let (ck, rk) = kinds(tx_type);
let lo = -(1i32 << (col_clamp - 1));
let hi = (1i32 << (col_clamp - 1)) - 1;
let mut t = [0i32; 32];
for i in 0..n {
let row = &dequant[i * n..i * n + n];
if row.iter().all(|&v| v == 0) {
residual[i * n..i * n + n].iter_mut().for_each(|v| *v = 0);
continue;
}
t[..n].copy_from_slice(row);
inverse_1d(&mut t, rk, log2, row_clamp);
for j in 0..n {
residual[i * n + j] = round2(t[j], row_shift).clamp(lo, hi);
}
}
for j in 0..n {
for i in 0..n {
t[i] = residual[i * n + j];
}
inverse_1d(&mut t, ck, log2, col_clamp);
for i in 0..n {
residual[i * n + j] = round2(t[i], 4);
}
}
}
/// Orthonormal forward basis matrices `[k][i]` (row k = basis function k), sizes 4..=32.
struct Bases {
dct: [Vec<f32>; 4],
adst: [Vec<f32>; 3],
/// The same matrices transposed (`[i][k]`).
dct_t: [Vec<f32>; 4],
adst_t: [Vec<f32>; 3],
}
fn transpose(m: &[f32]) -> Vec<f32> {
let n = (m.len() as f64).sqrt() as usize;
let mut t = vec![0f32; n * n];
for k in 0..n {
for i in 0..n {
t[i * n + k] = m[k * n + i];
}
}
t
}
fn bases() -> &'static Bases {
static B: OnceLock<Bases> = OnceLock::new();
B.get_or_init(|| {
let pi = std::f64::consts::PI;
let dct = std::array::from_fn(|l| {
let n = 4usize << l;
let mut m = vec![0f32; n * n];
for k in 0..n {
let c = if k == 0 { std::f64::consts::FRAC_1_SQRT_2 } else { 1.0 };
for i in 0..n {
m[k * n + i] = (c * (2.0 / n as f64).sqrt() * (pi * (2 * i + 1) as f64 * k as f64 / (2 * n) as f64).cos()) as f32;
}
}
m
});
let adst = std::array::from_fn(|l| {
let n = 4usize << l;
let mut m = vec![0f32; n * n];
for k in 0..n {
for i in 0..n {
m[k * n + i] = if n == 4 {
// the AV1 4-point ADST (sin(pi (i + 1)(2k + 1) / 9) basis)
(2.0 / 3.0 * (pi * ((i + 1) * (2 * k + 1)) as f64 / 9.0).sin()) as f32
} else {
((2.0 / n as f64).sqrt() * (pi * ((2 * i + 1) * (2 * k + 1)) as f64 / (4 * n) as f64).sin()) as f32
};
}
}
m
});
let dct_t = std::array::from_fn(|l| transpose(&dct[l]));
let adst_t = std::array::from_fn(|l| transpose(&adst[l]));
Bases { dct, adst, dct_t, adst_t }
})
}
fn basis_t(kind: Kind, n: usize) -> &'static [f32] {
let l = n.trailing_zeros() as usize - 2;
match kind {
Kind::Dct => &bases().dct_t[l],
Kind::Adst => &bases().adst_t[l],
}
}
fn basis(kind: Kind, n: usize) -> &'static [f32] {
let l = n.trailing_zeros() as usize - 2;
match kind {
Kind::Dct => &bases().dct[l],
Kind::Adst => &bases().adst[l],
}
}
/// Forward 2-D transform of the `n x n` residual (row stride `n`) into orthonormal-domain
/// coefficients scaled by 8 (so that `level = out / q` with the spec's dequantiser).
pub(crate) fn forward_2d(residual: &[i32], out: &mut [f32], n: usize, tx_type: usize) {
match n {
4 => forward_2d_n::<4, 16>(residual, out, tx_type),
8 => forward_2d_n::<8, 64>(residual, out, tx_type),
16 => forward_2d_n::<16, 256>(residual, out, tx_type),
_ => forward_2d_dyn(residual, out, n, tx_type),
}
}
/// `forward_2d` for a fixed size, so `tmp` is exactly `NN = N * N` floats (no 4 KiB zeroing).
#[inline(always)]
fn forward_2d_n<const N: usize, const NN: usize>(residual: &[i32], out: &mut [f32], tx_type: usize) {
let n = N;
let (ck, rk) = kinds(tx_type);
let bc = &basis(ck, n)[..NN];
let brt = &basis_t(rk, n)[..NN];
let residual = &residual[..NN];
let out = &mut out[..NN];
let mut tmp = [0f32; NN];
for i in 0..n {
let t = &mut tmp[i * n..i * n + n];
for j in 0..n {
let r = residual[i * n + j];
if r == 0 {
continue;
}
let r = r as f32;
for (o, &b) in t.iter_mut().zip(&brt[j * n..j * n + n]) {
*o += r * b;
}
}
}
out.iter_mut().for_each(|v| *v = 0.0);
for k in 0..n {
let o = &mut out[k * n..k * n + n];
for i in 0..n {
let b = 8.0 * bc[k * n + i];
for (v, &t) in o.iter_mut().zip(&tmp[i * n..i * n + n]) {
*v += b * t;
}
}
}
}
/// 32x32 (and any other size): a const-generic 32 version measured slower.
fn forward_2d_dyn(residual: &[i32], out: &mut [f32], n: usize, tx_type: usize) {
let (ck, rk) = kinds(tx_type);
let bc = basis(ck, n);
let brt = basis_t(rk, n);
// tmp[i][k] = sum_j residual[i][j] * br[k][j] (horizontal; written as row updates so that
// the inner loops vectorise)
let mut tmp = [0f32; 32 * 32];
for i in 0..n {
let t = &mut tmp[i * n..i * n + n];
for j in 0..n {
let r = residual[i * n + j];
if r == 0 {
continue;
}
let r = r as f32;
for (o, &b) in t.iter_mut().zip(&brt[j * n..j * n + n]) {
*o += r * b;
}
}
}
// out[k][j] = 8 * sum_i bc[k][i] * tmp[i][j] (vertical)
out[..n * n].iter_mut().for_each(|v| *v = 0.0);
for k in 0..n {
let o = &mut out[k * n..k * n + n];
for i in 0..n {
let b = 8.0 * bc[k * n + i];
for (v, &t) in o.iter_mut().zip(&tmp[i * n..i * n + n]) {
*v += b * t;
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tables::{TX_4X4, TX_8X8, TX_16X16, TX_32X32};
/// forward (float) then the normative inverse reproduces the residual: the forward basis
/// and scale match the decoder's inverse transforms for every supported size and type.
#[test]
fn forward_matches_inverse() {
let mut seed = 99u32;
let mut rnd = || {
seed = seed.wrapping_mul(1_103_515_245).wrapping_add(12345);
((seed >> 16) % 201) as i32 - 100
};
for (tx, n) in [(TX_4X4, 4), (TX_8X8, 8), (TX_16X16, 16), (TX_32X32, 32)] {
let denom = if tx == TX_32X32 { 2.0 } else { 1.0 };
for tx_type in [DCT_DCT, ADST_DCT, DCT_ADST, ADST_ADST] {
if n == 32 && tx_type != DCT_DCT {
continue;
}
let res: Vec<i32> = (0..n * n).map(|_| rnd()).collect();
let mut coef = vec![0f32; n * n];
forward_2d(&res, &mut coef, n, tx_type);
// q = 8 / denom keeps full precision: dequant = level * q / denom = coef
let deq: Vec<i32> = coef.iter().map(|&c| (c / denom).round() as i32).collect();
let mut out = vec![0i32; n * n];
inverse_2d(&deq, &mut out, tx, tx_type, 8);
let err: i32 = res.iter().zip(&out).map(|(a, b)| (a - b).abs()).max().unwrap();
assert!(err <= 1, "tx {tx} type {tx_type}: max error {err}");
}
}
}
}
File diff suppressed because it is too large. Load diff
-6
View File
@@ -1,6 +0,0 @@
//! The crate's integration tests, one binary (each module is a former `tests/<name>.rs`).
mod bench;
mod common;
mod ffmpeg_oracle;
mod roundtrip;
+1 -1
View File
@@ -129,7 +129,7 @@ pub use sim2::{
CausticsSetup, FoamDisc, FoamEnv, FoamPlan, Piece, PiecePlan, PieceTex, PixelPlan, WavePlan, Waves, caustics_setup, foam_full_plan, piece_plan, pixel_plan,
wave_world_plan,
};
pub use utility::{Lut, load_lut};
pub use utility::{Lut, check_lut_files, load_lut, lut_file, lut_generation, lut_params};
pub use vr::{equi_dir as vr_equi_dir, rotation as vr_rotation};
/// Effect categories in Effects & Presets order.
+260 -15
View File
@@ -2,7 +2,8 @@
//! lookup tables (.cube).
use std::collections::HashMap;
use std::sync::{Arc, Mutex, OnceLock};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock, PoisonError};
use effectcraft_color::luminance;
use effectcraft_keyframe::Value;
@@ -330,28 +331,165 @@ impl Lut {
}
}
type LutCache = Mutex<HashMap<String, Option<Arc<Lut>>>>;
/// A LUT file's size and modification time when it was read (`None`: inline text, or a file
/// that could not be described). A file whose stamp moved is read again (#3493).
type FileStamp = Option<(u64, Option<std::time::SystemTime>)>;
/// Load (and cache) a LUT from inline `.cube` text or a file path.
/// At most this many parsed LUTs (files and inline texts) are kept, and at most
/// [`MAX_CACHED_BYTES`] of them; the least recently used go first.
const MAX_CACHED_LUTS: usize = 64;
const MAX_CACHED_BYTES: usize = 512 << 20;
/// At most this many LUT files are followed by [`check_lut_files`] beyond the ones whose LUT is
/// kept: the frames made with a LUT that left the cache are still dropped when its file changes.
const MAX_FOLLOWED_FILES: usize = 1024;
/// A parsed LUT (or the failure to parse one) and what it was read from.
struct CachedLut {
stamp: FileStamp,
lut: Option<Arc<Lut>>,
used: u64,
/// The parsed tables and the parameter text, counted against [`MAX_CACHED_BYTES`].
bytes: usize,
}
/// [`load_lut`]'s cache, by parameter text, and the stamp each LUT file was last read with.
#[derive(Default)]
struct LutCache {
map: HashMap<String, CachedLut>,
files: HashMap<String, FileStamp>,
clock: u64,
bytes: usize,
}
impl LutCache {
/// Forget the LUT kept for `src`.
fn remove(&mut self, src: &str) {
if let Some(e) = self.map.remove(src) {
self.bytes = self.bytes.saturating_sub(e.bytes);
}
}
/// Note that the file at `path` was read with `stamp`: a different stamp than the last read's
/// means it changed on disk, and frames made before may show the old LUT.
fn read_file(&mut self, path: &str, stamp: FileStamp) {
if self.files.insert(path.to_string(), stamp).is_some_and(|old| old != stamp) {
GENERATION.fetch_add(1, Ordering::AcqRel);
}
if self.files.len() > MAX_FOLLOWED_FILES {
let map = &self.map;
self.files.retain(|p, _| p.as_str() == path || map.keys().any(|src| lut_file(src) == Some(p.as_str())));
}
}
/// Keep at most [`MAX_CACHED_LUTS`] LUTs and [`MAX_CACHED_BYTES`], always the one for `keep`.
fn evict(&mut self, keep: &str) {
while self.map.len() > MAX_CACHED_LUTS || (self.bytes > MAX_CACHED_BYTES && self.map.len() > 1) {
let Some(oldest) = self.map.iter().filter(|(k, _)| k.as_str() != keep).min_by_key(|(_, e)| e.used).map(|(k, _)| k.clone()) else { break };
self.remove(&oldest);
}
}
}
/// How often a LUT file was found changed on disk ([`lut_generation`]).
static GENERATION: AtomicU64 = AtomicU64::new(0);
fn lut_cache() -> std::sync::MutexGuard<'static, LutCache> {
static CACHE: OnceLock<Mutex<LutCache>> = OnceLock::new();
CACHE.get_or_init(Mutex::default).lock().unwrap_or_else(PoisonError::into_inner)
}
/// The stamp of the file at `path` now: one `metadata` call.
fn file_stamp(path: &str) -> FileStamp {
std::fs::metadata(path).ok().map(|md| (md.len(), md.modified().ok()))
}
/// The parameters (paths in the effect's group) of `effect` that [`load_lut`] reads.
pub fn lut_params(effect: &str) -> &'static [&'static str] {
match effect {
"ec.utility.applylut" => &["lut"],
"ec.color.lumetri" => &["basicCorrection/inputLutFile", "creative/lookFile"],
_ => &[],
}
}
/// The file a LUT parameter names; `None` for inline `.cube` text or an empty parameter.
pub fn lut_file(src: &str) -> Option<&str> {
// `.cube` text always spans lines (a size header, then data rows); a path never does, even one
// whose file name contains `LUT_` (#3454). Trimmed, so a trailing newline is still a path.
let path = src.trim();
(!path.is_empty() && !path.contains('\n')).then_some(path)
}
/// Changes each time a LUT file [`load_lut`] read is found changed on disk (by [`load_lut`]
/// itself or [`check_lut_files`]): frames made before then may show the old LUT.
pub fn lut_generation() -> u64 {
GENERATION.load(Ordering::Acquire)
}
/// Look at every LUT file read (one `metadata` call each) and forget the LUTs of the ones that
/// changed on disk since, so the next [`load_lut`] reads them again. Returns [`lut_generation`].
pub fn check_lut_files() -> u64 {
let files: Vec<(String, FileStamp)> = lut_cache().files.iter().map(|(p, s)| (p.clone(), *s)).collect();
// (stamped without the lock: a file on a slow share must not hold up renders)
let changed: Vec<(String, FileStamp, FileStamp)> =
files.into_iter().filter_map(|(path, old)| Some(file_stamp(&path)).filter(|now| *now != old).map(|now| (path, old, now))).collect();
if !changed.is_empty() {
let mut c = lut_cache();
for (path, old, now) in changed {
// (a render that read the file meanwhile has noted its new stamp already)
if c.files.get(&path) == Some(&old) {
let stale: Vec<String> = c.map.keys().filter(|src| lut_file(src) == Some(path.as_str())).cloned().collect();
for src in stale {
c.remove(&src);
}
c.read_file(&path, now);
}
}
}
lut_generation()
}
/// Load (and cache) a LUT from inline `.cube` text or a file path. A file is stamped (one
/// `metadata` call) on every load and read again once its size or modification time moved, so a
/// file edited, created, deleted or repaired on disk is followed; inline text is its own content.
/// An edit that keeps both the size and the modification time can't be told apart.
pub fn load_lut(src: &str) -> Option<Arc<Lut>> {
if src.trim().is_empty() {
return None;
}
static CACHE: OnceLock<LutCache> = OnceLock::new();
let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new()));
if let Ok(m) = cache.lock()
&& let Some(v) = m.get(src)
let file = lut_file(src);
let stamp = file.and_then(file_stamp);
{
return v.clone();
let mut c = lut_cache();
c.clock += 1;
let now = c.clock;
if let Some(e) = c.map.get_mut(src)
&& e.stamp == stamp
{
e.used = now;
return e.lut.clone();
}
}
// `.cube` text always spans lines (a size header, then data rows); a path never does, even one
// whose file name contains `LUT_` (#3454). Trimmed, as the path is, so a trailing newline is a path.
let inline = src.trim().contains('\n');
let parsed = if inline { parse_cube(src) } else { std::fs::read_to_string(src.trim()).ok().and_then(|t| parse_cube(&t)) }.map(Arc::new);
if let Ok(mut m) = cache.lock() {
m.insert(src.to_string(), parsed.clone());
// (read and parsed without the lock; a file written after it was stamped has a newer stamp,
// and is read again next time)
let lut = match file {
Some(path) => std::fs::read_to_string(path).ok().and_then(|t| parse_cube(&t)),
None => parse_cube(src),
}
parsed
.map(Arc::new);
let tables = lut.as_ref().map_or(0, |l| l.d1.len().saturating_add(l.d3.len()).saturating_mul(std::mem::size_of::<[f32; 3]>()));
let bytes = tables.saturating_add(src.len());
let mut c = lut_cache();
if let Some(path) = file {
c.read_file(path, stamp);
}
c.remove(src);
let used = c.clock;
c.map.insert(src.to_string(), CachedLut { stamp, lut: lut.clone(), used, bytes });
c.bytes = c.bytes.saturating_add(bytes);
c.evict(src);
lut
}
fn apply_lut(ctx: &EffectCtx, mut b: Buf) -> Buf {
@@ -500,6 +638,113 @@ mod tests {
std::fs::remove_dir_all(&dir).unwrap();
}
/// #3493: a LUT file was read once per process; an edited or newly created file never loaded.
#[test]
fn a_lut_file_is_read_again_once_it_changes() {
const BLACK: &str = "LUT_1D_SIZE 2\n0 0 0\n0 0 0\n";
const WHITE: &str = "LUT_1D_SIZE 2\n1 1 1\n1 1 1\n";
let dir = std::env::temp_dir().join(format!("ec-fx-3493-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let write = |name: &str, text: &str, secs: u64| {
let path = dir.join(name);
std::fs::write(&path, text).unwrap();
let f = std::fs::File::options().write(true).open(&path).unwrap();
f.set_modified(std::time::UNIX_EPOCH + std::time::Duration::from_secs(secs)).unwrap();
path.to_string_lossy().into_owned()
};
let at = |src: &str| load_lut(src).map(|l| l.apply([0.5; 3]));
let edited = write("edited.cube", BLACK, 1_000);
assert_eq!(at(&edited), Some([0.0; 3]));
write("edited.cube", WHITE, 2_000);
assert_eq!(at(&edited), Some([1.0; 3]), "an edited file, same size");
let created = dir.join("created.cube").to_string_lossy().into_owned();
assert_eq!(at(&created), None);
write("created.cube", WHITE, 1_000);
assert_eq!(at(&created), Some([1.0; 3]), "a file created after a failed load");
let repaired = write("repaired.cube", "not a lut", 1_000);
assert_eq!(at(&repaired), None);
write("repaired.cube", WHITE, 2_000);
assert_eq!(at(&repaired), Some([1.0; 3]), "a repaired file");
std::fs::remove_file(&repaired).unwrap();
assert_eq!(at(&repaired), None, "a deleted file");
// Inline text is its own content: the same text is the same LUT.
let inline = load_lut(BLACK).unwrap();
assert!(Arc::ptr_eq(&inline, &load_lut(BLACK).unwrap()));
std::fs::remove_dir_all(&dir).unwrap();
}
/// A file that changed is noticed without a render loading it, and the generation that tells
/// frames made before it apart moves.
#[test]
fn check_lut_files_forgets_a_changed_file() {
let dir = std::env::temp_dir().join(format!("ec-fx-3493-check-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("grade.cube");
std::fs::write(&path, identity_cube(2)).unwrap();
let src = path.to_string_lossy().into_owned();
assert!(load_lut(&src).is_some());
let before = check_lut_files();
assert!(lut_cache().map.contains_key(&src), "an unchanged file stays");
std::fs::write(&path, identity_cube(3)).unwrap();
assert!(check_lut_files() > before);
assert!(!lut_cache().map.contains_key(&src), "a changed file is read again");
assert_eq!(load_lut(&src).map(|l| l.n3), Some(3));
std::fs::remove_dir_all(&dir).unwrap();
}
/// The cache keeps at most [`MAX_CACHED_LUTS`] LUTs, the least recently used going first.
#[test]
fn the_lut_cache_is_bounded() {
// (text no other test loads: a load elsewhere would make it recently used)
let oldest = format!("TITLE \"bounded first\"\n{}", identity_cube(2));
let first = load_lut(&oldest).unwrap();
for i in 0..MAX_CACHED_LUTS + 8 {
let text = format!("TITLE \"bounded {i}\"\n{}", identity_cube(2));
assert!(load_lut(&text).is_some());
assert!(lut_cache().map.len() <= MAX_CACHED_LUTS);
}
assert!(!Arc::ptr_eq(&first, &load_lut(&oldest).unwrap()), "the oldest was let go");
let c = lut_cache();
assert_eq!(c.bytes, c.map.values().map(|e| e.bytes).sum::<usize>(), "the bytes kept add up");
assert!(c.bytes <= MAX_CACHED_BYTES);
}
/// A LUT file whose LUT left the cache is still followed: its frames are dropped when it
/// changes, though no render loads it again first.
#[test]
fn a_file_whose_lut_left_the_cache_is_still_followed() {
let dir = std::env::temp_dir().join(format!("ec-fx-3493-evicted-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("old.cube");
std::fs::write(&path, identity_cube(2)).unwrap();
let src = path.to_string_lossy().into_owned();
assert!(load_lut(&src).is_some());
for i in 0..MAX_CACHED_LUTS + 8 {
assert!(load_lut(&format!("TITLE \"evict {i}\"\n{}", identity_cube(2))).is_some());
}
assert!(!lut_cache().map.contains_key(&src), "its LUT left the cache");
std::fs::write(&path, identity_cube(3)).unwrap();
check_lut_files();
assert_eq!(lut_cache().files.get(&src), Some(&file_stamp(&src)), "the change was noticed");
std::fs::remove_dir_all(&dir).unwrap();
}
/// Past [`MAX_FOLLOWED_FILES`], the file just read is still followed (a cache of its own:
/// the shared one's followed files belong to the other tests too).
#[test]
fn the_file_just_read_stays_followed_past_the_limit() {
let mut c = LutCache::default();
for i in 0..MAX_FOLLOWED_FILES + 8 {
let path = format!("/followed/{i}.cube");
c.read_file(&path, Some((1, None)));
assert!(c.files.contains_key(&path), "{i}: the file just read");
}
assert!(c.files.len() <= MAX_FOLLOWED_FILES, "the others no longer cached are let go");
}
#[test]
fn one_d_lut_with_domain() {
let lut = parse_cube("LUT_1D_SIZE 2\nDOMAIN_MIN 0 0 0\nDOMAIN_MAX 2 2 2\n1 1 1\n0 0 0\n").unwrap();
+1
View File
@@ -1,4 +1,5 @@
pub mod camera_track;
pub(crate) mod frames_key;
pub mod mask_track;
pub mod models;
pub mod roto;
+14 -4
View File
@@ -26,9 +26,10 @@ use effectcraft_track::camtrack::linalg::{self, Similarity, V3};
use effectcraft_track::camtrack::{AnalyzeOpts, CameraSolve, CameraTracks, SolveSettings, Target, TrackAnalyzer};
use serde::Serialize;
use crate::analysis::frames_key::{self, signature};
use crate::offload::JobKind;
use crate::tracking::lock;
use crate::warp::{analysis_times, signature};
use crate::warp::analysis_times;
use crate::{Event, Session};
/// Live analysis progress (serde for agents / the control channel).
@@ -124,8 +125,17 @@ fn str_of(g: &PropGroup, m: &str) -> String {
/// What a tracker's tracks are made from: the layer's frames and Detailed Analysis.
fn tracks_key(project: &Project, cid: ItemId, l: &Layer, g: &PropGroup) -> String {
tracks_key_of(signature(project, cid, l), g)
}
fn tracks_key_of(signature: String, g: &PropGroup) -> String {
let detailed = effectcraft_effects::warp_stab::param(&static_params(g), "advanced/detailedAnalysis").is_some_and(Value::as_bool);
format!("{}{}", signature(project, cid, l), if detailed { "+detailed" } else { "" })
format!("{signature}{}", if detailed { "+detailed" } else { "" })
}
/// Whether the tracker's saved tracks are made from the layer's current frames and settings.
fn tracks_match(project: &Project, cid: ItemId, l: &Layer, g: &PropGroup) -> bool {
frames_key::key_matches(project, cid, l, &str_of(g, TRACKS_KEY), |s, _| tracks_key_of(s, g))
}
/// Parameters of an instance from static values (the tracker's settings are not animated).
@@ -165,7 +175,7 @@ pub(crate) fn invalidate(before: &Project, after: &mut Project) -> Vec<(ItemId,
let old_layer = before.comp(*cid).and_then(|bc| bc.layer(l.id));
for g in fx.groups().filter(|g| is_tracker(g)) {
let tracked = !str_of(g, TRACKS).is_empty();
if tracked && str_of(g, TRACKS_KEY) != tracks_key(after, *cid, l, g) {
if tracked && !tracks_match(after, *cid, l, g) {
clears.push((*cid, l.id, g.uid, true));
todo.push((*cid, l.id, g.uid));
} else if tracked && str_of(g, SOLVE_KEY) != ct::solve_key(&ct::settings(&static_params(g))) {
@@ -325,7 +335,7 @@ impl Session {
let key = tracks_key(&self.project, comp, l, g);
let settings = ct::settings(&params);
let solve_key = ct::solve_key(&settings);
let tracks = ct::tracks(&params).filter(|_| str_of(g, TRACKS_KEY) == key);
let tracks = ct::tracks(&params).filter(|_| tracks_match(&self.project, comp, l, g));
let n = times.len();
let work = CamWork {
project: self.project.clone(),
+545
View File
@@ -0,0 +1,545 @@
//! What an analysis of a layer is made from, as one key shared by the Warp Stabilizer, the 3D
//! Camera Tracker and Roto Brush / Object Matte.
//!
//! The key hashes a text this module writes field by field. The source item (footage and its
//! settings, solid), the Time Remap property and the masks and effect groups (their properties,
//! keyframes and values) are destructured or matched in full, and each variant is written as a
//! fixed word: a new field or variant doesn't compile until it is decided here, written if it
//! changes the layer's frames, left out (with a reason) if it doesn't. Renaming a field or variant
//! doesn't change keys. Of the layer and of a precomp, only the fields named in `layer_frames` are
//! read (a precomp's contents are #3535). The
//! text leaves out observations (whether footage is available) and data that never changes pixels
//! (colour labels, UI hints, markers), so they never drop saved analyses (#3534, #3536).
//!
//! Keys saved by 0.22–0.24 hashed derived `Debug` text instead. [`legacy`] still recognises
//! them, and a matching saved key is kept rather than rewritten: frozen Roto Brush mattes and
//! segmentations hash the saved key itself.
use std::fmt::Write as _;
use effectcraft_color::ColorSpace;
use effectcraft_keyframe::{Ease, FeatherPoint, Gradient, Interp, Keyframe, ShapePath, Value};
use effectcraft_project::{
AlphaMode, CineonSettings, CineonUnits, Expression, FeatherFalloff, FieldOrder, Footage, FootageKind, GroupKind, ItemId, ItemKind, Layer, LayerSource,
LightKind, MaskMode, MaskMotionBlur, Node, PrimitiveKind, Project, PropGroup, Property, Solid, SourceLayer, Uid,
};
use effectcraft_time::{FrameRate, Tick};
pub(crate) mod legacy;
/// The version of the text, its first word: a later change to what it writes bumps it.
const VERSION: &str = "frames/1";
/// Property groups nest a few levels (effect ▸ group ▸ property); deeper trees are cut here.
const MAX_DEPTH: usize = 32;
fn fnv(s: &str) -> u64 {
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
for b in s.as_bytes() {
h ^= *b as u64;
h = h.wrapping_mul(0x0100_0000_01b3);
}
h
}
fn hex(s: &str) -> String {
format!("{:016x}", fnv(s))
}
/// Which signature a key is made from: today's, or one an earlier release saved.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Era {
Current,
Legacy,
}
/// The signature of `layer`'s frames: its source (and the source item), In/Out, start time,
/// stretch, Time Remap and the comp frame rate. Warp Stabilizer and 3D Camera Tracker keys are
/// made from it.
pub(crate) fn signature(p: &Project, comp: ItemId, layer: &Layer) -> String {
hex(&signature_text(p, comp, layer))
}
/// The text [`signature`] hashes.
pub(crate) fn signature_text(p: &Project, comp: ItemId, layer: &Layer) -> String {
let mut t = Text::new();
t.word(VERSION);
t.layer_frames(p, comp, layer);
t.0
}
/// A Roto Brush's (or Object Matte's) Input Key: the layer's frames, its masks and the effects
/// above the instance `uid`.
pub(crate) fn input_key(p: &Project, comp: ItemId, layer: &Layer, uid: Uid) -> String {
input_key_of(signature(p, comp, layer), layer, uid)
}
/// An Input Key from a [`signature`].
pub(crate) fn input_key_of(signature: String, layer: &Layer, uid: Uid) -> String {
let mut t = Text::new();
t.word(VERSION);
t.word(&signature);
t.inputs_above(layer, uid);
hex(&t.0)
}
/// Whether `saved`, a key saved with an analysis of `layer`, is for the layer's current frames.
/// `key` makes such a key from a signature of the given era. A key an earlier release saved for
/// the same frames matches too: keep it rather than rewrite it (analysing writes today's).
pub(crate) fn key_matches(p: &Project, comp: ItemId, layer: &Layer, saved: &str, key: impl Fn(String, Era) -> String) -> bool {
key(signature(p, comp, layer), Era::Current) == saved || legacy::signatures(p, comp, layer).into_iter().any(|s| key(s, Era::Legacy) == saved)
}
/// The text a key is hashed from. Fields are `name=value;`; strings are quoted and escaped, so
/// no value can end its field early.
struct Text(String);
impl Text {
fn new() -> Text {
Text(String::new())
}
fn word(&mut self, w: &str) {
self.0.push_str(w);
self.0.push(';');
}
fn field(&mut self, name: &str, value: impl std::fmt::Display) {
let _ = write!(self.0, "{name}={value};");
}
fn str(&mut self, name: &str, s: &str) {
let _ = write!(self.0, "{name}={s:?};");
}
fn num(&mut self, name: &str, v: f64) {
let _ = write!(self.0, "{name}={v:?};");
}
fn nums(&mut self, name: &str, v: &[f64]) {
let _ = write!(self.0, "{name}={v:?};");
}
fn floats(&mut self, name: &str, v: &[f32]) {
let _ = write!(self.0, "{name}={v:?};");
}
fn opt<T>(&mut self, name: &str, v: Option<&T>, write: impl FnOnce(&mut Text, &T)) {
match v {
Some(v) => {
let _ = write!(self.0, "{name}{{");
write(self, v);
self.0.push_str("};");
}
None => self.word(&format!("{name}=none")),
}
}
fn tick(&mut self, name: &str, t: Tick) {
self.field(name, t.0);
}
fn rate(&mut self, name: &str, r: FrameRate) {
let FrameRate { num, den } = r;
let _ = write!(self.0, "{name}={num}/{den};");
}
/// What a layer's frames are made of, before its masks and effects.
fn layer_frames(&mut self, p: &Project, comp: ItemId, layer: &Layer) {
self.layer_source(&layer.source);
if let Some(item) = layer.source.item() {
match p.item(item).map(|i| &i.kind) {
Some(ItemKind::Footage(f)) => self.footage(f),
Some(ItemKind::Solid(s)) => self.solid(s),
// A precomp's own contents aren't in the signature yet (#3535).
Some(ItemKind::Comp(c)) => {
self.word("comp");
self.field("w", c.width);
self.field("h", c.height);
self.rate("rate", c.frame_rate);
self.tick("duration", c.duration);
}
Some(ItemKind::Folder) | None => self.word("item=none"),
}
}
self.tick("in", layer.in_point);
self.tick("out", layer.out_point);
self.tick("start", layer.start_time);
self.num("stretch", layer.stretch);
self.opt("timeRemap", layer.props.get("timeRemap"), |t, pr| t.property(pr));
self.opt("compRate", p.comp(comp).map(|c| &c.frame_rate), |t, r| t.rate("rate", *r));
}
fn layer_source(&mut self, s: &LayerSource) {
match s {
LayerSource::Footage { item } => self.field("footage", item.0),
LayerSource::Comp { item } => self.field("comp", item.0),
LayerSource::Solid { item } => self.field("solid", item.0),
LayerSource::Model { item } => self.field("model", item.0),
LayerSource::Text => self.word("text"),
LayerSource::Shape => self.word("shape"),
LayerSource::Null => self.word("null"),
LayerSource::Camera => self.word("camera"),
LayerSource::Light { kind } => self.field(
"light",
match kind {
LightKind::Parallel => "parallel",
LightKind::Spot => "spot",
LightKind::Point => "point",
LightKind::Ambient => "ambient",
LightKind::Environment => "environment",
},
),
LayerSource::Primitive { kind } => self.field(
"primitive",
match kind {
PrimitiveKind::Cube => "cube",
PrimitiveKind::Sphere => "sphere",
PrimitiveKind::Plane => "plane",
PrimitiveKind::Torus => "torus",
PrimitiveKind::Cone => "cone",
PrimitiveKind::Cylinder => "cylinder",
},
),
}
}
fn solid(&mut self, s: &Solid) {
let Solid { color, width, height, pixel_aspect } = s;
self.word("solid");
self.floats("color", color);
self.field("w", width);
self.field("h", height);
self.num("par", *pixel_aspect);
}
fn footage(&mut self, f: &Footage) {
let Footage {
path,
kind,
width,
height,
pixel_aspect,
frame_rate,
native_rate,
duration,
has_video,
has_audio,
alpha,
premul_color,
loop_count,
codec,
// Whether the file is there is an observation (`footage.check`), not an edit: an
// offline file is the same footage, and its analyses stay valid (#3534).
missing: _,
sequence,
color_profile,
layer,
fields,
invert_alpha,
linear_light,
preserve_rgb,
cineon,
data,
page,
alphabetical,
start_timecode,
file_timecode,
// Markers annotate the footage; they never change its frames.
markers: _,
placed_page,
} = f;
self.word("footage");
self.str("path", path);
self.field(
"kind",
match kind {
FootageKind::Video => "video",
FootageKind::Still => "still",
FootageKind::Sequence => "sequence",
FootageKind::Audio => "audio",
FootageKind::Model => "model",
FootageKind::Data => "data",
},
);
self.field("w", width);
self.field("h", height);
self.num("par", *pixel_aspect);
self.rate("rate", *frame_rate);
self.opt("nativeRate", native_rate.as_ref(), |t, r| t.rate("rate", *r));
self.tick("duration", *duration);
self.field("video", has_video);
self.field("audio", has_audio);
self.field(
"alpha",
match alpha {
AlphaMode::Straight => "straight",
AlphaMode::Premultiplied => "premultiplied",
AlphaMode::Ignore => "ignore",
},
);
self.floats("matte", premul_color);
self.field("loop", loop_count);
self.str("codec", codec);
self.field("frames", sequence.len());
for s in sequence {
self.str("file", s);
}
self.opt("profile", color_profile.as_ref(), |t, c| t.word(color_space(*c)));
self.opt("layer", layer.as_ref(), |t, l| t.source_layer(l));
self.field(
"fields",
match fields {
FieldOrder::Off => "off",
FieldOrder::UpperFirst => "upper",
FieldOrder::LowerFirst => "lower",
},
);
self.field("invertAlpha", invert_alpha);
self.field("linearLight", linear_light);
self.field("preserveRgb", preserve_rgb);
self.cineon(cineon);
self.opt("data", data.as_ref(), |t, d| t.str("text", d));
self.field("page", page);
self.field("alphabetical", alphabetical);
self.opt("startTimecode", start_timecode.as_ref(), |t, v| t.field("frame", v));
self.opt("fileTimecode", file_timecode.as_ref(), |t, v| t.field("frame", v));
self.field("placedPage", placed_page);
}
fn source_layer(&mut self, l: &SourceLayer) {
let SourceLayer { index, name, layer_size, embedded, placed } = l;
self.field("index", index);
// The layer is found by its index; the name only labels it.
let _ = name;
self.field("layerSize", layer_size);
self.opt("embedded", embedded.as_ref(), |t, e| t.str("id", e));
self.field("placed", placed);
}
fn cineon(&mut self, c: &CineonSettings) {
let CineonSettings { log_conversion, converted_black, converted_white, black, white, gamma, rolloff, units } = c;
self.word("cineon");
self.field("log", log_conversion);
self.floats("points", &[*converted_black, *converted_white, *black, *white, *gamma, *rolloff]);
self.field(
"units",
match units {
CineonUnits::TenBit => "10bit",
CineonUnits::EightBit => "8bit",
CineonUnits::Float => "float",
},
);
}
/// The layer's masks and the effects above the instance `uid`: what the effect's input is
/// made of besides the layer's frames.
fn inputs_above(&mut self, layer: &Layer, uid: Uid) {
if let Some(m) = layer.masks() {
self.word("masks");
self.group(m, 0);
}
if let Some(fx) = layer.effects() {
self.word("effects");
for g in fx.groups().take_while(|g| g.uid != uid) {
self.group(g, 0);
}
}
}
fn group(&mut self, g: &PropGroup, depth: usize) {
// Expressions find effects and groups by name (`effect("Blur")`, `propertyGroup(1).name`).
// The uid and colour label never change pixels.
let PropGroup { uid: _, match_id, name, kind, enabled, label: _, children } = g;
if depth >= MAX_DEPTH {
self.word("tooDeep");
return;
}
self.str("group", match_id);
self.str("name", name);
self.group_kind(kind);
self.field("enabled", enabled);
for c in children {
match c {
Node::Prop(p) => self.property(p),
Node::Group(g) => self.group(g, depth + 1),
}
}
self.word("end");
}
fn group_kind(&mut self, k: &GroupKind) {
match k {
GroupKind::Plain => self.word("plain"),
GroupKind::Indexed => self.word("indexed"),
// A mask's colour and lock only show it in the UI.
GroupKind::Mask { mode, inverted, color: _, locked: _, motion_blur, feather_falloff, roto_bezier } => {
self.field(
"mask",
match mode {
MaskMode::None => "none",
MaskMode::Add => "add",
MaskMode::Subtract => "subtract",
MaskMode::Intersect => "intersect",
MaskMode::Lighten => "lighten",
MaskMode::Darken => "darken",
MaskMode::Difference => "difference",
},
);
self.field("inverted", inverted);
self.field(
"motionBlur",
match motion_blur {
MaskMotionBlur::SameAsLayer => "layer",
MaskMotionBlur::On => "on",
MaskMotionBlur::Off => "off",
},
);
self.field(
"falloff",
match feather_falloff {
FeatherFalloff::Smooth => "smooth",
FeatherFalloff::Linear => "linear",
},
);
self.field("rotoBezier", roto_bezier);
}
GroupKind::Effect { effect } => self.str("effect", effect),
// A motion tracker's settings say how to track, not how to draw the layer.
GroupKind::Tracker { settings: _ } => self.word("tracker"),
GroupKind::Essential { overridden } => {
self.word("essential");
for u in overridden {
self.field("overridden", u);
}
}
}
}
fn property(&mut self, pr: &Property) {
// Expressions read the name (`thisProperty.name`) and seed `random`/`wiggle` with the
// uid: the uid is written for a property with an expression. UI hints and the 2D/3D-only
// and hold-only flags say where and how it can be edited, not what it evaluates to.
let Property { uid, match_id, name, value, keys, expr, ui: _, spatial, hold_only: _, three_d_only: _, two_d_only: _, shown_dims: _, static_only: _ } =
pr;
self.str("prop", match_id);
self.str("name", name);
if expr.is_some() {
self.field("uid", uid);
}
self.value(value);
self.field("spatial", spatial);
for k in keys {
self.keyframe(k);
}
self.opt("expr", expr.as_ref(), |t, e| {
let Expression { text, enabled } = e;
t.str("text", text);
t.field("enabled", enabled);
});
}
fn keyframe(&mut self, k: &Keyframe) {
// A key's colour label only shows it in the UI.
let Keyframe {
time,
value,
in_interp,
out_interp,
in_ease,
out_ease,
continuous,
auto_bezier,
spatial_in,
spatial_out,
spatial_auto,
spatial_continuous,
roving,
label: _,
muted,
} = k;
self.tick("key", *time);
self.value(value);
self.field("interp", format_args!("{}/{}", interp(*in_interp), interp(*out_interp)));
for (side, eases) in [("inEase", in_ease), ("outEase", out_ease)] {
for e in eases {
let Ease { speed, influence } = e;
self.nums(side, &[*speed, *influence]);
}
}
self.field("continuous", continuous);
self.field("autoBezier", auto_bezier);
self.nums("spatialIn", spatial_in);
self.nums("spatialOut", spatial_out);
self.field("spatialAuto", spatial_auto);
self.field("spatialContinuous", spatial_continuous);
self.field("roving", roving);
self.field("muted", muted);
}
fn value(&mut self, v: &Value) {
match v {
Value::Scalar(x) => self.num("scalar", *x),
Value::Vec2(x) => self.nums("vec2", x),
Value::Vec3(x) => self.nums("vec3", x),
Value::Color(x) => self.nums("color", x),
Value::Bool(b) => self.field("bool", b),
Value::Enum(i) => self.field("enum", i),
Value::Path(p) => self.shape_path(p),
// A text document has dozens of fields and no place in what a key covers today (a
// text layer's Source Text is not under its masks or effects): its project-file form.
Value::Text(d) => self.str("text", &serde_json::to_string(d).unwrap_or_default()),
Value::Layer(l) => self.opt("layer", l.as_ref(), |t, id| t.field("id", id)),
Value::Gradient(g) => {
let Gradient { colors, opacities } = g;
self.word("gradient");
for (at, c) in colors {
self.num("stop", *at);
self.floats("rgba", c);
}
for (at, o) in opacities {
self.num("stop", *at);
self.floats("opacity", &[*o]);
}
}
Value::Str(s) => self.str("str", s),
}
}
fn shape_path(&mut self, p: &ShapePath) {
let ShapePath { vertices, in_tangents, out_tangents, closed, feather } = p;
self.word("path");
for (name, points) in [("v", vertices), ("in", in_tangents), ("out", out_tangents)] {
for pt in points {
self.nums(name, pt);
}
}
self.field("closed", closed);
for f in feather {
let FeatherPoint { segment, t, radius, tension } = f;
self.field("featherSegment", segment);
self.nums("feather", &[*t, *radius, *tension]);
}
}
}
fn interp(i: Interp) -> &'static str {
match i {
Interp::Linear => "linear",
Interp::Bezier => "bezier",
Interp::Hold => "hold",
}
}
fn color_space(c: ColorSpace) -> &'static str {
match c {
ColorSpace::Srgb => "srgb",
ColorSpace::Rec709 => "rec709",
ColorSpace::Rec2020 => "rec2020",
ColorSpace::DisplayP3 => "p3",
ColorSpace::AcesCg => "acescg",
ColorSpace::Aces2065 => "aces2065",
ColorSpace::Rec2100Pq => "rec2100pq",
ColorSpace::Rec2100Hlg => "rec2100hlg",
}
}
@@ -0,0 +1,147 @@
//! Signatures as 0.22–0.24 wrote them, to recognise the keys those releases saved. Nothing new is
//! keyed with them. They hash derived `Debug` text, so `tests::analysis_signature` pins keys
//! those releases saved: if a type change alters this text, write that part out here.
use effectcraft_project::{Footage, ItemId, ItemKind, Layer, LayerSource, Project, Uid};
use super::fnv;
/// The signatures a saved key of `layer` may have been made from. The footage's availability is
/// tried both ways: those releases hashed it, though it isn't part of the footage (#3534). Before
/// `Footage::placed_page` was added in 0.23, the footage text ended without that field.
pub(crate) fn signatures(p: &Project, comp: ItemId, layer: &Layer) -> Vec<String> {
let src = match &layer.source {
LayerSource::Footage { item } | LayerSource::Solid { item } | LayerSource::Comp { item } => match p.item(*item).map(|i| &i.kind) {
Some(ItemKind::Footage(f)) => {
let mut out = Vec::with_capacity(4);
for missing in [false, true] {
out.push(signature_with_source(p, comp, layer, &footage_text(f, missing, true)));
if matches!(layer.source, LayerSource::Footage { .. }) && !f.placed_page {
out.push(signature_with_source(p, comp, layer, &footage_text(f, missing, false)));
}
}
return out;
}
Some(ItemKind::Solid(s)) => format!("{s:?}"),
Some(ItemKind::Comp(c)) => format!("{}x{}@{:?}/{:?}", c.width, c.height, c.frame_rate, c.duration),
_ => String::new(),
},
_ => String::new(),
};
vec![signature_with_source(p, comp, layer, &src)]
}
/// A Roto Brush Input Key as 0.22–0.24 made it from a [`signatures`] entry.
pub(crate) fn input_key_of(mut s: String, layer: &Layer, uid: Uid) -> String {
if let Some(m) = layer.masks() {
s.push_str(&format!("{m:?}"));
}
if let Some(fx) = layer.effects() {
for g in fx.groups() {
if g.uid == uid {
break;
}
s.push_str(&format!("{g:?}"));
}
}
format!("{:016x}", fnv(&s))
}
/// A footage item as 0.23–0.24 wrote it into a signature (without `placed_page` before 0.23),
/// with `missing` in place of the item's.
pub(crate) fn footage_text(f: &Footage, missing: bool, placed_page: bool) -> String {
format!("{:?}", FootageText { f, missing, placed_page })
}
struct FootageText<'a> {
f: &'a Footage,
missing: bool,
placed_page: bool,
}
impl std::fmt::Debug for FootageText<'_> {
fn fmt(&self, out: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// Every field is named so that a new one doesn't compile until it is decided here: a new
// field was never in these keys, so it stays out.
let Footage {
path,
kind,
width,
height,
pixel_aspect,
frame_rate,
native_rate,
duration,
has_video,
has_audio,
alpha,
premul_color,
loop_count,
codec,
missing: _,
sequence,
color_profile,
layer,
fields,
invert_alpha,
linear_light,
preserve_rgb,
cineon,
data,
page,
alphabetical,
start_timecode,
file_timecode,
markers,
placed_page,
} = self.f;
let mut d = out.debug_struct("Footage");
d.field("path", path)
.field("kind", kind)
.field("width", width)
.field("height", height)
.field("pixel_aspect", pixel_aspect)
.field("frame_rate", frame_rate)
.field("native_rate", native_rate)
.field("duration", duration)
.field("has_video", has_video)
.field("has_audio", has_audio)
.field("alpha", alpha)
.field("premul_color", premul_color)
.field("loop_count", loop_count)
.field("codec", codec)
.field("missing", &self.missing)
.field("sequence", sequence)
.field("color_profile", color_profile)
.field("layer", layer)
.field("fields", fields)
.field("invert_alpha", invert_alpha)
.field("linear_light", linear_light)
.field("preserve_rgb", preserve_rgb)
.field("cineon", cineon)
.field("data", data)
.field("page", page)
.field("alphabetical", alphabetical)
.field("start_timecode", start_timecode)
.field("file_timecode", file_timecode)
.field("markers", markers);
if self.placed_page {
d.field("placed_page", placed_page);
}
d.finish()
}
}
fn signature_with_source(p: &Project, comp: ItemId, layer: &Layer, src: &str) -> String {
let rate = p.comp(comp).map(|c| format!("{:?}", c.frame_rate)).unwrap_or_default();
let s = format!(
"{:?}|{src}|{:?}|{:?}|{:?}|{}|{:?}|{rate}",
layer.source,
layer.in_point,
layer.out_point,
layer.start_time,
layer.stretch,
layer.props.get("timeRemap")
);
format!("{:016x}", fnv(&s))
}
+9 -34
View File
@@ -8,8 +8,8 @@
//! (`Renderer::layer_input`, source → masks → the effects above it). `roto.freeze` runs the same
//! pass and stores the final mattes in the effect (one undo step). `sync`, run after every
//! edit, keeps each instance's hidden Input Key equal to a signature of what its frames are made
//! of (the layer's source and timing, its masks and the effects above it) and drops frozen
//! mattes made from other frames.
//! of (the layer's source and timing, its masks and the effects above it: `analysis::frames_key`),
//! and drops frozen mattes made from other frames. Footage going offline keeps them.
//!
//! Object Matte instances run through the same jobs (`objectMatte.propagate` / `.freeze`): the
//! frames are [`om::job_frames`] around the reference frame, each segmented through
@@ -31,6 +31,7 @@ use effectcraft_render::{EvalCtx, ExprHost, FootageSource, LayerCache, RenderOpt
use effectcraft_time::Tick;
use serde::{Deserialize, Serialize};
use crate::analysis::frames_key::{self, Era};
use crate::tracking::lock;
use crate::{Event, Session};
@@ -207,40 +208,10 @@ fn set_str(g: &mut PropGroup, m: &str, v: String) {
}
}
fn fnv(s: &str) -> u64 {
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
for b in s.as_bytes() {
h ^= *b as u64;
h = h.wrapping_mul(0x0100_0000_01b3);
}
h
}
/// What the effect's input frames are made of: the layer's source and timing, its masks and the
/// effects above the Roto Brush.
pub fn input_key(p: &Project, comp: ItemId, layer: &Layer, uid: Uid) -> String {
input_key_with_signature(crate::warp::signature(p, comp, layer), layer, uid)
}
/// Recognize the input key serialized before 0.23 without re-keying its frozen matte.
fn input_key_before_placed_page(p: &Project, comp: ItemId, layer: &Layer, uid: Uid) -> Option<String> {
let signature = crate::warp::signature_before_placed_page(p, comp, layer)?;
Some(input_key_with_signature(signature, layer, uid))
}
fn input_key_with_signature(mut s: String, layer: &Layer, uid: Uid) -> String {
if let Some(m) = layer.masks() {
s.push_str(&format!("{m:?}"));
}
if let Some(fx) = layer.effects() {
for g in fx.groups() {
if g.uid == uid {
break;
}
s.push_str(&format!("{g:?}"));
}
}
format!("{:016x}", fnv(&s))
frames_key::input_key(p, comp, layer, uid)
}
/// After an edit: refresh Input Keys (Roto Brush and Object Matte); frozen mattes made from
@@ -258,7 +229,11 @@ pub(crate) fn sync(before: &Project, after: &mut Project) -> Vec<(ItemId, LayerI
let old = before.comp(*cid).and_then(|bc| bc.layer(l.id)).and_then(|ol| ol.props.find_group(g.uid));
let saved_key = str_of(g, INPUT_KEY);
// Keep a matching old key: the frozen cache itself also hashes that key.
if saved_key != key && input_key_before_placed_page(after, *cid, l, g.uid).as_deref() != Some(saved_key.as_str()) {
let key_of = |s, era| match era {
Era::Current => frames_key::input_key_of(s, l, g.uid),
Era::Legacy => frames_key::legacy::input_key_of(s, l, g.uid),
};
if !frames_key::key_matches(after, *cid, l, &saved_key, key_of) {
set.push((*cid, l.id, g.uid, key));
todo.push((*cid, l.id, g.uid));
} else if old.is_none_or(|o| guard_of(o) != guard_of(g)) {
+8 -55
View File
@@ -6,10 +6,11 @@
//! analyzer (step 1 of 2, "Analyzing in background"); step 2 ("Stabilizing") derives the
//! stabilization plan once to validate and cache the result. When the job finishes, the analysis is
//! written into the effect's hidden Analysis parameter as one undo step, together with a key of
//! what it was made from (the layer's source, In/Out, start, stretch and Time Remap). Edits that
//! change those clear the analysis (`invalidate`, run after every edit) and queue the effect
//! for re-analysis, which frontends start with [`Session::poll_warp`] (After Effects re-analyses
//! automatically too).
//! what it was made from (the layer's source, In/Out, start, stretch and Time Remap; the key is
//! `analysis::frames_key`'s, shared with the 3D Camera Tracker and Roto Brush). Edits that change
//! those clear the analysis (`invalidate`, run after every edit) and queue the effect for
//! re-analysis, which frontends start with [`Session::poll_warp`] (After Effects re-analyses
//! automatically too). Footage going offline is not such a change.
use crate::offload::{JobKind, rate};
use std::sync::atomic::{AtomicBool, Ordering};
@@ -17,13 +18,14 @@ use std::sync::{Arc, Mutex};
use effectcraft_effects::warp_stab::{self, ANALYSIS, ANALYSIS_KEY};
use effectcraft_keyframe::Value;
use effectcraft_project::{GroupKind, ItemId, ItemKind, Layer, LayerId, LayerSource, Project, PropGroup, Uid};
use effectcraft_project::{GroupKind, ItemId, ItemKind, Layer, LayerId, Project, PropGroup, Uid};
use effectcraft_raster::Image;
use effectcraft_render::{EvalCtx, ExprHost, FootageSource, LayerCache, Renderer};
use effectcraft_time::Tick;
use effectcraft_track::stabilize::{AnalyzeOpts, Analyzer, WarpAnalysis};
use serde::Serialize;
use crate::analysis::frames_key::{self, signature};
use crate::tracking::lock;
use crate::{Event, Session};
@@ -98,54 +100,6 @@ pub(crate) struct WarpWork {
pub times: Vec<Tick>,
}
fn fnv(s: &str) -> u64 {
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
for b in s.as_bytes() {
h ^= *b as u64;
h = h.wrapping_mul(0x0100_0000_01b3);
}
h
}
/// What an analysis of `layer` depends on (its frames): source (and the footage item's
/// interpretation), In/Out, start time, stretch, Time Remap and the comp frame rate.
pub fn signature(p: &Project, comp: ItemId, layer: &Layer) -> String {
let src = match &layer.source {
LayerSource::Footage { item } | LayerSource::Solid { item } | LayerSource::Comp { item } => match p.item(*item).map(|i| &i.kind) {
Some(ItemKind::Footage(f)) => format!("{f:?}"),
Some(ItemKind::Solid(s)) => format!("{s:?}"),
Some(ItemKind::Comp(c)) => format!("{}x{}@{:?}/{:?}", c.width, c.height, c.frame_rate, c.duration),
_ => String::new(),
},
_ => String::new(),
};
signature_with_source(p, comp, layer, &src)
}
/// Before `Footage::placed_page` was added in 0.23, the persisted signature hashed the
/// same Debug representation without that last field. Only ordinary footage can match it.
pub(crate) fn signature_before_placed_page(p: &Project, comp: ItemId, layer: &Layer) -> Option<String> {
let LayerSource::Footage { item } = &layer.source else { return None };
let ItemKind::Footage(footage) = &p.item(*item)?.kind else { return None };
let src = format!("{footage:?}");
let old = src.strip_suffix(", placed_page: false }")?;
Some(signature_with_source(p, comp, layer, &format!("{old} }}")))
}
fn signature_with_source(p: &Project, comp: ItemId, layer: &Layer, src: &str) -> String {
let rate = p.comp(comp).map(|c| format!("{:?}", c.frame_rate)).unwrap_or_default();
let s = format!(
"{:?}|{src}|{:?}|{:?}|{:?}|{}|{:?}|{rate}",
layer.source,
layer.in_point,
layer.out_point,
layer.start_time,
layer.stretch,
layer.props.get("timeRemap")
);
format!("{:016x}", fnv(&s))
}
fn is_warp(g: &PropGroup) -> bool {
matches!(&g.kind, GroupKind::Effect { effect } if effect == warp_stab::ID)
}
@@ -169,11 +123,10 @@ pub(crate) fn invalidate(before: &Project, after: &mut Project) -> Vec<(ItemId,
if !fx.groups().any(is_warp) {
continue;
}
let sig = signature(after, *cid, l);
let old_layer = before.comp(*cid).and_then(|bc| bc.layer(l.id));
for g in fx.groups().filter(|g| is_warp(g)) {
let analysed = !str_of(g, ANALYSIS).is_empty();
if analysed && str_of(g, ANALYSIS_KEY) != sig {
if analysed && !frames_key::key_matches(after, *cid, l, &str_of(g, ANALYSIS_KEY), |s, _| s) {
clear.push((*cid, l.id, g.uid));
todo.push((*cid, l.id, g.uid));
} else if !analysed && old_layer.and_then(|ol| ol.props.find_group(g.uid)).is_none() {
+7 -3
View File
@@ -319,15 +319,19 @@ impl Prober {
return f.map(|footage| Probed { name, footage, ask_alpha: false, warning: None }).map_err(fail);
}
let importer = self.importer.as_ref().ok_or_else(|| fail("media import is not available in this build".into()))?;
let mut f = crate::sequence::probe(importer.as_ref(), src, self.sequence_rate).map_err(fail)?;
let mut warning = None;
// What the file's own import left out (a model's textures over the limits) is a warning too.
let (mut f, mut warning) = match src {
Source::File(_) => importer.probe_noting(path).map_err(fail)?,
_ => (crate::sequence::probe(importer.as_ref(), src, self.sequence_rate).map_err(fail)?, None),
};
// Settings ▸ Import ▸ Report Missing Frames (numbered sequences).
if f.kind == FootageKind::Sequence
&& !f.alphabetical
&& self.report_missing_frames
&& let Some(gaps) = crate::sequence::missing_report(&f.sequence)
{
warning = Some(format!("{name}: {gaps} (the previous frame is held)"));
let gaps = format!("{name}: {gaps} (the previous frame is held)");
warning = Some(warning.map_or(gaps.clone(), |w| format!("{w}; {gaps}")));
}
// Settings ▸ Import ▸ Interpret Unlabeled Alpha As: images only (a 3D model renders its
// own alpha, and audio and data have none).
+30 -1
View File
@@ -1408,6 +1408,13 @@ fn convert_expr_to_keys(s: &mut Session, p: &Value) -> Result<Value> {
if sel.is_empty() {
return Err(bad(CMD, "no `path` given and no selected property has an expression"));
}
// Every layer is checked before the first is converted: a refusal leaves them all as they were.
let step = comp.frame_duration().0;
for (lid, _) in &sel {
if let Some(l) = comp.layer(*lid) {
check_convertible(step, l)?;
}
}
let mut n = 0;
for (lid, uid) in sel {
n += convert_one_expr(s, cid, lid, uid)?.as_u64().unwrap_or(0);
@@ -1418,14 +1425,36 @@ fn convert_expr_to_keys(s: &mut Session, p: &Value) -> Result<Value> {
convert_one_expr(s, cid, lid, uid)
}
/// Most keyframes Convert Expression to Keyframes makes: 2^20, 4.8 hours at 60 fps (After Effects
/// compositions run to 3 hours, 648,000 frames at 60 fps).
const MAX_CONVERTED_KEYS: u64 = 1 << 20;
const _: () = assert!(MAX_CONVERTED_KEYS >= 3 * 3600 * 60);
/// One evaluation and one key per frame of the layer: its In and Out points and the composition's
/// frame duration are saved data, so the step must advance and the count (a partial last frame
/// rounded up, as the loop steps, in 128 bits) is checked before any key is made.
fn check_convertible(step: i64, layer: &Layer) -> Result<()> {
const CMD: &str = "prop.convertExpressionToKeyframes";
if step <= 0 {
return Err(bad(CMD, "the composition's frame duration is not positive"));
}
let (step, span) = (i128::from(step), i128::from(layer.out_point.0) - i128::from(layer.in_point.0));
let frames = if span > 0 { (span + step - 1) / step } else { 0 };
if frames > i128::from(MAX_CONVERTED_KEYS) {
return Err(bad(CMD, format!("the layer spans {frames} frames; at most {MAX_CONVERTED_KEYS} are converted")));
}
Ok(())
}
/// Replaces the expression on one property with keyframes sampled from its evaluated values.
/// Returns the number of properties converted.
fn convert_one_expr(s: &mut Session, cid: ItemId, lid: LayerId, uid: Uid) -> Result<Value> {
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?.clone();
let layer = comp.layer(lid).ok_or(EngineError::NoComp)?.clone();
let pr = layer.props.find(uid).ok_or_else(|| bad("prop.convertExpressionToKeyframes", "no property"))?.clone();
let mut keys = vec![];
let fd = comp.frame_duration();
check_convertible(fd.0, &layer)?;
let mut keys = vec![];
let mut t = layer.in_point;
while t < layer.out_point {
let ctx = effectcraft_render::EvalCtx {
+1
View File
@@ -1,6 +1,7 @@
pub mod doc_path;
pub mod footage_check;
pub mod footage_reload;
pub mod lut_reload;
pub mod media_browser;
pub mod media_cache;
pub mod sequence;
+90
View File
@@ -0,0 +1,90 @@
//! LUT files that change on disk (#3493).
//!
//! A render follows a LUT file by itself: [`effectcraft_effects::load_lut`] stamps the file and
//! reads it again once it changed, and a layer's cache key holds the stamp. What the desktop app
//! keeps of earlier renders, the frames of its viewer and RAM preview, is dropped when
//! [`effectcraft_effects::lut_generation`] moves. The [`Watcher`] looks at the LUT files in use
//! every two seconds, so an edit shows without anything rendering first, and wakes the interface
//! only when one changed.
use std::sync::mpsc::{RecvTimeoutError, SyncSender};
use std::time::Duration;
/// Moves each time a LUT file in use was found changed on disk: frames rendered before may show
/// the old LUT ([`effectcraft_effects::lut_generation`]).
pub fn generation() -> u64 {
effectcraft_effects::lut_generation()
}
/// Stamp the LUT files in use now ([`effectcraft_effects::check_lut_files`]): the ones that
/// changed are read again by the next render. Returns [`generation`].
pub fn check() -> u64 {
effectcraft_effects::check_lut_files()
}
/// How often the LUT files in use are stamped.
pub const INTERVAL: Duration = Duration::from_secs(2);
/// A worker thread that stamps the LUT files in use ([`effectcraft_effects::check_lut_files`])
/// and runs `wake` when one changed. Dropping the watcher ends the thread.
pub struct Watcher {
_stop: SyncSender<()>,
}
impl Watcher {
/// Start the worker. `None` where there are no threads (the web app, whose LUTs don't come
/// from files) or one couldn't be started.
pub fn start(wake: impl Fn() + Send + 'static) -> Option<Watcher> {
Self::start_with(wake, INTERVAL)
}
/// [`Watcher::start`] stamping every `every` (tests).
pub fn start_with(wake: impl Fn() + Send + 'static, every: Duration) -> Option<Watcher> {
if cfg!(target_arch = "wasm32") {
return None;
}
let (tx, rx) = std::sync::mpsc::sync_channel::<()>(1);
std::thread::Builder::new()
.name("lut-watch".into())
.spawn(move || {
let mut seen = effectcraft_effects::lut_generation();
// (ends once the watcher, the only sender, is dropped)
while let Err(RecvTimeoutError::Timeout) = rx.recv_timeout(every) {
let now = check();
if now != seen {
seen = now;
wake();
}
}
})
.ok()?;
Some(Watcher { _stop: tx })
}
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
use super::*;
/// A LUT file edited on disk wakes the interface without a render loading it.
#[test]
fn an_edited_lut_file_wakes_the_interface() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("watched.cube");
std::fs::write(&path, "LUT_1D_SIZE 2\n0 0 0\n1 1 1\n").unwrap();
let src = path.to_string_lossy().into_owned();
assert!(effectcraft_effects::load_lut(&src).is_some());
let before = effectcraft_effects::lut_generation();
let (tx, rx) = std::sync::mpsc::channel();
let _watcher = Watcher::start_with(
move || {
let _ = tx.send(());
},
Duration::from_millis(10),
)
.unwrap();
std::fs::write(&path, "LUT_1D_SIZE 3\n0 0 0\n0.5 0.5 0.5\n1 1 1\n").unwrap();
rx.recv_timeout(Duration::from_secs(10)).unwrap();
assert!(effectcraft_effects::lut_generation() > before);
}
}
+1
View File
@@ -61,6 +61,7 @@ pub use effectcraft_track as track;
pub use footage::doc_path;
pub use footage::footage_check;
pub use footage::footage_reload;
pub use footage::lut_reload;
pub use footage::media_browser;
pub use footage::media_cache;
pub use footage::sequence;
+5
View File
@@ -106,6 +106,11 @@ pub trait Importer: Send + Sync {
/// Probe one file and return footage metadata. Image sequences are the engine's
/// ([`sequence`]): it groups numbered stills and probes their first file here.
fn probe(&self, path: &str) -> std::result::Result<effectcraft_project::Footage, String>;
/// [`probe`](Self::probe), and what the import left out of the file (a 3D model's textures
/// over the limits), which the import shows the user.
fn probe_noting(&self, path: &str) -> std::result::Result<(effectcraft_project::Footage, Option<String>), String> {
self.probe(path).map(|f| (f, None))
}
/// A footage file's bytes are now at `path` (extracted from a template): hosts whose media
/// layer reads from memory (the browser) register them; file-based ones need nothing.
fn register(&self, _path: &str, _data: &[u8]) {}
+3
View File
@@ -1,6 +1,7 @@
mod add_item_options;
mod aep_export;
mod aep_import;
mod analysis_signature;
mod anim_presets;
mod anim_tools;
mod aux_footage;
@@ -27,8 +28,10 @@ mod key_metadata_order;
mod key_time;
mod keyframe_text;
mod keylight;
mod legacy_analysis_keys;
mod limits;
mod lottie;
mod lut_files;
mod m137;
mod m145;
mod markers;
@@ -0,0 +1,315 @@
//! Warp Stabilizer, 3D Camera Tracker and Roto Brush keys saved by 0.24 keep matching their
//! layer's frames after edits that don't change them, and a real change still clears them.
use effectcraft_effects::camera_tracker::{TRACKS, TRACKS_KEY};
use effectcraft_effects::roto::{FROZEN, INPUT_KEY};
use effectcraft_effects::warp_stab::{ANALYSIS, ANALYSIS_KEY};
use effectcraft_keyframe::Value;
use effectcraft_project::{ItemId, LayerId, Project};
use serde_json::json;
use crate::Session;
const COMP: ItemId = ItemId(2);
const CLIP: LayerId = LayerId(3);
const WARP: u64 = 26;
const TRACKER: u64 = 54;
const ROTO: u64 = 86;
/// Saved by 0.24.1 (before #3534/#3536): the clip of `tracked-0.22.ecproj` with Time Remap, a
/// mask, a Gaussian Blur and a Roto Brush, its analyses replaced by short stand-ins. The keys
/// are the ones that version computed for it.
const ANALYSED_0_24: &str = include_str!("fixtures/analysed-0.24.ecproj");
const SIGNATURE_0_24: &str = "03efb7c4b0f27b65";
const ROTO_INPUT_0_24: &str = "7b319ce93027617c";
fn open(json: &str) -> Session {
let mut s = Session::default();
s.replace_project(Project::from_json(json).unwrap(), None);
s.open_comp(COMP);
s
}
/// The (data, key) of the Warp Stabilizer, the 3D Camera Tracker and the Roto Brush.
fn saved(s: &Session) -> [(String, String); 3] {
let layer = s.project.comp(COMP).unwrap().layer(CLIP).unwrap();
let get = |uid: u64, data: &str, key: &str| {
let params = crate::camera_track::static_params(layer.props.find_group(uid).unwrap());
let text = |id: &str| match params.get(id) {
Some(Value::Str(s)) => s.clone(),
other => panic!("{id}: {other:?}"),
};
(text(data), text(key))
};
[get(WARP, ANALYSIS, ANALYSIS_KEY), get(TRACKER, TRACKS, TRACKS_KEY), get(ROTO, FROZEN, INPUT_KEY)]
}
fn add_to_render_queue(s: &mut Session) {
s.execute_checked("renderQueue.add", json!({"comp": COMP.0, "format": "png", "output": "frame.png"})).unwrap();
}
#[test]
fn analyses_saved_by_0_24_survive_edits_that_keep_their_frames() {
let mut s = open(ANALYSED_0_24);
let before = saved(&s);
assert_eq!(before[0], ("saved analysis".into(), SIGNATURE_0_24.into()));
assert_eq!(before[1], ("saved tracks".into(), SIGNATURE_0_24.into()));
assert_eq!(before[2], ("saved frozen".into(), ROTO_INPUT_0_24.into()));
add_to_render_queue(&mut s);
assert_eq!(saved(&s), before);
s.execute_checked("edit.undo", json!({})).unwrap();
assert_eq!(saved(&s), before);
// Saved and reopened, the keys still match.
let mut s = open(&s.project.to_json());
add_to_render_queue(&mut s);
assert_eq!(saved(&s), before);
// Other frames: all three are cleared (the Roto Brush gets a new key), and undo brings them back.
s.execute_checked("layer.timing", json!({"layer": CLIP.0, "out": 0.25})).unwrap();
let after = saved(&s);
assert_eq!(after[0], (String::new(), String::new()));
assert_eq!(after[1], (String::new(), String::new()));
assert_eq!(after[2].0, "");
assert_ne!(after[2].1, ROTO_INPUT_0_24);
s.execute_checked("edit.undo", json!({})).unwrap();
assert_eq!(saved(&s), before);
// Time Remap is part of the frames.
s.execute_checked("prop.set", json!({"layer": CLIP.0, "path": "timeRemap", "value": 0.3})).unwrap();
assert!(saved(&s).iter().all(|(data, _)| data.is_empty()));
s.execute_checked("edit.undo", json!({})).unwrap();
// The Roto Brush's input also has the layer's masks and the effects above it.
s.execute_checked("prop.set", json!({"layer": CLIP.0, "path": "effects/#3/blurriness", "value": 4})).unwrap();
let after = saved(&s);
assert_eq!(after[2].0, "");
assert_ne!(after[2].1, ROTO_INPUT_0_24);
s.execute_checked("edit.undo", json!({})).unwrap();
s.execute_checked("prop.set", json!({"layer": CLIP.0, "path": "masks/#1/expansion", "value": 3})).unwrap();
assert_eq!(saved(&s)[2].0, "");
s.execute_checked("edit.undo", json!({})).unwrap();
assert_eq!(saved(&s), before);
}
/// The text keys are made from today, written field by field (#3536). It changes only when this
/// test is changed with it: a new field of a type it writes doesn't compile until it is decided
/// in `analysis::frames_key`, and renaming a field or variant doesn't change it.
#[test]
fn signature_text_is_pinned() {
let s = open(ANALYSED_0_24);
let layer = s.project.comp(COMP).unwrap().layer(CLIP).unwrap();
let key = r#"frames/1;footage=1;footage;path="/tmp/effectcraft-3456-shake.mp4";kind=video;w=160;h=120;par=1.0;rate=12/1;nativeRate=none;duration=254016000000;video=true;audio=false;alpha=ignore;matte=[0.0, 0.0, 0.0];loop=1;codec="H.264 (High)";frames=0;profile{rec709;};layer=none;fields=off;invertAlpha=false;linearLight=false;preserveRgb=false;cineon;log=false;points=[0.0, 1023.0, 95.0, 685.0, 1.7, 20.0];units=10bit;data=none;page=0;alphabetical=false;startTimecode=none;fileTimecode=none;placedPage=false;in=0;out=254016000000;start=0;stretch=100.0;timeRemap{prop="timeRemap";name="Time Remap";scalar=0.0;spatial=false;key=0;scalar=0.2;interp=linear/linear;continuous=false;autoBezier=false;spatialIn=[0.0, 0.0, 0.0];spatialOut=[0.0, 0.0, 0.0];spatialAuto=true;spatialContinuous=false;roving=false;muted=false;key=254016000000;scalar=1.0;interp=linear/linear;continuous=false;autoBezier=false;spatialIn=[0.0, 0.0, 0.0];spatialOut=[0.0, 0.0, 0.0];spatialAuto=true;spatialContinuous=false;roving=false;muted=false;expr=none;};compRate{rate=12/1;};"#;
assert_eq!(crate::analysis::frames_key::signature_text(&s.project, COMP, layer), key);
}
/// Keys made today (after analysing again) match through edits, undo and save/reopen too, and
/// renaming or relabelling never drops them.
#[test]
fn todays_keys_survive_edits_that_keep_their_frames() {
let mut s = open(ANALYSED_0_24);
// Analysing again writes today's keys.
let layer = s.project.comp(COMP).unwrap().layer(CLIP).unwrap();
let signature = crate::analysis::frames_key::signature(&s.project, COMP, layer);
let input = crate::roto::input_key(&s.project, COMP, layer, ROTO);
assert_ne!(signature, SIGNATURE_0_24);
s.edit("analyse", None, |p, _| {
let l = p.comp_mut(COMP).unwrap().layer_mut(CLIP).unwrap();
for (uid, id, key) in [(WARP, ANALYSIS_KEY, &signature), (TRACKER, TRACKS_KEY, &signature), (ROTO, INPUT_KEY, &input)] {
l.props.find_group_mut(uid).unwrap().get_mut(id).unwrap().value = Value::Str(key.clone());
}
Ok(())
})
.unwrap();
// The Roto Brush's key covers the effects above it: the Warp Stabilizer's new key changed it.
let layer = s.project.comp(COMP).unwrap().layer(CLIP).unwrap();
let input = crate::roto::input_key(&s.project, COMP, layer, ROTO);
s.edit("roto key", None, |p, _| {
let g = p.comp_mut(COMP).unwrap().layer_mut(CLIP).unwrap().props.find_group_mut(ROTO).unwrap();
g.get_mut(INPUT_KEY).unwrap().value = Value::Str(input.clone());
g.get_mut(FROZEN).unwrap().value = Value::Str("saved frozen".into());
Ok(())
})
.unwrap();
let before = saved(&s);
assert_eq!(before[0].1, signature);
assert_eq!(before[2], ("saved frozen".into(), input));
add_to_render_queue(&mut s);
assert_eq!(saved(&s), before);
s.execute_checked("edit.undo", json!({})).unwrap();
assert_eq!(saved(&s), before);
let mut s = open(&s.project.to_json());
add_to_render_queue(&mut s);
assert_eq!(saved(&s), before);
// Offline and back online (#3534).
for missing in [true, false] {
if let Some(effectcraft_project::ItemKind::Footage(f)) = std::sync::Arc::make_mut(&mut s.project).item_mut(ItemId(1)).map(|i| &mut i.kind) {
f.missing = missing;
}
add_to_render_queue(&mut s);
assert_eq!(saved(&s), before);
}
// Colour labels and footage markers only show things.
s.edit("label", None, |p, _| {
let l = p.comp_mut(COMP).unwrap().layer_mut(CLIP).unwrap();
l.props.find_group_mut(82).unwrap().label = Some(effectcraft_color::Label::Yellow);
if let Some(effectcraft_project::ItemKind::Footage(f)) = p.item_mut(ItemId(1)).map(|i| &mut i.kind) {
f.markers.push(effectcraft_project::Marker::default());
}
Ok(())
})
.unwrap();
assert_eq!(saved(&s), before);
// Expressions find effects by name: renaming the effect above the Roto Brush is a change for it.
s.edit("rename", None, |p, _| {
p.comp_mut(COMP).unwrap().layer_mut(CLIP).unwrap().props.find_group_mut(82).unwrap().name = "Soft".into();
Ok(())
})
.unwrap();
assert_eq!(saved(&s)[..2], before[..2]);
assert_eq!(saved(&s)[2].0, "");
s.execute_checked("edit.undo", json!({})).unwrap();
assert_eq!(saved(&s), before);
// A real change still clears them.
s.execute_checked("file.interpretFootage", json!({"items": [1], "invertAlpha": true})).unwrap();
assert!(saved(&s).iter().all(|(data, _)| data.is_empty()));
}
/// Footage going offline (or coming back) is an observation, not an edit: the next edit keeps
/// every analysis (#3534).
#[test]
fn offline_footage_keeps_analyses() {
let mut s = open(ANALYSED_0_24);
let before = saved(&s);
let missing = |s: &Session| matches!(&s.project.item(ItemId(1)).unwrap().kind, effectcraft_project::ItemKind::Footage(f) if f.missing);
// The fixture's footage path doesn't exist here: the check marks it missing.
let r = s.execute_checked("footage.check", json!({"wait": true})).unwrap();
assert_eq!(r["missing"], 1, "{r}");
assert!(missing(&s));
add_to_render_queue(&mut s);
assert_eq!(saved(&s), before);
// Saved and reopened while offline, then back online.
let mut s = open(&s.project.to_json());
assert!(missing(&s));
add_to_render_queue(&mut s);
assert_eq!(saved(&s), before);
if let Some(effectcraft_project::ItemKind::Footage(f)) = std::sync::Arc::make_mut(&mut s.project).item_mut(ItemId(1)).map(|i| &mut i.kind) {
f.missing = false;
}
add_to_render_queue(&mut s);
assert_eq!(saved(&s), before);
// A real change while offline still clears them.
s.execute_checked("file.interpretFootage", json!({"items": [1], "invertAlpha": true})).unwrap();
assert!(saved(&s).iter().all(|(data, _)| data.is_empty()));
}
/// A key 0.24.1 saved while the footage was offline (it hashed the availability) matches too,
/// online or offline. 0.24.1 gave the Roto Brush this Input Key when the fixture's footage went
/// offline and an edit cleared the other two analyses.
#[test]
fn keys_saved_by_0_24_while_offline_still_match() {
const ROTO_INPUT_0_24_OFFLINE: &str = "6183fdd46b514259";
let mut s = open(ANALYSED_0_24);
s.edit("offline", None, |p, _| {
if let Some(effectcraft_project::ItemKind::Footage(f)) = p.item_mut(ItemId(1)).map(|i| &mut i.kind) {
f.missing = true;
}
let l = p.comp_mut(COMP).unwrap().layer_mut(CLIP).unwrap();
// What 0.24.1's edit cleared then.
use effectcraft_effects::camera_tracker::{AVERAGE_ERROR, METHOD_USED, SOLVE, SOLVE_KEY};
for (uid, id) in
[(WARP, ANALYSIS), (WARP, ANALYSIS_KEY), (TRACKER, SOLVE), (TRACKER, SOLVE_KEY), (TRACKER, METHOD_USED), (TRACKER, TRACKS), (TRACKER, TRACKS_KEY)]
{
l.props.find_group_mut(uid).unwrap().prop_mut(id).unwrap().value = Value::Str(String::new());
}
l.props.find_group_mut(TRACKER).unwrap().prop_mut(AVERAGE_ERROR).unwrap().value = Value::Scalar(0.0);
let g = l.props.find_group_mut(ROTO).unwrap();
g.get_mut(INPUT_KEY).unwrap().value = Value::Str(ROTO_INPUT_0_24_OFFLINE.into());
Ok(())
})
.unwrap();
let roto = |s: &Session| saved(s)[2].clone();
assert_eq!(roto(&s), ("saved frozen".into(), ROTO_INPUT_0_24_OFFLINE.into()));
for missing in [true, false] {
if let Some(effectcraft_project::ItemKind::Footage(f)) = std::sync::Arc::make_mut(&mut s.project).item_mut(ItemId(1)).map(|i| &mut i.kind) {
f.missing = missing;
}
add_to_render_queue(&mut s);
assert_eq!(roto(&s), ("saved frozen".into(), ROTO_INPUT_0_24_OFFLINE.into()));
}
}
/// Expressions seed `random` and `wiggle` with the property's uid: a Time Remap with an expression
/// keys its uid (a duplicated layer gets new uids), one without doesn't.
#[test]
fn an_expression_keys_its_property_uid() {
let s = open(ANALYSED_0_24);
let layer = s.project.comp(COMP).unwrap().layer(CLIP).unwrap().clone();
let text = |l: &effectcraft_project::Layer| crate::analysis::frames_key::signature_text(&s.project, COMP, l);
let renumbered = |l: &effectcraft_project::Layer| {
let mut l = l.clone();
l.props.get_mut("timeRemap").unwrap().uid += 1000;
l
};
assert_eq!(text(&renumbered(&layer)), text(&layer));
let mut with_expr = layer.clone();
with_expr.props.get_mut("timeRemap").unwrap().expr =
Some(effectcraft_project::Expression { text: "seedRandom(0, true); random(0, 1)".into(), enabled: true });
assert_ne!(text(&renumbered(&with_expr)), text(&with_expr));
}
/// Non-default values of the types the key writes are written as their fixed words (#3536).
#[test]
fn nested_values_are_written_as_fixed_words() {
use effectcraft_project::{
AlphaMode, CineonUnits, FieldOrder, FootageKind, GroupKind, ItemKind, LayerSource, MaskMode, MaskMotionBlur, Solid, SourceLayer,
};
let mut s = open(ANALYSED_0_24);
let p = std::sync::Arc::make_mut(&mut s.project);
if let Some(ItemKind::Footage(f)) = p.item_mut(ItemId(1)).map(|i| &mut i.kind) {
f.kind = FootageKind::Sequence;
f.sequence = vec!["a_0001.png".into(), "a_0002.png".into()];
f.alpha = AlphaMode::Premultiplied;
f.premul_color = [0.5, 0.25, 1.0];
f.fields = FieldOrder::UpperFirst;
f.cineon.units = CineonUnits::Float;
f.cineon.log_conversion = true;
f.color_profile = Some(effectcraft_color::ColorSpace::DisplayP3);
f.layer = Some(SourceLayer { index: 3, name: "Sky".into(), layer_size: true, embedded: Some("id-7".into()), placed: true });
f.native_rate = Some(effectcraft_time::FrameRate { num: 30000, den: 1001 });
f.start_timecode = Some(42);
f.data = Some("{\"k\":1}".into());
}
let layer = p.comp(COMP).unwrap().layer(CLIP).unwrap().clone();
let text = crate::analysis::frames_key::signature_text(p, COMP, &layer);
let footage = text.split(";in=").next().unwrap();
assert_eq!(
footage,
r#"frames/1;footage=1;footage;path="/tmp/effectcraft-3456-shake.mp4";kind=sequence;w=160;h=120;par=1.0;rate=12/1;nativeRate{rate=30000/1001;};duration=254016000000;video=true;audio=false;alpha=premultiplied;matte=[0.5, 0.25, 1.0];loop=1;codec="H.264 (High)";frames=2;file="a_0001.png";file="a_0002.png";profile{p3;};layer{index=3;layerSize=true;embedded{id="id-7";};placed=true;};fields=upper;invertAlpha=false;linearLight=false;preserveRgb=false;cineon;log=true;points=[0.0, 1023.0, 95.0, 685.0, 1.7, 20.0];units=float;data{text="{\"k\":1}";};page=0;alphabetical=false;startTimecode{frame=42;};fileTimecode=none;placedPage=false"#
);
let solid = p.add_item("Solid", Default::default(), None, ItemKind::Solid(Solid { color: [1.0, 0.5, 0.0], width: 64, height: 48, pixel_aspect: 2.0 }));
let mut on_solid = layer.clone();
on_solid.source = LayerSource::Solid { item: solid };
let text = crate::analysis::frames_key::signature_text(p, COMP, &on_solid);
assert_eq!(text.split(";in=").next().unwrap(), format!("frames/1;solid={};solid;color=[1.0, 0.5, 0.0];w=64;h=48;par=2.0", solid.0));
// Every mask mode and motion blur setting gives its own Input Key.
let mask = layer.masks().unwrap().groups().next().unwrap().uid;
let mut keys = std::collections::BTreeSet::new();
for mode in MaskMode::ALL {
for blur in [MaskMotionBlur::SameAsLayer, MaskMotionBlur::On, MaskMotionBlur::Off] {
let mut l = layer.clone();
if let GroupKind::Mask { mode: m, motion_blur, .. } = &mut l.props.find_group_mut(mask).unwrap().kind {
(*m, *motion_blur) = (mode, blur);
}
keys.insert(crate::analysis::frames_key::input_key(p, COMP, &l, ROTO));
}
}
assert_eq!(keys.len(), MaskMode::ALL.len() * 3);
}
+1
View File
@@ -0,0 +1 @@
{"schema":2,"settings":{"bit_depth":"Bpc8","linearize":false,"working_space":null,"blend_linear":false,"time_display":"Timecode","frame_start":0,"audio_sample_rate":48000,"gpu_acceleration":true,"color_engine":"Adobe","hdr":"Clip","output_space":null,"working_gamma":2.2},"items":{"1":{"id":1,"name":"effectcraft-3456-shake.mp4","label":"Aqua","comment":"","parent":null,"kind":{"type":"Footage","path":"/tmp/effectcraft-3456-shake.mp4","kind":"Video","width":160,"height":120,"pixel_aspect":1.0,"frame_rate":{"num":12,"den":1},"native_rate":null,"duration":254016000000,"has_video":true,"has_audio":false,"alpha":"Ignore","premul_color":[0.0,0.0,0.0],"loop_count":1,"codec":"H.264 (High)","missing":false,"color_profile":"Rec709"}},"2":{"id":2,"name":"effectcraft-3456-shake","label":"Sandstone","comment":"","parent":null,"kind":{"type":"Comp","width":160,"height":120,"pixel_aspect":1.0,"frame_rate":{"num":12,"den":1},"duration":254016000000,"display_start":0,"background":[0.0,0.0,0.0],"work_area":[0,254016000000],"layers":[{"id":3,"name":"effectcraft-3456-shake.mp4","source":{"type":"Footage","item":1},"label":"Aqua","comment":"","start_time":0,"in_point":0,"out_point":254016000000,"stretch":100.0,"switches":{"video":true,"audio":true,"solo":false,"locked":false,"shy":false,"collapse":false,"quality":"Best","sampling":"Bilinear","effects":true,"frame_blend":"Off","motion_blur":false,"adjustment":false,"three_d":false,"guide":false},"blend_mode":"Normal","preserve_transparency":false,"track_matte":null,"parent":null,"markers":[],"auto_orient":"Off","props":{"uid":4,"match":"layer","name":"effectcraft-3456-shake.mp4","kind":{"kind":"Plain"},"enabled":true,"children":[{"node":"Prop","uid":76,"match":"timeRemap","name":"Time Remap","value":{"t":"Scalar","v":0.0},"keys":[{"time":0,"value":{"t":"Scalar","v":0.2},"in_interp":"Linear","out_interp":"Linear","in_ease":[],"out_ease":[],"continuous":false,"auto_bezier":false,"spatial_in":[0.0,0.0,0.0],"spatial_out":[0.0,0.0,0.0],"spatial_auto":true,"spatial_continuous":false,"roving":false},{"time":254016000000,"value":{"t":"Scalar","v":1.0},"in_interp":"Linear","out_interp":"Linear","in_ease":[],"out_ease":[],"continuous":false,"auto_bezier":false,"spatial_in":[0.0,0.0,0.0],"spatial_out":[0.0,0.0,0.0],"spatial_auto":true,"spatial_continuous":false,"roving":false}],"ui":{"kind":"Number"},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Group","uid":5,"match":"masks","name":"Masks","kind":{"kind":"Plain"},"enabled":true,"children":[{"node":"Group","uid":77,"match":"mask","name":"Mask 1","kind":{"kind":"Mask","mode":"Add","inverted":false,"color":[177,180,79],"locked":false,"motion_blur":"SameAsLayer","feather_falloff":"Smooth","roto_bezier":false},"enabled":true,"children":[{"node":"Prop","uid":78,"match":"path","name":"Mask Path","value":{"t":"Path","v":{"vertices":[[10.0,10.0],[120.0,10.0],[120.0,100.0],[10.0,100.0]],"in_tangents":[[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0]],"out_tangents":[[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0]],"closed":false}},"ui":{"kind":"Path"},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":79,"match":"feather","name":"Mask Feather","value":{"t":"Vec2","v":[0.0,0.0]},"ui":{"kind":"Pixels"},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":80,"match":"opacity","name":"Mask Opacity","value":{"t":"Scalar","v":100.0},"ui":{"kind":"Slider","min":0.0,"max":100.0,"slider_min":0.0,"slider_max":100.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":81,"match":"expansion","name":"Mask Expansion","value":{"t":"Scalar","v":0.0},"ui":{"kind":"Pixels"},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false}]}]},{"node":"Group","uid":6,"match":"effects","name":"Effects","kind":{"kind":"Plain"},"enabled":true,"children":[{"node":"Group","uid":26,"match":"ec.distort.warpstabilizer","name":"Warp Stabilizer","kind":{"kind":"Effect","effect":"ec.distort.warpstabilizer"},"enabled":true,"children":[{"node":"Group","uid":28,"match":"stabilization","name":"Stabilization","kind":{"kind":"Plain"},"enabled":true,"children":[{"node":"Prop","uid":27,"match":"result","name":"Result","value":{"t":"Enum","v":0},"ui":{"kind":"Popup","options":["Smooth Motion","No Motion"]},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":29,"match":"smoothness","name":"Smoothness","value":{"t":"Scalar","v":50.0},"ui":{"kind":"Slider","min":0.0,"max":1000.0,"slider_min":0.0,"slider_max":100.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":30,"match":"mLine truncated
@@ -0,0 +1,8 @@
asset: analysed-0.24.ecproj
title: The tracked-0.22 clip with Time Remap, a mask, Gaussian Blur and Roto Brush, keyed by EffectCraft 0.24.1
author: arnav-hiwarkar
source: original work
license: MIT OR Apache-2.0
license-file: ../../../../../LICENSE-MIT
added: 2026-11-12 by arnav-hiwarkar
notes: Made from tracked-0.22.ecproj with 0.24.1 engine commands (enable Time Remap, a rectangle mask, Gaussian Blur and Roto Brush), its saved analyses replaced by short stand-in strings, and the Warp Stabilizer, 3D Camera Tracker and Roto Brush keys that 0.24.1 computed for it. Written as compact JSON. No media is needed: the tests only check that the keys are kept or cleared.
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,8 @@
asset: tracked-0.22.ecproj
title: One clip with an analysed Warp Stabilizer and 3D Camera Tracker from EffectCraft 0.22.0
author: arnav-hiwarkar
source: original work
license: MIT OR Apache-2.0
license-file: ../../../../../LICENSE-MIT
added: 2026-11-12 by arnav-hiwarkar
notes: Saved by the released 0.22.0 CLI after importing a generated 160x120, 12-frame shaking crop of an ffmpeg testsrc2 pattern, applying both effects and analysing them. The source path is a generic test path; the video is not needed by the tests, which only check that the saved analyses are kept or cleared.
@@ -0,0 +1,127 @@
//! Warp Stabilizer and 3D Camera Tracker analyses saved by an earlier release keep matching
//! their footage after an edit that doesn't change it (#3456), and a real change still clears them.
use effectcraft_effects::camera_tracker::{SOLVE, TRACKS, TRACKS_KEY};
use effectcraft_effects::warp_stab::{ANALYSIS, ANALYSIS_KEY};
use effectcraft_keyframe::Value;
use effectcraft_project::{ItemId, LayerId, Project};
use serde_json::json;
use crate::Session;
const FOOTAGE: ItemId = ItemId(1);
const COMP: ItemId = ItemId(2);
const CLIP: LayerId = LayerId(3);
const WARP: u64 = 26;
const TRACKER: u64 = 54;
/// The analysis (as its length and a hash: it's long) and key of the Warp Stabilizer and the
/// 3D Camera Tracker.
fn saved(s: &Session) -> [(usize, u64, String); 2] {
use std::hash::{Hash, Hasher};
let layer = s.project.comp(COMP).unwrap().layer(CLIP).unwrap();
let get = |uid: u64, data: &str, key: &str| {
let params = crate::camera_track::static_params(layer.props.find_group(uid).unwrap());
let text = |id: &str| match params.get(id) {
Some(Value::Str(s)) => s.clone(),
other => panic!("{id}: {other:?}"),
};
let analysis = text(data);
let mut h = std::collections::hash_map::DefaultHasher::new();
analysis.hash(&mut h);
(analysis.len(), h.finish(), text(key))
};
[get(WARP, ANALYSIS, ANALYSIS_KEY), get(TRACKER, TRACKS, TRACKS_KEY)]
}
fn open(json: &str) -> Session {
let mut s = Session::default();
s.replace_project(Project::from_json(json).unwrap(), None);
s.open_comp(COMP);
s
}
#[test]
fn analyses_saved_by_0_22_survive_edits_that_keep_their_frames() {
// Saved by the released 0.22.0 CLI after analysing both effects; its footage is offline here.
let mut s = open(include_str!("fixtures/tracked-0.22.ecproj"));
let before = saved(&s);
let layer = s.project.comp(COMP).unwrap().layer(CLIP).unwrap();
for (len, _, key) in &before {
assert!(*len > 0);
// The key predates Footage::placed_page, so it isn't today's signature.
assert_ne!(key, &crate::analysis::frames_key::signature(&s.project, COMP, layer));
}
// Adding to the render queue edits the project, as `effectcraft-cli render` does.
s.execute_checked("renderQueue.add", json!({"comp": COMP.0, "format": "png", "output": "frame.png"})).unwrap();
assert_eq!(saved(&s), before);
s.execute_checked("edit.undo", json!({})).unwrap();
assert_eq!(saved(&s), before);
// Saved and reopened (by this version), the old keys are kept and still match.
let mut s = open(&s.project.to_json());
s.execute_checked("renderQueue.add", json!({"comp": COMP.0, "format": "png", "output": "frame.png"})).unwrap();
assert_eq!(saved(&s), before);
// Other frames, from other timing or a reinterpreted footage item: both analyses are
// cleared, and undo brings them back.
let cleared = |s: &Session| saved(s).iter().all(|(len, _, key)| *len == 0 && key.is_empty());
s.execute_checked("layer.timing", json!({"layer": CLIP.0, "out": 0.5})).unwrap();
assert!(cleared(&s));
s.execute_checked("edit.undo", json!({})).unwrap();
assert_eq!(saved(&s), before);
s.execute_checked("file.interpretFootage", json!({"items": [FOOTAGE.0], "invertAlpha": true})).unwrap();
assert!(cleared(&s));
s.execute_checked("edit.undo", json!({})).unwrap();
assert_eq!(saved(&s), before);
// Footage framed as a placed page has other frames too, though 0.22 had no such field.
s.edit("place page", None, |p, _| {
if let Some(effectcraft_project::ItemKind::Footage(f)) = p.item_mut(FOOTAGE).map(|i| &mut i.kind) {
f.placed_page = true;
}
Ok(())
})
.unwrap();
assert!(cleared(&s));
}
/// Solving again reuses the 0.22 tracks rather than tracking the (here offline) footage again.
#[test]
fn camera_tracker_solves_again_from_tracks_saved_by_0_22() {
let mut s = open(include_str!("fixtures/tracked-0.22.ecproj"));
let tracks = saved(&s)[1].clone();
let solve = |s: &Session| {
let g = s.project.comp(COMP).unwrap().layer(CLIP).unwrap().props.find_group(TRACKER).unwrap();
crate::camera_track::static_params(g).get(SOLVE).cloned().unwrap()
};
// Another solve method, and back, clears the solve and keeps the tracks.
for method in [1, 0] {
s.execute_checked("prop.set", json!({"layer": CLIP.0, "path": "effects/#2/advanced/solveMethod", "value": method})).unwrap();
}
assert_eq!(solve(&s), Value::Str(String::new()));
assert_eq!(saved(&s)[1], tracks);
s.execute_checked("camera.analyze", json!({"layer": CLIP.0, "effect": TRACKER, "wait": true})).unwrap();
assert!(matches!(solve(&s), Value::Str(v) if !v.is_empty()));
assert_eq!(saved(&s)[1], tracks);
}
/// The footage text analysis keys are hashed from, as 0.23 saved it. A new `Footage` field must
/// not change it (or every saved analysis is dropped again).
#[test]
fn footage_signature_text_is_pinned() {
use effectcraft_project::{Footage, FootageKind};
let f = Footage {
path: "clip.mp4".into(),
kind: FootageKind::Video,
width: 160,
height: 120,
invert_alpha: true,
page: 2,
placed_page: true,
..Footage::default()
};
let fields = r#"path: "clip.mp4", kind: Video, width: 160, height: 120, pixel_aspect: 1.0, frame_rate: FrameRate { num: 30, den: 1 }, native_rate: None, duration: Tick(0), has_video: false, has_audio: false, alpha: Straight, premul_color: [0.0, 0.0, 0.0], loop_count: 1, codec: "", missing: false, sequence: [], color_profile: None, layer: None, fields: Off, invert_alpha: true, linear_light: false, preserve_rgb: false, cineon: CineonSettings { log_conversion: false, converted_black: 0.0, converted_white: 1023.0, black: 95.0, white: 685.0, gamma: 1.7, rolloff: 20.0, units: TenBit }, data: None, page: 2, alphabetical: false, start_timecode: None, file_timecode: None, markers: []"#;
assert_eq!(crate::analysis::frames_key::legacy::footage_text(&f, false, true), format!("Footage {{ {fields}, placed_page: true }}"));
assert_eq!(crate::analysis::frames_key::legacy::footage_text(&f, false, false), format!("Footage {{ {fields} }}"));
}
+188
View File
@@ -0,0 +1,188 @@
//! A LUT file that changes on disk renders again (#3493): Apply Color LUT and Lumetri's Input
//! LUT name a `.cube` file; an edit to it, or a file created, deleted or repaired, shows on the
//! next render of the same frame, from warm layer caches in memory and on disk, through a precomp
//! and a layer reading that precomp, and a frame kept on disk made with the old file is refused.
use std::path::Path;
use std::time::{Duration, UNIX_EPOCH};
use serde_json::{Value, json};
use crate::Session;
use crate::render::RenderOpts;
use effectcraft_project::ItemId;
use effectcraft_render::disk_cache::{DiskCache, comp_content_key, frame_key};
use effectcraft_render::reads::ReadLog;
use effectcraft_time::Tick;
/// Every input to black, or to white (1D, two entries: the same size, so only the modification
/// time tells the two apart).
const BLACK: &str = "LUT_1D_SIZE 2\n0 0 0\n0 0 0\n";
const WHITE: &str = "LUT_1D_SIZE 2\n1 1 1\n1 1 1\n";
const GREY: f32 = 128.0 / 255.0;
/// Write `text` to `path` with its modification time `secs` after the epoch.
fn write(path: &Path, text: &str, secs: u64) {
std::fs::write(path, text).unwrap();
let f = std::fs::File::options().write(true).open(path).unwrap();
f.set_modified(UNIX_EPOCH + Duration::from_secs(secs)).unwrap();
}
/// A session, its layer buffers written to a disk cache in `disk` when given.
fn session(disk: Option<&Path>) -> Session {
let mut s = Session::default();
if let Some(dir) = disk {
s.execute_checked("prefs.set", json!({"values": {"disk.diskCacheFolder": dir.to_string_lossy(), "disk.diskCacheEnabled": true}})).unwrap();
s.disk_cache.as_ref().unwrap().set_min_layer_ms(0);
}
s
}
/// Comp "Grade": a grey solid graded by `effect` (`params` set on it). Comp "Shot" shows it as a
/// precomp layer, under a solid that copies the precomp's channels (Set Channels): that layer is
/// cached with what the precomp shows. Returns (Grade, Shot).
fn shot(s: &mut Session, effect: &str, params: &[(&str, Value)]) -> (ItemId, ItemId) {
s.execute_checked("comp.new", json!({"name": "Shot", "width": 8, "height": 8, "frameRate": 24, "duration": 1})).unwrap();
let shot = s.active_comp_id().unwrap();
let plate = s.execute_checked("layer.newSolid", json!({"name": "Plate", "color": "#808080", "width": 8, "height": 8})).unwrap()["layer"].clone();
s.execute_checked("effect.apply", json!({"layer": plate, "effect": effect})).unwrap();
for (path, value) in params {
s.execute_checked("prop.set", json!({"layer": plate, "path": format!("effects/#1/{path}"), "value": value})).unwrap();
}
let pre = s.execute_checked("layer.precompose", json!({"layers": [plate], "name": "Grade"})).unwrap();
let grade = ItemId(pre["comp"].as_u64().unwrap());
let copy = s.execute_checked("layer.newSolid", json!({"name": "Copy", "color": "#00ff00", "width": 8, "height": 8})).unwrap()["layer"].clone();
s.execute_checked("effect.apply", json!({"layer": copy, "effect": "Set Channels"})).unwrap();
for i in 1..=3 {
s.execute_checked("prop.set", json!({"layer": copy, "path": format!("effects/#1/sourceLayer{i}"), "value": pre["layer"]})).unwrap();
}
(grade, shot)
}
/// The red and green of the centre of both comps' first frame.
fn colours(s: &Session, (grade, shot): (ItemId, ItemId)) -> [f32; 4] {
let at = |comp| {
let img = s.render(comp, Tick::ZERO, RenderOpts::default());
img.get(i64::from(img.width / 2), i64::from(img.height / 2))
};
let (g, c) = (at(grade), at(shot));
[g[0], g[1], c[0], c[1]]
}
#[track_caller]
fn assert_all(got: [f32; 4], want: f32) {
assert!(got.iter().all(|v| (v - want).abs() < 0.01), "{got:?}, want {want}");
}
#[test]
fn an_edited_lut_file_renders_again_from_warm_caches() {
let dir = tempfile::tempdir().unwrap();
let lut = dir.path().join("grade.cube");
write(&lut, BLACK, 1_000);
let mut s = session(None);
let comps = shot(&mut s, "Apply Color LUT", &[("lut", json!(lut.to_string_lossy()))]);
assert_all(colours(&s, comps), 0.0);
let misses = s.layer_cache.stats().misses;
assert_all(colours(&s, comps), 0.0);
assert_eq!(s.layer_cache.stats().misses, misses, "an unchanged file keeps the cached layers");
// A frame on disk made with the file names it.
let frames = DiskCache::open(dir.path().join("frames"), 1 << 30).unwrap();
let key = frame_key(comp_content_key(&s.project, comps.1), 0, 1000, 0);
let log = ReadLog::new();
let mut r = s.renderer(RenderOpts::default());
r.reads = Some(&log);
let _ = r.comp_frame(comps.1, Tick::ZERO);
let files = log.into_files();
assert!(files.get(&lut.to_string_lossy()).is_some(), "the render notes the LUT file: {files:?}");
frames.put_frame_now(key, 1, 1, &[0; 4], &files);
assert!(frames.get_frame(key, None).is_some());
let generation = effectcraft_effects::lut_generation();
write(&lut, WHITE, 2_000);
assert_all(colours(&s, comps), 1.0);
assert!(effectcraft_effects::lut_generation() > generation, "the viewer's frames made before are dropped");
assert!(frames.get_frame(key, None).is_none(), "the frame on disk made with the old file");
}
#[test]
fn an_edited_lut_file_is_not_served_from_the_disk_cache() {
let dir = tempfile::tempdir().unwrap();
let (lut, disk) = (dir.path().join("grade.cube"), dir.path().join("cache"));
write(&lut, BLACK, 1_000);
let mut s = session(Some(&disk));
let comps = shot(&mut s, "Apply Color LUT", &[("lut", json!(lut.to_string_lossy()))]);
assert_all(colours(&s, comps), 0.0);
let dc = s.disk_cache.clone().unwrap();
dc.flush();
assert!(dc.stats().entries > 0, "layer buffers written");
let project = s.project.clone();
drop((s, dc));
// A restart on the same cache, after the file changed.
write(&lut, WHITE, 2_000);
let mut s = session(Some(&disk));
s.project = project;
s.bump();
assert_all(colours(&s, comps), 1.0);
}
#[test]
fn a_lut_file_created_deleted_or_repaired_renders_again() {
let dir = tempfile::tempdir().unwrap();
let lut = dir.path().join("later.cube");
let mut s = session(None);
let comps = shot(&mut s, "Apply Color LUT", &[("lut", json!(lut.to_string_lossy()))]);
assert_all(colours(&s, comps), GREY);
write(&lut, WHITE, 1_000);
assert_all(colours(&s, comps), 1.0);
std::fs::remove_file(&lut).unwrap();
assert_all(colours(&s, comps), GREY);
write(&lut, "not a LUT", 2_000);
assert_all(colours(&s, comps), GREY);
write(&lut, BLACK, 3_000);
assert_all(colours(&s, comps), 0.0);
}
#[test]
fn lumetri_follows_its_input_lut_file() {
let dir = tempfile::tempdir().unwrap();
let lut = dir.path().join("input.cube");
write(&lut, BLACK, 1_000);
let mut s = session(None);
let comps = shot(&mut s, "Lumetri Color", &[("basicCorrection/inputLut", json!(1)), ("basicCorrection/inputLutFile", json!(lut.to_string_lossy()))]);
assert_all(colours(&s, comps), 0.0);
write(&lut, WHITE, 2_000);
assert_all(colours(&s, comps), 1.0);
}
/// A precomp instance whose Essential Property names another LUT file follows that file, also
/// for a layer that reads the instance through a layer parameter.
#[test]
fn an_overridden_lut_file_renders_again() {
let dir = tempfile::tempdir().unwrap();
let (base, overridden) = (dir.path().join("base.cube"), dir.path().join("override.cube"));
write(&base, WHITE, 1_000);
write(&overridden, BLACK, 1_000);
let mut s = session(None);
s.execute_checked("comp.new", json!({"name": "Grade", "width": 8, "height": 8, "frameRate": 24, "duration": 1})).unwrap();
let grade = s.active_comp_id().unwrap();
let plate = s.execute_checked("layer.newSolid", json!({"name": "Plate", "color": "#808080", "width": 8, "height": 8})).unwrap()["layer"].clone();
s.execute_checked("effect.apply", json!({"layer": plate, "effect": "Apply Color LUT"})).unwrap();
s.execute_checked("prop.set", json!({"layer": plate, "path": "effects/#1/lut", "value": base.to_string_lossy()})).unwrap();
let control = s.execute_checked("essential.addProperty", json!({"layer": plate, "path": "effects/#1/lut", "name": "LUT"})).unwrap()["controls"][0].clone();
s.execute_checked("comp.new", json!({"name": "Shot", "width": 8, "height": 8, "frameRate": 24, "duration": 1})).unwrap();
let shot = s.active_comp_id().unwrap();
let instance = s.execute_checked("layer.addItem", json!({"item": grade.0})).unwrap()["layer"].clone();
s.execute_checked("essential.set", json!({"layer": instance, "control": control, "value": overridden.to_string_lossy()})).unwrap();
let copy = s.execute_checked("layer.newSolid", json!({"name": "Copy", "color": "#00ff00", "width": 8, "height": 8})).unwrap()["layer"].clone();
s.execute_checked("effect.apply", json!({"layer": copy, "effect": "Set Channels"})).unwrap();
for i in 1..=3 {
s.execute_checked("prop.set", json!({"layer": copy, "path": format!("effects/#1/sourceLayer{i}"), "value": instance})).unwrap();
}
let centre = |s: &Session| {
let img = s.render(shot, Tick::ZERO, RenderOpts::default());
let p = img.get(i64::from(img.width / 2), i64::from(img.height / 2));
[p[0], p[1], p[0], p[1]]
};
assert_all(centre(&s), 0.0);
write(&overridden, WHITE, 2_000);
assert_all(centre(&s), 1.0);
}
+19
View File
@@ -96,6 +96,25 @@ fn imported_files_go_into_the_comp_where_they_were_dropped() {
assert!(s.execute("layer.addItem", json!({"item": "a.png", "position": [1.0]})).is_err(), "position needs x and y");
}
/// What an import left out of a file (a 3D model's textures over the limits) comes back in the
/// import's `warnings`.
#[test]
fn what_an_import_left_out_is_a_warning() {
use effectcraft_project::{Footage, FootageKind};
struct Probe;
impl crate::Importer for Probe {
fn probe(&self, path: &str) -> Result<Footage, String> {
Ok(Footage { path: path.into(), kind: FootageKind::Model, ..Default::default() })
}
fn probe_noting(&self, path: &str) -> Result<(Footage, Option<String>), String> {
Ok((self.probe(path)?, Some(format!("{path}: texture `a.png` left out"))))
}
}
let mut s = Session { importer: Some(std::sync::Arc::new(Probe)), ..Default::default() };
let r = s.execute("file.import", json!({"paths": ["/m/scene.obj"]})).unwrap();
assert_eq!(r["warnings"], json!(["/m/scene.obj: texture `a.png` left out"]));
}
/// #270: files dropped or picked in the Import dialog (`file.import {background}`) are probed in
/// a background job that says which file it is reading and how many are left; then they arrive
/// in one undo step, all selected, with a count. The same file imported again arrives again.
+25
View File
@@ -1581,3 +1581,28 @@ fn a_typed_component_moves_its_follow_components_by_each_layers_own_change() {
let keys: Vec<Vec<f64>> = prop(&s, b, "audio/levels").keys.iter().map(|k| k.value.components()).collect();
assert_eq!(keys, vec![vec![-20.0, -30.0], vec![-4.0, -34.0]], "B's 1 s key rises 6 dB on both channels");
}
#[test]
fn convert_expression_to_keyframes_refuses_a_layer_of_millions_of_frames() {
let (mut s, l) = setup();
s.execute("prop.setExpression", json!({"layer": l, "path": "transform/rotation", "expression": "value"})).unwrap();
// A saved Out point a million seconds after the In point.
let cid = s.active_comp_id().unwrap();
std::sync::Arc::make_mut(&mut s.project).comp_mut(cid).unwrap().layer_mut(effectcraft_project::LayerId(l)).unwrap().out_point =
effectcraft_time::Tick::from_seconds_f64(1e6);
let e = s.execute("prop.convertExpressionToKeyframes", json!({"layer": l, "path": "transform/rotation"})).unwrap_err().to_string();
assert!(e.contains("at most"), "{e}");
assert!(prop(&s, l, "transform/rotation").keys.is_empty());
}
#[test]
fn convert_expression_to_keyframes_refuses_a_zero_frame_duration() {
let (mut s, l) = setup();
s.execute("prop.setExpression", json!({"layer": l, "path": "transform/rotation", "expression": "value"})).unwrap();
// A saved frame rate of 0/1 s has a frame duration of 0: the sampling loop never advanced.
let cid = s.active_comp_id().unwrap();
std::sync::Arc::make_mut(&mut s.project).comp_mut(cid).unwrap().frame_rate.den = 0;
let e = s.execute("prop.convertExpressionToKeyframes", json!({"layer": l, "path": "transform/rotation"})).unwrap_err().to_string();
assert!(e.contains("frame duration"), "{e}");
assert!(prop(&s, l, "transform/rotation").keys.is_empty());
}
+6 -9
View File
@@ -1,6 +1,6 @@
[package]
name = "effectcraft-export"
description = "Render Queue jobs and output modules: H.264 MP4 (+AAC), ProRes and uncompressed MOV (+PCM) via FilmCraft, HEVC / AV1 MP4 (+AAC) and WebM (VP9 or AV1 + Opus) via EffectCraft encoders, PNG/JPEG/TIFF/EXR/Targa sequences, animated GIF, WAV/AIFF"
description = "Render Queue jobs and output modules: H.264 MP4 (+AAC), ProRes and uncompressed MOV (+PCM) , HEVC / AV1 MP4 (+AAC) and WebM (VP9 or AV1) via craft-libs codecs, Opus via effectcraft-opusenc, PNG/JPEG/TIFF/EXR/Targa sequences, animated GIF, WAV/AIFF"
version.workspace = true
edition.workspace = true
license.workspace = true
@@ -14,14 +14,10 @@ effectcraft-time = { workspace = true }
effectcraft-project = { workspace = true }
effectcraft-raster = { workspace = true }
effectcraft-render = { workspace = true }
filmcraft-h264enc = { workspace = true }
filmcraft-prores = { workspace = true }
filmcraft-aac = { workspace = true }
filmcraft-isobmff = { workspace = true }
craft-video = { workspace = true }
craft-audio = { workspace = true }
craft-media = { workspace = true }
effectcraft-opusenc = { workspace = true }
effectcraft-vp9enc = { workspace = true }
effectcraft-hevcenc = { workspace = true }
effectcraft-av1enc = { workspace = true }
image = { workspace = true, features = ["png", "jpeg", "tiff", "exr", "tga"] }
exr = { workspace = true }
gif = { workspace = true }
@@ -35,6 +31,7 @@ tempfile = { workspace = true }
effectcraft-media = { workspace = true }
effectcraft-effects = { workspace = true }
effectcraft-color = { workspace = true }
filmcraft-opus = { workspace = true }
filmcraft-hevc = { workspace = true }
filmcraft-av1 = { workspace = true }
filmcraft-vp9 = { workspace = true }
effectcraft-keyframe = { workspace = true }
+26 -26
View File
@@ -1,13 +1,13 @@
//! Movie export: FilmCraft H.264, HEVC (`effectcraft-hevcenc`) and AV1 (`effectcraft-av1enc`)
//! Movie export: H.264 (`craft_video::h264`), HEVC (`craft_video::hevc`) and AV1 (`craft_video::av1`)
//! → MP4 (+ AAC), ProRes and uncompressed `raw ` → MOV (+ PCM), muxed by
//! FilmCraft's ISO BMFF / QuickTime writer.
//! craft-media's ISO BMFF / QuickTime writer.
use std::io::Write;
use craft_media::isobmff::{Brand, ColorInfo, FourCc, Mp4Writer, PcmConfig, SampleEntry, TrackConfig, WriteSample, WriterOptions};
use effectcraft_project::render_queue::{AudioFormat, Channels, OutputFormat, ProResProfile};
use effectcraft_project::{Comp, ProjectSettings};
use effectcraft_time::{FrameRate, Tick};
use filmcraft_isobmff::{Brand, ColorInfo, FourCc, Mp4Writer, PcmConfig, SampleEntry, TrackConfig, WriteSample, WriterOptions};
use rayon::prelude::*;
use crate::{Cx, ExportError, Report, Result, State, batch_size, wants_audio};
@@ -117,7 +117,7 @@ pub(crate) trait VideoEncoder: Send {
// ---------------------------------------------------------------- H.264
struct H264 {
enc: filmcraft_h264enc::Encoder,
enc: craft_video::h264::Encoder,
w: u32,
h: u32,
rate: FrameRate,
@@ -129,26 +129,26 @@ struct H264 {
impl H264 {
fn new(w: u32, h: u32, rate: FrameRate, kbps: u32, codes: Codes) -> Result<H264> {
let mut cfg = filmcraft_h264enc::EncoderConfig::new(w, h, rate.num as u32, rate.den as u32);
cfg.format = filmcraft_h264enc::PacketFormat::LengthPrefixed;
let mut cfg = craft_video::h264::EncoderConfig::new(w, h, rate.num as u32, rate.den as u32);
cfg.format = craft_video::h264::PacketFormat::LengthPrefixed;
cfg.aud = false;
cfg.keyint = (rate.as_f64() * 2.0).round().max(1.0) as u32;
let kbps = kbps.max(100);
cfg.rate = filmcraft_h264enc::RateControl::Vbr { target_kbps: kbps, max_kbps: kbps * 3 / 2 };
cfg.color = filmcraft_h264enc::ColorConfig { primaries: codes.primaries, transfer: codes.transfer, matrix: codes.matrix, full_range: false };
let enc = filmcraft_h264enc::Encoder::new(cfg).map_err(enc)?;
cfg.rate = craft_video::h264::RateControl::Vbr { target_kbps: kbps, max_kbps: kbps * 3 / 2 };
cfg.color = craft_video::h264::ColorConfig { primaries: codes.primaries, transfer: codes.transfer, matrix: codes.matrix, full_range: false };
let enc = craft_video::h264::Encoder::new(cfg).map_err(enc)?;
Ok(H264 { enc, w, h, rate, codes, y: vec![], u: vec![], v: vec![] })
}
fn packets(&self, ps: Vec<filmcraft_h264enc::Packet>) -> Vec<Packet> {
fn packets(&self, ps: Vec<craft_video::h264::Packet>) -> Vec<Packet> {
ps.into_iter().map(|p| Packet { data: p.data, key: p.keyframe, cto: (p.pts - p.dts) as i32 }).collect()
}
}
impl VideoEncoder for H264 {
fn sample_entry(&self) -> SampleEntry {
let cfg = filmcraft_isobmff::AvcConfig::parse(&self.enc.avcc()).unwrap_or_else(|_| {
let cfg = craft_media::isobmff::AvcConfig::parse(&self.enc.avcc()).unwrap_or_else(|_| {
let (sps, pps) = self.enc.sps_pps();
filmcraft_isobmff::AvcConfig::new(vec![sps], vec![pps], 4)
craft_media::isobmff::AvcConfig::new(vec![sps], vec![pps], 4)
});
let mut entry = SampleEntry::avc(cfg, self.w as u16, self.h as u16);
tag_nclx_limited(&mut entry, self.codes);
@@ -170,7 +170,7 @@ impl VideoEncoder for H264 {
fn encode_yuv420(&mut self, p: &Yuv420, index: u64) -> Result<Vec<Packet>> {
let (w, cw) = (self.w as usize, (self.w as usize).div_ceil(2));
let (y, u, v) = p.slices(w, self.h as usize);
let frame = filmcraft_h264enc::YuvFrame { y, u, v, y_stride: w, uv_stride: cw };
let frame = craft_video::h264::YuvFrame { y, u, v, y_stride: w, uv_stride: cw };
let ps = self.enc.try_encode(&frame, index as i64 * self.rate.den).map_err(enc)?;
Ok(self.packets(ps))
}
@@ -188,8 +188,8 @@ pub(crate) use effectcraft_raster::yuv::rgba_to_yuv420;
// ---------------------------------------------------------------- ProRes
struct ProRes {
enc: filmcraft_prores::Encoder,
profile: filmcraft_prores::Profile,
enc: craft_video::prores::Encoder,
profile: craft_video::prores::Profile,
w: u32,
h: u32,
alpha: bool,
@@ -202,8 +202,8 @@ fn prores_colr(c: Codes) -> ColorInfo {
ColorInfo::Nclc { primaries: c.primaries.into(), transfer: c.transfer.into(), matrix: c.matrix.into() }
}
fn prores_profile(p: ProResProfile) -> filmcraft_prores::Profile {
use filmcraft_prores::Profile;
fn prores_profile(p: ProResProfile) -> craft_video::prores::Profile {
use craft_video::prores::Profile;
match p {
ProResProfile::Proxy => Profile::Proxy,
ProResProfile::Lt => Profile::Lt,
@@ -220,18 +220,18 @@ impl ProRes {
let profile = if channels == Channels::Rgba && !profile.is_4444() { ProResProfile::P4444 } else { profile };
let profile = prores_profile(profile);
let alpha = channels == Channels::Rgba;
let mut cfg = filmcraft_prores::EncoderConfig::new(profile, w, h);
let mut cfg = craft_video::prores::EncoderConfig::new(profile, w, h);
cfg.encode_alpha = alpha;
// The frame header carries the same H.273 codes as the `colr` atom, so readers that trust
// either one agree.
if let ColorInfo::Nclc { primaries, transfer, matrix } = colr {
let code = |c| u8::try_from(c).unwrap_or(2);
cfg.color = filmcraft_prores::ColorInfo { primaries: code(primaries), transfer: code(transfer), matrix: code(matrix) };
cfg.color = craft_video::prores::ColorInfo { primaries: code(primaries), transfer: code(transfer), matrix: code(matrix) };
}
ProRes { enc: filmcraft_prores::Encoder::with_config(cfg), profile, w, h, alpha, colr }
ProRes { enc: craft_video::prores::Encoder::with_config(cfg), profile, w, h, alpha, colr }
}
fn is_444(&self) -> bool {
matches!(self.profile, filmcraft_prores::Profile::P4444 | filmcraft_prores::Profile::P4444Xq)
matches!(self.profile, craft_video::prores::Profile::P4444 | craft_video::prores::Profile::P4444Xq)
}
}
@@ -244,8 +244,8 @@ impl VideoEncoder for ProRes {
entry
}
fn encode(&mut self, rgba: &[u8], _index: u64) -> Result<Vec<Packet>> {
let chroma = if self.is_444() { filmcraft_prores::ChromaFormat::Yuv444 } else { filmcraft_prores::ChromaFormat::Yuv422 };
let mut fr = filmcraft_prores::Frame::new(self.w, self.h, chroma, 10, self.alpha);
let chroma = if self.is_444() { craft_video::prores::ChromaFormat::Yuv444 } else { craft_video::prores::ChromaFormat::Yuv422 };
let mut fr = craft_video::prores::Frame::new(self.w, self.h, chroma, 10, self.alpha).map_err(enc)?;
rgba_to_yuv_10(rgba, self.w as usize, self.h as usize, self.is_444(), &mut fr.y, &mut fr.cb, &mut fr.cr);
if let Some(a) = fr.alpha.as_mut() {
for (d, s) in a.iter_mut().zip(rgba.as_chunks::<4>().0.iter()) {
@@ -291,7 +291,7 @@ fn rgba_to_yuv_10(rgba: &[u8], w: usize, h: usize, full_chroma: bool, y: &mut [u
// ---------------------------------------------------------------- audio
enum Audio {
Aac(Box<filmcraft_aac::Encoder>),
Aac(Box<craft_audio::aac::Encoder>),
Pcm,
}
@@ -401,7 +401,7 @@ pub(crate) async fn movie(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut St
// from the media duration and drop the last frame.
let frames_ts = st.total as i128 * rate.den as i128;
let seg = (frames_ts * movie_ts + rate.num as i128 / 2) / rate.num as i128;
vcfg.edits = vec![filmcraft_isobmff::Edit { segment_duration: seg as u64, media_time: start, media_rate: 0x10000 }];
vcfg.edits = vec![craft_media::isobmff::Edit { segment_duration: seg as u64, media_time: start, media_rate: 0x10000 }];
}
let vt = mux.add_track(vcfg).map_err(mux_err)?;
let sr = job.output.audio_sample_rate.clamp(8_000, 192_000);
@@ -411,7 +411,7 @@ pub(crate) async fn movie(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut St
let mut audio = None;
if with_audio {
let (a, entry, start) = if brand == Brand::Mp4 {
let e = filmcraft_aac::Encoder::new(filmcraft_aac::EncoderConfig::cbr(sr, chans as usize, 160_000 * chans)).map_err(enc)?;
let e = craft_audio::aac::Encoder::new(craft_audio::aac::EncoderConfig::cbr(sr, chans as usize, 160_000 * chans)).map_err(enc)?;
let entry = SampleEntry::aac(e.audio_specific_config(), chans, sr);
let priming = e.priming_samples() as i64;
(Audio::Aac(Box::new(e)), entry, Some(priming))
+17 -17
View File
@@ -1,10 +1,10 @@
//! HEVC (`effectcraft-hevcenc`) and AV1 (`effectcraft-av1enc`) video encoders for the MP4
//! HEVC (`craft_video::hevc`) and AV1 (`craft_video::av1`) video encoders for the MP4
//! movie writer (`hvc1` / `av01` sample entries) and AV1 in WebM, configured from the Output
//! Module's [`VideoCodecOptions`].
use craft_media::isobmff::{Av1Config, CodecConfig, FourCc, HevcConfig, SampleEntry};
use effectcraft_project::render_queue::{CodecProfile, OutputModule, RateControlMode, VideoCodecOptions};
use effectcraft_time::FrameRate;
use filmcraft_isobmff::{Av1Config, CodecConfig, FourCc, HevcConfig, SampleEntry};
use rayon::prelude::*;
use crate::encode::{Codes, Packet, VideoEncoder};
@@ -55,7 +55,7 @@ struct Planes {
// ---------------------------------------------------------------- HEVC
pub(crate) struct Hevc {
enc: effectcraft_hevcenc::Encoder,
enc: craft_video::hevc::Encoder,
w: u32,
h: u32,
bits: u8,
@@ -64,8 +64,8 @@ pub(crate) struct Hevc {
}
/// The HEVC encoder settings for an output module.
pub(crate) fn hevc_config(w: u32, h: u32, rate: FrameRate, om: &OutputModule) -> effectcraft_hevcenc::EncoderConfig {
use effectcraft_hevcenc as he;
pub(crate) fn hevc_config(w: u32, h: u32, rate: FrameRate, om: &OutputModule) -> craft_video::hevc::EncoderConfig {
use craft_video::hevc as he;
let o: &VideoCodecOptions = &om.codec;
let mut cfg = he::EncoderConfig::new(w, h, rate.num as u32, rate.den as u32);
cfg.profile = match o.profile {
@@ -86,7 +86,7 @@ impl Hevc {
let mut cfg = hevc_config(w, h, rate, om);
(cfg.colour_primaries, cfg.transfer_characteristics, cfg.matrix_coeffs) = (codes.primaries, codes.transfer, codes.matrix);
let bits = cfg.profile.bit_depth();
let enc = effectcraft_hevcenc::Encoder::new(cfg).map_err(enc_err)?;
let enc = craft_video::hevc::Encoder::new(cfg).map_err(enc_err)?;
Ok(Hevc { enc, w, h, bits, codes, planes: Planes::default() })
}
}
@@ -102,8 +102,8 @@ impl VideoEncoder for Hevc {
let (w, h) = (self.w as usize, self.h as usize);
let p = &mut self.planes;
rgba_to_yuv420_bits(rgba, w, h, self.bits, &mut p.y, &mut p.u, &mut p.v);
let frame = effectcraft_hevcenc::Frame { y: &p.y, u: &p.u, v: &p.v, y_stride: w, uv_stride: w.div_ceil(2) };
let pk = self.enc.encode(&frame);
let frame = craft_video::hevc::Frame { y: &p.y, u: &p.u, v: &p.v, y_stride: w, uv_stride: w.div_ceil(2) };
let pk = self.enc.encode(&frame).map_err(enc_err)?;
Ok(vec![Packet { data: pk.data, key: pk.keyframe, cto: 0 }])
}
fn flush(&mut self) -> Result<Vec<Packet>> {
@@ -114,7 +114,7 @@ impl VideoEncoder for Hevc {
// ---------------------------------------------------------------- AV1
pub(crate) struct Av1 {
enc: effectcraft_av1enc::Encoder,
enc: craft_video::av1::Encoder,
w: u32,
h: u32,
bits: u8,
@@ -123,8 +123,8 @@ pub(crate) struct Av1 {
}
/// The AV1 encoder settings for an output module.
pub(crate) fn av1_config(w: u32, h: u32, rate: FrameRate, om: &OutputModule) -> effectcraft_av1enc::EncoderConfig {
use effectcraft_av1enc as ae;
pub(crate) fn av1_config(w: u32, h: u32, rate: FrameRate, om: &OutputModule) -> craft_video::av1::EncoderConfig {
use craft_video::av1 as ae;
let o: &VideoCodecOptions = &om.codec;
let mut cfg = ae::EncoderConfig::new(w, h, rate.num as u32, rate.den as u32);
cfg.bit_depth = o.profile.bit_depth();
@@ -142,7 +142,7 @@ impl Av1 {
let mut cfg = av1_config(w, h, rate, om);
(cfg.color_primaries, cfg.transfer_characteristics, cfg.matrix_coefficients) = (codes.primaries, codes.transfer, codes.matrix);
let bits = cfg.bit_depth;
let enc = effectcraft_av1enc::Encoder::new(cfg).map_err(enc_err)?;
let enc = craft_video::av1::Encoder::new(cfg).map_err(enc_err)?;
Ok(Av1 { enc, w, h, bits, codes, planes: Planes::default() })
}
/// The `av1C` record (also the WebM CodecPrivate).
@@ -162,8 +162,8 @@ impl VideoEncoder for Av1 {
let (w, h) = (self.w as usize, self.h as usize);
let p = &mut self.planes;
rgba_to_yuv420_bits(rgba, w, h, self.bits, &mut p.y, &mut p.u, &mut p.v);
let frame = effectcraft_av1enc::Frame { y: &p.y, u: &p.u, v: &p.v, y_stride: w, uv_stride: w.div_ceil(2) };
let pk = self.enc.encode(&frame);
let frame = craft_video::av1::Frame { y: &p.y, u: &p.u, v: &p.v, y_stride: w, uv_stride: w.div_ceil(2) };
let pk = self.enc.encode(&frame).map_err(enc_err)?;
Ok(vec![Packet { data: pk.data, key: pk.keyframe, cto: 0 }])
}
fn flush(&mut self) -> Result<Vec<Packet>> {
@@ -196,9 +196,9 @@ mod tests {
om.keyframe_interval = 12;
let rate = FrameRate::new(30, 1);
let h = hevc_config(64, 32, rate, &om);
assert_eq!(h.profile, effectcraft_hevcenc::Profile::Main10);
assert_eq!(h.profile, craft_video::hevc::Profile::Main10);
assert_eq!(h.level_idc, Some(123));
assert_eq!(h.rate, effectcraft_hevcenc::RateControl::ConstantQp(4));
assert_eq!(h.rate, craft_video::hevc::RateControl::ConstantQp(4));
assert_eq!(h.keyint, 12);
let a = av1_config(64, 32, rate, &om);
assert_eq!((a.bit_depth, a.level_idx, a.keyint), (10, Some(9), 12));
@@ -206,6 +206,6 @@ mod tests {
om.keyframe_interval = 0;
om.bitrate_kbps = 3000;
let a = av1_config(64, 32, rate, &om);
assert_eq!((a.rate, a.keyint), (effectcraft_av1enc::RateControl::Bitrate { kbps: 3000 }, 60));
assert_eq!((a.rate, a.keyint), (craft_video::av1::RateControl::Bitrate { kbps: 3000 }, 60));
}
}
+5 -5
View File
@@ -2,16 +2,16 @@
//!
//! | Format | Container / files | Video | Alpha | Audio |
//! |---|---|---|---|---|
//! | H.264 | MP4 | FilmCraft H.264 High, 8-bit 4:2:0 BT.709 limited, VBR | no | AAC-LC (FilmCraft), mono/stereo |
//! | H.264 | MP4 | `craft_video::h264` High, 8-bit 4:2:0 BT.709 limited, VBR | no | AAC-LC (`craft_audio::aac`), mono/stereo |
//! | ProRes | QuickTime MOV | FilmCraft ProRes 422 Proxy/LT/422/HQ, 10-bit; 4444/4444 XQ 4:4:4 | 4444 (16-bit alpha coding) | PCM 16/24-bit or 32-bit float, mono/stereo |
//! | Uncompressed | QuickTime MOV (`raw `) | 8-bit RGB (depth 24, rows padded to even bytes) or ARGB (depth 32) | RGB + Alpha (straight or premultiplied) | PCM 16/24-bit or 32-bit float, mono/stereo |
//! | PNG / JPEG / TIFF sequence | one file per frame | 8-bit | PNG, TIFF | — |
//! | OpenEXR sequence | one file per frame, scan lines | 32-bit float (default) or half float, linear light, premultiplied; compression None, RLE, ZIPS, ZIP (default), PIZ, PXR24, B44, B44A, DWAA, DWAB | yes | — |
//! | Targa sequence | one file per frame | uncompressed 8-bit: 24-bit RGB, 32-bit RGB + Alpha (8 alpha bits), 8-bit grey for Alpha; top-left origin | yes (straight or premultiplied) | — |
//! | Animated GIF | GIF89a | 256-colour palette per frame (NeuQuant) | 1-bit | — |
//! | WebM | WebM (Matroska) | VP9 profile 0 (`effectcraft-vp9enc`: key + inter frames, a key frame every 2 s, loop filter), 8-bit 4:2:0; or AV1 (`effectcraft-av1enc`) | VP9 alpha (BlockAdditional) | Opus (`effectcraft-opusenc`: SILK / hybrid / CELT by bitrate and application), 48 kHz |
//! | HEVC | MP4 (`hvc1`) | `effectcraft-hevcenc` Main / Main 10 4:2:0, I + P slices, bitrate or constant quality, level, key-frame interval | no | AAC-LC (FilmCraft) |
//! | AV1 | MP4 (`av01`) | `effectcraft-av1enc` Main 8/10-bit 4:2:0, key + inter frames | no | AAC-LC (FilmCraft) |
//! | WebM | WebM (Matroska) | VP9 profile 0 (`craft_video::vp9`: key + inter frames, a key frame every 2 s, loop filter), 8-bit 4:2:0; or AV1 (`craft_video::av1`) | VP9 alpha (BlockAdditional) | Opus (`effectcraft-opusenc`: SILK / hybrid / CELT by bitrate and application), 48 kHz |
//! | HEVC | MP4 (`hvc1`) | `craft_video::hevc` Main / Main 10 4:2:0, I + P slices, bitrate or constant quality, level, key-frame interval | no | AAC-LC (`craft_audio::aac`) |
//! | AV1 | MP4 (`av01`) | `craft_video::av1` Main 8/10-bit 4:2:0, key + inter frames | no | AAC-LC (`craft_audio::aac`) |
//! | WAV / AIFF | RIFF WAVE / AIFF (AIFF-C for float) | — | — | PCM 16/24-bit or 32-bit float, mono/stereo (audio only) |
//!
//! Every frame goes through the internal `pipeline` module: the Render Settings overrides (Effects, Solo Switches,
@@ -321,7 +321,7 @@ async fn sequence(cx: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut State<'_>)
let mut i = 0;
while i < st.total {
let end = (i + batch).min(st.total);
let ks: Vec<u64> = (i..end).filter(|k| !(cx.settings.skip_existing && out::exists(cx.sink, &sequence_path(cx.path, f0 + *k as i64)))).collect();
let ks: Vec<u64> = (i..end).filter(|k| !(cx.settings.skip_existing && cx.frame_exists(&sequence_path(cx.path, f0 + *k as i64)))).collect();
let written: Vec<Result<u64>> = cx
.frames(comp, ks, |k, img| {
let path = sequence_path(cx.path, f0 + k as i64);
+14
View File
@@ -894,6 +894,20 @@ impl<'a> Cx<'a> {
}
}
/// Whether Skip Existing finds `path` already written: at its own place or, with Use Storage
/// Overflow, in any overflow folder (checked before a frame is placed, so a skipped frame
/// reserves no quota).
pub fn frame_exists(&self, path: &str) -> bool {
if out::exists(self.sink, path) {
return true;
}
if !self.job.settings.storage_overflow {
return false;
}
let Some(name) = std::path::Path::new(path).file_name() else { return false };
self.job.options.overflow.iter().any(|dir| out::exists(self.sink, &std::path::Path::new(dir).join(name).to_string_lossy()))
}
/// Where a file goes: `path`, or (Use Storage Overflow) the first overflow folder with room
/// for `bytes` when the quota hook says the output volume is full.
pub fn place(&self, path: &str, bytes: u64) -> String {
+1 -1
View File
@@ -7,7 +7,7 @@
//! A R G B / R G B order, and each row is padded to an even number of bytes (only depth 24 at odd
//! widths needs it).
use filmcraft_isobmff::{CodecConfig, FourCc, SampleEntry, VideoParams};
use craft_media::isobmff::{CodecConfig, FourCc, SampleEntry, VideoParams};
use crate::encode::{Packet, VideoEncoder};
use crate::{ExportError, Result};
+6 -6
View File
@@ -5,7 +5,7 @@
//! (size patched at the end), Info, Tracks and one Cluster per render batch. Video frames are
//! SimpleBlocks; with alpha (Channels: RGB + Alpha) each frame is a BlockGroup whose
//! BlockAdditional (BlockAddID 1) carries a second VP9 frame coding the alpha channel as luma,
//! with `AlphaMode` 1 on the track, as WebM defines. VP9 comes from `effectcraft-vp9enc` (key
//! with `AlphaMode` 1 on the track, as WebM defines. VP9 comes from `craft_video::vp9` (key
//! frames every two seconds, inter frames between them: SimpleBlocks carry the key flag, inter
//! BlockGroups a ReferenceBlock; the alpha stream's key frames line up with the colour stream's),
//! Opus from `effectcraft-opusenc` (CELT, 48 kHz stereo, 20 ms packets,
@@ -142,7 +142,7 @@ pub(crate) async fn webm(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut Sta
let colour_channels = if job.output.channels == Channels::Alpha { Channels::Alpha } else { Channels::Rgb };
let quality = job.output.quality.clamp(1, 100);
let fps = rate.as_f64().max(1.0);
let cfg = effectcraft_vp9enc::EncoderConfig {
let cfg = craft_video::vp9::EncoderConfig {
width: w,
height: h,
quality,
@@ -152,8 +152,8 @@ pub(crate) async fn webm(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut Sta
frame_rate: fps,
loop_filter: true,
};
let mut color_enc = effectcraft_vp9enc::Vp9Encoder::new(cfg.clone());
let mut alpha_enc = alpha.then(|| effectcraft_vp9enc::Vp9Encoder::new(cfg.clone()));
let mut color_enc = craft_video::vp9::Vp9Encoder::new(cfg.clone());
let mut alpha_enc = alpha.then(|| craft_video::vp9::Vp9Encoder::new(cfg.clone()));
let with_audio = wants_audio(job);
let opus_channels = if job.output.audio_channels == 1 { 1usize } else { 2 };
let mut opus = with_audio.then(|| opus_encoder(job));
@@ -266,12 +266,12 @@ pub(crate) async fn webm(job: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut Sta
for (j, px) in pixels.iter().enumerate() {
let (color, a) = rayon::join(
|| {
let (y, u, vv) = effectcraft_vp9enc::rgba_to_yuv420(px, w, h, false);
let (y, u, vv) = craft_video::vp9::rgba_to_yuv420(px, w, h, false);
color_enc.encode_frame(&y, &u, &vv, false)
},
|| {
alpha_enc.as_mut().map(|ea| {
let (y, u, vv) = effectcraft_vp9enc::alpha_to_yuv420(px, w, h);
let (y, u, vv) = craft_video::vp9::alpha_to_yuv420(px, w, h);
ea.encode_frame(&y, &u, &vv, false).data
})
},
@@ -1,13 +1,13 @@
//! Speed / efficiency measurements on ffmpeg-generated test sources (ignored by default):
//! `cargo test -p effectcraft-av1enc --test it bench:: -- --ignored --nocapture`.
//! `cargo test -p effectcraft-export --test it av1_encoder::bench:: -- --ignored --nocapture`.
use crate::common;
use super::common;
use std::process::Command;
use std::time::Instant;
use common::*;
use effectcraft_av1enc::{Encoder, EncoderConfig, RateControl};
use craft_video::av1::{Encoder, EncoderConfig, RateControl};
/// Raw 8-bit 4:2:0 frames of an ffmpeg lavfi source, or None without ffmpeg.
fn lavfi(src: &str, w: usize, h: usize, frames: usize) -> Option<Vec<Pic>> {
@@ -52,7 +52,7 @@ fn run(name: &str, pics: &[Pic], rate: RateControl, keyint: u32) {
let mut sizes = Vec::new();
for p in pics {
let t = Instant::now();
let pkt = enc.encode(&p.frame());
let pkt = enc.encode(&p.frame()).expect("encode");
let dt = t.elapsed().as_secs_f64();
if pkt.keyframe {
t_key += dt;
@@ -1,6 +1,6 @@
#![allow(dead_code)]
use effectcraft_av1enc::{Encoder, EncoderConfig, Frame, Packet};
use craft_video::av1::{Encoder, EncoderConfig, Frame, Packet};
/// A synthetic 4:2:0 picture.
pub struct Pic {
@@ -95,7 +95,7 @@ pub fn encode_and_check(cfg: EncoderConfig, pics: &[Pic]) -> Run {
let mut dec = filmcraft_av1::Decoder::with_threads(1);
let mut run = Run { packets: Vec::new(), recons: Vec::new(), psnr_y: Vec::new(), lf_levels: Vec::new() };
for (i, p) in pics.iter().enumerate() {
let pkt = enc.encode(&p.frame());
let pkt = enc.encode(&p.frame()).expect("encode");
let rec = enc.last_reconstruction().expect("reconstruction");
let out = dec.decode(&pkt.data).unwrap_or_else(|e| panic!("frame {i}: decode error {e:?}"));
assert_eq!(out.len(), 1, "frame {i}: one picture per packet");
@@ -2,12 +2,12 @@
//! bit for bit. Skipped when `ffmpeg` (with libdav1d) is not installed. ffmpeg's native `av1`
//! decoder only drives hardware decoders, so it is not used.
use crate::common;
use super::common;
use std::process::Command;
use common::*;
use effectcraft_av1enc::{Encoder, EncoderConfig, Packet, RateControl};
use craft_video::av1::{Encoder, EncoderConfig, Packet, RateControl};
fn have_libdav1d() -> bool {
let Ok(out) = Command::new("ffmpeg").args(["-hide_banner", "-decoders"]).output() else {
@@ -53,7 +53,7 @@ fn check(name: &str, cfg: EncoderConfig, pics: &[Pic]) -> Vec<u32> {
let mut recons = Vec::new();
let mut levels = Vec::new();
for p in pics {
packets.push(enc.encode(&p.frame()));
packets.push(enc.encode(&p.frame()).expect("encode"));
recons.push(enc.last_reconstruction().expect("reconstruction"));
levels.push(enc.last_loop_filter_level().expect("level"));
}
@@ -0,0 +1,6 @@
//! craft-video's AV1 encoder against the filmcraft-av1 decoder and ffmpeg's libdav1d.
mod bench;
mod common;
mod ffmpeg_oracle;
mod roundtrip;
@@ -1,10 +1,10 @@
//! Round trips through FilmCraft's spec-derived AV1 decoder: decoded frames must equal the
//! encoder's own reconstruction bit for bit.
use crate::common;
use super::common;
use common::*;
use effectcraft_av1enc::{EncoderConfig, RateControl};
use craft_video::av1::{EncoderConfig, RateControl};
fn cfg(w: u32, h: u32, bd: u8, q: u8, keyint: u32) -> EncoderConfig {
let mut c = EncoderConfig::new(w, h, 30, 1);
@@ -89,8 +89,8 @@ fn bitrate_mode_is_accurate_over_many_groups() {
let pics: Vec<Pic> = (0..n).map(|t| synth(192, 128, bd, t)).collect();
let mut c = cfg(192, 128, bd as u8, 0, keyint);
c.rate = RateControl::Bitrate { kbps };
let mut enc = effectcraft_av1enc::Encoder::new(c).unwrap();
let bits: usize = pics.iter().map(|p| enc.encode(&p.frame()).data.len() * 8).sum();
let mut enc = craft_video::av1::Encoder::new(c).unwrap();
let bits: usize = pics.iter().map(|p| enc.encode(&p.frame()).expect("encode").data.len() * 8).sum();
let got = bits as f64 / (n as f64 / 30.0) / 1000.0;
eprintln!("{bd} bit, keyint {keyint}: {got:.1} kbit/s for {kbps}");
assert!((got / kbps as f64 - 1.0).abs() < 0.05, "{got:.1} kbit/s for a {kbps} kbit/s target ({bd} bit, keyint {keyint})");
@@ -99,7 +99,7 @@ fn bitrate_mode_is_accurate_over_many_groups() {
#[test]
fn headers() {
let enc = effectcraft_av1enc::Encoder::new(cfg(1920, 1080, 10, 100, 60)).unwrap();
let enc = craft_video::av1::Encoder::new(cfg(1920, 1080, 10, 100, 60)).unwrap();
let c = enc.av1c();
assert_eq!(c[0], 0x81);
assert_eq!(c[1] & 0x1f, 8, "1080p30 is level 4.0");
@@ -1,7 +1,7 @@
//! Round trips through the filmcraft-hevc decoder and (when installed) ffmpeg: decoded pictures must
//! equal the encoder's own reconstruction bit-exactly.
use effectcraft_hevcenc::{Encoder, EncoderConfig, Frame, Profile, RateControl};
use craft_video::hevc::{Encoder, EncoderConfig, Frame, Profile, RateControl};
use std::process::Command;
struct Pic {
@@ -74,7 +74,7 @@ fn encode(cfg: EncoderConfig, pics: &[Pic]) -> Run {
let mut enc = Encoder::new(cfg).unwrap();
let mut run = Run { packets: vec![], keys: vec![], recons: vec![], hvcc: enc.hvcc(), sets: enc.parameter_sets(), psnr_y: vec![] };
for p in pics {
let pkt = enc.encode(&p.frame());
let pkt = enc.encode(&p.frame()).expect("encode");
let rec = enc.last_reconstruction().unwrap().clone();
run.psnr_y.push(psnr(&p.y, &rec[0], bd));
run.packets.push(pkt.data);
@@ -393,7 +393,7 @@ fn hvcc_layout() {
}
/// Speed / size / quality report on ffmpeg-generated 1080p test content:
/// `cargo test -p effectcraft-hevcenc --test roundtrip bench_1080p -- --ignored --nocapture`
/// `cargo test -p effectcraft-export --test it hevc_encoder::bench_1080p -- --ignored --nocapture`
/// (`HEVCENC_BENCH_SRC` selects another lavfi source).
#[test]
#[ignore]
@@ -424,7 +424,7 @@ fn bench_1080p() {
let mut enc = Encoder::new(cfg(w as u32, h as u32, qp, 30, Profile::Main)).unwrap();
for (i, p) in pics.iter().enumerate() {
let t = std::time::Instant::now();
let pkt = enc.encode(&p.frame());
let pkt = enc.encode(&p.frame()).expect("encode");
let dt = t.elapsed();
let rec = enc.last_reconstruction().unwrap();
eprintln!(
+2
View File
@@ -1,10 +1,12 @@
//! The crate's integration tests, one binary (each module is a former `tests/<name>.rs`).
mod audio_sample_positions;
mod av1_encoder;
mod banding;
mod exr_scene_linear;
mod h264_gpu_yuv;
mod hevc_av1_roundtrip;
mod hevc_encoder;
#[cfg(not(target_arch = "wasm32"))]
mod mov_audio_sample_positions;
mod movie_bytes;
+5 -1
View File
@@ -97,7 +97,11 @@ fn h264_movie_bytes_are_pinned() {
// FilmCraft 09aaf9b's encoder lists its settings in the first frame's user-data SEI (211
// bytes where 0.1.1's name took 50): 161 bytes more than the FilmCraft 2c5ba7a pin. The encoder's
// version string "0.8.0" -> "0.12.0" in that SEI adds one more byte (and one to the size fields).
assert_eq!((data.len(), fnv1a(&data)), (104_342, 17_327_612_315_319_115_693), "H.264 MP4");
// craft-video's encoder (craft-libs) is that encoder at a later FilmCraft revision than the
// d5ead4b pin: it names itself "craft-h264enc 0.1.0" in the SEI (5 bytes fewer), and with these
// settings its packets match the pin's for the first ten frames and differ after (24 bytes more
// in all, with the size fields).
assert_eq!((data.len(), fnv1a(&data)), (104_366, 4_413_091_804_733_884_658), "H.264 MP4");
}
#[test]
+2 -2
View File
@@ -6,13 +6,13 @@
use std::path::Path;
use std::process::Command;
use craft_media::isobmff::{ColorInfo, TrackKind};
use effectcraft_color::Label;
use effectcraft_export::render_queue::{OutputFormat, OutputModule, RenderSettings, TimeSpan};
use effectcraft_export::{Job, export};
use effectcraft_project::{ColorSpace, Comp, ItemKind, LayerSource, Project, Solid, build};
use effectcraft_render::NoFootage;
use effectcraft_time::{FrameRate, Tick};
use filmcraft_isobmff::{ColorInfo, TrackKind};
/// (name, Output color space, H.273 primaries / transfer / matrix, the same as ffprobe names them)
const ROWS: &[(&str, Option<ColorSpace>, [u16; 3], [&str; 3])] = &[
@@ -81,7 +81,7 @@ fn mp4_tags_describe_the_frames() {
render(output, format, &path);
let bytes = std::fs::read(&path).expect("read movie");
let mp4 = filmcraft_isobmff::open(bytes.as_slice()).expect("demux");
let mp4 = craft_media::isobmff::open(bytes.as_slice()).expect("demux");
let track = mp4.tracks.iter().find(|t| t.kind == TrackKind::Video).expect("video track");
let colr = track.entries[0].video.as_ref().and_then(|v| v.color.clone());
assert_eq!(colr, Some(ColorInfo::Nclx { primaries, transfer, matrix, full_range: false }), "{codec} {name}: colr");
+5 -5
View File
@@ -9,6 +9,7 @@
use std::path::{Path, PathBuf};
use std::sync::Arc;
use craft_media::isobmff::{AvcConfig, Brand, Mp4Writer, SampleEntry, TrackConfig, WriteSample, WriterOptions};
use effectcraft_color::Label;
use effectcraft_export::render_queue::{OutputFormat, OutputModule, RenderSettings, TimeSpan};
use effectcraft_export::{Job, export};
@@ -16,7 +17,6 @@ use effectcraft_media::MediaPool;
use effectcraft_project::{Comp, Footage, ItemKind, LayerSource, Project, build};
use effectcraft_raster::Image;
use effectcraft_time::{FrameRate, Tick};
use filmcraft_isobmff::{AvcConfig, Brand, Mp4Writer, SampleEntry, TrackConfig, WriteSample, WriterOptions};
const W: u32 = 128;
const H: u32 = 32;
@@ -38,18 +38,18 @@ fn ms_rounded(rate: FrameRate, n: i64) -> Vec<u32> {
/// An H.264 MP4 (video track timescale 1000) with one frame per entry of `durations` (ms);
/// frame k shows k in binary.
fn write_movie(path: &Path, durations: &[u32]) {
let mut cfg = filmcraft_h264enc::EncoderConfig::new(W, H, 30, 1);
cfg.format = filmcraft_h264enc::PacketFormat::LengthPrefixed;
let mut cfg = craft_video::h264::EncoderConfig::new(W, H, 30, 1);
cfg.format = craft_video::h264::PacketFormat::LengthPrefixed;
cfg.aud = false;
cfg.bframes = 0;
cfg.keyint = 30;
cfg.scenecut = false;
let mut enc = filmcraft_h264enc::Encoder::new(cfg).expect("encoder");
let mut enc = craft_video::h264::Encoder::new(cfg).expect("encoder");
let (u, v) = (vec![128u8; (W * H / 4) as usize], vec![128u8; (W * H / 4) as usize]);
let mut packets = Vec::new();
for k in 0..durations.len() {
let y: Vec<u8> = (0..W * H).map(|i| if (k >> (i % W * BARS / W)) & 1 == 1 { 235 } else { 16 }).collect();
let frame = filmcraft_h264enc::YuvFrame { y: &y, u: &u, v: &v, y_stride: W as usize, uv_stride: W as usize / 2 };
let frame = craft_video::h264::YuvFrame { y: &y, u: &u, v: &v, y_stride: W as usize, uv_stride: W as usize / 2 };
packets.extend(enc.try_encode(&frame, k as i64).expect("encode"));
}
packets.extend(enc.flush());
+2 -2
View File
@@ -20,9 +20,9 @@ fn encode(pcm: &[f32], channels: u8, bitrate: u32) -> (OpusEncoder, Vec<Vec<u8>>
(enc, packets)
}
/// Decodes with filmcraft-opus, drops the pre-skip and returns planar channels of `len` samples.
/// Decodes with craft-audio, drops the pre-skip and returns planar channels of `len` samples.
fn decode(head: &[u8], packets: &[Vec<u8>], len: usize) -> Vec<Vec<f32>> {
let mut dec = filmcraft_opus::Decoder::new(head).expect("OpusHead");
let mut dec = craft_audio::opus::Decoder::new(head).expect("OpusHead");
dec.set_trim_pre_skip(true);
let mut out: Vec<Vec<f32>> = vec![Vec::new(); dec.channels()];
for p in packets {
+2 -2
View File
@@ -5,6 +5,7 @@
use std::path::Path;
use std::process::Command;
use craft_media::isobmff::{ColorInfo, TrackKind};
use effectcraft_color::Label;
use effectcraft_export::render_queue::{Channels, OutputFormat, OutputModule, RenderSettings, TimeSpan, sequence_path};
use effectcraft_export::{Job, export};
@@ -12,7 +13,6 @@ use effectcraft_media::MediaPool;
use effectcraft_project::{ColorSpace, Comp, ItemKind, LayerSource, Project, Solid, build};
use effectcraft_render::{FootageSource, NoFootage};
use effectcraft_time::{FrameRate, Tick};
use filmcraft_isobmff::{ColorInfo, TrackKind};
struct Row {
name: &'static str,
@@ -114,7 +114,7 @@ fn prores_colr_describes_the_frames() {
render(row, &path);
let bytes = std::fs::read(&path).expect("read movie");
let mov = filmcraft_isobmff::open(bytes.as_slice()).expect("demux");
let mov = craft_media::isobmff::open(bytes.as_slice()).expect("demux");
let track = mov.tracks.iter().find(|t| t.kind == TrackKind::Video).expect("video track");
let [primaries, transfer, matrix] = row.codes;
let colr = track.entries[0].video.as_ref().and_then(|v| v.color.clone());
+48
View File
@@ -444,6 +444,54 @@ fn cancelled_export_removes_only_files_it_opened() {
std::fs::remove_dir_all(dir).unwrap();
}
/// Skip Existing keeps a frame that is already in the overflow folder the frame is placed in
/// (it checked only the primary destination, then truncated the overflow file).
#[test]
fn skip_existing_keeps_a_frame_in_the_overflow_folder() {
use std::path::PathBuf;
// Room only in the second overflow folder; the frame already sits in the first (which is full).
struct Overflow(PathBuf);
impl StorageQuota for Overflow {
fn has_room(&self, path: &str, _: u64) -> bool {
std::path::Path::new(path).starts_with(&self.0)
}
}
let guard = tempfile::tempdir().unwrap();
let (dir, full, over) = (guard.path().to_path_buf(), guard.path().join("full"), guard.path().join("over"));
std::fs::create_dir_all(&full).unwrap();
std::fs::create_dir_all(&over).unwrap();
std::fs::write(full.join("clip_00000.png"), b"keep").unwrap();
let quota = Overflow(over.clone());
let (p, cid) = project(FrameRate::new(25, 1), |_, _| {});
let settings = RenderSettings { skip_existing: true, storage_overflow: true, ..Default::default() };
let om = OutputModule::for_format(OutputFormat::PngSequence);
let path = dir.join("clip_[#####].png");
let result = export(
&Job {
project: &p,
footage: &NoFootage,
expr: None,
accel: None,
comp: cid,
settings: &settings,
output: &om,
path: path.to_str().unwrap(),
sink: None,
nested_switches: true,
options: JobOptions {
storage: Some(&quota),
overflow: vec![full.to_string_lossy().into_owned(), over.to_string_lossy().into_owned()],
..Default::default()
},
},
&mut |_| true,
);
assert!(result.is_ok(), "{result:?}");
assert_eq!(std::fs::read(full.join("clip_00000.png")).unwrap(), b"keep");
assert!(!over.join("clip_00000.png").exists(), "no duplicate in another overflow folder");
assert!(over.join("clip_00001.png").exists(), "the other frames are still written");
}
/// A GPU compositor stand-in that renders every frame solid green (the CPU draws the bar and the
/// block on black) and keeps Auto's timing history.
#[derive(Default)]
+4 -4
View File
@@ -288,15 +288,15 @@ fn prores_alpha_final_run_is_present_in_exported_movies() {
run_frames(&project, comp, &MediaPool::new(), &output, &path, 1);
let bytes = std::fs::read(&path).expect("exported MOV");
let movie = filmcraft_isobmff::open(bytes.as_slice()).expect("demux exported MOV");
let video = movie.tracks.iter().find(|track| track.kind == filmcraft_isobmff::TrackKind::Video).expect("video track");
let movie = craft_media::isobmff::open(bytes.as_slice()).expect("demux exported MOV");
let video = movie.tracks.iter().find(|track| track.kind == craft_media::isobmff::TrackKind::Video).expect("video track");
assert_eq!(video.samples.len(), 1);
let sample = &video.samples[0];
let frame = &bytes[sample.offset as usize..][..sample.size as usize];
let (header, start, size) = filmcraft_prores::FrameHeader::parse(frame).expect("ProRes header");
let (header, start, size) = craft_video::prores::FrameHeader::parse(frame).expect("ProRes header");
assert_eq!((header.width, header.height), (16, 16));
let picture = &frame[start..size];
let header = filmcraft_prores::PictureHeader::parse(picture).expect("picture header");
let header = craft_video::prores::PictureHeader::parse(picture).expect("picture header");
assert_eq!(header.num_slices, 1);
let slice = &picture[header.header_size + 2..];
let color_bytes: usize = slice[2..8].as_chunks::<2>().0.iter().map(|b| u16::from_be_bytes(*b) as usize).sum();
+3 -3
View File
@@ -8,6 +8,7 @@
use std::path::{Path, PathBuf};
use std::process::Command;
use craft_media::isobmff::TrackKind;
use effectcraft_color::Label;
use effectcraft_export::render_queue::{AudioFormat, AudioOutput, Channels, OutputFormat, OutputModule, RenderSettings, TimeSpan, sequence_path};
use effectcraft_export::{Job, export};
@@ -15,7 +16,6 @@ use effectcraft_media::MediaPool;
use effectcraft_project::{Comp, ItemId, ItemKind, LayerSource, Project, Solid, build};
use effectcraft_render::FootageSource;
use effectcraft_time::{FrameRate, Tick};
use filmcraft_isobmff::TrackKind;
const W: u32 = 33;
const H: u32 = 20;
@@ -103,7 +103,7 @@ fn reference_frames(p: &Project, cid: ItemId, footage: &dyn FootageSource, om: &
/// The frames as stored in the movie, unpacked to RGBA (rows padded to even bytes).
fn stored_frames(path: &Path, alpha: bool) -> Vec<Vec<u8>> {
let bytes = std::fs::read(path).expect("read movie");
let mov = filmcraft_isobmff::open(bytes.as_slice()).expect("demux");
let mov = craft_media::isobmff::open(bytes.as_slice()).expect("demux");
assert!(mov.is_quicktime);
let t = mov.tracks.iter().find(|t| t.kind == TrackKind::Video).expect("video track");
let e = &t.entries[0];
@@ -204,7 +204,7 @@ fn uncompressed_with_pcm_audio() {
let path = d.join("comp.mov");
assert!(run(&p, cid, &pool, &om, &path).audio);
let bytes = std::fs::read(&path).expect("read");
let mov = filmcraft_isobmff::open(bytes.as_slice()).expect("demux");
let mov = craft_media::isobmff::open(bytes.as_slice()).expect("demux");
let a = mov.tracks.iter().find(|t| t.kind == TrackKind::Audio).expect("audio track");
assert_eq!(a.timescale, 48_000);
// 0.6 s of audio at 48 kHz.
+2 -2
View File
@@ -1,7 +1,7 @@
//! The VP9 intra encoder (`effectcraft-vp9enc`) round-trips through FilmCraft's VP9 decoder (and
//! The VP9 intra encoder (`craft_video::vp9`) round-trips through FilmCraft's VP9 decoder (and
//! ffmpeg as an external oracle when installed): sizes, lossless exactness, PSNR.
use effectcraft_vp9enc::{EncoderConfig, Vp9Encoder};
use craft_video::vp9::{EncoderConfig, Vp9Encoder};
use filmcraft_vp9::{Decoder, Plane};
fn plane_u8(p: &Plane) -> Vec<u8> {
+53 -11
View File
@@ -9,7 +9,8 @@
use effectcraft_geom::{Mat3, Mat4};
use effectcraft_keyframe::Value;
use effectcraft_project::{Comp, ItemId, ItemKind, Layer, LayerId, LayerSource, Node, PropGroup, Property};
use effectcraft_project::ae_order::{self, AeChild};
use effectcraft_project::{Comp, GroupKind, ItemId, ItemKind, Layer, LayerId, LayerSource, Node, PropGroup, Property};
use effectcraft_render::EvalCtx;
use effectcraft_time::Tick;
@@ -272,6 +273,19 @@ fn node_resp(path: String, n: &Node, index: usize) -> Resp {
])
}
/// A top-level slot the layer has no node for, as group data: `@marker` (the markers, built by the
/// prelude) or `@absent` (an empty group, as After Effects shows an unused slot).
fn slot_resp(path: &str, s: &ae_order::AeSlot, index: usize) -> Resp {
Resp::List(vec![
Resp::Str(path.into()),
Resp::Bool(true),
Resp::Str(s.name.into()),
Resp::Str(s.match_name.into()),
Resp::Num(0.0),
Resp::Num(index as f64),
])
}
fn find_child<'g>(g: &'g PropGroup, key: &Key) -> Option<&'g Node> {
match key {
Key::Index(i) => usize::try_from(*i).ok().filter(|i| *i >= 1).and_then(|i| g.children.get(i - 1)),
@@ -283,6 +297,9 @@ fn find_child<'g>(g: &'g PropGroup, key: &Key) -> Option<&'g Node> {
.find(|n| n.match_id() == m)
.or_else(|| g.children.iter().find(|n| n.name().eq_ignore_ascii_case(name)))
.or_else(|| g.children.iter().find(|n| compact(n.name()) == c || compact(n.match_id()) == c))
// An effect by its After Effects match name, an imported placeholder's effect id
// (`effect("Pseudo/0.25")`; its match id is one path segment, `Pseudo_0_25`).
.or_else(|| g.children.iter().find(|n| matches!(n.as_group().map(|g| &g.kind), Some(GroupKind::Effect { effect }) if effect == name)))
}
}
}
@@ -348,7 +365,36 @@ impl<'a> Resolver<'a> {
let uid = segs.get(keep - 1)?.strip_prefix('@')?.parse::<u64>().ok()?;
let index = parent.children.iter().position(|c| c.uid() == uid)?;
let n = parent.children.get(index)?;
Some(node_resp(group_path, n, index + 1))
// A top-level group's number is After Effects' (see `ae_order`).
let number = if keep == 1 { ae_order::ae_index(l, n.match_id()) } else { None }.unwrap_or(index + 1);
Some(node_resp(group_path, n, number))
}
/// A child of a layer (`group` empty) or of one of its groups, by name or 1-based number.
fn child(&self, comp: u64, layer: u64, group: &str, key: &Key) -> Option<Resp> {
let l = self.layer(comp, layer)?;
// A layer's numbers are After Effects' (Marker is 1, unused groups keep their slot), and so
// are its match names (`thisLayer("ADBE Effect Parade")`, as scripts such as Karton write).
let slot = match key {
Key::Index(i) => usize::try_from(*i).ok(),
Key::Name(name) => ae_order::ae_index_of_match_name(l, name),
};
if group.is_empty()
&& ae_order::ae_slots(&l.source).is_some()
&& let Some(i) = slot
{
return Some(match ae_order::ae_child(l, i)? {
AeChild::Node(n) => node_resp(format!("@{}", n.uid()), n, i),
AeChild::Marker => slot_resp("@marker", &ae_order::MARKER, 1),
AeChild::Absent(s) => slot_resp("@absent", s, i),
});
}
let g = if group.is_empty() { &l.props } else { l.props.group(group)? };
let n = find_child(g, key)?;
let index = if group.is_empty() { ae_order::ae_index(l, n.match_id()) } else { None }
.unwrap_or_else(|| g.children.iter().position(|c| c.uid() == n.uid()).unwrap_or(0) + 1);
let path = if group.is_empty() { format!("@{}", n.uid()) } else { format!("{group}/@{}", n.uid()) };
Some(node_resp(path, n, index))
}
fn try_resolve(&self, req: &Req) -> Option<Resp> {
@@ -403,14 +449,7 @@ impl<'a> Resolver<'a> {
Resp::Bool(l.switches.video),
])
}
Req::Child { comp, layer, group, key } => {
let l = self.layer(*comp, *layer)?;
let g = if group.is_empty() { &l.props } else { l.props.group(group)? };
let n = find_child(g, key)?;
let index = g.children.iter().position(|c| c.uid() == n.uid()).unwrap_or(0) + 1;
let path = if group.is_empty() { format!("@{}", n.uid()) } else { format!("{group}/@{}", n.uid()) };
node_resp(path, n, index)
}
Req::Child { comp, layer, group, key } => return self.child(*comp, *layer, group, key),
Req::Ancestor { comp, layer, path, up } => return self.ancestor(*comp, *layer, path, *up),
Req::PropInfo { comp, layer, path } => {
let (l, p) = self.prop(*comp, *layer, path)?;
@@ -423,7 +462,10 @@ impl<'a> Resolver<'a> {
Some(g) => l.props.group(g)?,
None => &l.props,
};
g.children.iter().position(|n| format!("@{}", n.uid()) == last).map(|i| i + 1)
let i = g.children.iter().position(|n| format!("@{}", n.uid()) == last)?;
// A top-level property (an enabled Time Remap) has After Effects' number.
let top = if parent.is_none() { g.children.get(i).and_then(|n| ae_order::ae_index(l, n.match_id())) } else { None };
Some(top.unwrap_or(i + 1))
});
Resp::List(vec![
Resp::Str(p.name.clone()),
+2
View File
@@ -495,6 +495,8 @@ function __mod(a, d) { return ((a % d) + d) % d; }
function __child(c, l, group, key) {
var info = __h(__CHILD, c, l, group, key);
if (info === null) return undefined;
// `thisLayer(1)` is the layer's markers, as in After Effects (see `ae_order`).
if (group === '' && info[0] === '@marker') return new Markers(c, l);
return info[1] ? __mkGroup(c, l, info) : __mkProp(c, l, info[0]);
}
+23
View File
@@ -1376,6 +1376,28 @@ fn checkbox_and_dropdown_results() {
assert_close!(f.ev(f.b, ROT, "effect('Dropdown Menu Control')('Menu') * 10", 0.0).unwrap().as_f64(), 10.0);
}
/// An effect EffectCraft does not have (an imported After Effects placeholder, #3087) is read by
/// name like any other: its parameters by their names, a popup 1-based. It is also found by its
/// After Effects match name, its effect id (the group's match id is one path segment).
#[test]
fn an_unknown_effects_parameters_are_read_by_name() {
let mut f = fx();
let g = group_push(&mut f.p, |ids| {
let mut g = ids.group("Pseudo_0_25", "Settings");
g.kind = effectcraft_project::GroupKind::Effect { effect: "Pseudo/0.25".into() };
g.children.push(ids.prop("param1", "Speed", Value::Scalar(3.0)).into());
g.children.push(ids.prop("param2", "Mode", Value::Enum(1)).into());
g
});
f.layer_mut(f.b).props.sub_mut("effects").unwrap().children.push(g.into());
assert_close!(f.ev(f.b, ROT, "effect('Settings')('Speed') * 2", 0.0).unwrap().as_f64(), 6.0);
assert_close!(f.ev(f.b, ROT, "effect('Settings')('Mode') * 10", 0.0).unwrap().as_f64(), 20.0);
assert_close!(f.ev(f.b, ROT, "effect('Settings')(1)", 0.0).unwrap().as_f64(), 3.0);
assert_close!(f.ev(f.b, ROT, "effect('Pseudo/0.25')('Speed')", 0.0).unwrap().as_f64(), 3.0);
assert_close!(f.ev(f.b, ROT, "thisLayer('Effects')('Pseudo/0.25')('Speed')", 0.0).unwrap().as_f64(), 3.0);
assert_close!(f.ev(f.b, ROT, "thisLayer('ADBE Effect Parade')('Pseudo/0.25')('Speed')", 0.0).unwrap().as_f64(), 3.0);
}
#[test]
fn syntax_error_reports_line() {
let f = fx();
@@ -2025,6 +2047,7 @@ fn an_expression_cant_change_the_prelude_for_the_next() {
}
}
mod ae_layer_order;
mod property_group;
/// Timing harness for the prelude's cost on the evaluation path. Ignored: it is a measurement, not
+98
View File
@@ -0,0 +1,98 @@
//! A layer's top-level numbers are After Effects' (`project::ae_order`): Marker is 1, and slots the
//! layer does not use (Time Remap, Motion Trackers, Layer Styles…) keep their place. Rigs that read
//! a palette by number, such as `comp("Palette").layer(1)(4)(n)(1)` on a shape layer, failed
//! silently before: `(4)` reached Transform, the expression's `try` fell back to the stored value and
//! every linked colour rendered near-black.
use super::*;
use effectcraft_project::Property;
/// The fixture with a Slider Control (value 7) on layer "Shape".
fn with_shape_slider() -> Fx {
let mut f = fx();
let spec = effectcraft_effects::find("ec.control.slider").unwrap();
let mut slider = group_push(&mut f.p, |ids| effectcraft_effects::instantiate(spec, ids, "Swatch 1", [20.0, 20.0]));
slider.prop_mut("slider").unwrap().value = Value::Scalar(7.0);
f.layer_mut(f.shape).props.sub_mut("effects").unwrap().children.push(slider.into());
f
}
fn yes(f: &Fx, cond: &str) -> f64 {
f.num(&format!("({cond}) ? 1 : 0"), 0.0)
}
#[test]
fn effects_by_number_on_a_shape_layer_is_four() {
let f = with_shape_slider();
// The Ray Dynamic Color lookup: layer(1)(4)(swatch)(1).
assert_close!(f.num("thisComp.layer('Shape')(4)(1)(1)", 0.0), 7.0);
assert_close!(f.num("try { thisComp.layer('Shape')(4)(1)(1) } catch (e) { -1 }", 0.0), 7.0);
}
#[test]
fn effects_by_number_on_a_solid_is_five() {
let f = fx();
assert_close!(f.num("thisComp.layer('A')(5)(1)(1)", 0.0), 42.0);
assert_close!(f.num("thisComp.layer('A')(5)('Slider Control')('Slider')", 0.0), 42.0);
}
#[test]
fn top_level_names_follow_after_effects() {
let f = fx();
assert_close!(yes(&f, "thisComp.layer('A')(4).name == 'Masks'"), 1.0);
assert_close!(yes(&f, "thisComp.layer('A')(5).name == 'Effects'"), 1.0);
assert_close!(yes(&f, "thisComp.layer('A')(6).name == 'Transform'"), 1.0);
assert_close!(yes(&f, "thisComp.layer('Shape')(2).name == 'Contents'"), 1.0);
assert_close!(yes(&f, "thisComp.layer('Shape')(5).name == 'Transform'"), 1.0);
assert_close!(yes(&f, "thisComp.layer('Title')(2).name == 'Text'"), 1.0);
assert_close!(yes(&f, "thisComp.layer('Title')(4).name == 'Effects'"), 1.0);
assert_close!(f.num("thisComp.layer('A')(6)('Position')[0]", 0.0), 50.0);
}
#[test]
fn one_is_the_markers() {
let f = fx();
assert_close!(f.num("thisComp.layer('A')(1).numKeys", 0.0), 2.0);
assert_close!(f.num("thisComp.layer('A')(1).key(2).time", 0.0), 4.0);
}
#[test]
fn an_unused_slot_is_an_empty_group() {
let f = fx();
// Layer Styles (7) and Data (12) exist in After Effects before they are used.
assert_close!(yes(&f, "thisComp.layer('A')(7).name == 'Layer Styles'"), 1.0);
assert_close!(f.num("thisComp.layer('A')(12).numProperties", 0.0), 0.0);
assert_close!(f.num("try { thisComp.layer('A')(12)(1); 1 } catch (e) { -1 }", 0.0), -1.0);
// Past the last slot there is nothing.
assert_close!(f.num("try { thisComp.layer('A')(16); 1 } catch (e) { -1 }", 0.0), -1.0);
}
#[test]
fn property_index_of_a_top_level_group_is_after_effects() {
let f = fx();
assert_close!(f.num("thisComp.layer('A').effect('Slider Control').propertyGroup(1).propertyIndex", 0.0), 5.0);
assert_close!(f.num("thisComp.layer('A')('Transform').propertyIndex", 0.0), 6.0);
assert_close!(f.num("thisComp.layer('Shape')('Contents').propertyIndex", 0.0), 2.0);
}
#[test]
fn top_level_groups_by_after_effects_match_name() {
// Karton's expressions: thisLayer("ADBE Effect Parade")("…").
let f = with_shape_slider();
assert_close!(f.num("thisComp.layer('A')('ADBE Effect Parade')('Slider Control')('Slider')", 0.0), 42.0);
assert_close!(f.num("thisComp.layer('Shape')('ADBE Effect Parade')(1)(1)", 0.0), 7.0);
assert_close!(f.num("thisComp.layer('A')('ADBE Transform Group')('Position')[0]", 0.0), 50.0);
assert_close!(f.num("thisComp.layer('A')('ADBE Marker').numKeys", 0.0), 2.0);
assert_close!(f.num("thisComp.layer('A')('ADBE Effect Parade').propertyIndex", 0.0), 5.0);
}
#[test]
fn an_enabled_time_remap_is_number_two() {
// Enabled Time Remap is a property at the top of the tree; After Effects numbers it 2.
let mut f = fx();
let uid = f.p.next_id;
f.p.next_id += 1;
f.layer_mut(f.a).props.children.insert(0, Property::new(uid, "timeRemap", "Time Remap", Value::Scalar(0.0)).into());
assert_close!(f.num("thisComp.layer('A')('Time Remap').propertyIndex", 0.0), 2.0);
assert_close!(f.num("thisComp.layer('A')(2).propertyIndex", 0.0), 2.0);
}
-15
View File
@@ -1,15 +0,0 @@
[package]
name = "effectcraft-hevcenc"
description = "Clean-room pure-Rust HEVC (H.265) encoder (Main / Main 10, I and P slices, CABAC) for MP4 export, from ITU-T H.265"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
[lints]
workspace = true
[dependencies]
[dev-dependencies]
filmcraft-hevc = { workspace = true }
-88
View File
@@ -1,88 +0,0 @@
# effectcraft-hevcenc
Clean-room, pure-Rust HEVC / H.265 encoder for EffectCraft's MP4 export (layer L0, `std` only,
no `unsafe`, builds for `wasm32-unknown-unknown`).
## What it produces
- **Profiles:** Main (8-bit) and Main 10 (10-bit), 4:2:0, Main tier. `general_level_idc` is taken
from the config or chosen as the lowest level whose MaxLumaPs, MaxLumaSr (and, in bitrate mode,
MaxBR) fit (Table A.8).
- **Parameter sets:** VPS, SPS (with VUI: BT.709 colour description, `video_full_range_flag`,
timing info from the frame rate) and PPS, as raw NAL units (`Encoder::parameter_sets`) and as an
`hvcC` record (ISO/IEC 14496-15 §8.3.3.1, `lengthSizeMinusOne` 3, complete VPS / SPS / PPS
arrays, `Encoder::hvcc`).
- **Pictures:** one slice per picture; `IDR_N_LP` every `keyint` pictures (`1` = all intra, `0` =
only the first), `TRAIL_R` P pictures otherwise, each referencing the previous picture (one
short-term RPS in the SPS, `num_ref_idx_l0_active` 1, no reordering, pts = dts). Packets are
length-prefixed (4-byte big-endian) NAL units without parameter sets.
- **Picture size:** any even width / height; the coded size is padded to a multiple of 8 by edge
replication and cropped with the conformance window. Odd sizes are rejected with
`Error::InvalidConfig` (4:2:0 conformance-window offsets are in units of two luma samples).
## Coding tools
- 64x64 CTUs, coding units 64x64 .. 8x8 chosen by rate-distortion optimisation: every candidate is
actually predicted, transformed, quantised and reconstructed, and its rate is measured with a
CABAC bit estimator that evolves the same context states as the real coder. Split decisions
compare the best unsplit candidate with the recursively coded children (early exit after a skip).
- **Intra:** all 35 modes (SATD search on a coarse grid plus refinement and the MPMs), 2Nx2N at
8..32 and NxN (four 4x4 PUs) at 8x8, chroma in DM mode, MPM / remaining-mode coding, reference
substitution, [1 2 1] and strong (32x32) smoothing, DC / angular boundary filters.
- **Inter (P):** skip and merge (spatial candidates + zero candidates, `MaxNumMergeCand` 5) and AMVP
with mvd coding; integer motion search (predictor starts + square pattern, steps 16..1) and
half / quarter-sample refinement on pre-interpolated half-sample planes; the coded prediction uses
the normative 8-tap / 4-tap interpolation filters and reference-picture edge clamping.
- **Transforms:** DST-VII 4x4 (intra luma) and DCT 4..32 (inverse by even/odd decomposition,
bit-identical to the matrix form), dead-zone quantisation (1/3 intra, 1/6 inter), flat scaling,
sign data hiding, inferred transform splits only (`max_transform_hierarchy_depth_*` 0, so 64x64
CUs use four 32x32 TUs).
- **Entropy coding:** CABAC (context initialisation by slice QP and init type, decision / bypass /
terminate bins, flush), `end_of_slice_segment_flag`, byte alignment, emulation prevention.
- **In-loop filters:** the deblocking filter is on (the encoder deblocks its own reconstruction, so
references match the decoder); SAO is disabled.
- **Rate control:** `ConstantQp(qp)` or `Bitrate { kbps }`, a per-picture QP from a bits-x-Qstep
model per picture type (I pictures get roughly 4x the bits of a P picture) with a buffer that
spreads over- and undershoot over the following pictures.
Not implemented: B pictures / reordering, multiple references, TMVP, AMP and other inter partition
shapes, residual quadtree splits, transform skip, scaling lists, PCM, SAO, RDOQ, cu_qp_delta /
adaptive quantisation, tiles / WPP / multiple slices, range extensions (4:2:2, 4:4:4, > 10 bits).
## Measurements
On a shared, heavily loaded machine, opt-level 3: about 0.45 s of CPU per 1920x1080 picture
(ffmpeg `testsrc2`, QP 22 / 32). On ffmpeg's `mandelbrot` 1080p source (8 pictures, IPPP, QP 32)
the stream is about 12 % larger at about 0.2 dB lower mean PSNR-Y than x265 `--preset medium` at
the same QP without psy tuning (110.5 kB / 42.3 dB vs 98.3 kB / 42.5 dB). The synthetic test image
reaches 45.8 dB PSNR-Y at QP 22.
## Tests
`cargo test -p effectcraft-hevcenc`:
- every stream is decoded with the first-party `filmcraft-hevc` decoder and compared bit-exactly
with the encoder's reconstruction (`Encoder::last_reconstruction`, hidden API);
- when `ffmpeg` is on `PATH`, the Annex-B elementary stream is decoded with
`ffmpeg -v error -xerror` (no stderr output allowed) and compared bit-exactly as well (skipped
otherwise). ffmpeg is used only as an external test oracle;
- covered: 8-bit and 10-bit, all-intra and IP, QP 0 noise (escape codes), QP 0..51, strong
deblocking at high QP, sizes 8x8 .. 200x136 with cropping, POC wrap (300 pictures without IDR),
bitrate mode within 2x of the target, `hvcC` layout;
- `bench_1080p` (ignored) reports speed, size and PSNR on 1080p content generated by ffmpeg.
## Specifications
- ITU-T H.265 (V8, 08/2021) | ISO/IEC 23008-2, *High efficiency video coding*: 7 (syntax and
semantics), 8.4 - 8.7 (intra / inter prediction, scaling and transforms, deblocking), 9.3 (CABAC,
including the informative encoder description of 9.3.4), Annex A (profiles, tiers and levels),
Annex E (VUI).
- ISO/IEC 14496-15 (2019), §8.3.3.1 HEVCDecoderConfigurationRecord.
Implemented from the specification text. Constant tables (CABAC context layout and initValues,
rangeTabLPS / transIdx, scan orders, the DCT / DST matrices, intra angles, interpolation filters,
the chroma QP table, the deblocking beta / tC tables) and the decoder-side reconstruction
arithmetic (intra reference substitution / filtering / prediction, fractional interpolation,
deblocking) are mirrored from FilmCraft's first-party, spec-derived `filmcraft-hevc` decoder (same
organisation, MIT OR Apache-2.0), so that encoder and decoder reconstruct identically. No
third-party encoder or decoder source (x265, libde265, ffmpeg, HM, ...) was consulted.
-135
View File
@@ -1,135 +0,0 @@
//! RBSP bit writer (7.2, 9.2 Exp-Golomb) and NAL unit encapsulation with emulation prevention (7.3.1).
/// MSB-first bit writer.
#[derive(Default)]
pub struct BitWriter {
buf: Vec<u8>,
acc: u64,
nbits: u32,
}
impl BitWriter {
pub fn new() -> Self {
Self::default()
}
/// Write the `n` (<= 32) low bits of `v`.
#[inline]
pub fn put(&mut self, v: u32, n: u32) {
debug_assert!(n <= 32);
if n == 0 {
return;
}
let v = (v as u64) & ((1u64 << n) - 1);
self.acc = (self.acc << n) | v;
self.nbits += n;
while self.nbits >= 8 {
self.nbits -= 8;
self.buf.push((self.acc >> self.nbits) as u8);
}
self.acc &= (1u64 << self.nbits) - 1;
}
#[inline]
pub fn bit(&mut self, b: u32) {
self.put(b & 1, 1);
}
pub fn flag(&mut self, b: bool) {
self.put(b as u32, 1);
}
/// ue(v).
pub fn ue(&mut self, v: u32) {
let x = v as u64 + 1;
let len = 64 - x.leading_zeros(); // bits of x
// len - 1 leading zeros, then x in len bits
self.put(0, len - 1);
if len > 32 {
self.put((x >> 32) as u32, len - 32);
self.put(x as u32, 32);
} else {
self.put(x as u32, len);
}
}
/// se(v).
pub fn se(&mut self, v: i32) {
let k = if v > 0 { 2 * v as u32 - 1 } else { (-(v as i64) as u32) * 2 };
self.ue(k);
}
pub fn is_aligned(&self) -> bool {
self.nbits == 0
}
/// rbsp_trailing_bits(): stop bit and zero alignment.
pub fn trailing(&mut self) {
self.bit(1);
self.align_zero();
}
pub fn align_zero(&mut self) {
if self.nbits > 0 {
self.put(0, 8 - self.nbits);
}
}
pub fn into_bytes(mut self) -> Vec<u8> {
self.align_zero();
self.buf
}
}
/// Build a NAL unit (2-byte header, `nuh_layer_id` 0, `TemporalId` 0) from an RBSP, inserting
/// emulation prevention bytes.
pub fn nal_unit(nal_type: u8, rbsp: &[u8]) -> Vec<u8> {
let mut out = Vec::with_capacity(rbsp.len() + rbsp.len() / 64 + 4);
out.push(nal_type << 1);
out.push(1);
let mut zeros = 0;
for &b in rbsp {
if zeros >= 2 && b <= 3 {
out.push(3);
zeros = 0;
}
out.push(b);
if b == 0 {
zeros += 1;
} else {
zeros = 0;
}
}
// cabac_zero_words / trailing zero bytes never occur: every RBSP ends with the stop bit.
out
}
pub const NAL_TRAIL_R: u8 = 1;
pub const NAL_IDR_N_LP: u8 = 20;
pub const NAL_VPS: u8 = 32;
pub const NAL_SPS: u8 = 33;
pub const NAL_PPS: u8 = 34;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn exp_golomb() {
let mut w = BitWriter::new();
w.ue(0); // 1
w.ue(1); // 010
w.ue(2); // 011
w.ue(3); // 00100
w.se(-1); // ue(2) = 011
w.trailing();
// 1 010 011 00100 011 + stop bit: 1010 0110 0100 0111
assert_eq!(w.into_bytes(), vec![0xa6, 0x47]);
}
#[test]
fn emulation_prevention() {
let n = nal_unit(1, &[0, 0, 1, 0, 0, 0, 0, 0, 4]);
assert_eq!(&n[2..], &[0, 0, 3, 1, 0, 0, 3, 0, 0, 3, 0, 4]);
}
}
-220
View File
@@ -1,220 +0,0 @@
//! CABAC: context initialisation (9.3.2.2), the arithmetic encoder (9.3.4.x, informative encoder
//! description: EncodeDecision, EncodeBypass, EncodeTerminate, EncodeFlush) and a fractional-bit
//! estimator with the same context-state evolution, used for rate-distortion decisions.
use crate::bitstream::BitWriter;
use crate::tables::{CABAC_INIT, NEXT_STATE, NUM_CTX, RANGE_TAB_LPS};
use std::sync::OnceLock;
/// Context states, each `pStateIdx << 1 | valMps`.
pub type Contexts = [u8; NUM_CTX];
/// Initialise all context variables for `slice_qp` and `init_type` (9.3.2.2).
pub fn init_contexts(slice_qp: i32, init_type: usize) -> Contexts {
let mut ctx = [0u8; NUM_CTX];
let qp = slice_qp.clamp(0, 51);
for (c, &v) in ctx.iter_mut().zip(CABAC_INIT[init_type].iter()) {
let slope = (v >> 4) as i32;
let offset = (v & 15) as i32;
let m = slope * 5 - 45;
let n = (offset << 3) - 16;
let pre = (((m * qp) >> 4) + n).clamp(1, 126);
*c = if pre <= 63 { ((63 - pre) << 1) as u8 } else { (((pre - 64) << 1) | 1) as u8 };
}
ctx
}
/// Destination of binarised syntax elements: the real arithmetic coder or the bit estimator.
pub trait Sink {
fn decision(&mut self, ctx: usize, bin: u32);
fn bypass(&mut self, bin: u32);
/// `n` bypass bins carrying the low `n` bits of `v`, MSB first.
fn bypass_bits(&mut self, v: u32, n: u32) {
for i in (0..n).rev() {
self.bypass((v >> i) & 1);
}
}
fn terminate(&mut self, bin: u32);
}
/// Arithmetic encoder writing into a bit writer.
pub struct CabacEncoder {
pub ctx: Contexts,
low: u32,
range: u32,
outstanding: u32,
first: bool,
pub w: BitWriter,
}
impl CabacEncoder {
/// Start encoding slice data into `w` (which must be byte aligned).
pub fn new(w: BitWriter, ctx: Contexts) -> Self {
debug_assert!(w.is_aligned());
CabacEncoder { ctx, low: 0, range: 510, outstanding: 0, first: true, w }
}
#[inline]
fn put_bit(&mut self, b: u32) {
if self.first {
self.first = false;
} else {
self.w.bit(b);
}
while self.outstanding > 0 {
self.w.bit(1 - b);
self.outstanding -= 1;
}
}
#[inline]
fn renorm(&mut self) {
while self.range < 256 {
if self.low < 256 {
self.put_bit(0);
} else if self.low >= 512 {
self.low -= 512;
self.put_bit(1);
} else {
self.low -= 256;
self.outstanding += 1;
}
self.range <<= 1;
self.low <<= 1;
}
}
/// EncodeFlush after a terminating bin equal to 1; the final bit written is the
/// rbsp_stop_one_bit. Returns the writer (byte aligned with zero bits).
pub fn finish(mut self) -> BitWriter {
self.range = 2;
self.renorm();
let b = (self.low >> 9) & 1;
self.put_bit(b);
self.w.put(((self.low >> 7) & 3) | 1, 2);
self.w.align_zero();
self.w
}
}
impl Sink for CabacEncoder {
#[inline]
fn decision(&mut self, ctx_idx: usize, bin: u32) {
let s = self.ctx[ctx_idx] as usize;
let mps = (s & 1) as u32;
let q = ((self.range >> 6) & 3) as usize;
let lps = RANGE_TAB_LPS[s >> 1][q] as u32;
self.range -= lps;
if bin != mps {
self.low += self.range;
self.range = lps;
self.ctx[ctx_idx] = NEXT_STATE[s][1];
} else {
self.ctx[ctx_idx] = NEXT_STATE[s][0];
}
self.renorm();
}
#[inline]
fn bypass(&mut self, bin: u32) {
self.low <<= 1;
if bin != 0 {
self.low += self.range;
}
if self.low >= 1024 {
self.put_bit(1);
self.low -= 1024;
} else if self.low < 512 {
self.put_bit(0);
} else {
self.low -= 512;
self.outstanding += 1;
}
}
fn terminate(&mut self, bin: u32) {
self.range -= 2;
if bin != 0 {
self.low += self.range;
// the caller flushes with finish()
} else {
self.renorm();
}
}
}
/// Fractional bit cost (1/32768 bit units) of coding the MPS / LPS in each state.
fn cost_table() -> &'static [[u32; 2]; 64] {
static T: OnceLock<[[u32; 2]; 64]> = OnceLock::new();
T.get_or_init(|| {
let mut t = [[0u32; 2]; 64];
// pLPS(s) = 0.5 * alpha^s with alpha = (0.01875 / 0.5)^(1/63) (9.3.4.3 design)
let alpha = (0.01875f64 / 0.5).powf(1.0 / 63.0);
for (s, e) in t.iter_mut().enumerate() {
let p = 0.5 * alpha.powi(s as i32);
e[0] = (-(1.0 - p).log2() * 32768.0).round() as u32;
e[1] = (-p.log2() * 32768.0).round() as u32;
}
t
})
}
pub const BIT: u64 = 32768;
/// Bit estimator: tracks context states like the encoder and accumulates the ideal code length.
#[derive(Clone)]
pub struct Estimator {
pub ctx: Contexts,
/// Accumulated cost in 1/32768 bits.
pub bits: u64,
table: &'static [[u32; 2]; 64],
}
impl Estimator {
pub fn new(ctx: Contexts) -> Self {
Estimator { ctx, bits: 0, table: cost_table() }
}
}
impl Sink for Estimator {
#[inline]
fn decision(&mut self, ctx_idx: usize, bin: u32) {
let s = self.ctx[ctx_idx] as usize;
let lps = (bin != (s & 1) as u32) as usize;
self.bits += self.table[s >> 1][lps] as u64;
self.ctx[ctx_idx] = NEXT_STATE[s][lps];
}
#[inline]
fn bypass(&mut self, _bin: u32) {
self.bits += BIT;
}
#[inline]
fn bypass_bits(&mut self, _v: u32, n: u32) {
self.bits += BIT * n as u64;
}
fn terminate(&mut self, _bin: u32) {
self.bits += 7; // ~0 bits for a 0 bin
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn context_init_formula() {
let ctx = init_contexts(30, 0);
// initValue 154: m = 0, n = 64 -> pStateIdx 0, valMps 1
assert_eq!(ctx[crate::tables::CU_TRANSQUANT_BYPASS], 1);
// split_cu_flag ctx 0 (initValue 139) at QP 30: preCtxState 62
assert_eq!(ctx[crate::tables::SPLIT_CU], (63 - 62) << 1);
}
#[test]
fn costs_are_sane() {
let t = cost_table();
assert_eq!(t[0][0], 32768);
assert_eq!(t[0][1], 32768);
assert!(t[62][0] < 1000 && t[62][1] > 5 * 32768);
}
}
-148
View File
@@ -1,148 +0,0 @@
//! Deblocking filter (8.7.2) over a whole reconstructed picture, mirrored from the filmcraft-hevc
//! decoder: all vertical edges on the 8x8 grid first, then all horizontal edges. One slice, one QP,
//! uni-directional prediction from a single reference picture, offsets 0.
use crate::frame::{Blk, E_EDGE_H, E_EDGE_V, F_CBF, F_INTRA};
use crate::tables::{BETA_TABLE, TC_TABLE, qpc_420};
#[inline]
fn tc_beta(q: i32, bs: i32, bd: u32) -> (i32, i32) {
let qb = q.clamp(0, 51);
let qt = (q + 2 * (bs - 1)).clamp(0, 53);
((TC_TABLE[qt as usize] as i32) << (bd - 8), (BETA_TABLE[qb as usize] as i32) << (bd - 8))
}
/// Boundary strength (8.7.2.4) between 4x4 blocks p and q on a transform / prediction edge.
fn boundary_strength(p: &Blk, q: &Blk) -> i32 {
if (p.flags | q.flags) & F_INTRA != 0 {
return 2;
}
if (p.flags | q.flags) & F_CBF != 0 {
return 1;
}
let far = (p.mv[0] as i32 - q.mv[0] as i32).abs() >= 4 || (p.mv[1] as i32 - q.mv[1] as i32).abs() >= 4;
far as i32
}
/// Deblock the planes in place. `qp` is the slice QpY (without QpBdOffset).
pub fn deblock(planes: &mut [Vec<u16>; 3], blk: &[Blk], w: usize, h: usize, qp: i32, bd: u32) {
let (w4, h4) = (w / 4, h / 4);
let cw = w / 2;
// chroma tc (bS 2 only; QpC from the averaged luma QP, no offsets)
let qt = (qpc_420(qp) + 2).clamp(0, 53);
let tc_c = (TC_TABLE[qt as usize] as i32) << (bd - 8);
// vertical edges
for by in 0..h4 {
for bx in (2..w4).step_by(2) {
let qi = by * w4 + bx;
if blk[qi].flags & E_EDGE_V == 0 {
continue;
}
let bs = boundary_strength(&blk[qi - 1], &blk[qi]);
if bs == 0 {
continue;
}
let (x, y) = (bx * 4, by * 4);
let (tc, beta) = tc_beta(qp, bs, bd);
filter_luma(&mut planes[0], y * w + x, 1, w, tc, beta, bd);
// chroma: 8x8 chroma grid (16 luma samples), one 4-sample chroma segment per 8 luma rows
if bs == 2 && bx % 4 == 0 && by % 2 == 0 {
for c in 1..3 {
filter_chroma(&mut planes[c], (y / 2) * cw + x / 2, 1, cw, tc_c, bd);
}
}
}
}
// horizontal edges
for by in (2..h4).step_by(2) {
for bx in 0..w4 {
let qi = by * w4 + bx;
if blk[qi].flags & E_EDGE_H == 0 {
continue;
}
let bs = boundary_strength(&blk[qi - w4], &blk[qi]);
if bs == 0 {
continue;
}
let (x, y) = (bx * 4, by * 4);
let (tc, beta) = tc_beta(qp, bs, bd);
filter_luma(&mut planes[0], y * w + x, w, 1, tc, beta, bd);
if bs == 2 && by % 4 == 0 && bx % 2 == 0 {
for c in 1..3 {
filter_chroma(&mut planes[c], (y / 2) * cw + x / 2, cw, 1, tc_c, bd);
}
}
}
}
}
/// Filter one 4-sample luma edge segment. `o` = offset of q0 of the first line, `step` = distance
/// between samples across the edge, `along` = distance between lines.
fn filter_luma(s: &mut [u16], o: usize, step: usize, along: usize, tc: i32, beta: i32, bd: u32) {
let px = |s: &[u16], k: usize, i: usize| s[o + k * along - (i + 1) * step] as i32;
let qx = |s: &[u16], k: usize, i: usize| s[o + k * along + i * step] as i32;
let dp0 = (px(s, 0, 2) - 2 * px(s, 0, 1) + px(s, 0, 0)).abs();
let dp3 = (px(s, 3, 2) - 2 * px(s, 3, 1) + px(s, 3, 0)).abs();
let dq0 = (qx(s, 0, 2) - 2 * qx(s, 0, 1) + qx(s, 0, 0)).abs();
let dq3 = (qx(s, 3, 2) - 2 * qx(s, 3, 1) + qx(s, 3, 0)).abs();
let (dpq0, dpq3) = (dp0 + dq0, dp3 + dq3);
let (dp, dq) = (dp0 + dp3, dq0 + dq3);
let d = dpq0 + dpq3;
if d >= beta {
return;
}
let dsam = |s: &[u16], k: usize, dpq: i32| -> bool {
dpq < (beta >> 2)
&& (px(s, k, 3) - px(s, k, 0)).abs() + (qx(s, k, 0) - qx(s, k, 3)).abs() < (beta >> 3)
&& (px(s, k, 0) - qx(s, k, 0)).abs() < ((5 * tc + 1) >> 1)
};
let strong = dsam(s, 0, 2 * dpq0) && dsam(s, 3, 2 * dpq3);
let dep = dp < ((beta + (beta >> 1)) >> 3);
let deq = dq < ((beta + (beta >> 1)) >> 3);
let max = (1i32 << bd) - 1;
for k in 0..4 {
let base = o + k * along;
let p = |i: usize| s[base - (i + 1) * step] as i32;
let q = |i: usize| s[base + i * step] as i32;
let (p0, p1, p2, p3) = (p(0), p(1), p(2), p(3));
let (q0, q1, q2, q3) = (q(0), q(1), q(2), q(3));
if strong {
let t2 = 2 * tc;
s[base - step] = ((p2 + 2 * p1 + 2 * p0 + 2 * q0 + q1 + 4) >> 3).clamp(p0 - t2, p0 + t2) as u16;
s[base - 2 * step] = ((p2 + p1 + p0 + q0 + 2) >> 2).clamp(p1 - t2, p1 + t2) as u16;
s[base - 3 * step] = ((2 * p3 + 3 * p2 + p1 + p0 + q0 + 4) >> 3).clamp(p2 - t2, p2 + t2) as u16;
s[base] = ((p1 + 2 * p0 + 2 * q0 + 2 * q1 + q2 + 4) >> 3).clamp(q0 - t2, q0 + t2) as u16;
s[base + step] = ((p0 + q0 + q1 + q2 + 2) >> 2).clamp(q1 - t2, q1 + t2) as u16;
s[base + 2 * step] = ((p0 + q0 + q1 + 3 * q2 + 2 * q3 + 4) >> 3).clamp(q2 - t2, q2 + t2) as u16;
} else {
let mut delta = (9 * (q0 - p0) - 3 * (q1 - p1) + 8) >> 4;
if delta.abs() >= tc * 10 {
continue;
}
delta = delta.clamp(-tc, tc);
s[base - step] = (p0 + delta).clamp(0, max) as u16;
s[base] = (q0 - delta).clamp(0, max) as u16;
if dep {
let dp = ((((p2 + p0 + 1) >> 1) - p1 + delta) >> 1).clamp(-(tc >> 1), tc >> 1);
s[base - 2 * step] = (p1 + dp).clamp(0, max) as u16;
}
if deq {
let dq = ((((q2 + q0 + 1) >> 1) - q1 - delta) >> 1).clamp(-(tc >> 1), tc >> 1);
s[base + step] = (q1 + dq).clamp(0, max) as u16;
}
}
}
}
/// Filter one 4-sample chroma edge segment.
fn filter_chroma(s: &mut [u16], o: usize, step: usize, along: usize, tc: i32, bd: u32) {
let max = (1i32 << bd) - 1;
for k in 0..4 {
let base = o + k * along;
let (p0, p1) = (s[base - step] as i32, s[base - 2 * step] as i32);
let (q0, q1) = (s[base] as i32, s[base + step] as i32);
let delta = ((((q0 - p0) << 2) + p1 - q1 + 4) >> 3).clamp(-tc, tc);
s[base - step] = (p0 + delta).clamp(0, max) as u16;
s[base] = (q0 - delta).clamp(0, max) as u16;
}
}
File diff suppressed because it is too large. Load diff
-157
View File
@@ -1,157 +0,0 @@
//! Fractional sample interpolation (8.5.3.3.3) and default weighted prediction (8-262), mirrored
//! from the filmcraft-hevc decoder. Reference sample fetches clamp to the picture (8-228, 8-229).
use crate::tables::{CHROMA_FILTER, LUMA_FILTER};
/// One plane of a reference picture.
#[derive(Clone, Copy)]
pub struct PlaneRef<'a> {
pub data: &'a [u16],
pub w: usize,
pub h: usize,
}
impl PlaneRef<'_> {
/// Copy a w x h window at (x0, y0) with edge replication.
fn window(&self, x0: i32, y0: i32, w: usize, h: usize, out: &mut [i16], os: usize) {
let (pw, ph) = (self.w as i32, self.h as i32);
let inside_x = x0 >= 0 && x0 + w as i32 <= pw;
for r in 0..h {
let yy = (y0 + r as i32).clamp(0, ph - 1) as usize;
let row = &self.data[yy * self.w..yy * self.w + self.w];
let dst = &mut out[r * os..r * os + w];
if inside_x {
for (d, &s) in dst.iter_mut().zip(&row[x0 as usize..x0 as usize + w]) {
*d = s as i16;
}
} else {
for (c, d) in dst.iter_mut().enumerate() {
*d = row[(x0 + c as i32).clamp(0, pw - 1) as usize] as i16;
}
}
}
}
}
/// Luma prediction samples (14-bit intermediate) of a w x h block at (x, y) displaced by the
/// quarter-sample vector `mv`, into `out` (stride w).
pub fn mc_luma(f: PlaneRef, bd: u32, x: i32, y: i32, mv: [i16; 2], size: (usize, usize), out: &mut [i16]) {
let (w, h) = size;
let (fx, fy) = ((mv[0] & 3) as usize, (mv[1] & 3) as usize);
let xi = x + (mv[0] as i32 >> 2);
let yi = y + (mv[1] as i32 >> 2);
let shift1 = bd.min(12) - 8;
let shift3 = 14 - bd;
let ws = w + 7;
let mut win = vec![0i16; ws * (h + 7)];
if fx == 0 && fy == 0 {
f.window(xi, yi, w, h, &mut win, ws);
for r in 0..h {
for c in 0..w {
out[r * w + c] = win[r * ws + c] << shift3;
}
}
return;
}
f.window(xi - 3, yi - 3, w + 7, h + 7, &mut win, ws);
let hf = &LUMA_FILTER[fx];
let vf = &LUMA_FILTER[fy];
if fy == 0 {
for r in 0..h {
let row = &win[(r + 3) * ws..];
for c in 0..w {
let s: i32 = (0..8).map(|k| hf[k] as i32 * row[c + k] as i32).sum();
out[r * w + c] = (s >> shift1) as i16;
}
}
} else if fx == 0 {
for r in 0..h {
for c in 0..w {
let s: i32 = (0..8).map(|k| vf[k] as i32 * win[(r + k) * ws + c + 3] as i32).sum();
out[r * w + c] = (s >> shift1) as i16;
}
}
} else {
let mut tmp = vec![0i16; ws * (h + 7)];
for r in 0..h + 7 {
let row = &win[r * ws..];
for c in 0..w {
let s: i32 = (0..8).map(|k| hf[k] as i32 * row[c + k] as i32).sum();
tmp[r * ws + c] = (s >> shift1) as i16;
}
}
for r in 0..h {
for c in 0..w {
let s: i32 = (0..8).map(|k| vf[k] as i32 * tmp[(r + k) * ws + c] as i32).sum();
out[r * w + c] = (s >> 6) as i16;
}
}
}
}
/// Chroma prediction samples of a w x h block at chroma position (x, y) with a 1/8-sample vector.
pub fn mc_chroma(f: PlaneRef, bd: u32, x: i32, y: i32, mv: [i16; 2], size: (usize, usize), out: &mut [i16]) {
let (w, h) = size;
let (fx, fy) = ((mv[0] & 7) as usize, (mv[1] & 7) as usize);
let xi = x + (mv[0] as i32 >> 3);
let yi = y + (mv[1] as i32 >> 3);
let shift1 = bd.min(12) - 8;
let shift3 = 14 - bd;
let ws = w + 7;
let mut win = vec![0i16; ws * (h + 7)];
if fx == 0 && fy == 0 {
f.window(xi, yi, w, h, &mut win, ws);
for r in 0..h {
for c in 0..w {
out[r * w + c] = win[r * ws + c] << shift3;
}
}
return;
}
f.window(xi - 1, yi - 1, w + 3, h + 3, &mut win, ws);
let hf = &CHROMA_FILTER[fx];
let vf = &CHROMA_FILTER[fy];
if fy == 0 {
for r in 0..h {
let row = &win[(r + 1) * ws..];
for c in 0..w {
let s: i32 = (0..4).map(|k| hf[k] as i32 * row[c + k] as i32).sum();
out[r * w + c] = (s >> shift1) as i16;
}
}
} else if fx == 0 {
for r in 0..h {
for c in 0..w {
let s: i32 = (0..4).map(|k| vf[k] as i32 * win[(r + k) * ws + c + 1] as i32).sum();
out[r * w + c] = (s >> shift1) as i16;
}
}
} else {
let mut tmp = vec![0i16; ws * (h + 7)];
for r in 0..h + 3 {
let row = &win[r * ws..];
for c in 0..w {
let s: i32 = (0..4).map(|k| hf[k] as i32 * row[c + k] as i32).sum();
tmp[r * ws + c] = (s >> shift1) as i16;
}
}
for r in 0..h {
for c in 0..w {
let s: i32 = (0..4).map(|k| vf[k] as i32 * tmp[(r + k) * ws + c] as i32).sum();
out[r * w + c] = (s >> 6) as i16;
}
}
}
}
/// Default weighted prediction, one list (8-262): 14-bit samples to `bd`-bit samples.
pub fn put_uni(p: &[i16], w: usize, h: usize, bd: u32, dst: &mut [u16], ds: usize) {
let shift = 14 - bd;
let off = if shift > 0 { 1 << (shift - 1) } else { 0 };
let max = (1i32 << bd) - 1;
for r in 0..h {
for c in 0..w {
dst[r * ds + c] = ((p[r * w + c] as i32 + off) >> shift).clamp(0, max) as u16;
}
}
}
-254
View File
@@ -1,254 +0,0 @@
//! Intra sample prediction (8.4.4.2), mirrored from the filmcraft-hevc decoder so the encoder
//! reconstructs exactly like a decoder: reference substitution, filtering (incl. strong intra
//! smoothing), planar, DC and the 33 angular modes.
use crate::tables::{INTRA_PRED_ANGLE, INV_ANGLE};
/// Reference samples of an nTbS block: `left[0]` = `top[0]` = p[-1][-1], `left[1 + y]` = p[-1][y],
/// `top[1 + x]` = p[x][-1] for x, y = 0..2*nTbS-1.
#[derive(Clone)]
pub struct Refs {
pub left: [u16; 129],
pub top: [u16; 129],
}
impl Default for Refs {
fn default() -> Self {
Refs { left: [0; 129], top: [0; 129] }
}
}
/// Substitution process (8.4.4.2.2). `avail_left[1 + y]` / `avail_top[1 + x]` (index 0 = corner) tell
/// which samples are available; unavailable ones are replaced.
pub fn substitute(r: &mut Refs, avail_left: &[bool; 129], avail_top: &[bool; 129], n: usize, bit_depth: u32) {
let n2 = 2 * n;
// Sequence order: p[-1][2n-1] .. p[-1][-1], p[0][-1] .. p[2n-1][-1]
let any = avail_left[..=n2].iter().any(|&a| a) || avail_top[1..=n2].iter().any(|&a| a);
if !any {
let v = 1u16 << (bit_depth - 1);
r.left[..=n2].fill(v);
r.top[..=n2].fill(v);
return;
}
if !avail_left[n2] {
// search upwards then along the top
let mut found = None;
for y in (0..n2).rev() {
if avail_left[y] {
found = Some(r.left[y]);
break;
}
}
if found.is_none() {
for x in 1..=n2 {
if avail_top[x] {
found = Some(r.top[x]);
break;
}
}
}
r.left[n2] = found.unwrap_or(0);
}
for y in (0..n2).rev() {
if !avail_left[y] {
r.left[y] = r.left[y + 1];
}
}
r.top[0] = r.left[0];
for x in 1..=n2 {
if !avail_top[x] {
r.top[x] = r.top[x - 1];
}
}
}
/// Filtering process of neighbouring samples (8.4.4.2.3) for luma (and 4:4:4 chroma).
pub fn filter(r: &mut Refs, mode: u32, n: usize, strong_enabled: bool, is_luma: bool, bit_depth: u32) {
if mode == 1 || n == 4 {
return;
}
let min_dist = (mode as i32 - 26).abs().min((mode as i32 - 10).abs());
let thres = match n {
8 => 7,
16 => 1,
_ => 0,
};
if min_dist <= thres {
return;
}
let n2 = 2 * n;
let c = r.left[0] as i32;
if strong_enabled && is_luma && n == 32 {
let (bl, tr) = (r.left[n2] as i32, r.top[n2] as i32);
let thr = 1 << (bit_depth - 5);
if (c + tr - 2 * r.top[n] as i32).abs() < thr && (c + bl - 2 * r.left[n] as i32).abs() < thr {
for i in 0..63 {
r.left[1 + i] = (((63 - i as i32) * c + (i as i32 + 1) * bl + 32) >> 6) as u16;
r.top[1 + i] = (((63 - i as i32) * c + (i as i32 + 1) * tr + 32) >> 6) as u16;
}
return;
}
}
let (l, t) = (r.left, r.top);
let corner = ((l[1] as u32 + 2 * c as u32 + t[1] as u32 + 2) >> 2) as u16;
for i in 1..n2 {
r.left[i] = ((l[i - 1] as u32 + 2 * l[i] as u32 + l[i + 1] as u32 + 2) >> 2) as u16;
r.top[i] = ((t[i - 1] as u32 + 2 * t[i] as u32 + t[i + 1] as u32 + 2) >> 2) as u16;
}
r.left[0] = corner;
r.top[0] = corner;
}
/// Predict an n x n block with `mode` into `out` (stride `os`). `edge_filters`: DC / horizontal /
/// vertical boundary smoothing (luma blocks smaller than 32x32).
pub fn predict(r: &Refs, mode: u32, n: usize, edge_filters: bool, bit_depth: u32, out: &mut [u16], os: usize) {
let max = (1i32 << bit_depth) - 1;
match mode {
0 => {
// planar
let log2 = n.trailing_zeros();
let tr = r.top[1 + n] as i32;
let bl = r.left[1 + n] as i32;
for y in 0..n {
let l = r.left[1 + y] as i32;
for x in 0..n {
let t = r.top[1 + x] as i32;
let v = ((n - 1 - x) as i32 * l + (x as i32 + 1) * tr + (n - 1 - y) as i32 * t + (y as i32 + 1) * bl + n as i32) >> (log2 + 1);
out[y * os + x] = v as u16;
}
}
}
1 => {
let log2 = n.trailing_zeros();
let sum: u32 = r.top[1..=n].iter().map(|&v| v as u32).sum::<u32>() + r.left[1..=n].iter().map(|&v| v as u32).sum::<u32>();
let dc = ((sum + n as u32) >> (log2 + 1)) as u16;
for y in 0..n {
out[y * os..y * os + n].fill(dc);
}
if edge_filters && n < 32 {
let d = dc as u32;
out[0] = ((r.left[1] as u32 + 2 * d + r.top[1] as u32 + 2) >> 2) as u16;
for x in 1..n {
out[x] = ((r.top[1 + x] as u32 + 3 * d + 2) >> 2) as u16;
}
for y in 1..n {
out[y * os] = ((r.left[1 + y] as u32 + 3 * d + 2) >> 2) as u16;
}
}
}
_ => {
let angle = INTRA_PRED_ANGLE[mode as usize] as i32;
// reference array ref[-n..=2n] stored at offset n
let mut refa = [0i32; 3 * 64 + 1];
let base = n as i32;
let (main, side) = if mode >= 18 { (&r.top, &r.left) } else { (&r.left, &r.top) };
for x in 0..=n {
refa[(base + x as i32) as usize] = main[x] as i32; // ref[x] = p[-1+x][-1]
}
if angle < 0 {
let lim = (n as i32 * angle) >> 5;
if lim < -1 {
let inv = INV_ANGLE[(mode - 11) as usize] as i32;
for x in lim..=-1 {
let idx = -1 + ((x * inv + 128) >> 8);
refa[(base + x) as usize] = side[(idx + 1) as usize] as i32;
}
}
} else {
for x in n + 1..=2 * n {
refa[(base + x as i32) as usize] = main[x] as i32;
}
}
let horizontal = mode < 18;
for j in 0..n {
let pos = (j as i32 + 1) * angle;
let idx = pos >> 5;
let fact = pos & 31;
for i in 0..n {
let k = (base + i as i32 + idx + 1) as usize;
let v = if fact != 0 { ((32 - fact) * refa[k] + fact * refa[k + 1] + 16) >> 5 } else { refa[k] };
if horizontal {
out[i * os + j] = v as u16;
} else {
out[j * os + i] = v as u16;
}
}
}
if edge_filters && n < 32 {
if mode == 26 {
for y in 0..n {
let v = r.top[1] as i32 + ((r.left[1 + y] as i32 - r.left[0] as i32) >> 1);
out[y * os] = v.clamp(0, max) as u16;
}
} else if mode == 10 {
for x in 0..n {
let v = r.left[1] as i32 + ((r.top[1 + x] as i32 - r.top[0] as i32) >> 1);
out[x] = v.clamp(0, max) as u16;
}
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn refs(f: impl Fn(i32) -> u16) -> Refs {
let mut r = Refs::default();
r.left[0] = f(0);
r.top[0] = f(0);
for i in 1..129 {
r.left[i] = f(-(i as i32));
r.top[i] = f(i as i32);
}
r
}
#[test]
fn dc_and_planar_flat() {
let r = refs(|_| 100);
let mut out = [0u16; 64];
predict(&r, 1, 8, true, 8, &mut out, 8);
assert!(out.iter().all(|&v| v == 100));
predict(&r, 0, 8, true, 8, &mut out, 8);
assert!(out.iter().all(|&v| v == 100));
}
#[test]
fn pure_vertical_and_horizontal() {
let r = refs(|i| (128 + i) as u16);
let mut out = [0u16; 16];
predict(&r, 26, 4, false, 8, &mut out, 4);
for y in 0..4 {
for x in 0..4 {
assert_eq!(out[y * 4 + x], r.top[1 + x]);
}
}
predict(&r, 10, 4, false, 8, &mut out, 4);
for y in 0..4 {
for x in 0..4 {
assert_eq!(out[y * 4 + x], r.left[1 + y]);
}
}
// diagonal mode 34 reads top[x + y + 2]
predict(&r, 34, 4, false, 8, &mut out, 4);
assert_eq!(out[4 + 1], r.top[1 + 1 + 1 + 1]);
}
#[test]
fn substitution() {
let mut r = Refs::default();
let mut al = [false; 129];
let at = [false; 129];
r.left[3] = 77;
al[3] = true;
substitute(&mut r, &al, &at, 4, 8);
assert!(r.left[..=8].iter().all(|&v| v == 77));
assert!(r.top[..=8].iter().all(|&v| v == 77));
let mut r = Refs::default();
substitute(&mut r, &[false; 129], &[false; 129], 4, 10);
assert_eq!(r.top[5], 512);
}
}
-365
View File
@@ -1,365 +0,0 @@
//! Clean-room pure-Rust HEVC (H.265) encoder, implemented from ITU-T Rec. H.265 (ISO/IEC 23008-2).
//!
//! Main and Main 10 profiles, 4:2:0, one slice per picture: IDR pictures and single-reference P
//! pictures (no reordering), 64x64 CTUs with rate-distortion coding-unit decisions (8x8 .. 64x64),
//! intra (35 modes, NxN at 8x8), merge / skip and AMVP inter prediction with quarter-sample motion,
//! DCT / DST transforms and CABAC. The deblocking filter is on; SAO is not used.
//!
//! ```
//! use effectcraft_hevcenc::{Encoder, EncoderConfig, Frame};
//! let mut enc = Encoder::new(EncoderConfig::new(64, 48, 30, 1)).unwrap();
//! let (y, c) = (vec![128u16; 64 * 48], vec![128u16; 32 * 24]);
//! let packet = enc.encode(&Frame { y: &y, u: &c, v: &c, y_stride: 64, uv_stride: 32 });
//! assert!(packet.keyframe && !packet.data.is_empty());
//! let _hvcc = enc.hvcc();
//! ```
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
mod bitstream;
mod cabac;
mod deblock;
mod frame;
mod inter;
mod intra;
mod me;
mod params;
#[rustfmt::skip]
mod tables;
mod transform;
use bitstream::{BitWriter, NAL_IDR_N_LP, NAL_TRAIL_R, nal_unit};
use frame::{FrameCoder, SliceKind};
use params::{LOG2_MAX_POC_LSB, LOG2_MIN_CB, MAX_MERGE_CAND, SeqParams};
/// Profile written in the parameter sets.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Profile {
/// Main: 8-bit 4:2:0.
#[default]
Main,
/// Main 10: 10-bit 4:2:0.
Main10,
}
impl Profile {
pub fn bit_depth(self) -> u8 {
match self {
Profile::Main => 8,
Profile::Main10 => 10,
}
}
fn idc(self) -> u8 {
match self {
Profile::Main => 1,
Profile::Main10 => 2,
}
}
}
/// Rate control.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RateControl {
/// Constant QP (0–51; lower is better).
ConstantQp(u8),
/// Average bitrate target in kbit/s (frame-level QP adaptation).
Bitrate { kbps: u32 },
}
/// Encoder settings.
#[derive(Clone, Debug, PartialEq)]
pub struct EncoderConfig {
/// Picture size; must be even (4:2:0 cropping is in units of two luma samples).
pub width: u32,
pub height: u32,
/// Frame rate numerator / denominator (VUI timing and rate control).
pub fps_num: u32,
pub fps_den: u32,
pub profile: Profile,
/// `general_level_idc` (30 × level, e.g. 93 = level 3.1); `None` picks the lowest level that fits.
pub level_idc: Option<u8>,
pub rate: RateControl,
/// Frames between IDR pictures (1 = all intra, 0 = only the first picture).
pub keyint: u32,
/// BT.709 limited range is signalled in the VUI unless this is set.
pub full_range: bool,
/// The VUI colour description (ITU-T H.273 code points); BT.709 by default.
pub colour_primaries: u8,
pub transfer_characteristics: u8,
pub matrix_coeffs: u8,
}
impl EncoderConfig {
pub fn new(width: u32, height: u32, fps_num: u32, fps_den: u32) -> Self {
EncoderConfig {
width,
height,
fps_num,
fps_den,
profile: Profile::Main,
level_idc: None,
rate: RateControl::ConstantQp(28),
keyint: 60,
full_range: false,
colour_primaries: 1,
transfer_characteristics: 1,
matrix_coeffs: 1,
}
}
}
/// One input picture, 4:2:0, samples at the profile's bit depth (8-bit values 0–255 for Main).
/// Luma is `width` x `height`, chroma `width / 2` x `height / 2`.
#[derive(Clone, Copy, Debug)]
pub struct Frame<'a> {
pub y: &'a [u16],
pub u: &'a [u16],
pub v: &'a [u16],
pub y_stride: usize,
pub uv_stride: usize,
}
/// One coded picture (an access unit): NAL units, each prefixed by a 4-byte big-endian length
/// (ISO/IEC 14496-15 sample format; parameter sets are only in [`Encoder::hvcc`]).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Packet {
pub data: Vec<u8>,
/// IDR picture.
pub keyframe: bool,
}
#[derive(Debug, PartialEq, Eq)]
pub enum Error {
InvalidConfig(String),
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Error::InvalidConfig(s) => write!(f, "invalid HEVC encoder config: {s}"),
}
}
}
impl std::error::Error for Error {}
/// Frame-level rate control for [`RateControl::Bitrate`]: a bits ≈ X / Qstep model per picture type
/// and a buffer that spreads over- / undershoot over the following pictures.
struct RateCtl {
target: f64,
/// sum(actual) - sum(target), bits.
buffer: f64,
/// Complexity X = bits * Qstep for I and P pictures.
x: [Option<f64>; 2],
last_qp: [i32; 2],
init_qp: i32,
}
fn qstep(qp: i32) -> f64 {
2f64.powf((qp as f64 - 4.0) / 6.0)
}
impl RateCtl {
fn new(kbps: u32, cfg: &EncoderConfig) -> Self {
let fps = cfg.fps_num as f64 / cfg.fps_den.max(1) as f64;
let target = kbps as f64 * 1000.0 / fps.max(0.001);
let bpp = target / (cfg.width as f64 * cfg.height as f64);
let init_qp = (28.0 - 6.0 * (bpp / 0.08).log2()).round().clamp(10.0, 46.0) as i32;
RateCtl { target, buffer: 0.0, x: [None, None], last_qp: [init_qp - 3, init_qp], init_qp }
}
fn qp(&self, idr: bool) -> i32 {
let t = idr as usize ^ 1; // 0 = I, 1 = P
let tp = (self.target - self.buffer / 12.0).clamp(0.3 * self.target, 2.0 * self.target);
let want = if idr { 4.0 * tp } else { tp };
let x = match (self.x[t], self.x[0]) {
(Some(x), _) => x,
(None, Some(xi)) => xi / 5.0,
(None, None) => return if idr { self.init_qp - 3 } else { self.init_qp },
};
let qp = (4.0 + 6.0 * (x / want).log2()).round() as i32;
qp.clamp(self.last_qp[t] - 6, self.last_qp[t] + 6).clamp(1, 51)
}
fn update(&mut self, idr: bool, qp: i32, bits: f64) {
let t = idr as usize ^ 1;
let x = bits * qstep(qp);
self.x[t] = Some(match self.x[t] {
Some(old) => 0.5 * old + 0.5 * x,
None => x,
});
self.last_qp[t] = qp;
self.buffer += bits - self.target;
}
}
/// HEVC encoder. Pictures come out in input order (no reordering: I and P only).
pub struct Encoder {
cfg: EncoderConfig,
seq: SeqParams,
sets: [Vec<u8>; 3],
frames: u64,
/// POC of the previous picture (relative to the last IDR).
poc: u32,
reference: Option<[Vec<u16>; 3]>,
recon: Option<[Vec<u16>; 3]>,
rc: Option<RateCtl>,
}
impl Encoder {
pub fn new(cfg: EncoderConfig) -> Result<Encoder, Error> {
if cfg.width == 0 || cfg.height == 0 {
return Err(Error::InvalidConfig("empty frame".into()));
}
if !cfg.width.is_multiple_of(2) || !cfg.height.is_multiple_of(2) {
return Err(Error::InvalidConfig(format!("{}x{}: 4:2:0 HEVC needs even dimensions", cfg.width, cfg.height)));
}
if cfg.width > 16384 || cfg.height > 16384 {
return Err(Error::InvalidConfig("picture larger than 16384 samples".into()));
}
if cfg.fps_num == 0 || cfg.fps_den == 0 {
return Err(Error::InvalidConfig("zero frame rate".into()));
}
match cfg.rate {
RateControl::ConstantQp(q) if q > 51 => return Err(Error::InvalidConfig(format!("QP {q} > 51"))),
RateControl::Bitrate { kbps: 0 } => return Err(Error::InvalidConfig("zero bitrate".into())),
_ => {}
}
let min_cb = 1u32 << LOG2_MIN_CB;
let (coded_width, coded_height) = (cfg.width.div_ceil(min_cb) * min_cb, cfg.height.div_ceil(min_cb) * min_cb);
let kbps = match cfg.rate {
RateControl::Bitrate { kbps } => Some(kbps),
RateControl::ConstantQp(_) => None,
};
let level_idc = cfg.level_idc.unwrap_or_else(|| params::choose_level(coded_width, coded_height, cfg.fps_num, cfg.fps_den, kbps));
let seq = SeqParams {
coded_width,
coded_height,
width: cfg.width,
height: cfg.height,
bit_depth: cfg.profile.bit_depth() as u32,
profile_idc: cfg.profile.idc(),
level_idc,
full_range: cfg.full_range,
colour_primaries: cfg.colour_primaries,
transfer_characteristics: cfg.transfer_characteristics,
matrix_coeffs: cfg.matrix_coeffs,
fps_num: cfg.fps_num,
fps_den: cfg.fps_den,
};
let sets = [params::vps(&seq), params::sps(&seq), params::pps()];
let rc = kbps.map(|k| RateCtl::new(k, &cfg));
Ok(Encoder { cfg, seq, sets, frames: 0, poc: 0, reference: None, recon: None, rc })
}
pub fn config(&self) -> &EncoderConfig {
&self.cfg
}
/// VPS, SPS, PPS NAL units (2-byte NAL header, emulation prevention, no start codes or length
/// prefixes).
pub fn parameter_sets(&self) -> [Vec<u8>; 3] {
self.sets.clone()
}
/// HEVCDecoderConfigurationRecord (`hvcC` payload) with the parameter sets.
pub fn hvcc(&self) -> Vec<u8> {
params::hvcc(&self.seq, &self.sets)
}
/// `general_level_idc` written in the parameter sets.
pub fn level_idc(&self) -> u8 {
self.seq.level_idc
}
/// Reconstruction of the last encoded picture (what a decoder outputs), cropped planes
/// `[Y, Cb, Cr]` with strides `width` and `width / 2`. For tests.
#[doc(hidden)]
pub fn last_reconstruction(&self) -> Option<&[Vec<u16>; 3]> {
self.recon.as_ref()
}
/// Copy the input into coded-size planes, replicating the right / bottom edges.
fn pad_input(&self, f: &Frame) -> [Vec<u16>; 3] {
let max = (1u32 << self.seq.bit_depth) - 1;
let mut out: [Vec<u16>; 3] = Default::default();
for (c, plane) in out.iter_mut().enumerate() {
let (src, stride, w, h, cw, ch) = if c == 0 {
(f.y, f.y_stride, self.seq.width, self.seq.height, self.seq.coded_width, self.seq.coded_height)
} else {
let s = if c == 1 { f.u } else { f.v };
(s, f.uv_stride, self.seq.width / 2, self.seq.height / 2, self.seq.coded_width / 2, self.seq.coded_height / 2)
};
let (w, h, cw, ch) = (w as usize, h as usize, cw as usize, ch as usize);
assert!(stride >= w && src.len() >= (h - 1) * stride + w, "HEVC encoder: plane {c} smaller than {w}x{h} (stride {stride})");
plane.reserve(cw * ch);
for y in 0..ch {
let row = &src[y.min(h - 1) * stride..][..w];
plane.extend(row.iter().map(|&v| (v as u32).min(max) as u16));
let last = plane.last().copied().unwrap_or(0);
plane.extend(std::iter::repeat_n(last, cw - w));
}
}
out
}
/// Encodes one picture.
pub fn encode(&mut self, frame: &Frame) -> Packet {
let src = self.pad_input(frame);
let keyint = self.cfg.keyint as u64;
let idr = self.reference.is_none() || (keyint > 0 && self.frames.is_multiple_of(keyint));
self.poc = if idr { 0 } else { self.poc + 1 };
let qp = match (&self.rc, self.cfg.rate) {
(Some(rc), _) => rc.qp(idr),
(None, RateControl::ConstantQp(q)) => q as i32,
(None, RateControl::Bitrate { .. }) => 28,
};
let (w, h) = (self.seq.coded_width as usize, self.seq.coded_height as usize);
let bd = self.seq.bit_depth;
let kind = if idr { SliceKind::I } else { SliceKind::P };
let me = if idr { None } else { self.reference.as_ref().map(|r| me::MeRef::new(&r[0], w, h, bd)) };
let refp = if idr { None } else { self.reference.as_ref() };
let mut fc = FrameCoder::new(frame::FrameConfig { bit_depth: bd, width: w, height: h, kind, slice_qp: qp }, &src, refp, me.as_ref());
// slice_segment_header() (7.3.6.1)
let mut bw = BitWriter::new();
bw.put(1, 1); // first_slice_segment_in_pic_flag
if idr {
bw.put(0, 1); // no_output_of_prior_pics_flag
}
bw.ue(0); // slice_pic_parameter_set_id
bw.ue(if idr { 2 } else { 1 }); // slice_type I / P
if !idr {
bw.put(self.poc & ((1 << LOG2_MAX_POC_LSB) - 1), LOG2_MAX_POC_LSB); // slice_pic_order_cnt_lsb
bw.put(1, 1); // short_term_ref_pic_set_sps_flag (the only SPS set, no index coded)
bw.put(0, 1); // num_ref_idx_active_override_flag
bw.ue(5 - MAX_MERGE_CAND as u32); // five_minus_max_num_merge_cand
}
bw.se(qp - 26); // slice_qp_delta (init_qp = 26)
// byte_alignment()
bw.put(1, 1);
bw.align_zero();
let ctx = cabac::init_contexts(qp, if idr { 0 } else { 1 });
let mut enc = cabac::CabacEncoder::new(bw, ctx);
fc.encode(&mut enc);
fc.deblock();
let rbsp = enc.finish().into_bytes();
let nal = nal_unit(if idr { NAL_IDR_N_LP } else { NAL_TRAIL_R }, &rbsp);
let mut data = Vec::with_capacity(nal.len() + 4);
data.extend_from_slice(&(nal.len() as u32).to_be_bytes());
data.extend_from_slice(&nal);
if let Some(rc) = &mut self.rc {
rc.update(idr, qp, data.len() as f64 * 8.0);
}
// output picture: cropped reconstruction
let rec = std::mem::take(&mut fc.rec);
let (ow, oh) = (self.seq.width as usize, self.seq.height as usize);
let crop = |p: &[u16], stride: usize, w: usize, h: usize| -> Vec<u16> { (0..h).flat_map(|y| p[y * stride..y * stride + w].iter().copied()).collect() };
self.recon = Some([crop(&rec[0], w, ow, oh), crop(&rec[1], w / 2, ow / 2, oh / 2), crop(&rec[2], w / 2, ow / 2, oh / 2)]);
self.reference = Some(rec);
self.frames += 1;
Packet { data, keyframe: idr }
}
}
-144
View File
@@ -1,144 +0,0 @@
//! Motion search reference: the previous reconstructed luma plane padded by edge replication, plus
//! half-sample planes interpolated with the 8-tap half-sample filter. Quarter-sample positions are
//! approximated by averaging neighbouring half-grid samples. Used for estimation only; the coded
//! prediction always uses the normative interpolation in `inter`.
use crate::tables::LUMA_FILTER;
const MARGIN: i32 = 80;
pub struct MeRef {
/// [integer, horizontal half, vertical half, diagonal half] samples, each `stride` x `rows`.
planes: [Vec<u16>; 4],
stride: usize,
rows: usize,
w: i32,
h: i32,
}
impl MeRef {
pub fn new(y: &[u16], w: usize, h: usize, bd: u32) -> MeRef {
let m = MARGIN as usize;
let (stride, rows) = (w + 2 * m, h + 2 * m);
let mut pad = vec![0u16; stride * rows];
for r in 0..rows {
let sy = (r as i32 - MARGIN).clamp(0, h as i32 - 1) as usize;
let src = &y[sy * w..sy * w + w];
let row = &mut pad[r * stride..r * stride + stride];
row[..m].fill(src[0]);
row[m..m + w].copy_from_slice(src);
row[m + w..].fill(src[w - 1]);
}
let max = (1i32 << bd) - 1;
let f = &LUMA_FILTER[2];
let filt_h = |p: &[u16]| -> Vec<u16> {
let mut o = vec![0u16; stride * rows];
for r in 0..rows {
let row = &p[r * stride..r * stride + stride];
for x in 0..stride {
let mut s = 0i32;
for k in 0..8 {
let xx = (x as i32 - 3 + k as i32).clamp(0, stride as i32 - 1) as usize;
s += f[k] as i32 * row[xx] as i32;
}
o[r * stride + x] = ((s + 32) >> 6).clamp(0, max) as u16;
}
}
o
};
let filt_v = |p: &[u16]| -> Vec<u16> {
let mut o = vec![0u16; stride * rows];
let mut acc = vec![0i32; stride];
for r in 0..rows {
acc.fill(0);
for k in 0..8 {
let rr = (r as i32 - 3 + k as i32).clamp(0, rows as i32 - 1) as usize;
let src = &p[rr * stride..rr * stride + stride];
let coef = f[k] as i32;
for (a, &s) in acc.iter_mut().zip(src) {
*a += coef * s as i32;
}
}
for (d, &a) in o[r * stride..r * stride + stride].iter_mut().zip(&acc) {
*d = ((a + 32) >> 6).clamp(0, max) as u16;
}
}
o
};
let hp = filt_h(&pad);
let vp = filt_v(&pad);
let dp = filt_v(&hp);
MeRef { planes: [pad, hp, vp, dp], stride, rows, w: w as i32, h: h as i32 }
}
/// Integer motion vector range keeping an n x n block (plus filter margin) inside the padding.
pub fn int_range(&self, x: i32, y: i32, n: usize) -> (i32, i32, i32, i32) {
let n = n as i32;
let lo_x = -MARGIN + 4 - x;
let hi_x = self.w + MARGIN - n - 4 - x;
let lo_y = -MARGIN + 4 - y;
let hi_y = self.h + MARGIN - n - 4 - y;
(lo_x.max(-256), hi_x.min(256), lo_y.max(-256), hi_y.min(256))
}
/// SAD of the source block against the integer-position reference block at (rx, ry).
pub fn sad(&self, src: &[u16], ss: usize, rx: i32, ry: i32, n: usize) -> u32 {
let p = &self.planes[0];
let base = (ry + MARGIN) as usize * self.stride + (rx + MARGIN) as usize;
let mut s = 0u32;
for r in 0..n {
let a = &src[r * ss..r * ss + n];
let b = &p[base + r * self.stride..base + r * self.stride + n];
s += a.iter().zip(b).map(|(&x, &y)| (x as i32 - y as i32).unsigned_abs()).sum::<u32>();
}
s
}
/// Approximate luma prediction of an n x n block at (x, y) with quarter-sample vector `mv`.
pub fn approx_pred(&self, x: i32, y: i32, n: usize, mv: [i16; 2], out: &mut [u16]) {
// per axis: one or two (half-sample fraction, integer offset) taps
let axis = |v: i32| -> [(usize, i32); 2] {
if v & 1 == 0 {
let hv = v >> 1;
[((hv & 1) as usize, hv >> 1); 2]
} else {
let (a, b) = ((v - 1) >> 1, (v + 1) >> 1);
[((a & 1) as usize, a >> 1), ((b & 1) as usize, b >> 1)]
}
};
let (mx, my) = (mv[0] as i32, mv[1] as i32);
let ax = axis(mx);
let ay = axis(my);
let two = mx & 1 != 0 || my & 1 != 0;
let taps = [(ax[0], ay[0]), (ax[1], ay[1])];
let ntaps = if two { 2 } else { 1 };
let mut first = true;
for &((fx, ox), (fy, oy)) in taps.iter().take(ntaps) {
let plane = &self.planes[fx + 2 * fy];
let (bx, by) = (x + ox + MARGIN, y + oy + MARGIN);
let inside = bx >= 0 && by >= 0 && bx as usize + n <= self.stride && by as usize + n <= self.rows;
for r in 0..n {
let dst = &mut out[r * n..r * n + n];
if inside {
let o = (by as usize + r) * self.stride + bx as usize;
let src = &plane[o..o + n];
if first {
dst.copy_from_slice(src);
} else {
for (d, &s) in dst.iter_mut().zip(src) {
*d = ((*d as u32 + s as u32 + 1) >> 1) as u16;
}
}
} else {
let yy = (by + r as i32).clamp(0, self.rows as i32 - 1) as usize;
for (c, d) in dst.iter_mut().enumerate() {
let xx = (bx + c as i32).clamp(0, self.stride as i32 - 1) as usize;
let s = plane[yy * self.stride + xx];
*d = if first { s } else { ((*d as u32 + s as u32 + 1) >> 1) as u16 };
}
}
}
first = false;
}
}
}
-265
View File
@@ -1,265 +0,0 @@
//! Parameter sets (7.3.2.1 VPS, 7.3.2.2 SPS with E.2.1 VUI, 7.3.2.3 PPS), profile_tier_level (7.3.3),
//! level selection (Annex A, Table A.8) and the `hvcC` record (ISO/IEC 14496-15 §8.3.3.1).
use crate::bitstream::{BitWriter, NAL_PPS, NAL_SPS, NAL_VPS, nal_unit};
/// Fixed coding structure of the encoder.
pub const LOG2_CTB: u32 = 6;
pub const LOG2_MIN_CB: u32 = 3;
pub const LOG2_MIN_TB: u32 = 2;
pub const LOG2_MAX_TB: u32 = 5;
pub const LOG2_MAX_POC_LSB: u32 = 8;
/// MaxNumMergeCand.
pub const MAX_MERGE_CAND: usize = 5;
/// Sequence-level settings shared by the parameter-set writers.
#[derive(Clone, Debug)]
pub struct SeqParams {
/// Coded (padded) size, multiples of the minimum CB size.
pub coded_width: u32,
pub coded_height: u32,
/// Output (cropped) size.
pub width: u32,
pub height: u32,
pub bit_depth: u32,
pub profile_idc: u8,
pub level_idc: u8,
pub full_range: bool,
pub colour_primaries: u8,
pub transfer_characteristics: u8,
pub matrix_coeffs: u8,
pub fps_num: u32,
pub fps_den: u32,
}
/// (level_idc, MaxLumaPs, MaxLumaSr, MaxBR main tier in kbit/s) of Table A.8 (and A.9 for luma rates).
const LEVELS: [(u8, u64, u64, u64); 13] = [
(30, 36_864, 552_960, 128),
(60, 122_880, 3_686_400, 1_500),
(63, 245_760, 7_372_800, 3_000),
(90, 552_960, 16_588_800, 6_000),
(93, 983_040, 33_177_600, 10_000),
(120, 2_228_224, 66_846_720, 12_000),
(123, 2_228_224, 133_693_440, 20_000),
(150, 8_912_896, 267_386_880, 25_000),
(153, 8_912_896, 534_773_760, 40_000),
(156, 8_912_896, 1_069_547_520, 60_000),
(180, 35_651_584, 1_069_547_520, 60_000),
(183, 35_651_584, 2_139_095_040, 120_000),
(186, 35_651_584, 4_278_190_080, 240_000),
];
/// Lowest level whose picture size, sample rate and (when known) bitrate limits fit.
pub fn choose_level(width: u32, height: u32, fps_num: u32, fps_den: u32, kbps: Option<u32>) -> u8 {
let ps = width as u64 * height as u64;
let sr = (ps as f64 * fps_num as f64 / fps_den.max(1) as f64).ceil() as u64;
for &(idc, max_ps, max_sr, max_br) in &LEVELS {
let max_dim = ((max_ps * 8) as f64).sqrt() as u64;
if ps <= max_ps && (width as u64) <= max_dim && (height as u64) <= max_dim && sr <= max_sr && kbps.is_none_or(|k| k as u64 <= max_br) {
return idc;
}
}
186
}
fn profile_tier_level(w: &mut BitWriter, p: &SeqParams) {
w.put(0, 2); // general_profile_space
w.put(0, 1); // general_tier_flag (Main tier)
w.put(p.profile_idc as u32, 5);
w.put(compat_flags(p.profile_idc), 32);
w.put(1, 1); // general_progressive_source_flag
w.put(0, 1); // general_interlaced_source_flag
w.put(0, 1); // general_non_packed_constraint_flag
w.put(1, 1); // general_frame_only_constraint_flag
w.put(0, 32); // general_reserved_zero_43bits ...
w.put(0, 11);
w.put(0, 1); // general_inbld_flag / reserved
w.put(p.level_idc as u32, 8);
// sps_max_sub_layers_minus1 == 0: no sub-layer flags
}
/// general_profile_compatibility_flag[j] as a 32-bit word (flag 0 is the MSB). A Main stream is also
/// Main 10 compatible.
fn compat_flags(profile_idc: u8) -> u32 {
let mut f = 1u32 << (31 - profile_idc as u32);
if profile_idc == 1 {
f |= 1 << (31 - 2);
}
f
}
pub fn vps(p: &SeqParams) -> Vec<u8> {
let mut w = BitWriter::new();
w.put(0, 4); // vps_video_parameter_set_id
w.put(1, 1); // vps_base_layer_internal_flag
w.put(1, 1); // vps_base_layer_available_flag
w.put(0, 6); // vps_max_layers_minus1
w.put(0, 3); // vps_max_sub_layers_minus1
w.put(1, 1); // vps_temporal_id_nesting_flag
w.put(0xffff, 16);
profile_tier_level(&mut w, p);
w.put(1, 1); // vps_sub_layer_ordering_info_present_flag
w.ue(1); // vps_max_dec_pic_buffering_minus1
w.ue(0); // vps_max_num_reorder_pics
w.ue(0); // vps_max_latency_increase_plus1
w.put(0, 6); // vps_max_layer_id
w.ue(0); // vps_num_layer_sets_minus1
w.put(0, 1); // vps_timing_info_present_flag
w.put(0, 1); // vps_extension_flag
w.trailing();
nal_unit(NAL_VPS, &w.into_bytes())
}
pub fn sps(p: &SeqParams) -> Vec<u8> {
let mut w = BitWriter::new();
w.put(0, 4); // sps_video_parameter_set_id
w.put(0, 3); // sps_max_sub_layers_minus1
w.put(1, 1); // sps_temporal_id_nesting_flag
profile_tier_level(&mut w, p);
w.ue(0); // sps_seq_parameter_set_id
w.ue(1); // chroma_format_idc 4:2:0
w.ue(p.coded_width);
w.ue(p.coded_height);
let crop = p.coded_width != p.width || p.coded_height != p.height;
w.flag(crop); // conformance_window_flag
if crop {
// offsets in chroma sample units (SubWidthC = SubHeightC = 2)
w.ue(0);
w.ue((p.coded_width - p.width) / 2);
w.ue(0);
w.ue((p.coded_height - p.height) / 2);
}
w.ue(p.bit_depth - 8); // bit_depth_luma_minus8
w.ue(p.bit_depth - 8); // bit_depth_chroma_minus8
w.ue(LOG2_MAX_POC_LSB - 4);
w.put(1, 1); // sps_sub_layer_ordering_info_present_flag
w.ue(1); // sps_max_dec_pic_buffering_minus1
w.ue(0); // sps_max_num_reorder_pics
w.ue(0); // sps_max_latency_increase_plus1
w.ue(LOG2_MIN_CB - 3);
w.ue(LOG2_CTB - LOG2_MIN_CB);
w.ue(LOG2_MIN_TB - 2);
w.ue(LOG2_MAX_TB - LOG2_MIN_TB);
w.ue(0); // max_transform_hierarchy_depth_inter
w.ue(0); // max_transform_hierarchy_depth_intra
w.put(0, 1); // scaling_list_enabled_flag
w.put(0, 1); // amp_enabled_flag
w.put(0, 1); // sample_adaptive_offset_enabled_flag
w.put(0, 1); // pcm_enabled_flag
w.ue(1); // num_short_term_ref_pic_sets
// st_ref_pic_set(0): one negative picture at delta POC -1, used by the current picture
w.ue(1); // num_negative_pics
w.ue(0); // num_positive_pics
w.ue(0); // delta_poc_s0_minus1
w.put(1, 1); // used_by_curr_pic_s0_flag
w.put(0, 1); // long_term_ref_pics_present_flag
w.put(0, 1); // sps_temporal_mvp_enabled_flag
w.put(1, 1); // strong_intra_smoothing_enabled_flag
w.put(1, 1); // vui_parameters_present_flag
vui(&mut w, p);
w.put(0, 1); // sps_extension_present_flag
w.trailing();
nal_unit(NAL_SPS, &w.into_bytes())
}
fn vui(w: &mut BitWriter, p: &SeqParams) {
w.put(0, 1); // aspect_ratio_info_present_flag
w.put(0, 1); // overscan_info_present_flag
w.put(1, 1); // video_signal_type_present_flag
w.put(5, 3); // video_format: unspecified
w.flag(p.full_range);
w.put(1, 1); // colour_description_present_flag
w.put(p.colour_primaries as u32, 8); // colour_primaries
w.put(p.transfer_characteristics as u32, 8); // transfer_characteristics
w.put(p.matrix_coeffs as u32, 8); // matrix_coeffs
w.put(0, 1); // chroma_loc_info_present_flag
w.put(0, 1); // neutral_chroma_indication_flag
w.put(0, 1); // field_seq_flag
w.put(0, 1); // frame_field_info_present_flag
w.put(0, 1); // default_display_window_flag
w.put(1, 1); // vui_timing_info_present_flag
w.put(p.fps_den, 32); // vui_num_units_in_tick
w.put(p.fps_num, 32); // vui_time_scale
w.put(0, 1); // vui_poc_proportional_to_timing_flag
w.put(0, 1); // vui_hrd_parameters_present_flag
w.put(0, 1); // bitstream_restriction_flag
}
pub fn pps() -> Vec<u8> {
let mut w = BitWriter::new();
w.ue(0); // pps_pic_parameter_set_id
w.ue(0); // pps_seq_parameter_set_id
w.put(0, 1); // dependent_slice_segments_enabled_flag
w.put(0, 1); // output_flag_present_flag
w.put(0, 3); // num_extra_slice_header_bits
w.put(1, 1); // sign_data_hiding_enabled_flag
w.put(0, 1); // cabac_init_present_flag
w.ue(0); // num_ref_idx_l0_default_active_minus1
w.ue(0); // num_ref_idx_l1_default_active_minus1
w.se(0); // init_qp_minus26
w.put(0, 1); // constrained_intra_pred_flag
w.put(0, 1); // transform_skip_enabled_flag
w.put(0, 1); // cu_qp_delta_enabled_flag
w.se(0); // pps_cb_qp_offset
w.se(0); // pps_cr_qp_offset
w.put(0, 1); // pps_slice_chroma_qp_offsets_present_flag
w.put(0, 1); // weighted_pred_flag
w.put(0, 1); // weighted_bipred_flag
w.put(0, 1); // transquant_bypass_enabled_flag
w.put(0, 1); // tiles_enabled_flag
w.put(0, 1); // entropy_coding_sync_enabled_flag
w.put(0, 1); // pps_loop_filter_across_slices_enabled_flag
w.put(1, 1); // deblocking_filter_control_present_flag
w.put(0, 1); // deblocking_filter_override_enabled_flag
w.put(0, 1); // pps_deblocking_filter_disabled_flag
w.se(0); // pps_beta_offset_div2
w.se(0); // pps_tc_offset_div2
w.put(0, 1); // pps_scaling_list_data_present_flag
w.put(0, 1); // lists_modification_present_flag
w.ue(0); // log2_parallel_merge_level_minus2
w.put(0, 1); // slice_segment_header_extension_present_flag
w.put(0, 1); // pps_extension_present_flag
w.trailing();
nal_unit(NAL_PPS, &w.into_bytes())
}
/// HEVCDecoderConfigurationRecord with one VPS, SPS and PPS (lengthSizeMinusOne = 3).
pub fn hvcc(p: &SeqParams, sets: &[Vec<u8>; 3]) -> Vec<u8> {
let mut o = vec![1u8]; // configurationVersion
o.push(p.profile_idc); // profile_space 0, tier 0, profile_idc
o.extend_from_slice(&compat_flags(p.profile_idc).to_be_bytes());
// general_constraint_indicator_flags (48 bits): progressive, interlaced, non_packed, frame_only
o.extend_from_slice(&[0x90, 0, 0, 0, 0, 0]);
o.push(p.level_idc);
o.extend_from_slice(&[0xf0, 0x00]); // reserved + min_spatial_segmentation_idc 0
o.push(0xfc); // reserved + parallelismType 0
o.push(0xfc | 1); // reserved + chroma_format_idc 1
o.push(0xf8 | (p.bit_depth - 8) as u8);
o.push(0xf8 | (p.bit_depth - 8) as u8);
o.extend_from_slice(&[0, 0]); // avgFrameRate unspecified
// constantFrameRate 0, numTemporalLayers 1, temporalIdNested 1, lengthSizeMinusOne 3
o.push((1 << 3) | (1 << 2) | 3);
o.push(3); // numOfArrays
for (set, ty) in sets.iter().zip([NAL_VPS, NAL_SPS, NAL_PPS]) {
o.push(0x80 | ty); // array_completeness 1
o.extend_from_slice(&1u16.to_be_bytes());
o.extend_from_slice(&(set.len() as u16).to_be_bytes());
o.extend_from_slice(set);
}
o
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn levels() {
assert_eq!(choose_level(1920, 1080, 30, 1, None), 120);
assert_eq!(choose_level(1920, 1080, 60, 1, None), 123);
assert_eq!(choose_level(3840, 2160, 30, 1, None), 150);
assert_eq!(choose_level(1280, 720, 30, 1, None), 93);
assert_eq!(choose_level(64, 64, 30, 1, None), 30);
assert_eq!(choose_level(1920, 1080, 30, 1, Some(15_000)), 123);
}
}
-236
View File
@@ -1,236 +0,0 @@
//! Constant tables of ITU-T H.265, mirrored from the first-party, spec-derived `filmcraft-hevc`
//! decoder (same organisation, MIT OR Apache-2.0): CABAC context layout and initValues (9.3.2.2),
//! rangeTabLPS / transIdx (Tables 9-52, 9-53), scans (6.5.3 - 6.5.5), transform matrices (8.6.4.2),
//! intra angles (Tables 8-5, 8-6), interpolation filters (8.5.3.3.3) and the chroma QP mapping (Table 8-10).
#![allow(dead_code)]
/// Table 9-52 (same values as H.264) rangeTabLPS[pStateIdx][qCodIRangeIdx].
#[rustfmt::skip]
pub static RANGE_TAB_LPS: [[u8; 4]; 64] = [
[128, 176, 208, 240], [128, 167, 197, 227], [128, 158, 187, 216], [123, 150, 178, 205],
[116, 142, 169, 195], [111, 135, 160, 185], [105, 128, 152, 175], [100, 122, 144, 166],
[95, 116, 137, 158], [90, 110, 130, 150], [85, 104, 123, 142], [81, 99, 117, 135],
[77, 94, 111, 128], [73, 89, 105, 122], [69, 85, 100, 116], [66, 80, 95, 110],
[62, 76, 90, 104], [59, 72, 86, 99], [56, 69, 81, 94], [53, 65, 77, 89],
[51, 62, 73, 85], [48, 59, 69, 80], [46, 56, 66, 76], [43, 53, 63, 72],
[41, 50, 59, 69], [39, 48, 56, 65], [37, 45, 54, 62], [35, 43, 51, 59],
[33, 41, 48, 56], [32, 39, 46, 53], [30, 37, 43, 50], [29, 35, 41, 48],
[27, 33, 39, 45], [26, 31, 37, 43], [24, 30, 35, 41], [23, 28, 33, 39],
[22, 27, 32, 37], [21, 26, 30, 35], [20, 24, 29, 33], [19, 23, 27, 31],
[18, 22, 26, 30], [17, 21, 25, 28], [16, 20, 23, 27], [15, 19, 22, 25],
[14, 18, 21, 24], [14, 17, 20, 23], [13, 16, 19, 22], [12, 15, 18, 21],
[12, 14, 17, 20], [11, 14, 16, 19], [11, 13, 15, 18], [10, 12, 15, 17],
[10, 12, 14, 16], [9, 11, 13, 15], [9, 11, 12, 14], [8, 10, 12, 14],
[8, 9, 11, 13], [7, 9, 11, 12], [7, 9, 10, 12], [7, 8, 10, 11],
[6, 8, 9, 11], [6, 7, 9, 10], [6, 7, 8, 9], [2, 2, 2, 2],
];
/// Table 9-53 transIdxLPS.
#[rustfmt::skip]
static TRANS_IDX_LPS: [u8; 64] = [
0, 0, 1, 2, 2, 4, 4, 5, 6, 7, 8, 9, 9, 11, 11, 12,
13, 13, 15, 15, 16, 16, 18, 18, 19, 19, 21, 21, 22, 22, 23, 24,
24, 25, 26, 26, 27, 27, 28, 29, 29, 30, 30, 30, 31, 32, 32, 33,
33, 33, 34, 34, 35, 35, 35, 36, 36, 36, 37, 37, 37, 38, 38, 63,
];
/// Table 9-53 transIdxMPS.
#[rustfmt::skip]
static TRANS_IDX_MPS: [u8; 64] = [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32,
33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 62, 63,
];
/// Combined state transition: index = (pStateIdx << 1 | valMPS) * 2 + bin_is_lps.
/// Each context is stored as `pStateIdx << 1 | valMPS`.
pub static NEXT_STATE: [[u8; 2]; 128] = {
let mut t = [[0u8; 2]; 128];
let mut s = 0;
while s < 128 {
let p = s >> 1;
let mps = s & 1;
// MPS path
t[s][0] = (TRANS_IDX_MPS[p] << 1) | mps as u8;
// LPS path
let new_mps = if p == 0 { 1 - mps } else { mps };
t[s][1] = (TRANS_IDX_LPS[p] << 1) | new_mps as u8;
s += 1;
}
t
};
/// Up-right diagonal scan (6.5.3) of a `N x N` block as (x, y) pairs.
const fn diag<const L: usize>(n: usize) -> [(u8, u8); L] {
let mut out = [(0u8, 0u8); L];
let mut i = 0;
let mut x: i32 = 0;
let mut y: i32 = 0;
while i < L {
while y >= 0 {
if (x as usize) < n && (y as usize) < n {
out[i] = (x as u8, y as u8);
i += 1;
}
y -= 1;
x += 1;
}
y = x;
x = 0;
}
out
}
/// Horizontal (6.5.4, `vertical == false`) or vertical (6.5.5) scan.
const fn hv<const L: usize>(n: usize, vertical: bool) -> [(u8, u8); L] {
let mut out = [(0u8, 0u8); L];
let mut i = 0;
while i < L {
let (a, b) = ((i % n) as u8, (i / n) as u8);
out[i] = if vertical { (b, a) } else { (a, b) };
i += 1;
}
out
}
pub static SCAN_1: [[(u8, u8); 1]; 3] = [[(0, 0)], [(0, 0)], [(0, 0)]];
pub static SCAN_2: [[(u8, u8); 4]; 3] = [diag::<4>(2), hv::<4>(2, false), hv::<4>(2, true)];
pub static SCAN_4: [[(u8, u8); 16]; 3] = [diag::<16>(4), hv::<16>(4, false), hv::<16>(4, true)];
pub static SCAN_8: [[(u8, u8); 64]; 3] = [diag::<64>(8), hv::<64>(8, false), hv::<64>(8, true)];
/// ScanOrder[log2BlockSize][scanIdx] (log2BlockSize 0..=3).
#[inline]
pub fn scan_order(log2: u32, scan_idx: usize) -> &'static [(u8, u8)] {
match log2 {
0 => &SCAN_1[scan_idx],
1 => &SCAN_2[scan_idx],
2 => &SCAN_4[scan_idx],
_ => &SCAN_8[scan_idx],
}
}
/// Up-right diagonal scan for log2 size 2 or 3.
pub fn scan_diag(log2: u32) -> &'static [(u8, u8)] {
scan_order(log2, 0)
}
/// Table 8-10: QpC as a function of qPi (ChromaArrayType 1).
#[inline]
pub fn qpc_420(qpi: i32) -> i32 {
if qpi < 30 {
qpi
} else if qpi > 43 {
qpi - 6
} else {
QPC_30_43[(qpi - 30) as usize] as i32
}
}
/// Table 9-50 ctxIdxMap for 4x4 sig_coeff_flag contexts.
pub static CTX_IDX_MAP: [u8; 16] = [0, 1, 4, 5, 2, 3, 4, 5, 6, 6, 8, 8, 7, 7, 8, 8];
/// levelScale (8-309).
pub static LEVEL_SCALE: [i32; 6] = [40, 45, 51, 57, 64, 72];
/// DST-VII 4x4 matrix (8.6.4.2, trType 1).
pub static DST_MATRIX: [[i8; 4]; 4] = [[29, 55, 74, 84], [74, 74, 0, -74], [84, -29, -74, 55], [55, -84, 74, -29]];
// CABAC context layout: offset of each syntax element in the context array (Table 9-4).
pub const SAO_MERGE: usize = 0;
pub const SAO_TYPE: usize = 1;
pub const SPLIT_CU: usize = 2;
pub const CU_TRANSQUANT_BYPASS: usize = 5;
pub const CU_SKIP: usize = 6;
pub const PRED_MODE: usize = 9;
pub const PART_MODE: usize = 10;
pub const PREV_INTRA_LUMA: usize = 14;
pub const INTRA_CHROMA: usize = 15;
pub const RQT_ROOT_CBF: usize = 16;
pub const MERGE_FLAG: usize = 17;
pub const MERGE_IDX: usize = 18;
pub const INTER_PRED_IDC: usize = 19;
pub const REF_IDX: usize = 24;
pub const MVP_FLAG: usize = 26;
pub const SPLIT_TRANSFORM: usize = 27;
pub const CBF_LUMA: usize = 30;
pub const CBF_CHROMA: usize = 32;
pub const ABS_MVD_GT0: usize = 37;
pub const ABS_MVD_GT1: usize = 38;
pub const CU_QP_DELTA_ABS: usize = 39;
pub const TRANSFORM_SKIP: usize = 41;
pub const LAST_X_PREFIX: usize = 43;
pub const LAST_Y_PREFIX: usize = 61;
pub const CODED_SUB_BLOCK: usize = 79;
pub const SIG_COEFF: usize = 83;
pub const GT1: usize = 127;
pub const GT2: usize = 151;
pub const EXPLICIT_RDPCM: usize = 157;
pub const EXPLICIT_RDPCM_DIR: usize = 159;
pub const CU_CHROMA_QP_OFFSET_FLAG: usize = 161;
pub const CU_CHROMA_QP_OFFSET_IDX: usize = 162;
pub const NUM_CTX: usize = 163;
/// initValue per initType (9.3.2.2).
pub static CABAC_INIT: [[u8; NUM_CTX]; 3] = [
[153, 200, 139, 141, 157, 154, 154, 154, 154, 154, 184, 154, 154, 154, 184, 63, 154, 154, 154, 154, 154, 154, 154, 154, 154, 154, 154, 153, 138, 138, 111, 141, 94, 138, 182, 154, 154, 154, 154, 154, 154, 139, 139, 110, 110, 124, 125, 140, 153, 125, 127, 140, 109, 111, 143, 127, 111, 79, 108, 123, 63, 110, 110, 124, 125, 140, 153, 125, 127, 140, 109, 111, 143, 127, 111, 79, 108, 123, 63, 91, 171, 134, 141, 111, 111, 125, 110, 110, 94, 124, 108, 124, 107, 125, 141, 179, 153, 125, 107, 125, 141, 179, 153, 125, 107, 125, 141, 179, 153, 125, 140, 139, 182, 182, 152, 136, 152, 136, 153, 136, 139, 111, 136, 139, 111, 141, 111, 140, 92, 137, 138, 140, 152, 138, 139, 153, 74, 149, 92, 139, 107, 122, 152, 140, 179, 166, 182, 140, 227, 122, 197, 138, 153, 136, 167, 152, 152, 154, 154, 154, 154, 154, 154],
[153, 185, 107, 139, 126, 154, 197, 185, 201, 149, 154, 139, 154, 154, 154, 152, 79, 110, 122, 95, 79, 63, 31, 31, 153, 153, 168, 124, 138, 94, 153, 111, 149, 107, 167, 154, 154, 140, 198, 154, 154, 139, 139, 125, 110, 94, 110, 95, 79, 125, 111, 110, 78, 110, 111, 111, 95, 94, 108, 123, 108, 125, 110, 94, 110, 95, 79, 125, 111, 110, 78, 110, 111, 111, 95, 94, 108, 123, 108, 121, 140, 61, 154, 155, 154, 139, 153, 139, 123, 123, 63, 153, 166, 183, 140, 136, 153, 154, 166, 183, 140, 136, 153, 154, 166, 183, 140, 136, 153, 154, 170, 153, 123, 123, 107, 121, 107, 121, 167, 151, 183, 140, 151, 183, 140, 140, 140, 154, 196, 196, 167, 154, 152, 167, 182, 182, 134, 149, 136, 153, 121, 136, 137, 169, 194, 166, 167, 154, 167, 137, 182, 107, 167, 91, 122, 107, 167, 139, 139, 139, 139, 154, 154],
[153, 160, 107, 139, 126, 154, 197, 185, 201, 134, 154, 139, 154, 154, 183, 152, 79, 154, 137, 95, 79, 63, 31, 31, 153, 153, 168, 224, 167, 122, 153, 111, 149, 92, 167, 154, 154, 169, 198, 154, 154, 139, 139, 125, 110, 124, 110, 95, 94, 125, 111, 111, 79, 125, 126, 111, 111, 79, 108, 123, 93, 125, 110, 124, 110, 95, 94, 125, 111, 111, 79, 125, 126, 111, 111, 79, 108, 123, 93, 121, 140, 61, 154, 170, 154, 139, 153, 139, 123, 123, 63, 124, 166, 183, 140, 136, 153, 154, 166, 183, 140, 136, 153, 154, 166, 183, 140, 136, 153, 154, 170, 153, 138, 138, 122, 121, 122, 121, 167, 151, 183, 140, 151, 183, 140, 140, 140, 154, 196, 167, 167, 154, 152, 167, 182, 182, 134, 149, 136, 153, 121, 136, 122, 169, 208, 166, 167, 154, 152, 167, 182, 107, 167, 91, 107, 107, 167, 139, 139, 139, 139, 154, 154],
];
/// Table 8-5: intraPredAngle for predModeIntra 0..34 (0 for planar / DC).
pub static INTRA_PRED_ANGLE: [i8; 35] = [0, 0, 32, 26, 21, 17, 13, 9, 5, 2, 0, -2, -5, -9, -13, -17, -21, -26, -32, -26, -21, -17, -13, -9, -5, -2, 0, 2, 5, 9, 13, 17, 21, 26, 32];
/// Table 8-6: invAngle for predModeIntra 11..25 (index = mode - 11).
pub static INV_ANGLE: [i16; 15] = [-4096, -1638, -910, -630, -482, -390, -315, -256, -315, -390, -482, -630, -910, -1638, -4096];
/// Table 8-10: QpC for qPi = 30..43 (qPi < 30: QpC = qPi; qPi > 43: QpC = qPi - 6).
pub static QPC_30_43: [u8; 14] = [29, 30, 31, 32, 33, 33, 34, 34, 35, 35, 36, 36, 37, 37];
/// Luma 8-tap interpolation filter fL[xFrac][k] (8-236..8-238), taps at offsets -3..4.
pub static LUMA_FILTER: [[i8; 8]; 4] = [[0, 0, 0, 64, 0, 0, 0, 0], [-1, 4, -10, 58, 17, -5, 1, 0], [-1, 4, -11, 40, 40, -11, 4, -1], [0, 1, -5, 17, 58, -10, 4, -1]];
/// Chroma 4-tap interpolation filter fC[xFrac][k] (8-255..8-261), taps at offsets -1..2.
pub static CHROMA_FILTER: [[i8; 4]; 8] = [[0, 64, 0, 0], [-2, 58, 10, -2], [-4, 54, 16, -2], [-6, 46, 28, -4], [-4, 36, 36, -4], [-4, 28, 46, -6], [-2, 16, 54, -4], [-2, 10, 58, -2]];
/// DCT matrix (8-319, 8-321): TRANS_MATRIX[n][m] = transMatrix[m][n] (row n = basis function).
pub static TRANS_MATRIX: [[i8; 32]; 32] = [
[64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64],
[90, 90, 88, 85, 82, 78, 73, 67, 61, 54, 46, 38, 31, 22, 13, 4, -4, -13, -22, -31, -38, -46, -54, -61, -67, -73, -78, -82, -85, -88, -90, -90],
[90, 87, 80, 70, 57, 43, 25, 9, -9, -25, -43, -57, -70, -80, -87, -90, -90, -87, -80, -70, -57, -43, -25, -9, 9, 25, 43, 57, 70, 80, 87, 90],
[90, 82, 67, 46, 22, -4, -31, -54, -73, -85, -90, -88, -78, -61, -38, -13, 13, 38, 61, 78, 88, 90, 85, 73, 54, 31, 4, -22, -46, -67, -82, -90],
[89, 75, 50, 18, -18, -50, -75, -89, -89, -75, -50, -18, 18, 50, 75, 89, 89, 75, 50, 18, -18, -50, -75, -89, -89, -75, -50, -18, 18, 50, 75, 89],
[88, 67, 31, -13, -54, -82, -90, -78, -46, -4, 38, 73, 90, 85, 61, 22, -22, -61, -85, -90, -73, -38, 4, 46, 78, 90, 82, 54, 13, -31, -67, -88],
[87, 57, 9, -43, -80, -90, -70, -25, 25, 70, 90, 80, 43, -9, -57, -87, -87, -57, -9, 43, 80, 90, 70, 25, -25, -70, -90, -80, -43, 9, 57, 87],
[85, 46, -13, -67, -90, -73, -22, 38, 82, 88, 54, -4, -61, -90, -78, -31, 31, 78, 90, 61, 4, -54, -88, -82, -38, 22, 73, 90, 67, 13, -46, -85],
[83, 36, -36, -83, -83, -36, 36, 83, 83, 36, -36, -83, -83, -36, 36, 83, 83, 36, -36, -83, -83, -36, 36, 83, 83, 36, -36, -83, -83, -36, 36, 83],
[82, 22, -54, -90, -61, 13, 78, 85, 31, -46, -90, -67, 4, 73, 88, 38, -38, -88, -73, -4, 67, 90, 46, -31, -85, -78, -13, 61, 90, 54, -22, -82],
[80, 9, -70, -87, -25, 57, 90, 43, -43, -90, -57, 25, 87, 70, -9, -80, -80, -9, 70, 87, 25, -57, -90, -43, 43, 90, 57, -25, -87, -70, 9, 80],
[78, -4, -82, -73, 13, 85, 67, -22, -88, -61, 31, 90, 54, -38, -90, -46, 46, 90, 38, -54, -90, -31, 61, 88, 22, -67, -85, -13, 73, 82, 4, -78],
[75, -18, -89, -50, 50, 89, 18, -75, -75, 18, 89, 50, -50, -89, -18, 75, 75, -18, -89, -50, 50, 89, 18, -75, -75, 18, 89, 50, -50, -89, -18, 75],
[73, -31, -90, -22, 78, 67, -38, -90, -13, 82, 61, -46, -88, -4, 85, 54, -54, -85, 4, 88, 46, -61, -82, 13, 90, 38, -67, -78, 22, 90, 31, -73],
[70, -43, -87, 9, 90, 25, -80, -57, 57, 80, -25, -90, -9, 87, 43, -70, -70, 43, 87, -9, -90, -25, 80, 57, -57, -80, 25, 90, 9, -87, -43, 70],
[67, -54, -78, 38, 85, -22, -90, 4, 90, 13, -88, -31, 82, 46, -73, -61, 61, 73, -46, -82, 31, 88, -13, -90, -4, 90, 22, -85, -38, 78, 54, -67],
[64, -64, -64, 64, 64, -64, -64, 64, 64, -64, -64, 64, 64, -64, -64, 64, 64, -64, -64, 64, 64, -64, -64, 64, 64, -64, -64, 64, 64, -64, -64, 64],
[61, -73, -46, 82, 31, -88, -13, 90, -4, -90, 22, 85, -38, -78, 54, 67, -67, -54, 78, 38, -85, -22, 90, 4, -90, 13, 88, -31, -82, 46, 73, -61],
[57, -80, -25, 90, -9, -87, 43, 70, -70, -43, 87, 9, -90, 25, 80, -57, -57, 80, 25, -90, 9, 87, -43, -70, 70, 43, -87, -9, 90, -25, -80, 57],
[54, -85, -4, 88, -46, -61, 82, 13, -90, 38, 67, -78, -22, 90, -31, -73, 73, 31, -90, 22, 78, -67, -38, 90, -13, -82, 61, 46, -88, 4, 85, -54],
[50, -89, 18, 75, -75, -18, 89, -50, -50, 89, -18, -75, 75, 18, -89, 50, 50, -89, 18, 75, -75, -18, 89, -50, -50, 89, -18, -75, 75, 18, -89, 50],
[46, -90, 38, 54, -90, 31, 61, -88, 22, 67, -85, 13, 73, -82, 4, 78, -78, -4, 82, -73, -13, 85, -67, -22, 88, -61, -31, 90, -54, -38, 90, -46],
[43, -90, 57, 25, -87, 70, 9, -80, 80, -9, -70, 87, -25, -57, 90, -43, -43, 90, -57, -25, 87, -70, -9, 80, -80, 9, 70, -87, 25, 57, -90, 43],
[38, -88, 73, -4, -67, 90, -46, -31, 85, -78, 13, 61, -90, 54, 22, -82, 82, -22, -54, 90, -61, -13, 78, -85, 31, 46, -90, 67, 4, -73, 88, -38],
[36, -83, 83, -36, -36, 83, -83, 36, 36, -83, 83, -36, -36, 83, -83, 36, 36, -83, 83, -36, -36, 83, -83, 36, 36, -83, 83, -36, -36, 83, -83, 36],
[31, -78, 90, -61, 4, 54, -88, 82, -38, -22, 73, -90, 67, -13, -46, 85, -85, 46, 13, -67, 90, -73, 22, 38, -82, 88, -54, -4, 61, -90, 78, -31],
[25, -70, 90, -80, 43, 9, -57, 87, -87, 57, -9, -43, 80, -90, 70, -25, -25, 70, -90, 80, -43, -9, 57, -87, 87, -57, 9, 43, -80, 90, -70, 25],
[22, -61, 85, -90, 73, -38, -4, 46, -78, 90, -82, 54, -13, -31, 67, -88, 88, -67, 31, 13, -54, 82, -90, 78, -46, 4, 38, -73, 90, -85, 61, -22],
[18, -50, 75, -89, 89, -75, 50, -18, -18, 50, -75, 89, -89, 75, -50, 18, 18, -50, 75, -89, 89, -75, 50, -18, -18, 50, -75, 89, -89, 75, -50, 18],
[13, -38, 61, -78, 88, -90, 85, -73, 54, -31, 4, 22, -46, 67, -82, 90, -90, 82, -67, 46, -22, -4, 31, -54, 73, -85, 90, -88, 78, -61, 38, -13],
[9, -25, 43, -57, 70, -80, 87, -90, 90, -87, 80, -70, 57, -43, 25, -9, -9, 25, -43, 57, -70, 80, -87, 90, -90, 87, -80, 70, -57, 43, -25, 9],
[4, -13, 22, -31, 38, -46, 54, -61, 67, -73, 78, -82, 85, -88, 90, -90, 90, -90, 88, -85, 82, -78, 73, -67, 61, -54, 46, -38, 31, -22, 13, -4],
];
/// Table 8-12: beta' for Q = 0..51.
pub static BETA_TABLE: [u8; 52] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64];
/// Table 8-12: tC' for Q = 0..53.
pub static TC_TABLE: [u8; 54] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 5, 5, 6, 6, 7, 8, 9, 10, 11, 13, 14, 16, 18, 20, 22, 24];
-328
View File
@@ -1,328 +0,0 @@
//! Forward transforms (encoder side, any integer approximation is allowed), quantisation, and the
//! normative scaling (8.6.3) and inverse transforms (8.6.4.2) the decoder applies. The inverse path
//! is exact integer arithmetic: the even/odd decomposition computes the same sums as the matrix
//! products of the specification.
use crate::tables::{DST_MATRIX, LEVEL_SCALE, TRANS_MATRIX};
#[inline]
fn m(n: usize, k: usize, i: usize) -> i32 {
// k-th basis function of the n-point DCT, sample i
TRANS_MATRIX[k * (32 / n)][i] as i32
}
/// 1-D forward DCT of `x` (length n) into `out`.
fn fdct1d(x: &[i32], out: &mut [i32], n: usize) {
if n <= 4 {
for k in 0..n {
let mut s = 0;
for i in 0..n {
s += m(n, k, i) * x[i];
}
out[k] = s;
}
return;
}
let h = n / 2;
let mut e = [0i32; 16];
let mut o = [0i32; 16];
for i in 0..h {
e[i] = x[i] + x[n - 1 - i];
o[i] = x[i] - x[n - 1 - i];
}
let mut ev = [0i32; 16];
fdct1d(&e[..h], &mut ev[..h], h);
for k in 0..h {
out[2 * k] = ev[k];
let kk = 2 * k + 1;
let mut s = 0;
for i in 0..h {
s += m(n, kk, i) * o[i];
}
out[kk] = s;
}
}
/// 1-D inverse DCT: x[i] = sum_k M[k][i] * c[k].
fn idct1d(c: &[i32], out: &mut [i32], n: usize) {
if n <= 4 {
for i in 0..n {
let mut s = 0;
for k in 0..n {
s += m(n, k, i) * c[k];
}
out[i] = s;
}
return;
}
let h = n / 2;
let mut ce = [0i32; 16];
for k in 0..h {
ce[k] = c[2 * k];
}
let mut e = [0i32; 16];
idct1d(&ce[..h], &mut e[..h], h);
for i in 0..h {
let mut o = 0;
let mut k = 1;
while k < n {
let v = c[k];
if v != 0 {
o += m(n, k, i) * v;
}
k += 2;
}
out[i] = e[i] + o;
out[n - 1 - i] = e[i] - o;
}
}
fn fdst1d(x: &[i32], out: &mut [i32]) {
for k in 0..4 {
out[k] = (0..4).map(|i| DST_MATRIX[k][i] as i32 * x[i]).sum();
}
}
fn idst1d(c: &[i32], out: &mut [i32]) {
for i in 0..4 {
out[i] = (0..4).map(|k| DST_MATRIX[k][i] as i32 * c[k]).sum();
}
}
/// Forward 2-D transform of the n x n residual `r` (row-major) into `c`.
pub fn forward(r: &[i32], c: &mut [i32], n: usize, dst: bool, bit_depth: u32) {
let log2 = n.trailing_zeros();
let shift1 = log2 + bit_depth - 9;
let shift2 = log2 + 6;
let (r1, r2) = (1i32 << (shift1 - 1), 1i32 << (shift2 - 1));
let mut tmp = vec![0i32; n * n];
let mut out = [0i32; 32];
// rows (horizontal frequencies)
for y in 0..n {
let row = &r[y * n..y * n + n];
if dst {
fdst1d(row, &mut out);
} else {
fdct1d(row, &mut out, n);
}
for k in 0..n {
tmp[k * n + y] = (out[k] + r1) >> shift1; // transposed: tmp[kx][y]
}
}
// columns
let mut col = [0i32; 32];
for kx in 0..n {
col[..n].copy_from_slice(&tmp[kx * n..kx * n + n]);
if dst {
fdst1d(&col, &mut out);
} else {
fdct1d(&col, &mut out, n);
}
for ky in 0..n {
c[ky * n + kx] = (out[ky] + r2) >> shift2;
}
}
}
/// Inverse 2-D transform (8.6.4.2) of scaled coefficients `d` in place, producing residuals.
pub fn inverse(d: &mut [i32], n: usize, dst: bool, bit_depth: u32) {
let bd_shift = 20 - bit_depth;
let mut tmp = vec![0i32; n * n];
let mut col = [0i32; 32];
let mut out = [0i32; 32];
// max non-zero row, to skip empty work
let mut nz_cols = [false; 32];
for y in 0..n {
for x in 0..n {
if d[y * n + x] != 0 {
nz_cols[x] = true;
}
}
}
// 1. columns
for x in 0..n {
if !nz_cols[x] {
continue; // tmp column stays zero
}
for j in 0..n {
col[j] = d[j * n + x];
}
if dst {
idst1d(&col, &mut out);
} else {
idct1d(&col, &mut out, n);
}
for y in 0..n {
tmp[y * n + x] = ((out[y] + 64) >> 7).clamp(-32768, 32767);
}
}
// 2. rows
let round = 1 << (bd_shift - 1);
for y in 0..n {
let row = &tmp[y * n..y * n + n];
if dst {
idst1d(row, &mut out);
} else {
idct1d(row, &mut out, n);
}
for x in 0..n {
d[y * n + x] = (out[x] + round) >> bd_shift;
}
}
}
const QUANT_SCALE: [i64; 6] = [26214, 23302, 20560, 18396, 16384, 14564];
/// Quantise transform coefficients `c` into levels `l` with a dead-zone rounding offset
/// (`intra`: 1/3, otherwise 1/6). `qp` includes QpBdOffset. Returns the number of non-zero levels.
pub fn quantize(c: &[i32], l: &mut [i32], n: usize, qp: i32, intra: bool, bit_depth: u32) -> usize {
let log2 = n.trailing_zeros() as i32;
let tshift = 15 - bit_depth as i32 - log2;
let qbits = 14 + qp / 6 + tshift;
let scale = QUANT_SCALE[(qp % 6) as usize];
let offset = (if intra { 171i64 } else { 85 }) << (qbits - 9);
let mut nz = 0;
for i in 0..n * n {
let v = c[i] as i64;
let a = ((v.abs() * scale + offset) >> qbits).min(32767);
if a != 0 {
nz += 1;
}
l[i] = if v < 0 { -(a as i32) } else { a as i32 };
}
nz
}
/// Sign data hiding (7.3.8.11 signHidden): in every 4x4 sub-block whose first and last non-zero
/// coefficients (in scan order) are more than 3 positions apart, the sign of the first one is not
/// coded but inferred from the parity of the sum of absolute levels. Fix the parity where needed by
/// the +-1 level change that adds the least quantisation error, without moving the first / last
/// non-zero positions.
pub fn sign_hiding(c: &[i32], l: &mut [i32], log2: u32, scan_idx: usize, qp: i32, bit_depth: u32) {
use crate::tables::{SCAN_4, scan_order};
let n = 1usize << log2;
let tshift = 15 - bit_depth as i32 - log2 as i32;
let qbits = 14 + qp / 6 + tshift;
let scale = QUANT_SCALE[(qp % 6) as usize];
let sb_scan = scan_order(log2 - 2, scan_idx);
let pos = &SCAN_4[scan_idx];
for &(xs, ys) in sb_scan {
let idx = |p: usize| (ys as usize * 4 + pos[p].1 as usize) * n + xs as usize * 4 + pos[p].0 as usize;
let (Some(first), Some(last)) = ((0..16).find(|&p| l[idx(p)] != 0), (0..16).rev().find(|&p| l[idx(p)] != 0)) else { continue };
if last - first <= 3 {
continue;
}
let sum: i32 = (0..16).map(|p| l[idx(p)].abs()).sum();
let negative = l[idx(first)] < 0;
if negative == (sum & 1 == 1) {
continue;
}
// cost of +-1 changes in 1/256 units of quantisation error
let mut best: Option<(i64, usize, i32)> = None;
for p in first..=last {
let i = idx(p);
let q = ((c[i] as i64).abs() * scale) >> (qbits - 8);
let a = l[i].abs() as i64;
let err = |lv: i64| (q - (lv << 8)).abs();
let mut consider = |cost: i64, d: i32| {
if best.is_none_or(|b| cost < b.0) {
best = Some((cost, i, d));
}
};
if a < 32767 && (a > 0 || (p > first && p < last)) {
consider(err(a + 1) - err(a), 1);
}
if a > 1 || (a == 1 && p > first && p < last) {
consider(err(a - 1) - err(a), -1);
}
}
if let Some((_, i, d)) = best {
let a = l[i].abs() + d;
l[i] = if c[i] < 0 { -a } else { a };
}
}
}
/// Scaling process (8.6.2 / 8.6.3, flat scaling matrix): levels to scaled coefficients.
pub fn dequantize(l: &[i32], d: &mut [i32], n: usize, qp: i32, bit_depth: u32) {
let log2 = n.trailing_zeros();
let bd_shift = bit_depth + log2 - 5;
let round = 1i64 << (bd_shift - 1);
let scale = (LEVEL_SCALE[(qp % 6) as usize] as i64) << (qp / 6);
for i in 0..n * n {
let v = l[i];
d[i] = if v == 0 { 0 } else { ((v as i64 * 16 * scale + round) >> bd_shift).clamp(-32768, 32767) as i32 };
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Direct matrix form of the inverse transform, as written in the specification.
fn inverse_ref(c: &mut [i32], n: usize, dst: bool, bd: u32) {
let mut tmp = vec![0i32; n * n];
let step = 32 / n;
for x in 0..n {
for y in 0..n {
let mut s = 0i32;
for j in 0..n {
let m = if dst { DST_MATRIX[j][y] as i32 } else { TRANS_MATRIX[j * step][y] as i32 };
s += m * c[j * n + x];
}
tmp[y * n + x] = ((s + 64) >> 7).clamp(-32768, 32767);
}
}
let bd_shift = 20 - bd;
for y in 0..n {
for x in 0..n {
let mut s = 0i32;
for j in 0..n {
let m = if dst { DST_MATRIX[j][x] as i32 } else { TRANS_MATRIX[j * step][x] as i32 };
s += m * tmp[y * n + j];
}
c[y * n + x] = (s + (1 << (bd_shift - 1))) >> bd_shift;
}
}
}
#[test]
fn inverse_matches_matrix_form() {
let mut seed = 7u32;
for &(n, dst) in &[(4usize, true), (4, false), (8, false), (16, false), (32, false)] {
for _ in 0..20 {
let mut c = vec![0i32; n * n];
for v in c.iter_mut() {
seed = seed.wrapping_mul(1664525).wrapping_add(1013904223);
if (seed >> 24).is_multiple_of(3) {
*v = ((seed >> 8) % 2001) as i32 - 1000;
}
}
let mut a = c.clone();
let mut b = c.clone();
inverse(&mut a, n, dst, 8);
inverse_ref(&mut b, n, dst, 8);
assert_eq!(a, b, "n {n} dst {dst}");
}
}
}
#[test]
fn round_trip_is_close() {
for &(n, dst) in &[(4usize, true), (8, false), (32, false)] {
for bd in [8u32, 10] {
let r: Vec<i32> = (0..n * n).map(|i| ((i * 37 + i / n * 11) % 61) as i32 - 30).collect();
let mut c = vec![0; n * n];
forward(&r, &mut c, n, dst, bd);
let mut l = vec![0; n * n];
let qp = 4;
quantize(&c, &mut l, n, qp, true, bd);
let mut d = vec![0; n * n];
dequantize(&l, &mut d, n, qp, bd);
inverse(&mut d, n, dst, bd);
let err: i32 = r.iter().zip(&d).map(|(a, b)| (a - b).abs()).max().unwrap();
assert!(err <= 2, "n {n} bd {bd} err {err}");
}
}
}
}
+4 -1
View File
@@ -1,6 +1,6 @@
//! A fully wired [`Session`]: footage decoding through `effectcraft-media` (FilmCraft's codecs),
//! the media importer, the expression engine, JavaScript scripting (`effectcraft-script`) and
//! Render Queue export through `effectcraft-export` (FilmCraft's encoders). Frontends (desktop,
//! Render Queue export through `effectcraft-export` (craft-libs' encoders). Frontends (desktop,
//! CLI, MCP, web) start here.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
@@ -20,6 +20,9 @@ impl Importer for MediaImporter {
fn probe(&self, path: &str) -> Result<Footage, String> {
effectcraft_media::probe(path).map_err(|e| e.to_string())
}
fn probe_noting(&self, path: &str) -> Result<(Footage, Option<String>), String> {
effectcraft_media::probe_noting(path).map_err(|e| e.to_string())
}
}
/// Render Queue export via `effectcraft-export`: to the file system, or to `sink` (the web app
+2 -3
View File
@@ -22,9 +22,8 @@ effectcraft-pdf = { workspace = true }
effectcraft-model = { workspace = true }
filmcraft-codecs = { workspace = true }
filmcraft-media = { workspace = true }
filmcraft-aac = { workspace = true }
filmcraft-isobmff = { workspace = true }
filmcraft-matroska = { workspace = true }
craft-audio = { workspace = true }
craft-media = { workspace = true }
filmcraft-mpegts = { workspace = true }
filmcraft-frame = { workspace = true }
filmcraft-color = { workspace = true }
+11 -19
View File
@@ -6,7 +6,7 @@
use std::io;
use filmcraft_aac::AudioSpecificConfig;
use craft_audio::aac::AudioSpecificConfig;
use filmcraft_media::ByteReader;
/// How far into an MPEG TS / PS file the audio streams are looked for: the stream is indexed as
@@ -34,15 +34,16 @@ pub(crate) fn config(header: Option<&[u8]>, file: Option<&dyn ByteReader>) -> Op
/// are in its fragments, not the `moov`).
fn mp4(header: &[u8], file: Option<&dyn ByteReader>) -> Option<Vec<u8>> {
let mp4 = match file {
Some(f) => filmcraft_isobmff::open(Head(f, f.len())),
None => filmcraft_isobmff::open(header),
Some(f) => craft_media::isobmff::open(Head(f, f.len())),
None => craft_media::isobmff::open(header),
};
let mp4 = mp4.ok()?;
let playable =
|t: &&filmcraft_isobmff::Track| t.kind == filmcraft_isobmff::TrackKind::Audio && !t.samples.is_empty() && !t.entries.is_empty() && t.timescale > 0;
let playable = |t: &&craft_media::isobmff::Track| {
t.kind == craft_media::isobmff::TrackKind::Audio && !t.samples.is_empty() && !t.entries.is_empty() && t.timescale > 0
};
let track = mp4.tracks.iter().find(playable)?;
match &track.entries.first()?.codec {
filmcraft_isobmff::CodecConfig::Aac(a) => Some(a.asc.clone()),
craft_media::isobmff::CodecConfig::Aac(a) => Some(a.asc.clone()),
_ => None,
}
}
@@ -50,9 +51,9 @@ fn mp4(header: &[u8], file: Option<&dyn ByteReader>) -> Option<Vec<u8>> {
/// The track FilmCraft's Matroska source plays: the first audio track with frames, found by
/// indexing the clusters as that source does.
fn matroska(file: &dyn ByteReader) -> Option<Vec<u8>> {
let mkv = filmcraft_matroska::open(Head(file, file.len())).ok()?;
match &mkv.tracks.iter().find(|t| t.kind == filmcraft_matroska::TrackKind::Audio && !t.samples.is_empty())?.codec {
filmcraft_matroska::Codec::Aac { asc } => Some(asc.clone()),
let mkv = craft_media::matroska::open(Head(file, file.len())).ok()?;
match &mkv.tracks.iter().find(|t| t.kind == craft_media::matroska::TrackKind::Audio && !t.samples.is_empty())?.codec {
craft_media::matroska::Codec::Aac { asc } => Some(asc.clone()),
_ => None,
}
}
@@ -88,16 +89,7 @@ impl Head<'_> {
}
}
impl filmcraft_isobmff::ByteSource for Head<'_> {
fn len(&self) -> u64 {
self.1
}
fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> {
self.read(offset, buf)
}
}
impl filmcraft_matroska::ByteSource for Head<'_> {
impl craft_media::ByteSource for Head<'_> {
fn len(&self) -> u64 {
self.1
}
+2 -2
View File
@@ -19,7 +19,7 @@
use std::f32::consts::FRAC_1_SQRT_2;
use std::sync::Arc;
use filmcraft_aac::{AudioSpecificConfig, ProgramConfig};
use craft_audio::aac::{AudioSpecificConfig, ProgramConfig};
/// A source channel's contribution to the left and right outputs, before normalisation.
pub type Pair = [f32; 2];
@@ -185,7 +185,7 @@ mod tests {
}
}
/// AudioSpecificConfigs as ffmpeg 8.1 and FilmCraft's encoder write them (48 kHz AAC-LC).
/// AudioSpecificConfigs as ffmpeg 8.1 and craft-audio's encoder write them (48 kHz AAC-LC).
const PCE_FFMPEG_61: &str = "118004c848002000c4400d4c61766336322e32382e31303256e500";
const PCE_FILMCRAFT_61: &str = "118004c845000108840000";
+37 -1
View File
@@ -93,7 +93,18 @@ impl Anim {
if crate::webp_anim::is_webp(bytes) {
return crate::webp_anim::load(bytes);
}
let dec = GifDecoder::new(Cursor::new(bytes)).map_err(|e| MediaError::Decode(format!("GIF: {e}")))?;
let mut dec = GifDecoder::new(Cursor::new(bytes)).map_err(|e| MediaError::Decode(format!("GIF: {e}")))?;
// A frame may be far larger than the canvas, and the decoder allocates its buffer before
// decoding it: no single buffer may pass what all the frames may hold.
let mut limits = image::Limits::no_limits();
limits.max_alloc = Some(MAX_BYTES as u64);
image::ImageDecoder::set_limits(&mut dec, limits).map_err(|e| MediaError::Decode(format!("GIF: {e}")))?;
// The decoder allocates the full logical canvas for the first frame, however small the
// frames themselves are: check it before decoding any.
let (w, h) = image::ImageDecoder::dimensions(&dec);
if u64::from(w) * u64::from(h) * 4 > MAX_BYTES as u64 {
return Err(MediaError::Unsupported(format!("GIF canvas of {w}×{h} is too large to hold in memory")));
}
let (mut frames, mut starts) = (Vec::new(), Vec::new());
let (mut at, mut size) = (0i64, 0usize);
for frame in dec.into_frames() {
@@ -179,6 +190,17 @@ mod tests {
assert_eq!(colour_at(&pool, &f, 5.0), [0.0, 0.0, 1.0]);
}
#[test]
fn a_frame_far_larger_than_the_canvas_is_refused_before_it_is_allocated() {
// A 1×1 canvas and a 20000×20000 frame (1.6 GB of RGBA); the data itself is not there.
let mut bytes = b"GIF89a".to_vec();
// (a two-entry global colour table, so the frame gets as far as its buffer)
bytes.extend([1, 0, 1, 0, 0x80, 0, 0, 0, 0, 0, 255, 255, 255]);
bytes.extend([0x2c, 0, 0, 0, 0, 0x20, 0x4e, 0x20, 0x4e, 0, 2, 0]);
let e = crate::gif_anim::Anim::load(&bytes).err().expect("refused").to_string();
assert!(e.to_lowercase().contains("memory"), "{e}");
}
#[test]
fn a_zero_delay_is_ten_hundredths_like_in_browsers() {
let f = probe_bytes("a.gif", gif(&[(RED, 0), (GREEN, 1)]).into()).unwrap();
@@ -212,4 +234,18 @@ mod tests {
assert!(pool.frame_at(&f, Tick::ZERO).is_err());
let _ = probe_bytes("a.gif", bytes.into());
}
#[test]
fn a_huge_canvas_is_refused_before_decoding() {
// A 65535×65535 logical screen (16 GiB of RGBA) holding one 1×1 frame.
let mut out = Vec::new();
{
let mut enc = gif::Encoder::new(&mut out, u16::MAX, u16::MAX, &[]).unwrap();
for _ in 0..2 {
enc.write_frame(&gif::Frame::from_rgb(1, 1, &RED)).unwrap();
}
}
let e = super::Anim::load(&out).err().unwrap();
assert!(e.to_string().contains("too large"), "{e}");
}
}
Loaded 100 of 155 files, more files were not shown because too many files have changed in this diff. Show more