Compare commits

...
238 Commits
Author SHA1 Message Date
c57541674d #188: regression test — a copied Graphic clip pastes at the playhead
Engine test from #205 (the shortcut half of that PR is superseded by #204).

Co-Authored-By: carlitosteso3 <carlitosteso3@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 20:36:21 -04:00
Brandon Thomas a4536bcfed Merge pull request #180 from SaymonMaster14/feat/windows-nvenc-h264
Windows: NVENC H.264 hardware encoding for Export (opt-in)
2026-10-07 18:17:05 -04:00
Brandon ThomasandClaude Opus 5.5 853f03b1aa M-HW: NVENC on top of the shared hardware-encoding setting (#183); never-crash fixes
Merge origin/main into the NVENC branch. #183 already provides the
HardwareEncoding enum, ExportSettings.hardware_encoding, the
hardwareEncoding export param and the Export > Video > Hardware Encoding
checkbox, so the duplicates from this branch are dropped and NVENC uses
them. filmcraft-export is now an all-platform dependency of
filmcraft-platform (VideoToolbox and NVENC both register encoders).

Never-crash fixes in the NVENC backend:
- submit() rejects a driver input pitch narrower than a row (and unlocks
  the buffer); fill_nv12 uses get_mut instead of slicing rows.
- composition offsets use saturating math and i32::try_from; frame-rate,
  size and timestamp casts are checked; sizes above u16::MAX decline.
- Annex B scanning and NAL type checks use get()/first().
- A failed nvEncOpenEncodeSessionEx that returns a handle destroys it.

ffi.rs carries NVIDIA's MIT notice for nvEncodeAPI.h, listed in
ATTRIBUTION.md under a new "Third-party source code" section.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 18:16:12 -04:00
Brandon Thomas 71483312b6 Merge pull request #162 from SaymonMaster14/feat/windows-vp9-av1-hwdecode
Windows: VP9 + AV1 hardware decode (Media Foundation / DXVA)

# Conflicts:
#	ROADMAP.md
#	crates/platform/README.md
2026-10-07 17:58:12 -04:00
Brandon Thomas 13f71e3111 Merge pull request #175 from Luna161/fix/110-import-refreshes-offline
Engine: file.import refreshes the offline-missing list (#110)
2026-10-07 17:56:50 -04:00
Brandon ThomasandClaude Opus 5.5 4e4efcef12 M-relink: file.import also drops the cached slate of media it brought back (#110)
refresh() cleared the Missing badge, but the media pool kept the
MEDIA NOT FOUND slate cached under the item, so the monitors kept
showing it. The regression test now checks the rendered frame too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 17:56:33 -04:00
Brandon Thomas a4b92f1bec Merge remote-tracking branch 'origin/main' into pr-175 2026-10-07 17:54:19 -04:00
Brandon Thomas 1fe80344c7 Merge pull request #195 from midasdf/fix/vertical-type-tool-flyout
M10: choose vertical titles from the Type tool flyout
2026-10-07 17:53:53 -04:00
Brandon ThomasandClaude Opus 5.5 bd5387dff6 Merge main into #195: vertical type on top of point/paragraph text (#166)
The Type-tool click now goes through new_text_action; Vertical Type swaps
in graphics.newVerticalText and never draws a paragraph box (vertical text
is point text). Drops the dated ROADMAP log line (the maintainers keep the log).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 17:53:45 -04:00
Brandon ThomasandClaude Opus 5.5 6ce2038a00 M-HW: keep the Windows-only annexb/biplanar helpers warning-free on other systems (#141)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 17:50:20 -04:00
Brandon Thomas fcf1c45583 Merge pull request #141 from SaymonMaster14/feat/windows-media-foundation-hwdecode
Windows: Media Foundation/D3D11 hardware H.264 + HEVC decode

# Conflicts:
#	README.md
#	ROADMAP.md
#	crates/platform/Cargo.toml
#	crates/platform/src/lib.rs
#	docs/architecture.md
#	docs/performance.md
2026-10-07 17:48:06 -04:00
Brandon Thomas b5f197567b Merge pull request #186 from dcarnelutti/platform/videotoolbox-hevc-encode
platform: H.265 (HEVC) export with VideoToolbox

# Conflicts:
#	crates/export/src/settings_tests.rs
#	crates/ui-egui/tests/export_ui.rs
2026-10-07 17:47:10 -04:00
Brandon Thomas 84fcbeb1b9 Merge pull request #183 from dcarnelutti/platform/videotoolbox-h264-encode
platform: opt-in hardware H.264 encoding with VideoToolbox

# Conflicts:
#	crates/engine/src/export_tests.rs
2026-10-07 17:46:57 -04:00
Brandon Thomas d18bc04023 Merge pull request #184 from dcarnelutti/render/overlay-bounds-and-buffer-reuse
render: composite only what overlays cover, and reuse the float images
2026-10-07 17:46:38 -04:00
Brandon Thomas fed7201fcf Merge pull request #185 from dcarnelutti/export/progress-eta
export: show the estimated time left of a render next to its percentage
2026-10-07 17:46:37 -04:00
Brandon Thomas cbf181bd1f Merge pull request #176 from RicSchonfelder/i18n-pt-br
i18n: add Brazilian Portuguese (pt-br) UI translation
2026-10-07 17:46:33 -04:00
Brandon Thomas ce5d365c78 Merge pull request #165 from carlitosteso3/fix/media-browser-probe-157
Media Browser: probing a file doesn't read it whole (#157)

# Conflicts:
#	crates/engine/src/media_pool.rs
2026-10-07 17:46:32 -04:00
Brandon Thomas d01e1b893d Merge pull request #145 from carlitosteso3/fix/color-matte-29
Color Matte: pick the color on creation and change it later (#29)
2026-10-07 17:46:23 -04:00
Brandon Thomas c86847ff72 Merge pull request #155 from carlitosteso3/fix/playback-stalled-audio-136
Playback: a stalled audio device no longer freezes the playhead (#136)
2026-10-07 17:46:22 -04:00
Brandon Thomas 0810b403ce Merge pull request #148 from EthanSuquet/fix/h264-rc-slow-start
h264enc: 1-pass bitrate modes no longer starve the opening second
2026-10-07 17:46:21 -04:00
Brandon Thomas 8b3f118878 Merge pull request #173 from carlitosteso3/fix/shortcut-modifiers-164
Shortcut recorder accepts modifier chords; Add Edit cuts only selected clips (#164, items 1 and 5)
2026-10-07 17:46:20 -04:00
Brandon Thomas b4c65bdf8a Merge pull request #189 from Luna161/fix/168-project-select-all
Engine: project.selectAll and project.deselectAll for the Project panel (#168)
2026-10-07 17:46:19 -04:00
Brandon Thomas 47f75df15e Merge pull request #182 from justjohn12345/pr/layer-box-visibility
Graphics: only selected layers have a box, and a hidden layer has none
2026-10-07 17:44:08 -04:00
Brandon Thomas 91a36a4a3f Merge pull request #166 from justjohn12345/pr/text-box-modes
Graphics: point text and paragraph text, as Premiere has them
2026-10-07 17:44:07 -04:00
Brandon Thomas a3667ad26e Merge pull request #190 from ajsongpilot/fix/new-from-file-anchor
Graphics: New Layer from File anchors the picture at its own centre
2026-10-07 17:44:06 -04:00
midasdf b7beca9bb9 M10: choose vertical titles from the Type tool flyout 2026-10-08 06:13:41 +09:00
AJ DepewandClaude Opus 5.5 57069293fb Graphics: New Layer from File anchors the picture at its own centre
graphics.newFromFile resolved the Motion anchor with the sequence frame size
instead of the imported picture's size, so a picture smaller than the frame
got its anchor at the frame centre (e.g. 960,540 for a 4x2 image). Setting
Motion ▸ Position then moved the wrong point and the picture landed far from
where it was asked to go. place_video_clip now resolves auto points with the
source's own size (Project::source_size), falling back to the frame size.

The new-layer-from-file test checks the anchor is the picture's centre; it
fails before this change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 14:35:41 -06:00
06bc7ef9ec Engine: project.selectAll and project.deselectAll for the Project panel (#168)
Root cause: the only Select All was `edit.selectAll`, which fills the
timeline clip selection (`state.selection`). Nothing filled the Project
panel's selection (`state.project_selection`), so with 161 imported
items the user had to click each one.

Fix:
- `project_panel::commands()` gets `project.selectAll` (selects every
  item in the project) and `project.deselectAll` (clears the Project
  panel selection). They are regular journalled commands with no menu
  entry and no shortcut of their own, so they add no shortcut conflicts.
- `handle_shortcuts` (ui-egui) remaps a fired `edit.selectAll` /
  `edit.deselectAll` to the `project.*` command when the Project panel
  has focus. Cmd+A / Cmd+Shift+A keep acting on timeline clips
  everywhere else, and `edit.selectAll` behaves exactly as before.

Out of scope: no menu entry. The Edit ▸ Select All menu item still
calls `edit.selectAll` directly, because menu clicks don't go through
the focus remap. The regression test checks the engine commands but not
the UI keyboard remap.

Regression test: project_panel_tests::select_all_selects_every_project_item
(fails without the fix: unknown command).

Co-Authored-By: ninso112 <ninso112@pm.me>
Co-Authored-By: Luna161 <Rosenkranzrene@gmail.com>
2026-10-07 20:21:49 +00:00
Dario CarneluttiandClaude Sonnet 5.5 790b3a0697 platform: H.265 (HEVC) export with VideoToolbox
Adds `Format::Hevc` (Export > Format > H.265 (HEVC); `"format": "hevc"` in
`file.exportMedia`): HEVC Main, 8-bit 4:2:0, in MP4 (`hvc1`) or QuickTime, with AAC audio,
encoded by the macOS hardware encoder. There is no built-in H.265 encoder (one in pure Rust
is a project of its own, and x265 is GPL), so the format exists only where the OS has one.

- `videotoolbox_encode`: the session wrapper creates HEVC sessions too (`VtProfile::HevcMain`;
  the profile also says which codec). Keyframes are the HEVC random access points (NAL types
  16 to 21); the parameter sets are VPS / SPS / PPS; the `hvcC` record in the MP4 sample
  entry is the one VideoToolbox writes (sample description extension atoms), so profile,
  level and flags are the encoder's own. `VtEncoder::uses_hardware()` asks VideoToolbox
  whether the session runs on a hardware encoder (a test checks H.264 and HEVC), so a
  requirement dropped by accident could never become a silent software encode.
- `hardware_encode`: one adapter for both codecs. Choosing the format is the opt-in (the
  `hardware_encoding` setting is for H.264). `hevc_available()` (one small hardware session,
  created once) is registered with the new `filmcraft_export::register_format_probe`, so
  `available(Format::Hevc)`, the format list of Export mode and `exportFormats` follow the
  machine. `Format::has_builtin_encoder` says which formats need such a probe.
- `export`: `Format::is_h26x` where H.264 and H.265 behave alike (MP4 or QuickTime, AAC, size
  estimate, summary line). Two-pass VBR is refused up front ("H.265 export has no two-pass
  mode") and HDR sequences export as SDR, because there is no encoder to fall back to.
- Export mode: H.265 shows H.264's multiplexer, audio, metadata and bitrate controls, without
  profile, level, two-pass or the hardware checkbox, and says "Encoder: Hardware".

Apple M1 (8 cores), 1080p25, a 9:29 timeline (camera clip, ProRes 4444 overlays, AAC,
loudness): hardware H.265 at 10 Mb/s 195 s, hardware H.264 at 20 Mb/s 204 s (CPU 1029 s and
1042 s; the same H.264 export took 193 s and 200 s on other runs). It is not faster: the codec
that compresses further is the more expensive one (raw encoders: 166 and 189 frames/s), and
the export is bound by the CPU compositor, not by the media engine.

Quality per bit, 30 s of the same timeline against a ProRes 422 HQ export (average PSNR over
the three planes, SSIM): 20 Mb/s 46.88 dB / 0.9902 (H.264) and 46.91 dB / 0.9903 (H.265);
10 Mb/s 44.96 / 0.9863 and 45.09 / 0.9863; 6 Mb/s 43.72 / 0.9833 and 44.31 / 0.9843; 4 Mb/s
42.91 / 0.9807 and 43.64 / 0.9825; 3 Mb/s 42.37 / 0.9786 and 43.05 / 0.9807. The same picture
at 10 Mb/s and above; at 3 to 6 Mb/s H.265 needs 22 to 31 % less bitrate for the same PSNR.
Both formats therefore keep the same default bitrate. Details in docs/performance.md (HW3).

Tests: tests/hardware_encode.rs gets the HEVC counterparts of the H.264 ones (what is taken
and declined, a round trip through our HEVC decoder with luma PSNR above 30 dB, keyframes, MP4
and QuickTime exports with AAC, ffmpeg / ffprobe reading `hevc` / `Main` / `hvc1` /
`yuv420p` / BT.709, exact sizes, hostile configurations, encoders dropped at any point, the
format list agreeing with the probe, sessions on the hardware encoder); settings_tests.rs
checks names, ids, defaults, the summary, two-pass refusal and the probe; export_ui.rs the
controls H.265 shows and hides.

Stacked on the hardware H.264 encoder (the first commit of this branch).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 14:00:08 -06:00
Dario CarneluttiandClaude Sonnet 5.5 283ea80a62 export: show the estimated time left of a render next to its percentage
Export mode, the status bar and the Progress panel showed "Encoding 37%" and nothing about how
long the rest would take. They now say "37% · 2:05 left".

- `Progress::eta()` (the new `pace` module) is the time left at the job's speed over the last
  15 seconds. Each call is also a reading, so the UI polling on every frame it draws the job
  feeds it, and none of the places that advance `done` had to change. A trailing window follows
  the real speed changes of an export (an intro, a banner, plain camera footage) where an
  average since the start lags; a stall makes the estimate grow instead of freezing it; a long
  idle start (the loudness pass) is not counted as the job's speed; nothing is shown until a
  second of readings has progress, and nothing once the job is done or finished.
- `format_eta`: `45 s`, `2:05`, `1:02:05`, rounded up.
- Shown in the status bar ("Exporting... 37% · 2:05 left", and the `status.job.progress`
  automation label), in the Export queue (on its own line: the column is narrow) and in the
  Progress panel. The engine adds `etaSeconds` (null while unknown) to every job of `jobs.list`
  and to the encoding items of `export.queue.list`; docs/agents.md says so.

Measured on a whole 9:29 export (193 s, Apple M1), asking every 3 s: the first estimate comes
after 6 s; from 30 s on, the predicted end of the export is on average 1.1 s early and never
more than 14.5 s off (7.5 % of the run). The status bar read "9% · 3:00 left" at 21 s and
"97% · 5 s left" at 184 s.

Tests: `pace` (steady job, speed change, stall, idle start, count going back, bounded history,
extreme values, a whole `Progress`), `format_eta`, the engine (`etaSeconds` of jobs and queue
items), and export_ui (status bar label and queue item).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 13:48:52 -06:00
Dario CarneluttiandClaude Sonnet 5.5 d2ab33ba76 render: composite only what overlays cover, and reuse the float images
The CPU compositor, which is what export runs, works on premultiplied linear f32 images,
33 MB each at 1080p, and every layer was one of them. A profile of a 9:29 export with a
hardware H.264 encoder (so the encoder is no longer the bottleneck) put 61-64 % of the busy
CPU in compositing, 12 % in zeroing and copying memory, 8-11 % each in the float -> 8-bit
and RGBA -> Y'CbCr conversions and 4-7 % in decoding the ProRes overlays: a banner that is
transparent except for its bottom 100 rows still cost a whole conversion and a whole mix,
and the bottom layer paid for a zero-filled canvas and a pass that mixes it over that canvas.

Three changes, each of which gives the bits the general path gives:

- The canvas is allocated when a layer needs it, and an opaque first layer (a Y'CbCr frame
  without an alpha plane, opacity 100 %, Normal blend, the size of the output) becomes the
  canvas instead of being mixed over zeros.
- A clip of plain media whose frame has an alpha plane (a ProRes 4444 banner) is converted
  and mixed only inside the rectangle where its alpha is not zero: `VideoFrame::alpha_region`,
  `to_linear_f32_region` and `blend::composite_at` (`composite` is `composite_at` at the
  origin; Dissolve's pattern follows the pixel's place in the output). A clip with effects,
  opacity masks, frame blending, colour management or a picture that is not placed one to
  one on the output takes the general path, as before.
- `filmcraft_frame::pool` keeps idle f32 images (320 MiB at most). `take_f32_overwritten`
  hands one back with its old contents, which the conversions overwrite whole (so no
  zero-fill), and the export pipeline gives each frame's image back after the 8-bit
  conversion.

Apple M1 (8 cores), a machine that was not idle, so the two builds alternate and the
median is reported:

- Synthetic 1080p frame (`cargo run --release -p filmcraft-render --example frame_bench`,
  5 rounds): camera only 8.9 -> 6.5 ms, camera + banner 16.2 -> 7.8 ms, same picture checksum.
- A real project (1080p25 camera clip, ProRes 4444 banner and subscribe bar), 30 s with the
  banner exported with the built-in encoder, which is deterministic: 46.4 -> 36.7 s, and
  both exports are the same file (same MD5), so every frame of the real pipeline matches.
- The same project with a hardware encoder, 3 rounds: 30 s with the banner 17.4 -> 11.2 s
  (CPU 99 -> 56 s), 30 s of the camera alone 11.4 -> 8.8 s, 20 s with the subscribe bar
  11.1 -> 7.0 s.

Tests: `render/src/region_tests.rs` compares each shortcut with the general path bit for bit
(an opaque bottom layer, banners over and under a camera, an 8-bit sticker, every blend mode,
several opacities, moved, scaled and effect clips, a bigger source, reduced-resolution
rendering), each render twice so the second starts from recycled buffers, and checks which
layers take a shortcut; the frame tests check that a region is the crop of the whole
conversion, that `alpha_region` is the box around what is not transparent, and that a buffer
full of NaN never leaks into a conversion, for every pixel format. Breaking a shortcut on
purpose (a region one pixel off, an opaque layer taken as the canvas at half opacity, a
conversion that skips the alpha channel) makes them fail.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 13:35:20 -06:00
Dario CarneluttiandClaude Sonnet 5.5 4cab6bc5da platform: opt-in hardware H.264 encoding with VideoToolbox
Export encodes H.264 on the CPU with the built-in encoder, which is most of the time
of an export (about two thirds of the busy CPU in a profile of a 20 s export). On
macOS the media engine can do it: a VideoToolbox compression session behind
`filmcraft_export::VideoEncoder`, registered by `filmcraft_platform::register()`.

- `ExportSettings::hardware_encoding` (`HardwareEncoding::Off` | `Auto`; Export > Video >
  Hardware Encoding, `"hardwareEncoding": "off|auto"` in `file.exportMedia`, a boolean is
  understood too), off by default: the built-in encoder's output is byte-identical on
  every machine, a hardware encoder's is not.
- `videotoolbox_encode` (FFI, same containment as the decoder: SAFETY comments, no
  panic across the callback, safe API) and `hardware_encode` (safe adapter and factory).
- The factory declines, so the built-in encoder is used, for other formats, MXF, two-pass
  VBR, HDR, odd sizes, non-square pixels and any configuration VideoToolbox cannot create a
  hardware session for. An encoder that fails mid-export stops it with an error: unlike a
  decoder, it cannot hand a half-written stream to another one.
- No B-frames: on real 1080p footage the quality is the same with and without them
  (+-0.3 dB at equal bitrate) and the bitrate lands closer to the target, and without
  them every frame is presented at its decode time (no composition offsets, no edit list).
- `export::register_encoder` ignores a factory registered twice; `encoder_registered`.

Apple M1, 8 cores, single runs: a 9:29 timeline (camera clip, ProRes 4444 overlays with
alpha, AAC, loudness) exports in 311 s instead of 793 s (2.5x faster); its densest 134 s
in 84 s instead of 395 s (4.7x). The outputs compare at SSIM 0.990 / PSNR 46.5 dB. The encoder
alone runs 200 fps at 1080p (docs/performance.md).

Tests (tests/hardware_encode.rs): what is taken and declined, a round trip through our
software decoder, an export that decodes in our decoder and in ffmpeg, the fallback for
everything hardware declines, exact output sizes, an empty range, hostile configurations
and encoders dropped at any point; the engine's `hardwareEncoding` parameter.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 13:34:51 -06:00
Brandon ThomasandClaude Opus 5.5 86f3375775 Rename PrintCraft to PdfCraft (storytold/pdfcraft) (#177)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 14:45:32 -04:00
Davi Andrei a7b51aa313 nvenc: fix a doc path 2026-10-07 15:42:38 -03:00
Davi AndreiandClaude Sonnet 5.5 11b199dbcd Docs: NVENC H.264 hardware encoding
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MMorBHwct72udS2LiC3ZHp
2026-10-07 15:42:28 -03:00
Davi AndreiandClaude Sonnet 5.5 6db932a9ba Windows: NVENC H.264 hardware encoding for Export (work in progress, #30)
NVENC through nvEncodeAPI64.dll (API 12.1, FFI layout checked against the C header by generated
tests), registered as an Export encoder in front of the software one; Export > Hardware encoding
(off by default). Declines two-pass VBR, HDR, MXF, unsupported sizes; B-frames, IDR/GOP, VUI, avcC.
Tests: decode with our decoder (PSNR), pipeline export vs software, decline paths.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MMorBHwct72udS2LiC3ZHp
2026-10-07 15:41:02 -03:00
RicSchonfelder 9a4a85d8e1 i18n: Brazilian Portuguese (pt-br) joins Edit > Language
Language::PtBr is persisted as pt-br and translated through a new
PORTUGUESE table with the same 347 menu labels as SPANISH, so every
translated key still resolves to a real menu item. The new
app.language.portuguese command checks, switches and restores the
language like the other three, and the native menu maps it back.
Cargo.lock is untouched.
2026-10-07 15:26:26 -03:00
Luna161andninso112 16cc1c808c Engine: file.import refreshes the offline-missing list (#110)
file.import created new items but never rebuilt Session::offline.missing.
The UI reads that list to drive the Program slate and the Project
panel 'Media missing' badge, so any re-imported item the project
already listed as missing stayed listed as missing until on_open ran
again (project reopen) or the caller manually relinked.

Add a single crate::relink::refresh(s) call at the end of file.import,
matching the call on_open already makes after a project opens. Closes
the slate/badge symptom without requiring reopen or per-item relink.

The deeper SharedSource cache eviction issue the reporter observed
with media.autoRelink is out of scope here; a follow-up should call
MediaPool::remove for items whose path now resolves before re-insert.

Co-Authored-By: ninso112 <ninso112@pm.me>
Co-Authored-By: Luna161 <Rosenkranzrene@gmail.com>
2026-10-07 18:20:23 +00:00
carlitosteso3andClaude Opus 5.5 d47e794437 sequence.addEdit: selected clips under the playhead are cut, and only they (#164)
Add Edit always cut every targeted track, so with one clip selected it cut
all tracks. As in Premiere, selected clips under the playhead are now cut
and nothing else; with none there, the targeted tracks are, as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 12:37:50 -05:00
carlitosteso3andClaude Opus 5.5 98c022e0b0 shortcuts: recording a chord skips the modifier key presses (#164)
egui 0.36 reports pressing Shift, Ctrl, Alt or the Windows / Cmd key as a
key event of its own, before the key they modify. The Keyboard Shortcuts
recorder took that first press and refused it ("AltLeft can't be used as a
shortcut"), so no chord with a modifier could be recorded. Modifier keys on
their own are now skipped; the chord is recorded with the key they modify.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 12:37:49 -05:00
justjohn12345andClaude Opus 5.5 b6281f968f Graphics: only selected layers have a box, and a hidden layer has none
Every layer of the selected graphic was outlined on the Program monitor,
so a box stayed after its layer was deselected, and a layer whose
visibility was off kept its box and could still be clicked and dragged.

As in Premiere Pro 26: a layer has a box only while it is selected (or
typed into), and a layer whose visibility is off is not on the monitor
at all: no box, no handles, no click target.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 13:24:43 -04:00
carlitosteso3andClaude Opus 5.5 a54bf13ebc Merge upstream main into fix/color-matte-29 (keep both tests at the end of clip_ops_tests.rs)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 12:02:28 -05:00
carlitosteso3andClaude Opus 5.5 dd404568ae media browser: probing a file doesn't read it whole (#157)
Looking at a folder probes each visible file for its properties. A format
no streaming reader takes (AVI, which isn't supported at all, and WAV,
MP3 and the other byte-opened formats) fell through open_reader's
whole-file path: a 290 MB AVI took 518 MB of memory and a full read just
to report that it isn't supported, a 247 MB WAV 500 MB.

- filmcraft-media: open_reader_within(.., max_whole) refuses, after the
  sniffing head, a file no reader opener takes when it is larger than
  max_whole. open_reader is open_reader_within with no limit.
- engine: MediaPool::probe_file uses it with PROBE_WHOLE_FILE_MAX (64 MiB);
  media_browser::probe calls probe_file. Import and playback still use
  open_file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 11:21:53 -05:00
Davi AndreiandClaude Sonnet 5.5 79cb1d0f8d Windows: VP9 + AV1 hardware decode through Media Foundation / DXVA (#30)
Extends the Windows backend (#141) to VP9 (profiles 0 and 2) and AV1 (main, 8/10-bit), 4:2:0.

- codecs::hw: FrameStreamInfo (vpcC / av1C): profile, bit depth, chroma, picture size and colour as
  the software decoders report them (vp9_color / av1_color are now shared with them), random-access
  samples, in-band format changes; StreamInfo lets HybridDecoder handle NAL and frame-coded streams.
- platform: media_foundation::stream (what each codec needs: DXVA profile, MFT request, input
  format), MfDecoder generalised; VP9 frames / AV1 temporal units go in as they are; the MFT's
  declared picture size (display aperture) is checked against the bitstream's.
- Declined up front: VP9 profiles 1/3, AV1 profiles 1/2, 4:2:2/4:4:4, mono, 12-bit, no codec
  extension, no DXVA profile. A key frame of another size or a different sequence header falls back
  to the software decoder.
- Tests: bit-exact parity (360p / 1080p / 2160p, seeks, resets, flush, hidden frames), forced
  failure, damaged samples and av1C, format change fallback, WebM / Matroska through the media stack.
- Bench: AV1 fixtures with libaom when ffmpeg lacks SVT-AV1.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MMorBHwct72udS2LiC3ZHp
2026-10-07 12:39:45 -03:00
Brandon Thomas 8fcad73c92 Merge pull request #159 from storytold/fix/90-web-api-rejects-errors
Web: window.filmcraft rejects with Error objects everywhere (#90)
2026-10-07 10:57:54 -04:00
Brandon ThomasandClaude Opus 5.5 b82825acb8 Web: window.filmcraft rejects with Error objects everywhere (#90)
readFile (missing path), importUrl and openProject (HTTP errors) and openProject (neither a File
nor a URL) rejected with plain strings, so e.message was undefined and e instanceof Error false,
unlike execute / request. Their promises now go through as_error, which wraps a string in an Error
and passes an Error through unchanged.

Checked in Chrome against the web build: all four cases reject with an Error carrying the message
("/files/nope.mp4: not found", "…: HTTP 404", "need a File or URL").

Fixes #90

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 10:57:48 -04:00
Brandon Thomas 3561e856a6 Merge pull request #158 from storytold/fix/107-flatpak-media-access
Packaging: the Flatpak can read a project's media wherever it lives (#107)
2026-10-07 10:53:01 -04:00
Brandon ThomasandClaude Opus 5.5 20ddf9c49e Packaging: the Flatpak can read a project's media wherever it lives (#107)
The manifest granted only xdg-pictures, on the premise that the portals make filesystem access
unnecessary. But a project refers to its media by absolute path and the document portal exposes
only the project file, so a project in ~/Videos or ~/Music opened with all its media missing.
Grant the home directory and the usual external-drive mount points (/media, /run/media, /mnt), as
other video editors on Flathub do; nothing system-wide.

Fixes #107

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 10:50:24 -04:00
Brandon Thomas 5695626216 Merge pull request #156 from storytold/fix/docs-85-86-87-88-99
Docs: releasing guide, CLI export options, README and CLAUDE.md drift (#85, #86, #87, #88, #99)
2026-10-07 10:49:14 -04:00
Brandon ThomasandClaude Opus 5.5 fa67dfa372 Docs: releasing guide, CLI export options, README and CLAUDE.md drift (#85, #86, #87, #88, #99)
- docs/releasing.md (#99): release.yml points readers to it twice and it didn't exist. Written from
  the workflow and packaging scripts as they are (macOS, Windows x64/x86/arm64, Linux x86_64/aarch64
  with the glibc 2.35 floor, web; draft release, secrets).
- filmcraft-cli help (#86): export lists --scale, --quality, --no-audio and --queue, and apv among
  the formats.
- README (#87): more than 650 engine commands (671 today), not about 135.
- README (#88): the web line says the browser app ships with every release and links docs/web.md.
- CLAUDE.md (#85): the Illustrator-class sibling is ../vectorcraft (formerly DrawCraft).

Fixes #85
Fixes #86
Fixes #87
Fixes #88
Fixes #99

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 10:49:08 -04:00
Brandon Thomas 3186a754f2 Merge pull request #151 from carlitosteso3/fix/transcripts-89-97-98
Transcripts: disabled, not failing, in builds without speech-to-text (#89, #97, #98)
2026-10-07 10:44:59 -04:00
Brandon ThomasandClaude Opus 5.5 a066748354 Merge main: the transcript checks landed in #146; keep Transcribe Sequence and the docs
#146 landed the same transcript.generate / downloadModel / import changes, so this branch keeps
main's versions of those files and adds what #146 missed: Transcribe Sequence (sequence.transcribe)
is disabled like transcript.generate in a build without speech-to-text, and docs/transcripts.md
describes the disabled state. A test asserts both directions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 10:44:47 -04:00
Brandon Thomas 2647a2d9f8 Merge remote-tracking branch 'origin/main' into pr151
# Conflicts:
#	crates/engine/src/settings_tests.rs
#	crates/engine/src/transcript_tests.rs
2026-10-07 10:44:47 -04:00
carlitosteso3andClaude Opus 5.5 0da0a3430a playback: a stalled audio device no longer freezes the playhead (#136)
The playhead follows the audio clock (frames the output device consumed).
An output stream can open without error and then never call back (ALSA
with a busy or misconfigured device): the clock stayed at 0 and Play did
nothing, with no message.

advance_playback now notes when the audio clock last moved; if it stands
still for AUDIO_STALL_S (1 s) while playing, playback continues from where
the audio got to on the wall clock, the stream is stopped, a warning is
logged and the status bar says the audio output is not responding.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 09:42:42 -05:00
Brandon Thomas 3628bbe744 Merge pull request #154 from storytold/fix/91-92-bridge-blocking-export
Bridge: a blocking export runs as an app job, so it neither times out nor freezes the app (#91, #92)
2026-10-07 10:42:35 -04:00
Brandon ThomasandClaude Opus 5.5 bd12dcae81 Bridge: a blocking export runs as an app job, so it neither times out nor freezes the app (#91, #92)
file.exportMedia with wait: true was forwarded to the app unchanged. The app then encoded on its UI
thread: it showed no progress and answered no other control request until the encode ended, and the
control server's 60 s reply limit reported "timeout" for any longer export while it went on and
succeeded.

BridgeClient::execute now starts the export without wait and polls jobs.list until the job
finishes, returning the same {job, path, result} (or the export's error). filmcraft-cli --bridge
exec and MCP bridge mode both use it, and MCP command_run in bridge mode now gets the same progress
notifications and cancellation as headless mode.

Tested against a fake app (wait: true never reaches it, one export started, result and error
returned) and end to end against the desktop app: a blocking demo export returned its 642-frame
result with exit 0 while ui.inspect was answered in ~0.05 s throughout.

Fixes #91
Fixes #92

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 10:42:28 -04:00
carlitosteso3andClaude Opus 5.5 b8fa786cad transcripts: disabled, not failing, in builds without speech-to-text (#89, #97, #98)
- transcript.generate is enabled only with a recogniser: one installed in
  Session::transcriber, or the build's own (feature `whisper`). Otherwise
  describe, command_list enabled_only and the menu report it disabled with
  "speech-to-text is not available in this build" as the reason (#97).
  Transcribe Sequence, which runs it, follows.
- transcript.downloadModel is enabled only with `speech-download` (#98).
- file.import with Automatically transcribe clips on no longer skips
  transcription silently when it can't run: the disabled command's reason
  lands in the import's errors as "transcription: ..." (#89).
- docs/transcripts.md describes the disabled state.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 09:14:05 -05:00
Brandon Thomas a273a95ad2 Merge pull request #147 from storytold/fix/93-rpm-glibc-floor
Packaging: the rpm requires glibc >= 2.35, as the deb does (#93)
2026-10-07 10:07:56 -04:00
Brandon ThomasandClaude Opus 5.5 a50f6162ba Packaging: the rpm requires glibc >= 2.35, as the deb does (#93)
The binaries are built on Ubuntu 22.04 (glibc 2.35). The deb says libc6 (>= 2.35), but the rpm
named no glibc floor, so dnf installed it on the RHEL 9 family (glibc 2.34), where both binaries
then failed with "GLIBC_2.35 not found". Now dnf refuses the install there.

Fixes #93

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 10:06:42 -04:00
Brandon Thomas be5b34b383 Merge pull request #146 from storytold/fix/97-98-89-transcripts-without-speech
Transcripts: builds without speech-to-text say so (#97, #98, #89)
2026-10-07 10:05:02 -04:00
Brandon ThomasandClaude Opus 5.5 621240f761 Transcripts: builds without speech-to-text say so (#97, #98, #89)
- transcript.generate is enabled only with an installed transcriber or the whisper feature; it
  reported enabled and then always failed with "speech-to-text is not available in this build".
- transcript.downloadModel is enabled only with the speech-download feature.
- An import with Automatically transcribe clips (all imported) on reports a
  "transcription: speech-to-text is not available in this build …" error instead of importing
  silently untranscribed.

Fixes #97
Fixes #98
Fixes #89

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 10:04:55 -04:00
carlitosteso3andClaude Opus 5.5 56eaea2fa3 Color Matte: pick the color on creation and change it later (#29)
- File ▸ New ▸ Color Matte… (and Project ▸ New Item) opens a New Color Matte
  dialog: color picker, name, width, height and duration. Called with params
  (CLI, control, MCP) it still creates the matte directly.
- project.matteColor {item?, color}: change a Color Matte's color (the
  selected one by default); every clip of it follows and it undoes.
  Double-clicking a Color Matte in the Project panel opens its color picker,
  as in Premiere.
- media pool: a generator's cache key now holds its parameters, so a matte
  whose color changes (or comes back with undo) is generated again instead of
  the pool serving the first one forever.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 08:58:01 -05:00
Brandon Thomas e975621bbd Merge pull request #144 from storytold/fix/114-render-tools-read-only
MCP: render_frame and render_preview leave the playhead where it was (#114)
2026-10-07 09:55:32 -04:00
Brandon ThomasandClaude Opus 5.5 65c6b7365d MCP: render_frame and render_preview leave the playhead where it was (#114)
Both tools are annotated readOnlyHint, but a call with `seconds` moved the active sequence's
playhead (and, with Selection Follows Playhead on, the selection) to that time, in headless and
bridge mode alike.

- headless: Session::render_program_at renders the frame at `seconds` (frame-snapped, as the
  playhead would be) without touching the session.
- bridge: the Program monitor screenshot needs the live playhead there, so the tool records the
  playhead and selection, takes the screenshot and puts both back (the selection only if it changed,
  since selecting also leaves trim mode).

Regression test: rendering at 5 s and 8 s with Selection Follows Playhead on leaves playhead and
selection unchanged and still renders the requested frame (it moved the playhead to 8 s before).

Fixes #114

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 09:55:24 -04:00
justjohn12345andClaude Opus 5.5 8407f233c1 Graphics: point text and paragraph text, as Premiere has them
A text layer is now one of two types, each with Premiere Pro 26's handles:

- Point text (Type tool click): every handle scales the layer about its
  anchor point, both axes alike; the font size is untouched.
- Paragraph text (Type tool drag): the dragged rectangle is a box the text
  wraps in. Handles move that side or corner of the box, the opposite side
  stays, the text re-wraps at the same size. Lines below the box are not
  shown and the bottom-right handle turns into a red plus.
- The anchor point can be dragged with the Selection tool; the layer stays.
  It is picked before anything under it, so a shape dragged by its exact
  centre moves its anchor.
- Properties > Text > wrench opens Text Properties, where Text Layer Type
  switches a layer between the two (graphics.setTextType); the text stays
  where it is.

Shapes keep stretching away from their opposite side.

New: text layer parameter box_height, graphics.newText `box`, and
textType / box / overflow / anchor / scale in graphics.list. A layer saved
before a parameter existed can now be given it with graphics.set.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 09:54:26 -04:00
Brandon Thomas 50f8d12dd9 Merge pull request #143 from storytold/fix/125-oracle-sequence-fixture-race
Tests: image-sequence oracle fixtures are written atomically (#125)
2026-10-07 09:49:41 -04:00
Brandon ThomasandClaude Opus 5.5 ba411138d4 Tests: image-sequence oracle fixtures are written atomically (#125)
make_sequence had ffmpeg write numbered stills straight into the shared seq_<ext> directory and
treated it as ready once frames 1 and 12 existed. Two tests generating it at once (png_sequence_exact
and missing_frames_hold_the_previous_frame) read each other's half-written PNGs; one that fails to
decode is held as missing, so frame 6 equalled frame 3. Six parallel processes on a fresh fixture
dir failed 18 of 120 runs before, 0 of 120 after.

ffmpeg now writes into a testkit temp_path directory that is renamed into place (with a .complete
marker) only when all twelve frames are there; the gap copy is private to its test.

Fixes #125

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 09:49:35 -04:00
Brandon Thomas 0dfad0b321 Merge pull request #142 from storytold/fix/66-hostile-edit-list-subclips
Hardening: hostile MP4 edit lists and cyclic subclip chains (#66)
2026-10-07 09:46:03 -04:00
Brandon ThomasandClaude Opus 5.5 0dd66d8aa3 Hardening: hostile MP4 edit lists and cyclic subclip chains (#66)
- codecs: a resampled MP4 audio read scales the edit-list offset to the source rate in i128 and
  saturates the window arithmetic; a hostile media_time overflowed i64.
- engine: media_duration follows a subclip's parent chain in a loop bounded at 16 hops instead of
  recursing; a cyclic or very deep chain in a damaged project overflowed the stack.

Each has a regression test that failed before (overflow panic / stack overflow).

Fixes #66

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 09:44:45 -04:00
EthanSuquetandClaude Opus 5.5 68173aa82a h264enc: 1-pass bitrate modes no longer starve the opening second (#74)
The 1-pass ABR rate factor counts one second of virtual inter frames so the
first I frame gets a fair share of the budget. That history was priced once,
at the first frame, with the model's initial coefficient guess, which is
several times too high on ordinary content, and then only faded out. Every
VBR/CBR export therefore coded its first second 6-9 dB below the rest.

A virtual frame now costs what the P and B frames coded so far cost on
average (the old guess only until the first of them), re-estimated per frame.
On the synthetic 640x360p60 test at 2 Mb/s, 0.1-0.5 s goes from 25.0 dB to
32.1 dB against 33 dB after the first second, at the same bitrate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 09:41:14 -04:00
Davi AndreiandClaude Sonnet 5.5 932cdb77f5 Docs: Windows hardware decoding (platform README, ADR 0001, architecture, performance, roadmap)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MMorBHwct72udS2LiC3ZHp
2026-10-07 10:07:40 -03:00
Davi AndreiandClaude Sonnet 5.5 5e440a6607 Windows: Media Foundation / Direct3D 11 hardware H.264 + HEVC decode (#30)
New backend in crates/platform (media_foundation/): a Direct3D-aware decoder MFT is driven at the
level of single access units (Annex B), given the process's D3D11 video device through an
IMFDXGIDeviceManager so it decodes with DXVA, and its NV12 / P010 textures are read back through a
staging texture into planar Yuv8 / Yuv16. H.264 Baseline/Main/High and HEVC Main / Main 10, 4:2:0.

- Hardware is verified: non-D3D-aware or async MFTs, streams the GPU's DXVA decoder does not list,
  and system-memory output (Microsoft's MFT software fallback) are declined or fail the stream so
  HybridDecoder continues with our decoder.
- mfplat.dll is loaded at run time so Windows N editions still start.
- register() / registered() / hardware_decoder_for() cover Windows; perf.stats reports the backend.
- Tests (Windows): bit-exact parity with the software decoders at 640x360, 1080p and 2160p
  (resets, seeks, flush), forced mid-stream failure, damaged input, concurrency, repeated init.
- Bench: runs on Windows (ffmpeg on PATH, process/thread CPU clocks), HEVC Main 10 2160p row,
  hardware counters per row.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MMorBHwct72udS2LiC3ZHp
2026-10-07 10:07:40 -03:00
Brandon Thomas 94a22d7a83 Merge pull request #130 from punkhop/fix/premiere-ui-type
Theme: interface type closer to Premiere's
2026-10-07 08:33:06 -04:00
Brandon Thomas 6a02e92004 Merge remote-tracking branch 'origin/main' into pr-130 2026-10-07 08:27:41 -04:00
Brandon ThomasandClaude Opus 5.5 736760752b Theme: keep the interface in Inter; Source Sans 3 is an Adobe font (AGENTS.md §1.1)
The timecode, colour and menu changes stay; the interface face from craft-fonts is left out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 08:27:41 -04:00
Brandon Thomas 6262126056 Merge pull request #105 from mweinbach/feat/apv-codec
Codecs: add clean-room APV (RFC 9924) decoder, encoder, container support, and export presets
2026-10-07 07:10:17 -04:00
Brandon Thomas cd3fe20ef9 Merge remote-tracking branch 'origin/main' into apv-105 2026-10-07 07:09:54 -04:00
Brandon Thomas 94cda9dca4 Merge pull request #116 from justjohn12345/pr/nested-interchange
Nested sequences: interchange (AAF compositions, OMF rendered sound, EDL reel AX)
2026-10-07 07:09:39 -04:00
Brandon Thomas 16475596d3 Merge remote-tracking branch 'origin/main' into nest-116
# Conflicts:
#	crates/engine/src/commands.rs
2026-10-07 07:09:20 -04:00
Brandon Thomas d4e438e932 Merge remote-tracking branch 'origin/main' into apv-105 2026-10-07 07:08:58 -04:00
Brandon Thomas 9c026067a9 Merge pull request #132 from punkhop/fix/playback-rate-conversion
Audio: play a sequence on a device at another rate without phase jumps
2026-10-07 07:08:32 -04:00
Brandon Thomas 7916cfb80e Merge pull request #131 from punkhop/fix/audio-plays-ahead
Audio: mix playback 200 ms ahead so a busy Mac doesn't drop sound
2026-10-07 07:08:29 -04:00
Brandon Thomas 566164cf7d Merge pull request #129 from carlitosteso3/fix/he-aac-108
HE-AAC plays at its output rate; AAC export caps the bitrate (#108, parts 1–2)
2026-10-07 07:08:25 -04:00
Brandon Thomas b4caf39f5f Merge pull request #117 from justjohn12345/pr/add-tracks-dialog
Sequence: Add Tracks… opens Premiere's dialog (amount, placement, track type)
2026-10-07 07:08:21 -04:00
Brandon ThomasandClaude Opus 5.5 3f3d6ab45b Audio: the channel test lets the mixer get ahead before playing, so a busy runner doesn't flake it
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 06:34:20 -04:00
Brandon ThomasandClaude Opus 5.5 b94c81b5d1 HE-AAC: probing reads at most one access unit's worth of bytes per sample
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 06:34:19 -04:00
Brandon ThomasandClaude Opus 5.5 a1d245e517 Sequence: the Add Tracks dialog's OK check cannot overflow on huge counts
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 06:34:16 -04:00
Brandon Thomas 005745d9ec Merge remote-tracking branch 'origin/main' into apv-105
# Conflicts:
#	crates/codecs/src/mp4.rs
2026-10-07 06:01:14 -04:00
Brandon ThomasandClaude Opus 5.5 d3c3b0f6e8 NEST: hostile project data cannot panic a nest's length, oversize its mix or multiply AAF needs
A negative clip duration no longer panics the clamp when a nest follows its contents; a nested
sequence's claimed sample rate is clamped before it sizes the mix buffer; audio_needs lists each
nested sequence once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 06:00:36 -04:00
Brandon Thomas 19d2f15148 Merge remote-tracking branch 'origin/main' into nest-116
# Conflicts:
#	crates/ui-egui/src/lib.rs
#	crates/ui-egui/src/panels/timeline.rs
2026-10-07 06:00:36 -04:00
Brandon Thomas a4c4d38550 Merge pull request #123 from Luskish/fix/control-close-on-malformed-input
Control: close the connection on input that isn't a request (#119)
2026-10-07 05:57:55 -04:00
Brandon Thomas 0232c53404 Merge pull request #124 from punkhop/fix/ripple-trim-l-cut-head
Ripple trim: a shorter head after an L cut keeps the earlier sound in place
2026-10-07 05:57:51 -04:00
Brandon Thomas a481f05e26 Merge pull request #104 from punkhop/fix/ripple-trim-j-cut-head
Ripple trim: a shorter head on a J-cut take is no longer refused
2026-10-07 05:57:46 -04:00
Brandon Thomas 13e5591bb2 Merge pull request #121 from punkhop/fix/user-workspaces
Window ▸ Workspaces: save your own workspaces, like Premiere
2026-10-07 05:57:42 -04:00
Brandon Thomas 7811da4ec0 Merge pull request #122 from coygeek/docs/add-star-history
docs: add star history chart to README
2026-10-07 05:57:38 -04:00
Brandon Thomas ce9d43a014 Merge pull request #128 from punkhop/fix/crisp-line-icons
Icons: draw straight lines on whole device pixels
2026-10-07 05:57:34 -04:00
Brandon Thomas 98979fdf74 Merge pull request #127 from carlitosteso3/i18n-spanish
i18n: Spanish interface language (Español)
2026-10-07 05:57:31 -04:00
Brandon Thomas dc16c0e219 Merge pull request #126 from carlitosteso3/fix/packaging-metadata
Packaging: describe FilmCraft, not PhotoCraft, in package metadata (#94, #100)
2026-10-07 05:57:27 -04:00
Brandon Thomas 631235e8b2 Merge pull request #120 from justjohn12345/pr/timeline-scrolling
Timeline: the wheel scrolls as in Premiere, and the view cannot be lost
2026-10-07 05:57:23 -04:00
Brandon Thomas 2bfcd512c2 Merge pull request #79 from justjohn12345/pr/layer-corner-scaling
graphics: all eight layer handles scale towards the pointer
2026-10-07 05:57:19 -04:00
Brandon Thomas aa1143ea74 Merge pull request #109 from dcarnelutti/gpu/alpha-plane-upload
gpu: upload and composite the alpha plane of Y'CbCr frames
2026-10-07 05:57:15 -04:00
Brandon Thomas 36d8114d2f Merge pull request #118 from HEOJUNFO/fix/probe-pixfmt-from-config
codecs: MP4/MOV pixel format and alpha come from hvcC, avcC and the ProRes frame header (#103)
2026-10-07 05:57:10 -04:00
Brandon Thomas 79057f9c36 Merge pull request #102 from EthanSuquet/fix/mp4-duration-edit-list
codecs: an MP4/MOV clip lasts as long as its edit list plays it
2026-10-07 05:57:06 -04:00
Brandon Thomas cb69b55e56 Merge pull request #101 from EthanSuquet/fix/h264enc-corrupt-frames
h264enc: strict ffmpeg oracle that sees damaged slices (#74)
2026-10-07 05:57:01 -04:00
Brandon Thomas 7fcbaeab5e Merge pull request #83 from EthanSuquet/fix/webm-frame-lookup-rounding
codecs: look video frames up by the nearest timestamp unit (WebM at 30 fps drops every third frame)
2026-10-07 05:56:56 -04:00
Brandon Thomas 205e4bf68e Merge pull request #96 from punkhop/fix/move-onto-occupied-spot
timeline.move: report the clips an overwrite move covers
2026-10-07 05:56:52 -04:00
Brandon Thomas b8cc3925c3 Merge pull request #68 from punkhop/fix/clear-deletes-a-bin
project: Clear deletes a bin it is given, with everything in it
2026-10-07 05:56:48 -04:00
Brandon Thomas 6a0fca1cd1 Merge pull request #64 from punkhop/fix/xml-master-clip-keeps-its-bin
interchange: an FCP7 master clip lands in its bin when a sequence used it first
2026-10-07 05:56:44 -04:00
Brandon Thomas 05a731b309 Merge pull request #77 from justjohn12345/pr/test-fixes
Tests: fix seed_sweep overflow and the speed-dependent export progress test
2026-10-07 05:56:39 -04:00
Brandon ThomasandClaude Opus 5.5 df3b4ecbde Control: a connection's slot is freed even if its thread panics or can't start
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 05:56:23 -04:00
Peet GuercioandClaude Opus 5.5 ea68e14a39 Merge fix/audio-plays-ahead: the resampler runs inside playback_mix
Problem: both branches change start_audio, so the nightly updater stops on the conflict.
Solution: keep play-ahead's structure; the rate converter lives in playback_mix (now FnMut).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 00:52:42 -07:00
Peet GuercioandClaude Opus 5.5 a4ff06f4ad Audio: play a sequence on a device at another rate without phase jumps
Problem: with the device at another rate than the sequence (44.1 kHz
device, 48 kHz sequence), each buffer truncated its source start (phase
lost every block: a buzz), took the nearest sample (aliasing), and asked
the mixer for overlapping spans, so the mixer's graph cache missed every
buffer and rebuilt effect state.

Solution: audio-dsp StreamResampler interpolates each output sample from
its absolute position (exact rational), bit-identical however the stream
is cut, and pulls the source as one contiguous stream. start_audio uses
it when rates differ and restarts it when the rate or layout changes.

Context: tests cover block-size invariance at four rate pairs, a 1 kHz
tone within 3e-3, contiguous pulls, seeks and hostile input. Same lines
as #131; whichever lands second needs a small rebase.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 00:35:29 -07:00
Peet Guercio bf00c29b14 Merge remote-tracking branch 'origin/fix/ripple-trim-j-cut-head' into fix/ripple-trim-l-cut-head
# Conflicts:
#	crates/edit/src/lib.rs
#	crates/edit/src/tests.rs
#	crates/engine/src/split_edit_ripple_trim_tests.rs
2026-10-06 23:56:32 -07:00
Peet GuercioandClaude Opus 5.5 bb5d7ca0a6 Audio: mix playback 200 ms ahead so a busy Mac doesn't drop sound
Problem: playback decoded and mixed every ~10 ms device buffer inside the
cpal callback (AAC decode, effects, opening a clip's file at a cut, rayon,
locks). On a loaded Mac any stall missed the device deadline: static and
dropouts, different on every play.

Solution: play_ahead mixes on its own thread into a lock-free ring kept
200 ms ahead; the callback only copies. An underrun plays silence, is
counted, and the mixer skips the same span so sound stays locked to the
picture. Any device width plays the channels it shares with the mix.
perf.stats reports playback.audio (callbacks, underruns, missingFrames,
minLeadMs). The program mix moved to playback_mix so bench_audio can play a
real project through a simulated 48 kHz device and count dropouts.

Context: on a real 22-sequence project, load average 38-58, 15 s per cut:
mixing in the callback overran 8-170 times, mixing ahead 0 (ring never
below 149 ms). The web build keeps mixing in its callback (no threads).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 23:47:47 -07:00
carlitosteso3andClaude Opus 5.5 463a59c1b4 codecs: HE-AAC plays at its output rate; AAC export caps the bitrate (#108)
- aac: the decoder notes SBR data in fill elements (EXT_SBR_DATA /
  EXT_SBR_DATA_CRC), so implicitly signalled HE-AAC is recognised;
  Decoder::sbr() covers explicit signalling too.
- codecs: aac_output_rate() gives an AAC stream's output rate (the
  extension rate, or twice a <= 24 kHz core when SBR data is present); the
  MP4 reader reports it instead of the core rate, so sequences made from an
  HE-AAC clip get 44.1 kHz instead of 22.05 kHz. Our decoder now also takes
  explicitly signalled HE-AAC (it decodes the AAC-LC core) and, when the
  stream rate is twice the core rate, interpolates the core to it with a
  streaming half-band upsampler. The SBR high band is not reconstructed yet.
- export: the AAC bitrate is capped at 6 bits per sample and channel
  (ISO/IEC 14496-3 frame limit) instead of failing with "bitrate out of
  range" (320 kbps stereo at 22.05 kHz).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 22:28:30 -05:00
carlitosteso3andClaude Opus 5.5 96e9a00997 packaging: describe FilmCraft, not PhotoCraft, in package metadata (#94, #100)
The Linux, macOS, web and Windows packaging still carried PhotoCraft's
image-editor metadata.

- nfpm.yaml (#94): deb/rpm summary and description describe the video
  editor; filmcraft-cli is a command runner, MCP server and exporter;
  Debian section video instead of graphics.
- AppStream (#100): AudioVideo/Video/AudioVideoEditing categories, matching
  the desktop entry; video keywords; the screenshot is the README hero image
  (the old filmcraft-demo.jpg URL was a 404).
- macOS Info.plist.in (#100): export the .fcproj project type (JSON) instead
  of PhotoCraft's .pcraft; app category video; drop the PSB and QOI imported
  types, which FilmCraft does not read.
- filmcraft.wxs header comment: the MSI declares no file associations.
- web hosting guide: iframe title "FilmCraft video editor".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 22:06:08 -05:00
carlitosteso3andClaude Opus 5.5 ed535180cb i18n: Spanish interface language
Add Español next to English and 日本語 (Edit ▸ Language ▸ Español, also in the
native menu bar). SPANISH covers every menu, submenu and menu item label
(347 entries, Latin American Spanish); names, formats and percentages stay
as they are. A new test checks that every entry is a current menu label, so
a renamed command cannot leave a dead entry behind.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 22:06:02 -05:00
Peet GuercioandClaude Opus 5.5 066dcf5b98 Theme: menu items every 24 px, as in Premiere
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 20:02:13 -07:00
Peet GuercioandClaude Opus 5.5 f9ca62f67e Theme: interface type closer to Premiere's
Measured from Premiere screenshots at 1x: panel tabs and tooltips are a
humanist sans at 12 px; the big timecode is regular weight, 76 x 10 px
for 00:00:16:05, blue #4096f3; menus are the system's, 13 pt, #dedede.

- The interface face is Source Sans 3 (OFL), the closest open face to
  Premiere's, read from craft-fonts (CRAFT_FONTS_DIR) like the Japanese
  faces. Inter stays right behind it for symbols it lacks, and is the
  face when the app is built without craft-fonts. The web build embeds
  it too.
- The timecode over the timeline, under the Source and Program monitors
  and in the Reference Monitor is regular weight at 16 (Source Sans 3's
  width for Premiere's), in the timecode blue #4096f3 (also the scrubby
  value blue).
- The menu bar's menus and submenus are 13 pt in #dedede.

Tests: with craft-fonts, every weight of the interface text is Source
Sans 3 with Inter behind it; without, the interface keeps Inter; Japanese
still renders from craft-fonts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 19:48:51 -07:00
Peet GuercioandClaude Opus 5.5 3a48a99c94 Icons: draw straight lines on whole device pixels
The panel menu mark (≡) on the active tab was three 1.5 pt lines placed
at fractional positions, so at 1x they straddled pixels and anti-aliasing
made the gaps look uneven (3 px then 4 px). Every line icon had the same
half-pixel blur.

The icon pen now draws strokes a whole number of device pixels wide and
snaps every horizontal or vertical segment (and any that runs less than
a pixel sideways) onto the pixel grid, rounding from the icon's centre
the same way on both sides, so equal steps on the 16 grid stay equal on
screen at 1x and 2x. The tab's menu mark is now the Hamburger icon drawn
by the pen instead of hand-drawn lines.

Tests: every icon at 1x and 2x at four sizes off the pixel grid has only
whole-pixel straight lines; the menu mark's two gaps are equal at 1x,
1.5x and 2x.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 19:40:55 -07:00
Coy Geek 8d5acae231 docs: add star history chart to README
Show FilmCraft GitHub star growth with a linked Star History chart at the bottom of the README. Preserve the date view and top-left legend.
2026-10-06 19:33:01 -07:00
LuskishandClaude Opus 5.5 023127e146 Control: close the connection on input that isn't a request (#119)
A line that is not a JSON object with a string `method` (an HTTP request
line, other non-JSON text, a JSON array, invalid UTF-8, a line over 4 MiB)
now gets one error reply and the connection is closed, so a browser's
cross-origin fetch can't smuggle a command in its body. Connections are
capped at 16. Same transport as LightCraft (storytold/lightcraft#129).

Fixes #119.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 22:32:13 -04:00
Peet GuercioandClaude Opus 5.5 480b9e7655 Ripple trim: an L cut's sound stays only when its clip ends at the cut
A linked clip that spans the cut while its partner reaches past it too is
no L cut, and still refuses, like the same clip unlinked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 19:30:22 -07:00
Peet GuercioandClaude Opus 5.5 77d3b41a5c Ripple trim: a shorter head after an L cut keeps the earlier sound in place
A ripple trim that shortens a clip's head was refused when the previous
clip's linked sound ran on past the cut on a sync-locked track (an L cut).
That clip never moves, so its sound stays put and the L cut still ends
where it did. Unlinked material across the cut (a music bed) still refuses.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 19:21:38 -07:00
Peet GuercioandClaude Opus 5.5 fc5fcd3322 feat(ui): save your own workspaces, like Premiere
Problem: Window > Workspaces only had the nine built-in layouts; a layout
you arranged could not be kept, renamed or brought back.

Solution: one alphabetical list of built-in and user workspaces, plus
Save Changes to this Workspace, Save as New Workspace..., Reset to Saved
Layout and Edit Workspaces... (rename, delete; built-ins restore instead
of delete). Saved in workspaces.json beside preferences.json, so an older
build rewriting preferences never erases them. The workspace in use
reopens at launch; ui.set and window.workspace.<name> switch to user
workspaces like built-ins.

Context: tests in crates/ui-egui/tests/workspaces_ui.rs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 19:18:02 -07:00
justjohn12345andClaude Opus 5.5 0bcfcfff16 Timeline: the wheel scrolls as in Premiere, and the view cannot be lost
Three problems with scrolling the Timeline:

1. Cmd + wheel zoomed, like Option + wheel. egui turns Cmd + wheel into a
   zoom before the panel sees it, and the panel only knew "zoom" and "scroll
   sideways".
2. The plain wheel scrolled sideways; the tracks could only be scrolled up
   and down with Shift held.
3. The view could be scrolled without limit past the end of the sequence (39
   minutes past a 26 second one). There the zoom scroll bar's thumb sat at
   the right end and stayed there when dragged: the bar's range grew with the
   scroll position, so the view moved but the thumb did not.

Now, as Premiere Pro 26.5.2 does on macOS (checked in the app):
- wheel: the tracks under the pointer, up and down (video tracks above the
  divider, audio tracks below);
- Cmd + wheel: the Timeline, sideways;
- Option + wheel: zoom about the pointer.
The existing setting Timeline Mouse Scrolling ("Vertical" by default) is
wired up: "Horizontal" swaps the first two. A sideways gesture (trackpad
swipe, tilt wheel, Shift + wheel) always scrolls sideways and a pinch zooms.
The wheel is read from its events, with their own modifiers.

The Timeline ends ten minutes past the end of the sequence, where Premiere's
view stops too, and the view is kept inside it however it is moved (wheel,
scroll bar, zoom, a script; not-a-number positions are reset).

The zoom scroll bar spans that extent. Its thumb is as wide as the share in
view, never narrower than 34 points, and its travel covers the whole scroll
range: it reaches both ends of the bar and stays under the pointer while
dragged (the drag follows the pointer's position, not a sum of steps). A
click or press beside the thumb brings the thumb there. The handles at its
ends zoom as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 22:14:00 -04:00
justjohn12345andClaude Opus 5.5 f6d78f7e0c Sequence: the Add Tracks dialog's fields span its width
The placement and track type lists had a fixed width, narrower than the
dialog, which left an empty band down its right side. Each row is now a label
in a column as wide as the widest label and a list that takes the rest of the
row, up to the group's right edge, as in Premiere's dialog.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 21:45:38 -04:00
heojunfoandClaude Opus 5.5 f761a299a7 codecs: MP4/MOV pixel format and alpha come from hvcC, avcC and the ProRes frame header (#103)
The probe guessed the pixel format from the codec profile alone: HEVC
reported nothing, H.264 High 4:2:2 had no bit depth, and ProRes 4444
claimed alpha because of its fourcc.

- HEVC: chroma format and bit depth from hvcC.
- H.264: from the avcC High-profile extension (ISO/IEC 14496-15 §5.3.3),
  else from the first SPS; unknown (empty) if neither can be read.
- ProRes: the first frame header gives the chroma format and alpha
  (alpha_channel_type), as the first DNx frame header already does.

Checked against ffprobe on ffmpeg-made HEVC 4:2:0/4:2:2 8/10-bit,
H.264 4:2:0/4:2:2 8/10-bit and ProRes 422 HQ / 4444 with and without
alpha. Unit tests cover hvcC, avcC (extension and SPS fallback) and
ProRes 4444 with and without alpha.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-07 10:44:38 +09:00
justjohn12345andClaude Opus 5.5 13a0da9c2b Sequence: Add Tracks… opens Premiere's dialog (amount, placement, track type)
Sequence ▸ Add Tracks… added one video track at once: no dialog, and no way
in the interface to add an audio track.

It now opens the dialog Premiere Pro 26.5.2 shows, checked in the app:
- "Add video tracks": Amount, Placement.
- "Add audio tracks": Amount, Placement, Track type (Standard, 5.1, Adaptive,
  Mono).
- "Add audio submix tracks": Amount, Placement, Track type (Stereo, 5.1,
  Adaptive, Mono); its placement is off while the sequence has no submix
  track.
Placement is "Before First Track" or after one of the tracks, after the last
by default. The defaults are Premiere's: one video and one audio track, no
submix track. OK is one undo step.

`sequence.addTracks` takes the same choices as params (`videoAfter`,
`audioAfter`, `submixAfter`, `audioType`, `submix`, `submixType`) and returns
the new tracks' ids. Called without a place it still appends, and without
amounts it still adds one video track, so scripts keep working; only the menu
item opens the dialog. Tracks are numbered by their place, as in Premiere: a
track added after Video 1 is the new Video 2 and default names above it move
up, while a name the user gave is kept.

Amounts were not checked before (any number of tracks was created). At most
99 tracks are added at a time and a sequence has at most 999 of a kind; a
wrong amount, place or type is an error that changes nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 21:39:03 -04:00
justjohn12345andClaude Opus 5.5 1ebc1440e7 NEST11: the architecture doc says a plain nest's layers go into the frame plan
docs/architecture.md still listed every nested sequence among the things
rendered on the CPU and handed to the GPU as one image. Since NEST11 that
holds only for nests that are not plain.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 20:53:53 -04:00
justjohn12345andClaude Opus 5.5 e13151d87b NEST10: the captions doc says nested captions are part of the nest's picture
docs/captions.md still said nested sequences do not burn in their own
captions. Since NEST10 the captions of a nested sequence are drawn wherever
the nest is shown, in the Program monitor and in exports.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 20:53:53 -04:00
justjohn12345andClaude Opus 5.5 9b31f4eb84 NEST15: nested sequences in AAF and OMF, the way Premiere Pro writes them
A nested sequence was left out of both formats as a gap, with a report entry
telling the user to "render and replace" it first (a command FilmCraft does
not have). An AAF with nested compositions was read with gaps in their place.

What Premiere Pro 26.5.2 does, read off files it exported for a sequence with
a nest:
- AAF: the nested sequence is a composition mob of its own, and its clips are
  source clips that point at it.
- OMF: the nested sequence's sound is rendered into the document as one clip
  named after the sequence.

Export
- AAF: a nested sequence is written as a composition mob (no usage code; the
  exported sequence stays the top-level one). A clip of it is a source clip
  at that mob's first slot of the clip's kind, its start in that slot's edit
  units. Nests in nests are followed; a nest used twice is written once. With
  embedded or consolidated audio, the media of the clips inside a nest is
  prepared with the rest (`NestNeeds::Inside`).
- OMF: `audio_needs` lists the range of the nested sequence each nest clip
  plays (`NestNeeds::Render`); the engine mixes it through the export audio
  pipeline with what is on the clip, and it is written as media. Without that
  essence the nest is a gap and the report names the sequence.

Import (AAF)
- A source clip that points at a composition becomes a clip of a nested
  sequence; the composition is read once.
- Premiere Pro's layout is read: all video tracks in one slot (a nested scope
  with a segment per track; before, only the last segment was read, so a
  Premiere AAF came in with one video track), and "top-level" tagged on nested
  compositions too (top-level are those no other composition uses).
- A composition without a frame size takes that of the first picture it
  shows, not of the first picture in the file.

A sequence that claims to be inside itself is a gap with a report entry in
both directions; the walks are bounded (16 levels).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 20:53:34 -04:00
justjohn12345andClaude Opus 5.5 12585410b3 NEST15: a nested sequence is reel AX in an EDL, in every reel mode
The export report already said a nested sequence is written "as a single
source (reel AX)", but the reel came from the reel mode: with the default
(file name) a nest called "Nested Sequence 02" got reel NESTED_S. A nested
sequence has no tape and no file, so its reel is now AX whatever the mode.

Premiere Pro 26.5.2 writes the same for a nest (seen in an EDL it exported):
one event from reel AX, the nested sequence's name in "FROM CLIP NAME", and
the nested sequence's own time as source timecode. A test pins that event.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 20:53:19 -04:00
justjohn12345andClaude Opus 5.5 cdd9836705 NEST13: the panel menu closes on a click elsewhere and on Escape
Found while looking at the tab menu in the running app: once open, a panel
menu stayed open until one of its entries was chosen. It was meant to close on
a click elsewhere, but the test for that needed the press and the release of
the click in the same frame, which a real mouse never delivers. A right-click
on a tab now opens the menu, so the stuck menu was easy to run into.

The menu now remembers the frame it opened in (the click that opens it is not
a click elsewhere) and closes on any later click outside it, or on Escape. A
right-click on another tab moves it to that tab.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 20:29:41 -04:00
justjohn12345andClaude Opus 5.5 eeec772671 NEST14: a project reopens with its sequence tabs and their views
Premiere Pro 26.5.2 reopens a project with the same sequence tabs, in the
same order, the same one shown, each at the zoom it was left at. FilmCraft
opened every project on its first sequence; the "Restore open sequences when
opening projects" preference existed and nothing read it.

A saved project file now has a `view` beside `project`: the open sequences in
tab order, the active one, and each sequence's view from NEST12. It is not
part of the project: no undo step, no "edited" mark, and no schema bump (older
builds ignore it). `file.open` restores it when the preference is on.

Nothing in the view is trusted. Ids that are not sequences of the project and
repeats are dropped, numbers are clamped, and a view that cannot be read is
ignored instead of failing the open. A view with no open sequence leaves the
project on its first sequence, so a project saved by a script or the CLI does
not open on an empty Timeline.

Opening or recovering a project now tells the frontend which sequence is
shown, so the Timeline takes that sequence's view.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 20:23:19 -04:00
justjohn12345andClaude Opus 5.5 6cff0f0b5d NEST13: sequence tabs get Premiere's menu, drag to reorder and a list for tabs that do not fit
Checked in Premiere Pro 26.5.2: a right-click on a sequence tab that is not
shown shows it and opens the panel menu, which has "Close Panel", "Close Other
Timeline Panels" and "Reveal Sequence in Project"; a dragged tab follows the
pointer and its neighbours make room.

- A right-click on any tab shows it and opens its panel menu.
- The Timeline's menu gains "Close Other Timeline Panels" (new command
  `sequence.closeOthers`); its entries have automation ids
  (`panel.menu.Timeline.close`, `.closeOthers`, `.revealSequence`).
- A sequence tab dragged sideways changes places with a neighbour when the
  pointer passes that neighbour's middle (new command `sequence.moveTab`).
- Tabs that do not fit: the shown tab is always in the strip (tabs before it
  are left out until it fits), and the chevrons at the right end open a list
  of every tab instead of stepping to the next one. Ids `timeline.tabs.more`
  and `timeline.tabs.list.<sequence>`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 20:23:07 -04:00
justjohn12345andClaude Opus 5.5 6aefdef661 NEST12: every sequence keeps its own Timeline zoom, scroll and track heights
The Timeline had one view for all sequence tabs, and showing another sequence
fitted it to the panel every time. In Premiere Pro 26.5.2 each sequence tab
has its own zoom and its own track heights (expanding the tracks of one
sequence leaves the others as they were).

Each sequence now has a `SequenceView` (zoom, horizontal scroll, the vertical
scroll of the video and audio halves, video and audio track height) in
`EditorState::timeline_views`. The panel's view is the active sequence's: it
is put away when another sequence is shown and taken back when the sequence is
shown again, also when a tab is closed. A sequence shown for the first time is
fitted, at the default track heights. A view changed in the session (a
command, the control channel) is taken over by the panel. The view of a
deleted sequence is dropped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 20:21:19 -04:00
justjohn12345andClaude Opus 5.5 5e730ab020 NEST11: the frame plan draws a plain nest's layers itself; a nest's sound clip gets a waveform
Frame plan. A nest was always handed to the compositor as one image rendered
on the CPU. A plain nest (same frame size and colour settings as the sequence
it is in, no effects, masks, opacity, blend mode or motion on the clip, every
layer inside it blended normally, not a multicam angle) now contributes its own
layers to the plan, with its captions, so the GPU composites them directly.
Nests in nests are followed up to the nesting depth limit. Anything that is
not plain is planned as one image as before.

Waveforms. Premiere draws a waveform on the sound clip of a nest. The Timeline
now mixes the nested sequence in the background (under `catch_unwind`), keeps
one peak per 256 samples, and mixes again when the sequence's sound changes,
showing the old waveform until the new one is ready.

Tests: a plain nest is planned as its own layers and looks the same as the
reference render, also nested twice and over another layer; five kinds of nest
that are not plain are still drawn right; a nest's sound clip gets a waveform
that follows its sequence.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 19:52:28 -04:00
justjohn12345andClaude Opus 5.5 a8b803c7a9 NEST10: a nest's sound follows its speed, direction and effects; its captions are part of its picture
Sound. A nest's audio went around the path that clips of media take, so speed,
reverse and the clip's audio effects did nothing to it, and a nested sequence
at another sample rate was mixed at the outer rate without converting. The
nested mix is now read through the same path as a media source (`effected`
takes a reader instead of a `MediaSource`): it is mixed at the nested
sequence's own rate, resampled to the outer one, and then goes through speed,
reverse and the clip's effects like any clip. The nesting depth limit still
applies.

Captions. Premiere Pro 26.5.2 draws the captions of a nested sequence in the
sequence it is nested in, as part of the nest's picture. A nested sequence is
now rendered with its captions whether or not the outer sequence shows its
own, and the preview cache key of a nest covers its caption tracks.

Tests: a nest sounds as its sequence does, keeps pitch and timing at another
sample rate, changes with speed and reverse like a clip, and starts later when
trimmed in; speed, reverse and frame hold pick the right frame of the nested
sequence; opacity and a Crop effect apply to the nest's whole picture; nested
captions are drawn and outer ones only when asked for.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 19:52:20 -04:00
justjohn12345andClaude Opus 5.5 642d3b2800 NEST9: a nest of another size or frame rate, and Fit / Fill frame in the clip menu
A nested sequence whose frame size differs from the sequence it is in comes in
centred at its own size with Scale 100, as in Premiere Pro 26.5.2 (a 1280x720
nest in a 1920x1080 sequence). The clip context menu gains Premiere's "Fit to
frame" and "Fill frame" next to "Scale to Frame Size".

Tests pin the behaviour: a smaller nest sits in the middle, a larger one is
cropped by the frame, a nest at another frame rate shows its sequence at the
same moment, Fit and Fill frame set Scale to 150 for that pair of sizes, and
Scale to Frame Size fills the frame and leaves Scale alone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 19:50:27 -04:00
justjohn12345andClaude Opus 5.5 5ce9fbb48a NEST8: Multi-Camera submenu in the clip context menu
Enable (ticked when on), Flatten, and the cameras of the selected nested
sequence clip to switch to; greyed out when no selected clip is a nested
sequence. The commands already existed in the Clip menu.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 19:25:01 -04:00
justjohn12345andClaude Opus 5.5 4164fa2e7c NEST6: Reveal in Project and Reveal Sequence in Project
clip.revealInProject (clip context menu) selects the clip's source in the
Project panel and shows it there: the panel comes forward with the search
cleared, the list opens the bins on the way, and the icon and freeform views go
into the bin that holds the item. sequence.revealInProject (Timeline tab menu)
does the same for the sequence being edited.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 19:24:41 -04:00
justjohn12345andClaude Opus 5.5 598268721a NEST5: a sequence in the Source Monitor is marked and edited in like a clip
Mark In / Mark Out on a sequence loaded in the Source Monitor did nothing: the
marks were only stored for media. They are now the sequence's own In and Out, so
Insert and Overwrite edit in the marked part (as a nest, or as its clips with
the nest toggle off).

Tests also pin Match Frame on a nest: it loads the nested sequence at the frame
the nest shows, through a trim and a speed change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 19:23:45 -04:00
justjohn12345andClaude Opus 5.5 559a8b7543 NEST4: the nest toggle edits a sequence in as a nest or as its clips
The Timeline's "Insert and overwrite sequences as nests or individual clips"
button was drawn always on and did nothing. It now toggles
(sequence.nestSequences). Off, a sequence is edited in as its clips, as observed
in Premiere Pro 26.5.2: the clips come with their transitions and links, the
source's tracks that hold clips go to consecutive tracks from the destination
track up, and missing tracks are added. A sequence can then go into itself as
plain clips. Multi-camera sources stay one clip.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 19:23:17 -04:00
justjohn12345 642cfb6bdf Merge branch 'pr/nested-safety' into pr/nested-editing 2026-10-06 19:10:58 -04:00
justjohn12345 29fd297045 Merge branch 'pr/sequence-tabs' into pr/nested-editing 2026-10-06 19:10:58 -04:00
justjohn12345andClaude Opus 5.5 ca489f9fce NEST2: Nest and Make Subsequence as Premiere Pro 26.5.2 does them
Observed in the app on 2026-10-06 (about 35 test nests):

- The nest is a linked picture + sound pair only when the selected sound is on
  one track and that track is free for the nest's length. With sound on several
  tracks, or another clip in the way on its track, the nest is picture only: the
  selected sound stays in the sequence (unlinked) and a copy with its own ids
  goes into the nest. How many video tracks the selection uses does not matter.
- Where the picture goes. With L the lowest selected video track and `a` the
  number of the highest audio track holding selected sound, it takes the lowest
  track T from L up such that T is free for the nest's whole length, and so is
  every video track numbered from T up to a - 1 that the selection had clips on.
  If none will do, a new track is added. Before, the nest could land on top of
  an unselected clip.
- In the new sequence, picture tracks keep their positions up to the highest one
  used. Sound tracks are A1 followed by the other tracks used, in order
  (A1 + A3 become A1, A2; A3 alone becomes an empty A1 and A2).
- After Nest nothing is selected in the timeline and the new sequence is
  selected in the Project panel; clip.nest returns the nest's clips.
- Make Subsequence loads its result in the Source Monitor.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 18:23:01 -04:00
mweinbach 15787f7fe8 Codecs: add clean-room APV (RFC 9924) decoder, encoder, container support, and export presets 2026-10-06 17:24:34 -04:00
justjohn12345andClaude Opus 5.5 fc557a1c10 NEST3: a nest follows its contents
A nest keeps its length when its sequence changes. Tests now pin what already
held: it trims out to reveal added material and no further, shows and plays
nothing past shortened contents, and the outer sequence shows edits made inside.

New: the Timeline hatches the part of a nest past the end of its contents, as
Premiere does (Project::nest_overhang, automation id timeline.clip.<id>.empty).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 17:23:38 -04:00
justjohn12345andClaude Opus 5.5 094ea74bde NEST2: Nest keeps transitions, track names and channel layouts
Nest… copied only the clips: transitions between them were lost and the new
sequence's tracks had default names and stereo layouts. Transitions whose clips
are all nested now go into the nest with them, and the tracks are laid out like
the parent's (shared with Make Subsequence). Clips on locked tracks are left out
instead of being duplicated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 17:23:38 -04:00
justjohn12345andClaude Opus 5.5 29d9d0ac5a NEST1: a sequence can never contain itself
A sequence placed inside itself (directly or through another nest) crashed the
app: nested audio mixing and the frame plan's multi-camera shortcut recursed
until the stack overflowed.

- render: the audio mixer and the multi-camera shortcut follow nests to the same
  depth as the picture (MAX_NEST_DEPTH), then give silence / fall back.
- project: Project::nest_cycle finds a sequence that contains itself.
- engine: every edit that would create one is refused, whichever command asks
  (place, Source insert/overwrite, paste, ...). A project opened with a cycle
  already in it can still be edited and repaired.

Regression tests: both crashes (stack overflow before), the refusals, repair.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 17:23:38 -04:00
Peet GuercioandClaude Opus 5.5 7f77bdfd3a Ripple trim: a head trim grabbed by its early sound uses the picture's cut
Sync-locked tracks rippled from the grabbed member's start, so grabbing a
J cut's early sound checked and shifted from before the picture's cut and
was refused. For a head trim the cut is the latest member's start. Adds the
test only the new stretch catches: a clip starting at the cut on a
sync-locked track, which the old stretch let fall out of sync.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 14:22:13 -07:00
Peet GuercioandClaude Opus 5.5 27124080bf Ripple trim: a shorter head closes the stretch after the cut
A ripple trim that shortens a clip's head was refused as a sync-lock
conflict whenever a sync-locked track held material just BEFORE the cut,
because the check looked at the stretch before it. With a J cut that is
the outgoing clip's sound on the other audio track, so the J-cut take
could never lose its head. The stretch that closes is the one just after
the cut; the clip's own linked partners stay the caller's to trim.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 14:16:39 -07:00
Dario CarneluttiandClaude Sonnet 5.5 1b92ea210b gpu: upload and composite the alpha plane of Y'CbCr frames
The GPU compositor uploaded only the Y, Cb and Cr planes of a Yuv8/Yuv16 frame and
the shader returned alpha 1.0 for them, so a ProRes 4444 overlay (banner, lower third,
outro) was drawn opaque in the Program monitor and covered the footage under it.
Exports were correct because they use the CPU compositor.

Frames with an alpha plane now upload it as a fourth texture (R8Unorm, or R16Float
converted like the other planes), bound at binding 5 of the layer and blend layouts.
A uniform slot (p3.y) carries the alpha scale (0 = no alpha plane); the shader reads
the alpha at full resolution and premultiplies the linear colour by it.

Adds gpu_draws_yuv_alpha_plane_like_the_cpu: an alpha ramp over an opaque layer at
8, 10 and 12 bits, GPU against the CPU compositor. It fails without the change
(p99 diff 190/255) and passes with it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-06 15:04:48 -06:00
justjohn12345andClaude Opus 5.5 3f7fd8252f Timeline: tab menu says Close Panel, as Premiere's does; test finds the nest by its sequence
Checked in Premiere Pro 26.5.2: the tab's menu item is "Close Panel" and it
closes that sequence's tab. Premiere also leaves nothing selected after Nest,
so the tabs test no longer relies on the selection to find the nest clip.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 16:46:18 -04:00
EthanSuquetandClaude Opus 5.5 1f2f20a700 codecs: an MP4/MOV clip lasts as long as its edit list plays it
The clip duration came from the media duration (`mdhd`), which runs on
the decode timeline. ffmpeg / x264 MP4s with B-frames skip the reorder
delay with an edit, so every one imported a frame too long (a 120-frame
file became 121 frames, the last a held repeat). A video track delayed
by a leading empty edit was a frame short, and its last frame could not
be reached.

Use the sum of the track's edits (movie timescale, what `tkhd` records)
when there is an edit list. Fragmented files, and edit lists that add up
to nothing or overflow a Tick, keep the media duration.

Tests: a unit test with crafted edit lists (skip, empty edit, hostile
sizes) and an ffmpeg oracle test (libx264 with B-frames: 60 frames,
was 61).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 16:37:06 -04:00
Peet GuercioandClaude Opus 5.5 dfaf31bfec Timeline: timeline.move reports the clips an overwrite move covers
An overwrite move shortens, splits or removes whatever already sits where a
clip lands, as Premiere's drag does, but the reply only named the clips it
moved: a script moving clips one at a time never learned that an earlier move
had cut one it had not reached yet. The reply now lists each covered clip
under `overwritten` with its length before and after and the ids what is
left of it lives on as. The edit itself is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 13:19:04 -07:00
EthanSuquetandClaude Opus 5.5 3eae70b11e h264enc: strict ffmpeg oracle that sees damaged slices (#74)
ffmpeg prints "corrupt decoded frame" as a warning, so the oracle's
`-v error -ec 0` decode let a stream with a whole slice missing pass
silently. Switching that decode to `-v warning` is not enough: with
`-ec 0`, ffmpeg 7.1/8.1 flags every picture that has more than one
slice, libx264's multi-slice streams included, while the pixels are
unchanged. That is the 119/120 in #74; the encoder's bitstream is not
at fault (VideoToolbox decodes the same streams bit-identically, and
ffmpeg with strict error detection reports nothing).

The oracle now decodes with ffmpeg's default concealment, `-v warning`
and `-err_detect +crccheck+bitstream+buffer+explode`, fails on any
output or a non-zero exit, and still compares every pixel with the
encoder's reconstruction. A negative control drops and truncates
slices (CAVLC and CABAC, 3 slices) and checks the oracle reports each
one; it fails with the old flags.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 16:02:53 -04:00
EthanSuquetandClaude Opus 5.5 2b49201e84 codecs: video frames are looked up by the nearest timestamp unit, so a 1 ms WebM shows every frame
Problem (#73): a 30 fps WebM played and exported with every third frame
missing and the frame before it shown twice (20 unique frames a second).
The same happens at 29.97, 60, 59.94, 24 and 23.976 fps, and with MP4
files whose video track has a 1 ms timescale. 25 and 50 fps were fine.

Cause: Matroska stores block timestamps in TimestampScale units (usually
1 ms), rounded to the nearest unit, so at 30 fps frame 2 (66.67 ms) is
stored as 67. MkvSource::video_frame converted the requested time to track
units with a floor (66), and the lookup (last sample with pts <= target)
returned frame 1. Every frame whose timestamp was rounded up was skipped.
Mp4Source::video_at, and the web build's WebCodecs MP4 path, floored the
same way against the track timescale; normal MP4 timescales hold frame
times exactly, so only coarse (1000) timescales were hit.

Fix: new Tick::to_rational_round (nearest unit, halves up, total for zero
and negative timebases), used for the video lookup target and the
catch-up threshold in mkv.rs, mp4.rs and webcodecs.rs. A requested time
now matches a frame whose stored timestamp is within half a unit of it,
the same precision the timestamps have. Truncating muxers (stamps rounded
down) still work. Times on exact timebases (90 kHz, 15360, 30000/1001…)
convert exactly as before.

Test: crates/codecs/src/rounded_pts_tests.rs builds synthetic Motion-JPEG
streams in the test (each picture shows its index as black/white blocks),
muxed as WebM with 1 ms timestamps and as MOV with a 1000 timescale, at
30, 29.97, 60, 59.94, 24, 23.976 and 25 fps with nearest and truncated
stamps. Requesting every frame's start over 3 s must show every frame
exactly once, and every frame's midpoint must show that frame. Before the
fix both tests failed ("30 fps, Nearest ms stamps: 30 of 90 frames never
shown [2, 5, 8, 11]…, 30 shown twice [1, 4, 7, 10]…"). The time crate
tests cover the rounding, ties and hostile timebases.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 15:16:37 -04:00
Brandon Thomas 771b614ad4 Merge pull request #81 from storytold/pr/craft-fonts
Fonts: use craft-fonts as an optional build input (Japanese UI and title fallback)
2026-10-06 15:08:06 -04:00
Brandon ThomasandClaude Opus 5.5 7f8e102b13 Fonts: the Japanese interface uses craft-fonts first; absolute CRAFT_FONTS_DIR
The merged Japanese interface (#38) looked only for a system font. When
FilmCraft is built with craft-fonts, theme::install already appends the
Japanese faces to every font family, so switching to Japanese uses them
(no system scan) and works on the web too; otherwise it falls back to an
installed system font as before. Docs use an absolute CRAFT_FONTS_DIR
(build.rs runs in crates/text, so a relative path resolves from there).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 14:26:14 -04:00
justjohn12345andClaude Opus 5.5 b0aeabdb8d graphics: all eight layer handles scale towards the pointer
A corner handle scales both axes alike with the opposite corner held in place;
the edge handles (top, right, bottom, left) are now grabbable and stretch only
their own axis with the opposite edge held in place.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 14:17:29 -04:00
justjohn12345andClaude Opus 5.5 c80d23fd2e graphics: a corner handle scales the layer away from the opposite corner
Dragging a corner handle of a graphic layer in the Program monitor scaled about
the layer's anchor, so a text layer (anchor at its bottom-left) grew up and to
the right whichever corner was dragged. The opposite corner now stays in place.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 13:52:20 -04:00
justjohn12345andClaude Opus 5.5 ea491ef467 automation: the export progress test no longer depends on machine speed
A short export can finish inside one 100 ms poll, which left a single progress
notification and no time to answer the ping. The test now tries longer exports
until one outlasts a few polls, and cancels a longer one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 13:51:43 -04:00
justjohn12345andClaude Opus 5.5 10b007cea9 Timeline: sequence tabs, Premiere-style clip menu, Nest name dialog
- The Timeline panel shows one tab per open sequence (x closes the active one);
  closing a sequence keeps the panel, and opening one restores a closed panel.
- Double-clicking a nested sequence clip opens it in its own tab.
- The clip context menu follows Premiere's grouping and adds Paste/Remove
  Attributes, Ungroup, Synchronize, Merge Clips, Make Subsequence, Reveal Nested
  Sequence and the frame hold / field options; right-click selects the clip.
- Nest... asks for the name (Nested Sequence Name) and numbers the default.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 13:51:43 -04:00
justjohn12345andClaude Opus 5.5 fb824c6fb0 mpeg2v: seed_sweep derives its seeds without overflowing
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 13:51:43 -04:00
Brandon ThomasandClaude Opus 5.5 9953befe28 Fonts: use craft-fonts as an optional build input
crates/text/build.rs embeds the fonts of a storytold/craft-fonts checkout
named by CRAFT_FONTS_DIR as filmcraft_text::fonts::CRAFT_FONTS (native:
all of them; wasm32: only BIZ UDPGothic Regular). Unset, CRAFT_FONTS is
empty and nothing changes. A bad CRAFT_FONTS_DIR is a warning, or an
error with CRAFT_FONTS_REQUIRED=1. Never a Cargo dependency, no network.

- UI: the Japanese faces are the last fallback of every egui font family
  (BIZ UDPGothic first, Bold first in the semibold/medium families).
- Text engine: registered after the bundled faces; fallback_for picks
  them after the bundled faces and before system faces (Mincho for serif
  text, Gothic otherwise, nearest weight).
- Tests: Japanese glyphs (no tofu) in the UI and title paths, skipped
  without craft-fonts; the theme works with CRAFT_FONTS empty.
- Release: every build job checks out craft-fonts at a pinned commit and
  builds with CRAFT_FONTS_DIR + CRAFT_FONTS_REQUIRED; packages carry
  OFL-<family>.txt. NOTICE, ATTRIBUTION.md (optional build input), AGENTS.md,
  CLAUDE.md, README and docs/contributing.md describe it.

FilmCraft main bundles no Japanese font, so no font files move.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 11:40:29 -04:00
Brandon Thomas a2f6ba8b44 Merge pull request #72 from storytold/pr/docs-hw-decode-correction
Docs: hardware decode correction; log the 2026-10-06 community batch
2026-10-06 11:39:47 -04:00
Brandon ThomasandClaude Opus 5.5 83481c146f Docs: hardware decode was only active in the desktop app since #41; log the 2026-10-06 community batch
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 11:39:41 -04:00
Brandon Thomas 5c8471c9f4 Merge pull request #41 from justjohn12345/pr/decode-memory
MEM1–MEM4 + HW1: clip memory on a timeline from 12 GB to 1.9 GB; hardware decode actually on
2026-10-06 11:38:03 -04:00
Brandon Thomas 37361900a9 Merge pull request #38 from midasdf/feat/japanese-interface-language
i18n: Japanese interface language (uses an installed system font)
2026-10-06 11:37:57 -04:00
Brandon Thomas e89feeac4d Merge pull request #58 from punkhop/fix/speed-ripples-linked-clips-once
edit: a speed change with ripple moves later clips once
2026-10-06 11:37:52 -04:00
Brandon Thomas 555bfe7c18 Merge pull request #57 from punkhop/fix/ripple-delete-split-edit
edit: ripple delete closes one gap for a clip with a split edit
2026-10-06 11:37:47 -04:00
Brandon Thomas 5dd09386f6 Merge pull request #56 from punkhop/fix/ripple-trim-keeps-split-edit
edit: a ripple trim takes a later split edit along
2026-10-06 11:37:42 -04:00
Brandon Thomas 475c294678 Merge pull request #45 from punkhop/fix/move-linked-partners
engine: timeline.move takes linked partners along
2026-10-06 11:37:38 -04:00
Brandon Thomas 51026bd2b2 Merge pull request #60 from punkhop/fix/place-on-a-sound-track
engine: timeline.place on an audio track places the sound there
2026-10-06 11:37:32 -04:00
Brandon Thomas d886d2f322 Merge pull request #44 from punkhop/fix/unknown-track-is-an-error
engine: naming a track that does not exist is an error
2026-10-06 11:37:28 -04:00
Brandon Thomas 39ef62607d Merge pull request #47 from punkhop/fix/app-help-and-unknown-flags
filmcraft: --help prints usage and an unknown option is an error
2026-10-06 11:37:22 -04:00
Brandon Thomas 8dfa8fff4c Merge pull request #52 from punkhop/fix/explicit-targets-enable
engine: a command whose targets are named in the parameters does not need a selection
2026-10-06 11:37:16 -04:00
Brandon Thomas 8a795324f4 Merge pull request #50 from punkhop/fix/replace-reports-short-media
engine: Replace With Clip reports clips that run past the new media
2026-10-06 11:37:11 -04:00
Brandon Thomas eb3ca3e811 Merge pull request #49 from punkhop/fix/replace-from-bin-keep-source-in
engine: clip.replaceFromBin can keep the clip's source In
2026-10-06 11:37:05 -04:00
Brandon Thomas 950879ef10 Merge pull request #59 from punkhop/fix/inspect-reports-reverse
engine: sequence.inspect reports a reversed clip
2026-10-06 11:36:58 -04:00
Brandon Thomas 7377def476 Merge pull request #48 from punkhop/fix/sequence-inspect-readback
engine: sequence.inspect reports clip ends, gain and marker comments
2026-10-06 11:36:53 -04:00
Brandon Thomas 5bc07026c7 Merge pull request #43 from punkhop/fix/import-auto-points
engine: a project saved after an interchange import opens again
2026-10-06 11:36:46 -04:00
Brandon Thomas a3b077877f Merge pull request #51 from punkhop/fix/interchange-export-reports-dropped-graphics
interchange: an export names every title it cannot carry
2026-10-06 11:36:41 -04:00
Brandon Thomas a407099019 Merge pull request #46 from punkhop/fix/export-interchange-unknown-format
engine: file.exportInterchange refuses an unknown format
2026-10-06 11:36:36 -04:00
Brandon Thomas bccc3dd031 Merge pull request #42 from punkhop/fix/mp4-audio-thumps
codecs: resampled MP4 audio reads apply the edit list once
2026-10-06 11:36:31 -04:00
Brandon Thomas bd40764756 Merge pull request #69 from storytold/pr/windows-arm64
Windows on ARM64: release builds, PE header check, install test on ARM64 hardware
2026-10-06 10:10:16 -04:00
Brandon ThomasandClaude Opus 5.5 e6d693cc24 Windows ARM64 workflow: pin third-party actions by commit
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 09:51:06 -04:00
Brandon ThomasandClaude Opus 5.5 ac906666d9 Windows on ARM64: release builds, PE header check, install test on ARM64 hardware
Release builds add an arm64 MSI and portable zip, cross-compiled on the x64
runner (signing and WiX as for x64). package.ps1 checks each binary's PE
header before packaging: Machine must match -Arch, the app must be a GUI
program and the CLI a console program. It skips the CLI smoke run when an
ARM64 build can't run on the host. A new Windows ARM64 workflow packages the
ARM64 MSI, installs it on a Windows 11 ARM64 runner, checks both installed
exes are ARM64, runs the CLI, and uninstalls. Ported from printcraft#66.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 09:38:38 -04:00
Brandon ThomasandClaude Opus 5.5 6a9fdce2ef codecs: released decoders are dropped off the cache lock; dirty-pool bit-exact test
trim_decoders dropped the decoders it took from idle caches while the requesting cache's lock was held. Dropping a decoder can block (a VideoToolbox session waits for its frames in flight), so the render path paid that latency under the lock. trim_decoders now returns the released decoders and frame_late keeps them in a local declared before its lock guard, so they drop after the guard on every return path; the cap is enforced exactly as before.

New tests/pool_bitexact.rs: primes the frame pool with 0xAA-filled plane buffers, then decodes an H.264 fixture into them; every frame must match ffmpeg bit for bit, and the pool must report the reuse.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 09:16:09 -04:00
punkhop 64d41b266a project: Clear counts each item and bin once
A bin inside another named bin goes with it and is not counted again;
an item named and also inside a named bin is counted once. The reply's
counts now match what went. The params line stays {"items":[id]?} so
a caller naming targets keeps the same shape as before.
2026-10-06 06:10:56 -07:00
punkhop 8e867cb8c9 project: Clear deletes a bin it is given, with everything in it
Problem: no command could delete a bin. `project.delete` takes item
ids, and a bin's id passed to it answered ok and changed nothing, so a
bin emptied after an XML import (every clip moved to new bins) stayed
in the project for good.

Solution: `project.delete` also accepts bin ids in `items`. A bin
named there is taken out of the tree with its sub-bins, and every item
inside goes the way a named item goes (out of the project, off every
timeline). The project's own top bin is never removed. The reply now
says how many items and bins went. One undo step, as before.

Test: clear_deletes_a_bin_with_everything_in_it (fails before: the
bins stay).
2026-10-06 06:06:34 -07:00
Brandon ThomasandClaude Opus 5.5 47c6b03681 filmcraft: --help, --version and argument errors show a message box on Windows
Windows release builds have no console (windows_subsystem = "windows", added on main after this branch), so --help printed nothing and an unknown option or a bad FILMCRAFT_CONTROL_PORT quit with exit code 2 and no visible message. The text is still printed, and on Windows release builds also shown in a message box.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 09:05:59 -04:00
Brandon Thomas 39d81aee14 Merge remote-tracking branch 'origin/main' into pr-47-fix 2026-10-06 08:46:53 -04:00
Brandon ThomasandClaude Opus 5.5 2f49131f64 edit: speed changes refuse NaN and never overflow the timeline
set_speed_group accepted NaN (speed <= 0.0 is false for NaN), and a tiny speed (1e-7) saturated the new duration to i64::MAX, after which the ripple shift overflowed (panic in debug, wraparound in release). Non-finite speeds are refused, the new duration is capped at what the timeline can hold, and the ripple shift uses checked arithmetic; a refused edit changes nothing (it works on a copy). Regression test with hostile speeds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 08:46:30 -04:00
Peet GuercioandClaude Opus 5.5 56cc93f4ea interchange: an FCP7 master clip lands in its bin when a sequence used it first
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 05:42:03 -07:00
midasdfandClaude Opus 5.5 bab130c358 i18n: Japanese interface language using an installed system font
Edit > Language switches English/Japanese and persists in UI state
(`app.language.english` / `app.language.japanese`, reachable through the
control channel). Core native and in-window menu labels are translated;
untranslated labels stay English. The in-window header fits the document
title beside the localized menus.

No font is bundled. Japanese text uses a Japanese font already installed on
the system (Hiragino, Yu Gothic, Meiryo, Noto Sans CJK JP, Source Han Sans,
IPA, … or any installed face covering the menus' characters), added to every
theme font family as the last fallback. Without one, switching to Japanese is
refused with a message and a saved Japanese setting falls back to English
(the web build cannot read system fonts). Titles already fall back to
installed fonts through the text engine.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 08:41:17 -04:00
Brandon Thomas 61ab6f5c7d Merge pull request #63 from storytold/pr/release-0.2.1
Release: FilmCraft v0.2.1
2026-10-06 08:01:17 -04:00
Brandon ThomasandClaude Opus 5.5 e659671bdf Release: FilmCraft v0.2.1
Fixes the Windows installer: the Start Menu shortcut and Add/Remove Programs icon were blank, and the shortcut description was wrong. Release builds no longer open a console window behind the app. Export can no longer panic (filmcraft-export never-crash).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 08:01:04 -04:00
Brandon Thomas bc1523a33f Merge pull request #62 from storytold/pr/never-crash-export
Never crash: filmcraft-export without expect()/unreachable!()
2026-10-06 07:58:18 -04:00
Brandon ThomasandClaude Opus 5.5 136424dc93 Never crash: filmcraft-export without expect()/unreachable!()
The five 'mux created' / 'audio' expects in the stepped exporter now return
an ExportError::Encode instead of panicking if the writer or audio pipeline
is missing, and the non-stepped dispatch returns Unsupported instead of
unreachable!(). The crate root gets the never-crash deny attribute, so every
FilmCraft production crate now carries it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 07:58:07 -04:00
Brandon Thomas 6bf2756cde Merge pull request #61 from storytold/pr/windows-packaging
Windows packaging: Start Menu/Add-Remove icon, no console window, correct description
2026-10-06 07:54:51 -04:00
Brandon ThomasandClaude Opus 5.5 c60d3f9c4c release.yml: explicit if for the wasm-bindgen install (shellcheck SC2015)
packaging-lint has failed on main since this step was added; same behaviour.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 07:53:46 -04:00
Brandon ThomasandClaude Opus 5.5 7fee797ee7 Windows packaging: Start Menu/Add-Remove icon, no console window, correct description
The MSI Icon id had no .ico/.exe extension, which Windows Installer needs for
advertised shortcuts and ARPPRODUCTICON, so both showed a blank icon. Release
builds of the desktop app are now GUI-subsystem (no console window; the CLI stays
a console program), the shortcut/summary description names what FilmCraft does, and
packaging-lint rejects an Icon id without an extension. Found in printcraft#57.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 07:51:02 -04:00
Brandon Thomas 508a5a933f Merge pull request #28 from storybored379/pr/mcp-conventions
MCP: tool annotations, core tools, resources, export progress and cancellation
2026-10-06 07:27:58 -04:00
Brandon Thomas 5012fbd598 Merge pull request #19 from storybored379/pr/deterministic-export
Export: same file on every machine (fixed mux interleave, H.264 slices by frame size)
2026-10-06 07:27:44 -04:00
Brandon Thomas 1f7e4f802e Merge pull request #39 from storybored379/fix/ttml-timing
Captions: report invalid TTML timing parameters on import
2026-10-06 07:27:28 -04:00
punkhopandClaude Opus 5.5 a8e4c815eb edit: ripple delete closes one gap for a clip with a split edit
Problem: `edit.rippleDelete` on a clip whose linked sound has a
different edge than its picture (a J or an L cut) treated the two
ranges as two gaps and closed both on every affected track. With two or
more clips after it the later ones were moved up twice and the edit was
refused ("items overlap"). With one clip after it the delete went
through, and sequence markers after it were moved by both gaps (one
that landed inside the second gap was removed).

Solution: one set of stretches closes on every track: the time the
deleted clips covered, less whatever stays on the tracks that lose a
clip. Those tracks move up by the same amount, into time that is free
on all of them, so later clips stay in sync and nothing is overwritten.
For a J or an L cut that is the picture's range. Straight cuts close as
before, also with the sounds on alternating tracks. A track that is
locked loses nothing and does not count. `ripple_delete_items` returns
the stretches it closed and the command ripples the markers by those,
so the two cannot disagree.

Things to know. A gap can stay on one track when a clip that stays on
another of the tracks covers part of the deleted time: a sound shorter
than its picture with other sound right up against it, or unlinked
clips on different tracks deleted in one call. When nothing can close
at all the edit is refused and nothing changes; some such calls went
through before, moving clips by a gap another track did not have. A
selection wholly on locked tracks is refused as locked; before, it
deleted nothing and still shifted the sync-locked tracks.

Tests: an edit-crate test (a split on both sides, two neighbours,
clips apart in time, sounds on alternating tracks, a short sound with
and without neighbours, a locked track, the refusal); engine tests
through `edit.rippleDelete` for a J cut with a marker, undo and redo,
an L cut, two neighbours with a split between them, two neighbours with
sounds on alternating tracks, and a straight cut.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 23:23:27 -07:00
punkhopandClaude Opus 5.5 4a0ab32480 edit: a ripple trim takes a later split edit along
Problem: `timeline.trim` with `mode: "ripple"` on the clip before a
split edit moved the later picture and left its linked sound behind.
With a J cut (the next clip's sound starts before its picture, on a
sync-locked track where the trimmed clip has no partner) a sound that
led its picture by 12 frames led by 20 after lengthening by 8, with no
error. Shortening was refused as a sync-lock conflict, because the
early sound sits in the stretch that closes.

Solution: in `ripple_trim_group`, a clip that starts before the cut,
reaches past it and is linked to a clip that shifts now shifts with it,
on the tracks that ripple (the members' tracks and sync-locked tracks).
It no longer counts as material in the way of a shortening. When it has
no room to follow (another clip right before it, or the sequence start)
the trim is refused with the sync-lock error and nothing changes (an
overlap on any track that ripples now reports that error instead of
the generic "items overlap"). A
linked clip that ends before the cut is left alone, as before, and so
are the trimmed clips' own partners. A transition into a follower from
a clip that stays behind would be left over a gap; it is removed.

Tests: an edit-crate test for longer, shorter, both refusals, the
clip that ends before the cut, the In edge, the trimmed clip's own
partners and the transition; engine tests through `timeline.trim` for
longer and shorter with undo and redo, and for both refusals.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 23:23:27 -07:00
punkhopandClaude Opus 5.5 4df7e75085 engine: timeline.place on an audio track places the sound there
Problem: `timeline.place {item, track: "A3"}` (an audio track given as
`track`). For an item with picture and sound it put a video item on the
audio track A3 and a second, sound clip on the default audio track. For
a sound-only item it ignored `track` and placed on the default audio
track.

Solution: `track` is where the picture goes and `audioTrack` where the
sound goes. An audio track given as `track` now places the sound alone,
on that track. What cannot be meant is a parameter error that says why,
and changes nothing: an audio track as `track` together with
`audioTrack`; a video track as `audioTrack`; an audio track for an item
with no sound; a video track alone for an item with no picture. Calls
that name a video track as `track` and an audio track as `audioTrack`
(the timeline panel's drop does) are unchanged. The parameter hint and
`docs/agents.md` say so.

Tests: track_params_tests.rs places a clip with picture and sound and a
sound-only item on audio tracks by name and by id, checks each refusal
for its error kind, its text, an untouched project and undo history,
and checks the usual forms still work.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 23:14:24 -07:00
punkhopandClaude Opus 5.5 f06bfc4648 edit: a speed change with ripple moves later clips once
Problem: `clip.speedDuration` with `ripple: true` on a clip that has
linked sound set the speed on the picture and then on its sound, and
each one rippled the later material on its own. Slower (50%) moved the
later clips by twice the change and left a double gap. Faster (200%)
was refused ("items overlap") when more than one clip followed: the
second ripple pulled the farther clips onto the nearer ones.

Solution: `set_speed_group` changes a clip and its linked partners on
other tracks as one edit and ripples once, on the members' tracks and
on sync-locked tracks. The command groups the selected clips by link
(one clip per track in a group); clips that are not linked, or linked
clips of one track, still change one after the other. When the members'
lengths change by different amounts (a split edit), later material
moves by the largest change, so no member is overlapped and the tracks
stay in sync; the shorter member is followed by a gap. The group edit
works on a copy, so a failure changes nothing. `set_speed` keeps its
signature and behaviour for one clip.

Tests: an edit-crate test (slower, faster, a split edit both ways, two
clips of one track and a missing clip refused with nothing changed);
engine tests through `clip.speedDuration` for slower with undo and
redo, faster, two clips in one call, no ripple, picture and sound both
named with Linked Selection off, linked clips of one track, a split
edit, and a clip that is not in the sequence.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 23:14:24 -07:00
punkhopandClaude Opus 5.5 7eb4f1fc7b engine: sequence.inspect reports a reversed clip
Problem: a clip set to play backward (`clip.speedDuration` with
`reverse: true`) read back from `sequence.inspect` exactly like a
forward clip: same `speed`, same source range, nothing that said it was
reversed. An agent could set it and not confirm it.

Solution: clips gain `reverse` (bool) in `sequence.inspect`, named as
in the project file and in the command. Additive; existing keys are
unchanged. `docs/agents.md` lists it and says what it means for the
source range.

Tests: sequence_inspect_tests.rs reverses a demo clip through the
command and checks that only that clip reports `reverse: true`, and
none after undo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 22:45:21 -07:00
punkhopandClaude Opus 5.5 ff8aa8749d engine: a project saved after an interchange import opens again
Problem: a Final Cut 7 XML whose Basic Motion filter sets only `scale`
makes the importer add the Motion effect with its defaults, where
`position` and `anchor` are the NaN "auto" sentinel. Placing a clip
resolves those with `resolve_auto_points`; the interchange import did
not (any format: the clips are built with the effect defaults).
serde_json writes NaN as `null`, and the reader then refused the file:
"project file is damaged: invalid type: null, expected f64". The project
could be saved but never opened again.

Solution:
- project: a point parameter's value (`ParamValue::Vec2`) reads a `null`
  coordinate back as NaN, so "auto" survives a save. Only there: `Vec2`
  itself is unchanged, and a `null` in a mask vertex or any other point
  is still a damaged file.
- project: `Project::resolve_placed_auto_points` resolves the points of
  the clips in chosen sequences. Points measured in the frame use the
  sequence size. `anchor` is measured in the clip's source
  (`Project::source_size`, a subclip through its parent, as the renderer
  resolves it) and is resolved only for sources the caller says have
  their final size.
- engine: the import resolves in the edits it already makes, so the undo
  steps are what they were. In "Import ...": everything but the anchors
  of file media, whose size is only what the document says so far (an
  EDL says nothing and the importer assumes the sequence size). In each
  "Link Media": the anchors of that file's clips, from the probed size.
  A clip whose file is not found keeps an "auto" anchor, which the
  renderer centres in whatever size the media has, as before this
  change.
- engine: a later Link Media (relink.rs `apply`, behind `media.relink`
  and `media.autoRelink`) resolves those waiting anchors in its own undo
  step, when it has read the file. Nothing else resolves them: a file
  that merely comes back at its old path, or a forced relink that does
  not read the file, leaves the anchor "auto" (still rendered centred).

Why no schema step and no repair on load: the file's shape is not
changed. Files with `null` points were written by every build before
this one, at the current schema version, so a migration (keyed on the
version) cannot select them, and a bump would only make every new
project unreadable to those builds. They open now and their points are
"auto", exactly as in the session that wrote them; resolving them on
load would mean guessing the size of media that was never linked.
docs/project-files.md describes `null` points.

Tests: project
`point_params_keep_auto_through_json_and_no_other_point_reads_null` and
`placed_auto_points_resolve_once_the_source_size_is_final`; format
`auto_points_written_as_null_open_again`; engine
(interchange_auto_points_tests.rs): import with the media missing, save,
reopen, undo, redo; a linked file whose real size differs from the
declared and the sequence size (undo of Link Media and of the import,
redo); an EDL clip smaller than its sequence; import with the media
missing, save, reopen, relink (anchor becomes a number, undo, redo, a
second relink leaves it). All fail without the change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 20:28:54 -07:00
punkhopandClaude Opus 5.5 8f74d18829 engine: timeline.move takes linked partners along
Behaviour change to the default: with Linked Selection on (the default),
`timeline.move` now also moves the linked partners of the listed clips.
A partner lands on its own track in the same mode as the listed clip, so
a caller that lists only a picture clip can now overwrite audio at the
destination time. `"linked": false` gives the old behaviour (only the
listed clips move); the timeline panel passes it, so dragging is
unchanged.

Problem: `timeline.move {"moves": [{clip, track, time}]}` moved only the
listed clip. Its linked sound stayed where it was, out of sync, although
Linked Selection was on and `timeline.trim`, slide and select all act on
linked partners. Separately, a `time` near i64::MAX overflowed the tick
addition in the edit (a panic in debug builds, a wrapped position in
release).

Solution: a linked partner that is not itself in `moves` moves by the
same time offset and stays on its own track. A partner that is listed is
moved once, to where the list says. Two kinds of partner are left
exactly as they are: one on a locked track (the listed clip still moves,
as it did before), and one whose position would not change, which is the
case when the listed clip only changes track. Re-placing such a partner
would drop the transitions at its edges and report a move that did not
happen. A new optional `linked` parameter overrides the toggle for one
call. The command returns `{"moved": [ids]}`, the clips that moved.

No clip is moved before the sequence start. When one would be (a split
edit whose sound starts earlier, or several listed clips asked too far
left), all clips of the call land later by the same amount, so the
spacing asked for is kept. This replaces the per-clip clamp for a call
that lists several clips with a time below zero; a single clip still
lands at zero. The offsets are summed in i128 and checked on the way
back: a start past Tick::MAX is a parameter error and nothing moves.

Tests (timeline_move_tests.rs): partners follow, undo / redo, both
listed, `linked: false`, toggle off, `linked: true`; a locked partner; a
picture moved to another track at the same time leaves its sound and the
sound's crossfade untouched; the common stop at the sequence start with
a split edit and with two listed clips; hostile times (i64::MAX,
i64::MIN, junk). All fail without the change, the hostile one with the
overflow panic. docs/control-protocol.md and docs/agents.md describe the
default, the `linked` parameter and the result.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 20:24:23 -07:00
punkhopandClaude Opus 5.5 6de389c75a engine: a command whose targets are named in the parameters does not need a selection
Problem: a command gated on the selection refused to run although the
caller named what to act on. `clip.replaceFromBin {clips, item}` answered
"select a clip in the Project panel"; `edit.clear`, `edit.rippleDelete`,
`edit.pasteAttributes`, `clip.enable`, `clip.link`, `clip.speedDuration`
and `clip.audioGain` with `clips` answered "no clips selected". A script
or agent had to change the user's selection first. The cause is the order
in Session::execute: `enabled()` runs before the parameters are read, and
it only knows the selection.

Fix: Session::execute asks enablement per call. When `enabled()` passes,
nothing changes. When it fails and the parameters name targets under a
key the command documents as ids (`clips` / `clip`: clips of the active
sequence, `items` / `item`: project items), the same `enabled()` runs
once more with those targets standing in for the selection, and the
selections are put back before the command runs. So only the selection
condition is answered by the named targets: no sequence, an empty
clipboard or the wrong kind of clip still disable the command, ids of
nothing do not count, and a command that does not document the key
(`edit.cut`) still needs a selection. This works for every command
because the predicates already resolve their targets the way `run` does
with empty parameters. `is_enabled` (menus, `engine.commands`) is
unchanged.

`clip.audioGain` already read `clips`; its parameter doc now says so.

Tests (explicit_targets_tests.rs): the commands above with and without
parameters, undo/redo, the selections left untouched, menu enablement
unchanged, and the cases that must still be refused. Four of the five
fail without the change in execute.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 20:05:12 -07:00
punkhopandClaude Opus 5.5 4aa3f79953 interchange: FCP7 XML import reports a clip item whose file is not defined
Problem: a clip item whose `<file id="...">` reference has no definition
anywhere in the document was dropped without a word, so a sequence could
come back one clip short with an empty import report. FilmCraft's own
export writes titles and adjustment layers this way.

Solution: the importer adds a warning that names the clip item: `clip
"Title" refers to a file the document does not define; skipped`. Nothing
else about the import changes.

Test: `fcp7_import_reports_a_clip_item_whose_file_is_not_defined`
(FilmCraft's own export, a hand-written document, and a document whose
files are all defined).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 20:02:27 -07:00
punkhopandClaude Opus 5.5 6899f15e51 interchange: an export names every title it cannot carry
Problem: exporting a sequence with a graphic (title) clip to Final Cut
Pro 7 XML returned a report that listed other losses and said nothing
about the title. The XML holds a clip item for it that points at a file
the document never defines, and importing the XML gives the sequence
back without the title. OTIO (a clip with a missing media reference,
read back as offline media) and EDL (an ordinary event) were silent in
the same way; FCPXML said "clip without media skipped" and AAF "graphics,
titles and adjustment layers are not exported" without saying which clip.
Adjustment layers take the same paths.

Solution: every exporter names each graphic clip and adjustment layer
it cannot carry, one warning per clip, with what was written instead:
`graphic clip "Title" at frame 48 has no Final Cut Pro 7 XML equivalent:
it is written as a clip item without media and is not read back on
import`. One helper (`common::uncarried_clip`) builds the name for all
formats. What is written is not changed, byte for byte.

Why only a warning: FCP7 XML has a Text generator, but this crate's
importer does not read one (unknown generators become Black Video), and
a title here is a stack of text and shape layers with per-character
styles, pins and roll settings that the generator's few parameters
cannot hold. Writing one would need a new import path and would still
lose most of a title, so the honest result for now is to say what
happens. crates/interchange/README.md has the table per format.

Tests: crates/interchange/tests/uncarried_clips.rs (each format names
the title and the layer once; two titles are two lines; nothing is said
without such clips; a re-import gives back what the report says), and
the engine's `interchange_export_reports_the_title_it_cannot_carry`
through `file.exportInterchange`. The two naming tests fail without the
change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 20:01:34 -07:00
punkhopandClaude Opus 5.5 5bf2203bb8 codecs: resampled MP4 audio reads apply the edit list once
Problem: a clip with AAC audio in MP4 whose sample rate differs from the
sequence's (48 kHz clip in a 44.1 kHz sequence) exported with loud
low-frequency thumps, several times full scale, recurring through the clip.
Every exported container was affected (AAC clips them into thumps, PCM
clips at full scale); a WAV export had a single one at the clip's start.

Cause: Mp4Source::audio decodes a window starting at s0, the requested
presentation sample minus the edit-list offset, then resamples it. The
resampler derived its sub-sample phase from s0, so the edit-list offset
(-1024 samples of AAC priming) was applied a second time: the read
position started about 1024 samples before the window, was clamped to
index 0 with a large negative fraction, and linear interpolation
extrapolated a ramp over the first ~940 samples of every request. Export
asks for audio one batch of video frames at a time, so the ramp repeated
at each request. Sources at the sequence rate take the copy path and
were unaffected, as were tracks without an edit list.

Fix: take the phase from the presentation sample the window starts at
(before the edit-list offset is subtracted).

Test: aac_mp4_resampled_reads_follow_the_edit_list
(crates/codecs/tests/mp4_oracle.rs, with `require_ffmpeg!` and the
shared fixture helper as docs/testing.md asks of new oracle tests) reads
an ffmpeg AAC fixture at 44.1 kHz in frame-sized pieces and compares it
with the 48 kHz decode interpolated at the same times (peak was 7.35
against a source level of 0.15 before the fix). docs/testing.md lists it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 19:29:26 -07:00
punkhopandClaude Opus 5.5 d3ee1dfd22 engine: Replace With Clip reports clips that run past the new media
Problem: when the replacement is shorter than the clip's slot, the clip
silently runs past the end of its media and the renderer holds the last
frame. Nothing in the command's result says so, so a script or agent
that swaps a take cannot tell.

Solution: the result of the three Replace With Clip commands
(`clip.replaceFromSource`, `clip.replaceFromSourceMatchFrame`,
`clip.replaceFromBin`) gains `short`: one `{clip, shortByFrames}` per
replaced clip that now plays past the end of its media, in sequence
frames and never more than the clip's own length. It is empty when none
does; stills and other sources without an end, and held frames, are
never short. The edit itself is not changed, and the parameter docs are
untouched (results are described in docs/control-protocol.md).

Test: `replace_with_clip_reports_clips_that_run_past_the_new_media`
(From Bin with a 12-frame subclip, undo / redo, From Source Monitor,
Match Frame, the cases that are not short, and an In past the end of the
new media capped at the clip's length).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 19:28:20 -07:00
punkhopandClaude Opus 5.5 0e3aebee5d engine: clip.replaceFromBin can keep the clip's source In
Problem: `clip.replaceFromBin` always restarts the clip at the new
item's In point (or its start). That matches Premiere's Replace With
Clip > From Bin, but a script or agent swapping one take for another has
no way to keep the clip's place in the media.

Solution: the default is unchanged, and so is its result. An optional
`keepSourceIn` (default false) keeps each clip's current source In. A
subclip that restricts trims has no media outside its range, so there a
kept In outside the range is moved to the subclip's first or last frame;
with `keepSourceIn` the result gains `sourceInClamped`, the clips this
was done for. The parameter doc lists the new parameter only (a result
description in it would take the command out of the Keyboard Shortcuts
list, which reads the doc to see whether a command needs parameters).

Tests: `replace_from_bin_keeps_the_source_in_on_request` (default and
its result, keepSourceIn, undo / redo, the disabled case, subclips before,
after and around the In, an unrestricted subclip, junk values), and
`list_searches_labels_and_keys` now asserts the three Replace With Clip
commands are bindable. docs/control-protocol.md describes the commands.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 19:25:50 -07:00
punkhopandClaude Opus 5.5 22229df105 filmcraft: --help prints usage and an unknown option is an error
Problem: `filmcraft --help` opened the app. Every argument the parser
did not know was taken as a file to open, so `--help`, `-h` or a
mistyped flag started a window (and tried to import "--help" as media).
`--control` with a missing or invalid port, and an invalid
`FILMCRAFT_CONTROL_PORT`, started the app without the control server and
said nothing, which leaves a script waiting for a server that never
comes.

Solution: argument parsing moves into its own module (`args.rs`,
`args::parse`), which runs before anything else starts. `--help` / `-h`
print the usage (the options the app parses: --control, --demo, --empty,
--recover, --no-recover, --data-dir, --version) and exit 0. An unknown
option, or `--control` / `--data-dir` without a usable value, prints the
error and the usage on stderr and exits 2. The whole line is checked, so
`--version --bogus` is an error too. A `FILMCRAFT_CONTROL_PORT` that is
not a port is the same error as a bad `--control` (exit 2), for the same
reason; an empty value counts as unset, and the value is not looked at
when `--control` is given or for `--help` / `--version`. `--` ends the
options, so a file whose name starts with a dash can still be opened; a
lone `-` and the `-psn_...` argument macOS adds to app launches are not
treated as options.

Tests (in args.rs): `help_and_version_do_not_start_the_app`,
`unknown_options_are_errors`,
`a_bad_port_in_the_environment_is_an_error_like_a_bad_control_flag`,
`known_options_and_files_parse_as_before`. docs/contributing.md
mentions `--help` and the errors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 19:21:56 -07:00
punkhopandClaude Opus 5.5 285da5c66b engine: file.exportInterchange refuses an unknown format
Problem: `file.exportInterchange {"format": "<anything unknown>"}` wrote
FCP7 XML and returned ok, so a typo or an unsupported format produced a
file of the wrong kind under the name that was asked for.

Solution: only a missing `format` means FCP7 XML. A given format must be
one of the six documented names (edl, xml, fcpxml, otio, aaf, omf: each
format's extension, in either case). Anything else, including a value
that is not a string, is a parameter error that lists exactly those
names, and nothing is written. No other spelling is accepted (".xml",
"fcpxmld", "omfi"): none was accepted before either, they silently
became XML. The parameter doc now lists aaf and omf, which the command
already took, and the default; docs/architecture.md says the same.

Test: `export_interchange_refuses_an_unknown_format`, next to the
interchange round-trip test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 19:20:02 -07:00
punkhopandClaude Opus 5.5 51ecd70763 engine: sequence.inspect reports clip ends, gain and marker comments
Problem: `sequence.inspect` is how an agent verifies an edit, but it
left out where a clip ends in the sequence and in its media, a clip's
audio gain, and the comment of a marker, so those edits could not be
checked from the readback.

Solution: each clip also reports `end`, `endFrame`, `sourceOut` (which
depends on speed, so it cannot be derived from `sourceIn` + `duration`)
and `gainDb`; each sequence marker also reports `comment`. Every
existing key stays. docs/agents.md lists what the readback holds.

Test: `sequence_inspect_reports_clip_ends_gain_and_marker_comments`
(sequence_inspect_tests.rs), on a clip at 200 %, a clip with gain and a
marker with a comment made through the commands.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 19:17:52 -07:00
punkhopandClaude Opus 5.5 9d3975a697 engine: naming a track that does not exist is an error
Problem: `timeline.place {"audioTrack": "A2"}` on a sequence that has
only A1 placed the clip on A1, overwrote what was there and returned ok.
`track_p` returned `None` both for "no track asked for" and for "that
track does not exist", so callers fell back to the source-patched track.
It also took any first letter other than V as an audio track, accepted
track ids that are not in the sequence, and `split_at(1)` panicked on an
empty or non-ASCII name.

Solution: `track_p` returns `Result<Option<TrackId>>` and takes the
command id, like the other fallible parameter helpers. An absent (or
null) parameter is `Ok(None)` and keeps every default as it was. A name
or id the active sequence does not have is a parameter error
(`EngineError::BadParams`): "invalid parameters for `timeline.place`: no
track A2 in this sequence (`audioTrack`)". All callers propagate it:
timeline.place (`track`, `audioTrack`), timeline.move, timeline.razor,
timeline.setTrack, timeline.setTargeting, sequence.closeGap,
sequence.deleteTrack, sequence.deleteTracks, the go-to-gap commands,
sequence.transcribe and the multicam sync reference track.

Not changed: a `timeline.move` entry without a `clip`, `track` or `time`
is still skipped, as before; only a track that was named and is missing
is an error.

Test: `naming_a_missing_track_is_an_error_not_a_default` in
track_params_tests.rs (missing and hostile names, the error kind, nothing
edited, no undo step, existing tracks by name and id still resolve).
docs/agents.md notes the rule.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 19:10:19 -07:00
justjohn12345andClaude Opus 5.5 4f3e119ac2 MEM4: decode into the planes of evicted frames
With MEM1-MEM3 twelve clips on a timeline still took 5.1 GB, only 2.5 GB of
it live: each decoded picture allocated three planes, each eviction freed
them, and the system allocator kept the freed pages.

filmcraft_frame::pool keeps the planes of frames the GOP caches evict (up to
192 MiB per sample type; a frame something else still holds is left alone).
The H.264 decoder, through a plane allocator hook that keeps the crate free
of dependencies, and the VideoToolbox path take their output planes from it.

perf.stats reports decode.planePoolMB and decode.planesReused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 16:57:16 -04:00
Brandon ThomasandClaude Opus 5.5 5d1165d06b MCP: cancelled exports delete only their own files
remove_partial removed every '<stem>[digits].<any ext>' file in the output folder modified since the export started, so cancelling an export to trailer.mp4 also deleted trailer.aep or trailer2.psd if they were saved during the export. It now removes only the output file, numbered stills with the output's extension, and the .srt/.vtt caption sidecar. Regression test with decoy files.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 16:54:24 -04:00
justjohn12345andClaude Opus 5.5 b999b69f07 HW1: register the hardware decoders in every desktop run
The desktop app called filmcraft_platform::register() as an argument of
log::info!. A log macro does not evaluate its arguments while no logger takes
its level, and the app installs none, so VideoToolbox was never registered:
perf.stats showed hardware decoding enabled with 0 sessions, 0 declined and
every frame decoded in software. The CLI and the bench register directly and
were not affected.

Registration is now a statement of its own, with a start-up test that runs
without a logger.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 16:42:28 -04:00
justjohn12345andClaude Opus 5.5 4486652f07 MEM3: one frame budget shared by all sources
Each GOP cache keeps up to 384 MB of decoded frames (at least 64), and
nothing bounded the total: twelve clips on a timeline held 3.8 GB of frames
nobody was looking at, and no perf.stats counter showed it.

The pool now counts the frames of every cache against a 1 GiB budget. Over
it, caches idle for 3 s give up frames, least recently used cache first.
Caches in use keep their own budget, since a frame evicted before it is
shown costs a re-decode from the keyframe.

perf.stats reports decode.cacheMB and decode.cacheBudgetMB.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 16:39:48 -04:00
justjohn12345andClaude Opus 5.5 517b6b041b MEM2: idle sources give up their decoders beyond a cap
Every source kept its decoder for good once it had decoded a frame, with its
reference pictures and the pictures its frame threads hold in flight: about
290 MB per H.264 clip, 3.5 GB for twelve clips on a timeline.

The GOP caches now share a pool. Beyond four live decoders, the least
recently used caches that have been idle for 3 s drop theirs and make a new
one when asked again (a restart at the sync sample, as after a seek). Caches
in use keep their decoder whatever the count, so a composite of many layers
never restarts decoders per frame. Other caches are only try-locked, so two
caches trimming each other cannot deadlock.

perf.stats reports decode.liveDecoders.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 16:39:48 -04:00
justjohn12345andClaude Opus 5.5 ac8279d293 MEM1: desktop reads media files in place
The desktop host had no Services::reader, so MediaPool::open_file read every
clip whole and kept its bytes for as long as the source stayed open: 2.9 GB
for twelve clips on a timeline (malloc_history, 15 allocations in open_file).

FsServices::reader now returns a FileReader that keeps the file open and
serves positional reads, so MP4/MOV, Matroska and the other reader openers
load the index and then single samples, as the web host already does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 16:39:48 -04:00
Brandon Thomas ada55eb625 Merge pull request #35 from storytold/pr/gpu-effects
GPU2: standard effects on the GPU compositor (#30)
2026-10-05 16:27:05 -04:00
Brandon ThomasandClaude Opus 5.5 adfd9a66de docs: point agents to the shared test corpora (#36)
Real-file test oracles live in storytold/photocraft-corpus, explained in
craftrules standards/test-corpora.md. Never commit large binary fixtures
here; fetch them pinned and sha256-verified.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 08:24:17 -04:00
storybored379andOpenAI Codex 9c06722119 Captions: report invalid TTML timing parameters on import
Co-Authored-By: OpenAI Codex <noreply@openai.com>
2026-10-04 21:48:25 -07:00
storybored379andClaude Opus 5.5 cad16825e3 MCP: progress notifications and cancellation for blocking exports
command_run file.exportMedia with wait: true (headless) runs as the
background export job and uses the MCP progress and cancellation utilities:

- with _meta.progressToken, notifications/progress reports frames done /
  total with the job status, at most every 100 ms (none without a token);
- notifications/cancelled stops the job at the next batch (jobs.cancel),
  deletes the partial output and sends no response;
- the session lock is only held for short polls, so ping, doc_inspect,
  jobs.list etc. are answered while it encodes.

Without wait, and in bridge mode, nothing changes. Test
export_progress_and_cancel.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 13:51:38 -07:00
storybored379andClaude Opus 5.5 8ee7658303 MCP: filmcraft://document and filmcraft://commands resources, with MCP 2026-07-28 cache hints
- resources/list and resources/read serve the project (tree + active
  sequence, as doc_inspect) and the command catalog (as command_list) as
  JSON, for clients that attach context from resources.
- Results are built with rmcp's types, so resultType follows the negotiated
  revision; for 2026-07-28 clients (current Claude Code) they also carry
  ttlMs and cacheScope, like the generated tools/list. The resource list is
  fixed (10 min), document reads are never cached (0).
- get_info now declares the resources capability; the instructions text
  moves to a const, unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 13:51:28 -07:00
storybored379andClaude Opus 5.5 0f70015b93 MCP: tool titles and annotations, command_batch / doc_inspect / render_preview, strict arguments
- Every tool has a title and readOnly / destructive / idempotent / openWorld
  hints, set in its #[tool] attribute, so clients can run the read-only
  tools without asking and ask before edits.
- New tools: command_batch (several commands, stop at the first error by
  default), doc_inspect (project tree + active sequence in one call) and
  render_preview (= render_frame).
- An unknown tool argument is a -32602 error naming it and the accepted
  ones, instead of being ignored.
- A line that is not JSON gets a -32700 reply (id null) instead of being
  dropped without an answer: serve_io filters lines in front of rmcp.
- A panicking command no longer poisons the session lock for the rest of the
  session ("session lock poisoned"); it is reported as "internal error: …"
  (AGENTS.md §0.6).
- docs/agents.md § Conventions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 13:51:21 -07:00
storybored379andClaude Opus 5.5 a55d20c454 export: same file on every machine (fixed mux interleave, H.264 slices by frame size)
Exporting the same project twice could give different files, because two
export parameters followed the number of cores the process sees:

- The muxer got one chunk per render batch, and a batch is one frame per
  rayon thread. The chunk layout (stsc/stco, PCM packet sizes) changed with
  the core count; the samples themselves did not.
- The H.264 encoder used one slice per core (capped at one per four MB rows),
  so the bitstream and every decoded picture changed with the core count.

On a host whose CPU quota changes (containers, power limits), two exports in a
row differed. Now packets are muxed in fixed groups of 16 output frames
(INTERLEAVE), each followed by its audio, whatever the batch size, and H.264
exports use one slice per four macroblock rows. Hosts with 17 or more threads
already used these values, so their 1080p output does not change.

Tests: determinism_tests (fail on main): same bytes for ProRes, H.264 and
Motion-JPEG at 2/3/5/16 cores and 1/7 frames per step; 64 slices for a
4096-line H.264 export.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 08:32:49 -07:00
260 changed files with 30456 additions and 1597 deletions

No files matched your search

+4
View File
@@ -47,6 +47,10 @@ jobs:
- name: XML, desktop entry, AppStream, Flatpak manifest
run: |
xmllint --noout packaging/windows/filmcraft.wxs packaging/macos/*.plist* packaging/linux/*.xml*
# Windows Installer needs Icon ids ending in .ico or .exe, or shortcuts show a blank icon.
if grep -oE '<Icon Id="[^"]*"' packaging/windows/filmcraft.wxs | grep -vE '\.(ico|exe)"$'; then
echo "::error::Icon Id must end in .ico or .exe"; exit 1
fi
desktop-file-validate packaging/linux/ai.storyteller.filmcraft.desktop
sed -e 's/@VERSION@/0.0.0/' -e 's/@DATE@/2026-01-01/' packaging/linux/ai.storyteller.filmcraft.metainfo.xml.in >"$RUNNER_TEMP/ai.storyteller.filmcraft.metainfo.xml"
appstreamcli validate --no-net --explain "$RUNNER_TEMP/ai.storyteller.filmcraft.metainfo.xml"
+40 -2
View File
@@ -70,6 +70,12 @@ jobs:
FILMCRAFT_BUILD_DATE: ${{ needs.version.outputs.date }}
steps:
- uses: actions/checkout@v4
# Fonts (optional build input, required for releases): docs/contributing.md#building-with-craft-fonts
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
repository: storytold/craft-fonts
ref: abb83316d96aa59c1cf64784289e378fe9fa5695 # bump deliberately
path: craft-fonts
- uses: dtolnay/rust-toolchain@stable
with:
targets: aarch64-apple-darwin, x86_64-apple-darwin
@@ -90,6 +96,8 @@ jobs:
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts
CRAFT_FONTS_REQUIRED: "1"
run: packaging/macos/package.sh --arch universal
- uses: actions/upload-artifact@v4
with:
@@ -112,11 +120,20 @@ jobs:
include:
- { arch: x64, target: x86_64-pc-windows-msvc }
- { arch: x86, target: i686-pc-windows-msvc }
# Windows on ARM: cross-compiled on the x64 runner, so signing and WiX run as above.
# .github/workflows/windows-arm64.yml installs and runs it on ARM64 hardware.
- { arch: arm64, target: aarch64-pc-windows-msvc }
env:
FILMCRAFT_VERSION: ${{ needs.version.outputs.version }}
FILMCRAFT_BUILD_DATE: ${{ needs.version.outputs.date }}
steps:
- uses: actions/checkout@v4
# Fonts (optional build input, required for releases): docs/contributing.md#building-with-craft-fonts
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
repository: storytold/craft-fonts
ref: abb83316d96aa59c1cf64784289e378fe9fa5695 # bump deliberately
path: craft-fonts
- uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ matrix.target }}
@@ -141,6 +158,8 @@ jobs:
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts
CRAFT_FONTS_REQUIRED: "1"
run: ./packaging/windows/package.ps1 -Arch ${{ matrix.arch }}
- uses: actions/upload-artifact@v4
with:
@@ -167,6 +186,12 @@ jobs:
NFPM_VERSION: 2.47.0
steps:
- uses: actions/checkout@v4
# Fonts (optional build input, required for releases): docs/contributing.md#building-with-craft-fonts
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
repository: storytold/craft-fonts
ref: abb83316d96aa59c1cf64784289e378fe9fa5695 # bump deliberately
path: craft-fonts
- name: Install build and packaging tools
run: |
sudo apt-get update
@@ -184,6 +209,9 @@ jobs:
if: inputs.version != ''
run: cargo xtask version set "$FILMCRAFT_VERSION"
- name: Build and package (AppImage, deb, rpm, tar.gz)
env:
CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts
CRAFT_FONTS_REQUIRED: "1"
run: packaging/linux/package.sh
- name: Check the packages
run: |
@@ -212,6 +240,12 @@ jobs:
WASM_BINDGEN_VERSION: 0.2.129
steps:
- uses: actions/checkout@v4
# Fonts (optional build input, required for releases): docs/contributing.md#building-with-craft-fonts
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
repository: storytold/craft-fonts
ref: abb83316d96aa59c1cf64784289e378fe9fa5695 # bump deliberately
path: craft-fonts
- uses: dtolnay/rust-toolchain@stable
with:
targets: wasm32-unknown-unknown
@@ -221,13 +255,17 @@ jobs:
- name: Install wasm-bindgen CLI
run: |
# Must match the wasm-bindgen crate version exactly (WASM_BINDGEN in xtask/src/main.rs).
command -v wasm-bindgen >/dev/null && wasm-bindgen --version | grep -q "$WASM_BINDGEN_VERSION" \
|| cargo install wasm-bindgen-cli --version "$WASM_BINDGEN_VERSION" --locked
if ! { command -v wasm-bindgen >/dev/null && wasm-bindgen --version | grep -q "$WASM_BINDGEN_VERSION"; }; then
cargo install wasm-bindgen-cli --version "$WASM_BINDGEN_VERSION" --locked
fi
wasm-bindgen --version
- name: Apply version override
if: inputs.version != ''
run: cargo xtask version set "$FILMCRAFT_VERSION"
- name: Build and zip
env:
CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts
CRAFT_FONTS_REQUIRED: "1"
run: packaging/web/package.sh
- uses: actions/upload-artifact@v4
with:
+95
View File
@@ -0,0 +1,95 @@
# Windows on ARM: package the ARM64 release the way release.yml does (cross-compiled on an x64
# runner, unsigned here), then install that MSI on a Windows 11 ARM64 runner, check the installed
# binaries are ARM64, run the CLI natively, and uninstall. (A native ARM64 `cargo test` job is left
# out for now: PdfCraft saw an intermittent access violation in egui UI tests there.)
name: Windows ARM64
on:
push:
branches: [main]
pull_request:
paths:
- Cargo.toml
- Cargo.lock
- "**/Cargo.toml"
- "**/build.rs"
- .github/workflows/windows-arm64.yml
- packaging/windows/**
schedule:
- cron: "41 4 * * 1" # weekly, so drift in the runner images shows up
workflow_dispatch:
concurrency:
group: windows-arm64-${{ github.ref }}
cancel-in-progress: true
permissions:
contents: read
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
jobs:
package:
name: package (cross-compiled on x64)
runs-on: windows-latest
timeout-minutes: 90
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@89b12181fb390509a0842a86cc55eeb8eb928c1d # stable
with:
targets: aarch64-pc-windows-msvc
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
with:
key: windows-arm64-package
- name: Install WiX
shell: pwsh
run: dotnet tool install --global wix --version 5.0.2
- name: Build and package (unsigned)
shell: pwsh
env:
DIST: ${{ github.workspace }}\dist\arm64
run: ./packaging/windows/package.ps1 -Arch arm64
- uses: actions/upload-artifact@v4
with:
name: filmcraft-windows-arm64
path: dist/arm64/*
if-no-files-found: error
retention-days: 7
install:
name: install and run on ARM64
needs: package
runs-on: windows-11-arm
timeout-minutes: 30
steps:
- uses: actions/download-artifact@v4
with:
name: filmcraft-windows-arm64
path: dist
- name: Install the MSI, check it, run it, uninstall it
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
$msi = (Get-ChildItem dist/*.msi | Select-Object -First 1).FullName
$p = Start-Process msiexec.exe -ArgumentList '/i', "`"$msi`"", '/qn', '/l*v', 'install.log' -Wait -PassThru
if ($p.ExitCode -ne 0) { Get-Content install.log -Tail 60; throw "msiexec /i exited $($p.ExitCode)" }
$dir = Join-Path $env:ProgramFiles 'FilmCraft'
foreach ($exe in 'filmcraft.exe', 'filmcraft-cli.exe') {
$path = Join-Path $dir $exe
if (-not (Test-Path $path)) { throw "$exe not installed in $dir" }
$bytes = [System.IO.File]::ReadAllBytes($path)
$machine = [BitConverter]::ToUInt16($bytes, [BitConverter]::ToInt32($bytes, 0x3C) + 4)
if ($machine -ne 0xAA64) { throw "$exe is for machine 0x$('{0:X}' -f $machine), not ARM64" }
Write-Output "ok $path (ARM64)"
}
# The installed CLI runs natively on ARM64.
$cli = Join-Path $dir 'filmcraft-cli.exe'
$out = & $cli --version 2>&1 | Out-String
if ($LASTEXITCODE -ne 0) { Write-Output $out; throw "filmcraft-cli --version exited $LASTEXITCODE" }
Write-Output "ok filmcraft-cli --version: $($out.Trim())"
$p = Start-Process msiexec.exe -ArgumentList '/x', "`"$msi`"", '/qn' -Wait -PassThru
if ($p.ExitCode -ne 0) { throw "msiexec /x exited $($p.ExitCode)" }
if (Test-Path (Join-Path $dir 'filmcraft.exe')) { throw 'uninstall left filmcraft.exe behind' }
Write-Output 'ok uninstalled'
+14 -1
View File
@@ -21,7 +21,7 @@ panic path, and fix a crash before building on top of it. The cross-app standard
code alone (a literal that always parses): a single-item `#[allow(clippy::expect_used)]` with the reason.
3. **No `unsafe`** (`unsafe_code = "forbid"` for the workspace). The single exception is
`crates/platform`, which needs `unsafe` to call the operating system's media APIs (hardware
video decoding through VideoToolbox; later encoding and other OSes) and does nothing else. It
video decoding through VideoToolbox and Media Foundation / Direct3D 11; later encoding and Linux) and does nothing else. It
uses `unsafe_code = "deny"` with `#[allow(unsafe_code)]` only on its FFI modules, a
`// SAFETY:` comment on every `unsafe` block, a safe `Result`-returning public API, and the
pure-Rust decoder as the tested fallback ([ADR 0001](docs/adr/0001-platform-ffi.md)).
@@ -92,6 +92,13 @@ reproduce an image (for example, point lists traced from someone else's icon).
need a sidecar and an `ATTRIBUTION.md` row (licence `LicenseRef-ArtCraft-Trademark`). No other
non-open asset is allowed, and this exception never covers third-party marks (Adobe, Discord, GitHub
and other logos stay out; draw a generic icon instead).
9. **Fonts live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), never in this
repo.** Don't commit new font files (the small Latin UI fonts already in `assets/fonts/` stay). A
font FilmCraft needs is added to craft-fonts, which the app reads through the optional build input
`CRAFT_FONTS_DIR=<absolute path of a craft-fonts checkout>` (`crates/text/build.rs` embeds the fonts in its
`fonts/manifest.txt` as `filmcraft_text::fonts::CRAFT_FONTS`; unset, it is empty and the app uses its
bundled and system fonts). Never add craft-fonts to a `Cargo.toml`. Code using `CRAFT_FONTS` must work
when it is empty. Standard: [`craftrules/standards/fonts.md`](https://github.com/storytold/craftrules/blob/main/standards/fonts.md).
## 2. Clean-room code
@@ -120,6 +127,12 @@ See [§0](#0-never-crash). It outranks every other engineering rule.
See `CLAUDE.md`: pure Rust, dependency layering (`cargo xtask layers`), exact `Tick` time, everything is
a command, everything is agent-drivable, and the quality gates (`cargo xtask ci`) before every commit.
Shared real-file test corpora (Photoshop-authored PSDs, etc.) live in
[`storytold/photocraft-corpus`](https://github.com/storytold/photocraft-corpus), explained in
[craftrules `standards/test-corpora.md`](https://github.com/storytold/craftrules/blob/main/standards/test-corpora.md).
Never commit large binary fixtures to this repo; fetch them pinned by commit and sha256-verified,
as PhotoCraft does with `cargo xtask corpus`.
## See also
- [CONTRIBUTING.md](CONTRIBUTING.md) and [docs/contributing.md](docs/contributing.md): setup, gates, commits, how to add things
+24
View File
@@ -106,6 +106,21 @@ is traced or derived from Adobe artwork.
| Lumetri Presets (Effects panel: Cinematic, Film Emulation, Monochrome, Technical) and their preview picture | `crates/render/src/lumetri_presets.rs`: Lumetri parameter values chosen by contributors, descriptive names, and a procedural preview picture (dusk sky, ridges, lake, grey ramp, colour chips) |
| Colour palette and layout metrics | `crates/ui-egui/src/theme.rs`: colour values and sizes only; no artwork |
## Optional build input: craft-fonts
These fonts are **not files in this repository**. Builds made with the optional build input
`CRAFT_FONTS_DIR` (all official releases; see [docs/contributing.md](docs/contributing.md#building-with-craft-fonts))
embed them from [storytold/craft-fonts](https://github.com/storytold/craft-fonts), where each file,
its author, pinned upstream source and licence text are listed in its
[ATTRIBUTION.md](https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md). Release packages
carry each font's licence as `OFL-<family>.txt`.
| Font | Use in FilmCraft | Licence |
|---|---|---|
| BIZ UDPGothic Regular, Bold (Morisawa) | Japanese UI text; Japanese fallback for sans titles (the web build embeds only Regular) | OFL-1.1 |
| Shippori Mincho Regular (FONTDASU) | Japanese fallback for serif titles (native builds) | OFL-1.1 |
| BIZ UDMincho Regular (Morisawa) | Japanese fallback for serif titles (native builds) | OFL-1.1 |
## First-party brand marks
The ArtCraft name, wordmark and logos are trademarks of the ArtCraft Team. They are not open source and
@@ -124,6 +139,15 @@ remove them (AGENTS.md §1.8).
| `docs/brand/artcraft-mark.png` | ArtCraft Team | Original work: first-party ArtCraft brand mark (ArtCraft symbol ("A" mark), blue) | ArtCraft trademark, not open source; `docs/brand/LICENSE-brand.txt` (not MIT/Apache) |
| `docs/brand/artcraft-mark.svg` | ArtCraft Team | Original work: first-party ArtCraft brand mark (ArtCraft symbol ("A" mark), blue) | ArtCraft trademark, not open source; `docs/brand/LICENSE-brand.txt` (not MIT/Apache) |
## Third-party source code
Source files that are transcribed from third-party code rather than written from scratch. Each keeps
the original copyright and permission notice in its header.
| File | Author | Source | Licence |
|---|---|---|---|
| `crates/platform/src/nvenc/ffi.rs` | NVIDIA Corporation (`nvEncodeAPI.h`); FilmCraft contributors (Rust transcription) | Structures, function table and constants transcribed from `nvEncodeAPI.h`, NVIDIA Video Codec SDK, API 12.1 (https://developer.nvidia.com/video-codec-sdk) | MIT (Copyright (c) 2010-2023 NVIDIA Corporation; notice kept in the file header) |
## Downloaded at runtime
These files are never in the repository or the app bundle. FilmCraft downloads them into the
+2 -1
View File
@@ -1,6 +1,6 @@
# FilmCraft — instructions for agents
FilmCraft is a clean-room, open-source, pure-Rust non-linear video editor targeting Adobe Premiere Pro parity (and beyond). Native on macOS, Windows, Linux; web via WASM. Sibling of `../photocraft` (Photoshop), `../printcraft` (Acrobat) and `../drawcraft` (Illustrator), with the same conventions.
FilmCraft is a clean-room, open-source, pure-Rust non-linear video editor targeting Adobe Premiere Pro parity (and beyond). Native on macOS, Windows, Linux; web via WASM. Sibling of `../photocraft` (Photoshop), `../pdfcraft` (Acrobat) and `../vectorcraft` (Illustrator; formerly DrawCraft), with the same conventions.
## Start every session here
`plan/` is maintainer-local (gitignored, not in the repo). Each step names the public equivalent to use if you don't have it.
@@ -11,6 +11,7 @@ FilmCraft is a clean-room, open-source, pure-Rust non-linear video editor target
## Non-negotiables
**Read [`AGENTS.md`](AGENTS.md) first; its rules override everything here.**
- **Never crash** ([`AGENTS.md`](AGENTS.md) §0, standard: [`craftrules/standards/never-crash.md`](https://github.com/storytold/craftrules/blob/main/standards/never-crash.md)). People depend on FilmCraft; a crash loses their work, so this outranks feature work. No `unwrap`/`expect`/`panic!`/`unreachable!`/`todo!`/`unimplemented!` or `unsafe` outside tests: return `Result<T, E>` and propagate with `?` (`ok_or`, `let … else`, `if let`). Treat every number from media, project files, presets or CLI/MCP/control params as hostile: `get()` instead of `[i]`, checked/saturating math, no division by possibly-zero values, capped allocations, bounded recursion. `lock().unwrap_or_else(PoisonError::into_inner)`; background jobs run under `catch_unwind`. The panic hook + UI `catch_unwind` (`crates/ui-egui/src/crash.rs`) are the last-resort guard, not a licence. Every crash fix gets a regression test that panicked before. In particular (§1): never use Adobe iconography, images or any other Adobe asset. Every asset must be openly licensed (OSS / public domain / Creative Commons, or original work by a contributor) and must have a `<file>.attribution` sidecar plus an entry in `ATTRIBUTION.md`. `cargo xtask assets` enforces this.
- **Fonts** live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), never in this repo (no new font files here; [`AGENTS.md`](AGENTS.md) §1.9, standard: [`craftrules/standards/fonts.md`](https://github.com/storytold/craftrules/blob/main/standards/fonts.md)). Build with them: `git clone https://github.com/storytold/craft-fonts ../craft-fonts && CRAFT_FONTS_DIR="$PWD/../craft-fonts" cargo run -p filmcraft` (`crates/text/build.rs` embeds them as `filmcraft_text::fonts::CRAFT_FONTS`, used for Japanese in the UI and titles). Unset, `CRAFT_FONTS` is empty and everything must still build, test and run; never add craft-fonts to a `Cargo.toml`. Tests on its glyphs skip when it is empty, so run the gates with and without `CRAFT_FONTS_DIR` when you touch fonts.
- **Clean-room.** Never read/disassemble anything inside Adobe app bundles (names/listings only). Never copy Adobe icons, presets, LUTs, fonts. Never copy GPL/LGPL/AGPL code (FFmpeg, x264, x265, MLT, Kdenlive, Shotcut, Olive, LAME…). ffmpeg/ffprobe run only as external test oracles / fixture generators — never linked or shipped.
- **Pure Rust** in the product. OS media APIs only via Rust bindings in `crates/platform` (hardware decoding; the one crate allowed `unsafe`, see `AGENTS.md` §0.3 and `docs/adr/0001-platform-ffi.md`), optional, behind traits, with our decoders as the fallback.
- **Layering** ([`docs/architecture.md`](docs/architecture.md) §1, enforced by `cargo xtask layers`): nothing below L5 depends on egui/eframe/winit/rfd/cpal. L0 codec/container crates depend only on `filmcraft-bitstream`.
Generated
+73 -46
View File
@@ -992,6 +992,16 @@ dependencies = [
"windows 0.54.0",
]
[[package]]
name = "cpu-time"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e9e393a7668fe1fad3075085b86c781883000b4ede868f43627b34a87c8b7ded"
dependencies = [
"libc",
"winapi",
]
[[package]]
name = "cpufeatures"
version = "0.2.17"
@@ -1655,7 +1665,7 @@ dependencies = [
[[package]]
name = "filmcraft"
version = "0.2.0"
version = "0.2.1"
dependencies = [
"chrono",
"cpal",
@@ -1677,7 +1687,7 @@ dependencies = [
[[package]]
name = "filmcraft-aac"
version = "0.2.0"
version = "0.2.1"
dependencies = [
"filmcraft-bitstream",
"filmcraft-testkit",
@@ -1687,22 +1697,32 @@ dependencies = [
[[package]]
name = "filmcraft-ac3"
version = "0.2.0"
version = "0.2.1"
dependencies = [
"filmcraft-testkit",
"thiserror 2.0.21",
]
[[package]]
name = "filmcraft-apv"
version = "0.2.1"
dependencies = [
"filmcraft-bitstream",
"filmcraft-testkit",
"rayon",
"thiserror 2.0.21",
]
[[package]]
name = "filmcraft-audio-dsp"
version = "0.2.0"
version = "0.2.1"
dependencies = [
"filmcraft-testkit",
]
[[package]]
name = "filmcraft-automation"
version = "0.2.0"
version = "0.2.1"
dependencies = [
"base64 0.22.1",
"filmcraft-engine",
@@ -1718,7 +1738,7 @@ dependencies = [
[[package]]
name = "filmcraft-av1"
version = "0.2.0"
version = "0.2.1"
dependencies = [
"filmcraft-bitstream",
"filmcraft-testkit",
@@ -1729,14 +1749,14 @@ dependencies = [
[[package]]
name = "filmcraft-bitstream"
version = "0.2.0"
version = "0.2.1"
dependencies = [
"proptest",
]
[[package]]
name = "filmcraft-captions"
version = "0.2.0"
version = "0.2.1"
dependencies = [
"filmcraft-color",
"filmcraft-project",
@@ -1749,11 +1769,11 @@ dependencies = [
[[package]]
name = "filmcraft-cfb"
version = "0.2.0"
version = "0.2.1"
[[package]]
name = "filmcraft-cli"
version = "0.2.0"
version = "0.2.1"
dependencies = [
"filmcraft-automation",
"filmcraft-codecs",
@@ -1770,10 +1790,11 @@ dependencies = [
[[package]]
name = "filmcraft-codecs"
version = "0.2.0"
version = "0.2.1"
dependencies = [
"filmcraft-aac",
"filmcraft-ac3",
"filmcraft-apv",
"filmcraft-av1",
"filmcraft-bitstream",
"filmcraft-color",
@@ -1802,7 +1823,7 @@ dependencies = [
[[package]]
name = "filmcraft-color"
version = "0.2.0"
version = "0.2.1"
dependencies = [
"proptest",
"serde",
@@ -1810,7 +1831,7 @@ dependencies = [
[[package]]
name = "filmcraft-dnx"
version = "0.2.0"
version = "0.2.1"
dependencies = [
"filmcraft-bitstream",
"filmcraft-testkit",
@@ -1820,7 +1841,7 @@ dependencies = [
[[package]]
name = "filmcraft-edit"
version = "0.2.0"
version = "0.2.1"
dependencies = [
"filmcraft-media",
"filmcraft-project",
@@ -1832,7 +1853,7 @@ dependencies = [
[[package]]
name = "filmcraft-engine"
version = "0.2.0"
version = "0.2.1"
dependencies = [
"filmcraft-audio-dsp",
"filmcraft-captions",
@@ -1863,9 +1884,10 @@ dependencies = [
[[package]]
name = "filmcraft-export"
version = "0.2.0"
version = "0.2.1"
dependencies = [
"filmcraft-aac",
"filmcraft-apv",
"filmcraft-audio-dsp",
"filmcraft-codecs",
"filmcraft-color",
@@ -1892,7 +1914,7 @@ dependencies = [
[[package]]
name = "filmcraft-format"
version = "0.2.0"
version = "0.2.1"
dependencies = [
"filmcraft-media",
"filmcraft-project",
@@ -1904,7 +1926,7 @@ dependencies = [
[[package]]
name = "filmcraft-frame"
version = "0.2.0"
version = "0.2.1"
dependencies = [
"filmcraft-color",
"filmcraft-time",
@@ -1914,7 +1936,7 @@ dependencies = [
[[package]]
name = "filmcraft-geom"
version = "0.2.0"
version = "0.2.1"
dependencies = [
"proptest",
"serde",
@@ -1922,7 +1944,7 @@ dependencies = [
[[package]]
name = "filmcraft-golden"
version = "0.2.0"
version = "0.2.1"
dependencies = [
"filmcraft-color",
"filmcraft-frame",
@@ -1939,7 +1961,7 @@ dependencies = [
[[package]]
name = "filmcraft-gpu"
version = "0.2.0"
version = "0.2.1"
dependencies = [
"filmcraft-color",
"filmcraft-frame",
@@ -1956,7 +1978,7 @@ dependencies = [
[[package]]
name = "filmcraft-h264"
version = "0.2.0"
version = "0.2.1"
dependencies = [
"filmcraft-bitstream",
"filmcraft-testkit",
@@ -1966,7 +1988,7 @@ dependencies = [
[[package]]
name = "filmcraft-h264enc"
version = "0.2.0"
version = "0.2.1"
dependencies = [
"filmcraft-bitstream",
"filmcraft-testkit",
@@ -1976,7 +1998,7 @@ dependencies = [
[[package]]
name = "filmcraft-hevc"
version = "0.2.0"
version = "0.2.1"
dependencies = [
"filmcraft-bitstream",
"filmcraft-testkit",
@@ -1986,7 +2008,7 @@ dependencies = [
[[package]]
name = "filmcraft-interchange"
version = "0.2.0"
version = "0.2.1"
dependencies = [
"filmcraft-cfb",
"filmcraft-color",
@@ -2003,7 +2025,7 @@ dependencies = [
[[package]]
name = "filmcraft-isobmff"
version = "0.2.0"
version = "0.2.1"
dependencies = [
"filmcraft-bitstream",
"filmcraft-testkit",
@@ -2014,7 +2036,7 @@ dependencies = [
[[package]]
name = "filmcraft-matroska"
version = "0.2.0"
version = "0.2.1"
dependencies = [
"filmcraft-testkit",
"serde_json",
@@ -2022,7 +2044,7 @@ dependencies = [
[[package]]
name = "filmcraft-media"
version = "0.2.0"
version = "0.2.1"
dependencies = [
"filmcraft-color",
"filmcraft-frame",
@@ -2035,7 +2057,7 @@ dependencies = [
[[package]]
name = "filmcraft-mpeg2v"
version = "0.2.0"
version = "0.2.1"
dependencies = [
"filmcraft-testkit",
"rayon",
@@ -2044,7 +2066,7 @@ dependencies = [
[[package]]
name = "filmcraft-mpegts"
version = "0.2.0"
version = "0.2.1"
dependencies = [
"filmcraft-testkit",
"thiserror 2.0.21",
@@ -2052,34 +2074,37 @@ dependencies = [
[[package]]
name = "filmcraft-mxf"
version = "0.2.0"
version = "0.2.1"
dependencies = [
"filmcraft-testkit",
]
[[package]]
name = "filmcraft-ogg"
version = "0.2.0"
version = "0.2.1"
dependencies = [
"filmcraft-testkit",
]
[[package]]
name = "filmcraft-opus"
version = "0.2.0"
version = "0.2.1"
dependencies = [
"filmcraft-testkit",
]
[[package]]
name = "filmcraft-platform"
version = "0.2.0"
version = "0.2.1"
dependencies = [
"filmcraft-codecs",
"filmcraft-color",
"filmcraft-export",
"filmcraft-frame",
"filmcraft-isobmff",
"filmcraft-media",
"filmcraft-project",
"filmcraft-render",
"filmcraft-testkit",
"filmcraft-time",
"log",
@@ -2087,11 +2112,12 @@ dependencies = [
"objc2-core-media",
"objc2-core-video",
"objc2-video-toolbox",
"windows 0.62.2",
]
[[package]]
name = "filmcraft-project"
version = "0.2.0"
version = "0.2.1"
dependencies = [
"filmcraft-color",
"filmcraft-geom",
@@ -2105,7 +2131,7 @@ dependencies = [
[[package]]
name = "filmcraft-prores"
version = "0.2.0"
version = "0.2.1"
dependencies = [
"filmcraft-bitstream",
"filmcraft-testkit",
@@ -2115,7 +2141,7 @@ dependencies = [
[[package]]
name = "filmcraft-render"
version = "0.2.0"
version = "0.2.1"
dependencies = [
"filmcraft-audio-dsp",
"filmcraft-captions",
@@ -2135,7 +2161,7 @@ dependencies = [
[[package]]
name = "filmcraft-scopes"
version = "0.2.0"
version = "0.2.1"
dependencies = [
"filmcraft-color",
"serde",
@@ -2144,7 +2170,7 @@ dependencies = [
[[package]]
name = "filmcraft-speech"
version = "0.2.0"
version = "0.2.1"
dependencies = [
"candle-core",
"candle-nn",
@@ -2162,14 +2188,14 @@ dependencies = [
[[package]]
name = "filmcraft-testkit"
version = "0.2.0"
version = "0.2.1"
dependencies = [
"png",
]
[[package]]
name = "filmcraft-text"
version = "0.2.0"
version = "0.2.1"
dependencies = [
"filmcraft-color",
"harfrust",
@@ -2180,7 +2206,7 @@ dependencies = [
[[package]]
name = "filmcraft-time"
version = "0.2.0"
version = "0.2.1"
dependencies = [
"proptest",
"serde",
@@ -2188,8 +2214,9 @@ dependencies = [
[[package]]
name = "filmcraft-ui-egui"
version = "0.2.0"
version = "0.2.1"
dependencies = [
"cpu-time",
"eframe",
"egui",
"egui_kittest",
@@ -2221,7 +2248,7 @@ dependencies = [
[[package]]
name = "filmcraft-vp9"
version = "0.2.0"
version = "0.2.1"
dependencies = [
"filmcraft-bitstream",
"rayon",
@@ -2230,7 +2257,7 @@ dependencies = [
[[package]]
name = "filmcraft-web"
version = "0.2.0"
version = "0.2.1"
dependencies = [
"eframe",
"egui",
@@ -7211,7 +7238,7 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7"
[[package]]
name = "xtask"
version = "0.2.0"
version = "0.2.1"
dependencies = [
"filmcraft-testkit",
"serde_json",
+5 -1
View File
@@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"]
default-members = ["crates/*", "apps/*", "xtask"]
[workspace.package]
version = "0.2.0"
version = "0.2.1"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
@@ -29,6 +29,7 @@ filmcraft-hevc = { path = "crates/hevc" }
filmcraft-vp9 = { path = "crates/vp9" }
filmcraft-prores = { path = "crates/prores" }
filmcraft-dnx = { path = "crates/dnx" }
filmcraft-apv = { path = "crates/apv" }
filmcraft-av1 = { path = "crates/av1" }
filmcraft-aac = { path = "crates/aac" }
filmcraft-opus = { path = "crates/opus" }
@@ -101,6 +102,9 @@ opt-level = 3
[profile.dev.package.filmcraft-dnx]
opt-level = 3
[profile.dev.package.filmcraft-apv]
opt-level = 3
[profile.dev.package.filmcraft-av1]
opt-level = 3
+3
View File
@@ -15,4 +15,7 @@ list (author, source, license) is in ATTRIBUTION.md.
Inter font (assets/fonts/Inter-*.ttf) — OFL-1.1. See assets/fonts/OFL-Inter.txt.
Noto Serif font (assets/fonts/NotoSerif-Regular.ttf) — OFL-1.1. See assets/fonts/OFL-NotoSerif.txt.
JetBrains Mono font (assets/fonts/JetBrainsMono-Regular.ttf) — OFL-1.1. See assets/fonts/OFL-JetBrainsMono.txt.
Builds made with craft-fonts (CRAFT_FONTS_DIR; all official releases) also embed the fonts listed in
https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md (BIZ UDPGothic, Shippori Mincho,
BIZ UDMincho) — OFL-1.1. Their licence texts ship with the packages as OFL-<family>.txt.
Public-domain film and NASA frames and CC0 music shown in README screenshots (docs/images/) — public domain / CC0-1.0. See ATTRIBUTION.md.
+20 -7
View File
@@ -184,7 +184,7 @@ No FFmpeg inside. The video codecs, AAC, Opus and the containers are our own Rus
| **Matroska / WebM** | ✓ | | Lacing, Cues, header stripping, HDR colour metadata |
| **Stills** | ✓ | ✓ | Import PNG, JPEG, GIF, WebP, TIFF and BMP; export PNG sequences and animated GIF |
Also imported: MPEG-2 / MPEG-1 video, AC-3, MP2, MXF (OP1a / OP-Atom), MPEG transport and program streams (AVCHD, broadcast, DVD), Ogg and image sequences. Not yet: HEVC and AV1 export, camera RAW, E-AC-3. Hardware decoding works on macOS (VideoToolbox), with Linux and Windows to follow ([#30](https://github.com/storytold/filmcraft/issues/30)).
Also imported: MPEG-2 / MPEG-1 video, AC-3, MP2, MXF (OP1a / OP-Atom), MPEG transport and program streams (AVCHD, broadcast, DVD), Ogg and image sequences. Not yet: HEVC and AV1 export, camera RAW, E-AC-3. Hardware decoding works on macOS (VideoToolbox) and Windows (Media Foundation), with Linux to follow; H.264 export can use NVIDIA's encoder on Windows (opt-in) ([#30](https://github.com/storytold/filmcraft/issues/30)).
<br>
@@ -196,7 +196,7 @@ Also imported: MPEG-2 / MPEG-1 video, AC-3, MP2, MXF (OP1a / OP-Atom), MPEG tran
<p align="center"><sub>Export mode, set to write the trailer as H.264 MP4.</sub></p>
- **H.264 MP4 with AAC, using our own encoders.** A 6-second 960×540 render takes 1.3 seconds and decodes cleanly in ffmpeg with error concealment switched off.
- **H.264 MP4 with AAC, using our own encoders.** A 6-second 960×540 render takes 1.3 seconds and decodes in ffmpeg without a single warning, with strict error detection on.
- **Also:** Apple ProRes 422 HQ and Motion JPEG in QuickTime, MXF OP1a and Avid-style OP-Atom (DNxHR, ProRes or H.264 with PCM and start timecode), PNG sequences, animated GIF and WAV.
- **Background jobs** with progress and cancel, so you keep editing while it renders.
- **Render previews:** the render bar marks segments green, yellow or red; rendered previews are cached by content, so an edit only invalidates what it touches and undo brings the green back.
@@ -220,7 +220,7 @@ Import merges the document's bins, media and sequences into your project as one
## Built for agents
Every menu item, button, slider and drag in FilmCraft is a **command** with an id, typed parameters and an enabled state. There are about 135 engine commands so far, with the rest of Premiere's catalogue on the way. The UI, the CLI, a JSON control channel and an **MCP server** all dispatch the same commands, so Claude or any agent can cut, trim, grade, mix and export exactly the way a person does. The UI can also be driven at the level of mouse and keyboard: every widget has an automation id, and agents can click, drag, type and take screenshots.
Every menu item, button, slider and drag in FilmCraft is a **command** with an id, typed parameters and an enabled state. There are more than 650 engine commands (`filmcraft-cli commands` lists them), with the rest of Premiere's catalogue on the way. The UI, the CLI, a JSON control channel and an **MCP server** all dispatch the same commands, so Claude or any agent can cut, trim, grade, mix and export exactly the way a person does. The UI can also be driven at the level of mouse and keyboard: every widget has an automation id, and agents can click, drag, type and take screenshots.
```jsonc
// over the control channel (JSON lines on TCP) or as MCP tool calls
@@ -238,7 +238,7 @@ The trailer and the grades in these screenshots were built exactly this way, by
## Everywhere
- **Native** on macOS, Windows and Linux, with a native macOS menu bar.
- **The web:** every crate up to the engine compiles to `wasm32`; the browser front end is next.
- **The web:** the same engine and UI run in the browser via WebAssembly (`apps/filmcraft-web`, see [docs/web.md](docs/web.md)); every release ships it as `filmcraft-web-<version>.zip`.
- **Swappable UI.** The interface is one crate (`ui-egui`) over the engine, so a different front end can replace it without touching editing logic.
<br>
@@ -252,6 +252,13 @@ cargo run --release -p filmcraft-cli -- commands # list every engine c
cargo run --release -p filmcraft-cli -- mcp # MCP server (headless)
```
Japanese text in the interface and in titles comes from [craft-fonts](https://github.com/storytold/craft-fonts), an optional build input (release builds always include it; without it FilmCraft uses its own and the system's fonts):
```sh
git clone https://github.com/storytold/craft-fonts ../craft-fonts
CRAFT_FONTS_DIR="$PWD/../craft-fonts" cargo run --release -p filmcraft
```
The control protocol is documented in [docs/control-protocol.md](docs/control-protocol.md). Stuck, or want to show what you made? Ask in [Discord](https://discord.gg/artcraft).
## Documentation
@@ -279,7 +286,7 @@ We track two numbers ([ROADMAP.md](ROADMAP.md#honest-assessment-2026-10-05)):
The biggest gaps today:
- **Speed on big footage.** Hardware decoding works on macOS; Windows and Linux have no hardware path yet. Blend modes and the most common effects run on the GPU, but Lumetri, keys, export and encoding still run on the CPU ([#30](https://github.com/storytold/filmcraft/issues/30)).
- **Speed on big footage.** Hardware decoding works on macOS and Windows; Linux has no hardware path yet. Blend modes and the most common effects run on the GPU, but Lumetri, keys and export rendering still run on the CPU; H.264 encoding can use the hardware encoder on macOS and on Windows with an NVIDIA GPU (opt-in, Export ▸ Hardware encoding), and H.265 export is hardware-only there ([#30](https://github.com/storytold/filmcraft/issues/30)).
- **No plugins.** No VST3 / Audio Units or OpenFX hosting.
- **Delivery codecs.** H.264 is our only delivery-codec export; no HEVC or AV1 export yet.
- **Real-world media and platforms.** Our decoders are bit-exact on conformance streams, but camera and phone files in the wild are less tested. Windows and Linux get far less testing than macOS.
@@ -315,7 +322,7 @@ stand on its own.
| <img src="https://raw.githubusercontent.com/storytold/vectorcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.vectorcraft.png" alt="" width="32" height="32"> | **VectorCraft** | Vector illustration | [GitHub](https://github.com/storytold/vectorcraft) | [Website](https://getartcraft.com/apps/vectorcraft) |
| <img src="https://raw.githubusercontent.com/storytold/filmcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.filmcraft.png" alt="" width="32" height="32"> | **FilmCraft** | **Video editing, color and sound · you are here** | [GitHub](https://github.com/storytold/filmcraft) | [Website](https://getartcraft.com/apps/filmcraft) |
| <img src="https://raw.githubusercontent.com/storytold/lightcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.lightcraft.png" alt="" width="32" height="32"> | **LightCraft** | Photo library and raw development | [GitHub](https://github.com/storytold/lightcraft) | [Website](https://getartcraft.com/apps/lightcraft) |
| <img src="https://raw.githubusercontent.com/storytold/printcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.printcraft.png" alt="" width="32" height="32"> | **PrintCraft** | Reading, organizing and protecting PDFs | [GitHub](https://github.com/storytold/printcraft) | [Website](https://getartcraft.com/apps/printcraft) |
| <img src="https://raw.githubusercontent.com/storytold/pdfcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.pdfcraft.png" alt="" width="32" height="32"> | **PdfCraft** | Reading, organizing and protecting PDFs | [GitHub](https://github.com/storytold/pdfcraft) | [Website](https://getartcraft.com/apps/pdfcraft) |
| <img src="https://raw.githubusercontent.com/storytold/effectcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.effectcraft.png" alt="" width="32" height="32"> | **EffectCraft** | Motion graphics and visual effects | [GitHub](https://github.com/storytold/effectcraft) | [Website](https://getartcraft.com/apps/effectcraft) |
| <img src="https://raw.githubusercontent.com/storytold/designcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.designcraft.png" alt="" width="32" height="32"> | **DesignCraft** | Page layout and publishing | [GitHub](https://github.com/storytold/designcraft) | [Website](https://getartcraft.com/apps/designcraft) |
@@ -351,7 +358,9 @@ FilmCraft is dual-licensed under [MIT](LICENSE-MIT) or [Apache-2.0](LICENSE-APAC
Copyright (c) 2026 ArtCraft Team and the FilmCraft contributors. Required notices are in [NOTICE](NOTICE).
Bundled fonts, icons, images and other assets keep their own open licenses; each one is listed
with its author, source and license in [ATTRIBUTION.md](ATTRIBUTION.md).
with its author, source and license in [ATTRIBUTION.md](ATTRIBUTION.md). Builds made with
[craft-fonts](https://github.com/storytold/craft-fonts) (all official releases) also embed its fonts
(OFL-1.1), listed in its [ATTRIBUTION.md](https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md).
**Footage and music in the screenshots:** NASA's Apollo 11 film and television footage from [images.nasa.gov](https://images.nasa.gov) (launch, Launch Control Center, lunar surface and recovery) and the Apollo 11 air-to-ground voice transcript, all US Government works in the public domain (NASA does not endorse this project); *Night of the Living Dead* (1968), *Carnival of Souls* (1962) and *Charade* (1963), all in the US public domain; *Earth Views from the ISS* by NASA; Chopin's Nocturne Op. 48 No. 1 and Ballade No. 1, performed for Musopen and released under CC0. The media itself is not in this repository. Sources and details for every asset are in [ATTRIBUTION.md](ATTRIBUTION.md).
@@ -370,3 +379,7 @@ Forks and modified versions must remove them.
<a href="https://getartcraft.com/"><img alt="ArtCraft" src="docs/brand/artcraft-mark.svg" width="28"></a><br>
<sub>Made by the <a href="https://getartcraft.com/">ArtCraft</a> team and community.</sub>
</p>
## Star history
[![Star History Chart](https://api.star-history.com/svg?repos=storytold/filmcraft&type=Date&legend=top-left)](https://www.star-history.com/?repos=storytold%2Ffilmcraft&type=date&legend=top-left)
+12 -6
View File
@@ -36,7 +36,7 @@ before choosing work.
| **Correctness in depth** | not tracked | **~60–70%** | A first-time contributor found four real bugs in core paths within hours (#5–#8: AIFF import failed, Slide left linked audio behind, transitions didn't follow ripple trims, export ignored start/end times). User reports: Color Matte always grey with no picker (#29); ALSA audio error on Linux (#23). Settings are "most wired", not all. |
| **Codecs and media** | ~90% | **~75%** | Our decoders are bit-exact on conformance streams. Real camera and phone media (variable frame rate, damaged files, unusual containers) is far less tested. No camera RAW (RED, BRAW, ARRIRAW), no E-AC-3. |
| **Export** | ~92% | **~70%** | Delivery: H.264 only (ProRes, DNxHR and image sequences cover mastering). No HEVC or AV1 export. AAF and OMF have never been validated in Avid Media Composer or Pro Tools. Export renders and encodes on the CPU only. |
| **Performance and hardware** | ~62% | **~35–40%** | Premiere runs effects, decoding and encoding on the GPU and the hardware media engines. Here, hardware decode works on macOS only (VideoToolbox, #33). The GPU does compositing, blend modes (#32) and 31 common effects (GPU2): colour adjustments, crop/flip/transform, blurs, sharpen. Lumetri, keys, masks, the remaining effects, export and encoding are CPU. Linux and Windows have no hardware path. 8K and AV1 aren't real-time. The effect list shows Premiere's "GPU accelerated" badge, but only 31 effect ids run on the GPU here; the rest, Lumetri included, run on the CPU. |
| **Performance and hardware** | ~62% | **~35–40%** | Premiere runs effects, decoding and encoding on the GPU and the hardware media engines. Here, hardware decode works on macOS (VideoToolbox, #33; active in the desktop app only since #41, so releases up to 0.2.1 decoded in software) and Windows (Media Foundation / Direct3D 11 DXVA, H.264, HEVC Main / Main 10, VP9 and AV1 4:2:0 8/10-bit, #30). The GPU does compositing, blend modes (#32) and 31 common effects (GPU2): colour adjustments, crop/flip/transform, blurs, sharpen. Lumetri, keys, masks, the remaining effects and export rendering are CPU; H.264 encoding can use VideoToolbox on macOS (opt-in per export, no B-frames) and NVENC on Windows with an NVIDIA GPU (opt-in per export), and H.265 (HEVC) export exists there only, through the same hardware encoder. Linux has no hardware path. 8K isn't real-time (AV1 is on Windows with a hardware decoder). The effect list shows Premiere's "GPU accelerated" badge, but only 31 effect ids run on the GPU here; the rest, Lumetri included, run on the CPU. |
| **Stability** | not tracked | **improving, unproven** | The never-crash pass (no panics in product code, last-resort guards) landed on 2026-10-04. There's no field record from real users' projects yet. |
| **Plugins and pro ecosystem** | not tracked | **~0–10%** | No audio plugin hosting (VST3 / Audio Units) and no third-party video effects (OpenFX). For many professional editors this alone rules FilmCraft out. Team Projects and Productions are out of scope by design. |
| **AI features** | partial | **~25–35%** | Speech to text exists but is off in default builds (the `whisper` feature). Enhance Speech is a DSP chain, not a model. Auto Reframe is approximate. No Generative Extend, and no media-intelligence search or auto colour. |
@@ -48,10 +48,10 @@ before choosing work.
In priority order. Agents should prefer this work over adding more checklist items.
1. **Hardware acceleration** (#30), the most visible gap to users:
- hardware decode on Linux (VA-API) and Windows (Media Foundation);
- hardware decode on Linux (VA-API);
- zero-copy decoded frames into wgpu;
- the remaining effects on the GPU: Lumetri, keys, Vignette, Video Limiter, masks (31 common effects are done);
- GPU export, then hardware encode (H.264 / HEVC).
- GPU export, then hardware encode: H.264 and H.265 on macOS are in (H.264 opt-in; H.265 has no other encoder), H.264 on NVENC (Windows, opt-in); HEVC on Windows and Linux remain.
2. **A measured parity number.** Add `cargo xtask parity`, run in CI. It should cover menus,
commands, effects, transitions, panels, preferences and formats against the Premiere snapshot in
`plan/premiere/`. It should report presence and fidelity separately (exact, approximate, stub).
@@ -63,7 +63,7 @@ In priority order. Agents should prefer this work over adding more checklist ite
through XML / AAF.
5. **Windows and Linux at runtime.** CI that runs the test suite and a headless playback/export
smoke test on both, not just release builds. Fix the Linux audio path (#23).
6. **Delivery codecs.** HEVC and AV1 export: hardware encoders first, and `rav1e` (BSD-2) for AV1.
6. **Delivery codecs.** HEVC export is in on macOS (VideoToolbox, 8-bit, no software encoder); still to do: HEVC elsewhere, 10-bit / HDR HEVC, and AV1 (`rav1e`, BSD-2).
7. **Plugin hosting** (VST3 / Audio Units, then OpenFX). Needs FFI, so it falls under the isolated
`unsafe` crate rule (AGENTS.md §0.3). **Owner decision needed** before starting.
8. **AI features** with openly licensed local models: transcription on by default, text-based
@@ -100,7 +100,7 @@ matched against `filmcraft-cli commands` and the UI command table. Effects: the
| Graphics and captions | 8% | text engine, shapes, per-character styles, our own graphics templates (.fcgt, 8 built-ins, export/install/edit), rolls/crawls, responsive pins + time, captions SRT/VTT/SCC/MCC/STL/TTML/DFXP, transcripts | ~85% |
| Export | 8% | own H.264/AAC, ProRes, DNxHR, MXF OP1a/OP-Atom, image sequences, GIF, WAV, 5.1; preset library + user presets, full Export-mode settings, queue, Quick Export; AAF (Edit Protocol) import/export, OMF 2.0 export; no AAF/OMF validation against Avid/Pro Tools yet | ~92% |
| Preferences and project management | 5% | Settings dialog with 16 categories (most settings wired), project settings, scratch disks, search bins, templates | ~80% |
| Performance | 5% | 1080p real-time, 3×1080p; 4K H.264 real-time at load ≤140 (−23% decoder cycles, opt-in draft decoding at 1/2–1/4); HEVC 2.5× cheaper, catch-up decoding, `cargo xtask bench` + `perf.stats`; blend modes on the GPU (#32); 8K and AV1 not yet real-time on a loaded machine; no hardware path on Windows/Linux (see the honest assessment: ~35–40% against Premiere) | ~62% |
| Performance | 5% | 1080p real-time, 3×1080p; 4K H.264 real-time at load ≤140 (−23% decoder cycles, opt-in draft decoding at 1/2–1/4); HEVC 2.5× cheaper, catch-up decoding, `cargo xtask bench` + `perf.stats`; blend modes on the GPU (#32); 8K and AV1 not yet real-time on a loaded machine; no hardware path on Linux, and on Windows only decode and opt-in NVENC H.264 export (see the honest assessment: ~35–40% against Premiere) | ~62% |
| **Weighted total** | | | **~87%** |
## Estimate to parity
@@ -154,11 +154,13 @@ Status: ✅ done · 🟡 in progress · ⬜ not started. Estimates are remaining
## Running now
- **Hardware acceleration (#30):** landed: blend modes on the GPU (#32); VideoToolbox hardware decode + the `platform` FFI crate (#33); 31 common effects on the GPU (GPU2). Next: VA-API (Linux) and Media Foundation (Windows) decode, zero-copy upload, Lumetri on the GPU.
- **Hardware acceleration (#30):** landed: blend modes on the GPU (#32); VideoToolbox hardware decode + the `platform` FFI crate (#33); 31 common effects on the GPU (GPU2). Windows: Media Foundation / Direct3D 11 H.264 + HEVC decode (HW2) and VP9 + AV1 (HW3), NVENC H.264 export (HW4, opt-in). Next: VA-API (Linux) decode, zero-copy upload, Lumetri on the GPU.
- **Next:** [Where we are lacking](#where-we-are-lacking) items 1–5. GPU export waits for the export-crate work (#19 and the never-crash follow-up) to land.
## Log
- **2026-10-06:** 21 community PRs landed (#19, #28, #38, #39, #41–#60). Highlights: hardware decoding is now actually on in the desktop app (#41: `register()` sat inside a `log::info!` that never ran, so #33's VideoToolbox path only worked in the CLI and benchmarks); decode memory on long timelines cut sharply (frame pool, shared GOP-cache budget, positional file reads); exports are byte-identical across machines (#19); crash fix for odd track names over MCP (#44); ripple trim, ripple delete and speed changes move split-edit clips once (#56–#58); Japanese interface using an installed system font (#38; no fonts bundled); MCP annotations, resources, export progress and cancellation (#28).
- **2026-10-05:** honest assessment added (checklist ~87% vs ready for real work ~50–60%). Hardware acceleration started (#30): blend modes on the GPU (#32); VideoToolbox decode + `platform` crate, the one crate allowed `unsafe` (#33). Community fixes landed: AIFF import, export start/end ranges, transitions following ripple trims, Slide moving linked audio (#5–#8).
- **2026-10-04 (later):** interchange + MXF export (M11.4/M6.6): own compound-file container (`crates/cfb`), AAF Edit Protocol import/export (embedded/linked/consolidated audio, video mixdown, handles, breakout to mono), OMF 2.0 export (Bento), MXF OP1a/OP-Atom writer (DNxHR/ProRes/H.264/PCM) as export formats. 1605 tests.
@@ -200,3 +202,7 @@ Status: ✅ done · 🟡 in progress · ⬜ not started. Estimates are remaining
- **2026-09-30 (midday):** HEVC decoder, Matroska/WebM demuxer and audio DSP merged; HEVC import wired; asset rules (AGENTS.md, ATTRIBUTION.md, `cargo xtask assets`); README with hero screenshot and the Craft family.
- **2026-09-30 (late morning):** keyframe value/velocity graphs; xtask gates; H.264 MP4 export; Lumetri curves, wheels, looks, HSL secondary.
- **2026-09-30 (early morning):** H.264 decoder, ProRes, AAC; GPU compositor; MCP; Premiere 26 visual fidelity pass.
### Interface localization
Edit > Language switches English/Japanese/Spanish/Portuguese (Brazilian) and persists in UI state. Commands `app.language.english`, `app.language.japanese`, `app.language.spanish` and `app.language.portuguese` are reachable through the control channel. Core native/in-window menu labels are translated; untranslated labels use English. Japanese text uses the Japanese fonts from [craft-fonts](https://github.com/storytold/craft-fonts) when FilmCraft is built with them (`CRAFT_FONTS_DIR`; all official releases, including the web build), otherwise a Japanese font already installed on the system; with neither, switching to Japanese is refused with a message. Dialog/panel translation coverage remains open. Existing vertical text support is preserved.
+23 -5
View File
@@ -27,12 +27,16 @@ SUBCOMMANDS
inspect [project|sequence] project tree or active sequence as JSON (default: both)
import <file>... import media into the project
export <out> [--preset name] [--format f] [--range r] [--start s --end s] [--settings json]
[--scale f] [--quality 0-100] [--no-audio] [--queue]
export the active sequence and wait for it to finish: with an
export preset (`export --list-presets`; built-in or the user's), or
a format (h264|prores|dnxhr|mjpeg|mxf-op1a|mxf-opatom|png|tiff|bmp|gif|wav|aiff, guessed
a format (h264|hevc|prores|dnxhr|apv|mjpeg|mxf-op1a|mxf-opatom|png|tiff|bmp|gif|wav|aiff, guessed
from the extension); --range entire|inOut|workArea, or a custom
range in seconds; --settings is ExportSettings JSON merged over the
preset; --queue adds to the export queue and runs it instead
preset; --scale renders at a fraction of the frame size (0.5 =
half); --quality 0-100 for the formats that take one; --no-audio
leaves the sound out; --queue adds to the export queue and runs it
instead
export --list-presets [query] list export presets (name, category, format) as JSON
render --seconds S --out f.png [--scale 0.5] render one Program frame to PNG
probe <media> [--image-sequence]
@@ -105,7 +109,8 @@ impl Backend {
async fn exec(&mut self, id: &str, params: Value) -> Result<Value, String> {
match self {
Backend::Local(s) => s.execute(id, params).map_err(|e| e.to_string()),
Backend::Bridge(b) => b.call("engine.execute", json!({"command": id, "params": params})).await.map_err(|e| e.to_string()),
// a blocking export runs as an app job polled by the client (#91, #92)
Backend::Bridge(b) => b.execute(id, params).await.map_err(|e| e.to_string()),
}
}
@@ -149,14 +154,19 @@ fn format_for(path: &str) -> Option<&'static str> {
})
}
/// OS hardware video decoders (VideoToolbox on macOS, Media Foundation on Windows) in front of our
/// own, as in the desktop app. Also what `mcp` and the headless commands decode with.
fn register_hardware_decoders() -> filmcraft_platform::Availability {
filmcraft_platform::register()
}
#[tokio::main]
async fn main() {
if matches!(std::env::args().nth(1).as_deref(), Some("--version" | "-V")) {
println!("filmcraft-cli {}", env!("CARGO_PKG_VERSION"));
return;
}
// OS hardware video decoders (VideoToolbox on macOS) in front of our own, as in the desktop app.
let _ = filmcraft_platform::register();
register_hardware_decoders();
let a = Args::parse(std::env::args().skip(1));
let Some(cmd) = a.pos(0) else { usage("missing subcommand") };
match cmd {
@@ -373,6 +383,14 @@ async fn main() {
#[cfg(test)]
mod format_tests {
/// The CLI (and MCP / headless runs, which share its entry point) registers the hardware
/// decoders at start-up.
#[test]
fn startup_registers_the_hardware_decoders() {
let hardware = super::register_hardware_decoders();
assert_eq!(filmcraft_platform::registered(), cfg!(any(target_os = "macos", target_os = "windows")), "{hardware:?}");
}
#[test]
fn export_format_from_extension() {
assert_eq!(super::format_for("out/clip.MXF"), Some("mxf-op1a"));
+22 -6
View File
@@ -170,11 +170,11 @@ pub fn install() -> Result<(), JsValue> {
&obj,
"readFile",
Closure::<dyn Fn(String) -> js_sys::Promise>::new(|path: String| {
future_to_promise(async move {
future_to_promise(caught(async move {
let blob = crate::fs::blob(&path).ok_or_else(|| JsValue::from_str(&format!("{path}: not found")))?;
let buf = JsFuture::from(blob.array_buffer()).await?;
Ok(js_sys::Uint8Array::new(&buf).into())
})
}))
})
.into_js_value(),
)?;
@@ -191,10 +191,10 @@ pub fn install() -> Result<(), JsValue> {
&obj,
"importUrl",
Closure::<dyn Fn(String, JsValue) -> js_sys::Promise>::new(|url: String, name: JsValue| {
future_to_promise(async move {
future_to_promise(caught(async move {
let f = fetch_file(&url, name.as_string()).await?;
Ok(to_js(&crate::import::import_files(vec![f]).await))
})
}))
})
.into_js_value(),
)?;
@@ -202,13 +202,13 @@ pub fn install() -> Result<(), JsValue> {
&obj,
"openProject",
Closure::<dyn Fn(JsValue) -> js_sys::Promise>::new(|src: JsValue| {
future_to_promise(async move {
future_to_promise(caught(async move {
let file = match src.as_string() {
Some(url) => fetch_file(&url, None).await?,
None => files_of(&src).into_iter().next().ok_or("need a File or URL")?,
};
crate::import::open_project_file(file).await.map(|v| to_js(&v)).map_err(|e| JsValue::from(js_sys::Error::new(&e)))
})
}))
})
.into_js_value(),
)?;
@@ -216,3 +216,19 @@ pub fn install() -> Result<(), JsValue> {
js_sys::Reflect::set(&w, &"filmcraft".into(), &obj)?;
Ok(())
}
/// `f`, rejecting with an [`as_error`] `Error`.
async fn caught(f: impl std::future::Future<Output = Result<JsValue, JsValue>>) -> Result<JsValue, JsValue> {
f.await.map_err(as_error)
}
/// Every member rejects with an `Error` (#90), as `execute` and `request` do, so `e.message` and
/// `e instanceof Error` work: a plain string (a fetch status, "not found") becomes one, and an
/// `Error` passes through unchanged.
fn as_error(e: JsValue) -> JsValue {
if e.is_instance_of::<js_sys::Error>() {
return e;
}
let msg = e.as_string().unwrap_or_else(|| format!("{e:?}"));
js_sys::Error::new(&msg).into()
}
+2 -1
View File
@@ -502,7 +502,8 @@ impl MediaSource for WcSource {
}
let t = &self.file.tracks[self.track];
let n = t.samples.len();
let target = req.time.max(Tick::ZERO).to_rational_floor(1, t.timescale.max(1) as i64);
// nearest, as `Mp4Source` looks frames up (sample times are rounded to the timescale)
let target = req.time.max(Tick::ZERO).to_rational_round(1, t.timescale.max(1) as i64);
let i = t.sample_at_presentation_time(target).unwrap_or(n - 1).min(n - 1);
let want = t.samples[i].pts;
self.collect(&mut c, want);
+171
View File
@@ -0,0 +1,171 @@
//! The desktop app's command line (`filmcraft --help`).
/// `filmcraft --help`.
pub const USAGE: &str = "\
Usage: filmcraft [options] [project.fcproj | media files...]
Options:
--control <port> start the localhost JSON-lines control server
(also: FILMCRAFT_CONTROL_PORT)
--demo open the demo project
--empty start with an empty project
--recover recover the newest unsaved changes without asking
--no-recover start without asking about unsaved changes
--data-dir <dir> folder for auto-save, crash recovery and logs
(also: FILMCRAFT_DATA_DIR)
--version print the version and exit
-h, --help print this help and exit
";
/// What the command line asks for.
#[derive(Debug, PartialEq)]
pub enum Cli {
Run(Launch),
Help,
Version,
}
/// Options of a normal start.
#[derive(Debug, PartialEq)]
pub struct Launch {
pub control_port: Option<u16>,
/// A project and / or media files to open.
pub files: Vec<String>,
pub demo: bool,
/// `--demo` / `--empty` given: skip Settings ▸ General ▸ At Startup.
pub startup_flag: bool,
pub recover: Option<bool>,
pub data_dir: Option<std::path::PathBuf>,
}
/// Parse the arguments after the program name. `env_control_port` is the value of
/// `FILMCRAFT_CONTROL_PORT`, used when `--control` is not given (an empty value counts as unset).
///
/// An option we don't know, or one without a usable value, is an error: opening a window for a
/// mistyped flag helps nobody, and starting without the control server that was asked for leaves
/// a script waiting for it. That holds for the whole line, so `--version --bogus` is an error
/// too, and for a port from the environment exactly as for one from `--control`.
pub fn parse(env_control_port: Option<String>, args: impl IntoIterator<Item = String>) -> Result<Cli, String> {
let mut l = Launch { control_port: None, files: Vec::new(), demo: true, startup_flag: false, recover: None, data_dir: None };
let (mut help, mut version) = (false, false);
let mut args = args.into_iter();
while let Some(a) = args.next() {
match a.as_str() {
"-h" | "--help" => help = true,
"--version" => version = true,
"--control" => {
let port = args.next().ok_or("--control needs a port number")?;
l.control_port = Some(port.parse().map_err(|_| format!("--control needs a port number, got `{port}`"))?);
}
"--demo" => (l.demo, l.startup_flag) = (true, true),
"--empty" => (l.demo, l.startup_flag) = (false, true),
"--recover" => l.recover = Some(true),
"--no-recover" => l.recover = Some(false),
"--data-dir" => l.data_dir = Some(args.next().map(std::path::PathBuf::from).ok_or("--data-dir needs a folder")?),
// everything after `--` is a file, whatever it looks like
"--" => l.files.extend(args.by_ref()),
// macOS adds a process serial number when it launches an app bundle
_ if a.starts_with("-psn_") => {}
_ if a.len() > 1 && a.starts_with('-') => return Err(format!("unknown option `{a}`")),
_ => l.files.push(a),
}
}
if help {
return Ok(Cli::Help);
}
if version {
return Ok(Cli::Version);
}
if l.control_port.is_none()
&& let Some(port) = env_control_port.as_deref().map(str::trim).filter(|p| !p.is_empty())
{
l.control_port = Some(port.parse().map_err(|_| format!("FILMCRAFT_CONTROL_PORT needs a port number, got `{port}`"))?);
}
Ok(Cli::Run(l))
}
#[cfg(test)]
mod tests {
use super::*;
fn parse_env(env: Option<&str>, args: &[&str]) -> Result<Cli, String> {
parse(env.map(str::to_string), args.iter().map(|a| a.to_string()))
}
fn parse_args(args: &[&str]) -> Result<Cli, String> {
parse_env(None, args)
}
fn launch(args: &[&str]) -> Launch {
match parse_args(args) {
Ok(Cli::Run(l)) => l,
other => panic!("{args:?} should start the app, got {other:?}"),
}
}
/// `filmcraft --help` used to open the app with "--help" as a media file to import.
#[test]
fn help_and_version_do_not_start_the_app() {
assert_eq!(parse_args(&["--help"]), Ok(Cli::Help));
assert_eq!(parse_args(&["-h"]), Ok(Cli::Help));
assert_eq!(parse_args(&["--empty", "--help"]), Ok(Cli::Help));
assert_eq!(parse_args(&["--version"]), Ok(Cli::Version));
assert_eq!(parse_args(&["--version", "--help"]), Ok(Cli::Help));
assert_eq!(parse_args(&["a.mp4", "--version"]), Ok(Cli::Version));
for flag in ["--control", "--demo", "--empty", "--recover", "--no-recover", "--data-dir", "--version", "--help"] {
assert!(USAGE.contains(flag), "usage lists {flag}");
}
}
#[test]
fn unknown_options_are_errors() {
assert_eq!(parse_args(&["--frobnicate"]), Err("unknown option `--frobnicate`".to_string()));
assert!(parse_args(&["a.mp4", "-x"]).is_err());
assert!(parse_args(&["--Help"]).is_err());
assert!(parse_args(&["--control"]).is_err(), "missing port");
assert!(parse_args(&["--control", "abc"]).unwrap_err().contains("abc"));
assert!(parse_args(&["--control", "70000"]).is_err(), "not a port");
assert!(parse_args(&["--data-dir"]).is_err(), "missing folder");
// the whole line is checked, whatever comes first
assert_eq!(parse_args(&["--version", "--bogus"]), Err("unknown option `--bogus`".to_string()));
assert_eq!(parse_args(&["--bogus", "--version"]), Err("unknown option `--bogus`".to_string()));
assert_eq!(parse_args(&["--help", "--bogus"]), Err("unknown option `--bogus`".to_string()));
assert!(parse_args(&["--help", "--control"]).is_err());
}
/// A bad `FILMCRAFT_CONTROL_PORT` used to start the app without the control server, silently.
#[test]
fn a_bad_port_in_the_environment_is_an_error_like_a_bad_control_flag() {
for bad in ["abc", "70000", "-1", "98 76", "9876x", "\u{fffd}"] {
let e = parse_env(Some(bad), &[]).unwrap_err();
assert!(e.contains("FILMCRAFT_CONTROL_PORT") && e.contains(bad), "{bad}: {e}");
assert!(parse_env(Some(bad), &["--empty", "a.mp4"]).is_err(), "{bad}");
// the flag wins, so the environment's value is not looked at; nor for --help / --version
assert_eq!(parse_env(Some(bad), &["--control", "9"]).map(|c| matches!(c, Cli::Run(l) if l.control_port == Some(9))), Ok(true), "{bad}");
assert_eq!(parse_env(Some(bad), &["--help"]), Ok(Cli::Help));
assert_eq!(parse_env(Some(bad), &["--version"]), Ok(Cli::Version));
}
// unset or empty: no control server
assert_eq!(launch(&[]).control_port, None);
assert_eq!(parse_env(Some(""), &[]), Ok(Cli::Run(launch(&[]))));
assert_eq!(parse_env(Some(" "), &[]), Ok(Cli::Run(launch(&[]))));
// a good one is the default
assert_eq!(parse_env(Some("1234"), &[]), Ok(Cli::Run(Launch { control_port: Some(1234), ..launch(&[]) })));
assert_eq!(parse_env(Some("1234"), &["--control", "9"]).map(|c| matches!(c, Cli::Run(l) if l.control_port == Some(9))), Ok(true));
}
#[test]
fn known_options_and_files_parse_as_before() {
let none = launch(&[]);
assert_eq!(none, Launch { control_port: None, files: vec![], demo: true, startup_flag: false, recover: None, data_dir: None });
let l = launch(&["--control", "9876", "--empty", "--no-recover", "--data-dir", "/tmp/fc", "cut.fcproj", "a.mp4"]);
assert_eq!(l.control_port, Some(9876));
assert_eq!((l.demo, l.startup_flag, l.recover), (false, true, Some(false)));
assert_eq!(l.data_dir, Some(std::path::PathBuf::from("/tmp/fc")));
assert_eq!(l.files, ["cut.fcproj", "a.mp4"]);
assert_eq!((launch(&["--demo"]).demo, launch(&["--demo"]).startup_flag, launch(&["--recover"]).recover), (true, true, Some(true)));
// `--` ends the options; a lone `-` and macOS' process serial number are not options
assert_eq!(launch(&["--", "--odd name.mov", "-h"]).files, ["--odd name.mov", "-h"]);
assert_eq!(launch(&["-", "-psn_0_12345"]).files, ["-"]);
}
}
+14 -1
View File
@@ -12,6 +12,7 @@ pub struct CpalOut {
stream: Option<cpal::Stream>,
played: Arc<AtomicU64>,
rate: u32,
channels: u16,
hw: AudioHardwarePrefs,
/// Sequence sample rate for "Attempt to force hardware to document sample rate".
document_rate: Option<u32>,
@@ -44,7 +45,14 @@ impl CpalOut {
let host = cpal::default_host();
let dev = host.default_output_device()?;
let cfg = dev.default_output_config().ok()?;
Some(Self { stream: None, played: Arc::new(AtomicU64::new(0)), rate: cfg.sample_rate().0, hw: AudioHardwarePrefs::default(), document_rate: None })
Some(Self {
stream: None,
played: Arc::new(AtomicU64::new(0)),
rate: cfg.sample_rate().0,
channels: cfg.channels(),
hw: AudioHardwarePrefs::default(),
document_rate: None,
})
}
/// The stream configuration the settings ask for, falling back to the device default.
@@ -77,6 +85,7 @@ impl AudioOut for CpalOut {
config.buffer_size = cpal::BufferSize::Fixed(self.hw.buffer_size);
}
self.rate = cfg.sample_rate().0;
self.channels = cfg.channels();
self.played.store(0, Ordering::SeqCst);
let played = self.played.clone();
let err = |e| eprintln!("filmcraft: audio stream error: {e}");
@@ -103,6 +112,9 @@ impl AudioOut for CpalOut {
fn sample_rate(&self) -> u32 {
self.rate
}
fn channels(&self) -> usize {
self.channels as usize
}
fn played_frames(&self) -> Option<u64> {
self.stream.as_ref().map(|_| self.played.load(Ordering::SeqCst))
}
@@ -122,6 +134,7 @@ impl AudioOut for CpalOut {
&& let Ok(cfg) = self.config(&dev)
{
self.rate = cfg.sample_rate().0;
self.channels = cfg.channels();
}
}
}
+261 -34
View File
@@ -1,13 +1,27 @@
//! Localhost JSON-lines control server (one request per line, one reply per line). Loopback only.
//!
//! The server only ever reads requests: a line that is not a JSON object with a string `method`
//! (an HTTP request line from a browser's cross-origin `fetch`, a stray `nc`, binary junk) gets
//! one error reply and the connection is closed, so nothing after it is executed. Lines are
//! bounded ([`MAX_LINE`]) and so is the number of open connections ([`MAX_CONNECTIONS`]); junk
//! never reaches the UI thread. See `docs/control-protocol.md`.
use std::io::{BufRead, BufReader, Write};
use std::io::{BufRead, BufReader, Read, Write};
use std::net::{TcpListener, TcpStream};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::{Receiver, Sender, channel};
use std::time::Duration;
use filmcraft_ui_egui::ControlRequest;
use serde_json::{Value, json};
/// Longest accepted request line (bytes, without the newline). Requests are small JSON objects;
/// anything longer is refused and the connection closed.
pub const MAX_LINE: usize = 4 * 1024 * 1024;
/// Connections served at once; further ones get an error line and are closed.
pub const MAX_CONNECTIONS: usize = 16;
pub fn start(port: u16, ctx: egui::Context) -> Receiver<ControlRequest> {
let (tx, rx) = channel::<ControlRequest>();
let listener = match TcpListener::bind(("127.0.0.1", port)) {
@@ -18,44 +32,257 @@ pub fn start(port: u16, ctx: egui::Context) -> Receiver<ControlRequest> {
}
};
eprintln!("filmcraft: control server listening on 127.0.0.1:{port}");
std::thread::spawn(move || {
for stream in listener.incoming().flatten() {
let tx = tx.clone();
let ctx = ctx.clone();
std::thread::spawn(move || serve(stream, tx, ctx));
}
});
std::thread::spawn(move || accept_loop(listener, tx, ctx));
rx
}
fn serve(stream: TcpStream, tx: Sender<ControlRequest>, ctx: egui::Context) {
let Ok(read) = stream.try_clone() else { return };
let mut out = stream;
for line in BufReader::new(read).lines() {
let Ok(line) = line else { break };
if line.trim().is_empty() {
fn accept_loop(listener: TcpListener, tx: Sender<ControlRequest>, ctx: egui::Context) {
let open = Arc::new(AtomicUsize::new(0));
for mut stream in listener.incoming().flatten() {
if open.fetch_add(1, Ordering::SeqCst) >= MAX_CONNECTIONS {
open.fetch_sub(1, Ordering::SeqCst);
let _ = writeln!(stream, "{}", json!({"ok": false, "error": "too many control connections"}));
continue;
}
let reply = match serde_json::from_str::<Value>(&line) {
Ok(msg) => {
let id = msg.get("id").cloned().unwrap_or(Value::Null);
let method = msg.get("method").and_then(Value::as_str).unwrap_or("").to_string();
let params = msg.get("params").cloned().unwrap_or(json!({}));
let (req, rrx) = ControlRequest::new(method, params);
if tx.send(req).is_err() {
break;
}
ctx.request_repaint();
let mut r = rrx.recv_timeout(Duration::from_secs(60)).unwrap_or_else(|_| json!({"ok": false, "error": "timeout"}));
if let Some(o) = r.as_object_mut() {
o.insert("id".into(), id);
}
r
}
Err(e) => json!({"ok": false, "error": format!("bad JSON: {e}")}),
};
if writeln!(out, "{reply}").is_err() {
break;
let tx = tx.clone();
let ctx = ctx.clone();
// The slot is given back when the guard drops: after `serve` returns, if it panics, or if
// the thread can't be started (the closure, and with it the guard, is dropped).
let slot = Slot(Arc::clone(&open));
let spawned = std::thread::Builder::new().name("control-conn".into()).spawn(move || {
let _slot = slot;
serve(stream, &tx, &ctx);
});
if let Err(e) = spawned {
eprintln!("filmcraft: control server could not start a connection thread: {e}");
}
}
}
/// One counted connection; decrements the open-connection count when dropped.
struct Slot(Arc<AtomicUsize>);
impl Drop for Slot {
fn drop(&mut self) {
self.0.fetch_sub(1, Ordering::SeqCst);
}
}
fn serve(stream: TcpStream, tx: &Sender<ControlRequest>, ctx: &egui::Context) {
let Ok(read) = stream.try_clone() else { return };
serve_lines(read, stream, |method, params| {
let (req, rrx) = ControlRequest::new(method, params);
tx.send(req).ok()?;
ctx.request_repaint();
Some(rrx.recv_timeout(Duration::from_secs(60)).unwrap_or_else(|_| json!({"ok": false, "error": "timeout"})))
});
}
/// One parsed line.
enum Line {
Request {
id: Value,
method: String,
params: Value,
},
Blank,
/// Not a request: reply with this error and close the connection.
Reject(String),
}
fn parse_line(bytes: &[u8]) -> Line {
let Ok(text) = std::str::from_utf8(bytes) else {
return Line::Reject("not a control request (invalid UTF-8); closing the connection".into());
};
let text = text.trim();
if text.is_empty() {
return Line::Blank;
}
let msg = match serde_json::from_str::<Value>(text) {
Ok(v) => v,
Err(e) => return Line::Reject(format!("bad JSON ({e}); expected one JSON request object per line; closing the connection")),
};
let Some(obj) = msg.as_object() else {
return Line::Reject("not a control request (expected a JSON object); closing the connection".into());
};
let Some(method) = obj.get("method").and_then(Value::as_str) else {
return Line::Reject("not a control request (missing string `method`); closing the connection".into());
};
Line::Request { id: obj.get("id").cloned().unwrap_or(Value::Null), method: method.to_string(), params: obj.get("params").cloned().unwrap_or(json!({})) }
}
/// Read one `\n`-terminated line of at most `max` bytes into `buf` (newline stripped).
/// `Ok(false)` at end of stream; `Err` when the line is too long or the read fails.
fn read_bounded_line(reader: &mut impl BufRead, buf: &mut Vec<u8>, max: usize) -> Result<bool, String> {
buf.clear();
// `take` bounds the bytes buffered for one line: a peer can't make us allocate more than `max`.
let limit = u64::try_from(max).unwrap_or(u64::MAX).saturating_add(1);
let n = reader.take(limit).read_until(b'\n', buf).map_err(|e| e.to_string())?;
if n == 0 {
return Ok(false);
}
if buf.last() == Some(&b'\n') {
buf.pop();
if buf.last() == Some(&b'\r') {
buf.pop();
}
return Ok(true);
}
if buf.len() > max {
return Err(format!("request line longer than {max} bytes; closing the connection"));
}
// Last line without a newline, then end of stream.
Ok(true)
}
/// Serve requests from `read`, answering on `out`, until the peer closes, sends something that is
/// not a request, or `handle` returns `None` (app gone). `handle` gets `(method, params)` and
/// returns the reply object (the request's `id` is added here).
fn serve_lines<R: Read, W: Write>(read: R, mut out: W, mut handle: impl FnMut(String, Value) -> Option<Value>) {
let mut reader = BufReader::new(read);
let mut buf = Vec::new();
loop {
let reject = match read_bounded_line(&mut reader, &mut buf, MAX_LINE) {
Ok(false) => return,
Err(e) => e,
Ok(true) => match parse_line(&buf) {
Line::Blank => continue,
Line::Reject(e) => e,
Line::Request { id, method, params } => {
let Some(mut r) = handle(method, params) else { return };
if let Some(o) = r.as_object_mut() {
o.insert("id".into(), id);
}
if writeln!(out, "{r}").and_then(|()| out.flush()).is_err() {
return;
}
continue;
}
},
};
let _ = writeln!(out, "{}", json!({"ok": false, "error": reject})).and_then(|()| out.flush());
return;
}
}
#[cfg(test)]
mod tests {
use super::*;
fn run(input: &[u8]) -> (Vec<Value>, Vec<String>) {
let mut out = Vec::new();
let mut calls = Vec::new();
serve_lines(input, &mut out, |m, _p| {
calls.push(m);
Some(json!({"ok": true, "result": null}))
});
let replies = String::from_utf8(out).unwrap().lines().map(|l| serde_json::from_str::<Value>(l).unwrap()).collect();
(replies, calls)
}
#[test]
fn requests_are_answered_in_order_with_ids() {
let (r, calls) = run(b"{\"id\":1,\"method\":\"a\"}\n\n{\"id\":2,\"method\":\"b\",\"params\":{}}\r\n{\"method\":\"c\"}");
assert_eq!(calls, ["a", "b", "c"]);
assert_eq!(r.len(), 3);
assert_eq!(r[0]["id"], 1);
assert_eq!(r[1]["id"], 2);
assert_eq!(r[2]["id"], Value::Null);
}
#[test]
fn http_request_closes_before_the_body_runs() {
// A browser's cross-origin `fetch` POST (issue #119): the request line is rejected and the
// connection closed, so the JSON body is never executed.
let http = b"POST / HTTP/1.1\r\nHost: 127.0.0.1:9876\r\nOrigin: https://attacker.example\r\nContent-Type: text/plain\r\n\r\n\
{\"id\":7,\"method\":\"engine.execute\",\"params\":{\"command\":\"file.openDemoProject\",\"params\":{}}}\n";
let (r, calls) = run(http);
assert!(calls.is_empty(), "nothing may run: {calls:?}");
assert_eq!(r.len(), 1);
assert_eq!(r[0]["ok"], false);
assert!(r[0]["error"].as_str().unwrap().contains("closing the connection"));
}
#[test]
fn non_request_json_closes_the_connection() {
for junk in [
&b"[1,2]\n{\"method\":\"a\"}\n"[..],
b"{\"id\":1}\n{\"method\":\"a\"}\n",
b"{\"method\":5}\n{\"method\":\"a\"}\n",
b"\xff\xfe\n{\"method\":\"a\"}\n",
] {
let (r, calls) = run(junk);
assert!(calls.is_empty(), "{calls:?}");
assert_eq!(r.len(), 1);
assert_eq!(r[0]["ok"], false);
}
}
#[test]
fn a_request_before_junk_still_runs() {
let (r, calls) = run(b"{\"method\":\"a\"}\nGET / HTTP/1.1\n{\"method\":\"b\"}\n");
assert_eq!(calls, ["a"]);
assert_eq!(r.len(), 2);
assert_eq!(r[1]["ok"], false);
}
#[test]
fn overlong_line_is_refused() {
// One byte over the limit, then a valid request: neither runs.
let mut input = vec![b'x'; MAX_LINE + 1];
input.extend_from_slice(b"\n{\"method\":\"a\"}\n");
let (r, calls) = run(&input);
assert!(calls.is_empty(), "{calls:?}");
assert_eq!(r.len(), 1);
assert!(r[0]["error"].as_str().unwrap().contains("longer than"));
}
#[test]
fn line_at_the_limit_is_accepted() {
let mut buf = Vec::new();
let line = vec![b'a'; 10];
let mut input = line.clone();
input.push(b'\n');
assert_eq!(read_bounded_line(&mut &input[..], &mut buf, 10), Ok(true));
assert_eq!(buf, line);
assert!(read_bounded_line(&mut &[b'a'; 11][..], &mut buf, 10).is_err());
}
#[test]
fn tcp_connection_is_closed_after_junk() {
// End to end over a real loopback socket (the transport the app uses).
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
let addr = listener.local_addr().unwrap();
let server = std::thread::spawn(move || {
let (s, _) = listener.accept().unwrap();
let read = s.try_clone().unwrap();
serve_lines(read, s, |_, _| Some(json!({"ok": true})));
});
let mut c = TcpStream::connect(addr).unwrap();
c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
c.write_all(b"{\"id\":7,\"method\":\"x\"}\nhello\n{\"method\":\"y\"}\n").unwrap();
let mut text = String::new();
c.read_to_string(&mut text).unwrap(); // returns at EOF: the server closed the connection
server.join().unwrap();
let lines: Vec<&str> = text.lines().collect();
assert_eq!(lines.len(), 2, "{text}");
assert!(lines[0].contains("\"id\":7"));
assert!(lines[1].contains("closing the connection"));
}
#[test]
fn extra_connections_are_refused() {
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
let addr = listener.local_addr().unwrap();
let (tx, _rx) = channel::<ControlRequest>();
std::thread::spawn(move || accept_loop(listener, tx, egui::Context::default()));
// Idle connections are accepted in order and held open.
let held: Vec<TcpStream> = (0..16).map(|_| TcpStream::connect(addr).unwrap()).collect();
let mut extra = TcpStream::connect(addr).unwrap();
extra.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
let mut line = String::new();
BufReader::new(&mut extra).read_line(&mut line).unwrap();
assert!(line.contains("too many control connections"), "{line}");
drop(held);
}
}
+63 -28
View File
@@ -1,23 +1,26 @@
//! FilmCraft desktop app.
//!
//! Usage: `filmcraft [--control <port>] [--demo|--empty] [--recover|--no-recover] [--data-dir <dir>]
//! [project.fcproj | media files…]`
//! [project.fcproj | media files…]`; `--help` prints the options, `--version` the version. An
//! unknown option is an error (exit code 2), not a file to open.
//!
//! Without a project, `--demo` or `--empty`, Settings ▸ General ▸ At Startup decides: Show Home
//! (the demo project), Open Most Recent, or an empty project.
//!
//! `--control <port>` (or `FILMCRAFT_CONTROL_PORT`) starts a localhost JSON-lines control server;
//! see `filmcraft_ui_egui::control` for the methods.
//! see `filmcraft_ui_egui::control` for the methods. A port that is not a number is an error from
//! either source.
//!
//! Auto-save and the crash-recovery journal run in every session (data in `--data-dir`, else
//! `FILMCRAFT_DATA_DIR`, else the per-user application data folder). If a previous session died
//! with unsaved changes the app asks to recover them; `--recover` recovers the newest without
//! asking, `--no-recover` starts without asking (the changes stay available via File ▸ Recover
//! Unsaved Changes…).
#![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")]
#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))]
mod app_nap;
mod args;
mod audio;
mod audio_in;
mod control_server;
@@ -25,6 +28,7 @@ mod control_server;
mod native_menu;
mod window_raise;
use args::{Cli, Launch};
use chrono::TimeZone;
use filmcraft_engine::Session;
use filmcraft_engine::autosave::{AutosaveConfig, default_data_dir};
@@ -45,37 +49,47 @@ fn app_icon() -> egui::IconData {
eframe::icon_data::from_png_bytes(png).unwrap_or_default()
}
fn main() -> eframe::Result {
app_nap::disable();
let mut control_port: Option<u16> = std::env::var("FILMCRAFT_CONTROL_PORT").ok().and_then(|p| p.parse().ok());
let mut files = Vec::new();
let mut demo = true;
// --demo / --empty given: skip Settings ▸ General ▸ At Startup
let mut startup_flag = false;
let mut recover: Option<bool> = None;
let mut data_dir = None;
let mut args = std::env::args().skip(1);
while let Some(a) = args.next() {
match a.as_str() {
"--control" => control_port = args.next().and_then(|p| p.parse().ok()),
"--demo" => (demo, startup_flag) = (true, true),
"--empty" => (demo, startup_flag) = (false, true),
"--recover" => recover = Some(true),
"--no-recover" => recover = Some(false),
"--data-dir" => data_dir = args.next().map(std::path::PathBuf::from),
"--version" => {
println!("filmcraft {}", env!("CARGO_PKG_VERSION"));
return Ok(());
}
_ => files.push(a),
}
/// Print `text` (stdout, or stderr for an error). A Windows release build has no console
/// (`windows_subsystem = "windows"`), so there it is also shown in a message box: otherwise `--help`
/// would print nothing and a bad option would quit without a word.
fn tell(text: &str, error: bool) {
if error {
eprint!("{text}");
} else {
print!("{text}");
}
#[cfg(all(target_os = "windows", not(debug_assertions)))]
{
let level = if error { rfd::MessageLevel::Error } else { rfd::MessageLevel::Info };
let _ = rfd::MessageDialog::new().set_level(level).set_title("FilmCraft").set_description(text).show();
}
}
fn main() -> eframe::Result {
// lossy, so a value that is not Unicode is reported like any other bad port instead of ignored
let env_port = std::env::var_os("FILMCRAFT_CONTROL_PORT").map(|p| p.to_string_lossy().into_owned());
let Launch { control_port, files, demo, startup_flag, recover, data_dir } = match args::parse(env_port, std::env::args().skip(1)) {
Ok(Cli::Run(l)) => l,
Ok(Cli::Help) => {
tell(args::USAGE, false);
return Ok(());
}
Ok(Cli::Version) => {
tell(&format!("filmcraft {}\n", env!("CARGO_PKG_VERSION")), false);
return Ok(());
}
Err(e) => {
tell(&format!("filmcraft: {e}\n\n{}", args::USAGE), true);
std::process::exit(2);
}
};
app_nap::disable();
// Panics anywhere go to <data dir>/Logs/crash-<day>.log with a backtrace; the UI pass and
// frame workers catch them and keep running (see filmcraft_ui_egui::crash).
filmcraft_ui_egui::crash::install(data_dir.clone().or_else(default_data_dir).map(|d| d.join("Logs")));
// OS hardware video decoders (VideoToolbox on macOS) in front of our own; Settings ▸ Playback ▸
// Hardware decoding switches them off. Unsupported streams and failures use our decoders.
log::info!("hardware decoding: {:?}", filmcraft_platform::register());
register_hardware_decoders();
let options = eframe::NativeOptions {
viewport: egui::ViewportBuilder::default()
.with_title("FilmCraft")
@@ -225,6 +239,15 @@ fn open_path(path: &str, reveal: bool) -> Result<(), String> {
cmd.spawn().map(|_| ()).map_err(|e| format!("can't open {path}: {e}"))
}
/// Put the OS hardware video decoders in front of our own. Registered in a statement of its own:
/// a log macro does not evaluate its arguments while no logger takes its level, which left the
/// hardware decoders out of every run.
fn register_hardware_decoders() -> filmcraft_platform::Availability {
let hardware = filmcraft_platform::register();
log::info!("hardware decoding: {hardware:?}");
hardware
}
/// Local UTC offset at a unix time (auto-save file names and recovery times use local time).
fn local_offset(unix: i64) -> i32 {
chrono::Local.timestamp_opt(unix, 0).single().map(|d| d.offset().local_minus_utc()).unwrap_or(0)
@@ -243,3 +266,15 @@ fn agent_event_loop(agent: bool) -> Option<eframe::EventLoopBuilderHook> {
let _ = agent;
None
}
#[cfg(test)]
mod tests {
/// Start-up registers the hardware decoders whether or not anything is logged (no logger is
/// installed here, as in a normal run).
#[test]
fn startup_registers_the_hardware_decoders_without_a_logger() {
assert!(!log::log_enabled!(log::Level::Info));
let hardware = super::register_hardware_decoders();
assert_eq!(filmcraft_platform::registered(), cfg!(any(target_os = "macos", target_os = "windows")), "{hardware:?}");
}
}
+21 -3
View File
@@ -25,10 +25,12 @@ pub type ShortcutUpdater = Box<dyn FnMut(&[Item])>;
pub fn install(app: &FilmcraftApp, ctx: egui::Context) -> (Receiver<String>, ShortcutUpdater) {
let items = menu_items(app);
let mut native: Vec<(String, MenuItem)> = Vec::new();
let mut titles: Vec<(String, Submenu)> = Vec::new();
let bar = Menu::new();
let app_menu = Submenu::new("FilmCraft", true);
// FilmCraft ▸ Settings ▸ <category> (Premiere's app-menu layout; General is Cmd+,)
let settings = Submenu::new("Settings", true);
let settings = Submenu::new(app.ui.language.tr("Settings"), true);
titles.push(("Settings".into(), settings.clone()));
for it in items.iter().filter(|i| i.id.starts_with("app.settings.")) {
let label = it.label.trim_end_matches('…').to_string();
let mi = MenuItem::with_id(it.id.clone(), label, true, it.shortcut.as_deref().and_then(accel));
@@ -48,7 +50,8 @@ pub fn install(app: &FilmcraftApp, ctx: egui::Context) -> (Receiver<String>, Sho
]);
let _ = bar.append(&app_menu);
for top in MENUS {
let sub = Submenu::new(top, true);
let sub = Submenu::new(app.ui.language.tr(top), true);
titles.push((top.into(), sub.clone()));
let mine: Vec<&Item> = items.iter().filter(|i| i.path.first().map(String::as_str) == Some(top) && !i.id.starts_with("app.settings.")).collect();
// submenus by path prefix (e.g. Clip ▸ Video Options ▸ Time Interpolation), created where
// their first item appears
@@ -62,7 +65,8 @@ pub fn install(app: &FilmcraftApp, ctx: egui::Context) -> (Receiver<String>, Sho
parent = match subs.iter().find(|(k, _)| *k == key) {
Some((_, s)) => s.clone(),
None => {
let s = Submenu::new(&it.path[depth], true);
let s = Submenu::new(app.ui.language.tr(&it.path[depth]), true);
titles.push((it.path[depth].clone(), s.clone()));
let _ = parent.append(&s);
subs.push((key, s.clone()));
s
@@ -88,8 +92,22 @@ pub fn install(app: &FilmcraftApp, ctx: egui::Context) -> (Receiver<String>, Sho
}
});
let update: ShortcutUpdater = Box::new(move |items: &[Item]| {
let checked = |id: &str| items.iter().any(|it| it.id == id && it.checked == Some(true));
let language = if checked("app.language.japanese") {
filmcraft_ui_egui::i18n::Language::Ja
} else if checked("app.language.spanish") {
filmcraft_ui_egui::i18n::Language::Es
} else if checked("app.language.portuguese") {
filmcraft_ui_egui::i18n::Language::PtBr
} else {
filmcraft_ui_egui::i18n::Language::En
};
for (title, submenu) in &titles {
submenu.set_text(language.tr(title));
}
for (id, mi) in &native {
if let Some(it) = items.iter().find(|i| &i.id == id) {
mi.set_text(&it.label);
let _ = mi.set_accelerator(it.shortcut.as_deref().and_then(accel));
}
}
+42 -2
View File
@@ -19,6 +19,10 @@ const ID_PCE: u32 = 5;
const ID_FIL: u32 = 6;
const ID_END: u32 = 7;
/// `extension_type` of a fill element carrying SBR data (ISO/IEC 14496-3 §4.5.2.8.2, Table 4.121).
const EXT_SBR_DATA: u32 = 13;
const EXT_SBR_DATA_CRC: u32 = 14;
/// One decoded `individual_channel_stream` before stereo processing and synthesis.
struct Ics {
info: IcsInfo,
@@ -45,6 +49,8 @@ pub struct Decoder {
offsets: Vec<usize>,
channels: Vec<ChannelState>,
noise_state: u32,
/// A fill element carried SBR data (implicitly signalled HE-AAC).
sbr_seen: bool,
}
impl Decoder {
@@ -67,7 +73,7 @@ impl Decoder {
if layout.is_empty() && asc.channel_config != 0 {
return Err(Error::InvalidConfig("unsupported channel configuration"));
}
let mut d = Decoder { asc, layout: Vec::new(), offsets: Vec::new(), channels: Vec::new(), noise_state: 0x2545_F491 };
let mut d = Decoder { asc, layout: Vec::new(), offsets: Vec::new(), channels: Vec::new(), noise_state: 0x2545_F491, sbr_seen: false };
d.set_layout(layout);
Ok(d)
}
@@ -90,6 +96,12 @@ impl Decoder {
pub fn sample_rate(&self) -> u32 {
self.asc.sample_rate
}
/// Whether the stream is HE-AAC: SBR signalled in the `AudioSpecificConfig` (explicit) or SBR
/// data seen in a fill element of a decoded access unit (implicit). Only the AAC-LC core is
/// decoded, at [`Self::sample_rate`]; the SBR high band is not reconstructed.
pub fn sbr(&self) -> bool {
self.asc.sbr || self.sbr_seen
}
pub fn channels(&self) -> usize {
self.channels.len()
}
@@ -174,7 +186,11 @@ impl Decoder {
count += br.read_bits(8)? as usize;
count -= 1;
}
br.skip(count * 8)?;
if count > 0 {
let ext = br.read_bits(4)?;
self.sbr_seen |= matches!(ext, EXT_SBR_DATA | EXT_SBR_DATA_CRC);
br.skip(count * 8 - 4)?;
}
}
_ => break, // ID_END
}
@@ -542,3 +558,27 @@ fn synth(state: &mut ChannelState, info: &IcsInfo, spec: &[f32]) -> Vec<f32> {
state.prev_shape = cur;
out
}
#[cfg(test)]
mod tests {
use super::*;
/// Implicitly signalled HE-AAC (an AAC-LC config) is recognised from the SBR fill element.
#[test]
fn sbr_fill_element_marks_implicit_he_aac() {
// AAC-LC, 22.05 kHz, stereo
let mut dec = Decoder::new(&[0x13, 0x90]).unwrap();
assert!(!dec.sbr());
// ID_FIL, count 1, extension_type EXT_SBR_DATA (+ 4 bits of payload), ID_END
let _ = dec.decode(&[0b1100_0011, 0b1010_0001, 0b1100_0000]);
assert!(dec.sbr());
// other fill payloads (EXT_FILL) don't
let mut dec = Decoder::new(&[0x13, 0x90]).unwrap();
let _ = dec.decode(&[0b1100_0010, 0b0000_0001, 0b1100_0000]);
assert!(!dec.sbr());
// explicit signalling: AOT 5, core 22.05 kHz, stereo, extension 44.1 kHz, core AOT 2
let dec = Decoder::new(&[0x2B, 0x92, 0x08, 0x00]).unwrap();
assert!(dec.sbr());
assert_eq!(dec.sample_rate(), 22_050);
}
}
+21
View File
@@ -0,0 +1,21 @@
[package]
name = "filmcraft-apv"
description = "Clean-room Advanced Professional Video (APV, IETF RFC 9924) decoder and encoder"
version.workspace = true
edition.workspace = true
license.workspace = true
[features]
default = ["threads"]
threads = ["dep:rayon"]
[dependencies]
filmcraft-bitstream.workspace = true
rayon = { workspace = true, optional = true }
thiserror.workspace = true
[dev-dependencies]
filmcraft-testkit.workspace = true
[lints]
workspace = true
+74
View File
@@ -0,0 +1,74 @@
# filmcraft-apv
Clean-room Advanced Professional Video (APV) decoder and encoder in pure Rust, implemented strictly
from the public **IETF RFC 9924** specification (*Advanced Professional Video*, February 2026,
ISSN 2070-1721).
Layer L0: depends only on `filmcraft-bitstream`, `thiserror`, and (optional, feature `threads`,
default on) `rayon`. Builds for `wasm32-unknown-unknown`; `unsafe_code = "forbid"`.
## API
```rust
use filmcraft_apv::*;
// Decode one APV Access Unit (or raw bitstream AU prefixed with a 32-bit au_size).
let frame: Frame = decode_frame(&au)?;
let f8 = decode_frame_with(&au, &DecodeOptions { bit_depth: Some(8), threads: true })?;
decode_frame_into(&au, &DecodeOptions::default(), &mut frame_buf)?;
let hdr: FrameHeader = probe(&au)?;
// Split a multi-AU raw .apv bitstream (RFC 9924 Appendix A).
let aus: Vec<&[u8]> = split_raw_bitstream(&raw_apv_bytes)?;
// Encode progressive intra frames.
let mut enc = Encoder::new(Profile::P422_10, 1920, 1080)?;
let au: Vec<u8> = enc.encode(&frame)?; // Access Unit starting with 'aPv1'
let raw_au: Vec<u8> = enc.encode_raw_au(&frame)?; // Prefixed with 32-bit au_size (ISOBMFF apv1 / .apv)
let apvc: Vec<u8> = enc.decoder_config_record(); // APVDecoderConfigurationRecord payload
```
## Specification Coverage (IETF RFC 9924)
### Decoder
- **Access Units & PBUs (§5.3.1–5.3.3, Appendix A)**: Accepts both unprefixed Access Units
(`'aPv1'` signature) and length-prefixed `raw_bitstream_access_unit()` packets. Parses primary
(`pbu_type == 1`), non-primary (`2`), preview (`25`), auxiliary alpha (`27`), AU info (`65`),
metadata (`66`), and filler (`67`) PBUs. PBUs or frame headers with non-zero `reserved_zero_*`
fields are ignored per §5.3.3 and §5.3.5.
- **Profiles & Sampling (§9.3)**: All 7 standard profiles (`422-10` idc 33, `422-12` idc 44,
`444-10` idc 55, `444-12` idc 66, `4444-10` idc 77, `4444-12` idc 88, `400-10` idc 99) at
coded bit depths 10–16, with optional output depth rescaling (`8..=16`).
- **Quantization Matrices & Tiles (§5.3.7–5.3.8, §5.3.12–5.3.14)**: Default flat (`16`) and
custom per-component 8×8 quantization matrices (`use_q_matrix`), optional `tile_size_in_fh`
verification, and independent per-tile, per-component byte-aligned entropy partitions. Tiles
decode in parallel via `rayon` when `threads` is enabled.
- **Entropy Decoding (§5.3.15–5.3.16, §7.1)**: Adaptive Golomb-Rice / Exp-Golomb VLC decoding for
`abs_dc_coeff_diff`, `coeff_zero_run`, and `abs_ac_coeff_minus1` with state tracking (`PrevDC`,
`PrevDcDiff`, `Prev1stAcLevel`, `PrevLevel`, `PrevRun`) across the 8×8 blocks of each macroblock.
- **Scaling & Inverse Transform (§6.3)**: Exact integer dequantization (`levelScale = [40, 45, 51,
57, 64, 71]`, `bdShift = BitDepth - 2`) and 2-D separable 8×8 integer inverse transform using the
RFC 9924 Figure 25 `transMatrix`. Note: in RFC 9924 §6.3.2.2, `transMatrix[m][n]` has row `m` as
the frequency index (row 0 is `[64; 8]`) and column `n` as the spatial sample index, so the 1-D
inverse transform evaluates `sum_j transMatrix[j][i] * x[j]`.
- **Metadata (§8)**: Parses `metadata_mdcv` (`payloadType == 5`, Mastering Display Color Volume)
and `metadata_cll` (`payloadType == 6`, Content Light-Level Information).
- **Robustness (§10)**: All size fields, tile coordinates, VLC codeword lengths, and coefficient
ranges (`-32768..=32767`) are checked before allocation or shift. Verified by `tests/fuzz.rs`
across thousands of mutated and random inputs.
### Encoder
- Progressive intra encoding for all 7 profiles (`422-10`, `422-12`, `444-10`, `444-12`,
`4444-10`, `4444-12`, `400-10`).
- Supports fixed `qp` or binary-search frame-budget rate control over forward-transformed tiles.
- Emits conforming tile grids (`tile_width_in_mbs >= 16`, `tile_height_in_mbs >= 8`,
`TileCols, TileRows <= 20`), optional custom quantization matrices, optional `MDCV`/`CLL`
metadata PBUs, and `APVDecoderConfigurationRecord` (`apvC`) metadata.
## Accuracy (vs FFmpeg as an External Oracle)
`tests/oracle.rs` encodes synthetic test patterns across all 7 profiles, odd dimensions, multiple
tiles, custom asymmetric quantization matrices, and HDR metadata PBUs, then decodes the resulting
`.apv` streams with `ffmpeg -v error -xerror -f apv` and compares against `filmcraft_apv::decode_frame`.
Because APV specifies an exact integer inverse transform, **`filmcraft-apv` is 100% bit-exact
(`max_diff = 0`) with FFmpeg's APV decoder across every profile and test case.**
+217
View File
@@ -0,0 +1,217 @@
//! RFC 9924 §6.3 scaling and 8x8 integer inverse transform, plus the matching forward transform.
use crate::tables::LEVEL_SCALE;
/// 1D 8-point inverse transform using the RFC 9924 §6.3.2.3 even/odd butterfly decomposition,
/// shifting each output by `(sum + round) >> shift`.
#[inline(always)]
fn idct_1d(x0: i32, x1: i32, x2: i32, x3: i32, x4: i32, x5: i32, x6: i32, x7: i32, round: i32, shift: u32) -> [i32; 8] {
if (x1 | x2 | x3 | x4 | x5 | x6 | x7) == 0 {
let v = (x0 * 64 + round) >> shift;
return [v; 8];
}
let e0 = 64 * (x0 + x4);
let e1 = 64 * (x0 - x4);
let e2 = 35 * x2 - 84 * x6;
let e3 = 84 * x2 + 35 * x6;
let even0 = e0 + e3;
let even1 = e1 + e2;
let even2 = e1 - e2;
let even3 = e0 - e3;
let odd0 = 89 * x1 + 75 * x3 + 50 * x5 + 18 * x7;
let odd1 = 75 * x1 - 18 * x3 - 89 * x5 - 50 * x7;
let odd2 = 50 * x1 - 89 * x3 + 18 * x5 + 75 * x7;
let odd3 = 18 * x1 - 50 * x3 + 75 * x5 - 89 * x7;
[
(even0 + odd0 + round) >> shift,
(even1 + odd1 + round) >> shift,
(even2 + odd2 + round) >> shift,
(even3 + odd3 + round) >> shift,
(even3 - odd3 + round) >> shift,
(even2 - odd2 + round) >> shift,
(even1 - odd1 + round) >> shift,
(even0 - odd0 + round) >> shift,
]
}
/// Fast path when an 8x8 block has only a DC coefficient (`coeff[1..64]` are all zero).
#[inline]
pub fn scale_and_idct8x8_dc_only(dc_coeff: i16, q0: u8, qp: u8, bit_depth: u8, out: &mut [u16; 64]) {
let bd_shift_scale = (bit_depth as u32).saturating_sub(2);
let scale_round = if bd_shift_scale > 0 { 1i64 << (bd_shift_scale - 1) } else { 0 };
let level_scale = LEVEL_SCALE[(qp % 6) as usize] as i64;
let qp_shift = (qp / 6) as u32;
let scaled = ((dc_coeff as i64 * q0 as i64 * level_scale) << qp_shift) + scale_round;
let d0 = (scaled >> bd_shift_scale).clamp(-32768, 32767) as i32;
let g0 = (d0 * 64 + 64) >> 7;
let bd_shift = 20u32.saturating_sub(bit_depth as u32);
let round = 1i32 << (bd_shift - 1);
let mid = 1i32 << (bit_depth - 1);
let max_val = (1i32 << bit_depth) - 1;
let sample = (((g0 * 64 + round) >> bd_shift) + mid).clamp(0, max_val) as u16;
out.fill(sample);
}
/// Scale and inverse-transform one 8x8 block of transform coefficients (indexed by `y * 8 + x`)
/// into reconstructed samples at `bit_depth` (`10..=16`), per RFC 9924 §6.3.
#[inline]
pub fn scale_and_idct8x8(coeff: &[i16; 64], q_matrix: &[u8; 64], qp: u8, bit_depth: u8, out: &mut [u16; 64]) {
let bd_shift_scale = (bit_depth as u32).saturating_sub(2);
let scale_round = if bd_shift_scale > 0 { 1i64 << (bd_shift_scale - 1) } else { 0 };
let level_scale = LEVEL_SCALE[(qp % 6) as usize] as i64;
let qp_shift = (qp / 6) as u32;
let mut d = [0i32; 64];
for idx in 0..64 {
let c = coeff[idx] as i64;
if c != 0 {
let qm = q_matrix[idx] as i64;
let scaled = ((c * qm * level_scale) << qp_shift) + scale_round;
d[idx] = (scaled >> bd_shift_scale).clamp(-32768, 32767) as i32;
}
}
// 1D vertical transform on each column x = 0..8, followed by (e + 64) >> 7
let mut g = [0i32; 64];
for x in 0..8 {
let col = idct_1d(d[x], d[8 + x], d[16 + x], d[24 + x], d[32 + x], d[40 + x], d[48 + x], d[56 + x], 64, 7);
for i in 0..8 {
g[i * 8 + x] = col[i];
}
}
// 1D horizontal transform on each row y = 0..8, followed by final bit-depth shift and offset
let bd_shift = 20u32.saturating_sub(bit_depth as u32);
let round = 1i32 << (bd_shift - 1);
let mid = 1i32 << (bit_depth - 1);
let max_val = (1i32 << bit_depth) - 1;
for y in 0..8 {
let r = &g[y * 8..y * 8 + 8];
let row = idct_1d(r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], round, bd_shift);
for i in 0..8 {
out[y * 8 + i] = (row[i] + mid).clamp(0, max_val) as u16;
}
}
}
/// 1D 8-point forward butterfly transform matching `TRANS_MATRIX`.
#[inline(always)]
fn fdct_1d(x0: i32, x1: i32, x2: i32, x3: i32, x4: i32, x5: i32, x6: i32, x7: i32, round: i32, shift: u32) -> [i32; 8] {
let s0 = x0 + x7;
let d0 = x0 - x7;
let s1 = x1 + x6;
let d1 = x1 - x6;
let s2 = x2 + x5;
let d2 = x2 - x5;
let s3 = x3 + x4;
let d3 = x3 - x4;
let es0 = s0 + s3;
let ed0 = s0 - s3;
let es1 = s1 + s2;
let ed1 = s1 - s2;
[
(64 * (es0 + es1) + round) >> shift,
(89 * d0 + 75 * d1 + 50 * d2 + 18 * d3 + round) >> shift,
(84 * ed0 + 35 * ed1 + round) >> shift,
(75 * d0 - 18 * d1 - 89 * d2 - 50 * d3 + round) >> shift,
(64 * (es0 - es1) + round) >> shift,
(50 * d0 - 89 * d1 + 18 * d2 + 75 * d3 + round) >> shift,
(35 * ed0 - 84 * ed1 + round) >> shift,
(18 * d0 - 50 * d1 + 75 * d2 - 89 * d3 + round) >> shift,
]
}
/// Forward 8x8 transform of level-shifted samples (`sample - (1 << (bit_depth - 1))`) into the
/// scaled coefficient domain `d[y * 8 + x]` matching [`scale_and_idct8x8`].
#[inline]
pub fn fdct8x8(samples: &[u16; 64], bit_depth: u8) -> [i32; 64] {
let mid = 1i32 << (bit_depth - 1);
let shift1 = (bit_depth as u32).saturating_sub(5);
let add1 = if shift1 > 0 { 1i32 << (shift1 - 1) } else { 0 };
// Horizontal forward pass
let mut t = [0i32; 64];
for y in 0..8 {
let s = &samples[y * 8..y * 8 + 8];
let row = fdct_1d(
s[0] as i32 - mid,
s[1] as i32 - mid,
s[2] as i32 - mid,
s[3] as i32 - mid,
s[4] as i32 - mid,
s[5] as i32 - mid,
s[6] as i32 - mid,
s[7] as i32 - mid,
add1,
shift1,
);
t[y * 8..y * 8 + 8].copy_from_slice(&row);
}
// Vertical forward pass
let mut f = [0i32; 64];
for u in 0..8 {
let col = fdct_1d(t[u], t[8 + u], t[16 + u], t[24 + u], t[32 + u], t[40 + u], t[48 + u], t[56 + u], 128, 8);
for v in 0..8 {
f[v * 8 + u] = col[v];
}
}
f
}
/// Quantize forward-transformed coefficients `f` (in the `d` domain) at `qp` with `q_matrix`.
#[inline]
pub fn quantize8x8(f: &[i32; 64], q_matrix: &[u8; 64], qp: u8, bit_depth: u8) -> [i16; 64] {
let bd_shift_scale = (bit_depth as u32).saturating_sub(2);
let level_scale = LEVEL_SCALE[(qp % 6) as usize] as i64;
let qp_shift = (qp / 6) as u32;
let mut out = [0i16; 64];
for idx in 0..64 {
let val = f[idx] as i64;
if val == 0 {
continue;
}
let sign = if val < 0 { -1i64 } else { 1i64 };
let abs_val = val.unsigned_abs() as i64;
let qm = q_matrix[idx].max(1) as i64;
let den = (qm * level_scale) << qp_shift;
let num = abs_val << bd_shift_scale;
// Deadzone/rounding offset: 1/2 for DC, 3/8 for AC
let offset = if idx == 0 { den / 2 } else { (den * 3) / 8 };
let level = ((num + offset) / den).min(32767);
out[idx] = (level * sign) as i16;
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn fdct_idct_roundtrip_10bit() {
let mut src = [0u16; 64];
for (i, s) in src.iter_mut().enumerate() {
*s = (64 + (i * 13) % 850) as u16;
}
let qm = [16u8; 64];
// At qp = 0 (very fine quantization), roundtrip is within 1 LSB
let f = fdct8x8(&src, 10);
let q = quantize8x8(&f, &qm, 0, 10);
let mut rec = [0u16; 64];
scale_and_idct8x8(&q, &qm, 0, 10, &mut rec);
for i in 0..64 {
let err = (src[i] as i32 - rec[i] as i32).abs();
assert!(err <= 1, "idx {i}: src={} rec={} err={err}", src[i], rec[i]);
}
}
}
+484
View File
@@ -0,0 +1,484 @@
//! RFC 9924 APV frame and tile decoder.
use filmcraft_bitstream::BitReader;
use crate::dct::{scale_and_idct8x8, scale_and_idct8x8_dc_only};
use crate::header::{
FrameHeader, PBU_ALPHA_FRAME, PBU_METADATA, PBU_NON_PRIMARY_FRAME, PBU_PREVIEW_FRAME, PBU_PRIMARY_FRAME, parse_au_pbus, parse_frame_header,
parse_metadata_pbu, read_byte_alignment,
};
use crate::tables::ZIGZAG_8X8;
use crate::{ChromaFormat, ContentLightLevel, Error, Frame, MasteringDisplay, Result};
/// Options for [`decode_frame_with`] and [`decode_frame_into`].
#[derive(Debug, Clone)]
pub struct DecodeOptions {
/// Output sample bit depth (`8..=16`). `None` keeps the stream's coded bit depth (`10..=16`).
pub bit_depth: Option<u8>,
/// Decode tiles in parallel when the `threads` feature is enabled.
pub threads: bool,
}
impl Default for DecodeOptions {
fn default() -> Self {
Self { bit_depth: None, threads: true }
}
}
/// Parse RFC 9924 §7.1.4 variable-length codeword (`h(v)`).
#[inline]
pub(crate) fn read_vlc(r: &mut BitReader, k_param: u32) -> Result<u32> {
let mut symbol_value: u64 = 0;
let mut k = k_param;
let parse_exp_golomb = if r.read_bit().map_err(|_| Error::Truncated)? {
false
} else if !r.read_bit().map_err(|_| Error::Truncated)? {
symbol_value += 1u64 << k;
false
} else {
symbol_value += 2u64 << k;
true
};
if parse_exp_golomb {
loop {
if r.read_bit().map_err(|_| Error::Truncated)? {
break;
}
symbol_value += 1u64 << k;
k += 1;
if k > 28 {
return Err(Error::Invalid("VLC codeword exceeds maximum length"));
}
}
}
if k > 0 {
symbol_value += r.read_bits(k).map_err(|_| Error::Truncated)? as u64;
}
u32::try_from(symbol_value).map_err(|_| Error::Invalid("VLC symbol overflow"))
}
/// Probe the primary frame header of an Access Unit without decoding its tiles.
pub fn probe(data: &[u8]) -> Result<FrameHeader> {
let pbus = parse_au_pbus(data)?;
for pbu in &pbus {
if matches!(pbu.pbu_type, PBU_PRIMARY_FRAME | PBU_NON_PRIMARY_FRAME | PBU_PREVIEW_FRAME)
&& let Some(hdr) = parse_frame_header(pbu.payload)?
{
return Ok(hdr);
}
}
Err(Error::Invalid("no decodable frame PBU in access unit"))
}
/// Decode one APV Access Unit with default options.
pub fn decode_frame(data: &[u8]) -> Result<Frame> {
decode_frame_with(data, &DecodeOptions::default())
}
/// Decode one APV Access Unit with custom [`DecodeOptions`].
pub fn decode_frame_with(data: &[u8], opts: &DecodeOptions) -> Result<Frame> {
let mut out = Frame::new(2, 2, ChromaFormat::Yuv422, 10, false);
decode_frame_into(data, opts, &mut out)?;
Ok(out)
}
/// Decode one APV Access Unit into `out`, reusing its plane allocations when possible.
pub fn decode_frame_into(data: &[u8], opts: &DecodeOptions, out: &mut Frame) -> Result<FrameHeader> {
if let Some(d) = opts.bit_depth
&& !(8..=16).contains(&d)
{
return Err(Error::Invalid("requested output bit_depth must be in 8..=16"));
}
let pbus = parse_au_pbus(data)?;
let mut primary: Option<(u16, FrameHeader, &[u8])> = None;
let mut alpha_pbu: Option<(FrameHeader, &[u8])> = None;
let mut mdcv: Option<MasteringDisplay> = None;
let mut cll: Option<ContentLightLevel> = None;
for pbu in &pbus {
match pbu.pbu_type {
PBU_PRIMARY_FRAME => {
if primary.is_none()
&& let Some(hdr) = parse_frame_header(pbu.payload)?
{
primary = Some((pbu.group_id, hdr, pbu.payload));
}
}
PBU_NON_PRIMARY_FRAME | PBU_PREVIEW_FRAME => {
if primary.is_none()
&& let Some(hdr) = parse_frame_header(pbu.payload)?
{
primary = Some((pbu.group_id, hdr, pbu.payload));
}
}
PBU_ALPHA_FRAME => {
if alpha_pbu.is_none()
&& let Some(hdr) = parse_frame_header(pbu.payload)?
{
alpha_pbu = Some((hdr, pbu.payload));
}
}
PBU_METADATA => {
let _ = parse_metadata_pbu(pbu.payload, &mut mdcv, &mut cll);
}
_ => {}
}
}
let (_group_id, hdr, payload) = primary.ok_or(Error::Invalid("no primary frame PBU in access unit"))?;
let out_depth = opts.bit_depth.unwrap_or(hdr.bit_depth);
decode_pbu_planes(&hdr, payload, out_depth, opts.threads, out)?;
out.mastering_display = mdcv;
out.content_light = cll;
// If the primary frame has no 4th component and an auxiliary alpha frame PBU (type 27) is present
// with matching dimensions, decode its luma plane as the alpha plane.
if out.alpha.is_none()
&& let Some((ahdr, apayload)) = alpha_pbu
&& ahdr.width == hdr.width
&& ahdr.height == hdr.height
{
let mut aframe = Frame::new(ahdr.width, ahdr.height, ahdr.chroma, out_depth, false);
if decode_pbu_planes(&ahdr, apayload, out_depth, opts.threads, &mut aframe).is_ok() {
out.alpha = Some(aframe.y);
}
}
Ok(hdr)
}
#[derive(Clone)]
struct DecodedTile {
x0: u32,
y0: u32,
w_luma: u32,
h_luma: u32,
/// Decoded pixels for each component `c` in `0..num_comps`, packed with stride `w_luma / sub_w`.
comps: [Vec<u16>; 4],
}
fn decode_pbu_planes(hdr: &FrameHeader, payload: &[u8], out_depth: u8, threads: bool, out: &mut Frame) -> Result<()> {
let num_tiles = hdr.num_tiles();
let mut pos = hdr.header_bytes;
let mut tile_slices: Vec<(usize, &[u8])> = Vec::with_capacity(num_tiles);
for tile_idx in 0..num_tiles {
let sz_bytes = payload.get(pos..pos + 4).ok_or(Error::Truncated)?;
let tile_size = u32::from_be_bytes([sz_bytes[0], sz_bytes[1], sz_bytes[2], sz_bytes[3]]) as usize;
if tile_size == 0 {
return Err(Error::Invalid("tile_size cannot be 0"));
}
if let Some(fh_sizes) = &hdr.tile_sizes_in_fh
&& fh_sizes.get(tile_idx).copied() != Some(tile_size as u32)
{
return Err(Error::Invalid("tile_size does not match tile_size_in_fh"));
}
pos += 4;
let tile_end = pos.checked_add(tile_size).ok_or(Error::Truncated)?;
let tile_bytes = payload.get(pos..tile_end).ok_or(Error::Truncated)?;
pos = tile_end;
tile_slices.push((tile_idx, tile_bytes));
}
// Verify any trailing filler bytes in the frame PBU are 0xFF (RFC 9924 §5.3.4 & §5.3.11)
if payload.get(pos..).is_some_and(|rest| rest.iter().any(|&b| b != 0xFF)) {
return Err(Error::Invalid("non-0xFF filler byte at end of frame PBU"));
}
#[cfg(feature = "threads")]
let decoded_tiles: Result<Vec<DecodedTile>> = if threads && tile_slices.len() > 1 {
use rayon::prelude::*;
tile_slices.into_par_iter().map(|(idx, bytes)| decode_single_tile(hdr, idx, bytes, out_depth, false)).collect()
} else {
tile_slices.into_iter().map(|(idx, bytes)| decode_single_tile(hdr, idx, bytes, out_depth, threads)).collect()
};
#[cfg(not(feature = "threads"))]
let decoded_tiles: Result<Vec<DecodedTile>> = {
let _ = threads;
tile_slices.into_iter().map(|(idx, bytes)| decode_single_tile(hdr, idx, bytes, out_depth, false)).collect()
};
let mut decoded_tiles = decoded_tiles?;
// Prepare output frame metadata
let w = hdr.width as usize;
let h = hdr.height as usize;
let cw = hdr.chroma.chroma_width(hdr.width) as usize;
let ch = hdr.chroma.chroma_height(hdr.height) as usize;
let n_luma = w.checked_mul(h).ok_or(Error::Invalid("frame luma size overflow"))?;
let n_chroma = cw.checked_mul(ch).ok_or(Error::Invalid("frame chroma size overflow"))?;
out.width = hdr.width;
out.height = hdr.height;
out.chroma = hdr.chroma;
out.bit_depth = out_depth;
out.color = hdr.color;
out.profile_idc = hdr.profile_idc;
out.level_idc = hdr.level_idc;
out.band_idc = hdr.band_idc;
// Zero-copy fast path when a single tile covers the exact frame dimensions without macroblock padding.
if decoded_tiles.len() == 1 && decoded_tiles[0].w_luma == hdr.width && decoded_tiles[0].h_luma == hdr.height {
let [y, cb, cr, a] = std::mem::take(&mut decoded_tiles[0].comps);
out.y = y;
if hdr.chroma.num_comps() >= 3 {
out.cb = cb;
out.cr = cr;
} else {
out.cb.clear();
out.cr.clear();
}
out.alpha = if hdr.chroma == ChromaFormat::Yuv4444 { Some(a) } else { None };
return Ok(());
}
out.y.resize(n_luma, 0);
out.cb.resize(n_chroma, 0);
out.cr.resize(n_chroma, 0);
if hdr.chroma == ChromaFormat::Yuv4444 {
let a = out.alpha.get_or_insert_with(Vec::new);
a.resize(n_luma, 0);
} else {
out.alpha = None;
}
// Copy each tile's reconstructed samples into the cropped output planes (RFC 9924 §6)
let sub_w = hdr.chroma.sub_width_c() as usize;
let sub_h = hdr.chroma.sub_height_c() as usize;
for tile in &decoded_tiles {
copy_tile_comp(&tile.comps[0], tile.w_luma as usize, tile.h_luma as usize, tile.x0 as usize, tile.y0 as usize, &mut out.y, w, h);
if hdr.chroma.num_comps() >= 3 {
let tw_c = (tile.w_luma as usize) / sub_w;
let th_c = (tile.h_luma as usize) / sub_h;
let tx_c = (tile.x0 as usize) / sub_w;
let ty_c = (tile.y0 as usize) / sub_h;
copy_tile_comp(&tile.comps[1], tw_c, th_c, tx_c, ty_c, &mut out.cb, cw, ch);
copy_tile_comp(&tile.comps[2], tw_c, th_c, tx_c, ty_c, &mut out.cr, cw, ch);
}
if hdr.chroma == ChromaFormat::Yuv4444
&& let Some(alpha) = out.alpha.as_mut()
{
copy_tile_comp(&tile.comps[3], tile.w_luma as usize, tile.h_luma as usize, tile.x0 as usize, tile.y0 as usize, alpha, w, h);
}
}
Ok(())
}
fn copy_tile_comp(src: &[u16], tw: usize, th: usize, tx: usize, ty: usize, dst: &mut [u16], fw: usize, fh: usize) {
if tx >= fw || ty >= fh {
return;
}
let copy_w = tw.min(fw - tx);
let copy_h = th.min(fh - ty);
for r in 0..copy_h {
let s_off = r * tw;
let d_off = (ty + r) * fw + tx;
dst[d_off..d_off + copy_w].copy_from_slice(&src[s_off..s_off + copy_w]);
}
}
fn decode_single_tile(hdr: &FrameHeader, tile_idx: usize, tile_bytes: &[u8], out_depth: u8, par_comps: bool) -> Result<DecodedTile> {
let num_comps = hdr.chroma.num_comps();
let min_hdr_size = 5 + 5 * num_comps;
if tile_bytes.len() < min_hdr_size {
return Err(Error::Truncated);
}
// tile_header(tileIdx) (RFC 9924 §5.3.13)
let tile_header_size = u16::from_be_bytes([tile_bytes[0], tile_bytes[1]]) as usize;
let tile_index = u16::from_be_bytes([tile_bytes[2], tile_bytes[3]]) as usize;
if tile_index != tile_idx {
return Err(Error::CorruptTile(tile_idx));
}
if tile_header_size < min_hdr_size || tile_header_size > tile_bytes.len() {
return Err(Error::CorruptTile(tile_idx));
}
let mut tile_data_size = [0usize; 4];
for c in 0..num_comps {
let off = 4 + c * 4;
let sz = u32::from_be_bytes([tile_bytes[off], tile_bytes[off + 1], tile_bytes[off + 2], tile_bytes[off + 3]]) as usize;
if sz == 0 {
return Err(Error::CorruptTile(tile_idx));
}
tile_data_size[c] = sz;
}
let max_tile_qp = (51 + hdr.qp_bd_offset()) as u8;
let mut tile_qp = [0u8; 4];
for c in 0..num_comps {
let qp = tile_bytes[4 + num_comps * 4 + c];
if qp > max_tile_qp {
return Err(Error::CorruptTile(tile_idx));
}
tile_qp[c] = qp;
}
let reserved_zero_8bits = tile_bytes[4 + num_comps * 5];
if reserved_zero_8bits != 0 {
return Err(Error::CorruptTile(tile_idx));
}
let tx = tile_idx % (hdr.tile_cols as usize);
let ty = tile_idx / (hdr.tile_cols as usize);
let x0 = hdr.col_starts[tx];
let x1 = hdr.col_starts[tx + 1];
let y0 = hdr.row_starts[ty];
let y1 = hdr.row_starts[ty + 1];
let w_luma = x1.saturating_sub(x0);
let h_luma = y1.saturating_sub(y0);
let mut comp_off = tile_header_size;
let mut comp_slices: Vec<(usize, &[u8])> = Vec::with_capacity(num_comps);
for c in 0..num_comps {
let comp_end = comp_off.checked_add(tile_data_size[c]).ok_or(Error::CorruptTile(tile_idx))?;
let comp_bytes = tile_bytes.get(comp_off..comp_end).ok_or(Error::CorruptTile(tile_idx))?;
comp_off = comp_end;
comp_slices.push((c, comp_bytes));
}
#[cfg(feature = "threads")]
let decoded_comps: Result<Vec<Vec<u16>>> = if par_comps && comp_slices.len() > 1 {
use rayon::prelude::*;
comp_slices.into_par_iter().map(|(c, comp_bytes)| decode_tile_comp(hdr, tile_idx, c, comp_bytes, tile_qp[c], w_luma, h_luma, out_depth)).collect()
} else {
comp_slices.into_iter().map(|(c, comp_bytes)| decode_tile_comp(hdr, tile_idx, c, comp_bytes, tile_qp[c], w_luma, h_luma, out_depth)).collect()
};
#[cfg(not(feature = "threads"))]
let decoded_comps: Result<Vec<Vec<u16>>> = {
let _ = par_comps;
comp_slices.into_iter().map(|(c, comp_bytes)| decode_tile_comp(hdr, tile_idx, c, comp_bytes, tile_qp[c], w_luma, h_luma, out_depth)).collect()
};
let mut comps: [Vec<u16>; 4] = Default::default();
for (c, buf) in decoded_comps?.into_iter().enumerate() {
comps[c] = buf;
}
Ok(DecodedTile { x0, y0, w_luma, h_luma, comps })
}
#[allow(clippy::too_many_arguments)]
fn decode_tile_comp(hdr: &FrameHeader, tile_idx: usize, c: usize, comp_bytes: &[u8], qp: u8, w_luma: u32, h_luma: u32, out_depth: u8) -> Result<Vec<u16>> {
let num_mb_cols = w_luma / 16;
let num_mb_rows = h_luma / 16;
let sub_w = if c == 0 { 1 } else { hdr.chroma.sub_width_c() };
let sub_h = if c == 0 { 1 } else { hdr.chroma.sub_height_c() };
let tw_c = (w_luma / sub_w) as usize;
let th_c = (h_luma / sub_h) as usize;
let blk_w = (16 / sub_w) as usize;
let blk_h = (16 / sub_h) as usize;
let blocks_x = blk_w / 8;
let blocks_y = blk_h / 8;
let mut comp_buf = vec![0u16; tw_c * th_c];
let mut r = BitReader::new(comp_bytes);
let mut prev_dc: i32 = 0;
let mut prev_dc_diff: u32 = 20;
let mut prev_1st_ac_level: u32 = 0;
let q_mat = &hdr.q_matrix[c];
let coded_depth = hdr.bit_depth;
for mb_y in 0..(num_mb_rows as usize) {
for mb_x in 0..(num_mb_cols as usize) {
for by in 0..blocks_y {
for bx in 0..blocks_x {
// abs_dc_coeff_diff (RFC 9924 §5.3.15 & §7.1.1)
let k_dc = (prev_dc_diff >> 1).min(5);
let abs_dc_diff = read_vlc(&mut r, k_dc).map_err(|_| Error::CorruptTile(tile_idx))?;
let sign_dc = if abs_dc_diff > 0 { r.read_bit().map_err(|_| Error::CorruptTile(tile_idx))? } else { false };
let diff = if sign_dc { -(abs_dc_diff as i64) } else { abs_dc_diff as i64 };
let dc = prev_dc as i64 + diff;
if !(-32768..=32767).contains(&dc) {
return Err(Error::CorruptTile(tile_idx));
}
prev_dc = dc as i32;
prev_dc_diff = abs_dc_diff;
let mut coeff = [0i16; 64];
coeff[0] = dc as i16;
// ac_coeff_coding (RFC 9924 §5.3.16 & §7.1.2–7.1.3)
let mut scan_pos = 1usize;
let mut first_ac = true;
let mut prev_level = prev_1st_ac_level;
let mut prev_run = 0u32;
while scan_pos < 64 {
let k_run = (prev_run >> 2).min(2);
let run = read_vlc(&mut r, k_run).map_err(|_| Error::CorruptTile(tile_idx))? as usize;
scan_pos = scan_pos.checked_add(run).ok_or(Error::CorruptTile(tile_idx))?;
if scan_pos > 64 {
return Err(Error::CorruptTile(tile_idx));
}
prev_run = run as u32;
if scan_pos < 64 {
let k_lvl = (prev_level >> 2).min(4);
let abs_ac_minus1 = read_vlc(&mut r, k_lvl).map_err(|_| Error::CorruptTile(tile_idx))?;
let sign_ac = r.read_bit().map_err(|_| Error::CorruptTile(tile_idx))?;
let abs_level = (abs_ac_minus1 as u64) + 1;
let level_i64 = if sign_ac { -(abs_level as i64) } else { abs_level as i64 };
if !(-32768..=32767).contains(&level_i64) {
return Err(Error::CorruptTile(tile_idx));
}
coeff[ZIGZAG_8X8[scan_pos] as usize] = level_i64 as i16;
scan_pos += 1;
prev_level = abs_level as u32;
if first_ac {
first_ac = false;
prev_1st_ac_level = prev_level;
}
}
}
let mut rec = [0u16; 64];
if first_ac {
scale_and_idct8x8_dc_only(coeff[0], q_mat[0], qp, coded_depth, &mut rec);
} else {
scale_and_idct8x8(&coeff, q_mat, qp, coded_depth, &mut rec);
}
if out_depth != coded_depth {
rescale_block(&mut rec, coded_depth, out_depth);
}
let px0 = mb_x * blk_w + bx * 8;
let py0 = mb_y * blk_h + by * 8;
for ry in 0..8 {
let dst_row = (py0 + ry) * tw_c + px0;
comp_buf[dst_row..dst_row + 8].copy_from_slice(&rec[ry * 8..ry * 8 + 8]);
}
}
}
}
}
read_byte_alignment(&mut r).map_err(|_| Error::CorruptTile(tile_idx))?;
Ok(comp_buf)
}
#[inline]
fn rescale_block(block: &mut [u16; 64], from_depth: u8, to_depth: u8) {
if to_depth > from_depth {
let shift = (to_depth - from_depth) as u32;
let fill_shift = from_depth as u32;
for s in block.iter_mut() {
let v = *s as u32;
*s = ((v << shift) | (v >> (fill_shift - shift))) as u16;
}
} else if to_depth < from_depth {
let shift = (from_depth - to_depth) as u32;
let round = 1u32 << (shift - 1);
let max_v = (1u32 << to_depth) - 1;
for s in block.iter_mut() {
*s = (((*s as u32) + round) >> shift).min(max_v) as u16;
}
}
}
+598
View File
@@ -0,0 +1,598 @@
//! RFC 9924 APV intra frame encoder.
use filmcraft_bitstream::BitWriter;
use crate::dct::{fdct8x8, quantize8x8};
use crate::header::{FrameHeader, MAX_DIMENSION, PBU_PRIMARY_FRAME, write_frame_header, write_metadata_pbu};
use crate::tables::{DEFAULT_Q_MATRIX_VAL, ZIGZAG_8X8, select_level_and_band};
use crate::{ChromaFormat, ColorInfo, ContentLightLevel, Error, Frame, MasteringDisplay, Profile, Result};
/// Generate RFC 9924 §7.2.4 variable-length codeword (`h(v)`).
#[inline]
pub(crate) fn write_vlc(w: &mut BitWriter, symbol_val: u32, k_param: u32) {
const PREFIX_VLC: [[u32; 2]; 3] = [[1, 0], [0, 0], [0, 1]];
let mut symbol_value = symbol_val;
let val_prefix = ((symbol_val >> k_param) as usize).min(2);
let mut bit_count = 0usize;
let mut k = k_param;
while symbol_value >= (1u32 << k) {
symbol_value -= 1u32 << k;
if bit_count < 2 {
w.write_bits(PREFIX_VLC[val_prefix][bit_count], 1);
} else {
w.write_bits(0, 1);
}
if bit_count >= 2 {
k += 1;
}
bit_count += 1;
}
if bit_count < 2 {
w.write_bits(PREFIX_VLC[val_prefix][bit_count], 1);
} else {
w.write_bits(1, 1);
}
if k > 0 {
w.write_bits(symbol_value, k);
}
}
/// Exact bit length of a VLC codeword generated by [`write_vlc`].
#[inline]
pub(crate) fn vlc_bit_len(symbol_val: u32, k_param: u32) -> u32 {
if symbol_val < (1u32 << k_param) {
1 + k_param
} else if symbol_val < (2u32 << k_param) {
2 + k_param
} else {
let rem = (symbol_val >> k_param) - 1;
let zeros = 31 - rem.leading_zeros();
3 + k_param + 2 * zeros
}
}
/// APV encoder configuration.
#[derive(Debug, Clone)]
pub struct EncoderConfig {
pub profile: Profile,
pub width: u32,
pub height: u32,
pub chroma: ChromaFormat,
pub bit_depth: u8,
pub color: ColorInfo,
pub color_description_present: bool,
/// Fixed tile quantization parameter (`0..=51 + QpBdOffset`). When `None`, rate control
/// chooses a uniform QP per frame to fit [`Self::target_frame_bytes`].
pub qp: Option<u8>,
/// Target encoded frame size in bytes when `qp` is `None`.
pub target_frame_bytes: u32,
/// Tile width in 16x16 macroblocks (RFC 9924 §9.4.1 requires `>= 16`).
pub tile_width_in_mbs: u32,
/// Tile height in 16x16 macroblocks (RFC 9924 §9.4.1 requires `>= 8`).
pub tile_height_in_mbs: u32,
pub level_idc: u8,
pub band_idc: u8,
/// Optional custom per-component 8x8 quantization matrices (`y * 8 + x`).
pub q_matrix: Option<[[u8; 64]; 4]>,
/// Write `tile_size_in_fh` array in `frame_header()` (`tile_size_present_in_fh_flag = 1`).
pub write_tile_sizes_in_fh: bool,
pub mastering_display: Option<MasteringDisplay>,
pub content_light: Option<ContentLightLevel>,
}
impl EncoderConfig {
pub fn new(profile: Profile, width: u32, height: u32) -> Self {
let chroma = profile.default_chroma();
let bit_depth = profile.default_bit_depth();
let w_mbs = width.div_ceil(16).max(1);
let h_mbs = height.div_ceil(16).max(1);
// Choose conforming tile dimensions (>= 16x8 MBs, <= 20x20 tiles) with ~4-8 tiles on HD/4K.
let tile_width_in_mbs = w_mbs.div_ceil(4).max(16).max(w_mbs.div_ceil(20));
let tile_height_in_mbs = h_mbs.div_ceil(4).max(8).max(h_mbs.div_ceil(20));
let target_frame_bytes = profile.nominal_frame_bytes(width, height);
let kbps = ((target_frame_bytes as u64) * 8 * 30 / 1000).max(1000) as u32;
let (level_idc, band_idc) = select_level_and_band((width as u64) * (height as u64) * 30, kbps);
Self {
profile,
width,
height,
chroma,
bit_depth,
color: ColorInfo::BT709,
color_description_present: true,
qp: None,
target_frame_bytes,
tile_width_in_mbs,
tile_height_in_mbs,
level_idc,
band_idc,
q_matrix: None,
write_tile_sizes_in_fh: false,
mastering_display: None,
content_light: None,
}
}
}
/// APV intra encoder.
pub struct Encoder {
cfg: EncoderConfig,
hdr: FrameHeader,
}
struct PreparedTileComp {
/// Forward-transformed 8x8 blocks in MB-then-subblock scan order.
blocks: Vec<[i32; 64]>,
}
struct PreparedTile {
tile_idx: usize,
comps: Vec<PreparedTileComp>,
}
impl Encoder {
pub fn new(profile: Profile, width: u32, height: u32) -> Result<Self> {
Self::with_config(EncoderConfig::new(profile, width, height))
}
pub fn with_config(cfg: EncoderConfig) -> Result<Self> {
if cfg.width == 0 || cfg.height == 0 || cfg.width > MAX_DIMENSION || cfg.height > MAX_DIMENSION {
return Err(Error::Input(format!("unsupported dimensions {}x{}", cfg.width, cfg.height)));
}
if cfg.chroma == ChromaFormat::Yuv422 && !cfg.width.is_multiple_of(2) {
return Err(Error::Input("4:2:2 requires even frame width".into()));
}
if !(10..=16).contains(&cfg.bit_depth) {
return Err(Error::Input(format!("unsupported coded bit depth {}", cfg.bit_depth)));
}
if !cfg.profile.supports(cfg.chroma, cfg.bit_depth) {
return Err(Error::Input(format!("profile {} does not support {:?} {}-bit", cfg.profile.name(), cfg.chroma, cfg.bit_depth)));
}
if cfg.tile_width_in_mbs == 0 || cfg.tile_height_in_mbs == 0 {
return Err(Error::Input("tile dimensions in MBs must be non-zero".into()));
}
let w_mbs = cfg.width.div_ceil(16);
let h_mbs = cfg.height.div_ceil(16);
let tile_cols = w_mbs.div_ceil(cfg.tile_width_in_mbs);
let tile_rows = h_mbs.div_ceil(cfg.tile_height_in_mbs);
if tile_cols > 20 || tile_rows > 20 {
return Err(Error::Input(format!("tile grid {tile_cols}x{tile_rows} exceeds RFC 9924 limit of 20x20")));
}
let mut col_starts = Vec::with_capacity(tile_cols as usize + 1);
let mut s = 0u32;
while s < w_mbs {
col_starts.push(s * 16);
s += cfg.tile_width_in_mbs;
}
col_starts.push(w_mbs * 16);
let mut row_starts = Vec::with_capacity(tile_rows as usize + 1);
let mut s = 0u32;
while s < h_mbs {
row_starts.push(s * 16);
s += cfg.tile_height_in_mbs;
}
row_starts.push(h_mbs * 16);
if let Some(qm) = &cfg.q_matrix {
for c in 0..cfg.chroma.num_comps() {
if qm[c].contains(&0) {
return Err(Error::Input("q_matrix entries must be non-zero (1..=255)".into()));
}
}
}
let hdr = FrameHeader {
profile_idc: cfg.profile.idc(),
level_idc: cfg.level_idc,
band_idc: cfg.band_idc.min(3),
width: cfg.width,
height: cfg.height,
chroma: cfg.chroma,
bit_depth: cfg.bit_depth,
capture_time_distance: 0,
color_description_present: cfg.color_description_present,
color: cfg.color,
use_q_matrix: cfg.q_matrix.is_some(),
q_matrix: cfg.q_matrix.unwrap_or([[DEFAULT_Q_MATRIX_VAL; 64]; 4]),
tile_width_in_mbs: cfg.tile_width_in_mbs,
tile_height_in_mbs: cfg.tile_height_in_mbs,
tile_cols,
tile_rows,
col_starts,
row_starts,
tile_sizes_in_fh: None,
header_bytes: 0,
};
Ok(Self { cfg, hdr })
}
pub fn config(&self) -> &EncoderConfig {
&self.cfg
}
pub fn target_frame_bytes(&self) -> u32 {
self.cfg.target_frame_bytes
}
/// Encode one frame into an APV Access Unit (`b"aPv1"...`), suitable for MP4/MOV (`apv1`) or MKV (`V_APV`).
pub fn encode(&mut self, frame: &Frame) -> Result<Vec<u8>> {
if frame.width != self.cfg.width || frame.height != self.cfg.height {
return Err(Error::Input(format!("frame is {}x{}, encoder is {}x{}", frame.width, frame.height, self.cfg.width, self.cfg.height)));
}
if frame.chroma != self.cfg.chroma {
return Err(Error::Input(format!("frame chroma {:?} does not match encoder {:?}", frame.chroma, self.cfg.chroma)));
}
if !(8..=16).contains(&frame.bit_depth) {
return Err(Error::Input(format!("unsupported input bit depth {}", frame.bit_depth)));
}
let n_luma = (frame.width as usize) * (frame.height as usize);
let n_chroma = (frame.chroma_width() as usize) * (frame.chroma_height() as usize);
if frame.y.len() != n_luma || frame.cb.len() != n_chroma || frame.cr.len() != n_chroma {
return Err(Error::Input("plane buffer lengths do not match frame geometry".into()));
}
if self.cfg.chroma == ChromaFormat::Yuv4444 && frame.alpha.as_ref().is_none_or(|a| a.len() != n_luma) {
return Err(Error::Input("4:4:4:4 profile requires an alpha plane of width * height samples".into()));
}
let prepared = self.prepare_tiles(frame);
let max_qp = (51 + self.hdr.qp_bd_offset()) as u8;
let qp = match self.cfg.qp {
Some(q) => q.min(max_qp),
None => self.select_qp(&prepared, max_qp),
};
let encoded_tiles: Vec<Vec<u8>> = {
#[cfg(feature = "threads")]
{
use rayon::prelude::*;
prepared.par_iter().map(|t| self.encode_tile(t, qp)).collect()
}
#[cfg(not(feature = "threads"))]
{
prepared.iter().map(|t| self.encode_tile(t, qp)).collect()
}
};
let mut hdr = self.hdr.clone();
hdr.color = if !self.cfg.color_description_present {
ColorInfo::default()
} else if frame.color != ColorInfo::BT709 {
frame.color
} else {
self.cfg.color
};
if self.cfg.write_tile_sizes_in_fh {
hdr.tile_sizes_in_fh = Some(encoded_tiles.iter().map(|t| t.len() as u32).collect());
}
let fh_bytes = write_frame_header(&hdr);
let tiles_total_bytes: usize = encoded_tiles.iter().map(|t| 4 + t.len()).sum();
let pbu_size = 4 + fh_bytes.len() + tiles_total_bytes;
let mdcv = frame.mastering_display.as_ref().or(self.cfg.mastering_display.as_ref());
let cll = frame.content_light.as_ref().or(self.cfg.content_light.as_ref());
let meta_pbu = write_metadata_pbu(1, mdcv, cll);
let meta_total = meta_pbu.as_ref().map_or(0, |m| 4 + m.len());
let mut au = Vec::with_capacity(4 + 4 + pbu_size + meta_total);
au.extend_from_slice(b"aPv1");
// Primary frame PBU (pbu_type = 1, group_id = 1)
au.extend_from_slice(&(pbu_size as u32).to_be_bytes());
au.push(PBU_PRIMARY_FRAME);
au.extend_from_slice(&1u16.to_be_bytes());
au.push(0); // reserved_zero_8bits
au.extend_from_slice(&fh_bytes);
for t in &encoded_tiles {
au.extend_from_slice(&(t.len() as u32).to_be_bytes());
au.extend_from_slice(t);
}
if let Some(m) = meta_pbu {
au.extend_from_slice(&(m.len() as u32).to_be_bytes());
au.extend_from_slice(&m);
}
Ok(au)
}
/// Encode one frame as a `raw_bitstream_access_unit()` (prefixed by `au_size: u32 BE`, RFC 9924 Appendix A).
pub fn encode_raw_au(&mut self, frame: &Frame) -> Result<Vec<u8>> {
let au = self.encode(frame)?;
let mut raw = Vec::with_capacity(4 + au.len());
raw.extend_from_slice(&(au.len() as u32).to_be_bytes());
raw.extend_from_slice(&au);
Ok(raw)
}
/// Build the `APVDecoderConfigurationRecord` payload (for ISOBMFF `apvC` or Matroska CodecPrivate).
pub fn decoder_config_record(&self) -> Vec<u8> {
let mut v = Vec::with_capacity(24);
v.push(1); // configurationVersion = 1
v.push(1); // number_of_configuration_entry = 1
v.push(PBU_PRIMARY_FRAME); // pbu_type[0] = 1
v.push(1); // number_of_frame_info[0] = 1
let flags = if self.cfg.color_description_present { 0x02 } else { 0x00 } | 0x01; // capture_time_distance_ignored = 1
v.push(flags);
v.push(self.hdr.profile_idc);
v.push(self.hdr.level_idc);
v.push(self.hdr.band_idc);
v.extend_from_slice(&self.hdr.width.to_be_bytes());
v.extend_from_slice(&self.hdr.height.to_be_bytes());
v.push((self.hdr.chroma.idc() << 4) | (self.hdr.bit_depth.saturating_sub(8) & 0x0F));
v.push(0); // capture_time_distance = 0
if self.cfg.color_description_present {
v.push(self.cfg.color.primaries);
v.push(self.cfg.color.transfer);
v.push(self.cfg.color.matrix);
v.push(if self.cfg.color.full_range { 0x80 } else { 0x00 });
}
v
}
fn prepare_tiles(&self, frame: &Frame) -> Vec<PreparedTile> {
let num_tiles = self.hdr.num_tiles();
let prepare_one = |tile_idx: usize| -> PreparedTile {
let tx = tile_idx % (self.hdr.tile_cols as usize);
let ty = tile_idx / (self.hdr.tile_cols as usize);
let x0 = self.hdr.col_starts[tx];
let x1 = self.hdr.col_starts[tx + 1];
let y0 = self.hdr.row_starts[ty];
let y1 = self.hdr.row_starts[ty + 1];
let num_mb_cols = (x1 - x0) / 16;
let num_mb_rows = (y1 - y0) / 16;
let num_comps = self.hdr.chroma.num_comps();
let mut comps = Vec::with_capacity(num_comps);
for c in 0..num_comps {
let (plane, pw, ph, sub_w, sub_h) = match c {
0 => (frame.y.as_slice(), frame.width as usize, frame.height as usize, 1u32, 1u32),
1 => (
frame.cb.as_slice(),
frame.chroma_width() as usize,
frame.chroma_height() as usize,
self.hdr.chroma.sub_width_c(),
self.hdr.chroma.sub_height_c(),
),
2 => (
frame.cr.as_slice(),
frame.chroma_width() as usize,
frame.chroma_height() as usize,
self.hdr.chroma.sub_width_c(),
self.hdr.chroma.sub_height_c(),
),
_ => (frame.alpha.as_deref().unwrap_or(&[]), frame.width as usize, frame.height as usize, 1u32, 1u32),
};
let blk_w = (16 / sub_w) as usize;
let blk_h = (16 / sub_h) as usize;
let blocks_x = blk_w / 8;
let blocks_y = blk_h / 8;
let total_blocks = (num_mb_cols as usize) * (num_mb_rows as usize) * blocks_x * blocks_y;
let mut blocks = Vec::with_capacity(total_blocks);
let coded_depth = self.hdr.bit_depth;
let in_depth = frame.bit_depth;
for mb_y in 0..num_mb_rows {
for mb_x in 0..num_mb_cols {
let x_mb_c = ((x0 + mb_x * 16) / sub_w) as usize;
let y_mb_c = ((y0 + mb_y * 16) / sub_h) as usize;
for by in 0..blocks_y {
for bx in 0..blocks_x {
let bx0 = x_mb_c + bx * 8;
let by0 = y_mb_c + by * 8;
let mut samples = [0u16; 64];
for ry in 0..8 {
let sy = (by0 + ry).min(ph.saturating_sub(1));
for rx in 0..8 {
let sx = (bx0 + rx).min(pw.saturating_sub(1));
let v = plane[sy * pw + sx];
samples[ry * 8 + rx] = scale_sample(v, in_depth, coded_depth);
}
}
blocks.push(fdct8x8(&samples, coded_depth));
}
}
}
}
comps.push(PreparedTileComp { blocks });
}
PreparedTile { tile_idx, comps }
};
#[cfg(feature = "threads")]
{
use rayon::prelude::*;
(0..num_tiles).into_par_iter().map(prepare_one).collect()
}
#[cfg(not(feature = "threads"))]
{
(0..num_tiles).map(prepare_one).collect()
}
}
fn select_qp(&self, tiles: &[PreparedTile], max_qp: u8) -> u8 {
let target_bytes = (self.cfg.target_frame_bytes as usize).max(64);
let frame_bytes_at = |qp: u8| -> usize {
let tile_bytes = |t: &PreparedTile| -> usize {
let num_comps = t.comps.len();
let mut sz = 4 + (5 + 5 * num_comps);
for (c, comp) in t.comps.iter().enumerate() {
let bits = self.estimate_comp_bits(comp, c, qp);
sz += (bits.div_ceil(8) as usize).max(1);
}
sz
};
#[cfg(feature = "threads")]
let sum: usize = {
use rayon::prelude::*;
tiles.par_iter().map(tile_bytes).sum()
};
#[cfg(not(feature = "threads"))]
let sum: usize = tiles.iter().map(tile_bytes).sum();
24 + sum
};
let mut lo = 0u8;
let mut hi = max_qp;
if frame_bytes_at(0) <= target_bytes {
return 0;
}
while lo < hi {
let mid = lo + (hi - lo) / 2;
if frame_bytes_at(mid) <= target_bytes {
hi = mid;
} else {
lo = mid + 1;
}
}
lo
}
fn estimate_comp_bits(&self, comp: &PreparedTileComp, c: usize, qp: u8) -> u64 {
let qm = &self.hdr.q_matrix[c];
let depth = self.hdr.bit_depth;
let mut prev_dc: i32 = 0;
let mut prev_dc_diff: u32 = 20;
let mut prev_1st_ac_level: u32 = 0;
let mut bits: u64 = 0;
for f_blk in &comp.blocks {
let coeff = quantize8x8(f_blk, qm, qp, depth);
let dc = coeff[0] as i32;
let diff = dc - prev_dc;
let abs_dc_diff = diff.unsigned_abs();
let k_dc = (prev_dc_diff >> 1).min(5);
bits += vlc_bit_len(abs_dc_diff, k_dc) as u64;
if abs_dc_diff > 0 {
bits += 1;
}
prev_dc = dc;
prev_dc_diff = abs_dc_diff;
let mut scan_pos = 1usize;
let mut first_ac = true;
let mut prev_level = prev_1st_ac_level;
let mut prev_run = 0u32;
while scan_pos < 64 {
let mut run = 0u32;
while scan_pos + (run as usize) < 64 && coeff[ZIGZAG_8X8[scan_pos + (run as usize)] as usize] == 0 {
run += 1;
}
let k_run = (prev_run >> 2).min(2);
bits += vlc_bit_len(run, k_run) as u64;
scan_pos += run as usize;
prev_run = run;
if scan_pos < 64 {
let level = coeff[ZIGZAG_8X8[scan_pos] as usize];
let abs_level = level.unsigned_abs() as u32;
let k_lvl = (prev_level >> 2).min(4);
bits += vlc_bit_len(abs_level - 1, k_lvl) as u64 + 1;
scan_pos += 1;
prev_level = abs_level;
if first_ac {
first_ac = false;
prev_1st_ac_level = prev_level;
}
}
}
}
bits
}
fn encode_tile(&self, tile: &PreparedTile, qp: u8) -> Vec<u8> {
let num_comps = tile.comps.len();
let mut comp_payloads: Vec<Vec<u8>> = Vec::with_capacity(num_comps);
let depth = self.hdr.bit_depth;
for (c, comp) in tile.comps.iter().enumerate() {
let qm = &self.hdr.q_matrix[c];
let mut w = BitWriter::new();
let mut prev_dc: i32 = 0;
let mut prev_dc_diff: u32 = 20;
let mut prev_1st_ac_level: u32 = 0;
for f_blk in &comp.blocks {
let coeff = quantize8x8(f_blk, qm, qp, depth);
let dc = coeff[0] as i32;
let diff = dc - prev_dc;
let abs_dc_diff = diff.unsigned_abs();
let k_dc = (prev_dc_diff >> 1).min(5);
write_vlc(&mut w, abs_dc_diff, k_dc);
if abs_dc_diff > 0 {
w.write_bit(diff < 0);
}
prev_dc = dc;
prev_dc_diff = abs_dc_diff;
let mut scan_pos = 1usize;
let mut first_ac = true;
let mut prev_level = prev_1st_ac_level;
let mut prev_run = 0u32;
while scan_pos < 64 {
let mut run = 0u32;
while scan_pos + (run as usize) < 64 && coeff[ZIGZAG_8X8[scan_pos + (run as usize)] as usize] == 0 {
run += 1;
}
let k_run = (prev_run >> 2).min(2);
write_vlc(&mut w, run, k_run);
scan_pos += run as usize;
prev_run = run;
if scan_pos < 64 {
let level = coeff[ZIGZAG_8X8[scan_pos] as usize];
let abs_level = level.unsigned_abs() as u32;
let k_lvl = (prev_level >> 2).min(4);
write_vlc(&mut w, abs_level - 1, k_lvl);
w.write_bit(level < 0);
scan_pos += 1;
prev_level = abs_level;
if first_ac {
first_ac = false;
prev_1st_ac_level = prev_level;
}
}
}
}
comp_payloads.push(w.finish());
}
// Write tile_header(tileIdx) (RFC 9924 §5.3.13)
let tile_header_size = (5 + 5 * num_comps) as u16;
let total_size = tile_header_size as usize + comp_payloads.iter().map(Vec::len).sum::<usize>();
let mut out = Vec::with_capacity(total_size);
out.extend_from_slice(&tile_header_size.to_be_bytes());
out.extend_from_slice(&(tile.tile_idx as u16).to_be_bytes());
for cp in &comp_payloads {
out.extend_from_slice(&(cp.len() as u32).to_be_bytes());
}
for _ in 0..num_comps {
out.push(qp);
}
out.push(0); // reserved_zero_8bits
for cp in comp_payloads {
out.extend_from_slice(&cp);
}
out
}
}
#[inline]
fn scale_sample(v: u16, from_depth: u8, to_depth: u8) -> u16 {
let max_in = (1u32 << from_depth) - 1;
let v = (v as u32).min(max_in);
if to_depth == from_depth {
v as u16
} else if to_depth > from_depth {
let shift = (to_depth - from_depth) as u32;
((v << shift) | (v >> ((from_depth as u32) - shift))) as u16
} else {
let shift = (from_depth - to_depth) as u32;
let round = 1u32 << (shift - 1);
let max_out = (1u32 << to_depth) - 1;
(((v + round) >> shift).min(max_out)) as u16
}
}
+460
View File
@@ -0,0 +1,460 @@
//! RFC 9924 §5.3 and §8 syntax structures: Access Unit, PBU, Frame Header, Tile Info, and Metadata.
use filmcraft_bitstream::{BitReader, BitWriter};
use crate::tables::DEFAULT_Q_MATRIX_VAL;
use crate::{ChromaFormat, ColorInfo, ContentLightLevel, Error, MasteringDisplay, Result};
/// Four-character signature `'aPv1'` (`0x61507631`) at the start of every APV Access Unit (RFC 9924 §5.3.1).
pub const AU_SIGNATURE: [u8; 4] = *b"aPv1";
/// Primitive Bitstream Unit (PBU) types (RFC 9924 §5.3.3 Table 3).
pub const PBU_PRIMARY_FRAME: u8 = 1;
pub const PBU_NON_PRIMARY_FRAME: u8 = 2;
pub const PBU_PREVIEW_FRAME: u8 = 25;
pub const PBU_DEPTH_FRAME: u8 = 26;
pub const PBU_ALPHA_FRAME: u8 = 27;
pub const PBU_AU_INFO: u8 = 65;
pub const PBU_METADATA: u8 = 66;
pub const PBU_FILLER: u8 = 67;
/// Maximum supported frame dimension in luma samples (guards against hostile allocations).
pub const MAX_DIMENSION: u32 = 16384;
/// Maximum tiles per axis (RFC 9924 §9.4.1 specifies 20; we allow up to 64 for robustness).
pub const MAX_TILE_DIM: u32 = 64;
/// Parsed `frame_header()` and derived tile geometry (RFC 9924 §5.3.5–5.3.8).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FrameHeader {
pub profile_idc: u8,
pub level_idc: u8,
pub band_idc: u8,
pub width: u32,
pub height: u32,
pub chroma: ChromaFormat,
pub bit_depth: u8,
pub capture_time_distance: u8,
pub color_description_present: bool,
pub color: ColorInfo,
pub use_q_matrix: bool,
/// Per-component 8x8 quantization matrix in raster order (`y * 8 + x`).
pub q_matrix: [[u8; 64]; 4],
pub tile_width_in_mbs: u32,
pub tile_height_in_mbs: u32,
pub tile_cols: u32,
pub tile_rows: u32,
/// Tile column start positions in luma samples (`len == tile_cols + 1`).
pub col_starts: Vec<u32>,
/// Tile row start positions in luma samples (`len == tile_rows + 1`).
pub row_starts: Vec<u32>,
pub tile_sizes_in_fh: Option<Vec<u32>>,
/// Byte offset within the PBU payload where `frame_header()` ends (start of the tile loop).
pub header_bytes: usize,
}
impl FrameHeader {
pub fn frame_width_in_mbs(&self) -> u32 {
self.width.div_ceil(16)
}
pub fn frame_height_in_mbs(&self) -> u32 {
self.height.div_ceil(16)
}
pub fn num_tiles(&self) -> usize {
(self.tile_cols as usize) * (self.tile_rows as usize)
}
pub fn qp_bd_offset(&self) -> i32 {
(self.bit_depth.saturating_sub(8) as i32) * 6
}
}
/// A parsed PBU slice inside an Access Unit.
#[derive(Debug, Clone)]
pub struct PbuSlice<'a> {
pub pbu_type: u8,
pub group_id: u16,
/// Payload after the 4-byte `pbu_header()`.
pub payload: &'a [u8],
}
/// Unwrap an Access Unit byte slice: accepts either a direct `access_unit` starting with `'aPv1'`
/// or a `raw_bitstream_access_unit` prefixed with a 32-bit big-endian `au_size` (RFC 9924 Appendix A).
pub fn unwrap_au(data: &[u8]) -> Result<&[u8]> {
if data.len() < 4 {
return Err(Error::Truncated);
}
if data[..4] == AU_SIGNATURE {
return Ok(data);
}
if data.len() >= 8 && data[4..8] == AU_SIGNATURE {
let au_size = u32::from_be_bytes([data[0], data[1], data[2], data[3]]) as usize;
if au_size < 4 || au_size == 0xFFFF_FFFF {
return Err(Error::Invalid("invalid au_size in raw bitstream"));
}
let end = 4usize.checked_add(au_size).ok_or(Error::Truncated)?;
return data.get(4..end).ok_or(Error::Truncated);
}
Err(Error::Invalid("missing aPv1 access unit signature"))
}
/// Split a raw `.apv` bitstream (`raw_bitstream_access_unit()` sequence per RFC 9924 Appendix A)
/// into individual Access Unit slices (each starting with `'aPv1'`).
pub fn split_raw_bitstream(mut data: &[u8]) -> Result<Vec<&[u8]>> {
if data.is_empty() {
return Err(Error::Truncated);
}
// If the buffer starts directly with 'aPv1', treat the entire buffer as a single AU.
if data.len() >= 4 && data[..4] == AU_SIGNATURE {
return Ok(vec![data]);
}
let mut aus = Vec::new();
while !data.is_empty() {
if data.len() < 8 {
return Err(Error::Truncated);
}
let au_size = u32::from_be_bytes([data[0], data[1], data[2], data[3]]) as usize;
if au_size < 4 || au_size == 0xFFFF_FFFF {
return Err(Error::Invalid("invalid au_size in raw bitstream"));
}
let end = 4usize.checked_add(au_size).ok_or(Error::Truncated)?;
let au = data.get(4..end).ok_or(Error::Truncated)?;
if au[..4] != AU_SIGNATURE {
return Err(Error::Invalid("missing aPv1 signature in raw bitstream AU"));
}
aus.push(au);
data = &data[end..];
}
if aus.is_empty() {
return Err(Error::Truncated);
}
Ok(aus)
}
/// Parse the PBU list of a single Access Unit (RFC 9924 §5.3.1–5.3.3).
/// PBUs with `reserved_zero_8bits > 0` are ignored as required by RFC 9924 §5.3.3.
pub fn parse_au_pbus(data: &[u8]) -> Result<Vec<PbuSlice<'_>>> {
let au = unwrap_au(data)?;
if au.len() < 8 {
return Err(Error::Truncated);
}
let mut pos = 4usize;
let mut pbus = Vec::new();
while pos < au.len() {
let sz_bytes = au.get(pos..pos + 4).ok_or(Error::Truncated)?;
let pbu_size = u32::from_be_bytes([sz_bytes[0], sz_bytes[1], sz_bytes[2], sz_bytes[3]]) as usize;
if pbu_size == 0 || pbu_size == 0xFFFF_FFFF {
return Err(Error::Invalid("invalid pbu_size"));
}
if pbu_size < 4 {
return Err(Error::Truncated);
}
pos += 4;
let pbu_end = pos.checked_add(pbu_size).ok_or(Error::Truncated)?;
let pbu = au.get(pos..pbu_end).ok_or(Error::Truncated)?;
pos = pbu_end;
let pbu_type = pbu[0];
let group_id = u16::from_be_bytes([pbu[1], pbu[2]]);
let reserved_zero_8bits = pbu[3];
if reserved_zero_8bits > 0 {
// RFC 9924 §5.3.3: Decoders MUST ignore PBU with reserved_zero_8bits > 0.
continue;
}
if group_id == 0xFFFF || (group_id == 0 && pbu_type <= 64) {
return Err(Error::Invalid("invalid PBU group_id"));
}
pbus.push(PbuSlice { pbu_type, group_id, payload: &pbu[4..] });
}
Ok(pbus)
}
/// Read `byte_alignment()` and verify all alignment bits are zero (RFC 9924 §5.3.17).
pub fn read_byte_alignment(r: &mut BitReader) -> Result<()> {
while !r.is_byte_aligned() {
let bit = r.read_bit().map_err(|_| Error::Truncated)?;
if bit {
return Err(Error::Invalid("non-zero alignment bit"));
}
}
Ok(())
}
/// Parse `frame_header()` from the payload of a frame PBU (after `pbu_header()`), per RFC 9924 §5.3.5–5.3.8.
/// Returns `Ok(None)` if any `reserved_zero_*` field is non-zero (RFC 9924 §5.3.5 requires ignoring the PBU).
pub fn parse_frame_header(payload: &[u8]) -> Result<Option<FrameHeader>> {
let mut r = BitReader::new(payload);
// frame_info() (RFC 9924 §5.3.6)
let profile_idc = r.read_bits(8).map_err(|_| Error::Truncated)? as u8;
let level_idc = r.read_bits(8).map_err(|_| Error::Truncated)? as u8;
let band_idc = r.read_bits(3).map_err(|_| Error::Truncated)? as u8;
let reserved_zero_5bits = r.read_bits(5).map_err(|_| Error::Truncated)? as u8;
let width = r.read_bits(24).map_err(|_| Error::Truncated)?;
let height = r.read_bits(24).map_err(|_| Error::Truncated)?;
let chroma_format_idc = r.read_bits(4).map_err(|_| Error::Truncated)? as u8;
let bit_depth_minus8 = r.read_bits(4).map_err(|_| Error::Truncated)? as u8;
let capture_time_distance = r.read_bits(8).map_err(|_| Error::Truncated)? as u8;
let fi_reserved_8 = r.read_bits(8).map_err(|_| Error::Truncated)? as u8;
// frame_header() (RFC 9924 §5.3.5)
let fh_reserved_8_a = r.read_bits(8).map_err(|_| Error::Truncated)? as u8;
if reserved_zero_5bits > 0 || fi_reserved_8 > 0 || fh_reserved_8_a > 0 {
return Ok(None);
}
if width == 0 || height == 0 || width > MAX_DIMENSION || height > MAX_DIMENSION {
return Err(Error::Invalid("unsupported frame dimensions"));
}
let chroma = ChromaFormat::from_idc(chroma_format_idc).ok_or(Error::Invalid("invalid chroma_format_idc"))?;
if chroma == ChromaFormat::Yuv422 && !width.is_multiple_of(2) {
return Err(Error::Invalid("4:2:2 frame_width must be even"));
}
if !(2..=8).contains(&bit_depth_minus8) {
return Err(Error::Invalid("bit_depth_minus8 out of range 2..=8"));
}
let bit_depth = bit_depth_minus8 + 8;
let color_description_present = r.read_bit().map_err(|_| Error::Truncated)?;
let color = if color_description_present {
let primaries = r.read_bits(8).map_err(|_| Error::Truncated)? as u8;
let transfer = r.read_bits(8).map_err(|_| Error::Truncated)? as u8;
let matrix = r.read_bits(8).map_err(|_| Error::Truncated)? as u8;
let full_range = r.read_bit().map_err(|_| Error::Truncated)?;
ColorInfo { primaries, transfer, matrix, full_range }
} else {
ColorInfo::default()
};
let use_q_matrix = r.read_bit().map_err(|_| Error::Truncated)?;
let mut q_matrix = [[DEFAULT_Q_MATRIX_VAL; 64]; 4];
if use_q_matrix {
for c in 0..chroma.num_comps() {
for y in 0..8 {
for x in 0..8 {
let q = r.read_bits(8).map_err(|_| Error::Truncated)? as u8;
if q == 0 {
return Err(Error::Invalid("q_matrix entry 0 is reserved"));
}
q_matrix[c][y * 8 + x] = q;
}
}
}
}
// tile_info() (RFC 9924 §5.3.8)
let tile_width_in_mbs = r.read_bits(20).map_err(|_| Error::Truncated)?;
let tile_height_in_mbs = r.read_bits(20).map_err(|_| Error::Truncated)?;
if tile_width_in_mbs == 0 || tile_height_in_mbs == 0 {
return Err(Error::Invalid("tile dimensions in MBs must be non-zero"));
}
let w_mbs = width.div_ceil(16);
let h_mbs = height.div_ceil(16);
let tile_cols = w_mbs.div_ceil(tile_width_in_mbs);
let tile_rows = h_mbs.div_ceil(tile_height_in_mbs);
if tile_cols == 0 || tile_rows == 0 || tile_cols > MAX_TILE_DIM || tile_rows > MAX_TILE_DIM {
return Err(Error::Invalid("too many tiles in frame"));
}
let mut col_starts = Vec::with_capacity(tile_cols as usize + 1);
let mut start_mb = 0u32;
while start_mb < w_mbs {
col_starts.push(start_mb * 16);
start_mb = start_mb.saturating_add(tile_width_in_mbs);
}
col_starts.push(w_mbs * 16);
let mut row_starts = Vec::with_capacity(tile_rows as usize + 1);
let mut start_mb = 0u32;
while start_mb < h_mbs {
row_starts.push(start_mb * 16);
start_mb = start_mb.saturating_add(tile_height_in_mbs);
}
row_starts.push(h_mbs * 16);
let num_tiles = (tile_cols as usize) * (tile_rows as usize);
let tile_size_present_in_fh = r.read_bit().map_err(|_| Error::Truncated)?;
let tile_sizes_in_fh = if tile_size_present_in_fh {
let mut sizes = Vec::with_capacity(num_tiles);
for _ in 0..num_tiles {
let sz = r.read_bits(32).map_err(|_| Error::Truncated)?;
if sz == 0 {
return Err(Error::Invalid("tile_size_in_fh cannot be 0"));
}
sizes.push(sz);
}
Some(sizes)
} else {
None
};
let fh_reserved_8_b = r.read_bits(8).map_err(|_| Error::Truncated)? as u8;
if fh_reserved_8_b > 0 {
return Ok(None);
}
read_byte_alignment(&mut r)?;
Ok(Some(FrameHeader {
profile_idc,
level_idc,
band_idc,
width,
height,
chroma,
bit_depth,
capture_time_distance,
color_description_present,
color,
use_q_matrix,
q_matrix,
tile_width_in_mbs,
tile_height_in_mbs,
tile_cols,
tile_rows,
col_starts,
row_starts,
tile_sizes_in_fh,
header_bytes: r.byte_pos(),
}))
}
/// Write `frame_header()` to a byte vector (RFC 9924 §5.3.5–5.3.8).
pub fn write_frame_header(h: &FrameHeader) -> Vec<u8> {
let mut w = BitWriter::new();
// frame_info()
w.write_bits(h.profile_idc as u32, 8);
w.write_bits(h.level_idc as u32, 8);
w.write_bits((h.band_idc & 7) as u32, 3);
w.write_bits(0, 5); // reserved_zero_5bits
w.write_bits(h.width, 24);
w.write_bits(h.height, 24);
w.write_bits(h.chroma.idc() as u32, 4);
w.write_bits(h.bit_depth.saturating_sub(8) as u32, 4);
w.write_bits(h.capture_time_distance as u32, 8);
w.write_bits(0, 8); // reserved_zero_8bits
// frame_header()
w.write_bits(0, 8); // reserved_zero_8bits
w.write_bit(h.color_description_present);
if h.color_description_present {
w.write_bits(h.color.primaries as u32, 8);
w.write_bits(h.color.transfer as u32, 8);
w.write_bits(h.color.matrix as u32, 8);
w.write_bit(h.color.full_range);
}
w.write_bit(h.use_q_matrix);
if h.use_q_matrix {
for c in 0..h.chroma.num_comps() {
for y in 0..8 {
for x in 0..8 {
w.write_bits(h.q_matrix[c][y * 8 + x].max(1) as u32, 8);
}
}
}
}
// tile_info()
w.write_bits(h.tile_width_in_mbs, 20);
w.write_bits(h.tile_height_in_mbs, 20);
if let Some(sizes) = &h.tile_sizes_in_fh {
w.write_bit(true);
for &sz in sizes {
w.write_bits(sz, 32);
}
} else {
w.write_bit(false);
}
w.write_bits(0, 8); // reserved_zero_8bits
w.finish()
}
/// Parse a `metadata()` PBU payload (after `pbu_header()`), extracting MDCV (`payloadType == 5`)
/// and CLL (`payloadType == 6`) if present (RFC 9924 §5.3.10 & §8).
pub fn parse_metadata_pbu(payload: &[u8], mdcv: &mut Option<MasteringDisplay>, cll: &mut Option<ContentLightLevel>) -> Result<()> {
if payload.len() < 4 {
return Err(Error::Truncated);
}
let metadata_size = u32::from_be_bytes([payload[0], payload[1], payload[2], payload[3]]) as usize;
let body = payload.get(4..4usize.checked_add(metadata_size).ok_or(Error::Truncated)?).ok_or(Error::Truncated)?;
let mut pos = 0usize;
while pos < body.len() {
let mut payload_type = 0u32;
while *body.get(pos).ok_or(Error::Truncated)? == 0xFF {
payload_type = payload_type.checked_add(255).ok_or(Error::Invalid("metadata payloadType overflow"))?;
pos += 1;
}
payload_type = payload_type.checked_add(*body.get(pos).ok_or(Error::Truncated)? as u32).ok_or(Error::Invalid("metadata payloadType overflow"))?;
pos += 1;
let mut payload_size = 0usize;
while *body.get(pos).ok_or(Error::Truncated)? == 0xFF {
payload_size = payload_size.checked_add(255).ok_or(Error::Invalid("metadata payloadSize overflow"))?;
pos += 1;
}
payload_size = payload_size.checked_add(*body.get(pos).ok_or(Error::Truncated)? as usize).ok_or(Error::Invalid("metadata payloadSize overflow"))?;
pos += 1;
let end = pos.checked_add(payload_size).ok_or(Error::Truncated)?;
let item = body.get(pos..end).ok_or(Error::Truncated)?;
pos = end;
match payload_type {
5 if item.len() >= 24 => {
let u16_at = |i: usize| u16::from_be_bytes([item[i], item[i + 1]]);
let u32_at = |i: usize| u32::from_be_bytes([item[i], item[i + 1], item[i + 2], item[i + 3]]);
*mdcv = Some(MasteringDisplay {
primaries: [(u16_at(0), u16_at(2)), (u16_at(4), u16_at(6)), (u16_at(8), u16_at(10))],
white_point: (u16_at(12), u16_at(14)),
max_luminance: u32_at(16),
min_luminance: u32_at(20),
});
}
6 if item.len() >= 4 => {
*cll = Some(ContentLightLevel { max_cll: u16::from_be_bytes([item[0], item[1]]), max_fall: u16::from_be_bytes([item[2], item[3]]) });
}
// Filler metadata (§8.2.1): must be 0xFF bytes
10 if item.iter().any(|&b| b != 0xFF) => {
return Err(Error::Invalid("non-0xFF byte in filler metadata"));
}
_ => {
// RFC 9924 §10: A decoder MUST NOT try to process metadata whose type is not recognized.
}
}
}
Ok(())
}
/// Build a `metadata()` PBU (including its 4-byte `pbu_header`) carrying MDCV and/or CLL metadata.
pub fn write_metadata_pbu(group_id: u16, mdcv: Option<&MasteringDisplay>, cll: Option<&ContentLightLevel>) -> Option<Vec<u8>> {
if mdcv.is_none() && cll.is_none() {
return None;
}
let mut body = Vec::new();
if let Some(m) = mdcv {
body.push(5); // payloadType = 5 (MDCV)
body.push(24); // payloadSize = 24
for &(x, y) in &m.primaries {
body.extend_from_slice(&x.to_be_bytes());
body.extend_from_slice(&y.to_be_bytes());
}
body.extend_from_slice(&m.white_point.0.to_be_bytes());
body.extend_from_slice(&m.white_point.1.to_be_bytes());
body.extend_from_slice(&m.max_luminance.to_be_bytes());
body.extend_from_slice(&m.min_luminance.to_be_bytes());
}
if let Some(c) = cll {
body.push(6); // payloadType = 6 (CLL)
body.push(4); // payloadSize = 4
body.extend_from_slice(&c.max_cll.to_be_bytes());
body.extend_from_slice(&c.max_fall.to_be_bytes());
}
let mut pbu = Vec::with_capacity(8 + body.len());
pbu.push(PBU_METADATA);
pbu.extend_from_slice(&group_id.to_be_bytes());
pbu.push(0); // reserved_zero_8bits
pbu.extend_from_slice(&(body.len() as u32).to_be_bytes());
pbu.extend_from_slice(&body);
Some(pbu)
}
+329
View File
@@ -0,0 +1,329 @@
//! Clean-room Advanced Professional Video (APV) codec, implemented strictly from IETF RFC 9924
//! (February 2026).
//!
//! - **Decoder** ([`decode_frame`], [`decode_frame_with`], [`decode_frame_into`], [`probe`]):
//! every profile in RFC 9924 §9 (`422-10`, `422-12`, `444-10`, `444-12`, `4444-10`, `4444-12`,
//! `400-10`) at 10–16 bits per sample, custom quantization matrices, multi-tile parallel decoding
//! (behind the `threads` feature), 4:4:4:4 and auxiliary alpha PBU (`pbu_type == 27`) support,
//! and HDR static metadata (`MDCV` and `CLL`, RFC 9924 §8).
//! - **Encoder** ([`Encoder`]): progressive intra frame encoding across all 7 profiles with fixed-QP
//! or frame-budget rate control, plus `APVDecoderConfigurationRecord` (`apvC`) generation.
//!
//! See the crate README for specification edition, accuracy against external oracles, and design notes.
#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))]
pub mod dct;
mod decode;
mod encode;
pub mod header;
pub mod tables;
pub use decode::{DecodeOptions, decode_frame, decode_frame_into, decode_frame_with, probe};
pub use encode::{Encoder, EncoderConfig};
pub use header::{AU_SIGNATURE, FrameHeader, split_raw_bitstream, unwrap_au};
/// APV codec errors.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum Error {
#[error("truncated APV bitstream")]
Truncated,
#[error("invalid APV bitstream: {0}")]
Invalid(&'static str),
#[error("corrupt APV tile {0}")]
CorruptTile(usize),
#[error("invalid APV encoder input: {0}")]
Input(String),
}
pub type Result<T> = std::result::Result<T, Error>;
/// Chroma format (`chroma_format_idc` in RFC 9924 §4.1 Table 2).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ChromaFormat {
/// `chroma_format_idc == 0`: 4:0:0 monochrome (1 component).
Monochrome,
/// `chroma_format_idc == 2`: 4:2:2 YCbCr (3 components, `SubWidthC = 2, SubHeightC = 1`).
Yuv422,
/// `chroma_format_idc == 3`: 4:4:4 YCbCr (3 components, `SubWidthC = 1, SubHeightC = 1`).
Yuv444,
/// `chroma_format_idc == 4`: 4:4:4:4 YCbCrA (4 components, `SubWidthC = 1, SubHeightC = 1`).
Yuv4444,
}
impl ChromaFormat {
pub fn from_idc(idc: u8) -> Option<Self> {
match idc {
0 => Some(Self::Monochrome),
2 => Some(Self::Yuv422),
3 => Some(Self::Yuv444),
4 => Some(Self::Yuv4444),
_ => None,
}
}
pub fn idc(self) -> u8 {
match self {
Self::Monochrome => 0,
Self::Yuv422 => 2,
Self::Yuv444 => 3,
Self::Yuv4444 => 4,
}
}
pub fn num_comps(self) -> usize {
match self {
Self::Monochrome => 1,
Self::Yuv422 | Self::Yuv444 => 3,
Self::Yuv4444 => 4,
}
}
pub fn sub_width_c(self) -> u32 {
match self {
Self::Yuv422 => 2,
_ => 1,
}
}
pub fn sub_height_c(self) -> u32 {
1
}
pub fn chroma_width(self, width: u32) -> u32 {
match self {
Self::Monochrome => 0,
Self::Yuv422 => width.div_ceil(2),
Self::Yuv444 | Self::Yuv4444 => width,
}
}
pub fn chroma_height(self, height: u32) -> u32 {
match self {
Self::Monochrome => 0,
_ => height,
}
}
pub fn has_alpha(self) -> bool {
self == Self::Yuv4444
}
}
/// APV profiles defined in RFC 9924 §9.3.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Profile {
/// `profile_idc == 33`: 422-10 profile (4:2:2, 10-bit).
#[default]
P422_10,
/// `profile_idc == 44`: 422-12 profile (4:2:2, 10–12-bit).
P422_12,
/// `profile_idc == 55`: 444-10 profile (4:2:2..4:4:4, 10-bit).
P444_10,
/// `profile_idc == 66`: 444-12 profile (4:2:2..4:4:4, 10–12-bit).
P444_12,
/// `profile_idc == 77`: 4444-10 profile (4:2:2..4:4:4:4, 10-bit).
P4444_10,
/// `profile_idc == 88`: 4444-12 profile (4:2:2..4:4:4:4, 10–12-bit).
P4444_12,
/// `profile_idc == 99`: 400-10 profile (4:0:0, 10-bit).
P400_10,
}
impl Profile {
pub const ALL: [Profile; 7] =
[Profile::P422_10, Profile::P422_12, Profile::P444_10, Profile::P444_12, Profile::P4444_10, Profile::P4444_12, Profile::P400_10];
pub fn idc(self) -> u8 {
match self {
Self::P422_10 => 33,
Self::P422_12 => 44,
Self::P444_10 => 55,
Self::P444_12 => 66,
Self::P4444_10 => 77,
Self::P4444_12 => 88,
Self::P400_10 => 99,
}
}
pub fn from_idc(idc: u8) -> Option<Self> {
Self::ALL.into_iter().find(|p| p.idc() == idc)
}
pub fn name(self) -> &'static str {
match self {
Self::P422_10 => "APV 422-10",
Self::P422_12 => "APV 422-12",
Self::P444_10 => "APV 444-10",
Self::P444_12 => "APV 444-12",
Self::P4444_10 => "APV 4444-10",
Self::P4444_12 => "APV 4444-12",
Self::P400_10 => "APV 400-10",
}
}
pub fn short_name(self) -> &'static str {
match self {
Self::P422_10 => "422-10",
Self::P422_12 => "422-12",
Self::P444_10 => "444-10",
Self::P444_12 => "444-12",
Self::P4444_10 => "4444-10",
Self::P4444_12 => "4444-12",
Self::P400_10 => "400-10",
}
}
pub fn default_chroma(self) -> ChromaFormat {
match self {
Self::P422_10 | Self::P422_12 => ChromaFormat::Yuv422,
Self::P444_10 | Self::P444_12 => ChromaFormat::Yuv444,
Self::P4444_10 | Self::P4444_12 => ChromaFormat::Yuv4444,
Self::P400_10 => ChromaFormat::Monochrome,
}
}
pub fn default_bit_depth(self) -> u8 {
match self {
Self::P422_12 | Self::P444_12 | Self::P4444_12 => 12,
_ => 10,
}
}
/// Check whether `(chroma, bit_depth)` conforms to this profile per RFC 9924 §9.3.
pub fn supports(self, chroma: ChromaFormat, bit_depth: u8) -> bool {
let c = chroma.idc();
let b = bit_depth.saturating_sub(8);
match self {
Self::P422_10 => c == 2 && b == 2,
Self::P422_12 => c == 2 && (2..=4).contains(&b),
Self::P444_10 => (2..=3).contains(&c) && b == 2,
Self::P444_12 => (2..=3).contains(&c) && (2..=4).contains(&b),
Self::P4444_10 => (2..=4).contains(&c) && b == 2,
Self::P4444_12 => (2..=4).contains(&c) && (2..=4).contains(&b),
Self::P400_10 => c == 0 && b == 2,
}
}
/// Nominal target bytes per frame for `(width, height)`.
pub fn nominal_frame_bytes(self, width: u32, height: u32) -> u32 {
let bpp = match self {
Self::P400_10 => 1.5,
Self::P422_10 => 3.0,
Self::P422_12 => 3.8,
Self::P444_10 => 4.2,
Self::P444_12 => 5.0,
Self::P4444_10 => 5.2,
Self::P4444_12 => 6.2,
};
let bytes = ((width as f64) * (height as f64) * bpp / 8.0).round() as u32;
bytes.max(512)
}
/// Nominal data rate in Mbit/s at 1920x1080 29.97 fps.
pub fn nominal_mbps_1080p30(self) -> f64 {
(self.nominal_frame_bytes(1920, 1080) as f64) * 8.0 * 29.97 / 1e6
}
}
/// Human-readable profile name from `profile_idc` (e.g. `"APV 422-10"`).
pub fn profile_name(profile_idc: u8) -> String {
Profile::from_idc(profile_idc).map(|p| p.name().to_string()).unwrap_or_else(|| format!("APV (profile {profile_idc})"))
}
/// Colour description from `frame_header()` (ITU-T H.273 code points, RFC 9924 §5.3.5).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ColorInfo {
pub primaries: u8,
pub transfer: u8,
pub matrix: u8,
pub full_range: bool,
}
impl Default for ColorInfo {
/// Inferred values when `color_description_present_flag == 0` (RFC 9924 §5.3.5: 2, 2, 2, 0).
fn default() -> Self {
Self { primaries: 2, transfer: 2, matrix: 2, full_range: false }
}
}
impl ColorInfo {
pub const BT709: Self = Self { primaries: 1, transfer: 1, matrix: 1, full_range: false };
pub const BT2020_PQ: Self = Self { primaries: 9, transfer: 16, matrix: 9, full_range: false };
pub const BT2020_HLG: Self = Self { primaries: 9, transfer: 18, matrix: 9, full_range: false };
}
/// Mastering Display Color Volume metadata (`payloadType == 5`, RFC 9924 §8.2.3).
///
/// Chromaticities are in 0.16 fixed-point (1/65536), order `[R, G, B]`;
/// `max_luminance` is 24.8 fixed-point cd/m²; `min_luminance` is 18.14 fixed-point cd/m².
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct MasteringDisplay {
pub primaries: [(u16, u16); 3],
pub white_point: (u16, u16),
pub max_luminance: u32,
pub min_luminance: u32,
}
/// Content Light-Level Information metadata (`payloadType == 6`, RFC 9924 §8.2.4).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ContentLightLevel {
pub max_cll: u16,
pub max_fall: u16,
}
/// A decoded (or to-be-encoded) APV frame: planar `u16` samples, rows packed without padding.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Frame {
pub width: u32,
pub height: u32,
pub chroma: ChromaFormat,
/// Significant bits per sample (`10..=16`, or `8..=16` when rescaled via [`DecodeOptions`]).
pub bit_depth: u8,
pub y: Vec<u16>,
pub cb: Vec<u16>,
pub cr: Vec<u16>,
pub alpha: Option<Vec<u16>>,
pub color: ColorInfo,
pub profile_idc: u8,
pub level_idc: u8,
pub band_idc: u8,
pub mastering_display: Option<MasteringDisplay>,
pub content_light: Option<ContentLightLevel>,
}
impl Frame {
/// Allocate a black video-range frame.
pub fn new(width: u32, height: u32, chroma: ChromaFormat, bit_depth: u8, with_alpha: bool) -> Self {
let n = (width as usize) * (height as usize);
let cw = chroma.chroma_width(width) as usize;
let ch = chroma.chroma_height(height) as usize;
let cn = cw * ch;
let shift = bit_depth.saturating_sub(8) as u32;
let has_alpha = with_alpha || chroma == ChromaFormat::Yuv4444;
Self {
width,
height,
chroma,
bit_depth,
y: vec![(16u32 << shift) as u16; n],
cb: vec![(128u32 << shift) as u16; cn],
cr: vec![(128u32 << shift) as u16; cn],
alpha: has_alpha.then(|| vec![((1u32 << bit_depth) - 1) as u16; n]),
color: ColorInfo::BT709,
profile_idc: Profile::P422_10.idc(),
level_idc: 90,
band_idc: 2,
mastering_display: None,
content_light: None,
}
}
pub fn chroma_width(&self) -> u32 {
self.chroma.chroma_width(self.width)
}
pub fn chroma_height(&self) -> u32 {
self.chroma.chroma_height(self.height)
}
}
+59
View File
@@ -0,0 +1,59 @@
//! RFC 9924 tables: zig-zag scan, 8x8 transform matrix, quantization level scales, and level limits.
/// 8x8 zig-zag scan order (`ScanOrder[sPos] = yC * 8 + xC`), derived from RFC 9924 §4.4.1 Figure 5.
pub const ZIGZAG_8X8: [u8; 64] = [
0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29,
22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63,
];
/// 8x8 transform matrix (`transMatrix` in RFC 9924 §6.3.2.3 Figure 25).
pub const TRANS_MATRIX: [[i32; 8]; 8] = [
[64, 64, 64, 64, 64, 64, 64, 64],
[89, 75, 50, 18, -18, -50, -75, -89],
[84, 35, -35, -84, -84, -35, 35, 84],
[75, -18, -89, -50, 50, 89, 18, -75],
[64, -64, -64, 64, 64, -64, -64, 64],
[50, -89, 18, 75, -75, -18, 89, -50],
[35, -84, 84, -35, -35, 84, -84, 35],
[18, -50, 75, -89, 89, -75, 50, -18],
];
/// Quantization scaling list `levelScale[k]` for `k = qP % 6` (RFC 9924 §6.3.1).
pub const LEVEL_SCALE: [i32; 6] = [40, 45, 51, 57, 64, 71];
/// Default flat quantization matrix value when `use_q_matrix == 0` (RFC 9924 §5.3.7).
pub const DEFAULT_Q_MATRIX_VAL: u8 = 16;
/// General level limits (`level_idc`, max luma sample rate, and max coded data rate in Mbit/s per band)
/// from RFC 9924 §9.4.2 Table 4.
pub const LEVEL_LIMITS: [(u8, u64, [u32; 4]); 14] = [
(30, 3_041_280, [8, 11, 15, 23]),
(33, 6_082_560, [16, 21, 30, 45]),
(60, 15_667_200, [39, 54, 76, 114]),
(63, 31_334_400, [78, 108, 152, 227]),
(90, 66_846_720, [114, 159, 222, 333]),
(93, 133_693_440, [227, 317, 444, 666]),
(120, 265_420_800, [455, 637, 892, 1_338]),
(123, 530_841_600, [910, 1_274, 1_784, 2_675]),
(150, 1_061_683_200, [1_820, 2_548, 3_567, 5_350]),
(153, 2_123_366_400, [3_639, 5_095, 7_133, 10_699]),
(180, 4_777_574_400, [7_278, 10_189, 14_265, 21_397]),
(183, 8_493_465_600, [14_556, 20_378, 28_529, 42_793]),
(210, 16_986_931_200, [29_111, 40_756, 57_058, 85_586]),
(213, 33_973_862_400, [58_222, 81_511, 114_115, 171_172]),
];
/// Choose the lowest conforming `(level_idc, band_idc)` for a luma sample rate and bitrate (in kbps).
pub fn select_level_and_band(luma_samples_per_sec: u64, kbps: u32) -> (u8, u8) {
let mbps = kbps.div_ceil(1000);
for &(level_idc, max_samples, bands) in &LEVEL_LIMITS {
if luma_samples_per_sec <= max_samples {
for (band_idc, &max_mbps) in bands.iter().enumerate() {
if mbps <= max_mbps {
return (level_idc, band_idc as u8);
}
}
}
}
(213, 3)
}
+136
View File
@@ -0,0 +1,136 @@
//! Robustness: mutated, truncated, spliced, and random bitstreams must never panic (errors are fine).
use std::panic::{AssertUnwindSafe, catch_unwind};
use filmcraft_apv::*;
struct Rng(u64);
impl Rng {
fn next(&mut self) -> u64 {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
self.0
}
fn below(&mut self, n: usize) -> usize {
(self.next() % n.max(1) as u64) as usize
}
}
fn seeds() -> Vec<Vec<u8>> {
let mut v = Vec::new();
for (p, w, h) in
[(Profile::P422_10, 64u32, 48u32), (Profile::P422_12, 70, 38), (Profile::P444_10, 48, 32), (Profile::P4444_10, 64, 32), (Profile::P400_10, 32, 32)]
{
let chroma = p.default_chroma();
let depth = p.default_bit_depth();
let mut f = Frame::new(w, h, chroma, depth, chroma == ChromaFormat::Yuv4444);
for (i, s) in f.y.iter_mut().enumerate() {
*s = (64 + (i * 37) % 800) as u16;
}
if let Some(a) = f.alpha.as_mut() {
for (i, s) in a.iter_mut().enumerate() {
*s = ((i * 19) % 1024) as u16;
}
}
let mut cfg = EncoderConfig::new(p, w, h);
cfg.qp = Some(16);
let mut enc = Encoder::with_config(cfg).expect("seed encoder");
v.push(enc.encode(&f).expect("seed encode"));
v.push(enc.encode_raw_au(&f).expect("seed encode_raw_au"));
}
v
}
#[test]
fn mutated_streams_never_panic() {
let seeds = seeds();
for s in &seeds {
decode_frame(s).expect("seed decodes");
}
let mut rng = Rng(0x9e3779b97f4a7c15);
let mut decoded_ok = 0usize;
let iters = 3000usize;
for i in 0..iters {
let mut d = seeds[i % seeds.len()].clone();
match rng.below(6) {
0 => {
// Bit flips
for _ in 0..1 + rng.below(8) {
let p = rng.below(d.len());
d[p] ^= 1 << rng.below(8);
}
}
1 => {
// Random byte overwrites
for _ in 0..1 + rng.below(4) {
let p = rng.below(d.len());
d[p] = rng.next() as u8;
}
}
2 => {
// Truncation
let n = rng.below(d.len());
d.truncate(n);
}
3 => {
// Corrupt header fields
if d.len() > 8 {
let p = 4 + rng.below(24.min(d.len() - 4));
d[p] = rng.next() as u8;
}
}
4 => {
// Corrupt tile payload region
let start = 24.min(d.len().saturating_sub(1));
let off = start + rng.below(d.len().saturating_sub(start).max(1));
for b in d.iter_mut().skip(off).take(1 + rng.below(48)) {
*b = rng.next() as u8;
}
}
_ => {
// Splice random bytes
let p = rng.below(d.len());
let extra: Vec<u8> = (0..1 + rng.below(16)).map(|_| rng.next() as u8).collect();
d.splice(p..p, extra);
}
}
let res = catch_unwind(AssertUnwindSafe(|| {
for depth in [None, Some(8), Some(16)] {
let opts = DecodeOptions { bit_depth: depth, threads: i % 2 == 0 };
if let Ok(f) = decode_frame_with(&d, &opts) {
decoded_ok += 1;
assert_eq!(f.y.len(), (f.width as usize) * (f.height as usize));
}
}
let _ = probe(&d);
let _ = split_raw_bitstream(&d);
}));
assert!(res.is_ok(), "panic on mutated stream iteration {i}");
}
println!("{decoded_ok} of {} mutated decodes succeeded", iters * 3);
}
#[test]
fn random_bytes_never_panic() {
let mut rng = Rng(123456789);
for i in 0..2000 {
let n = rng.below(400);
let mut d: Vec<u8> = (0..n).map(|_| rng.next() as u8).collect();
if d.len() >= 8 && rng.below(2) == 0 {
d[..4].copy_from_slice(b"aPv1");
} else if d.len() >= 12 && rng.below(2) == 0 {
let au_sz = (n - 4) as u32;
d[..4].copy_from_slice(&au_sz.to_be_bytes());
d[4..8].copy_from_slice(b"aPv1");
}
let res = catch_unwind(AssertUnwindSafe(|| {
let _ = decode_frame(&d);
let _ = probe(&d);
let _ = split_raw_bitstream(&d);
}));
assert!(res.is_ok(), "panic on random bytes iteration {i}");
}
}
+230
View File
@@ -0,0 +1,230 @@
//! Conformance, bit-exactness, and quality tests against ffmpeg's APV decoder (external oracle).
use std::path::{Path, PathBuf};
use std::process::Command;
use filmcraft_apv::{
ChromaFormat, ContentLightLevel, DecodeOptions, Encoder, EncoderConfig, Frame, MasteringDisplay, Profile, decode_frame, decode_frame_with, probe,
};
fn ffmpeg() -> Option<PathBuf> {
filmcraft_testkit::ffmpeg_or_skip("apv oracle")
}
fn fixture_dir() -> PathBuf {
filmcraft_testkit::fixtures_dir("apv")
}
fn native_pix_fmt(profile: Profile) -> &'static str {
match profile {
Profile::P422_10 => "yuv422p10le",
Profile::P422_12 => "yuv422p12le",
Profile::P444_10 => "yuv444p10le",
Profile::P444_12 => "yuv444p12le",
Profile::P4444_10 => "yuva444p10le",
Profile::P4444_12 => "yuva444p12le",
Profile::P400_10 => "gray10le",
}
}
/// Decode a raw `.apv` file with ffmpeg (`-v error -xerror`) to planar `u16` samples.
fn ffmpeg_decode_raw(ff: &Path, apv_path: &Path, pix_fmt: &str) -> (Vec<u16>, String) {
let out = Command::new(ff)
.args(["-hide_banner", "-v", "error", "-xerror", "-f", "apv", "-i"])
.arg(apv_path)
.args(["-f", "rawvideo", "-pix_fmt", pix_fmt, "-"])
.output()
.expect("run ffmpeg");
let stderr = String::from_utf8_lossy(&out.stderr).into_owned();
assert!(out.status.success(), "ffmpeg failed on {:?}: {}", apv_path, stderr);
let samples = out.stdout.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes([c[0], c[1]])).collect();
(samples, stderr)
}
fn synthetic_frame(profile: Profile, w: u32, h: u32) -> Frame {
let chroma = profile.default_chroma();
let depth = profile.default_bit_depth();
let mut f = Frame::new(w, h, chroma, depth, chroma == ChromaFormat::Yuv4444);
let max_v = (1u32 << depth) - 1;
let lo = 16u32 << (depth - 8);
let hi = 235u32 << (depth - 8);
let span = hi - lo;
for y in 0..h {
for x in 0..w {
// Mix smooth gradients, diagonal edges, and high-frequency patterns
let grad = (x * 7 + y * 13) % span;
let checker = if ((x / 3) ^ (y / 5)) & 1 == 0 { 40 << (depth - 10) } else { 0 };
f.y[(y * w + x) as usize] = (lo + (grad + checker) % span).min(max_v) as u16;
}
}
let cw = f.chroma_width();
let ch = f.chroma_height();
for y in 0..ch {
for x in 0..cw {
let u = lo + ((x * 11 + y * 5 + 100) % span);
let v = lo + ((x * 3 + y * 17 + 300) % span);
f.cb[(y * cw + x) as usize] = u.min(max_v) as u16;
f.cr[(y * cw + x) as usize] = v.min(max_v) as u16;
}
}
if let Some(a) = f.alpha.as_mut() {
for y in 0..h {
for x in 0..w {
let dx = x as i32 - (w as i32) / 2;
let dy = y as i32 - (h as i32) / 2;
a[(y * w + x) as usize] =
if dx * dx + dy * dy < ((w.min(h) as i32) / 3).pow(2) { max_v as u16 } else { ((x * 19 + y * 23) % (max_v + 1)) as u16 };
}
}
}
f
}
fn flatten_frame(f: &Frame) -> Vec<u16> {
let mut v = Vec::new();
v.extend_from_slice(&f.y);
v.extend_from_slice(&f.cb);
v.extend_from_slice(&f.cr);
if let Some(a) = &f.alpha {
v.extend_from_slice(a);
}
v
}
fn psnr(a: &[u16], b: &[u16], peak: f64) -> f64 {
if a.is_empty() {
return 99.0;
}
let mse: f64 = a.iter().zip(b).map(|(&x, &y)| (x as f64 - y as f64).powi(2)).sum::<f64>() / a.len() as f64;
if mse == 0.0 { 99.0 } else { 10.0 * (peak * peak / mse).log10() }
}
#[test]
fn all_profiles_bit_exact_with_ffmpeg() {
let Some(ff) = ffmpeg() else { return };
let dir = fixture_dir();
for profile in Profile::ALL {
let (w, h) = (320u32, 192u32);
let src = synthetic_frame(profile, w, h);
let mut cfg = EncoderConfig::new(profile, w, h);
cfg.qp = Some(12);
let mut enc = Encoder::with_config(cfg).expect("encoder init");
let raw_au = enc.encode_raw_au(&src).expect("encode_raw_au");
let apv_path = dir.join(format!("oracle_{}.apv", profile.short_name()));
std::fs::write(&apv_path, &raw_au).expect("write .apv");
let (ff_samples, stderr) = ffmpeg_decode_raw(&ff, &apv_path, native_pix_fmt(profile));
assert!(stderr.trim().is_empty(), "{profile:?}: ffmpeg stderr: {stderr}");
let ours = decode_frame(&raw_au).expect("our decode");
let our_samples = flatten_frame(&ours);
assert_eq!(our_samples.len(), ff_samples.len(), "{profile:?}: sample count mismatch");
let max_diff = our_samples.iter().zip(&ff_samples).map(|(&a, &b)| (a as i32 - b as i32).unsigned_abs()).max().unwrap_or(0);
assert_eq!(max_diff, 0, "{profile:?}: our decoder must be 100% bit-exact with ffmpeg (max_diff={max_diff})");
let peak = ((1u32 << profile.default_bit_depth()) - 1) as f64;
let y_psnr = psnr(&ours.y, &src.y, peak);
assert!(y_psnr > 45.0, "{profile:?}: expected high PSNR at qp=12, got {y_psnr:.2} dB");
}
}
#[test]
fn odd_dimensions_and_multi_tile_bit_exact_with_ffmpeg() {
let Some(ff) = ffmpeg() else { return };
let dir = fixture_dir();
for (profile, w, h) in [
(Profile::P422_10, 640u32, 360u32),
(Profile::P422_10, 334, 202),
(Profile::P444_10, 333, 201),
(Profile::P4444_12, 512, 288),
(Profile::P400_10, 70, 38),
] {
let mut src = synthetic_frame(profile, w, h);
src.mastering_display = Some(MasteringDisplay {
primaries: [(46400, 19136), (11141, 52232), (8585, 3015)],
white_point: (20493, 21561),
max_luminance: 1000 << 8,
min_luminance: 1,
});
src.content_light = Some(ContentLightLevel { max_cll: 1000, max_fall: 400 });
let mut enc = Encoder::new(profile, w, h).expect("encoder init");
let raw_au = enc.encode_raw_au(&src).expect("encode");
let apv_path = dir.join(format!("oracle_geom_{}_{w}x{h}.apv", profile.short_name()));
std::fs::write(&apv_path, &raw_au).expect("write .apv");
let (ff_samples, stderr) = ffmpeg_decode_raw(&ff, &apv_path, native_pix_fmt(profile));
assert!(stderr.trim().is_empty(), "{profile:?} {w}x{h}: {stderr}");
let hdr = probe(&raw_au).expect("probe");
assert_eq!((hdr.width, hdr.height), (w, h));
let ours = decode_frame(&raw_au).expect("decode");
assert_eq!(ours.mastering_display, src.mastering_display);
assert_eq!(ours.content_light, src.content_light);
let our_samples = flatten_frame(&ours);
assert_eq!(our_samples, ff_samples, "{profile:?} {w}x{h}: bit-exact match with ffmpeg failed");
// Also verify single-threaded decode produces identical output
let ours_st = decode_frame_with(&raw_au, &DecodeOptions { bit_depth: None, threads: false }).expect("decode single-threaded");
assert_eq!(ours, ours_st);
}
}
#[test]
fn custom_q_matrix_and_fh_tile_sizes_bit_exact_with_ffmpeg() {
let Some(ff) = ffmpeg() else { return };
let dir = fixture_dir();
let profile = Profile::P444_12;
let (w, h) = (512u32, 256u32);
let src = synthetic_frame(profile, w, h);
let mut q_matrix = [[16u8; 64]; 4];
for (c, qm) in q_matrix.iter_mut().enumerate() {
for y in 0..8 {
for x in 0..8 {
// Intentionally asymmetric (x != y weight) to verify exact (x, y) matrix orientation
qm[y * 8 + x] = (10 + c * 3 + y * 5 + x * 2) as u8;
}
}
}
let mut cfg = EncoderConfig::new(profile, w, h);
cfg.qp = Some(18);
cfg.q_matrix = Some(q_matrix);
cfg.write_tile_sizes_in_fh = true;
cfg.tile_width_in_mbs = 16;
cfg.tile_height_in_mbs = 8;
let mut enc = Encoder::with_config(cfg).expect("encoder init");
let raw_au = enc.encode_raw_au(&src).expect("encode");
let apv_path = dir.join("oracle_custom_qmat_444-12.apv");
std::fs::write(&apv_path, &raw_au).expect("write .apv");
let (ff_samples, stderr) = ffmpeg_decode_raw(&ff, &apv_path, native_pix_fmt(profile));
assert!(stderr.trim().is_empty(), "ffmpeg stderr: {stderr}");
let hdr = probe(&raw_au).expect("probe");
assert!(hdr.use_q_matrix);
assert!(hdr.tile_sizes_in_fh.is_some());
assert_eq!(hdr.num_tiles(), 4);
let ours = decode_frame(&raw_au).expect("decode");
let our_samples = flatten_frame(&ours);
assert_eq!(our_samples, ff_samples, "asymmetric q_matrix decode must be bit-exact with ffmpeg");
// Verify 8-bit and 16-bit rescaled output
let d8 = decode_frame_with(&raw_au, &DecodeOptions { bit_depth: Some(8), threads: true }).expect("decode 8-bit");
assert_eq!(d8.bit_depth, 8);
assert!(d8.y.iter().all(|&s| s <= 255));
let d16 = decode_frame_with(&raw_au, &DecodeOptions { bit_depth: Some(16), threads: true }).expect("decode 16-bit");
assert_eq!(d16.bit_depth, 16);
}
+2
View File
@@ -7,6 +7,7 @@
//! engine and UI can build controls generically.
//! * [`biquad`] — RBJ-cookbook biquads (TDF-II) with analytic magnitude response.
//! * [`sync`] — offset between two recordings of one event (GCC-PHAT, sample-accurate).
//! * [`resample`] — streaming, block-invariant rate conversion for playback on a device at another rate.
//! * [`channels`] — channel layouts, ITU-R BS.775 up/downmix, 5.1 mixdown types, the 5.1 panner.
//!
//! Conventions: audio is **planar f32** (`&mut [&mut [f32]]`, one slice per channel, all the same
@@ -27,6 +28,7 @@ pub mod fft;
pub mod loudness;
pub mod oversample;
pub mod remix;
pub mod resample;
mod smooth;
pub mod sync;
+170
View File
@@ -0,0 +1,170 @@
//! Streaming sample-rate conversion for playback, when the output device runs at another rate
//! than the sequence (a 44.1 kHz device playing a 48 kHz sequence).
//!
//! Every output sample's source position comes from its absolute output frame, as an exact
//! rational (`frame × from / to`), and is linearly interpolated, so the output is identical however
//! the stream is cut into blocks: no phase jump at block boundaries. Source frames are pulled in
//! contiguous, non-overlapping spans, so whatever produces them (the mixer, with its effect state)
//! sees one continuous stream. Output lags the source by one source sample (≈21 µs at 48 kHz),
//! which is what lets each block interpolate without reading ahead.
/// Converts a planar stream from `from` Hz to `to` Hz, block by block.
#[derive(Debug, Clone)]
pub struct StreamResampler {
from: u32,
to: u32,
/// Source frames `[held_start, held_start + held[c].len())` kept from the last pull.
held_start: i64,
held: Vec<Vec<f32>>,
/// The output frame the next block is expected to start at (contiguous playback).
next_out: Option<i64>,
}
impl StreamResampler {
/// Rates of zero are treated as 1 Hz rather than dividing by zero.
pub fn new(from: u32, to: u32) -> Self {
Self { from: from.max(1), to: to.max(1), held_start: 0, held: Vec::new(), next_out: None }
}
pub fn rates(&self) -> (u32, u32) {
(self.from, self.to)
}
/// The source frame whose sample lands at (or just before) output frame `out`.
fn source_index(&self, out: i64) -> (i64, f32) {
let p = out as i128 * self.from as i128;
let to = self.to as i128;
(p.div_euclid(to) as i64, (p.rem_euclid(to) as f64 / to as f64) as f32)
}
/// Output frames `[out, out + n)`, planar. `pull(start, frames)` returns source frames
/// `[start, start + frames)`, planar (missing samples read as silence). A block that does not
/// continue the previous one (a seek) starts the stream afresh.
pub fn process(&mut self, out: i64, n: usize, mut pull: impl FnMut(i64, usize) -> Vec<Vec<f32>>) -> Vec<Vec<f32>> {
if n == 0 {
return vec![Vec::new(); self.held.len().max(1)];
}
let (first, _) = self.source_index(out);
let (last, _) = self.source_index(out.saturating_add(n as i64 - 1));
// interpolation reads source frames first - 1 ..= last
if self.next_out != Some(out) || self.held.is_empty() {
self.held_start = first - 1;
self.held.clear();
}
let held_end = self.held_start + self.held.first().map_or(0, Vec::len) as i64;
if last + 1 > held_end {
let want = (last + 1 - held_end) as usize;
let got = pull(held_end, want);
if self.held.is_empty() {
self.held = vec![Vec::new(); got.len().max(1)];
}
for (c, h) in self.held.iter_mut().enumerate() {
let src = got.get(c).map(Vec::as_slice).unwrap_or_default();
h.extend((0..want).map(|i| src.get(i).copied().unwrap_or(0.0)));
}
}
let mut dst = vec![vec![0.0f32; n]; self.held.len()];
for (i, frame) in (out..).take(n).enumerate() {
let (s, frac) = self.source_index(frame);
// held starts at first - 1, so the earlier frame is always held
let k = usize::try_from(s - self.held_start).unwrap_or(0);
for (d, h) in dst.iter_mut().zip(&self.held) {
let a = k.checked_sub(1).and_then(|j| h.get(j)).copied().unwrap_or(0.0);
let b = h.get(k).copied().unwrap_or(0.0);
if let Some(x) = d.get_mut(i) {
*x = a + (b - a) * frac;
}
}
}
// keep what the next block can still read: from its first frame - 1 on
let (next_first, _) = self.source_index(out.saturating_add(n as i64));
let drop = (next_first - 1 - self.held_start).clamp(0, self.held.first().map_or(0, Vec::len) as i64) as usize;
for h in &mut self.held {
h.drain(..drop);
}
self.held_start += drop as i64;
self.next_out = Some(out.saturating_add(n as i64));
dst
}
}
#[cfg(test)]
mod tests {
use super::*;
/// A sine at `hz`, sampled at `rate`, from absolute frame `start`; logs every pull.
fn sine(hz: f64, rate: u32, pulls: &mut Vec<(i64, usize)>) -> impl FnMut(i64, usize) -> Vec<Vec<f32>> + '_ {
move |start, frames| {
pulls.push((start, frames));
let ch: Vec<f32> = (0..frames).map(|i| (2.0 * std::f64::consts::PI * hz * (start + i as i64) as f64 / rate as f64).sin() as f32).collect();
vec![ch.clone(), ch]
}
}
fn convert(from: u32, to: u32, blocks: &[usize], total: usize) -> (Vec<f32>, Vec<(i64, usize)>) {
let mut r = StreamResampler::new(from, to);
let mut pulls = Vec::new();
let mut out = Vec::new();
let mut pos = 0i64;
let mut k = 0;
while (pos as usize) < total {
let n = blocks[k % blocks.len()].min(total - pos as usize);
let b = r.process(pos, n, sine(1000.0, from, &mut pulls));
assert_eq!(b.len(), 2);
assert!(b.iter().all(|c| c.len() == n));
out.extend_from_slice(&b[0]);
pos += n as i64;
k += 1;
}
(out, pulls)
}
#[test]
fn output_is_the_same_however_the_stream_is_cut() {
for (from, to) in [(48_000, 44_100), (44_100, 48_000), (48_000, 96_000), (96_000, 48_000)] {
let (whole, _) = convert(from, to, &[20_000], 20_000);
for blocks in [&[512][..], &[333], &[1, 7, 512, 64]] {
let (cut, _) = convert(from, to, blocks, 20_000);
assert_eq!(cut, whole, "{from}→{to} in blocks {blocks:?}");
}
}
}
#[test]
fn a_tone_converts_to_the_same_tone() {
// 1 kHz at 48 kHz played on a 44.1 kHz device: within linear interpolation's error of the
// ideal tone, one source sample late
let (from, to) = (48_000u32, 44_100u32);
let (out, _) = convert(from, to, &[512], 20_000);
for (o, x) in out.iter().enumerate().skip(2) {
let t = o as f64 / to as f64 - 1.0 / from as f64;
let want = (2.0 * std::f64::consts::PI * 1000.0 * t).sin() as f32;
assert!((x - want).abs() < 3e-3, "frame {o}: {x} vs {want}");
}
}
#[test]
fn the_source_is_pulled_as_one_continuous_stream() {
for (from, to) in [(48_000, 44_100), (44_100, 48_000)] {
let (_, pulls) = convert(from, to, &[512, 333], 20_000);
for w in pulls.windows(2) {
assert_eq!(w[0].0 + w[0].1 as i64, w[1].0, "{from}→{to}: {:?} then {:?}", w[0], w[1]);
}
}
}
#[test]
fn a_seek_starts_afresh_and_hostile_input_stays_finite() {
let mut r = StreamResampler::new(48_000, 44_100);
let mut pulls = Vec::new();
let _ = r.process(0, 512, sine(1000.0, 48_000, &mut pulls));
let _ = r.process(1_000_000, 512, sine(1000.0, 48_000, &mut pulls));
assert_eq!(pulls.last().map(|p| p.0), Some(1_000_000 * 48_000 / 44_100 - 1));
// a mixer returning too few channels and samples, and zero rates
let mut r = StreamResampler::new(0, 0);
let b = r.process(5, 64, |_, _| vec![vec![1.0; 3]]);
assert_eq!(b.len(), 1);
assert!(b[0].iter().all(|x| x.is_finite()));
assert!(r.process(0, 0, |_, _| Vec::new()).iter().all(Vec::is_empty));
}
}
+111
View File
@@ -10,6 +10,9 @@ use tokio::sync::Mutex;
use crate::AutomationError;
/// How often a blocking export's app job is polled.
const JOB_POLL: Duration = Duration::from_millis(250);
type Conn = (BufReader<tokio::net::tcp::OwnedReadHalf>, tokio::net::tcp::OwnedWriteHalf);
pub struct BridgeClient {
@@ -29,6 +32,40 @@ impl BridgeClient {
Ok(Self { addr, conn: Mutex::new(None), next_id: AtomicU64::new(1) })
}
/// Run engine command `id` in the app. A blocking export (`file.exportMedia` with
/// `wait: true`, see [`crate::long_job::LONG_COMMANDS`]) is started as an app job and polled
/// here until it finishes, so the app keeps repainting (its status bar shows the progress) and
/// answering other requests, and no request waits on the control server's 60 s reply limit
/// (#91, #92). The reply is the same as a blocking export's: `{job, path, result}`, or the
/// export's error.
pub async fn execute(&self, id: &str, mut params: Value) -> Result<Value, AutomationError> {
if !crate::long_job::is_long(id, &params) {
return self.call("engine.execute", json!({"command": id, "params": params})).await;
}
if let Some(p) = params.as_object_mut() {
p.insert("wait".into(), json!(false));
}
let mut start = self.call("engine.execute", json!({"command": id, "params": params})).await?;
let Some(job) = start.get("job").and_then(Value::as_u64) else { return Ok(start) };
let result = loop {
tokio::time::sleep(JOB_POLL).await;
let jobs = self.call("engine.execute", json!({"command": "jobs.list", "params": {}})).await?;
let Some(j) = jobs.as_array().and_then(|a| a.iter().find(|j| j["id"].as_u64() == Some(job))).cloned() else {
break Value::Null;
};
if j["finished"].as_bool() == Some(true) {
break j["result"].clone();
}
};
if let Some(e) = result.get("error").and_then(Value::as_str) {
return Err(AutomationError::App(format!("export failed: {e}")));
}
if let Some(o) = start.as_object_mut() {
o.insert("result".into(), result);
}
Ok(start)
}
/// Call a control method; returns `result` or the app's error.
pub async fn call(&self, method: &str, params: Value) -> Result<Value, AutomationError> {
let mut guard = self.conn.lock().await;
@@ -74,3 +111,77 @@ impl BridgeClient {
Err(AutomationError::Bridge("unreachable".into()))
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
use tokio::net::TcpListener;
/// A stand-in for the app's control server: the export starts job 7, which `jobs.list` reports
/// running twice and then finished with `result`. Every request is recorded.
async fn fake_app(result: Value) -> (String, Arc<Mutex<Vec<Value>>>) {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap().to_string();
let seen = Arc::new(Mutex::new(Vec::new()));
let log = seen.clone();
tokio::spawn(async move {
let (s, _) = listener.accept().await.unwrap();
let (r, mut w) = s.into_split();
let mut lines = BufReader::new(r).lines();
let mut polls = 0;
while let Ok(Some(line)) = lines.next_line().await {
let req: Value = serde_json::from_str(&line).unwrap();
log.lock().await.push(req.clone());
let reply = match req["params"]["command"].as_str() {
Some("file.exportMedia") => json!({"job": 7, "path": "/tmp/out.mov"}),
Some("jobs.list") => {
polls += 1;
let finished = polls >= 3;
json!([{"id": 7, "finished": finished, "result": if finished { result.clone() } else { Value::Null }}])
}
_ => json!(null),
};
let line = format!("{}\n", json!({"id": req["id"], "ok": true, "result": reply}));
w.write_all(line.as_bytes()).await.unwrap();
}
});
(addr, seen)
}
/// A blocking bridge export runs as an app job (#91, #92): the app never sees `wait: true` (it
/// would encode on its UI thread and the reply would time out after 60 s), and the caller still
/// gets the finished result.
#[tokio::test]
async fn a_blocking_export_is_polled_as_a_job() {
let (addr, seen) = fake_app(json!({"frames": 642})).await;
let b = BridgeClient::new(addr).unwrap();
let r = b.execute("file.exportMedia", json!({"path": "/tmp/out.mov", "wait": true})).await.unwrap();
assert_eq!(r, json!({"job": 7, "path": "/tmp/out.mov", "result": {"frames": 642}}));
let seen = seen.lock().await;
assert_eq!(seen[0]["params"]["params"]["wait"], json!(false));
assert!(seen.iter().all(|q| q["params"]["params"]["wait"] != json!(true)));
assert_eq!(seen.iter().filter(|q| q["params"]["command"] == "file.exportMedia").count(), 1, "started once");
assert_eq!(seen.iter().filter(|q| q["params"]["command"] == "jobs.list").count(), 3);
}
#[tokio::test]
async fn a_failed_blocking_export_is_an_error() {
let (addr, _) = fake_app(json!({"error": "encode: disk full"})).await;
let b = BridgeClient::new(addr).unwrap();
let e = b.execute("file.exportMedia", json!({"path": "/tmp/out.mov", "wait": true})).await.unwrap_err();
assert!(e.to_string().contains("export failed: encode: disk full"), "{e}");
}
/// Everything else is forwarded unchanged.
#[tokio::test]
async fn other_commands_are_forwarded() {
let (addr, seen) = fake_app(Value::Null).await;
let b = BridgeClient::new(addr).unwrap();
b.execute("file.exportMedia", json!({"path": "/tmp/out.mov"})).await.unwrap();
b.execute("sequence.inspect", json!({})).await.unwrap();
let seen = seen.lock().await;
assert_eq!(seen.len(), 2);
assert_eq!(seen[1]["params"]["command"], "sequence.inspect");
}
}
+1
View File
@@ -11,6 +11,7 @@
#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))]
pub mod bridge;
pub mod long_job;
pub mod server;
pub use bridge::BridgeClient;
+183
View File
@@ -0,0 +1,183 @@
//! Long exports over MCP (docs/agents.md § Long exports): `file.exportMedia` with `wait: true`
//! runs as a background engine job; the server reports its progress as MCP
//! `notifications/progress` (when the request carried a `progressToken`) and stops it on
//! `notifications/cancelled`, deleting the partial output. The session lock is only held for
//! short polls, so other requests are answered while the export runs.
use std::path::Path;
use std::time::{Duration, SystemTime};
use rmcp::RoleServer;
use rmcp::model::{CallToolResult, ContentBlock as Content, ProgressNotificationParam, ProgressToken};
use rmcp::service::{Peer, RequestContext};
use serde_json::{Value, json};
use crate::server::FilmcraftMcp;
/// Engine commands that block until a render is written when called with `wait: true`.
pub const LONG_COMMANDS: &[&str] = &["file.exportMedia"];
/// How often the job is polled (and at most how often progress is reported).
const POLL: Duration = Duration::from_millis(100);
/// Whether `command_run {id, params}` is a long call this module runs.
pub fn is_long(id: &str, params: &Value) -> bool {
LONG_COMMANDS.contains(&id) && params.get("wait").and_then(Value::as_bool) == Some(true)
}
/// Sends `notifications/progress` for one request; progress only ever increases.
struct Reporter {
peer: Peer<RoleServer>,
token: Option<ProgressToken>,
last: f64,
}
impl Reporter {
async fn report(&mut self, done: f64, total: f64, message: &str) {
let Some(token) = self.token.clone() else { return };
if total <= 0.0 || done <= self.last {
return;
}
self.last = done;
let mut p = ProgressNotificationParam::new(token, done).with_total(total);
if !message.is_empty() {
p = p.with_message(message);
}
let _ = self.peer.notify_progress(p).await;
}
}
impl FilmcraftMcp {
/// Run `id` (a [`LONG_COMMANDS`] entry, `wait: true`) as a job, reporting progress and
/// honouring cancellation.
pub(crate) async fn run_long(&self, id: &str, mut params: Value, context: &RequestContext<RoleServer>) -> CallToolResult {
let started = SystemTime::now();
if let Some(p) = params.as_object_mut() {
p.insert("wait".into(), json!(false));
}
let start = match self.run(id, params).await {
Ok(v) => v,
Err(e) => return CallToolResult::error(vec![Content::text(e.to_string())]),
};
let Some(job) = start.get("job").and_then(Value::as_u64) else {
return CallToolResult::error(vec![Content::text(format!("{id} started no job: {start}"))]);
};
let path = start.get("path").and_then(Value::as_str).unwrap_or_default().to_string();
let mut rep = Reporter { peer: context.peer.clone(), token: context.meta.get_progress_token(), last: 0.0 };
loop {
let state = self.job_state(job).await;
let finished = state.as_ref().is_none_or(|j| j["finished"].as_bool() == Some(true));
if let Some(j) = &state {
let (done, total) = (j["done"].as_f64().unwrap_or(0.0), j["total"].as_f64().unwrap_or(0.0));
rep.report(done, total, j["status"].as_str().unwrap_or_default()).await;
}
if finished {
let result = state.map(|j| j["result"].clone()).unwrap_or(Value::Null);
if let Some(e) = result.get("error").and_then(Value::as_str) {
return CallToolResult::error(vec![Content::text(format!("export failed: {e}"))]);
}
let mut out = start;
if let Some(o) = out.as_object_mut() {
o.insert("result".into(), result);
}
return CallToolResult::success(vec![Content::text(serde_json::to_string_pretty(&out).unwrap_or_default())]);
}
tokio::select! {
_ = context.ct.cancelled() => break,
_ = tokio::time::sleep(POLL) => {}
}
}
// Cancelled: stop the encode at the next batch, wait for the worker, delete the partial file.
let _ = self.run("jobs.cancel", json!({"job": job})).await;
for _ in 0..600 {
if self.job_state(job).await.is_none_or(|j| j["finished"].as_bool() == Some(true)) {
break;
}
tokio::time::sleep(POLL).await;
}
remove_partial(&path, started);
CallToolResult::error(vec![Content::text("cancelled")])
}
/// The job's `jobs.list` entry.
async fn job_state(&self, job: u64) -> Option<Value> {
let jobs = self.run("jobs.list", json!({})).await.ok()?;
jobs.as_array()?.iter().find(|j| j["id"].as_u64() == Some(job)).cloned()
}
}
/// Delete what an interrupted export wrote, and nothing else: the output file itself, the numbered
/// stills of an image sequence (`<stem><digits>.<same extension>`) and the caption sidecar
/// (`<stem>.srt` / `<stem>.vtt`), each only if it was written since `since`. Other files that
/// merely share the name's stem (`<stem>.aep`, `<stem>2.psd`, …) are never touched, even when they
/// were saved during the export.
pub fn remove_partial(path: &str, since: SystemTime) {
let p = Path::new(path);
let (Some(dir), Some(stem), Some(file)) = (p.parent(), p.file_stem().and_then(|s| s.to_str()), p.file_name().and_then(|s| s.to_str())) else {
return;
};
let ext = p.extension().and_then(|s| s.to_str()).unwrap_or_default();
let dir = if dir.as_os_str().is_empty() { Path::new(".") } else { dir };
let Ok(entries) = std::fs::read_dir(dir) else { return };
// file times are coarser than the clock
let since = since.checked_sub(Duration::from_secs(1)).unwrap_or(since);
for e in entries.flatten() {
let name = e.file_name();
let Some(name) = name.to_str() else { continue };
if is_export_output(name, file, stem, ext) && e.metadata().is_ok_and(|m| m.is_file() && m.modified().is_ok_and(|t| t >= since)) {
let _ = std::fs::remove_file(e.path());
}
}
}
/// Whether `name` is a file an export to `file` (`stem` + `.ext`) writes.
fn is_export_output(name: &str, file: &str, stem: &str, ext: &str) -> bool {
if name == file {
return true;
}
let Some(rest) = name.strip_prefix(stem) else { return false };
if let Some(sidecar) = rest.strip_prefix('.') {
return sidecar.eq_ignore_ascii_case("srt") || sidecar.eq_ignore_ascii_case("vtt");
}
// image sequence: one or more digits, then the output's own extension
let digits = rest.len() - rest.trim_start_matches(|c: char| c.is_ascii_digit()).len();
digits > 0 && !ext.is_empty() && rest.get(digits..).is_some_and(|r| r.strip_prefix('.').is_some_and(|x| x == ext))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_the_exports_own_files_are_removed() {
let dir = std::env::temp_dir().join(format!("fc-remove-partial-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let started = SystemTime::now();
let ours = ["trailer.png", "trailer000.png", "trailer123.png", "trailer.srt", "trailer.vtt"];
// same stem, written during the export, but not the export's
let theirs = ["trailer.aep", "trailer2.psd", "trailer.docx", "trailer000.jpg", "trailers.png", "trailer.png.bak", "other.png"];
for f in ours.iter().chain(theirs.iter()) {
std::fs::write(dir.join(f), b"x").unwrap();
}
remove_partial(&dir.join("trailer.png").to_string_lossy(), started);
for f in ours {
assert!(!dir.join(f).exists(), "{f} should be removed");
}
for f in theirs {
assert!(dir.join(f).exists(), "{f} must not be removed");
}
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn files_older_than_the_export_are_kept() {
let dir = std::env::temp_dir().join(format!("fc-remove-partial-old-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("clip.mp4"), b"x").unwrap();
remove_partial(&dir.join("clip.mp4").to_string_lossy(), SystemTime::now() + Duration::from_secs(60));
assert!(dir.join("clip.mp4").exists());
let _ = std::fs::remove_dir_all(&dir);
}
}
+610 -37
View File
@@ -1,6 +1,6 @@
//! The MCP server. Tool names are snake_case.
use std::sync::{Arc, Mutex};
use std::sync::{Arc, Mutex, PoisonError};
use base64::Engine as _;
use filmcraft_engine::Session;
@@ -19,6 +19,19 @@ pub enum Backend {
Bridge(Arc<BridgeClient>),
}
/// A panic payload as text.
fn panic_message(p: Box<dyn std::any::Any + Send>) -> String {
p.downcast_ref::<&str>().map(|s| s.to_string()).or_else(|| p.downcast_ref::<String>().cloned()).unwrap_or_else(|| "panic".into())
}
/// A failed blocking task: a panic is reported as an internal error and the session stays usable.
fn join_error(e: tokio::task::JoinError) -> AutomationError {
match e.try_into_panic() {
Ok(p) => AutomationError::Other(format!("internal error: {}", panic_message(p))),
Err(e) => AutomationError::Other(e.to_string()),
}
}
#[derive(Clone)]
pub struct FilmcraftMcp {
backend: Arc<Backend>,
@@ -44,6 +57,24 @@ pub struct RunParams {
pub params: Option<Value>,
}
#[derive(Debug, Deserialize, JsonSchema)]
pub struct BatchStep {
/// Command id.
pub id: String,
/// Parameters object.
#[serde(default)]
pub params: Option<Value>,
}
#[derive(Debug, Deserialize, JsonSchema)]
pub struct BatchParams {
/// Commands to run in order.
pub steps: Vec<BatchStep>,
/// Stop at the first failing step (default true).
#[serde(default)]
pub stop_on_error: Option<bool>,
}
#[derive(Debug, Default, Deserialize, JsonSchema)]
pub struct RenderParams {
/// Timeline time in seconds (default: the playhead).
@@ -148,9 +179,60 @@ impl FilmcraftMcp {
}
pub async fn serve_stdio(self) -> Result<(), AutomationError> {
let running = self.serve(rmcp::transport::stdio()).await.map_err(|e| AutomationError::Other(format!("MCP init: {e}")))?;
running.waiting().await.map_err(|e| AutomationError::Other(e.to_string()))?;
Ok(())
self.serve_io(tokio::io::stdin(), tokio::io::stdout()).await
}
/// Serve MCP over any line stream. A line that isn't JSON gets a JSON-RPC parse error
/// (`-32700`, id null) instead of being dropped silently; the rest go to the rmcp service. One
/// writer task owns `output`, so replies never interleave.
pub async fn serve_io(
self,
input: impl tokio::io::AsyncRead + Unpin + Send + 'static,
output: impl tokio::io::AsyncWrite + Unpin + Send + 'static,
) -> Result<(), AutomationError> {
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
let (mut to_service, service_in) = tokio::io::duplex(1 << 20);
let (service_out, from_service) = tokio::io::duplex(1 << 20);
let (err_tx, mut err_rx) = tokio::sync::mpsc::unbounded_channel::<String>();
let reader = tokio::spawn(async move {
let mut lines = BufReader::new(input).lines();
while let Ok(Some(line)) = lines.next_line().await {
if line.trim().is_empty() {
continue;
}
match serde_json::from_str::<Value>(&line) {
Ok(_) => {
if to_service.write_all(format!("{line}\n").as_bytes()).await.is_err() {
break;
}
}
Err(e) => {
let reply = json!({"jsonrpc": "2.0", "id": null, "error": {"code": -32700, "message": format!("parse error: {e}")}});
let _ = err_tx.send(reply.to_string());
}
}
}
// EOF: closing the pipe ends the service
let _ = to_service.shutdown().await;
});
let writer = tokio::spawn(async move {
let mut output = output;
let mut replies = BufReader::new(from_service).lines();
loop {
let line = tokio::select! {
l = replies.next_line() => match l { Ok(Some(l)) => l, _ => break },
Some(e) = err_rx.recv() => e,
};
if output.write_all(format!("{line}\n").as_bytes()).await.is_err() || output.flush().await.is_err() {
break;
}
}
});
let running = self.serve((service_in, service_out)).await.map_err(|e| AutomationError::Other(format!("MCP init: {e}")))?;
let r = running.waiting().await.map_err(|e| AutomationError::Other(e.to_string()));
reader.abort();
let _ = writer.await;
r.map(|_| ())
}
/// Run an engine command on whichever backend.
@@ -160,16 +242,24 @@ impl FilmcraftMcp {
let s = s.clone();
let id = id.to_string();
tokio::task::spawn_blocking(move || {
let mut g = s.lock().map_err(|_| AutomationError::Other("session lock poisoned".into()))?;
// A command that panicked earlier poisoned the lock; the session is still usable.
let mut g = s.lock().unwrap_or_else(PoisonError::into_inner);
g.execute(&id, params).map_err(AutomationError::from)
})
.await
.map_err(|e| AutomationError::Other(e.to_string()))?
.map_err(join_error)?
}
Backend::Bridge(b) => b.call("engine.execute", json!({"command": id, "params": params})).await,
Backend::Bridge(b) => b.execute(id, params).await,
}
}
/// The project tree plus the active sequence (null when there is none).
async fn document(&self) -> Result<Value, AutomationError> {
let project = self.run("project.inspect", json!({})).await?;
let sequence = self.run("sequence.inspect", json!({})).await.ok();
Ok(json!({"project": project, "sequence": sequence}))
}
fn bridge_client(&self) -> Option<Arc<BridgeClient>> {
match &*self.backend {
Backend::Bridge(b) => Some(b.clone()),
@@ -190,7 +280,9 @@ impl FilmcraftMcp {
#[tool_router]
impl FilmcraftMcp {
#[tool(
description = "List every command (id, label, menu path, shortcut, parameter doc, enabled now). Menus, shortcuts, panels and timeline gestures all map to these ids."
title = "List commands",
description = "List every command (id, label, menu path, shortcut, parameter doc, enabled now). Menus, shortcuts, panels and timeline gestures all map to these ids.",
annotations(read_only_hint = true, destructive_hint = false, idempotent_hint = true, open_world_hint = false)
)]
async fn command_list(&self, Parameters(p): Parameters<ListParams>) -> Result<CallToolResult, McpError> {
let r = self.run("command.list", json!({})).await.map(|v| {
@@ -213,76 +305,167 @@ impl FilmcraftMcp {
}
#[tool(
description = "Run a command by id with JSON params, e.g. {\"id\":\"timeline.razor\",\"params\":{\"seconds\":3.5}} or {\"id\":\"effects.apply\",\"params\":{\"effect\":\"Gaussian Blur\"}}. Undoable edits land in History."
title = "Run a command",
description = "Run a command by id with JSON params, e.g. {\"id\":\"timeline.razor\",\"params\":{\"seconds\":3.5}} or {\"id\":\"effects.apply\",\"params\":{\"effect\":\"Gaussian Blur\"}}. Undoable edits land in History.",
annotations(read_only_hint = false, destructive_hint = true, idempotent_hint = false, open_world_hint = false)
)]
async fn command_run(&self, Parameters(p): Parameters<RunParams>) -> Result<CallToolResult, McpError> {
wrap(self.run(&p.id, p.params.unwrap_or(json!({}))).await)
}
#[tool(description = "Project tree (bins and items with ids, types, durations), active sequence, source clip.")]
#[tool(
title = "Run several commands",
description = "Run several commands in order: {steps: [{id, params?}], stop_on_error?: true}. Returns {completed, failed, results: [{ok, result | error}]}; each edit is its own undo step.",
annotations(read_only_hint = false, destructive_hint = true, idempotent_hint = false, open_world_hint = false)
)]
async fn command_batch(&self, Parameters(p): Parameters<BatchParams>) -> Result<CallToolResult, McpError> {
let stop = p.stop_on_error.unwrap_or(true);
let (mut completed, mut failed, mut results) = (0u32, 0u32, Vec::new());
for st in p.steps {
match self.run(&st.id, st.params.unwrap_or(json!({}))).await {
Ok(v) => {
completed += 1;
results.push(json!({"ok": true, "result": v}));
}
Err(e) => {
failed += 1;
results.push(json!({"ok": false, "error": e.to_string()}));
if stop {
break;
}
}
}
}
let v = json!({"completed": completed, "failed": failed, "results": results});
Ok(if failed > 0 { CallToolResult::error(vec![Content::text(v.to_string())]) } else { ok_json(&v) })
}
#[tool(
title = "Inspect the document",
description = "The project as JSON: the tree (as project_inspect) plus the active sequence (as sequence_inspect; null when there is none).",
annotations(read_only_hint = true, destructive_hint = false, idempotent_hint = true, open_world_hint = false)
)]
async fn doc_inspect(&self) -> Result<CallToolResult, McpError> {
wrap(self.document().await)
}
#[tool(
title = "Render a preview",
description = "The active sequence's frame at `seconds` (default: the playhead) as PNG, same as render_frame (bridge mode: Program monitor screenshot).",
annotations(read_only_hint = true, destructive_hint = false, idempotent_hint = true, open_world_hint = false)
)]
async fn render_preview(&self, p: Parameters<RenderParams>) -> Result<CallToolResult, McpError> {
self.render_frame(p).await
}
#[tool(
title = "Inspect the project tree",
description = "Project tree (bins and items with ids, types, durations), active sequence, source clip.",
annotations(read_only_hint = true, destructive_hint = false, idempotent_hint = true, open_world_hint = false)
)]
async fn project_inspect(&self) -> Result<CallToolResult, McpError> {
wrap(self.run("project.inspect", json!({})).await)
}
#[tool(
description = "The active sequence as JSON: settings, tracks, clips (ids, start/duration in ticks and frames, effects), transitions, markers, in/out, playhead, selection. 254016000000 ticks = 1 second."
title = "Inspect the active sequence",
description = "The active sequence as JSON: settings, tracks, clips (ids, start/duration in ticks and frames, effects), transitions, markers, in/out, playhead, selection. 254016000000 ticks = 1 second.",
annotations(read_only_hint = true, destructive_hint = false, idempotent_hint = true, open_world_hint = false)
)]
async fn sequence_inspect(&self) -> Result<CallToolResult, McpError> {
wrap(self.run("sequence.inspect", json!({})).await)
}
#[tool(description = "Import media files by absolute path (MP4/MOV, WAV/MP3/FLAC/AIFF/Ogg, PNG/JPEG/…).")]
#[tool(
title = "Import media",
description = "Import media files by absolute path (MP4/MOV, WAV/MP3/FLAC/AIFF/Ogg, PNG/JPEG/…).",
annotations(read_only_hint = false, destructive_hint = false, idempotent_hint = false, open_world_hint = false)
)]
async fn media_import(&self, Parameters(p): Parameters<TypeParams>) -> Result<CallToolResult, McpError> {
let paths: Vec<&str> = p.text.split('\n').map(str::trim).filter(|s| !s.is_empty()).collect();
wrap(self.run("file.import", json!({"paths": paths})).await)
}
#[tool(description = "Render the active sequence's frame (at `seconds` or the playhead) and return it as PNG.")]
#[tool(
title = "Render a frame",
description = "Render the active sequence's frame (at `seconds` or the playhead) and return it as PNG.",
annotations(read_only_hint = true, destructive_hint = false, idempotent_hint = true, open_world_hint = false)
)]
async fn render_frame(&self, Parameters(p): Parameters<RenderParams>) -> Result<CallToolResult, McpError> {
let max = p.max_side.unwrap_or(960);
match &*self.backend {
Backend::Headless(s) => {
let s = s.clone();
let r = tokio::task::spawn_blocking(move || -> Result<Vec<u8>, AutomationError> {
let mut g = s.lock().map_err(|_| AutomationError::Other("lock".into()))?;
if let Some(sec) = p.seconds {
g.set_playhead(filmcraft_time::Tick::from_seconds_f64(sec));
}
let g = s.lock().unwrap_or_else(PoisonError::into_inner);
// read-only: render at `seconds` without moving the playhead (#114)
let t = p.seconds.map_or_else(|| g.playhead(), filmcraft_time::Tick::from_seconds_f64);
let (w, h) =
g.active_sequence().map(|q| (q.settings.width, q.settings.height)).ok_or_else(|| AutomationError::Other("no sequence".into()))?;
let scale = (max as f32 / w.max(h) as f32).min(1.0);
let img = g.render_program(scale).ok_or_else(|| AutomationError::Other("no sequence".into()))?;
let img = g.render_program_at(scale, t).ok_or_else(|| AutomationError::Other("no sequence".into()))?;
png_rgba(img.w as u32, img.h as u32, img.over_black_rgba8(), max)
})
.await
.map_err(|e| McpError::internal_error(e.to_string(), None))?;
.unwrap_or_else(|e| Err(join_error(e)));
Ok(match r {
Ok(png) => png_result(&png, "rendered frame"),
Err(e) => fail(e),
})
}
Backend::Bridge(b) => {
if let Some(sec) = p.seconds
&& let Err(e) = b.call("engine.execute", json!({"command": "playhead.set", "params": {"seconds": sec}})).await
{
let Some(sec) = p.seconds else {
return self.screenshot(&b.clone(), Some("Program".into()), max).await;
};
// The Program monitor shows the playhead's frame, so the live playhead has to move
// for the screenshot; put it (and the selection, which may follow it) back after,
// so the tool stays read-only (#114).
let before = match self.run("sequence.inspect", json!({})).await {
Ok(v) => v,
Err(e) => return Ok(fail(e)),
};
if let Err(e) = self.run("playhead.set", json!({"seconds": sec})).await {
return Ok(fail(e));
}
self.screenshot(&b.clone(), Some("Program".into()), max).await
let shot = self.screenshot(&b.clone(), Some("Program".into()), max).await;
if let Some(t) = before.get("playhead").and_then(Value::as_i64) {
let _ = self.run("playhead.set", json!({"time": t})).await;
}
// only when it changed: selecting also leaves trim mode
let now = self.run("sequence.inspect", json!({})).await.ok();
if let Some(sel) = before.get("selection").filter(|v| v.is_array())
&& now.as_ref().and_then(|n| n.get("selection")) != Some(sel)
{
let _ = self.run("timeline.select", json!({"clips": sel})).await;
}
shot
}
}
}
#[tool(description = "Live app: UI state (tool, workspace, panels, timeline zoom, playback, selection, fps).")]
#[tool(
title = "Live app: UI state",
description = "Live app: UI state (tool, workspace, panels, timeline zoom, playback, selection, fps).",
annotations(read_only_hint = true, destructive_hint = false, idempotent_hint = true, open_world_hint = false)
)]
async fn ui_inspect(&self) -> Result<CallToolResult, McpError> {
self.ui("ui.inspect", json!({})).await
}
#[tool(description = "Live app: every on-screen interactive element with id, label and rect (points). Use ids with ui_click/ui_drag.")]
#[tool(
title = "Live app: on-screen elements",
description = "Live app: every on-screen interactive element with id, label and rect (points). Use ids with ui_click/ui_drag.",
annotations(read_only_hint = true, destructive_hint = false, idempotent_hint = true, open_world_hint = false)
)]
async fn ui_elements(&self, Parameters(p): Parameters<ElementsParams>) -> Result<CallToolResult, McpError> {
self.ui("ui.elements", json!({"prefix": p.prefix.unwrap_or_default()})).await
}
#[tool(description = "Live app: click an element by id or at x,y (points). Supports right/middle button, double-click (count=2) and modifiers.")]
#[tool(
title = "Live app: click",
description = "Live app: click an element by id or at x,y (points). Supports right/middle button, double-click (count=2) and modifiers.",
annotations(read_only_hint = false, destructive_hint = true, idempotent_hint = false, open_world_hint = false)
)]
async fn ui_click(&self, Parameters(p): Parameters<ClickParams>) -> Result<CallToolResult, McpError> {
let mut v = json!({"button": p.button, "count": p.count, "modifiers": p.modifiers});
if let Some(id) = p.id {
@@ -295,23 +478,37 @@ impl FilmcraftMcp {
}
#[tool(
description = "Live app: press-drag-release from one point/element to another (move clips, trim edges, scrub, resize panels, drop project items onto tracks)."
title = "Live app: drag",
description = "Live app: press-drag-release from one point/element to another (move clips, trim edges, scrub, resize panels, drop project items onto tracks).",
annotations(read_only_hint = false, destructive_hint = true, idempotent_hint = false, open_world_hint = false)
)]
async fn ui_drag(&self, Parameters(p): Parameters<DragParams>) -> Result<CallToolResult, McpError> {
self.ui("ui.drag", json!({"from": p.from, "to": p.to, "steps": p.steps, "modifiers": p.modifiers})).await
}
#[tool(description = "Live app: press a key or shortcut (e.g. `Space`, `L`, `Cmd+K`, `Shift+Delete`, `Cmd+Z`).")]
#[tool(
title = "Live app: press a key",
description = "Live app: press a key or shortcut (e.g. `Space`, `L`, `Cmd+K`, `Shift+Delete`, `Cmd+Z`).",
annotations(read_only_hint = false, destructive_hint = true, idempotent_hint = false, open_world_hint = false)
)]
async fn ui_key(&self, Parameters(p): Parameters<KeyParams>) -> Result<CallToolResult, McpError> {
self.ui("ui.key", json!({"key": p.key})).await
}
#[tool(description = "Live app: type text into the focused field.")]
#[tool(
title = "Live app: type text",
description = "Live app: type text into the focused field.",
annotations(read_only_hint = false, destructive_hint = true, idempotent_hint = false, open_world_hint = false)
)]
async fn ui_type(&self, Parameters(p): Parameters<TypeParams>) -> Result<CallToolResult, McpError> {
self.ui("ui.type", json!({"text": p.text})).await
}
#[tool(description = "Live app: screenshot of the window or one panel (PNG).")]
#[tool(
title = "Live app: screenshot",
description = "Live app: screenshot of the window or one panel (PNG).",
annotations(read_only_hint = true, destructive_hint = false, idempotent_hint = true, open_world_hint = false)
)]
async fn ui_screenshot(&self, Parameters(p): Parameters<ShotParams>) -> Result<CallToolResult, McpError> {
match self.bridge_client() {
Some(b) => self.screenshot(&b, p.panel, p.max_side.unwrap_or(1600)).await,
@@ -320,7 +517,9 @@ impl FilmcraftMcp {
}
#[tool(
description = "Live app: call any control-channel method directly (ui.set, ui.scroll, ui.timeline.hit, ui.timeline.locate, ui.playback, ui.panel.show, ui.menu.list, …)."
title = "Live app: control-channel call",
description = "Live app: call any control-channel method directly (ui.set, ui.scroll, ui.timeline.hit, ui.timeline.locate, ui.playback, ui.panel.show, ui.menu.list, …).",
annotations(read_only_hint = false, destructive_hint = true, idempotent_hint = false, open_world_hint = false)
)]
async fn ui_control(&self, Parameters(p): Parameters<ControlParams>) -> Result<CallToolResult, McpError> {
self.ui(&p.method, p.params.unwrap_or(json!({}))).await
@@ -350,12 +549,104 @@ impl FilmcraftMcp {
}
}
#[tool_handler(
router = self.tool_router,
name = "filmcraft",
instructions = "FilmCraft video editor (Premiere Pro-class). Every edit is an engine command: `command_list` to discover ids/params, `command_run` to execute (undoable). `project_inspect`/`sequence_inspect` return ids you can pass to commands; `render_frame` shows the result. In bridge mode the `ui_*` tools drive the live app: `ui_elements` lists clickable ids, `ui_click`/`ui_drag`/`ui_key` operate it, `ui_screenshot` shows it. Time is in ticks: 254016000000 per second (commands also accept `seconds`, `frame` or `timecode`)."
)]
impl ServerHandler for FilmcraftMcp {}
impl FilmcraftMcp {
/// The first argument `tool` doesn't take, as a message naming the ones it does.
fn unknown_arg(&self, tool: &str, args: Option<&rmcp::model::JsonObject>) -> Option<String> {
let def = self.tool_router.get(tool)?;
let props = def.input_schema.get("properties").and_then(Value::as_object).cloned().unwrap_or_default();
let bad = args?.keys().find(|k| !props.contains_key(*k))?;
let accepted: Vec<&str> = props.keys().map(String::as_str).collect();
let accepted = if accepted.is_empty() { "no arguments".to_string() } else { accepted.join(", ") };
Some(format!("unknown argument \"{bad}\" for {tool}; expected: {accepted}"))
}
}
const INSTRUCTIONS: &str = "FilmCraft video editor (Premiere Pro-class). Every edit is an engine command: `command_list` to discover ids/params, `command_run` to execute (undoable; `command_batch` runs several). `doc_inspect` (or `project_inspect`/`sequence_inspect`) returns ids you can pass to commands; `render_preview` shows the result. In bridge mode the `ui_*` tools drive the live app: `ui_elements` lists clickable ids, `ui_click`/`ui_drag`/`ui_key` operate it, `ui_screenshot` shows it. Time is in ticks: 254016000000 per second (commands also accept `seconds`, `frame` or `timecode`).";
/// Resources: the project (as `doc_inspect`) and the command catalog (as `command_list`).
const DOCUMENT_URI: &str = "filmcraft://document";
const COMMANDS_URI: &str = "filmcraft://commands";
/// MCP 2026-07-28 clients (current Claude Code) require `ttlMs` and `cacheScope` on list and read
/// results; rmcp fills `resultType` and leaves the cache hints to the server, as the generated
/// `tools/list` does. The resource list never changes; the document does, so reads aren't cached.
fn cache_hints(context: &rmcp::service::RequestContext<rmcp::RoleServer>, ttl_ms: u64) -> Option<(u64, rmcp::model::CacheScope)> {
context.protocol_version().is_some_and(|v| v >= rmcp::model::ProtocolVersion::V_2026_07_28).then_some((ttl_ms, rmcp::model::CacheScope::Private))
}
#[tool_handler(router = self.tool_router)]
impl ServerHandler for FilmcraftMcp {
fn get_info(&self) -> rmcp::model::ServerConfig {
rmcp::model::ServerConfig::new(rmcp::model::ServerCapabilities::builder().enable_tools().enable_resources().build())
.with_server_info(rmcp::model::Implementation::new("filmcraft", env!("CARGO_PKG_VERSION")))
.with_instructions(INSTRUCTIONS.to_string())
}
/// Strict arguments and long exports in front of the tool router.
async fn call_tool(
&self,
request: rmcp::model::CallToolRequestParams,
context: rmcp::service::RequestContext<rmcp::RoleServer>,
) -> Result<rmcp::model::CallToolResponse, McpError> {
if let Some(m) = self.unknown_arg(&request.name, request.arguments.as_ref()) {
return Err(McpError::invalid_params(m, None));
}
// A blocking export reports progress and can be cancelled (docs/agents.md § Long exports).
// Bridge mode too: the app runs it as a job, so it stays responsive (#91, #92).
if request.name == "command_run"
&& let Some(a) = &request.arguments
&& let Some(id) = a.get("id").and_then(Value::as_str)
{
let params = a.get("params").cloned().filter(Value::is_object).unwrap_or_else(|| json!({}));
if crate::long_job::is_long(id, &params) {
return Ok(self.run_long(id, params, &context).await.into());
}
}
let tcc = rmcp::handler::server::tool::ToolCallContext::new(self, request, context);
self.tool_router.call(tcc).await
}
async fn list_resources(
&self,
_request: Option<rmcp::model::PaginatedRequestParams>,
context: rmcp::service::RequestContext<rmcp::RoleServer>,
) -> Result<rmcp::model::ListResourcesResult, McpError> {
use rmcp::model::Resource;
let mut r = rmcp::model::ListResourcesResult::with_all_items(vec![
Resource::new(DOCUMENT_URI, "document")
.with_title("Project")
.with_description("The project tree and the active sequence (same as doc_inspect).")
.with_mime_type("application/json"),
Resource::new(COMMANDS_URI, "commands")
.with_title("Command catalog")
.with_description("Every command with id, label, menu path, shortcut, params and enabled state (same as command_list).")
.with_mime_type("application/json"),
]);
if let Some((ttl, scope)) = cache_hints(&context, 600_000) {
r = r.with_ttl_ms(ttl).with_cache_scope(scope);
}
Ok(r)
}
async fn read_resource(
&self,
request: rmcp::model::ReadResourceRequestParams,
context: rmcp::service::RequestContext<rmcp::RoleServer>,
) -> Result<rmcp::model::ReadResourceResponse, McpError> {
let v = match request.uri.as_str() {
DOCUMENT_URI => self.document().await,
COMMANDS_URI => self.run("command.list", json!({})).await,
other => return Err(McpError::resource_not_found(format!("resource not found: {other}"), None)),
}
.map_err(|e| McpError::internal_error(e.to_string(), None))?;
let text = serde_json::to_string_pretty(&v).map_err(|e| McpError::internal_error(e.to_string(), None))?;
let mut r = rmcp::model::ReadResourceResult::new(vec![rmcp::model::ResourceContents::text(text, request.uri).with_mime_type("application/json")]);
if let Some((ttl, scope)) = cache_hints(&context, 0) {
r = r.with_ttl_ms(ttl).with_cache_scope(scope);
}
Ok(r.into())
}
}
#[cfg(test)]
mod tests {
@@ -371,4 +662,286 @@ mod tests {
let r = m.render_frame(Parameters(RenderParams { seconds: Some(1.0), max_side: Some(320) })).await.unwrap();
assert_ne!(r.is_error, Some(true));
}
/// `render_frame` / `render_preview` are annotated read-only (#114): rendering at `seconds`
/// leaves the playhead, and the selection that follows it, where they were, and still renders
/// the frame at `seconds`.
#[tokio::test]
async fn rendering_at_a_time_does_not_move_the_playhead() {
let m = FilmcraftMcp::headless(demo());
m.run("sequence.selectionFollowsPlayhead", json!({"on": true})).await.unwrap();
m.run("playhead.set", json!({"seconds": 1.0})).await.unwrap();
let before = m.run("sequence.inspect", json!({})).await.unwrap();
let png = |r: CallToolResult| serde_json::to_string(&r.content).unwrap();
let at_playhead = png(m.render_frame(Parameters(RenderParams { seconds: None, max_side: Some(64) })).await.unwrap());
for seconds in [5.0, 8.0] {
let r = m.render_frame(Parameters(RenderParams { seconds: Some(seconds), max_side: Some(64) })).await.unwrap();
assert_ne!(png(r), at_playhead, "renders the frame at {seconds} s");
m.render_preview(Parameters(RenderParams { seconds: Some(seconds), max_side: Some(64) })).await.unwrap();
}
let after = m.run("sequence.inspect", json!({})).await.unwrap();
assert_eq!(after["playhead"], before["playhead"]);
assert_eq!(after["selection"], before["selection"]);
}
/// One request/response exchange over `serve_io`, as an MCP client sees it.
struct Client {
tx: tokio::io::DuplexStream,
rx: tokio::io::Lines<tokio::io::BufReader<tokio::io::DuplexStream>>,
}
impl Client {
fn start(s: Session) -> Self {
use tokio::io::AsyncBufReadExt;
let (tx, server_in) = tokio::io::duplex(1 << 22);
let (server_out, rx) = tokio::io::duplex(1 << 22);
tokio::spawn(FilmcraftMcp::headless(s).serve_io(server_in, server_out));
Self { tx, rx: tokio::io::BufReader::new(rx).lines() }
}
async fn send(&mut self, line: &str) {
use tokio::io::AsyncWriteExt;
self.tx.write_all(format!("{line}\n").as_bytes()).await.unwrap();
}
async fn next(&mut self) -> Value {
serde_json::from_str(&self.rx.next_line().await.unwrap().unwrap()).unwrap()
}
async fn ask(&mut self, msg: Value) -> Value {
self.send(&msg.to_string()).await;
self.next().await
}
async fn init(&mut self) -> Value {
let r = self.ask(json!({"jsonrpc":"2.0","id":0,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"t","version":"1"}}})).await;
self.send(&json!({"jsonrpc":"2.0","method":"notifications/initialized"}).to_string()).await;
r
}
async fn call(&mut self, id: u64, name: &str, arguments: Value) -> Value {
self.ask(json!({"jsonrpc":"2.0","id":id,"method":"tools/call","params":{"name":name,"arguments":arguments}})).await
}
}
fn demo() -> Session {
let mut s = Session::default();
s.execute("file.openDemoProject", json!({})).unwrap();
s
}
/// Every listed tool has a title and the four hints, and the core tools are listed.
#[tokio::test(flavor = "multi_thread")]
async fn tools_are_titled_and_annotated() {
let mut c = Client::start(demo());
let init = c.init().await;
assert_eq!(init["result"]["serverInfo"]["name"], "filmcraft");
let tools = c.ask(json!({"jsonrpc":"2.0","id":1,"method":"tools/list"})).await["result"]["tools"].as_array().cloned().unwrap();
for t in &tools {
assert!(t["title"].is_string(), "{} has no title", t["name"]);
for h in ["readOnlyHint", "destructiveHint", "idempotentHint", "openWorldHint"] {
assert!(t["annotations"][h].is_boolean(), "{} lacks {h}", t["name"]);
}
}
let names: Vec<&str> = tools.iter().filter_map(|t| t["name"].as_str()).collect();
for want in ["command_list", "command_run", "command_batch", "doc_inspect", "render_preview", "project_inspect", "render_frame", "ui_click"] {
assert!(names.contains(&want), "{want} not listed");
}
let ro = |n: &str| tools.iter().find(|t| t["name"] == n).map(|t| t["annotations"]["readOnlyHint"].clone());
assert_eq!((ro("command_list"), ro("command_run")), (Some(json!(true)), Some(json!(false))));
}
/// Strict arguments, malformed JSON, batch, doc_inspect and render_preview over the raw line
/// protocol.
#[tokio::test(flavor = "multi_thread")]
async fn strict_arguments_and_parse_errors() {
let mut c = Client::start(demo());
c.init().await;
let r = c.call(1, "command_list", json!({"filter": "razor", "enabled_only": true})).await;
assert!(r["result"]["content"][0]["text"].as_str().unwrap().contains("timeline.razor"), "{r}");
// an unknown argument names itself and the accepted ones
let r = c.call(2, "command_list", json!({"filtr": "x"})).await;
assert_eq!(r["error"]["code"], -32602, "{r}");
let m = r["error"]["message"].as_str().unwrap();
assert!(m.contains("\"filtr\"") && m.contains("filter") && m.contains("enabled_only"), "{m}");
let r = c.call(3, "doc_inspect", json!({"verbose": true})).await;
assert_eq!(r["error"]["code"], -32602, "{r}");
// command params stay free-form
let r = c.call(4, "command_run", json!({"id": "playhead.set", "params": {"seconds": 0.5}})).await;
assert_eq!(r["result"]["isError"], false, "{r}");
// malformed JSON: a parse error, and the server keeps serving
c.send("{\"jsonrpc\": \"2.0\", \"id\": 5, BROKEN").await;
let r = c.next().await;
assert_eq!((r["error"]["code"].as_i64(), r["id"].is_null()), (Some(-32700), true), "{r}");
let r = c.ask(json!({"jsonrpc":"2.0","id":6,"method":"ping"})).await;
assert!(r["result"].is_object(), "{r}");
// batch: stops at the first failure and reports both
let r =
c.call(7, "command_batch", json!({"steps": [{"id": "playhead.set", "params": {"seconds": 0.5}}, {"id": "no.such"}, {"id": "playhead.set"}]})).await;
assert_eq!(r["result"]["isError"], true, "{r}");
let v: Value = serde_json::from_str(r["result"]["content"][0]["text"].as_str().unwrap()).unwrap();
assert_eq!((v["completed"].as_u64(), v["failed"].as_u64(), v["results"].as_array().map(Vec::len)), (Some(1), Some(1), Some(2)), "{v}");
let r = c.call(8, "doc_inspect", json!({})).await;
let v: Value = serde_json::from_str(r["result"]["content"][0]["text"].as_str().unwrap()).unwrap();
assert!(v["project"].is_object() && v["sequence"].is_object(), "{v}");
let r = c.call(9, "render_preview", json!({"max_side": 64})).await;
assert_eq!(r["result"]["content"][0]["type"], "image", "{r}");
}
/// `filmcraft://document` and `filmcraft://commands` are listed and readable as JSON.
#[tokio::test(flavor = "multi_thread")]
async fn resources_document_and_commands() {
let mut c = Client::start(demo());
let init = c.init().await;
assert!(init["result"]["capabilities"]["resources"].is_object(), "{init}");
assert!(init["result"]["instructions"].as_str().unwrap().contains("doc_inspect"), "{init}");
let r = c.ask(json!({"jsonrpc":"2.0","id":1,"method":"resources/list"})).await;
let uris: Vec<&str> = r["result"]["resources"].as_array().unwrap().iter().filter_map(|x| x["uri"].as_str()).collect();
assert_eq!(uris, [DOCUMENT_URI, COMMANDS_URI], "{r}");
let r = c.ask(json!({"jsonrpc":"2.0","id":2,"method":"resources/read","params":{"uri":DOCUMENT_URI}})).await;
assert_eq!(r["result"]["contents"][0]["mimeType"], "application/json", "{r}");
let v: Value = serde_json::from_str(r["result"]["contents"][0]["text"].as_str().unwrap()).unwrap();
assert!(v["project"].is_object() && v["sequence"].is_object(), "{v}");
let r = c.ask(json!({"jsonrpc":"2.0","id":3,"method":"resources/read","params":{"uri":COMMANDS_URI}})).await;
assert!(r["result"]["contents"][0]["text"].as_str().unwrap().contains("timeline.razor"), "{r}");
let r = c.ask(json!({"jsonrpc":"2.0","id":4,"method":"resources/read","params":{"uri":"filmcraft://nope"}})).await;
assert!(r["error"]["code"].is_i64(), "{r}");
}
/// MCP 2026-07-28 clients (current Claude Code) negotiate per request and reject list and read
/// results without `resultType`, `ttlMs` and `cacheScope`; sessions that negotiated an older
/// revision through `initialize` get the old shape.
#[tokio::test(flavor = "multi_thread")]
async fn modern_clients_get_result_type_and_cache_hints() {
let mut c = Client::start(Session::default());
let meta = json!({
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
"io.modelcontextprotocol/clientInfo": {"name": "t", "version": "1"},
"io.modelcontextprotocol/clientCapabilities": {},
});
let r = c.ask(json!({"jsonrpc":"2.0","id":1,"method":"server/discover","params":{"_meta":meta}})).await;
assert!(r["result"]["supportedVersions"].as_array().unwrap().contains(&json!("2026-07-28")), "{r}");
for (id, method, params) in [
(2, "tools/list", json!({"_meta": meta})),
(3, "resources/list", json!({"_meta": meta})),
(4, "resources/read", json!({"_meta": meta, "uri": DOCUMENT_URI})),
] {
let r = c.ask(json!({"jsonrpc":"2.0","id":id,"method":method,"params":params})).await;
assert_eq!(r["result"]["resultType"], "complete", "{method}: {r}");
assert!(r["result"]["ttlMs"].is_u64(), "{method}: {r}");
assert!(matches!(r["result"]["cacheScope"].as_str(), Some("public" | "private")), "{method}: {r}");
}
let mut c = Client::start(Session::default());
c.init().await;
for (id, method, params) in [(2, "tools/list", json!({})), (3, "resources/list", json!({})), (4, "resources/read", json!({"uri": DOCUMENT_URI}))] {
let r = c.ask(json!({"jsonrpc":"2.0","id":id,"method":method,"params":params})).await;
assert!(r["result"].is_object() && r["result"].get("resultType").is_none() && r["result"].get("ttlMs").is_none(), "{method}: {r}");
}
}
/// docs/agents.md § Long exports: a blocking export reports `notifications/progress` for its
/// token (none without one), answers `ping` meanwhile, and `notifications/cancelled` stops
/// it, deletes the partial file and sends no response.
#[tokio::test(flavor = "multi_thread")]
async fn export_progress_and_cancel() {
let dir = std::env::temp_dir().join(format!("filmcraft-mcp-progress-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let mut c = Client::start(demo());
c.init().await;
let export = |id: u64, name: &str, token: Option<Value>, seconds: f64| {
let path = dir.join(name).to_string_lossy().to_string();
let params = json!({"path": path, "format": "h264", "width": 640, "height": 360, "audio": false, "range": "custom", "startSeconds": 0, "endSeconds": seconds, "wait": true});
let mut call =
json!({"jsonrpc":"2.0","id":id,"method":"tools/call","params":{"name":"command_run","arguments":{"id":"file.exportMedia","params":params}}});
if let Some(t) = token {
call["params"]["_meta"] = json!({"progressToken": t});
}
call.to_string()
};
// no token: no notifications, the same response as before
c.send(&export(1, "quiet.mp4", None, 0.5)).await;
let m = c.next().await;
assert_eq!((m["id"].as_u64(), &m["result"]["isError"]), (Some(1), &json!(false)), "{m}");
// progress, strictly increasing, with a total; ping answered while the export runs. The
// job is polled every 100 ms, so a fast machine finishes a short export within one poll:
// a longer one is tried until the export outlasts a few polls.
let (mut notes, mut pong) = (0, false);
for (attempt, seconds) in [1.0, 4.0, 16.0].into_iter().enumerate() {
let (id, ping, name) = (20 + attempt as u64, 30 + attempt as u64, format!("a{attempt}.mp4"));
c.send(&export(id, &name, Some(json!("tok")), seconds)).await;
let (mut last, mut pinged) = (-1.0, false);
(notes, pong) = (0, false);
let done = loop {
let m = c.next().await;
if m["method"] == "notifications/progress" {
assert_eq!(m["params"]["progressToken"], "tok", "{m}");
let p = m["params"]["progress"].as_f64().unwrap();
assert!(p > last && m["params"]["total"].as_f64().unwrap() >= p, "{m}");
last = p;
notes += 1;
if !pinged {
pinged = true;
c.send(&json!({"jsonrpc": "2.0", "id": ping, "method": "ping"}).to_string()).await;
}
} else if m["id"] == ping {
pong = true;
} else if m["id"] == id {
break m;
}
};
assert_eq!(done["result"]["isError"], false, "{done}");
assert!(notes >= 1, "a finished export reports its progress at least once");
assert!(dir.join(&name).exists());
if notes >= 2 && pong {
break;
}
// the ping's answer is still on its way: read it so it cannot be taken for a later reply
while pinged && !pong {
pong = c.next().await["id"] == ping;
}
pong = false;
}
assert!(notes >= 2 && pong, "{notes} notifications, ping answered during the export: {pong}");
// cancel after the first notification: no response, no partial file
c.send(&export(4, "b.mp4", Some(json!(7)), 20.0)).await;
loop {
let m = c.next().await;
assert_ne!(m["id"], 4, "finished before the cancel: {m}");
if m["method"] == "notifications/progress" {
break;
}
}
c.send(r#"{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":4}}"#).await;
let t0 = std::time::Instant::now();
while dir.join("b.mp4").exists() || t0.elapsed() < std::time::Duration::from_millis(500) {
assert!(t0.elapsed().as_secs() < 30, "partial file still there");
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
}
c.send(r#"{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"command_run","arguments":{"id":"jobs.list"}}}"#).await;
let m = loop {
let m = c.next().await;
assert_ne!(m["id"], 4, "no response for a cancelled request: {m}");
if m["id"] == 5 {
break m;
}
};
let jobs: Value = serde_json::from_str(m["result"]["content"][0]["text"].as_str().unwrap()).unwrap();
let last = jobs.as_array().and_then(|a| a.last()).cloned().unwrap_or_default();
assert_eq!(last["result"]["error"], "cancelled", "{jobs}");
assert!(!dir.join("b.mp4").exists());
let _ = std::fs::remove_dir_all(&dir);
}
/// A command that panicked used to poison the session lock, and every later call failed with
/// "session lock poisoned" until the server was restarted.
#[tokio::test(flavor = "multi_thread")]
async fn a_poisoned_session_lock_keeps_serving() {
let m = FilmcraftMcp::headless(demo());
let Backend::Headless(s) = &*m.backend else { panic!("headless backend") };
let s = s.clone();
let _ = std::thread::spawn(move || {
let _g = s.lock().unwrap();
panic!("a command panicked");
})
.join();
let v = m.run("sequence.inspect", json!({})).await.unwrap();
assert!(v.is_object(), "{v}");
let r = m.render_frame(Parameters(RenderParams { seconds: Some(0.5), max_side: Some(64) })).await.unwrap();
assert_ne!(r.is_error, Some(true));
}
}
+70 -15
View File
@@ -184,28 +184,45 @@ struct Timing {
tick_rate: i64,
}
fn positive_integer(s: &str) -> Option<i64> {
let s = s.trim();
if s.is_empty() || !s.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
s.parse::<i64>().ok().filter(|v| *v > 0)
}
fn parse_ratio(s: &str) -> Option<(i64, i64)> {
let mut it = s.split_whitespace().map(|x| x.parse::<i64>().ok());
let mut it = s.split_whitespace().map(positive_integer);
let a = it.next()??;
let b = it.next().flatten().unwrap_or(1);
(a > 0 && b > 0).then_some((a, b))
let b = it.next()??;
it.next().is_none().then_some((a, b))
}
fn attr<'a>(n: roxmltree::Node<'a, '_>, local: &str) -> Option<&'a str> {
n.attributes().find(|a| a.name() == local).map(|a| a.value())
}
fn timing(root: roxmltree::Node) -> Timing {
let base = attr(root, "frameRate").and_then(|v| v.trim().parse::<i64>().ok()).filter(|v| *v > 0).unwrap_or(30);
let (mn, md) = attr(root, "frameRateMultiplier").and_then(parse_ratio).unwrap_or((1, 1));
let rate = FrameRate::new(base * mn, md);
let sub = attr(root, "subFrameRate").and_then(|v| v.trim().parse::<i64>().ok()).filter(|v| *v > 0).unwrap_or(1);
let tick_rate = attr(root, "tickRate").and_then(|v| v.trim().parse::<i64>().ok()).filter(|v| *v > 0).unwrap_or(if attr(root, "frameRate").is_some() {
base * sub
} else {
1
});
Timing { rate, base, sub_frame_rate: sub, tick_rate }
fn timing(root: roxmltree::Node) -> Result<Timing> {
let invalid =
|name: &str| Error::Syntax { line: root.document().text_pos_at(root.range().start).row as usize, msg: format!("invalid TTML timing parameter {name}") };
let integer = |name: &str, default| match attr(root, name) {
Some(v) => positive_integer(v).ok_or_else(|| invalid(name)),
None => Ok(default),
};
let base = integer("frameRate", 30)?;
let (mn, md) = match attr(root, "frameRateMultiplier") {
Some(v) => parse_ratio(v).ok_or_else(|| invalid("frameRateMultiplier"))?,
None => (1, 1),
};
let rate = FrameRate::new(base.checked_mul(mn).ok_or_else(|| invalid("frameRateMultiplier"))?, md);
let sub = integer("subFrameRate", 1)?;
let tick_rate = match attr(root, "tickRate") {
Some(v) => positive_integer(v).ok_or_else(|| invalid("tickRate"))?,
None if attr(root, "frameRate").is_some() => base.checked_mul(sub).ok_or_else(|| invalid("subFrameRate"))?,
None => 1,
};
Ok(Timing { rate, base, sub_frame_rate: sub, tick_rate })
}
/// Seconds as an exact decimal string → ticks.
@@ -383,7 +400,7 @@ pub fn parse(text: &str) -> Result<Document> {
if root.tag_name().name() != "tt" {
return Err(Error::NotFormat("TTML"));
}
let tm = timing(root);
let tm = timing(root)?;
let mut styles = std::collections::HashMap::new();
for s in root.descendants().filter(|n| n.is_element() && n.tag_name().name() == "style") {
if let Some(id) = s.attributes().find(|a| a.name() == "id").map(|a| a.value()) {
@@ -478,6 +495,44 @@ mod tests {
Timing { rate, base: rate.timecode_base(), sub_frame_rate: 1, tick_rate: 1 }
}
#[test]
fn invalid_timing_parameters_return_an_error() {
for params in [
r#"ttp:frameRate="0""#,
r#"ttp:frameRate="-25""#,
r#"ttp:frameRate="""#,
r#"ttp:subFrameRate="0""#,
r#"ttp:tickRate="-1""#,
r#"ttp:frameRateMultiplier="1 0""#,
r#"ttp:frameRateMultiplier="1""#,
r#"ttp:frameRateMultiplier="1 2 3""#,
] {
let xml = format!(
r#"<tt xmlns="http://www.w3.org/ns/ttml" xmlns:ttp="http://www.w3.org/ns/ttml#parameter" {params}><body><div><p begin="1s" end="2s">Hello</p></div></body></tt>"#
);
assert!(crate::parse(xml.as_bytes(), crate::Format::Ttml).is_err(), "{params}");
}
}
#[test]
fn missing_timing_parameters_keep_defaults() {
for (params, begin, end) in [
("", "1s", "2s"),
(r#"ttp:frameRate="25""#, "25f", "50f"),
(r#"ttp:frameRate="30" ttp:subFrameRate="2""#, "60t", "120t"),
(r#"ttp:frameRate="30" ttp:subFrameRate="2" ttp:tickRate="10""#, "10t", "20t"),
(r#"ttp:frameRate="25" ttp:frameRateMultiplier="2 1""#, "50f", "100f"),
] {
let xml = format!(
r#"<tt xmlns="http://www.w3.org/ns/ttml" xmlns:ttp="http://www.w3.org/ns/ttml#parameter" {params}><body><div><p begin="{begin}" end="{end}">Hello</p></div></body></tt>"#
);
let doc = crate::parse(xml.as_bytes(), crate::Format::Ttml).unwrap();
assert_eq!(doc.cues.len(), 1, "{params}");
assert_eq!(doc.cues[0].start, Tick(TICKS_PER_SECOND), "{params}");
assert_eq!(doc.cues[0].end, Tick(2 * TICKS_PER_SECOND), "{params}");
}
}
#[test]
fn time_expressions() {
let t = tm(FrameRate::FPS_25);
+1
View File
@@ -28,6 +28,7 @@ filmcraft-vp9 = { workspace = true }
filmcraft-prores = { workspace = true }
filmcraft-dnx = { workspace = true }
filmcraft-av1 = { workspace = true }
filmcraft-apv = { workspace = true }
filmcraft-aac = { workspace = true }
filmcraft-opus = { workspace = true }
thiserror = { workspace = true }
+177
View File
@@ -0,0 +1,177 @@
//! Standalone APV raw bitstream source (RFC 9924 Appendix A: `.apv` elementary streams).
//!
//! Each access unit in a raw bitstream is prefixed by a 4-byte big-endian `au_size` followed by
//! the `'aPv1'` signature (unprefixed single-AU streams starting directly with `'aPv1'` are also
//! accepted). Every frame is intra-coded, so random access is direct.
use std::sync::Arc;
use filmcraft_color::{ColorInfo, Matrix, Range, Transfer};
use filmcraft_frame::{AudioBuffer, VideoFrame};
use filmcraft_media::{FrameRequest, MediaError, MediaInfo, MediaKind, MediaSource, SharedSource, VideoStreamInfo};
use filmcraft_time::{FrameRate, Tick};
use crate::CodecError;
use crate::gop::{GopCache, VideoSamples};
use crate::video::{ApvDecoder, VideoDecoder, primaries_from_code};
/// Sniff a raw APV bitstream: either a `raw_bitstream_access_unit()` (`[au_size: u32]['aPv1']`) or
/// an unprefixed `access_unit()` starting with `'aPv1'`.
pub fn sniff(head: &[u8]) -> bool {
(head.len() >= 8 && &head[4..8] == b"aPv1" && u32::from_be_bytes([head[0], head[1], head[2], head[3]]) >= 8) || head.starts_with(b"aPv1")
}
pub struct ApvSource {
info: MediaInfo,
bytes: crate::Src,
samples: Vec<(u64, u32)>,
rate: FrameRate,
video: GopCache,
}
pub(crate) fn apv_pixfmt_label(chroma: filmcraft_apv::ChromaFormat, bit_depth: u8) -> String {
let sub = match chroma {
filmcraft_apv::ChromaFormat::Monochrome => "Monochrome",
filmcraft_apv::ChromaFormat::Yuv422 => "YUV 4:2:2",
filmcraft_apv::ChromaFormat::Yuv444 => "YUV 4:4:4",
filmcraft_apv::ChromaFormat::Yuv4444 => "YUVA 4:4:4:4",
};
format!("{sub} {bit_depth}-bit")
}
impl ApvSource {
pub fn open(name: &str, bytes: Arc<[u8]>) -> crate::Result<Self> {
Self::open_reader(name, Arc::new(filmcraft_media::reader::MemReader(bytes)))
}
pub fn open_reader(name: &str, reader: filmcraft_media::SharedReader) -> crate::Result<Self> {
let len = reader.len();
let mut samples = Vec::new();
let mut pos = 0u64;
let mut hdr = [0u8; 8];
while pos + 8 <= len {
if reader.read_at(pos, &mut hdr).is_err() {
break;
}
if &hdr[4..8] == b"aPv1" {
let sz = u32::from_be_bytes([hdr[0], hdr[1], hdr[2], hdr[3]]);
if sz < 8 || pos + 4 + sz as u64 > len {
break;
}
samples.push((pos + 4, sz));
pos += 4 + sz as u64;
} else if pos == 0 && &hdr[0..4] == b"aPv1" && len <= u32::MAX as u64 {
samples.push((0, len as u32));
break;
} else {
break;
}
}
let Some(&(off0, sz0)) = samples.first() else {
return Err(CodecError::Container("APV: no valid access units".into()));
};
let first = filmcraft_media::reader::read_range(&*reader, off0, sz0 as usize).map_err(|e| CodecError::Container(e.to_string()))?;
let fh = filmcraft_apv::probe(&first).map_err(|e| CodecError::Decode(e.to_string()))?;
let mut color = ColorInfo { matrix: filmcraft_frame::default_matrix(fh.width, fh.height), ..ColorInfo::REC709 };
let mut explicit_color = None;
if fh.color_description_present {
if let Some(m) = Matrix::from_code(fh.color.matrix) {
color.matrix = m;
}
if let Some(t) = Transfer::from_code(fh.color.transfer) {
color.transfer = t;
}
if let Some(p) = primaries_from_code(fh.color.primaries) {
color.primaries = p;
}
if fh.color.full_range {
color.range = Range::Full;
}
explicit_color = Some(color);
}
let rate = FrameRate::FPS_24;
let duration = Tick::from_rational(samples.len() as i64 * rate.den, 1, rate.num);
let total_bits: u64 = samples.iter().map(|s| s.1 as u64 * 8).sum();
let secs = duration.seconds();
let bitrate = (secs > 0.0).then(|| (total_bits as f64 / secs) as u64);
let codec = match filmcraft_apv::Profile::from_idc(fh.profile_idc) {
Some(p) => p.name().into(),
None => "APV".into(),
};
let info = MediaInfo {
name: name.to_string(),
kind: MediaKind::Movie,
duration,
video: Some(VideoStreamInfo {
width: fh.width,
height: fh.height,
frame_rate: rate,
par: (1, 1),
codec,
pixel_format: apv_pixfmt_label(fh.chroma, fh.bit_depth),
color,
has_alpha: fh.chroma == filmcraft_apv::ChromaFormat::Yuv4444,
bitrate,
hdr: None,
}),
audio: None,
container: "APV".into(),
start_timecode: None,
file_size: Some(len),
};
Ok(Self { info, bytes: crate::Src(reader), samples, rate, video: GopCache::new(explicit_color) })
}
}
struct ApvVideo<'a>(&'a ApvSource);
impl VideoSamples for ApvVideo<'_> {
fn count(&self) -> usize {
self.0.samples.len()
}
fn pts(&self, i: usize) -> i64 {
i as i64
}
fn sync_before(&self, i: usize) -> usize {
i
}
fn sample_at(&self, t: i64) -> Option<usize> {
(!self.0.samples.is_empty()).then(|| t.clamp(0, self.0.samples.len() as i64 - 1) as usize)
}
fn read(&self, i: usize) -> crate::Result<Vec<u8>> {
let (off, sz) = self.0.samples.get(i).copied().ok_or_else(|| CodecError::Container("sample index out of range".into()))?;
filmcraft_media::reader::read_range(&*self.0.bytes.0, off, sz as usize).map_err(|e| CodecError::Container(e.to_string()))
}
fn make_decoder(&self) -> crate::Result<Box<dyn VideoDecoder>> {
Ok(Box::new(ApvDecoder))
}
}
impl MediaSource for ApvSource {
fn info(&self) -> &MediaInfo {
&self.info
}
fn video_frame(&self, req: FrameRequest) -> Result<Arc<VideoFrame>, MediaError> {
let frame_idx = self.rate.frame_at(req.time.max(Tick::ZERO));
Ok(self.video.frame(&ApvVideo(self), frame_idx)?)
}
fn audio(&self, _start: i64, _frames: usize, _sample_rate: u32) -> Result<AudioBuffer, MediaError> {
Err(MediaError::NoStream("audio"))
}
}
pub fn opener(name: &str, bytes: Arc<[u8]>) -> Option<Result<SharedSource, MediaError>> {
if !sniff(&bytes) {
return None;
}
Some(ApvSource::open(name, bytes).map(|s| Arc::new(s) as SharedSource).map_err(Into::into))
}
pub fn reader_opener(name: &str, head: &[u8], reader: &filmcraft_media::SharedReader) -> Option<Result<SharedSource, MediaError>> {
if !sniff(head) {
return None;
}
Some(ApvSource::open_reader(name, reader.clone()).map(|s| Arc::new(s) as SharedSource).map_err(Into::into))
}
+147 -11
View File
@@ -15,8 +15,8 @@ use symphonia::core::probe::Hint;
use crate::{CodecError, Result};
enum Inner {
/// Our own AAC-LC decoder.
Aac { dec: Box<filmcraft_aac::Decoder>, asc: Vec<u8> },
/// Our own AAC-LC decoder. `up` interpolates HE-AAC's core to the output rate (see [`Upsample2x`]).
Aac { dec: Box<filmcraft_aac::Decoder>, asc: Vec<u8>, up: Option<Box<Upsample2x>> },
/// AAC whose configuration arrives with the first frame (ADTS / LATM).
AacPending,
/// Our own Opus decoder (always 48 kHz output; pre-skip is left to container timestamps).
@@ -82,11 +82,13 @@ impl PacketDecoder {
let dec = symphonia::default::get_codecs().make(&p, &DecoderOptions::default()).map_err(|e| CodecError::Unsupported(e.to_string()))?;
Ok(Self { inner: Inner::Symphonia(dec), channels: 0 })
}
/// AAC: our decoder for AAC-LC; symphonia for other object types (HE-AAC…).
/// AAC: our decoder for AAC-LC and the AAC-LC core of HE-AAC (v1/v2); symphonia for other
/// object types. `sample_rate` is the stream's output rate: when it is twice the core rate
/// (HE-AAC, see [`aac_output_rate`]) the decoded core is upsampled to it.
pub fn aac(asc: &[u8], sample_rate: u32) -> Result<Self> {
let lc = asc.first().map(|b| b >> 3) == Some(2);
if lc && let Ok(dec) = filmcraft_aac::Decoder::new(asc) {
return Ok(Self { inner: Inner::Aac { dec: Box::new(dec), asc: asc.to_vec() }, channels: 0 });
if let Ok(dec) = filmcraft_aac::Decoder::new(asc) {
let up = (dec.sample_rate().checked_mul(2) == Some(sample_rate)).then(|| Box::new(Upsample2x::new(dec.channels())));
return Ok(Self { inner: Inner::Aac { dec: Box::new(dec), asc: asc.to_vec(), up }, channels: 0 });
}
Self::new(CODEC_TYPE_AAC, sample_rate, Some(asc.to_vec()))
}
@@ -119,7 +121,7 @@ impl PacketDecoder {
return Ok(());
}
let dec = filmcraft_aac::Decoder::new(asc).map_err(|e| CodecError::Unsupported(format!("AAC: {e}")))?;
self.inner = Inner::Aac { dec: Box::new(dec), asc: asc.to_vec() };
self.inner = Inner::Aac { dec: Box::new(dec), asc: asc.to_vec(), up: None };
Ok(())
}
/// AC-3 (ATSC A/52).
@@ -133,7 +135,7 @@ impl PacketDecoder {
pub fn for_isobmff(c: &filmcraft_isobmff::CodecConfig, rate: u32) -> Result<Self> {
use filmcraft_isobmff::CodecConfig as C;
match c {
C::Aac(a) => Self::aac(&a.asc, if a.sample_rate > 0 { a.sample_rate } else { rate }),
C::Aac(a) => Self::aac(&a.asc, if rate > 0 { rate } else { a.sample_rate }),
C::Mp3 => Self::new(CODEC_TYPE_MP3, rate, None),
C::Ac3 { .. } => Self::ac3(),
C::Alac { cookie } => Self::new(CODEC_TYPE_ALAC, rate, Some(cookie.clone())),
@@ -145,8 +147,11 @@ impl PacketDecoder {
/// Decode one packet into planar channels.
pub fn decode(&mut self, data: &[u8], ts: u64) -> Result<Vec<Vec<f32>>> {
let dec = match &mut self.inner {
Inner::Aac { dec, .. } => {
let out = dec.decode(data).map_err(|e| CodecError::Decode(e.to_string()))?;
Inner::Aac { dec, up, .. } => {
let mut out = dec.decode(data).map_err(|e| CodecError::Decode(e.to_string()))?;
if let Some(up) = up {
out = up.process(out);
}
self.channels = out.len();
return Ok(out);
}
@@ -202,10 +207,13 @@ impl PacketDecoder {
}
pub fn reset(&mut self) {
match &mut self.inner {
Inner::Aac { dec, asc } => {
Inner::Aac { dec, asc, up } => {
if let Ok(d) = filmcraft_aac::Decoder::new(asc) {
**dec = d;
}
if let Some(up) = up {
up.reset();
}
}
Inner::Opus { dec, .. } => dec.reset(),
Inner::Symphonia(d) => d.reset(),
@@ -215,6 +223,94 @@ impl PacketDecoder {
}
}
/// The output rate of an AAC stream: twice the core rate for HE-AAC (ISO/IEC 14496-3 §1.6.5).
/// Explicit signalling names the rate in the `AudioSpecificConfig`; with implicit signalling (an
/// AAC-LC config at 24 kHz or less) SBR is only visible as fill-element data in the access units,
/// so the first ones are decoded to look for it. `None` if `asc` is not one our decoder reads.
pub fn aac_output_rate<'a>(asc: &[u8], first_units: impl IntoIterator<Item = &'a [u8]>) -> Option<u32> {
let mut dec = filmcraft_aac::Decoder::new(asc).ok()?;
let core = dec.sample_rate();
if let Some(ext) = dec.config().extension_sample_rate {
return Some(ext);
}
if core <= 24_000 {
for au in first_units {
let _ = dec.decode(au);
if dec.sbr() {
return Some(core * 2);
}
}
}
Some(core)
}
/// Taps on each side of the interpolation point in [`Upsample2x`].
const UPSAMPLE_HALF: usize = 12;
/// 2× upsampler for HE-AAC. Our decoder reconstructs the AAC-LC core at half the output rate and
/// not yet the SBR high band, so the core is interpolated to the output rate: timing and pitch are
/// right and the band above the core's Nyquist stays empty. Even outputs are the input samples,
/// odd ones a Blackman-windowed sinc half-band interpolation over 2 × [`UPSAMPLE_HALF`] inputs.
/// The look-ahead delays the output by `UPSAMPLE_HALF` input samples (0.5 ms at 24 kHz); the
/// state carries across packets, so a seek primed with the preceding packet gives the same
/// samples as continuous decoding.
#[derive(Clone)]
pub struct Upsample2x {
taps: [f32; 2 * UPSAMPLE_HALF],
/// The last `2 × UPSAMPLE_HALF` input samples per channel.
hist: Vec<Vec<f32>>,
}
impl Upsample2x {
pub fn new(channels: usize) -> Self {
let m = UPSAMPLE_HALF as f64;
let mut taps = [0f32; 2 * UPSAMPLE_HALF];
let mut sum = 0.0;
for (k, t) in taps.iter_mut().enumerate() {
// distance from the interpolation point (halfway between two inputs)
let x = k as f64 - m + 0.5;
let sinc = (std::f64::consts::PI * x).sin() / (std::f64::consts::PI * x);
let w = 0.42 + 0.5 * (std::f64::consts::PI * x / m).cos() + 0.08 * (2.0 * std::f64::consts::PI * x / m).cos();
*t = (sinc * w) as f32;
sum += sinc * w;
}
for t in &mut taps {
*t = (*t as f64 / sum) as f32;
}
Self { taps, hist: vec![vec![0.0; 2 * UPSAMPLE_HALF]; channels] }
}
pub fn reset(&mut self) {
for h in &mut self.hist {
h.fill(0.0);
}
}
pub fn process(&mut self, input: Vec<Vec<f32>>) -> Vec<Vec<f32>> {
if self.hist.len() < input.len() {
self.hist.resize(input.len(), vec![0.0; 2 * UPSAMPLE_HALF]);
}
let m = UPSAMPLE_HALF;
input
.into_iter()
.zip(&mut self.hist)
.map(|(x, hist)| {
let mut buf = std::mem::take(hist);
buf.extend_from_slice(&x);
let mut out = Vec::with_capacity(x.len() * 2);
// output pair i is centred on buf[i + m]: the sample itself, then the point halfway
// to the next one from buf[i + 1 ..= i + 2m]
for w in buf.windows(2 * m + 1).take(x.len()) {
out.push(w[m]);
out.push(w[1..].iter().zip(&self.taps).map(|(a, b)| a * b).sum());
}
*hist = buf.split_off(buf.len() - 2 * m);
out
})
.collect()
}
}
/// Whether AC-3 audio decodes (our ATSC A/52 decoder).
pub const AC3_DECODER: bool = true;
@@ -603,3 +699,43 @@ pub fn opener(name: &str, bytes: Arc<[u8]>) -> Option<std::result::Result<Shared
}
Some(AudioFileSource::decode(name, bytes).map(|s| Arc::new(s) as SharedSource).map_err(Into::into))
}
#[cfg(test)]
mod he_aac_tests {
use super::*;
/// AAC-LC config, 22.05 kHz stereo.
const LC_22K: [u8; 2] = [0x13, 0x90];
/// An access unit holding only a fill element with SBR data (ID_FIL, EXT_SBR_DATA, ID_END).
const SBR_FILL: [u8; 3] = [0b1100_0011, 0b1010_0001, 0b1100_0000];
#[test]
fn output_rate_doubles_for_he_aac() {
// explicit: the extension rate from the config
assert_eq!(aac_output_rate(&[0x2B, 0x92, 0x08, 0x00], []), Some(44_100));
// implicit: SBR data in the first access units of a ≤ 24 kHz AAC-LC stream
assert_eq!(aac_output_rate(&LC_22K, [&SBR_FILL[..]]), Some(44_100));
assert_eq!(aac_output_rate(&LC_22K, []), Some(22_050));
// AAC-LC at 44.1 kHz stays as it is, even with SBR-looking fill data
assert_eq!(aac_output_rate(&[0x12, 0x10], [&SBR_FILL[..]]), Some(44_100));
}
#[test]
fn upsampler_interpolates_continuously_across_packets() {
let f = 1000.0 / 22_050.0;
let x: Vec<f32> = (0..4096).map(|i| (2.0 * std::f32::consts::PI * f * i as f32).sin()).collect();
let mut up = Upsample2x::new(1);
let mut y = Vec::new();
for chunk in x.chunks(1024) {
y.extend(up.process(vec![chunk.to_vec()]).remove(0));
}
assert_eq!(y.len(), 8192);
// output 2k + 1 is input k − UPSAMPLE_HALF + ½ (the look-ahead delay), within 0.1 %
let d = UPSAMPLE_HALF as f32;
for k in 100..4000 {
let want = (2.0 * std::f32::consts::PI * f * (k as f32 - d + 0.5)).sin();
assert!((y[2 * k + 1] - want).abs() < 1e-3, "{k}: {} vs {want}", y[2 * k + 1]);
assert_eq!(y[2 * k], x[k - UPSAMPLE_HALF]);
}
}
}
+357 -12
View File
@@ -5,8 +5,11 @@
//! for the next frames therefore hit the cache or continue the running decoder without re-seeking.
use std::collections::BTreeMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError, TryLockError, Weak};
use std::time::Duration;
use web_time::Instant;
use filmcraft_color::ColorInfo;
use filmcraft_frame::VideoFrame;
@@ -68,7 +71,7 @@ fn count_frames<T>(out: &[T]) {
/// Run a decoder call, adding its wall time to the process-wide counter.
fn timed<R>(f: impl FnOnce() -> R) -> R {
let t0 = web_time::Instant::now();
let t0 = Instant::now();
let r = f();
DECODE_NS.fetch_add(t0.elapsed().as_nanos() as u64, Ordering::Relaxed);
r
@@ -135,9 +138,35 @@ struct State {
/// The cached frames that were decoded in draft mode: served to draft requests only.
drafts: std::collections::BTreeSet<i64>,
bytes: usize,
/// When a frame was last asked of this cache.
last_used: Instant,
}
impl State {
/// Give up the decoder (and the spare intra decoders): the next request that has to decode
/// makes a new one and restarts at a sync sample. Returned so they are dropped off the lock.
fn release_decoder(&mut self, pool: &Pool) -> Vec<Box<dyn VideoDecoder>> {
let mut out = std::mem::take(&mut self.spare);
if let Some(d) = self.decoder.take() {
pool.decoders.fetch_sub(1, Ordering::Relaxed);
out.push(d);
}
self.next = usize::MAX;
out
}
/// Evict frames, earliest first, while `more` says so.
fn release_frames(&mut self, pool: &Pool, more: impl Fn() -> bool) {
while more() {
let Some((pts, f)) = self.frames.pop_first() else { break };
self.drafts.remove(&pts);
self.bytes = self.bytes.saturating_sub(f.byte_size());
pool.bytes.fetch_sub(f.byte_size(), Ordering::Relaxed);
EVICTED.fetch_add(1, Ordering::Relaxed);
filmcraft_frame::pool::recycle(f);
}
}
/// The cached frame at `pts`, unless it is a draft frame and the request wants the exact one.
fn cached(&self, pts: i64, draft_ok: bool) -> Option<&Arc<VideoFrame>> {
self.frames.get(&pts).filter(|_| draft_ok || !self.drafts.contains(&pts))
@@ -178,9 +207,140 @@ impl Drop for DecodingGuard {
}
}
/// A decoder keeps its reference and in-flight pictures (hundreds of MB for a frame-threaded
/// 4K decoder), so only this many caches keep theirs once idle: a timeline's other clips make a
/// new one when the playhead reaches them, which costs what a seek costs.
const MAX_LIVE_DECODERS: usize = 4;
/// A cache asked for a frame this recently is in use (a layer of the frame being composited,
/// the next clip being prefetched): it keeps its decoder whatever the count.
const IDLE: Duration = Duration::from_secs(3);
/// Decoded frames all caches may hold together before idle ones give theirs up. Each cache also
/// has its own budget, which alone let every clip on a timeline keep hundreds of MB of frames
/// nobody was looking at.
pub const FRAME_BUDGET: usize = 1 << 30;
/// What the caches of a process share: the cap on live decoders and the frame budget.
struct Pool {
caches: Mutex<Vec<Weak<Shared>>>,
/// Caches that hold a decoder.
decoders: AtomicUsize,
max_decoders: usize,
idle: Duration,
/// Bytes of the frames the caches hold.
bytes: AtomicUsize,
budget: usize,
}
/// The part of a [`GopCache`] its pool reaches.
struct Shared {
state: Mutex<State>,
pool: Arc<Pool>,
}
impl Drop for Shared {
fn drop(&mut self) {
let st = self.state.get_mut().unwrap_or_else(PoisonError::into_inner);
drop(st.release_decoder(&self.pool));
self.pool.bytes.fetch_sub(st.bytes, Ordering::Relaxed);
}
}
/// A cache's state unless another thread is using it (it is then decoding: not idle).
fn try_state(c: &Shared) -> Option<MutexGuard<'_, State>> {
match c.state.try_lock() {
Ok(g) => Some(g),
Err(TryLockError::Poisoned(e)) => Some(e.into_inner()),
Err(TryLockError::WouldBlock) => None,
}
}
impl Pool {
fn new(max_decoders: usize, idle: Duration, budget: usize) -> Self {
Self { caches: Mutex::new(Vec::new()), decoders: AtomicUsize::new(0), max_decoders, idle, bytes: AtomicUsize::new(0), budget }
}
/// The pool of every cache in the process.
fn global() -> Arc<Pool> {
static POOL: std::sync::OnceLock<Arc<Pool>> = std::sync::OnceLock::new();
POOL.get_or_init(|| Arc::new(Pool::new(MAX_LIVE_DECODERS, IDLE, FRAME_BUDGET))).clone()
}
fn register(&self, c: &Arc<Shared>) {
let mut g = self.caches.lock().unwrap_or_else(PoisonError::into_inner);
g.retain(|w| w.strong_count() > 0);
g.push(Arc::downgrade(c));
}
/// The idle caches other than `me` that `keep` selects, least recently used first. Other
/// caches are only ever try-locked, so two caches trimming each other cannot deadlock.
fn idle_others(&self, me: &Shared, keep: impl Fn(&State) -> bool) -> Vec<Arc<Shared>> {
let all: Vec<Arc<Shared>> = self.caches.lock().unwrap_or_else(PoisonError::into_inner).iter().filter_map(Weak::upgrade).collect();
let mut idle: Vec<(Instant, Arc<Shared>)> = all
.into_iter()
.filter(|c| !std::ptr::eq(Arc::as_ptr(c), me))
.filter_map(|c| {
let used = try_state(&c).filter(|st| keep(st) && st.last_used.elapsed() >= self.idle).map(|st| st.last_used)?;
Some((used, c))
})
.collect();
idle.sort_by_key(|(used, _)| *used);
idle.into_iter().map(|(_, c)| c).collect()
}
/// Take the decoders of idle caches, least recently used first, down to the cap. The caller
/// drops them with no cache lock held: dropping a decoder can block (a hardware session waits
/// for its frames in flight).
#[must_use = "drop the released decoders with no cache lock held"]
fn trim_decoders(&self, me: &Shared) -> Vec<Box<dyn VideoDecoder>> {
let mut released = Vec::new();
if self.decoders.load(Ordering::Relaxed) <= self.max_decoders {
return released;
}
for c in self.idle_others(me, |st| st.decoder.is_some()) {
if self.decoders.load(Ordering::Relaxed) <= self.max_decoders {
break;
}
if let Some(mut st) = try_state(&c) {
released.extend(st.release_decoder(self));
}
}
released
}
/// Evict the frames of idle caches, least recently used first, down to the budget. Caches in
/// use keep theirs (each within its own budget): a frame evicted before it is shown costs a
/// re-decode from the keyframe.
fn trim_frames(&self, me: &Shared) {
let over = || self.bytes.load(Ordering::Relaxed) > self.budget;
if !over() {
return;
}
for c in self.idle_others(me, |st| !st.frames.is_empty()) {
if !over() {
break;
}
if let Some(mut st) = try_state(&c) {
st.release_frames(self, over);
}
}
}
}
/// Caches that hold a decoder right now, process-wide (`perf.stats`).
pub fn live_decoders() -> usize {
Pool::global().decoders.load(Ordering::Relaxed)
}
/// Bytes of decoded frames the caches hold right now, process-wide (`perf.stats`).
pub fn cached_bytes() -> usize {
Pool::global().bytes.load(Ordering::Relaxed)
}
/// Decoder + decoded-frame cache for one video track.
pub struct GopCache {
state: Mutex<State>,
shared: Arc<Shared>,
/// Colour signalled by the container, which wins over the bitstream's.
explicit_color: Option<ColorInfo>,
/// Clockwise quarter turns from the container's display matrix, applied to every frame.
@@ -200,7 +360,13 @@ const CONTINUE_THROUGH: usize = 48;
impl GopCache {
pub fn new(explicit_color: Option<ColorInfo>) -> Self {
Self {
// unit tests count decoder restarts: each of their caches gets a pool of its own
let pool = if cfg!(test) { Arc::new(Pool::new(MAX_LIVE_DECODERS, IDLE, FRAME_BUDGET)) } else { Pool::global() };
Self::in_pool(explicit_color, pool)
}
fn in_pool(explicit_color: Option<ColorInfo>, pool: Arc<Pool>) -> Self {
let shared = Arc::new(Shared {
state: Mutex::new(State {
decoder: None,
intra: false,
@@ -211,11 +377,12 @@ impl GopCache {
frames: BTreeMap::new(),
drafts: Default::default(),
bytes: 0,
last_used: Instant::now(),
}),
explicit_color,
rotation: 0,
budget: 384 << 20,
}
pool: pool.clone(),
});
pool.register(&shared);
Self { shared, explicit_color, rotation: 0, budget: 384 << 20 }
}
/// Turn every decoded frame clockwise by `quarter_turns` × 90° (the container's display
@@ -245,9 +412,11 @@ impl GopCache {
st.drafts.remove(&pts);
}
let budget = self.budget.max(MIN_FRAMES * f.byte_size());
let before = st.bytes;
st.bytes += f.byte_size();
if let Some(old) = st.frames.insert(pts, Arc::new(f)) {
st.bytes -= old.byte_size();
filmcraft_frame::pool::recycle(old);
}
// evict frames far from the most recent (keep a window around the working position)
while st.bytes > budget && st.frames.len() > 2 {
@@ -257,8 +426,17 @@ impl GopCache {
st.drafts.remove(&victim);
st.bytes -= v.byte_size();
EVICTED.fetch_add(1, Ordering::Relaxed);
// its planes serve the next decoded pictures instead of going back to the allocator
filmcraft_frame::pool::recycle(v);
}
}
let pool = &self.shared.pool;
if st.bytes >= before {
pool.bytes.fetch_add(st.bytes - before, Ordering::Relaxed);
} else {
pool.bytes.fetch_sub(before - st.bytes, Ordering::Relaxed);
}
pool.trim_frames(&self.shared);
}
/// Store decoder output (in presentation order) and advance `out_max`.
@@ -297,8 +475,13 @@ impl GopCache {
return self.private_frame(s, i, want_pts, n);
}
let draft = filmcraft_media::cancel::draft();
let mut st = self.state.lock().unwrap_or_else(|e| e.into_inner());
// Idle caches' decoders released below. Declared before the lock guard, so it is dropped
// after the guard on every return path: dropping a decoder can block (a hardware session
// waits for its frames in flight) and must not hold this cache's lock.
let mut released: Vec<Box<dyn VideoDecoder>> = Vec::new();
let mut st = self.shared.state.lock().unwrap_or_else(|e| e.into_inner());
let _decoding = DecodingGuard::enter(me);
st.last_used = Instant::now();
if let Some(f) = st.cached(want_pts, draft) {
HITS.fetch_add(1, Ordering::Relaxed);
return Ok(f.clone());
@@ -309,7 +492,9 @@ impl GopCache {
st.intra = d.intra_only();
st.decoder = Some(d);
st.next = usize::MAX;
self.shared.pool.decoders.fetch_add(1, Ordering::Relaxed);
}
released.extend(self.shared.pool.trim_decoders(&self.shared));
// Nothing cached: the work ahead (possibly a seek and a GOP of decoding) is only worth it
// while someone still wants the frame.
if filmcraft_media::cancel::cancelled() {
@@ -462,7 +647,7 @@ impl GopCache {
DECODED.fetch_add(1, Ordering::Relaxed);
timed(|| dec.decode(&data, want_pts))
});
let mut st = self.state.lock().unwrap_or_else(|e| e.into_inner());
let mut st = self.shared.state.lock().unwrap_or_else(|e| e.into_inner());
if st.spare.len() < 16 {
st.spare.push(dec);
}
@@ -480,7 +665,6 @@ mod tests {
use super::*;
use crate::video::DecodedFrame;
use std::collections::VecDeque;
use std::sync::atomic::AtomicUsize;
/// `n` samples, a sync sample every `gop`, pts = 1000 · index (no reordering).
struct Samples {
@@ -716,4 +900,165 @@ mod tests {
assert_eq!(index_of(&c.frame(&s, 7_000).expect("frame")), 7);
assert_eq!(s.resets.load(Ordering::Relaxed), 1);
}
#[test]
fn idle_caches_give_up_their_decoders_beyond_the_cap() {
let pool = Arc::new(Pool::new(2, Duration::ZERO, FRAME_BUDGET));
let live = || pool.decoders.load(Ordering::Relaxed);
let s: Vec<Samples> = (0..5).map(|_| samples(300, 250, 3, false)).collect();
let c: Vec<GopCache> = (0..5).map(|_| GopCache::in_pool(None, pool.clone())).collect();
// a clip after another, as when clips are dropped on a timeline
for k in 0..5 {
assert_eq!(index_of(&c[k].frame(&s[k], 10_000).expect("frame")), 10);
assert!(live() <= 2, "{} live decoders after clip {k}", live());
}
assert_eq!(live(), 2);
// the most recently used keep theirs and carry on without a seek
assert_eq!(index_of(&c[4].frame(&s[4], 20_000).expect("frame")), 20);
assert_eq!(s[4].resets.load(Ordering::Relaxed), 1);
// a cache that lost its decoder still serves what it cached…
let decodes = s[0].decodes.load(Ordering::Relaxed);
assert_eq!(index_of(&c[0].frame(&s[0], 10_000).expect("cached")), 10);
assert_eq!(s[0].decodes.load(Ordering::Relaxed), decodes);
// …and decodes again with a new decoder, from the sync sample
assert_eq!(index_of(&c[0].frame(&s[0], 20_000).expect("frame")), 20);
assert_eq!(s[0].resets.load(Ordering::Relaxed), 2);
assert_eq!(live(), 2);
// a dropped cache no longer counts
drop(c);
assert_eq!(live(), 0);
}
#[test]
fn caches_in_use_keep_their_decoders_whatever_the_cap() {
// every layer of one composited frame was asked moments ago: none is idle
let pool = Arc::new(Pool::new(2, Duration::from_secs(3600), FRAME_BUDGET));
let s: Vec<Samples> = (0..5).map(|_| samples(300, 250, 3, false)).collect();
let c: Vec<GopCache> = (0..5).map(|_| GopCache::in_pool(None, pool.clone())).collect();
for t in [10_000, 11_000, 12_000] {
for k in 0..5 {
assert_eq!(index_of(&c[k].frame(&s[k], t).expect("frame")) as i64, t / 1000);
}
}
assert_eq!(pool.decoders.load(Ordering::Relaxed), 5);
assert!(s.iter().all(|s| s.resets.load(Ordering::Relaxed) == 1), "no decoder restarted");
}
#[test]
fn intra_caches_give_up_their_spare_decoders_too() {
let pool = Arc::new(Pool::new(1, Duration::ZERO, FRAME_BUDGET));
let (a, b) = (samples(50, 1, 0, true), samples(50, 1, 0, true));
let (ca, cb) = (GopCache::in_pool(None, pool.clone()), GopCache::in_pool(None, pool.clone()));
assert_eq!(index_of(&ca.frame(&a, 3_000).expect("frame")), 3);
assert_eq!(index_of(&cb.frame(&b, 4_000).expect("frame")), 4);
let st = ca.shared.state.lock().unwrap();
assert!(st.decoder.is_none() && st.spare.is_empty());
drop(st);
assert_eq!(pool.decoders.load(Ordering::Relaxed), 1);
assert_eq!(index_of(&ca.frame(&a, 5_000).expect("frame")), 5);
}
#[test]
fn idle_caches_give_up_their_frames_beyond_the_shared_budget() {
// 1×1 RGBA pictures: 4 bytes each, a shared budget of ten of them
let pool = Arc::new(Pool::new(usize::MAX, Duration::ZERO, 40));
let held = || pool.bytes.load(Ordering::Relaxed);
let (a, b) = (samples(300, 250, 0, false), samples(300, 250, 0, false));
let (ca, cb) = (GopCache::in_pool(None, pool.clone()), GopCache::in_pool(None, pool.clone()));
// the only cache keeps what its own budget allows
assert_eq!(index_of(&ca.frame(&a, 10_000).expect("frame")), 10);
assert_eq!(held(), 44);
// a second clip takes the room from the idle first one, earliest frames first
assert_eq!(index_of(&cb.frame(&b, 5_000).expect("frame")), 5);
assert_eq!(held(), 40);
let decodes = b.decodes.load(Ordering::Relaxed);
assert!((0..=5).all(|i| index_of(&cb.frame(&b, i * 1000).expect("cached")) as i64 == i));
assert_eq!(b.decodes.load(Ordering::Relaxed), decodes, "the clip in use lost nothing");
let st = ca.shared.state.lock().unwrap();
assert_eq!((st.frames.len(), st.bytes), (4, 16));
assert_eq!(st.frames.keys().next(), Some(&7_000));
drop(st);
// an evicted frame decodes again
assert_eq!(index_of(&ca.frame(&a, 2_000).expect("frame")), 2);
assert!(held() <= 40 + 4 * 3, "{} bytes held", held());
drop((ca, cb));
assert_eq!(held(), 0);
}
#[test]
fn caches_in_use_keep_their_frames_whatever_the_shared_budget() {
let pool = Arc::new(Pool::new(usize::MAX, Duration::from_secs(3600), 40));
let (a, b) = (samples(300, 250, 0, false), samples(300, 250, 0, false));
let (ca, cb) = (GopCache::in_pool(None, pool.clone()), GopCache::in_pool(None, pool.clone()));
assert_eq!(index_of(&ca.frame(&a, 10_000).expect("frame")), 10);
assert_eq!(index_of(&cb.frame(&b, 10_000).expect("frame")), 10);
assert_eq!(pool.bytes.load(Ordering::Relaxed), 88);
let decodes = a.decodes.load(Ordering::Relaxed);
assert_eq!(index_of(&ca.frame(&a, 0).expect("cached")), 0);
assert_eq!(a.decodes.load(Ordering::Relaxed), decodes);
}
/// Pictures big enough for the plane pool (its own size, so that parallel tests cannot take
/// the buffers), no reordering, one long GOP.
struct Big(usize);
const BIG: (u32, u32) = (200, 101);
impl VideoDecoder for Big {
fn decode(&mut self, _sample: &[u8], pts: i64) -> crate::Result<Vec<DecodedFrame>> {
let mut px = filmcraft_frame::pool::take_u8((BIG.0 * BIG.1 * 4) as usize);
px.resize((BIG.0 * BIG.1 * 4) as usize, (pts / 1000) as u8);
Ok(vec![DecodedFrame { pts, frame: VideoFrame::rgba8(BIG.0, BIG.1, px), draft: false }])
}
fn flush(&mut self) -> Vec<DecodedFrame> {
Vec::new()
}
fn reset(&mut self) {}
fn name(&self) -> &str {
"big"
}
}
impl VideoSamples for Big {
fn count(&self) -> usize {
self.0
}
fn pts(&self, i: usize) -> i64 {
i as i64 * 1000
}
fn sync_before(&self, _i: usize) -> usize {
0
}
fn sample_at(&self, t: i64) -> Option<usize> {
let i = (t / 1000) as usize;
(i < self.0).then_some(i)
}
fn read(&self, i: usize) -> crate::Result<Vec<u8>> {
Ok(vec![i as u8])
}
fn make_decoder(&self) -> crate::Result<Box<dyn VideoDecoder>> {
Ok(Box::new(Big(self.0)))
}
}
#[test]
fn evicted_frames_are_decoded_into_again() {
let s = Big(200);
// room for MIN_FRAMES pictures only
let mut c = GopCache::new(None);
c.budget = 0;
let reused = || filmcraft_frame::pool::stats().reused;
let before = reused();
// the cache holds MIN_FRAMES pictures: none is evicted yet, every plane is new
for i in 0..MIN_FRAMES as i64 {
assert_eq!(c.frame(&s, i * 1000).expect("frame").width, BIG.0);
}
assert_eq!(reused(), before);
// from here on each picture evicts one, whose buffer the next picture is decoded into
let more = 40;
for i in MIN_FRAMES as i64..MIN_FRAMES as i64 + more {
let f = c.frame(&s, i * 1000).expect("frame");
assert!(matches!(&f.data, filmcraft_frame::PixelData::Rgba8(d) if d.iter().all(|&b| b == i as u8)), "frame {i} has its own pixels");
}
assert!(reused() - before >= more as u64 - 2, "{} of {more} planes recycled", reused() - before);
}
}
+79
View File
@@ -12,6 +12,7 @@ use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use filmcraft_isobmff::{CodecConfig, SampleEntry};
pub use crate::hw_frame::{FrameCodec, FrameStreamInfo, PictureParams};
use crate::video::{avcc_length_size, h264_disposable, hevc_disposable, hvcc_length_size_and_tid, sar_par, vui_color};
use crate::{CodecError, Result};
@@ -29,6 +30,19 @@ pub fn hardware_decoding() -> bool {
ENABLED.load(Ordering::Relaxed)
}
static BACKEND: std::sync::Mutex<Option<&'static str>> = std::sync::Mutex::new(None);
/// Record the OS decoder backend `filmcraft_platform::register` put in front of our decoders
/// ("VideoToolbox", "Media Foundation"), for `perf.stats`.
pub fn set_hw_backend(name: &'static str) {
*BACKEND.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(name);
}
/// The registered hardware decoder backend, if any ([`set_hw_backend`]).
pub fn hw_backend() -> Option<&'static str> {
*BACKEND.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
/// Process-wide hardware decoding counters (they only grow; subtract two snapshots to measure an
/// interval). Frames decoded in software are `GopStats::frames - frames`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
@@ -120,6 +134,71 @@ pub struct NalStreamInfo {
pub reorder: usize,
}
/// Any stream a hardware decoder can take: what [`crate::hw`]'s hybrid decoder needs to know about
/// it to find restart points and in-band parameter changes.
#[derive(Clone, Debug)]
pub enum StreamInfo {
Nal(NalStreamInfo),
Frame(FrameStreamInfo),
}
impl From<NalStreamInfo> for StreamInfo {
fn from(i: NalStreamInfo) -> Self {
Self::Nal(i)
}
}
impl From<FrameStreamInfo> for StreamInfo {
fn from(i: FrameStreamInfo) -> Self {
Self::Frame(i)
}
}
impl StreamInfo {
/// Whether decoding can restart at `sample` with no earlier state (IDR / IRAP, a key frame).
pub fn is_irap(&self, sample: &[u8]) -> bool {
match self {
Self::Nal(i) => i.is_irap(sample),
Self::Frame(i) => i.is_random_access(sample),
}
}
/// An HEVC CRA restarts nothing by itself (its RASL pictures need the previous restart point).
pub fn keeps_previous_restart(&self, sample: &[u8]) -> bool {
match self {
Self::Nal(i) => i.codec == NalCodec::Hevc && i.nal_types(sample).contains(&21),
Self::Frame(_) => false,
}
}
/// Whether `sample` carries parameters different from the ones the hardware decoder was set up
/// with (parameter sets, a sequence header, a key frame of another format).
pub fn parameters_changed(&self, sample: &[u8]) -> bool {
match self {
Self::Nal(i) => {
i.nals(sample).into_iter().any(|n| n.first().is_some_and(|&h| i.is_parameter_set(i.nal_type(h))) && !i.parameter_sets.iter().any(|p| p == n))
}
Self::Frame(i) => i.parameters_changed(sample),
}
}
/// As the software decoder's [`crate::VideoDecoder::is_random_access`].
pub fn is_random_access(&self, sample: &[u8]) -> Option<bool> {
match self {
Self::Nal(i) => i.is_random_access(sample),
Self::Frame(i) => Some(i.is_random_access(sample)),
}
}
/// As the software decoder's [`crate::VideoDecoder::is_disposable`].
pub fn is_disposable(&self, sample: &[u8]) -> bool {
match self {
Self::Nal(i) => i.is_disposable(sample),
Self::Frame(_) => false,
}
}
}
/// Length-prefixed parameter-set entries (`u16` length + bytes) starting at `pos`.
fn read_sets(rec: &[u8], pos: &mut usize, count: usize, out: &mut Vec<Vec<u8>>) -> Result<()> {
for _ in 0..count {
+256
View File
@@ -0,0 +1,256 @@
//! What a hardware decoder needs to know about a VP9 or AV1 stream so that it behaves exactly like
//! our software decoder for it (the frame-coded counterpart of [`crate::hw::NalStreamInfo`]):
//! codec profile, bit depth and chroma format from the container's `vpcC` / `av1C`, the picture
//! size and colour as the software decoder reports them (read from the bitstream the same way),
//! random-access samples, and in-band changes of the stream's parameters.
use filmcraft_color::{ColorInfo, Primaries, Transfer};
use filmcraft_isobmff::{CodecConfig, SampleEntry};
use crate::video::primaries_from_code;
use crate::{CodecError, Result};
/// The two frame-coded codecs hardware decoders take besides H.264 / HEVC.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FrameCodec {
Vp9,
Av1,
}
/// Picture parameters read from a random-access sample.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PictureParams {
/// Picture size in luma samples (the decoded size).
pub size: (u32, u32),
pub bit_depth: u32,
/// `subsampling_x`, `subsampling_y`.
pub subsampling: (u8, u8),
/// Colour of every output picture, as the software decoder reports it.
pub color: ColorInfo,
}
/// A VP9 or AV1 stream, from its sample entry.
#[derive(Clone, Debug)]
pub struct FrameStreamInfo {
pub codec: FrameCodec,
/// VP9 `profile` (0..=3) / AV1 `seq_profile` (0..=2).
pub profile: u8,
pub bit_depth: u32,
pub subsampling: (u8, u8),
pub mono: bool,
/// Picture size: the sample entry's, checked against the bitstream's.
pub size: (u32, u32),
/// AV1: the `av1C` configuration OBUs (the sequence header the decoder is primed with).
pub config_obus: Vec<u8>,
/// AV1: the sequence header's payload; VP9: none.
sequence_header: Option<Vec<u8>>,
/// Colour of the stream when it is known before the first picture (AV1: from the sequence
/// header).
pub color: Option<ColorInfo>,
/// VP9: transfer and primaries from the container (not in the bitstream).
transfer: Option<Transfer>,
primaries: Option<Primaries>,
}
/// The OBUs of a low-overhead AV1 sample: `(type, payload)`, stopping at the first malformed one.
fn obus(data: &[u8]) -> Vec<(u8, &[u8])> {
let mut out = Vec::new();
let mut pos = 0usize;
while let Some(&h) = data.get(pos) {
let (obu_type, ext, has_size) = ((h >> 3) & 0xf, h & 4 != 0, h & 2 != 0);
let mut p = pos + 1 + usize::from(ext);
let size = if has_size {
let (mut v, mut shift, mut n) = (0usize, 0u32, 0usize);
loop {
let Some(&b) = data.get(p + n) else { return out };
v |= usize::from(b & 0x7f).checked_shl(shift).unwrap_or(0);
n += 1;
if b & 0x80 == 0 || n >= 8 {
break;
}
shift += 7;
}
p += n;
v
} else {
data.len().saturating_sub(p)
};
let Some(payload) = data.get(p..p.saturating_add(size)) else { return out };
out.push((obu_type, payload));
pos = p + size;
}
out
}
/// VP9 colour as our decoder reports it: `color_space` and range from the bitstream, transfer and
/// primaries from the container when it says. (Shared with `Vp9Decoder`.)
pub(crate) fn vp9_color(width: u32, height: u32, color_space: u8, full_range: bool, transfer: Option<Transfer>, primaries: Option<Primaries>) -> ColorInfo {
use filmcraft_color::{Matrix, Range};
let mut color = ColorInfo { matrix: filmcraft_frame::default_matrix(width, height), ..ColorInfo::REC709 };
// color_space (7.2.2): 1 BT.601, 2 BT.709, 3 SMPTE-170, 4 SMPTE-240, 5 BT.2020, 7 sRGB.
match color_space {
1 | 3 => color.matrix = Matrix::Bt601,
2 | 4 => color.matrix = Matrix::Bt709,
5 => {
color.matrix = Matrix::Bt2020Ncl;
color.primaries = Primaries::Bt2020;
}
_ => {}
}
if let Some(t) = transfer {
color.transfer = t;
}
if let Some(p) = primaries {
color.primaries = p;
}
if full_range {
color.range = Range::Full;
}
color
}
/// AV1 colour as our decoder reports it. (Shared with `Av1Decoder`.)
pub(crate) fn av1_color(width: u32, height: u32, matrix_coefficients: u8, transfer: u8, primaries: u8, full_range: bool) -> ColorInfo {
let mut color = ColorInfo::REC709;
color.matrix = filmcraft_color::Matrix::from_code(matrix_coefficients).unwrap_or_else(|| filmcraft_frame::default_matrix(width, height));
if let Some(t) = Transfer::from_code(transfer) {
color.transfer = t;
}
color.primaries = match primaries {
9 => Primaries::Bt2020,
12 => Primaries::P3D65,
5 => Primaries::Bt601_625,
6 => Primaries::Bt601_525,
_ => Primaries::Bt709,
};
if full_range {
color.range = filmcraft_color::Range::Full;
}
color
}
impl FrameStreamInfo {
/// The stream info of a `vpcC` / `av1C` sample entry (`None` for other codecs).
pub fn from_entry(e: &SampleEntry) -> Option<Result<Self>> {
let size = e.video.as_ref().map_or((0, 0), |v| (u32::from(v.width), u32::from(v.height)));
match &e.codec {
CodecConfig::Vp9(c) => {
// vpcC chroma_subsampling: 0 / 1 4:2:0, 2 4:2:2, 3 4:4:4
let subsampling = match c.chroma_subsampling {
0 | 1 => (1, 1),
2 => (1, 0),
_ => (0, 0),
};
Some(Ok(Self {
codec: FrameCodec::Vp9,
profile: c.profile,
bit_depth: u32::from(c.bit_depth),
subsampling,
mono: false,
size,
config_obus: Vec::new(),
sequence_header: None,
color: None,
transfer: Transfer::from_code(c.transfer_characteristics),
primaries: primaries_from_code(c.colour_primaries),
}))
}
CodecConfig::Av1(c) => Some(Self::from_av1(c, size)),
_ => None,
}
}
fn from_av1(c: &filmcraft_isobmff::Av1Config, entry_size: (u32, u32)) -> Result<Self> {
let seq =
obus(&c.config_obus).into_iter().find(|(t, _)| *t == 1).map(|(_, p)| p).ok_or_else(|| CodecError::Decode("av1C has no sequence header".into()))?;
let h = filmcraft_av1::SequenceHeader::parse(seq).map_err(|e| CodecError::Decode(e.to_string()))?;
let size = (h.max_frame_width, h.max_frame_height);
if entry_size != (0, 0) && entry_size != size {
// the sample entry and the sequence header disagree: leave the stream to our decoder
return Err(CodecError::Decode(format!("sample entry says {}x{}, the sequence header {}x{}", entry_size.0, entry_size.1, size.0, size.1)));
}
let cc = &h.color;
Ok(Self {
codec: FrameCodec::Av1,
profile: h.profile,
bit_depth: u32::from(cc.bit_depth),
subsampling: (cc.subsampling_x, cc.subsampling_y),
mono: cc.mono_chrome,
size,
config_obus: c.config_obus.clone(),
sequence_header: Some(seq.to_vec()),
color: Some(av1_color(size.0, size.1, cc.matrix_coefficients, cc.transfer_characteristics, cc.color_primaries, cc.color_range)),
transfer: None,
primaries: None,
})
}
/// Whether `sample` has a sequence header OBU of its own (AV1).
pub fn carries_sequence_header(&self, sample: &[u8]) -> bool {
self.codec == FrameCodec::Av1 && obus(sample).iter().any(|(t, _)| *t == 1)
}
/// A description made by hand (tests of what a backend declines).
#[doc(hidden)]
pub fn for_tests(codec: FrameCodec, profile: u8, bit_depth: u32, subsampling: (u8, u8), size: (u32, u32)) -> Self {
Self {
codec,
profile,
bit_depth,
subsampling,
mono: false,
size,
config_obus: Vec::new(),
sequence_header: None,
color: None,
transfer: None,
primaries: None,
}
}
/// Whether decoding can start at `sample` (a VP9 key frame / an AV1 temporal unit whose first
/// frame is a shown key frame): the software decoders' own test.
pub fn is_random_access(&self, sample: &[u8]) -> bool {
match self.codec {
FrameCodec::Vp9 => filmcraft_vp9::is_keyframe(sample),
FrameCodec::Av1 => filmcraft_av1::is_key_frame_unit(sample),
}
}
/// The picture parameters a random-access `sample` declares (a VP9 key frame header; an AV1
/// sample carrying a sequence header), or `None`.
pub fn picture_params(&self, sample: &[u8]) -> Option<PictureParams> {
match self.codec {
FrameCodec::Vp9 => {
let k = filmcraft_vp9::keyframe_info(sample)?;
let color = vp9_color(k.width, k.height, k.color.color_space, k.color.full_range, self.transfer, self.primaries);
Some(PictureParams {
size: (k.width, k.height),
bit_depth: k.bit_depth,
subsampling: (u8::from(k.subsampling_x), u8::from(k.subsampling_y)),
color,
})
}
FrameCodec::Av1 => {
let seq = obus(sample).into_iter().find(|(t, _)| *t == 1).map(|(_, p)| p)?;
let h = filmcraft_av1::SequenceHeader::parse(seq).ok()?;
let cc = &h.color;
let size = (h.max_frame_width, h.max_frame_height);
let color = av1_color(size.0, size.1, cc.matrix_coefficients, cc.transfer_characteristics, cc.color_primaries, cc.color_range);
Some(PictureParams { size, bit_depth: u32::from(cc.bit_depth), subsampling: (cc.subsampling_x, cc.subsampling_y), color })
}
}
}
/// Whether `sample` declares parameters the hardware session was not set up for: an AV1
/// sequence header that differs from `av1C`'s, a VP9 key frame of another size, bit depth or
/// chroma format. The decoder then hands the stream to our software decoder.
pub fn parameters_changed(&self, sample: &[u8]) -> bool {
match self.codec {
FrameCodec::Av1 => obus(sample).into_iter().any(|(t, p)| t == 1 && self.sequence_header.as_deref() != Some(p)),
FrameCodec::Vp9 => {
self.picture_params(sample).is_some_and(|p| p.size != self.size || p.bit_depth != self.bit_depth || p.subsampling != self.subsampling)
}
}
}
}
+16 -5
View File
@@ -18,9 +18,11 @@
#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))]
pub mod apv;
pub mod audio;
pub mod gop;
pub mod hw;
mod hw_frame;
pub mod mkv;
pub mod mp4;
pub mod mpeg;
@@ -30,8 +32,9 @@ pub mod video;
use std::sync::{Arc, RwLock};
pub use apv::ApvSource;
pub use audio::AudioFileSource;
pub use gop::{GopStats, gop_stats};
pub use gop::{FRAME_BUDGET, GopStats, cached_bytes, gop_stats, live_decoders};
pub use mkv::MkvSource;
pub use mp4::Mp4Source;
pub use mpeg::MpegSource;
@@ -65,11 +68,12 @@ impl From<CodecError> for filmcraft_media::MediaError {
}
/// Our own (pure-Rust) decoders, in the order they are tried.
const BUILTIN_FACTORIES: [VideoDecoderFactory; 8] = [
const BUILTIN_FACTORIES: [VideoDecoderFactory; 9] = [
video::h264_factory,
video::hevc_factory,
video::vp9_factory,
video::av1_factory,
video::apv_factory,
video::prores_factory,
video::dnx_factory,
video::mjpeg_factory,
@@ -89,6 +93,11 @@ pub fn register_video_decoder(f: VideoDecoderFactory) {
}
}
/// Whether `f` is among the registered video decoder factories (startup diagnostics, tests).
pub fn video_decoder_registered(f: VideoDecoderFactory) -> bool {
factories().read().unwrap_or_else(|e| e.into_inner()).iter().any(|x| std::ptr::fn_addr_eq(*x, f))
}
/// Create a decoder for a sample entry.
pub fn make_video_decoder(entry: &filmcraft_isobmff::SampleEntry) -> Result<Box<dyn VideoDecoder>> {
let g = factories().read().unwrap_or_else(|e| e.into_inner());
@@ -112,14 +121,14 @@ pub fn software_video_decoder(entry: &filmcraft_isobmff::SampleEntry) -> Result<
}
/// Openers for the engine's media pool (MP4/MOV, Matroska/WebM, MXF, Ogg Opus/Vorbis, MPEG TS/PS and
/// MPEG-1/2 video elementary streams, standalone audio).
/// MPEG-1/2 video elementary streams, APV raw bitstreams, standalone audio).
pub fn openers() -> Vec<filmcraft_media::Opener> {
vec![mp4::opener, mkv::opener, mxf::opener, ogg::opener, mpeg::opener, audio::opener]
vec![mp4::opener, mkv::opener, mxf::opener, ogg::opener, mpeg::opener, apv::opener, audio::opener]
}
fn reader_registry() -> &'static RwLock<Vec<filmcraft_media::ReaderOpener>> {
static R: std::sync::OnceLock<RwLock<Vec<filmcraft_media::ReaderOpener>>> = std::sync::OnceLock::new();
R.get_or_init(|| RwLock::new(vec![mp4::reader_opener, mkv::reader_opener, mxf::reader_opener, ogg::reader_opener, mpeg::reader_opener]))
R.get_or_init(|| RwLock::new(vec![mp4::reader_opener, mkv::reader_opener, mxf::reader_opener, ogg::reader_opener, mpeg::reader_opener, apv::reader_opener]))
}
/// Openers that read containers through a [`filmcraft_media::ByteReader`] (index now, samples on
@@ -164,5 +173,7 @@ pub fn open_bytes(name: &str, bytes: Arc<[u8]>) -> std::result::Result<filmcraft
filmcraft_media::open_bytes(name, bytes, &openers())
}
#[cfg(test)]
mod rounded_pts_tests;
#[cfg(test)]
mod tests;
+9 -1
View File
@@ -100,9 +100,12 @@ fn to_tick(t: &filmcraft_matroska::Track, pts: i64) -> Tick {
Tick::from_rational(pts * n, 1, d)
}
/// A time as the track timestamp to look a frame up by: rounded to the nearest tick, as muxers
/// round frame times to `TimestampScale` (usually 1 ms). Flooring skipped every frame whose
/// timestamp was rounded up (every third frame at 30 fps).
fn from_tick(t: &filmcraft_matroska::Track, time: Tick) -> i64 {
let (n, d) = tb(t);
time.to_rational_floor(n, d)
time.to_rational_round(n, d)
}
/// VP9 configuration from the Matroska `CodecPrivate` feature list (ID / length / value triples:
@@ -142,6 +145,7 @@ fn sample_entry(c: &Codec, private: &[u8], v: Option<&filmcraft_matroska::VideoI
Some(match c {
Codec::Vp9 { private } => SampleEntry::video(FourCc(*b"vp09"), CodecConfig::Vp9(vp9_config(private, v)), w, h),
Codec::Av1 { av1c } => SampleEntry::video(FourCc(*b"av01"), CodecConfig::Av1(filmcraft_isobmff::Av1Config::parse(av1c).unwrap_or_default()), w, h),
Codec::Apv { apvc } => SampleEntry::apv(filmcraft_isobmff::ApvConfig::parse(apvc).unwrap_or_default(), w, h),
Codec::Avc { avcc } => SampleEntry::avc(AvcConfig::parse(avcc).ok()?, w, h),
Codec::Hevc { hvcc } => SampleEntry::hevc(HevcConfig::parse(hvcc).ok()?, w, h),
Codec::ProRes { fourcc } => SampleEntry::prores(FourCc(fourcc.unwrap_or(*b"apcn")), w, h),
@@ -203,6 +207,10 @@ fn codec_label(c: &Codec) -> String {
Codec::Vp8 => "VP8".into(),
Codec::Vp9 { .. } => "VP9".into(),
Codec::Av1 { .. } => "AV1".into(),
Codec::Apv { apvc } => match filmcraft_isobmff::ApvConfig::parse(apvc).ok().and_then(|a| filmcraft_apv::Profile::from_idc(a.profile_idc)) {
Some(p) => p.name().into(),
None => "APV".into(),
},
Codec::ProRes { .. } => "Apple ProRes".into(),
Codec::Mjpeg => "Motion JPEG".into(),
Codec::Aac { .. } => "AAC".into(),
+291 -28
View File
@@ -18,6 +18,9 @@ use crate::gop::{GopCache, VideoSamples};
use crate::video::VideoDecoder;
use crate::{CodecError, make_video_decoder};
/// Most bytes read from one AAC access unit when probing for HE-AAC at open (8 channels × 6144 bits).
const MAX_AAC_PROBE_UNIT: usize = 8 * 6144 / 8;
struct AudioState {
decoder: Option<PacketDecoder>,
/// Decoded packets by sample index.
@@ -62,7 +65,7 @@ fn hdr_metadata(md: Option<&filmcraft_isobmff::MasteringDisplay>, cll: Option<(u
fn color_from(entry: &filmcraft_isobmff::SampleEntry, w: u32, h: u32) -> ColorInfo {
let mut c = ColorInfo { matrix: filmcraft_frame::default_matrix(w, h), transfer: Transfer::Bt709, primaries: Primaries::Bt709, range: Range::Limited };
// VP9 carries its colour description in vpcC (used when there is no colr box).
// VP9 and APV carry their colour description in vpcC / apvC (used when there is no colr box).
let vpc = match &entry.codec {
CodecConfig::Vp9(v) => Some(filmcraft_isobmff::ColorInfo::Nclx {
primaries: v.colour_primaries as u16,
@@ -70,6 +73,12 @@ fn color_from(entry: &filmcraft_isobmff::SampleEntry, w: u32, h: u32) -> ColorIn
matrix: v.matrix_coefficients as u16,
full_range: v.full_range,
}),
CodecConfig::Apv(a) if a.color_description_present => Some(filmcraft_isobmff::ColorInfo::Nclx {
primaries: a.color_primaries as u16,
transfer: a.transfer_characteristics as u16,
matrix: a.matrix_coefficients as u16,
full_range: a.full_range,
}),
_ => None,
};
if let Some(col) = entry.video.as_ref().and_then(|v| v.color.as_ref()).or(vpc.as_ref()) {
@@ -148,7 +157,8 @@ impl Mp4Source {
codec: codec_label(&entry.codec),
pixel_format: pixfmt_label(&entry.codec),
color,
has_alpha: matches!(&entry.codec, CodecConfig::ProRes { fourcc } if fourcc.0 == *b"ap4h" || fourcc.0 == *b"ap4x"),
// ProRes 4444 alpha comes from its first frame header (`open_reader`)
has_alpha: matches!(&entry.codec, CodecConfig::Apv(a) if a.chroma_format_idc == 4),
bitrate,
hdr: entry.video.as_ref().and_then(|v| hdr_metadata(v.mastering_display.as_ref(), v.content_light)),
};
@@ -170,6 +180,19 @@ impl Mp4Source {
info.has_alpha = h.alpha;
}
}
if matches!(entry.codec, CodecConfig::ProRes { .. }) {
// a 4444 fourcc doesn't mean the frames carry alpha (alpha_channel_type does): read the first frame header
let s0 = &t.samples[0];
if let Some(h) = filmcraft_media::reader::read_range(&*bytes.0, s0.offset, s0.size as usize).ok().and_then(|d| filmcraft_prores::probe(&d).ok())
{
info.has_alpha = h.alpha != filmcraft_prores::AlphaType::None;
let sub = match h.chroma {
filmcraft_prores::ChromaFormat::Yuv422 => "4:2:2 10-bit",
filmcraft_prores::ChromaFormat::Yuv444 => "4:4:4 12-bit",
};
info.pixel_format = format!("{} {sub}", if info.has_alpha { "YUVA" } else { "YUV" });
}
}
info
});
let audio = atrack.map(|i| {
@@ -178,7 +201,21 @@ impl Mp4Source {
let ap = entry.audio.clone().unwrap_or_default();
let (rate, ch, bits) = match &entry.codec {
CodecConfig::Aac(a) => (
if a.sample_rate > 0 { a.sample_rate } else { ap.sample_rate as u32 },
{
// HE-AAC plays at twice the core rate the AudioSpecificConfig starts with
// an AAC access unit is at most 6144 bits per channel: a hostile `stsz` can't make us read more
let units = t
.samples
.iter()
.take(8)
.filter_map(|x| filmcraft_media::reader::read_range(&*bytes.0, x.offset, (x.size as usize).min(MAX_AAC_PROBE_UNIT)).ok());
let units: Vec<Vec<u8>> = units.collect();
match crate::audio::aac_output_rate(&a.asc, units.iter().map(Vec::as_slice)) {
Some(r) => r,
None if a.sample_rate > 0 => a.sample_rate,
None => ap.sample_rate as u32,
}
},
if a.channel_config > 0 { a.channel_config as u32 } else { ap.channels },
None,
),
@@ -188,17 +225,7 @@ impl Mp4Source {
};
AudioStreamInfo { sample_rate: rate.max(1), channels: ch.max(1), codec: codec_label(&entry.codec), bits_per_sample: bits }
});
let duration = {
let v = vtrack.map(|i| {
let t = &file.tracks[i];
Tick::from_rational(t.duration as i64, 1, t.timescale as i64)
});
let a = atrack.map(|i| {
let t = &file.tracks[i];
Tick::from_rational(t.duration as i64, 1, t.timescale as i64)
});
v.or(a).unwrap_or_default()
};
let duration = vtrack.or(atrack).and_then(|i| file.tracks.get(i)).map(|t| presentation_duration(&file, t)).unwrap_or_default();
let start_timecode = file.tracks.iter().find_map(|t| match t.codec() {
Some(CodecConfig::Timecode(tc)) => tc.start_frame.map(|f| f as i64),
_ => None,
@@ -261,8 +288,10 @@ impl Mp4Source {
fn video_at(&self, t: Tick) -> crate::Result<Arc<VideoFrame>> {
let ti = self.vtrack.ok_or_else(|| CodecError::Unsupported("no video".into()))?;
let ts = self.file.tracks[ti].timescale as i64;
let late = filmcraft_media::cancel::catch_up().map(|m| (t - m).to_rational_floor(1, ts));
self.video.frame_late(&Mp4Video { src: self, track: ti }, t.to_rational_floor(1, ts), late)
// Nearest, not floor: with a coarse timescale (1000) sample times are rounded, and a
// floored lookup lands one unit short of every frame whose time was rounded up.
let late = filmcraft_media::cancel::catch_up().map(|m| (t - m).to_rational_round(1, ts));
self.video.frame_late(&Mp4Video { src: self, track: ti }, t.to_rational_round(1, ts), late)
}
fn audio_packet(&self, st: &mut AudioState, i: usize) -> crate::Result<Arc<Vec<Vec<f32>>>> {
@@ -359,7 +388,10 @@ impl MediaSource for Mp4Source {
let ch = ainfo.channels.max(1) as usize;
// Map the requested window to source samples (edit list offset applied: presentation = pts + edit_offset).
let ratio = src_rate as f64 / sample_rate as f64;
let s0 = (start as f64 * ratio).floor() as i64 - self.audio_offset * src_rate as i64 / track.timescale.max(1) as i64;
let p0 = (start as f64 * ratio).floor() as i64;
// (in i128: a hostile edit list can make the offset large enough to overflow i64)
let offset = i128::from(self.audio_offset) * i128::from(src_rate) / i128::from(track.timescale.max(1));
let s0 = i64::try_from(i128::from(p0) - offset).unwrap_or(if offset > 0 { i64::MIN } else { i64::MAX });
let need = (frames as f64 * ratio).ceil() as i64 + 2;
// Samples-per-unit: the track timescale is usually the sample rate for audio.
let unit = src_rate as f64 / track.timescale.max(1) as f64;
@@ -369,14 +401,14 @@ impl MediaSource for Mp4Source {
let mut i = first;
while i < track.samples.len() {
let pk_start = (self.audio_starts[i] as f64 * unit) as i64;
if pk_start >= s0 + need {
if pk_start >= s0.saturating_add(need) {
break;
}
let pk = self.audio_packet(&mut st, i)?;
for (c, dst) in src.iter_mut().enumerate() {
let Some(chan) = pk.get(c.min(pk.len().saturating_sub(1))) else { continue };
for (k, v) in chan.iter().enumerate() {
let pos = pk_start + k as i64 - s0;
let pos = pk_start.saturating_add(k as i64).saturating_sub(s0);
if pos >= 0 && (pos as usize) < dst.len() {
dst[pos as usize] = *v;
}
@@ -393,8 +425,9 @@ impl MediaSource for Mp4Source {
}
return Ok(out);
}
// resample the local window
let frac = s0 as f64 - start as f64 * ratio;
// Resample the local window. Its first sample is presentation sample `p0`; the edit list
// offset is already in `s0` and must not shift the read position a second time.
let frac = p0 as f64 - start as f64 * ratio;
let mut out = AudioBuffer::silence(sample_rate, ch, frames);
for k in 0..frames {
let pos = k as f64 * ratio - frac;
@@ -427,6 +460,10 @@ fn codec_label(c: &CodecConfig) -> String {
CodecConfig::Hevc(_) => "HEVC".into(),
CodecConfig::Vp9(c) => format!("VP9 (Profile {})", c.profile),
CodecConfig::Av1(c) => format!("AV1 ({} Profile)", ["Main", "High", "Professional"].get(c.seq_profile as usize).unwrap_or(&"Main")),
CodecConfig::Apv(a) => match filmcraft_apv::Profile::from_idc(a.profile_idc) {
Some(p) => p.name().into(),
None => "APV".into(),
},
CodecConfig::ProRes { fourcc } => match &fourcc.0 {
b"apco" => "Apple ProRes 422 Proxy".into(),
b"apcs" => "Apple ProRes 422 LT".into(),
@@ -451,14 +488,37 @@ fn codec_label(c: &CodecConfig) -> String {
}
}
/// "YUV 4:2:2 10-bit" from an H.264 / HEVC `chroma_format_idc` and bit depth.
fn yuv_label(chroma_format_idc: u32, bits: u32) -> String {
let sub = match chroma_format_idc {
0 => "4:0:0",
1 => "4:2:0",
2 => "4:2:2",
_ => "4:4:4",
};
format!("YUV {sub} {bits}-bit")
}
/// `chroma_format_idc` and luma bit depth of an H.264 track: from the `avcC` High-profile extension
/// (ISO/IEC 14496-15 §5.3.3), else from its first SPS. The profile alone can't say (High 4:2:2 is
/// 8 or 10-bit, High 10 can be 8-bit).
fn avc_format(a: &filmcraft_isobmff::AvcConfig) -> Option<(u32, u32)> {
// reserved bits set: '111111' chroma_format, '11111' bit_depth_luma_minus8 (else not an extension)
if !matches!(a.profile, 66 | 77 | 88)
&& let &[chroma, depth, ..] = a.ext.as_slice()
&& chroma & 0xFC == 0xFC
&& depth & 0xF8 == 0xF8
{
return Some(((chroma & 3) as u32, (depth & 7) as u32 + 8));
}
let sps = filmcraft_h264::params::Sps::parse(&filmcraft_bitstream::unescape_rbsp(a.sps.first()?.get(1..)?)).ok()?;
Some((sps.chroma_format_idc, sps.bit_depth_luma))
}
fn pixfmt_label(c: &CodecConfig) -> String {
match c {
CodecConfig::Avc(a) => match a.profile {
110 => "YUV 4:2:0 10-bit".into(),
122 => "YUV 4:2:2".into(),
244 => "YUV 4:4:4".into(),
_ => "YUV 4:2:0 8-bit".into(),
},
CodecConfig::Avc(a) => avc_format(a).map(|(chroma, bits)| yuv_label(chroma, bits)).unwrap_or_default(),
CodecConfig::Hevc(h) => yuv_label(h.chroma_format_idc as u32, h.bit_depth_luma as u32),
CodecConfig::Vp9(c) => {
let sub = match c.chroma_subsampling {
2 => "4:2:2",
@@ -467,7 +527,12 @@ fn pixfmt_label(c: &CodecConfig) -> String {
};
format!("YUV {sub} {}-bit", c.bit_depth.max(8))
}
CodecConfig::ProRes { fourcc } if fourcc.0[2] == b'4' => "YUVA 4:4:4 12-bit".into(),
CodecConfig::Apv(a) => {
let chroma = filmcraft_apv::ChromaFormat::from_idc(a.chroma_format_idc).unwrap_or(filmcraft_apv::ChromaFormat::Yuv422);
crate::apv::apv_pixfmt_label(chroma, a.bit_depth_minus8.saturating_add(8))
}
// 4444 until the first frame header says whether it codes alpha (`open_reader`)
CodecConfig::ProRes { fourcc } if fourcc.0[2] == b'4' => "YUV 4:4:4 12-bit".into(),
CodecConfig::ProRes { .. } => "YUV 4:2:2 10-bit".into(),
CodecConfig::Jpeg { .. } => "YUV 4:2:x 8-bit".into(),
_ => String::new(),
@@ -481,6 +546,25 @@ pub fn opener(name: &str, bytes: Arc<[u8]>) -> Option<Result<SharedSource, Media
Some(Mp4Source::open(name, bytes).map(|s| Arc::new(s) as SharedSource).map_err(Into::into))
}
/// How long a track plays. With an edit list that is the sum of its edits (ISO/IEC 14496-12
/// §8.6.6, movie timescale), as `tkhd` records it. The media duration (`mdhd`) runs on the decode
/// timeline: it is longer than the presentation by the B-frame delay an edit skips (`media_time`, one
/// extra frame on every ffmpeg / x264 MP4 with B-frames) and shorter by a leading empty edit (the last
/// frame of a delayed video track was never shown). Fragmented files, and edit lists that add up to
/// nothing or to more than a [`Tick`] holds, keep the media duration.
fn presentation_duration(file: &Mp4File, t: &filmcraft_isobmff::Track) -> Tick {
let media = Tick::from_rational(t.duration as i64, 1, t.timescale as i64);
if file.fragmented || t.edits.is_empty() || file.timescale == 0 {
return media;
}
let edits = t.edits.iter().fold(0u128, |a, e| a.saturating_add(e.segment_duration as u128));
let ticks = edits.saturating_mul(filmcraft_time::TICKS_PER_SECOND as u128) / file.timescale as u128;
match i64::try_from(ticks) {
Ok(t) if t > 0 => Tick(t),
_ => media,
}
}
/// [`filmcraft_media::ReaderOpener`] for MP4/MOV.
pub fn reader_opener(name: &str, head: &[u8], reader: &filmcraft_media::SharedReader) -> Option<Result<SharedSource, MediaError>> {
if !sniff(head) {
@@ -518,6 +602,45 @@ mod tests {
b.into()
}
/// A four-frame 25 fps ProRes MOV (64×32) whose video track carries `edits`.
fn mov_with_edits(edits: Vec<filmcraft_isobmff::Edit>) -> Arc<[u8]> {
let fr = filmcraft_prores::Frame::new(64, 32, filmcraft_prores::ChromaFormat::Yuv422, 10, false);
let data = filmcraft_prores::Encoder::new(filmcraft_prores::Profile::Hq, 64, 32).encode(&fr).expect("encode");
let mut mux = Mp4Writer::new(std::io::Cursor::new(Vec::new()), WriterOptions::new(Brand::Mov)).expect("writer");
let mut cfg = TrackConfig::new(SampleEntry::prores(FourCc(*b"apch"), 64, 32), 25);
cfg.edits = edits;
let t = mux.add_track(cfg).expect("track");
for _ in 0..4 {
mux.write_sample(t, WriteSample { data: &data, duration: 1, composition_offset: 0, is_sync: true }).expect("sample");
}
mux.finish().expect("finish").into_inner().into()
}
/// A clip lasts as long as its edit list presents it, not as long as its media (`mdhd`) runs.
/// Every ffmpeg / x264 MP4 with B-frames skips its reorder delay with an edit and imported one
/// frame too long; a video track delayed by an empty edit lost its last frame.
#[test]
fn duration_follows_the_edit_list() {
use filmcraft_isobmff::Edit;
let frames = |s: &Mp4Source| s.info().duration.to_rational_floor(1, 25);
// no edit list: the media duration
assert_eq!(frames(&Mp4Source::open("plain.mov", mov_with_edits(Vec::new())).expect("open")), 4);
// skip the first frame (B-frame delay style): three frames play (movie timescale 1000 ms)
let skip = vec![Edit { segment_duration: 120, media_time: 1, media_rate: 0x10000 }];
assert_eq!(frames(&Mp4Source::open("skip.mov", mov_with_edits(skip)).expect("open")), 3);
// a one-frame empty edit, then all four frames: five frames, and the last one is there
let delayed =
vec![Edit { segment_duration: 40, media_time: -1, media_rate: 0x10000 }, Edit { segment_duration: 160, media_time: 0, media_rate: 0x10000 }];
let s = Mp4Source::open("delayed.mov", mov_with_edits(delayed)).expect("open");
assert_eq!(frames(&s), 5);
assert!(s.video_frame(FrameRequest::full(Tick::from_rational(4, 1, 25))).is_ok());
// hostile segment durations fall back to the media duration instead of wrapping
let huge = vec![Edit { segment_duration: u64::MAX, media_time: 0, media_rate: 0x10000 }];
assert_eq!(frames(&Mp4Source::open("huge.mov", mov_with_edits(huge)).expect("open")), 4);
let zero = vec![Edit { segment_duration: 0, media_time: 0, media_rate: 0x10000 }];
assert_eq!(frames(&Mp4Source::open("zero.mov", mov_with_edits(zero)).expect("open")), 4);
}
/// Overwrite the big-endian u32 `skip` bytes after the first `fourcc` box type.
fn patch_u32(b: &mut [u8], fourcc: &[u8; 4], skip: usize, v: u32) {
let k = b.windows(4).position(|x| x == fourcc).expect("box") + 4 + skip;
@@ -601,4 +724,144 @@ mod tests {
let s = Mp4Source::open("cw2.mov", rotated_mov([0, 2 * ONE, 0, -2 * ONE, 0, 0, 64 * ONE, 0, W])).expect("open");
assert_eq!(s.info().video.as_ref().map(|v| (v.width, v.height)), Some((32, 64)));
}
#[test]
fn hevc_pixel_format_comes_from_hvcc() {
for (chroma, bits, want) in [(1, 8, "YUV 4:2:0 8-bit"), (1, 10, "YUV 4:2:0 10-bit"), (2, 8, "YUV 4:2:2 8-bit"), (2, 10, "YUV 4:2:2 10-bit")] {
let c = filmcraft_isobmff::HevcConfig { general_profile_idc: 1, chroma_format_idc: chroma, bit_depth_luma: bits, ..Default::default() };
assert_eq!(pixfmt_label(&CodecConfig::Hevc(c)), want);
}
}
/// A High-profile SPS NAL unit (ITU-T H.264 §7.3.2.1.1) with the given chroma format and bit depth, 16×16.
fn high_sps(profile: u8, chroma: u32, bits: u32) -> Vec<u8> {
let mut w = filmcraft_bitstream::BitWriter::new();
w.write_bits(0x67, 8);
w.write_bits(profile as u32, 8);
w.write_bits(0, 8); // constraint flags
w.write_bits(30, 8); // level
w.write_ue(0); // seq_parameter_set_id
w.write_ue(chroma);
if chroma == 3 {
w.write_bit(false); // separate_colour_plane_flag
}
w.write_ue(bits - 8); // luma
w.write_ue(bits - 8); // chroma
w.write_bits(0, 2); // no transform bypass, no scaling matrices
w.write_ue(0); // log2_max_frame_num_minus4
w.write_ue(2); // pic_order_cnt_type
w.write_ue(1); // max_num_ref_frames
w.write_bit(false); // gaps_in_frame_num_allowed
w.write_ue(0); // pic_width_in_mbs_minus1
w.write_ue(0); // pic_height_in_map_units_minus1
w.write_bits(0b110, 3); // frame_mbs_only, direct_8x8_inference, no cropping
w.write_bit(false); // no VUI
w.rbsp_trailing();
w.finish()
}
#[test]
fn avc_pixel_format_comes_from_avcc_not_the_profile() {
let avc =
|profile: u8, sps: Vec<u8>, ext: Vec<u8>| CodecConfig::Avc(filmcraft_isobmff::AvcConfig { profile, sps: vec![sps], ext, ..Default::default() });
// High 4:2:2 at 10 and 8 bits, from the avcC extension (chroma_format 2, bit_depth_luma_minus8)
assert_eq!(pixfmt_label(&avc(122, high_sps(122, 2, 10), vec![0xFE, 0xFA, 0xFA, 0])), "YUV 4:2:2 10-bit");
assert_eq!(pixfmt_label(&avc(122, high_sps(122, 2, 8), vec![0xFE, 0xF8, 0xF8, 0])), "YUV 4:2:2 8-bit");
// no extension (or not a valid one): the SPS says
assert_eq!(pixfmt_label(&avc(122, high_sps(122, 2, 10), Vec::new())), "YUV 4:2:2 10-bit");
assert_eq!(pixfmt_label(&avc(110, high_sps(110, 1, 10), vec![0, 0, 0, 0])), "YUV 4:2:0 10-bit");
assert_eq!(pixfmt_label(&avc(244, high_sps(244, 3, 10), Vec::new())), "YUV 4:4:4 10-bit");
// an unreadable SPS and no extension: unknown, not a guess
assert_eq!(pixfmt_label(&avc(122, vec![0x67, 122], Vec::new())), "");
}
/// A one-frame 32×16 ProRes MOV with the given profile, chroma format and fourcc.
fn prores_mov(profile: filmcraft_prores::Profile, fourcc: &[u8; 4], chroma: filmcraft_prores::ChromaFormat, alpha: bool) -> Arc<[u8]> {
let (w, h) = (32u32, 16u32);
let fr = filmcraft_prores::Frame::new(w, h, chroma, if chroma == filmcraft_prores::ChromaFormat::Yuv444 { 12 } else { 10 }, alpha);
let data = filmcraft_prores::Encoder::new(profile, w, h).encode(&fr).expect("encode");
let mut mux = Mp4Writer::new(std::io::Cursor::new(Vec::new()), WriterOptions::new(Brand::Mov)).expect("writer");
let t = mux.add_track(TrackConfig::new(SampleEntry::prores(FourCc(*fourcc), w as u16, h as u16), 25)).expect("track");
mux.write_sample(t, WriteSample { data: &data, duration: 1, composition_offset: 0, is_sync: true }).expect("sample");
mux.finish().expect("finish").into_inner().into()
}
/// `ap4h` / `ap4x` don't imply alpha: the frame header's alpha_channel_type does.
#[test]
fn prores_alpha_comes_from_the_frame_header() {
use filmcraft_prores::{ChromaFormat, Profile};
for (profile, fourcc, chroma, alpha, want) in [
(Profile::P4444, b"ap4h", ChromaFormat::Yuv444, false, "YUV 4:4:4 12-bit"),
(Profile::P4444, b"ap4h", ChromaFormat::Yuv444, true, "YUVA 4:4:4 12-bit"),
(Profile::P4444Xq, b"ap4x", ChromaFormat::Yuv444, false, "YUV 4:4:4 12-bit"),
(Profile::Hq, b"apch", ChromaFormat::Yuv422, false, "YUV 4:2:2 10-bit"),
] {
let s = Mp4Source::open("p.mov", prores_mov(profile, fourcc, chroma, alpha)).expect("open");
let v = s.info().video.as_ref().expect("video");
assert_eq!((v.pixel_format.as_str(), v.has_alpha), (want, alpha), "{}", String::from_utf8_lossy(fourcc));
}
}
}
#[cfg(test)]
mod he_aac_tests {
use filmcraft_isobmff::{Brand, Mp4Writer, SampleEntry, TrackConfig, WriteSample, WriterOptions};
use filmcraft_media::MediaSource;
/// #108: an HE-AAC MP4 (explicit SBR signalling, core 22.05 kHz, output 44.1 kHz, timescale
/// 44.1 kHz) built here from our AAC-LC encoder: the stream has no SBR data, which only the
/// high band would need. It was reported at the 22.05 kHz core rate, so sequences made from
/// such a clip were created at 22.05 kHz.
#[test]
fn he_aac_plays_at_the_output_rate() {
let core = 22_050u32;
let n = core as usize * 2;
let tone: Vec<f32> = (0..n).map(|i| 0.25 * (2.0 * std::f32::consts::PI * 1000.0 * i as f32 / core as f32).sin()).collect();
let mut enc = filmcraft_aac::Encoder::new(filmcraft_aac::EncoderConfig::cbr(core, 2, 64_000)).unwrap();
let mut aus = enc.encode(&[&tone, &tone]);
aus.extend(enc.flush());
// AOT 5, core 22.05 kHz, stereo, extension 44.1 kHz, core AOT 2
let asc = vec![0x2B, 0x92, 0x08, 0x00];
let mut mux = Mp4Writer::new(std::io::Cursor::new(Vec::new()), WriterOptions::new(Brand::Mp4)).unwrap();
let t = mux.add_track(TrackConfig::new(SampleEntry::aac(asc, 2, 44_100), 44_100)).unwrap();
for au in &aus {
mux.write_sample(t, WriteSample { data: au, duration: 2048, composition_offset: 0, is_sync: true }).unwrap();
}
let b = mux.finish().unwrap().into_inner();
let src = super::Mp4Source::open("he.mp4", b.into()).unwrap();
assert_eq!(src.info().audio.as_ref().unwrap().sample_rate, 44_100);
// one second from 0.5 s at 44.1 kHz: the 1 kHz tone at its level (not silence, not shifted)
let buf = src.audio(22_050, 44_100, 44_100).unwrap();
let x = &buf.channels[0];
let peak = x.iter().fold(0f32, |m, v| m.max(v.abs()));
assert!((0.2..0.3).contains(&peak), "peak {peak}");
let crossings = x.windows(2).filter(|w| w[0] < 0.0 && w[1] >= 0.0).count();
assert!((995..=1005).contains(&crossings), "{crossings} Hz");
}
/// A hostile edit list (#66): an AAC track whose edit puts it absurdly far off, read at another
/// rate, scaled the offset to the source rate in i64 and overflowed. It reads as silence now.
#[test]
fn hostile_audio_edit_offset_never_overflows() {
use filmcraft_isobmff::Edit;
let rate = 32_000u32;
let tone: Vec<f32> = (0..rate as usize / 2).map(|i| 0.25 * (i as f32 * 0.05).sin()).collect();
let mut enc = filmcraft_aac::Encoder::new(filmcraft_aac::EncoderConfig::cbr(rate, 1, 64_000)).unwrap();
let mut aus = enc.encode(&[&tone]);
aus.extend(enc.flush());
// AOT 2 (AAC-LC), 32 kHz (index 5), mono
let asc = vec![0x12, 0x88];
for media_time in [i64::MAX, i64::MAX / 3, i64::MIN / 3] {
let mut mux = Mp4Writer::new(std::io::Cursor::new(Vec::new()), WriterOptions::new(Brand::Mp4)).unwrap();
let mut cfg = TrackConfig::new(SampleEntry::aac(asc.clone(), 1, rate), rate);
cfg.edits = vec![Edit { segment_duration: 500, media_time, media_rate: 0x10000 }];
let t = mux.add_track(cfg).unwrap();
for au in &aus {
mux.write_sample(t, WriteSample { data: au, duration: 1024, composition_offset: 0, is_sync: true }).unwrap();
}
let src = super::Mp4Source::open("hostile.mp4", mux.finish().unwrap().into_inner().into()).unwrap();
let buf = src.audio(0, 4800, 48_000).unwrap();
assert!(buf.channels.iter().flatten().all(|v| v.is_finite() && v.abs() <= 1.0), "media_time {media_time}");
}
}
}
+136
View File
@@ -0,0 +1,136 @@
//! Frame lookup against timestamps rounded to the container's timebase (issue #73).
//!
//! WebM stores timestamps in 1 ms units, so at 30 fps frame 2 (66.67 ms) is stored as 67. Flooring
//! the requested time to 66 picked frame 1 instead: every third frame was skipped and the one
//! before it shown twice. MP4 has the same problem when a muxer picks a 1 ms track timescale.
//!
//! The streams are synthetic Motion-JPEG: each picture shows its index as a row of black and
//! white blocks, so a decoded frame says which sample it came from.
use std::io::Cursor;
use std::sync::Arc;
use filmcraft_frame::{PixelData, VideoFrame};
use filmcraft_isobmff::{Brand, Mp4Writer, SampleEntry, TrackConfig, WriteSample, WriterOptions};
use filmcraft_matroska::{MkvWriter, MuxOptions, TrackKind, TrackSpec};
use filmcraft_media::{FrameRequest, MediaSource};
use filmcraft_time::{FrameRate, TICKS_PER_SECOND, Tick};
/// Bits of the frame index drawn per picture, one `BLOCK`-pixel square each.
const BITS: u32 = 8;
const BLOCK: u32 = 16;
const SECONDS: i64 = 3;
/// The rates that don't divide 1 ms evenly (affected), and 25 fps (never was).
const RATES: [FrameRate; 7] =
[FrameRate::FPS_30, FrameRate::FPS_29_97, FrameRate::FPS_60, FrameRate::FPS_59_94, FrameRate::FPS_24, FrameRate::FPS_23_976, FrameRate::FPS_25];
/// How the muxer quantised the exact frame times to milliseconds.
#[derive(Clone, Copy, Debug)]
enum Stamp {
/// To the nearest millisecond, halves up (mkvmerge, ffmpeg).
Nearest,
/// Truncated.
Floor,
}
fn picture(index: usize) -> Vec<u8> {
let img = image::GrayImage::from_fn(BITS * BLOCK, BLOCK, |x, _| image::Luma([if (index >> (x / BLOCK)) & 1 == 1 { 255 } else { 0 }]));
let mut out = Vec::new();
image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, 90).encode_image(&img).unwrap();
out
}
fn index_of(f: &VideoFrame) -> usize {
let PixelData::Rgba8(px) = &f.data else { panic!("MJPEG decodes to RGBA8") };
(0..BITS).filter(|b| px[((BLOCK / 2 * f.width + b * BLOCK + BLOCK / 2) * 4) as usize] > 127).map(|b| 1 << b).sum()
}
fn frame_count(rate: FrameRate) -> usize {
rate.frame_at(Tick(SECONDS * TICKS_PER_SECOND)) as usize
}
/// Frame `k`'s start in milliseconds, as the muxer stores it.
fn stamp_ms(rate: FrameRate, k: usize, stamp: Stamp) -> i64 {
let (num, den) = (rate.num as i128, rate.den as i128);
let exact2 = 2 * k as i128 * 1000 * den; // twice the time in ms, times num
(match stamp {
Stamp::Nearest => (exact2 + num) / (2 * num),
Stamp::Floor => exact2 / (2 * num),
}) as i64
}
fn webm(rate: FrameRate, stamp: Stamp) -> Arc<[u8]> {
let mut spec = TrackSpec::new(TrackKind::Video, "V_MJPEG");
spec.video_size = Some((BITS * BLOCK, BLOCK));
spec.default_duration_ns = Some((1_000_000_000 * rate.den / rate.num) as u64);
let opts = MuxOptions { doc_type: "webm".into(), ..MuxOptions::default() };
assert_eq!(opts.timestamp_scale, 1_000_000, "1 ms timestamps");
let mut w = MkvWriter::new(Cursor::new(Vec::new()), vec![spec], opts).unwrap();
for k in 0..frame_count(rate) {
w.write_frame(0, stamp_ms(rate, k, stamp) * 1_000_000, true, &picture(k), None).unwrap();
}
w.finish().unwrap().into_inner().into()
}
fn mp4_1ms(rate: FrameRate, stamp: Stamp) -> Arc<[u8]> {
let mut w = Mp4Writer::new(Cursor::new(Vec::new()), WriterOptions::new(Brand::Mov)).unwrap();
let t = w.add_track(TrackConfig::new(SampleEntry::jpeg((BITS * BLOCK) as u16, BLOCK as u16), 1000)).unwrap();
let n = frame_count(rate);
for k in 0..n {
let duration = (stamp_ms(rate, k + 1, stamp) - stamp_ms(rate, k, stamp)) as u32;
w.write_sample(t, WriteSample { data: &picture(k), duration, composition_offset: 0, is_sync: true }).unwrap();
}
w.finish().unwrap().into_inner().into()
}
/// Plays the stream back at its own rate (every frame's start), and asks for every frame's
/// midpoint too. Returns what went wrong: frames never shown, frames shown twice, wrong midpoints.
fn problems(src: &dyn MediaSource, rate: FrameRate) -> Vec<String> {
let n = frame_count(rate);
let at = |t: Tick| index_of(&src.video_frame(FrameRequest::full(t)).unwrap());
let mut shown = vec![0usize; n];
for k in 0..n {
shown[at(rate.tick_of(k as i64)).min(n - 1)] += 1;
}
let mut out = Vec::new();
let dropped: Vec<usize> = (0..n).filter(|&k| shown[k] == 0).collect();
let repeated: Vec<usize> = (0..n).filter(|&k| shown[k] > 1).collect();
if !dropped.is_empty() || !repeated.is_empty() {
out.push(format!(
"{} of {n} frames never shown {:?}…, {} shown twice {:?}…",
dropped.len(),
&dropped[..dropped.len().min(4)],
repeated.len(),
&repeated[..repeated.len().min(4)]
));
}
let mid: Vec<(usize, usize)> = (0..n).map(|k| (k, at(rate.tick_of(k as i64) + Tick(rate.frame_duration().0 / 2)))).filter(|(k, got)| k != got).collect();
if !mid.is_empty() {
out.push(format!("{} mid-frame requests wrong, e.g. (wanted, got) {:?}", mid.len(), &mid[..mid.len().min(4)]));
}
out
}
fn check(container: &str, open: fn(FrameRate, Stamp) -> Arc<[u8]>) {
let mut failures = Vec::new();
for rate in RATES {
for stamp in [Stamp::Nearest, Stamp::Floor] {
let src = crate::open_bytes(&format!("synthetic.{container}"), open(rate, stamp)).unwrap();
for p in problems(src.as_ref(), rate) {
failures.push(format!("{rate}, {stamp:?} ms stamps: {p}"));
}
}
}
assert!(failures.is_empty(), "{container}:\n{}", failures.join("\n"));
}
#[test]
fn webm_with_1ms_timestamps_shows_every_frame_once() {
check("webm", webm);
}
#[test]
fn mp4_with_a_1ms_timescale_shows_every_frame_once() {
check("mov", mp4_1ms);
}
+37
View File
@@ -578,3 +578,40 @@ fn opus_mp4_stereo() {
"MPEG-4",
);
}
#[test]
fn apv_mp4_and_raw_bitstream_decode() {
use filmcraft_isobmff::{ApvConfig, Brand, Mp4Writer, SampleEntry, TrackConfig, WriteSample, WriterOptions};
let (w, h) = (64u32, 32u32);
let mut fr = filmcraft_apv::Frame::new(w, h, filmcraft_apv::ChromaFormat::Yuv422, 10, false);
for (i, y) in fr.y.iter_mut().enumerate() {
*y = if (i as u32 % w) < w / 2 { 850 } else { 150 };
}
let mut enc = filmcraft_apv::Encoder::new(filmcraft_apv::Profile::P422_10, w, h).expect("encoder");
let au = enc.encode_raw_au(&fr).expect("encode_raw_au");
let apvc = ApvConfig::parse(&enc.decoder_config_record()).expect("parse apvC");
// 1. Raw .apv elementary stream
let raw_src = crate::open_bytes("clip.apv", au.clone().into()).expect("open raw .apv");
let raw_v = raw_src.info().video.as_ref().expect("video info");
assert_eq!((raw_v.width, raw_v.height), (w, h));
assert_eq!(raw_v.codec, "APV 422-10");
assert_eq!(raw_v.pixel_format, "YUV 4:2:2 10-bit");
let decoded_raw = raw_src.video_frame(FrameRequest::full(Tick::ZERO)).expect("decode raw frame");
assert_eq!((decoded_raw.width, decoded_raw.height), (w, h));
// 2. MP4 with apv1 + apvC
let mut mux = Mp4Writer::new(std::io::Cursor::new(Vec::new()), WriterOptions::new(Brand::Mp4)).expect("writer");
let vt = mux.add_track(TrackConfig::new(SampleEntry::apv(apvc, w as u16, h as u16), 24)).expect("track");
mux.write_sample(vt, WriteSample { data: &au, duration: 1, composition_offset: 0, is_sync: true }).expect("sample");
let mp4_bytes: Arc<[u8]> = mux.finish().expect("finish").into_inner().into();
let mp4_src = crate::open_bytes("clip.mp4", mp4_bytes).expect("open mp4");
let mp4_v = mp4_src.info().video.as_ref().expect("mp4 video info");
assert_eq!((mp4_v.width, mp4_v.height), (w, h));
assert_eq!(mp4_v.codec, "APV 422-10");
assert_eq!(mp4_v.pixel_format, "YUV 4:2:2 10-bit");
let decoded_mp4 = mp4_src.video_frame(FrameRequest::full(Tick::ZERO)).expect("decode mp4 frame");
assert_eq!(decoded_mp4.to_rgba8(), decoded_raw.to_rgba8());
}
+79 -40
View File
@@ -204,12 +204,14 @@ pub struct H264Decoder {
impl H264Decoder {
pub fn new(avcc: Vec<u8>) -> Result<Self> {
recycle_h264_planes();
let dec = filmcraft_h264::Decoder::from_avcc(&avcc).map_err(|e| CodecError::Decode(e.to_string()))?;
let length_size = avcc_length_size(&avcc);
Ok(Self { avcc, dec, length_size, draft: false })
}
/// A decoder for Annex B byte-stream samples (start codes, in-band parameter sets: MXF, TS).
pub fn annexb() -> Self {
recycle_h264_planes();
Self { avcc: Vec::new(), dec: filmcraft_h264::Decoder::new(), length_size: 0, draft: false }
}
fn convert(p: filmcraft_h264::Picture) -> DecodedFrame {
@@ -269,6 +271,12 @@ impl VideoDecoder for H264Decoder {
}
}
/// The H.264 decoder's output planes come from the frames the caches evicted
/// (`filmcraft_frame::pool`) instead of the allocator.
fn recycle_h264_planes() {
filmcraft_h264::set_plane_allocator(filmcraft_frame::pool::take_u8);
}
/// Worker threads each H.264 decoder uses (frame threading; 1 on wasm).
pub fn h264_threads() -> usize {
filmcraft_h264::default_threads()
@@ -404,32 +412,14 @@ impl Vp9Decoder {
/// `None` for a picture whose planes mix sample types (never produced by the decoder).
fn convert(&self, p: filmcraft_vp9::Picture) -> Option<DecodedFrame> {
use filmcraft_color::{Matrix, Primaries, Range};
use filmcraft_color::Range;
use filmcraft_frame::{Chroma, PixelData};
use filmcraft_vp9::Plane;
use std::sync::Arc;
let (w, h) = (p.width as usize, p.height as usize);
let (cw, ch) = (p.chroma_width as usize, p.chroma_height as usize);
let mut color = filmcraft_color::ColorInfo { matrix: filmcraft_frame::default_matrix(p.width, p.height), ..filmcraft_color::ColorInfo::REC709 };
// color_space (7.2.2): 1 BT.601, 2 BT.709, 3 SMPTE-170, 4 SMPTE-240, 5 BT.2020, 7 sRGB.
match p.color.color_space {
1 | 3 => color.matrix = Matrix::Bt601,
2 | 4 => color.matrix = Matrix::Bt709,
5 => {
color.matrix = Matrix::Bt2020Ncl;
color.primaries = Primaries::Bt2020;
}
_ => {}
}
if let Some(t) = self.transfer {
color.transfer = t;
}
if let Some(pr) = self.primaries {
color.primaries = pr;
}
if p.color.full_range {
color.range = Range::Full;
}
// (shared with the hardware decoders: `hw_frame::vp9_color`)
let color = crate::hw_frame::vp9_color(p.width, p.height, p.color.color_space, p.color.full_range, self.transfer, self.primaries);
let (pts, draft) = (p.pts, p.draft);
if p.color.color_space == 7 {
// RGB (profiles 1 / 3, 4:4:4): the planes carry G, B, R.
@@ -528,25 +518,8 @@ impl Av1Decoder {
let draft = p.draft;
let w = p.width as usize;
let h = p.height as usize;
let mut color = filmcraft_color::ColorInfo::REC709;
if let Some(m) = filmcraft_color::Matrix::from_code(p.matrix_coefficients) {
color.matrix = m;
} else {
color.matrix = filmcraft_frame::default_matrix(p.width, p.height);
}
if let Some(t) = filmcraft_color::Transfer::from_code(p.transfer_characteristics) {
color.transfer = t;
}
color.primaries = match p.color_primaries {
9 => filmcraft_color::Primaries::Bt2020,
12 => filmcraft_color::Primaries::P3D65,
5 => filmcraft_color::Primaries::Bt601_625,
6 => filmcraft_color::Primaries::Bt601_525,
_ => filmcraft_color::Primaries::Bt709,
};
if p.full_range {
color.range = filmcraft_color::Range::Full;
}
// (shared with the hardware decoders: `hw_frame::av1_color`)
let color = crate::hw_frame::av1_color(p.width, p.height, p.matrix_coefficients, p.transfer_characteristics, p.color_primaries, p.full_range);
let chroma = match (p.subsampling_x, p.subsampling_y) {
(1, 1) => filmcraft_frame::Chroma::C420,
(1, 0) => filmcraft_frame::Chroma::C422,
@@ -668,6 +641,72 @@ pub fn prores_factory(e: &SampleEntry) -> Option<Result<Box<dyn VideoDecoder>>>
matches!(e.codec, CodecConfig::ProRes { .. }).then(|| Ok(Box::new(ProResDecoder) as Box<dyn VideoDecoder>))
}
/// Our APV (Advanced Professional Video, RFC 9924) decoder (every frame is intra; tiles decode in
/// parallel).
pub struct ApvDecoder;
/// Convert a decoded APV frame to a [`VideoFrame`].
pub fn apv_to_video_frame(f: filmcraft_apv::Frame) -> VideoFrame {
use std::sync::Arc;
let chroma = match f.chroma {
filmcraft_apv::ChromaFormat::Yuv422 => filmcraft_frame::Chroma::C422,
filmcraft_apv::ChromaFormat::Monochrome | filmcraft_apv::ChromaFormat::Yuv444 | filmcraft_apv::ChromaFormat::Yuv4444 => filmcraft_frame::Chroma::C444,
};
let mut color = filmcraft_color::ColorInfo { matrix: filmcraft_frame::default_matrix(f.width, f.height), ..filmcraft_color::ColorInfo::REC709 };
if let Some(m) = filmcraft_color::Matrix::from_code(f.color.matrix) {
color.matrix = m;
}
if let Some(t) = filmcraft_color::Transfer::from_code(f.color.transfer) {
color.transfer = t;
}
if let Some(p) = primaries_from_code(f.color.primaries) {
color.primaries = p;
}
if f.color.full_range {
color.range = filmcraft_color::Range::Full;
}
let neutral = 1u16 << f.bit_depth.saturating_sub(1);
let (cb, cr) = if f.chroma == filmcraft_apv::ChromaFormat::Monochrome {
let u = vec![neutral; (f.width as usize) * (f.height as usize)];
(u.clone(), u)
} else {
(f.cb, f.cr)
};
let data = if f.bit_depth == 8 {
let to8 = |p: Vec<u16>| Arc::new(p.into_iter().map(|v| v as u8).collect::<Vec<u8>>());
filmcraft_frame::PixelData::Yuv8 { planes: [to8(f.y), to8(cb), to8(cr)], chroma, alpha: f.alpha.map(to8) }
} else {
filmcraft_frame::PixelData::Yuv16 {
planes: [Arc::new(f.y), Arc::new(cb), Arc::new(cr)],
chroma,
bits: f.bit_depth as u32,
alpha: f.alpha.map(Arc::new),
}
};
VideoFrame { width: f.width, height: f.height, data, color, par: (1, 1), pts: filmcraft_time::Tick::ZERO }
}
impl VideoDecoder for ApvDecoder {
fn decode(&mut self, sample: &[u8], pts: i64) -> Result<Vec<DecodedFrame>> {
let f = filmcraft_apv::decode_frame(sample).map_err(|e| CodecError::Decode(e.to_string()))?;
Ok(vec![DecodedFrame { pts, frame: apv_to_video_frame(f), draft: false }])
}
fn flush(&mut self) -> Vec<DecodedFrame> {
Vec::new()
}
fn reset(&mut self) {}
fn name(&self) -> &str {
"FilmCraft APV"
}
fn intra_only(&self) -> bool {
true
}
}
pub fn apv_factory(e: &SampleEntry) -> Option<Result<Box<dyn VideoDecoder>>> {
matches!(e.codec, CodecConfig::Apv(_)).then(|| Ok(Box::new(ApvDecoder) as Box<dyn VideoDecoder>))
}
/// Our DNxHD / DNxHR (VC-3) decoder (every frame is intra; macroblock rows decode in parallel).
pub struct DnxDecoder;
+25 -10
View File
@@ -13,19 +13,33 @@ use filmcraft_media::sequence::{FrameLoader, ImageSequenceSource, Numbered, sequ
use filmcraft_media::{FrameRequest, MediaKind, MediaSource};
use filmcraft_time::FrameRate;
/// Twelve numbered stills written by ffmpeg, shared by every test that uses `ext` (#125).
///
/// ffmpeg writes into a private temporary directory, which is renamed into place only when all
/// twelve frames are there, so a test never reads a sequence another test is still writing (a
/// half-written PNG decodes as missing, and the sequence then holds the previous frame). A test that
/// loses the race keeps the winner's copy. The `.complete` marker tells a finished cache from a
/// directory left by an older, non-atomic generator (hence the `_v2` name).
fn make_sequence(ff: &Path, ext: &str, codec_args: &[&str]) -> Option<std::path::PathBuf> {
let d = dir().join(format!("seq_{ext}"));
let first = d.join(format!("img_0001.{ext}"));
if first.exists() && d.join(format!("img_0012.{ext}")).exists() {
let d = dir().join(format!("seq_{ext}_v2"));
let complete = |d: &Path| d.join(".complete").exists();
if complete(&d) {
return Some(d);
}
let _ = std::fs::create_dir_all(&d);
let pattern = d.join(format!("img_%04d.{ext}"));
let tmp = filmcraft_testkit::fixtures::temp_path(&d);
std::fs::create_dir_all(&tmp).ok()?;
let pattern = tmp.join(format!("img_%04d.{ext}"));
let mut args = vec!["-y", "-v", "error", "-f", "lavfi", "-i", "testsrc2=size=96x64:rate=25", "-frames:v", "12"];
args.extend_from_slice(codec_args);
args.extend_from_slice(&["-f", "image2"]);
let st = std::process::Command::new(ff).args(&args).arg(&pattern).status().ok()?;
st.success().then_some(d)
let made = std::process::Command::new(ff).args(&args).arg(&pattern).status().is_ok_and(|st| st.success())
&& (1..=12).all(|n| tmp.join(format!("img_{n:04}.{ext}")).exists())
&& std::fs::write(tmp.join(".complete"), b"").is_ok();
if made && std::fs::rename(&tmp, &d).is_ok() {
return Some(d);
}
let _ = std::fs::remove_dir_all(&tmp);
complete(&d).then_some(d)
}
fn loader() -> FrameLoader {
@@ -104,9 +118,9 @@ fn webp_sequence_lossless() {
fn missing_frames_hold_the_previous_frame() {
let ff = filmcraft_testkit::require_ffmpeg!();
let Some(d) = make_sequence(&ff, "png", &[]) else { return };
// a copy without frames 5 and 6
let gap = dir().join("seq_png_gap");
let _ = std::fs::create_dir_all(&gap);
// a private copy without frames 5 and 6
let gap = filmcraft_testkit::fixtures::temp_path(&dir().join("seq_png_gap"));
std::fs::create_dir_all(&gap).unwrap();
for n in (1..=12).filter(|n| *n != 5 && *n != 6) {
let name = format!("img_{n:04}.png");
std::fs::copy(d.join(&name), gap.join(&name)).unwrap();
@@ -119,6 +133,7 @@ fn missing_frames_hold_the_previous_frame() {
assert_eq!(at(4), at(3));
assert_eq!(at(5), at(3));
assert_ne!(at(6), at(3));
let _ = std::fs::remove_dir_all(&gap);
}
#[test]
+55
View File
@@ -0,0 +1,55 @@
//! MP4 audio against ffmpeg: ffmpeg writes an AAC track (with the edit list that skips the encoder
//! priming), and reads at another sample rate must land on the same source samples as the native
//! decode, however the requests are cut.
mod common;
use common::*;
/// A source whose rate differs from the sequence's is resampled per request. An AAC track in MP4
/// carries an edit list that skips the encoder priming (ffmpeg: 1024 samples), and every request
/// must still land on the same source samples: reading at 44.1 kHz in video-frame-sized pieces (as
/// an export does) equals the 48 kHz decode interpolated at the same times.
#[test]
fn aac_mp4_resampled_reads_follow_the_edit_list() {
let ff = filmcraft_testkit::require_ffmpeg!();
let Some(f) = fixture(&ff, "tone_aac_48k.mp4", &["-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000:d=3", "-c:a", "aac", "-b:a", "128k"]) else {
panic!("could not write the AAC fixture")
};
let src = filmcraft_codecs::open_bytes("tone_aac_48k.mp4", bytes(&f)).unwrap();
let native = src.audio(0, 2 * 48_000, 48_000).unwrap().channels[0].clone();
let ratio = 48_000.0 / 44_100.0;
// 30 fps at 44.1 kHz, starting mid-file and off the 48 kHz grid
let (mut start, piece) = (22_051i64, 1470usize);
let (mut worst, mut peak) = (0f32, 0f32);
for _ in 0..20 {
let got = src.audio(start, piece, 44_100).unwrap();
for (k, &v) in got.channels[0].iter().enumerate() {
let pos = (start + k as i64) as f64 * ratio;
let i0 = pos.floor() as usize;
let want = native[i0] + (native[i0 + 1] - native[i0]) * (pos - i0 as f64) as f32;
worst = worst.max((v - want).abs());
peak = peak.max(v.abs());
}
start += piece as i64;
}
let level = native.iter().fold(0f32, |m, v| m.max(v.abs()));
assert!(peak <= level * 1.01, "resampled peak {peak} above the source's {level}");
assert!(worst < 1e-4, "resampled read differs from the source by {worst}");
}
/// ffmpeg's MP4 muxer skips the B-frame reorder delay with an edit list, so the media (`mdhd`) runs
/// one frame past what plays. The clip must be as long as ffmpeg decodes it: 60 frames, not 61.
#[test]
fn bframe_mp4_duration_is_the_decoded_frame_count() {
let ff = filmcraft_testkit::require_ffmpeg!();
let args = ["-f", "lavfi", "-i", "testsrc2=size=160x96:rate=30:duration=2", "-c:v", "libx264", "-bf", "2", "-pix_fmt", "yuv420p"];
let Some(f) = fixture(&ff, "bframes_x264.mp4", &args) else {
eprintln!("SKIPPED: ffmpeg without libx264");
return;
};
let n = ffmpeg_frames(&ff, &f, "yuv420p").len() / (160 * 96 * 3 / 2);
assert_eq!(n, 60);
let src = filmcraft_codecs::open_bytes("bframes_x264.mp4", bytes(&f)).unwrap();
assert_eq!(src.info().duration, filmcraft_time::FrameRate::FPS_30.tick_of(n as i64));
}
+63
View File
@@ -0,0 +1,63 @@
//! Decoded pictures are written into recycled plane buffers (`filmcraft_frame::pool`). A recycled
//! buffer still holds an old picture, so the decoder must overwrite every byte: here the pool is
//! primed with buffers full of 0xAA before decoding, and every frame must still match ffmpeg bit
//! for bit. (Its own process: the pool is global.)
mod common;
use std::sync::Arc;
use common::*;
use filmcraft_frame::{Chroma, PixelData, VideoFrame};
use filmcraft_media::FrameRequest;
#[test]
fn dirty_recycled_planes_decode_bit_exact() {
let ff = filmcraft_testkit::require_ffmpeg!();
// 640×480: luma and chroma planes are both large enough to be pooled
let Some(file) = fixture(
&ff,
"pool_h264.mp4",
&[
"-f",
"lavfi",
"-i",
"testsrc2=s=640x480:r=24:d=1,noise=alls=10:allf=t",
"-c:v",
"libx264",
"-preset",
"fast",
"-x264-params",
"bframes=2:keyint=12",
"-pix_fmt",
"yuv420p",
],
) else {
return;
};
let (w, h) = (640usize, 480usize);
let raw = ffmpeg_frames(&ff, &file, "yuv420p");
let fsize = w * h * 3 / 2;
let n = raw.len() / fsize;
assert!(n >= 20, "{n} frames");
let reference = |i: usize| raw_planes(&raw[i * fsize..(i + 1) * fsize], w, h, w / 2, h / 2, 1);
// prime the pool with dirty buffers of exactly the plane sizes the decoder asks for
for _ in 0..8 {
let dirty = |len: usize| Arc::new(vec![0xAAu8; len]);
let f = VideoFrame {
data: PixelData::Yuv8 { planes: [dirty(w * h), dirty(w * h / 4), dirty(w * h / 4)], chroma: Chroma::C420, alpha: None },
..VideoFrame::rgba8(w as u32, h as u32, vec![0; w * h * 4])
};
filmcraft_frame::pool::recycle(Arc::new(f));
}
let reused_before = filmcraft_frame::pool::stats().reused;
let src = filmcraft_codecs::open_bytes("pool_h264.mp4", bytes(&file)).expect("open");
let rate = src.info().frame_rate();
for i in 0..n {
let f = src.video_frame(FrameRequest::full(rate.tick_of(i as i64))).expect("frame");
assert_eq!(max_diff(&planes(&f), &reference(i)), 0, "frame {i} decoded into a recycled buffer");
}
assert!(filmcraft_frame::pool::stats().reused > reused_before, "the decoder took the dirty pooled buffers");
}
+178 -55
View File
@@ -351,21 +351,66 @@ pub fn delete_items(seq: &mut Sequence, items: &[ClipId]) -> usize {
n
}
/// Ripple delete track items: remove them and close the resulting gaps.
pub fn ripple_delete_items(seq: &mut Sequence, items: &[ClipId]) -> Result<()> {
// Collect per-track ranges to close (merged), processed right-to-left.
let mut ranges: Vec<(TrackId, TimeRange)> = Vec::new();
/// The stretches a ripple delete of `items` closes, in time order: the time the deleted items
/// covered, less whatever stays on the tracks that lose an item. Every such track then moves up
/// by the same amount, into time that is free on all of them, so later clips stay in sync and
/// nothing is overwritten. A clip and its linked sound with a split edit have different edges;
/// closing each one's own range would move the tracks twice. Locked tracks lose nothing and do
/// not count.
fn ripple_delete_spans(seq: &Sequence, items: &[ClipId]) -> Vec<TimeRange> {
let (mut deleted, mut kept) = (Vec::new(), Vec::new());
for tr in seq.all_tracks().filter(|t| !t.locked && t.items.iter().any(|i| items.contains(&i.id))) {
for i in &tr.items {
if items.contains(&i.id) { deleted.push(i.range()) } else { kept.push(i.range()) }
}
}
let kept = merged(kept);
let mut spans = Vec::new();
for r in merged(deleted) {
let mut at = r.start;
for k in kept.iter().filter(|k| k.overlaps(&r)) {
if k.start > at {
spans.push(TimeRange::from_bounds(at, k.start));
}
at = at.max(k.end());
}
if at < r.end() {
spans.push(TimeRange::from_bounds(at, r.end()));
}
}
spans
}
/// `ranges` in time order, with the ones that touch or overlap joined.
fn merged(mut ranges: Vec<TimeRange>) -> Vec<TimeRange> {
ranges.sort_by_key(|r| r.start);
let mut out: Vec<TimeRange> = Vec::new();
for r in ranges {
match out.last_mut() {
Some(last) if r.start <= last.end() => *last = TimeRange::from_bounds(last.start, last.end().max(r.end())),
_ => out.push(r),
}
}
out
}
/// Ripple delete track items: remove them and close the resulting gaps. Returns the stretches
/// that were closed, in time order. Refused when no gap can close (what stays on the items'
/// tracks covers all of their time): that would be a plain delete.
pub fn ripple_delete_items(seq: &mut Sequence, items: &[ClipId]) -> Result<Vec<TimeRange>> {
// Collect the tracks that lose an item; the gaps close right-to-left.
let mut affected: Vec<TrackId> = Vec::new();
for c in items {
let (tid, it) = seq.find_item(*c).ok_or(EditError::NoItem(*c))?;
ranges.push((tid, it.range()));
let (tid, _) = seq.find_item(*c).ok_or(EditError::NoItem(*c))?;
affected.push(tid);
}
let spans = ripple_delete_spans(seq, items);
if spans.is_empty() && !items.is_empty() {
let locked = affected.iter().all(|t| seq.track(*t).is_some_and(|tr| tr.locked));
return Err(if locked { EditError::Locked } else { EditError::Other("no gap can close: other clips on these tracks cover the deleted time".into()) });
}
// Group identical ranges across tracks (linked A/V) into one ripple.
let mut spans: Vec<TimeRange> = ranges.iter().map(|r| r.1).collect();
spans.sort_by_key(|r| (r.start, r.duration));
spans.dedup();
let mut work = seq.clone();
delete_items(&mut work, items);
let affected: Vec<TrackId> = ranges.iter().map(|r| r.0).collect();
for span in spans.iter().rev() {
// the gap actually closable: from span.start to the next material on affected tracks
for tr in work.all_tracks_mut() {
@@ -383,7 +428,7 @@ pub fn ripple_delete_items(seq: &mut Sequence, items: &[ClipId]) -> Result<()> {
}
}
*seq = work;
Ok(())
Ok(spans)
}
/// Close the gap containing `t` on a track (Ripple Delete on a gap).
@@ -505,6 +550,7 @@ pub fn trim(seq: &mut Sequence, clip: ClipId, edge: Edge, mode: TrimMode, delta:
let (tid, it) = seq.find_item(clip).ok_or(EditError::NoItem(clip))?;
let old_end = it.end();
let old_start = it.start;
let own_link = it.link;
let speed = it.speed.abs();
let mut work = seq.clone();
{
@@ -537,8 +583,12 @@ pub fn trim(seq: &mut Sequence, clip: ClipId, edge: Edge, mode: TrimMode, delta:
continue;
}
if tr.id == tid || tr.sync_lock {
if tr.id != tid && shift < Tick::ZERO && !track_range_empty(tr, TimeRange::new(at + shift - Tick(if edge == Edge::In { 1 } else { 0 }), -shift))
{
// the stretch that closes: a shorter head takes it from just after the cut, a
// shorter tail from just before it
let closing = if edge == Edge::In { TimeRange::new(old_start, -shift) } else { TimeRange::new(at + shift, -shift) };
// (the clip's own linked partners are the caller's to trim or leave)
let in_the_way = tr.items.iter().any(|i| i.range().overlaps(&closing) && (own_link.is_none() || i.link != own_link));
if tr.id != tid && shift < Tick::ZERO && in_the_way {
return Err(EditError::SyncLockConflict);
}
let from = if edge == Edge::In { old_start + Tick(1) } else { old_end };
@@ -559,8 +609,9 @@ pub fn trim(seq: &mut Sequence, clip: ClipId, edge: Edge, mode: TrimMode, delta:
/// Ripple-trim one edge of a group of linked items (e.g. a clip and its audio partners) as a single
/// edit: every member's edge moves by the same delta, later material on the members' tracks and on
/// sync-locked tracks shifts by the change. Only tracks without a group member can block the edit
/// (a sync-locked track whose material would be overwritten).
/// sync-locked tracks shifts by the change, and so does a clip that starts before the cut, reaches
/// past it and is linked to a clip that shifts (a split edit). The edit is refused when it would
/// overwrite material on a sync-locked track, or when such a linked clip has no room to follow.
pub fn ripple_trim_group(seq: &mut Sequence, clips: &[ClipId], edge: Edge, delta: Tick, ctx: &mut EditCtx) -> Result<Tick> {
let Some(&first) = clips.first() else { return Ok(Tick::ZERO) };
let mut d = delta;
@@ -601,32 +652,75 @@ pub fn ripple_trim_group(seq: &mut Sequence, clips: &[ClipId], edge: Edge, delta
origins.push((tid, from));
}
}
let main_from = {
// a shorter or longer head: the cut is the latest member's start (a sound that leads its picture
// starts earlier), whichever member was grabbed
let main_from = if edge == Edge::In {
origins.iter().map(|o| o.1).max().unwrap_or_default()
} else {
let (tid, _) = seq.find_item(first).ok_or(EditError::NoItem(first))?;
origins.iter().find(|(t, _)| *t == tid).map(|o| o.1).unwrap_or_default()
};
let shift = if edge == Edge::In { -d } else { d };
for tr in work.all_tracks_mut() {
if tr.locked {
continue;
}
let member = origins.iter().find(|(t, _)| *t == tr.id).map(|o| o.1);
if member.is_none() && !tr.sync_lock {
continue;
}
let from = member.unwrap_or(main_from);
if member.is_none() && shift < Tick::ZERO {
let at = if edge == Edge::In { from - Tick(1) } else { from };
if !track_range_empty(tr, TimeRange::new(at + shift, -shift)) {
// where the shift starts on each track that ripples: the members' tracks and the sync-locked ones
let rippling: Vec<(TrackId, Tick, bool)> = work
.all_tracks()
.filter(|tr| !tr.locked)
.filter_map(|tr| match origins.iter().find(|(t, _)| *t == tr.id) {
Some(o) => Some((tr.id, o.1, true)),
None => tr.sync_lock.then_some((tr.id, main_from, false)),
})
.collect();
// A split edit: the linked partner of a later clip can start before the shift does and reach
// past it (its sound leads the cut). It follows the clip it is linked to, or the two would
// drift apart.
// (the trimmed clips' own partners are trimmed, or left alone, by the caller: they never follow)
let own_links: Vec<u64> = clips.iter().filter_map(|c| work.find_item(*c).and_then(|(_, i)| i.link)).collect();
let mut shifting_links: Vec<u64> = Vec::new();
for (tid, from, _) in &rippling {
let Some(tr) = work.track(*tid) else { continue };
let later = tr.items.iter().filter(|i| !clips.contains(&i.id) && i.start >= *from);
shifting_links.extend(later.filter_map(|i| i.link).filter(|l| !own_links.contains(l)));
}
// every linked clip: its link, and where it is and ends
let linked: Vec<(u64, ClipId, Tick)> = work.all_tracks().flat_map(|tr| tr.items.iter().filter_map(|i| i.link.map(|l| (l, i.id, i.end())))).collect();
for (tid, from, member) in rippling {
let Some(tr) = work.track_mut(tid) else { continue };
let follows = |i: &TrackItem| i.start < from && i.end() > from && i.link.is_some_and(|l| shifting_links.contains(&l));
// An L cut: the sound of a clip that ends at the cut runs on into the shortened head. That clip
// stays put, so its sound stays with it and the L cut still ends where it did. (Unlinked material
// across the cut, a music bed, still refuses, and so does a linked clip whose partner reaches past
// the cut.)
let stays = |i: &TrackItem| {
let cut = from - Tick(1);
let mut partners = linked.iter().filter(|p| Some(p.0) == i.link && p.1 != i.id).peekable();
edge == Edge::In && i.start < cut && i.link.is_some_and(|l| !own_links.contains(&l)) && partners.peek().is_some() && partners.all(|p| p.2 <= cut)
};
if !member && shift < Tick::ZERO {
// a shorter head closes the stretch just after the cut, a shorter tail the one before it
let closing = if edge == Edge::In { TimeRange::new(from - Tick(1), -shift) } else { TimeRange::new(from + shift, -shift) };
let own = |i: &TrackItem| i.link.is_some_and(|l| own_links.contains(&l));
if tr.items.iter().any(|i| i.range().overlaps(&closing) && !follows(i) && !own(i) && !stays(i)) {
return Err(EditError::SyncLockConflict);
}
}
let followers: Vec<ClipId> = tr.items.iter().filter(|i| !clips.contains(&i.id) && follows(i)).map(|i| i.id).collect();
for i in &mut tr.items {
if !clips.contains(&i.id) && i.start >= from {
if !clips.contains(&i.id) && (i.start >= from || followers.contains(&i.id)) {
i.start += shift;
}
}
tr.sort();
// a transition into a follower from a clip that stayed behind no longer sits on a cut
let ends: Vec<(ClipId, Tick)> = tr.items.iter().map(|i| (i.id, i.end())).collect();
let starts: Vec<(ClipId, Tick)> = tr.items.iter().map(|i| (i.id, i.start)).collect();
tr.transitions.retain(|t| match (t.from, t.to) {
(Some(a), Some(b)) if followers.contains(&b) => ends.iter().find(|e| e.0 == a).map(|e| e.1) == starts.iter().find(|x| x.0 == b).map(|x| x.1),
_ => true,
});
// a follower with no room (a clip in its way, or the sequence start) blocks the edit
if tr.items.first().is_some_and(|i| i.start < Tick::ZERO) || tr.items.windows(2).any(|w| w[0].end() > w[1].start) {
return Err(EditError::SyncLockConflict);
}
}
transitions_follow_cuts(seq, &mut work);
work.check().map_err(EditError::Other)?;
@@ -751,41 +845,70 @@ pub fn rate_stretch(seq: &mut Sequence, clip: ClipId, edge: Edge, delta: Tick, c
/// Set speed/duration (Clip ▸ Speed/Duration…). `ripple` shifts following material.
pub fn set_speed(seq: &mut Sequence, clip: ClipId, speed: f64, reverse: bool, ripple: bool, ctx: &mut EditCtx) -> Result<()> {
if speed <= 0.0 {
set_speed_group(seq, &[clip], speed, reverse, ripple, ctx)
}
/// Speed/Duration on a clip and its linked partners on other tracks (its sound) as a single edit.
/// `clips` holds at most one clip per track. Every member takes the speed, and with `ripple` the
/// later material moves once, on the members' tracks and on sync-locked tracks. Rippling each
/// member on its own would move the later clips once per member. When the members' lengths change
/// by different amounts (a split edit), the later material moves by the largest change, so no
/// member is overlapped and the tracks stay in sync. Nothing changes when the edit fails.
pub fn set_speed_group(seq: &mut Sequence, clips: &[ClipId], speed: f64, reverse: bool, ripple: bool, ctx: &mut EditCtx) -> Result<()> {
if !(speed.is_finite() && speed > 0.0) {
return Err(EditError::Other("speed must be positive".into()));
}
let (tid, it) = seq.find_item(clip).ok_or(EditError::NoItem(clip))?;
let src_len = it.source_out() - it.source_in;
let mut new_dur = Tick((src_len.0 as f64 / speed).round() as i64).max(ctx.min_duration);
let old_end = it.end();
let tr = seq.track(tid).ok_or(EditError::NoTrack(tid))?;
let (_, next_start) = neighbours(tr, clip);
if !ripple {
new_dur = new_dur.min(next_start - it.start);
}
let delta = new_dur - it.duration;
let before = ripple.then(|| seq.clone());
{
let (_, it) = seq.find_item_mut(clip).ok_or(EditError::NoItem(clip))?;
let mut work = seq.clone();
// per member track: where its later material starts, and by how much the member's length changed
let mut origins: Vec<(TrackId, Tick, Tick)> = Vec::new();
for clip in clips {
let (tid, it) = work.find_item(*clip).ok_or(EditError::NoItem(*clip))?;
if origins.iter().any(|o| o.0 == tid) {
return Err(EditError::Other("clips on one track change speed one at a time".into()));
}
let src_len = it.source_out() - it.source_in;
// a tiny speed saturates the cast: keep the clip's end representable
let room = Tick(Tick::MAX.0.saturating_sub(it.start.0.max(0)));
let mut new_dur = Tick((src_len.0 as f64 / speed).round() as i64).min(room).max(ctx.min_duration);
let old_end = it.end();
let tr = work.track(tid).ok_or(EditError::NoTrack(tid))?;
let (_, next_start) = neighbours(tr, *clip);
if !ripple {
new_dur = new_dur.min(next_start - it.start);
}
let delta = new_dur - it.duration;
let (_, it) = work.find_item_mut(*clip).ok_or(EditError::NoItem(*clip))?;
it.speed = speed;
it.reverse = reverse;
it.duration = new_dur;
origins.push((tid, old_end, delta));
}
if ripple && delta != Tick::ZERO {
for tr in seq.all_tracks_mut() {
if !tr.locked && (tr.id == tid || tr.sync_lock) {
for i in &mut tr.items {
if i.id != clip && i.start >= old_end {
i.start += delta;
}
}
tr.sort();
let main_from = origins.first().map(|o| o.1).unwrap_or_default();
let shift = origins.iter().map(|o| o.2).max().unwrap_or_default();
if ripple && shift != Tick::ZERO {
for tr in work.all_tracks_mut() {
if tr.locked {
continue;
}
let member = origins.iter().find(|o| o.0 == tr.id).map(|o| o.1);
if member.is_none() && !tr.sync_lock {
continue;
}
let from = member.unwrap_or(main_from);
for i in &mut tr.items {
if !clips.contains(&i.id) && i.start >= from {
// later clips must still end on the representable timeline
let start = i.start.0.checked_add(shift.0).filter(|s| s.checked_add(i.duration.0).is_some());
i.start = Tick(start.ok_or_else(|| EditError::Other("the speed change would move later clips past the end of the timeline".into()))?);
}
}
tr.sort();
}
}
if let Some(before) = before {
transitions_follow_cuts(&before, seq);
if ripple {
transitions_follow_cuts(seq, &mut work);
}
*seq = work;
Ok(())
}
+305
View File
@@ -148,6 +148,81 @@ fn ripple_delete_and_conflict() {
assert_eq!(fx.spans(v1), vec![(0, 10), (20, 10)], "unchanged on failure");
}
#[test]
fn ripple_delete_closes_the_time_free_on_every_track() {
// four clips on V1 with their sounds on A1; the second sound starts 2 early and ends 2 late
let build = || {
let mut fx = Fx::new();
let (v1, a1) = (fx.v(0), fx.a(0));
let v: Vec<ClipId> = [(0, 10), (10, 10), (20, 10), (30, 10)].iter().map(|(s, d)| fx.put(v1, *s, *d, 0)).collect();
let a: Vec<ClipId> = [(0, 8), (8, 14), (22, 8), (30, 10)].iter().map(|(s, d)| fx.put(a1, *s, *d, 0)).collect();
(fx, v, a)
};
let span = |start, len| TimeRange::new(f(start), f(len));
// one clip with a split edit on both sides: the picture's stretch closes, everything later stays in sync
let (mut fx, v, a) = build();
assert_eq!(ripple_delete_items(&mut fx.seq, &[v[1], a[1]]), Ok(vec![span(10, 10)]));
assert_eq!(fx.spans(fx.v(0)), vec![(0, 10), (10, 10), (20, 10)]);
assert_eq!(fx.spans(fx.a(0)), vec![(0, 8), (12, 8), (20, 10)]);
fx.seq.check().unwrap();
// two neighbours with a split edit between them close as one stretch
let (mut fx, v, a) = build();
assert_eq!(ripple_delete_items(&mut fx.seq, &[v[1], a[1], v[2], a[2]]), Ok(vec![span(10, 20)]));
assert_eq!(fx.spans(fx.v(0)), vec![(0, 10), (10, 10)]);
assert_eq!(fx.spans(fx.a(0)), vec![(0, 8), (10, 10)]);
// clips apart in time each close their own gap
let (mut fx, v, a) = build();
assert_eq!(ripple_delete_items(&mut fx.seq, &[v[0], a[0], v[3], a[3]]), Ok(vec![span(0, 8), span(30, 10)]));
fx.seq.check().unwrap();
// straight cuts with the sounds on alternating tracks: V1 [0,10) [10,20) [20,30), A1 [0,10) [20,30), A2 [10,20)
let mut fx = Fx::new();
let (v1, a1, a2) = (fx.v(0), fx.a(0), fx.a(1));
let v: Vec<ClipId> = [0, 10, 20].iter().map(|s| fx.put(v1, *s, 10, 0)).collect();
let (s0, s1) = (fx.put(a1, 0, 10, 0), fx.put(a2, 10, 10, 0));
fx.put(a1, 20, 10, 0);
assert_eq!(ripple_delete_items(&mut fx.seq, &[v[0], s0, v[1], s1]), Ok(vec![span(0, 20)]));
assert_eq!((fx.spans(v1), fx.spans(a1), fx.spans(a2)), (vec![(0, 10)], vec![(0, 10)], vec![]));
// a sound shorter than its picture with nothing round it: the whole picture closes
let mut fx = Fx::new();
let (v1, a1) = (fx.v(0), fx.a(0));
let (p, s) = (fx.put(v1, 10, 10, 0), fx.put(a1, 12, 6, 0));
fx.put(v1, 20, 10, 0);
fx.put(a1, 20, 10, 0);
assert_eq!(ripple_delete_items(&mut fx.seq, &[p, s]), Ok(vec![span(10, 10)]));
// with the neighbours' sound right up against it, only the sound's stretch can close
let mut fx = Fx::new();
let (v1, a1) = (fx.v(0), fx.a(0));
fx.put(a1, 0, 12, 0);
let (p, s) = (fx.put(v1, 10, 10, 0), fx.put(a1, 12, 6, 0));
fx.put(v1, 20, 10, 0);
fx.put(a1, 18, 12, 0);
assert_eq!(ripple_delete_items(&mut fx.seq, &[p, s]), Ok(vec![span(12, 6)]));
assert_eq!((fx.spans(v1), fx.spans(a1)), (vec![(14, 10)], vec![(0, 12), (12, 12)]));
// a linked sound on a locked track stays, and does not shrink the gap that closes
let mut fx = Fx::new();
let (v1, a1) = (fx.v(0), fx.a(0));
let (p, s) = (fx.put(v1, 10, 10, 0), fx.put(a1, 12, 6, 0));
fx.put(v1, 20, 10, 0);
fx.seq.track_mut(a1).unwrap().locked = true;
fx.seq.track_mut(a1).unwrap().sync_lock = false;
assert_eq!(ripple_delete_items(&mut fx.seq, &[p, s]), Ok(vec![span(10, 10)]));
assert_eq!((fx.spans(v1), fx.spans(a1)), (vec![(10, 10)], vec![(12, 6)]));
// nothing can close: what stays on each track covers the other track's deleted time. Refused, unchanged.
let mut fx = Fx::new();
let (v1, a1) = (fx.v(0), fx.a(0));
let x = fx.put(v1, 10, 10, 0);
fx.put(v1, 30, 10, 0);
fx.put(a1, 10, 10, 0);
let y = fx.put(a1, 30, 10, 0);
let before = fx.seq.clone();
assert!(matches!(ripple_delete_items(&mut fx.seq, &[x, y]), Err(EditError::Other(_))));
assert_eq!(fx.seq, before);
}
#[test]
fn close_gap_works() {
let mut fx = Fx::new();
@@ -192,6 +267,79 @@ fn ripple_trim_shifts_following() {
assert_eq!(fx.spans(v1), vec![(0, 12), (12, 10)]);
}
#[test]
fn ripple_trim_group_takes_a_split_edit_along() {
// V1: a [0,10) then b [10,20). b's linked sound leads it by 4 on sync-locked A1: [6,20).
let mut fx = Fx::new();
let (v1, a1) = (fx.v(0), fx.a(0));
let a = fx.put(v1, 0, 10, 0);
let b = fx.put(v1, 10, 10, 0);
let sound = fx.put(a1, 6, 14, 0);
for c in [b, sound] {
fx.seq.find_item_mut(c).unwrap().1.link = Some(7);
}
let mut n = fx.next;
ripple_trim_group(&mut fx.seq, &[a], Edge::Out, f(3), &mut Fx::ctx(&mut n)).unwrap();
assert_eq!((fx.spans(v1), fx.spans(a1)), (vec![(0, 13), (13, 10)], vec![(9, 14)]), "longer: the early sound follows its picture");
ripple_trim_group(&mut fx.seq, &[a], Edge::Out, -f(5), &mut Fx::ctx(&mut n)).unwrap();
assert_eq!((fx.spans(v1), fx.spans(a1)), (vec![(0, 8), (8, 10)], vec![(4, 14)]), "shorter: it follows too");
// the sound would start before the sequence does: refused, nothing changes
assert_eq!(ripple_trim_group(&mut fx.seq, &[a], Edge::Out, -f(5), &mut Fx::ctx(&mut n)), Err(EditError::SyncLockConflict));
// another clip right before the sound leaves it no room either
fx.put(a1, 0, 4, 0);
assert_eq!(ripple_trim_group(&mut fx.seq, &[a], Edge::Out, -f(2), &mut Fx::ctx(&mut n)), Err(EditError::SyncLockConflict));
assert_eq!((fx.spans(v1), fx.spans(a1)), (vec![(0, 8), (8, 10)], vec![(0, 4), (4, 14)]), "unchanged on failure");
// a linked clip that ends before the cut is not a split edit and stays where it is
let early = fx.put(fx.a(1), 0, 3, 0);
fx.seq.find_item_mut(early).unwrap().1.link = Some(7);
ripple_trim_group(&mut fx.seq, &[a], Edge::Out, f(2), &mut Fx::ctx(&mut n)).unwrap();
assert_eq!(fx.spans(fx.a(1)), vec![(0, 3)]);
fx.seq.check().unwrap();
// In edge: V1 b [10,20), c [20,30); c's sound starts 12 early on A1: [8,30). b loses 3 at its head.
let mut fx = Fx::new();
let (v1, v2, a1, a2) = (fx.v(0), fx.v(1), fx.a(0), fx.a(1));
fx.put(v1, 0, 10, 0);
let b = fx.put(v1, 10, 10, 0);
let c = fx.put(v1, 20, 10, 0);
let c_sound = fx.put(a1, 8, 22, 0);
// two more clips linked to b that the caller did not put in the group
let b_sound = fx.put(a2, 10, 10, 0);
let b_top = fx.put(v2, 12, 8, 0);
for (x, link) in [(c, 7), (c_sound, 7), (b, 8), (b_sound, 8), (b_top, 8)] {
fx.seq.find_item_mut(x).unwrap().1.link = Some(link);
}
let mut n = fx.next;
ripple_trim_group(&mut fx.seq, &[b], Edge::In, f(3), &mut Fx::ctx(&mut n)).unwrap();
assert_eq!((fx.spans(v1), fx.spans(a1)), (vec![(0, 10), (10, 7), (17, 10)], vec![(5, 22)]), "c and its early sound move up together");
assert_eq!((fx.spans(v2), fx.spans(a2)), (vec![(9, 8)], vec![(10, 10)]), "the trimmed clip's own partners never follow");
// a crossfade into the early sound from a clip that stays behind no longer sits on a cut: it goes
let mut fx = Fx::new();
let (v1, a1) = (fx.v(0), fx.a(0));
let a = fx.put(v1, 0, 10, 0);
let b = fx.put(v1, 10, 10, 0);
let stays = fx.put(a1, 0, 6, 0);
let sound = fx.put(a1, 6, 14, 0);
for x in [b, sound] {
fx.seq.find_item_mut(x).unwrap().1.link = Some(7);
}
fx.seq.track_mut(a1).unwrap().transitions = vec![Transition {
id: TransitionId(1),
effect: filmcraft_project::find_effect("cross_dissolve").unwrap().instance(),
start: f(4),
duration: f(4),
from: Some(stays),
to: Some(sound),
align: Default::default(),
reverse: false,
}];
let mut n = fx.next;
ripple_trim_group(&mut fx.seq, &[a], Edge::Out, f(3), &mut Fx::ctx(&mut n)).unwrap();
assert_eq!(fx.spans(a1), vec![(0, 6), (9, 14)]);
assert!(fx.seq.track(a1).unwrap().transitions.is_empty());
}
#[test]
fn roll_slip_slide() {
let mut fx = Fx::new();
@@ -269,6 +417,44 @@ fn rate_stretch_and_speed() {
assert_eq!(fx.spans(v1), vec![(0, 5)]);
}
#[test]
fn speed_on_a_linked_group_ripples_once() {
// V1: a [0,10), b [10,20). A1: a's sound [0,10), b's sound [10,20).
let build = |sound_len: i64| {
let mut fx = Fx::new();
let (v1, a1) = (fx.v(0), fx.a(0));
let a = fx.put(v1, 0, 10, 0);
fx.put(v1, 10, 10, 0);
let sound = fx.put(a1, 0, sound_len, 0);
fx.put(a1, sound_len, 10, 0);
(fx, a, sound)
};
for (speed, picture, later) in [(0.5, (0, 20), (20, 10)), (2.0, (0, 5), (5, 10))] {
let (mut fx, a, sound) = build(10);
let mut n = fx.next;
set_speed_group(&mut fx.seq, &[a, sound], speed, false, true, &mut Fx::ctx(&mut n)).unwrap();
assert_eq!((fx.spans(fx.v(0)), fx.spans(fx.a(0))), (vec![picture, later], vec![picture, later]), "{speed}");
}
// a split edit: the sound is 4 longer. Later clips move by the larger change, on both tracks.
let (mut fx, a, sound) = build(14);
let mut n = fx.next;
set_speed_group(&mut fx.seq, &[a, sound], 0.5, false, true, &mut Fx::ctx(&mut n)).unwrap();
assert_eq!((fx.spans(fx.v(0)), fx.spans(fx.a(0))), (vec![(0, 20), (24, 10)], vec![(0, 28), (28, 10)]));
let (mut fx, a, sound) = build(14);
let mut n = fx.next;
set_speed_group(&mut fx.seq, &[a, sound], 2.0, false, true, &mut Fx::ctx(&mut n)).unwrap();
assert_eq!((fx.spans(fx.v(0)), fx.spans(fx.a(0))), (vec![(0, 5), (5, 10)], vec![(0, 7), (9, 10)]));
fx.seq.check().unwrap();
// two clips of one track are not one group; a missing clip changes nothing
let (mut fx, a, _) = build(10);
let b = fx.seq.video_tracks[0].items[1].id;
let before = fx.seq.clone();
let mut n = fx.next;
assert!(set_speed_group(&mut fx.seq, &[a, b], 2.0, false, true, &mut Fx::ctx(&mut n)).is_err());
assert!(set_speed_group(&mut fx.seq, &[a, ClipId(1)], 2.0, false, true, &mut Fx::ctx(&mut n)).is_err());
assert_eq!(fx.seq, before);
}
#[test]
fn move_with_insert_and_overwrite() {
let mut fx = Fx::new();
@@ -367,3 +553,122 @@ fn merge(v: Vec<(i64, i64)>) -> Vec<(i64, i64)> {
fn unused_kind_import() {
let _ = TrackKind::Video;
}
#[test]
fn hostile_speeds_are_refused_or_clamped_never_overflow() {
// a tiny speed used to saturate the new duration to i64::MAX, then the ripple shift overflowed
for speed in [1e-7, 1e-300, f64::MIN_POSITIVE, f64::NAN, f64::INFINITY, -1.0, 0.0] {
let mut fx = Fx::new();
let v1 = fx.v(0);
let a = fx.put(v1, 0, 10, 10);
let _b = fx.put(v1, 10, 10, 10);
let before = fx.seq.clone();
let mut n = fx.next;
let r = set_speed_group(&mut fx.seq, &[a], speed, false, true, &mut Fx::ctx(&mut n));
match r {
Ok(()) => fx.seq.check().unwrap(),
Err(_) => assert_eq!(format!("{:?}", fx.seq), format!("{before:?}"), "{speed}: a refused edit changes nothing"),
}
}
}
#[test]
fn shorter_head_into_an_l_cut_keeps_the_earlier_sound_where_it_is() {
// V1: a [0,10), b [10,20), c [20,30). a's sound on sync-locked A1 runs 3 into b: [0,13) (an L
// cut). b loses 3 at its head: a never moves, so its sound stays and the L cut still ends at 13.
let mut fx = Fx::new();
let (v1, a1) = (fx.v(0), fx.a(0));
let a = fx.put(v1, 0, 10, 0);
let b = fx.put(v1, 10, 10, 0);
fx.put(v1, 20, 10, 0);
let a_sound = fx.put(a1, 0, 13, 0);
for x in [a, a_sound] {
fx.seq.find_item_mut(x).unwrap().1.link = Some(7);
}
let mut n = fx.next;
ripple_trim_group(&mut fx.seq, &[b], Edge::In, f(3), &mut Fx::ctx(&mut n)).unwrap();
assert_eq!((fx.spans(v1), fx.spans(a1)), (vec![(0, 10), (10, 7), (17, 10)], vec![(0, 13)]));
fx.seq.check().unwrap();
// later material on A1 moves up with the pictures; landing on the L cut's sound refuses
let later = fx.put(a1, 15, 5, 0);
assert_eq!(ripple_trim_group(&mut fx.seq, &[b], Edge::In, f(3), &mut Fx::ctx(&mut n)), Err(EditError::SyncLockConflict));
assert_eq!(fx.spans(a1), vec![(0, 13), (15, 5)], "unchanged on failure");
fx.seq.find_item_mut(later).unwrap().1.start = f(20);
ripple_trim_group(&mut fx.seq, &[b], Edge::In, f(2), &mut Fx::ctx(&mut n)).unwrap();
assert_eq!((fx.spans(v1), fx.spans(a1)), (vec![(0, 10), (10, 5), (15, 10)], vec![(0, 13), (18, 5)]));
// unlinked material across the cut (a music bed) still refuses
let mut fx = Fx::new();
let (v1, a1) = (fx.v(0), fx.a(0));
fx.put(v1, 0, 10, 0);
let b = fx.put(v1, 10, 10, 0);
fx.put(a1, 0, 13, 0);
let mut n = fx.next;
assert_eq!(ripple_trim_group(&mut fx.seq, &[b], Edge::In, f(3), &mut Fx::ctx(&mut n)), Err(EditError::SyncLockConflict));
// so does a link with no partner left
fx.seq.track_mut(a1).unwrap().items[0].link = Some(9);
assert_eq!(ripple_trim_group(&mut fx.seq, &[b], Edge::In, f(3), &mut Fx::ctx(&mut n)), Err(EditError::SyncLockConflict));
// a linked cutaway across the cut whose own partner reaches past it too is no L cut: it refuses
let mut fx = Fx::new();
let (v1, v2, a1) = (fx.v(0), fx.v(1), fx.a(0));
fx.put(v1, 0, 10, 0);
let b = fx.put(v1, 10, 10, 0);
fx.put(v1, 20, 10, 0);
let x = fx.put(v2, 5, 20, 0);
let xs = fx.put(a1, 5, 20, 0);
for c in [x, xs] {
fx.seq.find_item_mut(c).unwrap().1.link = Some(7);
}
let mut n = fx.next;
assert_eq!(ripple_trim_group(&mut fx.seq, &[b], Edge::In, f(3), &mut Fx::ctx(&mut n)), Err(EditError::SyncLockConflict));
}
#[test]
fn shorter_head_closes_the_stretch_after_the_cut_on_sync_locked_tracks() {
// V1: a [0,10), b [10,20). a's sound on sync-locked A1 runs up to the cut: [0,10). b loses 3 at
// its head; the stretch that closes is [10,13), where A1 is empty, so nothing refuses.
for group in [false, true] {
let mut fx = Fx::new();
let (v1, a1) = (fx.v(0), fx.a(0));
fx.put(v1, 0, 10, 0);
let b = fx.put(v1, 10, 10, 0);
fx.put(v1, 20, 10, 0);
fx.put(a1, 0, 10, 0);
let later = fx.put(a1, 20, 5, 0);
let mut n = fx.next;
if group {
ripple_trim_group(&mut fx.seq, &[b], Edge::In, f(3), &mut Fx::ctx(&mut n)).unwrap();
} else {
trim(&mut fx.seq, b, Edge::In, TrimMode::Ripple, f(3), &mut Fx::ctx(&mut n)).unwrap();
}
assert_eq!((fx.spans(v1), fx.spans(a1)), (vec![(0, 10), (10, 7), (17, 10)], vec![(0, 10), (17, 5)]), "group {group}");
// material inside the stretch that closes still refuses
fx.seq.find_item_mut(later).unwrap().1.start = f(11);
let r = if group {
ripple_trim_group(&mut fx.seq, &[b], Edge::In, f(2), &mut Fx::ctx(&mut n))
} else {
trim(&mut fx.seq, b, Edge::In, TrimMode::Ripple, f(2), &mut Fx::ctx(&mut n))
};
assert_eq!(r, Err(EditError::SyncLockConflict), "group {group}");
}
// a clip on a sync-locked track that starts at the cut stays put while the pictures after it move
// up: only the stretch after the cut sees it (the old stretch, before the cut, let it through)
for group in [false, true] {
let mut fx = Fx::new();
let (v1, a1) = (fx.v(0), fx.a(0));
fx.put(v1, 0, 10, 0);
let b = fx.put(v1, 10, 10, 0);
fx.put(v1, 20, 10, 0);
fx.put(a1, 10, 5, 0);
let mut n = fx.next;
let r = if group {
ripple_trim_group(&mut fx.seq, &[b], Edge::In, f(3), &mut Fx::ctx(&mut n))
} else {
trim(&mut fx.seq, b, Edge::In, TrimMode::Ripple, f(3), &mut Fx::ctx(&mut n))
};
assert_eq!(r, Err(EditError::SyncLockConflict), "group {group}");
assert_eq!(fx.spans(v1), vec![(0, 10), (10, 10), (20, 10)], "unchanged on failure");
}
}
+32 -13
View File
@@ -19,8 +19,8 @@ use std::sync::{Arc, Mutex};
use serde_json::{Value, json};
use filmcraft_interchange::essence::{AudioEssence, AudioNeed, EssenceData, EssenceKey, MediaOptions, MixdownVideo, NeedOptions, audio_needs};
use filmcraft_project::{ItemId, Project, SequenceSettings, TrackKind};
use filmcraft_interchange::essence::{AudioEssence, AudioNeed, EssenceData, EssenceKey, MediaOptions, MixdownVideo, NeedOptions, NestNeeds, audio_needs};
use filmcraft_project::{ClipId, ItemId, Project, Sequence, SequenceSettings, Track, TrackItem, TrackKind};
use filmcraft_time::{Tick, TimeRange};
use crate::commands::{bad, bool_p, str_p, u64_p};
@@ -50,6 +50,10 @@ pub struct AudioPlan {
pub handles: Tick,
pub render_effects: bool,
pub breakout: bool,
/// Nested sequences on the audio tracks. OMF: their sound is rendered into the export, as
/// Premiere Pro does. AAF: they are written as compositions, so the media of the clips inside
/// them is prepared like the rest.
pub nests: NestNeeds,
}
fn plan_from(s: &Session, p: &Value, seq: ItemId, cmd: &str, omf: bool) -> Result<AudioPlan> {
@@ -85,6 +89,7 @@ fn plan_from(s: &Session, p: &Value, seq: ItemId, cmd: &str, omf: bool) -> Resul
handles: q.settings.frame_rate.tick_of(frames),
render_effects: bool_p(p, "renderAudioEffects").unwrap_or(false),
breakout: bool_p(p, "breakoutToMono").unwrap_or(false),
nests: if omf { NestNeeds::Render } else { NestNeeds::Inside },
})
}
@@ -154,12 +159,8 @@ fn decode(s: &Session, need: &AudioNeed, sample_rate: u32) -> Result<Vec<Vec<f32
/// pipeline's audio mixer.
fn render_clip(s: &Session, seq: ItemId, need: &AudioNeed, sample_rate: u32, bits: u16) -> Result<Vec<Vec<f32>>> {
let EssenceKey::Clip(clip_id) = need.key else { return decode(s, need, sample_rate) };
let q = s.project.sequence(seq).ok_or(EngineError::NoSequence)?;
let (track, c) = q
.tracks(TrackKind::Audio)
.iter()
.find_map(|t| t.items.iter().find(|c| c.id == clip_id).map(|c| (t, c.clone())))
.ok_or_else(|| EngineError::Other("clip not found".into()))?;
let (q, track, c) = audio_clip(&s.project, seq, clip_id).ok_or_else(|| EngineError::Other("clip not found".into()))?;
let c = c.clone();
let mut p: Project = (*s.project).clone();
let settings = SequenceSettings { sample_rate, ..q.settings.clone() };
let rs = p.new_sequence("AAF audio render", settings, 0, 1, None);
@@ -204,6 +205,19 @@ fn render_clip(s: &Session, seq: ItemId, need: &AudioNeed, sample_rate: u32, bit
Ok(dequantize(&pcm, ch as usize, b))
}
/// The audio clip `clip` with its track and sequence: in `seq`, or in a sequence nested in it
/// (clip ids are unique in a project).
fn audio_clip(p: &Project, seq: ItemId, clip: ClipId) -> Option<(&Sequence, &Track, &TrackItem)> {
let first = p.sequence(seq).into_iter();
let others = p.sequences().filter(|i| i.id != seq).filter_map(|i| p.sequence(i.id));
for q in first.chain(others) {
if let Some((t, c)) = q.tracks(TrackKind::Audio).iter().find_map(|t| t.items.iter().find(|c| c.id == clip).map(|c| (t, c))) {
return Some((q, t, c));
}
}
None
}
fn safe_name(s: &str) -> String {
let n: String = s.chars().map(|c| if c.is_alphanumeric() || " -_.".contains(c) { c } else { '_' }).collect();
let n = n.trim().trim_matches('.').to_string();
@@ -221,19 +235,24 @@ pub fn prepare_audio(s: &Session, seq: ItemId, plan: &AudioPlan, media_dir: &str
if plan.mode == AudioMode::Linked && !plan.trim && !plan.render_effects {
return Ok((Vec::new(), Vec::new()));
}
let needs =
audio_needs(&s.project, seq, &NeedOptions { handles: plan.handles, per_clip: plan.render_effects, whole_media: !plan.trim && !plan.render_effects });
let needs = audio_needs(
&s.project,
seq,
&NeedOptions { handles: plan.handles, per_clip: plan.render_effects, whole_media: !plan.trim && !plan.render_effects, nests: plan.nests },
);
let mut essence = Vec::new();
let mut files = Vec::new();
let mut used = std::collections::HashSet::new();
for need in &needs {
let planar = if plan.render_effects { render_clip(s, seq, need, plan.sample_rate, plan.bits)? } else { decode(s, need, plan.sample_rate)? };
// a nested sequence has no file to read: its sound is mixed, with what is on the clip
let nest = s.project.sequence(need.item).is_some();
let planar = if plan.render_effects || nest { render_clip(s, seq, need, plan.sample_rate, plan.bits)? } else { decode(s, need, plan.sample_rate)? };
let frames = planar.first().map_or(0, Vec::len) as u64;
let groups: Vec<(Option<u32>, Vec<&Vec<f32>>)> =
if plan.breakout { planar.iter().enumerate().map(|(c, x)| (Some(c as u32), vec![x])).collect() } else { vec![(None, planar.iter().collect())] };
let base = match need.key {
EssenceKey::Clip(c) => {
let name = s.project.sequence(seq).and_then(|q| q.find_item(c)).map(|(_, ti)| ti.name.clone()).unwrap_or_default();
let name = audio_clip(&s.project, seq, c).map(|(_, _, ti)| ti.name.clone()).unwrap_or_default();
format!("{} {}", safe_name(&name), c.0)
}
EssenceKey::Media(_) => safe_name(
@@ -302,7 +321,7 @@ pub fn prepare_audio(s: &Session, seq: ItemId, plan: &AudioPlan, media_dir: &str
bits: plan.bits,
channels: n,
data,
effects_rendered: plan.render_effects,
effects_rendered: plan.render_effects || nest,
});
}
}
+89
View File
@@ -208,6 +208,95 @@ fn omf_renders_clip_effects_into_embedded_audio() {
let _ = std::fs::remove_dir_all(dir);
}
/// `setup`, with both clips nested into "Inner" (one linked picture + sound nest on V1 / A1) and
/// −6.0206 dB (half amplitude) on the nest's sound clip.
fn setup_nested(name: &str) -> (Session, Vec<ItemId>, ItemId, ItemId, std::path::PathBuf) {
let (mut s, items, seq, dir) = setup(name);
s.execute("sequence.open", json!({"item": seq.0})).unwrap();
let clips: Vec<u64> = s.project.sequence(seq).unwrap().all_tracks().flat_map(|t| t.items.iter().map(|c| c.id.0)).collect();
s.execute("timeline.select", json!({"clips": clips})).unwrap();
let inner = ItemId(s.execute("clip.nest", json!({"name": "Inner"})).unwrap()["sequence"].as_u64().unwrap());
let mut p = (*s.project).clone();
let q = p.sequence_mut(seq).unwrap();
assert_eq!((q.video_tracks[0].items.len(), q.audio_tracks[0].items.len()), (1, 1), "one linked nest");
q.audio_tracks[0].items[0].effect_mut("volume").unwrap().params.insert("level".into(), Param::new(ParamValue::Float(-6.020_599_913)));
s.project = Arc::new(p);
(s, items, seq, inner, dir)
}
/// Premiere Pro renders the sound of a nested sequence into an OMF as one clip named after the
/// sequence (seen in an OMF it exported). So do we: the nest is mixed, with what is on its clip.
#[test]
fn omf_renders_the_sound_of_a_nested_sequence() {
let (mut s, items, seq, inner, dir) = setup_nested("omf-nest");
let nest = s.project.sequence(seq).unwrap().audio_tracks[0].items[0].clone();
let path = dir.join("nest.omf").to_string_lossy().into_owned();
let r = s.execute("file.exportOmf", json!({"path": path, "handles": 0, "sequence": seq.0})).unwrap();
assert!(!r["report"].to_string().contains("nested"), "{r}");
let r = s.execute("file.importAaf", json!({"path": path})).unwrap();
let q = s.project.sequence(imported_seq(&r)).unwrap().clone();
let a = &q.audio_tracks[0].items;
assert_eq!(a.len(), 1, "the nest is one clip");
assert_eq!((a[0].name.as_str(), a[0].start, a[0].duration), ("Inner", nest.start, nest.duration));
assert!(s.project.sequence(a[0].item).is_none(), "media in the document, not a sequence");
// what it plays: the nested sequence's two clips one after the other, at half amplitude
let inside = s.project.sequence(inner).unwrap().audio_tracks[0].items.clone();
assert_eq!(inside.len(), 2);
let got = audio_of(&s, a[0].item, a[0].source_in.to_units_floor(48_000), 96_000);
for (k, oc) in inside.iter().enumerate() {
let want = audio_of(&s, oc.item, oc.source_in.to_units_floor(48_000), 48_000);
assert_eq!(oc.item, items[k]);
let peak = want[0].iter().fold(0f32, |m, x| m.max(x.abs()));
assert!(peak > 0.01, "the demo scene has audio");
// (away from the cut between the two clips)
for i in 480..47_520 {
let g = got[0][k * 48_000 + i];
assert!((g - want[0][i] * 0.5).abs() < 2e-3, "clip {k} sample {i}: {g} vs {}", want[0][i] * 0.5);
}
}
let _ = std::fs::remove_dir_all(dir);
}
/// An AAF holds a nested sequence as a composition of its own (as Premiere Pro's does): it comes
/// back as a sequence that the nest clips use, with its own clips, and with embedded audio the
/// media inside it is in the document too.
#[test]
fn aaf_keeps_a_nested_sequence_as_a_sequence() {
let (mut s, items, seq, inner, dir) = setup_nested("aaf-nest");
let path = dir.join("nest.aaf").to_string_lossy().into_owned();
let r = s.execute("file.exportAaf", json!({"path": path, "audio": "embedded", "trimAudio": true, "handles": 6, "sequence": seq.0})).unwrap();
assert!(!r["report"].to_string().contains("gap"), "{r}");
let r = s.execute("file.import", json!({"paths": [path]})).unwrap();
let q = s.project.sequence(imported_seq(&r)).unwrap().clone();
let (v, a) = (&q.video_tracks[0].items, &q.audio_tracks[0].items);
assert_eq!((v.len(), a.len()), (1, 1));
let nested = v[0].item;
assert_ne!(nested, inner, "a sequence of the imported document");
assert_eq!((a[0].item, s.project.item(nested).unwrap().name.as_str()), (nested, "Inner"));
assert!(v[0].link.is_some() && v[0].link == a[0].link, "picture and sound of the nest are linked");
let level = a[0].effect("volume").and_then(|e| e.param("level")).and_then(|p| p.value.as_f64()).unwrap();
assert!((level + 6.0206).abs() < 1e-2, "the level stays on the nest's clip: {level}");
// inside: the two clips, their picture linked to the movies, their sound in the document
let n = s.project.sequence(nested).unwrap().clone();
let orig = s.project.sequence(inner).unwrap().clone();
for kind in [TrackKind::Video, TrackKind::Audio] {
let got: Vec<_> = n.tracks(kind)[0].items.iter().map(|c| (c.start, c.duration)).collect();
let want: Vec<_> = orig.tracks(kind)[0].items.iter().map(|c| (c.start, c.duration)).collect();
assert_eq!(got, want, "{kind:?}");
}
assert_eq!(path_of(&s, n.video_tracks[0].items[0].item), path_of(&s, items[0]));
for (c, oc) in n.audio_tracks[0].items.iter().zip(&orig.audio_tracks[0].items) {
let p = path_of(&s, c.item);
assert!(p.ends_with(".wav") && std::path::Path::new(&p).exists(), "{p}");
let got = audio_of(&s, c.item, c.source_in.to_units_floor(48_000), 4800);
let want = audio_of(&s, oc.item, oc.source_in.to_units_floor(48_000), 4800);
for i in 0..4800 {
assert!((got[0][i] - want[0][i]).abs() <= 1.0 / 32_768.0 + 1e-6, "sample {i}");
}
}
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn commands_are_registered_with_menus_and_validate_params() {
for (id, menu) in [("file.exportAaf", &["File", "Export"][..]), ("file.exportOmf", &["File", "Export"][..]), ("file.importAaf", &[][..])] {
+60 -7
View File
@@ -237,9 +237,15 @@ pub(crate) fn commands() -> Vec<CommandSpec> {
can_replace_from_source,
|s, p| replace_with(s, p, Replace::MatchFrame),
),
spec("clip.replaceFromBin", "From Bin", &["Clip", "Replace With Clip"], None, r#"{"clips":[id]?,"item":id?}"#, can_replace_from_bin, |s, p| {
replace_with(s, p, Replace::Bin)
}),
spec(
"clip.replaceFromBin",
"From Bin",
&["Clip", "Replace With Clip"],
None,
r#"{"clips":[id]?,"item":id?,"keepSourceIn":bool=false}"#,
can_replace_from_bin,
|s, p| replace_with(s, p, Replace::Bin),
),
]
}
@@ -1664,12 +1670,22 @@ fn replace_with(s: &mut Session, p: &Value, how: Replace) -> Result<Value> {
Replace::Bin => item_range(&s.project, new_item, s.prefs.timeline.still_duration(s.sequence_rate())).map(|r| r.start).unwrap_or_default(),
_ => source_range(s).map(|(_, r)| r.start).unwrap_or_default(),
};
// From Bin starts at the item's In point, as Premiere does; `keepSourceIn` keeps each clip's own
let keep_in = how == Replace::Bin && bool_p(p, "keepSourceIn").unwrap_or(false);
// ...but a subclip that restricts trims has no media outside its range: a kept In stays on
// one of its frames (first frame, last frame)
let keep_within = match &pi.kind {
ItemKind::Subclip { range, restrict_trims: true, .. } => {
Some((range.start, (range.end() - item_rate(&s.project, new_item).frame_duration()).max(range.start)))
}
_ => None,
};
let src_ph = s.state.source_playhead;
let ph = s.playhead();
let targets = with_links(s, &clips_p(s, p));
let src_channels = pi.as_media().and_then(|m| m.interpret.audio_channels.as_ref()).and_then(|a| a.clips.first().cloned()).unwrap_or_default();
let replaced = s.edit_sequence("Replace With Clip", |q, _, _| {
let mut out = Vec::new();
let (replaced, clamped) = s.edit_sequence("Replace With Clip", |q, _, _| {
let (mut out, mut clamped) = (Vec::new(), Vec::new());
for c in &targets {
let Some((tid, _)) = q.find_item(*c) else { continue };
let kind = q.track(tid).map(|t| t.kind).unwrap_or_default();
@@ -1680,6 +1696,13 @@ fn replace_with(s: &mut Session, p: &Value, how: Replace) -> Result<Value> {
let src_in = match how {
// the Source monitor frame lines up with the sequence playhead
Replace::MatchFrame => src_ph - Tick(((ph - it.start).0 as f64 * it.speed.abs()).round() as i64),
_ if keep_in => {
let kept = keep_within.map(|(first, last)| it.source_in.clamp(first, last)).unwrap_or(it.source_in);
if kept != it.source_in {
clamped.push(c.0);
}
kept
}
_ => in_point,
};
if src_in < Tick::ZERO {
@@ -1699,7 +1722,37 @@ fn replace_with(s: &mut Session, p: &Value, how: Replace) -> Result<Value> {
if out.is_empty() {
return Err(EngineError::Other("the replacement has no video or audio for the selected clips".into()));
}
Ok(out)
Ok((out, clamped))
})?;
Ok(json!({"clips": replaced, "item": new_item.0}))
let mut result = json!({"clips": replaced, "item": new_item.0, "short": short_clips(s, &replaced)});
if keep_in {
// the clips whose In was outside a trims-restricted subclip and now sits on its nearest frame
result["sourceInClamped"] = json!(clamped);
}
Ok(result)
}
/// The clips among `clips` that play past the end of their media, with how many sequence frames
/// of the clip have no media (at most the clip's own length). The edit is left as it is (the
/// renderer holds the last frame there); this is so whoever replaced the clip knows.
fn short_clips(s: &Session, clips: &[u64]) -> Vec<Value> {
let Some(q) = s.active_sequence() else { return Vec::new() };
let frame = q.settings.frame_rate.frame_duration().0.max(1);
clips
.iter()
.filter_map(|c| {
let (_, it) = q.find_item(ClipId(*c))?;
// stills, mattes and other sources without an end are never short; nor is a held frame
let media_end = crate::media_duration(&s.project, &s.media, it.item)?;
let over = it.source_out().0.saturating_sub(media_end.0);
if over <= 0 || it.frame_hold.is_some() {
return None;
}
// media ticks past the end, as sequence ticks of this clip
let length = it.duration.0.max(0);
let ticks = ((over as f64 / it.speed.abs().max(1e-9)).round().min(length as f64) as i64).min(length);
let frames = ticks.saturating_add(frame - 1) / frame;
(frames > 0).then(|| json!({"clip": c, "shortByFrames": frames}))
})
.collect()
}
+212
View File
@@ -602,6 +602,154 @@ fn replace_with_clip_from_source_match_frame_and_bin() {
assert!(s.execute("clip.replaceFromBin", json!({"item": music.0})).is_err());
}
/// Replace With Clip ▸ From Bin restarts the clip at the new item's In point (as Premiere does);
/// `keepSourceIn` keeps the clip's place in the media instead.
#[test]
fn replace_from_bin_keeps_the_source_in_on_request() {
let mut s = demo();
let rate = s.sequence_rate();
s.execute("sequence.linkedSelection", json!({"on": false})).unwrap();
let c = v1(&s)[3].clone();
let dunes = item_named(&s, "Desert_Dunes.mp4");
let forest = item_named(&s, "Misty_Forest.mp4");
// disabled without a clip and a replacement, with or without the new parameter
s.execute("timeline.select", json!({"clips": []})).unwrap();
assert!(matches!(s.execute("clip.replaceFromBin", json!({"keepSourceIn": true})), Err(crate::EngineError::Disabled(..))));
// give the clip a source In that is not the start of its media
s.execute("timeline.trim", json!({"clip": c.id.0, "edge": "in", "mode": "regular", "deltaFrames": 7})).unwrap();
let trimmed = clip(&s, c.id.0);
assert_eq!(trimmed.source_in, c.source_in + rate.tick_of(7));
select(&mut s, &[c.id.0]);
s.execute("project.select", json!({"items": [dunes.0]})).unwrap();
let before = s.project.clone();
// default: the replacement starts at the item's In point, and the result is what it was
let r = s.execute("clip.replaceFromBin", json!({})).unwrap();
assert_eq!((clip(&s, c.id.0).item, clip(&s, c.id.0).source_in), (dunes, Tick::ZERO));
assert_eq!(r, json!({"clips": [c.id.0], "item": dunes.0, "short": []}));
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(*s.project, *before);
// keepSourceIn: the same place in the new media, everything else as before
let r = s.execute("clip.replaceFromBin", json!({"keepSourceIn": true})).unwrap();
let got = clip(&s, c.id.0);
assert_eq!((got.item, got.source_in, got.start, got.duration), (dunes, trimmed.source_in, trimmed.start, trimmed.duration));
assert_eq!(r, json!({"clips": [c.id.0], "item": dunes.0, "short": [], "sourceInClamped": []}));
let after = s.project.clone();
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(*s.project, *before);
s.execute("edit.redo", json!({})).unwrap();
assert_eq!(*s.project, *after);
s.execute("edit.undo", json!({})).unwrap();
s.execute("clip.replaceFromBin", json!({"keepSourceIn": false})).unwrap();
assert_eq!(clip(&s, c.id.0).source_in, Tick::ZERO);
s.execute("edit.undo", json!({})).unwrap();
// a subclip that restricts trims has no media outside its range: a kept In before or after it
// moves to its first or last frame, and the result names the clip
let sub = |s: &mut Session, from: Tick, to: Tick, restrict: bool| {
let r = s.execute("clip.makeSubclip", json!({"item": forest.0, "start": from.0, "end": to.0, "restrictTrims": restrict})).unwrap();
ItemId(r["item"].as_u64().unwrap())
};
let kept = trimmed.source_in;
let media_frame = s.project.item(forest).unwrap().as_media().unwrap().frame_rate().frame_duration();
assert!(kept > rate.tick_of(10) && media_frame > Tick::ZERO);
let later = sub(&mut s, kept + rate.tick_of(3), kept + rate.tick_of(15), true);
let earlier = sub(&mut s, Tick::ZERO, kept - rate.tick_of(2), true);
let loose = sub(&mut s, kept + rate.tick_of(3), kept + rate.tick_of(15), false);
for (item, want, clamped) in [(later, kept + rate.tick_of(3), true), (earlier, kept - rate.tick_of(2) - media_frame, true), (loose, kept, false)] {
let r = s.execute("clip.replaceFromBin", json!({"item": item.0, "keepSourceIn": true})).unwrap();
let got = clip(&s, c.id.0);
assert_eq!((got.item, got.source_in, got.start, got.duration), (item, want, trimmed.start, trimmed.duration));
assert_eq!(r["sourceInClamped"], if clamped { json!([c.id.0]) } else { json!([]) });
s.execute("edit.undo", json!({})).unwrap();
}
// a kept In that is already inside the subclip stays where it is
let around = sub(&mut s, kept - rate.tick_of(5), kept + rate.tick_of(23), true);
let r = s.execute("clip.replaceFromBin", json!({"item": around.0, "keepSourceIn": true})).unwrap();
assert_eq!((clip(&s, c.id.0).source_in, &r["sourceInClamped"]), (kept, &json!([])));
// hostile values of the flag fall back to the default
s.execute("edit.undo", json!({})).unwrap();
for junk in [json!("yes"), json!(1), json!(null), json!([true])] {
let r = s.execute("clip.replaceFromBin", json!({"item": dunes.0, "keepSourceIn": junk})).unwrap();
assert_eq!((clip(&s, c.id.0).source_in, r.get("sourceInClamped")), (Tick::ZERO, None));
s.execute("edit.undo", json!({})).unwrap();
}
}
/// A replacement shorter than the clip's slot left the clip running past the end of its media
/// without a word. The three Replace With Clip commands now say which clips are short, by how
/// many sequence frames.
#[test]
fn replace_with_clip_reports_clips_that_run_past_the_new_media() {
let mut s = demo();
let rate = s.sequence_rate();
let demo_seq = s.state.active_sequence.unwrap();
s.execute("sequence.linkedSelection", json!({"on": false})).unwrap();
let c = v1(&s)[3].clone();
let slot = rate.frame_at(c.duration);
let forest = item_named(&s, "Misty_Forest.mp4");
let forest_len = s.project.item(forest).unwrap().as_media().unwrap().info.duration;
assert!(slot > 12 && forest_len > c.duration + rate.tick_of(40), "the clip is longer than 12 frames and shorter than the media");
let state = |s: &Session| {
let it = clip(s, c.id.0);
(it.item, it.source_in, it.start, it.duration)
};
select(&mut s, &[c.id.0]);
// From Bin, with 12 frames of media (a subclip that restricts trims): the edit is what it
// always was, and the result says the clip is short
let r = s.execute("clip.makeSubclip", json!({"item": forest.0, "start": rate.tick_of(10).0, "end": rate.tick_of(22).0})).unwrap();
let short = ItemId(r["item"].as_u64().unwrap());
let before = s.project.clone();
let r = s.execute("clip.replaceFromBin", json!({"item": short.0})).unwrap();
assert_eq!(state(&s), (short, rate.tick_of(10), c.start, c.duration), "the edit itself is not changed");
assert_eq!(r["short"], json!([{"clip": c.id.0, "shortByFrames": slot - 12}]));
let after = s.project.clone();
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(*s.project, *before);
s.execute("edit.redo", json!({})).unwrap();
assert_eq!(*s.project, *after);
s.execute("edit.undo", json!({})).unwrap();
// long enough media: nothing is short
assert_eq!(s.execute("clip.replaceFromBin", json!({"item": forest.0})).unwrap()["short"], json!([]));
s.execute("edit.undo", json!({})).unwrap();
// From Source Monitor, with the Source In 20 frames before the end of the media
let frames = |t: Tick| (t.0 + rate.frame_duration().0 - 1) / rate.frame_duration().0;
s.execute("source.open", json!({"item": forest.0})).unwrap();
let mark = forest_len - rate.tick_of(20);
s.execute("project.setMarks", json!({"item": forest.0, "in": mark.0})).unwrap();
let r = s.execute("clip.replaceFromSource", json!({})).unwrap();
let got = clip(&s, c.id.0);
assert_eq!(r["short"], json!([{"clip": c.id.0, "shortByFrames": frames(got.source_out() - forest_len)}]));
assert_eq!(frames(got.source_out() - forest_len), slot - 20);
s.execute("edit.undo", json!({})).unwrap();
// Match Frame: the last frame of the media on the clip's first frame
s.execute("playhead.set", json!({"time": c.start.0})).unwrap();
s.execute("source.setPlayhead", json!({"time": (forest_len - rate.tick_of(1)).0})).unwrap();
let r = s.execute("clip.replaceFromSourceMatchFrame", json!({})).unwrap();
assert_eq!(r["short"], json!([{"clip": c.id.0, "shortByFrames": slot - 1}]));
s.execute("edit.undo", json!({})).unwrap();
// with enough media after the frame, nothing is short
s.execute("source.setPlayhead", json!({"frame": 5})).unwrap();
assert_eq!(s.execute("clip.replaceFromSourceMatchFrame", json!({})).unwrap()["short"], json!([]));
s.execute("edit.undo", json!({})).unwrap();
// never more than the clip itself: an In that lies past the end of the new media altogether
s.execute("timeline.trim", json!({"clip": c.id.0, "edge": "in", "mode": "regular", "deltaFrames": 7})).unwrap();
let trimmed = clip(&s, c.id.0);
s.execute("file.newSequence", json!({"name": "Brief"})).unwrap();
let brief = s.state.active_sequence.unwrap();
s.execute("timeline.place", json!({"item": forest.0, "time": 0})).unwrap();
let placed = s.active_sequence().unwrap().video_tracks[0].items[0].clone();
s.execute("timeline.trim", json!({"clip": placed.id.0, "edge": "out", "mode": "regular", "delta": (rate.tick_of(3) - placed.duration).0})).unwrap();
s.execute("sequence.open", json!({"item": demo_seq.0})).unwrap();
select(&mut s, &[c.id.0]);
assert!(trimmed.source_in > s.project.sequence(brief).unwrap().duration(), "the kept In is past the end of the nested sequence");
let r = s.execute("clip.replaceFromBin", json!({"clips": [c.id.0], "item": brief.0, "keepSourceIn": true})).unwrap();
assert_eq!(clip(&s, c.id.0).source_in, trimmed.source_in);
assert_eq!(r["short"], json!([{"clip": c.id.0, "shortByFrames": rate.frame_at(trimmed.duration)}]), "all of the clip, not more");
}
#[test]
fn audio_source_channels_pick_what_a_clip_plays() {
let mut it = v1(&demo())[0].clone();
@@ -689,3 +837,67 @@ fn subclip_source_monitor_trims_and_markers() {
s.execute("edit.undo", json!({})).unwrap();
assert!(matches!(s.project.item(sub).unwrap().kind, ItemKind::Subclip { restrict_trims: false, .. }));
}
/// #29: a Color Matte's color can be changed after it is created; the generated frames follow,
/// and undo brings the old color back (the media pool regenerates the matte, it doesn't keep
/// serving the first one).
#[test]
fn color_matte_color_changes_and_undoes() {
let mut s = demo();
let matte = s.execute("file.newColorMatte", json!({"width": 64, "height": 36, "color": "#ff0000"})).unwrap()["item"].as_u64().unwrap();
let px = |s: &Session| {
let f = s.source(ItemId(matte)).unwrap().video_frame(filmcraft_media::FrameRequest::full(Tick::ZERO)).unwrap();
f.to_rgba8()[..3].to_vec()
};
assert_eq!(px(&s), [255, 0, 0]);
let r = s.execute("project.matteColor", json!({"item": matte, "color": "#0000ff"})).unwrap();
assert_eq!(r["color"], "#0000ff");
assert_eq!(px(&s), [0, 0, 255]);
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(px(&s), [255, 0, 0]);
// the selected matte when no item is named; anything else is refused
s.state.project_selection = vec![ItemId(matte)];
s.execute("project.matteColor", json!({"color": "#00ff00"})).unwrap();
assert_eq!(px(&s), [0, 255, 0]);
let bars = s.execute("file.newBarsAndTone", json!({})).unwrap()["item"].as_u64().unwrap();
assert!(s.execute("project.matteColor", json!({"item": bars, "color": "#00ff00"})).is_err());
assert!(s.execute("project.matteColor", json!({"item": matte, "color": "green"})).is_err());
}
/// A damaged project whose subclip is its own parent (#66): `media_duration` followed the chain
/// without a bound and overflowed the stack. It gives up after a few hops now.
#[test]
fn a_cyclic_subclip_chain_has_no_media_duration() {
let mut s = demo();
let ocean = item_named(&s, "Ocean_Sunset.mp4");
s.execute("source.open", json!({"item": ocean.0})).unwrap();
let sub = ItemId(s.execute("clip.makeSubclip", json!({})).unwrap()["item"].as_u64().unwrap());
s.execute("clip.editSubclip", json!({"item": sub.0, "restrictTrims": false})).unwrap();
let Some(ItemKind::Subclip { parent, .. }) = std::sync::Arc::make_mut(&mut s.project).item_mut(sub).map(|i| &mut i.kind) else { panic!() };
*parent = sub;
assert_eq!(crate::media_duration(&s.project, &s.media, sub), None);
}
/// #164: Add Edit with a clip selected cut every targeted track. Like Premiere it now cuts only
/// the selected clips under the playhead; with nothing selected there, the targeted tracks.
#[test]
fn add_edit_cuts_only_the_selected_clips() {
let mut s = demo();
let count = |s: &Session| {
let q = s.active_sequence().unwrap();
(q.video_tracks.iter().map(|t| t.items.len()).sum::<usize>(), q.audio_tracks.iter().map(|t| t.items.len()).sum::<usize>())
};
// a V1 clip and a time inside it
let first = v1(&s)[1].clone();
let t = first.start + filmcraft_time::Tick(first.duration.0 / 2);
let (v0, a0) = count(&s);
s.state.selection = vec![first.id];
s.execute("sequence.addEdit", json!({"time": t.0})).unwrap();
let (v1n, a1n) = count(&s);
assert_eq!((v1n, a1n), (v0 + 1, a0), "only the selected V1 clip is cut");
// nothing selected under the playhead: every targeted track is cut
s.execute("edit.undo", json!({})).unwrap();
s.state.selection.clear();
let r = s.execute("sequence.addEdit", json!({"time": t.0})).unwrap();
assert!(r["cuts"].as_u64().unwrap() > 1, "{r}");
}
+499 -107
View File
@@ -110,6 +110,33 @@ fn has_clipboard(s: &Session) -> std::result::Result<(), String> {
if s.state.clipboard.is_empty() { Err("clipboard is empty".into()) } else { Ok(()) }
}
/// The ids a caller named under `many` (a list) or `one` (a single id), when the command documents
/// that key as ids (`"clips":[id]`, `"item":id`); `None` when it named none.
fn named_ids(spec: &CommandSpec, p: &Value, many: &str, one: &str) -> Option<Vec<u64>> {
let ids: Vec<u64> = if spec.params.contains(&format!("\"{many}\":[id]"))
&& let Some(a) = p.get(many).and_then(Value::as_array)
{
a.iter().filter_map(Value::as_u64).collect()
} else if spec.params.contains(&format!("\"{one}\":id")) {
u64_p(p, one).into_iter().collect()
} else {
Vec::new()
};
(!ids.is_empty()).then_some(ids)
}
/// Timeline clips named explicitly in `clips` / `clip` (see [`Session::execute`]): only clips of
/// the active sequence count, so an id of nothing does not stand in for a selection.
pub(crate) fn named_clips(s: &Session, spec: &CommandSpec, p: &Value) -> Option<Vec<ClipId>> {
let seq = s.active_sequence()?;
let clips: Vec<ClipId> = named_ids(spec, p, "clips", "clip")?.into_iter().map(ClipId).filter(|c| seq.find_item(*c).is_some()).collect();
(!clips.is_empty()).then_some(clips)
}
/// Project items named explicitly in `items` / `item`, likewise.
pub(crate) fn named_items(s: &Session, spec: &CommandSpec, p: &Value) -> Option<Vec<ItemId>> {
let items: Vec<ItemId> = named_ids(spec, p, "items", "item")?.into_iter().map(ItemId).filter(|i| s.project.item(*i).is_some()).collect();
(!items.is_empty()).then_some(items)
}
// ---------- param helpers ----------
pub(crate) fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
@@ -187,23 +214,114 @@ pub(crate) fn clips_p(s: &Session, p: &Value) -> Vec<ClipId> {
None => clip_p(p, "clip").map(|c| vec![c]).unwrap_or_else(|| s.state.selection.clone()),
}
}
pub(crate) fn track_p(s: &Session, p: &Value, k: &str) -> Option<TrackId> {
let v = p.get(k)?;
if let Some(id) = v.as_u64() {
return Some(TrackId(id));
}
// "V1", "A2"
let name = v.as_str()?;
let seq = s.active_sequence()?;
let (kind, idx) = name.split_at(1);
let i: usize = idx.parse().ok()?;
let tracks = if kind.eq_ignore_ascii_case("v") { &seq.video_tracks } else { &seq.audio_tracks };
tracks.get(i.checked_sub(1)?).map(|t| t.id)
/// The track parameter `k` names: a track id, or "V1" / "A2" (kind and 1-based number).
/// `Ok(None)` when the parameter is absent. Naming a track the active sequence does not have is
/// an error (bad parameters of `cmd`): callers fall back to a default track only when no track
/// was asked for.
pub(crate) fn track_p(s: &Session, p: &Value, k: &str, cmd: &str) -> Result<Option<TrackId>> {
let v = match p.get(k) {
None | Some(Value::Null) => return Ok(None),
Some(v) => v,
};
let seq = s.active_sequence().ok_or(EngineError::NoSequence)?;
let by_name = |name: &str| {
let mut rest = name.chars();
let tracks = match rest.next()? {
'v' | 'V' => &seq.video_tracks,
'a' | 'A' => &seq.audio_tracks,
_ => return None,
};
let i: usize = rest.as_str().parse().ok()?;
tracks.get(i.checked_sub(1)?).map(|t| t.id)
};
let found = match v.as_u64() {
Some(id) => seq.track(TrackId(id)).map(|t| t.id),
None => v.as_str().and_then(by_name),
};
let named = v.as_str().map(str::to_string).unwrap_or_else(|| v.to_string());
found.map(Some).ok_or_else(|| bad(cmd, format!("no track {named} in this sequence (`{k}`)")))
}
pub(crate) fn item_p(p: &Value, k: &str) -> Option<ItemId> {
u64_p(p, k).map(ItemId)
}
/// `timeline.move`: move the listed clips to (track, time). With Linked Selection on (or
/// `linked: true`) the linked partners of a listed clip that are not listed themselves follow by
/// the same time offset on their own tracks, so picture and sound stay in sync; a partner on a
/// locked track, or one whose position would not change, stays as it is. Nothing moves before the sequence start: when a clip would,
/// every clip of the call lands later by the same amount, so the spacing asked for is kept.
/// `overwritten` lists every clip the move covered without being asked to move it: its length
/// before and after (ticks) and the clips what is left of it now lives on as (none = removed; a
/// clip a moved clip lands inside is split in two).
fn move_clips(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "timeline.move";
let mut listed: Vec<(ClipId, TrackId, Tick)> = Vec::new();
for m in p.get("moves").and_then(Value::as_array).into_iter().flatten() {
let track = track_p(s, m, "track", CMD)?;
if let (Some(clip), Some(track), Some(time)) = (clip_p(m, "clip"), track, m.get("time").and_then(Value::as_i64)) {
listed.push((clip, track, Tick(time)));
}
}
if listed.is_empty() {
return Err(bad(CMD, "need `moves`"));
}
let follow = bool_p(p, "linked").unwrap_or(s.state.linked_selection);
let q = s.active_sequence().ok_or(EngineError::NoSequence)?;
// (clip, destination track, new start, where a partner starts now). `time` is any i64: the
// sums are done in i128, where a few i64 values cannot overflow, and checked on the way back.
let mut plan: Vec<(ClipId, TrackId, i128, Option<i128>)> = Vec::new();
for &(clip, track, time) in &listed {
plan.push((clip, track, i128::from(time.0), None));
let Some((_, it)) = q.find_item(clip) else { continue }; // `edit::move_items` reports it
let Some(link) = it.link.filter(|_| follow) else { continue };
let offset = i128::from(time.0) - i128::from(it.start.0);
for t in q.all_tracks().filter(|t| !t.locked) {
for partner in t.items.iter().filter(|i| i.link == Some(link)) {
if !listed.iter().any(|m| m.0 == partner.id) && !plan.iter().any(|m| m.0 == partner.id) {
plan.push((partner.id, t.id, i128::from(partner.start.0) + offset, Some(i128::from(partner.start.0))));
}
}
}
}
let late = plan.iter().map(|m| -m.2).max().unwrap_or(0).max(0);
let mut moves: Vec<(ClipId, TrackId, Tick)> = Vec::with_capacity(plan.len());
for (clip, track, start, was) in plan {
// a partner that ends up where it is does not move (its listed clip only changed track):
// re-placing it would drop the transitions at its edges
if was == Some(start + late) {
continue;
}
let start = i64::try_from(start + late).ok().map(Tick).filter(|t| *t <= Tick::MAX).ok_or_else(|| bad(CMD, "`time` is out of range"))?;
moves.push((clip, track, start));
}
let ins = bool_p(p, "insert").unwrap_or(false);
// every clip on the sequence now: id -> (track, start, end, project item)
let spots = |s: &Session| -> Vec<(u64, TrackId, Tick, Tick, ItemId)> {
let q = s.active_sequence();
q.into_iter().flat_map(|q| q.all_tracks()).flat_map(|t| t.items.iter().map(move |i| (i.id.0, t.id, i.start, i.end(), i.item))).collect()
};
let before = spots(s);
s.edit_sequence(if ins { "Move (Insert)" } else { "Move" }, |q, ctx, _| Ok(edit::move_items(q, &moves, ins, ctx)?))?;
// An overwrite shortens, splits or removes whatever already sits where a clip lands, and a
// shortened clip may live on under a new id: name each clip the move changed without being
// asked to, with what is left of it, so the caller hears about it instead of finding out later.
let after = spots(s);
let moved = |c: u64| moves.iter().any(|m| m.0.0 == c);
let new = |c: u64| !before.iter().any(|b| b.0 == c);
let mut overwritten = Vec::new();
for &(c, track, start, end, item) in before.iter().filter(|b| !moved(b.0)) {
let kept = after.iter().find(|a| a.0 == c);
if ins || kept.is_some_and(|k| (k.2, k.3) == (start, end)) {
continue; // untouched (an insert only shifts clips, it never covers one)
}
let pieces: Vec<_> =
after.iter().filter(|a| a.0 == c || (new(a.0) && !moved(a.0) && a.1 == track && a.4 == item && a.2 >= start && a.3 <= end)).collect();
let now: i64 = pieces.iter().map(|a| (a.3 - a.2).0).sum();
overwritten.push(json!({"clip": c, "was": (end - start).0, "now": now, "pieces": pieces.iter().map(|a| a.0).collect::<Vec<_>>()}));
}
Ok(json!({"moved": moves.iter().map(|m| m.0.0).collect::<Vec<_>>(), "overwritten": overwritten}))
}
/// Expand a clip selection with linked partners (when linked selection is on).
pub fn with_links(s: &Session, clips: &[ClipId]) -> Vec<ClipId> {
let Some(seq) = s.active_sequence() else { return clips.to_vec() };
@@ -327,6 +445,35 @@ fn new_generator(s: &mut Session, g: Generator, name: &str, label: Label, p: &Va
Ok(json!({"item": id.0}))
}
/// `project.matteColor`: change a Color Matte's color (`item`, or the one selected in the Project
/// panel). Every clip of the matte follows; undo brings the old color back.
fn set_matte_color(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "project.matteColor";
let color = str_p(p, "color").and_then(filmcraft_color::parse_hex).ok_or_else(|| bad(CMD, "`color` must be #rrggbb"))?;
let is_matte = |s: &Session, id: ItemId| {
s.project.item(id).is_some_and(|it| matches!(&it.kind, ItemKind::Media(m) if matches!(m.media, MediaRef::Generator(Generator::ColorMatte { .. }))))
};
let item = match item_p(p, "item") {
Some(id) => id,
None => match s.state.project_selection.as_slice() {
[id] => *id,
_ => return Err(bad(CMD, "select one Color Matte (or pass `item`)")),
},
};
if !is_matte(s, item) {
return Err(bad(CMD, format!("item {} is not a Color Matte", item.0)));
}
s.edit("Color Matte Color", |pr, _| {
if let Some(ItemKind::Media(m)) = pr.item_mut(item).map(|it| &mut it.kind)
&& let MediaRef::Generator(Generator::ColorMatte { color: c }) = &mut m.media
{
*c = color;
}
Ok(())
})?;
Ok(json!({"item": item.0, "color": filmcraft_color::to_hex(color)}))
}
/// Place a project item on the timeline (drag from Project, or Insert/Overwrite from source).
pub(crate) fn place_item(
s: &mut Session,
@@ -340,6 +487,10 @@ pub(crate) fn place_item(
audio_split: Option<(TimeRange, Tick)>,
) -> Result<Vec<ClipId>> {
let pi = s.project.item(item).ok_or_else(|| bad(label, "no such item"))?.clone();
// the nest toggle off: a sequence edits in as its clips (a multi-camera source stays one clip)
if s.state.sequences_as_clips && pi.as_sequence().is_some_and(|q| q.multicam.is_none()) {
return crate::sequence_tools::place_sequence_clips(s, item, range, at, vdest, adest, insert, label);
}
let has_v = pi.has_video() && vdest.is_some();
let has_a = pi.has_audio() && adest.is_some();
if !has_v && !has_a {
@@ -601,6 +752,7 @@ fn build() -> Vec<CommandSpec> {
let c = str_p(p, "color").and_then(filmcraft_color::parse_hex).unwrap_or([0.1, 0.1, 0.1, 1.0]);
new_generator(s, Generator::ColorMatte { color: c }, "Color Matte", Label::Lavender, p)
}),
cmd!("project.matteColor", "Color Matte Color…", [], None, r##"{"item":id?,"color":"#rrggbb"}"##, always, set_matte_color),
cmd!("file.newCountingLeader", "Universal Counting Leader…", ["File", "New"], None, "{}", always, |s, p| new_generator(
s,
Generator::CountingLeader,
@@ -706,16 +858,17 @@ fn build() -> Vec<CommandSpec> {
let item_ids: Vec<ItemId> = ids.iter().filter(|i| !image_sequences.iter().any(|q| q["item"].as_u64() == Some(**i))).map(|i| ItemId(*i)).collect();
// Settings ▸ Media Analysis & Transcription ▸ Automatically transcribe clips
let ma = &s.prefs.media_analysis;
if ma.auto_transcribe
&& ma.auto_transcribe_scope == "allImported"
&& !ids.is_empty()
&& (s.transcriber.is_some() || crate::transcript::speech_available())
{
if ma.auto_transcribe && ma.auto_transcribe_scope == "allImported" && !ids.is_empty() {
let audio: Vec<u64> = ids.iter().copied().filter(|i| s.project.item(ItemId(*i)).is_some_and(|it| it.has_audio())).collect();
if !audio.is_empty()
&& let Err(e) = s.execute("transcript.generate", json!({"items": audio}))
{
errors.push(format!("transcription: {e}"));
if !audio.is_empty() {
// without speech-to-text the setting can't act: say so instead of importing
// silently untranscribed (#89)
let r = crate::transcript::can_transcribe(s)
.map_err(EngineError::Other)
.and_then(|()| s.execute("transcript.generate", json!({"items": audio})));
if let Err(e) = r {
errors.push(format!("transcription: {e}"));
}
}
}
let ingest = match crate::proxies::ingest(s, &item_ids) {
@@ -735,11 +888,25 @@ fn build() -> Vec<CommandSpec> {
if !image_sequences.is_empty() {
out["imageSequences"] = json!(image_sequences);
}
// Newly imported files may resolve paths the project already listed as offline
// (issue #110): rebuild s.offline.missing so the "Media missing" badge clears, and drop
// the cached slate of every item that came back so the monitors show the file again.
let was_missing = s.offline.missing.clone();
crate::relink::refresh(s);
for item in was_missing.iter().filter(|i| !s.offline.missing.contains(i)) {
s.media.remove(*item);
}
Ok(out)
}),
cmd!("file.exportInterchange", "Export Interchange", [], None, r#"{"format":"edl|xml|fcpxml|otio","path":str,"sequence":id?}"#, has_seq, |s, p| {
crate::interchange::export(s, p)
}),
cmd!(
"file.exportInterchange",
"Export Interchange",
[],
None,
r#"{"format":"edl|xml|fcpxml|otio|aaf|omf"=xml,"path":str,"sequence":id?}"#,
has_seq,
crate::interchange::export
),
cmd!("file.exportEdl", "EDL…", ["File", "Export"], None, r#"{"path":str}"#, has_seq, |s, p| {
let mut q = p.clone();
q["format"] = json!("edl");
@@ -889,7 +1056,7 @@ fn build() -> Vec<CommandSpec> {
"Media…",
["File", "Export"],
None,
r#"{"path":str,"preset":str?,"settings":ExportSettings?,"format":"h264|prores|dnxhr|mjpeg|mxf-op1a|mxf-opatom|png|tiff|bmp|gif|wav|aiff"?,"width":u32?,"height":u32?,"fps":f64?,"bitrateKbps":u32?,"bitrateMode":"cbr|vbr1Pass|vbr2Pass"?,"scale":f32=1,"audio":bool=true,"quality":0..100,"burnCaptions":bool=false,"captionSidecar":"srt|vtt"?,"loudnessLufs":f64?,"proresProfile":"proxy|lt|standard|hq"?,"dnxProfile":"lb|sq|hq|hqx"?,"mxfVideoCodec":"dnxhr|proRes|h264"?,"sequence":id?,"range":"entire|inOut|workArea|custom"?,"startSeconds":f64?,"endSeconds":f64?,"wait":bool=false}"#,
r#"{"path":str,"preset":str?,"settings":ExportSettings?,"format":"h264|hevc|prores|dnxhr|apv|mjpeg|mxf-op1a|mxf-opatom|png|tiff|bmp|gif|wav|aiff"?,"width":u32?,"height":u32?,"fps":f64?,"bitrateKbps":u32?,"bitrateMode":"cbr|vbr1Pass|vbr2Pass"?,"hardwareEncoding":"off|auto"?,"scale":f32=1,"audio":bool=true,"quality":0..100,"burnCaptions":bool=false,"captionSidecar":"srt|vtt"?,"loudnessLufs":f64?,"proresProfile":"proxy|lt|standard|hq"?,"dnxProfile":"lb|sq|hq|hqx"?,"apvProfile":"422-10|422-12|444-10|444-12"?,"mxfVideoCodec":"dnxhr|proRes|h264"?,"sequence":id?,"range":"entire|inOut|workArea|custom"?,"startSeconds":f64?,"endSeconds":f64?,"wait":bool=false}"#,
has_seq,
crate::export_tools::export_media
),
@@ -940,10 +1107,7 @@ fn build() -> Vec<CommandSpec> {
}
let sel = with_links(s, &clips_p(s, p));
s.edit_sequence("Ripple Delete", |q, _, st| {
let mut spans: Vec<TimeRange> = sel.iter().filter_map(|c| q.find_item(*c).map(|(_, i)| i.range())).collect();
spans.sort_by_key(|r| (r.start, r.duration));
spans.dedup();
edit::ripple_delete_items(q, &sel)?;
let spans = edit::ripple_delete_items(q, &sel)?;
if st.ripple_sequence_markers {
for r in spans.iter().rev() {
crate::sequence_tools::ripple_markers(&mut q.markers, r.end(), -r.duration);
@@ -1034,8 +1198,26 @@ fn build() -> Vec<CommandSpec> {
};
let sel = with_links(s, &clips_p(s, p));
s.edit_sequence("Speed/Duration", |q, ctx, _| {
// a clip and its linked partners on other tracks change as one edit, so a ripple
// moves the later clips once
let place = |q: &filmcraft_project::Sequence, c: ClipId| q.find_item(c).map(|(t, i)| (t, i.link));
let mut groups: Vec<Vec<ClipId>> = Vec::new();
for c in &sel {
// a clip that is not there goes on alone, so the edit fails with "no such item"
let Some((track, link)) = place(q, *c) else {
groups.push(vec![*c]);
continue;
};
let joins = |g: &Vec<ClipId>| link.is_some() && g.iter().all(|o| place(q, *o).is_some_and(|(t, l)| l == link && t != track));
match groups.iter_mut().find(|g| joins(g)) {
Some(g) => g.push(*c),
None => groups.push(vec![*c]),
}
}
for group in &groups {
edit::set_speed_group(q, group, speed, reverse, ripple, ctx)?;
}
for c in &sel {
edit::set_speed(q, *c, speed, reverse, ripple, ctx)?;
if let (Some(m), Some((_, it))) = (interp, q.find_item_mut(*c)) {
it.time_interpolation = m;
}
@@ -1114,7 +1296,7 @@ fn build() -> Vec<CommandSpec> {
"Audio Gain…",
["Clip", "Audio Options"],
Some("G"),
r#"{"mode":"set|adjust|normalizeMax|normalizeAll"?,"db":f64,"relative":bool?}"#,
r#"{"clips":[id]?,"mode":"set|adjust|normalizeMax|normalizeAll"?,"db":f64,"relative":bool?}"#,
has_selection,
|s, p| crate::mixer::audio_gain(s, p)
),
@@ -1123,6 +1305,26 @@ fn build() -> Vec<CommandSpec> {
crate::clip_ops::add_frame_hold(s, p)
}),
cmd!("clip.nest", "Nest…", ["Clip"], None, r#"{"name":str}"#, has_selection, |s, p| nest(s, p)),
// Reveal in Project (clip context menu) and Reveal Sequence in Project (Timeline tab menu):
// select the item in the Project panel and show it there
cmd!("clip.revealInProject", "Reveal in Project", [], None, r#"{"clip":id?}"#, has_seq, |s, p| {
let seq = s.active_sequence().ok_or(EngineError::NoSequence)?;
let t = s.playhead();
let tg = s.targeting().targeted;
// the named or first selected clip, else the topmost clip under the playhead on a targeted track
let item = clips_p(s, p)
.iter()
.find_map(|c| seq.find_item(*c).map(|(_, i)| i.item))
.or_else(|| {
seq.video_tracks.iter().rev().chain(seq.audio_tracks.iter()).filter(|tr| tg.contains(&tr.id)).find_map(|tr| tr.item_at(t).map(|i| i.item))
})
.ok_or_else(|| EngineError::Other("select a clip to reveal".into()))?;
reveal_in_project(s, item)
}),
cmd!("sequence.revealInProject", "Reveal Sequence in Project", [], None, r#"{"item":id?}"#, has_seq, |s, p| {
let item = item_p(p, "item").or(s.state.active_sequence).ok_or(EngineError::NoSequence)?;
reveal_in_project(s, item)
}),
// ================= Sequence =================
cmd!("sequence.open", "Open in Timeline", [], None, r#"{"item":id}"#, always, |s, p| {
let id = item_p(p, "item").ok_or_else(|| bad("sequence.open", "need `item`"))?;
@@ -1143,10 +1345,43 @@ fn build() -> Vec<CommandSpec> {
}
Ok(Value::Null)
}),
cmd!("sequence.closeOthers", "Close Other Timeline Panels", [], None, r#"{"item":id?}"#, has_seq, |s, p| {
let id = item_p(p, "item").or(s.state.active_sequence).ok_or(EngineError::NoSequence)?;
if !s.state.open_sequences.contains(&id) {
return Err(bad("sequence.closeOthers", "that sequence is not open"));
}
let closed = s.state.open_sequences.len().saturating_sub(1);
s.state.open_sequences = vec![id];
if s.state.active_sequence != Some(id) {
s.state.active_sequence = Some(id);
s.state.selection.clear();
s.events.push(crate::Event::OpenSequence(id));
}
Ok(json!({"closed": closed}))
}),
cmd!("sequence.moveTab", "Move Sequence Tab", [], None, r#"{"item":id?,"index":int}"#, has_seq, |s, p| {
let id = item_p(p, "item").or(s.state.active_sequence).ok_or(EngineError::NoSequence)?;
let to = u64_p(p, "index").ok_or_else(|| bad("sequence.moveTab", "need `index`"))?;
let from = s.state.open_sequences.iter().position(|x| *x == id).ok_or_else(|| bad("sequence.moveTab", "that sequence is not open"))?;
// past the end is the end
let to = usize::try_from(to).unwrap_or(usize::MAX).min(s.state.open_sequences.len().saturating_sub(1));
let tab = s.state.open_sequences.remove(from);
s.state.open_sequences.insert(to, tab);
Ok(json!({"index": to}))
}),
cmd!("sequence.addEdit", "Add Edit", ["Sequence"], Some("Cmd+K"), r#"{"time":ticks?}"#, has_seq, |s, p| {
let t = time_p(s, p, "").unwrap_or(s.playhead());
let tg = s.targeting().targeted;
let n = s.edit_sequence("Add Edit", |q, ctx, _| Ok(edit::razor(q, &tg, t, ctx)))?;
// Like Premiere: selected clips under the playhead are cut, and only they (#164);
// with none, the targeted tracks are.
let sel = s.state.selection.clone();
let selected_here =
s.active_sequence().is_some_and(|q| sel.iter().any(|c| q.find_item(*c).is_some_and(|(_, it)| it.start < t && t < it.start + it.duration)));
let n = if selected_here {
s.edit_sequence("Add Edit", |q, ctx, _| Ok(edit::razor_items(q, &sel, t, ctx)))?
} else {
let tg = s.targeting().targeted;
s.edit_sequence("Add Edit", |q, ctx, _| Ok(edit::razor(q, &tg, t, ctx)))?
};
Ok(json!({"cuts": n.len()}))
}),
cmd!("sequence.addEditAllTracks", "Add Edit to All Tracks", ["Sequence"], Some("Cmd+Shift+K"), r#"{"time":ticks?}"#, has_seq, |s, p| {
@@ -1208,7 +1443,7 @@ fn build() -> Vec<CommandSpec> {
set_transition
),
cmd!("sequence.closeGap", "Close Gap", ["Sequence"], None, r#"{"track":"V1"|id,"time":ticks}"#, has_seq, |s, p| {
let tr = track_p(s, p, "track").ok_or_else(|| bad("sequence.closeGap", "need `track`"))?;
let tr = track_p(s, p, "track", "sequence.closeGap")?.ok_or_else(|| bad("sequence.closeGap", "need `track`"))?;
let t = time_p(s, p, "").unwrap_or(s.playhead());
s.edit_sequence("Ripple Delete", |q, _, st| {
let before: Vec<(ClipId, Tick)> = q.track(tr).map(|x| x.items.iter().map(|i| (i.id, i.start)).collect()).unwrap_or_default();
@@ -1235,24 +1470,22 @@ fn build() -> Vec<CommandSpec> {
s.state.linked_selection = bool_p(p, "on").unwrap_or(!s.state.linked_selection);
Ok(json!({"linkedSelection": s.state.linked_selection}))
}),
cmd!("sequence.addTracks", "Add Tracks…", ["Sequence"], None, r#"{"video":n=1,"audio":n=0}"#, has_seq, |s, p| {
let nv = u64_p(p, "video").unwrap_or(1) as usize;
let na = u64_p(p, "audio").unwrap_or(0) as usize;
s.edit_sequence("Add Tracks", |q, ctx, _| {
for _ in 0..nv {
let n = q.video_tracks.len() + 1;
q.video_tracks.push(filmcraft_project::Track::new(TrackId(ctx.alloc()), TrackKind::Video, format!("Video {n}")));
}
for _ in 0..na {
let n = q.audio_tracks.len() + 1;
q.audio_tracks.push(filmcraft_project::Track::new(TrackId(ctx.alloc()), TrackKind::Audio, format!("Audio {n}")));
}
Ok(())
})?;
Ok(Value::Null)
cmd!("sequence.nestSequences", "Insert and overwrite sequences as nests or individual clips", [], None, r#"{"on":bool?}"#, always, |s, p| {
let nest = bool_p(p, "on").unwrap_or(s.state.sequences_as_clips);
s.state.sequences_as_clips = !nest;
Ok(json!({"nest": nest}))
}),
cmd!(
"sequence.addTracks",
"Add Tracks…",
["Sequence"],
None,
r#"{"video":n=1,"audio":n=0,"submix":n=0,"videoAfter":"first"|"V2"|n?,"audioAfter":"first"|"A2"|n?,"submixAfter":"first"|"S1"|n?,"audioType":"standard|5.1|adaptive|mono"?,"submixType":"stereo|5.1|adaptive|mono"?}"#,
has_seq,
crate::sequence_tools::add_tracks
),
cmd!("sequence.deleteTrack", "Delete Track", [], None, r#"{"track":"V3"|id}"#, has_seq, |s, p| {
let tr = track_p(s, p, "track").ok_or_else(|| bad("sequence.deleteTrack", "need `track`"))?;
let tr = track_p(s, p, "track", "sequence.deleteTrack")?.ok_or_else(|| bad("sequence.deleteTrack", "need `track`"))?;
s.edit_sequence("Delete Track", |q, _, _| {
q.video_tracks.retain(|t| t.id != tr);
q.audio_tracks.retain(|t| t.id != tr);
@@ -1559,15 +1792,30 @@ fn build() -> Vec<CommandSpec> {
"Place Clip",
[],
None,
r#"{"item":id,"track":"V1"|id?,"audioTrack":"A1"|id?,"time":ticks|"frame":i64|"seconds":f64,"insert":bool,"sourceIn":ticks?,"duration":ticks?}"#,
r#"{"item":id,"track":"V1"|id|"A1" (sound only)?,"audioTrack":"A1"|id?,"time":ticks|"frame":i64|"seconds":f64,"insert":bool,"sourceIn":ticks?,"duration":ticks?}"#,
has_seq,
|s, p| {
let item = item_p(p, "item").ok_or_else(|| bad("timeline.place", "need `item`"))?;
let at = time_p(s, p, "").unwrap_or(s.playhead());
let tg = s.targeting();
let v = track_p(s, p, "track").or(tg.video_dest);
let a = track_p(s, p, "audioTrack").or(tg.audio_dest);
let pi = s.project.item(item).ok_or_else(|| bad("timeline.place", "no such item"))?;
let is_audio = |t: TrackId| s.active_sequence().is_some_and(|q| q.audio_tracks.iter().any(|x| x.id == t));
// `track` is where the picture goes and `audioTrack` where the sound goes. A caller that
// names an audio track as `track` asks for the sound alone, on that track.
let (v, a) = match (track_p(s, p, "track", "timeline.place")?, track_p(s, p, "audioTrack", "timeline.place")?) {
(Some(t), Some(_)) if is_audio(t) => {
return Err(bad("timeline.place", "`track` names an audio track and `audioTrack` is given as well: name the sound's track once"));
}
(_, Some(t)) if !is_audio(t) => return Err(bad("timeline.place", "`audioTrack` names a video track")),
(Some(t), None) if is_audio(t) && !pi.has_audio() => {
return Err(bad("timeline.place", "`track` names an audio track and this item has no sound"));
}
(Some(t), None) if is_audio(t) => (None, Some(t)),
(Some(_), None) if !pi.has_video() => {
return Err(bad("timeline.place", "`track` names a video track and this item has no picture: name an audio track"));
}
(v, a) => (v.or(tg.video_dest), a.or(tg.audio_dest)),
};
let full = match &pi.kind {
// Settings ▸ Timeline ▸ Still Image Default Duration
ItemKind::Media(m)
@@ -1616,19 +1864,15 @@ fn build() -> Vec<CommandSpec> {
}
Ok(json!({"selection": s.state.selection.iter().map(|c| c.0).collect::<Vec<_>>()}))
}),
cmd!("timeline.move", "Move Clips", [], None, r#"{"moves":[{"clip":id,"track":id|"V2","time":ticks}],"insert":bool}"#, has_seq, |s, p| {
let moves: Vec<(ClipId, TrackId, Tick)> = p
.get("moves")
.and_then(Value::as_array)
.map(|a| a.iter().filter_map(|m| Some((clip_p(m, "clip")?, track_p(s, m, "track")?, Tick(m.get("time")?.as_i64()?)))).collect())
.unwrap_or_default();
if moves.is_empty() {
return Err(bad("timeline.move", "need `moves`"));
}
let ins = bool_p(p, "insert").unwrap_or(false);
s.edit_sequence(if ins { "Move (Insert)" } else { "Move" }, |q, ctx, _| Ok(edit::move_items(q, &moves, ins, ctx)?))?;
Ok(Value::Null)
}),
cmd!(
"timeline.move",
"Move Clips",
[],
None,
r#"{"moves":[{"clip":id,"track":id|"V2","time":ticks}],"insert":bool,"linked":bool?}"#,
has_seq,
move_clips
),
cmd!(
"timeline.trim",
"Trim Edit",
@@ -1830,7 +2074,7 @@ fn build() -> Vec<CommandSpec> {
}),
cmd!("timeline.razor", "Razor", [], None, r#"{"time":ticks,"track":"V1"|id?,"clip":id?}"#, has_seq, |s, p| {
let t = time_p(s, p, "").unwrap_or(s.playhead());
let tr = track_p(s, p, "track");
let tr = track_p(s, p, "track", "timeline.razor")?;
let clip = clip_p(p, "clip");
let n = if let Some(c) = clip {
let clips = with_links(s, &[c]);
@@ -1849,7 +2093,7 @@ fn build() -> Vec<CommandSpec> {
r#"{"track":"V1"|id,"locked":bool?,"syncLock":bool?,"enabled":bool?,"muted":bool?,"solo":bool?,"name":str?,"volumeDb":f64?,"pan":f64?}"#,
has_seq,
|s, p| {
let tr = track_p(s, p, "track").ok_or_else(|| bad("timeline.setTrack", "need `track`"))?;
let tr = track_p(s, p, "track", "timeline.setTrack")?.ok_or_else(|| bad("timeline.setTrack", "need `track`"))?;
let p = p.clone();
s.edit_sequence("Track Settings", |q, _, _| {
let t = q.track_mut(tr).ok_or(filmcraft_edit::EditError::NoTrack(tr))?;
@@ -1883,7 +2127,7 @@ fn build() -> Vec<CommandSpec> {
}
),
cmd!("timeline.setTargeting", "Track Targeting", [], None, r#"{"track":"V1"|id,"targeted":bool?,"sourcePatch":bool?}"#, has_seq, |s, p| {
let tr = track_p(s, p, "track").ok_or_else(|| bad("timeline.setTargeting", "need `track`"))?;
let tr = track_p(s, p, "track", "timeline.setTargeting")?.ok_or_else(|| bad("timeline.setTargeting", "need `track`"))?;
let seq_id = s.state.active_sequence.ok_or(EngineError::NoSequence)?;
let mut tg = s.targeting();
let is_video = s.active_sequence().is_some_and(|q| q.video_tracks.iter().any(|t| t.id == tr));
@@ -2095,12 +2339,33 @@ fn build() -> Vec<CommandSpec> {
Ok(Value::Null)
}),
cmd!("project.delete", "Clear", [], Some("Delete"), r#"{"items":[id]?}"#, has_project_selection, |s, p| {
let items: Vec<ItemId> = p
let asked: Vec<ItemId> = p
.get("items")
.and_then(Value::as_array)
.map(|a| a.iter().filter_map(|v| v.as_u64().map(ItemId)).collect())
.unwrap_or_else(|| s.state.project_selection.clone());
// A bin named here goes with everything in it, as in the Project panel of any editor.
let root = s.project.root.id;
let named: Vec<filmcraft_project::BinId> =
asked.iter().map(|i| filmcraft_project::BinId(i.0)).filter(|b| *b != root && s.project.root.find_bin(*b).is_some()).collect();
// a bin inside another named bin goes with that one
let bins: Vec<filmcraft_project::BinId> = named
.iter()
.copied()
.filter(|b| !named.iter().any(|o| o != b && s.project.root.find_bin(*o).is_some_and(|o| o.find_bin(*b).is_some())))
.collect();
let mut items: Vec<ItemId> = asked.iter().copied().filter(|i| !named.contains(&filmcraft_project::BinId(i.0))).collect();
for b in &bins {
if let Some(bin) = s.project.root.find_bin(*b) {
bin.all_items(&mut items);
}
}
items.sort_by_key(|i| i.0);
items.dedup();
s.edit("Clear", |pr, st| {
for b in &bins {
pr.root.remove_bin(*b);
}
for i in &items {
pr.items.remove(i);
pr.root.remove_item(*i);
@@ -2122,7 +2387,7 @@ fn build() -> Vec<CommandSpec> {
s.media.remove(*i);
}
s.fix_state();
Ok(Value::Null)
Ok(json!({"items": items.len(), "bins": bins.len()}))
}),
cmd!("project.moveToBin", "Move to Bin", [], None, r#"{"items":[id]?,"bin":binId|null}"#, always, |s, p| {
let items: Vec<ItemId> = match p.get("items").and_then(Value::as_array) {
@@ -2157,6 +2422,19 @@ fn build() -> Vec<CommandSpec> {
if let Some(v) = p.get("out") {
m.mark_out = v.as_i64().map(Tick);
}
} else if let Some(q) = it.as_sequence_mut() {
// a sequence loaded in the Source Monitor is marked like a clip: these are the
// sequence's own In and Out
if let Some(v) = p.get("in") {
q.mark_in = v.as_i64().map(Tick);
q.split.video_in = None;
q.split.audio_in = None;
}
if let Some(v) = p.get("out") {
q.mark_out = v.as_i64().map(Tick);
q.split.video_out = None;
q.split.audio_out = None;
}
}
Ok(())
})?;
@@ -2430,17 +2708,40 @@ fn paste(s: &mut Session, insert: bool) -> Result<Value> {
Ok(Value::Null)
}
/// Select `item` in the Project panel and ask the UI to show it there.
fn reveal_in_project(s: &mut Session, item: ItemId) -> Result<Value> {
s.project.item(item).ok_or_else(|| EngineError::Other("that clip's source is not in the project".into()))?;
s.state.project_selection = vec![item];
s.events.push(crate::Event::RevealInProject(item));
Ok(json!({"item": item.0}))
}
/// The name Nest… offers: the first unused "Nested Sequence NN".
pub fn next_nested_name(s: &Session) -> String {
(1..=s.project.items.len().saturating_add(1))
.map(|k| format!("Nested Sequence {k:02}"))
.find(|n| !s.project.items.values().any(|i| &i.name == n))
.unwrap_or_else(|| "Nested Sequence".to_string())
}
fn nest(s: &mut Session, p: &Value) -> Result<Value> {
let seq_id = s.state.active_sequence.ok_or(EngineError::NoSequence)?;
let sel = with_links(s, &s.state.selection.clone());
let q = s.active_sequence().ok_or(EngineError::NoSequence)?.clone();
let name = str_p(p, "name").map(str::to_string).unwrap_or_else(|| "Nested Sequence 01".to_string());
let name = str_p(p, "name").filter(|n| !n.trim().is_empty()).map(str::to_string).unwrap_or_else(|| next_nested_name(s));
let mut items: Vec<(TrackKind, usize, filmcraft_project::TrackItem)> = Vec::new();
// transitions go into the nest with their clips: those whose clips are all nested
let mut transitions: Vec<(TrackKind, usize, filmcraft_project::Transition)> = Vec::new();
for (k, ts) in [(TrackKind::Video, &q.video_tracks), (TrackKind::Audio, &q.audio_tracks)] {
for (ti, t) in ts.iter().enumerate() {
// clips on a locked track stay where they are (they cannot be removed from it)
for (ti, t) in ts.iter().enumerate().filter(|(_, t)| !t.locked) {
for i in t.items.iter().filter(|i| sel.contains(&i.id)) {
items.push((k, ti, i.clone()));
}
let nested = |c: Option<ClipId>| c.is_none_or(|c| sel.contains(&c));
for trn in t.transitions.iter().filter(|x| (x.from.is_some() || x.to.is_some()) && nested(x.from) && nested(x.to)) {
transitions.push((k, ti, trn.clone()));
}
}
}
if items.is_empty() {
@@ -2448,55 +2749,133 @@ fn nest(s: &mut Session, p: &Value) -> Result<Value> {
}
let start = items.iter().map(|i| i.2.start).min().unwrap_or_default();
let end = items.iter().map(|i| i.2.end()).max().unwrap_or_default();
let lowest_v = items.iter().filter(|i| i.0 == TrackKind::Video).map(|i| i.1).min();
let lowest_a = items.iter().filter(|i| i.0 == TrackKind::Audio).map(|i| i.1).min();
s.edit("Nest", |pr, st| {
let nid = pr.new_sequence(&name, q.settings.clone(), q.video_tracks.len(), q.audio_tracks.len(), None);
let span = TimeRange::new(start, end - start);
let tracks_of = |kind: TrackKind| -> Vec<usize> {
let mut v: Vec<usize> = items.iter().filter(|i| i.0 == kind).map(|i| i.1).collect();
v.sort_unstable();
v.dedup();
v
};
let (video_tracks, audio_tracks) = (tracks_of(TrackKind::Video), tracks_of(TrackKind::Audio));
// Premiere (26.5.2): the nest is a linked picture + sound pair only when the selected sound is
// on one track and that track is free for the nest's whole length. With sound on several
// tracks, or another clip in the way on its track, the nest is picture only: the selected sound
// stays where it is in this sequence, and a copy of it goes into the nest.
let sound_blocked = |ai: usize| q.audio_tracks.get(ai).is_none_or(|t| t.items.iter().any(|i| !sel.contains(&i.id) && i.range().overlaps(&span)));
let video_only = !video_tracks.is_empty() && (audio_tracks.len() > 1 || audio_tracks.first().is_some_and(|ai| sound_blocked(*ai)));
let (lowest_v, lowest_a) = (video_tracks.first().copied(), audio_tracks.first().copied().filter(|_| !video_only));
// In the nest, picture tracks keep their positions (V1 up to the highest one used). Sound
// tracks do not: A1 is always there, and the other tracks used follow it in order
// (A1 + A3 become A1, A2; A3 alone becomes an empty A1 and A2).
let nv = video_tracks.last().map_or(1, |i| i + 1);
let audio_at: std::collections::HashMap<usize, usize> =
audio_tracks.iter().filter(|i| **i != 0).enumerate().map(|(n, i)| (*i, n + 1)).chain(std::iter::once((0, 0))).collect();
let na = audio_at.values().max().map_or(1, |i| i + 1);
let nested_track = |k: TrackKind, ti: usize| if k == TrackKind::Audio { audio_at.get(&ti).copied().unwrap_or(ti) } else { ti };
// what leaves this sequence: everything nested, less the sound that stays behind
let removed: Vec<ClipId> = items.iter().filter(|i| !(video_only && i.0 == TrackKind::Audio)).map(|i| i.2.id).collect();
let stays = |k: TrackKind| video_only && k == TrackKind::Audio;
let r = s.edit("Nest", |pr, st| {
let nid = pr.new_sequence(&name, q.settings.clone(), nv, na, None);
// copies of clips and transitions that also stay behind need ids of their own
let fresh_clips: std::collections::HashMap<ClipId, ClipId> = items.iter().filter(|i| stays(i.0)).map(|i| (i.2.id, ClipId(pr.alloc_id()))).collect();
let fresh_transitions: Vec<Option<u64>> = transitions.iter().map(|t| stays(t.0).then(|| pr.alloc_id())).collect();
let copy = |c: ClipId| fresh_clips.get(&c).copied().unwrap_or(c);
{
let nq = pr.sequence_mut(nid).ok_or(EngineError::NoSequence)?;
// tracks take the name and channel layout of the track their clips came from
for (tr, src) in nq.video_tracks.iter_mut().zip(&q.video_tracks) {
tr.name = src.name.clone();
}
for (from, to) in &audio_at {
if let (Some(tr), Some(src)) = (nq.audio_tracks.get_mut(*to), q.audio_tracks.get(*from)) {
tr.channels = src.channels;
if from == to {
tr.name = src.name.clone();
}
}
}
for (k, ti, it) in &items {
let mut it = it.clone();
it.id = copy(it.id);
it.start -= start;
nq.tracks_mut(*k)[*ti].items.push(it);
nq.tracks_mut(*k).get_mut(nested_track(*k, *ti)).ok_or(EngineError::NoSequence)?.items.push(it);
}
for ((k, ti, trn), fresh) in transitions.iter().zip(&fresh_transitions) {
let mut trn = trn.clone();
if let Some(id) = fresh {
trn.id = filmcraft_project::TransitionId(*id);
}
(trn.from, trn.to) = (trn.from.map(copy), trn.to.map(copy));
trn.start -= start;
nq.tracks_mut(*k).get_mut(nested_track(*k, *ti)).ok_or(EngineError::NoSequence)?.transitions.push(trn);
}
for t in nq.all_tracks_mut() {
t.sort();
edit::remove_orphan_transitions(t);
}
nq.check().map_err(EngineError::Other)?;
}
let rate = q.settings.frame_rate;
let mut v = pr
.make_track_item(nid, TrackKind::Video, start, TimeRange::new(Tick::ZERO, end - start), rate)
.ok_or_else(|| EngineError::Other("cannot place the nested sequence".into()))?;
// the nest shows its sequence from the beginning, for the length of what was nested
let whole = TimeRange::new(Tick::ZERO, span.duration);
let mut v =
pr.make_track_item(nid, TrackKind::Video, start, whole, rate).ok_or_else(|| EngineError::Other("cannot place the nested sequence".into()))?;
for e in &mut v.effects {
resolve_auto_points(e, (q.settings.width, q.settings.height), (q.settings.width, q.settings.height));
}
let a = pr
.make_track_item(nid, TrackKind::Audio, start, TimeRange::new(Tick::ZERO, end - start), rate)
.ok_or_else(|| EngineError::Other("cannot place the nested sequence".into()))?;
let link = pr.alloc_id();
let a = pr.make_track_item(nid, TrackKind::Audio, start, whole, rate).ok_or_else(|| EngineError::Other("cannot place the nested sequence".into()))?;
let (link, new_video, new_audio) = (pr.alloc_id(), pr.alloc_id(), pr.alloc_id());
let seq = pr.sequence_mut(seq_id).ok_or(EngineError::NoSequence)?;
edit::delete_items(seq, &sel);
edit::delete_items(seq, &removed);
// sound left behind has lost its picture: it is no longer linked
if video_only {
let links: Vec<u64> = items.iter().filter(|i| i.0 == TrackKind::Video).filter_map(|i| i.2.link).collect();
for it in seq.audio_tracks.iter_mut().flat_map(|t| t.items.iter_mut()) {
if it.link.is_some_and(|l| links.contains(&l)) {
it.link = None;
}
}
}
// Where the nest goes, as Premiere Pro 26.5.2 places it (about 35 nests observed). With L
// the lowest video track of the selection and `a` the number of the highest audio track
// holding selected sound, the picture takes the lowest track T from L up such that
// 1. T is free of other clips for the nest's whole length, and
// 2. so is every video track numbered from T up to a - 1 that the selection had clips on.
// If no track will do, a new one is added on top. So the nest never lands on another clip,
// and it can be pushed above an unselected clip that shares a track with the selection
// when the sound sits on a higher-numbered track. The sound of a linked nest is on the one
// track its clips came from, which is free (a selection of sound alone moves up to the
// first free track).
let highest_sound = audio_tracks.last().map_or(0, |i| i + 1);
let mut ids = Vec::new();
if let Some(vi) = lowest_v {
let mut v = v;
v.link = lowest_a.map(|_| link);
ids.push(v.id);
let t = &mut seq.video_tracks[vi];
t.items.push(v);
for (kind, lowest, mut clip, new_track) in [(TrackKind::Video, lowest_v, v, new_video), (TrackKind::Audio, lowest_a, a, new_audio)] {
let Some(lowest) = lowest else { continue };
let tracks = seq.tracks_mut(kind);
let clear = |i: usize| tracks.get(i).is_some_and(|t| !t.locked && edit::track_range_empty(t, span));
let selection_clear = |t: usize| kind != TrackKind::Video || video_tracks.iter().filter(|i| **i >= t && **i + 1 < highest_sound).all(|i| clear(*i));
let free = (lowest..tracks.len()).find(|t| clear(*t) && selection_clear(*t));
let at = match free {
Some(i) => i,
None => {
let (word, n) = (if kind == TrackKind::Video { "Video" } else { "Audio" }, tracks.len() + 1);
tracks.push(filmcraft_project::Track::new(TrackId(new_track), kind, format!("{word} {n}")));
tracks.len() - 1
}
};
clip.link = (lowest_v.is_some() && lowest_a.is_some()).then_some(link);
ids.push(clip.id);
let t = tracks.get_mut(at).ok_or(EngineError::NoSequence)?;
t.items.push(clip);
t.sort();
}
if let Some(ai) = lowest_a {
let mut a = a;
a.link = lowest_v.map(|_| link);
ids.push(a.id);
let t = &mut seq.audio_tracks[ai];
t.items.push(a);
t.sort();
}
st.selection = ids;
Ok(nid)
})
.map(|n| json!({"sequence": n.0}))
seq.check().map_err(EngineError::Other)?;
// like Premiere: nothing stays selected in the timeline; the new sequence is selected in the Project panel
st.selection.clear();
st.project_selection = vec![nid];
Ok((nid, ids))
});
r.map(|(n, ids)| json!({"sequence": n.0, "clips": ids.iter().map(|c| c.0).collect::<Vec<_>>()}))
}
/// `effects.list`: every effect definition with its Effects-panel folder (optionally filtered by
@@ -2714,7 +3093,8 @@ pub fn inspect_sequence(s: &Session, id: ItemId, q: &filmcraft_project::Sequence
"id": t.id.0, "name": t.name, "locked": t.locked, "syncLock": t.sync_lock, "enabled": t.enabled, "muted": t.muted, "solo": t.solo,
"items": t.items.iter().map(|i| json!({
"clip": i.id.0, "item": i.item.0, "name": i.name, "start": i.start.0, "duration": i.duration.0,
"startFrame": rate.frame_at(i.start), "durationFrames": rate.frame_at(i.duration), "sourceIn": i.source_in.0, "speed": i.speed,
"startFrame": rate.frame_at(i.start), "durationFrames": rate.frame_at(i.duration), "sourceIn": i.source_in.0, "speed": i.speed, "reverse": i.reverse,
"end": i.end().0, "endFrame": rate.frame_at(i.end()), "sourceOut": i.source_out().0, "gainDb": i.gain_db,
"enabled": i.enabled, "link": i.link, "label": i.label.name(),
"effects": i.effects.iter().map(|e| json!({"effect": e.effect, "enabled": e.enabled, "masks": e.masks.len(), "params": e.params.iter().map(|(k, p)| (k.clone(), json!({"value": format!("{:?}", p.value), "keyframes": p.keyframes.len()}))).collect::<serde_json::Map<_, _>>()})).collect::<Vec<_>>(),
})).collect::<Vec<_>>(),
@@ -2731,7 +3111,7 @@ pub fn inspect_sequence(s: &Session, id: ItemId, q: &filmcraft_project::Sequence
"in": q.mark_in.map(|t| t.0),
"out": q.mark_out.map(|t| t.0),
"split": q.split,
"markers": q.markers.iter().map(|m| json!({"id": m.id.0, "start": m.start.0, "duration": m.duration.0, "kind": format!("{:?}", m.kind), "name": m.name, "color": m.color.name()})).collect::<Vec<_>>(),
"markers": q.markers.iter().map(|m| json!({"id": m.id.0, "start": m.start.0, "duration": m.duration.0, "kind": format!("{:?}", m.kind), "name": m.name, "comment": m.comment, "color": m.color.name()})).collect::<Vec<_>>(),
"video": q.video_tracks.iter().map(tr).collect::<Vec<_>>(),
"audio": q.audio_tracks.iter().map(tr).collect::<Vec<_>>(),
"selection": s.state.selection.iter().map(|c| c.0).collect::<Vec<_>>(),
@@ -2769,7 +3149,9 @@ fn write_project(s: &mut Session, path: &str, adopt: bool) -> Result<Value> {
{
name_project(std::sync::Arc::make_mut(&mut s.project), name);
}
let bytes = filmcraft_format::encode(&s.project, false);
// 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);
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);
@@ -2827,6 +3209,13 @@ fn open_project(s: &mut Session, path: &str) -> Result<Value> {
let loaded = filmcraft_format::decode(&bytes).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
let (from, migrated) = (loaded.schema_version, loaded.migrated());
install_project(s, loaded.project, Some(path.to_string()), true);
if let Some(view) = loaded.view.filter(|_| s.prefs.timeline.restore_open_sequences) {
s.restore_project_view(view);
}
// the frontend shows the project's active sequence (with its own view, when one was restored)
if let Some(seq) = s.state.active_sequence {
s.events.push(crate::Event::OpenSequence(seq));
}
s.note_recent_project();
s.loaded_schema = from;
if migrated {
@@ -2847,6 +3236,9 @@ fn recover(s: &mut Session, id: Option<&str>) -> Result<Value> {
let saved_at = per.local_time(c.meta.saved_unix);
let loaded = crate::autosave::load_candidate(&c).map_err(EngineError::Other)?;
install_project(s, loaded.project, c.meta.project_path.clone(), false);
if let Some(seq) = s.state.active_sequence {
s.events.push(crate::Event::OpenSequence(seq));
}
crate::relink::on_open(s);
// Our own journal must hold the recovered state before the old one is deleted.
s.sync_persistence();
+14 -18
View File
@@ -21,24 +21,20 @@ pub fn add_generator(p: &mut Project, pool: &MediaPool, src: GeneratorSource, na
i.name = name.to_string();
i
};
let g = src.generator.clone();
let id = p.add_item(
name,
label,
ItemKind::Media(MediaClip {
media: MediaRef::Generator(g),
info,
interpret: Default::default(),
mark_in: None,
mark_out: None,
markers: vec![],
offline: false,
proxy: None,
identity: None,
}),
bin,
);
pool.insert(id, Arc::new(src.with_name(name)));
let clip = MediaClip {
media: MediaRef::Generator(src.generator.clone()),
info,
interpret: Default::default(),
mark_in: None,
mark_out: None,
markers: vec![],
offline: false,
proxy: None,
identity: None,
};
let key = crate::media_pool::media_key(&clip);
let id = p.add_item(name, label, ItemKind::Media(clip), bin);
pool.insert_keyed(id, key, Arc::new(src.with_name(name)));
id
}
+177
View File
@@ -0,0 +1,177 @@
//! A caller that names its targets in the parameters (`clips`, `clip`, `item`, `items`) does not
//! need a selection: enablement is checked against the named targets. Without such parameters
//! (the menus, shortcuts and `engine.commands`) enablement is the selection's, as before.
use filmcraft_project::{ClipId, ItemId, TrackItem};
use serde_json::json;
use crate::{EngineError, Session};
fn demo() -> Session {
let mut s = Session::default();
s.execute("file.openDemoProject", json!({})).unwrap();
s.execute("sequence.linkedSelection", json!({"on": false})).unwrap();
s.state.selection.clear();
s.state.project_selection.clear();
s
}
fn item_named(s: &Session, name: &str) -> ItemId {
s.project.items.values().find(|i| i.name == name).map(|i| i.id).unwrap_or_else(|| panic!("no item {name}"))
}
fn v1(s: &Session) -> Vec<TrackItem> {
s.active_sequence().unwrap().video_tracks[0].items.clone()
}
fn a1(s: &Session) -> Vec<TrackItem> {
s.active_sequence().unwrap().audio_tracks[0].items.clone()
}
fn clip(s: &Session, id: ClipId) -> Option<TrackItem> {
s.active_sequence().unwrap().find_item(id).map(|(_, i)| i.clone())
}
fn disabled(r: crate::Result<serde_json::Value>) -> String {
match r {
Err(EngineError::Disabled(_, why)) => why,
other => panic!("expected a disabled command, got {other:?}"),
}
}
#[test]
fn replace_from_bin_takes_an_explicit_item_and_clips_without_any_selection() {
let mut s = demo();
let c = v1(&s)[0].clone();
let dunes = item_named(&s, "Desert_Dunes.mp4");
assert_ne!(c.item, dunes);
// nothing named, nothing selected: disabled, for the menus and for a caller alike
assert!(!s.is_enabled("clip.replaceFromBin"));
assert_eq!(disabled(s.execute("clip.replaceFromBin", json!({}))), "no clips selected");
// the clip is named but the replacement is not: still the Project panel's call
assert_eq!(disabled(s.execute("clip.replaceFromBin", json!({"clips": [c.id.0]}))), "select a clip in the Project panel");
// both named: runs with no timeline and no Project-panel selection
s.execute("clip.replaceFromBin", json!({"clips": [c.id.0], "item": dunes.0})).unwrap();
assert_eq!(clip(&s, c.id).unwrap().item, dunes);
assert!(s.state.selection.is_empty() && s.state.project_selection.is_empty(), "the selections are left as they were");
assert!(!s.is_enabled("clip.replaceFromBin"), "menu enablement still follows the selection");
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(clip(&s, c.id).unwrap().item, c.item);
// a timeline selection plus an explicit item (no Project-panel selection)
s.execute("timeline.select", json!({"clips": [c.id.0]})).unwrap();
s.execute("clip.replaceFromBin", json!({"item": dunes.0})).unwrap();
assert_eq!(clip(&s, c.id).unwrap().item, dunes);
}
#[test]
fn clip_commands_take_explicit_clips_without_a_selection() {
let mut s = demo();
let (a, b) = (v1(&s)[0].clone(), v1(&s)[1].clone());
for id in ["edit.clear", "edit.rippleDelete", "clip.audioGain", "edit.pasteAttributes", "clip.enable"] {
assert!(!s.is_enabled(id), "{id} is disabled without a selection");
assert!(matches!(s.execute(id, json!({})), Err(EngineError::Disabled(..))), "{id} with no parameters stays disabled");
}
// Clear
s.execute("edit.clear", json!({"clips": [a.id.0]})).unwrap();
assert!(clip(&s, a.id).is_none() && clip(&s, b.id).is_some());
s.execute("edit.undo", json!({})).unwrap();
assert!(clip(&s, a.id).is_some());
// Ripple Delete
let a_and_its_audio: Vec<u64> = s
.active_sequence()
.unwrap()
.all_tracks()
.flat_map(|t| &t.items)
.filter(|i| i.id == a.id || (i.link.is_some() && i.link == a.link))
.map(|i| i.id.0)
.collect();
s.execute("timeline.setTrack", json!({"track": "A2", "syncLock": false})).unwrap(); // the music on A2 would block the ripple
s.execute("edit.rippleDelete", json!({"clips": a_and_its_audio})).unwrap();
assert!(clip(&s, a.id).is_none());
assert_eq!(clip(&s, b.id).unwrap().start, a.start, "the next clip closes the gap");
s.execute("edit.undo", json!({})).unwrap();
// Audio Gain
let au = a1(&s)[0].clone();
s.execute("clip.audioGain", json!({"clips": [au.id.0], "mode": "set", "db": -6.0})).unwrap();
assert_eq!(clip(&s, au.id).unwrap().gain_db, -6.0);
// Enable
s.execute("clip.enable", json!({"clips": [a.id.0]})).unwrap();
assert!(!clip(&s, a.id).unwrap().enabled);
s.execute("edit.undo", json!({})).unwrap();
assert!(clip(&s, a.id).unwrap().enabled);
s.execute("edit.redo", json!({})).unwrap();
assert!(!clip(&s, a.id).unwrap().enabled);
// `clip.enable` documents `clips` only: a key it does not document is not a named target
assert_eq!(disabled(s.execute("clip.enable", json!({"clip": a.id.0}))), "no clips selected");
// Paste Attributes: naming the clips lifts only the selection condition, not the clipboard one
assert_eq!(disabled(s.execute("edit.pasteAttributes", json!({"clips": [b.id.0]}))), "copy a clip first");
s.execute("timeline.select", json!({"clips": [a.id.0]})).unwrap();
s.execute("edit.copy", json!({})).unwrap();
s.state.selection.clear();
s.execute("edit.pasteAttributes", json!({"clips": [b.id.0]})).unwrap();
assert!(s.state.selection.is_empty(), "the selection is left as it was");
for id in ["edit.clear", "edit.rippleDelete", "clip.audioGain", "edit.pasteAttributes"] {
assert!(!s.is_enabled(id), "menu enablement of {id} still follows the selection");
}
}
#[test]
fn naming_nothing_usable_does_not_enable_a_command() {
let mut s = demo();
let before = s.project.clone();
// no ids, ids of no clip, the wrong type, and a key the command does not take
for p in [json!({"clips": []}), json!({"clips": [987_654_321u64]}), json!({"clips": "all"}), json!({"clips": [-1, 1.5, null]}), json!({"items": [1]})] {
assert_eq!(disabled(s.execute("edit.rippleDelete", p.clone())), "nothing selected", "{p}");
}
assert_eq!(disabled(s.execute("clip.replaceFromBin", json!({"clips": [v1(&s)[0].id.0], "item": 987_654_321u64}))), "select a clip in the Project panel");
// `edit.cut` takes no `clips`: it works on the selection only
assert_eq!(disabled(s.execute("edit.cut", json!({"clips": [v1(&s)[0].id.0]}))), "no clips selected");
assert!(std::sync::Arc::ptr_eq(&before, &s.project), "nothing was edited");
}
#[test]
fn link_and_speed_take_explicit_clips_without_a_selection() {
let mut s = demo();
let (v, au) = (v1(&s)[0].clone(), a1(&s)[0].clone());
for id in ["clip.link", "clip.speedDuration"] {
assert!(!s.is_enabled(id));
assert_eq!(disabled(s.execute(id, json!({}))), "no clips selected");
}
// Link toggles the named pair
let was = v.link.is_some() && v.link == au.link;
let r = s.execute("clip.link", json!({"clips": [v.id.0, au.id.0]})).unwrap();
assert_eq!(r["linked"], !was);
assert_eq!(clip(&s, v.id).unwrap().link.is_some(), !was);
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(clip(&s, v.id).unwrap().link, v.link);
s.execute("edit.redo", json!({})).unwrap();
assert_eq!(clip(&s, v.id).unwrap().link.is_some(), !was);
s.execute("edit.undo", json!({})).unwrap();
// Speed/Duration on the last clip of V1 (nothing after it to run into)
let last = v1(&s).last().unwrap().clone();
s.execute("clip.speedDuration", json!({"clips": [last.id.0], "speed": 200})).unwrap();
let fast = clip(&s, last.id).unwrap();
assert!(fast.duration < last.duration, "{:?} -> {:?}", last.duration, fast.duration);
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(clip(&s, last.id).unwrap().duration, last.duration);
s.execute("edit.redo", json!({})).unwrap();
assert_eq!(clip(&s, last.id).unwrap().duration, fast.duration);
assert!(s.state.selection.is_empty() && !s.is_enabled("clip.speedDuration"), "menu enablement still follows the selection");
}
#[test]
fn naming_targets_lifts_only_the_selection_condition() {
// no sequence: named clips cannot stand in for one
let mut empty = Session::default();
assert_eq!(disabled(empty.execute("edit.clear", json!({"clips": [1]}))), "no sequence is open");
assert_eq!(disabled(empty.execute("clip.speedDuration", json!({"clips": [1], "speed": 50}))), "no sequence is open");
let mut s = demo();
let a = v1(&s)[0].clone();
// the wrong kind of target: a video clip is not a graphic
assert_eq!(disabled(s.execute("graphics.setText", json!({"clip": a.id.0, "text": "x"}))), "select a graphic clip");
// a locked track is still the edit's own business: named or selected, the clip stays
s.execute("timeline.setTrack", json!({"track": "V1", "locked": true})).unwrap();
let _ = s.execute("edit.clear", json!({"clips": [a.id.0]}));
assert!(clip(&s, a.id).is_some(), "a clip on a locked track is not removed");
}
+79
View File
@@ -179,6 +179,24 @@ fn every_builtin_preset_exports_and_ffprobe_confirms() {
assert!((vbr / (mbps * px) - 1.0).abs() < 0.25, "{name}: {vbr:.1} Mb/s vs nominal {:.1}", mbps * px);
assert_eq!(a["codec_name"], "pcm_s24le", "{name}");
}
"apv" => {
assert!(fmt_name.contains("mov"), "{name}: {fmt_name}");
assert_eq!(v["codec_name"], "apv", "{name}");
let p = settings["apvProfile"].as_str().unwrap();
let idc = match p {
"422-10" => "33",
"422-12" => "44",
"444-10" => "55",
"444-12" => "66",
"4444-10" => "77",
"4444-12" => "88",
"400-10" => "99",
other => other,
};
let got_profile = v["profile"].as_str().unwrap_or("");
assert!(got_profile == p || got_profile == idc, "{name}: profile {got_profile} != {p} ({idc})");
assert_eq!(a["codec_name"], "pcm_s24le", "{name}");
}
"mxf-op1a" => {
assert_eq!(fmt_name, "mxf", "{name}");
let codec = match settings["mxfVideoCodec"].as_str().unwrap() {
@@ -345,6 +363,67 @@ fn queue_cancels_a_running_export_and_retries_a_failed_one() {
assert!(queue(&mut s).iter().all(|i| i["id"] != bad));
}
#[test]
fn jobs_and_queue_items_report_the_time_they_have_left() {
use std::sync::atomic::Ordering;
use std::time::Duration;
use crate::export_tools::QueueStatus;
let mut s = demo();
let dir = Scratch::new("eta");
let job = crate::Job { id: 77, label: "Exporting".into(), progress: Default::default(), result: Default::default() };
job.progress.total.store(1000, Ordering::Relaxed);
assert!(job.to_json()["etaSeconds"].is_null(), "no speed measured yet");
// 50 units a second for 5 s, read from the near future (the JSON reads the real clock, which is then behind them)
let t0 = web_time::Instant::now() + Duration::from_secs(60);
for i in 0..=50u64 {
job.progress.done.store(i * 5, Ordering::Relaxed);
job.progress.eta_at(t0 + Duration::from_millis(i * 100));
}
let eta = job.to_json()["etaSeconds"].as_f64().expect("a number once the job has a speed");
assert!((eta - 15.0).abs() < 0.5, "750 units left at 50 a second: {eta}");
s.jobs.push(job);
// a queue item encoding that job shows it; one that waits shows nothing
for name in ["a.wav", "b.wav"] {
s.execute(
"export.queue.add",
json!({"preset": "Waveform Audio 48 kHz 16-bit", "path": dir.path(name), "range": "custom", "startSeconds": 0, "endSeconds": 0.25}),
)
.unwrap();
}
s.export_queue.items[0].status = QueueStatus::Encoding;
s.export_queue.items[0].job = Some(77);
let items = queue(&mut s);
assert!((items[0]["etaSeconds"].as_f64().expect("encoding") - 15.0).abs() < 0.5, "{}", items[0]);
assert_eq!(items[0]["status"], "encoding");
assert!(items[1]["etaSeconds"].is_null(), "{}", items[1]);
// and `jobs.list` carries it too
let jobs = s.execute("jobs.list", json!({})).unwrap();
let listed = jobs["jobs"].as_array().or(jobs.as_array()).expect("a list of jobs").iter().find(|j| j["id"] == 77).cloned().expect("the job is listed");
assert!(listed["etaSeconds"].as_f64().is_some(), "{listed}");
}
#[test]
fn hardware_encoding_is_off_unless_asked_for() {
use filmcraft_export::HardwareEncoding::{Auto, Off};
let s = demo();
let setting = |p: Value| crate::export_tools::settings_from_params(&s, &p, "file.exportMedia").map(|(_, st)| st.hardware_encoding);
assert_eq!(setting(json!({"path": "x.mp4"})).unwrap(), Off);
assert_eq!(setting(json!({"path": "x.mp4", "hardwareEncoding": "auto"})).unwrap(), Auto);
assert_eq!(setting(json!({"path": "x.mp4", "hardwareEncoding": "off"})).unwrap(), Off);
// a boolean is understood too: true is auto
assert_eq!(setting(json!({"path": "x.mp4", "hardwareEncoding": true})).unwrap(), Auto);
assert_eq!(setting(json!({"path": "x.mp4", "hardwareEncoding": false})).unwrap(), Off);
// anything else names the choices
let e = setting(json!({"path": "x.mp4", "hardwareEncoding": "gpu"})).unwrap_err().to_string();
assert!(e.contains("off | auto"), "{e}");
// and it travels in the settings object, with the default filling in when it is missing
assert_eq!(setting(json!({"path": "x.mp4", "settings": {"hardwareEncoding": "auto"}})).unwrap(), Auto);
let old: filmcraft_export::ExportSettings = serde_json::from_value(json!({"format": "h264"})).unwrap();
assert_eq!(old.hardware_encoding, Off);
}
#[test]
fn queue_exports_several_sequences_and_ranges() {
let mut s = demo();
+17 -1
View File
@@ -26,7 +26,7 @@ use std::sync::Arc;
use std::sync::atomic::Ordering;
use filmcraft_export::presets::{DEFAULT_PRESET, preset_key};
use filmcraft_export::{ExportPreset, ExportSettings, Format};
use filmcraft_export::{ExportPreset, ExportSettings, Format, HardwareEncoding};
use filmcraft_project::{ItemId, Project};
use filmcraft_time::{FrameRate, Tick, TimeRange};
use serde::{Deserialize, Serialize};
@@ -200,6 +200,18 @@ pub fn settings_from_params(s: &Session, p: &Value, cmd: &str) -> Result<(Option
if let Some(v) = u64_p(p, "keyframeDistance") {
settings.keyframe_distance = Some(v as u32);
}
if let Some(v) = p.get("hardwareEncoding") {
settings.hardware_encoding = match v {
Value::Bool(on) => {
if *on {
HardwareEncoding::Auto
} else {
HardwareEncoding::Off
}
}
other => serde_json::from_value(other.clone()).map_err(|_| bad(cmd, "hardwareEncoding: off | auto"))?,
};
}
if let Some(v) = bool_p(p, "burnCaptions") {
settings.burn_captions = v;
}
@@ -209,6 +221,9 @@ pub fn settings_from_params(s: &Session, p: &Value, cmd: &str) -> Result<(Option
if let Some(v) = str_p(p, "dnxProfile") {
settings.dnx_profile = v.to_string();
}
if let Some(v) = str_p(p, "apvProfile") {
settings.apv_profile = v.to_string();
}
if let Some(v) = str_p(p, "mxfVideoCodec") {
settings.mxf_video_codec = serde_json::from_value(json!(v)).map_err(|_| bad(cmd, "mxfVideoCodec: dnxhr | proRes | h264"))?;
}
@@ -513,6 +528,7 @@ fn item_json(s: &Session, it: &QueueItem) -> Value {
"range": it.settings.range,
"status": it.status,
"progress": progress,
"etaSeconds": job.filter(|_| it.status == QueueStatus::Encoding).and_then(|j| j.progress.eta()).map(|d| d.as_secs_f64()),
"statusText": status_text,
"job": it.job,
"error": it.error,
@@ -363,3 +363,20 @@ fn caption_formats_through_the_engine() {
}
}
}
/// #188: a copied Graphic clip pastes at the playhead as a second Graphic clip.
#[test]
fn copy_paste_duplicates_a_graphic_clip() {
let mut s = demo("gt-paste");
let c = clip_of(&s.execute("graphics.newText", json!({"text": "Lyric", "seconds": 2})).unwrap());
s.execute("timeline.select", json!({"clips": [c.0]})).unwrap();
let v = s.execute("edit.copy", json!({})).unwrap();
assert_eq!(v["copied"], 1, "{v}");
s.execute("playhead.set", json!({"seconds": 620})).unwrap();
s.execute("edit.paste", json!({})).unwrap();
let q = s.active_sequence().unwrap();
let pasted: Vec<&TrackItem> = q.all_tracks().flat_map(|t| t.items.iter()).filter(|i| i.id != c && i.item == item(&s, c).item).collect();
assert_eq!(pasted.len(), 1, "one copy");
assert!((pasted[0].start.seconds() - 620.0).abs() < 0.05, "at the playhead: {:?}", pasted[0].start);
assert_eq!(texts(&s, pasted[0].id), vec!["Lyric".to_string()]);
}
+153 -28
View File
@@ -9,8 +9,8 @@
use filmcraft_geom::Vec2;
use filmcraft_project::graphic::{self, LayerContent, SHAPE_OPTS, eval_layer, layer_display_name, layer_indices, new_shape_layer, new_text_layer};
use filmcraft_project::{ClipId, ItemId, ItemKind, Label, ParamValue, Sequence, TrackKind};
use filmcraft_render::graphic_clip::{item_layer_specs, layer_local_bounds, layer_quad};
use filmcraft_project::{ClipId, EffectInstance, ItemId, ItemKind, Label, Param, ParamValue, Sequence, TrackKind};
use filmcraft_render::graphic_clip::{item_layer_specs, layer_local_bounds, layer_quad, text_layout};
use filmcraft_time::{Tick, TimeRange};
use serde_json::{Value, json};
@@ -124,13 +124,15 @@ pub(crate) fn place_video_clip(
(q.settings.width, q.settings.height, q.settings.frame_rate)
};
let (src, dur) = source(pr, (w, h, rate));
// an imported picture (`graphics.newFromFile`) keeps its own size: centre its anchor in it
let src_size = pr.source_size(src).unwrap_or((w, h));
let t = rate.snap(t);
let dur = dur.max(rate.frame_duration());
let mut ti = pr.make_track_item(src, TrackKind::Video, t, TimeRange::new(Tick::ZERO, dur), rate).ok_or_else(|| bad("graphics.newText", "bad item"))?;
ti.name = name;
ti.effects.extend(extra);
for e in &mut ti.effects {
filmcraft_project::resolve_auto_points(e, (w, h), (w, h));
filmcraft_project::resolve_auto_points(e, (w, h), src_size);
}
let id = ti.id;
let track_id = filmcraft_project::TrackId(pr.alloc_id());
@@ -191,6 +193,7 @@ fn param_id(k: &str) -> &str {
"fauxBold" => "faux_bold",
"fauxItalic" => "faux_italic",
"boxWidth" => "box_width",
"boxHeight" => "box_height",
"anchorPoint" => "anchor",
"cornerRadius" => "corner_radius",
other => other,
@@ -214,6 +217,38 @@ pub(crate) fn to_param(template: &ParamValue, id: &str, v: &Value) -> Option<Par
crate::commands::json_to_param(template, v)
}
/// Parameter `id` of a layer, created from the layer definition when the layer was saved before
/// the parameter existed.
fn param_entry<'a>(e: &'a mut EffectInstance, id: &str) -> Option<&'a mut Param> {
if !e.params.contains_key(id) {
let d = filmcraft_project::find_effect(&e.effect)?.param(id)?.default.clone();
e.params.insert(id.to_string(), Param::new(d));
}
e.params.get_mut(id)
}
/// Set properties `props` on layer `e` (keyframe-aware at media time `mt`). Changing the text
/// keeps per-character styles on their characters.
fn apply_props(e: &mut EffectInstance, props: &serde_json::Map<String, Value>, mt: Tick) -> Result<()> {
for (k, v) in props {
if k == "enabled" {
e.enabled = v.as_bool().unwrap_or(true);
continue;
}
let id = param_id(k);
let prm = param_entry(e, id).ok_or_else(|| bad("graphics.set", format!("no property `{k}`")))?;
let pv = to_param(&prm.value, id, v).ok_or_else(|| bad("graphics.set", format!("`{k}`: value has the wrong type")))?;
let old = prm.value_at(mt);
prm.set_at(mt, pv.clone());
if let (ParamValue::Text(a), ParamValue::Text(b), "text") = (&old, &pv, id)
&& let Some(x) = e.layer.as_mut()
{
x.runs = filmcraft_project::graphic_design::adjust_runs(a, b, &x.runs);
}
}
Ok(())
}
/// Set properties `props` on a layer (keyframe-aware at time `tl`). Changing the text keeps
/// per-character styles on their characters.
pub(crate) fn set_props(s: &mut Session, clip: ClipId, eidx: usize, props: &serde_json::Map<String, Value>, tl: Tick, label: &str) -> Result<()> {
@@ -222,26 +257,91 @@ pub(crate) fn set_props(s: &mut Session, clip: ClipId, eidx: usize, props: &serd
let (_, it) = q.find_item_mut(clip).ok_or(filmcraft_edit::EditError::NoItem(clip))?;
let mt = it.source_time_at(tl.clamp(it.start, it.end() - Tick(1)));
let e = it.effects.get_mut(eidx).ok_or_else(|| bad("graphics.set", "no such layer"))?;
for (k, v) in &props {
if k == "enabled" {
e.enabled = v.as_bool().unwrap_or(true);
continue;
}
let id = param_id(k);
let prm = e.params.get_mut(id).ok_or_else(|| bad("graphics.set", format!("no property `{k}`")))?;
let pv = to_param(&prm.value, id, v).ok_or_else(|| bad("graphics.set", format!("`{k}`: value has the wrong type")))?;
let old = prm.value_at(mt);
prm.set_at(mt, pv.clone());
if let (ParamValue::Text(a), ParamValue::Text(b), "text") = (&old, &pv, id)
&& let Some(x) = e.layer.as_mut()
{
x.runs = filmcraft_project::graphic_design::adjust_runs(a, b, &x.runs);
}
}
apply_props(e, &props, mt)?;
Ok(())
})
}
/// Turn a text layer into point text (no box; the lines the box wrapped become real lines) or
/// paragraph text (a box fitted to the text). The text stays where it is: the layer's origin
/// moves between the first baseline and the box's top-left corner, and the anchor point is
/// renumbered to stay on the same spot.
fn set_text_type(s: &mut Session, p: &Value) -> Result<Value> {
const ID: &str = "graphics.setTextType";
let clip = target_clip(s, p).ok_or_else(|| bad(ID, "no graphic clip"))?;
let (layer, ei) = layer_effect_index(s, clip, p)?;
let to_paragraph = match str_p(p, "type").map(str::to_ascii_lowercase).as_deref() {
Some("paragraph" | "paragraph text") => true,
Some("point" | "point text") => false,
_ => return Err(bad(ID, "need `type`: point or paragraph")),
};
let seq = s.active_sequence().ok_or(EngineError::NoSequence)?;
let (_, it) = seq.find_item(clip).ok_or_else(|| bad(ID, "no such clip"))?;
let size = match s.project.item(it.item).map(|p| &p.kind) {
Some(ItemKind::Graphic { width, height, .. }) => (*width, *height),
_ => (seq.settings.width, seq.settings.height),
};
let ph = s.playhead();
let mt = it.source_time_at(ph.clamp(it.start, it.end() - Tick(1)));
let spec = it.effects.get(ei).and_then(|e| eval_layer(e, mt, size)).ok_or_else(|| bad(ID, "no such layer"))?;
let LayerContent::Text(tp) = &spec.content else { return Err(bad(ID, "not a text layer")) };
if tp.vertical {
return Err(bad(ID, "vertical text is always point text"));
}
let name = |paragraph: bool| if paragraph { "paragraph" } else { "point" };
if (tp.box_width > 0.0) == to_paragraph {
return Ok(json!({"clip": clip.0, "layer": layer, "type": name(to_paragraph), "changed": false}));
}
// where point text's origin (its alignment point on the first baseline) sits in a box `w` wide
let origin_x = |w: f32| match tp.align {
1 => w / 2.0,
2 => w,
_ => 0.0,
};
let mut props = serde_json::Map::new();
// what to add to the anchor so that it stays on the same spot of the picture
let shift = if to_paragraph {
let widest = text_layout(tp).lines.iter().map(|l| l.width).fold(0.0, f32::max);
// a little slack, so that no line wraps
let w = (widest.ceil() + 1.0).clamp(1.0, 100_000.0);
let boxed = text_layout(&graphic::TextProps { box_width: w, box_height: 0.0, ..tp.clone() });
let h = (boxed.bounds[3].ceil() + 1.0).clamp(1.0, 100_000.0);
props.insert("box_width".into(), json!(w));
props.insert("box_height".into(), json!(h));
(origin_x(w), boxed.lines.first().map_or(0.0, |l| l.baseline))
} else {
// every line, also those the box hides
let all = text_layout(&graphic::TextProps { box_height: 0.0, ..tp.clone() });
let mut text = String::with_capacity(tp.text.len());
for (i, l) in all.lines.iter().enumerate() {
let line = tp.text.get(l.range.clone()).unwrap_or_default();
// a wrapped line ends where the next begins: its trailing space becomes the line break
let wrapped = all.lines.get(i + 1).is_some_and(|n| n.range.start == l.range.end);
text.push_str(if wrapped { line.trim_end() } else { line });
if i + 1 < all.lines.len() {
text.push('\n');
}
}
props.insert("text".into(), json!(text));
props.insert("box_width".into(), json!(0.0));
props.insert("box_height".into(), json!(0.0));
(-origin_x(tp.box_width), -all.lines.first().map_or(0.0, |l| l.baseline))
};
s.edit_sequence("Text Layer Type", |q, _, _| {
let (_, it) = q.find_item_mut(clip).ok_or(filmcraft_edit::EditError::NoItem(clip))?;
let e = it.effects.get_mut(ei).ok_or_else(|| bad(ID, "no such layer"))?;
apply_props(e, &props, mt)?;
if let Some(a) = param_entry(e, "anchor") {
a.map_values(|v| match v.as_vec2() {
Some(a) => ParamValue::Vec2(Vec2::new(a.x + shift.0 as f64, a.y + shift.1 as f64)),
None => v,
});
}
Ok(())
})?;
Ok(json!({"clip": clip.0, "layer": layer, "type": name(to_paragraph), "changed": true}))
}
/// Layers of a graphic clip with their evaluated bounds (sequence/canvas pixels).
fn list_layers(s: &Session, clip: ClipId) -> Result<Value> {
let seq = s.active_sequence().ok_or(EngineError::NoSequence)?;
@@ -265,6 +365,14 @@ fn list_layers(s: &Session, clip: ClipId) -> Result<Value> {
LayerContent::Text(t) => ("text", Some(t.text.clone())),
LayerContent::Shape(sh) => (SHAPE_OPTS.get(sh.shape as usize).copied().unwrap_or("Shape"), None),
};
// point text has no box; paragraph text wraps in one and hides what does not fit
let (text_type, text_box, overflow) = match &sp.content {
LayerContent::Text(t) if t.box_width > 0.0 && !t.vertical => {
(Some("paragraph"), Some([t.box_width, t.box_height]), Some(text_layout(t).overflow))
}
LayerContent::Text(_) => (Some("point"), None, None),
LayerContent::Shape(_) => (None, None, None),
};
Some(json!({
"layer": i,
"effectIndex": ei,
@@ -272,7 +380,13 @@ fn list_layers(s: &Session, clip: ClipId) -> Result<Value> {
"kind": kind,
"text": text,
"enabled": e.enabled,
"textType": text_type,
"box": text_box,
"overflow": overflow,
"position": [sp.transform.position.x, sp.transform.position.y],
"anchor": [sp.transform.anchor.x, sp.transform.anchor.y],
"scale": sp.transform.scale.y * 100.0,
"scaleWidth": sp.transform.scale.x * 100.0,
"uid": extra.map_or(0, |x| x.uid),
"pin": extra.and_then(|x| x.pin.as_ref()).map(|p| serde_json::to_value(p).unwrap_or_default()),
"styles": extra.map(|x| serde_json::to_value(&x.runs).unwrap_or_default()).unwrap_or(json!([])),
@@ -751,7 +865,7 @@ pub fn commands() -> Vec<CommandSpec> {
"Text",
&["Graphics and Titles", "New Layer"],
Some("Cmd+T"),
r#"{"text":str="New Text","position":[x,y]?,"clip":id?,"newClip":bool?,"vertical":bool=false,"size":px=100,"font":str?,"fontStyle":str?,"seconds":f64=5,"track":index?,"time":ticks?}"#,
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,
|s, p| {
let text = str_p(p, "text").unwrap_or("New Text").to_string();
@@ -761,18 +875,20 @@ pub fn commands() -> Vec<CommandSpec> {
let (w, h) = s.active_sequence().map(|q| (q.settings.width, q.settings.height)).unwrap_or((1920, 1080));
let pos = vec2_p(p, "position").unwrap_or(Vec2::new(w as f64 / 2.0, h as f64 / 2.0));
let size = f64_p(p, "size").unwrap_or(100.0);
let mut layer = if p.get("vertical").and_then(Value::as_bool) == Some(true) {
graphic::new_vertical_text_layer(&text, pos, size)
} else {
new_text_layer(&text, pos, size)
};
layer.params.insert("ligatures".into(), filmcraft_project::Param::new(ParamValue::Bool(gp.ligatures)));
let vertical = p.get("vertical").and_then(Value::as_bool) == Some(true);
let mut layer = if vertical { graphic::new_vertical_text_layer(&text, pos, size) } else { new_text_layer(&text, pos, size) };
if let Some(b) = vec2_p(p, "box").filter(|_| !vertical) {
for (id, v) in [("box_width", b.x), ("box_height", b.y)] {
layer.params.insert(id.into(), Param::new(ParamValue::Float(v.clamp(1.0, 100_000.0))));
}
}
layer.params.insert("ligatures".into(), Param::new(ParamValue::Bool(gp.ligatures)));
if !gp.default_font.trim().is_empty() {
layer.params.insert("font".into(), filmcraft_project::Param::new(ParamValue::Text(gp.default_font.trim().into())));
layer.params.insert("font".into(), Param::new(ParamValue::Text(gp.default_font.trim().into())));
}
for (k, id) in [("font", "font"), ("fontStyle", "font_style")] {
if let Some(v) = str_p(p, k) {
layer.params.insert(id.into(), filmcraft_project::Param::new(ParamValue::Text(v.into())));
layer.params.insert(id.into(), Param::new(ParamValue::Text(v.into())));
}
}
let into = if p.get("newClip").and_then(Value::as_bool) == Some(true) { None } else { u64_p(p, "clip").map(ClipId) };
@@ -859,6 +975,15 @@ pub fn commands() -> Vec<CommandSpec> {
Ok(Value::Null)
},
),
spec(
"graphics.setTextType",
"Text Layer Type",
&[],
None,
r#"{"clip":id?,"layer":n|name?,"type":"point|paragraph" (point: no box, handles scale the text; paragraph: the text wraps in a box that handles resize)}"#,
has_graphic,
set_text_type,
),
spec("graphics.selectLayer", "Select Graphic Layer", &[], None, r#"{"clip":id?,"layers":[n]}"#, has_graphic, |s, p| {
let clip = target_clip(s, p).ok_or_else(|| bad("graphics.selectLayer", "no graphic clip"))?;
let layers: Vec<usize> =
+191
View File
@@ -129,6 +129,33 @@ fn graphic_renders_in_the_program_and_survives_save() {
assert!(fonts.as_array().unwrap().iter().any(|f| f["family"] == "Inter"));
}
/// `file.exportInterchange` wrote a title out of the document without saying so: the command's
/// report names every graphic clip a format cannot carry.
#[test]
fn interchange_export_reports_the_title_it_cannot_carry() {
let d = std::env::temp_dir().join(format!("fc-title-report-{}", std::process::id()));
std::fs::create_dir_all(&d).unwrap();
let mut s = demo();
let r = s.execute("graphics.newText", json!({"text": "Opening line", "time": 0, "seconds": 2.0})).unwrap();
let clip = ClipId(r["clip"].as_u64().unwrap());
let (track, it) = s.active_sequence().unwrap().find_item(clip).map(|(t, i)| (t, i.clone())).unwrap();
let frame = s.sequence_rate().frame_at(it.start);
let want = format!("graphic clip \"{}\" at frame {frame}", it.name);
for format in ["xml", "fcpxml", "otio", "aaf"] {
let path = d.join(format!("cut.{format}")).to_string_lossy().to_string();
let r = s.execute("file.exportInterchange", json!({"format": format, "path": path})).unwrap();
let named = r["report"].as_array().unwrap().iter().filter(|l| l.as_str().is_some_and(|l| l.starts_with(&want))).count();
assert_eq!(named, 1, "{format}: {}", r["report"]);
}
// an EDL holds one video track: the report names the title when its track is the one written
let q = s.active_sequence().unwrap();
assert_ne!(q.video_tracks[0].id, track, "the title sits above the footage");
let path = d.join("cut.edl").to_string_lossy().to_string();
let r = s.execute("file.exportInterchange", json!({"format": "edl", "path": path})).unwrap();
assert!(r["report"].to_string().contains("one video track"), "{}", r["report"]);
let _ = std::fs::remove_dir_all(&d);
}
fn quad_box(s: &mut Session, clip: u64, layer: usize) -> [f64; 4] {
let l = s.execute("graphics.list", json!({"clip": clip})).unwrap();
let q = l["layers"][layer]["quad"].as_array().unwrap().clone();
@@ -342,7 +369,171 @@ fn new_layer_from_file_places_the_image_above() {
assert_eq!(it.start, q.settings.frame_rate.snap(t));
let ti = q.video_tracks.iter().position(|tr| tr.id == tid).unwrap();
assert!(q.video_tracks[..ti].iter().any(|tr| tr.item_at(t).is_some()), "above the footage");
// the anchor is the picture's centre, not the frame's, so `position` places the picture
let anchor = it.effect("motion").unwrap().vec2_at("anchor", Tick::ZERO);
assert_eq!((anchor.x, anchor.y), (w as f64 / 2.0, h as f64 / 2.0));
assert_eq!(s.state.selection, vec![clip]);
assert!(s.execute("graphics.newFromFile", json!({})).is_err());
let _ = std::fs::remove_dir_all(&dir);
}
/// Where each line of text layer `layer` starts on the canvas (the left end of its baseline),
/// with the line's text.
fn line_starts(s: &Session, clip: ClipId, layer: usize) -> Vec<(String, f64, f64)> {
let spec = layers(s, clip).remove(layer);
let LayerContent::Text(t) = &spec.content else { panic!("not text") };
let l = filmcraft_render::graphic_clip::text_layout(t);
let m = filmcraft_render::graphic_clip::layer_matrix(&spec);
l.lines
.iter()
.map(|line| {
let p = m.apply(filmcraft_geom::Vec2::new(line.x as f64, line.baseline as f64));
(t.text[line.range.clone()].trim_end().to_string(), p.x, p.y)
})
.collect()
}
fn same_places(a: &[(String, f64, f64)], b: &[(String, f64, f64)]) {
assert_eq!(a.len(), b.len(), "{a:?} vs {b:?}");
for (x, y) in a.iter().zip(b) {
assert_eq!(x.0, y.0);
assert!((x.1 - y.1).abs() < 0.05 && (x.2 - y.2).abs() < 0.05, "line `{}` moved: {x:?} -> {y:?}", x.0);
}
}
const FOX: &str = "The quick brown fox jumps over the lazy dog";
#[test]
fn paragraph_text_wraps_in_its_box_and_hides_what_does_not_fit() {
let mut s = demo();
let r = s.execute("graphics.newText", json!({"text": FOX, "position": [270, 583], "box": [500, 150], "size": 60})).unwrap();
let clip = ClipId(r["clip"].as_u64().unwrap());
let list = s.execute("graphics.list", json!({"clip": clip.0})).unwrap();
let l = &list["layers"][0];
assert_eq!(l["textType"], "paragraph");
assert_eq!(l["box"], json!([500.0, 150.0]));
assert_eq!(l["overflow"], true, "three lines of 60 px text do not fit 150 px");
assert_eq!(l["localBounds"], json!([0.0, 0.0, 500.0, 150.0]), "the box is the layer's bounds");
assert_eq!(l["quad"][0], json!([270.0, 583.0]), "the position is the box's top-left corner");
assert_eq!(l["quad"][2], json!([770.0, 733.0]));
let shown = line_starts(&s, clip, 0);
assert_eq!(shown.len(), 2, "{shown:?}");
assert!(shown.iter().all(|(_, x, _)| (*x - 270.0).abs() < 8.0), "lines start at the box's left edge: {shown:?}");
// a taller box shows everything; the font size and scale are untouched
s.execute("graphics.set", json!({"clip": clip.0, "props": {"boxHeight": 400}})).unwrap();
let list = s.execute("graphics.list", json!({"clip": clip.0})).unwrap();
assert_eq!(list["layers"][0]["overflow"], false);
assert_eq!(list["layers"][0]["scale"], 100.0);
assert!(line_starts(&s, clip, 0).len() >= 3);
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(s.execute("graphics.list", json!({"clip": clip.0})).unwrap()["layers"][0]["overflow"], true);
// point text has no box, and a vertical layer never gets one
let r = s.execute("graphics.newText", json!({"text": "Title", "newClip": true, "track": 3})).unwrap();
let point = s.execute("graphics.list", json!({"clip": r["clip"]})).unwrap();
assert_eq!(point["layers"][0]["textType"], "point");
assert_eq!(point["layers"][0]["box"], json!(null));
let r = s.execute("graphics.newText", json!({"text": "Tate", "vertical": true, "box": [300, 300], "newClip": true, "track": 4})).unwrap();
assert_eq!(s.execute("graphics.list", json!({"clip": r["clip"]})).unwrap()["layers"][0]["textType"], "point");
}
#[test]
fn text_type_converts_both_ways_and_keeps_the_text_in_place() {
for align in ["left", "center", "right"] {
let mut s = demo();
let r = s.execute("graphics.newText", json!({"text": FOX, "position": [270, 400], "box": [500, 150], "size": 60})).unwrap();
let clip = ClipId(r["clip"].as_u64().unwrap());
// scaled and turned, so that the anchor arithmetic matters
s.execute("graphics.set", json!({"clip": clip.0, "props": {"align": align, "scale": 150, "scale_width": 150, "rotation": 20}})).unwrap();
let hidden = line_starts(&s, clip, 0);
assert_eq!(hidden.len(), 2, "the box hides the third line");
s.execute("graphics.set", json!({"clip": clip.0, "props": {"boxHeight": 0}})).unwrap();
let before = line_starts(&s, clip, 0);
assert!(before.len() >= 3);
s.execute("edit.undo", json!({})).unwrap();
let position = layers(&s, clip)[0].transform.position;
// paragraph → point: every line stays where it was, also the hidden one
let r = s.execute("graphics.setTextType", json!({"clip": clip.0, "type": "point"})).unwrap();
assert_eq!(r, json!({"clip": clip.0, "layer": 0, "type": "point", "changed": true}));
let list = s.execute("graphics.list", json!({"clip": clip.0})).unwrap();
assert_eq!(list["layers"][0]["textType"], "point", "{align}");
let spec = layers(&s, clip).remove(0);
assert_eq!(text_of(&spec).lines().count(), before.len(), "the wrapped lines became real lines: {:?}", text_of(&spec));
assert_eq!(text_of(&spec).replace('\n', " "), FOX, "nothing but the line breaks changed");
assert_eq!(spec.transform.position, position, "the layer's position is untouched ({align})");
assert!(spec.transform.anchor.y < -1.0, "the anchor, still on the box's old corner, is above the first baseline: {:?}", spec.transform.anchor);
same_places(&before, &line_starts(&s, clip, 0));
// again: nothing to do
assert_eq!(s.execute("graphics.setTextType", json!({"clip": clip.0, "type": "Point Text"})).unwrap()["changed"], false);
// point → paragraph: a box fitted to the text, which still does not move
s.execute("graphics.setTextType", json!({"clip": clip.0, "type": "paragraph"})).unwrap();
let list = s.execute("graphics.list", json!({"clip": clip.0})).unwrap();
let l = &list["layers"][0];
assert_eq!(l["textType"], "paragraph");
assert_eq!(l["overflow"], false, "the fitted box shows every line");
let widest = 500.0;
assert!(l["box"][0].as_f64().unwrap() <= widest + 2.0 && l["box"][0].as_f64().unwrap() > 200.0, "{}", l["box"]);
let spec = layers(&s, clip).remove(0);
assert_eq!(spec.transform.position, position);
// the anchor is level with the box's top again; the fitted box is narrower than the old
// one, so centred and right-aligned text leave the anchor to its left
let a = spec.transform.anchor;
assert!(a.y.abs() < 1e-3 && a.x < 1e-3 && (align != "left" || a.x.abs() < 1e-3), "{align}: {a:?}");
same_places(&before, &line_starts(&s, clip, 0));
// each conversion is one undo step
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(s.execute("graphics.list", json!({"clip": clip.0})).unwrap()["layers"][0]["textType"], "point");
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(s.execute("graphics.list", json!({"clip": clip.0})).unwrap()["layers"][0]["textType"], "paragraph");
same_places(&hidden, &line_starts(&s, clip, 0));
s.execute("edit.redo", json!({})).unwrap();
same_places(&before, &line_starts(&s, clip, 0));
}
}
#[test]
fn text_type_refuses_what_it_cannot_convert() {
let mut s = Session::default();
assert!(s.execute("graphics.setTextType", json!({"type": "point"})).is_err(), "no sequence");
let mut s = demo();
let r = s.execute("graphics.newText", json!({"text": "Title"})).unwrap();
let clip = r["clip"].as_u64().unwrap();
assert!(s.execute("graphics.setTextType", json!({"clip": clip})).is_err(), "no type");
assert!(s.execute("graphics.setTextType", json!({"clip": clip, "type": "wavy"})).is_err());
s.execute("graphics.newShape", json!({"shape": "ellipse", "clip": clip})).unwrap();
let e = s.execute("graphics.setTextType", json!({"clip": clip, "layer": 1, "type": "paragraph"})).unwrap_err();
assert!(e.to_string().contains("not a text layer"), "{e}");
s.execute("graphics.newText", json!({"text": "Tate", "vertical": true, "clip": clip})).unwrap();
let e = s.execute("graphics.setTextType", json!({"clip": clip, "layer": 2, "type": "paragraph"})).unwrap_err();
assert!(e.to_string().contains("vertical"), "{e}");
// a point-text layer keeps its own line breaks when it gets a box
s.execute("graphics.setText", json!({"clip": clip, "layer": 0, "text": "one\ntwo words\n\nfour"})).unwrap();
let before = line_starts(&s, ClipId(clip), 0);
s.execute("graphics.setTextType", json!({"clip": clip, "layer": 0, "type": "paragraph"})).unwrap();
same_places(&before, &line_starts(&s, ClipId(clip), 0));
s.execute("graphics.setTextType", json!({"clip": clip, "layer": 0, "type": "point"})).unwrap();
assert_eq!(text_of(&layers(&s, ClipId(clip))[0]), "one\ntwo words\n\nfour");
}
#[test]
fn a_layer_saved_before_the_box_height_existed_can_still_get_one() {
let mut s = demo();
let r = s.execute("graphics.newText", json!({"text": FOX, "box": [500, 150], "size": 60})).unwrap();
let clip = ClipId(r["clip"].as_u64().unwrap());
s.edit_sequence("old file", |q, _, _| {
let (_, it) = q.find_item_mut(clip).unwrap();
let ei = layer_indices(&it.effects)[0];
it.effects[ei].params.remove("box_height");
Ok(())
})
.unwrap();
let list = s.execute("graphics.list", json!({"clip": clip.0})).unwrap();
assert_eq!(list["layers"][0]["box"], json!([500.0, 0.0]), "as tall as its text");
assert_eq!(list["layers"][0]["overflow"], false);
s.execute("graphics.set", json!({"clip": clip.0, "props": {"box_height": 100}})).unwrap();
assert_eq!(s.execute("graphics.list", json!({"clip": clip.0})).unwrap()["layers"][0]["box"], json!([500.0, 100.0]));
}
+25 -9
View File
@@ -20,6 +20,10 @@ fn report_json(r: &filmcraft_interchange::Report) -> Vec<String> {
r.entries.iter().map(|e| if e.count > 1 { format!("{} (×{})", e.message, e.count) } else { e.message.clone() }).collect()
}
fn is_file_media(item: &filmcraft_project::ProjectItem) -> bool {
matches!(&item.kind, ItemKind::Media(m) if matches!(m.media, MediaRef::File { .. }))
}
/// Import a document: merge its bins, media and sequences into the project (one undo step), then
/// link each media file that exists on disk. Returns the new sequences.
pub fn import(s: &mut Session, path: &str, bytes: &[u8], format: Format) -> Result<Value> {
@@ -46,7 +50,15 @@ pub fn import(s: &mut Session, path: &str, bytes: &[u8], format: Format) -> Resu
};
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, _| Ok(filmcraft_interchange::merge_into(proj, fragment, None)))?;
let seqs = s.edit(&format!("Import {name}"), |proj, _| {
let seqs = filmcraft_interchange::merge_into(proj, fragment, None);
// A document that sets only some Motion parameters leaves the others at their "auto"
// (NaN) defaults. Resolve them as placing a clip does, for every format. A media file's
// picture size is only what the document says so far (an EDL says nothing: the importer
// assumes the sequence size), so its clips' anchors wait for Link Media below.
proj.resolve_placed_auto_points(|seq| !before.contains(&seq), |source| !is_file_media(source));
Ok(seqs)
})?;
// Link media: probe each new file-backed item that exists.
let new_media: Vec<(ItemId, String)> = s
.project
@@ -85,6 +97,8 @@ pub fn import(s: &mut Session, path: &str, bytes: &[u8], format: Format) -> Resu
filmcraft_interchange::rebase_source_timecode(proj, id, tc, rate);
}
}
// the picture size is now the file's own: centre the anchors of its clips in it
proj.resolve_placed_auto_points(|seq| !before.contains(&seq), |source| source.id == id);
Ok(())
})?;
s.media.insert_file(id, &mpath, src);
@@ -108,15 +122,17 @@ pub fn import(s: &mut Session, path: &str, bytes: &[u8], format: Format) -> Resu
}))
}
/// `file.exportInterchange {format: "edl"|"xml"|"fcpxml"|"otio", path, sequence?}`
/// `file.exportInterchange {format: "edl"|"xml"|"fcpxml"|"otio"|"aaf"|"omf" = "xml", path, sequence?}`
pub fn export(s: &mut Session, p: &Value) -> Result<Value> {
let format = match p.get("format").and_then(Value::as_str).unwrap_or("xml") {
"edl" => Format::Edl,
"fcpxml" => Format::Fcpxml,
"otio" => Format::Otio,
"aaf" => Format::Aaf,
"omf" => Format::Omf,
_ => Format::Fcp7Xml,
// FCP7 XML only when no format is asked for: a format we don't know is an error, not XML.
// The names are the documented ones (each format's extension, in either case) and nothing
// else, so the error can list exactly what is accepted.
let format = match p.get("format") {
None | Some(Value::Null) => Format::Fcp7Xml,
Some(v) => v.as_str().and_then(|name| Format::ALL.into_iter().find(|f| f.extension().eq_ignore_ascii_case(name))).ok_or_else(|| {
let names: Vec<&str> = Format::ALL.iter().map(|f| f.extension()).collect();
crate::commands::bad("file.exportInterchange", format!("unknown format {v}: use one of {}", names.join(", ")))
})?,
};
let path = p.get("path").and_then(Value::as_str).ok_or_else(|| EngineError::Other("need `path`".into()))?.to_string();
let seq = p.get("sequence").and_then(Value::as_u64).map(ItemId).or(s.state.active_sequence).ok_or(EngineError::NoSequence)?;
@@ -0,0 +1,218 @@
//! Interchange imports and the "auto" (NaN) point defaults of the effects they add: the points
//! are resolved as placing a clip resolves them, the anchor once the media's real size is known,
//! and a project saved after an import opens again.
use filmcraft_geom::Vec2;
use filmcraft_media::DemoScene;
use filmcraft_project::{ItemId, ParamValue, Project, TrackItem};
use filmcraft_time::Tick;
use serde_json::json;
use crate::Session;
use crate::media_test_util::{make_movie, tmp_dir};
const RATE: &str = "<rate><timebase>24</timebase><ntsc>FALSE</ntsc></rate>";
/// A 1920×1080 FCP7 XML sequence with one clip of `media/shot.mov` (declared 3840×2160) whose
/// Basic Motion filter sets only `scale`.
fn xml_with_a_scale_only_motion_filter() -> String {
format!(
r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xmeml>
<xmeml version="4">
<sequence id="sequence-1">
<name>Cut</name>
<duration>24</duration>
{RATE}
<media>
<video>
<format><samplecharacteristics>{RATE}<width>1920</width><height>1080</height></samplecharacteristics></format>
<track>
<clipitem id="clipitem-1">
<name>shot</name>
{RATE}
<start>0</start><end>24</end><in>0</in><out>24</out>
<file id="file-1">
<name>shot.mov</name>
<pathurl>media/shot.mov</pathurl>
{RATE}
<duration>24</duration>
<media><video><samplecharacteristics><width>3840</width><height>2160</height></samplecharacteristics></video></media>
</file>
<filter><effect>
<name>Basic Motion</name><effectid>basic</effectid><effectcategory>motion</effectcategory><effecttype>motion</effecttype><mediatype>video</mediatype>
<parameter><parameterid>scale</parameterid><name>Scale</name><value>50</value></parameter>
</effect></filter>
</clipitem>
</track>
</video>
</media>
</sequence>
</xmeml>
"#
)
}
fn first_clip(s: &Session, seq: ItemId) -> TrackItem {
s.project.sequence(seq).unwrap().video_tracks[0].items[0].clone()
}
fn motion_point(c: &TrackItem, k: &str) -> Vec2 {
c.effect("motion").unwrap().vec2_at(k, Tick::ZERO)
}
/// Every effect point parameter of every clip that is still "auto".
fn auto_points(p: &Project) -> Vec<String> {
let mut out = Vec::new();
for q in p.sequences().filter_map(|i| i.as_sequence()) {
for c in q.all_tracks().flat_map(|t| &t.items) {
for e in &c.effects {
for (k, v) in &e.params {
if matches!(&v.value, ParamValue::Vec2(v) if v.x.is_nan() || v.y.is_nan()) {
out.push(format!("{}.{k}", e.effect));
}
}
}
}
}
out
}
fn import(s: &mut Session, doc: &std::path::Path) -> (serde_json::Value, ItemId) {
let r = s.execute("file.import", json!({"paths": [doc.to_string_lossy()]})).unwrap();
let seq = ItemId(r["sequences"][0].as_u64().unwrap_or_else(|| panic!("no sequence in {r}")));
(r["documents"][0].clone(), seq)
}
/// A project saved after such an import held `null` points and could not be opened again
/// ("project file is damaged: invalid type: null, expected f64").
#[test]
fn a_project_saved_after_an_interchange_import_opens_again() {
let d = tmp_dir("ix-auto-offline");
let doc = d.join("cut.xml");
std::fs::write(&doc, xml_with_a_scale_only_motion_filter()).unwrap();
let mut s = Session::default();
let before = s.project.clone();
// the media file is not there: its real size is not known
let (r, seq) = import(&mut s, &doc);
assert_eq!((r["linkedMedia"].as_u64(), r["offlineMedia"].as_array().map(Vec::len)), (Some(0), Some(1)), "{r}");
let clip = first_clip(&s, seq);
assert_eq!(clip.effect("motion").unwrap().f64_at("scale", Tick::ZERO), 50.0);
assert_eq!(motion_point(&clip, "position"), Vec2::new(960.0, 540.0), "the frame centre, as placing a clip resolves it");
assert!(motion_point(&clip, "anchor").x.is_nan(), "the anchor waits for the media's real size");
assert_eq!(auto_points(&s.project), ["motion.anchor"]);
// the saved file opens again and holds the same project (NaN != NaN, so compare what is written)
let path = d.join("p.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!(filmcraft_format::encode(&t.project, false), filmcraft_format::encode(&s.project, false));
assert_eq!(auto_points(&t.project), ["motion.anchor"]);
assert_eq!(motion_point(&first_clip(&t, seq), "position"), Vec2::new(960.0, 540.0));
// without a link step the import is one undo step
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(*s.project, *before);
s.execute("edit.redo", json!({})).unwrap();
assert_eq!(auto_points(&s.project), ["motion.anchor"]);
let _ = std::fs::remove_dir_all(&d);
}
/// The anchor is centred in the file's real picture, not in the size the document declares
/// (3840×2160 here) or the sequence's.
#[test]
fn a_linked_clip_gets_its_anchor_from_the_real_size_of_the_media() {
let d = tmp_dir("ix-auto-linked");
std::fs::create_dir_all(d.join("media")).unwrap();
make_movie(&d.join("media/shot.mov"), DemoScene::OceanSunset, 320, 180, 24);
let doc = d.join("cut.xml");
std::fs::write(&doc, xml_with_a_scale_only_motion_filter()).unwrap();
let mut s = Session::default();
let before = s.project.clone();
let (r, seq) = import(&mut s, &doc);
assert_eq!(r["linkedMedia"], 1, "{r}");
let clip = first_clip(&s, seq);
assert_eq!(s.project.source_size(clip.item), Some((320, 180)));
assert_eq!((motion_point(&clip, "position"), motion_point(&clip, "anchor")), (Vec2::new(960.0, 540.0), Vec2::new(160.0, 90.0)));
assert_eq!(auto_points(&s.project), Vec::<String>::new());
// nothing is NaN, so the reopened project is equal
let path = d.join("p.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!(*t.project, *s.project);
// undo: Link Media takes the real size and the anchor back together, then the import itself
let linked = s.project.clone();
s.execute("edit.undo", json!({})).unwrap();
let clip = first_clip(&s, seq);
assert_eq!(s.project.source_size(clip.item), Some((3840, 2160)), "the size the document declared");
assert!(motion_point(&clip, "anchor").x.is_nan());
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(*s.project, *before);
s.execute("edit.redo", json!({})).unwrap();
s.execute("edit.redo", json!({})).unwrap();
assert_eq!(*s.project, *linked);
let _ = std::fs::remove_dir_all(&d);
}
/// An EDL says nothing about the picture: the importer assumes the sequence size for the media
/// until the file is probed. A clip smaller than the sequence must still be centred.
#[test]
fn an_edl_clip_is_centred_in_its_real_size_not_the_assumed_sequence_size() {
let d = tmp_dir("ix-auto-edl");
make_movie(&d.join("shot.mov"), DemoScene::OceanSunset, 320, 180, 24);
let doc = d.join("cut.edl");
let edl = "TITLE: Cut\nFCM: NON-DROP FRAME\n\n001 AX V C 00:00:00:00 00:00:01:00 01:00:00:00 01:00:01:00\n* FROM CLIP NAME: shot.mov\n* SOURCE FILE: shot.mov\n";
std::fs::write(&doc, edl).unwrap();
let mut s = Session::default();
let (r, seq) = import(&mut s, &doc);
assert_eq!(r["linkedMedia"], 1, "{r}");
let st = s.project.sequence(seq).unwrap().settings.clone();
assert_ne!((st.width, st.height), (320, 180), "the media is not the size of the sequence");
let clip = first_clip(&s, seq);
assert_eq!(motion_point(&clip, "position"), Vec2::new(st.width as f64 / 2.0, st.height as f64 / 2.0));
assert_eq!(motion_point(&clip, "anchor"), Vec2::new(160.0, 90.0), "the centre of the 320×180 picture");
assert_eq!(auto_points(&s.project), Vec::<String>::new());
let _ = std::fs::remove_dir_all(&d);
}
/// Imported with the media missing, saved, reopened, and only then linked: Link Media gives the
/// item its real size, and the anchors that waited for it become numbers.
#[test]
fn relinking_later_resolves_the_anchor_that_waited_for_the_real_size() {
let d = tmp_dir("ix-auto-relink");
let doc = d.join("cut.xml");
std::fs::write(&doc, xml_with_a_scale_only_motion_filter()).unwrap();
let mut s = Session::default();
let (_, seq) = import(&mut s, &doc);
let path = d.join("p.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();
let clip = first_clip(&t, seq);
assert!(motion_point(&clip, "anchor").x.is_nan(), "still auto after the reopen");
// the file turns up in another folder, smaller than the document said
std::fs::create_dir_all(d.join("found")).unwrap();
let found = d.join("found/shot.mov");
make_movie(&found, DemoScene::OceanSunset, 320, 180, 24);
let waiting = t.project.clone();
let r = t.execute("media.relink", json!({"item": clip.item.0, "path": found.to_string_lossy(), "force": true})).unwrap();
assert_eq!(r["relinked"].as_array().map(Vec::len), Some(1), "{r}");
let clip = first_clip(&t, seq);
assert_eq!(t.project.source_size(clip.item), Some((320, 180)));
assert_eq!((motion_point(&clip, "position"), motion_point(&clip, "anchor")), (Vec2::new(960.0, 540.0), Vec2::new(160.0, 90.0)));
assert_eq!(auto_points(&t.project), Vec::<String>::new());
// one undo step takes the link and the anchor back together
let linked = t.project.clone();
t.execute("edit.undo", json!({})).unwrap();
assert_eq!(filmcraft_format::encode(&t.project, false), filmcraft_format::encode(&waiting, false));
assert_eq!(auto_points(&t.project), ["motion.anchor"]);
t.execute("edit.redo", json!({})).unwrap();
assert_eq!(*t.project, *linked);
// an anchor that is already a number is not touched by a later relink to another size
std::fs::create_dir_all(d.join("other")).unwrap();
let other = d.join("other/shot.mov");
make_movie(&other, DemoScene::OceanSunset, 160, 90, 24);
t.execute("media.relink", json!({"item": clip.item.0, "path": other.to_string_lossy(), "force": true})).unwrap();
assert_eq!(motion_point(&first_clip(&t, seq), "anchor"), Vec2::new(160.0, 90.0));
let _ = std::fs::remove_dir_all(&d);
}
+154 -15
View File
@@ -163,6 +163,11 @@ impl Services for FsServices {
fn file_loader(&self) -> Option<filmcraft_media::sequence::FrameLoader> {
Some(std::sync::Arc::new(|p: &str| std::fs::read(p)))
}
/// Media are read in place from the open file: a clip costs its index, not its size.
#[cfg(any(unix, windows))]
fn reader(&self, path: &str) -> Option<std::io::Result<filmcraft_media::SharedReader>> {
Some(filmcraft_media::reader::FileReader::open(std::path::Path::new(path)).map(|r| std::sync::Arc::new(r) as filmcraft_media::SharedReader))
}
fn list_entries(&self, dir: &str) -> Option<std::io::Result<Vec<media_browser::DirEntry>>> {
Some(media_browser::std_list_entries(dir))
}
@@ -229,8 +234,17 @@ pub struct EditorState {
pub targeting: std::collections::BTreeMap<ItemId, Targeting>,
pub snapping: bool,
pub linked_selection: bool,
/// The Timeline's "Insert and overwrite sequences as nests or individual clips" toggle, turned
/// off: a sequence edits in as its clips instead of one nested clip.
#[serde(default)]
pub sequences_as_clips: bool,
/// 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
/// sequence keeps its own. The frontend writes the active sequence's view here as it changes
/// and takes a sequence's view from here when it becomes the active one.
#[serde(default)]
pub timeline_views: std::collections::BTreeMap<ItemId, filmcraft_project::SequenceView>,
/// Timeline clipboard (serialized track items with their relative track index).
#[serde(skip)]
pub clipboard: Vec<(TrackKind, usize, filmcraft_project::TrackItem)>,
@@ -290,10 +304,17 @@ pub struct EditorState {
/// Events for frontends (drained each frame).
#[derive(Clone, Debug, PartialEq, Serialize)]
pub enum Event {
ProjectChanged { revision: u64 },
Toast { message: String, error: bool },
ProjectChanged {
revision: u64,
},
Toast {
message: String,
error: bool,
},
OpenSequence(ItemId),
OpenSource(ItemId),
/// Show this item in the Project panel (Reveal in Project).
RevealInProject(ItemId),
}
pub struct Session {
@@ -383,6 +404,8 @@ impl Job {
"id": self.id,
"label": self.label,
"progress": self.progress.fraction(),
// seconds left at the job's recent speed; null until it can tell
"etaSeconds": self.progress.eta().map(|d| d.as_secs_f64()),
"done": self.progress.done.load(Ordering::Relaxed),
"total": self.progress.total.load(Ordering::Relaxed),
"status": self.progress.status.lock().unwrap_or_else(|e| e.into_inner()).clone(),
@@ -595,7 +618,7 @@ impl Session {
if self.exec_depth == 0 && spec.journal && self.trim_play.active() {
self.settle_trim_playback(id);
}
if let Err(why) = (spec.enabled)(self) {
if let Err(why) = self.enabled_for(spec, &params) {
let e = EngineError::Disabled(id.to_string(), why);
if self.exec_depth == 0 {
self.log.push(panels::Level::Warning, id, e.to_string());
@@ -645,15 +668,86 @@ impl Session {
}
}
/// Enablement of `spec` for one call. `enabled()` reads the selection, which is right for the
/// menus and for a call without targets. A caller that names its targets in `params`, under a
/// key the command documents (`clips` / `clip`: timeline clips, `items` / `item`: project
/// items), is asked the same question about those targets instead: the check runs again with
/// them standing in for the selection, so every other condition (an open sequence, a filled
/// clipboard, the kind of item…) still applies. The selections are put back before returning.
fn enabled_for(&mut self, spec: &CommandSpec, params: &Value) -> std::result::Result<(), String> {
let by_selection = (spec.enabled)(self);
if by_selection.is_ok() {
return by_selection;
}
let clips = commands::named_clips(self, spec, params);
let items = commands::named_items(self, spec, params);
if clips.is_none() && items.is_none() {
return by_selection;
}
let mut clips = clips.unwrap_or_else(|| self.state.selection.clone());
let mut items = items.unwrap_or_else(|| self.state.project_selection.clone());
std::mem::swap(&mut self.state.selection, &mut clips);
std::mem::swap(&mut self.state.project_selection, &mut items);
let by_params = (spec.enabled)(self);
self.state.selection = clips;
self.state.project_selection = items;
by_params
}
/// Whether the command can run on the current selection (what the menus show).
pub fn is_enabled(&self, id: &str) -> bool {
commands::find(id).is_some_and(|c| (c.enabled)(self).is_ok())
}
/// What is open, to store beside the project when it is saved.
pub fn project_view(&self) -> filmcraft_project::ProjectView {
let is_seq = |id: &ItemId| self.project.sequence(*id).is_some();
filmcraft_project::ProjectView {
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(),
}
}
/// Open what was open when the project was saved. Nothing in `view` is trusted: ids that are
/// not sequences of this project are dropped (also a second mention of the same sequence),
/// and numbers are brought into range. A 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) {
let mut open: Vec<ItemId> = Vec::new();
for id in view.open_sequences {
if self.project.sequence(id).is_some() && !open.contains(&id) {
open.push(id);
}
}
if !open.is_empty() {
self.state.active_sequence = view.active_sequence.filter(|id| open.contains(id)).or(open.first().copied());
self.state.open_sequences = open;
}
self.state.timeline_views =
view.sequences.into_iter().filter(|(id, _)| self.project.sequence(*id).is_some()).filter_map(|(id, v)| Some((id, v.checked()?))).collect();
}
/// Every edit passes through here: one that would put a sequence inside itself (directly or
/// through another nested sequence) is refused, whichever command asked for it. A project that
/// was opened with such a sequence already in it can still be edited (and repaired).
fn refuse_self_nesting(&self, edited: &Project) -> Result<()> {
match edited.nest_cycle() {
Some(id) if self.project.nest_cycle().is_none() => {
let name = edited.item(id).map(|i| i.name.as_str()).unwrap_or_default();
Err(EngineError::Other(format!("a sequence cannot be nested inside itself (\u{201c}{name}\u{201d})")))
}
_ => Ok(()),
}
}
/// Apply an undoable project edit. The closure gets a mutable copy; on error nothing changes.
pub fn edit<R>(&mut self, label: &str, f: impl FnOnce(&mut Project, &mut EditorState) -> Result<R>) -> Result<R> {
let mut p = (*self.project).clone();
let mut st = self.state.clone();
let r = f(&mut p, &mut st)?;
self.refuse_self_nesting(&p)?;
let old = std::mem::replace(&mut self.project, Arc::new(p));
self.history.undo.push((label.to_string(), old));
if self.history.undo.len() > self.history.limit {
@@ -678,6 +772,7 @@ impl Session {
let mut p = (*self.project).clone();
let mut st = self.state.clone();
let r = f(&mut p, &mut st)?;
self.refuse_self_nesting(&p)?;
self.project = Arc::new(p);
self.state = st;
self.bump();
@@ -744,6 +839,7 @@ impl Session {
self.state.active_sequence = p.sequences().next().map(|i| i.id);
}
self.state.open_sequences.retain(|s| p.sequence(*s).is_some());
self.state.timeline_views.retain(|s, _| p.sequence(*s).is_some());
if let Some(s) = self.state.source_item
&& p.item(s).is_none()
{
@@ -835,10 +931,17 @@ impl Session {
/// Render the active sequence at the playhead (CPU reference path).
pub fn render_program(&self, scale: f32) -> Option<filmcraft_render::Image> {
self.render_program_at(scale, self.playhead())
}
/// Render the active sequence at `t` (snapped to its frame, as the playhead would be) without
/// moving the playhead (CPU reference path).
pub fn render_program_at(&self, scale: f32, t: Tick) -> Option<filmcraft_render::Image> {
let seq = self.state.active_sequence?;
let t = self.sequence_rate().snap(t.max(Tick::ZERO));
let provider = self.media.provider(self.project.clone(), self.services.clone());
let opts = filmcraft_render::RenderOptions { scale, captions: true, ..Default::default() };
Some(filmcraft_render::render_sequence(&self.project, seq, self.playhead(), opts, &provider))
Some(filmcraft_render::render_sequence(&self.project, seq, t, opts, &provider))
}
}
@@ -853,20 +956,32 @@ pub fn media_start(p: &Project, id: ItemId) -> Tick {
/// Media duration of an item (None for stills/adjustment layers = unlimited handles).
pub fn media_duration(p: &Project, _pool: &MediaPool, id: ItemId) -> Option<Tick> {
let it = p.item(id)?;
match &it.kind {
filmcraft_project::ItemKind::Media(m) => match m.info.kind {
filmcraft_media::MediaKind::Still | filmcraft_media::MediaKind::Synthetic => None,
_ => Some(m.info.duration),
},
filmcraft_project::ItemKind::Sequence(s) => Some(s.duration()),
// a subclip that restricts trims ends at its Out point; otherwise its parent's media is the limit
filmcraft_project::ItemKind::Subclip { range, restrict_trims: true, .. } => Some(range.end()),
filmcraft_project::ItemKind::Subclip { parent, .. } => media_duration(p, _pool, *parent),
filmcraft_project::ItemKind::AdjustmentLayer { .. } | filmcraft_project::ItemKind::Graphic { .. } => None,
// a subclip's limit is its parent's: follow the chain, bounded (a damaged project file can make
// it cyclic or arbitrarily deep)
let mut id = id;
for _ in 0..=MAX_SUBCLIP_CHAIN {
let it = p.item(id)?;
return match &it.kind {
filmcraft_project::ItemKind::Media(m) => match m.info.kind {
filmcraft_media::MediaKind::Still | filmcraft_media::MediaKind::Synthetic => None,
_ => Some(m.info.duration),
},
filmcraft_project::ItemKind::Sequence(s) => Some(s.duration()),
// a subclip that restricts trims ends at its Out point; otherwise its parent's media is the limit
filmcraft_project::ItemKind::Subclip { range, restrict_trims: true, .. } => Some(range.end()),
filmcraft_project::ItemKind::Subclip { parent, .. } => {
id = *parent;
continue;
}
filmcraft_project::ItemKind::AdjustmentLayer { .. } | filmcraft_project::ItemKind::Graphic { .. } => None,
};
}
None
}
/// Subclips of subclips followed before giving up (real projects nest one or two deep).
const MAX_SUBCLIP_CHAIN: usize = 16;
#[cfg(test)]
mod aaf_omf_tests;
#[cfg(test)]
@@ -880,14 +995,20 @@ mod color_tests;
#[cfg(test)]
mod essential_sound_tests;
#[cfg(test)]
mod explicit_targets_tests;
#[cfg(test)]
mod export_tests;
#[cfg(test)]
mod file_tests;
#[cfg(test)]
mod image_sequence_tests;
#[cfg(test)]
mod interchange_auto_points_tests;
#[cfg(test)]
mod keyboard_tests;
#[cfg(test)]
mod linked_speed_tests;
#[cfg(test)]
mod masks_tests;
#[cfg(test)]
mod media_browser_tests;
@@ -898,6 +1019,12 @@ mod mixer_tests;
#[cfg(test)]
mod multicam_tests;
#[cfg(test)]
mod nest_editing_tests;
#[cfg(test)]
mod nest_fidelity_tests;
#[cfg(test)]
mod nesting_tests;
#[cfg(test)]
mod panels_tests;
#[cfg(test)]
mod presets_tests;
@@ -914,16 +1041,28 @@ mod relink_tests;
#[cfg(test)]
mod remix_tests;
#[cfg(test)]
mod ripple_delete_tests;
#[cfg(test)]
mod scopes_tests;
#[cfg(test)]
mod sequence_inspect_tests;
#[cfg(test)]
mod sequence_tabs_tests;
#[cfg(test)]
mod sequence_tools_tests;
#[cfg(test)]
mod settings_tests;
#[cfg(test)]
mod shortcuts_tests;
#[cfg(test)]
mod split_edit_ripple_trim_tests;
#[cfg(test)]
mod tests;
#[cfg(test)]
mod timeline_move_tests;
#[cfg(test)]
mod track_params_tests;
#[cfg(test)]
mod transcript_tests;
#[cfg(test)]
mod trim_tests;
+152
View File
@@ -0,0 +1,152 @@
//! `clip.speedDuration` with `ripple` on a clip that has linked sound: the clip and its sound
//! change as one edit, and the later clips move once.
use filmcraft_project::ClipId;
use filmcraft_time::Tick;
use serde_json::json;
use crate::Session;
fn range(s: &Session, c: ClipId) -> (Tick, Tick) {
s.active_sequence().unwrap().find_item(c).map(|(_, i)| (i.start, i.end())).unwrap()
}
/// Three 48-frame clips in a row, pictures on V1 and their linked sounds on A1: [(picture, sound); 3].
fn three_clips(s: &mut Session) -> [(ClipId, ClipId); 3] {
s.execute("file.openDemoProject", json!({})).unwrap();
s.execute("file.newSequence", json!({"name": "Speed", "video": 1, "audio": 1})).unwrap();
let rate = s.sequence_rate();
let item = s.project.items.values().find(|i| i.has_video() && i.has_audio() && i.as_media().is_some()).map(|i| i.id).unwrap();
for n in 0..3 {
s.execute("timeline.place", json!({"item": item.0, "frame": 48 * n, "sourceIn": rate.tick_of(48).0, "duration": rate.tick_of(48).0})).unwrap();
}
let q = s.active_sequence().unwrap();
[0, 1, 2].map(|n| (q.video_tracks[0].items[n].id, q.audio_tracks[0].items[n].id))
}
/// Slower with ripple moved the later clips twice (once for the picture, once for its sound) and
/// left a double gap.
#[test]
fn slower_with_ripple_moves_later_clips_once() {
let mut s = Session::default();
let [_, (picture2, sound2), (picture3, sound3)] = three_clips(&mut s);
let f = |n: i64| s.sequence_rate().tick_of(n);
let (f48, f144, f192) = (f(48), f(144), f(192));
let before = s.project.clone();
s.execute("clip.speedDuration", json!({"clips": [picture2.0], "speed": 50, "ripple": true})).unwrap();
let q = s.active_sequence().unwrap();
q.check().unwrap();
assert_eq!((range(&s, picture2), range(&s, sound2)), ((f48, f144), (f48, f144)), "the clip and its sound are twice as long");
assert_eq!((range(&s, picture3), range(&s, sound3)), ((f144, f192), (f144, f192)), "the next clip follows, once");
assert_eq!(q.duration(), f192);
let after = s.project.clone();
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(*s.project, *before, "one undo step restores it");
s.execute("edit.redo", json!({})).unwrap();
assert_eq!(*s.project, *after);
}
/// Faster with ripple was refused when more than one clip followed: the second ripple pulled the
/// farther clips onto the nearer ones.
#[test]
fn faster_with_ripple_moves_later_clips_once() {
let mut s = Session::default();
let [(picture1, sound1), (picture2, sound2), (picture3, sound3)] = three_clips(&mut s);
let f = |n: i64| s.sequence_rate().tick_of(n);
let (f0, f24, f72, f120) = (f(0), f(24), f(72), f(120));
s.execute("clip.speedDuration", json!({"clips": [picture1.0], "speed": 200, "ripple": true})).unwrap();
s.active_sequence().unwrap().check().unwrap();
for (picture, sound, at) in [(picture1, sound1, (f0, f24)), (picture2, sound2, (f24, f72)), (picture3, sound3, (f72, f120))] {
assert_eq!((range(&s, picture), range(&s, sound)), (at, at));
}
}
/// A clip that is not in the sequence is an error and nothing changes, also next to one that is.
#[test]
fn speed_on_a_missing_clip_is_an_error() {
let mut s = Session::default();
let [_, (picture2, _), _] = three_clips(&mut s);
let before = s.project.clone();
let undo = s.history.undo.len();
assert!(s.execute("clip.speedDuration", json!({"clips": [999_999], "speed": 50, "ripple": true})).is_err());
assert!(s.execute("clip.speedDuration", json!({"clips": [picture2.0, 999_999], "speed": 50, "ripple": true})).is_err());
assert_eq!(*s.project, *before);
assert_eq!(s.history.undo.len(), undo);
}
/// Several clips in one call each ripple in turn, as before.
#[test]
fn speed_with_ripple_on_two_clips_ripples_each() {
let mut s = Session::default();
let [(picture1, sound1), (picture2, sound2), (picture3, sound3)] = three_clips(&mut s);
let f = |n: i64| s.sequence_rate().tick_of(n);
let (f0, f24, f48, f96) = (f(0), f(24), f(48), f(96));
s.execute("clip.speedDuration", json!({"clips": [picture1.0, picture2.0], "speed": 200, "ripple": true})).unwrap();
s.active_sequence().unwrap().check().unwrap();
for (picture, sound, at) in [(picture1, sound1, (f0, f24)), (picture2, sound2, (f24, f48)), (picture3, sound3, (f48, f96))] {
assert_eq!((range(&s, picture), range(&s, sound)), (at, at));
}
}
/// Without `ripple` nothing after the clip moves.
#[test]
fn speed_without_ripple_leaves_later_clips() {
let mut s = Session::default();
let [_, (picture2, sound2), (picture3, sound3)] = three_clips(&mut s);
let f = |n: i64| s.sequence_rate().tick_of(n);
let (f48, f72, f96, f144) = (f(48), f(72), f(96), f(144));
s.execute("clip.speedDuration", json!({"clips": [picture2.0], "speed": 200})).unwrap();
assert_eq!((range(&s, picture2), range(&s, sound2)), ((f48, f72), (f48, f72)));
assert_eq!((range(&s, picture3), range(&s, sound3)), ((f96, f144), (f96, f144)));
}
/// Linked Selection off and both the picture and its sound named: still one edit, one ripple.
#[test]
fn speed_with_ripple_on_a_named_picture_and_sound() {
let mut s = Session::default();
let [_, (picture2, sound2), (picture3, sound3)] = three_clips(&mut s);
let f = |n: i64| s.sequence_rate().tick_of(n);
let (f48, f144, f192) = (f(48), f(144), f(192));
s.execute("sequence.linkedSelection", json!({"on": false})).unwrap();
s.execute("clip.speedDuration", json!({"clips": [picture2.0, sound2.0], "speed": 50, "ripple": true})).unwrap();
assert_eq!((range(&s, picture2), range(&s, sound2)), ((f48, f144), (f48, f144)));
assert_eq!((range(&s, picture3), range(&s, sound3)), ((f144, f192), (f144, f192)));
}
/// Two clips of one track that were linked to each other (Clip ▸ Link) ripple one after the
/// other, as unlinked clips do.
#[test]
fn speed_with_ripple_on_linked_clips_of_one_track() {
let mut s = Session::default();
let [(picture1, _), (picture2, _), (picture3, _)] = three_clips(&mut s);
let f = |n: i64| s.sequence_rate().tick_of(n);
let (f0, f96, f192, f240) = (f(0), f(96), f(192), f(240));
s.execute("timeline.setTrack", json!({"track": "A1", "syncLock": false})).unwrap();
s.execute("sequence.linkedSelection", json!({"on": false})).unwrap();
s.execute("timeline.select", json!({"clips": [picture1.0, picture2.0]})).unwrap();
// both are linked to their sounds, so the first call unlinks them and the second links the two
s.execute("clip.link", json!({})).unwrap();
assert_eq!(s.execute("clip.link", json!({})).unwrap()["linked"], true);
s.execute("sequence.linkedSelection", json!({"on": true})).unwrap();
s.execute("clip.speedDuration", json!({"clips": [picture1.0], "speed": 50, "ripple": true})).unwrap();
s.active_sequence().unwrap().check().unwrap();
assert_eq!((range(&s, picture1), range(&s, picture2), range(&s, picture3)), ((f0, f96), (f96, f192), (f192, f240)));
}
/// A split edit: the sound runs 12 frames longer than its picture. Slower, the later clips move
/// by the sound's change, so nothing lands on the sound and the next clip stays in sync.
#[test]
fn speed_with_ripple_on_a_split_edit() {
let mut s = Session::default();
let [_, (picture2, sound2), (picture3, sound3)] = three_clips(&mut s);
let f = |n: i64| s.sequence_rate().tick_of(n);
let (f48, f144, f156, f168) = (f(48), f(144), f(156), f(168));
s.execute("sequence.linkedSelection", json!({"on": false})).unwrap();
s.execute("timeline.trim", json!({"clip": sound3.0, "edge": "in", "mode": "regular", "deltaFrames": 12})).unwrap();
s.execute("timeline.trim", json!({"clip": sound2.0, "edge": "out", "mode": "regular", "deltaFrames": 12})).unwrap();
s.execute("sequence.linkedSelection", json!({"on": true})).unwrap();
s.execute("clip.speedDuration", json!({"clips": [picture2.0], "speed": 50, "ripple": true})).unwrap();
s.active_sequence().unwrap().check().unwrap();
assert_eq!((range(&s, picture2), range(&s, sound2)), ((f48, f144), (f48, f168)), "picture 48 to 96 frames, sound 60 to 120");
assert_eq!((range(&s, picture3).0, range(&s, sound3).0), (f156, f168), "the next sound still starts 12 after its picture");
}
+6 -2
View File
@@ -476,13 +476,17 @@ fn open_in_source(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"item": item.0}))
}
/// Media properties of a file (cached per path).
/// Media properties of a file (cached per path). Only the container's index is read; a format
/// without a streaming reader is read whole only when small (see [`MediaPool::probe_file`]), so
/// browsing a folder of large AVI or WAV files doesn't read all of them (#157).
///
/// [`MediaPool::probe_file`]: crate::media_pool::MediaPool::probe_file
pub fn probe(s: &mut Session, path: &str) -> Option<MediaInfo> {
if let Some(v) = s.browser.probes.get(path) {
return v.clone();
}
let info = if kind_of(path).is_some_and(|k| matches!(k, "video" | "audio" | "image")) {
s.media.open_file(path, &*s.services).ok().map(|src| src.info().clone())
s.media.probe_file(path, &*s.services).ok().map(|src| src.info().clone())
} else {
None
};
+28
View File
@@ -248,3 +248,31 @@ fn path_helpers() {
assert_eq!(media_browser::parent("C:\\Media"), Some("C:\\".into()));
assert_eq!(media_browser::base_name("/home/me/Movies/"), "Movies");
}
/// #157: browsing a folder read every file no streaming reader takes (an AVI, a WAV) whole into
/// memory, just to show its properties or to find out it isn't supported. Large ones are now
/// refused after the head; small ones still show their properties; MP4 is read through its index.
#[cfg(any(unix, windows))]
#[test]
fn probing_large_unstreamable_files_does_not_read_them_whole() {
let dir = crate::media_test_util::tmp_dir("browser-probe-large");
// a 100 MB "AVI" (sparse: nothing is written past the header)
let avi = dir.join("camera.avi");
let mut head = vec![0u8; 64];
head[..4].copy_from_slice(b"RIFF");
head[8..12].copy_from_slice(b"AVI ");
std::fs::write(&avi, &head).unwrap();
std::fs::OpenOptions::new().write(true).open(&avi).unwrap().set_len(crate::media_pool::PROBE_WHOLE_FILE_MAX + 36 * 1024 * 1024).unwrap();
let wav = dir.join("voice.wav");
std::fs::write(&wav, filmcraft_media::wav::write_wav16(&[0.1; 9_600], 2, 48_000)).unwrap();
let mov = dir.join("clip.mov");
crate::media_test_util::make_movie(&mov, filmcraft_media::DemoScene::OceanSunset, 64, 36, 24);
let mut s = Session::default();
assert!(media_browser::probe(&mut s, &avi.to_string_lossy()).is_none());
assert_eq!(media_browser::probe(&mut s, &wav.to_string_lossy()).unwrap().audio.unwrap().channels, 2);
assert!(media_browser::probe(&mut s, &mov.to_string_lossy()).unwrap().video.is_some());
// importing is unchanged: it still opens files through the full path
let r = s.execute("file.import", json!({"paths": [wav.to_string_lossy()]})).unwrap();
assert_eq!(r["items"].as_array().unwrap().len(), 1);
let _ = std::fs::remove_dir_all(&dir);
}
+67 -3
View File
@@ -53,13 +53,18 @@ impl Default for MediaPool {
}
}
/// Cache key of a media clip's full-resolution reference ("" matches anything: generators and
/// sources inserted without a key).
/// Largest file [`MediaPool::probe_file`] reads whole when no streaming reader takes it (WAV,
/// MP3 and other byte-opened formats, or an unsupported container such as AVI).
pub const PROBE_WHOLE_FILE_MAX: u64 = 64 * 1024 * 1024;
/// Cache key of a media clip's full-resolution reference ("" matches anything: sources inserted
/// without a key). A generator's key holds its parameters, so a Color Matte whose color changes
/// (or comes back with undo) is generated again.
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}"),
MediaRef::Generator(_) => String::new(),
MediaRef::Generator(g) => format!("generator:{g:?}"),
}
}
@@ -127,6 +132,11 @@ impl MediaPool {
self.sources.write().unwrap_or_else(|e| e.into_inner()).insert(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(|e| e.into_inner()).insert(item, (key, src));
}
/// Cache a source opened from `path` for an item.
pub fn insert_file(&self, item: ItemId, path: &str, src: SharedSource) {
self.sources.write().unwrap_or_else(|e| e.into_inner()).insert(item, (format!("file:{path}"), src));
@@ -186,6 +196,16 @@ impl MediaPool {
self.open_bytes(&file_name(path), bytes.into())
}
/// Open a file to look at it (Media Browser properties and thumbnails), not to import it: a
/// format without a streaming reader is read whole only up to [`PROBE_WHOLE_FILE_MAX`] bytes
/// (#157). Hosts without random-access readers open the file as [`Self::open_file`] does.
pub fn probe_file(&self, path: &str, services: &dyn Services) -> Result<SharedSource, MediaError> {
let Some(r) = services.reader(path) else { return self.open_file(path, services) };
let r = r.map_err(|e| if e.kind() == std::io::ErrorKind::NotFound { MediaError::Offline(e.to_string()) } else { MediaError::Io(e.to_string()) })?;
let openers = self.openers.read().unwrap_or_else(|e| e.into_inner()).clone();
filmcraft_media::reader::open_reader_within(&file_name(path), r, &filmcraft_codecs::reader_openers(), &openers, PROBE_WHOLE_FILE_MAX)
}
/// Resolve (and cache) the source for a project item, using proxies when they are enabled.
pub fn source_for(&self, p: &Project, item: ItemId, services: &dyn Services) -> Option<SharedSource> {
self.resolve(p, item, services, self.use_proxies())
@@ -382,3 +402,47 @@ impl MediaSource for ProxySource {
self.proxy.audio(start, frames, sample_rate)
}
}
#[cfg(test)]
mod tests {
use super::*;
/// A host whose whole-file read fails: opening must go through the reader.
struct ReaderOnly(Arc<[u8]>);
impl Services for ReaderOnly {
fn read_file(&self, path: &str) -> std::io::Result<Vec<u8>> {
Err(std::io::Error::other(format!("{path}: read whole")))
}
fn write_file(&self, _path: &str, _data: &[u8]) -> std::io::Result<()> {
Ok(())
}
fn reader(&self, _path: &str) -> Option<std::io::Result<filmcraft_media::SharedReader>> {
Some(Ok(Arc::new(filmcraft_media::reader::MemReader(self.0.clone()))))
}
}
#[test]
fn open_file_prefers_the_hosts_reader() {
let wav = filmcraft_media::wav::write_wav16(&[0.0, 0.5, -0.5, 0.25], 2, 48_000);
let s = MediaPool::default().open_file("a.wav", &ReaderOnly(wav.into())).unwrap();
assert!(s.info().has_audio());
}
/// The desktop host reads media in place instead of loading every clip into memory.
#[cfg(any(unix, windows))]
#[test]
fn fs_services_open_media_through_a_file_reader() {
let dir = std::env::temp_dir().join(format!("filmcraft-pool-reader-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("a.wav");
let wav = filmcraft_media::wav::write_wav16(&[0.0, 0.5, -0.5, 0.25], 2, 48_000);
std::fs::write(&path, &wav).unwrap();
let p = path.to_string_lossy().to_string();
let r = crate::FsServices.reader(&p).expect("a reader").unwrap();
assert_eq!(r.len(), wav.len() as u64);
assert!(MediaPool::default().open_file(&p, &crate::FsServices).unwrap().info().has_audio());
let missing = dir.join("missing.wav").to_string_lossy().to_string();
assert!(matches!(MediaPool::default().open_file(&missing, &crate::FsServices), Err(MediaError::Offline(_))));
std::fs::remove_dir_all(&dir).unwrap();
}
}
+1 -1
View File
@@ -382,7 +382,7 @@ fn synchronize(s: &mut Session, p: &Value) -> Result<Value> {
// reference unit
let reference = if let Some(c) = u64_p(p, "reference").map(ClipId) {
units.iter().position(|u| u.members.contains(&c)).ok_or_else(|| bad(cmd, "`reference` is not among the clips"))?
} else if let Some(t) = track_p(s, p, "track") {
} else if let Some(t) = track_p(s, p, "track", cmd)? {
units
.iter()
.position(|u| u.members.iter().any(|m| q.track(t).is_some_and(|tr| tr.item(*m).is_some())))
+230
View File
@@ -0,0 +1,230 @@
//! Editing with nested sequences: the nest toggle ("Insert and overwrite sequences as nests or
//! individual clips"), a sequence as a source, Match Frame on a nest, and Reveal in Project.
//! Premiere's behaviour was observed in Premiere Pro 26.5.2.
use super::*;
use filmcraft_project::{TrackItem, TrackKind};
use filmcraft_time::TimeRange;
use serde_json::json;
fn demo() -> Session {
let mut s = Session::default();
s.execute("file.openDemoProject", json!({})).unwrap();
s
}
fn clips(s: &Session, kind: TrackKind, idx: usize) -> Vec<TrackItem> {
s.active_sequence().unwrap().tracks(kind)[idx].items.clone()
}
/// A subsequence of the first three V1 clips of the demo (with their sound and the transitions
/// between them), and a new empty sequence, which is left active.
fn source_and_empty(s: &mut Session) -> (ItemId, ItemId) {
let v1: Vec<u64> = clips(s, TrackKind::Video, 0).iter().take(3).map(|c| c.id.0).collect();
s.execute("timeline.select", json!({"clips": v1})).unwrap();
let source = ItemId(s.execute("sequence.makeSubsequence", json!({"name": "Source"})).unwrap()["sequence"].as_u64().unwrap());
let empty = ItemId(s.execute("file.newSequence", json!({"name": "Target"})).unwrap()["sequence"].as_u64().unwrap());
s.execute("sequence.open", json!({"item": empty.0})).unwrap();
(source, empty)
}
#[test]
fn the_nest_toggle_is_on_by_default_and_can_be_set() {
let mut s = demo();
assert!(!s.state.sequences_as_clips);
assert_eq!(s.execute("sequence.nestSequences", json!({})).unwrap()["nest"], false);
assert!(s.state.sequences_as_clips);
assert_eq!(s.execute("sequence.nestSequences", json!({})).unwrap()["nest"], true);
assert_eq!(s.execute("sequence.nestSequences", json!({"on": false})).unwrap()["nest"], false);
assert_eq!(s.execute("sequence.nestSequences", json!({"on": false})).unwrap()["nest"], false);
assert!(s.state.sequences_as_clips);
}
#[test]
fn with_the_toggle_on_a_sequence_edits_in_as_one_nest() {
let mut s = demo();
let (source, _) = source_and_empty(&mut s);
let r = s.execute("timeline.place", json!({"item": source.0, "seconds": 0.0})).unwrap();
assert_eq!(r["clips"].as_array().unwrap().len(), 2, "one picture and one sound clip");
let v1 = clips(&s, TrackKind::Video, 0);
assert_eq!(v1.len(), 1);
assert_eq!(v1[0].item, source);
}
#[test]
fn with_the_toggle_off_a_sequence_edits_in_as_its_clips_with_their_transitions() {
let mut s = demo();
let (source, _) = source_and_empty(&mut s);
let src = s.project.sequence(source).unwrap().clone();
let (src_v, src_a) = (src.video_tracks[0].clone(), src.audio_tracks[0].clone());
assert!(src_v.items.len() == 3 && !src_v.transitions.is_empty(), "the source has transitions to carry");
s.execute("sequence.nestSequences", json!({"on": false})).unwrap();
let undo = s.history.undo.len();
let at = s.sequence_rate().tick_of(48);
s.execute("timeline.place", json!({"item": source.0, "time": at.0})).unwrap();
assert_eq!(s.history.undo.len(), undo + 1, "one undo step");
let q = s.active_sequence().unwrap();
q.check().unwrap();
let (v, a) = (&q.video_tracks[0], &q.audio_tracks[0]);
// the same clips, at the same places from `at`, as copies with ids of their own
assert_eq!(v.items.len(), 3);
for (new, old) in v.items.iter().zip(&src_v.items).chain(a.items.iter().zip(&src_a.items)) {
assert_eq!((new.item, new.start, new.duration, new.source_in), (old.item, old.start + at, old.duration, old.source_in));
assert_ne!(new.id, old.id);
}
assert!(v.items.iter().all(|i| s.project.sequence(i.item).is_none()), "no nest");
// picture and sound stay linked pair by pair, with links of their own
for (pic, snd) in v.items.iter().zip(&a.items) {
assert!(pic.link.is_some() && pic.link == snd.link);
}
assert!(v.items.iter().zip(&src_v.items).all(|(n, o)| n.link != o.link));
// the transitions came along, between the copies
assert_eq!((v.transitions.len(), a.transitions.len()), (src_v.transitions.len(), src_a.transitions.len()));
for (new, old) in v.transitions.iter().zip(&src_v.transitions) {
assert_eq!((new.start, new.duration), (old.start + at, old.duration));
assert!(new.id != old.id && new.from.is_none_or(|c| v.item(c).is_some()) && new.to.is_none_or(|c| v.item(c).is_some()));
}
// the copies are what is selected, and the source sequence is untouched
assert_eq!(s.state.selection.len(), v.items.len() + a.items.len());
assert_eq!(s.project.sequence(source).unwrap(), &src);
}
#[test]
fn source_tracks_with_clips_go_to_consecutive_tracks_and_missing_tracks_are_added() {
let mut s = demo();
let (source, target) = source_and_empty(&mut s);
// in the source, put the third clip's picture on V3 (V2 stays empty)
s.execute("sequence.open", json!({"item": source.0})).unwrap();
let third = clips(&s, TrackKind::Video, 0)[2].clone();
s.execute("timeline.move", json!({"moves": [{"clip": third.id.0, "track": "V3", "time": third.start.0}], "linked": false})).unwrap();
assert_eq!(s.active_sequence().unwrap().video_tracks[2].items.len(), 1);
s.execute("sequence.open", json!({"item": target.0})).unwrap();
s.execute("sequence.nestSequences", json!({"on": false})).unwrap();
// dropped on V1: source V1 and V3 land on V1 and V2
s.execute("timeline.place", json!({"item": source.0, "track": "V1", "seconds": 0.0})).unwrap();
let q = s.active_sequence().unwrap();
assert_eq!((q.video_tracks[0].items.len(), q.video_tracks[1].items.len(), q.video_tracks[2].items.len()), (2, 1, 0));
assert_eq!(q.video_tracks[1].items[0].item, third.item);
// dropped on the top track, V3: the second lane needs a V4, which is added
assert_eq!(q.video_tracks.len(), 3);
s.execute("timeline.place", json!({"item": source.0, "track": "V3", "seconds": 60.0})).unwrap();
let q = s.active_sequence().unwrap();
q.check().unwrap();
assert_eq!(q.video_tracks.len(), 4);
assert_eq!((q.video_tracks[2].items.len(), q.video_tracks[3].items.len()), (2, 1));
assert_eq!(q.video_tracks[3].name, "Video 4");
// one undo removes the clips and the track again
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(s.active_sequence().unwrap().video_tracks.len(), 3);
}
#[test]
fn from_the_source_monitor_the_marked_part_of_a_sequence_is_edited_in() {
let mut s = demo();
let (source, _) = source_and_empty(&mut s);
let rate = s.sequence_rate();
let src_v = s.project.sequence(source).unwrap().video_tracks[0].clone();
// In inside the first clip, Out inside the second
let (mark_in, mark_out) = (src_v.items[0].start + rate.tick_of(12), src_v.items[1].start + rate.tick_of(23));
s.execute("source.open", json!({"item": source.0})).unwrap();
s.execute("project.setMarks", json!({"item": source.0, "in": mark_in.0, "out": mark_out.0})).unwrap();
let marked = TimeRange::from_bounds(mark_in, mark_out + rate.frame_duration());
// as a nest: one clip showing that part of the sequence
s.execute("source.overwrite", json!({})).unwrap();
let nest = clips(&s, TrackKind::Video, 0)[0].clone();
assert_eq!((nest.item, nest.source_in, nest.duration), (source, marked.start, marked.duration));
s.execute("edit.undo", json!({})).unwrap();
// as clips: the two clips the marks cut through, trimmed to them
s.execute("sequence.nestSequences", json!({"on": false})).unwrap();
s.set_playhead(Tick::ZERO);
s.execute("source.overwrite", json!({})).unwrap();
let v = clips(&s, TrackKind::Video, 0);
assert_eq!(v.len(), 2);
assert_eq!((v[0].start, v[0].source_in), (Tick::ZERO, src_v.items[0].source_in + rate.tick_of(12)));
assert_eq!(v[0].end(), v[1].start);
assert_eq!(v[1].end(), marked.duration);
assert_eq!(v[1].source_in, src_v.items[1].source_in);
s.active_sequence().unwrap().check().unwrap();
}
#[test]
fn a_sequence_can_be_edited_into_itself_as_clips_but_not_as_a_nest() {
let mut s = demo();
let main = s.state.active_sequence.unwrap();
let before = clips(&s, TrackKind::Video, 0).len();
assert!(s.execute("timeline.place", json!({"item": main.0, "seconds": 120.0})).is_err());
s.execute("sequence.nestSequences", json!({"on": false})).unwrap();
s.execute("timeline.place", json!({"item": main.0, "seconds": 120.0})).expect("its clips are just clips");
assert_eq!(clips(&s, TrackKind::Video, 0).len(), before * 2);
assert_eq!(s.project.nest_cycle(), None);
}
#[test]
fn match_frame_on_a_nest_loads_the_nested_sequence_at_the_frame_it_shows() {
let mut s = demo();
let rate = s.sequence_rate();
let v = clips(&s, TrackKind::Video, 0)[1].id;
s.execute("timeline.select", json!({"clips": [v.0]})).unwrap();
let r = s.execute("clip.nest", json!({"name": "Inner"})).unwrap();
let (nested, nest) = (ItemId(r["sequence"].as_u64().unwrap()), ClipId(r["clips"][0].as_u64().unwrap()));
let clip = |s: &Session| s.active_sequence().unwrap().find_item(nest).unwrap().1.clone();
// plain: 9 frames into the nest is 9 frames into its sequence
s.set_playhead(clip(&s).start + rate.tick_of(9));
s.execute("sequence.matchFrame", json!({})).unwrap();
assert_eq!((s.state.source_item, s.state.source_playhead), (Some(nested), rate.tick_of(9)));
// trimmed in by 5 frames: the same timeline frame now shows frame 9 still, 4 frames into the clip
s.execute("timeline.trim", json!({"clip": nest.0, "edge": "in", "deltaFrames": 5})).unwrap();
s.set_playhead(clip(&s).start + rate.tick_of(4));
s.execute("sequence.matchFrame", json!({})).unwrap();
assert_eq!(s.state.source_playhead, rate.tick_of(9));
// at double speed, 4 frames in is 8 frames further into the sequence
s.execute("timeline.select", json!({"clips": [nest.0]})).unwrap();
s.execute("clip.speedDuration", json!({"speed": 200.0})).unwrap();
s.set_playhead(clip(&s).start + rate.tick_of(4));
s.execute("sequence.matchFrame", json!({})).unwrap();
assert_eq!((s.state.source_item, s.state.source_playhead), (Some(nested), rate.tick_of(5 + 8)));
}
#[test]
fn reveal_in_project_selects_the_clips_item_and_asks_the_ui_to_show_it() {
let mut s = demo();
let v1 = clips(&s, TrackKind::Video, 0);
s.drain_events();
// the selected clip
s.execute("timeline.select", json!({"clips": [v1[2].id.0]})).unwrap();
assert_eq!(s.execute("clip.revealInProject", json!({})).unwrap()["item"], v1[2].item.0);
assert_eq!(s.state.project_selection, vec![v1[2].item]);
assert!(s.drain_events().iter().any(|e| matches!(e, Event::RevealInProject(i) if *i == v1[2].item)));
// a named clip
s.execute("clip.revealInProject", json!({"clip": v1[0].id.0})).unwrap();
assert_eq!(s.state.project_selection, vec![v1[0].item]);
// nothing selected: the clip under the playhead on a targeted track
s.execute("timeline.select", json!({"clips": []})).unwrap();
s.set_playhead(v1[3].start + Tick(v1[3].duration.0 / 2));
s.execute("clip.revealInProject", json!({})).unwrap();
assert_eq!(s.state.project_selection, vec![v1[3].item]);
// the sequence in the Timeline
let main = s.state.active_sequence.unwrap();
s.execute("sequence.revealInProject", json!({})).unwrap();
assert_eq!(s.state.project_selection, vec![main]);
assert!(s.drain_events().iter().any(|e| matches!(e, Event::RevealInProject(i) if *i == main)));
}
#[test]
fn mark_in_and_out_in_the_source_monitor_mark_a_sequence_like_a_clip() {
// marks on a sequence loaded in the Source Monitor used to be dropped silently
let mut s = demo();
let (source, _) = source_and_empty(&mut s);
let rate = s.sequence_rate();
s.execute("source.open", json!({"item": source.0})).unwrap();
s.execute("markers.markIn", json!({"target": "source", "time": rate.tick_of(10).0})).unwrap();
s.execute("markers.markOut", json!({"target": "source", "time": rate.tick_of(40).0})).unwrap();
let q = s.project.sequence(source).unwrap();
assert_eq!((q.mark_in, q.mark_out), (Some(rate.tick_of(10)), Some(rate.tick_of(40))));
// and can be cleared again
s.execute("project.setMarks", json!({"item": source.0, "in": null, "out": null})).unwrap();
let q = s.project.sequence(source).unwrap();
assert_eq!((q.mark_in, q.mark_out), (None, None));
}
+73
View File
@@ -0,0 +1,73 @@
//! Nests whose sequence is another size than the sequence they are in: how they come in, and
//! Scale to Frame Size / Fit to frame / Fill frame on them. Premiere's behaviour was observed in
//! Premiere Pro 26.5.2 (a 1280x720 nest in a 1920x1080 sequence).
use super::*;
use filmcraft_project::TrackItem;
use serde_json::json;
/// The demo's 1920x1080 sequence with a 1280x720 sequence nested on V3 after its last clip.
/// Returns the session and the nest's picture clip.
fn small_nest() -> (Session, ClipId) {
let mut s = Session::default();
s.execute("file.openDemoProject", json!({})).unwrap();
let main = s.state.active_sequence.unwrap();
assert_eq!((s.active_sequence().unwrap().settings.width, s.active_sequence().unwrap().settings.height), (1920, 1080));
let footage = s.active_sequence().unwrap().video_tracks[0].items[0].item;
let small = ItemId(s.execute("file.newSequence", json!({"name": "Small", "width": 1280, "height": 720})).unwrap()["sequence"].as_u64().unwrap());
s.execute("sequence.open", json!({"item": small.0})).unwrap();
s.execute("timeline.place", json!({"item": footage.0, "seconds": 0.0})).unwrap();
s.execute("sequence.open", json!({"item": main.0})).unwrap();
let r = s.execute("timeline.place", json!({"item": small.0, "track": "V3", "seconds": 120.0})).unwrap();
let nest = ClipId(r["clips"][0].as_u64().unwrap());
assert_eq!(s.active_sequence().unwrap().find_item(nest).unwrap().1.item, small);
(s, nest)
}
fn clip(s: &Session, id: ClipId) -> TrackItem {
s.active_sequence().unwrap().find_item(id).unwrap().1.clone()
}
fn motion(it: &TrackItem, param: &str) -> f64 {
it.effect("motion").unwrap().param(param).unwrap().value.as_f64().unwrap()
}
#[test]
fn a_nest_of_another_size_comes_in_at_its_own_size() {
let (s, nest) = small_nest();
let it = clip(&s, nest);
assert!((motion(&it, "scale") - 100.0).abs() < 1e-9 && !it.scale_to_frame);
assert_eq!(filmcraft_render::source_size(&s.project, it.item), Some((1280, 720)));
}
#[test]
fn fit_and_fill_frame_scale_a_nest_to_the_sequence() {
let (mut s, nest) = small_nest();
s.execute("timeline.select", json!({"clips": [nest.0]})).unwrap();
// 1280x720 into 1920x1080: 150% either way (the same shape)
s.execute("clip.fitToFrame", json!({})).unwrap();
assert!((motion(&clip(&s, nest), "scale") - 150.0).abs() < 1e-6);
s.execute("edit.undo", json!({})).unwrap();
assert!((motion(&clip(&s, nest), "scale") - 100.0).abs() < 1e-9);
s.execute("clip.fillFrame", json!({})).unwrap();
assert!((motion(&clip(&s, nest), "scale") - 150.0).abs() < 1e-6);
}
#[test]
fn scale_to_frame_size_on_a_nest_fills_the_frame_and_leaves_scale_alone() {
let (mut s, nest) = small_nest();
s.execute("timeline.select", json!({"clips": [nest.0]})).unwrap();
s.execute("clip.scaleToFrameSize", json!({})).unwrap();
let it = clip(&s, nest);
assert!(it.scale_to_frame && (motion(&it, "scale") - 100.0).abs() < 1e-9);
// the picture: the nest's corner is now the frame's corner
let provider = s.media.full_res_provider(s.project.clone(), s.services.clone());
let opts = filmcraft_render::RenderOptions { scale: 0.25, ..Default::default() };
let t = it.start + Tick(it.duration.0 / 2);
let filled = filmcraft_render::render_sequence(&s.project, s.state.active_sequence.unwrap(), t, opts, &provider);
assert!(filled.get(2, 2)[3] > 0.98 && filled.get(filled.w - 3, filled.h - 3)[3] > 0.98);
// a toggle: off again, the nest is back in the middle with nothing in the corners
s.execute("clip.scaleToFrameSize", json!({})).unwrap();
let centred = filmcraft_render::render_sequence(&s.project, s.state.active_sequence.unwrap(), t, opts, &provider);
assert!(centred.get(2, 2)[3] < 0.02 && centred.get(centred.w / 2, centred.h / 2)[3] > 0.98);
}
+525
View File
@@ -0,0 +1,525 @@
//! Nested sequences: a sequence can never contain itself, whichever
//! command is asked to put it there, and Nest… keeps what was selected.
use super::*;
use filmcraft_project::TrackKind;
use filmcraft_time::TimeRange;
use serde_json::json;
fn demo() -> Session {
let mut s = Session::default();
s.execute("file.openDemoProject", json!({})).unwrap();
s
}
fn clip_ids(s: &Session, kind: TrackKind, idx: usize) -> Vec<u64> {
s.active_sequence().unwrap().tracks(kind)[idx].items.iter().map(|i| i.id.0).collect()
}
/// Nest the second V1 clip of the active sequence; returns (outer sequence, nested sequence).
fn nest_one(s: &mut Session, name: &str) -> (ItemId, ItemId) {
let outer = s.state.active_sequence.unwrap();
let v = clip_ids(s, TrackKind::Video, 0)[1];
s.execute("timeline.select", json!({"clips": [v]})).unwrap();
let r = s.execute("clip.nest", json!({"name": name})).unwrap();
(outer, ItemId(r["sequence"].as_u64().unwrap()))
}
/// The command fails with the self-nesting message and changes nothing (project and undo history).
fn refused(s: &mut Session, command: &str, params: serde_json::Value) {
let (before, undo) = (s.project.clone(), s.history.undo.len());
let e = s.execute(command, params).expect_err(command).to_string();
assert!(e.contains("cannot be nested inside itself"), "{command}: {e}");
assert!(Arc::ptr_eq(&before, &s.project), "{command} left the project alone");
assert_eq!(s.history.undo.len(), undo, "{command} added no undo step");
assert_eq!(s.project.nest_cycle(), None);
}
#[test]
fn a_sequence_cannot_be_placed_in_itself() {
let mut s = demo();
let a = s.state.active_sequence.unwrap();
refused(&mut s, "timeline.place", json!({"item": a.0, "seconds": 1.0}));
refused(&mut s, "timeline.place", json!({"item": a.0, "seconds": 1.0, "insert": true}));
// from the Source monitor as well
s.execute("source.open", json!({"item": a.0})).unwrap();
refused(&mut s, "source.insert", json!({}));
refused(&mut s, "source.overwrite", json!({}));
}
#[test]
fn a_sequence_cannot_be_placed_in_a_sequence_it_contains() {
let mut s = demo();
let (outer, nested) = nest_one(&mut s, "Inner");
// outer holds Inner: Inner cannot take outer, nor itself
s.execute("sequence.open", json!({"item": nested.0})).unwrap();
refused(&mut s, "timeline.place", json!({"item": outer.0, "seconds": 0.0}));
refused(&mut s, "timeline.place", json!({"item": nested.0, "seconds": 0.0}));
// one level further: a third sequence that holds outer cannot go into Inner either
s.execute("sequence.open", json!({"item": outer.0})).unwrap();
let third = ItemId(s.execute("file.newSequence", json!({"name": "Third"})).unwrap()["sequence"].as_u64().unwrap());
s.execute("sequence.open", json!({"item": third.0})).unwrap();
s.execute("timeline.place", json!({"item": outer.0, "seconds": 0.0})).expect("a nest of a nest is fine");
s.execute("sequence.open", json!({"item": nested.0})).unwrap();
refused(&mut s, "timeline.place", json!({"item": third.0, "seconds": 0.0}));
// the other direction stays allowed
s.execute("sequence.open", json!({"item": third.0})).unwrap();
s.execute("timeline.place", json!({"item": nested.0, "seconds": 30.0})).expect("Inner may be used twice");
}
#[test]
fn pasting_a_nest_into_its_own_sequence_is_refused() {
let mut s = demo();
let (_, nested) = nest_one(&mut s, "Inner");
// copy the nest clip, open the nested sequence and paste it there
let nest = s.active_sequence().unwrap().video_tracks[0].items.iter().find(|i| i.item == nested).unwrap().id;
s.execute("timeline.select", json!({"clips": [nest.0]})).unwrap();
s.execute("edit.copy", json!({})).unwrap();
s.execute("sequence.open", json!({"item": nested.0})).unwrap();
refused(&mut s, "edit.paste", json!({}));
refused(&mut s, "edit.pasteInsert", json!({}));
}
#[test]
fn a_project_opened_with_a_cycle_can_still_be_edited_and_repaired() {
let mut s = demo();
let a = s.state.active_sequence.unwrap();
// what a damaged project file would hold: the sequence on its own track
let mut p = (*s.project).clone();
let rate = p.sequence(a).unwrap().settings.frame_rate;
let it = p.make_track_item(a, TrackKind::Video, Tick(900 * filmcraft_time::TICKS_PER_SECOND), TimeRange::new(Tick::ZERO, rate.tick_of(24)), rate).unwrap();
let bad = it.id;
p.sequence_mut(a).unwrap().video_tracks[0].items.push(it);
s.project = Arc::new(p);
assert_eq!(s.project.nest_cycle(), Some(a));
// unrelated edits still work
let first = clip_ids(&s, TrackKind::Video, 0)[0];
s.execute("timeline.select", json!({"clips": [first]})).unwrap();
s.execute("clip.enable", json!({})).expect("edits are not locked out");
// and removing the clip repairs it, after which the guard is back
s.execute("timeline.select", json!({"clips": [bad.0]})).unwrap();
s.execute("edit.clear", json!({})).unwrap();
assert_eq!(s.project.nest_cycle(), None);
refused(&mut s, "timeline.place", json!({"item": a.0, "seconds": 1.0}));
}
/// The first V1 transition that joins two clips: (transition, outgoing clip, incoming clip).
fn joining_transition(s: &Session) -> (filmcraft_project::Transition, ClipId, ClipId) {
let v1 = &s.active_sequence().unwrap().video_tracks[0];
let t = v1.transitions.iter().find(|t| t.from.is_some() && t.to.is_some()).expect("the demo has a transition between two clips").clone();
let (from, to) = (t.from.unwrap(), t.to.unwrap());
(t, from, to)
}
fn frame_at(s: &Session, t: Tick) -> filmcraft_render::Image {
let provider = s.media.full_res_provider(s.project.clone(), s.services.clone());
let opts = filmcraft_render::RenderOptions { scale: 0.25, ..Default::default() };
filmcraft_render::render_sequence(&s.project, s.state.active_sequence.unwrap(), t, opts, &provider)
}
#[test]
fn nest_keeps_transitions_track_names_and_channel_layouts() {
let mut s = demo();
let outer = s.state.active_sequence.unwrap();
s.edit_sequence("setup", |q, _, _| {
q.video_tracks[0].name = "Picture".into();
q.audio_tracks[0].name = "Dialogue".into();
q.audio_tracks[0].channels = filmcraft_project::AudioChannels::Mono;
Ok(())
})
.unwrap();
let (trn, from, to) = joining_transition(&s);
let mid = trn.start + Tick(trn.duration.0 / 2);
let before = frame_at(&s, mid);
let start = s.active_sequence().unwrap().find_item(from).unwrap().1.start;
let audio_transitions = s.active_sequence().unwrap().audio_tracks[0].transitions.len();
s.execute("timeline.select", json!({"clips": [from.0, to.0]})).unwrap();
let linked: Vec<ClipId> = s.state.selection.clone();
let nested = ItemId(s.execute("clip.nest", json!({"name": "Inner"})).unwrap()["sequence"].as_u64().unwrap());
let q = s.project.sequence(nested).unwrap();
q.check().unwrap();
// the transition came along, on the same track, at the same place relative to its clips
let inner = q.video_tracks[0].transitions.iter().find(|t| t.id == trn.id).expect("the transition is inside the nest");
assert_eq!((inner.start, inner.duration, inner.from, inner.to), (trn.start - start, trn.duration, Some(from), Some(to)));
// so did the one between the linked sound clips, if the demo has it
let inner_audio =
q.audio_tracks[0].transitions.iter().filter(|t| t.from.is_some_and(|c| linked.contains(&c)) && t.to.is_some_and(|c| linked.contains(&c))).count();
let outer_q = s.project.sequence(outer).unwrap();
assert_eq!(outer_q.audio_tracks[0].transitions.len() + inner_audio, audio_transitions, "audio transitions moved, none lost");
// tracks are laid out like the parent's
assert_eq!(q.video_tracks[0].name, "Picture");
assert_eq!(q.audio_tracks[0].name, "Dialogue");
assert_eq!(q.audio_tracks[0].channels, filmcraft_project::AudioChannels::Mono);
// and there are only as many as the nested clips need (Premiere: V1 + A1 here, not the parent's three each)
assert_eq!((q.video_tracks.len(), q.audio_tracks.len()), (1, 1));
// the parent no longer holds the transition, and shows the same picture through the nest
assert!(outer_q.video_tracks[0].transitions.iter().all(|t| t.id != trn.id));
outer_q.check().unwrap();
let after = frame_at(&s, mid);
assert_eq!((before.w, before.h), (after.w, after.h));
let worst = before.px.iter().zip(&after.px).map(|(a, b)| (a - b).abs()).fold(0f32, f32::max);
assert!(worst < 0.01, "the frame inside the transition is unchanged by nesting (worst channel difference {worst})");
}
#[test]
fn nest_leaves_transitions_to_clips_outside_the_selection_out() {
let mut s = demo();
let (trn, from, _to) = joining_transition(&s);
// only the outgoing clip is nested: the transition needs both, so it is not carried
s.execute("timeline.select", json!({"clips": [from.0]})).unwrap();
let nested = ItemId(s.execute("clip.nest", json!({"name": "Half"})).unwrap()["sequence"].as_u64().unwrap());
let q = s.project.sequence(nested).unwrap();
q.check().unwrap();
assert!(q.all_tracks().all(|t| t.transitions.iter().all(|t| t.id != trn.id)));
s.active_sequence().unwrap().check().unwrap();
}
/// Nest the 4th and 5th V1 clips (with their sound) as "Inner". Returns the nested sequence, the
/// nest's video clip in the outer sequence, and the two nested clips' ids and lengths.
fn nest_two(s: &mut Session) -> (ItemId, ClipId, [(ClipId, Tick); 2]) {
let v1 = &s.active_sequence().unwrap().video_tracks[0];
let pair = [(v1.items[3].id, v1.items[3].duration), (v1.items[4].id, v1.items[4].duration)];
s.execute("timeline.select", json!({"clips": [pair[0].0.0, pair[1].0.0]})).unwrap();
let nested = ItemId(s.execute("clip.nest", json!({"name": "Inner"})).unwrap()["sequence"].as_u64().unwrap());
let nest = s.active_sequence().unwrap().video_tracks[0].items.iter().find(|i| i.item == nested).unwrap().id;
(nested, nest, pair)
}
fn nest_clip(s: &Session, id: ClipId) -> filmcraft_project::TrackItem {
s.active_sequence().unwrap().find_item(id).unwrap().1.clone()
}
fn mix_at(s: &Session, t: Tick, frames: usize) -> filmcraft_frame::AudioBuffer {
let q = s.active_sequence().unwrap();
let sr = q.settings.sample_rate as i64;
let provider = s.media.full_res_provider(s.project.clone(), s.services.clone());
filmcraft_render::audio::mix_sequence(&s.project, q, t.to_units_floor(sr), frames, &provider)
}
#[test]
fn a_nest_keeps_its_length_when_its_sequence_gets_shorter() {
let mut s = demo();
let outer = s.state.active_sequence.unwrap();
let (nested, nest, [(_, first), (second_id, second)]) = nest_two(&mut s);
let whole = nest_clip(&s, nest);
assert_eq!(whole.duration, first + second);
assert_eq!(s.project.nest_overhang(&whole), None);
// remove the second clip inside the nest
s.execute("sequence.open", json!({"item": nested.0})).unwrap();
s.execute("timeline.select", json!({"clips": [second_id.0]})).unwrap();
s.execute("edit.clear", json!({})).unwrap();
assert_eq!(s.active_sequence().unwrap().duration(), first);
s.execute("sequence.open", json!({"item": outer.0})).unwrap();
// the nest is as long as before; its end is now past the contents
let c = nest_clip(&s, nest);
assert_eq!(c.range(), whole.range());
let empty = s.project.nest_overhang(&c).expect("the end of the nest is empty");
assert_eq!(empty, TimeRange::new(c.start + first, second));
// there it shows and plays what the sequence would without the nest
let t = empty.start + Tick(empty.duration.0 / 2);
let (with_frame, with_mix) = (frame_at(&s, t), mix_at(&s, t, 4800));
s.execute("timeline.select", json!({"clips": [nest.0]})).unwrap();
s.execute("clip.enable", json!({})).unwrap();
let (without_frame, without_mix) = (frame_at(&s, t), mix_at(&s, t, 4800));
assert!(with_frame.px == without_frame.px, "nothing to see past the contents");
assert_eq!(with_mix.channels, without_mix.channels, "nothing to hear past the contents");
s.execute("clip.enable", json!({})).unwrap();
// it cannot be trimmed out further, and trimming the empty part off leaves a sound nest
s.execute("timeline.trim", json!({"clip": nest.0, "edge": "out", "deltaFrames": 12})).ok();
assert!(nest_clip(&s, nest).duration <= whole.duration, "no more empty time is added");
let back = nest_clip(&s, nest).duration - first;
s.execute("timeline.trim", json!({"clip": nest.0, "edge": "out", "delta": -back.0})).unwrap();
let c = nest_clip(&s, nest);
assert_eq!(c.duration, first);
assert_eq!(s.project.nest_overhang(&c), None);
s.active_sequence().unwrap().check().unwrap();
}
#[test]
fn a_nest_can_be_trimmed_out_to_reveal_what_its_sequence_gained() {
let mut s = demo();
let outer = s.state.active_sequence.unwrap();
let rate = s.sequence_rate();
let (nested, nest, [(_, first), (_, second)]) = nest_two(&mut s);
let whole = nest_clip(&s, nest);
// make room after the nest in the outer sequence: drop everything that follows it on V1/A1
let later: Vec<u64> = s.active_sequence().unwrap().video_tracks[0].items.iter().filter(|i| i.start >= whole.end()).map(|i| i.id.0).collect();
s.execute("timeline.select", json!({"clips": later})).unwrap();
s.execute("edit.clear", json!({})).unwrap();
// add 48 frames of media to the end of the nested sequence
let media = s.project.items.values().find(|i| i.name == "Desert_Dunes.mp4").unwrap().id;
s.execute("sequence.open", json!({"item": nested.0})).unwrap();
s.execute("timeline.place", json!({"item": media.0, "time": (first + second).0, "duration": rate.tick_of(48).0})).unwrap();
assert_eq!(s.active_sequence().unwrap().duration(), first + second + rate.tick_of(48));
s.execute("sequence.open", json!({"item": outer.0})).unwrap();
// the nest did not grow by itself
assert_eq!(nest_clip(&s, nest).range(), whole.range());
// trimming reveals the new material, up to the end of the contents and no further
s.execute("timeline.trim", json!({"clip": nest.0, "edge": "out", "deltaFrames": 10})).unwrap();
assert_eq!(nest_clip(&s, nest).duration, whole.duration + rate.tick_of(10));
s.execute("timeline.trim", json!({"clip": nest.0, "edge": "out", "deltaFrames": 500})).ok();
let c = nest_clip(&s, nest);
assert_eq!(c.duration, whole.duration + rate.tick_of(48));
assert_eq!(s.project.nest_overhang(&c), None);
}
#[test]
fn the_outer_sequence_shows_changes_made_inside_a_nest() {
let mut s = demo();
let outer = s.state.active_sequence.unwrap();
let (nested, nest, [(first_id, first), _]) = nest_two(&mut s);
let t = nest_clip(&s, nest).start + Tick(first.0 / 2);
let before = frame_at(&s, t);
let revision = s.revision;
// disable the clip that is on screen, inside the nest
s.execute("sequence.open", json!({"item": nested.0})).unwrap();
s.execute("timeline.select", json!({"clips": [first_id.0]})).unwrap();
s.execute("clip.enable", json!({})).unwrap();
s.execute("sequence.open", json!({"item": outer.0})).unwrap();
assert_ne!(s.revision, revision, "frames cached for the outer sequence are stale");
let after = frame_at(&s, t);
assert!(before.px != after.px, "the outer sequence shows the nest's new contents");
}
// ---- Nest… as Premiere Pro 26.5.2 does it (observed in the app, 2026-10-06)
#[test]
fn after_nest_nothing_is_selected_and_the_new_sequence_is_selected_in_the_project() {
let mut s = demo();
let v = clip_ids(&s, TrackKind::Video, 0)[1];
s.execute("timeline.select", json!({"clips": [v]})).unwrap();
let r = s.execute("clip.nest", json!({"name": "Inner"})).unwrap();
let nested = ItemId(r["sequence"].as_u64().unwrap());
assert!(s.state.selection.is_empty());
assert_eq!(s.state.project_selection, vec![nested]);
// the result names the nest's clips: one picture and one sound clip, linked, where the clips were
let clips: Vec<ClipId> = r["clips"].as_array().unwrap().iter().map(|c| ClipId(c.as_u64().unwrap())).collect();
let q = s.active_sequence().unwrap();
let (vt, vc) = q.find_item(clips[0]).unwrap();
let (at, ac) = q.find_item(clips[1]).unwrap();
assert_eq!((vt, at), (q.video_tracks[0].id, q.audio_tracks[0].id));
assert!(vc.item == nested && ac.item == nested && vc.link.is_some() && vc.link == ac.link);
// each shows the nested sequence from its start, for the length of what was nested
let inner = s.project.sequence(nested).unwrap().duration();
assert_eq!((vc.source_in, vc.duration, ac.source_in, ac.duration), (Tick::ZERO, inner, Tick::ZERO, inner));
assert_eq!(clips.len(), 2);
}
/// Move the sound of V1 clip `n` alone to audio track `track` ("A3"), keeping its time.
fn move_sound(s: &mut Session, n: usize, track: &str) -> (filmcraft_project::TrackItem, filmcraft_project::TrackItem) {
let q = s.active_sequence().unwrap();
let picture = q.video_tracks[0].items[n].clone();
let sound = q.all_tracks().flat_map(|t| t.items.iter()).find(|i| i.id != picture.id && i.link == picture.link).unwrap().clone();
s.execute("timeline.move", json!({"moves": [{"clip": sound.id.0, "track": track, "time": sound.start.0}], "linked": false})).unwrap();
let sound = s.active_sequence().unwrap().find_item(sound.id).unwrap().1.clone();
(picture, sound)
}
fn nest_of(s: &mut Session, clips: &[ClipId], name: &str) -> (ItemId, Vec<ClipId>) {
s.execute("timeline.select", json!({"clips": clips.iter().map(|c| c.0).collect::<Vec<_>>()})).unwrap();
let r = s.execute("clip.nest", json!({"name": name})).unwrap();
(ItemId(r["sequence"].as_u64().unwrap()), r["clips"].as_array().unwrap().iter().map(|c| ClipId(c.as_u64().unwrap())).collect())
}
fn track_index(s: &Session, kind: TrackKind, clip: ClipId) -> usize {
let q = s.active_sequence().unwrap();
let (track, _) = q.find_item(clip).unwrap();
q.tracks(kind).iter().position(|t| t.id == track).unwrap()
}
#[test]
fn clips_on_two_video_tracks_with_their_sound_on_one_track_nest_as_a_linked_pair() {
let mut s = demo();
// two neighbouring V1 clips with their sound on A1; the second one's picture goes up to V2
let (first, second) = {
let v1 = &s.active_sequence().unwrap().video_tracks[0].items;
(v1[4].clone(), v1[5].clone())
};
s.execute("timeline.move", json!({"moves": [{"clip": second.id.0, "track": "V2", "time": second.start.0}], "linked": false})).unwrap();
assert_eq!((track_index(&s, TrackKind::Video, first.id), track_index(&s, TrackKind::Video, second.id)), (0, 1));
let (nested, clips) = nest_of(&mut s, &[first.id, second.id], "Stack");
assert_eq!(clips.len(), 2, "picture and sound");
let q = s.active_sequence().unwrap();
q.check().unwrap();
let (picture, sound) = (q.find_item(clips[0]).unwrap().1, q.find_item(clips[1]).unwrap().1);
assert!(picture.item == nested && sound.item == nested && picture.link.is_some() && picture.link == sound.link);
assert_eq!((track_index(&s, TrackKind::Video, clips[0]), track_index(&s, TrackKind::Audio, clips[1])), (0, 0));
// inside: the pictures on V1 and V2, both sounds on A1
let inner = s.project.sequence(nested).unwrap();
assert_eq!((inner.video_tracks.len(), inner.audio_tracks.len()), (2, 1));
assert!(inner.video_tracks[0].item(first.id).is_some() && inner.video_tracks[1].item(second.id).is_some());
assert_eq!(inner.audio_tracks[0].items.len(), 2);
}
#[test]
fn clips_with_their_sound_on_several_tracks_nest_as_picture_only_and_the_sound_stays() {
let mut s = demo();
// two neighbouring V1 clips; the second one's sound goes to A3
let first = s.active_sequence().unwrap().video_tracks[0].items[3].clone();
let first_sound = s.active_sequence().unwrap().audio_tracks[0].items.iter().find(|i| i.link == first.link).unwrap().clone();
let (second, second_sound) = move_sound(&mut s, 4, "A3");
assert_eq!(track_index(&s, TrackKind::Audio, second_sound.id), 2);
let (nested, clips) = nest_of(&mut s, &[first.id, second.id], "Picture");
let q = s.active_sequence().unwrap();
q.check().unwrap();
// one clip came back: the picture, unlinked, on V1
assert_eq!(clips.len(), 1);
let nest = q.find_item(clips[0]).unwrap().1;
assert!(nest.item == nested && nest.link.is_none());
assert_eq!(track_index(&s, TrackKind::Video, clips[0]), 0);
assert!(q.audio_tracks.iter().all(|t| t.items.iter().all(|i| i.item != nested)), "no sound clip for the nest");
// the sound is where it was, the same clips, no longer linked to a picture
for (sound, at) in [(&first_sound, 0), (&second_sound, 2)] {
let left = q.audio_tracks[at].item(sound.id).expect("the sound stays in the sequence");
assert_eq!((left.range(), left.link), (sound.range(), None));
}
// inside: both pictures on V1; copies of the sound, linked to their pictures, on A1 and A2
// (the tracks used follow A1 without the gap)
let inner = s.project.sequence(nested).unwrap();
inner.check().unwrap();
assert_eq!((inner.video_tracks.len(), inner.audio_tracks.len()), (1, 2));
for (track, sound, picture) in [(0, &first_sound, &first), (1, &second_sound, &second)] {
let copy = &inner.audio_tracks[track].items[0];
assert!(copy.id != sound.id && copy.item == sound.item && copy.link == picture.link, "track {track}");
}
}
#[test]
fn a_nest_whose_sound_track_is_taken_is_picture_only_and_moves_up_a_video_track() {
let mut s = demo();
// the first and third V1 clips, but not the second: the nest spans all three, and the second
// clip and its sound are in the way on V1 and A1
let (first, between, third) = {
let v1 = &s.active_sequence().unwrap().video_tracks[0].items;
(v1[0].clone(), v1[1].clone(), v1[2].clone())
};
let sounds: Vec<filmcraft_project::TrackItem> =
s.active_sequence().unwrap().audio_tracks[0].items.iter().filter(|i| i.link == first.link || i.link == third.link).cloned().collect();
let before = (*s.project).clone();
let (nested, clips) = nest_of(&mut s, &[first.id, third.id], "Around");
let q = s.active_sequence().unwrap();
q.check().expect("no two clips overlap on a track");
assert_eq!(clips.len(), 1, "picture only");
let nest = q.find_item(clips[0]).unwrap().1.clone();
assert!(nest.item == nested && nest.link.is_none());
// V1 still holds the clip in between, so the nest took the first track above that was free for its whole length
let index = track_index(&s, TrackKind::Video, clips[0]);
assert!(index > 0 && q.video_tracks[0].item(between.id).is_some());
let was = before.sequence(s.state.active_sequence.unwrap()).unwrap();
let free = |i: usize| was.video_tracks.get(i).is_none_or(|t| !t.items.iter().any(|x| x.range().overlaps(&nest.range())));
assert!(free(index) && (1..index).all(|i| !free(i)), "track {index}");
// the sound stays on A1
for sound in &sounds {
assert_eq!(q.audio_tracks[0].item(sound.id).map(|i| (i.range(), i.link)), Some((sound.range(), None)));
}
}
#[test]
fn sound_on_a_track_other_than_a1_keeps_an_empty_a1_in_the_nest() {
let mut s = demo();
// one clip whose sound is on A3: a linked nest with its sound still on A3
let (picture, sound) = move_sound(&mut s, 1, "A3");
let (nested, clips) = nest_of(&mut s, &[picture.id], "Third");
assert_eq!(clips.len(), 2);
assert_eq!((track_index(&s, TrackKind::Video, clips[0]), track_index(&s, TrackKind::Audio, clips[1])), (0, 2));
// inside: A1 is there and empty, the sound is on A2
let inner = s.project.sequence(nested).unwrap();
assert_eq!((inner.video_tracks.len(), inner.audio_tracks.len()), (1, 2));
assert!(inner.audio_tracks[0].items.is_empty());
assert!(inner.audio_tracks[1].item(sound.id).is_some());
}
/// The arrangement Premiere was probed with: the 4th V1 clip stays on V1 with its sound on
/// `sound_track`; the 5th and 6th clips' pictures go up to V2, unlinked from their sound. Nesting
/// the 4th and 6th leaves the 5th's picture on V2, a track the selection has a clip on, inside the
/// nest's span. Returns the clips to nest and the one in the way.
fn stacked(s: &mut Session, sound_track: &str) -> ([ClipId; 2], ClipId) {
let (first, between, last) = {
let v1 = &s.active_sequence().unwrap().video_tracks[0].items;
(v1[3].id, v1[4].clone(), v1[5].clone())
};
if sound_track != "A1" {
move_sound(s, 3, sound_track);
}
for clip in [&between, &last] {
s.execute("timeline.select", json!({"clips": [clip.id.0]})).unwrap();
s.execute("clip.link", json!({})).unwrap();
s.execute("timeline.move", json!({"moves": [{"clip": clip.id.0, "track": "V2", "time": clip.start.0}], "linked": false})).unwrap();
}
assert_eq!((track_index(s, TrackKind::Video, between.id), track_index(s, TrackKind::Video, last.id)), (1, 1));
([first, last.id], between.id)
}
#[test]
fn a_clip_sharing_a_track_with_the_selection_pushes_the_nest_above_it_when_the_sound_is_on_a_higher_track() {
// sound on A3 (free): a linked nest, on V3 because V2 holds another clip and is numbered below the sound's track
let mut s = demo();
let (picked, in_the_way) = stacked(&mut s, "A3");
let (nested, clips) = nest_of(&mut s, &picked, "Above");
assert_eq!(clips.len(), 2, "linked: the sound track is free");
assert_eq!((track_index(&s, TrackKind::Video, clips[0]), track_index(&s, TrackKind::Audio, clips[1])), (2, 2));
let q = s.active_sequence().unwrap();
q.check().unwrap();
assert!(q.video_tracks[0].items.iter().all(|i| !i.range().overlaps(&q.find_item(clips[0]).unwrap().1.range())), "V1 was free all along");
assert_eq!(track_index(&s, TrackKind::Video, in_the_way), 1);
assert_eq!(s.project.sequence(nested).unwrap().video_tracks.len(), 2);
}
#[test]
fn a_clip_on_a_selected_track_numbered_at_or_above_the_sound_track_does_not_push_the_nest() {
// sound on A2 (taken by the score, so picture only): V2 is not below the sound's track, the nest stays on V1
let mut s = demo();
let (picked, in_the_way) = stacked(&mut s, "A2");
let (_, clips) = nest_of(&mut s, &picked, "Second");
assert_eq!(clips.len(), 1, "picture only: A2 is taken");
assert_eq!(track_index(&s, TrackKind::Video, clips[0]), 0);
assert_eq!(track_index(&s, TrackKind::Video, in_the_way), 1);
s.active_sequence().unwrap().check().unwrap();
// sound on A1 (taken by the clip in between's sound): the same
let mut s = demo();
let (picked, _) = stacked(&mut s, "A1");
let (_, clips) = nest_of(&mut s, &picked, "First");
assert_eq!(clips.len(), 1);
assert_eq!(track_index(&s, TrackKind::Video, clips[0]), 0);
s.active_sequence().unwrap().check().unwrap();
}
#[test]
fn a_nest_with_no_track_to_go_on_gets_a_new_one() {
// as the first case, with V3 taken as well: a fourth video track is added for the nest
let mut s = demo();
let (picked, _) = stacked(&mut s, "A3");
let (overlay, at) = {
let q = s.active_sequence().unwrap();
(q.video_tracks[1].items[0].id, q.find_item(picked[0]).unwrap().1.start)
};
s.execute("timeline.move", json!({"moves": [{"clip": overlay.0, "track": "V3", "time": at.0}], "linked": false})).unwrap();
assert_eq!(track_index(&s, TrackKind::Video, overlay), 2);
let tracks = s.active_sequence().unwrap().video_tracks.len();
let (_, clips) = nest_of(&mut s, &picked, "Top");
let q = s.active_sequence().unwrap();
q.check().unwrap();
assert_eq!((tracks, q.video_tracks.len()), (3, 4));
assert_eq!(track_index(&s, TrackKind::Video, clips[0]), 3);
// one undo takes the nest and its track away again
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(s.active_sequence().unwrap().video_tracks.len(), 3);
}
#[test]
fn make_subsequence_loads_the_new_sequence_in_the_source_monitor() {
let mut s = demo();
let outer = s.state.active_sequence.unwrap();
let v = clip_ids(&s, TrackKind::Video, 0)[1];
s.execute("timeline.select", json!({"clips": [v]})).unwrap();
let sub = ItemId(s.execute("sequence.makeSubsequence", json!({})).unwrap()["sequence"].as_u64().unwrap());
assert_eq!(s.state.source_item, Some(sub));
assert_eq!(s.state.project_selection, vec![sub]);
// it is not opened in the Timeline, and the selection is left alone
assert_eq!(s.state.active_sequence, Some(outer));
assert!(!s.state.open_sequences.contains(&sub));
assert!(s.state.selection.contains(&ClipId(v)));
assert!(s.drain_events().iter().any(|e| matches!(e, Event::OpenSource(i) if *i == sub)));
}
+27
View File
@@ -21,6 +21,15 @@ pub fn decode_json() -> Value {
"draftFrames": g.draft,
"h264Threads": filmcraft_codecs::video::h264_threads(),
"evicted": g.evicted,
// sources that hold a decoder right now (idle ones give theirs up beyond a cap)
"liveDecoders": filmcraft_codecs::live_decoders(),
// decoded frames all sources hold, and the budget idle sources are trimmed to
"cacheMB": filmcraft_codecs::cached_bytes() as f64 / 1e6,
"cacheBudgetMB": filmcraft_codecs::FRAME_BUDGET as f64 / 1e6,
// plane buffers of evicted frames waiting for the next decoded pictures, and how many
// planes were decoded into a recycled buffer
"planePoolMB": filmcraft_frame::pool::stats().idle_bytes as f64 / 1e6,
"planesReused": filmcraft_frame::pool::stats().reused,
"decodeMs": g.decode_ns as f64 / 1e6,
"decodeMsPerSample": g.decode_ms_per_sample(),
"framesDecoded": g.frames,
@@ -28,6 +37,8 @@ pub fn decode_json() -> Value {
// hardware decoders created, streams handed to software up front, mid-stream fallbacks.
"hardware": {
"enabled": filmcraft_codecs::hw::hardware_decoding(),
// the OS decoder backend registered at startup (null where there is none)
"backend": filmcraft_codecs::hw::hw_backend(),
"frames": hw.frames,
"softwareFrames": g.frames.saturating_sub(hw.frames),
"sessions": hw.sessions,
@@ -37,11 +48,18 @@ pub fn decode_json() -> Value {
})
}
/// Export counters: pictures encoded by hardware encoders, sessions, declined requests.
pub fn export_json() -> Value {
let hw = filmcraft_export::hw_encode_stats();
json!({"hardware": {"frames": hw.frames, "sessions": hw.sessions, "declined": hw.declined}})
}
/// The engine's `perf.stats`.
pub fn stats(s: &Session) -> Value {
let running = s.jobs.iter().filter(|j| j.result.lock().map(|r| r.is_none()).unwrap_or(false)).count();
json!({
"decode": decode_json(),
"export": export_json(),
"media": {"openSources": s.media.open_sources()},
"jobs": {"total": s.jobs.len(), "running": running},
})
@@ -71,6 +89,11 @@ mod tests {
"decodeMs",
"decodeMsPerSample",
"framesDecoded",
"liveDecoders",
"cacheMB",
"cacheBudgetMB",
"planePoolMB",
"planesReused",
] {
assert!(v["decode"][k].is_number(), "decode.{k} in {v}");
}
@@ -78,6 +101,10 @@ mod tests {
assert!(v["decode"]["hardware"][k].is_number(), "decode.hardware.{k} in {v}");
}
assert!(v["decode"]["hardware"]["enabled"].is_boolean());
assert!(v["decode"]["hardware"]["backend"].is_null() || v["decode"]["hardware"]["backend"].is_string());
for k in ["frames", "sessions", "declined"] {
assert!(v["export"]["hardware"][k].is_number(), "export.hardware.{k} in {v}");
}
assert!(v["media"]["openSources"].is_number());
assert_eq!(v["jobs"]["running"], json!(0));
assert_eq!(s.history.undo.len(), undo, "a query adds no undo step");
+9
View File
@@ -17,6 +17,7 @@
//! | `project.freeform.saveArrangement` / `.restoreArrangement` / `.arrangements` / `.deleteArrangement` | saved arrangements |
//! | `project.freeform.options` | Freeform View Options… (grid, snap, names, durations) |
//! | `project.renameBin` | rename a bin (inline rename, undoable) |
//! | `project.selectAll` / `project.deselectAll` | select every item in the project / clear the Project panel selection (Cmd+A / Cmd+Shift+A with the panel focused) |
use std::collections::BTreeMap;
@@ -1222,5 +1223,13 @@ pub(crate) fn commands() -> Vec<CommandSpec> {
freeform_options,
),
c("project.renameBin", "Rename Bin", r#"{"bin":binId,"name":str}"#, always, rename_bin),
c("project.selectAll", "Select All Project Items", "{}", always, |s, _| {
s.state.project_selection = s.project.items.keys().copied().collect();
Ok(json!({"selected": s.state.project_selection.len()}))
}),
c("project.deselectAll", "Deselect All Project Items", "{}", always, |s, _| {
s.state.project_selection.clear();
Ok(Value::Null)
}),
]
}
+19
View File
@@ -286,3 +286,22 @@ fn usage_counts_sequence_uses() {
assert_eq!(text, (if v > 0 { v } else { a }).to_string());
assert!(!matches!(it.kind, ItemKind::Graphic { .. }));
}
#[test]
fn select_all_selects_every_project_item() {
let mut s = demo();
assert!(s.project.items.len() >= 3);
s.state.project_selection.clear();
let r = s.execute("project.selectAll", json!({})).unwrap();
assert_eq!(r["selected"].as_u64(), Some(s.project.items.len() as u64));
assert_eq!(s.state.project_selection.len(), s.project.items.len());
assert!(s.project.items.keys().all(|i| s.state.project_selection.contains(i)));
s.execute("project.deselectAll", json!({})).unwrap();
assert!(s.state.project_selection.is_empty());
// the timeline Select All still selects timeline clips and leaves the Project panel alone
s.execute("project.selectAll", json!({})).unwrap();
let before = s.state.project_selection.clone();
s.execute("edit.selectAll", json!({})).unwrap();
assert!(!s.state.selection.is_empty());
assert_eq!(s.state.project_selection, before);
}
+42
View File
@@ -401,3 +401,45 @@ fn system_report_lists_the_build() {
assert!(r["decoders"].as_array().unwrap().iter().any(|d| d.as_str().unwrap().contains("H.264")));
assert_eq!(r["exportFormats"].as_array().unwrap().len(), filmcraft_export::Format::ALL.len());
}
#[test]
fn clear_deletes_a_bin_with_everything_in_it() {
let mut s = demo();
let before = s.project.items.len();
let outer = s.execute("file.newBin", json!({"name": "Old footage"})).unwrap()["bin"].as_u64().unwrap();
let inner = s.execute("file.newBin", json!({"name": "Inside", "parent": outer})).unwrap()["bin"].as_u64().unwrap();
let empty = s.execute("file.newBin", json!({"name": "Empty"})).unwrap()["bin"].as_u64().unwrap();
let ocean = item_named(&s, "Ocean_Sunset.mp4");
s.execute("project.moveToBin", json!({"items": [ocean.0], "bin": inner})).unwrap();
let dunes = item_named(&s, "Desert_Dunes.mp4");
let select = |s: &mut Session| s.execute("project.select", json!({"items": [dunes.0]})).unwrap();
select(&mut s);
// an empty bin, by its id: gone, nothing else touched
let r = s.execute("project.delete", json!({"items": [empty]})).unwrap();
assert_eq!(r, json!({"items": 0, "bins": 1}));
assert!(s.project.root.find_bin(filmcraft_project::BinId(empty)).is_none());
assert_eq!(s.project.items.len(), before);
// a bin holding a sub-bin holding a clip: all three go
select(&mut s);
let r = s.execute("project.delete", json!({"items": [outer]})).unwrap();
assert_eq!(r, json!({"items": 1, "bins": 1}));
assert!(s.project.root.find_bin(filmcraft_project::BinId(outer)).is_none());
assert!(s.project.root.find_bin(filmcraft_project::BinId(inner)).is_none());
assert!(s.project.item(ocean).is_none());
assert_eq!(s.project.items.len(), before - 1);
// undo puts the bins and the clip back where they were
s.execute("edit.undo", json!({})).unwrap();
assert!(s.project.root.find_bin(filmcraft_project::BinId(inner)).is_some());
assert_eq!(s.project.root.parent_of(ocean), Some(filmcraft_project::BinId(inner)));
// the clip, its bin and the bin around it all named: each counted once
select(&mut s);
let r = s.execute("project.delete", json!({"items": [ocean.0, inner, outer]})).unwrap();
assert_eq!(r, json!({"items": 1, "bins": 1}));
assert_eq!(s.project.items.len(), before - 1);
s.execute("edit.undo", json!({})).unwrap();
// the project's own top bin is never cleared
let root = s.project.root.id.0;
select(&mut s);
s.execute("project.delete", json!({"items": [root]})).unwrap();
assert_eq!(s.project.items.len(), before);
}
+6
View File
@@ -342,6 +342,12 @@ fn apply(s: &mut Session, plans: Vec<Plan>, align_timecode: bool, label: &str) -
m.info = info.clone();
}
proj.shift_media_time(p.item, shift);
if p.cand.info.is_some() {
// The item's size is now the file's own. Clips that came from an interchange import
// while the file was missing still have an "auto" (NaN) anchor waiting for it:
// centre it in the real picture. Points that are numbers are not touched.
proj.resolve_placed_auto_points(|_| true, |source| source.id == p.item);
}
}
Ok(())
})?;
+32
View File
@@ -145,3 +145,35 @@ fn make_offline_shows_the_slate_until_relinked() {
assert_eq!(frame_rgba(&mut s, 3, 1.0), online);
let _ = std::fs::remove_dir_all(&root);
}
// Regression test for issue #110: after `file.import` re-imports a file at a path the project
// already listed as offline, `s.offline.missing` must drop that item so the slate and the
// "Media missing" badge clear without reopening the project. Before the fix (the patch in
// `file.import` that calls `crate::relink::refresh(s)`), the slate stayed stale until reopen
// or per-item relink.
#[test]
fn reimport_clears_offline_list_after_path_resolves() {
let root = tmp_dir("relink-reimport");
let (path, items) = saved_project(&root);
let a = root.join("Media/a.mov");
// Delete a.mov so the saved project now points at a missing file, then reopen:
// `on_open` → `refresh` → `scan` registers items[0] as missing.
let online = frame_rgba(&mut open(&path), 3, 1.0);
std::fs::remove_file(&a).unwrap();
let mut s = open(&path);
assert!(s.offline.missing.contains(&items[0]), "setup: a.mov missing on reopen");
assert_ne!(frame_rgba(&mut s, 3, 1.0), online, "setup: the slate shows while a.mov is missing");
// Recreate the file at the exact path the project stores, then import. `file.import`
// must drop items[0] from `s.offline.missing`. Without the fix, the entry stays stale
// and the user has to reopen or `media.relink` each item.
make_movie(&a, DemoScene::Aurora, W, H, 12);
s.execute("file.import", json!({"paths": [a.to_string_lossy()]})).unwrap();
assert!(!s.offline.missing.contains(&items[0]), "issue #110 — file.import did not refresh s.offline.missing (still contains {:?})", s.offline.missing);
assert_eq!(s.execute("media.findMissing", json!({})).unwrap()["missing"].as_array().unwrap().len(), 0);
// and the monitors show the file again, not the cached slate
assert_eq!(frame_rgba(&mut s, 3, 1.0), online);
let _ = std::fs::remove_dir_all(&root);
}
+138
View File
@@ -0,0 +1,138 @@
//! `edit.rippleDelete` on a clip whose sound edge was split (a J or an L cut): the clip and its
//! sound go, and the later clips move up by one amount on every track.
use filmcraft_project::ClipId;
use filmcraft_time::Tick;
use serde_json::json;
use crate::Session;
fn range(s: &Session, c: ClipId) -> (Tick, Tick) {
s.active_sequence().unwrap().find_item(c).map(|(_, i)| (i.start, i.end())).unwrap()
}
/// Four 48-frame clips in a row, pictures on V1 and their linked sounds on A1: [(picture, sound); 4].
fn four_clips(s: &mut Session) -> [(ClipId, ClipId); 4] {
s.execute("file.openDemoProject", json!({})).unwrap();
s.execute("file.newSequence", json!({"name": "Split edits", "video": 1, "audio": 1})).unwrap();
let rate = s.sequence_rate();
let item = s.project.items.values().find(|i| i.has_video() && i.has_audio() && i.as_media().is_some()).map(|i| i.id).unwrap();
for n in 0..4 {
s.execute("timeline.place", json!({"item": item.0, "frame": 48 * n, "sourceIn": rate.tick_of(48).0, "duration": rate.tick_of(48).0})).unwrap();
}
let q = s.active_sequence().unwrap();
[0, 1, 2, 3].map(|n| (q.video_tracks[0].items[n].id, q.audio_tracks[0].items[n].id))
}
/// Move one sound edge alone, as a split edit does (Linked Selection off for the trim).
fn trim_sound(s: &mut Session, sound: ClipId, edge: &str, frames: i64) {
s.execute("sequence.linkedSelection", json!({"on": false})).unwrap();
s.execute("timeline.trim", json!({"clip": sound.0, "edge": edge, "mode": "regular", "deltaFrames": frames})).unwrap();
s.execute("sequence.linkedSelection", json!({"on": true})).unwrap();
}
/// The second clip's sound starts 12 frames early (a J cut). Ripple delete was refused: the picture
/// and the sound have different ranges, each range was closed on its own, and the clips after the
/// next one were moved up twice, onto it. With a single clip after it the delete went through and
/// a later marker moved twice.
#[test]
fn ripple_delete_of_a_j_cut_clip_closes_one_gap() {
let mut s = Session::default();
let [(_, sound1), (picture2, sound2), (picture3, sound3), (picture4, sound4)] = four_clips(&mut s);
let f = |n: i64| s.sequence_rate().tick_of(n);
let (f36, f48, f72, f96, f120, f144) = (f(36), f(48), f(72), f(96), f(120), f(144));
trim_sound(&mut s, sound1, "out", -12);
trim_sound(&mut s, sound2, "in", -12);
assert_eq!((range(&s, picture2).0, range(&s, sound2).0), (f48, f36), "the sound leads by 12 frames");
s.state.ripple_sequence_markers = true;
let marker = s.execute("markers.add", json!({"time": f120.0, "name": "Later"})).unwrap()["marker"].clone();
let before = s.project.clone();
s.execute("edit.rippleDelete", json!({"clips": [picture2.0]})).unwrap();
let q = s.active_sequence().unwrap();
q.check().unwrap();
assert!(q.find_item(picture2).is_none() && q.find_item(sound2).is_none(), "the clip and its sound are gone");
assert_eq!(range(&s, picture3), (f48, f96), "the next picture closes the gap");
assert_eq!(range(&s, sound3), (f48, f96), "and its sound moves up by the same amount");
assert_eq!((range(&s, picture4), range(&s, sound4)), ((f96, f144), (f96, f144)), "the clip after it moves up once");
assert_eq!(range(&s, sound1).1, f36, "the sound before is untouched");
assert_eq!(q.duration(), f144);
let at = q.markers.iter().find(|m| json!(m.id.0) == marker).map(|m| m.start);
assert_eq!(at, Some(f72), "a later marker moves up once, by the same amount");
let after = s.project.clone();
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(*s.project, *before, "one undo step restores it");
s.execute("edit.redo", json!({})).unwrap();
assert_eq!(*s.project, *after);
}
/// The second clip's sound runs 12 frames under the next picture (an L cut).
#[test]
fn ripple_delete_of_an_l_cut_clip_keeps_the_next_clip_in_sync() {
let mut s = Session::default();
let [_, (picture2, sound2), (picture3, sound3), (picture4, sound4)] = four_clips(&mut s);
let f = |n: i64| s.sequence_rate().tick_of(n);
let (f48, f60, f96, f108, f144) = (f(48), f(60), f(96), f(108), f(144));
trim_sound(&mut s, sound3, "in", 12);
trim_sound(&mut s, sound2, "out", 12);
assert_eq!((range(&s, picture2).1, range(&s, sound2).1), (f96, f108), "the sound runs on by 12 frames");
s.execute("edit.rippleDelete", json!({"clips": [picture2.0]})).unwrap();
let q = s.active_sequence().unwrap();
q.check().unwrap();
assert!(q.find_item(sound2).is_none());
assert_eq!(range(&s, picture3), (f48, f96));
assert_eq!(range(&s, sound3), (f60, f96), "the next sound still starts 12 frames after its picture");
assert_eq!((range(&s, picture4), range(&s, sound4)), ((f96, f144), (f96, f144)));
}
/// A straight cut is unchanged: the picture and its sound share one range and close one gap.
#[test]
fn ripple_delete_of_a_straight_cut_clip_is_unchanged() {
let mut s = Session::default();
let [_, (picture2, _), (picture3, sound3), _] = four_clips(&mut s);
let f = |n: i64| s.sequence_rate().tick_of(n);
let (f48, f96) = (f(48), f(96));
s.execute("edit.rippleDelete", json!({"clips": [picture2.0]})).unwrap();
assert_eq!((range(&s, picture3), range(&s, sound3)), ((f48, f96), (f48, f96)));
}
/// Two neighbours deleted together, with a split edit between them (the first one's sound runs 12
/// frames under the second picture): one gap closes, the size of both clips.
#[test]
fn ripple_delete_of_two_neighbours_with_a_split_edit_between_them() {
let mut s = Session::default();
let [_, (picture2, sound2), (picture3, sound3), (picture4, sound4)] = four_clips(&mut s);
let f = |n: i64| s.sequence_rate().tick_of(n);
let (f48, f96) = (f(48), f(96));
trim_sound(&mut s, sound3, "in", 12);
trim_sound(&mut s, sound2, "out", 12);
s.execute("edit.rippleDelete", json!({"clips": [picture2.0, picture3.0]})).unwrap();
let q = s.active_sequence().unwrap();
q.check().unwrap();
assert!([picture2, sound2, picture3, sound3].iter().all(|c| q.find_item(*c).is_none()));
assert_eq!((range(&s, picture4), range(&s, sound4)), ((f48, f96), (f48, f96)), "the clip after them closes the whole gap");
}
/// Straight cuts with the sounds on alternating audio tracks: deleting two neighbours closes the
/// whole gap, as it did before.
#[test]
fn ripple_delete_of_two_neighbours_with_sounds_on_alternating_tracks() {
let mut s = Session::default();
s.execute("file.openDemoProject", json!({})).unwrap();
s.execute("file.newSequence", json!({"name": "Alternating", "video": 1, "audio": 2})).unwrap();
let rate = s.sequence_rate();
let item = s.project.items.values().find(|i| i.has_video() && i.has_audio() && i.as_media().is_some()).map(|i| i.id).unwrap();
let mut pictures = Vec::new();
for n in 0..4 {
let track = if n % 2 == 0 { "A1" } else { "A2" };
let r = s.execute("timeline.place", json!({"item": item.0, "audioTrack": track, "frame": 48 * n, "duration": rate.tick_of(48).0})).unwrap();
pictures.push(ClipId(r["clips"][0].as_u64().unwrap()));
}
s.execute("edit.rippleDelete", json!({"clips": [pictures[1].0, pictures[2].0]})).unwrap();
let q = s.active_sequence().unwrap();
q.check().unwrap();
assert_eq!(range(&s, pictures[3]), (rate.tick_of(48), rate.tick_of(96)));
assert_eq!(q.audio_tracks[1].items.iter().map(|i| i.range()).collect::<Vec<_>>(), vec![q.video_tracks[0].items[1].range()], "its sound moved with it");
assert_eq!(q.duration(), rate.tick_of(96));
}
+9 -2
View File
@@ -57,7 +57,7 @@ pub(crate) fn commands() -> Vec<CommandSpec> {
&["Sequence"],
None,
r#"{"track":"mix"|"A1"|id?,"language":"en|auto"?,"diarize":bool?,"maxSpeakers":n?,"model":str?}"#,
has_audio_clips,
can_transcribe_sequence,
transcribe,
),
spec(
@@ -105,6 +105,13 @@ fn has_audio_clips(s: &Session) -> std::result::Result<(), String> {
if q.audio_tracks.iter().any(|t| !t.items.is_empty()) { Ok(()) } else { Err("the sequence has no audio clips".into()) }
}
/// Transcribe Sequence runs `transcript.generate`: disabled like it in a build without
/// speech-to-text (#97), and when the sequence has no sound.
fn can_transcribe_sequence(s: &Session) -> std::result::Result<(), String> {
crate::transcript::can_transcribe(s)?;
has_audio_clips(s)
}
fn has_caption_track(s: &Session) -> std::result::Result<(), String> {
has_seq(s)?;
if s.active_sequence().is_some_and(|q| !q.caption_tracks.is_empty()) { Ok(()) } else { Err("the sequence has no caption track".into()) }
@@ -225,7 +232,7 @@ fn transcribe(s: &mut Session, p: &Value) -> Result<Value> {
let track = match p.get("track") {
None => None,
Some(Value::String(t)) if t.eq_ignore_ascii_case("mix") => None,
Some(_) => Some(crate::commands::track_p(s, p, "track").ok_or_else(|| bad("sequence.transcribe", "unknown `track`"))?),
Some(_) => Some(crate::commands::track_p(s, p, "track", "sequence.transcribe")?.ok_or_else(|| bad("sequence.transcribe", "unknown `track`"))?),
};
let mut items = Vec::new();
for t in q.audio_tracks.iter().filter(|t| track.is_none_or(|x| x == t.id)) {
@@ -0,0 +1,89 @@
//! `sequence.inspect` is how an agent checks its edits: it has to show where a clip ends in the
//! sequence and in its media, the clip's audio gain, whether it plays backward and what a marker says.
use serde_json::json;
use crate::Session;
#[test]
fn sequence_inspect_reports_clip_ends_gain_and_marker_comments() {
let mut s = Session::default();
s.execute("file.openDemoProject", json!({})).unwrap();
let rate = s.sequence_rate();
// a clip at 200 %, a clip with gain and a marker with a comment, all made through commands
s.execute("sequence.linkedSelection", json!({"on": false})).unwrap();
let (fast, loud) = {
let q = s.active_sequence().unwrap();
(q.video_tracks[0].items.last().unwrap().id, q.audio_tracks[0].items[0].id)
};
s.execute("timeline.select", json!({"clips": [fast.0]})).unwrap();
s.execute("clip.speedDuration", json!({"speed": 200})).unwrap();
s.execute("timeline.select", json!({"clips": [loud.0]})).unwrap();
s.execute("clip.audioGain", json!({"mode": "set", "db": -6.5})).unwrap();
let marker = s.execute("markers.add", json!({"time": rate.tick_of(12).0, "name": "Beat", "comment": "cut on the downbeat"})).unwrap()["marker"].clone();
let q = s.active_sequence().unwrap().clone();
let js = s.execute("sequence.inspect", json!({})).unwrap();
let m = js["markers"].as_array().unwrap().iter().find(|m| m["id"] == marker).unwrap();
assert_eq!((m["name"].as_str(), m["comment"].as_str()), (Some("Beat"), Some("cut on the downbeat")));
let mut seen = 0;
for (key, tracks) in [("video", &q.video_tracks), ("audio", &q.audio_tracks)] {
for (ti, t) in tracks.iter().enumerate() {
for (ci, c) in t.items.iter().enumerate() {
let j = &js[key][ti]["items"][ci];
assert_eq!(j["clip"], c.id.0);
assert_eq!(j["end"], c.end().0, "{j}");
assert_eq!(j["end"].as_i64(), j["start"].as_i64().zip(j["duration"].as_i64()).map(|(a, b)| a + b));
assert_eq!(j["endFrame"], rate.frame_at(c.end()));
assert_eq!(j["sourceOut"], c.source_out().0, "{j}");
assert_eq!(j["gainDb"], c.gain_db);
// the keys that were there before stay
for old in ["item", "name", "start", "duration", "startFrame", "durationFrames", "sourceIn", "speed", "enabled", "link", "label", "effects"] {
assert!(j.get(old).is_some(), "{old} is still reported");
}
if c.id == fast {
assert_eq!(j["speed"], 2.0);
assert_eq!(
j["sourceOut"].as_i64().unwrap() - j["sourceIn"].as_i64().unwrap(),
2 * j["duration"].as_i64().unwrap(),
"at 200% a clip uses twice its length of media"
);
seen += 1;
}
if c.id == loud {
assert_eq!(j["gainDb"], -6.5);
seen += 1;
}
}
}
}
assert_eq!(seen, 2, "both edited clips were found in the readback");
}
/// A clip set to play backward read back exactly like a forward one: same `speed`, same source
/// range, and nothing that said it was reversed.
#[test]
fn sequence_inspect_reports_a_reversed_clip() {
let mut s = Session::default();
s.execute("file.openDemoProject", json!({})).unwrap();
let backward = s.active_sequence().unwrap().video_tracks[0].items[1].id;
let all = |js: &serde_json::Value| -> Vec<(u64, bool)> {
["video", "audio"]
.iter()
.flat_map(|k| js[*k].as_array().unwrap().iter())
.flat_map(|t| t["items"].as_array().unwrap().iter())
.map(|i| (i["clip"].as_u64().unwrap(), i["reverse"].as_bool().expect("every clip reports `reverse`")))
.collect()
};
let js = s.execute("sequence.inspect", json!({})).unwrap();
assert!(all(&js).iter().all(|(_, reversed)| !reversed), "nothing plays backward yet");
s.execute("sequence.linkedSelection", json!({"on": false})).unwrap();
s.execute("timeline.select", json!({"clips": [backward.0]})).unwrap();
s.execute("clip.speedDuration", json!({"speed": 100, "reverse": true})).unwrap();
let js = s.execute("sequence.inspect", json!({})).unwrap();
let reversed: Vec<u64> = all(&js).into_iter().filter(|(_, r)| *r).map(|(c, _)| c).collect();
assert_eq!(reversed, vec![backward.0], "only the reversed clip says so");
s.execute("edit.undo", json!({})).unwrap();
let js = s.execute("sequence.inspect", json!({})).unwrap();
assert!(all(&js).iter().all(|(_, reversed)| !reversed));
}
+164
View File
@@ -0,0 +1,164 @@
//! The Timeline's sequence tabs: closing the others, reordering, and what a project file keeps of
//! them (the open tabs in order, the active one, and each sequence's zoom, scroll and track
//! heights). Premiere's behaviour was observed in Premiere Pro 26.5.2.
use super::*;
use filmcraft_project::SequenceView;
use serde_json::json;
/// The demo project with two more sequences open: tabs [main, b, c], `c` active.
fn three_tabs() -> (Session, [ItemId; 3]) {
let mut s = Session::default();
s.execute("file.openDemoProject", json!({})).unwrap();
let main = s.state.active_sequence.unwrap();
let mut new = |name: &str| ItemId(s.execute("file.newSequence", json!({"name": name})).unwrap()["sequence"].as_u64().unwrap());
let (b, c) = (new("B"), new("C"));
assert_eq!(s.state.open_sequences, [main, b, c]);
assert_eq!(s.state.active_sequence, Some(c));
(s, [main, b, c])
}
fn view(pps: f64, scroll: f64) -> SequenceView {
SequenceView { pps, scroll, v_scroll: 12.0, a_scroll: 7.0, video_track_h: 90.0, audio_track_h: 40.0 }
}
fn temp_dir(name: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("filmcraft-tabs-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn close_others_keeps_one_tab_and_shows_it() {
let (mut s, [main, b, c]) = three_tabs();
// from the active tab
assert_eq!(s.execute("sequence.closeOthers", json!({})).unwrap()["closed"], json!(2));
assert_eq!((s.state.open_sequences.clone(), s.state.active_sequence), (vec![c], Some(c)));
// from another tab: that one becomes the active one
let (mut s, _) = three_tabs();
s.drain_events();
s.execute("sequence.closeOthers", json!({"item": b.0})).unwrap();
assert_eq!((s.state.open_sequences.clone(), s.state.active_sequence), (vec![b], Some(b)));
assert!(s.drain_events().contains(&Event::OpenSequence(b)));
// a sequence that is not open cannot be the one to keep
s.execute("sequence.close", json!({})).unwrap();
assert!(s.execute("sequence.closeOthers", json!({"item": main.0})).is_err());
}
#[test]
fn a_tab_moves_to_another_place_among_the_tabs() {
let (mut s, [main, b, c]) = three_tabs();
let (revision, steps) = (s.revision, s.history.undo.len());
s.execute("sequence.moveTab", json!({"item": c.0, "index": 0})).unwrap();
assert_eq!(s.state.open_sequences, [c, main, b]);
assert_eq!(s.state.active_sequence, Some(c), "moving a tab does not change which is shown");
s.execute("sequence.moveTab", json!({"item": c.0, "index": 1})).unwrap();
assert_eq!(s.state.open_sequences, [main, c, b]);
// past the end is the end; the active tab is the default
assert_eq!(s.execute("sequence.moveTab", json!({"index": u64::MAX})).unwrap()["index"], json!(2));
assert_eq!(s.state.open_sequences, [main, b, c]);
// not an undo step, not an edit
assert_eq!((s.revision, s.history.undo.len()), (revision, steps));
s.execute("sequence.close", json!({"item": b.0})).unwrap();
assert!(s.execute("sequence.moveTab", json!({"item": b.0, "index": 0})).is_err());
assert!(s.execute("sequence.moveTab", json!({"item": c.0})).is_err());
}
#[test]
fn a_saved_project_reopens_with_its_tabs_and_their_views() {
let (mut s, [main, b, c]) = three_tabs();
s.execute("sequence.moveTab", json!({"item": c.0, "index": 0})).unwrap();
s.execute("sequence.open", json!({"item": b.0})).unwrap();
s.state.timeline_views.insert(main, view(12.5, 3.0));
s.state.timeline_views.insert(b, view(400.0, 0.25));
let dir = temp_dir("reopen");
let path = dir.join("tabs.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!(t.state.open_sequences, [c, main, b]);
assert_eq!(t.state.active_sequence, Some(b));
assert_eq!(t.state.timeline_views.get(&main), Some(&view(12.5, 3.0)));
assert_eq!(t.state.timeline_views.get(&b), Some(&view(400.0, 0.25)));
assert_eq!(t.state.timeline_views.get(&c), None, "a sequence that was never shown has no view");
assert!(t.drain_events().contains(&Event::OpenSequence(b)));
assert!(!t.is_dirty());
// with the preference off, a project opens on its first sequence as before
let mut u = Session::default();
u.prefs.timeline.restore_open_sequences = false;
u.execute("file.open", json!({"path": path})).unwrap();
assert_eq!(u.state.open_sequences, [main]);
assert_eq!(u.state.active_sequence, Some(main));
assert!(u.state.timeline_views.is_empty());
// saved with every tab closed (or by a session that never showed a sequence): the project
// opens on its first sequence, not on an empty Timeline, and still knows the views
s.execute("sequence.closeOthers", json!({})).unwrap();
s.execute("sequence.close", json!({})).unwrap();
s.execute("file.save", json!({})).unwrap();
let mut w = Session::default();
w.execute("file.open", json!({"path": path})).unwrap();
assert_eq!((w.state.open_sequences.clone(), w.state.active_sequence), (vec![main], Some(main)));
assert_eq!(w.state.timeline_views.get(&b), Some(&view(400.0, 0.25)));
let _ = std::fs::remove_dir_all(&dir);
}
/// The view in a project file is not trusted: ids of things that are not sequences, repeats and
/// numbers out of range are dropped or brought into range, and a view that cannot be read at all
/// does not stop the project from opening.
#[test]
fn a_damaged_view_in_a_project_file_is_cleaned_up_or_ignored() {
let (mut s, [main, b, c]) = three_tabs();
let footage = s.project.sequence(main).unwrap().video_tracks[0].items[0].item;
let dir = temp_dir("damaged");
let path = dir.join("tabs.fcproj").to_string_lossy().to_string();
s.execute("file.saveAs", json!({"path": path})).unwrap();
let saved: serde_json::Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
let with_view = |view: serde_json::Value| {
let mut doc = saved.clone();
doc["view"] = view;
std::fs::write(&path, serde_json::to_vec(&doc).unwrap()).unwrap();
let mut t = Session::default();
t.execute("file.open", json!({"path": path})).unwrap();
t
};
let t = with_view(json!({
"open_sequences": [c.0, 999_999, footage.0, c.0, b.0],
"active_sequence": 999_999,
"sequences": {
b.0.to_string(): {"pps": 1e300, "scroll": -5.0, "v_scroll": 1e30, "a_scroll": -1.0, "video_track_h": 0.0, "audio_track_h": 1e9},
"999999": {"pps": 40.0, "scroll": 0.0, "video_track_h": 60.0, "audio_track_h": 56.0},
footage.0.to_string(): {"pps": 40.0, "scroll": 0.0, "video_track_h": 60.0, "audio_track_h": 56.0},
},
}));
assert_eq!(t.state.open_sequences, [c, b]);
assert_eq!(t.state.active_sequence, Some(c), "an active tab that is not open: the first tab");
assert_eq!(t.state.timeline_views.len(), 1);
let v = t.state.timeline_views[&b];
assert!(v.pps <= 1e5 && v.scroll == 0.0 && v.v_scroll <= 1e6 && v.a_scroll == 0.0);
assert!(v.video_track_h >= 8.0 && v.audio_track_h <= 600.0);
// not a view at all: the project opens as it does without one
for junk in [json!("tabs"), json!([1, 2, 3]), json!({"open_sequences": "all"}), json!({"sequences": {"x": 1}}), json!(null)] {
let t = with_view(junk.clone());
assert_eq!((t.state.open_sequences.clone(), t.state.active_sequence), (vec![main], Some(main)), "{junk}");
}
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn the_view_of_a_deleted_sequence_is_forgotten() {
let (mut s, [main, b, c]) = three_tabs();
for id in [main, b, c] {
s.state.timeline_views.insert(id, view(40.0, 0.0));
}
s.execute("project.delete", json!({"items": [b.0]})).unwrap();
assert_eq!(s.state.timeline_views.keys().copied().collect::<Vec<_>>(), [main, c]);
assert_eq!(s.state.open_sequences, [main, c]);
// the saved view never names it either
assert_eq!(s.project_view().open_sequences, [main, c]);
}
+254 -10
View File
@@ -27,7 +27,7 @@
//! takes its own range and lands offset by the difference of the In points (J- and L-cuts).
use filmcraft_edit as edit;
use filmcraft_project::{ClipId, ItemId, Label, Marker, MarkerId, MarkerKind, SplitMarks, TrackId, TrackItem, TrackKind};
use filmcraft_project::{AudioChannels, ClipId, ItemId, Label, Marker, MarkerId, MarkerKind, SplitMarks, TrackId, TrackItem, TrackKind};
use filmcraft_time::{Tick, TimeRange};
use serde_json::{Value, json};
@@ -304,7 +304,7 @@ fn go_to_gap(s: &mut Session, p: &Value, next: bool, in_track: bool) -> Result<V
let t = s.playhead();
let q = s.active_sequence().ok_or(EngineError::NoSequence)?;
let gaps: Vec<TimeRange> = if in_track {
let tracks: Vec<TrackId> = match track_p(s, p, "track") {
let tracks: Vec<TrackId> = match track_p(s, p, "track", if next { "sequence.goToNextGapInTrack" } else { "sequence.goToPrevGapInTrack" })? {
Some(id) => vec![id],
None => s.targeting().targeted,
};
@@ -348,6 +348,18 @@ fn join_through_edits(s: &mut Session, p: &Value) -> Result<Value> {
/// Sequence ▸ Make Subsequence: a new sequence (same settings and track layout) holding copies of the
/// selected clips, or of everything on targeted tracks between In and Out, trimmed to In/Out when
/// they are set. The new sequence is added to the project and selected; the original is unchanged.
/// Give a sequence made from part of `from` (Nest…, Make Subsequence) the track names and audio
/// channel layouts of `from`'s tracks, track for track.
pub(crate) fn lay_out_tracks_like(new: &mut filmcraft_project::Sequence, from: &filmcraft_project::Sequence) {
for (tr, src) in new.video_tracks.iter_mut().zip(&from.video_tracks) {
tr.name = src.name.clone();
}
for (tr, src) in new.audio_tracks.iter_mut().zip(&from.audio_tracks) {
tr.name = src.name.clone();
tr.channels = src.channels;
}
}
fn make_subsequence(s: &mut Session, p: &Value) -> Result<Value> {
let seq_id = s.state.active_sequence.ok_or(EngineError::NoSequence)?;
let q = s.active_sequence().ok_or(EngineError::NoSequence)?.clone();
@@ -420,13 +432,7 @@ fn make_subsequence(s: &mut Session, p: &Value) -> Result<Value> {
}
}
let nq = pr.sequence_mut(nid).ok_or(EngineError::NoSequence)?;
for (i, tr) in nq.video_tracks.iter_mut().enumerate() {
tr.name = q.video_tracks[i].name.clone();
}
for (i, tr) in nq.audio_tracks.iter_mut().enumerate() {
tr.name = q.audio_tracks[i].name.clone();
tr.channels = q.audio_tracks[i].channels;
}
lay_out_tracks_like(nq, &q);
for (kind, ti, it) in placed {
nq.tracks_mut(kind)[ti].items.push(it);
}
@@ -439,15 +445,253 @@ fn make_subsequence(s: &mut Session, p: &Value) -> Result<Value> {
}
nq.check().map_err(EngineError::Other)?;
st.project_selection = vec![nid];
// like Premiere: the subsequence is loaded in the Source Monitor, ready to edit from
st.source_item = Some(nid);
st.source_playhead = Tick::ZERO;
Ok(nid)
})?;
s.events.push(crate::Event::OpenSource(id));
Ok(json!({"sequence": id.0, "name": name}))
}
// ---------- a sequence edited in as its clips ----------
/// The nest toggle off ("Insert and overwrite sequences as nests or individual clips"): edit the
/// clips of sequence `item` that lie in `range` of it into the active sequence at `at`, instead of
/// one nested clip. As in Premiere, the clips come with their transitions and links; the source's
/// tracks that hold clips go to consecutive tracks from `vdest` / `adest` up (source V1 and V3
/// land on the destination track and the one above it), and tracks that are missing are added.
/// A kind without a destination track is left out.
#[allow(clippy::too_many_arguments)]
pub(crate) fn place_sequence_clips(
s: &mut Session,
item: ItemId,
range: TimeRange,
at: Tick,
vdest: Option<TrackId>,
adest: Option<TrackId>,
insert: bool,
label: &str,
) -> Result<Vec<ClipId>> {
let seq_id = s.state.active_sequence.ok_or(EngineError::NoSequence)?;
let src = s.project.sequence(item).ok_or_else(|| bad(label, "not a sequence"))?.clone();
let dst = s.active_sequence().ok_or(EngineError::NoSequence)?;
// (kind, how many tracks above the destination track, the clip trimmed to the range)
let mut items: Vec<(TrackKind, usize, TrackItem)> = Vec::new();
// source track index → tracks above the destination track, per kind
// (TrackKind has no Hash: the maps are keyed by "is audio")
let audio = |k: TrackKind| k == TrackKind::Audio;
let mut lanes: std::collections::HashMap<(bool, usize), usize> = std::collections::HashMap::new();
let mut base: std::collections::HashMap<bool, usize> = std::collections::HashMap::new();
for (kind, tracks, dest) in [(TrackKind::Video, &src.video_tracks, vdest), (TrackKind::Audio, &src.audio_tracks, adest)] {
let Some(first) = dest.and_then(|d| dst.tracks(kind).iter().position(|t| t.id == d)) else { continue };
base.insert(audio(kind), first);
let mut lane = 0;
for (ti, tr) in tracks.iter().enumerate() {
let clips: Vec<TrackItem> = tr.items.iter().filter_map(|it| edit::through::clip_item_to(it, range)).collect();
if clips.is_empty() {
continue;
}
lanes.insert((audio(kind), ti), lane);
items.extend(clips.into_iter().map(|c| (kind, lane, c)));
lane += 1;
}
}
if items.is_empty() {
return Err(EngineError::Other("no destination track for this sequence's clips (check source patching)".into()));
}
let media = s.media.clone();
s.edit(label, |p, st| {
// copies with ids, links and transitions of their own, moved to `at`
let mut ids = std::collections::HashMap::new();
let mut links = std::collections::HashMap::new();
let mut placed: Vec<(TrackKind, usize, TrackItem)> = Vec::new();
for (kind, lane, mut it) in items.clone() {
let id = ClipId(p.alloc_id());
ids.insert(it.id, id);
it.id = id;
it.start = at + (it.start - range.start);
if let Some(l) = it.link {
it.link = Some(*links.entry(l).or_insert_with(|| p.alloc_id()));
}
placed.push((kind, lane, it));
}
let mut transitions = Vec::new();
for (kind, tracks) in [(TrackKind::Video, &src.video_tracks), (TrackKind::Audio, &src.audio_tracks)] {
for (ti, tr) in tracks.iter().enumerate() {
let Some(lane) = lanes.get(&(audio(kind), ti)).copied() else { continue };
for trn in &tr.transitions {
let from = trn.from.map(|c| ids.get(&c).copied());
let to = trn.to.map(|c| ids.get(&c).copied());
if trn.start >= range.start && trn.end() <= range.end() && from != Some(None) && to != Some(None) {
let mut t = trn.clone();
t.id = filmcraft_project::TransitionId(p.alloc_id());
(t.from, t.to) = (from.flatten(), to.flatten());
t.start = at + (t.start - range.start);
transitions.push((kind, lane, t));
}
}
}
}
// tracks for every lane, added on top when the sequence has too few
let mut dest: std::collections::HashMap<(bool, usize), TrackId> = std::collections::HashMap::new();
for (is_audio, lane) in placed.iter().map(|x| (audio(x.0), x.1)).collect::<std::collections::BTreeSet<_>>() {
let kind = if is_audio { TrackKind::Audio } else { TrackKind::Video };
let index = base.get(&is_audio).copied().unwrap_or(0).saturating_add(lane);
while p.sequence(seq_id).ok_or(EngineError::NoSequence)?.tracks(kind).len() <= index {
let id = TrackId(p.alloc_id());
let tracks = p.sequence_mut(seq_id).ok_or(EngineError::NoSequence)?.tracks_mut(kind);
let (word, n) = (if kind == TrackKind::Video { "Video" } else { "Audio" }, tracks.len() + 1);
tracks.push(filmcraft_project::Track::new(id, kind, format!("{word} {n}")));
}
let id = p.sequence(seq_id).and_then(|q| q.tracks(kind).get(index)).map(|t| t.id).ok_or(EngineError::NoSequence)?;
dest.insert((is_audio, lane), id);
}
let placements: Vec<(TrackId, TrackItem)> = placed.into_iter().filter_map(|(k, lane, it)| Some((*dest.get(&(audio(k), lane))?, it))).collect();
let span = placements.iter().map(|x| x.1.start).min().zip(placements.iter().map(|x| x.1.end()).max());
let snapshot = std::sync::Arc::new(p.clone());
let snap = snapshot.clone();
let durations = move |id: ItemId| crate::media_duration(&snapshot, &media, id);
let starts = move |id: ItemId| crate::media_start(&snap, id);
let mut next = p.next_id;
let seq = p.sequence_mut(seq_id).ok_or(EngineError::NoSequence)?;
let min = seq.settings.frame_rate.frame_duration();
let mut ctx = edit::EditCtx { next_id: &mut next, media_duration: &durations, media_start: &starts, min_duration: min };
let new = if insert { edit::insert(seq, placements, &mut ctx)? } else { edit::overwrite(seq, placements, &mut ctx)? };
for (kind, lane, t) in transitions {
if let Some(tr) = dest.get(&(audio(kind), lane)).and_then(|id| seq.track_mut(*id)) {
tr.transitions.push(t);
}
}
for tr in seq.all_tracks_mut() {
tr.sort();
edit::remove_orphan_transitions(tr);
}
seq.check().map_err(EngineError::Other)?;
if insert
&& st.ripple_sequence_markers
&& let Some((a, b)) = span
{
ripple_markers(&mut seq.markers, a, b - a);
}
p.next_id = next;
st.selection = new.clone();
Ok(new)
})
}
// ---------- delete tracks ----------
/// Sequence ▸ Delete Tracks…: delete all empty video / audio tracks (`"empty"`) or one track per
/// kind. A sequence always keeps at least one video and one audio track.
/// The most tracks one `sequence.addTracks` adds of a kind, and the most a sequence may then
/// have of it. (Amounts come from dialogs, scripts and the control channel: never trusted.)
const MAX_ADDED_TRACKS: u64 = 99;
const MAX_TRACKS: usize = 999;
/// Where `sequence.addTracks` puts new tracks among the `len` tracks of their kind: the number of
/// tracks before them. `key` holds `"first"` (Before First Track), a track of that kind by name
/// (`"V2"`: after Video 2; `letter` is V, A or S) or a number (after that many tracks); without it
/// they go after the last track.
fn placement(p: &Value, key: &str, letter: char, len: usize) -> Result<usize> {
let cmd = "sequence.addTracks";
let after = match p.get(key) {
None | Some(Value::Null) => return Ok(len),
Some(v) => match (v.as_u64(), v.as_str()) {
(Some(n), _) => usize::try_from(n).ok(),
(None, Some(x)) if matches!(x.to_ascii_lowercase().as_str(), "first" | "before" | "beforefirst") => Some(0),
(None, Some(x)) if matches!(x.to_ascii_lowercase().as_str(), "last" | "end") => Some(len),
(None, Some(x)) => {
let mut rest = x.chars();
rest.next().filter(|c| c.eq_ignore_ascii_case(&letter)).and_then(|_| rest.as_str().parse::<usize>().ok())
}
(None, None) => None,
},
};
after.filter(|n| *n <= len).ok_or_else(|| bad(cmd, format!("`{key}` must be \"first\", a track ({letter}1–{letter}{len}) or how many tracks come before")))
}
/// Give the tracks that still carry a default name (`<prefix> <number>`) the number of their
/// place, as Premiere numbers its tracks; a track the user named keeps its name.
fn renumber(tracks: &mut [filmcraft_project::Track], prefix: &str) {
for (i, t) in tracks.iter_mut().enumerate() {
let default = t.name.strip_prefix(prefix).and_then(|r| r.strip_prefix(' ')).is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()));
if default {
t.name = format!("{prefix} {}", i + 1);
}
}
}
/// Sequence ▸ Add Tracks…: `video` / `audio` / `submix` tracks, each kind at its own place
/// (`videoAfter`, `audioAfter`, `submixAfter`; after the last track when not given), audio tracks
/// of `audioType` (Standard unless given) and submix tracks of `submixType` (Stereo). One undo
/// step. Tracks are numbered by their place, so default names after the new tracks move up.
pub(crate) fn add_tracks(s: &mut Session, p: &Value) -> Result<Value> {
use crate::commands::u64_p;
let cmd = "sequence.addTracks";
let q = s.active_sequence().ok_or(EngineError::NoSequence)?;
let amount = |key: &str, default: u64, have: usize| -> Result<usize> {
let n = match p.get(key) {
None | Some(Value::Null) => default,
Some(_) => u64_p(p, key).ok_or_else(|| bad(cmd, format!("`{key}` must be a number of tracks")))?,
};
if n > MAX_ADDED_TRACKS {
return Err(bad(cmd, format!("`{key}`: at most {MAX_ADDED_TRACKS} tracks at a time")));
}
if have.saturating_add(n as usize) > MAX_TRACKS {
return Err(bad(cmd, format!("`{key}`: a sequence has at most {MAX_TRACKS} tracks of a kind")));
}
Ok(n as usize)
};
let (nv, na, ns) = (amount("video", 1, q.video_tracks.len())?, amount("audio", 0, q.audio_tracks.len())?, amount("submix", 0, q.submix_tracks.len())?);
let (at_v, at_a, at_s) = (
placement(p, "videoAfter", 'V', q.video_tracks.len())?,
placement(p, "audioAfter", 'A', q.audio_tracks.len())?,
placement(p, "submixAfter", 'S', q.submix_tracks.len())?,
);
let channels = |key: &str, default: AudioChannels| match p.get(key).and_then(Value::as_str) {
None => Ok(default),
Some(x) => crate::mixer::channels_from(x).ok_or_else(|| bad(cmd, format!("`{key}`: unknown track type {x:?} (standard, stereo, 5.1, adaptive, mono)"))),
};
let (audio_type, submix_type) = (channels("audioType", AudioChannels::Stereo)?, channels("submixType", AudioChannels::Stereo)?);
if nv + na + ns == 0 {
return Err(bad(cmd, "no tracks to add"));
}
let added = s.edit_sequence("Add Tracks", |q, ctx, _| {
let mut new = |kind: TrackKind, prefix: &str, channels: Option<AudioChannels>| {
let mut t = filmcraft_project::Track::new(TrackId(ctx.alloc()), kind, format!("{prefix} 0"));
if let Some(c) = channels {
t.channels = c;
}
t
};
let mut ids: [Vec<u64>; 3] = Default::default();
for (k, (tracks, n, at, kind, prefix, ch)) in [
(&mut q.video_tracks, nv, at_v, TrackKind::Video, "Video", None),
(&mut q.audio_tracks, na, at_a, TrackKind::Audio, "Audio", Some(audio_type)),
(&mut q.submix_tracks, ns, at_s, TrackKind::Audio, "Submix", Some(submix_type)),
]
.into_iter()
.enumerate()
{
let at = at.min(tracks.len());
for i in 0..n {
let t = new(kind, prefix, ch);
if let Some(slot) = ids.get_mut(k) {
slot.push(t.id.0);
}
tracks.insert(at + i, t);
}
if n > 0 {
renumber(tracks, prefix);
}
}
Ok(ids)
})?;
let [video, audio, submix] = added;
Ok(json!({"video": video, "audio": audio, "submix": submix}))
}
fn delete_tracks(s: &mut Session, p: &Value) -> Result<Value> {
let seq_id = s.state.active_sequence.ok_or(EngineError::NoSequence)?;
let q = s.active_sequence().ok_or(EngineError::NoSequence)?;
@@ -460,7 +704,7 @@ fn delete_tracks(s: &mut Session, p: &Value) -> Result<Value> {
tracks.iter().filter(|t| t.items.is_empty()).map(|t| t.id).collect()
}
Some(_) => {
let id = track_p(s, p, key).ok_or_else(|| bad("sequence.deleteTracks", format!("unknown {key} track")))?;
let id = track_p(s, p, key, "sequence.deleteTracks")?.ok_or_else(|| bad("sequence.deleteTracks", format!("unknown {key} track")))?;
if !tracks.iter().any(|t| t.id == id) {
return Err(bad("sequence.deleteTracks", format!("`{key}` must name a {key} track")));
}
+103 -1
View File
@@ -1,7 +1,7 @@
//! Sequence / Markers menu commands (`sequence_tools`).
use super::*;
use filmcraft_project::{Label, MarkerKind};
use filmcraft_project::{AudioChannels, Label, MarkerKind, TrackKind};
use serde_json::json;
fn demo() -> Session {
@@ -189,6 +189,108 @@ fn make_subsequence_from_in_out_and_from_selection() {
assert!(s.project.items.values().all(|i| i.name != "Shot 3"));
}
/// Sequence ▸ Add Tracks…: where the new tracks go, what they are, and what the amounts may be.
/// Premiere Pro 26.5.2: Placement is "Before First Track" or after one of the tracks (after the
/// last by default); a track added after Video 1 is the new Video 2, and what was on Video 2 is
/// then on Video 3; audio tracks are Standard, 5.1, Adaptive or Mono, submix tracks Stereo, 5.1,
/// Adaptive or Mono.
#[test]
fn add_tracks_places_and_types_them() {
let mut s = demo();
let names = |s: &Session, kind: TrackKind| s.active_sequence().unwrap().tracks(kind).iter().map(|t| t.name.clone()).collect::<Vec<_>>();
let before = s.active_sequence().unwrap().clone();
assert_eq!(names(&s, TrackKind::Video), ["Video 1", "Video 2", "Video 3"]);
let on_v2 = before.video_tracks[1].items[0].id;
// without a place: after the last track (and one video track when nothing is said, as before)
let r = s.execute("sequence.addTracks", json!({})).unwrap();
assert_eq!((r["video"].as_array().unwrap().len(), r["audio"].as_array().unwrap().len(), r["submix"].as_array().unwrap().len()), (1, 0, 0));
assert_eq!(names(&s, TrackKind::Video), ["Video 1", "Video 2", "Video 3", "Video 4"]);
assert_eq!(s.active_sequence().unwrap().video_tracks[3].id.0, r["video"][0].as_u64().unwrap());
s.execute("edit.undo", json!({})).unwrap();
// after Video 1: two new empty tracks there, the tracks above move up and are numbered again
s.execute("sequence.addTracks", json!({"video": 2, "videoAfter": "V1"})).unwrap();
let q = s.active_sequence().unwrap();
assert_eq!(names(&s, TrackKind::Video), ["Video 1", "Video 2", "Video 3", "Video 4", "Video 5"]);
assert!(q.video_tracks[1].items.is_empty() && q.video_tracks[2].items.is_empty());
assert_eq!(q.video_tracks[3].id, before.video_tracks[1].id);
assert_eq!(q.video_tracks[3].items[0].id, on_v2, "what was on Video 2 is on Video 4");
assert_eq!(q.audio_tracks.len(), before.audio_tracks.len(), "no audio track was asked for");
// one undo step
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(*s.active_sequence().unwrap(), before);
// before the first track; a name the user gave is kept, default names follow their place
s.edit_sequence("Rename Track", |q, _, _| {
q.audio_tracks[1].name = "Music".into();
Ok(())
})
.unwrap();
s.execute("sequence.addTracks", json!({"video": 0, "audio": 1, "audioAfter": "first", "audioType": "mono"})).unwrap();
assert_eq!(names(&s, TrackKind::Audio), ["Audio 1", "Audio 2", "Music", "Audio 4"]);
let q = s.active_sequence().unwrap();
assert_eq!(q.audio_tracks[0].channels, AudioChannels::Mono);
assert_eq!(q.audio_tracks[1].id, before.audio_tracks[0].id);
// a number counts the tracks before the new ones; "Standard" is a stereo track
for (ty, want) in [("standard", AudioChannels::Stereo), ("5.1", AudioChannels::Surround51), ("adaptive", AudioChannels::Adaptive)] {
let r = s.execute("sequence.addTracks", json!({"video": 0, "audio": 1, "audioAfter": 2, "audioType": ty})).unwrap();
let q = s.active_sequence().unwrap();
assert_eq!((q.audio_tracks[2].id.0, q.audio_tracks[2].channels), (r["audio"][0].as_u64().unwrap(), want), "{ty}");
}
// submix tracks: stereo unless said, placed among the submix tracks
assert!(before.submix_tracks.is_empty());
s.execute("sequence.addTracks", json!({"video": 0, "submix": 2})).unwrap();
s.execute("sequence.addTracks", json!({"video": 0, "submix": 1, "submixAfter": "S1", "submixType": "5.1"})).unwrap();
let q = s.active_sequence().unwrap();
assert_eq!(
q.submix_tracks.iter().map(|t| (t.name.as_str(), t.channels)).collect::<Vec<_>>(),
[("Submix 1", AudioChannels::Stereo), ("Submix 2", AudioChannels::Surround51), ("Submix 3", AudioChannels::Stereo)]
);
// all three kinds at once are one undo step
let before = s.active_sequence().unwrap().clone();
let r = s.execute("sequence.addTracks", json!({"video": 1, "audio": 1, "submix": 1})).unwrap();
assert_eq!((r["video"].as_array().unwrap().len(), r["audio"].as_array().unwrap().len(), r["submix"].as_array().unwrap().len()), (1, 1, 1));
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(*s.active_sequence().unwrap(), before);
}
/// Amounts and places come from a dialog, a script or the control channel: a wrong one is an
/// error that changes nothing, and no amount can make the sequence grow without bound.
#[test]
fn add_tracks_refuses_what_it_cannot_do() {
let mut s = demo();
let before = s.active_sequence().unwrap().clone();
for bad in [
json!({"video": 0}),
json!({"video": 100}),
json!({"video": u64::MAX}),
json!({"video": 0, "audio": 1_000_000}),
json!({"video": "many"}),
json!({"video": 1, "videoAfter": "V9"}),
json!({"video": 1, "videoAfter": "A1"}),
json!({"video": 1, "videoAfter": 4}),
json!({"video": 1, "videoAfter": "top"}),
json!({"video": 0, "audio": 1, "audioAfter": "V1"}),
json!({"video": 0, "audio": 1, "audioType": "quad"}),
json!({"video": 0, "submix": 1, "submixAfter": "S1"}),
json!({"video": 0, "submix": 1, "submixType": "standard-ish"}),
] {
let r = s.execute("sequence.addTracks", bad.clone());
assert!(r.is_err(), "{bad} was accepted: {r:?}");
assert_eq!(*s.active_sequence().unwrap(), before, "{bad} changed the sequence");
}
// 99 at a time, and a sequence stops at 999 tracks of a kind
for _ in 0..10 {
s.execute("sequence.addTracks", json!({"video": 99})).unwrap();
}
assert_eq!(s.active_sequence().unwrap().video_tracks.len(), 3 + 990);
assert!(s.execute("sequence.addTracks", json!({"video": 7})).is_err());
s.execute("sequence.addTracks", json!({"video": 6})).unwrap();
assert_eq!(s.active_sequence().unwrap().video_tracks.len(), 999);
}
#[test]
fn delete_tracks_empty_and_specific() {
let mut s = demo();
+1 -1
View File
@@ -975,7 +975,7 @@ static CATEGORIES: &[Category] = &[
f("timeline.audioTransitionDuration", "Audio Transition Default Duration", Kind::Duration { unit_key: "timeline.audioTransitionUnit" }, true),
f("timeline.stillImageDuration", "Still Image Default Duration", Kind::Duration { unit_key: "timeline.stillImageUnit" }, true),
f("timeline.autoScroll", "Timeline Playback Auto-Scrolling", Kind::Choice(AUTO_SCROLL), true),
f("timeline.mouseScrolling", "Timeline Mouse Scrolling", Kind::Choice(MOUSE_SCROLL), false),
f("timeline.mouseScrolling", "Timeline Mouse Scrolling", Kind::Choice(MOUSE_SCROLL), true),
Row::Group(
"Default Audio Tracks",
&[
+29
View File
@@ -481,6 +481,35 @@ fn auto_transcribe_on_import_and_transcription_defaults() {
let _ = std::fs::remove_dir_all(&dir);
}
/// In a build without speech-to-text (the release builds), the transcript commands that can't
/// run say so through `enabled` (#97, #98), and an import with auto-transcribe on reports why it
/// made no transcript instead of saying nothing (#89).
#[test]
fn transcription_without_speech_to_text_says_so() {
let mut s = Session::default();
assert_eq!(s.is_enabled("transcript.generate"), crate::transcript::speech_available());
assert_eq!(s.is_enabled("transcript.downloadModel"), cfg!(feature = "speech-download"));
if crate::transcript::speech_available() {
return;
}
let dir = tmp_dir("prefs-no-speech");
let mov = dir.join("talk.mov");
crate::media_test_util::make_movie(&mov, filmcraft_media::DemoScene::OceanSunset, 64, 36, 24);
// off: an import reports nothing
let r = s.execute("file.import", json!({"paths": [mov.to_string_lossy()]})).unwrap();
assert_eq!(r["errors"], json!([]));
set(&mut s, "mediaAnalysis.autoTranscribe", json!(true));
set(&mut s, "mediaAnalysis.autoTranscribeScope", json!("allImported"));
let r = s.execute("file.import", json!({"paths": [mov.to_string_lossy()]})).unwrap();
let errors = r["errors"].as_array().unwrap();
assert!(errors.iter().any(|e| e.as_str().is_some_and(|e| e.starts_with("transcription:") && e.contains("not available in this build"))), "{errors:?}");
assert!(!s.project.transcripts.contains_key(&ItemId(r["items"][0].as_u64().unwrap())));
// with a transcriber installed (a host's), the command is enabled again
s.transcriber = Some(std::sync::Arc::new(filmcraft_speech::FixedTranscriber { transcript: Default::default(), id: "fixed".into() }));
assert!(s.is_enabled("transcript.generate"));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn hardware_decoding_setting_drives_the_decoder_switch() {
let mut s = Session::default();
+5
View File
@@ -205,6 +205,11 @@ fn list_searches_labels_and_keys() {
let r = s.shortcuts.commands();
assert!(r.iter().any(|c| c.id == "trim.forward"));
assert!(!r.iter().any(|c| c.id == "timeline.move"), "commands with required params are not bindable");
// a parameter doc holds parameters only (each optional or with a default): a result
// description in it would take the command out of this list
for id in ["clip.replaceFromBin", "clip.replaceFromSource", "clip.replaceFromSourceMatchFrame"] {
assert!(r.iter().any(|c| c.id == id), "{id} has no required parameter, so it can be bound");
}
let mut s = s;
let v = s.execute("shortcuts.list", json!({"query": "ripple delete"})).unwrap();
assert!(v.as_array().unwrap().iter().any(|c| c["id"] == "edit.rippleDelete"), "{v}");
@@ -0,0 +1,166 @@
//! A ripple trim ahead of a split edit: the later clip's sound starts before its picture (a J cut)
//! and has to move with it.
use filmcraft_project::ClipId;
use filmcraft_time::Tick;
use serde_json::json;
use crate::Session;
fn start(s: &Session, c: ClipId) -> Tick {
s.active_sequence().unwrap().find_item(c).map(|(_, i)| i.start).unwrap()
}
/// Two clips in a row on V1. The first has its sound on A1, the second on A2, and the second's
/// sound starts 12 frames before its picture. Returns (first picture, second picture, second sound).
fn j_cut(s: &mut Session) -> (ClipId, ClipId, ClipId) {
s.execute("file.openDemoProject", json!({})).unwrap();
s.execute("file.newSequence", json!({"name": "J cut", "video": 1, "audio": 2})).unwrap();
let rate = s.sequence_rate();
let item = s.project.items.values().find(|i| i.has_video() && i.has_audio() && i.as_media().is_some()).map(|i| i.id).unwrap();
let (source_in, len) = (rate.tick_of(48).0, rate.tick_of(48).0);
s.execute("timeline.place", json!({"item": item.0, "track": "V1", "audioTrack": "A1", "frame": 0, "sourceIn": source_in, "duration": len})).unwrap();
s.execute("timeline.place", json!({"item": item.0, "track": "V1", "audioTrack": "A2", "frame": 48, "sourceIn": source_in, "duration": len})).unwrap();
let q = s.active_sequence().unwrap();
let (first, second, sound) = (q.video_tracks[0].items[0].id, q.video_tracks[0].items[1].id, q.audio_tracks[1].items[0].id);
// the split: only the sound's In edge moves, so Linked Selection is off for this one trim
s.execute("sequence.linkedSelection", json!({"on": false})).unwrap();
s.execute("timeline.trim", json!({"clip": sound.0, "edge": "in", "mode": "regular", "deltaFrames": -12})).unwrap();
s.execute("sequence.linkedSelection", json!({"on": true})).unwrap();
assert_eq!(start(s, second) - start(s, sound), rate.tick_of(12), "the sound leads its picture by 12 frames");
(first, second, sound)
}
/// Lengthening the clip before a J cut moved the later picture and left its sound behind: a lead
/// of 12 frames became 20, with no error.
#[test]
fn lengthening_before_a_j_cut_keeps_the_sound_with_its_picture() {
ripple_and_check(8);
}
/// Shortening it was refused as a sync-lock conflict, because the early sound sat in the stretch
/// that closes.
#[test]
fn shortening_before_a_j_cut_keeps_the_sound_with_its_picture() {
ripple_and_check(-8);
}
fn ripple_and_check(frames: i64) {
let mut s = Session::default();
let (first, second, sound) = j_cut(&mut s);
let rate = s.sequence_rate();
let (picture_at, sound_at) = (start(&s, second), start(&s, sound));
let before = s.project.clone();
let r = s.execute("timeline.trim", json!({"clip": first.0, "edge": "out", "mode": "ripple", "deltaFrames": frames})).unwrap();
let by = rate.tick_of(frames);
assert_eq!(r["delta"], json!(by.0));
assert_eq!(start(&s, second), picture_at + by, "the later picture ripples");
assert_eq!(start(&s, sound), sound_at + by, "its sound still leads by 12 frames");
s.active_sequence().unwrap().check().unwrap();
let after = s.project.clone();
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(*s.project, *before, "one undo step puts both back");
s.execute("edit.redo", json!({})).unwrap();
assert_eq!(*s.project, *after);
}
/// The early sound has no room to follow: the sequence start, or another clip right before it on
/// its track. The trim is refused and nothing moves.
#[test]
fn ripple_trim_is_refused_when_the_early_sound_has_no_room() {
let mut s = Session::default();
let (first, second, sound) = j_cut(&mut s);
let rate = s.sequence_rate();
let before = s.project.clone();
// the sound starts at frame 36: 40 frames earlier is before the sequence starts
let e = s.execute("timeline.trim", json!({"clip": first.0, "edge": "out", "mode": "ripple", "deltaFrames": -40})).unwrap_err();
assert!(e.to_string().contains("sync"), "{e}");
assert_eq!(*s.project, *before, "a refused trim changes nothing");
let tone = s.project.items.values().find(|i| !i.has_video() && i.has_audio() && i.as_media().is_some()).map(|i| i.id).unwrap();
s.execute("timeline.place", json!({"item": tone.0, "audioTrack": "A2", "frame": 12, "duration": rate.tick_of(24).0})).unwrap();
let before = s.project.clone();
assert_eq!(s.active_sequence().unwrap().audio_tracks[1].items[0].end(), start(&s, sound));
let e = s.execute("timeline.trim", json!({"clip": first.0, "edge": "out", "mode": "ripple", "deltaFrames": -8})).unwrap_err();
assert!(e.to_string().contains("sync"), "{e}");
assert_eq!(*s.project, *before, "a refused trim changes nothing");
assert_eq!(start(&s, second) - start(&s, sound), rate.tick_of(12));
}
/// The mirror, an L cut: the first clip's sound runs 6 frames on into the second picture. Shortening
/// the second clip's head was refused as a sync-lock conflict, because the first clip's sound crossed
/// the cut. The first clip never moves, so its sound stays and the L cut still ends where it did.
#[test]
fn shortening_the_head_after_an_l_cut_keeps_the_earlier_sound_in_place() {
let mut s = Session::default();
let (first, second, sound) = j_cut(&mut s);
let rate = s.sequence_rate();
// undo the J cut, then run the first clip's sound (A1) 6 frames past its picture
s.execute("sequence.linkedSelection", json!({"on": false})).unwrap();
s.execute("timeline.trim", json!({"clip": sound.0, "edge": "in", "mode": "regular", "deltaFrames": 12})).unwrap();
let first_sound = s.active_sequence().unwrap().audio_tracks[0].items[0].id;
s.execute("timeline.trim", json!({"clip": first_sound.0, "edge": "out", "mode": "regular", "deltaFrames": 6})).unwrap();
s.execute("sequence.linkedSelection", json!({"on": true})).unwrap();
let end = |s: &Session, c: ClipId| s.active_sequence().unwrap().find_item(c).map(|(_, i)| i.end()).unwrap();
assert_eq!(end(&s, first_sound), start(&s, second) + rate.tick_of(6), "the L cut runs 6 frames into the second picture");
let (l_cut_ends, picture_at, picture_ends) = (end(&s, first_sound), start(&s, second), end(&s, second));
let before = s.project.clone();
s.execute("timeline.trim", json!({"clip": second.0, "edge": "in", "mode": "ripple", "deltaFrames": 3})).unwrap();
assert_eq!(end(&s, first_sound), l_cut_ends, "the L cut still ends where it did");
assert_eq!((start(&s, first), start(&s, first_sound)), (Tick::ZERO, Tick::ZERO));
assert_eq!((start(&s, second), end(&s, second)), (picture_at, picture_ends - rate.tick_of(3)), "the second picture is 3 frames shorter");
assert_eq!((start(&s, sound), end(&s, sound)), (start(&s, second), end(&s, second)), "its own sound with it");
s.active_sequence().unwrap().check().unwrap();
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(*s.project, *before, "one undo step puts it back");
}
/// A shorter head on the J-cut take itself: the picture and its early sound lose the same stretch
/// and the sound still leads by 12. It was refused as a sync-lock conflict because the check looked
/// at the stretch before the cut, where the first clip's sound sits on A1, instead of the stretch
/// the shorter head takes away.
#[test]
fn shorter_head_on_a_j_cut_take_shortens_picture_and_sound_together() {
shorter_head_on_a_j_cut_take(false);
}
/// The same trim grabbed by the early sound instead of the picture gives the same result.
#[test]
fn shorter_head_grabbed_by_the_early_sound_gives_the_same_result() {
shorter_head_on_a_j_cut_take(true);
}
fn shorter_head_on_a_j_cut_take(grab_sound: bool) {
let mut s = Session::default();
let (first, second, sound) = j_cut(&mut s);
let rate = s.sequence_rate();
let len = |s: &Session, c: ClipId| s.active_sequence().unwrap().find_item(c).map(|(_, i)| (i.duration, i.source_in)).unwrap();
let (picture_at, sound_at) = (start(&s, second), start(&s, sound));
let ((pic_len, pic_in), (snd_len, snd_in)) = (len(&s, second), len(&s, sound));
let first_before = len(&s, first);
let before = s.project.clone();
let r = s.execute("timeline.trim", json!({"clip": if grab_sound { sound.0 } else { second.0 }, "edge": "in", "mode": "ripple", "deltaFrames": 8})).unwrap();
let by = rate.tick_of(8);
assert_eq!(r["delta"], json!(by.0));
assert_eq!((start(&s, second), start(&s, sound)), (picture_at, sound_at), "both stay where they start");
assert_eq!(len(&s, second), (pic_len - by, pic_in + by), "the picture loses 8 from its head");
assert_eq!(len(&s, sound), (snd_len - by, snd_in + by), "its sound loses the same 8");
assert_eq!(start(&s, second) - start(&s, sound), rate.tick_of(12), "the sound still leads by 12");
assert_eq!(len(&s, first), first_before, "the clip before is untouched");
s.active_sequence().unwrap().check().unwrap();
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(*s.project, *before, "one undo step puts both back");
}
/// Material on a sync-locked track inside the stretch a shorter head takes away still refuses it.
#[test]
fn shorter_head_is_refused_when_a_sync_locked_track_has_material_in_the_stretch() {
let mut s = Session::default();
let (_, second, _) = j_cut(&mut s);
let rate = s.sequence_rate();
let tone = s.project.items.values().find(|i| !i.has_video() && i.has_audio() && i.as_media().is_some()).map(|i| i.id).unwrap();
s.execute("timeline.place", json!({"item": tone.0, "audioTrack": "A1", "frame": 50, "duration": rate.tick_of(24).0})).unwrap();
let before = s.project.clone();
let e = s.execute("timeline.trim", json!({"clip": second.0, "edge": "in", "mode": "ripple", "deltaFrames": 8})).unwrap_err();
assert!(e.to_string().contains("sync"), "{e}");
assert_eq!(*s.project, *before, "a refused trim changes nothing");
}
+33
View File
@@ -335,6 +335,39 @@ fn interchange_roundtrip_through_files() {
let _ = std::fs::remove_dir_all(&dir);
}
/// `file.exportInterchange {format: "<unknown>"}` used to write FCP7 XML without a word.
#[test]
fn export_interchange_refuses_an_unknown_format() {
let d = std::env::temp_dir().join(format!("fc-ix-format-{}", std::process::id()));
std::fs::create_dir_all(&d).unwrap();
let path = |n: &str| d.join(n).to_string_lossy().to_string();
let mut s = demo();
// unknown names, values that are not names, and spellings that are not the documented ones
for bad in [json!("premiere"), json!("mp4"), json!(""), json!(7), json!(["xml"]), json!(".xml"), json!("fcpxmld"), json!("omfi"), json!("xml ")] {
let e = s.execute("file.exportInterchange", json!({"format": bad, "path": path("bad.out")})).unwrap_err();
assert!(matches!(&e, EngineError::BadParams { cmd, .. } if cmd == "file.exportInterchange"), "{bad}: {e:?}");
let e = e.to_string();
assert!(e.contains("unknown format") && e.ends_with("use one of edl, xml, fcpxml, otio, aaf, omf"), "the error lists exactly the accepted names: {e}");
assert!(!d.join("bad.out").exists(), "nothing is written for {bad}");
}
// the documented formats still export (in either case), and no format still means FCP7 XML
let text = |n: &str| String::from_utf8_lossy(&std::fs::read(d.join(n)).unwrap()).into_owned();
s.execute("file.exportInterchange", json!({"path": path("default.xml")})).unwrap();
s.execute("file.exportInterchange", json!({"format": "xml", "path": path("a.xml")})).unwrap();
assert!(text("default.xml").contains("<xmeml") && text("a.xml").contains("<xmeml"));
s.execute("file.exportInterchange", json!({"format": "fcpxml", "path": path("a.fcpxml")})).unwrap();
assert!(text("a.fcpxml").contains("<fcpxml"));
s.execute("file.exportInterchange", json!({"format": "otio", "path": path("a.otio")})).unwrap();
assert!(text("a.otio").contains("OTIO_SCHEMA"));
s.execute("file.exportInterchange", json!({"format": "EDL", "path": path("a.edl")})).unwrap();
assert!(text("a.edl").contains("TITLE:"));
for (format, magic) in [("aaf", "aaf"), ("omf", "omf")] {
let r = s.execute("file.exportInterchange", json!({"format": format, "path": path(&format!("a.{magic}"))})).unwrap();
assert!(r["bytes"].as_u64().unwrap() > 0, "{format}");
}
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn move_items_to_bin_and_back_with_undo() {
let mut s = demo();
+249
View File
@@ -0,0 +1,249 @@
//! `timeline.move`: linked partners follow, locked partners stay, the group stops together at the
//! sequence start, and hostile times are refused.
use filmcraft_project::{ClipId, TrackId, TrackItem};
use filmcraft_time::Tick;
use serde_json::json;
use crate::{EngineError, Session};
fn demo() -> Session {
let mut s = Session::default();
s.execute("file.openDemoProject", json!({})).unwrap();
s
}
fn state(s: &Session, c: ClipId) -> (TrackId, Tick) {
s.active_sequence().unwrap().find_item(c).map(|(t, i)| (t, i.start)).unwrap()
}
/// The last picture clip of V1 and its linked sound: (V1, picture, sound's track, sound).
fn last_pair(s: &Session) -> (TrackId, TrackItem, TrackId, TrackItem) {
let q = s.active_sequence().unwrap();
let v = q.video_tracks[0].items.last().unwrap().clone();
let (a_track, a) = q.audio_tracks.iter().find_map(|t| t.items.iter().find(|i| i.link == v.link && v.link.is_some()).map(|i| (t.id, i.clone()))).unwrap();
(q.video_tracks[0].id, v, a_track, a)
}
/// An empty sequence with one linked picture + sound pair placed at `seconds`: (V1, picture, A1, sound).
fn pair_in_an_empty_sequence(s: &mut Session, seconds: f64) -> (TrackId, TrackItem, TrackId, TrackItem) {
s.execute("file.newSequence", json!({"name": "Moves", "video": 2, "audio": 2})).unwrap();
let item = s.project.items.values().find(|i| i.has_video() && i.has_audio() && i.as_media().is_some()).map(|i| i.id).unwrap();
s.execute("timeline.place", json!({"item": item.0, "seconds": seconds})).unwrap();
let q = s.active_sequence().unwrap();
let (v, a) = (q.video_tracks[0].items[0].clone(), q.audio_tracks[0].items[0].clone());
assert!(v.link.is_some() && v.link == a.link, "a placed clip's picture and sound are linked");
(q.video_tracks[0].id, v, q.audio_tracks[0].id, a)
}
/// `timeline.move` of one clip left its linked sound behind although Linked Selection was on.
#[test]
fn move_takes_linked_partners_along() {
let mut s = demo();
let rate = s.sequence_rate();
let (v_track, v, a_track, a) = last_pair(&s);
let end = s.active_sequence().unwrap().duration();
assert!(s.state.linked_selection, "linked selection is on by default");
let before = s.project.clone();
// only the picture is listed: the sound follows by the same offset, on its own track
let to = end + rate.tick_of(48);
let r = s.execute("timeline.move", json!({"moves": [{"clip": v.id.0, "track": "V1", "time": to.0}]})).unwrap();
assert_eq!(state(&s, v.id), (v_track, to));
assert_eq!(state(&s, a.id), (a_track, a.start + (to - v.start)), "linked audio stays in sync");
assert_eq!(r["moved"], json!([v.id.0, a.id.0]));
s.active_sequence().unwrap().check().unwrap();
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(*s.project, *before, "one undo step restores both clips");
s.execute("edit.redo", json!({})).unwrap();
assert_eq!((state(&s, v.id).1, state(&s, a.id).1), (to, a.start + (to - v.start)));
s.execute("edit.undo", json!({})).unwrap();
// listing both moves each exactly once
let (tv, ta) = (to, a.start + (to - v.start));
let r = s
.execute("timeline.move", json!({"moves": [{"clip": v.id.0, "track": "V1", "time": tv.0}, {"clip": a.id.0, "track": a_track.0, "time": ta.0}]}))
.unwrap();
assert_eq!((state(&s, v.id), state(&s, a.id)), ((v_track, tv), (a_track, ta)));
assert_eq!(r["moved"], json!([v.id.0, a.id.0]));
s.execute("edit.undo", json!({})).unwrap();
// `linked: false` moves just the listed clip, whatever the toggle says
let r = s.execute("timeline.move", json!({"moves": [{"clip": v.id.0, "track": "V1", "time": to.0}], "linked": false})).unwrap();
assert_eq!((state(&s, v.id), state(&s, a.id)), ((v_track, to), (a_track, a.start)));
assert_eq!(r["moved"], json!([v.id.0]));
s.execute("edit.undo", json!({})).unwrap();
// linked selection off: unchanged behaviour, only the listed clip moves
s.execute("sequence.linkedSelection", json!({"on": false})).unwrap();
s.execute("timeline.move", json!({"moves": [{"clip": v.id.0, "track": "V1", "time": to.0}]})).unwrap();
assert_eq!((state(&s, v.id), state(&s, a.id)), ((v_track, to), (a_track, a.start)));
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(*s.project, *before);
// ...unless the command asks for it
s.execute("timeline.move", json!({"moves": [{"clip": a.id.0, "track": a_track.0, "time": ta.0}], "linked": true})).unwrap();
assert_eq!((state(&s, v.id), state(&s, a.id)), ((v_track, tv), (a_track, ta)), "moving the sound takes the picture along");
}
/// A partner on a locked track cannot move; that must not refuse the move of the listed clip.
#[test]
fn a_linked_partner_on_a_locked_track_stays_and_the_listed_clip_still_moves() {
let mut s = demo();
let (v_track, v, a_track, a) = last_pair(&s);
let to = s.active_sequence().unwrap().duration() + s.sequence_rate().tick_of(48);
s.execute("timeline.setTrack", json!({"track": a_track.0, "locked": true})).unwrap();
let r = s.execute("timeline.move", json!({"moves": [{"clip": v.id.0, "track": "V1", "time": to.0}]})).unwrap();
assert_eq!(r["moved"], json!([v.id.0]), "the locked sound is not among the moved clips");
assert_eq!((state(&s, v.id), state(&s, a.id)), ((v_track, to), (a_track, a.start)));
s.active_sequence().unwrap().check().unwrap();
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(state(&s, v.id), (v_track, v.start));
// a listed clip whose own destination is locked is still refused, and nothing moves
let before = s.project.clone();
assert!(s.execute("timeline.move", json!({"moves": [{"clip": a.id.0, "track": a_track.0, "time": to.0}]})).is_err());
assert_eq!(*s.project, *before);
}
/// A partner that would land where it already is does not move: re-placing it would drop the
/// transitions at its edges and list it in `moved` for nothing. Moving only the picture to
/// another track at the same time leaves the sound as it was.
#[test]
fn a_partner_whose_position_does_not_change_is_left_alone() {
let mut s = demo();
let q = s.active_sequence().unwrap();
let a = q.audio_tracks[0].items[1].clone();
let (v_track, v) = q.video_tracks.iter().find_map(|t| t.items.iter().find(|i| i.link == a.link && a.link.is_some()).map(|i| (t.id, i.clone()))).unwrap();
let (a_track, v2) = (q.audio_tracks[0].id, q.video_tracks[1].id);
assert_ne!(v_track, v2);
s.execute("sequence.applyAudioTransition", json!({"clip": a.id.0})).unwrap();
let sound = |s: &Session| s.active_sequence().unwrap().track(a_track).unwrap().clone();
let before = sound(&s);
assert_eq!(before.transitions.len(), 1, "the sound clip has a crossfade");
// picture to V2 at the same time, Linked Selection on
let r = s.execute("timeline.move", json!({"moves": [{"clip": v.id.0, "track": v2.0, "time": v.start.0}]})).unwrap();
assert_eq!(state(&s, v.id), (v2, v.start));
assert_eq!(sound(&s), before, "the sound track, its clip and its crossfade are untouched");
assert_eq!(r["moved"], json!([v.id.0]), "the sound did not move, so it is not listed");
s.execute("edit.undo", json!({})).unwrap();
assert_eq!((state(&s, v.id), sound(&s)), ((v_track, v.start), before.clone()));
s.execute("edit.redo", json!({})).unwrap();
assert_eq!((state(&s, v.id), sound(&s)), ((v2, v.start), before.clone()));
s.execute("edit.undo", json!({})).unwrap();
// a real offset still takes the sound along
let later = v.start + s.sequence_rate().tick_of(2);
let r = s.execute("timeline.move", json!({"moves": [{"clip": v.id.0, "track": v2.0, "time": later.0}]})).unwrap();
assert_eq!(r["moved"], json!([v.id.0, a.id.0]));
assert_eq!(state(&s, a.id).1 - a.start, later - v.start);
}
/// When a clip would start before the sequence start, every clip of the call lands later by the
/// same amount: a split edit keeps its offset and several listed clips keep their spacing.
#[test]
fn the_group_stops_together_at_the_sequence_start() {
let mut s = demo();
let (v_track, v, a_track, a) = pair_in_an_empty_sequence(&mut s, 60.0);
let rate = s.sequence_rate();
let f = |n: i64| rate.tick_of(n);
let (lead, gap) = (f(10), f(100));
// make a split edit: the sound starts 10 frames before the picture
s.execute("timeline.move", json!({"moves": [{"clip": a.id.0, "track": a_track.0, "time": (a.start - lead).0}], "linked": false})).unwrap();
assert_eq!(state(&s, a.id).1, v.start - lead);
// ask for the picture at 4 frames: the sound would start 6 frames before zero
let r = s.execute("timeline.move", json!({"moves": [{"clip": v.id.0, "track": v_track.0, "time": f(4).0}]})).unwrap();
assert_eq!(r["moved"], json!([v.id.0, a.id.0]));
assert_eq!((state(&s, v.id).1, state(&s, a.id).1), (lead, Tick::ZERO), "the sound stops at zero and the picture keeps its 10 frames");
s.execute("edit.undo", json!({})).unwrap();
assert_eq!((state(&s, v.id).1, state(&s, a.id).1), (v.start, v.start - lead));
s.execute("edit.redo", json!({})).unwrap();
assert_eq!((state(&s, v.id).1, state(&s, a.id).1), (lead, Tick::ZERO));
s.execute("edit.undo", json!({})).unwrap();
// a second, unlinked clip 100 frames after the picture, on V2; both listed, both asked 20 frames too far left
let item = s.active_sequence().unwrap().video_tracks[0].items[0].item;
let v2 = s.active_sequence().unwrap().video_tracks[1].id;
s.execute("timeline.place", json!({"item": item.0, "time": (v.start + gap).0, "track": v2.0, "audioTrack": "A2"})).unwrap();
let w = s.active_sequence().unwrap().video_tracks[1].items[0].clone();
let back = v.start + f(20);
let moves = json!([{"clip": v.id.0, "track": v_track.0, "time": (v.start - back).0}, {"clip": w.id.0, "track": v2.0, "time": (w.start - back).0}]);
s.execute("timeline.move", json!({"moves": moves, "linked": false})).unwrap();
assert_eq!((state(&s, v.id).1, state(&s, w.id).1), (Tick::ZERO, gap), "the two clips are still 100 frames apart");
s.execute("edit.undo", json!({})).unwrap();
// with the links followed, the earliest clip of all (the split sound) is the one that stops at zero
s.execute("timeline.move", json!({"moves": moves})).unwrap();
assert_eq!((state(&s, a.id).1, state(&s, v.id).1, state(&s, w.id).1), (Tick::ZERO, lead, lead + gap));
s.active_sequence().unwrap().check().unwrap();
}
/// AGENTS.md §0.8: `time` is any i64. Out-of-range values are parameter errors, never a panic
/// (which `execute` would report as an internal error) and never a wrapped position.
#[test]
fn hostile_times_are_refused_or_clamped_never_a_panic() {
let mut s = demo();
let (v_track, v, a_track, a) = pair_in_an_empty_sequence(&mut s, 60.0);
let before = s.project.clone();
for linked in [true, false] {
for time in [i64::MAX, i64::MAX - 1, Tick::MAX.0 + 1] {
let e = s.execute("timeline.move", json!({"moves": [{"clip": v.id.0, "track": v_track.0, "time": time}], "linked": linked})).unwrap_err();
assert!(matches!(&e, EngineError::BadParams { cmd, .. } if cmd == "timeline.move"), "{time} linked={linked}: {e:?}");
assert_eq!(*s.project, *before, "{time}: nothing moved");
}
// far before the start: the clip lands at zero, as a small negative time does
for time in [i64::MIN, i64::MIN + 1, -1] {
s.execute("timeline.move", json!({"moves": [{"clip": v.id.0, "track": v_track.0, "time": time}], "linked": linked})).unwrap();
assert_eq!(state(&s, v.id).1, Tick::ZERO, "{time}");
assert_eq!(state(&s, a.id).1, if linked { Tick::ZERO } else { a.start }, "{time}");
s.execute("edit.undo", json!({})).unwrap();
}
}
// the sound asked far to the left and the picture far to the right in one call: out of range together
let moves = json!([{"clip": v.id.0, "track": v_track.0, "time": Tick::MAX.0}, {"clip": a.id.0, "track": a_track.0, "time": i64::MIN}]);
assert!(matches!(s.execute("timeline.move", json!({"moves": moves})), Err(EngineError::BadParams { .. })));
// junk entries are skipped as before; a call with nothing usable is a parameter error
for moves in
[json!([]), json!([{"clip": v.id.0, "track": v_track.0, "time": "soon"}]), json!([{"clip": v.id.0, "track": v_track.0, "time": 1e300}]), json!("all")]
{
assert!(matches!(s.execute("timeline.move", json!({"moves": moves})), Err(EngineError::BadParams { .. })), "{moves}");
}
assert!(s.execute("timeline.move", json!({"moves": [{"clip": 987_654_321u64, "track": v_track.0, "time": 0}]})).is_err(), "a clip that does not exist");
assert_eq!(*s.project, *before);
}
/// Moving one narration line onto a spot another line still held shortened that line and said
/// nothing; the result now names every clip the move changed without being asked to.
#[test]
fn a_move_that_lands_on_another_clip_reports_what_it_cut() {
let mut s = demo();
let (_, _, a_track, a1) = pair_in_an_empty_sequence(&mut s, 0.0);
let later = a1.end().0 as f64 / filmcraft_time::TICKS_PER_SECOND as f64 + 2.0;
let item = a1.item.0;
s.execute("timeline.place", json!({"item": item, "seconds": later})).unwrap();
let a2 = s.active_sequence().unwrap().track(a_track).unwrap().items[1].clone();
let line = |c: ClipId, t: Tick| json!({"moves": [{"clip": c.0, "track": a_track.0, "time": t.0}], "linked": false});
// onto empty space: nothing else changes, nothing is reported
let r = s.execute("timeline.move", line(a1.id, a2.end() + Tick(1000))).unwrap();
assert_eq!(r["overwritten"], json!([]));
s.execute("edit.undo", json!({})).unwrap();
// over the head of the next line: that line is shortened (living on under a new id), and the result says so
let half = Tick(a1.duration.0 / 2);
let r = s.execute("timeline.move", line(a1.id, a2.start - half)).unwrap();
let rest = s.active_sequence().unwrap().track(a_track).unwrap().items.last().unwrap().clone();
assert_eq!((rest.end(), rest.duration), (a2.end(), a2.duration - half), "the overwrite itself is unchanged");
assert_eq!(r["overwritten"], json!([{"clip": a2.id.0, "was": a2.duration.0, "now": rest.duration.0, "pieces": [rest.id.0]}]));
s.execute("edit.undo", json!({})).unwrap();
// over its tail: shortened in place, same id
let r = s.execute("timeline.move", line(a2.id, a1.end() - half)).unwrap();
assert_eq!(r["overwritten"], json!([{"clip": a1.id.0, "was": a1.duration.0, "now": (a1.duration - half).0, "pieces": [a1.id.0]}]));
s.execute("edit.undo", json!({})).unwrap();
// squarely onto it: the line under it is gone, and the result names it
let r = s.execute("timeline.move", line(a1.id, a2.start)).unwrap();
assert!(s.active_sequence().unwrap().find_item(a2.id).is_none());
assert_eq!(r["overwritten"], json!([{"clip": a2.id.0, "was": a2.duration.0, "now": 0, "pieces": []}]));
s.execute("edit.undo", json!({})).unwrap();
// inside a longer line: it is split in two around the moved one
s.execute("timeline.trim", json!({"clip": a1.id.0, "edge": "out", "delta": -(a1.duration.0 / 2)})).unwrap();
let short = s.active_sequence().unwrap().find_item(a1.id).unwrap().1.duration;
let r = s.execute("timeline.move", line(a1.id, a2.start + Tick(a2.duration.0 / 4))).unwrap();
let o = &r["overwritten"][0];
assert_eq!(r["overwritten"].as_array().unwrap().len(), 1, "{r}");
assert_eq!((o["clip"].as_u64(), o["now"].as_i64()), (Some(a2.id.0), Some((a2.duration - short).0)), "{r}");
assert_eq!(o["pieces"].as_array().unwrap().len(), 2, "{r}");
// an insert-mode move shifts clips along and covers nothing
s.execute("edit.undo", json!({})).unwrap();
let r = s.execute("timeline.move", json!({"moves": [{"clip": a1.id.0, "track": a_track.0, "time": a2.start.0}], "insert": true, "linked": false})).unwrap();
assert_eq!(r["overwritten"], json!([]));
}
+116
View File
@@ -0,0 +1,116 @@
//! Track parameters (`track`, `audioTrack`: an id, or "V1" / "A2"): a track the active sequence
//! does not have is a parameter error, never a silent default.
use serde_json::json;
use crate::{EngineError, Session};
fn demo() -> Session {
let mut s = Session::default();
s.execute("file.openDemoProject", json!({})).unwrap();
s
}
/// `timeline.place {audioTrack: "A2"}` on a sequence with only A1 used to fall back to the
/// source-patched track and overwrite what was on A1.
#[test]
fn naming_a_missing_track_is_an_error_not_a_default() {
let mut s = demo();
let seq = s.execute("file.newSequence", json!({"name": "One of each", "video": 1, "audio": 1})).unwrap();
let q = s.active_sequence().unwrap();
assert_eq!((q.video_tracks.len(), q.audio_tracks.len()), (1, 1), "{seq}");
let (v1, a1) = (q.video_tracks[0].id, q.audio_tracks[0].id);
let item = s.project.items.values().find(|i| i.has_video() && i.has_audio() && i.as_media().is_some()).map(|i| i.id).unwrap();
// omitted tracks keep their default: the source-patched V1 / A1
s.execute("timeline.place", json!({"item": item.0, "time": 0})).unwrap();
let before = s.project.clone();
let undo = s.history.undo.len();
for (key, name) in [("audioTrack", json!("A2")), ("track", json!("V2")), ("audioTrack", json!(999_999)), ("track", json!("V0")), ("track", json!("X1"))] {
let mut p = json!({"item": item.0, "time": 0});
p[key] = name.clone();
let e = s.execute("timeline.place", p).unwrap_err();
assert!(matches!(&e, EngineError::BadParams { cmd, .. } if cmd == "timeline.place"), "a parameter error of the command: {e:?}");
let e = e.to_string();
let shown = name.as_str().map(str::to_string).unwrap_or_else(|| name.to_string());
assert!(e.contains(&format!("no track {shown} in this sequence")), "{e}");
}
assert!(s.execute("timeline.place", json!({"item": item.0, "time": 0, "audioTrack": "A2"})).unwrap_err().to_string().contains("audioTrack"));
// hostile names are errors too, never a panic
for name in ["", "V", "é1", "1", "V-1", "A1.5", "V99999999999999999999"] {
assert!(s.execute("timeline.place", json!({"item": item.0, "time": 0, "track": name})).is_err(), "{name:?}");
}
// every command that takes a track by name refuses one that is not there
let clip = s.active_sequence().unwrap().video_tracks[0].items[0].id;
let e = s.execute("timeline.move", json!({"moves": [{"clip": clip.0, "track": "V2", "time": 0}]})).unwrap_err();
assert!(matches!(&e, EngineError::BadParams { cmd, .. } if cmd == "timeline.move"), "{e:?}");
assert!(s.execute("sequence.closeGap", json!({"track": "A2", "time": 0})).is_err());
assert!(s.execute("sequence.deleteTrack", json!({"track": "V2"})).is_err());
assert!(s.execute("sequence.deleteTrack", json!({"track": 999_999})).is_err());
assert!(s.execute("timeline.setTrack", json!({"track": "A2", "muted": true})).is_err());
assert!(s.execute("timeline.setTargeting", json!({"track": "V2", "targeted": true})).is_err());
assert!(s.execute("timeline.razor", json!({"track": "A2", "time": 10})).is_err());
assert!(s.execute("sequence.goToNextGapInTrack", json!({"track": "V2"})).is_err());
assert_eq!(*s.project, *before, "nothing was edited");
assert_eq!(s.history.undo.len(), undo, "and nothing was added to the undo history");
// tracks that exist still resolve by name (either case) and by id
s.execute("timeline.place", json!({"item": item.0, "seconds": 60.0, "track": "v1", "audioTrack": a1.0})).unwrap();
s.execute("timeline.setTrack", json!({"track": v1.0, "locked": true})).unwrap();
s.execute("timeline.setTrack", json!({"track": "a1", "muted": true})).unwrap();
let q = s.active_sequence().unwrap();
assert!(q.video_tracks[0].locked && q.audio_tracks[0].muted);
s.execute("edit.undo", json!({})).unwrap();
assert!(!s.active_sequence().unwrap().audio_tracks[0].muted);
}
/// `timeline.place {track: "A3"}` put a picture item on the audio track A3 and a second sound
/// clip on A1; a sound-only item went to A1 whatever audio track `track` named.
#[test]
fn place_on_an_audio_track_places_the_sound_there_and_nothing_else() {
let mut s = demo();
s.execute("file.newSequence", json!({"name": "Sound tracks", "video": 1, "audio": 3})).unwrap();
let a3 = s.active_sequence().unwrap().audio_tracks[2].id;
let with_picture = s.project.items.values().find(|i| i.has_video() && i.has_audio() && i.as_media().is_some()).map(|i| i.id).unwrap();
let sound_only = s.project.items.values().find(|i| !i.has_video() && i.has_audio() && i.as_media().is_some()).map(|i| i.id).unwrap();
let picture_only = s.project.items.values().find(|i| i.has_video() && !i.has_audio() && i.as_media().is_some()).map(|i| i.id).unwrap();
// how many clips sit on [V1, A1, A2, A3]
let counts = |s: &Session| {
let q = s.active_sequence().unwrap();
[q.video_tracks[0].items.len(), q.audio_tracks[0].items.len(), q.audio_tracks[1].items.len(), q.audio_tracks[2].items.len()]
};
// a clip with picture and sound, sent to A3 by name: its sound alone, on A3
let r = s.execute("timeline.place", json!({"item": with_picture.0, "track": "A3", "frame": 0})).unwrap();
assert_eq!(counts(&s), [0, 0, 0, 1], "{r}");
let q = s.active_sequence().unwrap();
assert_eq!(r["clips"], json!([q.audio_tracks[2].items[0].id.0]));
assert_eq!(q.audio_tracks[2].items[0].link, None, "no picture was placed, so nothing to link to");
q.check().unwrap();
// a sound-only item goes to the audio track named, by name or by id
s.execute("timeline.place", json!({"item": sound_only.0, "track": "A2", "frame": 0})).unwrap();
assert_eq!(counts(&s), [0, 0, 1, 1]);
s.execute("timeline.place", json!({"item": sound_only.0, "track": a3.0, "seconds": 120.0})).unwrap();
assert_eq!(counts(&s), [0, 0, 1, 2]);
// what cannot be meant is a parameter error that says why, and changes nothing
let before = s.project.clone();
let undo = s.history.undo.len();
for (p, why) in [
(json!({"item": with_picture.0, "track": "A3", "audioTrack": "A1", "seconds": 300.0}), "name the sound's track once"),
(json!({"item": with_picture.0, "audioTrack": "V1", "seconds": 300.0}), "`audioTrack` names a video track"),
(json!({"item": with_picture.0, "track": "V1", "audioTrack": "V1", "seconds": 300.0}), "`audioTrack` names a video track"),
(json!({"item": picture_only.0, "track": "A1", "seconds": 300.0}), "this item has no sound"),
(json!({"item": sound_only.0, "track": "V1", "seconds": 300.0}), "this item has no picture"),
] {
let e = s.execute("timeline.place", p.clone()).unwrap_err();
assert!(matches!(&e, EngineError::BadParams { cmd, .. } if cmd == "timeline.place"), "{p}: {e:?}");
assert!(e.to_string().contains(why), "{p}: {e}");
}
assert_eq!(*s.project, *before, "a refused place changes nothing");
assert_eq!(s.history.undo.len(), undo, "and adds nothing to the undo history");
// a sound-only item dropped on a video row still lands on the audio track sent with it
s.execute("timeline.place", json!({"item": sound_only.0, "track": "V1", "audioTrack": "A1", "seconds": 900.0})).unwrap();
s.execute("edit.undo", json!({})).unwrap();
// the usual forms are unchanged: picture on `track`, sound on `audioTrack` or the default A1
s.execute("timeline.place", json!({"item": with_picture.0, "track": "V1", "audioTrack": "A2", "seconds": 300.0})).unwrap();
assert_eq!(counts(&s), [1, 0, 2, 2]);
s.execute("timeline.place", json!({"item": with_picture.0, "seconds": 600.0})).unwrap();
assert_eq!(counts(&s), [2, 1, 2, 2]);
}
+22 -5
View File
@@ -56,6 +56,25 @@ fn has_transcripts(s: &Session) -> std::result::Result<(), String> {
if s.project.transcripts.is_empty() { Err("there are no transcripts".into()) } else { Ok(()) }
}
/// Why speech-to-text can't run in this build (no installed transcriber, built without `whisper`).
pub(crate) const NO_SPEECH: &str =
"speech-to-text is not available in this build (built without the `whisper` feature); import a transcript with transcript.set instead";
/// `transcript.generate` can run: a host installed a transcriber or the build has speech-to-text
/// (#97: it reported enabled and then always failed).
pub(crate) fn can_transcribe(s: &Session) -> std::result::Result<(), String> {
if s.transcriber.is_some() || speech_available() { Ok(()) } else { Err(NO_SPEECH.into()) }
}
/// `transcript.downloadModel` can run: built with `speech-download` (#98).
fn can_download(_: &Session) -> std::result::Result<(), String> {
if cfg!(feature = "speech-download") {
Ok(())
} else {
Err("model downloads are not available in this build (built without the `speech-download` feature)".into())
}
}
/// The media item behind a project item (subclips resolve to their parent).
fn media_item(s: &Session, item: ItemId) -> Option<ItemId> {
match &s.project.item(item)?.kind {
@@ -123,9 +142,7 @@ fn transcriber(s: &Session, p: &Value) -> Result<Arc<dyn Transcriber>> {
return Err(speech_err(SpeechError::UnknownModel(model.into())));
}
if !filmcraft_speech::available() {
return Err(EngineError::Other(
"speech-to-text is not available in this build (built without the `whisper` feature); import a transcript with transcript.set instead".into(),
));
return Err(EngineError::Other(NO_SPEECH.into()));
}
let dir = models_dir().ok_or_else(|| EngineError::Other("no data directory for speech models".into()))?;
filmcraft_speech::load(&dir, model).map_err(speech_err)
@@ -427,7 +444,7 @@ pub fn commands() -> Vec<CommandSpec> {
"Transcribe…",
&["Sequence", "Transcript"],
r#"{"items":[id]?,"model":"whisper-base"?,"language":"en|auto"?,"diarize":bool?,"maxSpeakers":n?}"#,
always,
can_transcribe,
generate,
true,
),
@@ -444,7 +461,7 @@ pub fn commands() -> Vec<CommandSpec> {
spec("transcript.inspect", "Inspect Transcript", &[], r#"{"paragraphGapSeconds":f?}"#, always, inspect, false),
spec("transcript.search", "Search Transcript", &[], r#"{"query":str}"#, always, search, false),
spec("transcript.models", "List Speech Models", &[], "{}", always, models, false),
spec("transcript.downloadModel", "Download Speech Model", &[], r#"{"model":"whisper-base"?}"#, always, download_model, true),
spec("transcript.downloadModel", "Download Speech Model", &[], r#"{"model":"whisper-base"?}"#, can_download, download_model, true),
spec("transcript.select", "Mark Selected Text", &[], r#"{"from":word,"to":word?}"#, has_transcript, select, true),
spec("transcript.extract", "Extract Selected Text", &[], r#"{"from":word,"to":word?}"#, has_transcript, |s, p| extract_or_lift(s, p, true), true),
spec("transcript.lift", "Lift Selected Text", &[], r#"{"from":word,"to":word?}"#, has_transcript, |s, p| extract_or_lift(s, p, false), true),
+5 -1
View File
@@ -163,8 +163,11 @@ fn generate_without_a_transcriber() {
let (mut s, item, _) = session();
s.transcriber = None;
let e = s.execute("transcript.generate", json!({"items": [item.0], "model": "nope"})).unwrap_err().to_string();
assert!(e.contains("unknown speech model"), "{e}");
// a build without speech-to-text says that first: the command is disabled (#97)
let why = if filmcraft_speech::available() { "unknown speech model" } else { "not available in this build" };
assert!(e.contains(why), "{e}");
if !filmcraft_speech::available() {
assert!(!s.is_enabled("sequence.transcribe"), "Transcribe Sequence follows transcript.generate");
let e = s.execute("transcript.generate", json!({"items": [item.0]})).unwrap_err().to_string();
assert!(e.contains("whisper") && e.contains("not available"), "{e}");
#[cfg(not(feature = "speech-download"))]
@@ -172,6 +175,7 @@ fn generate_without_a_transcriber() {
}
// defaults to the media of the open sequence's audio clips
s.transcriber = Some(Arc::new(FixedTranscriber { transcript: Transcript::default(), id: "empty".into() }));
assert!(s.is_enabled("sequence.transcribe"), "an installed recogniser enables Transcribe Sequence");
let r = s.execute("transcript.generate", json!({})).unwrap();
assert!(r["items"].as_array().unwrap().len() >= 2, "{r}");
}
+1
View File
@@ -22,6 +22,7 @@ filmcraft-text = { workspace = true }
filmcraft-isobmff = { workspace = true }
filmcraft-prores = { workspace = true }
filmcraft-dnx = { workspace = true }
filmcraft-apv = { workspace = true }
filmcraft-mxf = { workspace = true }
filmcraft-aac = { workspace = true }
filmcraft-h264enc = { workspace = true }
+80
View File
@@ -0,0 +1,80 @@
//! An export depends only on the project and the settings: the same file on every machine, however
//! many cores render it and however the work is cut into steps.
use super::*;
use crate::tests::project;
fn tmp(name: &str) -> String {
let d = std::env::temp_dir().join(format!("fc-export-det-{}", std::process::id()));
std::fs::create_dir_all(&d).unwrap();
d.join(name).to_string_lossy().to_string()
}
/// Export on a machine with `threads` cores: `export` renders one frame per core of the pool it
/// runs in.
fn export_with_cores(threads: usize, settings: &ExportSettings) -> Vec<u8> {
let (p, seq, m) = project();
let pool = rayon::ThreadPoolBuilder::new().num_threads(threads).build().unwrap();
pool.install(|| export(&p, seq, settings, &m, &Progress::default())).unwrap();
std::fs::read(&settings.path).unwrap()
}
/// Export a step at a time with `batch` frames per step (the web app uses 1).
fn export_stepped(batch: i64, settings: &ExportSettings) -> Vec<u8> {
let (p, seq, m) = project();
let prog = Progress::default();
let mut ex = Exporter::new(p, seq, settings, &prog).unwrap();
ex.set_batch(batch);
while !matches!(ex.step(&m, &prog).unwrap(), Step::Done(_)) {}
std::fs::read(&settings.path).unwrap()
}
#[test]
fn same_file_whatever_the_core_count() {
// 24 frames: one full interleave group and a partial one
for (format, ext) in [(Format::ProRes, "mov"), (Format::H264, "mp4"), (Format::Mjpeg, "mov")] {
let settings = |name: &str| ExportSettings { format, path: tmp(&format!("{name}.{ext}")), ..Default::default() };
let reference = export_with_cores(2, &settings(&format!("{}-2", format.id())));
for threads in [3, 5, 16] {
let other = export_with_cores(threads, &settings(&format!("{}-{threads}", format.id())));
assert!(reference == other, "{}: {threads} cores give a different file than 2 cores", format.label());
}
for batch in [1, 7] {
let other = export_stepped(batch, &settings(&format!("{}-b{batch}", format.id())));
assert!(reference == other, "{}: {batch} frame(s) per step give a different file", format.label());
}
}
}
/// Slice NAL units (types 1 and 5) in a length-prefixed (4-byte) H.264 sample.
fn slices_in(sample: &[u8]) -> usize {
let (mut n, mut i) = (0, 0);
while i + 4 <= sample.len() {
let len = u32::from_be_bytes([sample[i], sample[i + 1], sample[i + 2], sample[i + 3]]) as usize;
if let Some(&h) = sample.get(i + 4)
&& matches!(h & 0x1f, 1 | 5)
{
n += 1;
}
i += 4 + len;
}
n
}
#[test]
fn h264_slices_follow_the_frame_size_not_the_cores() {
// 4096 lines = 256 macroblock rows: one slice per four rows on every machine, also on machines
// with fewer than 64 cores (the encoder's default caps the slices at the core count)
let path = tmp("tall.mp4");
let s = ExportSettings { format: Format::H264, path: path.clone(), frame_size: Some((64, 4096)), include_audio: false, ..Default::default() };
let (p, seq, m) = project();
export(&p, seq, &s, &m, &Progress::default()).unwrap();
let bytes = std::fs::read(&path).unwrap();
let file = filmcraft_isobmff::open(bytes.as_slice()).unwrap();
let vt = file.track_of_kind(filmcraft_isobmff::TrackKind::Video).unwrap();
assert_eq!(file.tracks[vt].samples.len(), 24);
for i in 0..file.tracks[vt].samples.len() {
let sample = file.read_sample(bytes.as_slice(), vt, i).unwrap();
assert_eq!(slices_in(&sample), 64, "picture {i}");
}
}
Loaded 100 of 260 files, more files were not shown because too many files have changed in this diff. Show more