Merge branch 'main' into feat/amf-and-av1-encoder

This commit is contained in:
FredApps
2026-12-02 10:17:58 +01:00
committed by GitHub
180 changed files with 11150 additions and 2554 deletions
+15 -5
View File
@@ -4,10 +4,10 @@
"repository_id": 1398091865,
"producer_workflow_id": 430201213,
"producer_workflow_path": ".github/workflows/nightly.yml",
"producer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"producer_tooling_revision": "main",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main",
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
"signer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"signer_tooling_revision": "main",
"release_branch": "nightly-signer",
"manual_actors": [
"bflatastic",
@@ -83,7 +83,9 @@
}
},
"max_artifact_bytes": 2147483648,
"automatic_signer_actors": [],
"automatic_signer_actors": [
"github-actions[bot]"
],
"platforms": {
"windows-x86_64": {
"unsigned_artifact_name": "nightly-unsigned-windows-x86_64",
@@ -95,7 +97,15 @@
"unsigned_artifact_name": "nightly-unsigned-linux-x86_64",
"trust": {
"fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"
}
},
"package_formats": [
"appimage",
"arch",
"deb",
"flatpak",
"oci",
"rpm"
]
},
"macos-aarch64": {
"unsigned_artifact_name": "nightly-unsigned-macos-aarch64",
+9 -9
View File
@@ -40,12 +40,12 @@ jobs:
with:
persist-credentials: false
- name: Check out craft-fonts
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@f5141455aac7b2eb4708aa259d8ffcdf10fde939
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@main
with:
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@f5141455aac7b2eb4708aa259d8ffcdf10fde939
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@main
- id: rust
uses: storytold/craft-common-actions/actions/rust-channel@f5141455aac7b2eb4708aa259d8ffcdf10fde939
uses: storytold/craft-common-actions/actions/rust-channel@main
with:
targets: x86_64-pc-windows-msvc
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
@@ -115,12 +115,12 @@ jobs:
with:
persist-credentials: false
- name: Check out craft-fonts
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@f5141455aac7b2eb4708aa259d8ffcdf10fde939
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@main
with:
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@f5141455aac7b2eb4708aa259d8ffcdf10fde939
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@main
- id: rust
uses: storytold/craft-common-actions/actions/rust-channel@f5141455aac7b2eb4708aa259d8ffcdf10fde939
uses: storytold/craft-common-actions/actions/rust-channel@main
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
with:
toolchain: ${{ steps.rust.outputs.toolchain }}
@@ -178,12 +178,12 @@ jobs:
with:
persist-credentials: false
- name: Check out craft-fonts
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@f5141455aac7b2eb4708aa259d8ffcdf10fde939
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@main
with:
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@f5141455aac7b2eb4708aa259d8ffcdf10fde939
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@main
- id: rust
uses: storytold/craft-common-actions/actions/rust-channel@f5141455aac7b2eb4708aa259d8ffcdf10fde939
uses: storytold/craft-common-actions/actions/rust-channel@main
with:
targets: aarch64-apple-darwin
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
+1 -2
View File
@@ -11,9 +11,8 @@ permissions: {}
jobs:
dispatch:
# SOURCE PREPARATION: literal off until immutable shared tooling and policy qualification.
if: >-
false && github.repository == 'storytold/filmcraft' &&
github.repository == 'storytold/filmcraft' &&
github.event_name == 'workflow_run'
runs-on: ubuntu-latest
timeout-minutes: 5
+16 -2
View File
@@ -34,12 +34,26 @@ jobs:
checks: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@main
with:
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
tooling-revision: main
app-name: filmcraft
producer_run_id: ${{ inputs.producer_run_id }}
producer_run_attempt: ${{ inputs.producer_run_attempt }}
secrets:
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
# No secrets: inherit or raw platform values in this caller. Only the isolated native
# callee job may bind the existing release environment (which trusts release and
# nightly-signer) and export keys in its signing step.
+6 -4
View File
@@ -1,8 +1,9 @@
name: FilmCraft unsigned nightly
# Enabled for supervised manual runs by the reviewed manual actors only; no schedule yet.
# A later explicit opt-in may add a cadence (and a scheduled completion dispatcher with it).
# Automated daily schedule (03:00 UTC) plus supervised manual runs by the reviewed manual actors.
on:
schedule:
- cron: '0 3 * * *'
workflow_dispatch:
permissions:
@@ -22,9 +23,9 @@ jobs:
actions: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main
with:
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
tooling-revision: main
app-name: filmcraft
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
@@ -32,3 +33,4 @@ jobs:
# craft-common-actions main commit that merged the exact-analysis admission (#371, after #370,
# #369 and #364).
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
linux-package-formats: '["deb","rpm","appimage","flatpak","oci","arch"]'
+20
View File
@@ -0,0 +1,20 @@
name: Notify Services on Release Change
on:
release:
types:
- published
- unpublished
- created
- edited
- deleted
- prereleased
- released
permissions: {}
jobs:
notify:
uses: storytold/craft-common-actions/.github/workflows/notify-services.yml@main
secrets:
ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }}
+1 -1
View File
@@ -10,7 +10,7 @@ permissions:
contents: read
concurrency:
group: sonarcloud-${{ github.ref }}
group: ${{ github.ref == 'refs/heads/main' && format('sonarcloud-main-{0}', github.sha) || format('sonarcloud-{0}', github.ref) }}
# A push to main is the run that publishes coverage; superseded runs there would never finish.
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
+1 -1
View File
@@ -67,7 +67,7 @@ FilmCraft is a Rust video editor (workspace edition 2024). Run it with `cargo ru
- **Layout:** `crates/*` and `apps/*` (globbed), `xtask/`. Layers L0 to L5 are in `docs/architecture.md` §1; nothing below L5 depends on egui, eframe, winit, rfd or cpal. New crates include `[lints] workspace = true`; production crate roots declare their lint attributes before modules.
- **Checks for the crates you changed:** `cargo fmt --check`; `cargo clippy -p <crate> --all-targets -- -D warnings`; `cargo nextest run -p <crate>` (or `cargo test -p <crate>`); `cargo xtask layers` for dependency changes; `cargo xtask assets` for asset changes; `cargo xtask wasm` for L0 to L4, `filmcraft-ui-egui` and `filmcraft-web` (wasm32). `cargo xtask ci` runs all of them. Set `CRAFT_FONTS_DIR` too for font code.
- **`unsafe`:** the workspace sets `unsafe_code = "forbid"`. `crates/platform` is the one crate that uses it (OS media FFI; `unsafe_code = "deny"`, `#[allow(unsafe_code)]` on its FFI modules only; `docs/adr/0001-platform-ffi.md`).
- **`unsafe`:** the workspace sets `unsafe_code = "forbid"`. `crates/platform` is the one crate that uses it (OS media FFI, and on macOS lowering the scheduling priority of background job threads, `docs/adr/0002-background-thread-priority.md`; `unsafe_code = "deny"`, `#[allow(unsafe_code)]` on its FFI modules only; `docs/adr/0001-platform-ffi.md`).
- **Panic net:** the hook in `crates/ui-egui/src/crash.rs` logs panics; the UI pass runs under `catch_unwind`; `panic = "unwind"`. Clean crates deny the panicking lints; `clippy.toml` allows them in tests.
- **Time:** all edit math uses `filmcraft_time::Tick` (254 016 000 000 per second).
- **Commands and automation:** commands live in `crates/engine`; UI, CLI, control channel and MCP dispatch by command id. Each interactive widget registers an automation id.
Generated
+57 -36
View File
@@ -1419,7 +1419,7 @@ dependencies = [
[[package]]
name = "craft-fcproj-format"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=3af2280ee3434a2c860012df2f440652621c2c81#3af2280ee3434a2c860012df2f440652621c2c81"
source = "git+https://github.com/storytold/craft-libs?rev=33fb95c7189686cab2fc0a6dbc1882ce7237e2c2#33fb95c7189686cab2fc0a6dbc1882ce7237e2c2"
dependencies = [
"serde",
"serde_json",
@@ -1560,6 +1560,14 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-nightly"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24#1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24"
dependencies = [
"winsafe",
]
[[package]]
name = "craft-pdf"
version = "0.1.0"
@@ -2845,12 +2853,13 @@ dependencies = [
[[package]]
name = "filmcraft"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"arboard",
"chrono",
"cpal",
"craft-control-protocol",
"craft-nightly",
"craft-update",
"eframe",
"egui",
@@ -2884,14 +2893,14 @@ dependencies = [
[[package]]
name = "filmcraft-audio-dsp"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"filmcraft-testkit",
]
[[package]]
name = "filmcraft-automation"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"base64",
"craft-control-protocol",
@@ -2910,14 +2919,14 @@ dependencies = [
[[package]]
name = "filmcraft-bitstream"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"craft-media",
]
[[package]]
name = "filmcraft-captions"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"craft-captions",
"filmcraft-color",
@@ -2928,14 +2937,14 @@ dependencies = [
[[package]]
name = "filmcraft-cfb"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"craft-cfb",
]
[[package]]
name = "filmcraft-cli"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"craft-media",
"filmcraft-automation",
@@ -2956,7 +2965,7 @@ dependencies = [
[[package]]
name = "filmcraft-codecs"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"craft-audio",
"craft-jpeg",
@@ -2965,6 +2974,7 @@ dependencies = [
"craft-y4m",
"filmcraft-bitstream",
"filmcraft-color",
"filmcraft-dng",
"filmcraft-frame",
"filmcraft-isobmff",
"filmcraft-matroska",
@@ -2982,7 +2992,7 @@ dependencies = [
[[package]]
name = "filmcraft-color"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"proptest",
"serde",
@@ -2990,7 +3000,7 @@ dependencies = [
[[package]]
name = "filmcraft-dng"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"craft-raw",
"craft-tiff",
@@ -3004,7 +3014,7 @@ dependencies = [
[[package]]
name = "filmcraft-edit"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"filmcraft-geom",
"filmcraft-media",
@@ -3017,7 +3027,7 @@ dependencies = [
[[package]]
name = "filmcraft-engine"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"chrono",
"craft-docpath",
@@ -3045,6 +3055,7 @@ dependencies = [
"filmcraft-tts",
"image",
"log",
"rayon",
"roxmltree",
"serde",
"serde_json",
@@ -3055,7 +3066,7 @@ dependencies = [
[[package]]
name = "filmcraft-export"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"craft-audio",
"craft-dpx",
@@ -3090,21 +3101,24 @@ dependencies = [
[[package]]
name = "filmcraft-format"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"chrono",
"craft-docpath",
"craft-fcproj-format",
"filmcraft-media",
"filmcraft-project",
"filmcraft-time",
"log",
"serde",
"serde_json",
"sha2",
"tempfile",
]
[[package]]
name = "filmcraft-frame"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"filmcraft-color",
"filmcraft-time",
@@ -3114,7 +3128,7 @@ dependencies = [
[[package]]
name = "filmcraft-geom"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"proptest",
"serde",
@@ -3122,7 +3136,7 @@ dependencies = [
[[package]]
name = "filmcraft-golden"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"filmcraft-color",
"filmcraft-frame",
@@ -3139,7 +3153,7 @@ dependencies = [
[[package]]
name = "filmcraft-gpu"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"bytemuck",
"filmcraft-color",
@@ -3160,7 +3174,7 @@ dependencies = [
[[package]]
name = "filmcraft-interchange"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"craft-aaf",
"craft-audio",
@@ -3180,7 +3194,7 @@ dependencies = [
[[package]]
name = "filmcraft-isobmff"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"craft-media",
"filmcraft-testkit",
@@ -3190,7 +3204,7 @@ dependencies = [
[[package]]
name = "filmcraft-matroska"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"craft-media",
"filmcraft-testkit",
@@ -3199,7 +3213,7 @@ dependencies = [
[[package]]
name = "filmcraft-media"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"craft-audio",
"craft-dpx",
@@ -3220,12 +3234,13 @@ dependencies = [
"png",
"rayon",
"serde",
"serde_json",
"thiserror 2.0.21",
]
[[package]]
name = "filmcraft-platform"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"craft-video",
"filmcraft-bitstream",
@@ -3239,11 +3254,16 @@ dependencies = [
"filmcraft-render",
"filmcraft-testkit",
"filmcraft-time",
"libc",
"libloading",
"log",
"objc2 0.6.5",
"objc2-app-kit 0.3.2",
"objc2-core-foundation",
"objc2-core-graphics",
"objc2-core-media",
"objc2-core-video",
"objc2-quartz-core 0.3.2",
"objc2-video-toolbox",
"tempfile",
"windows 0.62.2",
@@ -3251,7 +3271,7 @@ dependencies = [
[[package]]
name = "filmcraft-project"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"filmcraft-color",
"filmcraft-geom",
@@ -3266,7 +3286,7 @@ dependencies = [
[[package]]
name = "filmcraft-render"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"filmcraft-audio-dsp",
"filmcraft-captions",
@@ -3286,7 +3306,7 @@ dependencies = [
[[package]]
name = "filmcraft-scopes"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"filmcraft-color",
"serde",
@@ -3295,7 +3315,7 @@ dependencies = [
[[package]]
name = "filmcraft-speech"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"candle-core",
"candle-nn",
@@ -3314,7 +3334,7 @@ dependencies = [
[[package]]
name = "filmcraft-testkit"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"chrono",
"png",
@@ -3323,7 +3343,7 @@ dependencies = [
[[package]]
name = "filmcraft-text"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"craft-font-catalog",
"filmcraft-color",
@@ -3337,7 +3357,7 @@ dependencies = [
[[package]]
name = "filmcraft-time"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"craft-time",
"craft-timeline",
@@ -3345,7 +3365,7 @@ dependencies = [
[[package]]
name = "filmcraft-tts"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"candle-core",
"candle-nn",
@@ -3360,7 +3380,7 @@ dependencies = [
[[package]]
name = "filmcraft-tts-text"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"serde",
"thiserror 2.0.21",
@@ -3368,7 +3388,7 @@ dependencies = [
[[package]]
name = "filmcraft-ui-egui"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"cpu-time",
"craft-behavior",
@@ -3386,6 +3406,7 @@ dependencies = [
"filmcraft-captions",
"filmcraft-codecs",
"filmcraft-color",
"filmcraft-dng",
"filmcraft-edit",
"filmcraft-engine",
"filmcraft-export",
@@ -3416,7 +3437,7 @@ dependencies = [
[[package]]
name = "filmcraft-web"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"craft-web-api",
"craft-web-host",
@@ -9943,7 +9964,7 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7"
[[package]]
name = "xtask"
version = "0.20.1"
version = "0.21.0"
dependencies = [
"filmcraft-testkit",
"serde_json",
+3 -2
View File
@@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"]
default-members = ["crates/*", "apps/*", "xtask"]
[workspace.package]
version = "0.20.1"
version = "0.21.0"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
@@ -65,9 +65,10 @@ craft-exr = { version = "0.1.0", git = "https://github.com/storytold/craft-libs"
craft-dpx = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a4db799563c9ccd7217e1731ec34c58f6ba57248" }
# Shared YUV4MPEG2 parser and frame index.
craft-jsonrpc = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a4db799563c9ccd7217e1731ec34c58f6ba57248", features = ["async-lines"] }
craft-fcproj-format = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3af2280ee3434a2c860012df2f440652621c2c81" }
craft-fcproj-format = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "33fb95c7189686cab2fc0a6dbc1882ce7237e2c2" }
craft-font-catalog = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a4db799563c9ccd7217e1731ec34c58f6ba57248", default-features = false }
craft-control-protocol = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a4db799563c9ccd7217e1731ec34c58f6ba57248" }
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24" }
craft-y4m = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a4db799563c9ccd7217e1731ec34c58f6ba57248" }
# Shared lossless JPEG decoding for DNG.
craft-raw = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a4db799563c9ccd7217e1731ec34c58f6ba57248", default-features = false }
+1
View File
@@ -283,6 +283,7 @@ The control protocol is documented in [docs/control-protocol.md](docs/control-pr
| [docs/testing.md](docs/testing.md) | Unit, property and ffmpeg-oracle tests, accuracy criteria, benchmarks |
| [docs/agents.md](docs/agents.md) | Driving FilmCraft over MCP and the control channel; how agents develop it |
| [docs/control-protocol.md](docs/control-protocol.md) | Control-channel and MCP reference |
| [Lined Script guide](docs/lined-script.md) | Import screenplay text, organize takes, mark dialogue and compare readings |
| [docs/project-files.md](docs/project-files.md) | `.fcproj` format, schema migrations, auto-save and crash recovery |
| [docs/graphics.md](docs/graphics.md) · [docs/captions.md](docs/captions.md) | Text engine, graphic clips and tools; caption tracks and formats |
| [ROADMAP.md](ROADMAP.md) | Stage, parity numbers, languages, what's next and the progress log |
+1
View File
@@ -19,6 +19,7 @@ neural-voices = ["filmcraft-engine/neural-voices"]
[dependencies]
craft-control-protocol = { workspace = true }
craft-nightly = { workspace = true }
filmcraft-engine = { workspace = true }
filmcraft-export = { workspace = true }
# The durable no-follow session record (nightly_session.rs).
+4 -39
View File
@@ -1,31 +1,13 @@
//! Build-time channel is distinct from a launch selector. A runtime environment cannot promote a stable build.
use crate::launch_profile::Profile;
use std::ffi::OsString;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BuildFlavor {
Stable,
NightlyV1,
}
pub use craft_nightly::BuildFlavor;
pub const COMPILED: BuildFlavor = if cfg!(filmcraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable };
pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> {
match (flavor, profile.is_nightly()) {
(BuildFlavor::NightlyV1, false) => Err("Open FilmCraft Nightly from ArtCraft Launcher".into()),
(BuildFlavor::Stable, true) => Err("This is a stable FilmCraft build; nightly-v1 requires the nightly build".into()),
_ => Ok(()),
}
}
pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool {
desktop_session && flavor == BuildFlavor::NightlyV1
}
pub fn version_query(args: &[OsString]) -> bool {
matches!(args, [arg] if arg == "--version" || arg == "-V")
}
pub fn version(flavor: BuildFlavor, stable: &str) -> String {
match flavor {
BuildFlavor::Stable => stable.to_owned(),
@@ -35,7 +17,8 @@ pub fn version(flavor: BuildFlavor, stable: &str) -> String {
#[cfg(test)]
mod tests {
use super::*;
use super::{BuildFlavor, needs_native_error, version};
#[test]
fn only_a_nightly_desktop_refusal_requests_a_native_dialog() {
assert!(needs_native_error(BuildFlavor::NightlyV1, true));
@@ -45,26 +28,8 @@ mod tests {
}
#[test]
fn nightly_build_without_a_profile_is_refused_before_startup() {
let started = std::cell::Cell::new(false);
let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true));
assert!(result.unwrap_err().contains("ArtCraft Launcher"));
assert!(!started.get());
}
#[test]
fn stable_and_nightly_flavors_accept_only_their_own_profile() {
let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root"));
assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok());
assert!(require_profile(BuildFlavor::Stable, &nightly).is_err());
assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok());
}
#[test]
fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() {
fn nightly_version_format_is_unambiguous() {
assert_eq!(version(BuildFlavor::Stable, "0.21.1"), "0.21.1");
assert_eq!(version(BuildFlavor::NightlyV1, "0.21.1"), "0.21.1 (nightly-v1)");
assert!(version_query(&["--version".into()]));
assert!(version_query(&["-V".into()]));
assert!(!version_query(&["--".into(), "--version".into()]));
assert!(!version_query(&[]));
}
}
+3 -4
View File
@@ -426,11 +426,10 @@ pub fn choose(start: &mut GraphicsStart, forced: bool, explicit_backend: bool, l
choose_with(start, forced, log_file, &exe, &display_drivers(), |exe, mode| {
let mut cmd = Command::new(exe);
cmd.arg(CHILD_ARG).arg(mode.name());
// A Nightly start hands its private profile to the test child: the child refuses to run
// without one (it is the same program with the same protocol), and its graphics record
// must not land in stable's data folder.
// A Nightly start hands its private profile to the test child so its graphics record
// stays in the same isolated profile and never lands in stable's data folder.
if let Some(root) = crate::launch_profile::current().root() {
cmd.args(["--launch-profile", crate::launch_profile::VERSION, "--profile-root"]).arg(root).arg("--");
cmd.args(crate::launch_profile::launch_arguments(root, &[]));
}
run_test(cmd, TIMEOUT)
})
+72 -222
View File
@@ -1,281 +1,131 @@
//! Launcher-owned nightly-v1 bootstrap. Selected before logging, updates, fonts or saved state.
//! Stable launches retain their original arguments and directory policy. No environment mutation.
//! Nightly-v1 bootstrap powered by `craft-nightly`. Selected before logging, updates, fonts or
//! saved state. Direct nightly launches self-isolate into `craft_nightly::canonical_profile_root`
//! while preserving user arguments; stable launches retain their original arguments and directory
//! policy.
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
use std::sync::OnceLock;
use std::path::Path;
pub const VERSION: &str = "nightly-v1";
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Profile {
Stable,
NightlyV1(PathBuf),
}
impl Profile {
pub fn is_nightly(&self) -> bool {
matches!(self, Self::NightlyV1(_))
}
pub fn root(&self) -> Option<&Path> {
match self {
Self::Stable => None,
Self::NightlyV1(root) => Some(root),
}
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct Launch {
pub profile: Profile,
pub args: Vec<OsString>,
}
static PROFILE: OnceLock<Profile> = OnceLock::new();
pub use craft_nightly::{BuildFlavor, Launch, Profile, ProfileError, StartupOptions};
pub fn current() -> &'static Profile {
PROFILE.get().unwrap_or(&Profile::Stable)
craft_nightly::current().unwrap_or(&Profile::Stable)
}
pub fn install(profile: Profile) -> Result<(), String> {
PROFILE.set(profile).map_err(|_| "the launch profile was already selected".into())
pub fn prepare_launch(flavor: BuildFlavor, args: impl IntoIterator<Item = OsString>) -> Result<Launch, ProfileError> {
let spec = crate::profile_root::app_profile_spec();
craft_nightly::prepare_launch(flavor, &spec, args, &StartupOptions::default())
}
/// Recognize only the agreed literal selector/root pair before `--`. Everything after it is
/// a file, even when it looks like a profile flag. No filesystem or startup hook runs here.
pub fn parse(args: Vec<OsString>) -> Result<Launch, String> {
let mut selector = None;
let mut root = None;
let mut other = Vec::new();
let mut files = Vec::new();
let mut iter = args.iter();
let mut delimiter = false;
while let Some(arg) = iter.next() {
if arg == "--" {
delimiter = true;
files.extend(iter.cloned());
break;
}
if arg == "--launch-profile" || arg == "--profile-root" {
let slot = if arg == "--launch-profile" { &mut selector } else { &mut root };
if slot.is_some() {
return Err("the profile selector and root must each occur exactly once".into());
}
let value = iter.next().filter(|v| !v.is_empty()).ok_or("the profile selector/root needs a value")?;
if value.to_string_lossy().starts_with("--") {
return Err("the profile selector/root needs a value".into());
}
*slot = Some(value.clone());
} else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") {
return Err("the nightly protocol requires separate literal selector/root argument tokens".into());
} else {
other.push(arg.clone());
}
}
match (selector, root) {
(None, None) => Ok(Launch { profile: Profile::Stable, args }),
(Some(version), Some(root)) if version == VERSION => {
if !delimiter || !other.is_empty() {
return Err("nightly-v1 accepts only its selector/root followed by -- and file names".into());
}
let root = PathBuf::from(root);
if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) {
return Err("the nightly profile root must be absolute and contain no parent traversal".into());
}
Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() })
}
(Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".into()),
_ => Err("--launch-profile and --profile-root must be supplied together".into()),
}
pub fn launch_arguments(root: &Path, user_args: &[OsString]) -> Vec<OsString> {
craft_nightly::launch_arguments(root, user_args)
}
/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`),
/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never
/// validated or touched, and `-- --version` stays a file name.
pub fn version_query(args: &[OsString]) -> bool {
let Some((last, pair)) = args.split_last() else { return false };
if last != "--version" && last != "-V" {
return false;
}
let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect();
matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1)
}
/// The graphics retry is signalled by its process-local relaunch marker
/// (`FILMCRAFT_GRAPHICS_RELAUNCHED`) and re-executes this program with an internal
/// `--graphics <mode>` before the file delimiter. Ordinary Launcher calls still use the strict
/// selector/root protocol; this is not authentication.
pub fn parse_startup(args: Vec<OsString>, compatibility_retry: bool) -> Result<Launch, String> {
let Some(mode) = compatibility_retry.then(|| internal_graphics(&args)).flatten() else { return parse(args) };
let mut launch = parse(without_graphics(&args))?;
if launch.profile.is_nightly() {
launch.args.splice(0..0, [OsString::from("--graphics"), mode]);
Ok(launch)
} else {
// Stable's argument order and parser remain unchanged.
parse(args)
}
}
/// The `--graphics <mode>` pair the retry inserted before the file delimiter, if it is there once.
fn internal_graphics(args: &[OsString]) -> Option<OsString> {
let delimiter = args.iter().position(|arg| arg == "--").unwrap_or(args.len());
let mut found = None;
let mut iter = args[..delimiter].iter();
while let Some(arg) = iter.next() {
if arg == "--graphics" {
if found.is_some() {
return None;
}
found = Some(iter.next()?.clone());
}
}
found
}
/// `args` without the internal `--graphics <mode>` pair before the file delimiter. Everything
/// after `--` is a file name, even one spelled `--graphics`.
fn without_graphics(args: &[OsString]) -> Vec<OsString> {
let mut out = Vec::with_capacity(args.len());
let mut iter = args.iter();
while let Some(arg) = iter.next() {
if arg == "--" {
out.push(arg.clone());
out.extend(iter.by_ref().cloned());
} else if arg == "--graphics" {
let _ = iter.next();
} else {
out.push(arg.clone());
}
}
out
}
/// Validation finishes before the caller's first startup effect. Stable never calls the nightly
/// root validator, so its old portable/config resolution stays unchanged.
pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result<PathBuf, String>) -> Result<Launch, String> {
if let Profile::NightlyV1(root) = &launch.profile {
launch.profile = Profile::NightlyV1(validate(root)?);
}
Ok(launch)
}
/// Resolve the selected private root before the caller's first startup effect.
pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option<OsString>, exe: Option<&Path>) -> Result<PathBuf, String> {
crate::profile_root::validate(root, env, exe, crate::profile_root::ensure_writable)
#[cfg(test)]
pub fn parse_startup(flavor: BuildFlavor, args: impl IntoIterator<Item = OsString>) -> Result<Launch, ProfileError> {
let spec = crate::profile_root::app_profile_spec();
craft_nightly::parse_startup(flavor, &spec, args, &StartupOptions::default())
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::Cell;
use std::ffi::OsString;
use std::path::{Path, PathBuf};
use craft_nightly::{NIGHTLY_V1_CONTRACT, ProfileError, canonical_profile_root};
use super::{BuildFlavor, Launch, Profile, current, launch_arguments, parse_startup};
fn args(values: &[&str]) -> Vec<OsString> {
values.iter().map(OsString::from).collect()
}
fn absolute() -> &'static str {
if cfg!(windows) { r"C:\NightlyData\profiles\filmcraft" } else { "/nightly-data/profiles/filmcraft" }
}
fn nightly() -> Vec<OsString> {
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"])
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--"])
}
#[test]
fn direct_nightly_launch_self_isolates_into_canonical_root_and_preserves_args() {
let expected_root = canonical_profile_root(crate::profile_root::APP_ID).unwrap();
let launch = parse_startup(BuildFlavor::NightlyV1, args(&["--empty", "cut.fcproj"])).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(expected_root));
assert!(launch.profile.is_nightly());
assert_eq!(launch.passthrough_args, args(&["--empty", "cut.fcproj"]));
assert!(launch.leading_flags.is_empty());
assert!(!launch.is_version_query());
}
#[test]
fn internal_graphics_retry_preserves_the_nightly_root_and_literal_files() {
let mut argv = args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--graphics", "dx12", "--"]);
let mut argv = args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--graphics", "dx12", "--"]);
argv.extend(args(&["project with spaces.fcproj", "--graphics", "--profile-root"]));
let launch = parse_startup(argv.clone(), true).unwrap();
let launch = parse_startup(BuildFlavor::NightlyV1, argv).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
assert_eq!(launch.args, args(&["--graphics", "dx12", "--", "project with spaces.fcproj", "--graphics", "--profile-root"]));
assert!(parse_startup(argv, false).is_err(), "an ordinary invocation must not gain extra protocol flags");
assert_eq!(launch.passthrough_args, args(&["--graphics", "dx12", "--", "project with spaces.fcproj", "--graphics", "--profile-root"]));
}
#[test]
fn retry_cannot_bypass_invalid_profiles_or_change_stable_arguments() {
let stable = args(&["--graphics", "dx12", "--new-instance", "stable.fcproj"]);
assert_eq!(parse_startup(stable.clone(), true).unwrap(), Launch { profile: Profile::Stable, args: stable });
let mut duplicate = args(&["--graphics", "dx12", "--graphics", "software"]);
duplicate.extend(nightly());
assert!(parse_startup(duplicate, true).is_err());
assert!(parse_startup(args(&["--graphics", "dx12", "--launch-profile", VERSION, "--profile-root", "relative", "--"]), true).is_err());
}
#[test]
fn stable_arguments_and_directory_policy_are_unchanged() {
for argv in [args(&[]), args(&["--new-instance", "a.fcproj"]), args(&["--", "--launch-profile", "file.fcproj"])] {
let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap();
assert_eq!(launch, Launch { profile: Profile::Stable, args: argv });
fn stable_arguments_are_unchanged_and_nightly_flags_are_refused() {
for argv in [args(&[]), args(&["--demo", "a.fcproj"]), args(&["--", "--launch-profile", "file.fcproj"])] {
let launch = parse_startup(BuildFlavor::Stable, argv.clone()).unwrap();
assert_eq!(launch, Launch { profile: Profile::Stable, passthrough_args: argv, leading_flags: Vec::new() });
}
assert!(matches!(parse_startup(BuildFlavor::Stable, nightly()), Err(ProfileError::NightlyFlagsInStableBuild)));
}
#[test]
fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() {
let mut argv = nightly();
argv.extend(args(&["--profile-root", "project with spaces.fcproj"]));
let launch = parse(argv).unwrap();
let launch = parse_startup(BuildFlavor::NightlyV1, argv).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
assert_eq!(launch.args, args(&["--", "--profile-root", "project with spaces.fcproj"]));
assert_eq!(launch.passthrough_args, args(&["--profile-root", "project with spaces.fcproj"]));
}
#[test]
fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() {
fn missing_duplicate_unknown_and_misplaced_profile_arguments_are_refused() {
for argv in [
args(&["--launch-profile", VERSION]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT]),
args(&["--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-instance", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute()]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--"]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", "", "--"]),
args(&["a.fcproj", "--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute()]),
] {
assert!(parse(argv).is_err());
assert!(parse_startup(BuildFlavor::NightlyV1, argv.clone()).is_err(), "{argv:?}");
}
}
#[test]
fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() {
let pair = &["--launch-profile", VERSION, "--profile-root", absolute()];
let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION];
for flag in ["--version", "-V"] {
for form in [pair, reversed] {
let mut argv = args(form);
argv.push(flag.into());
assert!(version_query(&argv), "{argv:?}");
}
}
fn recognizes_plain_and_launcher_version_queries_without_reinterpreting_files() {
for argv in [
args(&["--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-instance", "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]),
args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]),
args(&["--launch-profile", VERSION, "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]),
args(&["-V"]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--", "--version"]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--", "-V"]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--version"]),
args(&["--profile-root", absolute(), "--launch-profile", NIGHTLY_V1_CONTRACT, "-V"]),
] {
assert!(!version_query(&argv), "{argv:?}");
let launch = parse_startup(BuildFlavor::NightlyV1, argv.clone()).unwrap();
assert!(launch.is_version_query(), "{argv:?}");
}
// Outside the query the strict protocol still refuses the version flag.
assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err());
let file_named_version = parse_startup(BuildFlavor::NightlyV1, args(&["--", "--version"])).unwrap();
assert!(!file_named_version.is_version_query());
assert_eq!(file_named_version.passthrough_args, args(&["--", "--version"]));
}
#[test]
fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() {
let reached = Cell::new(false);
let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true));
assert!(result.is_err());
assert!(!reached.get());
}
#[test]
fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() {
let checked = PathBuf::from(absolute()).join("checked");
let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap();
assert_eq!(launch.profile.root(), Some(checked.as_path()));
assert!(launch.profile.is_nightly());
fn current_defaults_to_stable_and_launch_arguments_round_trip() {
assert!(!current().is_nightly());
assert!(current().root().is_none());
let encoded = launch_arguments(Path::new(absolute()), &args(&["cut.fcproj"]));
let parsed = parse_startup(BuildFlavor::NightlyV1, encoded).unwrap();
assert_eq!(parsed.profile, Profile::NightlyV1(PathBuf::from(absolute())));
assert_eq!(parsed.passthrough_args, args(&["cut.fcproj"]));
}
}
+89 -42
View File
@@ -139,9 +139,8 @@ fn report_launch_profile_error(error: &str) {
/// Returns the arguments the rest of the start parses, or `None` when this was a version query.
fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
let argv: Vec<std::ffi::OsString> = std::env::args_os().skip(1).collect();
// Plain `--version`/`-V`, or the Launcher's `--launch-profile nightly-v1 --profile-root <dir>
// --version`: answered before root validation, process identity, logging or any window.
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv)) {
// Bare version queries do not resolve a profile or depend on HOME/LOCALAPPDATA.
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && matches!(argv.as_slice(), [arg] if arg == "--version" || arg == "-V") {
use std::io::Write as _;
let _ = writeln!(std::io::stdout(), "FilmCraft {}", build_flavor::version(build_flavor::COMPILED, version_text()));
return None;
@@ -150,33 +149,25 @@ fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
// (`--test-graphics-start <mode>` [profile tokens]): its mode and root come from the parent,
// never from the environment.
let internal = argv.first().is_some_and(|arg| arg == graphics::probe::CHILD_ARG);
let early = if internal {
let tail = argv.get(2..).unwrap_or_default().to_vec();
launch_profile::parse(tail).unwrap_or_else(|error| {
report_launch_profile_error(&error);
std::process::exit(2)
})
} else {
let retry = std::env::var_os("FILMCRAFT_GRAPHICS_RELAUNCHED").is_some();
launch_profile::parse_startup(argv.clone(), retry).unwrap_or_else(|error| {
report_launch_profile_error(&error);
std::process::exit(2)
})
};
let early = build_flavor::require_profile(build_flavor::COMPILED, &early.profile)
.and_then(|()| initialize_nightly_process_identity().map_err(|error| error.to_string()))
.and_then(|()| {
launch_profile::prepare(early, |root| launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref()))
})
.unwrap_or_else(|error| {
report_launch_profile_error(&error);
std::process::exit(2)
});
let startup_args = if internal { argv.get(2..).unwrap_or_default().to_vec() } else { argv.clone() };
let early = launch_profile::prepare_launch(build_flavor::COMPILED, startup_args).unwrap_or_else(|error| {
report_launch_profile_error(&error.to_string());
std::process::exit(2)
});
// Plain `--version`/`-V`, or the Launcher's `--launch-profile nightly-v1 --profile-root <dir>
// -- --version`: answered before process identity, logging or any window.
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && !internal && early.is_version_query() {
use std::io::Write as _;
let _ = writeln!(std::io::stdout(), "FilmCraft {}", build_flavor::version(build_flavor::COMPILED, version_text()));
return None;
}
if let Err(error) = initialize_nightly_process_identity() {
report_launch_profile_error(&error.to_string());
std::process::exit(2);
}
let identity =
if early.profile.is_nightly() { filmcraft_ui_egui::os_window::LaunchIdentity::NightlyV1 } else { filmcraft_ui_egui::os_window::LaunchIdentity::Stable };
// Read the launch's own arguments before `install` takes the profile: `runnable_argv` borrows it.
let runnable = runnable_argv(internal, argv, &early);
if let Err(error) = launch_profile::install(early.profile).and_then(|()| filmcraft_ui_egui::os_window::select_identity(identity)) {
if let Err(error) = filmcraft_ui_egui::os_window::select_identity(identity) {
report_launch_profile_error(&error);
std::process::exit(2);
}
@@ -192,16 +183,36 @@ fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
build_flavor::BuildFlavor::Stable => version_text().to_owned(),
build_flavor::BuildFlavor::NightlyV1 => build_flavor::version(build_flavor::COMPILED, version_text()),
});
Some(runnable)
Some(runnable_argv(internal, argv, &early))
}
/// What `main` parses once the profile is selected. A Launcher start gets the profile's own tail
/// (`--` and the file names): the raw argv still holds `--launch-profile`/`--profile-root`, which
/// What `main` parses once the profile is selected. A Launcher start gets the profile's own
/// passthrough arguments: the raw argv still holds `--launch-profile`/`--profile-root`, which
/// `args::parse` refuses as unknown options, so every Nightly GUI start would exit 2. The graphics
/// test child keeps its `--test-graphics-start <mode>` re-entry line, and ignores the tokens after
/// it ([`graphics::probe::child_main`]).
fn runnable_argv(internal: bool, argv: Vec<std::ffi::OsString>, launch: &launch_profile::Launch) -> Vec<std::ffi::OsString> {
if internal { argv } else { launch.args.clone() }
if internal { argv } else { launch.leading_flags.iter().cloned().chain(launch.passthrough_args.iter().cloned()).collect() }
}
fn nightly_cli_override_error(nightly: bool, launch: &Launch) -> Option<&'static str> {
if !nightly {
return None;
}
if launch.control_port.is_some() || launch.control_input_only {
return Some("filmcraft: a nightly-v1 start does not start the stable control server; drive FilmCraft Nightly through ArtCraft Launcher");
}
if launch.data_dir.is_some() {
return Some("filmcraft: nightly-v1 cannot be combined with --data-dir; use --launch-profile nightly-v1 --profile-root <dir>");
}
None
}
fn reject_nightly_cli_overrides(nightly: bool, launch: &Launch) {
if let Some(error) = nightly_cli_override_error(nightly, launch) {
eprintln!("{error}");
std::process::exit(2);
}
}
fn main() -> eframe::Result {
@@ -245,10 +256,7 @@ fn main() -> eframe::Result {
std::process::exit(2);
}
};
if nightly && (launch.control_port.is_some() || launch.control_input_only) {
eprintln!("filmcraft: a nightly-v1 start does not start the stable control server; drive FilmCraft Nightly through ArtCraft Launcher");
std::process::exit(2);
}
reject_nightly_cli_overrides(nightly, &launch);
let data_root = launch.data_dir.clone().or_else(default_data_dir);
let log_dir = data_root.as_ref().map(|d| d.join(logging::LOG_DIR));
log::info!("{} {} ({} {})", filmcraft_ui_egui::os_window::name(), version_text(), std::env::consts::OS, std::env::consts::ARCH);
@@ -521,6 +529,14 @@ fn app_creator(
}
}),
);
// macOS colour-matches the picture to each display once its Metal layer says what it is
// (sRGB); wgpu leaves it untagged and resets it on resize, so this runs every frame (#2115)
cc.egui_ctx.on_end_pass(
"display-color",
Arc::new(|_| {
filmcraft_platform::display_color::tag_windows_srgb();
}),
);
let mut session = Session::default();
if let Some(dir) = data_dir.clone().or_else(default_data_dir) {
let mut cfg = AutosaveConfig::new(dir);
@@ -916,25 +932,56 @@ mod tests {
let os = |v: &[&str]| v.iter().map(std::ffi::OsString::from).collect::<Vec<_>>();
let root = if cfg!(windows) { r"C:\NightlyData\profiles\filmcraft" } else { "/nightly-data/profiles/filmcraft" };
let argv = os(&["--launch-profile", "nightly-v1", "--profile-root", root, "--", "cut.fcproj", "clip with spaces.mp4"]);
let launch = crate::launch_profile::parse(argv.clone()).unwrap();
let launch = crate::launch_profile::parse_startup(crate::build_flavor::BuildFlavor::NightlyV1, argv.clone()).unwrap();
let tail = super::runnable_argv(false, argv.clone(), &launch);
assert_eq!(tail, launch.args);
assert_eq!(tail, launch.passthrough_args);
match crate::args::parse(None, tail) {
Ok(crate::args::Cli::Run(l)) => assert_eq!(l.files, ["cut.fcproj", "clip with spaces.mp4"]),
other => panic!("a nightly launch should start the app, got {other:?}"),
}
// A `--version` the Launcher appends after `--` stays a file name, as for stable.
// Launcher version queries are handled before startup; a direct `-- --version` stays a file name.
let query = os(&["--launch-profile", "nightly-v1", "--profile-root", root, "--", "--version"]);
let launch = crate::launch_profile::parse(query.clone()).unwrap();
assert!(matches!(crate::args::parse(None, super::runnable_argv(false, query, &launch)), Ok(crate::args::Cli::Run(l)) if l.files == ["--version"]));
let launch = crate::launch_profile::parse_startup(crate::build_flavor::BuildFlavor::NightlyV1, query).unwrap();
assert!(launch.is_version_query());
let direct_file = os(&["--", "--version"]);
let launch = crate::launch_profile::parse_startup(crate::build_flavor::BuildFlavor::NightlyV1, direct_file.clone()).unwrap();
assert!(!launch.is_version_query());
assert!(
matches!(crate::args::parse(None, super::runnable_argv(false, direct_file, &launch)), Ok(crate::args::Cli::Run(l)) if l.files == ["--version"])
);
// The graphics test child keeps its re-entry head (`--test-graphics-start <mode>` first);
// the raw Launcher line stays what `args::parse` refuses.
let child = os(&["--test-graphics-start", "default", "--launch-profile", "nightly-v1", "--profile-root", root, "--"]);
let launch = crate::launch_profile::parse(child[2..].to_vec()).unwrap();
let launch = crate::launch_profile::parse_startup(crate::build_flavor::BuildFlavor::NightlyV1, child[2..].to_vec()).unwrap();
assert_eq!(super::runnable_argv(true, child.clone(), &launch), child);
assert!(crate::args::parse(None, argv).is_err(), "the raw Launcher line is not a FilmCraft command line");
}
#[test]
fn nightly_cli_overrides_are_refused_only_for_nightly_launches() {
let parse_run = |argv: &[&str]| match crate::args::parse(None, argv.iter().map(std::ffi::OsString::from)) {
Ok(crate::args::Cli::Run(launch)) => launch,
other => panic!("expected Run launch, got {other:?}"),
};
let plain = parse_run(&["--empty"]);
assert_eq!(super::nightly_cli_override_error(true, &plain), None);
super::reject_nightly_cli_overrides(true, &plain);
let stable_overrides = parse_run(&["--control", "9886", "--control-input-only", "--data-dir", "/tmp/stable"]);
assert_eq!(super::nightly_cli_override_error(false, &stable_overrides), None);
super::reject_nightly_cli_overrides(false, &stable_overrides);
let control = parse_run(&["--control", "9886"]);
assert!(super::nightly_cli_override_error(true, &control).unwrap().contains("control server"));
let mut input_only = plain.clone();
input_only.control_input_only = true;
assert!(super::nightly_cli_override_error(true, &input_only).unwrap().contains("control server"));
let data_dir = parse_run(&["--data-dir", "/tmp/custom"]);
assert!(super::nightly_cli_override_error(true, &data_dir).unwrap().contains("--data-dir"));
}
/// The new start after a graphics panic keeps the arguments and picks the next mode, replacing a
/// `--graphics` that was given (#2558).
#[test]
+177 -563
View File
@@ -1,294 +1,121 @@
//! App-owned nightly profile fences; no stable fallback, migration or process environment changes.
//! FilmCraft-specific nightly profile isolation spec for `craft-nightly`.
use std::ffi::OsString;
use std::sync::atomic::{AtomicU64, Ordering};
use std::path::PathBuf;
use std::path::{Component, Path, PathBuf};
use craft_nightly::AppProfileSpec;
pub const APP_ID: &str = "filmcraft";
pub const DISPLAY_NAME: &str = "FilmCraft";
pub const STABLE_DIR_NAMES: &[&str] = &["filmcraft", "FilmCraft"];
pub const FORBIDDEN_ENV_VARS: &[&str] = &["FILMCRAFT_DATA_DIR"];
/// The portable marker `filmcraft_engine::autosave` looks for beside the executable.
const PORTABLE_MARKER: &str = "portable.txt";
/// The folder a portable install keeps its data in, beside that marker.
const PORTABLE_DATA_DIR: &str = "data";
pub const PORTABLE_MARKERS: &[&str] = &["portable.txt"];
/// Folders that must remain directories inside the profile root.
pub const FOLDER_ONLY_ENTRIES: &[&str] = &["Recovery", "Logs", "Media Cache"];
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Platform {
Windows,
Linux,
Mac,
/// Builds the FilmCraft [`AppProfileSpec`] using the current process environment.
pub fn app_profile_spec() -> AppProfileSpec {
app_profile_spec_with_env(|key| std::env::var_os(key))
}
impl Platform {
fn current() -> Result<Self, String> {
match std::env::consts::OS {
"windows" => Ok(Self::Windows),
"linux" => Ok(Self::Linux),
"macos" => Ok(Self::Mac),
_ => Err("nightly-v1 is not defined for this operating system".into()),
/// Builds the FilmCraft [`AppProfileSpec`] using an injected environment lookup.
pub fn app_profile_spec_with_env(env: impl Fn(&str) -> Option<OsString>) -> AppProfileSpec {
AppProfileSpec {
app_id: APP_ID,
display_name: DISPLAY_NAME,
stable_dir_names: STABLE_DIR_NAMES,
stable_package_id: filmcraft_ui_egui::os_window::APP_ID,
nightly_package_id: filmcraft_ui_egui::os_window::NIGHTLY_PACKAGE_ID,
profile_root_env: None,
forbidden_env_vars: FORBIDDEN_ENV_VARS,
portable_markers: PORTABLE_MARKERS,
folder_only_entries: FOLDER_ONLY_ENTRIES,
extra_forbidden_roots: extra_forbidden_roots(&env),
}
}
fn non_empty_abs_env(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Option<PathBuf> {
let value = env(key)?;
if value.is_empty() {
return None;
}
let path = PathBuf::from(value);
path.is_absolute().then_some(path)
}
fn extra_forbidden_roots(env: &impl Fn(&str) -> Option<OsString>) -> Vec<PathBuf> {
#[cfg(target_os = "windows")]
{
let mut roots = Vec::new();
// The MSI's default per-user and per-machine folders (install-policy.wxi).
let local =
non_empty_abs_env(env, "LOCALAPPDATA").or_else(|| non_empty_abs_env(env, "USERPROFILE").map(|profile| profile.join("AppData").join("Local")));
if let Some(local) = local {
roots.push(local.join("Programs").join("ArtCraft").join("FilmCraft"));
}
}
fn ignores_case(self) -> bool {
self != Self::Linux
}
}
fn absolute(path: PathBuf, label: &str) -> Result<PathBuf, String> {
if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) {
return Err(format!("{label} must be absolute and contain no parent traversal"));
}
Ok(path)
}
fn required_base(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Result<PathBuf, String> {
let value = env(key).filter(|v| !v.is_empty()).ok_or_else(|| format!("cannot establish the stable {key} boundary"))?;
absolute(PathBuf::from(value), key)
}
fn xdg_base(env: &impl Fn(&str) -> Option<OsString>, key: &str, fallback: &str) -> Result<PathBuf, String> {
match env(key).filter(|v| !v.is_empty()) {
Some(value) => absolute(PathBuf::from(value), key),
None => Ok(required_base(env, "HOME")?.join(fallback)),
}
}
/// Resolve existing ancestors before creating anything. A dangling link or inaccessible ancestor
/// is not a missing directory that may be replaced or followed later.
fn canonical_future(path: &Path) -> Result<PathBuf, String> {
let mut parent = path;
let mut missing = Vec::new();
loop {
match std::fs::symlink_metadata(parent) {
Ok(_) => break,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
missing.push(parent.file_name().ok_or("the profile root has no existing ancestor")?.to_os_string());
parent = parent.parent().ok_or("the profile root has no existing ancestor")?;
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
if let Some(base) = non_empty_abs_env(env, key) {
roots.push(base.join("ArtCraft").join("FilmCraft"));
}
Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")),
}
roots
}
let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?;
for part in missing.into_iter().rev() {
resolved.push(part);
}
Ok(resolved)
}
fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool {
let parts = |p: &Path| {
p.components()
.map(|c| {
let value = c.as_os_str().to_string_lossy().into_owned();
if platform.ignores_case() { value.to_lowercase() } else { value }
})
.collect::<Vec<_>>()
};
let (a, b) = (parts(a), parts(b));
a.starts_with(&b) || b.starts_with(&a)
}
fn installation_boundary(platform: Platform, exe: &Path) -> Result<PathBuf, String> {
let parent = exe.parent().ok_or("cannot establish the installation boundary")?;
if platform == Platform::Mac {
// A profile in Resources is still inside the versioned install, not beside MacOS.
if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) {
return Ok(bundle.to_path_buf());
}
}
Ok(parent.to_path_buf())
}
fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option<OsString>, exe: &Path) -> Result<Vec<PathBuf>, String> {
let mut roots = match platform {
Platform::Windows => {
// %APPDATA%\FilmCraft is the per-user data directory (autosave::default_data_dir);
// %LOCALAPPDATA%\FilmCraft is fenced as well, so no future local cache can land there.
let mut roots =
["APPDATA", "LOCALAPPDATA"].into_iter().map(|key| required_base(env, key).map(|p| p.join("FilmCraft"))).collect::<Result<Vec<_>, _>>()?;
// The MSI's default per-user and per-machine folders (install-policy.wxi). A custom
// install folder is not known here; the executable's own folder is fenced below.
roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join("FilmCraft"));
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
if let Some(base) = env(key).filter(|v| !v.is_empty()) {
roots.push(absolute(PathBuf::from(base), key)?.join("ArtCraft").join("FilmCraft"));
}
}
roots
}
Platform::Linux => {
// The data directory is real; the config, cache and state roots are fenced so a
// future one cannot point Nightly at stable state. `~/.var/app` is the stable
// Flatpak's own per-app folder.
let mut roots =
[("XDG_DATA_HOME", ".local/share"), ("XDG_CONFIG_HOME", ".config"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")]
.into_iter()
.map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join("filmcraft")))
.collect::<Result<Vec<_>, _>>()?;
roots.extend(["/usr/bin/filmcraft", "/usr/local/bin/filmcraft", "/opt/filmcraft"].map(PathBuf::from));
let data = xdg_base(env, "XDG_DATA_HOME", ".local/share")?;
#[cfg(all(unix, not(target_os = "macos")))]
{
let mut roots = vec![PathBuf::from("/usr/bin/filmcraft"), PathBuf::from("/usr/local/bin/filmcraft"), PathBuf::from("/opt/filmcraft")];
let home = non_empty_abs_env(env, "HOME");
let data = non_empty_abs_env(env, "XDG_DATA_HOME").or_else(|| home.as_ref().map(|h| h.join(".local").join("share")));
if let Some(data) = data {
// Dev builds write a desktop entry and its hicolor icons into the XDG data dir
// (apps/filmcraft/src/dev_icon.rs); a Nightly profile is never inside them.
roots.push(data.join("applications").join("ai.storyteller.filmcraft.desktop"));
roots.push(data.join("icons").join("hicolor"));
roots.push(required_base(env, "HOME")?.join(".var/app/ai.storyteller.filmcraft"));
roots
}
Platform::Mac => {
let home = required_base(env, "HOME")?;
let library = home.join("Library");
vec![
library.join("Application Support/FilmCraft"),
library.join("Caches/FilmCraft"),
library.join("Caches/ai.storyteller.filmcraft"),
library.join("Preferences/FilmCraft"),
library.join("Preferences/ai.storyteller.filmcraft.plist"),
library.join("Saved Application State/ai.storyteller.filmcraft.savedState"),
home.join("Applications/FilmCraft.app"),
PathBuf::from("/Applications/FilmCraft.app"),
]
if let Some(home) = home {
roots.push(home.join(".var/app/ai.storyteller.filmcraft"));
}
};
roots.push(installation_boundary(platform, exe)?);
roots.into_iter().map(|p| canonical_future(&p)).collect()
}
roots
}
fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str, platform: Platform) -> Result<PathBuf, String> {
let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?;
let child = canonical_future(&chosen.join(name))?;
if child == chosen || !child.starts_with(&chosen) {
return Err(format!("the nightly {label} must stay inside its selected profile"));
}
// The target's own ancestors decide this, not the profile's: an alias may otherwise point into
// a Stable portable install that happens to sit inside the selected profile.
if is_portable_layout(&child, platform) {
return Err(format!("the nightly {label} must not use a portable FilmCraft installation or its data folder"));
}
Ok(child)
}
/// Every existing entry directly in the profile (logs, preferences and so on) must resolve inside
/// it, so a link there cannot point Nightly's writes at another app's data.
fn entries_stay_inside(root: &Path, platform: Platform) -> Result<(), String> {
let entries = match std::fs::read_dir(root) {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")),
};
for entry in entries {
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
private_subdirectory(root, entry.file_name(), "profile entry", platform)?;
}
Ok(())
}
/// Recognise the portable data namespace in both the supplied and resolved path. A marker only
/// counts beside a FilmCraft executable (above the chosen folder itself), so an unrelated
/// `portable.txt` higher up does not refuse the profile.
///
/// A `data` component counts only when its parent holds the portable marker: the Nightly Flatpak's
/// own `~/.var/app/…/data/filmcraft-nightly/profile`, and any home with a `data` folder, are
/// ordinary per-user paths, not a portable install's data directory.
fn is_portable_layout(path: &Path, platform: Platform) -> bool {
path.ancestors().enumerate().any(|(depth, ancestor)| {
ancestor.join(PORTABLE_MARKER).is_file() && (depth == 0 || ["filmcraft.exe", "filmcraft", "FilmCraft"].iter().any(|exe| ancestor.join(exe).is_file()))
}) || path.ancestors().any(|ancestor| {
let named_data = ancestor.file_name().is_some_and(|name| {
if platform.ignores_case() { name.to_string_lossy().eq_ignore_ascii_case(PORTABLE_DATA_DIR) } else { name == PORTABLE_DATA_DIR }
});
named_data && ancestor.parent().is_some_and(|install| install.join(PORTABLE_MARKER).is_file())
})
}
/// The app's existing exclusive write probe: create and remove a file in the profile.
pub fn ensure_writable(dir: &Path) -> std::io::Result<()> {
// The name is unique to this validation: two windows may validate the same writable profile at
// once, and a shared name would make the second `create_new` fail with AlreadyExists.
static NEXT: AtomicU64 = AtomicU64::new(0);
let probe = dir.join(format!("exclusive-write-probe-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?;
drop(file);
std::fs::remove_file(probe)
}
/// The writable hook is injected so the boundary tests exercise the real policy without starting
/// the app or changing global state.
pub fn validate(
root: &Path,
env: impl Fn(&str) -> Option<OsString>,
exe: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
validate_for(Platform::current()?, root, env, exe, writable)
}
fn validate_for(
platform: Platform,
root: &Path,
env: impl Fn(&str) -> Option<OsString>,
exe: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
absolute(root.to_path_buf(), "the nightly profile root")?;
// The stable data-directory override would point every write outside the private profile.
if env("FILMCRAFT_DATA_DIR").is_some_and(|v| !v.is_empty()) {
return Err("nightly-v1 cannot be combined with FILMCRAFT_DATA_DIR".into());
}
if platform != Platform::Windows {
// A native Nightly package must not inherit a Flatpak runtime: its socket namespace could
// point this profile at another app's instance. The Nightly Flatpak itself is not that
// case -- its sandbox data is `~/.var/app/ai.storyteller.filmcraft.nightly`, separate from
// stable -- so exactly the app's own Nightly id is accepted and every other value refused.
if let Some(id) = env("FLATPAK_ID").filter(|value| !value.is_empty())
&& id.as_os_str() != std::ffi::OsStr::new(filmcraft_ui_egui::os_window::NIGHTLY_PACKAGE_ID)
{
return Err("nightly-v1 native packages cannot inherit a Flatpak instance; launch through the native Launcher".into());
}
}
let chosen = canonical_future(root)?;
if is_portable_layout(root, platform) || is_portable_layout(&chosen, platform) {
return Err("the nightly root must not use a portable FilmCraft installation or its data folder".into());
}
let exe = absolute(exe.ok_or("cannot establish the installation boundary")?.to_path_buf(), "the executable")?;
let forbidden = forbidden_roots(platform, &env, &exe)?;
if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) {
return Err("the nightly root must not overlap stable data or an installation".into());
}
entries_stay_inside(&chosen, platform)?;
// Recovery can read, adopt, overwrite and sweep entries, and the log writer rotates files.
// Never let their aliases leave this private profile or alias portable data inside it.
private_subdirectory(&chosen, "Recovery", "recovery folder", platform)?;
private_subdirectory(&chosen, "Logs", "log folder", platform)?;
let mut create = std::fs::DirBuilder::new();
create.recursive(true);
#[cfg(unix)]
#[cfg(target_os = "macos")]
{
use std::os::unix::fs::DirBuilderExt as _;
create.mode(0o700);
let mut roots = vec![PathBuf::from("/Applications/FilmCraft.app")];
if let Some(home) = non_empty_abs_env(env, "HOME") {
let library = home.join("Library");
roots.push(library.join("Preferences/ai.storyteller.filmcraft.plist"));
roots.push(library.join("Saved Application State/ai.storyteller.filmcraft.savedState"));
roots.push(home.join("Applications/FilmCraft.app"));
}
roots
}
create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?;
let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?;
if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) {
return Err("the nightly profile changed while it was being validated".into());
#[cfg(not(any(unix, target_os = "windows")))]
{
let _ = env;
Vec::new()
}
private_subdirectory(&confirmed, "Recovery", "recovery folder", platform)?;
private_subdirectory(&confirmed, "Logs", "log folder", platform)?;
entries_stay_inside(&confirmed, platform)?;
writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?;
Ok(confirmed)
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeMap;
use std::ffi::OsString;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
struct Fixture {
use craft_nightly::{ProfileError, validate_and_prepare_root};
use super::{
APP_ID, DISPLAY_NAME, FOLDER_ONLY_ENTRIES, FORBIDDEN_ENV_VARS, PORTABLE_MARKERS, STABLE_DIR_NAMES, app_profile_spec_with_env, extra_forbidden_roots,
};
struct TempDir {
root: PathBuf,
env: BTreeMap<String, OsString>,
exe: PathBuf,
}
impl Fixture {
impl TempDir {
fn new() -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
let root = loop {
@@ -299,341 +126,128 @@ mod tests {
Err(error) => panic!("cannot create owned fixture: {error}"),
}
};
let home = root.join("home");
let exe = root.join("install/filmcraft");
std::fs::create_dir_all(&home).unwrap();
std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
std::fs::write(&exe, b"fixture executable, never run").unwrap();
let env = [("HOME", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))]
.into_iter()
.map(|(key, value)| (key.into(), value.into_os_string()))
.collect();
Self { root, env, exe }
}
fn get(&self, key: &str) -> Option<OsString> {
self.env.get(key).cloned()
}
fn check(&self, platform: Platform, root: &Path) -> Result<PathBuf, String> {
validate_for(platform, root, |key| self.get(key), Some(&self.exe), ensure_writable)
}
fn refuse(&self, platform: Platform, root: &Path) -> String {
let probed = std::cell::Cell::new(false);
let result = validate_for(
platform,
root,
|key| self.get(key),
Some(&self.exe),
|_| {
probed.set(true);
Ok(())
},
);
assert!(!probed.get(), "a refused root must never reach the writable probe");
result.unwrap_err()
}
fn home(&self) -> PathBuf {
PathBuf::from(self.get("HOME").unwrap())
Self { root }
}
}
impl Drop for Fixture {
impl Drop for TempDir {
fn drop(&mut self) {
std::fs::remove_dir_all(&self.root).unwrap();
let _ = std::fs::remove_dir_all(&self.root);
}
}
#[test]
fn portable_settings_from_another_install_are_refused_before_any_probe() {
let fixture = Fixture::new();
let stable_install = fixture.root.join("stable portable install");
let stable_data = stable_install.join("data");
std::fs::create_dir_all(&stable_data).unwrap();
std::fs::write(stable_install.join("portable.txt"), b"owned portable fixture").unwrap();
std::fs::write(stable_data.join("preferences.json"), b"stable settings must not change").unwrap();
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
for candidate in [&stable_data, &stable_data.join("nested nightly")] {
assert!(!fixture.refuse(platform, candidate).is_empty());
assert!(!stable_data.join("nested nightly").exists());
assert_eq!(std::fs::read(stable_data.join("preferences.json")).unwrap(), b"stable settings must not change");
}
}
// A portable marker with no FilmCraft executable beside it is someone else's file.
let unrelated = fixture.root.join("user folder");
std::fs::create_dir_all(&unrelated).unwrap();
std::fs::write(unrelated.join("portable.txt"), b"another app's marker").unwrap();
assert!(fixture.check(Platform::Windows, &unrelated.join("Launcher/nightly/filmcraft")).is_ok());
// A merely similar data folder name is not the portable namespace.
assert!(fixture.check(Platform::Linux, &fixture.root.join("data-backup/nightly")).is_ok());
fn failed_profile_preparation_does_not_start_with_stable() {
let tmp = TempDir::new();
let root = tmp.root.join("not-a-directory");
std::fs::write(&root, b"an ordinary file").unwrap();
let argv = craft_nightly::launch_arguments(&root, &[]);
let result = crate::launch_profile::prepare_launch(craft_nightly::BuildFlavor::NightlyV1, argv);
assert!(matches!(result, Err(ProfileError::NotADirectory(_))));
assert_eq!(std::fs::read(&root).unwrap(), b"an ordinary file");
}
#[test]
fn a_data_folder_beside_no_portable_marker_is_not_a_portable_install() {
let mut fixture = Fixture::new();
// The Nightly Flatpak's own sandbox data root is `…/ai.storyteller.filmcraft.nightly/data`,
// and a home may hold a plain `data` folder: neither is a portable install (#5225 review).
let plain = fixture.root.join("data/filmcraft-nightly/profile");
assert_eq!(fixture.check(Platform::Linux, &plain).unwrap(), plain);
let sandbox = fixture.home().join(".var/app/ai.storyteller.filmcraft.nightly/data/filmcraft-nightly/profile");
fixture.env.insert("FLATPAK_ID".into(), filmcraft_ui_egui::os_window::NIGHTLY_PACKAGE_ID.into());
assert_eq!(fixture.check(Platform::Linux, &sandbox).unwrap(), sandbox);
// Only the Nightly Flatpak's own id may inherit a sandbox; every other one is refused.
fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.filmcraft".into());
assert!(fixture.refuse(Platform::Linux, &sandbox).contains("Flatpak"));
fn spec_preserves_filmcraft_security_fence_parameters() {
let spec = app_profile_spec_with_env(|key| match key {
"HOME" | "LOCALAPPDATA" => Some(OsString::from("")),
"XDG_DATA_HOME" | "ProgramFiles" => Some(OsString::from("relative/path")),
_ => None,
});
assert_eq!(spec.app_id, APP_ID);
assert_eq!(spec.display_name, DISPLAY_NAME);
assert_eq!(spec.stable_dir_names, STABLE_DIR_NAMES);
assert_eq!(spec.stable_package_id, filmcraft_ui_egui::os_window::APP_ID);
assert_eq!(spec.nightly_package_id, filmcraft_ui_egui::os_window::NIGHTLY_PACKAGE_ID);
assert_eq!(spec.profile_root_env, None);
assert_eq!(spec.forbidden_env_vars, FORBIDDEN_ENV_VARS);
assert_eq!(spec.portable_markers, PORTABLE_MARKERS);
assert_eq!(spec.folder_only_entries, FOLDER_ONLY_ENTRIES);
}
#[test]
fn linux_fences_app_xdg_subtrees_but_allows_launcher_sibling() {
let mut fixture = Fixture::new();
for key in ["XDG_DATA_HOME", "XDG_CONFIG_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
fixture.env.insert(key.into(), fixture.root.join(key).into_os_string());
}
for key in ["XDG_DATA_HOME", "XDG_CONFIG_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
let stable = PathBuf::from(fixture.get(key).unwrap()).join("filmcraft");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("stable-sentinel"), b"stable bytes").unwrap();
for candidate in [stable.clone(), stable.join("nightly"), stable.parent().unwrap().to_path_buf()] {
assert!(fixture.refuse(Platform::Linux, &candidate).contains("overlap"));
}
assert_eq!(std::fs::read(stable.join("stable-sentinel")).unwrap(), b"stable bytes");
}
let data = PathBuf::from(fixture.get("XDG_DATA_HOME").unwrap());
let nightly = data.join("ArtCraftLauncher/nightly/profiles/filmcraft");
assert_eq!(fixture.check(Platform::Linux, &nightly).unwrap(), nightly);
assert_eq!(std::fs::read_dir(nightly).unwrap().count(), 0);
}
fn extra_forbidden_roots_cover_platform_install_and_stable_artifacts() {
let fixture = TempDir::new();
let mut env: BTreeMap<String, OsString> = BTreeMap::new();
let home = fixture.root.join("home");
env.insert("HOME".into(), home.clone().into_os_string());
env.insert("XDG_DATA_HOME".into(), fixture.root.join("xdg-data").into_os_string());
env.insert("LOCALAPPDATA".into(), fixture.root.join("local").into_os_string());
env.insert("ProgramFiles".into(), fixture.root.join("pf").into_os_string());
env.insert("ProgramW6432".into(), fixture.root.join("pf64").into_os_string());
env.insert("ProgramFiles(x86)".into(), fixture.root.join("pf86").into_os_string());
#[test]
fn linux_fences_the_dev_desktop_entry_the_icon_theme_and_the_stable_flatpak() {
let mut fixture = Fixture::new();
let data = fixture.root.join("xdg-data");
fixture.env.insert("XDG_DATA_HOME".into(), data.clone().into_os_string());
for stable in [data.join("applications/ai.storyteller.filmcraft.desktop"), data.join("icons/hicolor")] {
assert!(fixture.refuse(Platform::Linux, &stable.join("nightly")).contains("overlap"));
}
let flatpak = fixture.home().join(".var/app/ai.storyteller.filmcraft");
for candidate in [flatpak.clone(), flatpak.join("data/nightly")] {
assert!(fixture.refuse(Platform::Linux, &candidate).contains("overlap"));
}
assert!(!flatpak.exists());
// These are POSIX absolute paths: on a Windows host `/usr/bin/...` has no root and fails the
// absolute-path check before the fence, so the case only means anything on unix.
#[cfg(unix)]
for install in ["/usr/bin/filmcraft", "/usr/local/bin/filmcraft", "/opt/filmcraft"] {
assert!(fixture.refuse(Platform::Linux, &PathBuf::from(install).join("profile")).contains("overlap"));
}
assert!(fixture.check(Platform::Linux, &fixture.home().join(".var/app/ai.storyteller.launcher/nightly")).is_ok());
}
let roots = extra_forbidden_roots(&|key| env.get(key).cloned());
#[test]
fn mac_fences_only_app_library_subtrees_and_the_entire_bundle() {
let mut fixture = Fixture::new();
fixture.exe = fixture.root.join("install/FilmCraft Nightly.app/Contents/MacOS/FilmCraft");
std::fs::create_dir_all(fixture.exe.parent().unwrap()).unwrap();
std::fs::write(&fixture.exe, b"fixture executable, never run").unwrap();
let library = fixture.home().join("Library");
for suffix in [
"Application Support/FilmCraft",
"Caches/FilmCraft",
"Caches/ai.storyteller.filmcraft",
"Preferences/FilmCraft",
"Preferences/ai.storyteller.filmcraft.plist",
"Saved Application State/ai.storyteller.filmcraft.savedState",
] {
let stable = library.join(suffix);
assert!(fixture.refuse(Platform::Mac, &stable.join("nightly")).contains("overlap"));
assert!(!stable.exists());
}
let inside_resources = fixture.exe.parent().unwrap().parent().unwrap().join("Resources/profile");
assert!(fixture.refuse(Platform::Mac, &inside_resources).contains("overlap"));
assert!(!inside_resources.exists());
for bundle in [fixture.home().join("Applications/FilmCraft.app"), PathBuf::from("/Applications/FilmCraft.app")] {
assert!(!fixture.refuse(Platform::Mac, &bundle.join("profile")).is_empty());
}
let valid = library.join("Application Support/ArtCraftLauncher/nightly/profiles/filmcraft");
assert_eq!(fixture.check(Platform::Mac, &valid).unwrap(), valid);
}
#[test]
fn windows_roaming_local_and_install_fences_remain_active() {
let fixture = Fixture::new();
for key in ["APPDATA", "LOCALAPPDATA"] {
let stable = PathBuf::from(fixture.get(key).unwrap()).join("FilmCraft");
assert!(fixture.refuse(Platform::Windows, &stable.join("nightly")).contains("overlap"));
assert!(!stable.exists());
}
assert!(!fixture.refuse(Platform::Windows, &fixture.exe.parent().unwrap().join("profile")).is_empty());
assert!(fixture.check(Platform::Windows, &fixture.root.join("Launcher/profiles/filmcraft")).is_ok());
}
#[test]
fn windows_default_msi_install_folders_are_fenced() {
let mut fixture = Fixture::new();
let local = PathBuf::from(fixture.get("LOCALAPPDATA").unwrap());
let per_user = local.join("Programs").join("ArtCraft").join("FilmCraft");
assert!(fixture.refuse(Platform::Windows, &per_user.join("nightly")).contains("overlap"));
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
let base = fixture.root.join(format!("machine {key}"));
fixture.env.insert(key.into(), base.clone().into_os_string());
let machine = base.join("ArtCraft").join("FilmCraft");
assert!(fixture.refuse(Platform::Windows, &machine.join("nightly")).contains("overlap"));
assert!(!machine.exists());
}
let sibling = local.join("Programs").join("ArtCraft").join("ArtCraftLauncher").join("nightly").join("filmcraft");
assert!(fixture.check(Platform::Windows, &sibling).is_ok(), "the Launcher's own Programs sibling is not FilmCraft's install");
}
#[test]
fn overlap_check_handles_ancestor_descendant_and_prefix_lookalikes() {
let fixture = Fixture::new();
let root = fixture.home().join("nightly/profiles/filmcraft");
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
assert!(overlaps(&root, &root.join("Recovery"), platform));
assert!(overlaps(&root.join("Recovery"), &root, platform));
assert!(!overlaps(&root, &root.with_file_name("filmcraft-other"), platform));
}
}
#[cfg(unix)]
#[test]
fn recovery_and_log_aliases_cannot_redirect_to_stable_missing_or_profile_root_data() {
let fixture = Fixture::new();
let stable = fixture.home().join(".local/share/filmcraft/Recovery");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("stable-autosave"), b"stable recovery bytes").unwrap();
for (index, (name, target)) in
[("Recovery", stable.clone()), ("Logs", stable.clone()), ("Recovery", fixture.root.join("missing target"))].into_iter().enumerate()
#[cfg(all(unix, not(target_os = "macos")))]
{
let private = fixture.root.join(format!("nightly-{index}"));
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&target, private.join(name)).unwrap();
assert!(!fixture.refuse(Platform::Linux, &private).is_empty(), "{name} must not escape the private profile");
assert!(roots.contains(&PathBuf::from("/usr/bin/filmcraft")));
assert!(roots.contains(&PathBuf::from("/usr/local/bin/filmcraft")));
assert!(roots.contains(&PathBuf::from("/opt/filmcraft")));
assert!(roots.contains(&fixture.root.join("xdg-data/applications/ai.storyteller.filmcraft.desktop")));
assert!(roots.contains(&fixture.root.join("xdg-data/icons/hicolor")));
assert!(roots.contains(&home.join(".var/app/ai.storyteller.filmcraft")));
}
let private = fixture.root.join("nightly-self");
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&private, private.join("Recovery")).unwrap();
assert!(!fixture.refuse(Platform::Linux, &private).is_empty(), "Recovery cannot treat all profile settings as recovery entries");
assert_eq!(std::fs::read(stable.join("stable-autosave")).unwrap(), b"stable recovery bytes");
}
#[cfg(unix)]
#[test]
fn recovery_and_log_aliases_cannot_alias_a_portable_install_inside_the_profile() {
let fixture = Fixture::new();
for name in ["Recovery", "Logs"] {
// A Stable portable install nested in the selected profile: the alias target resolves
// inside the profile, so only the target's own ancestors can refuse it.
let private = fixture.root.join(format!("nightly-portable-{name}"));
let portable = private.join("downloads/stable");
let stable_data = portable.join("data");
std::fs::create_dir_all(stable_data.join(name)).unwrap();
std::fs::write(portable.join("portable.txt"), b"owned portable fixture").unwrap();
std::fs::write(portable.join("filmcraft"), b"fixture executable, never run").unwrap();
std::fs::write(stable_data.join("preferences.json"), b"stable settings must not change").unwrap();
std::os::unix::fs::symlink(stable_data.join(name), private.join(name)).unwrap();
assert!(fixture.refuse(Platform::Linux, &private).contains("portable"), "{name} must not alias portable data");
assert_eq!(std::fs::read(stable_data.join("preferences.json")).unwrap(), b"stable settings must not change");
#[cfg(target_os = "macos")]
{
assert!(roots.contains(&PathBuf::from("/Applications/FilmCraft.app")));
assert!(roots.contains(&home.join("Applications/FilmCraft.app")));
assert!(roots.contains(&home.join("Library/Preferences/ai.storyteller.filmcraft.plist")));
assert!(roots.contains(&home.join("Library/Saved Application State/ai.storyteller.filmcraft.savedState")));
}
// Ordinary nested directories stay accepted, as before.
let private = fixture.root.join("nightly-plain");
std::fs::create_dir_all(private.join("private-recovery")).unwrap();
std::os::unix::fs::symlink(private.join("private-recovery"), private.join("Recovery")).unwrap();
assert!(fixture.check(Platform::Linux, &private).is_ok());
}
#[test]
fn the_write_probe_does_not_collide_with_another_validation() {
let fixture = Fixture::new();
let dir = fixture.root.join("probe");
std::fs::create_dir(&dir).unwrap();
// A probe another window left in this profile must not refuse this launch.
std::fs::write(dir.join("exclusive-write-probe"), b"another validation").unwrap();
ensure_writable(&dir).unwrap();
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1, "this validation left no probe behind");
}
#[cfg(unix)]
#[test]
fn aliases_inside_the_private_profile_keep_it_usable() {
let fixture = Fixture::new();
let private = fixture.root.join("nightly-private");
let recovery = private.join("private-recovery");
let logs = private.join("private-logs");
std::fs::create_dir_all(&recovery).unwrap();
std::fs::create_dir_all(&logs).unwrap();
std::os::unix::fs::symlink(&recovery, private.join("Recovery")).unwrap();
std::os::unix::fs::symlink(&logs, private.join("Logs")).unwrap();
assert!(fixture.check(Platform::Linux, &private).is_ok());
}
#[cfg(unix)]
#[test]
fn any_profile_entry_alias_must_stay_inside_the_profile() {
let fixture = Fixture::new();
let stable = fixture.home().join(".local/share/filmcraft/effect-presets.json");
std::fs::create_dir_all(stable.parent().unwrap()).unwrap();
std::fs::write(&stable, b"stable preset bytes").unwrap();
for name in ["preferences.json", "workspaces.json", "Media Cache"] {
let private = fixture.root.join(format!("nightly-{name}"));
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&stable, private.join(name)).unwrap();
assert!(!fixture.refuse(Platform::Linux, &private).is_empty(), "{name} must not lead outside the profile");
#[cfg(target_os = "windows")]
{
assert!(roots.contains(&fixture.root.join("local/Programs/ArtCraft/FilmCraft")));
assert!(roots.contains(&fixture.root.join("pf/ArtCraft/FilmCraft")));
assert!(roots.contains(&fixture.root.join("pf64/ArtCraft/FilmCraft")));
assert!(roots.contains(&fixture.root.join("pf86/ArtCraft/FilmCraft")));
}
let private = fixture.root.join("nightly-inside");
std::fs::create_dir_all(private.join("Cache")).unwrap();
std::fs::write(private.join("preferences.json"), b"{}").unwrap();
std::os::unix::fs::symlink(private.join("Cache"), private.join("Media Cache")).unwrap();
assert!(fixture.check(Platform::Linux, &private).is_ok(), "regular files and links that stay inside are fine");
assert_eq!(std::fs::read(&stable).unwrap(), b"stable preset bytes");
}
#[test]
fn ambiguous_environment_and_non_native_sandbox_are_refused_before_creation() {
let mut fixture = Fixture::new();
let candidate = fixture.home().join("nightly/profiles/filmcraft");
fixture.env.insert("XDG_CACHE_HOME".into(), "relative/cache".into());
assert!(fixture.refuse(Platform::Linux, &candidate).contains("absolute"));
fixture.env.remove("XDG_CACHE_HOME");
fixture.env.insert("FILMCRAFT_DATA_DIR".into(), fixture.home().join("custom-stable").into_os_string());
assert!(fixture.refuse(Platform::Linux, &candidate).contains("FILMCRAFT_DATA_DIR"));
fixture.env.remove("FILMCRAFT_DATA_DIR");
fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.filmcraft".into());
assert!(fixture.refuse(Platform::Linux, &candidate).contains("Flatpak"));
fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.filmcraft.nightly-v1".into());
assert!(fixture.refuse(Platform::Linux, &candidate).contains("Flatpak"));
// The Nightly Flatpak itself is a native Nightly: its sandbox is already separate.
fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.filmcraft.nightly".into());
let in_the_nightly_sandbox = fixture.home().join("nightly-flatpak/profile");
assert!(fixture.check(Platform::Linux, &in_the_nightly_sandbox).is_ok(), "the Nightly Flatpak must start");
fixture.env.remove("FLATPAK_ID");
fixture.env.remove("HOME");
assert!(fixture.refuse(Platform::Linux, &candidate).contains("HOME"));
assert!(!candidate.exists());
}
fn nightly_profile_validates_hardens_and_reopens_with_settings_and_folders() {
let fixture = TempDir::new();
let private = fixture.root.join("nightly-profile");
let spec = app_profile_spec_with_env(|_| None);
#[test]
fn failed_write_probe_never_falls_back_to_stable() {
let fixture = Fixture::new();
let candidate = fixture.home().join("nightly-profile");
let refused = validate_for(Platform::Linux, &candidate, |key| fixture.get(key), Some(&fixture.exe), |_| Err(std::io::Error::other("read-only")));
assert!(refused.unwrap_err().contains("not writable"));
// The directory was created (and is empty), but nothing fell back to a stable location.
assert_eq!(std::fs::read_dir(&candidate).unwrap().count(), 0);
assert!(!fixture.home().join(".local/share/filmcraft").exists());
}
let confirmed = validate_and_prepare_root(&private, &spec).unwrap();
assert_eq!(confirmed, private);
#[test]
fn created_profile_is_owner_only_on_unix() {
let fixture = Fixture::new();
let private = fixture.check(Platform::Linux, &fixture.home().join("nightly/private")).unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt as _;
assert_eq!(std::fs::metadata(&private).unwrap().permissions().mode() & 0o777, 0o700);
assert_eq!(std::fs::metadata(&confirmed).unwrap().permissions().mode() & 0o777, 0o700);
}
assert!(private.is_dir());
for name in ["preferences.json", "workspaces.json", "nightly-session.lock", "nightly-session.json"] {
std::fs::write(confirmed.join(name), b"saved profile data").unwrap();
}
for name in FOLDER_ONLY_ENTRIES {
std::fs::create_dir(confirmed.join(name)).unwrap();
}
assert_eq!(validate_and_prepare_root(&private, &spec).unwrap(), private);
for name in FOLDER_ONLY_ENTRIES {
let path = confirmed.join(name);
std::fs::remove_dir(&path).unwrap();
std::fs::write(&path, b"not a directory").unwrap();
assert!(matches!(validate_and_prepare_root(&private, &spec), Err(ProfileError::ExpectedDirectoryEntry(_))), "{name} must stay a directory");
std::fs::remove_file(&path).unwrap();
std::fs::create_dir(&path).unwrap();
}
}
#[test]
fn extra_forbidden_roots_refuse_overlapping_profiles() {
let fixture = TempDir::new();
let forbidden = fixture.root.join("forbidden-install");
let mut spec = app_profile_spec_with_env(|_| None);
spec.extra_forbidden_roots.push(forbidden.clone());
let result = validate_and_prepare_root(&forbidden.join("nightly"), &spec);
assert!(matches!(result, Err(ProfileError::ForbiddenRootOverlap { .. })));
assert!(!forbidden.exists());
}
}
+2
View File
@@ -32,5 +32,7 @@ symphonia = { version = "0.5.5", default-features = false, features = ["aac", "m
[dev-dependencies]
filmcraft-testkit = { workspace = true }
# synthetic DNG frames for the CinemaDNG-in-MXF tests
filmcraft-dng = { workspace = true, features = ["writer"] }
serde_json = { workspace = true }
image = { version = "0.25", default-features = false, features = ["jpeg"] }
+86 -5
View File
@@ -9,6 +9,10 @@
//! - Audio: every PCM sound track (Broadcast Wave / AES3, ST 382; ST 331 AES3 elements in D-10)
//! is presented as one multichannel stream, sample-exact.
//! - Start timecode: the material package's timecode track.
//! - CinemaDNG (CinemaDNG Image Data Format Specification §7: one frame-wrapped DNG dataset per
//! edit unit): each picture is developed on its own by `filmcraft-dng` (through
//! `filmcraft_media::still::dng`, as DNG stills and CinemaDNG folders are) into scene-linear
//! Rec. 709 float frames; size and pixel format come from the first DNG, not the descriptor.
use std::sync::Arc;
@@ -26,6 +30,15 @@ pub fn sniff(head: &[u8]) -> bool {
craft_media::mxf::sniff(head)
}
/// CinemaDNG pictures of an MXF file.
struct DngPictures {
/// Developed pictures by (stored index, reduced-resolution level).
cache: filmcraft_media::FrameCache<(usize, u8)>,
settings: filmcraft_media::raw::RawSettings,
/// The first picture's as-shot white balance (temperature, tint).
as_shot: Option<(f64, f64)>,
}
pub struct MxfSource {
info: MediaInfo,
bytes: crate::Src,
@@ -44,6 +57,8 @@ pub struct MxfSource {
unsupported: Option<String>,
/// MPEG-2: the first sequence header (primes decoders that start without one).
mpeg2_header: Vec<u8>,
/// CinemaDNG: every picture is intra coded and developed on its own, outside the GOP cache.
dng: Option<DngPictures>,
/// Sound tracks combined into one stream: (track, first stored sample frame).
atracks: Vec<(usize, u64)>,
/// Presented sample frames.
@@ -211,6 +226,33 @@ fn avc_order_from_samples(r: &dyn filmcraft_media::ByteReader, samples: &[craft_
const AVC_ORDER_HEAD: usize = 2 << 10;
const AVC_ORDER_HEAD_MAX: usize = 16 << 10;
/// The first DNG's developed size, pixel format and as-shot white balance (or why it failed).
type DngProbe = Result<(u32, u32, String, Option<(f64, f64)>), MediaError>;
/// CinemaDNG: the first DNG's developed size, pixel format and as-shot white balance (the RGBA
/// descriptor describes the decoded picture, but nothing checks it does).
fn probe_cinema_dng(file: &MxfFile, bytes: &crate::Src, track: usize, name: &str) -> DngProbe {
let s = file.read_sample(bytes, track, 0).map_err(|e| MediaError::Decode(e.to_string()))?;
let (w, h, pf, _) = filmcraft_media::still::dng::probe(name, &s)?;
Ok((w, h, pf, filmcraft_media::still::dng::as_shot(&s)))
}
/// CinemaDNG: the codec name for the probe result, setting up the developed-picture cache, or
/// the reason the track cannot be played.
fn cinema_dng_codec(probe: Option<&DngProbe>, dng: &mut Option<DngPictures>, unsupported: &mut Option<String>) -> String {
match probe {
Some(Ok((_, _, _, as_shot))) => {
*dng = Some(DngPictures { cache: filmcraft_media::FrameCache::new(256 << 20), settings: Default::default(), as_shot: *as_shot });
filmcraft_media::still::dng::MXF_CODEC.into()
}
Some(Err(e)) => {
*unsupported = Some(format!("CinemaDNG in MXF: {e}"));
"CinemaDNG (unsupported)".into()
}
None => "CinemaDNG".into(),
}
}
impl MxfSource {
pub fn open(name: &str, bytes: Arc<[u8]>) -> crate::Result<Self> {
Self::open_reader(name, Arc::new(filmcraft_media::reader::MemReader(bytes)))
@@ -243,6 +285,7 @@ impl MxfSource {
let (mut vpts, mut vorder, mut vfirst, mut vcount) = (Vec::new(), Vec::new(), 0, 0);
let mut explicit_color = None;
let mut mpeg2_header = Vec::new();
let mut dng = None;
if let Some(vi) = vtrack {
let t = &file.tracks[vi];
let p = t.picture.clone().unwrap_or_default();
@@ -277,11 +320,16 @@ impl MxfSource {
.then(|| file.read_sample(&bytes, vi, 0).ok())
.flatten()
.and_then(|s| Some((craft_video::mpeg2::probe(&s)?, craft_video::mpeg2::scan_access_unit(&s), crate::video::mpeg2_sequence_header(&s)?)));
let (w, h) = match &mpeg {
Some((info, _, _)) => (info.width, info.height),
None => (p.frame_width(), p.frame_height()),
let dng_probe = (t.codec == Codec::CinemaDng).then(|| probe_cinema_dng(&file, &bytes, vi, name));
let (w, h) = match (&mpeg, &dng_probe) {
(Some((info, _, _)), _) => (info.width, info.height),
(None, Some(Ok((w, h, _, _)))) => (*w, *h),
_ => (p.frame_width(), p.frame_height()),
};
let par = if p.aspect_ratio.is_valid() && w > 0 && h > 0 {
let par = if dng_probe.is_some() {
// DNG DefaultScale is not applied: pixels are shown square
(1, 1)
} else if p.aspect_ratio.is_valid() && w > 0 && h > 0 {
let n = p.aspect_ratio.num as u64 * h as u64;
let d = p.aspect_ratio.den as u64 * w as u64;
let g = gcd(n, d).max(1);
@@ -299,6 +347,7 @@ impl MxfSource {
Codec::ProRes { profile } => prores_name(profile).into(),
c @ Codec::Avc { .. } => c.name().into(),
Codec::Mpeg2 if mpeg.is_some() => mpeg.as_ref().map(|m| m.0.codec_name()).unwrap_or_default(),
Codec::CinemaDng => cinema_dng_codec(dng_probe.as_ref(), &mut dng, &mut unsupported),
other => {
let why = format!("{} video in MXF (FilmCraft has no {} decoder)", other.name(), other.name());
unsupported = Some(why);
@@ -326,7 +375,11 @@ impl MxfSource {
mpeg2_header = header.clone();
}
let mut color = filmcraft_color::ColorInfo { matrix: filmcraft_frame::default_matrix(w, h), ..filmcraft_color::ColorInfo::REC709 };
if p.full_range() {
// CinemaDNG (developed: `dng` is set exactly when the probe succeeded)
if let Some(Ok((_, _, pf, _))) = &dng_probe {
pixel_format = pf.clone();
color = filmcraft_media::still::dng::LINEAR_709;
} else if p.full_range() {
color.range = filmcraft_color::Range::Full;
explicit_color = Some(color);
}
@@ -408,12 +461,25 @@ impl MxfSource {
video: GopCache::new(explicit_color),
unsupported,
mpeg2_header,
dng,
atracks: combined,
aframes,
file,
})
}
/// CinemaDNG: develop the picture shown at display position `d` at reduced-resolution `level`.
fn dng_frame(&self, track: usize, dng: &DngPictures, d: i64, level: u8) -> Result<Arc<VideoFrame>, MediaError> {
let stored = usize::try_from(d).ok().and_then(|d| self.vorder.get(d).copied()).ok_or(MediaError::Decode("MXF: picture out of range".into()))?;
if let Some(f) = dng.cache.get(&(stored, level)) {
return Ok(f);
}
let bytes = self.file.read_sample(&self.bytes, track, stored).map_err(|e| MediaError::Decode(e.to_string()))?;
let frame = Arc::new(filmcraft_media::still::dng::decode_with(&self.info.name, &bytes, &dng.settings, level)?.frame);
dng.cache.insert((stored, level), frame.clone());
Ok(frame)
}
/// The demuxed file (tracks, partitions, index, timecode).
pub fn file(&self) -> &MxfFile {
&self.file
@@ -482,6 +548,9 @@ impl MediaSource for MxfSource {
}
let rate = self.info.frame_rate();
let f = rate.frame_at(req.time.max(Tick::ZERO)).clamp(0, self.vcount - 1);
if let Some(dng) = &self.dng {
return self.dng_frame(ti, dng, self.vfirst + f, filmcraft_media::raw::scale_level(req.scale));
}
let late = filmcraft_media::cancel::catch_up().map(|m| self.vfirst + rate.frame_at(req.time - m));
let frame = self.video.frame_late(&MxfVideo { src: self, track: ti }, self.vfirst + f, late)?;
Ok(frame)
@@ -525,6 +594,18 @@ impl MediaSource for MxfSource {
filmcraft_media::resample_window_into(&src, s0, src_rate, start, sample_rate, &mut out.channels);
Ok(out)
}
fn raw_info(&self) -> Option<filmcraft_media::raw::RawInfo> {
self.dng.as_ref().map(|d| filmcraft_media::raw::RawInfo { as_shot: d.as_shot, settings: d.settings })
}
fn with_raw_settings(&self, settings: &filmcraft_media::raw::RawSettings) -> Option<SharedSource> {
self.dng.as_ref()?;
// a fresh source over the same reader (the index and metadata are read again)
let mut s = MxfSource::open_reader(&self.info.name, self.bytes.0.clone()).ok()?;
s.dng.as_mut()?.settings = *settings;
Some(Arc::new(s))
}
}
pub fn opener(name: &str, bytes: Arc<[u8]>) -> Option<Result<SharedSource, MediaError>> {
+195
View File
@@ -0,0 +1,195 @@
//! CinemaDNG in MXF (CinemaDNG Image Data Format Specification 1.0.0.0, §7): synthetic OP1a
//! files from our MXF writer, wrapping DNG frames from the `filmcraft-dng` test writer, one
//! frame-wrapped DNG dataset per edit unit with PCM sound and a start timecode. No tool we can
//! run reads CinemaDNG MXF, so the expected values are the DNGs' own (known) contents.
use std::io::Cursor;
use std::sync::Arc;
use craft_media::mxf::{FrameInfo, MxfWriter, PackageIds, Pattern, PictureCoding, PictureDesc, Rational, SoundDesc, StartTimecode, WriterConfig};
use filmcraft_codecs::MxfSource;
use filmcraft_color::Transfer;
use filmcraft_dng::tiff::tags;
use filmcraft_dng::writer::{Compression, Options, Value, write};
use filmcraft_frame::{PixelData, VideoFrame};
use filmcraft_media::{FrameRequest, MediaKind, MediaSource};
use filmcraft_time::FrameRate;
const W: usize = 16;
const H: usize = 12;
/// A 16 × 12 DNG of a flat grey at `level` of the 12-bit range: RGGB lossless JPEG white balanced
/// by neutral (0.5, 1, 0.5), or LinearRaw (three samples per pixel, uncompressed).
fn grey_dng(level: f64, linear_raw: bool) -> Vec<u8> {
let neutral = [0.5, 1.0, 0.5];
let mut o = Options {
width: W,
height: H,
bits: 12,
raw_tags: vec![(tags::WHITE_LEVEL, Value::Short(vec![4095; if linear_raw { 3 } else { 1 }]))],
main_tags: vec![(tags::AS_SHOT_NEUTRAL, Value::rationals(&neutral))],
..Default::default()
};
let px: Vec<u16> = if linear_raw {
o.samples_per_pixel = 3;
o.cfa = None;
(0..W * H * 3).map(|i| (level * neutral[i % 3] * 4095.0).round() as u16).collect()
} else {
o.compression = Compression::LosslessJpeg { predictor: 1, components: 2, restart_lines: 0, pt: 0 };
let pat = [0usize, 1, 1, 2];
(0..W * H).map(|i| (level * neutral[pat[(i / W % 2) * 2 + i % W % 2]] * 4095.0).round() as u16).collect()
};
write(&px, &o)
}
fn level(i: usize) -> f64 {
0.1 + 0.15 * i as f64
}
/// An OP1a CinemaDNG file: `n` frames at 24 fps, stereo 16-bit sound (sample k of channel 0 = k,
/// channel 1 = −k), start timecode 10:00:00:00.
fn cinemadng_mxf(n: usize, linear_raw: bool) -> Vec<u8> {
let rate = Rational::new(24, 1);
let mut cfg = WriterConfig::new(Pattern::Op1a, rate, PackageIds::from_seed("cinemadng test", "A001_C001"));
cfg.picture = Some(PictureDesc::new(PictureCoding::CinemaDng { linear_raw }, W as u32, H as u32));
cfg.sound = vec![SoundDesc { sample_rate: 48_000, channels: 2, bits: 16 }];
cfg.timecode = Some(StartTimecode { frames: 10 * 3600 * 24, rate, drop_frame: false });
let mut w = MxfWriter::new(Cursor::new(Vec::new()), cfg).unwrap();
for i in 0..n {
w.push_picture(&grey_dng(level(i), linear_raw), FrameInfo::intra()).unwrap();
let mut pcm = Vec::new();
for k in i * 2000..(i + 1) * 2000 {
pcm.extend_from_slice(&(k as i16).to_le_bytes());
pcm.extend_from_slice(&(-(k as i16)).to_le_bytes());
}
w.push_sound(0, &pcm).unwrap();
}
w.finish().unwrap().into_inner()
}
fn red(f: &VideoFrame) -> f32 {
match &f.data {
PixelData::RgbaF32(p) => p[(5 * W + 5) * 4],
_ => panic!("float frames"),
}
}
#[test]
fn cinemadng_mxf_plays_every_frame() {
for linear_raw in [false, true] {
let f = cinemadng_mxf(5, linear_raw);
let src = MxfSource::open("A001_C001.mxf", f.into()).unwrap();
let info = src.info();
assert_eq!(info.kind, MediaKind::Movie);
assert_eq!(info.container, "MXF OP1a");
let v = info.video.as_ref().unwrap();
assert_eq!((v.width, v.height, v.codec.as_str(), v.has_alpha, v.par), (16, 12, "CinemaDNG", false, (1, 1)));
let pf = if linear_raw { "linear 12-bit raw (uncompressed)" } else { "Bayer 12-bit raw (lossless JPEG)" };
assert_eq!(v.pixel_format, pf);
assert_eq!(v.color.transfer, Transfer::Linear);
assert_eq!(info.frame_rate(), FrameRate::FPS_24);
assert_eq!(info.duration, FrameRate::FPS_24.tick_of(5));
assert_eq!(info.start_timecode, Some(10 * 3600 * 24));
// every frame, in a scrambled order (each is developed on its own)
for i in [3usize, 0, 4, 1, 2, 3] {
let frame = src.video_frame(FrameRequest::full(FrameRate::FPS_24.tick_of(i as i64))).unwrap();
assert_eq!((frame.width, frame.height, frame.color.transfer), (16, 12, Transfer::Linear));
assert!((red(&frame) - level(i) as f32).abs() < 1e-3, "frame {i}: {}", red(&frame));
}
// the sound beside the pictures, sample-exact
let a = src.audio(1234, 3000, 48_000).unwrap();
for (j, k) in (1234..4234).enumerate() {
assert_eq!(a.channels[0][j], k as f32 / 32768.0);
assert_eq!(a.channels[1][j], -(k as f32) / 32768.0);
}
}
}
#[test]
fn cinemadng_mxf_opens_through_the_registered_openers() {
let f: Arc<[u8]> = cinemadng_mxf(2, false).into();
let src = filmcraft_media::open_bytes("clip.mxf", f, &filmcraft_codecs::openers()).unwrap();
assert_eq!(src.info().video.as_ref().unwrap().codec, "CinemaDNG");
assert!(src.video_frame(FrameRequest::full(FrameRate::FPS_24.tick_of(1))).is_ok());
}
#[test]
fn broken_dng_frames_are_errors_not_panics() {
// a picture that is not a DNG: the file opens (sound plays), the picture is unsupported
let rate = Rational::new(24, 1);
let mut cfg = WriterConfig::new(Pattern::Op1a, rate, PackageIds::from_seed("bad", "bad"));
cfg.picture = Some(PictureDesc::new(PictureCoding::CinemaDng { linear_raw: false }, 16, 12));
let mut w = MxfWriter::new(Cursor::new(Vec::new()), cfg).unwrap();
w.push_picture(b"II*\0\x08\0\0\0garbage", FrameInfo::intra()).unwrap();
let f = w.finish().unwrap().into_inner();
let src = MxfSource::open("bad.mxf", f.into()).unwrap();
assert!(src.info().video.as_ref().unwrap().codec.contains("unsupported"));
assert!(src.video_frame(FrameRequest::full(filmcraft_time::Tick::ZERO)).is_err());
// nothing to develop: no raw settings
assert!(src.raw_info().is_none());
assert!(src.with_raw_settings(&filmcraft_media::raw::RawSettings::default()).is_none());
}
#[test]
fn truncated_and_mutated_files_never_panic() {
let f = cinemadng_mxf(3, false);
let try_all = |b: Vec<u8>| {
let r = std::panic::catch_unwind(|| {
if let Ok(src) = MxfSource::open("x.mxf", b.into()) {
for i in 0..4 {
let _ = src.video_frame(FrameRequest::full(FrameRate::FPS_24.tick_of(i)));
}
let _ = src.audio(0, 5000, 48_000);
}
});
assert!(r.is_ok());
};
for n in (0..f.len()).step_by(97) {
try_all(f[..n].to_vec());
}
let mut seed = 0x9E37_79B9_7F4A_7C15u64;
for _ in 0..400 {
let mut b = f.clone();
for _ in 0..4 {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
let at = (seed as usize) % b.len();
b[at] ^= (seed >> 32) as u8 | 1;
}
try_all(b);
}
}
#[test]
fn raw_settings_reach_every_mxf_picture() {
let src = MxfSource::open("A001_C001.mxf", cinemadng_mxf(3, false).into()).unwrap();
let raw = src.raw_info().unwrap();
assert_eq!(raw.settings, filmcraft_media::raw::RawSettings::default());
let bright = src.with_raw_settings(&filmcraft_media::raw::RawSettings { exposure: 1.0, ..Default::default() }).unwrap();
assert_eq!(bright.info(), src.info());
assert_eq!(bright.raw_info().unwrap().settings.exposure, 1.0);
for i in 0..3 {
let t = FrameRate::FPS_24.tick_of(i as i64);
let (a, b) = (red(&src.video_frame(FrameRequest::full(t)).unwrap()), red(&bright.video_frame(FrameRequest::full(t)).unwrap()));
assert!((b - 2.0 * a).abs() < 1e-3 && (a - level(i) as f32).abs() < 1e-3, "frame {i}: {a} {b}");
// a reduced-resolution request: never smaller than asked for, same values
let q = bright.video_frame(FrameRequest { time: t, scale: 0.25 }).unwrap();
assert!(q.width >= 4 && q.height >= 3 && q.width < 16, "{}x{}", q.width, q.height);
}
// the sound is still there
assert!(bright.audio(0, 100, 48_000).is_ok());
}
#[test]
fn cinemadng_descriptor_rejects_other_depths() {
// CinemaDNG §7.2.2.3: the decoded image is 16 bits per component; another `depth` is an error
let rate = Rational::new(24, 1);
let mut cfg = WriterConfig::new(Pattern::Op1a, rate, PackageIds::from_seed("depth", "depth"));
let mut pd = PictureDesc::new(PictureCoding::CinemaDng { linear_raw: false }, W as u32, H as u32);
pd.depth = 10;
cfg.picture = Some(pd);
let err = MxfWriter::new(Cursor::new(Vec::new()), cfg).err().expect("depth 10 must be rejected");
assert_eq!(err.kind(), std::io::ErrorKind::InvalidInput);
assert!(err.to_string().contains("16 bits"), "{err}");
}
+4
View File
@@ -14,6 +14,10 @@ writer = []
# serde derives on the raw settings (`ProcessOptions`) for UI state and project files.
serde = ["dep:serde"]
[[example]]
name = "bench"
required-features = ["writer", "threads"]
[dependencies]
craft-tiff = { workspace = true }
craft-raw = { workspace = true, features = ["line-dng"] }
+17 -11
View File
@@ -93,6 +93,22 @@ pub enum TrimMode {
/// `links` maps old link groups to the new group for right-hand pieces (so linked partners split
/// in the same operation stay linked to each other).
pub fn split_track_at(track: &mut Track, t: Tick, ctx: &mut EditCtx, links: &mut HashMap<u64, u64>) -> Option<ClipId> {
let (old_id, new_id) = split_track_item(track, t, ctx, links)?;
// transitions: those after the cut that referenced the left piece now reference the right one;
// a transition spanning the cut on this clip's interior is removed.
track
.transitions
.retain(|tr| !(tr.start < t && t < tr.end() && (tr.from == Some(old_id) || tr.to == Some(old_id)) && !(tr.from.is_some() && tr.to.is_some())));
for tr in &mut track.transitions {
if tr.start >= t && tr.from == Some(old_id) {
tr.from = Some(new_id);
}
}
Some(new_id)
}
/// Split the clip and its link group. The caller places any transitions on the resulting edges.
fn split_track_item(track: &mut Track, t: Tick, ctx: &mut EditCtx, links: &mut HashMap<u64, u64>) -> Option<(ClipId, ClipId)> {
let idx = track.items.iter().position(|i| i.start < t && t < i.end())?;
let left = &mut track.items[idx];
let mut right = left.clone();
@@ -116,19 +132,9 @@ pub fn split_track_at(track: &mut Track, t: Tick, ctx: &mut EditCtx, links: &mut
let nl = *links.entry(l).or_insert_with(|| ctx.alloc());
right.link = Some(nl);
}
// transitions: those after the cut that referenced the left piece now reference the right one;
// a transition spanning the cut on this clip's interior is removed.
let old_id = track.items[idx].id;
track
.transitions
.retain(|tr| !(tr.start < t && t < tr.end() && (tr.from == Some(old_id) || tr.to == Some(old_id)) && !(tr.from.is_some() && tr.to.is_some())));
for tr in &mut track.transitions {
if tr.start >= t && tr.from == Some(old_id) {
tr.from = Some(new_id);
}
}
track.items.insert(idx + 1, right);
Some(new_id)
Some((old_id, new_id))
}
/// Remove all material in `range` on a track (splitting items at the boundaries).
+112 -48
View File
@@ -4,12 +4,12 @@
//! A multi-camera clip is a track item whose [`TrackItem::multicam`] is set; it refers to a
//! multi-camera source sequence. Its angle is a camera index of that source.
use std::collections::HashMap;
use std::collections::{BTreeMap, HashMap, HashSet};
use filmcraft_project::{ClipId, ItemId, MulticamSel, Sequence, Track, TrackId, TrackItem};
use filmcraft_project::{ClipId, ItemId, MulticamSel, Sequence, Track, TrackId, TrackItem, TrackKind};
use filmcraft_time::{Tick, TimeRange};
use crate::{EditCtx, EditError, Result, remove_orphan_transitions, split_track_at};
use crate::{EditCtx, EditError, Result, remove_orphan_transitions, split_track_at, split_track_item};
/// Whether `it` is a multi-camera clip (enabled or not).
pub fn is_multicam(it: &TrackItem) -> bool {
@@ -54,30 +54,21 @@ pub fn set_enabled(seq: &mut Sequence, clips: &[ClipId], enabled: bool) -> usize
/// Two adjacent pieces of one multi-camera clip that a cut between them would not change.
fn continuous(a: &TrackItem, b: &TrackItem) -> bool {
a.end() == b.start
&& a.item == b.item
&& a.multicam.is_some()
&& a.multicam == b.multicam
&& a.speed == b.speed
&& !a.reverse
&& !b.reverse
&& a.frame_hold.is_none()
&& b.frame_hold.is_none()
&& a.source_out() == b.source_in
&& a.enabled == b.enabled
&& a.gain_db == b.gain_db
&& a.effects == b.effects
a.multicam.is_some() && !a.reverse && a.frame_hold.is_none() && a.source_out() == b.source_in && crate::through::is_through_edit(a, b)
}
/// Remove through edits between pieces of the same multi-camera clip showing the same angle,
/// for edit points in `range` (inclusive of its ends). Returns the ids of the removed pieces.
pub fn heal_track(track: &mut Track, range: TimeRange) -> Vec<ClipId> {
heal_track_where(track, |a, b| b.start >= range.start && b.start <= range.end() && continuous(a, b))
}
fn heal_track_where(track: &mut Track, can_join: impl Fn(&TrackItem, &TrackItem) -> bool) -> Vec<ClipId> {
let mut removed = Vec::new();
let mut i = 0;
while i + 1 < track.items.len() {
let (a, b) = (&track.items[i], &track.items[i + 1]);
let at = b.start;
if at >= range.start && at <= range.end() && continuous(a, b) {
if can_join(a, b) {
let (aid, bid) = (a.id, b.id);
let dur = b.duration;
track.items[i].duration += dur;
@@ -105,47 +96,120 @@ pub fn heal_track(track: &mut Track, range: TimeRange) -> Vec<ClipId> {
pub struct Cut {
pub time: Tick,
pub angle: u32,
/// Whether linked audio follows this particular switch.
pub switch_audio: bool,
}
/// Apply a recording pass: on `tracks`, the multi-camera clips of `source` get angle `cuts[i].angle` from
/// `cuts[i].time` until the next cut, the last one until `end`. Clips are split at each cut and at
/// `end`; afterwards through edits inside the recorded range are healed, so pressing the angle that
/// is already showing adds no edit. Locked tracks are skipped. Returns the number of edit points
/// in the recorded range after the pass.
pub fn record(seq: &mut Sequence, tracks: &[TrackId], source: ItemId, cuts: &[Cut], end: Tick, ctx: &mut EditCtx) -> usize {
let mut cuts: Vec<Cut> = cuts.iter().copied().filter(|c| c.time < end).collect();
cuts.sort_by_key(|c| c.time);
// two presses at one time: the later wins
let mut dedup: Vec<Cut> = Vec::new();
for c in cuts {
match dedup.last_mut() {
Some(l) if l.time == c.time => *l = c,
_ => dedup.push(c),
}
/// For simultaneous presses, keep the last one that applies to this track kind.
fn track_cuts(cuts: impl Iterator<Item = Cut>) -> Vec<Cut> {
let mut by_time = BTreeMap::new();
for cut in cuts {
by_time.insert(cut.time, cut);
}
let Some(first) = dedup.first().map(|c| c.time) else { return 0 };
let mut links = HashMap::new();
let mut points = 0;
for tr in seq.all_tracks_mut() {
if tr.locked || !tracks.contains(&tr.id) {
continue;
by_time.into_values().collect()
}
/// A linked edit can disappear only when every member on both sides can join its
/// partner at the same time. Decide on the unsimplified tracks so track order cannot
/// change the outcome. Right-hand clip IDs stay valid across consecutive joins.
fn recorded_joins(seq: &Sequence, participants: &HashSet<ClipId>, first: Tick, end: Tick) -> HashSet<ClipId> {
let mut group_sizes = HashMap::<u64, usize>::new();
let mut linked = HashMap::<(u64, u64, Tick), Vec<ClipId>>::new();
let mut joins = HashSet::new();
for track in seq.all_tracks() {
for link in track.items.iter().filter_map(|item| item.link) {
*group_sizes.entry(link).or_default() += 1;
}
let mc_at = |tr: &Track, t: Tick| tr.items.iter().any(|i| i.start < t && t < i.end() && is_multicam(i) && i.item == source);
for t in dedup.iter().map(|c| c.time).chain([end]) {
if mc_at(tr, t) {
split_track_at(tr, t, ctx, &mut links);
for pair in track.items.windows(2) {
let (a, b) = (&pair[0], &pair[1]);
if b.start < first || b.start > end || !participants.contains(&a.id) || !participants.contains(&b.id) {
continue;
}
if !continuous(a, b) || track.transitions.iter().any(|tr| tr.from == Some(a.id) || tr.to == Some(b.id)) {
continue;
}
match (a.link, b.link) {
(Some(left), Some(right)) => linked.entry((left, right, b.start)).or_default().push(b.id),
(None, None) => {
joins.insert(b.id);
}
_ => {}
}
}
for (k, c) in dedup.iter().enumerate() {
let r_end = dedup.get(k + 1).map_or(end, |n| n.time);
for it in tr.items.iter_mut().filter(|i| i.start >= c.time && i.end() <= r_end && i.item == source) {
}
for ((left, right, _), members) in linked {
if group_sizes.get(&left) == Some(&members.len()) && group_sizes.get(&right) == Some(&members.len()) {
joins.extend(members);
}
}
joins
}
/// Keep audio transitions attached to their actual clip edges. A fade keeps its
/// full timeline range across a picture edit, even if the edge piece gets shorter.
fn split_recorded_audio(track: &mut Track, at: Tick, ctx: &mut EditCtx, links: &mut HashMap<u64, u64>) -> Option<ClipId> {
let (left, right) = split_track_item(track, at, ctx, links)?;
for transition in &mut track.transitions {
if transition.from == Some(left) {
transition.from = Some(right);
}
}
Some(right)
}
/// Apply a live pass to the source's video and linked audio tracks. Each eligible cut runs
/// until the next eligible cut on that track, or until the pass ends. Locked tracks are skipped.
/// Through edits are healed; returns the number of edit points inside the recorded range.
pub fn record(seq: &mut Sequence, tracks: &[TrackId], source: ItemId, cuts: &[Cut], end: Tick, ctx: &mut EditCtx) -> usize {
let before_end = cuts.iter().copied().filter(|cut| cut.time < end);
let video = track_cuts(before_end.clone());
let audio = track_cuts(before_end.filter(|cut| cut.switch_audio));
let Some(first) = video.first().map(|c| c.time) else { return 0 };
let mut participants = HashSet::new();
let mut video_links = HashSet::new();
for tr in seq.video_tracks.iter().filter(|tr| tracks.contains(&tr.id) && !tr.locked) {
for item in tr.items.iter().filter(|i| i.item == source && is_multicam(i) && i.end() >= first && i.start <= end) {
participants.insert(item.id);
video_links.extend(item.link);
}
}
for tr in seq.audio_tracks.iter().filter(|tr| tracks.contains(&tr.id) && !tr.locked) {
participants.extend(tr.items.iter().filter(|i| i.item == source && is_multicam(i) && i.link.is_some_and(|l| video_links.contains(&l))).map(|i| i.id));
}
let mut links_by_time = HashMap::new();
for tr in seq.all_tracks_mut().filter(|tr| !tr.locked && tracks.contains(&tr.id)) {
// Split linked picture and sound together even when only one angle changes.
// Right-to-left splitting gives both partners the same original link at each cut.
let split = match tr.kind {
TrackKind::Audio => split_recorded_audio,
TrackKind::Video => split_track_at,
};
for t in std::iter::once(end).chain(video.iter().rev().map(|c| c.time)) {
if tr.item_at(t).is_some_and(|i| i.start < t && participants.contains(&i.id))
&& let Some(right) = split(tr, t, ctx, links_by_time.entry(t).or_default())
{
participants.insert(right);
}
}
let cuts = match tr.kind {
TrackKind::Video => &video,
TrackKind::Audio => &audio,
};
for (k, c) in cuts.iter().enumerate() {
let r_end = cuts.get(k + 1).map_or(end, |n| n.time);
for it in tr.items.iter_mut().filter(|i| i.start >= c.time && i.end() <= r_end && participants.contains(&i.id)) {
if let Some(m) = &mut it.multicam {
m.angle = c.angle;
}
}
}
heal_track(tr, TimeRange::from_bounds(first, end));
points += tr.items.iter().filter(|i| i.start > first && i.start < end).count();
}
let joins = recorded_joins(seq, &participants, first, end);
let mut points = 0;
for tr in seq.all_tracks_mut().filter(|tr| !tr.locked && tracks.contains(&tr.id)) {
heal_track_where(tr, |_, b| joins.contains(&b.id));
points += tr.items.iter().filter(|i| i.start > first && i.start < end && participants.contains(&i.id)).count();
}
points
}
+4
View File
@@ -58,6 +58,10 @@ impl Alignment {
/// outgoing clip's start, the cut and the incoming clip's end; for a fade to or from nothing the cut
/// is its clip's edge. `None` when its clips are gone.
pub fn bounds(track: &Track, tr: &Transition) -> Option<(Tick, Tick, Tick)> {
if let Some(span) = track.multicam_fade_span(tr) {
let cut = if tr.to.is_some() { span.start } else { span.end() };
return Some((span.start, cut, span.end()));
}
let from = tr.from.and_then(|c| track.item(c));
let to = tr.to.and_then(|c| track.item(c));
match (from, to) {
+1
View File
@@ -52,5 +52,6 @@ image = { version = "0.25", default-features = false, features = ["png", "gif"]
filmcraft-testkit = { workspace = true }
tempfile = "3"
filmcraft-audio-dsp = { workspace = true, features = ["test-util"] }
rayon = { workspace = true }
filmcraft-dng = { workspace = true, features = ["writer"] }
filmcraft-isobmff = { workspace = true }
+19 -6
View File
@@ -85,6 +85,8 @@ impl AutoSavePrefs {
pub struct PlaybackPrefs {
/// "Preroll: N seconds" (Play Around, trim-mode loop playback).
pub preroll_seconds: f64,
/// Lead-in for Lined Script mark and row cues in the Source monitor.
pub lined_script_preroll_seconds: f64,
/// "Postroll: N seconds".
pub postroll_seconds: f64,
/// "Step forward/back many: N frames" (Shift+Right / Shift+Left).
@@ -107,6 +109,7 @@ impl Default for PlaybackPrefs {
fn default() -> Self {
Self {
preroll_seconds: 3.0,
lined_script_preroll_seconds: 0.5,
postroll_seconds: 2.0,
step_many_frames: 5,
pause_encoder_queue: true,
@@ -665,6 +668,8 @@ pub(crate) struct Sent {
struct Snapshot {
project: Arc<Project>,
/// The media pool the project's stored paths resolve through ([`crate::doc_path`]).
media: Arc<crate::MediaPool>,
revision: u64,
path: Option<String>,
}
@@ -814,8 +819,8 @@ impl Persistence {
})
}
pub(crate) fn send_dirty(&self, project: Arc<Project>, revision: u64, path: Option<String>) {
self.send(Msg::Dirty(Snapshot { project, revision, path }));
pub(crate) fn send_dirty(&self, project: Arc<Project>, media: Arc<crate::MediaPool>, revision: u64, path: Option<String>) {
self.send(Msg::Dirty(Snapshot { project, media, revision, path }));
}
pub(crate) fn send_clean(&self) {
@@ -1060,7 +1065,10 @@ impl Worker {
fn write_journal(&mut self) -> Result<u64, String> {
let Some(s) = &self.latest else { return Err("no unsaved recovery state to write".into()) };
let t0 = Instant::now();
let bytes = filmcraft_format::encode(&s.project, false);
// Recovery installs the snapshot with `meta.project_path` as its document: stored paths
// are relative to the project's own file (#3067).
let stored = crate::doc_path::project_for_document(&s.project, s.path.as_deref(), |p| s.media.follow(p));
let bytes = filmcraft_format::encode(&stored, false);
let serialize_ms = t0.elapsed().as_secs_f64() * 1000.0;
let t1 = Instant::now();
let unix = unix_now();
@@ -1113,11 +1121,15 @@ impl Worker {
}
(None, _) => (self.data_dir.join(names::AUTO_SAVE_DIR), s.project.name.clone()),
};
let unix = unix_now();
let t0 = Instant::now();
let bytes = filmcraft_format::encode(&s.project, false);
// Stored paths are relative to the file holding them: the timestamped copy in the
// auto-save directory, and the project file when Auto Save also saves the project (#3067).
let dst = dir.join(names::auto_save_name(&name, unix, (self.local_offset)(unix)));
let stored = crate::doc_path::project_for_document(&s.project, dst.to_str(), |p| s.media.follow(p));
let bytes = filmcraft_format::encode(&stored, false);
let serialize_ms = t0.elapsed().as_secs_f64() * 1000.0;
let t1 = Instant::now();
let unix = unix_now();
let r = names::write_auto_save(&dir, &name, unix, (self.local_offset)(unix), &bytes, self.prefs.max_versions as usize);
let write_ms = t1.elapsed().as_secs_f64() * 1000.0;
match r {
@@ -1127,7 +1139,8 @@ impl Worker {
if self.prefs.save_current_project
&& let Some(p) = &s.path
{
match filmcraft_format::atomic_write(Path::new(p), &bytes) {
let stored = crate::doc_path::project_for_document(&s.project, Some(p.as_str()), |x| s.media.follow(x));
match filmcraft_format::atomic_write(Path::new(p), &filmcraft_format::encode(&stored, false)) {
Ok(()) => {
let _ = self.events.send(WorkerEvent::SavedProject { path: p.clone(), revision: s.revision });
}
+279
View File
@@ -5,6 +5,10 @@
//! selection (`EditorState::caption_selection`) or the caption under the playhead. Caption tracks
//! are addressed by id or `"C1"`, `"C2"`… (top first); the default is the first caption track.
use std::io::Read;
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use filmcraft_captions::{Document, Format};
@@ -19,6 +23,188 @@ use crate::{EngineError, Result, Session};
type Run = fn(&mut Session, &Value) -> Result<Value>;
type Enabled = fn(&Session) -> std::result::Result<(), String>;
const STYLE_PRESET_FILE: &str = "caption-style-presets.json";
const STYLE_PRESET_FORMAT: &str = "filmcraft.caption-style-presets";
const MAX_STYLE_PRESETS: usize = 100;
const MAX_STYLE_PRESET_FILE_BYTES: u64 = 1024 * 1024;
const MAX_STYLE_PRESET_NAME_CHARS: usize = 100;
const MAX_STYLE_FONT_BYTES: usize = 1024;
/// A named, reusable caption track appearance.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CaptionStylePreset {
pub name: String,
pub style: CaptionStyle,
}
#[derive(Serialize, Deserialize)]
struct CaptionStylePresetFile {
format: String,
version: u32,
presets: Vec<CaptionStylePreset>,
}
/// User-created caption track styles persisted in the application data directory.
#[derive(Default)]
pub struct CaptionStyleLibrary {
user: Vec<CaptionStylePreset>,
dir: Option<PathBuf>,
load_error: Option<String>,
}
impl CaptionStyleLibrary {
/// Load saved styles from the app data directory. Invalid files are left untouched and reported.
pub fn set_dir(&mut self, data_dir: &Path) {
self.dir = Some(data_dir.to_path_buf());
self.user.clear();
self.load_error = None;
let path = data_dir.join(STYLE_PRESET_FILE);
let file = match std::fs::File::open(&path) {
Ok(file) => file,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return,
Err(e) => {
log::warn!("{}: {e}", path.display());
self.load_error = Some(e.to_string());
return;
}
};
let mut bytes = Vec::new();
let read = file.take(MAX_STYLE_PRESET_FILE_BYTES.saturating_add(1)).read_to_end(&mut bytes);
if let Err(e) = read {
log::warn!("{}: {e}", path.display());
self.load_error = Some(e.to_string());
return;
}
match if bytes.len() as u64 > MAX_STYLE_PRESET_FILE_BYTES {
Err("caption style preset file exceeds the 1 MiB limit".into())
} else {
parse_style_presets(&bytes)
} {
Ok(presets) => self.user = presets,
Err(e) => {
log::warn!("{}: {e}", path.display());
self.load_error = Some(e);
}
}
}
/// Return all user-saved caption track style presets.
pub fn all(&self) -> &[CaptionStylePreset] {
&self.user
}
/// Find a saved preset by its exact display name.
pub fn find(&self, name: &str) -> Option<CaptionStyle> {
self.user.iter().find(|p| p.name == name).map(|p| p.style.clone())
}
/// Save or replace a preset, persisting it before changing the in-memory list.
pub fn save(&mut self, name: &str, style: CaptionStyle) -> std::result::Result<(), String> {
let name = name.trim();
if name.is_empty() || name.chars().count() > MAX_STYLE_PRESET_NAME_CHARS || name.chars().any(char::is_control) {
return Err(format!("preset name must be 1–{MAX_STYLE_PRESET_NAME_CHARS} printable characters"));
}
let style = normalize_style(style).ok_or_else(|| "caption style has an invalid font or non-finite value".to_string())?;
let mut next = self.user.clone();
let key = style_preset_name_key(name);
if let Some(preset) = next.iter_mut().find(|p| style_preset_name_key(&p.name) == key) {
preset.name = name.to_string();
preset.style = style;
} else {
if next.len() >= MAX_STYLE_PRESETS {
return Err(format!("caption style preset limit ({MAX_STYLE_PRESETS}) reached"));
}
next.push(CaptionStylePreset { name: name.to_string(), style });
}
self.persist(&next)?;
self.user = next;
Ok(())
}
/// Delete a preset by its exact display name, persisting the change before removing it in memory.
pub fn delete(&mut self, name: &str) -> std::result::Result<bool, String> {
let Some(index) = self.user.iter().position(|p| p.name == name) else { return Ok(false) };
let mut next = self.user.clone();
next.remove(index);
self.persist(&next)?;
self.user = next;
Ok(true)
}
fn persist(&self, presets: &[CaptionStylePreset]) -> std::result::Result<(), String> {
if let Some(error) = &self.load_error {
return Err(format!("cannot save caption style presets because the existing file failed to load: {error}"));
}
let Some(dir) = &self.dir else { return Err("caption style preset persistence is not configured".into()) };
std::fs::create_dir_all(dir).map_err(|e| format!("could not create caption style preset directory: {e}"))?;
let bytes = style_preset_file_bytes(presets)?;
// what loads again: a file over the limit would be refused on the next launch
if bytes.len() as u64 > MAX_STYLE_PRESET_FILE_BYTES {
return Err("caption style presets would exceed the 1 MiB file limit".into());
}
filmcraft_format::atomic_write(&dir.join(STYLE_PRESET_FILE), &bytes).map_err(|e| e.to_string())
}
}
/// Normalize preset names with the same Unicode case-folding rule for saves and file validation.
fn style_preset_name_key(name: &str) -> String {
name.trim().to_lowercase()
}
fn normalize_style(mut style: CaptionStyle) -> Option<CaptionStyle> {
if style.font.len() > MAX_STYLE_FONT_BYTES
|| style.font_style.len() > MAX_STYLE_FONT_BYTES
|| !style.size.is_finite()
|| !style.margin.is_finite()
|| !style.line_spacing.is_finite()
|| !style.outline.is_finite()
{
return None;
}
style.size = style.size.clamp(4.0, 400.0);
style.margin = style.margin.clamp(0.0, 0.45);
style.line_spacing = style.line_spacing.clamp(0.8, 4.0);
style.outline = style.outline.clamp(0.0, 40.0);
Some(style)
}
fn style_preset_file_bytes(presets: &[CaptionStylePreset]) -> std::result::Result<Vec<u8>, String> {
serde_json::to_vec_pretty(&CaptionStylePresetFile { format: STYLE_PRESET_FORMAT.into(), version: 1, presets: presets.to_vec() })
.map_err(|e| format!("could not serialize caption style presets: {e}"))
}
fn parse_style_presets(bytes: &[u8]) -> std::result::Result<Vec<CaptionStylePreset>, String> {
if bytes.len() as u64 > MAX_STYLE_PRESET_FILE_BYTES {
return Err("caption style preset file exceeds the 1 MiB limit".into());
}
let file: CaptionStylePresetFile = serde_json::from_slice(bytes).map_err(|e| format!("invalid caption style preset file: {e}"))?;
if file.format != STYLE_PRESET_FORMAT {
return Err(format!("not a caption style preset file (format `{}`)", file.format));
}
if file.version != 1 {
return Err(format!("unsupported caption style preset version {}", file.version));
}
if file.presets.len() > MAX_STYLE_PRESETS {
return Err(format!("caption style preset file exceeds the {MAX_STYLE_PRESETS} preset limit"));
}
let mut names = std::collections::HashSet::new();
let mut presets = Vec::with_capacity(file.presets.len());
for mut preset in file.presets {
let name = preset.name.trim().to_string();
if name.is_empty() || name.chars().count() > MAX_STYLE_PRESET_NAME_CHARS || name.chars().any(char::is_control) {
return Err("caption style preset file contains an invalid name".into());
}
if !names.insert(style_preset_name_key(&name)) {
return Err("caption style preset file contains duplicate names".into());
}
preset.name = name.clone();
preset.style = normalize_style(preset.style).ok_or_else(|| format!("caption style preset `{name}` has an invalid style"))?;
presets.push(preset);
}
Ok(presets)
}
fn spec(
id: &'static str,
label: &'static str,
@@ -431,6 +617,60 @@ pub fn commands() -> Vec<CommandSpec> {
Ok(Value::Null)
},
),
spec("captions.copyStyle", "Copy Caption Track Style", &[], None, r#"{"track":id|"C1"?}"#, has_caption_track, |s, p| {
let tid = track_param(s, p).ok_or_else(|| bad("captions.copyStyle", "no such caption track"))?;
let style = s.active_sequence().and_then(|q| q.caption_track(tid)).map(|t| t.style.clone()).ok_or(EngineError::NoSequence)?;
s.caption_style_clipboard = Some(style);
Ok(json!({"track": tid.0, "copied": true}))
}),
spec("captions.pasteStyle", "Paste Caption Track Style", &[], None, r#"{"track":id|"C1"?}"#, has_caption_track, |s, p| {
let tid = track_param(s, p).ok_or_else(|| bad("captions.pasteStyle", "no such caption track"))?;
let style = s.caption_style_clipboard.clone().ok_or_else(|| bad("captions.pasteStyle", "copy a caption track style first"))?;
s.edit_sequence("Paste Caption Track Style", move |q, _, _| {
let track = q.caption_track_mut(tid).ok_or_else(|| bad("captions.pasteStyle", "no such caption track"))?;
track.style = style;
Ok(())
})?;
Ok(json!({"track": tid.0, "pasted": true}))
}),
spec("captions.stylePreset.save", "Save Caption Style Preset", &[], None, r#"{"name":str,"track":id|"C1"?}"#, has_caption_track, |s, p| {
let name = str_p(p, "name").ok_or_else(|| bad("captions.stylePreset.save", "need `name`"))?;
let tid = track_param(s, p).ok_or_else(|| bad("captions.stylePreset.save", "no such caption track"))?;
let style = s.active_sequence().and_then(|q| q.caption_track(tid)).map(|t| t.style.clone()).ok_or(EngineError::NoSequence)?;
s.caption_style_presets.save(name, style).map_err(|e| bad("captions.stylePreset.save", e))?;
Ok(json!({"name": name.trim()}))
}),
spec("captions.stylePreset.apply", "Apply Caption Style Preset", &[], None, r#"{"name":str,"track":id|"C1"?}"#, has_caption_track, |s, p| {
let name = str_p(p, "name").ok_or_else(|| bad("captions.stylePreset.apply", "need `name`"))?;
let tid = track_param(s, p).ok_or_else(|| bad("captions.stylePreset.apply", "no such caption track"))?;
let style =
s.caption_style_presets.find(name).ok_or_else(|| bad("captions.stylePreset.apply", format!("no caption style preset named `{name}`")))?;
s.edit_sequence("Apply Caption Style Preset", move |q, _, _| {
let track = q.caption_track_mut(tid).ok_or_else(|| bad("captions.stylePreset.apply", "no such caption track"))?;
track.style = style;
Ok(())
})?;
Ok(json!({"name": name, "track": tid.0}))
}),
spec("captions.stylePreset.delete", "Delete Caption Style Preset", &[], None, r#"{"name":str}"#, always, |s, p| {
let name = str_p(p, "name").ok_or_else(|| bad("captions.stylePreset.delete", "need `name`"))?;
let deleted = s.caption_style_presets.delete(name).map_err(|e| bad("captions.stylePreset.delete", e))?;
if !deleted {
return Err(bad("captions.stylePreset.delete", format!("no caption style preset named `{name}`")));
}
Ok(json!({"name": name, "deleted": true}))
}),
CommandSpec {
id: "captions.stylePreset.list",
label: "List Caption Style Presets",
menu: &[],
shortcut: None,
params: "{}",
enabled: always,
run: |s, _| Ok(json!({"presets": s.caption_style_presets.all()})),
journal: false,
named: crate::commands::NamedKeys::NONE,
},
spec(
"captions.add",
"Add Caption at Playhead",
@@ -668,3 +908,42 @@ fn show_all(s: &mut Session, on: bool) -> Result<Value> {
#[cfg(test)]
mod tests;
#[cfg(test)]
mod preset_file_tests {
use super::*;
#[test]
fn caption_style_preset_parser_survives_truncation_and_bit_flips() {
let valid = style_preset_file_bytes(&[CaptionStylePreset { name: "Safe".into(), style: CaptionStyle::default() }]).expect("valid preset serializes");
let mut candidates: Vec<Vec<u8>> = (0..valid.len()).map(|length| valid[..length].to_vec()).collect();
candidates.push(valid.clone());
for index in 0..valid.len() {
for bit in 0..8 {
let mut changed = valid.clone();
changed[index] ^= 1 << bit;
candidates.push(changed);
}
}
candidates.push(vec![b' '; MAX_STYLE_PRESET_FILE_BYTES as usize + 1]);
for candidate in candidates {
let parsed = std::panic::catch_unwind(|| parse_style_presets(&candidate));
assert!(parsed.is_ok(), "malformed preset data must return an error instead of panicking");
}
}
/// A style the file couldn't load again is refused on save: the font style is bounded like the font.
#[test]
fn a_preset_with_an_oversized_font_style_is_refused_and_not_written() {
let dir = tempfile::tempdir().expect("temp dir");
let mut library = CaptionStyleLibrary::default();
library.set_dir(dir.path());
let style = CaptionStyle { font_style: "x".repeat(MAX_STYLE_FONT_BYTES + 1), ..CaptionStyle::default() };
assert!(library.save("Long", style).is_err());
assert!(library.all().is_empty());
assert!(!dir.path().join(STYLE_PRESET_FILE).exists());
library.save("Fine", CaptionStyle::default()).expect("a normal preset saves");
assert_eq!(library.all().len(), 1);
}
}
+106
View File
@@ -429,3 +429,109 @@ fn caption_export_warns_about_characters_608_and_708_cannot_carry() {
assert_eq!(export(&mut s, "srt")["warnings"], json!([]));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn caption_track_styles_copy_paste_and_saved_presets_are_undoable_and_persisted() {
let dir = std::env::temp_dir().join(format!("fc-caption-style-presets-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let mut s = demo();
s.caption_style_presets.set_dir(&dir);
let first = s.execute("captions.newTrack", json!({"name": "First"})).unwrap()["track"].as_u64().unwrap();
let second = s.execute("captions.newTrack", json!({"name": "Second"})).unwrap()["track"].as_u64().unwrap();
s.execute("playhead.set", json!({"seconds": 1.0})).unwrap();
s.execute("captions.add", json!({"track": first, "text": "Keep my timing"})).unwrap();
s.execute("playhead.set", json!({"seconds": 4.0})).unwrap();
s.execute("captions.add", json!({"track": second, "text": "Also keep mine"})).unwrap();
s.execute("captions.setStyle", json!({"track": first, "font": "Inter", "size": 42.0, "color": "#22aaff", "anchor": "top"})).unwrap();
let first_style = s.active_sequence().unwrap().caption_tracks.iter().find(|t| t.id.0 == first).unwrap().style.clone();
let second_captions = s.active_sequence().unwrap().caption_tracks.iter().find(|t| t.id.0 == second).unwrap().captions.clone();
s.execute("captions.copyStyle", json!({"track": first})).unwrap();
s.execute("captions.setStyle", json!({"track": second, "size": 24.0, "anchor": "bottom"})).unwrap();
s.execute("captions.pasteStyle", json!({"track": second})).unwrap();
let target = s.active_sequence().unwrap().caption_tracks.iter().find(|t| t.id.0 == second).unwrap();
assert_eq!(target.style, first_style);
assert_eq!(target.captions, second_captions, "style paste preserves caption text and timing");
s.execute("edit.undo", json!({})).unwrap();
let target = s.active_sequence().unwrap().caption_tracks.iter().find(|t| t.id.0 == second).unwrap();
assert_eq!(target.style.size, 24.0, "pasting a style is one undo step");
s.execute("captions.stylePreset.save", json!({"track": first, "name": "Broadcast Blue"})).unwrap();
s.execute("captions.setStyle", json!({"track": first, "size": 18.0})).unwrap();
s.execute("captions.stylePreset.apply", json!({"track": first, "name": "Broadcast Blue"})).unwrap();
assert_eq!(s.active_sequence().unwrap().caption_tracks.iter().find(|t| t.id.0 == first).unwrap().style, first_style);
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(s.active_sequence().unwrap().caption_tracks.iter().find(|t| t.id.0 == first).unwrap().style.size, 18.0);
let list = s.execute("captions.stylePreset.list", json!({})).unwrap();
assert_eq!(list["presets"][0]["name"], "Broadcast Blue");
let mut loaded = crate::captions::CaptionStyleLibrary::default();
loaded.set_dir(&dir);
assert_eq!(loaded.find("Broadcast Blue"), Some(first_style));
assert!(loaded.delete("Broadcast Blue").unwrap());
assert!(loaded.find("Broadcast Blue").is_none());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn caption_style_preset_commands_reject_hostile_parameters_without_mutation() {
let mut s = demo();
s.execute("captions.newTrack", json!({"name": "Hostile test"})).unwrap();
let original_style = s.active_sequence().unwrap().caption_tracks[0].style.clone();
for name in [String::new(), "x".repeat(101), "line\nbreak".to_string()] {
assert!(s.execute("captions.stylePreset.save", json!({"track": "C1", "name": name})).is_err());
}
assert!(s.execute("captions.stylePreset.apply", json!({"track": "C1", "name": "missing"})).is_err());
assert!(s.execute("captions.stylePreset.delete", json!({"name": "missing"})).is_err());
assert!(s.execute("captions.pasteStyle", json!({"track": "C1"})).is_err());
assert!(s.caption_style_presets.all().is_empty());
assert_eq!(s.active_sequence().unwrap().caption_tracks[0].style, original_style);
}
#[test]
fn caption_style_preset_save_does_not_replace_a_file_that_failed_to_load() {
let dir = std::env::temp_dir().join(format!("fc-caption-style-presets-invalid-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("caption-style-presets.json");
let original = b"not a valid preset file";
std::fs::write(&path, original).unwrap();
let mut library = crate::captions::CaptionStyleLibrary::default();
library.set_dir(&dir);
assert!(library.save("Replacement", Default::default()).is_err());
assert!(library.all().is_empty());
assert_eq!(std::fs::read(&path).unwrap(), original);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn caption_style_preset_save_and_load_share_unicode_name_normalization() {
let dir = std::env::temp_dir().join(format!("fc-caption-style-presets-unicode-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let mut library = crate::captions::CaptionStyleLibrary::default();
library.set_dir(&dir);
library.save("Café", Default::default()).unwrap();
library.save("CAFÉ", Default::default()).unwrap();
assert_eq!(library.all().len(), 1);
let mut loaded = crate::captions::CaptionStyleLibrary::default();
loaded.set_dir(&dir);
assert_eq!(loaded.all().len(), 1);
assert!(loaded.find("CAFÉ").is_some());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn caption_style_preset_save_requires_a_persistence_directory() {
let mut library = crate::captions::CaptionStyleLibrary::default();
assert!(library.save("Temporary", Default::default()).is_err());
assert!(library.all().is_empty());
let mut session = demo();
session.execute("captions.newTrack", json!({"name": "No persistence"})).unwrap();
assert!(session.execute("captions.stylePreset.save", json!({"track": "C1", "name": "Temporary"})).is_err());
assert!(session.caption_style_presets.all().is_empty());
}
+3 -1
View File
@@ -66,7 +66,9 @@ pub(super) fn extract_audio(s: &mut Session, p: &Value) -> Result<Value> {
.and_then(|x| std::path::Path::new(x).parent())
.map(|d| d.to_string_lossy().into_owned())
.or_else(|| match &m.media {
MediaRef::File { path } => std::path::Path::new(path).parent().map(|d| d.to_string_lossy().into_owned()),
MediaRef::File { path } => {
s.media.follow(path).ok().and_then(|f| std::path::Path::new(&f).parent().map(|d| d.to_string_lossy().into_owned()))
}
_ => None,
})
.ok_or_else(|| EngineError::Other("save the project first: extracted audio is written next to it".into()))?,
+10 -3
View File
@@ -3305,7 +3305,7 @@ fn build() -> Vec<CommandSpec> {
.ok_or_else(|| bad("source.open", "need `item` (or a Project panel selection)"))?;
let source = s.project.item(id).ok_or_else(|| bad("source.open", "no such item"))?;
if matches!(source.kind, ItemKind::Script(_)) {
return Err(bad("source.open", "Scripts open in the Script panel, not the Source monitor"));
return Err(bad("source.open", "Scripts open in the Lined Script panel"));
}
s.state.source_item = Some(id);
// a subclip opens at its In point
@@ -4265,6 +4265,7 @@ fn build() -> Vec<CommandSpec> {
v.extend(crate::multicam::commands());
v.extend(crate::essential_sound::commands());
v.extend(crate::color::commands());
v.extend(crate::raw_settings::commands());
v.extend(crate::graphics::commands());
v.extend(crate::graphic_templates::commands());
v.extend(crate::shortcuts::commands());
@@ -5410,7 +5411,10 @@ fn write_project(s: &mut Session, path: &str, adopt: bool) -> Result<Value> {
}
// what is open (sequence tabs, how each is shown) goes into the file beside the project
let view = s.project_view();
let bytes = filmcraft_format::encode_with_view(&s.project, Some(&view), false);
// media paths are stored relative to the file when they can be (#3067): the session's project
// keeps its own paths
let stored = crate::doc_path::project_for_document(&s.project, Some(path), |p| s.media.follow(p));
let bytes = filmcraft_format::encode_with_view(&stored, Some(&view), false);
let mut backup = None;
if adopt && s.path.as_deref() == Some(path) && s.loaded_schema < filmcraft_format::SCHEMA_VERSION {
let b = schema_backup_path(path, s.loaded_schema);
@@ -5439,6 +5443,9 @@ fn schema_backup_path(path: &str, schema: u32) -> String {
/// Make `proj` the session's project (fresh history, media pool and editor state).
pub(crate) fn install_project(s: &mut Session, mut proj: filmcraft_project::Project, path: Option<String>, clean: bool) {
// Stored paths become the files they name at load; what cannot be followed keeps its stored
// path and the pool refuses it (#3067).
crate::doc_path::absolutize(&mut proj, path.as_deref());
let proxies = s.media.use_proxies();
s.media = std::sync::Arc::new(crate::MediaPool::default());
s.media.set_use_proxies(proxies);
@@ -5476,7 +5483,7 @@ fn open_project(s: &mut Session, path: &str) -> Result<Value> {
let (from, migrated) = (loaded.schema_version, loaded.migrated());
crate::masks::discard_jobs(s);
install_project(s, loaded.project, Some(path.to_string()), true);
if let Some(view) = loaded.view.filter(|_| s.prefs.timeline.restore_open_sequences) {
if let Some(view) = loaded.view {
s.restore_project_view(view);
}
// the frontend shows the project's active sequence (with its own view, when one was restored)
+215 -1
View File
@@ -8,9 +8,16 @@
//! are not stored-document paths and are followed as given. The media pool tells them apart
//! ([`crate::MediaPool::follow`]): it records the paths of each document it loads, with that
//! document, and forgets a path once the user picks it again.
//!
//! The other direction is [`store`], used when a document is written: a path is resolved against
//! the document it came from, then stored relative to the new document's folder when that
//! round-trips, so a project and the media beside it survive moving to another folder, drive,
//! share or machine (#3067).
use std::fmt;
use std::path::{Path, PathBuf};
use std::path::{Component, Path, PathBuf};
use filmcraft_project::{MediaRef, Project};
pub use craft_docpath::Refused;
@@ -60,6 +67,133 @@ fn foreign_root(path: &Path) -> bool {
b.starts_with(br"\\") || matches!((b.first(), b.get(1)), (Some(l), Some(b':')) if l.is_ascii_alphabetic())
}
/// `p` with every media and proxy `File` path in its stored form for a document written to
/// `document` (see [`store`]): paths beside the document are stored relative to its folder, so a
/// project and its media move together between drives, shares and machines. `document` = None (a
/// document without a file) keeps the paths as they are.
pub(crate) fn project_for_document<'p>(
p: &'p Project,
document: Option<&str>,
follow: impl Fn(&str) -> Result<String, NotFollowed>,
) -> std::borrow::Cow<'p, Project> {
// The web host opens only the files the user gave it, under their own virtual paths: a stored
// path is the key, so it is stored as given.
if cfg!(target_arch = "wasm32") {
return std::borrow::Cow::Borrowed(p);
}
let Some(document) = document.filter(|d| !d.is_empty()).map(PathBuf::from) else {
return std::borrow::Cow::Borrowed(p);
};
let document = std::path::absolute(&document).unwrap_or(document);
std::borrow::Cow::Owned(rewrite_paths(p, |path| store(path, &document, &follow)))
}
/// Give each stored `File` path of `p` its file, resolved against `document` ([`resolve`]): a
/// loaded project holds openable paths, the stored form is only what a document writes. A path
/// that cannot be followed stays as stored — the media pool records it with the document and
/// refuses it, so the item reads as missing rather than opening something else.
pub(crate) fn absolutize(p: &mut Project, document: Option<&str>) {
// Web stored paths are the keys of the files the user gave the host: they stay as stored.
if cfg!(target_arch = "wasm32") {
return;
}
let document = document.filter(|d| !d.is_empty()).map(PathBuf::from);
for it in p.items.values_mut() {
if let Some(m) = it.as_media_mut() {
for r in [&mut m.media].into_iter().chain(m.proxy.iter_mut()) {
if let MediaRef::File { path } = r
&& let Ok(file) = resolve(path, document.as_deref())
{
*path = file;
}
}
}
}
}
/// `p` with every media and proxy `File` path resolved by `follow`: the file a stored path points
/// to. Interchange documents name files for other apps to open, so they take the resolved path
/// rather than the stored one; a path `follow` cannot resolve is kept.
pub(crate) fn resolved_project(p: &Project, follow: impl Fn(&str) -> Result<String, NotFollowed>) -> Project {
rewrite_paths(p, |path| follow(path).unwrap_or_else(|_| path.to_string()))
}
fn rewrite_paths(p: &Project, f: impl Fn(&str) -> String) -> Project {
let mut out = p.clone();
for it in out.items.values_mut() {
if let Some(m) = it.as_media_mut() {
if let MediaRef::File { path } = &mut m.media {
*path = f(path);
}
if let Some(MediaRef::File { path }) = &mut m.proxy {
*path = f(path);
}
}
}
out
}
/// The string to store for `path` in a document at `document` (made absolute by the caller):
/// `follow` resolves the path against the document it was stored in ([`crate::MediaPool::follow`],
/// which knows each stored path's document), then the resolved file is written relative to
/// `document`'s folder when [`resolve`] takes it back to the same file — the form that survives
/// the project and its media moving together. Anything else keeps an absolute path: a file on
/// another drive or share cannot be reached relatively, and a path `follow` cannot resolve is
/// stored as it was.
pub(crate) fn store(path: &str, document: &Path, follow: impl Fn(&str) -> Result<String, NotFollowed>) -> String {
let Ok(file) = follow(path) else { return path.to_string() };
if !Path::new(&file).is_absolute() {
return path.to_string();
}
// `follow` returns stored paths already normalised; a path the user gave is normalised here so
// the round-trip check below compares like with like (`resolve` renders `.`/`..` away).
let file = resolve(&file, None).unwrap_or(file);
if let Some(rel) = relative(Path::new(&file), document)
&& resolve(&rel, Some(document)).as_deref() == Ok(file.as_str())
{
return rel;
}
file
}
/// `target` relative to `document`'s folder, `..` climbing out of it; `None` when they share no
/// root: a file cannot be reached relatively from another drive or share. The result uses `/`,
/// which [`resolve`] reads as a separator on every platform.
fn relative(target: &Path, document: &Path) -> Option<String> {
let t: Vec<_> = target.components().collect();
let d: Vec<_> = document.parent()?.components().collect();
let common = t.iter().zip(d.iter()).take_while(|(a, b)| same_root_comp(a, b)).count();
if common == 0 {
return None;
}
let mut rel = String::new();
for _ in common..d.len() {
rel.push_str("../");
}
for (i, c) in t.iter().enumerate().skip(common) {
if i > common {
rel.push('/');
}
rel.push_str(&c.as_os_str().to_string_lossy());
}
(!rel.is_empty()).then_some(rel)
}
/// Component equality for the shared-prefix walk of [`relative`]: the two leading components are
/// the same root — on Windows also when drive letters differ only in case (`C:` and `c:` are the
/// same drive). Compared case-insensitively there only; a name that differs in case still points
/// to a different folder where the filesystem says so.
fn same_root_comp(a: &Component, b: &Component) -> bool {
use std::path::Prefix;
match (a, b) {
(Component::Prefix(x), Component::Prefix(y)) => match (x.kind(), y.kind()) {
(Prefix::Disk(l), Prefix::Disk(m)) | (Prefix::VerbatimDisk(l), Prefix::VerbatimDisk(m)) => l.eq_ignore_ascii_case(&m),
_ => x == y,
},
_ => a == b,
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -95,4 +229,84 @@ mod tests {
assert_eq!(resolve(stored, None), Err(NotFollowed::Refused(Refused::Invalid)), "{stored}");
}
}
fn as_given(p: &str) -> Result<String, NotFollowed> {
Ok(p.to_string())
}
#[test]
fn store_writes_paths_relative_to_the_document() {
let dir = std::env::temp_dir().join("films");
let doc = dir.join("cut.fcproj");
let dir = dir.to_string_lossy().replace('\\', "/");
// beside, inside and above the document's folder: relative forms resolve back
assert_eq!(store(&format!("{dir}/a.mp4"), &doc, as_given), "a.mp4");
assert_eq!(store(&format!("{dir}/media/a.mp4"), &doc, as_given), "media/a.mp4");
let media = Path::new(&dir).parent().map(|p| p.join("m.mp4").to_string_lossy().replace('\\', "/"));
if let Some(m) = media {
assert_eq!(store(&m, &doc, as_given), "../m.mp4");
}
// a stored relative path from an older document is rebased onto the new one
let old = std::env::temp_dir().join("old").join("cut.fcproj");
let follow = |p: &str| resolve(p, Some(&old));
let rel = store("media/a.mp4", &doc, follow);
assert_eq!(resolve(&rel, Some(&doc)), resolve("media/a.mp4", Some(&old)));
// a relative path with no document behind it is stored as it was
assert_eq!(store("media/a.mp4", &doc, |_| Err(NotFollowed::NoDocumentFolder)), "media/a.mp4");
assert_eq!(store(r"\\192.0.2.1\share\x.mp4", &doc, |_| Err(NotFollowed::Refused(Refused::Network))), r"\\192.0.2.1\share\x.mp4");
}
#[test]
fn store_keeps_a_path_that_cannot_go_relative() {
// another drive has no relative form (Windows; on Unix every path shares the one root)
if cfg!(windows) {
assert_eq!(store(r"D:\m\a.mp4", Path::new(r"C:\p\c.fcproj"), as_given), r"D:\m\a.mp4");
} else {
assert_eq!(store("/m/a.mp4", Path::new("/p/c.fcproj"), as_given), "../m/a.mp4");
}
// a network path stays as given: it is only allowed on the document's own share
let doc = Path::new(if cfg!(windows) { r"\\srv\share\p\c.fcproj" } else { "/p/c.fcproj" });
assert_eq!(store(r"\\other\share\a.mp4", doc, as_given), r"\\other\share\a.mp4");
}
#[test]
fn project_for_document_rewrites_media_and_proxy_paths() {
let dir = std::env::temp_dir().join("films");
let doc = dir.join("cut.fcproj");
let mut p = Project::new("t");
let info = filmcraft_media::MediaInfo {
name: "a.mp4".into(),
kind: filmcraft_media::MediaKind::Movie,
duration: filmcraft_time::Tick(1),
video: None,
audio_streams: vec![],
container: String::new(),
start_timecode: None,
file_size: None,
};
let id = p.add_item(
"a",
filmcraft_project::Label::Blue,
filmcraft_project::ItemKind::Media(Box::new(filmcraft_project::MediaClip {
media: MediaRef::File { path: dir.join("a.mp4").to_string_lossy().into_owned() },
info,
interpret: Default::default(),
mark_in: None,
mark_out: None,
markers: vec![],
offline: false,
proxy: Some(MediaRef::File { path: dir.join("a.proxy.mp4").to_string_lossy().into_owned() }),
identity: None,
})),
None,
);
let stored = project_for_document(&p, Some(doc.to_str().unwrap_or_default()), as_given);
let m = stored.item(id).and_then(|i| i.as_media());
assert_eq!(m.map(|m| &m.media), Some(&MediaRef::File { path: "a.mp4".into() }));
assert_eq!(m.and_then(|m| m.proxy.as_ref()), Some(&MediaRef::File { path: "a.proxy.mp4".into() }));
// the session's project keeps the paths it had
let m = p.item(id).and_then(|i| i.as_media());
assert!(matches!(m.map(|m| &m.media), Some(MediaRef::File { path }) if path.starts_with(dir.to_string_lossy().as_ref())));
assert!(matches!(project_for_document(&p, None, as_given), std::borrow::Cow::Borrowed(_)));
}
}
+2 -1
View File
@@ -538,7 +538,8 @@ pub fn spawn_export(s: &mut Session, project: Arc<Project>, seq: ItemId, mut set
return Ok(id);
}
let run = move || {
let r = filmcraft_export::export(&project, seq, &settings, &provider, &prog).map_err(|e| e.to_string());
let r = filmcraft_export::on_own_threads(settings.max_threads, || filmcraft_export::export(&project, seq, &settings, &provider, &prog))
.map_err(|e| e.to_string());
*offline.lock().unwrap_or_else(|x| x.into_inner()) = provider.offline_used();
if let Err(e) = &r {
*prog.error.lock().unwrap_or_else(|x| x.into_inner()) = Some(e.clone());
+52
View File
@@ -121,6 +121,58 @@ fn new_project_answers_with_its_name_and_revision() {
assert_eq!(r["name"], "Untitled", "the default name");
}
/// Media paths are stored relative to the project file, so the project and the media beside it
/// keep working when the folder moves to another drive, share or machine (#3067). Files from
/// older builds hold absolute paths and open the same as before.
#[test]
fn media_paths_are_stored_relative_to_the_project_file() {
let d = temp_dir("rel-paths");
let media = d.join("media");
std::fs::create_dir_all(&media).unwrap();
let clip = media.join("clip.mov");
crate::media_test_util::make_movie(&clip, filmcraft_media::DemoScene::OceanSunset, 64, 36, 4);
let mut s = Session::default();
let r = s.execute("file.import", json!({"paths": [clip.to_string_lossy()]})).unwrap();
assert_eq!(r["errors"], json!([]), "{r}");
let item = filmcraft_project::ItemId(r["items"][0].as_u64().unwrap());
let proj = d.join("cut.fcproj");
s.execute("file.saveAs", json!({"path": proj.to_string_lossy()})).unwrap();
// the file holds the relative form; the session keeps the path it imported
let loaded = filmcraft_format::decode(&std::fs::read(&proj).unwrap()).unwrap();
let m = loaded.project.item(item).and_then(|i| i.as_media()).unwrap();
assert_eq!(m.media, filmcraft_project::MediaRef::File { path: "media/clip.mov".into() });
assert!(
matches!(&s.project.item(item).unwrap().as_media().unwrap().media, filmcraft_project::MediaRef::File { path } if path == clip.to_string_lossy().as_ref())
);
// Save As to another folder rebases the stored path, it does not blindly copy it.
let other = d.join("nested").join("saveas.fcproj");
std::fs::create_dir_all(other.parent().unwrap()).unwrap();
s.execute("file.saveAs", json!({"path": other.to_string_lossy()})).unwrap();
let loaded = filmcraft_format::decode(&std::fs::read(&other).unwrap()).unwrap();
let m = loaded.project.item(item).and_then(|i| i.as_media()).unwrap();
assert_eq!(m.media, filmcraft_project::MediaRef::File { path: "../media/clip.mov".into() });
// Move the whole folder: the moved project opens with its media found.
// Windows does not rename a folder with files open in it: close the session first.
drop(s);
let moved = temp_dir("rel-paths-moved");
std::fs::remove_dir(&moved).unwrap();
std::fs::rename(&d, &moved).unwrap();
let mut t = Session::default();
let r = t.execute("file.open", json!({"path": moved.join("cut.fcproj").to_string_lossy()})).unwrap();
assert_eq!(r["missingMedia"], json!(0), "{r}");
let m = t.project.item(item).and_then(|i| i.as_media()).unwrap();
assert_eq!(m.media, filmcraft_project::MediaRef::File { path: moved.join("media").join("clip.mov").to_string_lossy().into_owned() });
// A file written by an older build holds absolute paths; it opens and finds its media too.
let mut doc: Value = serde_json::from_slice(&std::fs::read(moved.join("cut.fcproj")).unwrap()).unwrap();
doc["project"]["items"][item.0.to_string()]["kind"]["Media"]["media"]["File"]["path"] = json!(moved.join("media").join("clip.mov").to_string_lossy());
let old = moved.join("old.fcproj");
std::fs::write(&old, serde_json::to_vec(&doc).unwrap()).unwrap();
let mut u = Session::default();
let r = u.execute("file.open", json!({"path": old.to_string_lossy()})).unwrap();
assert_eq!(r["missingMedia"], json!(0), "{r}");
let _ = std::fs::remove_dir_all(&moved);
}
/// Opening the demo after a saved project must not keep that path: Save would overwrite it.
#[test]
fn open_demo_project_clears_saved_path_so_save_does_not_overwrite() {
+1 -1
View File
@@ -43,7 +43,7 @@ fn query(id: &'static str, label: &'static str, params: &'static str, run: Run)
CommandSpec { id, label, menu: &[], shortcut: None, params, enabled: always, run, journal: false, named: crate::commands::NamedKeys::NONE }
}
const G: &[&str] = &["Graphics and Titles"];
const G: &[&str] = &["Graphics"];
const MAX_THUMBNAIL_DIMENSION: u32 = 1920;
fn has_graphic(s: &Session) -> std::result::Result<(), String> {
+12 -12
View File
@@ -820,13 +820,13 @@ const ALIGN_PARAMS: &str = r#"{"clip":id?,"layers":[n]? (default: the selected l
macro_rules! align_cmd {
($id:literal, $label:literal, $menu:expr, $how:literal, $mode:expr, $en:expr) => {
spec($id, $label, &["Graphics and Titles", $menu], None, ALIGN_PARAMS, $en, |s, p| align_layers(s, p, $how, $mode))
spec($id, $label, &["Graphics", $menu], None, ALIGN_PARAMS, $en, |s, p| align_layers(s, p, $how, $mode))
};
}
macro_rules! arrange_cmd {
($id:literal, $label:literal, $sc:literal, $to:literal) => {
spec($id, $label, &["Graphics and Titles", "Arrange"], Some($sc), r#"{"clip":id?,"layer":n?}"#, has_graphic, |s, p| arrange_layer(s, p, json!($to)))
spec($id, $label, &["Graphics", "Arrange"], Some($sc), r#"{"clip":id?,"layer":n?}"#, has_graphic, |s, p| arrange_layer(s, p, json!($to)))
};
}
@@ -845,13 +845,13 @@ fn menu_commands() -> Vec<CommandSpec> {
const F: &str = "Align to Video Frame";
const G: &str = "Align to Video Frame as Group";
const S: &str = "Align to Selection";
const D: &[&str] = &["Graphics and Titles", "Distribute"];
const SEL: &[&str] = &["Graphics and Titles", "Select"];
const D: &[&str] = &["Graphics", "Distribute"];
const SEL: &[&str] = &["Graphics", "Select"];
vec![
spec(
"graphics.newVerticalText",
"Vertical Text",
&["Graphics and Titles", "New Layer"],
&["Graphics", "New Layer"],
None,
r#"{"text":str="New Text","position":[x,y]?,"clip":id?,"size":px=100,"seconds":f64=5,"time":ticks?}"#,
has_seq,
@@ -864,7 +864,7 @@ fn menu_commands() -> Vec<CommandSpec> {
spec(
"graphics.newRectangle",
"Rectangle",
&["Graphics and Titles", "New Layer"],
&["Graphics", "New Layer"],
Some("Cmd+Alt+R"),
r#"{"position":[x,y]?,"size":[w,h]=[400,200],"clip":id?,"seconds":f64=5,"track":index?,"time":ticks?}"#,
has_seq,
@@ -873,7 +873,7 @@ fn menu_commands() -> Vec<CommandSpec> {
spec(
"graphics.newEllipse",
"Ellipse",
&["Graphics and Titles", "New Layer"],
&["Graphics", "New Layer"],
Some("Cmd+Alt+E"),
r#"{"position":[x,y]?,"size":[w,h]=[400,200],"clip":id?,"seconds":f64=5,"track":index?,"time":ticks?}"#,
has_seq,
@@ -882,7 +882,7 @@ fn menu_commands() -> Vec<CommandSpec> {
spec(
"graphics.newPolygon",
"Polygon",
&["Graphics and Titles", "New Layer"],
&["Graphics", "New Layer"],
None,
r#"{"position":[x,y]?,"size":[w,h]=[300,300],"sides":n=6,"clip":id?,"seconds":f64=5,"track":index?,"time":ticks?}"#,
has_seq,
@@ -911,7 +911,7 @@ fn menu_commands() -> Vec<CommandSpec> {
spec(
"graphics.newFromFile",
"From file…",
&["Graphics and Titles", "New Layer"],
&["Graphics", "New Layer"],
None,
r#"{"path":str,"time":ticks?,"track":index?} (imports the image or video and places it above the clips at the playhead)"#,
has_seq,
@@ -973,7 +973,7 @@ fn menu_commands() -> Vec<CommandSpec> {
spec(
"graphics.resetAllParameters",
"Reset All Parameters",
&["Graphics and Titles"],
&["Graphics"],
None,
r#"{"clip":id?,"layers":[n]? (default: the selected layers, else all)}"#,
has_graphic,
@@ -1002,7 +1002,7 @@ fn menu_commands() -> Vec<CommandSpec> {
spec(
"graphics.resetDuration",
"Reset Duration",
&["Graphics and Titles"],
&["Graphics"],
None,
r#"{"clip":id?,"seconds":f64=5 (the default graphic duration; limited by the next clip on the track)}"#,
has_graphic,
@@ -1031,7 +1031,7 @@ pub fn commands() -> Vec<CommandSpec> {
spec(
"graphics.newText",
"Text",
&["Graphics and Titles", "New Layer"],
&["Graphics", "New Layer"],
Some("Cmd+T"),
r#"{"text":str="New Text","position":[x,y]? (point text: its alignment point on the first baseline; with `box`: the box's top-left corner),"box":[w,h]? (paragraph text wrapped in a box this size),"clip":id?,"newClip":bool?,"vertical":bool=false,"size":px=100,"font":str?,"fontStyle":str?,"seconds":f64=5,"track":index?,"time":ticks?}"#,
has_seq,
+1 -1
View File
@@ -390,7 +390,7 @@ fn new_layer_menu_items_make_shapes_and_vertical_text() {
let b = quad_box(&mut s, v, 0);
assert!(b[3] - b[1] > 2.5 * (b[2] - b[0]), "vertical text is tall: {b:?}");
// the menu has the New Layer entries and no generic "Shape"
let ids: Vec<&str> = crate::command_specs().iter().filter(|c| c.menu == ["Graphics and Titles", "New Layer"]).map(|c| c.id).collect();
let ids: Vec<&str> = crate::command_specs().iter().filter(|c| c.menu == ["Graphics", "New Layer"]).map(|c| c.id).collect();
assert_eq!(
ids,
["graphics.newText", "graphics.newVerticalText", "graphics.newRectangle", "graphics.newEllipse", "graphics.newPolygon", "graphics.newFromFile"]
+6 -2
View File
@@ -65,11 +65,12 @@ pub fn import(s: &mut Session, path: &str, bytes: &[u8], format: Format, bin: Op
name: p.file_stem().map(|n| n.to_string_lossy().to_string()),
..Default::default()
};
let (fragment, report) = match format {
let (mut fragment, report) = match format {
// AAF / OMF may embed audio: write it next to the document (the media items point there)
Format::Aaf | Format::Omf => {
let r = if format == Format::Aaf { filmcraft_interchange::aaf::import(bytes, &opts) } else { filmcraft_interchange::omf::import(bytes, &opts) };
let (mut fragment, extracted, report) = r.map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
crate::doc_path::absolutize(&mut fragment.project, Some(path));
for m in extracted {
let media = fragment
.project
@@ -90,6 +91,7 @@ pub fn import(s: &mut Session, path: &str, bytes: &[u8], format: Format, bin: Op
sequence.settings.validate().map_err(|e| EngineError::Other(format!("{path}: invalid imported sequence settings: {e}")))?;
}
}
crate::doc_path::absolutize(&mut fragment.project, Some(path));
let before: std::collections::HashSet<ItemId> = s.project.items.keys().copied().collect();
let name = opts.name.clone().unwrap_or_else(|| format.name().to_string());
let seqs = s.edit(&format!("Import {name}"), |proj, _| {
@@ -190,7 +192,9 @@ pub fn export(s: &mut Session, p: &Value) -> Result<Value> {
name: s.project.item(seq).map(|i| i.name.clone()),
..Default::default()
};
let (bytes, report) = filmcraft_interchange::export(&s.project, seq, format, &opts).map_err(|e| EngineError::Other(e.to_string()))?;
// Other apps open the paths the document writes: resolved files, not stored paths.
let resolved = crate::doc_path::resolved_project(&s.project, |p| s.media.follow(p));
let (bytes, report) = filmcraft_interchange::export(&resolved, seq, format, &opts).map_err(|e| EngineError::Other(e.to_string()))?;
s.services.write_file(&path, &bytes).map_err(|e| EngineError::Other(e.to_string()))?;
Ok(json!({"path": path, "bytes": bytes.len(), "report": report_json(&report)}))
}
+1 -1
View File
@@ -797,7 +797,7 @@ pub fn commands() -> Vec<CommandSpec> {
s.toast(if on { "Audio during scrubbing on" } else { "Audio during scrubbing off" });
Ok(json!({"scrubAudio": on}))
}),
// ---- graphics and titles
// ---- graphics
spec("graphics.fontSizeUp", "Increase Font Size by One Unit", Some("Cmd+Alt+Right"), "{}", has_graphic, |s, _| font_size(s, 1.0)),
spec("graphics.fontSizeDown", "Decrease Font Size by One Unit", Some("Cmd+Alt+Left"), "{}", has_graphic, |s, _| font_size(s, -1.0)),
spec("graphics.fontSizeUp5", "Increase Font Size by Five Units", Some("Cmd+Alt+Shift+Right"), "{}", has_graphic, |s, _| font_size(s, 5.0)),
+19 -1
View File
@@ -47,6 +47,7 @@ pub mod project_manager;
pub mod project_panel;
pub mod project_tools;
pub mod proxies;
pub mod raw_settings;
pub mod relink;
pub mod remix;
pub mod scene_detect;
@@ -407,6 +408,9 @@ pub struct EditorState {
/// off: a sequence edits in as its clips instead of one nested clip.
#[serde(default)]
pub sequences_as_clips: bool,
/// Lined Script tab identities, independent of document edits.
#[serde(default)]
pub script_tabs: filmcraft_project::ScriptTabsView,
/// Open sequences (timeline tabs), in tab order.
pub open_sequences: Vec<ItemId>,
/// How each sequence is shown in the Timeline panel (zoom, scroll, track heights): every
@@ -576,6 +580,10 @@ pub struct Session {
pub scene_jobs: Vec<scene_detect::PendingScene>,
/// Effect presets (built-in + the user's, persisted in the data directory).
pub presets: presets::PresetLibrary,
/// User-saved caption track styles, persisted in the data directory.
pub caption_style_presets: captions::CaptionStyleLibrary,
/// Caption style copied for use on another track in this session.
pub caption_style_clipboard: Option<filmcraft_project::CaptionStyle>,
/// Export presets (built-in + the user's, persisted in the data directory) and favourites.
pub export_presets: export_tools::ExportPresetLibrary,
/// The export queue (session state, not saved with the project).
@@ -684,6 +692,8 @@ impl Session {
mask_jobs: Vec::new(),
scene_jobs: Vec::new(),
presets: Default::default(),
caption_style_presets: Default::default(),
caption_style_clipboard: None,
export_presets: Default::default(),
export_queue: Default::default(),
stepped: Vec::new(),
@@ -737,6 +747,7 @@ impl Session {
self.media.set_use_proxies(self.prefs.media.enable_proxies);
self.shortcuts.set_dir(&cfg.data_dir);
self.presets.set_dir(&cfg.data_dir);
self.caption_style_presets.set_dir(&cfg.data_dir);
self.export_presets.set_dir(&cfg.data_dir);
self.prefs_path = Some(prefs_path);
self.apply_media_cache();
@@ -768,7 +779,7 @@ impl Session {
return;
}
if dirty {
p.send_dirty(self.project.clone(), self.revision, self.path.clone());
p.send_dirty(self.project.clone(), self.media.clone(), self.revision, self.path.clone());
} else {
p.send_clean();
}
@@ -974,6 +985,7 @@ impl Session {
pub fn project_view(&self) -> filmcraft_project::ProjectView {
let is_seq = |id: &ItemId| self.project.sequence(*id).is_some();
filmcraft_project::ProjectView {
script_tabs: self.state.script_tabs.clone().checked(&self.project),
open_sequences: self.state.open_sequences.iter().copied().filter(is_seq).collect(),
active_sequence: self.state.active_sequence.filter(is_seq),
sequences: self.state.timeline_views.iter().filter(|(id, _)| is_seq(id)).map(|(id, v)| (*id, *v)).collect(),
@@ -987,6 +999,10 @@ impl Session {
/// view without any open sequence leaves the project on its first sequence: a project saved
/// by a session that never showed one (a script, the CLI) should not open on an empty Timeline.
pub fn restore_project_view(&mut self, view: filmcraft_project::ProjectView) {
self.state.script_tabs = view.script_tabs.checked(&self.project);
if !self.prefs.timeline.restore_open_sequences {
return;
}
let mut open: Vec<ItemId> = Vec::new();
for id in view.open_sequences {
if self.project.sequence(id).is_some() && !open.contains(&id) {
@@ -1501,6 +1517,8 @@ mod project_panel_tests;
#[cfg(test)]
mod proxies_tests;
#[cfg(test)]
mod raw_settings_tests;
#[cfg(test)]
mod relink_tests;
#[cfg(test)]
mod remix_tests;
+12 -2
View File
@@ -599,12 +599,22 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
Ok(Value::Object(out))
}
/// The project item that already references a file.
/// The project item that already references a file. Items loaded from a project file carry stored
/// paths (relative to it), so the comparison is between the files they resolve to.
pub fn item_for_path(s: &Session, path: &str) -> Option<ItemId> {
// A path that does not resolve on its own (on Windows, a rooted path without a drive) is
// compared as given, on both sides.
let file = |p: &str| crate::doc_path::resolve(p, None).unwrap_or_else(|_| p.to_string());
let path = file(path);
s.project
.items
.values()
.find(|i| i.as_media().is_some_and(|m| matches!(&m.media, filmcraft_project::MediaRef::File { path: p } if p == path)))
.find(|i| {
i.as_media().is_some_and(|m| {
matches!(&m.media, filmcraft_project::MediaRef::File { path: p }
if s.media.follow(p).ok().map(|f| file(&f)).as_deref() == Some(path.as_str()))
})
})
.map(|i| i.id)
}
+84 -18
View File
@@ -24,6 +24,7 @@ use std::sync::{Arc, Mutex, PoisonError, RwLock};
use filmcraft_frame::{AudioBuffer, VideoFrame};
use filmcraft_media::generators::GeneratorSource;
use filmcraft_media::raw::RawSettings;
use filmcraft_media::{FrameRequest, MediaError, MediaInfo, MediaSource, Opener, SharedSource};
use filmcraft_project::{ItemId, MediaClip, MediaRef, Project};
use filmcraft_render::offline::OfflineReason;
@@ -49,9 +50,14 @@ pub struct OfflineMedia {
pub error: String,
}
struct CachedSource {
key: String,
source: SharedSource,
reopened_for: Option<RawSettings>,
}
pub struct MediaPool {
/// item → (reference key, source)
sources: RwLock<HashMap<ItemId, (String, SharedSource)>>,
sources: RwLock<HashMap<ItemId, CachedSource>>,
proxies: RwLock<HashMap<ItemId, (String, SharedSource)>>,
offline: Arc<RwLock<HashMap<ItemId, OfflineStatus>>>,
use_proxies: AtomicBool,
@@ -89,7 +95,11 @@ pub const PROBE_WHOLE_FILE_MAX: u64 = 64 * 1024 * 1024;
pub fn media_key(m: &MediaClip) -> String {
match &m.media {
MediaRef::File { path } if m.offline => format!("offline:{path}"),
MediaRef::File { path } => format!("file:{path}"),
// camera raw settings change the pictures: a change (or its undo) opens the file again
MediaRef::File { path } => match &m.interpret.raw {
Some(r) => format!("file:{path}|raw:{r:?}"),
None => format!("file:{path}"),
},
MediaRef::Generator(g) => format!("generator:{g:?}"),
}
}
@@ -155,26 +165,34 @@ impl MediaPool {
/// Cache a source for an item, valid whatever the item's reference (generators).
pub fn insert(&self, item: ItemId, src: SharedSource) {
self.sources.write().unwrap_or_else(PoisonError::into_inner).insert(item, (String::new(), src));
self.insert_keyed(item, String::new(), src);
}
/// Cache a source for an item under its [`media_key`].
pub fn insert_keyed(&self, item: ItemId, key: String, src: SharedSource) {
self.sources.write().unwrap_or_else(PoisonError::into_inner).insert(item, (key, src));
self.sources.write().unwrap_or_else(PoisonError::into_inner).insert(item, CachedSource { key, source: src, reopened_for: None });
}
/// Cache a source opened from `path` for an item.
pub fn insert_file(&self, item: ItemId, path: &str, src: SharedSource) {
self.cache_file(item, path, src, None);
}
/// Cache a freshly replaced file, so resolving its RAW settings can reuse this open.
pub(crate) fn insert_reopened_file(&self, item: ItemId, path: &str, src: SharedSource, raw: Option<RawSettings>) {
self.cache_file(item, path, src, raw);
}
fn cache_file(&self, item: ItemId, path: &str, src: SharedSource, reopened_for: Option<RawSettings>) {
self.offline.write().unwrap_or_else(PoisonError::into_inner).remove(&item);
let src = self.unsupported_as_slate(item, path, src);
self.sources.write().unwrap_or_else(PoisonError::into_inner).insert(item, (format!("file:{path}"), src));
let source = self.unsupported_as_slate(item, path, src);
self.sources.write().unwrap_or_else(PoisonError::into_inner).insert(item, CachedSource { key: format!("file:{path}"), source, reopened_for });
}
/// `src` (opened from `path` for `item`) showing the unreadable slate for the frames it
/// cannot decode.
fn unsupported_as_slate(&self, item: ItemId, path: &str, src: SharedSource) -> SharedSource {
let slate = SlateSource::new(src.info().clone(), &file_name(path), OfflineReason::Unreadable);
Arc::new(UnsupportedAsSlate { inner: src, slate, item, path: path.to_string(), offline: self.offline.clone() })
Arc::new(UnsupportedAsSlate::new(src, item, path, self.offline.clone()))
}
pub fn remove(&self, item: ItemId) {
@@ -239,7 +257,7 @@ impl MediaPool {
}
pub fn cached(&self, item: ItemId) -> Option<SharedSource> {
self.sources.read().unwrap_or_else(PoisonError::into_inner).get(&item).map(|(_, s)| s.clone())
self.sources.read().unwrap_or_else(PoisonError::into_inner).get(&item).map(|cached| cached.source.clone())
}
/// Sources opened so far (originals and proxies; `perf.stats`).
@@ -347,19 +365,31 @@ impl MediaPool {
fn resolve(&self, p: &Project, item: ItemId, services: &dyn Services, proxies: bool) -> Option<SharedSource> {
let (item, m, _) = p.resolve_media(item)?;
let it = p.item(item)?;
// a proxy of camera raw footage has the Source Settings of the day it was made baked in
if proxies
&& !m.offline
&& !filmcraft_media::still::dng::is_camera_raw(&m.info)
&& let Some(MediaRef::File { path }) = &m.proxy
&& let Some(s) = self.proxy_source(item, path, m, services)
{
return Some(s);
}
let key = media_key(m);
if let Some((k, s)) = self.sources.read().unwrap_or_else(PoisonError::into_inner).get(&item)
&& (k.is_empty() || *k == key)
{
return Some(s.clone());
}
let reopened_file = {
let sources = self.sources.read().unwrap_or_else(PoisonError::into_inner);
match sources.get(&item) {
Some(cached) if cached.key.is_empty() || cached.key == key => return Some(cached.source.clone()),
Some(cached)
if cached.reopened_for.is_some()
&& cached.reopened_for == m.interpret.raw
&& let MediaRef::File { path } = &m.media
&& cached.key.strip_prefix("file:") == Some(path.as_str()) =>
{
Some(cached.source.clone())
}
_ => None,
}
};
let src: SharedSource = match &m.media {
MediaRef::Generator(g) => {
let v = m.info.video.as_ref();
@@ -370,6 +400,17 @@ impl MediaPool {
self.set_offline(item, OfflineReason::MadeOffline, path, "made offline");
Arc::new(SlateSource::new(m.info.clone(), &file_name(path), OfflineReason::MadeOffline))
}
// Develop the refreshed or relinked file on first use. A numbered sequence still
// needs its own opener.
MediaRef::File { .. }
if m.info.kind != filmcraft_media::MediaKind::ImageSequence
&& let Some(opened) = reopened_file
&& let Some(raw) = &m.interpret.raw
&& let Some(developed) = opened.with_raw_settings(raw) =>
{
self.offline.write().unwrap_or_else(PoisonError::into_inner).remove(&item);
developed
}
MediaRef::File { path } => match self.follow_media(path).and_then(|file| {
if m.info.kind == filmcraft_media::MediaKind::ImageSequence {
open_image_sequence(&file, services, m.info.frame_rate(), &it.name)
@@ -379,7 +420,7 @@ impl MediaPool {
}) {
Ok(s) => {
self.offline.write().unwrap_or_else(PoisonError::into_inner).remove(&item);
self.unsupported_as_slate(item, path, s)
self.unsupported_as_slate(item, path, with_item_raw_settings(s, m, path))
}
Err(_) if filmcraft_media::pending::is_set() => {
// the host is still fetching the file's bytes: show the slate for now, retry later
@@ -393,7 +434,7 @@ impl MediaPool {
}
},
};
self.sources.write().unwrap_or_else(PoisonError::into_inner).insert(item, (key, src.clone()));
self.insert_keyed(item, key, src.clone());
Some(src)
}
@@ -413,7 +454,7 @@ impl MediaPool {
let reader = services.reader(&file)?.ok()?;
let openers = self.openers.read().unwrap_or_else(PoisonError::into_inner).clone();
let src = filmcraft_media::reader::open_reader_within(&file_name(&file), reader, &filmcraft_codecs::reader_openers(), &openers, 0).ok()?;
Some(self.unsupported_as_slate(item, path, src))
Some(self.unsupported_as_slate(item, path, with_item_raw_settings(src, m, path)))
}
fn set_offline(&self, item: ItemId, reason: OfflineReason, path: &str, error: &str) {
@@ -464,6 +505,17 @@ impl MediaPool {
}
}
/// Clip ▸ Source Settings… of camera raw footage: `s` developed with the item's raw settings.
fn with_item_raw_settings(s: SharedSource, m: &MediaClip, path: &str) -> SharedSource {
match &m.interpret.raw {
Some(r) => s.with_raw_settings(r).unwrap_or_else(|| {
log::warn!("{path}: camera raw settings not applied (not camera raw, or it no longer develops)");
s
}),
None => s,
}
}
/// Implements [`filmcraft_render::SourceProvider`] over the pool for one project snapshot.
pub struct PoolProvider {
pub pool: Arc<MediaPool>,
@@ -602,6 +654,13 @@ struct UnsupportedAsSlate {
offline: Arc<RwLock<HashMap<ItemId, OfflineStatus>>>,
}
impl UnsupportedAsSlate {
fn new(inner: SharedSource, item: ItemId, path: &str, offline: Arc<RwLock<HashMap<ItemId, OfflineStatus>>>) -> Self {
let slate = SlateSource::new(inner.info().clone(), &file_name(path), OfflineReason::Unreadable);
Self { inner, slate, item, path: path.to_string(), offline }
}
}
impl MediaSource for UnsupportedAsSlate {
fn info(&self) -> &MediaInfo {
self.inner.info()
@@ -637,6 +696,13 @@ impl MediaSource for UnsupportedAsSlate {
fn audio_stream(&self, stream: usize, start: i64, frames: usize, sample_rate: u32) -> filmcraft_media::Result<AudioBuffer> {
self.inner.audio_stream(stream, start, frames, sample_rate)
}
fn raw_info(&self) -> Option<filmcraft_media::raw::RawInfo> {
self.inner.raw_info()
}
fn with_raw_settings(&self, settings: &filmcraft_media::raw::RawSettings) -> Option<SharedSource> {
let inner = self.inner.with_raw_settings(settings)?;
Some(Arc::new(Self::new(inner, self.item, &self.path, self.offline.clone())))
}
}
/// Consecutive failed video frames after which a monitor treats a source as damaged. A single
+2 -2
View File
@@ -162,9 +162,9 @@ impl Session {
if identity.is_some() {
m.identity = identity;
}
self.media.insert_reopened_file(id, &path, src, m.interpret.raw);
refreshed.push(id);
}
self.media.insert_file(id, &path, src);
refreshed.push(id);
}
self.bump_view();
Ok(json!({"refreshed": refreshed.iter().map(|i| i.0).collect::<Vec<_>>()}))
+6 -9
View File
@@ -955,21 +955,18 @@ fn cut(s: &mut Session, p: &Value) -> Result<Value> {
// stopped: switch the clip at the playhead
return switch_angle(s, p);
}
let (_, clip) = multicam_clip_at(s, t).ok_or_else(|| EngineError::Other("no multi-camera clip at the playhead".into()))?;
let (video_track, clip) = multicam_clip_at(s, t).ok_or_else(|| EngineError::Other("no multi-camera clip at the playhead".into()))?;
let angle = angle_p(s, p, clip.item, cmd)?;
if s.mcrec.tracks.is_empty() {
let q = s.active_sequence().ok_or(EngineError::NoSequence)?;
let mut tracks: Vec<TrackId> =
q.video_tracks.iter().filter(|tr| tr.item_at(t).is_some_and(|i| i.item == clip.item && i.multicam.is_some())).map(|tr| tr.id).collect();
tracks.truncate(1);
if s.state.multicam_audio_follows_video && !bool_p(p, "videoOnly").unwrap_or(false) {
let partners = audio_partners(q, &clip);
tracks.extend(q.audio_tracks.iter().filter(|tr| tr.items.iter().any(|i| partners.contains(&i.id))).map(|tr| tr.id));
}
let partners = audio_partners(q, &clip);
let mut tracks = vec![video_track];
tracks.extend(q.audio_tracks.iter().filter(|tr| tr.items.iter().any(|i| partners.contains(&i.id))).map(|tr| tr.id));
s.mcrec.tracks = tracks;
}
s.mcrec.source = Some(clip.item);
s.mcrec.cuts.push(Cut { time: t, angle });
let switch_audio = s.state.multicam_audio_follows_video && !bool_p(p, "videoOnly").unwrap_or(false);
s.mcrec.cuts.push(Cut { time: t, angle, switch_audio });
// provisional: the new angle runs to the end of this multi-camera clip (its contiguous pieces)
// until the pass stops
let end = s
+135
View File
@@ -567,6 +567,141 @@ fn live_switch_recording_from_playback_clock() {
assert_eq!(v1(&s), vec![(0, 1)]);
}
#[test]
fn mixed_recording_cuts_preserve_audio_scope() {
let (mut s, _, _, _) = mc_session("switch");
s.execute("multicam.audioFollowsVideo", json!({"enabled": true})).unwrap();
let before = s.project.clone();
s.execute("multicam.recordStart", json!({"frame": 0})).unwrap();
let cut = |s: &mut Session, frame: i64, camera: u64, video_only: bool| {
s.execute("multicam.cut", json!({"frame": frame, "camera": camera, "videoOnly": video_only})).unwrap();
};
cut(&mut s, 12, 3, true);
assert_eq!(a1(&s), [(0, 0), (12, 0)]);
cut(&mut s, 24, 2, false);
cut(&mut s, 48, 3, true);
assert_eq!(a1(&s), [(0, 0), (12, 0), (24, 1), (48, 1)], "a video-only cut keeps the preceding audio live");
cut(&mut s, 72, 3, false);
cut(&mut s, 72, 2, true);
s.execute("multicam.recordStop", json!({"frame": 84})).unwrap();
assert_eq!(v1(&s), [(0, 0), (12, 2), (24, 1), (48, 2), (72, 1), (84, 0)]);
assert_eq!(a1(&s), [(0, 0), (12, 0), (24, 1), (48, 1), (72, 2), (84, 0)]);
let q = s.active_sequence().unwrap();
for frame in [0, 12, 24, 48, 72, 84] {
let t = q.settings.frame_rate.tick_of(frame);
let video = q.video_tracks[0].item_at(t).unwrap();
let audio = q.audio_tracks[0].item_at(t).unwrap();
assert!(video.link.is_some() && video.link == audio.link, "paired splits remain linked at frame {frame}");
}
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(s.project, before);
}
#[test]
fn recorded_video_only_cut_keeps_audio_for_a_later_camera_edit() {
let (mut s, _, _, _) = mc_session("switch");
s.execute("multicam.audioFollowsVideo", json!({"enabled": true})).unwrap();
s.execute("multicam.recordStart", json!({"frame": 0})).unwrap();
s.execute("multicam.cut", json!({"frame": 24, "camera": 2})).unwrap();
s.execute("multicam.cut", json!({"frame": 48, "camera": 3, "videoOnly": true})).unwrap();
s.execute("multicam.recordStop", json!({"frame": 84})).unwrap();
s.execute("multicam.cutToCamera", json!({"frame": 60, "camera": 1})).unwrap();
assert_eq!(v1(&s), [(0, 0), (24, 1), (48, 2), (60, 0), (84, 0)]);
assert_eq!(a1(&s), [(0, 0), (24, 1), (48, 1), (60, 0), (84, 0)], "the later edit switches linked audio from frame 60");
}
#[test]
fn recorded_audio_change_keeps_its_matching_picture_edit() {
let (mut s, _, _, _) = mc_session("switch");
s.execute("multicam.audioFollowsVideo", json!({"enabled": true})).unwrap();
s.execute("multicam.recordStart", json!({"frame": 0})).unwrap();
s.execute("multicam.cut", json!({"frame": 12, "camera": 2, "videoOnly": true})).unwrap();
s.execute("multicam.cut", json!({"frame": 24, "camera": 2})).unwrap();
s.execute("multicam.cut", json!({"frame": 36, "camera": 2})).unwrap();
s.execute("multicam.recordStop", json!({"frame": 84})).unwrap();
assert_eq!(v1(&s), [(0, 0), (12, 1), (24, 1), (84, 0)], "retain the audio change but heal the repeated switch");
assert_eq!(a1(&s), [(0, 0), (12, 0), (24, 1), (84, 0)]);
s.execute("multicam.switchAngle", json!({"frame": 30, "camera": 3})).unwrap();
assert_eq!(v1(&s), [(0, 0), (12, 1), (24, 2), (84, 0)]);
assert_eq!(a1(&s), [(0, 0), (12, 0), (24, 2), (84, 0)]);
}
#[test]
fn video_only_recording_preserves_the_rendered_audio_fades() {
let (mut s, _, _, _) = mc_session("switch");
let clip = s.active_sequence().unwrap().audio_tracks[0].items[0].id.0;
for edge in ["in", "out"] {
s.execute("sequence.applyAudioTransition", json!({"clip": clip, "edge": edge, "frames": 40})).unwrap();
}
let mix = |s: &Session| {
let provider = s.media.provider(s.project.clone(), s.services.clone());
filmcraft_render::audio::mix_sequence(&s.project, s.active_sequence().unwrap(), 0, 4 * 48_000, &provider).channels
};
let before = mix(&s);
assert!(before[0].iter().any(|sample| sample.abs() > 1e-3));
s.execute("multicam.audioFollowsVideo", json!({"enabled": true})).unwrap();
s.execute("multicam.recordStart", json!({"frame": 0})).unwrap();
for (frame, camera) in [(12, 2), (24, 3), (72, 2)] {
s.execute("multicam.cut", json!({"frame": frame, "camera": camera, "videoOnly": true})).unwrap();
}
s.execute("multicam.recordStop", json!({"frame": 84})).unwrap();
let after = mix(&s);
for (a, b) in before.iter().flatten().zip(after.iter().flatten()) {
assert!((a - b).abs() < 1e-5, "a picture-only cut changed a faded sample: {a} vs {b}");
}
let seq = s.active_sequence().unwrap();
let audio = &seq.audio_tracks[0];
assert_eq!(audio.transitions.len(), 2);
assert_eq!(audio.transitions[0].to, Some(audio.items.first().unwrap().id));
assert_eq!(audio.transitions[1].from, Some(audio.items.last().unwrap().id));
for (picture, sound) in seq.video_tracks[0].items.iter().zip(&audio.items) {
assert_eq!(picture.range(), sound.range());
assert!(picture.link.is_some() && picture.link == sound.link);
}
let fade = audio.transitions[0].id.0;
let middle = audio.item_at(seq.settings.frame_rate.tick_of(30)).unwrap().id.0;
for frames in [6, 40] {
s.execute("sequence.setTransition", json!({"transition": fade, "frames": frames})).unwrap();
let seq = s.active_sequence().unwrap();
assert_eq!(seq.audio_tracks[0].transitions[0].duration, seq.settings.frame_rate.tick_of(frames));
}
s.execute("clip.audioGain", json!({"clips": [middle], "mode": "set", "db": -6.0})).unwrap();
let adjusted = mix(&s);
let window = 60_000..62_000; // frame 30, inside both the middle piece and the fade-in
let gain = 10.0_f32.powf(-6.0 / 20.0);
assert!(before[0][window.clone()].iter().any(|v| v.abs() > 1e-3));
for (old, new) in before[0][window.clone()].iter().zip(&adjusted[0][window]) {
assert!((new - old * gain).abs() < 1e-5, "the fade must follow the audio piece under the playhead");
}
}
#[test]
fn overlapping_multicam_fades_use_the_later_transition_in_the_overlap() {
let (mut s, _, _, _) = mc_session("switch");
let clip = s.active_sequence().unwrap().audio_tracks[0].items[0].id.0;
s.execute("sequence.applyAudioTransition", json!({"clip": clip, "edge": "in", "frames": 12})).unwrap();
s.execute("sequence.applyAudioTransition", json!({"clip": clip, "edge": "out", "frames": 48})).unwrap();
let fade_in = s.active_sequence().unwrap().audio_tracks[0].transitions[0].id.0;
// Frames 52..60 of a 96-frame clip initially contain only the fade-out.
let render_overlap = |s: &Session| {
let provider = s.media.provider(s.project.clone(), s.services.clone());
filmcraft_render::audio::mix_sequence(&s.project, s.active_sequence().unwrap(), 52 * 2000, 8 * 2000, &provider).channels
};
let fade_out_alone = render_overlap(&s);
assert!(fade_out_alone[0].iter().any(|sample| sample.abs() > 1e-3));
s.execute("sequence.setTransition", json!({"transition": fade_in, "frames": 72})).unwrap();
let check = |s: &Session| {
for (actual, expected) in render_overlap(s).iter().flatten().zip(fade_out_alone.iter().flatten()) {
assert!((actual - expected).abs() < 1e-5, "overlapping an earlier fade changed the fade-out: {actual} vs {expected}");
}
};
check(&s);
s.execute("multicam.recordStart", json!({"frame": 0})).unwrap();
s.execute("multicam.cut", json!({"frame": 56, "camera": 2, "videoOnly": true})).unwrap();
s.execute("multicam.recordStop", json!({"frame": 84})).unwrap();
check(&s);
}
#[test]
fn flatten_replaces_with_camera_clips() {
let (mut s, items, _, _) = mc_session("switch");
+37 -18
View File
@@ -157,9 +157,11 @@ pub const LOG_FIELDS: [&str; 9] = ["Description", "Scene", "Shot", "Take", "Log
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Field {
/// "Clip" or "File".
/// "Clip", "File" or "Metadata".
pub section: &'static str,
pub name: String,
/// Stable command selector; distinct from the displayed heading.
pub id: String,
pub value: String,
pub editable: bool,
}
@@ -196,7 +198,7 @@ pub fn metadata_fields(p: &Project, id: ItemId) -> Vec<Field> {
_ => it.frame_rate(),
};
let mut out = Vec::new();
let mut add = |section, name: &str, value: String, editable| out.push(Field { section, name: name.to_string(), value, editable });
let mut add = |section, name: &str, value: String, editable| out.push(Field { section, name: name.to_string(), id: name.to_string(), value, editable });
add("Clip", "Name", it.name.clone(), true);
add("Clip", "Label", it.label_value(), true);
add("Clip", "Media Type", it.type_label().to_string(), false);
@@ -241,12 +243,6 @@ pub fn metadata_fields(p: &Project, id: ItemId) -> Vec<Field> {
for k in LOG_FIELDS {
add("Clip", k, it.metadata.get(k).cloned().unwrap_or_default(), true);
}
// other stored fields (from imports, Edit Offline, agents…)
for (k, v) in &it.metadata {
if !LOG_FIELDS.contains(&k.as_str()) && !crate::project_panel::is_freeform_key(k) {
add("Clip", k, v.clone(), true);
}
}
if let Some(m) = media {
let path = match &m.media {
MediaRef::File { path } => path.clone(),
@@ -264,6 +260,12 @@ pub fn metadata_fields(p: &Project, id: ItemId) -> Vec<Field> {
}
add("File", "Status", if m.offline { "Offline".into() } else { "Online".into() }, false);
}
// Stored fields have their own identity even when named Name, Label or File Path.
for (k, v) in &it.metadata {
if !LOG_FIELDS.contains(&k.as_str()) && !crate::project_panel::is_internal_key(k) {
out.push(Field { section: "Metadata", name: k.clone(), id: filmcraft_project::find::metadata_id(k), value: v.clone(), editable: true });
}
}
out
}
@@ -285,7 +287,8 @@ fn metadata_get(s: &mut Session, p: &Value) -> Result<Value> {
/// `metadata.set {item?, field, value}` or `{item?, fields: {name: value}}`: one undo step.
/// Name renames the item, Label sets its label, every other name is a log field (an empty value
/// removes it).
/// removes it). An explicit `metadata:<exact key>` edits only stored metadata and preserves
/// an empty string as a present value. Use `metadata.get` field IDs when editing UI rows.
fn metadata_set(s: &mut Session, p: &Value) -> Result<Value> {
let id = metadata_target(s, p).ok_or_else(|| bad("metadata.set", "no item: pass `item` or `clip`, or select one"))?;
let mut changes: Vec<(String, String)> = Vec::new();
@@ -302,6 +305,12 @@ fn metadata_set(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad("metadata.set", "need `field` + `value` or `fields`"));
}
for (k, v) in &changes {
if let Some(key) = filmcraft_project::find::metadata_key(k) {
if key.trim().is_empty() || crate::project_panel::is_internal_key(key) {
return Err(bad("metadata.set", "empty or internal metadata key"));
}
continue;
}
if k.trim().is_empty() {
return Err(bad("metadata.set", "empty field name"));
}
@@ -317,22 +326,32 @@ fn metadata_set(s: &mut Session, p: &Value) -> Result<Value> {
}
let unchanged = {
let it = s.project.item(id).ok_or_else(|| bad("metadata.set", "no such item"))?;
changes.iter().all(|(k, v)| match k.to_ascii_lowercase().as_str() {
"name" => it.name == *v,
"label" => {
if let Some(color) = filmcraft_project::HexColor::parse(v) {
it.custom_label_color == Some(color)
} else {
it.custom_label_color.is_none() && Label::from_color_name(v) == Some(it.label)
}
changes.iter().all(|(k, v)| {
if let Some(key) = filmcraft_project::find::metadata_key(k) {
return it.metadata.get(key) == Some(v);
}
match k.to_ascii_lowercase().as_str() {
"name" => it.name == *v,
"label" => {
if let Some(color) = filmcraft_project::HexColor::parse(v) {
it.custom_label_color == Some(color)
} else {
it.custom_label_color.is_none() && Label::from_color_name(v) == Some(it.label)
}
}
_ if v.is_empty() => !it.metadata.contains_key(k),
_ => it.metadata.get(k) == Some(v),
}
_ => it.metadata.get(k).map(String::as_str).unwrap_or("") == v.as_str(),
})
};
if !unchanged {
s.edit("Edit Metadata", |pr, _| {
let it = pr.item_mut(id).ok_or_else(|| bad("metadata.set", "no such item"))?;
for (k, v) in &changes {
if let Some(key) = filmcraft_project::find::metadata_key(k) {
it.metadata.insert(key.to_string(), v.clone());
continue;
}
match k.to_ascii_lowercase().as_str() {
"name" => it.name = v.trim().to_string(),
"label" => {
+1
View File
@@ -742,6 +742,7 @@ pub fn render(s: &mut Session, mode: RenderMode, p: &Value) -> Result<Value> {
prog.finished.store(true, Ordering::Relaxed);
*res.lock().unwrap_or_else(|x| x.into_inner()) = Some(r);
};
let run = move || filmcraft_export::on_own_threads(0, run);
let run = crate::export_tools::guard_job(job.progress.clone(), job.result.clone(), run);
s.jobs.push(job);
let wait = p.get("wait").and_then(Value::as_bool).unwrap_or(false);
+12 -3
View File
@@ -227,9 +227,16 @@ pub fn run(s: &mut Session, p: &Value) -> Result<Value> {
let (prog, res) = (job.progress.clone(), job.result.clone());
let prev_dst = crate::previews::dir_for_project(&project_path);
let services = s.services.clone();
let media = s.media.clone();
let run = move || {
let t0 = web_time::Instant::now();
let r = execute(proj, work, sources, previews.map(|d| (d, prev_dst)), JobEnv { project_path: &project_path, pr, prog: &prog, services: &*services });
let r = execute(
proj,
work,
sources,
previews.map(|d| (d, prev_dst)),
JobEnv { project_path: &project_path, pr, prog: &prog, services: &*services, media: &media },
);
let secs = t0.elapsed().as_secs_f64();
let r = r.map(|bytes| filmcraft_export::Report {
path: project_path.clone(),
@@ -267,6 +274,7 @@ struct JobEnv<'a> {
pr: &'a Preset,
prog: &'a filmcraft_export::Progress,
services: &'a dyn crate::Services,
media: &'a crate::MediaPool,
}
fn execute(
@@ -276,7 +284,7 @@ fn execute(
previews: Option<(PathBuf, PathBuf)>,
env: JobEnv<'_>,
) -> std::result::Result<u64, String> {
let JobEnv { project_path, pr, prog, services } = env;
let JobEnv { project_path, pr, prog, services, media } = env;
let mut bytes = 0;
let openers = filmcraft_codecs::openers();
for w in &work {
@@ -328,7 +336,8 @@ fn execute(
if let Some((from, to)) = previews {
bytes += copy_dir(&from, &to).map_err(|e| format!("copying previews: {e}"))?;
}
let data = filmcraft_format::encode(&proj, false);
let stored = crate::doc_path::project_for_document(&proj, Some(project_path), |p| media.follow(p));
let data = filmcraft_format::encode(&stored, false);
filmcraft_format::atomic_write(Path::new(project_path), &data).map_err(|e| format!("{project_path}: {e}"))?;
prog.done.fetch_add(1, Ordering::Relaxed);
Ok(bytes + data.len() as u64)
+53 -19
View File
@@ -270,6 +270,17 @@ pub fn is_internal_key(k: &str) -> bool {
INTERNAL_KEYS.contains(&k) || k.starts_with(ARRANGEMENT_PREFIX)
}
/// Keep ordinary legacy headings; qualify collisions with built-ins and the selector prefix.
pub fn metadata_column(key: &str) -> String {
if BUILTIN_COLUMNS.iter().chain(["All", "Type", "Duration", "Path"].iter()).any(|c| c.eq_ignore_ascii_case(key))
|| filmcraft_project::find::metadata_key(key).is_some()
{
filmcraft_project::find::metadata_id(key)
} else {
key.to_string()
}
}
pub fn default_width(c: &str) -> f32 {
match c {
"Name" => 220.0,
@@ -286,8 +297,12 @@ pub fn all_columns(p: &Project) -> Vec<String> {
let mut extra: Vec<String> = Vec::new();
for it in p.items.values() {
for k in it.metadata.keys() {
if !is_internal_key(k) && !v.iter().any(|c| c.eq_ignore_ascii_case(k)) && !extra.contains(k) {
extra.push(k.clone());
// Exact log headings already refer to the same stored value.
if !is_internal_key(k) && !crate::panels::LOG_FIELDS.contains(&k.as_str()) && k != "Good" {
let column = metadata_column(k);
if !extra.contains(&column) {
extra.push(column);
}
}
}
}
@@ -328,6 +343,11 @@ pub fn usage(p: &Project, id: ItemId) -> (usize, usize) {
/// The text and sort key of one List view cell.
pub fn cell(p: &Project, it: &ProjectItem, column: &str) -> (String, SortKey) {
if let Some(key) = filmcraft_project::find::metadata_key(column) {
let value = it.metadata.get(key).cloned().unwrap_or_default();
let sort = SortKey::Text(value.to_lowercase());
return (value, sort);
}
let media = media_of(p, it);
let rate = match &it.kind {
ItemKind::Subclip { parent, .. } => p.item(*parent).map(|x| x.frame_rate()).unwrap_or_default(),
@@ -431,7 +451,7 @@ pub fn cell(p: &Project, it: &ProjectItem, column: &str) -> (String, SortKey) {
None => (String::new(), SortKey::Num(-1.0)),
},
"Date Created" => (it.created.to_string(), SortKey::Num(it.created as f64)),
_ => text(it.metadata.iter().find(|(k, _)| k.eq_ignore_ascii_case(column)).map(|(_, v)| v.clone()).unwrap_or_default()),
_ => text(it.metadata.get(column).cloned().unwrap_or_default()),
}
}
@@ -940,10 +960,10 @@ fn view_set(s: &mut Session, p: &Value) -> Result<Value> {
}
if let Some(v) = p.get("iconSort") {
match v {
Value::String(c) => pp.view.icon_sort.column = canonical_column(&s.project, c).unwrap_or_default(),
Value::String(c) => pp.view.icon_sort.column = canonical_column(&s.project, &pp.view.columns, c).unwrap_or_default(),
Value::Object(_) => {
if let Some(c) = str_p(v, "column") {
pp.view.icon_sort.column = canonical_column(&s.project, c).unwrap_or_default();
pp.view.icon_sort.column = canonical_column(&s.project, &pp.view.columns, c).unwrap_or_default();
}
if let Some(d) = bool_p(v, "descending") {
pp.view.icon_sort.descending = d;
@@ -957,8 +977,20 @@ fn view_set(s: &mut Session, p: &Value) -> Result<Value> {
}
/// The column's canonical spelling, or None for an unknown column ("" / "User Order" = None).
fn canonical_column(p: &Project, c: &str) -> Option<String> {
all_columns(p).into_iter().find(|x| x.eq_ignore_ascii_case(c.trim()))
fn canonical_column(p: &Project, shown: &[Column], c: &str) -> Option<String> {
if shown.iter().any(|x| x.name == c) {
return Some(c.to_string());
}
let columns = all_columns(p);
if columns.iter().any(|x| x == c) {
return Some(c.to_string());
}
// Explicit metadata selectors are case-sensitive, including unknown fields configured
// before import. Only built-in aliases retain the historical case-insensitive spelling.
if let Some(key) = filmcraft_project::find::metadata_key(c) {
return p.items.values().any(|it| it.metadata.contains_key(key)).then(|| c.to_string());
}
BUILTIN_COLUMNS.iter().find(|x| x.eq_ignore_ascii_case(c.trim())).map(|x| x.to_string())
}
fn columns_set(s: &mut Session, p: &Value) -> Result<Value> {
@@ -971,9 +1003,10 @@ fn columns_set(s: &mut Session, p: &Value) -> Result<Value> {
_ => return Err(bad("project.columns.set", "columns are names or {name, width}")),
};
// custom fields may be added before any item has them
let name = canonical_column(&s.project, &name).unwrap_or_else(|| name.trim().to_string());
if name.is_empty() {
return Err(bad("project.columns.set", "empty column name"));
let name = canonical_column(&s.project, &s.prefs.project_panel.view.columns, &name)
.unwrap_or_else(|| if filmcraft_project::find::metadata_key(&name).is_some() { name.clone() } else { name.trim().to_string() });
if name.is_empty() || filmcraft_project::find::metadata_key(&name).is_some_and(|k| k.trim().is_empty() || is_internal_key(k)) {
return Err(bad("project.columns.set", "empty or internal column name"));
}
if cols.iter().any(|c| c.name == name) {
continue;
@@ -1003,13 +1036,13 @@ fn columns_resize(s: &mut Session, p: &Value) -> Result<Value> {
let c = str_p(p, "column").ok_or_else(|| bad("project.columns.resize", "need `column`"))?;
let w = f64_p(p, "width").ok_or_else(|| bad("project.columns.resize", "need `width`"))? as f32;
let mut prefs = s.prefs.clone();
let col = prefs
.project_panel
.view
.columns
.iter_mut()
.find(|x| x.name.eq_ignore_ascii_case(c))
.ok_or_else(|| bad("project.columns.resize", format!("`{c}` is not shown")))?;
let name = if prefs.project_panel.view.columns.iter().any(|x| x.name == c) {
c.to_string()
} else {
canonical_column(&s.project, &prefs.project_panel.view.columns, c).unwrap_or_else(|| c.to_string())
};
let col =
prefs.project_panel.view.columns.iter_mut().find(|x| x.name == name).ok_or_else(|| bad("project.columns.resize", format!("`{c}` is not shown")))?;
col.width = w.clamp(30.0, 800.0);
save_prefs(s, prefs)?;
Ok(json!({"columns": s.prefs.project_panel.view.columns}))
@@ -1017,7 +1050,7 @@ fn columns_resize(s: &mut Session, p: &Value) -> Result<Value> {
fn sort(s: &mut Session, p: &Value) -> Result<Value> {
let c = str_p(p, "column").ok_or_else(|| bad("project.sort", "need `column`"))?;
let c = canonical_column(&s.project, c).ok_or_else(|| bad("project.sort", format!("unknown column `{c}`")))?;
let c = canonical_column(&s.project, &s.prefs.project_panel.view.columns, c).ok_or_else(|| bad("project.sort", format!("unknown column `{c}`")))?;
let mut prefs = s.prefs.clone();
let cur = &mut prefs.project_panel.view.sort;
let desc = bool_p(p, "descending").unwrap_or(cur.column == c && !cur.descending);
@@ -1245,7 +1278,8 @@ pub(crate) fn commands() -> Vec<CommandSpec> {
),
q("project.columns.list", "List Project Columns", "{}", |s, _| {
let shown = &s.prefs.project_panel.view.columns;
let all: Vec<Value> = all_columns(&s.project).into_iter().map(|n| json!({"name": n, "shown": shown.iter().any(|c| c.name == n)})).collect();
let all: Vec<Value> =
all_columns(&s.project).into_iter().map(|n| json!({"name": n, "label": n, "shown": shown.iter().any(|c| c.name == n)})).collect();
Ok(json!({"columns": shown, "available": all}))
}),
c("project.columns.set", "Metadata Display", r#"{"columns":[name|{"name":str,"width":f32}]}"#, always, columns_set),
+103
View File
@@ -108,6 +108,20 @@ fn sorting_by_a_column_and_reversing() {
assert!(s.execute("project.sort", json!({"column": "Nope"})).is_err());
}
#[test]
fn configured_metadata_column_can_sort_before_any_item_has_the_key() {
let mut s = demo();
assert!(s.project.items.values().all(|it| !it.metadata.contains_key("Mood")));
s.execute("project.columns.set", json!({"columns": ["Name", "metadata:Mood", "Unused"]})).unwrap();
s.execute("project.sort", json!({"column": "metadata:Mood"})).unwrap();
assert_eq!(s.prefs.project_panel.view.sort.column, "metadata:Mood");
s.execute("project.view.set", json!({"iconSort": "metadata:Mood"})).unwrap();
assert_eq!(s.prefs.project_panel.view.icon_sort.column, "metadata:Mood");
s.execute("project.sort", json!({"column": "Unused"})).unwrap();
assert!(s.execute("project.sort", json!({"column": "metadata:Unknown"})).is_err());
assert!(s.execute("project.sort", json!({"column": "Unknown"})).is_err());
}
#[test]
fn view_presets_save_restore_and_manage() {
let mut s = demo();
@@ -378,6 +392,95 @@ fn select_all_rejects_bad_bins_without_touching_the_selection() {
assert_eq!(r["selected"].as_u64(), Some(s.project.items.len() as u64));
}
#[test]
fn metadata_identity_survives_columns_sort_edit_and_reload() {
use filmcraft_project::find::{FindOp, FindQuery, metadata_id};
let mut s = demo();
let ids = media(&s);
let a = ids[0];
let b = ids[1];
let name = s.project.item(a).unwrap().name.clone();
s.execute(
"metadata.set",
json!({"item": a.0, "fields": {
"metadata:Scene": "upper", "metadata:scene": "lower", "metadata:Name": "z custom",
"metadata:Label": "not a label", "metadata:File Path": "original path",
"metadata:Mood": "z", "metadata:mood": "a", "metadata:Blank": "",
"metadata:metadata:Name": "literal prefix", "metadata:Name (metadata)": "literal suffix", "metadata:résumé": "unicode"
}}),
)
.unwrap();
s.execute("metadata.set", json!({"item": b.0, "field": "metadata:Name", "value": "a custom"})).unwrap();
let columns = project_panel::all_columns(&s.project);
for key in ["metadata:Name", "metadata:Label", "metadata:File Path", "metadata:scene", "Mood", "mood", "metadata:metadata:Name", "Name (metadata)"] {
assert!(columns.iter().any(|c| c == key), "missing {key}");
}
s.execute("project.columns.set", json!({"columns": ["Name", "metadata:Name", "Scene", "metadata:scene", "Mood", "mood"]})).unwrap();
s.execute("project.columns.resize", json!({"column": "mood", "width": 171})).unwrap();
let cols = &s.prefs.project_panel.view.columns;
assert_eq!(cols.iter().find(|c| c.name == "mood").unwrap().width, 171.0);
assert_ne!(cols.iter().find(|c| c.name == "Mood").unwrap().width, 171.0);
s.execute("project.sort", json!({"column": "metadata:Name", "descending": false})).unwrap();
let mut order = vec![a, b];
project_panel::sort_items(&s.project, &mut order, &s.prefs.project_panel.view.sort);
assert_eq!(order, vec![b, a]);
let it = s.project.item(a).unwrap();
for (key, expected) in
[("Name", name.as_str()), ("metadata:Name", "z custom"), ("Scene", "upper"), ("metadata:scene", "lower"), ("Mood", "z"), ("mood", "a")]
{
assert_eq!(project_panel::cell(&s.project, it, key).0, expected);
}
assert_eq!(project_panel::cell(&s.project, it, "Name (metadata)").0, "literal suffix");
assert_eq!(project_panel::cell(&s.project, it, "metadata:metadata:Name").0, "literal prefix");
assert_eq!(FindQuery::simple(&metadata_id("Name"), FindOp::Matches, "z custom").find(&s.project), vec![a]);
assert_eq!(FindQuery::simple("scene", FindOp::Matches, "lower").find(&s.project), vec![a]);
assert_eq!(FindQuery::simple("SCENE", FindOp::Matches, "upper").find(&s.project), vec![]);
let fields = crate::panels::metadata_fields(&s.project, a);
assert_eq!(fields.iter().filter(|f| f.name == "Name").count(), 2);
assert!(fields.iter().any(|f| f.id == "metadata:Label" && f.editable && f.value == "not a label"));
let n = s.history.undo.len();
s.execute("metadata.set", json!({"item": a.0, "field": "metadata:Name", "value": "edited"})).unwrap();
assert_eq!(s.project.item(a).unwrap().name, name);
assert_eq!(s.history.undo.len(), n + 1);
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(s.project.item(a).unwrap().metadata["Name"], "z custom");
s.execute("edit.redo", json!({})).unwrap();
let back = filmcraft_format::decode(&filmcraft_format::encode(&s.project, false)).unwrap().project;
assert_eq!(back.item(a).unwrap().metadata, s.project.item(a).unwrap().metadata);
assert_eq!(back.item(a).unwrap().metadata.get("Blank").map(String::as_str), Some(""));
assert!(!back.item(b).unwrap().metadata.contains_key("Blank"));
let prefs: crate::autosave::Preferences = serde_json::from_str(&serde_json::to_string(&s.prefs).unwrap()).unwrap();
assert_eq!(prefs.project_panel, s.prefs.project_panel);
}
#[test]
fn metadata_clear_removes_a_stored_empty_value_once() {
let mut s = demo();
let id = media(&s)[0];
s.execute("metadata.set", json!({"item": id.0, "field": "metadata:Mood", "value": ""})).unwrap();
assert_eq!(s.project.item(id).unwrap().metadata["Mood"], "");
let clear = json!({"item": id.0, "field": "Mood", "value": ""});
assert_eq!(s.execute("metadata.set", clear.clone()).unwrap()["changed"], true);
assert!(!s.project.item(id).unwrap().metadata.contains_key("Mood"));
assert_eq!(s.execute("metadata.set", clear).unwrap()["changed"], false);
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(s.project.item(id).unwrap().metadata["Mood"], "");
}
#[test]
fn explicit_metadata_rejects_invalid_keys_atomically() {
let mut s = demo();
let id = media(&s)[0];
for key in ["metadata:", "metadata: "] {
let before = filmcraft_format::encode(&s.project, false);
assert!(s.execute("metadata.set", json!({"item": id.0, "fields": {key: "x", "metadata:valid": "y"}})).is_err());
assert_eq!(filmcraft_format::encode(&s.project, false), before);
}
assert!(s.execute("metadata.set", json!({"item": id.0, "field": format!("metadata:{FREEFORM_POS}"), "value": "x"})).is_err());
assert!(s.execute("metadata.set", json!({"item": u64::MAX, "field": "metadata:Name", "value": "x"})).is_err());
}
/// New Item / File ▸ New take an optional `bin` and make the item there (#4093).
#[test]
fn new_items_land_in_the_given_bin() {
+9 -19
View File
@@ -16,7 +16,7 @@
//! | `edit.editOriginal` | Edit ▸ Edit Original (⌘E): the frontend opens the files (regular files with a media extension only) |
//! | `file.reveal` | Project panel ▸ Reveal in Finder / Show in Explorer: the frontend reveals the media file |
//! | `clip.editOffline` | Clip ▸ Edit Offline… |
//! | `clip.sourceSettings` | Clip ▸ Source Settings… |
//! | `clip.sourceSettings` | Clip ▸ Source Settings… (camera raw; `crate::raw_settings`, placed here) |
//! | `clip.restoreCaptionsFromSource` | Clip ▸ Restore Captions from Source Clip (always disabled: no embedded caption reader) |
//! | `clip.updateMetadata` | Clip ▸ Update Metadata… (XMP sidecars) |
//! | `clip.generateAudioWaveform` | Clip ▸ Generate Audio Waveform (the frontend rebuilds its peaks) |
@@ -176,7 +176,6 @@ pub(crate) fn commands() -> Vec<CommandSpec> {
has_offline_selection,
edit_offline,
),
query("clip.sourceSettings", "Source Settings…", &["Clip"], None, r#"{"item":id?}"#, has_media_selection, source_settings),
spec("clip.restoreCaptionsFromSource", "Restore Captions from Source Clip", &["Clip"], None, "{}", no_embedded_captions, |_, _| {
Err(EngineError::Other(NO_CAPTIONS.into()))
}),
@@ -348,7 +347,7 @@ fn has_find(s: &Session) -> std::result::Result<(), String> {
/// Project items the command works on: `items`, else the Project panel selection, else the media
/// of the selected timeline clips.
fn targets(s: &Session, p: &Value) -> Vec<ItemId> {
pub(crate) fn targets(s: &Session, p: &Value) -> Vec<ItemId> {
if let Some(a) = p.get("items").and_then(Value::as_array) {
return a.iter().filter_map(|v| v.as_u64().map(ItemId)).filter(|i| s.project.items.contains_key(i)).collect();
}
@@ -640,7 +639,8 @@ fn save_as_template(s: &mut Session, p: &Value) -> Result<Value> {
let mut proj = (*s.project).clone();
proj.name = name.clone();
proj.root.name = name.clone();
s.services.write_file(&path, &filmcraft_format::encode(&proj, false)).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
let stored = crate::doc_path::project_for_document(&proj, Some(&path), |p| s.media.follow(p));
s.services.write_file(&path, &filmcraft_format::encode(&stored, false)).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
Ok(json!({"path": path, "name": name}))
}
@@ -671,6 +671,7 @@ fn new_from_template(s: &mut Session, p: &Value) -> Result<Value> {
};
let bytes = s.services.read_file_bounded(&path, filmcraft_format::MAX_PROJECT_BYTES).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
let mut proj = filmcraft_format::decode(&bytes).map_err(|e| EngineError::Other(e.to_string()))?.project;
crate::doc_path::absolutize(&mut proj, Some(&path));
if s.is_dirty() && !bool_p(p, "force").unwrap_or(false) {
return Err(EngineError::Other("the project has unsaved changes: save it first, or pass {\"force\": true} to discard them".into()));
}
@@ -814,7 +815,8 @@ fn export_selection(s: &mut Session, p: &Value) -> Result<Value> {
let name = std::path::Path::new(&path).file_stem().map(|x| x.to_string_lossy().to_string()).unwrap_or_else(|| sub.name.clone());
sub.name = name.clone();
sub.root.name = name;
s.services.write_file(&path, &filmcraft_format::encode(&sub, false)).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
let stored = crate::doc_path::project_for_document(&sub, Some(&path), |p| s.media.follow(p));
s.services.write_file(&path, &filmcraft_format::encode(&stored, false)).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
Ok(json!({"path": path, "items": keep.iter().map(|i| i.0).collect::<Vec<_>>()}))
}
@@ -828,7 +830,8 @@ fn export_ale(s: &mut Session, p: &Value) -> Result<Value> {
// the whole project, in Project panel order
s.project.root.all_items(&mut items);
}
let doc = filmcraft_interchange::ale::export_items(&s.project, &items);
let resolved = crate::doc_path::resolved_project(&s.project, |p| s.media.follow(p));
let doc = filmcraft_interchange::ale::export_items(&resolved, &items);
if doc.rows.is_empty() {
return Err(EngineError::Other("none of the items is a clip that can be logged".into()));
}
@@ -1172,19 +1175,6 @@ fn edit_offline(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"item": id.0, "name": it.name, "metadata": it.metadata}))
}
fn source_settings(s: &mut Session, p: &Value) -> Result<Value> {
let id = targets(s, p).into_iter().find(|i| media_of(&s.project, *i).is_some()).ok_or_else(|| EngineError::Other("select a clip".into()))?;
let (_, m) = media_of(&s.project, id).ok_or_else(|| EngineError::Other("select a clip".into()))?;
let codec = m.info.video.as_ref().map(|v| v.codec.clone()).or_else(|| m.info.audio().map(|a| a.codec.clone())).unwrap_or_default();
Ok(json!({
"item": id.0,
"codec": codec,
"container": m.info.container,
"settings": [],
"message": format!("{} has no source settings in FilmCraft. Source settings apply to camera raw formats (R3D, ARRIRAW, CinemaDNG, ProRes RAW…), which FilmCraft does not decode.", if codec.is_empty() { "This clip".to_string() } else { codec.to_uppercase() }),
}))
}
fn xml_escape(s: &str) -> String {
s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;")
}
+13 -3
View File
@@ -304,10 +304,8 @@ fn start_job(s: &mut Session, label: String, work: Vec<(ItemId, ReservedOutput,
crate::media_queue::MEDIA_JOBS.ticket()
};
let (pool, project, services) = (s.media.clone(), s.project.clone(), s.services.clone());
let waiting = job.progress.clone();
let run = move || {
// a job cancelled while it waits raises the same flag the loop below checks
#[cfg(not(target_arch = "wasm32"))]
ticket.wait(&prog.cancel);
let t0 = web_time::Instant::now();
let mut bytes = 0;
let mut err = None;
@@ -353,6 +351,18 @@ fn start_job(s: &mut Session, label: String, work: Vec<(ItemId, ReservedOutput,
prog.finished.store(true, std::sync::atomic::Ordering::Relaxed);
*res.lock().unwrap_or_else(|x| x.into_inner()) = Some(r);
};
// its turn first, on the job's thread, so a queued job holds no pool of threads while it waits
// (a job cancelled while it waits raises the same flag the loop above checks); the ticket lets
// the next job go when this one is done
let run = move || {
#[cfg(not(target_arch = "wasm32"))]
ticket.wait(&waiting.cancel);
#[cfg(target_arch = "wasm32")]
let _ = &waiting;
filmcraft_export::on_own_threads(0, run);
#[cfg(not(target_arch = "wasm32"))]
drop(ticket);
};
let run = crate::export_tools::guard_job(job.progress.clone(), job.result.clone(), run);
s.jobs.push(job);
s.media_jobs.push(PendingJob { job: id, on_done, outputs, source_durations, started_from, epoch: s.document_epoch });
+260
View File
@@ -0,0 +1,260 @@
//! Camera raw Source Settings (Clip ▸ Source Settings…): how DNG footage (stills, CinemaDNG
//! folders, CinemaDNG in MXF) is developed, per media item. Behaviour follows Premiere's Source
//! Settings for camera raw formats as Adobe's public help describes it: the settings belong to
//! the source, so every clip of the item changes, and they are one undoable change.
//!
//! - `clip.sourceSettings {items?|item?, whiteBalance?, temperature?, tint?, exposure?,
//! highlights?, demosaic?, output?, reset?}`: change the settings of the camera raw items
//! addressed (default: the Project panel selection, else the media of the selected timeline
//! clips; subclips address their media). Values left out keep each item's current one.
//! `temperature` / `tint` set a custom white balance; `whiteBalance: "asShot"` goes back to the
//! camera's. `reset: true` develops as the file says. Without any setting it changes nothing
//! and describes the first item (as `media.rawInfo`; for other footage, why it has no source
//! settings), which is what the dialog shows.
//! - `media.rawInfo {item}`: whether the item is camera raw, its settings, and the file's as-shot
//! white balance as temperature and tint (the starting point of a custom one).
//!
//! The settings are stored in the item's `Interpretation::raw` (None = as the file says); the
//! media pool opens the item again with them ([`crate::media_pool::media_key`]).
use filmcraft_media::raw::{self, DemosaicQuality, Highlights, OutputSpace, RawSettings, WhiteBalance};
use filmcraft_project::{ItemId, ItemKind};
use serde_json::{Value, json};
use crate::commands::{CommandSpec, NamedKeys, always, bad, bool_p, f64_p, item_p, str_p};
use crate::{Result, Session};
const CMD: &str = "clip.sourceSettings";
/// The parameters that change settings (any of them, other than null or `reset: false`, makes
/// the command an edit).
const SETTING_KEYS: [&str; 8] = ["whiteBalance", "temperature", "tint", "exposure", "highlights", "demosaic", "output", "reset"];
pub(crate) fn commands() -> Vec<CommandSpec> {
vec![
CommandSpec {
id: CMD,
label: "Source Settings…",
menu: &["Clip"],
shortcut: None,
params: r#"{"items":[id]?,"item":id?,"whiteBalance":"asShot"|"custom"?,"temperature":kelvin?,"tint":n?,"exposure":stops?,"highlights":"clip"?,"demosaic":"fast"|"high"?,"output":"sceneLinearRec709"?,"reset":bool?}"#,
enabled: has_footage,
run: source_settings,
journal: true,
named: NamedKeys::NONE,
},
CommandSpec {
id: "media.rawInfo",
label: "Camera Raw Info",
menu: &[],
shortcut: None,
params: r#"{"item":id}"#,
enabled: always,
run: raw_info,
journal: false,
named: NamedKeys::NONE,
},
]
}
/// Whether a media item is camera raw footage FilmCraft develops.
fn is_raw(s: &Session, id: ItemId) -> bool {
s.project.item(id).and_then(|i| i.as_media()).is_some_and(|m| filmcraft_media::still::dng::is_camera_raw(&m.info))
}
/// The media items addressed by `p` (`items`, `item`, else the Project panel selection, else the
/// selected timeline clips), subclips resolved to their media, without duplicates.
fn footage(s: &Session, p: &Value) -> Vec<ItemId> {
let mut v = Vec::new();
for i in crate::project_tools::targets(s, p) {
if let Some((root, _, _)) = s.project.resolve_media(i)
&& !v.contains(&root)
{
v.push(root);
}
}
v
}
/// Enabled with footage selected; for footage that is not camera raw the dialog says why it has
/// no source settings.
fn has_footage(s: &Session) -> std::result::Result<(), String> {
if footage(s, &Value::Null).is_empty() { Err("select a clip".into()) } else { Ok(()) }
}
/// The settings as JSON (the command's parameter names).
pub fn settings_json(r: &RawSettings) -> Value {
let (wb, temperature, tint) = match r.white_balance {
WhiteBalance::AsShot => ("asShot", None, None),
WhiteBalance::Custom { temperature, tint } => ("custom", Some(temperature), Some(tint)),
};
json!({
"whiteBalance": wb,
"temperature": temperature,
"tint": tint,
"exposure": r.exposure,
"highlights": match r.highlights { Highlights::Clip => "clip", Highlights::Recover => "recover" },
"demosaic": match r.demosaic { DemosaicQuality::Fast => "fast", DemosaicQuality::High => "high" },
"output": match r.output { OutputSpace::SceneLinearRec709 => "sceneLinearRec709" },
})
}
/// A finite number parameter (None when absent; an error when present but not a number).
fn num(p: &Value, k: &str) -> Result<Option<f64>> {
match p.get(k) {
None | Some(Value::Null) => Ok(None),
Some(_) => f64_p(p, k).filter(|v| v.is_finite()).map(Some).ok_or_else(|| bad(CMD, format!("`{k}` must be a number"))),
}
}
/// A string parameter (None when absent; an error when present but not a string).
fn word<'a>(p: &'a Value, k: &str) -> Result<Option<&'a str>> {
match p.get(k) {
None | Some(Value::Null) => Ok(None),
Some(Value::String(s)) => Ok(Some(s)),
Some(_) => Err(bad(CMD, format!("`{k}` must be a string"))),
}
}
/// `cur` with the parameters of `p` applied.
fn apply(cur: RawSettings, p: &Value) -> Result<RawSettings> {
let mut r = cur;
for k in ["whiteBalance", "highlights", "demosaic", "output"] {
word(p, k)?;
}
if p.get("reset").is_some_and(|v| !v.is_boolean()) {
return Err(bad(CMD, "`reset` must be true or false"));
}
let (temperature, tint) = (num(p, "temperature")?, num(p, "tint")?);
match str_p(p, "whiteBalance") {
None => {}
Some("asShot") => {
if temperature.is_some() || tint.is_some() {
return Err(bad(CMD, "`temperature` / `tint` need `whiteBalance: \"custom\"` (or no `whiteBalance`)"));
}
r.white_balance = WhiteBalance::AsShot;
}
Some("custom") => {
if temperature.is_none() && !matches!(r.white_balance, WhiteBalance::Custom { .. }) {
return Err(bad(CMD, "a custom white balance needs `temperature` (kelvin)"));
}
}
Some(o) => return Err(bad(CMD, format!("whiteBalance must be \"asShot\" or \"custom\", got `{o}`"))),
}
if temperature.is_some() || tint.is_some() {
let (t0, n0) = match r.white_balance {
WhiteBalance::Custom { temperature, tint } => (Some(temperature), tint),
WhiteBalance::AsShot => (None, 0.0),
};
let t = temperature.or(t0).ok_or_else(|| bad(CMD, "a custom white balance needs `temperature` (kelvin)"))?;
r.white_balance = WhiteBalance::Custom { temperature: t, tint: tint.unwrap_or(n0) };
}
if let Some(e) = num(p, "exposure")? {
r.exposure = e;
}
match str_p(p, "highlights") {
None => {}
Some("clip") => r.highlights = Highlights::Clip,
// the decoder accepts Recover but does not reconstruct highlights yet: refuse it rather
// than store a setting that changes nothing
Some("recover") => return Err(bad(CMD, "highlight recovery is not available yet (highlights are clipped)")),
Some(o) => return Err(bad(CMD, format!("highlights must be \"clip\", got `{o}`"))),
}
match str_p(p, "demosaic") {
None => {}
Some("fast") => r.demosaic = DemosaicQuality::Fast,
Some("high") => r.demosaic = DemosaicQuality::High,
Some(o) => return Err(bad(CMD, format!("demosaic must be \"fast\" or \"high\", got `{o}`"))),
}
match str_p(p, "output") {
None | Some("sceneLinearRec709") => {}
Some(o) => return Err(bad(CMD, format!("output colour space must be \"sceneLinearRec709\" (scene-linear Rec. 709), got `{o}`"))),
}
r.validate().map_err(|e| bad(CMD, e))?;
Ok(r)
}
fn source_settings(s: &mut Session, p: &Value) -> Result<Value> {
if !p.is_object() && !p.is_null() {
return Err(bad(CMD, "parameters must be an object"));
}
let all = footage(s, p);
// null is unset for every key, `reset: false` too; any other value (also `false` for a number or
// a string) is set, so `apply` rejects it with a type error
let is_set = |k: &&str| p.get(*k).is_some_and(|v| !v.is_null() && !(*k == "reset" && *v == Value::Bool(false)));
if !SETTING_KEYS.iter().any(is_set) {
// describe the first item
let first = all.first().copied().ok_or_else(|| bad(CMD, "select a clip"))?;
return describe(s, first);
}
if all.is_empty() {
return Err(bad(CMD, "select a clip"));
}
let items: Vec<ItemId> = all.into_iter().filter(|i| is_raw(s, *i)).collect();
if items.is_empty() {
return Err(bad(CMD, "no camera raw footage selected: source settings apply to DNG stills, CinemaDNG folders and CinemaDNG MXF"));
}
let reset = bool_p(p, "reset").unwrap_or(false);
// check every item's result before changing any
let mut new = Vec::with_capacity(items.len());
for i in &items {
let cur = s.project.item(*i).and_then(|it| it.as_media()).and_then(|m| m.interpret.raw).unwrap_or_default();
let r = if reset { RawSettings::default() } else { apply(cur, p)? };
new.push((*i, (r != RawSettings::default()).then_some(r), r != cur));
}
// nothing changes: no empty undo step
if new.iter().any(|(_, _, changed)| *changed) {
s.edit("Source Settings", |pr, _| {
for (i, r, changed) in &new {
if let (true, Some(ItemKind::Media(m))) = (*changed, pr.item_mut(*i).map(|it| &mut it.kind)) {
m.interpret.raw = *r;
}
}
Ok(())
})?;
}
let first = new.first().and_then(|(_, r, _)| *r).unwrap_or_default();
Ok(json!({"items": items.iter().map(|i| i.0).collect::<Vec<_>>(), "settings": settings_json(&first)}))
}
fn raw_info(s: &mut Session, p: &Value) -> Result<Value> {
let id = item_p(p, "item").ok_or_else(|| bad("media.rawInfo", "need `item`"))?;
let Some((root, _, _)) = s.project.resolve_media(id) else { return Err(bad("media.rawInfo", "not a media item")) };
describe(s, root)
}
/// The Source Settings of media item `id`: its codec and container, whether it is camera raw, and
/// for camera raw its settings, the file's as-shot white balance and the value ranges.
fn describe(s: &Session, id: ItemId) -> Result<Value> {
let Some(m) = s.project.item(id).and_then(|i| i.as_media()) else { return Err(bad(CMD, "not a media item")) };
let codec = m.info.video.as_ref().map(|v| v.codec.clone()).or_else(|| m.info.audio().map(|a| a.codec.clone())).unwrap_or_default();
if !filmcraft_media::still::dng::is_camera_raw(&m.info) {
let what = if codec.is_empty() { "This clip".to_string() } else { codec.to_uppercase() };
return Ok(json!({
"item": id.0,
"raw": false,
"codec": codec,
"container": m.info.container,
"settings": null,
"message": format!("{what} has no source settings in FilmCraft. Source settings apply to camera raw formats; FilmCraft develops DNG and CinemaDNG (folders of DNG frames and MXF). R3D, ARRIRAW, BRAW and ProRes RAW are not decoded."),
}));
}
let pixel_format = m.info.video.as_ref().map(|v| v.pixel_format.clone()).unwrap_or_default();
let settings = m.interpret.raw.unwrap_or_default();
// the as-shot white comes from the file (None when it is offline or has no colour calibration)
let as_shot = s.media.full_res_source(&s.project, id, &*s.services).and_then(|src| src.raw_info()).and_then(|r| r.as_shot);
Ok(json!({
"item": id.0,
"raw": true,
"codec": codec,
"container": m.info.container,
"pixelFormat": pixel_format,
"settings": settings_json(&settings),
"asShot": as_shot.map(|(t, n)| json!({"temperature": t, "tint": n})),
"ranges": {
"temperature": [raw::TEMPERATURE_RANGE.0, raw::TEMPERATURE_RANGE.1],
"tint": [raw::TINT_RANGE.0, raw::TINT_RANGE.1],
"exposure": [-raw::MAX_EXPOSURE, raw::MAX_EXPOSURE],
},
}))
}
+527
View File
@@ -0,0 +1,527 @@
//! Camera raw Source Settings (`clip.sourceSettings`, `media.rawInfo`): CinemaDNG folders, DNG
//! stills and CinemaDNG in MXF developed with the item's settings, one undo step, saved in the
//! project; hostile parameters change nothing.
use std::path::Path;
use filmcraft_media::FrameRequest;
use filmcraft_media::raw::{DemosaicQuality, RawSettings, WhiteBalance};
use filmcraft_project::ItemId;
use filmcraft_time::FrameRate;
use serde_json::{Value, json};
use crate::Session;
use crate::media_test_util::tmp_dir;
const W: usize = 24;
const H: usize = 16;
/// The sRGB matrix from CIE XYZ (D65) to linear Rec. 709 (IEC 61966-2-1): as a DNG ColorMatrix
/// with calibration illuminant D65 it makes the camera's values linear Rec. 709.
const XYZ_TO_709: [f64; 9] = [3.2406, -1.5372, -0.4986, -0.9689, 1.8758, 0.0415, 0.0557, -0.2040, 1.0570];
/// A CinemaDNG frame: 24 × 16 RGGB, 12-bit lossless JPEG, a flat neutral grey at `level` shot
/// under D65 (as-shot neutral 1, 1, 1), 24 fps.
fn frame(level: f64) -> Vec<u8> {
use filmcraft_dng::tiff::tags;
use filmcraft_dng::writer::{Compression, Options, Value, write};
let px: Vec<u16> = (0..W * H).map(|_| (level * 4095.0).round() as u16).collect();
let o = Options {
width: W,
height: H,
bits: 12,
compression: Compression::LosslessJpeg { predictor: 1, components: 2, restart_lines: 0, pt: 0 },
raw_tags: vec![(tags::WHITE_LEVEL, Value::Short(vec![4095]))],
main_tags: vec![
(tags::COLOR_MATRIX_1, Value::srationals(&XYZ_TO_709)),
(tags::CALIBRATION_ILLUMINANT_1, Value::Short(vec![21])),
(tags::AS_SHOT_NEUTRAL, Value::rationals(&[1.0, 1.0, 1.0])),
(tags::FRAME_RATE, Value::SRational(vec![(24, 1)])),
],
..Default::default()
};
write(&px, &o)
}
fn level(i: usize) -> f64 {
0.1 + 0.15 * i as f64
}
fn demo() -> Session {
let mut s = Session::default();
s.execute("file.openDemoProject", json!({})).unwrap();
s
}
fn item_of(r: &Value) -> ItemId {
ItemId(r["items"][0].as_u64().unwrap_or_else(|| panic!("{r}")))
}
/// Import a three-frame CinemaDNG folder.
fn import_folder(s: &mut Session, dir: &Path) -> ItemId {
let paths: Vec<String> = (0..3)
.map(|i| {
let p = dir.join(format!("A001_C003_{i:06}.dng"));
std::fs::write(&p, frame(level(i))).unwrap();
p.to_string_lossy().to_string()
})
.collect();
item_of(&s.execute("file.import", json!({"paths": [paths[0]], "imageSequence": true})).unwrap())
}
/// The (red, green, blue) at the centre of frame `i`, through the media pool as the renderer
/// reads it.
fn rgb(s: &Session, item: ItemId, i: i64) -> [f32; 3] {
let src = s.media.source_for(&s.project, item, &*s.services).unwrap();
let f = src.video_frame(FrameRequest::full(FrameRate::FPS_24.tick_of(i))).unwrap();
let filmcraft_frame::PixelData::RgbaF32(px) = &f.data else { panic!("linear float frames") };
let at = ((H / 2) * f.width as usize + W / 2) * 4;
[px[at], px[at + 1], px[at + 2]]
}
fn raw_of(s: &Session, item: ItemId) -> Option<RawSettings> {
s.project.item(item).unwrap().as_media().unwrap().interpret.raw
}
#[test]
fn exposure_changes_every_frame_and_is_one_undo_step() {
let dir = tmp_dir("raw-exposure");
let mut s = demo();
let id = import_folder(&mut s, &dir);
let before: Vec<[f32; 3]> = (0..3).map(|i| rgb(&s, id, i)).collect();
for (i, c) in before.iter().enumerate() {
assert!((c[0] - level(i) as f32).abs() < 2e-3 && (c[2] - level(i) as f32).abs() < 2e-3, "frame {i}: {c:?}");
}
let undo_depth = s.history.undo.len();
let r = s.execute("clip.sourceSettings", json!({"items": [id.0], "exposure": 1.0})).unwrap();
assert_eq!(r["settings"]["exposure"], 1.0);
assert_eq!(s.history.undo.len(), undo_depth + 1);
assert_eq!(s.history.undo.last().unwrap().0, "Source Settings");
assert_eq!(raw_of(&s, id).unwrap().exposure, 1.0);
for (i, c) in before.iter().enumerate() {
let now = rgb(&s, id, i as i64);
for k in 0..3 {
assert!((now[k] - 2.0 * c[k]).abs() < 3e-3, "frame {i} channel {k}: {} vs {}", now[k], c[k]);
}
}
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(raw_of(&s, id), None);
assert!((rgb(&s, id, 2)[1] - before[2][1]).abs() < 1e-6, "undo develops as the file says again");
s.execute("edit.redo", json!({})).unwrap();
assert!((rgb(&s, id, 2)[1] - 2.0 * before[2][1]).abs() < 3e-3);
// reset goes back to the file's development and stores nothing
s.execute("clip.sourceSettings", json!({"items": [id.0], "reset": true})).unwrap();
assert_eq!(raw_of(&s, id), None);
assert!((rgb(&s, id, 1)[1] - before[1][1]).abs() < 1e-6);
}
#[test]
fn an_edit_that_changes_nothing_records_no_undo_step() {
let dir = tmp_dir("raw-noop");
let mut s = demo();
let id = import_folder(&mut s, &dir);
let depth = s.history.undo.len();
// null and `reset: false` are unset: the command only describes the item
let r = s.execute("clip.sourceSettings", json!({"items": [id.0], "whiteBalance": null, "reset": false})).unwrap();
assert_eq!(r["raw"], true);
// the settings the item already has, and a reset of an item without settings
s.execute("clip.sourceSettings", json!({"items": [id.0], "exposure": 0.0, "demosaic": "high"})).unwrap();
s.execute("clip.sourceSettings", json!({"items": [id.0], "reset": true})).unwrap();
assert_eq!(s.history.undo.len(), depth);
assert_eq!(raw_of(&s, id), None);
// a real change is still one step, and repeating it is not another
s.execute("clip.sourceSettings", json!({"items": [id.0], "exposure": 1.0})).unwrap();
s.execute("clip.sourceSettings", json!({"items": [id.0], "exposure": 1.0})).unwrap();
assert_eq!(s.history.undo.len(), depth + 1);
}
#[test]
fn false_is_not_unset_for_value_parameters() {
let dir = tmp_dir("raw-false");
let mut s = demo();
let id = import_folder(&mut s, &dir);
let depth = s.history.undo.len();
for k in ["exposure", "temperature", "tint", "whiteBalance", "highlights", "demosaic", "output"] {
assert!(s.execute("clip.sourceSettings", json!({"items": [id.0], k: false})).is_err(), "{k}: false");
}
assert_eq!(s.history.undo.len(), depth);
}
#[test]
fn an_item_that_already_has_the_settings_is_left_alone_in_a_multi_item_edit() {
let dir = tmp_dir("raw-multi");
let mut s = demo();
let a = import_folder(&mut s, &dir);
let dir2 = tmp_dir("raw-multi2");
let b = import_folder(&mut s, &dir2);
s.execute("clip.sourceSettings", json!({"items": [a.0], "exposure": 1.0})).unwrap();
let depth = s.history.undo.len();
// `a` already has this exposure, `b` does not: one step, and only `b` changes
s.execute("clip.sourceSettings", json!({"items": [a.0, b.0], "exposure": 1.0})).unwrap();
assert_eq!(s.history.undo.len(), depth + 1);
assert_eq!(raw_of(&s, a).unwrap().exposure, 1.0);
assert_eq!(raw_of(&s, b).unwrap().exposure, 1.0);
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(raw_of(&s, a).unwrap().exposure, 1.0);
assert_eq!(raw_of(&s, b), None);
}
#[test]
fn white_balance_from_the_as_shot_temperature() {
let dir = tmp_dir("raw-wb");
let mut s = demo();
let id = import_folder(&mut s, &dir);
let info = s.execute("media.rawInfo", json!({"item": id.0})).unwrap();
assert_eq!(info["raw"], true);
assert_eq!(info["settings"]["whiteBalance"], "asShot");
// shot under D65: about 6500 K; D65 is slightly green of the Planckian locus (Δuv +0.003), so
// the as-shot tint compensates with magenta (positive tint = a more magenta picture)
let t = info["asShot"]["temperature"].as_f64().unwrap();
let tint = info["asShot"]["tint"].as_f64().unwrap();
assert!((t - 6504.0).abs() < 60.0 && (7.0..12.0).contains(&tint), "{t} K, tint {tint}");
// the dialog's description is the same
let d = s.execute("clip.sourceSettings", json!({"item": id.0})).unwrap();
assert_eq!((d["raw"].clone(), d["asShot"].clone(), d["codec"].clone()), (json!(true), info["asShot"].clone(), json!("DNG sequence")));
assert_eq!(d["pixelFormat"], "Bayer 12-bit raw (lossless JPEG)");
let grey = rgb(&s, id, 1);
// the as-shot values as a custom white balance develop the same picture
s.execute("clip.sourceSettings", json!({"items": [id.0], "temperature": t, "tint": tint})).unwrap();
assert!(matches!(raw_of(&s, id).unwrap().white_balance, WhiteBalance::Custom { .. }));
let same = rgb(&s, id, 1);
for k in 0..3 {
assert!((same[k] - grey[k]).abs() < 0.01 * grey[k].max(0.01), "channel {k}: {same:?} vs {grey:?}");
}
// a tungsten white balance on daylight footage: the grey turns blue
s.execute("clip.sourceSettings", json!({"items": [id.0], "whiteBalance": "custom", "temperature": 3200})).unwrap();
let warm = rgb(&s, id, 1);
assert!(warm[2] > 1.3 * warm[0], "3200 K on D65 footage: {warm:?}");
// tint towards magenta lowers green
s.execute("clip.sourceSettings", json!({"items": [id.0], "temperature": t, "tint": 60})).unwrap();
let magenta = rgb(&s, id, 1);
assert!(magenta[1] < 0.95 * magenta[0] && magenta[1] < 0.95 * magenta[2], "{magenta:?}");
// back to the camera's
s.execute("clip.sourceSettings", json!({"items": [id.0], "whiteBalance": "asShot"})).unwrap();
assert_eq!(raw_of(&s, id), None);
let back = rgb(&s, id, 1);
for k in 0..3 {
assert!((back[k] - grey[k]).abs() < 1e-6);
}
}
#[test]
fn demosaic_quality_and_reduced_resolution_requests() {
let dir = tmp_dir("raw-demosaic");
let mut s = demo();
let id = import_folder(&mut s, &dir);
let high = rgb(&s, id, 0);
s.execute("clip.sourceSettings", json!({"items": [id.0], "demosaic": "fast"})).unwrap();
assert_eq!(raw_of(&s, id).unwrap().demosaic, DemosaicQuality::Fast);
let fast = rgb(&s, id, 0);
for k in 0..3 {
assert!((fast[k] - high[k]).abs() < 2e-3, "a flat field is the same with either demosaic");
}
// half-resolution playback asks the source for a smaller picture; it is never smaller than asked
let src = s.media.source_for(&s.project, id, &*s.services).unwrap();
let half = src.video_frame(FrameRequest { time: filmcraft_time::Tick::ZERO, scale: 0.5 }).unwrap();
assert!((12..24).contains(&half.width) && (8..16).contains(&half.height), "{}x{}", half.width, half.height);
}
#[test]
fn settings_apply_to_dng_stills_and_cinemadng_mxf() {
let dir = tmp_dir("raw-still-mxf");
let mut s = demo();
// a single DNG is a still
let still = dir.join("still.dng");
std::fs::write(&still, frame(0.25)).unwrap();
let sid = item_of(&s.execute("file.import", json!({"paths": [still.to_string_lossy()]})).unwrap());
// CinemaDNG in MXF (CinemaDNG specification §7), written by our MXF writer
let rate = craft_media::mxf::Rational::new(24, 1);
let mut cfg = craft_media::mxf::WriterConfig::new(craft_media::mxf::Pattern::Op1a, rate, craft_media::mxf::PackageIds::from_seed("raw", "A001_C004"));
cfg.picture = Some(craft_media::mxf::PictureDesc::new(craft_media::mxf::PictureCoding::CinemaDng { linear_raw: false }, W as u32, H as u32));
let mut w = craft_media::mxf::MxfWriter::new(std::io::Cursor::new(Vec::new()), cfg).unwrap();
for i in 0..3 {
w.push_picture(&frame(level(i)), craft_media::mxf::FrameInfo::intra()).unwrap();
}
let mxf = dir.join("A001_C004.mxf");
std::fs::write(&mxf, w.finish().unwrap().into_inner()).unwrap();
let mid = item_of(&s.execute("file.import", json!({"paths": [mxf.to_string_lossy()]})).unwrap());
assert_eq!(s.project.item(mid).unwrap().as_media().unwrap().info.video.as_ref().unwrap().codec, "CinemaDNG");
let (s0, m0) = (rgb(&s, sid, 0), rgb(&s, mid, 2));
assert!((m0[1] - level(2) as f32).abs() < 2e-3, "{m0:?}");
// both in one command: one undo step
s.execute("clip.sourceSettings", json!({"items": [sid.0, mid.0], "exposure": -1.0})).unwrap();
assert!((rgb(&s, sid, 0)[1] - 0.5 * s0[1]).abs() < 2e-3);
assert!((rgb(&s, mid, 2)[1] - 0.5 * m0[1]).abs() < 2e-3);
assert_eq!(s.execute("media.rawInfo", json!({"item": mid.0})).unwrap()["settings"]["exposure"], -1.0);
s.execute("edit.undo", json!({})).unwrap();
assert!((rgb(&s, sid, 0)[1] - s0[1]).abs() < 1e-6 && (rgb(&s, mid, 2)[1] - m0[1]).abs() < 1e-6);
}
#[test]
fn settings_are_saved_with_the_project() {
let dir = tmp_dir("raw-save");
let mut s = demo();
let id = import_folder(&mut s, &dir);
s.execute("clip.sourceSettings", json!({"items": [id.0], "exposure": 0.5, "temperature": 5000, "tint": -10, "demosaic": "fast"})).unwrap();
let want = raw_of(&s, id).unwrap();
assert_eq!(
want,
RawSettings {
white_balance: WhiteBalance::Custom { temperature: 5000.0, tint: -10.0 },
exposure: 0.5,
demosaic: DemosaicQuality::Fast,
..Default::default()
}
);
let bright = rgb(&s, id, 1);
let path = dir.join("raw.fcproj").to_string_lossy().to_string();
s.execute("file.saveAs", json!({"path": path})).unwrap();
let mut t = Session::default();
t.execute("file.open", json!({"path": path})).unwrap();
assert_eq!(raw_of(&t, id), Some(want));
let again = rgb(&t, id, 1);
for k in 0..3 {
assert!((again[k] - bright[k]).abs() < 1e-6);
}
}
#[test]
fn saving_current_and_legacy_projects_preserves_raw_settings_and_scripts() {
let dir = tmp_dir("raw-script-save");
let mut source = demo();
let media = import_folder(&mut source, &dir);
source.execute("clip.sourceSettings", json!({"items": [media.0], "exposure": 0.5, "temperature": 5000.5, "tint": -10.25, "demosaic": "fast"})).unwrap();
let script =
source.execute("script.importText", json!({"name": "Camera notes", "text": "Opening shot\nHold on the slate"})).unwrap()["item"].as_u64().unwrap();
let raw_params = json!({"item": media.0});
let script_params = json!({"item": script});
let settings = source.execute("media.rawInfo", raw_params.clone()).unwrap()["settings"].clone();
assert_eq!(settings["exposure"], 0.5);
let script_before = source.execute("script.inspect", script_params.clone()).unwrap();
for schema in [18, filmcraft_format::SCHEMA_VERSION] {
let path = dir.join(format!("raw-script-v{schema}.fcproj"));
source.execute("file.saveCopy", json!({"path": path})).unwrap();
if schema < filmcraft_format::SCHEMA_VERSION {
// An older schema-18 pin could already write Script items.
let mut document: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
document["schema_version"] = json!(schema);
std::fs::write(&path, serde_json::to_vec(&document).unwrap()).unwrap();
}
let mut session = Session::default();
let opened = session.execute("file.open", json!({"path": path})).unwrap();
assert_eq!(opened["schemaVersion"], schema);
session.execute("file.save", json!({})).unwrap();
let mut reopened = Session::default();
let opened = reopened.execute("file.open", json!({"path": path})).unwrap();
assert_eq!(opened["schemaVersion"], filmcraft_format::SCHEMA_VERSION);
assert_eq!(reopened.execute("media.rawInfo", raw_params.clone()).unwrap()["settings"], settings);
assert_eq!(reopened.execute("script.inspect", script_params.clone()).unwrap(), script_before);
}
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn hostile_parameters_change_nothing() {
let dir = tmp_dir("raw-hostile");
let mut s = demo();
let id = import_folder(&mut s, &dir);
s.execute("clip.sourceSettings", json!({"items": [id.0], "exposure": 0.25})).unwrap();
let project = s.project.clone();
let undo = s.history.undo.len();
let bad = [
json!({"items": [id.0], "exposure": 9.0}),
json!({"items": [id.0], "exposure": -1e308}),
json!({"items": [id.0], "exposure": "bright"}),
json!({"items": [id.0], "temperature": 100}),
json!({"items": [id.0], "temperature": 1e9}),
json!({"items": [id.0], "temperature": 5000, "tint": 151}),
json!({"items": [id.0], "tint": 10}),
json!({"items": [id.0], "whiteBalance": "custom"}),
json!({"items": [id.0], "whiteBalance": "asShot", "temperature": 5000}),
json!({"items": [id.0], "whiteBalance": "daylight"}),
json!({"items": [id.0], "highlights": "recover"}),
json!({"items": [id.0], "highlights": 3}),
json!({"items": [id.0], "demosaic": "ultra"}),
json!({"items": [id.0], "output": "rec2020"}),
json!({"items": [999_999], "exposure": 1.0}),
json!({"items": "all", "exposure": 1.0}),
json!({"items": [id.0], "reset": "yes"}),
json!([1, 2]),
];
for p in bad {
assert!(s.execute("clip.sourceSettings", p.clone()).is_err(), "{p} was accepted");
assert!(std::sync::Arc::ptr_eq(&project, &s.project) || *project == *s.project, "{p} changed the project");
assert_eq!(s.history.undo.len(), undo, "{p} added an undo step");
}
assert!(s.execute("media.rawInfo", json!({})).is_err());
assert!(s.execute("media.rawInfo", json!({"item": 999_999})).is_err());
}
#[test]
fn only_camera_raw_footage_has_source_settings() {
let mut s = demo();
// the demo's footage is generated, not camera raw: the dialog says why, settings are refused
let demo_item = s.project.items.values().find(|i| i.as_media().is_some()).unwrap().id;
let info = s.execute("media.rawInfo", json!({"item": demo_item.0})).unwrap();
assert_eq!((info["raw"].clone(), info["settings"].clone()), (json!(false), Value::Null));
assert!(info["message"].as_str().unwrap().contains("no source settings"), "{info}");
let undo = s.history.undo.len();
assert!(s.execute("clip.sourceSettings", json!({"items": [demo_item.0], "exposure": 1.0})).is_err());
assert_eq!(s.history.undo.len(), undo);
let c = crate::find_command("clip.sourceSettings").unwrap();
s.state.project_selection = vec![];
s.state.selection.clear();
assert!((c.enabled)(&s).is_err(), "nothing selected");
s.state.project_selection = vec![demo_item];
assert!((c.enabled)(&s).is_ok());
assert_eq!(c.menu, &["Clip"]);
// selected raw footage enables it, and the selection is the default target
let dir = tmp_dir("raw-enabled");
let id = import_folder(&mut s, &dir);
s.state.project_selection = vec![id];
assert!((c.enabled)(&s).is_ok());
s.execute("clip.sourceSettings", json!({"exposure": 0.5})).unwrap();
assert_eq!(raw_of(&s, id).unwrap().exposure, 0.5);
}
/// A three-frame CinemaDNG MXF whose frame `i` is a grey of `level(i) + lift`.
fn write_mxf(path: &Path, seed: &str, lift: f64) {
let rate = craft_media::mxf::Rational::new(24, 1);
let mut cfg = craft_media::mxf::WriterConfig::new(craft_media::mxf::Pattern::Op1a, rate, craft_media::mxf::PackageIds::from_seed("raw", seed));
cfg.picture = Some(craft_media::mxf::PictureDesc::new(craft_media::mxf::PictureCoding::CinemaDng { linear_raw: false }, W as u32, H as u32));
let mut w = craft_media::mxf::MxfWriter::new(std::io::Cursor::new(Vec::new()), cfg).unwrap();
for i in 0..3 {
w.push_picture(&frame(level(i) + lift), craft_media::mxf::FrameInfo::intra()).unwrap();
}
std::fs::write(path, w.finish().unwrap().into_inner()).unwrap();
}
fn centre(src: &filmcraft_media::SharedSource, i: i64) -> [f32; 3] {
let f = src.video_frame(FrameRequest::full(FrameRate::FPS_24.tick_of(i))).unwrap();
let filmcraft_frame::PixelData::RgbaF32(px) = &f.data else { panic!("linear float frames") };
let at = ((H / 2) * f.width as usize + W / 2) * 4;
[px[at], px[at + 1], px[at + 2]]
}
/// The frame as export and Render Previews read it: through a full-resolution provider with
/// sources of its own.
fn owned_rgb(s: &Session, item: ItemId, i: i64) -> [f32; 3] {
use filmcraft_render::SourceProvider;
let job = s.media.full_res_provider(s.project.clone(), s.services.clone()).own_sources();
let own = job.source(item).unwrap();
let shared = s.media.full_res_source(&s.project, item, &*s.services).unwrap();
assert!(!std::sync::Arc::ptr_eq(&own, &shared), "the job reads a copy of its own");
centre(&own, i)
}
fn full_res_rgb(s: &Session, item: ItemId, i: i64) -> [f32; 3] {
centre(&s.media.full_res_source(&s.project, item, &*s.services).unwrap(), i)
}
fn assert_cached_raw_development(s: &Session, id: ItemId, expected: f32) {
struct NoFileReads;
impl crate::Services for NoFileReads {
fn read_file(&self, path: &str) -> std::io::Result<Vec<u8>> {
panic!("the RAW clip reopened {path}");
}
fn write_file(&self, _path: &str, _data: &[u8]) -> std::io::Result<()> {
panic!("resolving a source must not write a file");
}
}
let source = s.media.full_res_source(&s.project, id, &NoFileReads).unwrap();
for channel in centre(&source, 0) {
assert!((channel - expected).abs() < 3e-3, "developed frame: {channel}, expected {expected}");
}
}
#[test]
fn refreshed_raw_clip_reuses_the_open_source_with_its_development_settings() {
let dir = tmp_dir("raw-refresh");
let path = dir.join("A001_C007.mxf");
write_mxf(&path, "A001_C007", 0.0);
let mut s = demo();
let id = item_of(&s.execute("file.import", json!({"paths": [path.to_string_lossy()]})).unwrap());
s.execute("clip.sourceSettings", json!({"items": [id.0], "exposure": 1.0})).unwrap();
assert_eq!(s.execute("media.refreshChanged", json!({})).unwrap()["refreshed"], json!([]));
std::thread::sleep(std::time::Duration::from_millis(30));
write_mxf(&path, "A001_C007", 0.1);
assert_eq!(s.execute("media.refreshChanged", json!({})).unwrap()["refreshed"], json!([id.0]));
assert_cached_raw_development(&s, id, (2.0 * (level(0) + 0.1)) as f32);
}
#[test]
fn relinked_raw_clip_reuses_the_open_source_with_its_development_settings() {
let dir = tmp_dir("raw-relink");
let old = dir.join("A001_C008.mxf");
let replacement = dir.join("A001_C009.mxf");
write_mxf(&old, "A001_C008", 0.0);
write_mxf(&replacement, "A001_C009", 0.2);
let mut s = demo();
let id = item_of(&s.execute("file.import", json!({"paths": [old.to_string_lossy()]})).unwrap());
s.execute("clip.sourceSettings", json!({"items": [id.0], "exposure": 1.0})).unwrap();
s.execute("media.relink", json!({"item": id.0, "path": replacement.to_string_lossy(), "force": true, "relinkOthers": false})).unwrap();
assert_cached_raw_development(&s, id, (2.0 * (level(0) + 0.2)) as f32);
}
fn same(a: [f32; 3], b: [f32; 3], what: &str) {
for k in 0..3 {
assert!((a[k] - b[k]).abs() < 1e-6, "{what}: channel {k}: {a:?} vs {b:?}");
}
}
#[test]
fn export_and_previews_develop_the_mxf_with_its_source_settings() {
let dir = tmp_dir("raw-owned");
let mut s = demo();
let mxf = dir.join("A001_C005.mxf");
write_mxf(&mxf, "A001_C005", 0.0);
let id = item_of(&s.execute("file.import", json!({"paths": [mxf.to_string_lossy()]})).unwrap());
let base = full_res_rgb(&s, id, 2);
same(owned_rgb(&s, id, 2), base, "as shot");
s.execute("clip.sourceSettings", json!({"items": [id.0], "exposure": 1.0})).unwrap();
let bright = full_res_rgb(&s, id, 2);
assert!((bright[1] - 2.0 * base[1]).abs() < 3e-3, "{bright:?} vs {base:?}");
same(owned_rgb(&s, id, 2), bright, "exposure +1");
s.execute("edit.undo", json!({})).unwrap();
same(owned_rgb(&s, id, 2), base, "undo");
s.execute("edit.redo", json!({})).unwrap();
same(owned_rgb(&s, id, 2), bright, "redo");
s.execute("clip.sourceSettings", json!({"items": [id.0], "reset": true})).unwrap();
same(owned_rgb(&s, id, 2), base, "reset");
s.execute("clip.sourceSettings", json!({"items": [id.0], "whiteBalance": "custom", "temperature": 3200})).unwrap();
let warm = owned_rgb(&s, id, 1);
assert!(warm[2] > 1.3 * warm[0], "3200 K on D65 footage: {warm:?}");
same(warm, full_res_rgb(&s, id, 1), "custom white balance");
}
#[test]
fn a_proxy_does_not_stand_in_for_camera_raw_footage() {
let dir = tmp_dir("raw-proxy");
let mut s = demo();
let mxf = dir.join("A001_C006.mxf");
write_mxf(&mxf, "A001_C006", 0.0);
let proxy = dir.join("A001_C006_proxy.mxf");
write_mxf(&proxy, "A001_C006_proxy", 0.4);
let id = item_of(&s.execute("file.import", json!({"paths": [mxf.to_string_lossy()]})).unwrap());
let base = rgb(&s, id, 2);
crate::proxies::attach(&mut s, &[(id, proxy.to_string_lossy().to_string())], true).unwrap();
s.media.set_use_proxies(true);
same(rgb(&s, id, 2), base, "proxies on");
s.execute("clip.sourceSettings", json!({"items": [id.0], "exposure": 1.0})).unwrap();
let bright = rgb(&s, id, 2);
assert!((bright[1] - 2.0 * base[1]).abs() < 3e-3, "{bright:?} vs {base:?}");
s.execute("clip.sourceSettings", json!({"items": [id.0], "whiteBalance": "custom", "temperature": 3200})).unwrap();
let warm = rgb(&s, id, 2);
assert!(warm[2] > 1.3 * warm[0], "3200 K on D65 footage: {warm:?}");
s.execute("edit.undo", json!({})).unwrap();
s.execute("edit.undo", json!({})).unwrap();
same(rgb(&s, id, 2), base, "undo");
}
+2 -1
View File
@@ -398,7 +398,8 @@ fn apply(s: &mut Session, plans: Vec<Plan>, align_timecode: bool, confirmed_item
s.media.allow(&p.cand.path);
}
for (item, path, src) in sources {
s.media.insert_file(item, &path, src);
let raw = s.project.item(item).and_then(|it| it.as_media()).and_then(|clip| clip.interpret.raw);
s.media.insert_reopened_file(item, &path, src, raw);
}
let gone: Vec<ItemId> = plans.iter().map(|p| p.item).collect();
s.offline.missing.retain(|i| !gone.contains(i));
+17 -4
View File
@@ -15,14 +15,27 @@ use crate::{Result, Session};
pub fn scope_signal(s: &Session, t: Tick, scale: f32, hdr: bool) -> Option<Signal> {
let seq = s.state.active_sequence?;
let provider = s.media.provider(s.project.clone(), s.services.clone());
Some(scope_signal_of(&s.project, seq, &provider, t, scale, hdr))
}
/// [`scope_signal`] of sequence `seq` with its own source provider, for a caller that renders
/// away from the session (the UI's scope worker thread).
pub fn scope_signal_of(
project: &filmcraft_project::Project,
seq: filmcraft_project::ItemId,
provider: &dyn filmcraft_render::SourceProvider,
t: Tick,
scale: f32,
hdr: bool,
) -> Signal {
if hdr {
let opts = filmcraft_render::RenderOptions { scale, working_output: true, ..Default::default() };
let img = filmcraft_render::render_sequence(&s.project, seq, t, opts, &provider);
return Some(Signal::from_rgba_f32_with(img.w, img.h, &img.px, scopes::MAX_W, scopes::MAX_H, scopes::linear_to_pq));
let img = filmcraft_render::render_sequence(project, seq, t, opts, provider);
return Signal::from_rgba_f32_with(img.w, img.h, &img.px, scopes::MAX_W, scopes::MAX_H, scopes::linear_to_pq);
}
let opts = filmcraft_render::RenderOptions { scale, captions: true, ..Default::default() };
let img = filmcraft_render::render_sequence(&s.project, seq, t, opts, &provider);
Some(Signal::from_rgba8(img.w, img.h, &img.over_black_rgba8()))
let img = filmcraft_render::render_sequence(project, seq, t, opts, provider);
Signal::from_rgba8(img.w, img.h, &img.over_black_rgba8())
}
fn levels_json(w: &scopes::Waveform, columns: usize) -> Value {
+123 -24
View File
@@ -3,8 +3,8 @@
use std::sync::Arc;
use filmcraft_project::{
BinId, ItemId, ItemKind, Label, MediaIdentity, MediaRef, Project, ScriptColor, ScriptDocument, ScriptLine, ScriptLineColor, ScriptLineId, ScriptMark,
ScriptMarkId, ScriptSlate, ScriptSlateId, ScriptTake, ScriptTakeId,
BinId, ItemId, ItemKind, Label, MediaIdentity, MediaRef, Project, ScriptColor, ScriptDocument, ScriptElement, ScriptLine, ScriptLineColor, ScriptLineId,
ScriptMark, ScriptMarkId, ScriptSlate, ScriptSlateId, ScriptTake, ScriptTakeId,
};
use filmcraft_time::Tick;
use serde::{Deserialize, Serialize};
@@ -65,8 +65,10 @@ fn create(s: &mut Session, p: &Value, import: bool) -> Result<Value> {
ScriptDocument::from_text(text(p, "text", cmd, ScriptDocument::MAX_TEXT_BYTES)?).map_err(|e| bad(cmd, e))?
} else {
let mut doc = ScriptDocument::new();
let id = ScriptLineId(doc.alloc_id().map_err(|e| bad(cmd, e))?);
doc.lines.push(ScriptLine { id, text: String::new(), scene: None, page: None });
for _ in 0..=ScriptDocument::LEADING_SETUP_ROWS {
let id = ScriptLineId(doc.alloc_id().map_err(|e| bad(cmd, e))?);
doc.lines.push(ScriptLine { id, text: String::new(), element: None, scene: None, page: None });
}
doc
};
let count = doc.lines.len();
@@ -249,6 +251,7 @@ fn paste_text(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(cmd, "pasted text exceeds the 50,000-line limit"));
}
let mut created = Vec::with_capacity(count);
let mut element = original.and_then(|_| draft.lines[insert_at].element);
for (index, row) in rows.split('\n').enumerate() {
if row.len() > ScriptDocument::MAX_LINE_BYTES {
return Err(bad(cmd, "a pasted script line exceeds the 16 KiB limit"));
@@ -260,8 +263,15 @@ fn paste_text(s: &mut Session, p: &Value) -> Result<Value> {
} else {
ScriptLineId(draft.alloc_id().map_err(|e| bad(cmd, e))?)
};
let old = (index == 0).then(|| original.and_then(|id| draft.lines.iter().find(|line| line.id == id))).flatten();
created.push(ScriptLine { id, text: row.to_owned(), scene: old.and_then(|line| line.scene.clone()), page: old.and_then(|line| line.page.clone()) });
let old = original.filter(|_| index == 0).map(|_| &draft.lines[insert_at]);
created.push(ScriptLine {
id,
text: row.to_owned(),
element,
scene: old.and_then(|line| line.scene.clone()),
page: old.and_then(|line| line.page.clone()),
});
element = element.map(ScriptElement::following);
}
let first = created.first().ok_or_else(|| bad(cmd, "there is no text to paste"))?.id;
let last = created.last().ok_or_else(|| bad(cmd, "there is no text to paste"))?;
@@ -330,8 +340,10 @@ fn split_line(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(cmd, "script text would exceed the 4 MiB limit"));
}
let created = ScriptLineId(doc.alloc_id().map_err(|e| bad(cmd, e))?);
let role = doc.lines[index].element;
let element = if after.is_empty() { role.map(ScriptElement::following) } else { role };
doc.lines[index].text = before.to_owned();
doc.lines.insert(index + 1, ScriptLine { id: created, text: after.to_owned(), scene: None, page: None });
doc.lines.insert(index + 1, ScriptLine { id: created, text: after.to_owned(), element, scene: None, page: None });
for take in doc.slates.iter_mut().flat_map(|slate| &mut slate.takes) {
if take.end_line == line {
take.end_line = created;
@@ -371,6 +383,9 @@ fn merge_with_previous(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(cmd, "script text would exceed the 4 MiB limit"));
}
let previous = prior.id;
if prior.text.is_empty() {
doc.lines[index - 1].element = doc.lines[index].element;
}
doc.lines[index - 1].text = merged.clone();
// delete_line removes the old row's marks and keeps marks already on
// the preceding row, while adjusting candle endpoints atomically.
@@ -438,15 +453,32 @@ fn move_take(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "script.moveTake";
let item = item(p, cmd)?;
let take = ScriptTakeId(id(p, "take", cmd)?);
let direction = p.get("direction").and_then(Value::as_i64).filter(|value| matches!(value, -1 | 1)).ok_or_else(|| bad(cmd, "direction must be -1 or 1"))?;
let index = s.edit("Reorder Script Candle", |project, _| {
let doc = script_mut(project, item, cmd)?;
let slate =
doc.slates.iter_mut().find(|slate| slate.takes.iter().any(|candidate| candidate.id == take)).ok_or_else(|| bad(cmd, "take does not exist"))?;
let index = slate.takes.iter().position(|candidate| candidate.id == take).ok_or_else(|| bad(cmd, "take does not exist"))?;
let next =
index.checked_add_signed(direction as isize).filter(|index| *index < slate.takes.len()).ok_or_else(|| bad(cmd, "take is already at that edge"))?;
slate.takes.swap(index, next);
let (slate, index) = doc
.slates
.iter_mut()
.find_map(|slate| {
let index = slate.takes.iter().position(|candidate| candidate.id == take)?;
Some((slate, index))
})
.ok_or_else(|| bad(cmd, "take does not exist"))?;
let next = match (p.get("toTake"), p.get("direction")) {
(Some(_), None) => {
let target = ScriptTakeId(id(p, "toTake", cmd)?);
slate.takes.iter().position(|candidate| candidate.id == target).ok_or_else(|| bad(cmd, "target must be in the same setup"))?
}
(None, Some(direction)) => {
let direction = direction.as_i64().filter(|n| matches!(n, -1 | 1)).ok_or_else(|| bad(cmd, "direction must be -1 or 1"))?;
index
.checked_add_signed(direction as isize)
.filter(|index| *index < slate.takes.len())
.ok_or_else(|| bad(cmd, "take is already at that edge"))?
}
_ => return Err(bad(cmd, "provide either toTake or direction")),
};
let moved = slate.takes.remove(index);
slate.takes.insert(next, moved);
Ok(next)
})?;
Ok(json!({"index":index}))
@@ -465,6 +497,19 @@ fn set_thumbnail_time(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"time":time}))
}
fn set_tree_outline_color(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "script.setTreeOutlineColor";
let item = item(p, cmd)?;
let id = ScriptSlateId(id(p, "slate", cmd)?);
let color = p.get("color").and_then(Value::as_str).and_then(ScriptColor::from_name).ok_or_else(|| bad(cmd, "color must be a known script color"))?;
s.edit("Set Tree Outline Color", |project, _| {
let slate = script_mut(project, item, cmd)?.slates.iter_mut().find(|slate| slate.id == id).ok_or_else(|| bad(cmd, "setup does not exist"))?;
slate.outline_color = color;
Ok(())
})?;
Ok(Value::Null)
}
fn move_thumbnail(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "script.moveThumbnail";
let item = item(p, cmd)?;
@@ -508,7 +553,8 @@ fn insert_line(s: &mut Session, p: &Value) -> Result<Value> {
None => 0,
};
let created = ScriptLineId(doc.alloc_id().map_err(|e| bad(cmd, e))?);
doc.lines.insert(index, ScriptLine { id: created, text: value, scene: None, page: None });
let element = index.checked_sub(1).and_then(|i| doc.lines[i].element).map(ScriptElement::following);
doc.lines.insert(index, ScriptLine { id: created, text: value, element, scene: None, page: None });
Ok(created)
})?;
Ok(json!({"line":created.0}))
@@ -600,7 +646,7 @@ fn add_slate(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(cmd, "script already has the maximum number of slates"));
}
let slate = ScriptSlateId(doc.alloc_id().map_err(|e| bad(cmd, e))?);
doc.slates.push(ScriptSlate { id: slate, name, thumbnail_line: None, thumbnail_x: None, takes: Vec::new() });
doc.slates.push(ScriptSlate { id: slate, outline_color: ScriptColor::Default, name, thumbnail_line: None, thumbnail_x: None, takes: Vec::new() });
Ok(slate)
})?;
Ok(json!({"slate":slate.0}))
@@ -647,7 +693,14 @@ fn add_take(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(cmd, "script already has the maximum number of slates"));
}
let slate = ScriptSlateId(doc.alloc_id().map_err(|e| bad(cmd, e))?);
doc.slates.push(ScriptSlate { id: slate, name: source_name.clone(), thumbnail_line: None, thumbnail_x: x, takes: Vec::new() });
doc.slates.push(ScriptSlate {
id: slate,
outline_color: ScriptColor::Default,
name: source_name.clone(),
thumbnail_line: None,
thumbnail_x: x,
takes: Vec::new(),
});
slate
};
let take = ScriptTakeId(doc.alloc_id().map_err(|e| bad(cmd, e))?);
@@ -960,6 +1013,15 @@ fn move_mark(s: &mut Session, p: &Value) -> Result<Value> {
Ok(Value::Null)
}
/// The Source monitor clamps to the visible source span and snaps down to its frame grid.
fn open_script_cue(s: &mut Session, source: ItemId, at: Tick, focus: bool) -> Result<Value> {
let lead = Tick::from_seconds_f64(s.prefs.playback.lined_script_preroll_seconds);
let time = at.0.saturating_sub(lead.0);
s.execute("source.open", json!({"item":source.0,"focus":focus}))?;
s.execute("source.setPlayhead", json!({"time":time}))?;
Ok(json!({"item":source.0,"time":s.state.source_playhead.0}))
}
fn cue_mark(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "script.cueMark";
let doc = script(&s.project, item(p, cmd)?, cmd)?;
@@ -977,9 +1039,7 @@ fn cue_mark(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(cmd, "mark is outside the linked source's visible span after relink; review the footage or rebind the take"));
}
let focus = p.get("focus").and_then(Value::as_bool).unwrap_or(true);
s.execute("source.open", json!({"item":source.0,"focus":focus}))?;
s.execute("source.setPlayhead", json!({"time":at.0}))?;
Ok(json!({"item":source.0,"time":s.state.source_playhead.0}))
open_script_cue(s, source, at, focus)
}
/// Cue a take at a script row. Marks anchor the source time; rows between two marks use
@@ -1021,9 +1081,7 @@ fn cue_line(s: &mut Session, p: &Value) -> Result<Value> {
if at < view.start || at >= view.end {
return Err(bad(cmd, "cue is outside the linked source's visible span after relink; review the footage or rebind the take"));
}
s.execute("source.open", json!({"item":source.0}))?;
s.execute("source.setPlayhead", json!({"time":at.0}))?;
Ok(json!({"item":source.0,"time":s.state.source_playhead.0}))
open_script_cue(s, source, at, true)
}
pub fn commands() -> Vec<CommandSpec> {
@@ -1044,6 +1102,7 @@ pub fn commands() -> Vec<CommandSpec> {
spec("script.splitLine", "Split Script Line", r#"{"item":id,"line":id,"text":str,"at":number}"#, split_line, true),
spec("script.mergeWithPrevious", "Join Script Lines", r#"{"item":id,"line":id,"text":str}"#, merge_with_previous, true),
spec("script.shiftSlate", "Move Script Setup", r#"{"item":id,"slate":id,"delta":number,"x":number?}"#, shift_slate, true),
spec("script.setTreeOutlineColor", "Set Tree Outline Color", r#"{"item":id,"slate":id,"color":name}"#, set_tree_outline_color, true),
spec("script.moveThumbnail", "Move Script Thumbnail", r#"{"item":id,"slate":id,"line":id,"x":number?}"#, move_thumbnail, true),
spec("script.insertLine", "Insert Script Line", r#"{"item":id,"after":id?,"text":str}"#, insert_line, true),
spec("script.deleteLine", "Delete Script Line", r#"{"item":id,"line":id}"#, delete_line, true),
@@ -1052,7 +1111,7 @@ pub fn commands() -> Vec<CommandSpec> {
spec("script.deleteSlate", "Delete Script Setup", r#"{"item":id,"slate":id}"#, delete_slate, true),
spec("script.addTake", "Add Script Take", r#"{"item":id,"slate":id?,"source":id,"startLine":id,"endLine":id,"x":number?}"#, add_take, true),
spec("script.deleteTake", "Delete Script Take", r#"{"item":id,"take":id}"#, delete_take, true),
spec("script.moveTake", "Reorder Script Take", r#"{"item":id,"take":id,"direction":-1|1}"#, move_take, true),
spec("script.moveTake", "Reorder Script Take", r#"{"item":id,"take":id,"direction":-1|1?, "toTake":id?}"#, move_take, true),
spec("script.setThumbnailTime", "Set Script Thumbnail Frame", r#"{"item":id,"take":id,"time":ticks}"#, set_thumbnail_time, true),
spec("script.rebindTake", "Rebind Script Take", r#"{"item":id,"take":id,"source":id,"discardMarks":bool?,"allMatching":bool?}"#, rebind_take, true),
spec("script.setCoverage", "Set Script Take Coverage", r#"{"item":id,"take":id,"startLine":id,"endLine":id}"#, set_coverage, true),
@@ -1101,6 +1160,35 @@ mod tests {
)
}
#[test]
fn screenplay_elements_survive_save_and_section_copy_and_follow_edits() {
use ScriptElement::{Action, Character, Dialogue, Parenthetical, SceneHeading, Transition};
let mut s = Session::default();
let mut doc = ScriptDocument::from_text("INT. ROOM - DAY\nA door opens.\nUSER\n(quietly)\nCome in.\nCUT TO:").unwrap();
let roles = [SceneHeading, Action, Character, Parenthetical, Dialogue, Transition];
for (line, role) in doc.lines.iter_mut().zip(roles) {
line.element = Some(role);
}
doc.lines[0].scene = Some("12A".into());
doc.lines[4].page = Some("9B".into());
let cue = doc.lines[2].id.0;
let item = Arc::make_mut(&mut s.project).add_item("Scene", Label::Blue, ItemKind::Script(Arc::new(doc.clone())), None).0;
let reopened = filmcraft_format::decode(&filmcraft_format::encode(&s.project, false)).unwrap();
assert_eq!(reopened.project.item(ItemId(item)).unwrap().as_script().unwrap(), &doc);
let section = s.execute("script.copySection", json!({"item":item,"startLine":doc.lines[0].id,"endLine":doc.lines[5].id,"slates":[]})).unwrap();
s.execute("script.pasteSection", json!({"item":item,"section":section})).unwrap();
let copy = &s.project.item(ItemId(item)).unwrap().as_script().unwrap().lines[6..];
for (row, old) in copy.iter().zip(&doc.lines) {
assert_eq!((&row.element, &row.scene, &row.page), (&old.element, &old.scene, &old.page));
assert_ne!(row.id, old.id);
}
let result = s.execute("script.splitLine", json!({"item":item,"line":cue,"text":"USER","at":4})).unwrap();
s.execute("script.pasteText", json!({"item":item,"line":result["line"],"baseText":"","start":0,"end":0,"text":"One\nTwo"})).unwrap();
let edited = &s.project.item(ItemId(item)).unwrap().as_script().unwrap().lines;
assert_eq!(edited[2].element, Some(Character));
assert!(edited[3..5].iter().all(|row| row.element == Some(Dialogue) && row.page.is_none() && row.scene.is_none()));
}
#[test]
fn text_paste_splits_at_unicode_caret_shifts_rows_and_preserves_annotations() {
let mut s = Session::default();
@@ -1210,6 +1298,10 @@ mod tests {
"lineColors":[{"line":rows[1],"color":"Rose"}],"offscreenLines":[rows[2]]}),
)
.unwrap();
s.execute("script.setTreeOutlineColor", json!({"item":origin,"slate":slate,"color":"Blue"})).unwrap();
s.execute("script.setTreeOutlineColor", json!({"item":origin,"slate":slate,"color":"Default"})).unwrap();
assert_eq!(s.project.item(ItemId(origin)).unwrap().as_script().unwrap().slates[0].outline_color, ScriptColor::Default);
s.execute("edit.undo", json!({})).unwrap();
let section = s.execute("script.copySection", json!({"item":origin,"startLine":rows[1],"endLine":rows[2],"slates":[slate]})).unwrap();
assert_eq!(section["lines"].as_array().unwrap().len(), 2);
assert_eq!(section["slates"][0]["takes"][0]["marks"].as_array().unwrap().len(), 1);
@@ -1221,6 +1313,7 @@ mod tests {
assert_eq!(doc.lines.iter().map(|line| line.text.as_str()).collect::<Vec<_>>(), ["Before", "B", "C", "After"]);
assert_eq!(doc.lines[1].scene.as_deref(), Some("2A"));
assert_eq!(doc.lines[1].id.0, result["startLine"].as_u64().unwrap());
assert_eq!(doc.slates[0].outline_color, ScriptColor::Blue);
let pasted = &doc.slates[0].takes[0];
assert_eq!(pasted.source, Some(media));
assert_eq!(pasted.start_line, doc.lines[1].id);
@@ -1751,6 +1844,12 @@ mod tests {
let mark =
s.execute("script.addMark", json!({"item":script,"take":take,"line":line,"sourceTime":rate.tick_of(30).0})).unwrap()["mark"].as_u64().unwrap();
let cued = s.execute("script.cueMark", json!({"item":script,"take":take,"mark":mark})).unwrap();
assert_eq!(cued["time"], rate.tick_of(24).0, "pre-roll stops at the subclip In");
s.execute("prefs.set", json!({"key":"playback.linedScriptPrerollSeconds","value":0.1})).unwrap();
let cued = s.execute("script.cueLine", json!({"item":script,"take":take,"line":line})).unwrap();
assert_eq!(cued["time"], rate.tick_of(27).0, "a fractional-frame lead-in rounds down");
s.execute("prefs.set", json!({"key":"playback.linedScriptPrerollSeconds","value":0.0})).unwrap();
let cued = s.execute("script.cueMark", json!({"item":script,"take":take,"mark":mark})).unwrap();
assert_eq!(cued["time"], rate.tick_of(30).0);
Arc::make_mut(&mut s.project).shift_media_time(parent, rate.tick_of(5));
let shifted = s.project.item(ItemId(script)).unwrap().as_script().unwrap().take(ScriptTakeId(take)).unwrap().marks[0].source_time;
+1
View File
@@ -527,6 +527,7 @@ pub(super) static CATEGORIES: &[Category] = &[
title: "Playback",
rows: &[
f("playback.prerollSeconds", "Preroll", float(0.0, 60.0, 0, "seconds"), true),
f("playback.linedScriptPrerollSeconds", "Lined Script Pre-Roll Playback", float(0.0, 5.0, 1, "seconds"), true),
f("playback.postrollSeconds", "Postroll", float(0.0, 60.0, 0, "seconds"), true),
f("playback.stepManyFrames", "Step forward/back many", int(1.0, 1000.0, "frames"), true),
b("playback.pauseEncoderQueue", "Pause Media Encoder queue during playback", false),
+2 -1
View File
@@ -115,7 +115,8 @@ fn stored_media_paths_open_only_on_this_computer_or_beside_the_project() {
}
let rel = items[refused];
assert_eq!(t.media.offline_status(rel), None, "a path beside the project opens");
assert!(t.media_stamps.contains_key("b.mov"));
// a stored path opens as the file it resolves to, and the watch stamps that file
assert!(t.media_stamps.contains_key(beside.to_string_lossy().as_ref()));
// linking a file in this session opens it, even at the path the project stored
if let Some(path) = slashed(&a) {
@@ -0,0 +1,83 @@
//! Background exports render on threads of their own. The monitors render their frames on the
//! global rayon pool: an export sharing it kept every thread busy, so the frames of a scrub or a
//! play during an export queued behind the export's work. With every thread of the global pool
//! held, an export started in the background must still finish.
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Condvar, Mutex, PoisonError};
use std::time::{Duration, Instant};
use filmcraft_engine::Session;
use serde_json::{Value, json};
/// Holds every thread of the global rayon pool until dropped.
struct GlobalPoolHeld(Arc<(Mutex<bool>, Condvar)>);
impl GlobalPoolHeld {
fn new() -> Self {
let gate = Arc::new((Mutex::new(false), Condvar::new()));
// made first, so a failed start below unwinds through its drop and lets the threads go
let held = Self(gate.clone());
let started = Arc::new(AtomicUsize::new(0));
let (g, n) = (gate.clone(), started.clone());
rayon::spawn_broadcast(move |_| {
n.fetch_add(1, Ordering::SeqCst);
let (open, cv) = &*g;
let mut open = open.lock().unwrap_or_else(PoisonError::into_inner);
while !*open {
open = cv.wait(open).unwrap_or_else(PoisonError::into_inner);
}
});
let t0 = Instant::now();
while started.load(Ordering::SeqCst) < rayon::current_num_threads() {
assert!(t0.elapsed() < Duration::from_secs(10), "the global pool's threads did not all start");
std::thread::sleep(Duration::from_millis(1));
}
held
}
}
impl Drop for GlobalPoolHeld {
fn drop(&mut self) {
let (open, cv) = &*self.0;
*open.lock().unwrap_or_else(PoisonError::into_inner) = true;
cv.notify_all();
}
}
fn scratch(name: &str) -> std::path::PathBuf {
let d = filmcraft_testkit::workspace_root().join("target").join("export-tests").join(format!("engine-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
d
}
/// Poll `jobs.list` until job `id` has finished (or `limit` passes); its entry.
fn wait_for(s: &mut Session, id: u64, limit: Duration) -> Value {
let t0 = Instant::now();
loop {
let jobs = s.execute("jobs.list", json!({})).unwrap();
let job = jobs.as_array().and_then(|a| a.iter().find(|j| j["id"] == id)).cloned().unwrap_or(Value::Null);
if job["finished"] == true || t0.elapsed() > limit {
return job;
}
std::thread::sleep(Duration::from_millis(20));
}
}
#[test]
fn a_background_export_does_not_wait_for_the_global_pool() {
let mut s = Session::default();
s.execute("file.openDemoProject", json!({})).unwrap();
let dir = scratch("own-threads");
let out = dir.join("Demo.mov").to_string_lossy().to_string();
let held = GlobalPoolHeld::new();
let r = s.execute("file.exportMedia", json!({"path": out, "format": "mjpeg", "range": "custom", "startSeconds": 0, "endSeconds": 0.25})).unwrap();
let id = r["job"].as_u64().unwrap();
let job = wait_for(&mut s, id, Duration::from_secs(60));
drop(held);
assert_eq!(job["finished"], json!(true), "the export waited for the global pool: {job}");
assert!(job["result"]["error"].is_null(), "{job}");
assert!(std::fs::metadata(&out).is_ok_and(|m| m.len() > 0), "no file written");
let _ = std::fs::remove_dir_all(&dir);
}
+60
View File
@@ -0,0 +1,60 @@
//! Background jobs hold no more threads than the machine has cores. Proxy jobs made their pool of
//! one thread per core and then waited in line inside it (#1831), so ten queued jobs on a 32-core
//! machine held 320 idle threads, and an export and Render Previews at once each made a pool of
//! their own. Its own test binary: the start hook it installs counts every background pool's
//! threads in the process.
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Duration, Instant};
use filmcraft_engine::Session;
use serde_json::{Value, json};
static STARTED: AtomicUsize = AtomicUsize::new(0);
fn count() {
STARTED.fetch_add(1, Ordering::SeqCst);
}
/// Poll `jobs.list` until every job in `ids` has finished (or `limit` passes); their entries.
fn wait_for(s: &mut Session, ids: &[u64], limit: Duration) -> Vec<Value> {
let t0 = Instant::now();
loop {
let jobs = s.execute("jobs.list", json!({})).unwrap();
let mine: Vec<Value> = jobs.as_array().unwrap().iter().filter(|j| ids.iter().any(|id| j["id"] == json!(id))).cloned().collect();
if (mine.len() == ids.len() && mine.iter().all(|j| j["finished"] == true)) || t0.elapsed() > limit {
return mine;
}
std::thread::sleep(Duration::from_millis(20));
}
}
#[test]
fn background_jobs_never_start_more_threads_than_cores() {
filmcraft_export::register_background_thread_start(count);
let dir = filmcraft_testkit::workspace_root().join("target").join("export-tests").join(format!("engine-queued-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let mut s = Session::default();
s.execute("file.openDemoProject", json!({})).unwrap();
let clip = dir.join("clip.mov").to_string_lossy().to_string();
let r = s.execute("file.exportMedia", json!({"path": clip, "format": "mjpeg", "range": "custom", "startSeconds": 0, "endSeconds": 0.25})).unwrap();
let made = wait_for(&mut s, &[r["job"].as_u64().unwrap()], Duration::from_secs(60));
assert!(made.iter().all(|j| j["result"]["error"].is_null()), "{made:?}");
let r = s.execute("file.import", json!({"paths": [clip]})).unwrap();
let item = r["items"][0].as_u64().unwrap();
let jobs: Vec<u64> = (0..3)
.map(|_| {
let r = s.execute("media.createProxies", json!({"items": [item], "preset": "prores_proxy_half"})).unwrap();
r["job"]["job"].as_u64().or_else(|| r["job"].as_u64()).unwrap_or_else(|| panic!("{r}"))
})
.collect();
let done = wait_for(&mut s, &jobs, Duration::from_secs(120));
assert!(done.len() == 3 && done.iter().all(|j| j["finished"] == true && j["result"]["error"].is_null()), "{done:?}");
let started = STARTED.load(Ordering::SeqCst);
let cores = std::thread::available_parallelism().map_or(1, |n| n.get());
assert!(started >= 1, "the jobs started no pool threads");
assert!(started <= cores, "{started} pool threads for an export and three proxy jobs ({cores} cores)");
let _ = std::fs::remove_dir_all(&dir);
}
+11
View File
@@ -18,6 +18,17 @@ file. Buffered writes are flushed before reads through that same handle. In-memo
sinks use their existing seekable byte buffer. Read, write and seek failures propagate as export
errors.
## Threads
`export` renders on the rayon pool it is called in, so the determinism tests can run it on pools
of any size and get the same file. Background jobs (exports, the export queue, Render Previews and
proxies) call it through `on_own_threads`, which runs them on the background pool: one thread per
core, shared by every background job, so an export and Render Previews at once split the cores
rather than each taking them all. A job capped below the cores (`max_threads`) gets a pool of
that many threads of its own. From a plain thread they would otherwise render on the global pool,
where the monitors render their frames, and those frames would queue behind the export's work
for as long as it ran.
## Animated GIF transparency
Animated GIF supports the existing `ExportSettings::alpha` option (#3396). In Export mode,
+53
View File
@@ -375,6 +375,59 @@ fn max_threads_does_not_change_the_file() {
}
}
#[test]
fn own_threads_are_a_pool_of_their_own() {
let cores = std::thread::available_parallelism().map_or(1, |n| n.get());
let (n, name) = on_own_threads(0, || (rayon::current_num_threads(), std::thread::current().name().map(str::to_owned)));
assert_eq!(n, cores, "one thread per core unless asked");
assert!(name.as_deref().is_some_and(|n| n.starts_with("filmcraft-export-")), "{name:?}");
assert_eq!(on_own_threads(2, rayon::current_num_threads), 2.min(cores));
assert_eq!(on_own_threads(u32::MAX, rayon::current_num_threads), cores, "never more threads than cores");
}
/// Two background jobs at once (an export and Render Previews) split the cores: each made a pool of
/// one thread per core, so together they ran twice as many threads as there are cores.
#[test]
fn background_jobs_share_one_pool() {
let cores = std::thread::available_parallelism().map_or(1, |n| n.get());
// a pool per job would run every job on a thread never seen before
let threads: std::collections::HashSet<_> = (0..=cores).map(|_| on_own_threads(0, || std::thread::current().id())).collect();
assert!(threads.len() <= cores, "{} threads for {} jobs on {cores} cores", threads.len(), cores + 1);
let together = std::thread::scope(|s| {
let jobs: Vec<_> = (0..2).map(|_| s.spawn(|| on_own_threads(0, rayon::current_num_threads))).collect();
jobs.into_iter().filter_map(|j| j.join().ok()).collect::<Vec<_>>()
});
assert_eq!(together, vec![cores, cores], "both jobs on the same pool of one thread per core");
}
/// A shared pool that could not be made (no threads to be had) was remembered as none for good, so
/// every later background job rendered on the global pool beside the monitors.
#[test]
fn a_shared_pool_that_could_not_be_made_is_tried_again() {
let slot = std::sync::Mutex::new(None);
assert_eq!(crate::run::made_once(&slot, || None::<u32>), None);
assert_eq!(crate::run::made_once(&slot, || Some(7)).as_deref(), Some(&7), "tried again");
assert_eq!(crate::run::made_once(&slot, || Some(8)).as_deref(), Some(&7), "made once it worked");
}
#[test]
fn own_threads_run_the_background_hook_as_they_start() {
static STARTED: std::sync::Mutex<Vec<std::thread::ThreadId>> = std::sync::Mutex::new(Vec::new());
fn note() {
STARTED.lock().unwrap().push(std::thread::current().id());
}
// a capped job makes its pool now, after the hook is in; the shared pool may have been made by
// another test before it
if std::thread::available_parallelism().map_or(1, |n| n.get()) < 2 {
return;
}
crate::register_background_thread_start(note);
let workers: std::collections::HashSet<_> = on_own_threads(1, || (0..64).into_par_iter().map(|_| std::thread::current().id()).collect());
let started = STARTED.lock().unwrap();
assert!(!workers.is_empty() && workers.iter().all(|w| started.contains(w)), "every thread of the pool ran the hook");
assert!(!started.contains(&std::thread::current().id()), "the calling thread keeps its priority");
}
#[test]
fn max_threads_is_a_setting_of_the_json_interface() {
let s: ExportSettings = serde_json::from_str(r#"{"format":"mjpeg","maxThreads":2}"#).unwrap();
+3 -3
View File
@@ -68,14 +68,14 @@ pub use output::{OutputSink, path_is_file};
pub(crate) use registry::reset_frame_renderers_for_tests;
pub use registry::{
AudioEncoder, AudioEncoderFactory, EncodedPacket, EncoderFactory, EncoderFrame, FrameRenderer, FrameRendererFactory, PrepareAhead, VideoEncoder, available,
encoder_registered, frame_renderer_registered, hdr_available, idle_renderer_count, register_audio_encoder, register_encoder, register_format_probe,
register_frame_renderer, register_hdr_probe, release_idle_renderers,
encoder_registered, frame_renderer_registered, hdr_available, idle_renderer_count, register_audio_encoder, register_background_thread_start,
register_encoder, register_format_probe, register_frame_renderer, register_hdr_probe, release_idle_renderers,
};
use registry::{audio_factories, video_factories};
pub(crate) use registry::{keep_idle_renderers, take_frame_renderer};
#[cfg(test)]
use run::gif_delay_cs;
pub use run::{export, export_range, frame_span, validate_range};
pub use run::{export, export_range, frame_span, on_own_threads, validate_range};
pub use stats::{
GpuRenderStats, HwEncodeStats, Stage, export_lock_wait, gpu_render_stats, hw_encode_stats, note_gpu_fallback, note_gpu_frame, note_hw_encode_declined,
note_hw_encode_declined_by, note_hw_encode_frame, note_hw_encode_session, note_stage, reset_export_lock_wait, stage_times, timed,
+20
View File
@@ -253,6 +253,26 @@ pub fn register_format_probe(format: Format, probe: fn() -> bool) {
}
}
fn background_thread_hook() -> &'static RwLock<Option<fn()>> {
static H: OnceLock<RwLock<Option<fn()>>> = OnceLock::new();
H.get_or_init(|| RwLock::new(None))
}
/// Say what to run on each thread of a background job's pool as it starts ([`crate::on_own_threads`]):
/// the platform layer lowers the thread's scheduling priority, so the monitors and the UI come
/// first while an export runs. A second registration replaces the first.
pub fn register_background_thread_start(f: fn()) {
*background_thread_hook().write().unwrap_or_else(PoisonError::into_inner) = Some(f);
}
/// Run the registered background-thread hook, if any, on the calling thread.
pub(crate) fn background_thread_start() {
let hook = *background_thread_hook().read().unwrap_or_else(PoisonError::into_inner);
if let Some(f) = hook {
f();
}
}
fn hdr_probes() -> &'static RwLock<Vec<FormatProbe>> {
static P: OnceLock<RwLock<Vec<FormatProbe>>> = OnceLock::new();
P.get_or_init(|| RwLock::new(Vec::new()))
+43
View File
@@ -66,6 +66,49 @@ fn capped_pool(max_threads: u32) -> Option<rayon::ThreadPool> {
rayon::ThreadPoolBuilder::new().num_threads(cap).thread_name(|i| format!("filmcraft-export-{i}")).build().ok()
}
/// Run `f`, a background job's exports, on the background pool: one thread per core, shared by
/// every background job, so two at once (an export and Render Previews) split the cores instead
/// of each taking them all. A job capped below the cores (`max_threads`, 0 = no cap) gets a pool
/// of that many threads of its own. From a plain thread an export renders on the global pool,
/// where the monitors render their frames: those then queue behind the export's work for as long
/// as it runs. Each thread runs the hook of [`crate::register_background_thread_start`] as it
/// starts (the platform layer lowers its priority). Runs `f` where it is called in the browser,
/// or when no pool can be made.
pub fn on_own_threads<T: Send>(max_threads: u32, f: impl FnOnce() -> T + Send) -> T {
static SHARED: std::sync::Mutex<Option<Arc<rayon::ThreadPool>>> = std::sync::Mutex::new(None);
let cores = std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get);
let pool = match usize::try_from(max_threads) {
Ok(cap) if cap > 0 && cap < cores => background_pool(cap).map(Arc::new),
_ => made_once(&SHARED, || background_pool(cores)),
};
match pool {
Some(pool) => pool.install(f),
None => f(),
}
}
/// What `slot` holds, or what `make` makes, kept in `slot`. A `make` that fails (no threads to be
/// had for now) leaves the slot empty, so the next call tries again.
pub(crate) fn made_once<T>(slot: &std::sync::Mutex<Option<Arc<T>>>, make: impl FnOnce() -> Option<T>) -> Option<Arc<T>> {
let mut held = slot.lock().unwrap_or_else(PoisonError::into_inner);
if held.is_none() {
*held = make().map(Arc::new);
}
held.clone()
}
fn background_pool(threads: usize) -> Option<rayon::ThreadPool> {
if cfg!(target_arch = "wasm32") {
return None;
}
rayon::ThreadPoolBuilder::new()
.num_threads(threads)
.thread_name(|i| format!("filmcraft-export-{i}"))
.start_handler(|_| super::registry::background_thread_start())
.build()
.ok()
}
/// Run an export (blocking; call from a worker thread). With `settings.max_threads` set it runs on
/// a pool of that many threads, so its rendering and software encoding use at most that many cores.
pub fn export(project: &Arc<Project>, seq: ItemId, settings: &ExportSettings, sources: &dyn SourceProvider, progress: &Progress) -> Result<Report> {
+3
View File
@@ -22,3 +22,6 @@ tempfile = "3.27"
[dev-dependencies]
filmcraft-time = { workspace = true }
craft-docpath = { workspace = true }
serde = { workspace = true }
sha2 = "0.10"
@@ -0,0 +1,152 @@
//! Developer-only project-folder conversion. See docs/project-files.md.
use craft_fcproj_format::records::ProjectRecords;
use filmcraft_format::{MAX_PROJECT_BYTES, atomic_write_new};
use filmcraft_media::reader::read_regular_file_bounded;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use sha2::{Digest, Sha256};
use std::collections::BTreeMap;
use std::fs;
use std::io;
use std::path::Path;
#[path = "paths.rs"]
mod paths;
#[path = "revisions.rs"]
pub(super) mod revisions;
pub(super) const ROOT: &str = "project.fcmod";
const FORMAT: &str = "filmcraft.project-folder";
const MANIFEST_LIMIT: u64 = 16 << 20;
const RECORD_LIMIT: usize = 100_000;
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Manifest {
format: String,
layout: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
revision: Option<revisions::Revision>,
envelope: String,
bins: Vec<(u64, String)>,
items: Vec<(u64, String)>,
}
fn invalid(reason: impl std::fmt::Display) -> io::Error {
io::Error::new(io::ErrorKind::InvalidData, reason.to_string())
}
fn digest(data: &[u8]) -> String {
format!("{:x}", Sha256::digest(data))
}
fn read_member(path: &Path, limit: u64) -> io::Result<Vec<u8>> {
if !fs::symlink_metadata(path)?.is_file() {
return Err(invalid(format!("expected a regular file at {}", path.display())));
}
read_regular_file_bounded(path, limit)
}
fn is_digest(hash: &str) -> bool {
hash.len() == 64 && hash.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}
fn load_payload(folder: &Path, hash: &str, remaining: &mut u64) -> io::Result<Value> {
if !is_digest(hash) {
return Err(invalid("invalid SHA-256 digest"));
}
let bytes = read_member(&folder.join(hash), *remaining)?;
if digest(&bytes) != hash {
return Err(invalid("SHA-256 mismatch"));
}
*remaining -= bytes.len() as u64;
Ok(serde_json::from_slice(&bytes)?)
}
fn load_group(folder: &Path, kind: &str, entries: &[(u64, String)], budget: &mut u64) -> io::Result<BTreeMap<u64, Value>> {
let mut group = BTreeMap::new();
for (id, hash) in entries {
let data = load_payload(folder, hash, budget).map_err(|e| invalid(format!("{kind} {id}: {e}")))?;
if data.get("id").and_then(Value::as_u64) != Some(*id) || group.insert(*id, data).is_some() {
return Err(invalid(format!("mismatched or repeated {kind} {id}")));
}
}
Ok(group)
}
fn assemble(folder: &Path, manifest: &Manifest, destination: &Path) -> io::Result<Vec<u8>> {
if manifest.format != FORMAT || !matches!((manifest.layout, &manifest.revision), (1, None) | (2, Some(_))) {
return Err(invalid(format!("unsupported project folder format {:?}, layout {}", manifest.format, manifest.layout)));
}
if let Some(revision) = &manifest.revision {
revision.validate()?;
}
if manifest.bins.len().saturating_add(manifest.items.len()) > RECORD_LIMIT {
return Err(invalid("too many project records"));
}
let mut budget = MAX_PROJECT_BYTES;
let envelope = load_payload(folder, &manifest.envelope, &mut budget).map_err(|e| invalid(format!("project metadata: {e}")))?;
let bins = load_group(folder, "bin", &manifest.bins, &mut budget)?;
let items = load_group(folder, "item", &manifest.items, &mut budget)?;
let mut records = ProjectRecords { envelope, bins, items };
paths::rebase(&mut records, &folder.join(ROOT), destination)?;
let document = records.into_document().map_err(invalid)?;
let bytes = serde_json::to_vec(&document)?;
filmcraft_format::decode(&bytes).map_err(invalid)?;
Ok(bytes)
}
fn write_payload(folder: &Path, value: Value, write_new: &mut impl FnMut(&Path, &[u8]) -> io::Result<()>) -> io::Result<String> {
let bytes = serde_json::to_vec(&value)?;
let hash = digest(&bytes);
let path = folder.join(&hash);
match write_new(&path, &bytes) {
Ok(()) => (),
// Equal content may share a payload. assemble verifies every referenced byte before publication.
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => (),
Err(e) => return Err(e),
}
Ok(hash)
}
pub(super) fn records_from(source: &Path, folder: &Path) -> io::Result<ProjectRecords> {
let mut records = {
let bytes = read_regular_file_bounded(source, MAX_PROJECT_BYTES)?;
filmcraft_format::decode(&bytes).map_err(invalid)?;
ProjectRecords::split(&bytes).map_err(invalid)?
};
if records.bins.len().saturating_add(records.items.len()) > RECORD_LIMIT {
return Err(invalid("too many project records"));
}
let root = folder.join(ROOT);
paths::rebase(&mut records, source, &root)?;
Ok(records)
}
fn materialize(folder: &Path, records: ProjectRecords, mut write_new: impl FnMut(&Path, &[u8]) -> io::Result<()>) -> io::Result<Manifest> {
let envelope = write_payload(folder, records.envelope, &mut write_new)?;
let mut group = |values: BTreeMap<u64, Value>| -> io::Result<Vec<_>> {
values.into_iter().map(|(id, value)| Ok((id, write_payload(folder, value, &mut write_new)?))).collect()
};
Ok(Manifest { format: FORMAT.to_owned(), layout: 1, revision: None, envelope, bins: group(records.bins)?, items: group(records.items)? })
}
pub(super) fn pack(source: &Path, folder: &Path, mut write_new: impl FnMut(&Path, &[u8]) -> io::Result<()>) -> io::Result<()> {
let records = records_from(source, folder)?;
fs::create_dir(folder)?; // Exclusively reserve a fresh destination. Never adopt an existing directory.
let root = folder.join(ROOT);
let manifest = materialize(folder, records, &mut write_new)?;
let bytes = serde_json::to_vec(&manifest)?;
if bytes.len() as u64 > MANIFEST_LIMIT {
return Err(invalid("manifest exceeds the folder layout's size limit"));
}
assemble(folder, &manifest, &root)?;
#[cfg(unix)]
fs::File::open(folder)?.sync_all()?;
write_new(&root, &bytes)
}
pub(super) fn unpack(folder: &Path, destination: &Path) -> io::Result<()> {
let manifest = serde_json::from_slice(&read_member(&folder.join(ROOT), MANIFEST_LIMIT)?)?;
atomic_write_new(destination, &assemble(folder, &manifest, destination)?)
}
@@ -0,0 +1,51 @@
//! Developer-only project-folder conversion. See docs/project-files.md.
mod converter;
use converter::{
pack,
revisions::{checkout, save},
unpack,
};
use filmcraft_format::atomic_write_new;
use std::{
io::{self, Write},
path::Path,
};
fn run() -> io::Result<()> {
let args: Vec<_> = std::env::args_os().skip(1).collect();
if let [command, source, destination] = args.as_slice() {
let (src, dest) = (Path::new(source), Path::new(destination));
if command == "pack" {
return pack(src, dest, atomic_write_new);
}
if command == "checkout" {
let revision = checkout(src, dest)?;
return writeln!(io::stdout().lock(), "{revision}");
}
if command == "unpack" {
return unpack(src, dest);
}
}
if let [command, folder, expected, source] = args.as_slice()
&& command == "save"
&& let Some(expected) = expected.to_str()
{
let revision = save(Path::new(folder), expected, Path::new(source))?;
return writeln!(io::stdout().lock(), "{revision}");
}
Err(io::Error::new(
io::ErrorKind::InvalidInput,
"usage: project_folder pack SOURCE.fcproj NEW_FOLDER | unpack FOLDER NEW_FILE.fcproj | checkout FOLDER NEW_FILE.fcproj | save FOLDER BASE_REVISION EDITED.fcproj",
))
}
fn main() -> std::process::ExitCode {
match run() {
Ok(()) => std::process::ExitCode::SUCCESS,
Err(e) => {
eprintln!("project_folder: {e}");
std::process::ExitCode::FAILURE
}
}
}
@@ -0,0 +1,87 @@
//! Rebase only file-backed originals and proxies. Keep opaque project fields and foreign
//! absolute paths verbatim. Never stat the media: an offline reference has the same identity.
use super::{ProjectRecords, invalid};
use craft_docpath::{PathKind, Refused};
use std::io;
use std::path::{Component, Path, PathBuf};
fn relative_to(target: &Path, base: &Path) -> Option<PathBuf> {
let mut t = target.components().peekable();
let mut b = base.components().peekable();
while t.peek().is_some() && t.peek() == b.peek() {
t.next();
b.next();
}
let mut result = PathBuf::new();
for part in b {
if !matches!(part, Component::Normal(_)) {
return None;
}
result.push("..");
}
result.extend(t);
Some(result)
}
fn relocated(stored: &str, old: &Path, new: &Path) -> io::Result<Option<String>> {
let resolve = |s: &str, doc: &Path| craft_docpath::resolve(s, Some(doc));
let original = resolve(stored, old);
// An explicit network path already names its target independently of the document.
if original == resolve(stored, new) || craft_docpath::classify(stored) == PathKind::Network {
return Ok(None);
}
let target = original.map_err(invalid)?;
let base = new.parent().ok_or_else(|| invalid("missing destination parent"))?;
for candidate in relative_to(&target, base).into_iter().chain(std::iter::once(target.clone())) {
let Some(text) = candidate.to_str() else { continue };
let at_destination = resolve(text, new);
// The original document resolved this absolute target. A different volume can
// retain the path as metadata even when media access there is denied.
if at_destination.as_ref() == Ok(&target) || (candidate == target && at_destination == Err(Refused::Network)) {
return Ok(Some(text.to_owned()));
}
}
Err(invalid("cannot preserve the stored path at the new location"))
}
pub(super) fn rebase(records: &mut ProjectRecords, from: &Path, to: &Path) -> io::Result<()> {
let old = std::path::absolute(from)?;
let new = std::path::absolute(to)?;
if old == new {
return Ok(());
}
for (id, item) in &mut records.items {
if let Some(media) = item.pointer_mut("/kind/Media") {
for key in ["media", "proxy"] {
if let Some(value) = media.get_mut(key).and_then(|v| v.pointer_mut("/File/path"))
&& let Some(path) = value.as_str()
&& let Some(updated) = relocated(path, &old, &new).map_err(|e| invalid(format!("item {id} {key}: {e}")))?
{
*value = updated.into();
}
}
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::relocated;
use craft_docpath::{Refused, resolve};
use std::path::Path;
#[test]
fn unc_links_survive_a_local_archive_roundtrip() {
let edit = Path::new(r"\\server\share\edit.fcproj");
let archive = Path::new("C:/archive/folder/project.fcmod");
let stored = r"media\a.mov";
let target = resolve(stored, Some(edit)).unwrap();
let archived = relocated(stored, edit, archive).unwrap().unwrap();
assert_eq!(Path::new(&archived), target);
assert_eq!(resolve(&archived, Some(archive)), Err(Refused::Network));
assert_eq!(relocated(&archived, archive, edit).unwrap(), None);
assert_eq!(resolve(&archived, Some(edit)).unwrap(), target);
assert_eq!(relocated("//server/share/media/a.mov", edit, archive).unwrap(), None);
}
}
@@ -0,0 +1,126 @@
//! Local writer serialization and optimistic revision checks. The manifest rename is the
//! commit point. Older manifests and payloads stay available by digest.
use super::{MANIFEST_LIMIT, Manifest, ROOT, assemble, digest, invalid, is_digest, materialize, read_member, records_from};
use craft_fcproj_format::records::ProjectRecords;
use filmcraft_format::atomic_write_new;
use serde::{Deserialize, Serialize};
use std::fs::{File, OpenOptions, TryLockError};
use std::time::{SystemTime, UNIX_EPOCH};
use std::{collections::BTreeMap, io, path::Path};
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(super) struct Revision {
number: u64,
parent: String,
bin_edits: BTreeMap<u64, Edit>,
item_edits: BTreeMap<u64, Edit>,
}
impl Revision {
pub(super) fn validate(&self) -> io::Result<()> {
if self.number == 0 || !is_digest(&self.parent) {
return Err(invalid("invalid project revision metadata"));
}
Ok(())
}
}
#[derive(Clone, Copy, Serialize, Deserialize)]
struct Edit {
utc_ms: i64,
revision: u64,
}
fn edits(old: &[(u64, String)], new: &[(u64, String)], previous: Option<&BTreeMap<u64, Edit>>, edit: Edit) -> BTreeMap<u64, Edit> {
let old: BTreeMap<_, _> = old.iter().map(|(id, hash)| (*id, hash)).collect();
new.iter()
.filter_map(|(id, hash)| {
let stamp = if old.get(id).copied() == Some(hash) { previous.and_then(|m| m.get(id)).copied() } else { Some(edit) };
stamp.map(|s| (*id, s))
})
.collect()
}
fn writer(folder: &Path) -> io::Result<File> {
let path = folder.join(".writer.lock");
match path.symlink_metadata() {
Ok(meta) if !meta.is_file() => return Err(invalid("project lock must be a regular file")),
Err(e) if e.kind() != io::ErrorKind::NotFound => return Err(e),
_ => {}
}
let file = OpenOptions::new().create(true).truncate(false).read(true).write(true).open(path)?;
match file.try_lock() {
Ok(()) => {}
Err(TryLockError::WouldBlock) => return Err(io::Error::new(io::ErrorKind::WouldBlock, "another writer holds the project lock")),
Err(TryLockError::Error(e)) => return Err(e),
}
Ok(file)
}
pub(in super::super) fn checkout(folder: &Path, destination: &Path) -> io::Result<String> {
let bytes = read_member(&folder.join(ROOT), MANIFEST_LIMIT)?;
let manifest = serde_json::from_slice(&bytes)?;
atomic_write_new(destination, &assemble(folder, &manifest, destination)?)?;
Ok(digest(&bytes))
}
fn publish(path: &Path, bytes: &[u8]) -> io::Result<()> {
if path.file_name().is_some_and(|name| name == ROOT) { filmcraft_format::atomic_write(path, bytes) } else { atomic_write_new(path, bytes) }
}
pub(in super::super) fn save(folder: &Path, expected: &str, source: &Path) -> io::Result<String> {
save_with(folder, expected, records_from(source, folder)?, publish)
}
pub(in super::super) fn save_with(
folder: &Path,
expected: &str,
records: ProjectRecords,
mut write: impl FnMut(&Path, &[u8]) -> io::Result<()>,
) -> io::Result<String> {
let _guard = writer(folder)?;
let root = folder.join(ROOT);
let previous_bytes = read_member(&root, MANIFEST_LIMIT)?;
let base = digest(&previous_bytes);
if expected != base {
return Err(io::Error::other(format!("stale project revision; current revision is {base}")));
}
let previous: Manifest = serde_json::from_slice(&previous_bytes)?;
assemble(folder, &previous, &root)?;
let mut next = materialize(folder, records, |p, b| {
// All reused bytes are verified by assemble before publishing the candidate.
if p.try_exists()? { Ok(()) } else { write(p, b) }
})?;
if previous.envelope == next.envelope && previous.items == next.items && previous.bins == next.bins {
return Ok(base);
}
let prior = previous.revision.as_ref();
let number = prior.map_or(0, |r| r.number).checked_add(1).ok_or_else(|| invalid("revision limit reached"))?;
let utc_ms = i64::try_from(SystemTime::now().duration_since(UNIX_EPOCH).map_err(invalid)?.as_millis()).map_err(invalid)?;
let edit = Edit { revision: number, utc_ms };
next.layout = 2;
next.revision = Some(Revision {
number,
parent: base.clone(),
bin_edits: edits(&previous.bins, &next.bins, prior.map(|r| &r.bin_edits), edit),
item_edits: edits(&previous.items, &next.items, prior.map(|r| &r.item_edits), edit),
});
let bytes = serde_json::to_vec(&next)?;
if bytes.len() as u64 > MANIFEST_LIMIT {
return Err(invalid("revision manifest exceeds size limit"));
}
assemble(folder, &next, &root)?;
let archive = folder.join(&base);
if archive.try_exists()? {
if read_member(&archive, MANIFEST_LIMIT)? != previous_bytes {
return Err(invalid("damaged archived manifest"));
}
} else {
write(&archive, &previous_bytes)?;
}
#[cfg(unix)]
File::open(folder)?.sync_all()?;
write(&root, &bytes)?;
Ok(digest(&bytes))
}
+21 -23
View File
@@ -41,7 +41,11 @@
//! would drop them when saving.
//! - **v16**: marker authors, named project swatches, and exact marker/clip hex colors.
//! - **v17**: optional marker URLs, independent of notes and retained across marker-type changes.
//! - **v18**: Script Project items with linked takes, marks, and independently positioned thumbnails.
//! - **v18**: camera raw Source Settings on media items (`Interpretation::raw`, #1078), defined in
//! storytold/craft-libs. Absent settings use the values from the footage. Builds from before the
//! craft-libs pin move also wrote Script items as v18; those files read as v18 here and upgrade.
//! - **v19**: Script Project items with linked takes, marks, and independently positioned thumbnails
//! (#2726), defined in storytold/craft-libs.
#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))]
@@ -54,10 +58,7 @@ use serde_json::Value;
pub use atomic::{atomic_write, atomic_write_new, atomic_write_no_follow};
pub use craft_fcproj_format::{FORMAT_ID, FormatError, MIGRATIONS, Migration, OLDEST_SCHEMA, detect_version, migrate_with};
/// Script items require a build that can preserve their takes and thumbnail positions.
pub const SCHEMA_VERSION: u32 = craft_fcproj_format::SCHEMA_VERSION + 1;
pub use craft_fcproj_format::{FORMAT_ID, FormatError, MIGRATIONS, Migration, OLDEST_SCHEMA, SCHEMA_VERSION, detect_version, migrate_with};
/// Largest project file this build will read (256 MiB). Project JSON is read whole, so
/// larger files would commit several times their size in memory before validation.
@@ -103,9 +104,7 @@ pub fn encode(project: &Project, pretty: bool) -> Vec<u8> {
/// outside the schema's promises: builds that do not know it ignore it, and it is dropped rather
/// than migrated when it cannot be read.
pub fn encode_with_view(project: &Project, view: Option<&ProjectView>, pretty: bool) -> Vec<u8> {
let envelope = craft_fcproj_format::EnvelopeOut { format: FORMAT_ID, schema_version: SCHEMA_VERSION, generator: generator(), project, view };
let encoded = if pretty { serde_json::to_vec_pretty(&envelope) } else { serde_json::to_vec(&envelope) };
encoded.unwrap_or_default()
craft_fcproj_format::encode(project, view, generator(), pretty)
}
/// Read a project file (any supported schema).
@@ -113,15 +112,7 @@ pub fn decode(bytes: &[u8]) -> Result<Loaded, FormatError> {
if bytes.len() as u64 > MAX_PROJECT_BYTES {
return Err(FormatError::Corrupt(format!("project file is {} bytes, over the {MAX_PROJECT_BYTES} byte limit", bytes.len())));
}
let (env, found) = match craft_fcproj_format::decode::<Project>(bytes) {
// The Script schema adds optional data. The shared migrations cover every earlier schema.
Err(FormatError::TooNew { found, .. }) if found == SCHEMA_VERSION => {
let env: craft_fcproj_format::EnvelopeIn<Project> = serde_json::from_slice(bytes).map_err(|e| FormatError::Corrupt(e.to_string()))?;
(env, found)
}
Err(FormatError::TooNew { found, .. }) => return Err(FormatError::TooNew { found, supported: SCHEMA_VERSION }),
result => result?,
};
let (env, found) = craft_fcproj_format::decode::<Project>(bytes)?;
validate_loaded(loaded(env, found))
}
@@ -229,7 +220,7 @@ mod tests {
#[test]
fn schema_version_matches_table() {
assert_eq!(SCHEMA_VERSION, 18);
assert_eq!(SCHEMA_VERSION, 19);
}
#[test]
@@ -320,11 +311,15 @@ mod tests {
let second = doc.lines[1].id;
let script = p.add_item("dialogue", Label::Blue, ItemKind::Script(Arc::new(doc)), None);
assert!(decode(&encode(&p, false)).is_ok());
// Previous Script builds saved these items in schema 17. Shared migrations must keep them.
let older = craft_fcproj_format::encode(&p, None::<&filmcraft_project::ProjectView>, "FilmCraft test".into(), false);
let loaded = decode(&older).unwrap();
assert!(loaded.migrated());
assert_eq!(loaded.project, p);
// Earlier Script builds saved these items in schema 17, and builds before the shared Script
// step in schema 18. Shared migrations must keep them.
for version in [17, 18] {
let mut older: Value = serde_json::from_slice(&encode(&p, false)).unwrap();
older["schema_version"] = Value::from(version);
let loaded = decode(&serde_json::to_vec(&older).unwrap()).unwrap();
assert!(loaded.migrated());
assert_eq!(loaded.project, p);
}
let doc = p.item_mut(script).unwrap().as_script_mut().unwrap();
doc.lines[1].id = first;
assert!(matches!(decode(&encode(&p, false)), Err(FormatError::Corrupt(_))));
@@ -335,6 +330,7 @@ mod tests {
let doc = p.item_mut(script).unwrap().as_script_mut().unwrap();
doc.next_id = 5;
doc.slates.push(ScriptSlate {
outline_color: ScriptColor::Rose,
id: ScriptSlateId(3),
name: "setup".into(),
thumbnail_line: None,
@@ -357,6 +353,7 @@ mod tests {
p.next_id = script.0;
let repaired = decode(&encode(&p, false)).unwrap();
assert!(repaired.project.next_id > script.0);
assert_eq!(repaired.project.item(script).unwrap().as_script().unwrap().slates[0].outline_color, ScriptColor::Rose);
let take = &repaired.project.item(script).unwrap().as_script().unwrap().slates[0].takes[0];
assert_eq!(take.source, None);
assert_eq!(take.source_name, "gone");
@@ -386,6 +383,7 @@ mod tests {
let mut p = Project::new("Tabs");
let seq = p.new_sequence("Sequence 01", SequenceSettings::default(), 1, 1, None);
let view = ProjectView {
script_tabs: Default::default(),
open_sequences: vec![seq],
active_sequence: Some(seq),
sequences: [(seq, SequenceView { pps: 80.0, scroll: 1.5, v_scroll: 0.0, a_scroll: 4.0, video_track_h: 60.0, audio_track_h: 56.0 })].into(),
+37
View File
@@ -289,6 +289,43 @@ fn v10_minimal_loads_with_m3_11_defaults() {
assert_eq!(&again.project, p);
}
/// Schema 15 (before camera raw Source Settings): a DNG sequence item whose Interpret Footage
/// has no `raw` settings loads with none (developed as the file says) and resaves unchanged.
#[test]
fn v15_dng_item_loads_without_raw_settings() {
let l = decode(&fixture("v15-dng.fcproj")).unwrap();
assert_eq!(l.schema_version, 15);
assert!(l.migrated());
let p = &l.project;
assert_eq!(p.name, "Before Raw Settings");
let m = p.item(filmcraft_project::ItemId(1)).and_then(|i| i.as_media()).unwrap();
assert_eq!(m.interpret.raw, None);
assert_eq!(m.interpret.par, Some((1, 1)));
assert_eq!(m.info.video.as_ref().unwrap().codec, "DNG sequence");
let again = decode(&encode(p, true)).unwrap();
assert_eq!(again.schema_version, SCHEMA_VERSION);
const { assert!(SCHEMA_VERSION >= 18) };
assert_eq!(&again.project, p);
// no settings: nothing new is written
assert!(!String::from_utf8(encode(p, false)).unwrap().contains("\"raw\""));
}
/// Raw settings round-trip through the current schema.
#[test]
fn raw_settings_roundtrip() {
use filmcraft_media::raw::{DemosaicQuality, RawSettings, WhiteBalance};
let mut p = decode(&fixture("v15-dng.fcproj")).unwrap().project;
let s = RawSettings {
white_balance: WhiteBalance::Custom { temperature: 3200.0, tint: 12.5 },
exposure: -0.75,
demosaic: DemosaicQuality::Fast,
..Default::default()
};
p.item_mut(filmcraft_project::ItemId(1)).and_then(|i| i.as_media_mut()).unwrap().interpret.raw = Some(s);
let l = decode(&encode(&p, false)).unwrap();
assert_eq!(l.project.item(filmcraft_project::ItemId(1)).and_then(|i| i.as_media()).unwrap().interpret.raw, Some(s));
}
/// #2809: `next_id` is read from the file, and nothing raised it past the ids already in it. A file
/// whose `next_id` lagged behind (an older build, a hand edit, a merge) handed out an id in use, and
/// the new item silently replaced the old one. Each kind of id is raised past on its own, so a kind
+1
View File
@@ -0,0 +1 @@
{"format":"filmcraft.project","generator":"FilmCraft 0.6.0","project":{"items":{"1":{"created":1,"id":1,"kind":{"Media":{"info":{"audio_streams":[],"container":"Image Sequence","duration":31752000000,"file_size":null,"kind":"ImageSequence","name":"A001_C001_0000.dng","start_timecode":864000,"video":{"bitrate":null,"codec":"DNG sequence","color":{"matrix":"Bt709","primaries":"Bt709","range":"Full","transfer":"Linear"},"frame_rate":{"den":1,"num":24},"has_alpha":false,"height":12,"par":[1,1],"pixel_format":"Bayer 12-bit raw (lossless JPEG)","width":16}},"interpret":{"frame_rate":null,"ignore_alpha":false,"invert_alpha":false,"par":[1,1]},"mark_in":null,"mark_out":null,"markers":[],"media":{"File":{"path":"/cards/A001_C001/A001_C001_0000.dng"}},"offline":false,"proxy":null}},"label":"Iris","metadata":{},"name":"A001_C001"}},"name":"Before Raw Settings","next_id":2,"root":{"children":[{"Item":1}],"id":0,"name":"Before Raw Settings"},"settings":{"action_safe":[10.0,10.0],"audio_display_samples":true,"capture_format":"DV","default_audio_transition_duration":254016000000,"default_still_duration":1270080000000,"default_transition_duration_frames":24,"ingest":{"action":"createProxies","destination":null,"enabled":false,"preset":""},"renderer":"FilmCraft GPU Acceleration (wgpu)","scratch":{"audioPreviews":null,"autoSave":null,"captured":null,"videoPreviews":null},"title_safe":[20.0,20.0],"video_display":"Timecode"}},"schema_version":15}
+1
View File
@@ -0,0 +1 @@
mod project_folder;
+446
View File
@@ -0,0 +1,446 @@
#[path = "../../examples/project_folder/converter.rs"]
mod converter;
use converter::{
ROOT, pack, records_from,
revisions::{checkout, save, save_with},
unpack,
};
use filmcraft_format::{SCHEMA_VERSION, atomic_write_new};
use serde_json::Value;
use serde_json::json;
use std::{fs, io, path::Path};
use tempfile::tempdir;
fn fixture(name: &str) -> Vec<u8> {
fs::read(Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures").join(name)).unwrap()
}
#[test]
fn legacy_roundtrips_match_ordinary_migration() {
let tmp = tempdir().unwrap();
for entry in fs::read_dir(Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures")).unwrap() {
let src = entry.unwrap().path();
if src.extension().is_none_or(|ext| ext != "fcproj") {
continue;
}
let folder = tmp.path().join(src.file_stem().unwrap());
let out = tmp.path().join(src.file_name().unwrap());
let bytes = fs::read(&src).unwrap();
pack(&src, &folder, atomic_write_new).unwrap();
unpack(&folder, &out).unwrap();
let result = fs::read(out).unwrap();
let schema = craft_fcproj_format::detect_bytes(&bytes).unwrap();
let expected = craft_fcproj_format::migrate_with(craft_fcproj_format::MIGRATIONS, serde_json::from_slice(&bytes).unwrap(), schema).unwrap();
assert_eq!(serde_json::from_slice::<Value>(&result).unwrap(), expected);
assert_eq!(filmcraft_format::decode(&result).unwrap().project, filmcraft_format::decode(&bytes).unwrap().project);
}
}
fn current() -> Value {
let loaded = filmcraft_format::decode(&fixture("v1-edit.fcproj")).unwrap();
let mut doc: Value = serde_json::from_slice(&filmcraft_format::encode(&loaded.project, false)).unwrap();
doc["extra"] = json!({"unknown":[null,{}]});
doc["view"] = json!({"open_sequences":[21,73],"active_sequence":73});
let p = &mut doc["project"];
let mut seq = p["items"]["21"].clone();
seq["id"] = json!(73);
seq["kind"]["Sequence"]["video_tracks"][0]["items"][0]["item"] = json!(21);
p["items"]["73"] = seq;
let mut unfiled = p["items"]["5"].clone();
unfiled["id"] = json!(74);
p["items"]["74"] = unfiled;
p["root"]["children"][0]["Bin"]["children"].as_array_mut().unwrap().push(json!({"Bin":{"id":88,"name":"Footage","children":[{"Item":73}]}}));
p["next_id"] = json!(900000);
doc
}
#[test]
fn camera_raw_settings_survive_pack_and_unpack() {
use filmcraft_project::{ItemKind, Label, ScriptDocument};
use std::sync::Arc;
let tmp = tempdir().unwrap();
let mut project = filmcraft_format::decode(&fixture("v1-edit.fcproj")).unwrap().project;
let script = ScriptDocument::from_text("A camera test").unwrap();
let script_id = project.add_item("Script", Label::Blue, ItemKind::Script(Arc::new(script.clone())), None);
let mut document: Value = serde_json::from_slice(&filmcraft_format::encode(&project, false)).unwrap();
let settings = json!({
"white_balance": {"Custom": {"temperature": 3200.0, "tint": 12.5}},
"exposure": -0.75,
"highlights": "Recover",
"demosaic": "Fast",
"output": "SceneLinearRec709"
});
let raw_path = "/project/items/5/kind/Media/interpret/raw";
document.pointer_mut("/project/items/5/kind/Media/interpret").unwrap()["raw"] = settings.clone();
for version in [18, SCHEMA_VERSION] {
let source = tmp.path().join(format!("source-{version}.fcproj"));
let folder = tmp.path().join(format!("folder-{version}"));
let export = tmp.path().join(format!("export-{version}.fcproj"));
document["schema_version"] = version.into();
let source_bytes = serde_json::to_vec(&document).unwrap();
fs::write(&source, &source_bytes).unwrap();
pack(&source, &folder, atomic_write_new).unwrap();
unpack(&folder, &export).unwrap();
let exported = fs::read(&export).unwrap();
let exported_document: Value = serde_json::from_slice(&exported).unwrap();
assert_eq!(exported_document.pointer(raw_path), Some(&settings));
let reopened = filmcraft_format::decode(&exported).unwrap();
assert_eq!(reopened.schema_version, SCHEMA_VERSION);
assert_eq!(reopened.project.item(script_id).unwrap().as_script(), Some(&script));
assert_eq!(fs::read(source).unwrap(), source_bytes);
}
}
#[test]
fn offline_sources_and_proxies_follow_the_document_and_views_and_opaque_fields_survive() {
let tmp = tempdir().unwrap();
let base = tmp.path();
let src = base.join("edit/cut.fcproj");
let folder = base.join("archive/day1/cut");
let out = base.join("delivery/restored.fcproj");
for parent in [&src, &folder, &out] {
fs::create_dir_all(parent.parent().unwrap()).unwrap();
}
let mut expected = current();
let orig = "/project/items/5/kind/Media/media";
let proxy = "/project/items/5/kind/Media/proxy";
expected.pointer_mut("/project/items/5/kind/Media").unwrap()["proxy"] = json!({"File":{"path":"../proxies/p.mov"}});
*expected.pointer_mut(orig).unwrap() = json!({"File":{"path":"media/a.mov"}});
let bytes = serde_json::to_vec(&expected).unwrap();
fs::write(&src, &bytes).unwrap();
pack(&src, &folder, atomic_write_new).unwrap();
unpack(&folder, &out).unwrap();
assert_eq!(fs::read(&src).unwrap(), bytes);
let result = fs::read(&out).unwrap();
let mut actual: Value = serde_json::from_slice(&result).unwrap();
let view = filmcraft_format::decode(&result).unwrap().view.unwrap();
assert_eq!(view.active_sequence, Some(filmcraft_project::ItemId(73)));
assert_eq!(view, filmcraft_format::decode(&bytes).unwrap().view.unwrap());
for ptr in [orig, proxy] {
let value = actual.pointer_mut(ptr).unwrap();
assert_eq!(
craft_docpath::resolve_absolute(value["File"]["path"].as_str().unwrap(), Some(&out)).unwrap(),
craft_docpath::resolve_absolute(expected.pointer(ptr).unwrap()["File"]["path"].as_str().unwrap(), Some(&src)).unwrap()
);
*value = expected.pointer(ptr).unwrap().clone();
}
assert_eq!(actual, expected);
}
#[test]
fn occupied_destinations_and_write_failures_preserve_existing_data() {
let tmp = tempdir().unwrap();
let src = tmp.path().join("input.fcproj");
let bytes = fixture("v1-edit.fcproj");
fs::write(&src, &bytes).unwrap();
let mut perms = fs::metadata(&src).unwrap().permissions();
perms.set_readonly(true);
fs::set_permissions(&src, perms).unwrap();
let folder = tmp.path().join("folder");
fs::create_dir(&folder).unwrap();
assert_eq!(pack(&src, &folder, atomic_write_new).unwrap_err().kind(), io::ErrorKind::AlreadyExists);
for fail_at in [1, 3] {
let dest = tmp.path().join(format!("failed-{fail_at}"));
let mut count = 0;
let err = pack(&src, &dest, |p, bytes| {
count += 1;
if count == fail_at {
return Err(io::Error::from(io::ErrorKind::StorageFull));
}
atomic_write_new(p, bytes)
})
.unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::StorageFull);
assert!(!dest.join(ROOT).exists());
assert!(unpack(&dest, &tmp.path().join("should-not-exist")).is_err());
}
let dest = tmp.path().join("complete");
pack(&src, &dest, atomic_write_new).unwrap();
assert_eq!(unpack(&dest, &src).unwrap_err().kind(), io::ErrorKind::AlreadyExists);
assert_eq!(fs::read(&src).unwrap(), bytes);
}
#[test]
fn damaged_missing_and_unknown_records_refuse_export() {
let tmp = tempdir().unwrap();
let src = tmp.path().join("input");
fs::write(&src, fixture("v1-edit.fcproj")).unwrap();
let dir = tmp.path().join("dir");
pack(&src, &dir, atomic_write_new).unwrap();
let root = dir.join(ROOT);
let mut m: Value = serde_json::from_slice(&fs::read(&root).unwrap()).unwrap();
let file = dir.join(m["items"][0][1].as_str().unwrap());
let out = tmp.path().join("export");
fs::write(&file, b"{}").unwrap();
for _ in 0..2 {
let error = unpack(&dir, &out).unwrap_err().to_string();
assert!(error.contains(&format!("item {}", m["items"][0][0])), "{error}");
assert!(!out.exists());
if file.exists() {
fs::remove_file(&file).unwrap();
}
}
m["layout"] = json!(2);
fs::write(root, serde_json::to_vec(&m).unwrap()).unwrap();
assert!(unpack(&dir, &out).unwrap_err().to_string().contains("unsupported"));
}
#[test]
fn verification_precedes_commit_and_interrupted_publication_is_unreadable() {
let tmp = tempdir().unwrap();
let src = tmp.path().join("src");
fs::write(&src, fixture("v1-edit.fcproj")).unwrap();
for corrupt in [true, false] {
let dir = tmp.path().join(format!("dest-{corrupt}"));
let result = pack(&src, &dir, |p, bytes| {
if corrupt {
atomic_write_new(p, b"corrupted")
} else if p.file_name().unwrap() == ROOT {
Err(io::ErrorKind::Interrupted.into())
} else {
atomic_write_new(p, bytes)
}
});
assert!(result.is_err());
assert!(!dir.join(ROOT).exists());
}
}
#[cfg(unix)]
#[test]
fn foreign_absolute_paths_are_preserved_in_both_directions() {
let tmp = tempdir().unwrap();
let src = tmp.path().join("src");
let folder = tmp.path().join("folder");
let out = tmp.path().join("out");
let mut doc = current();
let media = doc.pointer_mut("/project/items/5/kind/Media").unwrap();
media["media"] = json!({"File":{"path":r"C:\Camera\A.mov"}});
media["proxy"] = json!({"File":{"path":r"\\server\media\A.mov"}});
fs::write(&src, serde_json::to_vec(&doc).unwrap()).unwrap();
pack(&src, &folder, atomic_write_new).unwrap();
unpack(&folder, &out).unwrap();
assert_eq!(serde_json::from_slice::<Value>(&fs::read(out).unwrap()).unwrap(), doc);
}
#[test]
fn invalid_inputs_never_publish_a_destination() {
let tmp = tempdir().unwrap();
let input = tmp.path().join("input.fcproj");
let folder = tmp.path().join("folder");
let mut project = current();
project["schema_version"] = json!(filmcraft_format::SCHEMA_VERSION + 1);
fs::write(&input, serde_json::to_vec(&project).unwrap()).unwrap();
assert!(pack(&input, &folder, atomic_write_new).is_err());
assert!(!folder.exists());
fs::write(&input, fixture("v1-edit.fcproj")).unwrap();
pack(&input, &folder, atomic_write_new).unwrap();
let root = folder.join(ROOT);
let original: Value = serde_json::from_slice(&fs::read(&root).unwrap()).unwrap();
let mut repeated = original.clone();
repeated["items"].as_array_mut().unwrap().push(original["items"][0].clone());
let mut wrong_id = original.clone();
wrong_id["items"][0][0] = json!(900000);
let mut invalid_digest = original;
invalid_digest["envelope"] = json!("../input.fcproj");
let out = tmp.path().join("output.fcproj");
for manifest in [repeated, wrong_id, invalid_digest] {
fs::write(&root, serde_json::to_vec(&manifest).unwrap()).unwrap();
assert!(unpack(&folder, &out).is_err());
assert!(!out.exists());
}
}
#[test]
fn editing_one_sequence_changes_only_its_record() {
let tmp = tempdir().unwrap();
let source = tmp.path().join("source.fcproj");
let mut project = current();
let write_snapshot = |name: &str, doc: &Value| {
fs::write(&source, serde_json::to_vec(doc).unwrap()).unwrap();
let dir = tmp.path().join(name);
pack(&source, &dir, atomic_write_new).unwrap();
serde_json::from_slice::<Value>(&fs::read(dir.join(ROOT)).unwrap()).unwrap()
};
let first = write_snapshot("first", &project);
project["project"]["items"]["73"]["name"] = json!("Revised cut");
let second = write_snapshot("second", &project);
assert_eq!(first["bins"], second["bins"]);
assert_eq!(first["envelope"], second["envelope"]);
let items = |v: &Value| {
let entries: Vec<(u64, String)> = serde_json::from_value(v["items"].clone()).unwrap();
entries.into_iter().collect::<std::collections::BTreeMap<_, _>>()
};
let mut old = items(&first);
let mut new = items(&second);
let old_cut = old.remove(&73).unwrap();
let new_cut = new.remove(&73).unwrap();
assert_ne!(old_cut, new_cut);
assert_eq!(old, new);
let cut: Value = serde_json::from_slice(&fs::read(tmp.path().join("second").join(new_cut)).unwrap()).unwrap();
assert_eq!(cut, project["project"]["items"]["73"]);
}
fn write_doc(path: &Path, doc: &Value) {
fs::write(path, serde_json::to_vec(doc).unwrap()).unwrap();
}
#[test]
fn held_writer_lock_keeps_a_competing_save_from_publishing() {
let tmp = tempdir().unwrap();
let source = tmp.path().join("source.fcproj");
let edit = tmp.path().join("edit.fcproj");
let folder = tmp.path().join("project");
let mut doc = current();
write_doc(&source, &doc);
pack(&source, &folder, atomic_write_new).unwrap();
let base = checkout(&folder, &edit).unwrap();
doc["project"]["items"]["73"]["name"] = json!("Revised cut");
write_doc(&edit, &doc);
let lock = fs::OpenOptions::new().create_new(true).read(true).write(true).open(folder.join(".writer.lock")).unwrap();
lock.lock().unwrap();
assert_eq!(save(&folder, &base, &edit).unwrap_err().kind(), io::ErrorKind::WouldBlock);
let reopened = tmp.path().join("reopened.fcproj");
assert_eq!(checkout(&folder, &reopened).unwrap(), base);
drop(lock);
assert_ne!(save(&folder, &base, &edit).unwrap(), base);
}
#[test]
fn checkout_refuses_an_invalid_live_revision() {
let tmp = tempdir().unwrap();
let source = tmp.path().join("source.fcproj");
let folder = tmp.path().join("project");
let export = tmp.path().join("export.fcproj");
write_doc(&source, &current());
pack(&source, &folder, atomic_write_new).unwrap();
let root = folder.join(ROOT);
let mut manifest: Value = serde_json::from_slice(&fs::read(&root).unwrap()).unwrap();
manifest["layout"] = json!(2);
manifest["revision"] = json!({"number": 1, "parent": "invalid digest", "bin_edits": {}, "item_edits": {}});
write_doc(&root, &manifest);
assert_eq!(checkout(&folder, &export).unwrap_err().kind(), io::ErrorKind::InvalidData);
assert!(!export.exists());
}
#[test]
fn trim_publishes_only_its_record_and_revision_metadata_and_rejects_a_stale_editor() {
let tmp = tempdir().unwrap();
let src = tmp.path().join("src.fcproj");
let folder = tmp.path().join("folder");
let edit = tmp.path().join("edit.fcproj");
let mut doc = current();
write_doc(&src, &doc);
pack(&src, &folder, atomic_write_new).unwrap();
let base = checkout(&folder, &edit).unwrap();
let first: Value = serde_json::from_slice(&fs::read(folder.join(ROOT)).unwrap()).unwrap();
assert_eq!(save(&folder, &base, &edit).unwrap(), base);
let duration = &mut doc["project"]["items"]["73"]["kind"]["Sequence"]["video_tracks"][0]["items"][0]["duration"];
*duration = json!(duration.as_i64().unwrap() / 2);
write_doc(&edit, &doc);
let mut writes = Vec::new();
let next = save_with(&folder, &base, records_from(&edit, &folder).unwrap(), |path, bytes| {
writes.push((path.file_name().unwrap().to_owned(), bytes.len()));
if path.ends_with(ROOT) { filmcraft_format::atomic_write(path, bytes) } else { atomic_write_new(path, bytes) }
})
.unwrap();
let second: Value = serde_json::from_slice(&fs::read(folder.join(ROOT)).unwrap()).unwrap();
let cut = second["items"].as_array().unwrap().iter().find(|r| r[0] == 73).unwrap();
let cut_size = serde_json::to_vec(&doc["project"]["items"]["73"]).unwrap().len();
assert_eq!(
writes,
vec![
(cut[1].as_str().unwrap().into(), cut_size),
(base.as_str().into(), serde_json::to_vec(&first).unwrap().len()),
(ROOT.into(), serde_json::to_vec(&second).unwrap().len())
]
);
assert_eq!(second["bins"], first["bins"]);
assert_eq!(second["envelope"], first["envelope"]);
assert_eq!(second["revision"]["item_edits"].as_object().unwrap().len(), 1);
let stamp = second["revision"]["item_edits"]["73"].clone();
assert!(stamp["utc_ms"].as_i64().unwrap() > 0);
assert_eq!(stamp["revision"], 1);
assert_eq!(second["revision"]["parent"], base);
assert!(save(&folder, &base, &src).unwrap_err().to_string().contains("stale"));
doc["project"]["items"]["21"]["name"] = json!("Another reel");
write_doc(&edit, &doc);
save(&folder, &next, &edit).unwrap();
let third: Value = serde_json::from_slice(&fs::read(folder.join(ROOT)).unwrap()).unwrap();
assert_eq!(third["revision"]["item_edits"]["73"], stamp);
assert_eq!(third["revision"]["item_edits"]["21"]["revision"], 2);
}
#[test]
fn moving_a_sequence_survives_writer_death_at_each_publication_boundary() {
// The subprocess exits without running any Rust destructors, including the writer guard.
const CHILD: &str = "FILMCRAFT_FOLDER_MOVE_EXIT_TEST";
if let Some(dir) = std::env::var_os(CHILD) {
let dir = Path::new(&dir);
let base = fs::read_to_string(dir.join("base")).unwrap();
let stop: usize = fs::read_to_string(dir.join("stop")).unwrap().parse().unwrap();
let folder = dir.join("folder");
let records = records_from(&dir.join("moved"), &folder).unwrap();
let mut count = 0;
save_with(&folder, &base, records, |path, bytes| {
if count == stop {
std::process::exit(85)
}
if path.ends_with(ROOT) {
filmcraft_format::atomic_write(path, bytes)?;
} else {
atomic_write_new(path, bytes)?;
}
count += 1;
if path.ends_with(ROOT) {
std::process::exit(86)
}
Ok(())
})
.unwrap();
panic!("child missed commit");
}
for stop in 0..=4 {
let tmp = tempdir().unwrap();
let dir = tmp.path();
let folder = dir.join("folder");
let old = current();
write_doc(&dir.join("input"), &old);
pack(&dir.join("input"), &folder, atomic_write_new).unwrap();
let base = checkout(&folder, &dir.join("initial")).unwrap();
fs::write(dir.join("base"), &base).unwrap();
fs::write(dir.join("stop"), stop.to_string()).unwrap();
let mut moved = old.clone();
let bin = &mut moved["project"]["root"]["children"][0]["Bin"];
let list = bin["children"].as_array_mut().unwrap();
let nested = list.iter_mut().find_map(|v| v.get_mut("Bin")).unwrap();
let item = nested["children"].as_array_mut().unwrap().pop().unwrap();
list.push(item);
write_doc(&dir.join("moved"), &moved);
let status = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", "project_folder::moving_a_sequence_survives_writer_death_at_each_publication_boundary"])
.env(CHILD, dir)
.status()
.unwrap();
assert_eq!(status.code(), Some(if stop < 4 { 85 } else { 86 }));
let reopened = dir.join("reopened");
unpack(&folder, &reopened).unwrap();
let doc: Value = serde_json::from_slice(&fs::read(reopened).unwrap()).unwrap();
assert_eq!(&doc, if stop < 4 { &old } else { &moved });
if stop < 4 {
let next = save(&folder, &base, &dir.join("moved")).unwrap();
let retried = dir.join("retried");
assert_eq!(checkout(&folder, &retried).unwrap(), next);
assert_eq!(serde_json::from_slice::<Value>(&fs::read(retried).unwrap()).unwrap(), moved);
}
}
}
+3 -2
View File
@@ -22,7 +22,7 @@ filmcraft-frame = { workspace = true }
craft-audio = { workspace = true, features = ["pcm-encode"] }
craft-media = { workspace = true }
craft-media-source = { workspace = true }
filmcraft-dng = { workspace = true }
filmcraft-dng = { workspace = true, features = ["serde"] }
craft-dpx = { workspace = true }
rayon = { workspace = true }
serde = { workspace = true }
@@ -31,6 +31,7 @@ image = { version = "0.25", default-features = false, features = ["png", "jpeg",
[dev-dependencies]
filmcraft-testkit = { workspace = true }
filmcraft-dng = { workspace = true, features = ["writer"] }
filmcraft-dng = { workspace = true, features = ["writer", "serde"] }
serde_json = { workspace = true }
# APNG fixtures for the animated-image tests (the image crate does not encode APNG)
png = "0.18"
+15
View File
@@ -16,6 +16,7 @@ pub mod digits;
pub mod dpx;
pub mod generators;
pub mod pending;
pub mod raw;
pub mod reader;
pub mod sequence;
pub mod still;
@@ -266,6 +267,16 @@ pub trait MediaSource: Send + Sync {
fn audio_stream(&self, stream: usize, start: i64, frames: usize, sample_rate: u32) -> Result<AudioBuffer> {
if stream == 0 { self.audio(start, frames, sample_rate) } else { Err(MediaError::NoStream("audio")) }
}
/// Camera raw sources (DNG stills and sequences, CinemaDNG in MXF): the as-shot white balance
/// and the settings in use. None for every other source.
fn raw_info(&self) -> Option<raw::RawInfo> {
None
}
/// Camera raw sources: the same media developed with `settings` (a new source; this one is
/// unchanged). None for every other source.
fn with_raw_settings(&self, _settings: &raw::RawSettings) -> Option<SharedSource> {
None
}
}
pub type SharedSource = Arc<dyn MediaSource>;
@@ -302,6 +313,10 @@ pub fn open_bytes(name: &str, bytes: Arc<[u8]>, extra: &[Opener]) -> Result<Shar
if wav::sniff(&bytes) {
return Ok(Arc::new(wav::WavSource::parse(name, bytes)?));
}
// a DNG is a TIFF too: develop its raw image instead of reading its preview
if still::dng::sniff(&bytes) {
return Ok(Arc::new(still::dng::DngStill::open(name, bytes, raw::RawSettings::default())?));
}
// APNG, animated GIF, and animated WebP play as movies (#402); single-frame files fall through to the stills
if let Some(r) = animated::from_bytes(name, bytes.clone()) {
return Ok(Arc::new(r?));
+153
View File
@@ -0,0 +1,153 @@
//! Camera raw source settings: how DNG footage (stills, CinemaDNG folders and CinemaDNG in MXF) is
//! developed. The parity reference is Premiere's Source Settings for camera raw formats (white
//! balance, exposure, highlights, decode quality, output colour space), taken from Adobe's public
//! help only. A project stores them per media item (`Interpretation::raw`); the media pool opens
//! the item's source and asks it for a copy developed with them
//! ([`crate::MediaSource::with_raw_settings`]).
//!
//! Reduced resolution: a [`crate::FrameRequest`] scale below 1 asks the DNG decoder for a smaller
//! picture ([`scale_level`]: the largest power-of-two fraction of the full size that still covers
//! the request), so playback at ½ or ¼ resolution develops less.
use serde::{Deserialize, Serialize};
pub use filmcraft_dng::{DemosaicQuality, Highlights, OutputSpace, WhiteBalance};
/// Exposure change limit in stops (either way).
pub const MAX_EXPOSURE: f64 = 8.0;
/// White balance temperature range in kelvin.
pub const TEMPERATURE_RANGE: (f64, f64) = (2000.0, 15_000.0);
/// White balance tint range (positive towards magenta).
pub const TINT_RANGE: (f64, f64) = (-150.0, 150.0);
/// Per-item camera raw settings. The default develops exactly as the file says.
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct RawSettings {
pub white_balance: WhiteBalance,
/// Exposure change in stops, added to the file's BaselineExposure.
pub exposure: f64,
pub highlights: Highlights,
pub demosaic: DemosaicQuality,
pub output: OutputSpace,
}
impl RawSettings {
/// The decoder options for these settings, developing at reduced-resolution `level`
/// ([`scale_level`]) of a `width` × `height` picture.
pub fn options(&self, width: u32, height: u32, level: u8) -> filmcraft_dng::ProcessOptions {
filmcraft_dng::ProcessOptions {
white_balance: self.white_balance,
exposure: if self.exposure.is_finite() { self.exposure.clamp(-MAX_EXPOSURE, MAX_EXPOSURE) } else { 0.0 },
highlights: self.highlights,
demosaic: self.demosaic,
output: self.output,
target_size: target_size(width, height, level),
apply_opcodes: false,
}
}
/// Whether every value is in range (finite, exposure within ±[`MAX_EXPOSURE`], white balance
/// within [`TEMPERATURE_RANGE`] and [`TINT_RANGE`]).
pub fn validate(&self) -> Result<(), String> {
if !self.exposure.is_finite() || self.exposure.abs() > MAX_EXPOSURE {
return Err(format!("exposure must be between -{MAX_EXPOSURE} and {MAX_EXPOSURE} stops"));
}
if let WhiteBalance::Custom { temperature, tint } = self.white_balance {
if !temperature.is_finite() || temperature < TEMPERATURE_RANGE.0 || temperature > TEMPERATURE_RANGE.1 {
return Err(format!("temperature must be between {} and {} K", TEMPERATURE_RANGE.0, TEMPERATURE_RANGE.1));
}
if !tint.is_finite() || tint < TINT_RANGE.0 || tint > TINT_RANGE.1 {
return Err(format!("tint must be between {} and {}", TINT_RANGE.0, TINT_RANGE.1));
}
}
Ok(())
}
}
/// What a camera raw source reports for its Source Settings.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct RawInfo {
/// The as-shot white balance as (temperature in kelvin, tint), where the file has the colour
/// calibration to say (the starting point of a custom white balance).
pub as_shot: Option<(f64, f64)>,
/// The settings the source develops with.
pub settings: RawSettings,
}
/// The reduced-resolution level for a request at `scale` of full size: 0 = full resolution, `k` =
/// 1 / 2^k (at most 1/16), the smallest power-of-two fraction that still covers `scale`.
pub fn scale_level(scale: f32) -> u8 {
if !scale.is_finite() || scale >= 1.0 {
return 0;
}
let mut k = 0u8;
while k < 4 && scale <= 1.0 / f32::from(1u8 << (k + 1)) {
k += 1;
}
k
}
/// The smallest picture the decoder must make at `level` of a `width` × `height` picture (None =
/// full resolution).
pub fn target_size(width: u32, height: u32, level: u8) -> Option<(usize, usize)> {
if level == 0 {
return None;
}
let d = 1u32 << level.min(4);
Some((width.div_ceil(d).max(1) as usize, height.div_ceil(d).max(1) as usize))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn levels_cover_the_request() {
assert_eq!(scale_level(1.0), 0);
assert_eq!(scale_level(2.0), 0);
assert_eq!(scale_level(f32::NAN), 0);
assert_eq!(scale_level(0.75), 0);
assert_eq!(scale_level(0.5), 1);
assert_eq!(scale_level(0.3), 1);
assert_eq!(scale_level(0.25), 2);
assert_eq!(scale_level(0.01), 4);
assert_eq!(scale_level(-1.0), 4);
assert_eq!(target_size(4096, 2160, 0), None);
assert_eq!(target_size(4096, 2160, 1), Some((2048, 1080)));
assert_eq!(target_size(15, 9, 2), Some((4, 3)));
assert_eq!(target_size(1, 1, 9), Some((1, 1)));
}
#[test]
fn settings_map_to_decoder_options() {
let s = RawSettings { exposure: 1.5, demosaic: DemosaicQuality::Fast, ..Default::default() };
let o = s.options(100, 50, 1);
assert_eq!((o.exposure, o.demosaic, o.target_size), (1.5, DemosaicQuality::Fast, Some((50, 25))));
assert_eq!(RawSettings::default().options(8, 8, 0), filmcraft_dng::ProcessOptions::default());
// hostile values never reach the decoder
assert_eq!(RawSettings { exposure: f64::INFINITY, ..Default::default() }.options(8, 8, 0).exposure, 0.0);
assert_eq!(RawSettings { exposure: 99.0, ..Default::default() }.options(8, 8, 0).exposure, MAX_EXPOSURE);
}
#[test]
fn validation() {
assert!(RawSettings::default().validate().is_ok());
assert!(RawSettings { exposure: f64::NAN, ..Default::default() }.validate().is_err());
assert!(RawSettings { exposure: -9.0, ..Default::default() }.validate().is_err());
let wb = |temperature, tint| RawSettings { white_balance: WhiteBalance::Custom { temperature, tint }, ..Default::default() };
assert!(wb(5600.0, 10.0).validate().is_ok());
assert!(wb(500.0, 0.0).validate().is_err());
assert!(wb(5600.0, 151.0).validate().is_err());
assert!(wb(f64::NAN, 0.0).validate().is_err());
}
#[test]
fn serde_defaults_and_shape() {
let s: RawSettings = serde_json::from_str("{}").unwrap();
assert_eq!(s, RawSettings::default());
let s = RawSettings { white_balance: WhiteBalance::Custom { temperature: 3200.0, tint: -5.0 }, exposure: 0.5, ..Default::default() };
let j = serde_json::to_string(&s).unwrap();
assert_eq!(serde_json::from_str::<RawSettings>(&j).unwrap(), s);
}
}
+37 -12
View File
@@ -9,13 +9,16 @@
//! nearest later frame before the first).
//! - The frame rate is the caller's (Settings ▸ Media ▸ Indeterminate Media Timebase), except for
//! CinemaDNG: a frame rate and start time code in the first frame's tags are the sequence's.
//! - DNG frames are developed with the item's camera raw settings ([`crate::raw`]), at reduced
//! resolution when the request's scale allows.
use std::sync::Arc;
use filmcraft_frame::{AudioBuffer, VideoFrame};
use filmcraft_time::FrameRate;
use crate::{FrameCache, FrameRequest, MediaError, MediaInfo, MediaKind, MediaSource, Result, VideoStreamInfo};
use crate::raw::{RawInfo, RawSettings};
use crate::{FrameCache, FrameRequest, MediaError, MediaInfo, MediaKind, MediaSource, Result, SharedSource, VideoStreamInfo};
/// Reads a file's bytes (the host's file access).
pub type FrameLoader = Arc<dyn Fn(&str) -> std::io::Result<Vec<u8>> + Send + Sync>;
@@ -125,18 +128,27 @@ pub struct ImageSequenceSource {
info: MediaInfo,
frames: Vec<Option<String>>,
loader: FrameLoader,
cache: FrameCache<usize>,
/// Developed frames by (index, reduced-resolution level; 0 unless camera raw).
cache: FrameCache<(usize, u8)>,
/// DNG frames: the raw settings they are developed with and the first frame's as-shot white.
raw: Option<RawInfo>,
}
impl ImageSequenceSource {
/// `frames`: path per frame (`None`: missing). The first present frame is decoded now (size,
/// alpha); the rest on demand.
pub fn new(name: &str, frames: Vec<Option<String>>, rate: FrameRate, loader: FrameLoader) -> Result<Self> {
Self::with_settings(name, frames, rate, loader, RawSettings::default())
}
/// [`Self::new`] developing DNG frames with raw `settings` (other formats ignore them).
pub fn with_settings(name: &str, frames: Vec<Option<String>>, rate: FrameRate, loader: FrameLoader, settings: RawSettings) -> Result<Self> {
let first = frames.iter().flatten().next().ok_or_else(|| MediaError::Offline(format!("{name}: no frames")))?.clone();
let bytes = loader(&first).map_err(|e| {
if e.kind() == std::io::ErrorKind::NotFound { MediaError::Offline(format!("{first}: {e}")) } else { MediaError::Io(format!("{first}: {e}")) }
})?;
let (frame, has_alpha, pixel_format, timing) = decode_frame(&first, &bytes)?;
let (frame, has_alpha, pixel_format, timing) = decode_frame(&first, &bytes, &settings, 0)?;
let raw = timing.is_some().then(|| RawInfo { as_shot: crate::still::dng::as_shot(&bytes), settings });
let (w, h) = (frame.width, frame.height);
let (rate, start_timecode) = match timing {
Some(info) => crate::still::dng::sequence_timing(&info, rate),
@@ -167,8 +179,8 @@ impl ImageSequenceSource {
file_size: None,
};
let cache = FrameCache::new(256 << 20);
cache.insert(frames.iter().position(Option::is_some).unwrap_or(0), Arc::new(frame));
Ok(Self { info, frames, loader, cache })
cache.insert((frames.iter().position(Option::is_some).unwrap_or(0), 0), Arc::new(frame));
Ok(Self { info, frames, loader, cache, raw })
}
pub fn frame_count(&self) -> usize {
@@ -185,14 +197,16 @@ impl ImageSequenceSource {
self.frames.get(i).and_then(|f| f.as_deref())
}
fn decode(&self, i: usize) -> Result<Arc<VideoFrame>> {
if let Some(f) = self.cache.get(&i) {
fn decode(&self, i: usize, level: u8) -> Result<Arc<VideoFrame>> {
let level = if self.raw.is_some() { level } else { 0 };
if let Some(f) = self.cache.get(&(i, level)) {
return Ok(f);
}
let path = self.frames.get(i).and_then(|f| f.as_deref()).ok_or(MediaError::NoStream("video"))?;
let bytes = (self.loader)(path).map_err(|e| MediaError::Io(format!("{path}: {e}")))?;
let f = Arc::new(decode_frame(path, &bytes)?.0);
self.cache.insert(i, f.clone());
let settings = self.raw.map(|r| r.settings).unwrap_or_default();
let f = Arc::new(decode_frame(path, &bytes, &settings, level)?.0);
self.cache.insert((i, level), f.clone());
Ok(f)
}
}
@@ -208,8 +222,9 @@ impl MediaSource for ImageSequenceSource {
// the wanted frame, else the nearest earlier present frame, else the nearest later one
let candidates = (0..=want).rev().chain(want + 1..n);
let mut last_err = None;
let level = crate::raw::scale_level(req.scale);
for i in candidates.filter(|&i| self.frames[i].is_some()).take(8) {
match self.decode(i) {
match self.decode(i, level) {
Ok(f) => return Ok(f),
Err(e) => last_err = Some(e),
}
@@ -220,12 +235,22 @@ impl MediaSource for ImageSequenceSource {
fn audio(&self, _start: i64, _frames: usize, _sample_rate: u32) -> Result<AudioBuffer> {
Err(MediaError::NoStream("audio"))
}
fn raw_info(&self) -> Option<RawInfo> {
self.raw
}
fn with_raw_settings(&self, settings: &RawSettings) -> Option<SharedSource> {
self.raw?;
let s = Self::with_settings(&self.info.name, self.frames.clone(), self.info.frame_rate(), self.loader.clone(), *settings).ok()?;
Some(Arc::new(s))
}
}
/// Decode one frame file: OpenEXR, Radiance HDR and DNG camera raw as linear floats (DNG with its metadata, for
/// the sequence's timing), every other format through the still decoders as RGBA8. Returns the
/// frame, whether it has alpha, and its pixel format for the media info.
fn decode_frame(name: &str, bytes: &[u8]) -> Result<(VideoFrame, bool, String, Option<filmcraft_dng::Info>)> {
fn decode_frame(name: &str, bytes: &[u8], settings: &RawSettings, level: u8) -> Result<(VideoFrame, bool, String, Option<filmcraft_dng::Info>)> {
if crate::still::exr::sniff(bytes) {
let d = crate::still::exr::decode(name, bytes)?;
return Ok((d.frame, d.has_alpha, d.pixel_format, None));
@@ -235,7 +260,7 @@ fn decode_frame(name: &str, bytes: &[u8]) -> Result<(VideoFrame, bool, String, O
return Ok((frame, false, "RGB 32-bit float (RGBE)".to_string(), None));
}
if crate::still::dng::sniff(bytes) {
let d = crate::still::dng::decode(name, bytes)?;
let d = crate::still::dng::decode_with(name, bytes, settings, level)?;
return Ok((d.frame, false, d.pixel_format, Some(d.info)));
}
let img = crate::still::decode_raster(name, bytes)?;
-4
View File
@@ -254,10 +254,6 @@ pub struct StillSource {
impl StillSource {
pub fn decode(name: &str, bytes: &[u8]) -> Result<Self> {
// a DNG is a TIFF too: develop its raw image instead of reading its preview
if dng::sniff(bytes) {
return dng::still(name, bytes);
}
if hdr::sniff(bytes) {
return hdr::still(name, bytes);
}
+271 -38
View File
@@ -12,12 +12,26 @@
use std::sync::Arc;
use filmcraft_color::{ColorInfo, Transfer};
use filmcraft_frame::VideoFrame;
use filmcraft_frame::{AudioBuffer, VideoFrame};
use filmcraft_time::FrameRate;
use image::metadata::Orientation;
use super::{DEFAULT_STILL_DURATION, StillSource};
use crate::{MediaError, MediaInfo, MediaKind, Result, VideoStreamInfo};
use super::DEFAULT_STILL_DURATION;
use crate::raw::{self, RawInfo, RawSettings};
use crate::{FrameCache, FrameRequest, MediaError, MediaInfo, MediaKind, MediaSource, Result, SharedSource, VideoStreamInfo};
/// The codec name of DNG stills in the media info.
pub const CODEC: &str = "DNG";
/// The codec name of numbered DNG folders (CinemaDNG sequences).
pub const SEQUENCE_CODEC: &str = "DNG sequence";
/// The codec name of CinemaDNG in MXF.
pub const MXF_CODEC: &str = "CinemaDNG";
/// Whether media with this info is camera raw (developed by this module): a DNG still, a DNG
/// sequence or CinemaDNG in MXF.
pub fn is_camera_raw(info: &MediaInfo) -> bool {
info.video.as_ref().is_some_and(|v| matches!(v.codec.as_str(), CODEC | SEQUENCE_CODEC | MXF_CODEC))
}
/// Whether `b` is a DNG file.
pub fn sniff(b: &[u8]) -> bool {
@@ -25,7 +39,7 @@ pub fn sniff(b: &[u8]) -> bool {
}
/// The colour of developed frames: scene-linear light, Rec. 709 primaries.
const LINEAR_709: ColorInfo = ColorInfo { transfer: Transfer::Linear, ..ColorInfo::SRGB_FULL };
pub const LINEAR_709: ColorInfo = ColorInfo { transfer: Transfer::Linear, ..ColorInfo::SRGB_FULL };
/// A developed DNG frame.
pub struct Decoded {
@@ -43,53 +57,129 @@ fn error(name: &str, e: filmcraft_dng::Error) -> MediaError {
}
}
/// Develop a DNG file.
/// The pixel format shown in the media info, e.g. "Bayer 12-bit raw (lossless JPEG)".
pub fn pixel_format(i: &filmcraft_dng::Info) -> String {
let kind = if i.cfa { "Bayer" } else { "linear" };
format!("{kind} {}-bit raw ({})", i.bits, i.compression)
}
/// Read a DNG's metadata without developing it: the developed size, pixel format and tags (for
/// CinemaDNG in MXF, whose descriptor may not describe the picture).
pub fn probe(name: &str, bytes: &[u8]) -> Result<(u32, u32, String, filmcraft_dng::Info)> {
let i = filmcraft_dng::probe(bytes).map_err(|e| error(name, e))?;
let (Ok(w), Ok(h)) = (u32::try_from(i.width), u32::try_from(i.height)) else { return Err(MediaError::Decode(format!("{name}: picture too large"))) };
if w == 0 || h == 0 {
return Err(MediaError::Decode(format!("{name}: empty picture")));
}
Ok((w, h, pixel_format(&i), i))
}
/// Develop a DNG file as the file says, at full resolution.
pub fn decode(name: &str, bytes: &[u8]) -> Result<Decoded> {
let img = filmcraft_dng::decode(bytes).map_err(|e| error(name, e))?;
decode_with(name, bytes, &RawSettings::default(), 0)
}
/// Develop a DNG file with raw `settings` at reduced-resolution `level` ([`raw::scale_level`]: the
/// picture may be smaller than the file's, never smaller than 1 / 2^level of it).
pub fn decode_with(name: &str, bytes: &[u8], settings: &RawSettings, level: u8) -> Result<Decoded> {
let dng = filmcraft_dng::Dng::parse(bytes).map_err(|e| error(name, e))?;
let target = if level == 0 {
None
} else {
let i = dng.info().map_err(|e| error(name, e))?;
Some((u32::try_from(i.width).unwrap_or(u32::MAX), u32::try_from(i.height).unwrap_or(u32::MAX)))
};
let o = match target {
Some((w, h)) => settings.options(w, h, level),
None => settings.options(0, 0, 0),
};
let img = dng.develop_with(&o).map_err(|e| error(name, e))?;
let (w, h) = (u32::try_from(img.width), u32::try_from(img.height));
let (Ok(w), Ok(h)) = (w, h) else { return Err(MediaError::Decode(format!("{name}: picture too large"))) };
let i = &img.info;
let kind = if i.cfa { "Bayer" } else { "linear" };
let pixel_format = format!("{kind} {}-bit raw ({})", i.bits, i.compression);
let pixel_format = pixel_format(&img.info);
let mut frame = VideoFrame::rgba_f32(w, h, img.rgba);
frame.color = LINEAR_709;
Ok(Decoded { frame, pixel_format, info: img.info })
}
/// The size [`still`] reports for this file, from its metadata alone: the developed
/// (default-crop) size, read without developing a picture. DNG ignores EXIF
/// Orientation, so the decoder applies none.
/// The developed still's default-crop size, read without developing the picture.
/// DNG ignores EXIF orientation.
pub fn geometry(bytes: &[u8]) -> Option<(u32, u32, Orientation)> {
let info = filmcraft_dng::Dng::parse(bytes).ok()?.info().ok()?;
Some((u32::try_from(info.width).ok()?, u32::try_from(info.height).ok()?, Orientation::NoTransforms))
}
/// Open a DNG file as a still.
pub fn still(name: &str, bytes: &[u8]) -> Result<StillSource> {
let d = decode(name, bytes)?;
let info = MediaInfo {
name: name.to_string(),
kind: MediaKind::Still,
duration: DEFAULT_STILL_DURATION,
video: Some(VideoStreamInfo {
width: d.frame.width,
height: d.frame.height,
frame_rate: FrameRate::FPS_29_97,
par: (1, 1),
codec: "DNG".into(),
pixel_format: d.pixel_format,
color: LINEAR_709,
has_alpha: false,
bitrate: None,
hdr: None,
color_assumed: None,
}),
audio_streams: Vec::new(),
container: "Image".into(),
start_timecode: None,
file_size: Some(bytes.len() as u64),
};
Ok(StillSource { info, frame: Arc::new(d.frame), orientation: Orientation::NoTransforms })
/// The as-shot white balance of a DNG as (temperature in kelvin, tint), when it has the colour
/// calibration to say.
pub fn as_shot(bytes: &[u8]) -> Option<(f64, f64)> {
filmcraft_dng::Dng::parse(bytes).ok()?.as_shot_temperature_tint().ok().flatten()
}
/// A DNG still: developed with its raw settings, once per reduced-resolution level asked for.
pub struct DngStill {
info: MediaInfo,
bytes: Arc<[u8]>,
settings: RawSettings,
as_shot: Option<(f64, f64)>,
/// Developed pictures by level ([`raw::scale_level`]).
cache: FrameCache<u8>,
}
impl DngStill {
/// Develop `bytes` at full resolution with `settings` (an error if it cannot be developed).
pub fn open(name: &str, bytes: Arc<[u8]>, settings: RawSettings) -> Result<Self> {
let d = decode_with(name, &bytes, &settings, 0)?;
let info = MediaInfo {
name: name.to_string(),
kind: MediaKind::Still,
duration: DEFAULT_STILL_DURATION,
video: Some(VideoStreamInfo {
width: d.frame.width,
height: d.frame.height,
frame_rate: FrameRate::FPS_29_97,
par: (1, 1),
codec: CODEC.into(),
pixel_format: d.pixel_format,
color: LINEAR_709,
has_alpha: false,
bitrate: None,
hdr: None,
color_assumed: None,
}),
audio_streams: Vec::new(),
container: "Image".into(),
start_timecode: None,
file_size: Some(bytes.len() as u64),
};
let cache = FrameCache::new(512 << 20);
cache.insert(0, Arc::new(d.frame));
Ok(Self { info, as_shot: as_shot(&bytes), bytes, settings, cache })
}
}
impl MediaSource for DngStill {
fn info(&self) -> &MediaInfo {
&self.info
}
fn video_frame(&self, req: FrameRequest) -> Result<Arc<VideoFrame>> {
let level = raw::scale_level(req.scale);
if let Some(f) = self.cache.get(&level) {
return Ok(f);
}
let f = Arc::new(decode_with(&self.info.name, &self.bytes, &self.settings, level)?.frame);
self.cache.insert(level, f.clone());
Ok(f)
}
fn audio(&self, _start: i64, _frames: usize, _sample_rate: u32) -> Result<AudioBuffer> {
Err(MediaError::NoStream("audio"))
}
fn raw_info(&self) -> Option<RawInfo> {
Some(RawInfo { as_shot: self.as_shot, settings: self.settings })
}
fn with_raw_settings(&self, settings: &RawSettings) -> Option<SharedSource> {
// a file that developed once develops again; if not, the caller keeps this source
DngStill::open(&self.info.name, self.bytes.clone(), *settings).ok().map(|s| Arc::new(s) as SharedSource)
}
}
/// The frame rate and start time code (in frames at that rate) of a CinemaDNG sequence whose first
@@ -137,6 +227,13 @@ mod tests {
write(&px, &o)
}
fn red_at(f: &VideoFrame, x: usize, y: usize) -> f32 {
match &f.data {
PixelData::RgbaF32(p) => p[(y * f.width as usize + x) * 4],
_ => panic!("float frames"),
}
}
fn red(f: &VideoFrame) -> f32 {
match &f.data {
PixelData::RgbaF32(p) => p[(5 * 16 + 5) * 4],
@@ -205,6 +302,142 @@ mod tests {
}
}
#[test]
fn raw_settings_change_the_developed_still() {
let f: Arc<[u8]> = grey_dng(0.25, vec![]).into();
let src = crate::open_bytes("A001_C001_0001.dng", f.clone(), &[]).unwrap();
// no ColorMatrix: no as-shot temperature to offer, default settings in use
assert_eq!(src.raw_info(), Some(RawInfo { as_shot: None, settings: RawSettings::default() }));
let base = red(&src.video_frame(FrameRequest::full(filmcraft_time::Tick(0))).unwrap());
assert!((base - 0.25).abs() < 1e-3, "{base}");
// +1 stop doubles the scene-linear values, -2 quarters them
for (stops, factor) in [(1.0, 2.0), (-2.0, 0.25)] {
let s = src.with_raw_settings(&RawSettings { exposure: stops, ..Default::default() }).unwrap();
assert_eq!(s.raw_info().unwrap().settings.exposure, stops);
assert_eq!(s.info(), src.info());
let v = red(&s.video_frame(FrameRequest::full(filmcraft_time::Tick(0))).unwrap());
assert!((v - base * factor).abs() < 1e-3, "{stops}: {v}");
}
// the original source is unchanged
assert!((red(&src.video_frame(FrameRequest::full(filmcraft_time::Tick(0))).unwrap()) - base).abs() < 1e-6);
// the fast demosaic gives the same flat field
let fast = src.with_raw_settings(&RawSettings { demosaic: raw::DemosaicQuality::Fast, ..Default::default() }).unwrap();
assert!((red(&fast.video_frame(FrameRequest::full(filmcraft_time::Tick(0))).unwrap()) - base).abs() < 1e-3);
// other sources are not camera raw
let png = crate::still::StillSource::from_rgba("x.png", 2, 2, vec![0; 16], false, 16);
assert!(png.raw_info().is_none());
assert!(png.with_raw_settings(&RawSettings::default()).is_none());
assert!(is_camera_raw(src.info()));
assert!(!is_camera_raw(png.info()));
}
#[test]
fn reduced_resolution_requests_develop_smaller_pictures() {
let f: Arc<[u8]> = grey_dng(0.5, vec![]).into();
let src = crate::open_bytes("x.dng", f, &[]).unwrap();
let full = src.video_frame(FrameRequest::full(filmcraft_time::Tick(0))).unwrap();
assert_eq!((full.width, full.height), (16, 12));
// the decoder may develop a smaller picture, never one smaller than the request
let half = src.video_frame(FrameRequest { time: filmcraft_time::Tick(0), scale: 0.5 }).unwrap();
assert!((8..16).contains(&half.width) && (6..12).contains(&half.height), "{}x{}", half.width, half.height);
assert!((red_at(&half, 2, 2) - 0.5).abs() < 1e-3);
// the media info keeps the full size
assert_eq!(src.info().video.as_ref().unwrap().width, 16);
}
/// A 64 x 48 RGGB DNG with a sharp vertical edge at x = 32 and a horizontal ramp on each side.
fn edge_dng() -> Vec<u8> {
let (w, h) = (64usize, 48usize);
let neutral = [0.5, 1.0, 0.5];
let pat = [0usize, 1, 1, 2];
let px: Vec<u16> = (0..w * h)
.map(|i| {
let x = i % w;
let level = if x < 32 { 0.1 + 0.2 * (x as f64 / 32.0) } else { 0.7 + 0.2 * ((x - 32) as f64 / 32.0) };
(level * neutral[pat[(i / w % 2) * 2 + x % 2]] * 4095.0).round() as u16
})
.collect();
let o = Options {
width: w,
height: h,
bits: 12,
compression: Compression::LosslessJpeg { predictor: 1, components: 2, restart_lines: 0, pt: 0 },
raw_tags: vec![(tags::WHITE_LEVEL, Value::Short(vec![4095]))],
main_tags: vec![(tags::AS_SHOT_NEUTRAL, Value::rationals(&neutral))],
preview: true,
..Default::default()
};
write(&px, &o)
}
/// The picture is as sharp as developing the full frame and then averaging it down: at 1/2 and
/// 1/4 the reduced development differs from that box-filtered full development by under 0.01 on average
/// (at most 0.053, in the two columns beside the edge), has no gain error (the signed mean offset
/// is -0.0062 at both 1/2 and 1/4: one pixel of the 0.2 / 32 = 0.00625 per pixel ramp, a fixed sub-block
/// siting shift of the reduced path, independent of the level) and keeps the edge at least as steep.
#[test]
fn reduced_development_matches_the_box_filtered_full_picture() {
let bytes = edge_dng();
let src = crate::open_bytes("edge.dng", bytes.into(), &[]).unwrap();
let full = src.video_frame(FrameRequest::full(filmcraft_time::Tick(0))).unwrap();
for (scale, k) in [(0.5f32, 2usize), (0.25, 4)] {
let small = src.video_frame(FrameRequest { time: filmcraft_time::Tick(0), scale }).unwrap();
assert_eq!((small.width as usize * k, small.height as usize * k), (full.width as usize, full.height as usize), "1/{k}");
let (sw, sh) = (small.width as usize, small.height as usize);
let mut worst = 0.0f32;
let mut sum = 0.0f32;
let mut signed = 0.0f32;
for y in 0..sh {
for x in 0..sw {
let mut avg = 0.0;
for dy in 0..k {
for dx in 0..k {
avg += red_at(&full, x * k + dx, y * k + dy);
}
}
let d = red_at(&small, x, y) - avg / (k * k) as f32;
worst = worst.max(d.abs());
sum += d.abs();
signed += d;
}
}
// steepest step between neighbouring pixels in the middle row, in units of the picture's edge
let row = sh / 2;
let step_small = (1..sw).map(|x| (red_at(&small, x, row) - red_at(&small, x - 1, row)).abs()).fold(0.0f32, f32::max);
let step_full = (1..full.width as usize).map(|x| (red_at(&full, x, row * k) - red_at(&full, x - 1, row * k)).abs()).fold(0.0f32, f32::max);
// the edge is not softer than in the box-filtered full picture
assert!(step_small >= step_full, "1/{k}: edge step {step_small} < full {step_full}");
let mean = sum / (sw * sh) as f32;
assert!(mean < 0.01, "1/{k}: mean abs diff {mean}");
// measured -0.0062 at both 1/2 and 1/4 (the ramp slope, see above); the bound leaves
// 30 % margin, and since the mean level is about 0.5 it still catches a gain error of
// about 1.6 % (0.008 / 0.5) or more
let offset = signed / (sw * sh) as f32;
assert!(offset.abs() < 0.008, "1/{k}: signed mean offset {offset}");
assert!(worst < 0.06, "1/{k}: worst diff {worst}");
}
}
#[test]
fn raw_settings_reach_every_sequence_frame() {
let files: HashMap<String, Vec<u8>> = (0..2).map(|i| (format!("/c/B_{i:04}.dng"), grey_dng(0.1 + 0.2 * f64::from(i), vec![]))).collect();
let loader: FrameLoader =
Arc::new(move |p: &str| files.get(p).cloned().ok_or_else(|| std::io::Error::new(std::io::ErrorKind::NotFound, p.to_string())));
let frames = (0..2).map(|i| Some(format!("/c/B_{i:04}.dng"))).collect();
let s = ImageSequenceSource::new("B_0000.dng", frames, FrameRate::FPS_25, loader).unwrap();
assert_eq!(s.raw_info().unwrap().settings, RawSettings::default());
let bright = s.with_raw_settings(&RawSettings { exposure: 1.0, ..Default::default() }).unwrap();
assert_eq!(bright.info(), s.info());
for i in 0..2 {
let t = FrameRate::FPS_25.tick_of(i);
let (a, b) = (red(&s.video_frame(FrameRequest::full(t)).unwrap()), red(&bright.video_frame(FrameRequest::full(t)).unwrap()));
assert!((b - 2.0 * a).abs() < 1e-3, "frame {i}: {a} {b}");
}
let quarter = bright.video_frame(FrameRequest { time: FrameRate::FPS_25.tick_of(1), scale: 0.25 }).unwrap();
assert!((4..16).contains(&quarter.width) && quarter.height >= 3, "{}x{}", quarter.width, quarter.height);
assert!((red_at(&quarter, 1, 1) - 2.0 * 0.3).abs() < 1e-3);
}
#[test]
fn timing_without_cinemadng_tags_is_the_callers() {
let info = filmcraft_dng::probe(&grey_dng(0.5, vec![])).unwrap();
+8
View File
@@ -34,10 +34,18 @@ filmcraft-time = { workspace = true }
log = { workspace = true }
[target.'cfg(target_os = "macos")'.dependencies]
# pthread_set_qos_class_self_np for background job threads (thread_priority; MIT OR Apache-2.0,
# already in the lockfile)
libc = "0.2"
objc2-core-foundation = "0.3.2"
objc2-core-media = "0.3.2"
objc2-core-video = "0.3.2"
objc2-video-toolbox = "0.3.2"
# display_color: tag the window's Metal layer with the colour space FilmCraft draws in
objc2 = "0.6"
objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "NSApplication", "NSResponder", "NSWindow", "NSView", "NSColorSpace", "objc2-quartz-core", "objc2-core-graphics"] }
objc2-quartz-core = { version = "0.3.2", default-features = false, features = ["std", "CALayer", "CAMetalLayer", "objc2-core-graphics"] }
objc2-core-graphics = { version = "0.3.2", default-features = false, features = ["std", "CGColorSpace"] }
# Windows: Media Foundation decoder MFTs + Direct3D 11 / DXVA through the official `windows` bindings
# (MIT OR Apache-2.0; already in the lockfile through wgpu / winit).
+17 -3
View File
@@ -2,9 +2,11 @@
OS media integration for FilmCraft (layer L5): hardware video decoding through the operating
system's codecs, behind `filmcraft_codecs::VideoDecoder`, and hardware H.264 and H.265 (HEVC)
encoding, behind `filmcraft_export::VideoEncoder`. It holds OS media FFI and nothing else.
It is the one crate of the workspace allowed to contain `unsafe`, under the rules of
[ADR 0001](../../docs/adr/0001-platform-ffi.md) and [AGENTS.md](../../AGENTS.md) (rule 13, `unsafe` in `## This repository`).
encoding, behind `filmcraft_export::VideoEncoder`. It holds OS media FFI and, on macOS, the call
that lowers the priority of background job threads, and nothing else. It is the one crate of the
workspace allowed to contain `unsafe`, under the rules of
[ADR 0001](../../docs/adr/0001-platform-ffi.md), [ADR 0002](../../docs/adr/0002-background-thread-priority.md)
and [AGENTS.md](../../AGENTS.md) (rule 13, `unsafe` in `## This repository`).
```rust
// at startup (the desktop app, filmcraft-cli, the bench)
@@ -291,6 +293,18 @@ level 4 High tier, which many hardware decoders refuse; it is now level 4.1 Main
PQ / HLG, limited), and for PQ `mdcv` and `clli`; 8-bit SDR HEVC is unchanged and has no `colr`
(the VUI carries its description, as in the software H.264 path).
## Background job threads (macOS)
`register()` installs a call to `thread_priority::lower_current_thread` (a refusal is logged) as
the export crate's background-thread hook (`filmcraft_export::register_background_thread_start`). Each thread of the
pool that exports, the export queue, Render Previews and proxy jobs render on
(`filmcraft_export::on_own_threads`) runs it as it starts and drops to the lowest relative
priority (−15) of the default QoS class, so the monitors' frame workers (default class at 0) and
the main thread (user-interactive) get the cores first while the machine is busy. Not the utility
class: macOS runs that on the efficiency cores first, which made an export 15 % slower on an idle
machine. Threads those threads create start at the default class at 0 again, so decoders an export
opens keep their priority. Windows and Linux are not covered yet ([ADR 0002](../../docs/adr/0002-background-thread-priority.md)).
## Guarantees
- **Never undecodable:** the factory declines (returns `None`, so the software decoder is used)
+70
View File
@@ -0,0 +1,70 @@
//! The colour space of the window's picture, for the operating system's colour management.
//!
//! FilmCraft draws sRGB-encoded BT.709 pixels (the GPU resolve applies the sRGB curve; egui's UI
//! colours are sRGB). On macOS the window's `CAMetalLayer` has no colour space unless one is set,
//! and an untagged layer is shown without colour matching: its values go to the display as they
//! are, so on a wide-gamut (Display P3) screen BT.709 red is shown as P3 red, oversaturated
//! (#2115). wgpu configures the layer with a nil colour space for its sRGB surface colour space,
//! and does so again whenever it reconfigures the surface (a resize), so [`tag_windows_srgb`]
//! is called every frame and only acts on a layer that has none.
//!
//! This is an SDR choice. Settings ▸ Color ▸ Extended Dynamic Range Monitoring
//! (`color.extendedDynamicRange`) is not wired yet; when it is, an EDR surface needs an extended
//! colour space (and `wantsExtendedDynamicRangeContent`) on the layer instead, so this call has to
//! skip those layers or tag them differently, or it will clamp them back to SDR sRGB.
//!
//! The one non-media OS call in this crate after `cursor`: `crates/platform` is the only crate
//! allowed `unsafe` (AGENTS.md §0.3, ADR 0001), and walking a layer's sublayers is an `unsafe`
//! binding.
/// Tag the Metal layers of the app's windows that have no colour space with sRGB, so macOS colour
/// matches FilmCraft's picture to each display. Returns how many layers it tagged; elsewhere (and
/// off the main thread) it does nothing.
#[cfg(target_os = "macos")]
#[allow(unsafe_code)]
pub fn tag_windows_srgb() -> usize {
use objc2::MainThreadMarker;
use objc2_app_kit::{NSApplication, NSColorSpace};
use objc2_quartz_core::{CALayer, CAMetalLayer};
let Some(mtm) = MainThreadMarker::new() else { return 0 };
let Some(srgb) = NSColorSpace::sRGBColorSpace().CGColorSpace() else { return 0 };
let tag = |layer: &CALayer| -> usize {
match layer.downcast_ref::<CAMetalLayer>() {
Some(metal) if metal.colorspace().is_none() => {
metal.setColorspace(Some(&srgb));
1
}
_ => 0,
}
};
let mut tagged = 0;
for window in NSApplication::sharedApplication(mtm).windows().iter() {
let Some(root) = window.contentView().and_then(|v| v.layer()) else { continue };
tagged += tag(&root);
// wgpu (raw-window-metal) puts its CAMetalLayer as a sublayer of the view's layer.
// SAFETY: called on the main thread (`mtm`), reading the sublayers of a layer we hold a
// strong reference to; the array is retained and only read.
let subs = unsafe { root.sublayers() };
// a snapshot of retained layers: each stays alive while it is tagged, and a change to the
// layer tree meanwhile cannot invalidate the loop (enumerating a mutated NSArray panics)
for layer in subs.map(|a| a.to_vec()).unwrap_or_default() {
tagged += tag(&layer);
}
}
tagged
}
#[cfg(not(target_os = "macos"))]
pub fn tag_windows_srgb() -> usize {
0
}
#[cfg(test)]
mod tests {
/// Tests run off the main thread (and without windows elsewhere): nothing to tag, no panic.
#[test]
fn off_the_main_thread_it_tags_nothing() {
assert_eq!(std::thread::spawn(super::tag_windows_srgb).join().ok(), Some(0));
}
}
+10
View File
@@ -37,6 +37,7 @@ mod annexb;
#[cfg_attr(not(any(target_os = "windows", target_os = "linux")), allow(dead_code))]
mod biplanar;
pub mod cursor;
pub mod display_color;
#[cfg(target_os = "macos")]
pub mod hardware_encode;
pub mod hybrid;
@@ -46,6 +47,9 @@ pub mod media_foundation;
pub mod nvdec;
#[cfg(any(target_os = "windows", all(target_os = "linux", target_pointer_width = "64")))]
pub mod nvenc;
#[cfg(target_os = "macos")]
#[allow(unsafe_code)]
pub mod thread_priority;
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
pub mod vaapi;
#[cfg(target_os = "macos")]
@@ -78,6 +82,12 @@ pub fn register() -> Availability {
{
filmcraft_codecs::register_video_decoder(videotoolbox_factory);
filmcraft_export::register_encoder(hardware_encode::videotoolbox_encoder_factory);
filmcraft_export::register_background_thread_start(|| {
// a thread the system refuses to lower runs at the default priority, as before ADR 0002
if let Err(e) = thread_priority::lower_current_thread() {
log::debug!("could not lower a background thread's priority: {e}");
}
});
filmcraft_export::register_format_probe(filmcraft_export::Format::Hevc, hardware_encode::hevc_available);
// the probe creates a hardware session (about 0.1 s): answer it now, off the UI thread,
// before the first draw of the format list asks
+52
View File
@@ -0,0 +1,52 @@
//! Scheduling priority of background work (ADR 0002): the threads of an export, Render Previews or
//! proxy job ([`filmcraft_export::on_own_threads`]) run at the default quality-of-service class
//! with the lowest relative priority, below the monitors' frame workers (the default class at 0)
//! and the user-interactive main thread, so editing stays responsive while an export runs. Not the
//! utility class: macOS runs utility threads on the efficiency cores first, and an export of a
//! sequence with effects took 15 % longer on an idle M4 Max. A thread these threads create starts
//! at the default class at 0 again (macOS does not pass the class on), so decoders an export opens
//! keep their priority.
/// The relative priority of background job threads within the default class: the lowest
/// (`QOS_MIN_RELATIVE_PRIORITY`).
const RELATIVE_PRIORITY: i32 = -15;
/// Lower the calling thread below the default class's other threads. A thread the system refuses
/// stays as it was, and the error says why.
pub fn lower_current_thread() -> std::io::Result<()> {
// SAFETY: `pthread_set_qos_class_self_np` changes only the calling thread's own scheduling
// class; it takes two plain integers and has no memory-safety preconditions.
let r = unsafe { libc::pthread_set_qos_class_self_np(libc::qos_class_t::QOS_CLASS_DEFAULT, RELATIVE_PRIORITY) };
if r == 0 { Ok(()) } else { Err(std::io::Error::from_raw_os_error(r)) }
}
#[cfg(test)]
mod tests {
use super::*;
/// The calling thread's QoS class (as its raw value) and relative priority.
fn class() -> (u32, i32) {
let mut class = libc::qos_class_t::QOS_CLASS_UNSPECIFIED;
let mut relative = 0;
// SAFETY: `pthread_self` is the calling thread, alive for the call; both out-pointers are
// valid, writable locals.
let r = unsafe { libc::pthread_get_qos_class_np(libc::pthread_self(), &mut class, &mut relative) };
assert_eq!(r, 0);
(class as u32, relative)
}
#[test]
fn lowers_only_the_calling_thread() {
let default = libc::qos_class_t::QOS_CLASS_DEFAULT as u32;
std::thread::spawn(move || {
assert_eq!(class(), (default, 0));
lower_current_thread().unwrap();
assert_eq!(class(), (default, RELATIVE_PRIORITY));
// a thread it creates is not lowered with it
let child = std::thread::spawn(class).join().unwrap();
assert_eq!(child, (default, 0));
})
.join()
.unwrap();
}
}
+18 -2
View File
@@ -89,7 +89,7 @@ pub struct SearchBin {
}
/// The columns offered by the Find dialog, in its order (metadata fields after the built-ins).
pub const COLUMNS: [&str; 15] = [
pub const COLUMNS: [&str; 18] = [
"All",
"Name",
"Label",
@@ -105,10 +105,26 @@ pub const COLUMNS: [&str; 15] = [
"Log Note",
"Scene",
"Shot",
"Take",
"Client",
"Camera Angle",
];
/// An explicit stored-metadata selector. Strip exactly one prefix, so a key that itself
/// starts with `metadata:` remains addressable. No normalization of user keys is performed.
pub fn metadata_key(column: &str) -> Option<&str> {
column.strip_prefix("metadata:")
}
pub fn metadata_id(key: &str) -> String {
format!("metadata:{key}")
}
/// The text of one column of an item (empty when the item has no such value).
pub fn column_text(p: &Project, it: &ProjectItem, column: &str) -> String {
if let Some(key) = metadata_key(column) {
return it.metadata.get(key).cloned().unwrap_or_default();
}
let media = match &it.kind {
ItemKind::Media(m) => Some(m.as_ref()),
ItemKind::Subclip { parent, .. } => p.item(*parent).and_then(|x| x.as_media()),
@@ -138,7 +154,7 @@ pub fn column_text(p: &Project, it: &ProjectItem, column: &str) -> String {
Some(MediaRef::File { path }) => path.clone(),
_ => String::new(),
},
_ => it.metadata.iter().find(|(k, _)| k.eq_ignore_ascii_case(column)).map(|(_, v)| v.clone()).unwrap_or_default(),
_ => it.metadata.get(column).cloned().unwrap_or_default(),
}
}
+34 -15
View File
@@ -285,6 +285,12 @@ pub struct PinNode {
/// New bounds of every layer after pinning (same order as `nodes`). Targets are resolved before
/// the layers pinned to them; pins in a cycle, or to a missing layer, are ignored.
pub fn resolve_pins(nodes: &[PinNode], frame: [f64; 4]) -> Vec<[f64; 4]> {
resolve_pins_counting(nodes, frame, &mut 0)
}
/// [`resolve_pins`], adding to `steps` once per layer visited while following pins, so a test
/// can bound the work without timing it.
fn resolve_pins_counting(nodes: &[PinNode], frame: [f64; 4], steps: &mut usize) -> Vec<[f64; 4]> {
let mut out: Vec<Option<[f64; 4]>> = vec![None; nodes.len()];
// first layer with each uid, as the linear search found it
let mut by_uid = std::collections::HashMap::with_capacity(nodes.len());
@@ -310,6 +316,7 @@ pub fn resolve_pins(nodes: &[PinNode], frame: [f64; 4]) -> Vec<[f64; 4]> {
for start in 0..nodes.len() {
let mut i = start;
let (mut b, cacheable) = loop {
*steps += 1;
if let Some(b) = out[i] {
break (b, true);
}
@@ -533,7 +540,7 @@ pub fn remap_time(m: &GraphicMeta, u: Tick, d: Tick) -> Tick {
m.design_in + Tick(local)
}
/// A source graphic (Graphics and Titles ▸ Upgrade to Source Graphic): the layers and settings
/// A source graphic (Graphics ▸ Upgrade to Source Graphic): the layers and settings
/// shared by every clip of one project item. Editing one instance updates the others.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
@@ -625,20 +632,32 @@ mod tests {
#[test]
fn a_long_pin_chain_resolves_without_deep_recursion() {
// layer k is pinned to layer k + 1: a 200k-long acyclic chain from a template
let n = 200_000u64;
let b = [0.0, 0.0, 10.0, 10.0];
let nodes: Vec<PinNode> = (1..=n)
.map(|uid| PinNode { uid, pin: (uid < n).then(|| Pin::new(PinTarget::Layer(uid + 1), [true; 4], b, b)), bounds: b, resizable: true })
.collect();
let t = std::time::Instant::now();
let out = std::thread::Builder::new().stack_size(256 << 10).spawn(move || resolve_pins(&nodes, [0.0; 4])).unwrap().join().unwrap();
assert_eq!(out.len(), n as usize);
// Coverage instrumentation can slow this allocation- and hash-map-heavy stress test
// substantially. Keep the normal performance budget strict, with a bounded allowance
// only for instrumented runs (the shared SonarCloud workflow sets LLVM_PROFILE_FILE).
let budget = if std::env::var_os("LLVM_PROFILE_FILE").is_some() { 30 } else { 10 };
assert!(t.elapsed().as_secs() < budget, "{:?} (budget: {budget}s)", t.elapsed());
// layer k is pinned to layer k + 1: an n-long acyclic chain from a template, resolved on a
// small stack, with the number of layers visited counted rather than the time taken
let resolve = |n: u64| {
let b = [0.0, 0.0, 10.0, 10.0];
let nodes: Vec<PinNode> = (1..=n)
.map(|uid| PinNode { uid, pin: (uid < n).then(|| Pin::new(PinTarget::Layer(uid + 1), [true; 4], b, b)), bounds: b, resizable: true })
.collect();
std::thread::Builder::new()
.stack_size(256 << 10)
.spawn(move || {
let mut steps = 0;
(resolve_pins_counting(&nodes, [0.0; 4], &mut steps), steps)
})
.unwrap()
.join()
.unwrap()
};
// Following the chain from every layer would take about n * n / 2 visits. The depth limit
// keeps each layer to about one chain's length, whatever the host's speed. The shorter
// chain comes first so that a quadratic walk fails here in seconds instead of stalling.
for n in [20_000u64, 200_000] {
let (out, steps) = resolve(n);
assert_eq!(out.len(), n as usize);
let per_layer = 2 * MAX_PIN_CHAIN;
assert!(steps <= per_layer * n as usize, "{steps} visits for {n} layers (at most {per_layer} each)");
}
}
#[test]
+4
View File
@@ -28,6 +28,10 @@ pub struct Interpretation {
/// is edited into a sequence. None = one stereo clip of the first two channels.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub audio_channels: Option<AudioChannelMap>,
/// Clip ▸ Source Settings… for camera raw footage (DNG stills, CinemaDNG folders and MXF):
/// how the raw pictures are developed. None = as the file says.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub raw: Option<filmcraft_media::raw::RawSettings>,
}
/// Modify ▸ Audio Channels: the clip channel format and, per audio clip, the source channels it
+4 -3
View File
@@ -47,7 +47,8 @@ pub use mixer::{AutomationMode, InputMap, MixerStrip, TrackSend};
pub use multicam::{Camera, MergedClip, MulticamAudio, MulticamSel, MulticamSource};
pub use narration::{Narration, VocalPitch};
pub use script::{
ScriptColor, ScriptDocument, ScriptLine, ScriptLineColor, ScriptLineId, ScriptMark, ScriptMarkId, ScriptSlate, ScriptSlateId, ScriptTake, ScriptTakeId,
ScriptColor, ScriptDocument, ScriptElement, ScriptLine, ScriptLineColor, ScriptLineId, ScriptMark, ScriptMarkId, ScriptSlate, ScriptSlateId, ScriptTake,
ScriptTakeId,
};
pub use transcript::{Speaker, Transcript, Word};
@@ -79,7 +80,7 @@ pub use source::resolve_auto_points;
pub use track::{
AudioChannels, FieldOptions, FieldProcessing, Marker, MarkerKind, TimeInterpolation, Track, TrackItem, TrackKind, Transition, TransitionAlign,
};
pub use view::{MAX_LUT_TEXT_BYTES, ProjectLut, ProjectView, SequenceView};
pub use view::{MAX_LUT_TEXT_BYTES, ProjectLut, ProjectView, ScriptTabsView, SequenceView};
id_type!(ItemId);
id_type!(BinId);
id_type!(TrackId);
@@ -112,7 +113,7 @@ pub struct Project {
/// Schema v11.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub search_bins: Vec<SearchBin>,
/// Source graphics (Graphics and Titles ▸ Upgrade to Source Graphic): shared layers by
/// Source graphics (Graphics ▸ Upgrade to Source Graphic): shared layers by
/// project item. Schema v12.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub source_graphics: BTreeMap<ItemId, SourceGraphic>,
+44 -1
View File
@@ -35,6 +35,10 @@ pub enum ScriptColor {
}
impl ScriptColor {
fn is_default(&self) -> bool {
*self == Self::Default
}
pub const ALL: [Self; 19] = [
Self::Default,
Self::White,
@@ -118,11 +122,34 @@ script_id!(ScriptSlateId);
script_id!(ScriptTakeId);
script_id!(ScriptMarkId);
/// Screenplay formatting attached to a logical row, independent of its production labels.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum ScriptElement {
SceneHeading,
Action,
Character,
Dialogue,
Parenthetical,
Transition,
}
impl ScriptElement {
/// Default for a new row entered after a typed screenplay element.
pub fn following(self) -> Self {
match self {
Self::Character | Self::Parenthetical | Self::Dialogue => Self::Dialogue,
Self::SceneHeading | Self::Transition | Self::Action => Self::Action,
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ScriptLine {
pub id: ScriptLineId,
pub text: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub element: Option<ScriptElement>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub scene: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub page: Option<String>,
@@ -170,6 +197,9 @@ pub struct ScriptTake {
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ScriptSlate {
pub id: ScriptSlateId,
/// Default follows the theme outline. Each take and row retains its own fill.
#[serde(default, skip_serializing_if = "ScriptColor::is_default")]
pub outline_color: ScriptColor,
pub name: String,
/// Optional independent row for the setup thumbnail; defaults to its first candle.
#[serde(default, skip_serializing_if = "Option::is_none")]
@@ -188,6 +218,9 @@ pub struct ScriptDocument {
}
impl ScriptDocument {
/// Editable setup rows above the writing position in a new screenplay.
pub const LEADING_SETUP_ROWS: usize = 4;
/// Maximum accepted plain text size and logical line count. Source text is untrusted input.
pub const MAX_TEXT_BYTES: usize = 4 * 1024 * 1024;
pub const MAX_LINES: usize = 50_000;
@@ -225,7 +258,7 @@ impl ScriptDocument {
if content.len() > Self::MAX_LINE_BYTES {
return Err("a script line exceeds the 16 KiB limit");
}
doc.lines.push(ScriptLine { id, text: content.to_owned(), scene: None, page: None });
doc.lines.push(ScriptLine { id, text: content.to_owned(), element: None, scene: None, page: None });
}
Ok(doc)
}
@@ -453,6 +486,14 @@ impl ScriptDocument {
mod tests {
use super::*;
#[test]
fn legacy_row_labels_and_indentation_round_trip_without_a_role() {
let legacy = serde_json::json!({"id":1,"text":" A line","scene":"1A","page":"3"});
let row: ScriptLine = serde_json::from_value(legacy.clone()).unwrap();
assert!(row.element.is_none());
assert_eq!(serde_json::to_value(row).unwrap(), legacy);
}
#[test]
fn text_import_preserves_logical_rows() {
let doc = ScriptDocument::from_text("\u{feff} A\r\n\r\nA\n").unwrap();
@@ -465,6 +506,7 @@ mod tests {
fn deleting_a_line_discards_its_marks_but_keeps_remaining_coverage() {
let mut doc = ScriptDocument::from_text("one\ntwo\nthree").unwrap();
doc.slates.push(ScriptSlate {
outline_color: ScriptColor::Default,
id: ScriptSlateId(4),
name: "setup".into(),
thumbnail_line: None,
@@ -503,6 +545,7 @@ mod tests {
assert!(doc.validate().is_err());
doc.next_id = 4;
doc.slates.push(ScriptSlate {
outline_color: ScriptColor::Default,
id: ScriptSlateId(3),
name: "setup".into(),
thumbnail_line: None,
+37
View File
@@ -354,6 +354,43 @@ impl Track {
let idx = self.items.partition_point(|i| i.start <= t);
idx.checked_sub(1).map(|i| &self.items[i]).filter(|i| t < i.end())
}
/// A one-sided audio fade can span several pieces after a multicamera switch.
/// Follow contiguous pieces of the same source so a shortened fade can grow again.
pub fn multicam_fade_span(&self, fade: &Transition) -> Option<TimeRange> {
if self.kind != TrackKind::Audio {
return None;
}
let (anchor, incoming) = match (fade.from, fade.to) {
(None, Some(id)) => (id, true),
(Some(id), None) => (id, false),
_ => return None,
};
let index = self.items.iter().position(|item| item.id == anchor)?;
let item = &self.items[index];
item.multicam.as_ref()?;
let continues = |a: &TrackItem, b: &TrackItem| {
a.end() == b.start
&& a.item == b.item
&& a.multicam.is_some()
&& b.multicam.is_some()
&& a.speed == b.speed
&& a.reverse == b.reverse
&& a.frame_hold == b.frame_hold
&& a.source_time_at(b.start).0.abs_diff(b.source_time_at(b.start).0) <= 1
};
let (mut first, mut last) = (index, index);
if incoming {
while self.items.get(last + 1).is_some_and(|next| continues(&self.items[last], next)) {
last += 1;
}
} else {
while first > 0 && continues(&self.items[first - 1], &self.items[first]) {
first -= 1;
}
}
Some(TimeRange::from_bounds(self.items[first].start, self.items[last].end()))
}
pub fn item(&self, id: ClipId) -> Option<&TrackItem> {
self.items.iter().find(|i| i.id == id)
}
+23 -1
View File
@@ -36,11 +36,33 @@ impl SequenceView {
}
}
/// What was open when a project was saved: the Timeline's sequence tabs in order, the active one,
/// Open Lined Script tabs in order and the selected tab. A null ID denotes the internal Help
/// script. Only tab identities belong here, never a copy of the practice document.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct ScriptTabsView {
pub open: Vec<Option<ItemId>>,
pub active: Option<ItemId>,
}
impl ScriptTabsView {
pub fn checked(mut self, project: &super::Project) -> Self {
let mut seen = std::collections::HashSet::new();
self.open.retain(|tab| tab.is_none_or(|id| project.item(id).is_some_and(|item| item.as_script().is_some())) && seen.insert(*tab));
if !self.open.contains(&self.active) {
self.active = self.open.first().copied().flatten();
}
self
}
}
/// What was open when a project was saved: the Lined Script tabs, the Timeline's sequence tabs,
/// how each sequence was shown and where its playhead was. Stored beside the project in its file,
/// not in it: it is not part of the edit and never an undo step.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct ProjectView {
#[serde(default)]
pub script_tabs: ScriptTabsView,
#[serde(default)]
pub open_sequences: Vec<ItemId>,
#[serde(default)]
+25 -8
View File
@@ -107,15 +107,35 @@ pub(crate) fn track_input_at(
let live =
ClipLive { vol: ovs.get(&(track.id, CLIP_LANE_VOLUME.to_string())).copied(), pan: ovs.get(&(track.id, CLIP_LANE_PAN.to_string())).copied(), depth };
let range = TimeRange::from_bounds(Tick::from_units(start, sr as i64), Tick::from_units(start + frames as i64, sr as i64));
let mut tbuf = AudioBuffer::silence(sr, w, frames);
let mut dry = AudioBuffer::silence(sr, w, frames);
for item in track.items.iter().filter(|i| i.enabled && i.range().overlaps(&range)) {
mix_item(project, item, item, win, sources, &mut tbuf, &live);
mix_item(project, item, item, win, sources, &mut dry, &live);
}
// audio transitions: attenuate the covered region of each side
// Each transition replaces its span in track order. Keep the underlying clip mix
// available so an overlapping fade always starts from the audio of the active piece.
let mut transitioned = None;
for tr in &track.transitions {
if !tr.range().overlaps(&range) {
continue;
}
let output = transitioned.get_or_insert_with(|| dry.clone());
// A one-sided fade across multicamera edits follows what each piece actually
// plays. Reading only the anchor's handles would play its angle over later cuts.
if let Some(span) = track.multicam_fade_span(tr) {
let fade_start = tr.start.to_units_floor(sr as i64);
let duration = tr.duration.to_units_floor(sr as i64).max(1) as f32;
let first = start.max(fade_start).max(span.start.to_units_floor(sr as i64));
let end = (start + frames as i64).min(tr.end().to_units_floor(sr as i64)).min(span.end().to_units_floor(sr as i64));
for sample in first..end {
let (outgoing, incoming) = transitions::audio_gains(&tr.effect.effect, (sample - fade_start) as f32 / duration);
let gain = if tr.to.is_some() { incoming } else { outgoing };
let i = (sample - start) as usize;
for (dst, src) in output.channels.iter_mut().zip(&dry.channels) {
dst[i] = src[i] * gain;
}
}
continue;
}
// Re-mix: recompute the covered samples with crossfade gains. Both sides play over the
// whole transition, into their handles as the picture does, so a transition centred on a
// cut overlaps the two clips instead of only fading each on its own side of the cut.
@@ -129,9 +149,6 @@ pub(crate) fn track_input_at(
}
let n = (s1 - s0) as usize;
let off = (s0 - start) as usize;
for ch in tbuf.channels.iter_mut() {
ch[off..off + n].fill(0.0);
}
let mut a = AudioBuffer::silence(sr, w, n);
let mut b = AudioBuffer::silence(sr, w, n);
if let (Some(f), Some(orig)) = (&from, from_src) {
@@ -146,11 +163,11 @@ pub(crate) fn track_input_at(
let p = (base + i as f32) / dur;
let (ga, gb) = transitions::audio_gains(&tr.effect.effect, p);
for c in 0..w {
tbuf.channels[c][off + i] += a.channels[c][i] * ga + b.channels[c][i] * gb;
output.channels[c][off + i] = a.channels[c][i] * ga + b.channels[c][i] * gb;
}
}
}
tbuf
transitioned.unwrap_or(dry)
}
/// `item` lengthened to cover `[t0, t1)` with its media timing unchanged: the part before its in
+2
View File
@@ -64,6 +64,8 @@ filmcraft-interchange = { workspace = true }
# test root needs explicitly so glyph and accessibility assertions run against the bundled faces.
egui = { workspace = true, features = ["default_fonts", "monochrome_emoji_fonts"] }
egui_kittest = { workspace = true, features = ["eframe", "wgpu"] }
# synthetic DNG footage for the Source Settings dialog test
filmcraft-dng = { workspace = true, features = ["writer"] }
tempfile = "3"
# build.rs bakes contributors/contributors.json into the binary (About ▸ Contributors).
+8 -10
View File
@@ -3,21 +3,19 @@
The egui frontend draws panels and dialogs, and dispatches project changes through the engine.
Interactive controls keep stable automation ids regardless of the interface language.
## Script coverage
## Lined Script coverage
Before a script is created or imported, the Script panel shows a short getting-started guide for
text import, Project clip drops, candle coverage and Source playback, and frame-linked marks.
The guide wraps and scrolls in small panels and disappears when a script is open. A ? button at the
right of the Script toolbar opens the same guide in a scrollable help popover at any time.
Lined Script opens project items in tabs. Its internal Help tab appears when the last script closes and can be reopened from the question-mark menu. Practice edits and marks reset when the user leaves Help.
USER asks HELP how to use a lined script. HELP walks through four numbered steps in dialogue.
The scene wraps and scrolls in small panels. The **?** button includes quick instructions and a link to the [Lined Script guide](../../docs/lined-script.md).
Toolbar controls wrap onto additional rows when the panel is narrow, keeping Scene/Page labels
with their menus and placing search and the document below the measured toolbar height.
Plain text copied from another app can be pasted directly into Script. With no script open,
paste creates a script; otherwise it inserts rows after the selected range (or appends).
Plain text copied from another app can be pasted directly into Lined Script. Paste inserts rows after the selected range (or appends). Choose **Blank** first to keep pasted text as a project script.
While editing a row, paste replaces the text selection at the caret. Each hard line break
adds a row, including blank and terminal rows, with CRLF treated as one break. Later rows
retain stable IDs, labels, candles and marks. A single Undo removes the paste while keeping
text typed beforehand. Clicking outside a Script text field commits the edit and releases input
text typed beforehand. Clicking outside a Lined Script text field commits the edit and releases input
focus, including clicks into blank canvas or another panel. Oversized text, lines and invalid
offsets fail before any paste edit.
@@ -27,7 +25,7 @@ Hidden marks cannot be selected or used to cue Source and do not choose the defa
Scene and Page menus retain repeated labels as separate navigation points in script order.
Double-clicking a candle, its mark or a setup thumbnail cues the linked clip and activates Source
for playback shortcuts. Thumbnails open the displayed candle at its thumbnail frame (or first
visible mark, then source start). A single mark click cues Source while retaining Script editing focus.
visible mark, then source start). A single mark click cues Source while retaining Lined Script editing focus.
Setup thumbnails and take-number boxes sit above the first covered row; candle caps, endpoint
handles, off-screen notation and marks align with that row, including blank and wrapped lines.
Candles extend to the exact top and bottom boundaries of their covered rows. The short gray end
@@ -60,7 +58,7 @@ or fingerprint, only the targeted candle can be identified safely. `script.rebin
this batch behavior through optional `allMatching:true`; its default remains a single take.
Script `layout.rs` shares row measurements and candle geometry across painting, endpoint targets and
off-screen notation. `selection.rs` owns document-local state transitions: switching scripts through
the toolbar, commands, creation/import or Find in Script clears old edits, drags and replacement
the toolbar, commands, creation/import or Find in Lined Script clears old edits, drags and replacement
confirmations while retaining view preferences and the section clipboard.
The `script_ui` integration tests cover endpoint drags, hidden-mark targets and repeated labels;
engine tests cover saved data, undo/redo, section copies and deleting hidden lines.
+2 -2
View File
@@ -23,7 +23,7 @@ use std::time::{Duration, Instant};
use filmcraft_engine::Session;
use filmcraft_project::{ItemId, ParamValue, Project, SequenceSettings, TrackKind, find_effect, resolve_auto_points};
use filmcraft_time::{FrameRate, Tick, TimeRange};
use filmcraft_ui_egui::frames::{FrameKey, FrameServer, JobRecord, PREROLL_TIMEOUT_S, PlaybackMeter, Target, process_cpu_time, thread_cpu_time};
use filmcraft_ui_egui::frames::{FrameKey, FrameServer, JobRecord, Lookback, PREROLL_TIMEOUT_S, PlaybackMeter, Target, process_cpu_time, thread_cpu_time};
use serde_json::{Value, json};
use crate::fixtures::fixture;
@@ -151,7 +151,7 @@ impl Display {
if let Some((comp, dev)) = self.gpu.as_mut() {
let plan = server.get_plan(&key).map(|p| (key, p));
exact = plan.is_some();
if let Some((k, plan)) = plan.or_else(|| server.nearest_plan(key, 6))
if let Some((k, plan)) = plan.or_else(|| server.nearest_plan(key, Lookback::backward(6)))
&& self.last != Some(k)
{
let before = comp.uploaded_bytes;
+19 -4
View File
@@ -19,10 +19,14 @@ mod window;
impl FilmcraftApp {
/// Build the app around one shared `FrameServer`, falling back to the default language on an unparsable preference, loading workspaces from the prefs
/// directory and seeding IME epoch/sequence identity.
pub fn new(mut session: Session) -> Self {
pub fn new(session: Session) -> Self {
let frames = Arc::new(FrameServer::new(session.media.clone(), session.services.clone(), session.previews.clone(), FrameServer::default_workers()));
Self::with_frames(session, frames)
}
pub(crate) fn with_frames(mut session: Session, frames: Arc<FrameServer>) -> Self {
session.shortcuts.register_external(menus::external_commands());
let recovery = !session.recovery_candidates().is_empty();
let frames = Arc::new(FrameServer::new(session.media.clone(), session.services.clone(), session.previews.clone(), FrameServer::default_workers()));
let workspaces =
session.prefs_path.as_ref().and_then(|p| p.parent()).map(|d| dock::WorkspacePrefs::load(&d.join(dock::WORKSPACES_FILE))).unwrap_or_default();
let language = i18n::Language::parse(&session.prefs.general.interface_language).unwrap_or_default();
@@ -30,9 +34,11 @@ impl FilmcraftApp {
let ime_active_sequence = session.state.active_sequence;
Self {
session,
script_practice: None,
ui: UiState { language, ..UiState::default() },
tokens: Tokens::for_kind(ThemeKind::Dark),
frames,
scope_worker: scope_worker::ScopeWorker::new(),
playback: Playback { speed: 1.0, ..Default::default() },
source_playback: Default::default(),
audio: None,
@@ -299,6 +305,7 @@ impl FilmcraftApp {
let _ = self.apply_dock(craft_behavior::dock::Action::activate(PanelKind::Timeline));
}
filmcraft_engine::Event::OpenSource(_) | filmcraft_engine::Event::CueSource(_) => {
panels::script::close_example(self);
let cue = matches!(ev, filmcraft_engine::Event::CueSource(_));
let focused = self.ui.focused;
// a closed Source panel reopens, and another panel's maximize would hide it
@@ -334,7 +341,9 @@ impl FilmcraftApp {
self.logic_session_events();
self.logic_command_inbox(ctx);
self.advance_playback(ctx);
self.advance_source_playback(ctx);
if panels::script::with_example_monitor(self, |preview| preview.advance_source_playback(ctx)).is_none() {
self.advance_source_playback(ctx);
}
self.poll_jobs(ctx);
capture::drain(self, ctx);
capture::request_hidden_paint(self, ctx);
@@ -385,7 +394,7 @@ impl FilmcraftApp {
self.auto.begin_frame();
self.apply_prefs(&ctx);
self.sync_timeline_view();
self.ui.script.sync_project(&self.session.project_instance);
self.ui.script.sync_project(&self.session.project_instance, &self.session.state.script_tabs);
panels::metadata::follow_selection(self);
self.handle_drops(&ctx);
panels::script::finish_edit_on_click_away(self, &ctx);
@@ -406,6 +415,12 @@ impl FilmcraftApp {
self.playback.playing = false;
}
if !ctx.will_discard() {
if self.auto.find_current("script.tabs").is_none() {
self.ui.script.leave_practice();
}
if !self.ui.script.is_practicing() && panels::script::example_monitor(self).is_none() {
self.script_practice = None;
}
self.cancel_value_drag(&ctx);
}
self.error_window(ui.ctx());
+7 -2
View File
@@ -22,6 +22,9 @@ impl FilmcraftApp {
ctx.send_viewport_cmd(egui::ViewportCommand::Fullscreen(restore));
return;
}
if self.ui.clip_dialog.is_some() {
return;
}
if self.ui.focused == PanelKind::Script
&& panels::script::has_text_paste_undo(self)
&& ctx.text_edit_focused()
@@ -32,7 +35,9 @@ impl FilmcraftApp {
}
return;
}
let mut take_focused = false;
if self.ui.focused == PanelKind::Script && !ctx.text_edit_focused() && self.dialog.is_none() {
take_focused = panels::script::preview_arrow_keys(self, ctx);
let pasted = ctx.input_mut(|input| {
let mut pasted = Vec::new();
input.events.retain(|event| {
@@ -56,7 +61,7 @@ impl FilmcraftApp {
}
// The runtime keeps egui's focus on the framework stop or the hosted canvas a press reached,
// so egui's own `egui_wants_keyboard_input` would end every shortcut after a click on a panel.
if crate::framework::keyboard_taken(ctx) || self.dialog == Some(Dialog::Shortcuts) || self.ui.clip_dialog.is_some() {
if (!take_focused && crate::framework::keyboard_taken(ctx)) || self.dialog == Some(Dialog::Shortcuts) {
return;
}
// A focused text field takes every unmodified key, including the ones our shortest
@@ -87,7 +92,7 @@ impl FilmcraftApp {
// most specific chords still go first across both scopes (the sort is stable, so the
// panel still wins a tie). Before matching was exact, the Timeline's `Delete` (Clear)
// swallowed the app-wide `Shift+Delete` (Ripple Delete) this way (#680).
let focused = self.ui.focused.title();
let focused = self.ui.focused.context_name();
let mut fire = Vec::new();
let modifiers = i.modifiers;
// With no text on the system clipboard, egui-winit drops the Ctrl+V press but still
+13 -3
View File
@@ -94,7 +94,19 @@ impl FilmcraftApp {
}
pub fn thumbnail(&mut self, ctx: &egui::Context, item: filmcraft_project::ItemId, t: Tick, width: u32) -> Option<(egui::TextureId, egui::Vec2)> {
let pi = self.session.project.item(item)?;
self.thumbnail_in(ctx, self.session.project.clone(), item, t, width, self.item_revision(item))
}
pub(crate) fn thumbnail_in(
&mut self,
ctx: &egui::Context,
project: Arc<filmcraft_project::Project>,
item: filmcraft_project::ItemId,
t: Tick,
width: u32,
rev: u64,
) -> Option<(egui::TextureId, egui::Vec2)> {
let pi = project.item(item)?;
let src_w = match &pi.kind {
filmcraft_project::ItemKind::Media(m) => m.info.video.as_ref()?.width,
filmcraft_project::ItemKind::Sequence(s) => s.settings.width,
@@ -102,7 +114,6 @@ impl FilmcraftApp {
};
let rate = pi.frame_rate();
let frame = rate.frame_at(t);
let rev = self.item_revision(item);
let key = FrameKey { target: Target::Item(item), frame, size: width, revision: rev, draft: false };
let name = format!("thumb-{}-{}-{}", item.0, frame, width);
if let Some(img) = self.frames.get(&key) {
@@ -111,7 +122,6 @@ impl FilmcraftApp {
return Some((id, egui::vec2(img.w as f32, img.h as f32)));
}
let scale = width as f32 / src_w.max(1) as f32;
let project = self.session.project.clone();
self.frames.request(key, rate.tick_of(frame), scale, &project, 50);
let shown = self.texture_existing(&name);
if shown.is_some() {

Some files were not shown because too many files have changed in this diff Show More