255 Commits
Author SHA1 Message Date
Skyler Lehmkuhl 91543202ed Release 1.0.10-alpha (rebuild: egui fork patch fix) 2026-07-14 14:15:10 -04:00
Skyler Lehmkuhl 73104e5803 CI: fail fast when the egui fork's patch doesn't apply
A [patch.crates-io] whose version doesn't satisfy the dependency
requirement is silently IGNORED by cargo — it emits a warning ('patch was
not used in the crate graph') and builds against the real crates.io crate
instead. The 1.0.10-alpha release build hit exactly this: the fork's
version bump to 0.33.3 had never been committed, so CI cloned 0.33.2, the
patch was dropped, and the build failed four minutes later with 'cannot
find type CursorImage' in a file that had nothing to do with the cause.
The one line that explained it was scrolled far above the errors.

Check for the warning right after cloning the fork and fail there, naming
both versions.
2026-07-14 14:14:59 -04:00
Skyler Lehmkuhl a09b0c1a93 Release 1.0.10-alpha 2026-07-14 13:42:01 -04:00
Skyler Lehmkuhl 421f8fdcc6 Bump version to 1.0.10-alpha 2026-07-14 13:42:01 -04:00
Skyler Lehmkuhl 07b2478a0e Merge take management into painting UX branch
Conflicts were almost all upstream's take work inserting code next to
lines our earlier cycle-recording commits had touched, plus one API
change we had to follow:

- ClipInstance trim access changed (ci.trim_start -> a ci_trim_start
  local; trim_end now needs .raw()). Took upstream's form throughout
  timeline.rs; the already-merged lines around each hunk were using it,
  so keeping ours would not have compiled.
- recording.rs wrap_at_cycle now bumps current_pass after
  close_active_notes, so a note held across the boundary has its tail
  attributed to the pass that's ending and its re-opened half to the one
  beginning. Upstream's version is a superset of ours.
- Kept our headers-only timeline mode (drop the track area below 1.5x the
  layer-header width); upstream had not touched that block.

Everything else (TRASH glyph, take actions, SetCycleMidiSeparateTakes,
engine cycle-MIDI plumbing, render_take_menu) was purely additive.

Workspace compiles; daw-backend's 32 tests pass, including the cycle and
MIDI take-slicing suites that sit directly on the resolved code.
2026-07-14 13:27:01 -04:00
Skyler Lehmkuhl 5e73f7f75d Painting UX: unified color/brush tools, tablet buttons, layer opacity
Addresses a batch of issues found during a painting test.

Tools
- Paint bucket used the background color unconditionally. It now picks
  FG/BG like the brush does, via a shared Color: [FG][BG] row that every
  color-using tool renders (brush, bucket, eyedropper).
- The eyedropper previously inferred its target swatch from
  active_color_mode, which was only ever set as a side effect of opening
  a color picker — so where a sample landed depended on invisible state.
  It now has an explicit toggle, and active_color_mode is gone.
- Effect brushes (dodge/burn, sponge, blur, smudge, clone, heal, pattern)
  were stuck on a hardcoded Gaussian dab. Replaced ~20 flat per-tool
  fields with a BrushKind -> BrushSlot model: every dab-painting tool now
  owns its size/strength/hardness/spacing, its .myb preset, and its FG/BG
  choice, and gets the full brush library. base_settings already flowed
  into the dab engine independently of blend_mode, so this needed no core
  or WGSL changes.

Cursors
- Rebuilt around three kinds instead of "icon = cursor": System (real OS
  cursor for Select/Transform), Precise (glyph with a real tip, e.g.
  pencil/pipette), and Badge (crosshair marks the click point, glyph sits
  to its bottom-right) for icons with no focus point.
- Cursors are now OS-composited via egui::CursorImage rather than painted
  into the scene, so they no longer lag the pointer. Glyphs are rasterized
  from egui's font atlas using epaint's own placement maths, so they land
  where painter.text put them. Drops the SVG cursor rasterization path.

Tablet
- The Wayland backend never handled zwp_tablet_tool_v2 Button events, so
  stylus barrel buttons were silently dropped. Both Wayland and X11 now
  emit them, with actions bound in Preferences (Pan/Eyedropper/Eraser).
  A pan-bound button suppresses the tool the way Alt+drag does, since the
  pen tip is still down while panning. Also adds middle-mouse panning.

Timeline
- Raster layers had no opacity control; the slider always drove volume,
  which is meaningless on them. The layer row is now three tiers, and each
  layer only shows controls that apply to it: Vector/Video get both volume
  and opacity (they can hold movie clips with audio), Raster/Text get
  opacity, Audio gets volume. Mute/solo are hidden where there's no audio.
- Layer toggles use Lucide icons with tooltips, and gain a visibility
  (eye) toggle. LayerProperty::Visible already existed but was only
  reachable from the info panel.
- Below 1.5x the layer-header width, the track area is dropped and the
  headers take the full pane.

Panes
- Color picker popups closed on any click (including on their own hue
  slider) and would not close on a drag — so drawing on the stage left one
  open. Shared color_swatch widget closes on a press outside instead.
- Stage header gains undo/redo buttons for tablet use, and taller targets.
- Toolbar is real egui layout (horizontal_wrapped) instead of absolute
  rect math, so it scrolls when the pane is too short.
- Tools with no SVG icon use Lucide glyphs instead of a TODO placeholder.
2026-07-14 13:04:38 -04:00
Skyler Lehmkuhl 8cde113797 Cycle recording phase 1: transport loop region
Adds a cycle (loop) region: a range on the timeline ruler that the
transport wraps at during playback. This is the substrate for
GarageBand-style multi-take cycle recording (phases 2 and 3).

The region is authored in BEATS so it stays put musically across tempo
changes. It lives on the Document (saved in the .beam, serde-defaulted
so old files load) and is edited through SetCycleRegionAction, so it is
undoable and marks the document modified like any other edit.

Backend:
- Engine gains loop_region/loop_enabled plus a wrap at the single
  playhead-advance point in process(). The wrap is phase-preserving
  (modulo, so an overshoot larger than the loop can't strand the
  playhead outside the region) and gated on playhead >= 0 so a count-in
  pre-roll never wraps.
- Sounding voices are deliberately NOT reset at the wrap the way
  Command::Seek does, since that would chop sustain and reverb tails at
  every pass.
- MidiRecordingState::wrap_at_cycle writes note-offs for held notes at
  the region end and re-opens them at the region start, so a key held
  across the boundary can't end up with a negative duration or hang.
- loop_bounds_frozen freezes the region's sample bounds for the duration
  of an *audio* recording. Phrased positively on audio so future
  multi-track recording inherits it: MIDI is beat-segmented and
  tempo-invariant, but audio is segmented geometrically and we have no
  time-stretch, so cross-tempo audio takes wouldn't be compable anyway.
- Command::Play jumps to loop_start when starting from outside the
  region; starting inside it plays from where you are.

Editor:
- Cycle lane along the bottom of the ruler (bottom, so it doesn't cover
  the bar numbers), painted inside render_ruler under the ticks. Only
  exists while looping is armed; with cycle off the ruler is entirely
  the playhead scrubber, as before.
- Drag to create/move/resize with a three-zone hit test, previewed
  locally and committed as ONE action on release. Driven off raw pointer
  state rather than an egui Response: the lane sits inside the timeline's
  content response, and a second widget on the same pixels just contests
  hover every frame.
- snap_to_grid/quantize_grid_size take a min_grid_px "visual coarseness"
  parameter instead of a hardcoded constant, with two named profiles:
  SNAP_PX_FINE for the playhead and clip edges, SNAP_PX_CYCLE (coarser)
  for the cycle region, so loops land on bars rather than odd
  subdivisions.
- Cycle toggle button using the Lucide repeat glyph.

Cargo.lock picks up the 1.0.9-alpha version bump it missed.
2026-07-14 13:03:24 -04:00
Skyler Lehmkuhl 6924fc0ffe Take management: move takes onto the clip instance
Take management should be per clip instance — deleting a take from one
half of a comped split shouldn't pull it out from under the other half.
That's cleanest if the takes themselves live on the instance rather than
the clip, so they do now.

AudioClipType::TakeFolder is gone entirely. A clip is plain Sampled/Midi
content again, and an instance with a non-empty `takes` list simply
OVERRIDES it with whichever take is active. Splitting already clones the
instance, so each half gets its own take list for free — no index
remapping across instances, no copy-on-write, no shared-state surprise —
and comping still works, because the halves can still each select a
different take. It collapsed machinery too: resolve() moved from the clip
to the instance, and owns_audio_pool_index went back to a one-liner.

Management (DeleteTakeAction, DeleteUnusedTakesAction, RenameTakeAction):
- Right-click a clip with more than one take: `Delete "<active take>"`
  and "Delete Unused Takes". Deletion is named after the take that's
  PLAYING rather than being a generic entry, so you pick the victim by
  selecting it — one clear act instead of hunting a small trash icon in a
  list (which is where this started, and it was fiddly).
- Double-click a take in the dropdown to rename it in place.
- What happens to the selection on delete is the subtle part, and there's
  a test per case: deleting a take BELOW the active one shifts the
  selection down so you keep hearing the same take; deleting the ACTIVE
  take lands on whatever slid into its place (not silently back to take
  1); deleting the LAST take steps back one. The only take can't be
  deleted at all — the menu item isn't offered.
- Deleted takes' audio stays in the pool: undo has to put it back, and
  the other half of a split may still be playing it.

Fixes:
- A recording that stopped before the loop came round wasn't joining an
  existing take list — it landed as a separate overlapping clip. Trigger-
  on-wrap is right for the FIRST recording, but once takes exist there,
  a further run is plainly another take however short. The engine can't
  know that (it's document state), so the editor passes `force_takes`
  with the start-recording command and the run is cut and padded to the
  region even with zero wraps. This forced cycle_loop_len and `wrapped`
  apart on the MIDI side: the region length has to be known from the
  start, but the clip should only pin to full-region length AFTER a pass
  completes, or the bar jumps to full width the moment you hit record.
- Recording a second take left BOTH sounding. append_cycle_takes tore
  down the recording's backend clip by looking it up in
  clip_instance_to_backend_map — but on the audio path the recording
  instance isn't in that map yet; it's only added during promotion, which
  the append path skips. The event already carries the engine's clip id,
  so it's handed over explicitly now.
- The take badge is hidden when there's only one take — no choice to make.
2026-07-14 12:58:33 -04:00
Skyler Lehmkuhl c62164c365 Cycle recording: MIDI separate-takes mode, and append to existing folders
Completes the cycle-recording spec. Three related pieces:

MIDI separate takes (Preferences > Audio > "Cycle MIDI recording"):
- Each pass becomes its own MIDI clip, folded into a take folder — the same
  shape audio always gets — instead of merging into one clip. Merge stays
  the default.
- Notes are bucketed by the pass they were played in. The pass counter bumps
  BETWEEN close_active_notes and the re-note_on at a wrap, so a key held
  across the boundary has its sounding half filed under the pass that's
  ending and its re-opened half under the pass that's beginning. Put the bump
  on either side of that pair and the whole note lands in one pass; there's a
  test named for exactly that.
- A silent INTERIOR pass still yields an empty take, so take N is always pass
  N — otherwise the numbering silently shifts and "take 3" stops meaning "the
  third time round". A TRAILING empty pass is dropped: that's what hitting
  stop shortly after a wrap gives you, a stop artifact rather than a take you
  played. (Audio already behaved this way via its short-final-take rule.)
- Still triggers on the wrap: stop inside the first pass and it's an ordinary
  single recording, whatever the preference says.

Append to an existing take folder (AppendTakesAction):
- Cycle-recording over a region that already holds a take folder now ADDS to
  that folder rather than dropping a second clip on top of it, which stranded
  the new takes in an overlapping clip you couldn't audition against the old.
- "Same region" means same start AND same loop length: resize the cycle region
  and you get a fresh folder, rather than takes of a different length appended
  to an existing one, which would break the uniform-take invariant that
  comping-via-split depends on.
- The recording's own clip/instance are throwaway scaffolding here (the takes
  already live in the backend pools), so they're discarded; the single
  AppendTakesAction is the whole undoable step.

Don't play the region you're recording over:
- While recording into a MIDI track, every clip on that track is silenced
  EXCEPT the one being recorded into. A take folder already sitting in the
  cycle region was otherwise playing its active take underneath you on every
  pass, fighting the part you were trying to record.
- The recording clip itself is exempt, because in merge mode that's precisely
  what you want to hear: the overdub you've been building up. Other tracks are
  untouched.
2026-07-14 12:10:08 -04:00
Skyler Lehmkuhl 6629adc7d2 Cycle recording: monitor the MIDI overdub on later passes
In merge mode every pass layers into the same clip, so a later pass has to
PLAY BACK what earlier passes laid down — otherwise you overdub against
silence, which defeats the point of merging (you can't put a hi-hat on a
kick you can't hear).

Two things stood in the way, and they turned out to be the same bug:

- The captured notes only reached the backend's MIDI pool clip at STOP, so
  during the session the sequencer had nothing to schedule. The wrap now
  folds the notes captured so far into the pool clip. Their offsets drop
  straight in: a cycle MIDI recording is anchored at loop_start, so they're
  already region-relative.

- The recording-progress block resizes the clip instance every audio buffer
  from `playhead - start_time`. The playhead jumps BACKWARDS at a wrap, so
  that duration collapsed to zero and grew again on every pass. It reset the
  clip bar to zero each pass (visible), and it shrank the clip instance back
  to nothing at each wrap (invisible) — so even once the notes were in the
  pool, the sequencer saw a zero-length instance and scheduled none of them.

Fixed at the root: once the transport has wrapped, the recording spans the
whole cycle region and STAYS there — it doesn't track the playhead at all.
`cycle_loop_len` (set at the first wrap) pins it, which both holds the clip
bar at full region length after pass one and keeps the instance stretched
across the region so the merged notes get scheduled.

Writing the events reuses the clip's existing Vec, so it's allocation-free
after the first wrap; mutating the pool from the audio thread is what
Command::UpdateMidiClipNotes already does.
2026-07-14 10:39:12 -04:00
Skyler LehmkuhlandClaude Opus 4.8 a5cdbfd0fd Type the time domains: no raw f64 in any time-carrying API
Three bugs in a row came from the same root: a time value crossing an API
boundary as a bare f64, with the caller and the callee disagreeing about
whether it meant seconds or beats. Recording landed at the wrong time,
MIDI clips grew too fast, and a 1-second split played back as half a
second. Each was "obviously" one domain at the call site and read as the
other on the far side. This makes the mismatch a compile error.

Backend API — every time-carrying f64 is gone:
- Commands: Seek/SetOffset/SetTrimStart/SetTrimEnd -> Seconds; MoveClip/
  ExtendClip/CreateMidiClip/AddMidiNote/AddLoadedMidiClip/
  UpdateMidiClipNotes/AddMidiClipSync and all four automation commands ->
  Beats; TrimClip -> TrimRange.
- Events/queries: PlaybackPosition, WaveformChunksReady's time range,
  AudioFileReady::duration, PoolFileInfo, get_playhead_seconds -> Seconds.
- Serialized: MidiClipData::duration and AutomationKeyframeData::time ->
  Beats. Both newtypes are #[serde(transparent)], so the .beam on-disk
  format is unchanged.
- Several controller methods ALREADY took Beats and unwrapped it to shove
  into the command — the newtype was being discarded at the very boundary
  it existed to protect.

TrimRange, for the domain-polymorphic case: a clip's content time is
SECONDS for sampled audio but BEATS for MIDI, so a single newtype can't
express it (there was even a comment in engine.rs saying so, and that
rationalization is what let the bug through). A domain-tagged enum can.
The engine rejects a range whose domain doesn't match the track, and the
range is built from the clip (clip.trim_range()) so callers can't pick
the wrong variant.

ContentTime, for the trim fields: ClipInstance::trim_start/trim_end are
content times, and were the last untyped f64 — the actual root of the
split bug. ContentTime is deliberately a DEAD END: no .to_seconds(), no
.to_beats(), no arithmetic with Seconds or Beats. Content times combine
freely with each other (same clip, same domain — safe), so the ~100
passthrough sites cost nothing; the only exit is resolving against the
clip that knows the domain (AudioClip::resolve_content_time /
Document::resolve_content_time / ClipDuration::same_domain). Mixing
domains no longer compiles.

Two more live bugs the types surfaced:
- ClipInstance::effective_duration_beats took a SECONDS clip duration and
  subtracted trim_start from it. For a TRIMMED MIDI clip that subtracted
  a beats offset from a seconds duration, so the clip's timeline length
  was wrong at any tempo but 60 BPM. Untrimmed clips happened to work,
  which is why it hid. It now takes a ClipDuration and resolves in the
  clip's own domain: beats content carries over directly (tempo-
  invariant), wall-clock content converts at the clip's position.
  Regression test asserts a clip trimmed to beats 2..6 is 4 beats long at
  60/90/120 BPM.
- Trim validation clamped a content-domain trim against a wall-clock gap.
  gap_to_content/content_to_secs now convert at the clip's position.

Also folds two more copies of the backend add-logic into
BackendContext::add_clip_instance (split and remove_clip_instances both
re-add clips), so the trim/duration conversions live in exactly one place
instead of four.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-14 09:31:04 -04:00
Skyler LehmkuhlandClaude Opus 4.8 16e3d676d6 Cycle recording: multi-take capture, take folders, comping
Recording into a cycle region now produces one take per pass. Pick a take
from a badge on the clip; split the clip and pick different takes on the
halves, and you've comped.

Data model (phase 2):
- AudioClipType::TakeFolder { takes, recorded_loop_beats } holds the take
  list on the CLIP; ClipInstance::active_take holds the selection on the
  INSTANCE. That split is what makes comping fall out of the existing
  split action for free — split clones the instance, so the two halves
  share one take list but choose independently. recorded_loop_beats lets
  a future time-stretch/conform pass reconcile audio takes if the tempo
  moves under them.
- AudioClip::resolve(active_take) -> ResolvedContent{Audio|Midi|Recording}
  collapses a take folder to what an instance actually plays. A folder is
  not a distinct *case* at call sites — it's an audio or MIDI clip whose
  identity depends on which take is live — so every backend-sync site now
  resolves through this instead of matching clip_type raw. Reverse lookups
  go through owns_audio_pool_index/owns_midi_clip_id, since a folder owns
  one pool file per take, not just the active one.
- BackendContext::add_clip_instance/remove_clip_instance: switching takes
  is a remove + re-add (there's no in-place pool-swap command), and that's
  the same work AddClipInstanceAction does. One implementation, on the
  context that already owns the controller and both ID maps, so the
  seconds-vs-beats conversions can't drift between copies.

Capture (phase 3):
- Takes are cut GEOMETRICALLY at stop, in exact loop-length multiples. The
  playhead advances before the capture block in process(), so the wrap
  instant isn't sample-exact against the buffer just captured — but the
  geometry is. wrap_count only decides *whether* the recording is
  multi-take, never where the cuts land.
- Partial passes are padded with silence: punch in mid-region and take 1
  gets silence prepended back to the region start; stop mid-pass and the
  last take gets silence appended. Every take is the same length, which is
  the invariant comping depends on. A final take under 50ms of real audio
  is dropped as a stop artifact (but a take that FILLED the region never
  is, however short the region).
- MIDI merges, and it falls out for free: anchoring the recording at
  loop_start rather than the punch-in point means the transport always
  wraps back INTO the region, so every note's offset already lands inside
  [0, loop_len) and passes overdub with no folding logic at all.
- The whole session commits as ONE undoable action via push_applied.

Fixes found on the way:
- Split was seconds/beats confused on MIDI. trim_start/trim_end are
  domain-polymorphic exactly like AudioClip::duration was — SECONDS for
  audio/video/vector, BEATS for MIDI — and split mapped the split point
  into clip content in seconds unconditionally. Now it works in the clip's
  own domain via Document::clip_trim_duration(). Regression test included.
- TrimClip took raw f64s whose meaning flipped by track type, and the
  engine set an AUDIO clip's external_duration = Beats(end - start) where
  those bounds were SECONDS — so a 1-second split played back as half a
  second at 120 BPM. Replaced with a domain-tagged TrimRange, built from
  the clip (clip.trim_range()) so the wrong unit isn't expressible, and
  the span is now converted at the clip's position on the timeline.
- The live preview grew past the loop end while the playhead wrapped. It
  now grows through the first pass then pins at the region length, and the
  waveform inside restarts at the region start on each pass. The pass
  offset is derived from the captured buffer, not the playhead — those
  advance on different clocks, and differencing them made the waveform
  jitter horizontally.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-13 14:40:10 -04:00
Skyler LehmkuhlandClaude Opus 4.8 f957b01dcf Cycle recording phase 1: transport loop region
Adds a cycle (loop) region: a range on the timeline ruler that the
transport wraps at during playback. This is the substrate for
GarageBand-style multi-take cycle recording (phases 2 and 3).

The region is authored in BEATS so it stays put musically across tempo
changes. It lives on the Document (saved in the .beam, serde-defaulted
so old files load) and is edited through SetCycleRegionAction, so it is
undoable and marks the document modified like any other edit.

Backend:
- Engine gains loop_region/loop_enabled plus a wrap at the single
  playhead-advance point in process(). The wrap is phase-preserving
  (modulo, so an overshoot larger than the loop can't strand the
  playhead outside the region) and gated on playhead >= 0 so a count-in
  pre-roll never wraps.
- Sounding voices are deliberately NOT reset at the wrap the way
  Command::Seek does, since that would chop sustain and reverb tails at
  every pass.
- MidiRecordingState::wrap_at_cycle writes note-offs for held notes at
  the region end and re-opens them at the region start, so a key held
  across the boundary can't end up with a negative duration or hang.
- loop_bounds_frozen freezes the region's sample bounds for the duration
  of an *audio* recording. Phrased positively on audio so future
  multi-track recording inherits it: MIDI is beat-segmented and
  tempo-invariant, but audio is segmented geometrically and we have no
  time-stretch, so cross-tempo audio takes wouldn't be compable anyway.
- Command::Play jumps to loop_start when starting from outside the
  region; starting inside it plays from where you are.

Editor:
- Cycle lane along the bottom of the ruler (bottom, so it doesn't cover
  the bar numbers), painted inside render_ruler under the ticks. Only
  exists while looping is armed; with cycle off the ruler is entirely
  the playhead scrubber, as before.
- Drag to create/move/resize with a three-zone hit test, previewed
  locally and committed as ONE action on release. Driven off raw pointer
  state rather than an egui Response: the lane sits inside the timeline's
  content response, and a second widget on the same pixels just contests
  hover every frame.
- snap_to_grid/quantize_grid_size take a min_grid_px "visual coarseness"
  parameter instead of a hardcoded constant, with two named profiles:
  SNAP_PX_FINE for the playhead and clip edges, SNAP_PX_CYCLE (coarser)
  for the cycle region, so loops land on bars rather than odd
  subdivisions.
- Cycle toggle button using the Lucide repeat glyph.

Cargo.lock picks up the 1.0.9-alpha version bump it missed.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-13 02:13:06 -04:00
Skyler Lehmkuhl 9f67a82e3e README: update status + add prebuilt-release run instructions
Export system and node editor UI are complete; piano roll editor is in progress.
Add a "Download a prebuilt release" section (GitHub releases) for users who don't
want to build from source, and nest the build-from-source steps under their own heading.
2026-07-12 09:39:17 -04:00
Skyler Lehmkuhl ddd6e0cdbc Stop tracking TODO.md; remove completed plan docs
TODO.md is personal working notes — untrack it (kept locally) and gitignore it.
Delete GPU_VIDEO_DECODE_PLAN.md and STREAMING_TO_DISK_PLAN.md (the latter already
removed); both plans are complete.
2026-07-12 09:19:59 -04:00
Skyler Lehmkuhl a94f6004e5 Release 1.0.9-alpha 2026-07-12 09:09:17 -04:00
Skyler Lehmkuhl a3706dd2c4 Bump version to 1.0.9-alpha 2026-07-12 09:09:17 -04:00
Skyler LehmkuhlandClaude Opus 4.8 ba4395602d Make recording an undoable action; fixes MIDI recording not marking doc modified
Recording (audio and MIDI) mutated the document directly in the AudioEvent
handlers, outside the action system — so it was never undoable, and dirty-
tracking leaned on an ad-hoc `media_modified` flag that the MIDI stop handler
forgot to set (hence: recording a MIDI clip didn't trigger the save-on-close
prompt).

Recording is temporal (the clip streams into the document live over the take),
so it can't be applied by one synchronous execute(). Instead, commit the
finished take as an *already-applied* action:

- ActionExecutor::push_applied(action) — registers an action whose effect is
  already present (clears redo, bumps the epoch so the doc reads as modified,
  pushes to the undo stack) WITHOUT re-running execute()/execute_backend().
  Undo then removes the content via rollback/rollback_backend; redo re-adds it.
- AddClipInstanceAction::already_applied(...) — constructs the action pre-seeded
  into its post-execute state (executed + the existing backend clip id) so the
  first undo can remove the live-recorded clip from both doc and backend, and
  redo re-adds it through the normal path.
- Both recording stop handlers now finalize, then push_applied this action.
  Keeping the clip in the document (not a transient) matters for streaming-to-
  disk and keeps the doc the single source of truth.

Recordings now bump the epoch like every other edit, so the media_modified
flag is dropped for recordings (kept only as a defensive fallback if the action
can't be built). Whole workspace compiles; 299 core tests pass.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-11 19:23:46 -04:00
Skyler Lehmkuhl 8ed2320dca Type AudioClip duration by clip kind; fix MIDI clips growing too fast
The MIDI-clip-end-grows-too-fast bug was a units confusion: AudioClip.duration
is documented "seconds" but MIDI clips store their length in BEATS (they share
the AudioClip struct with sampled clips). The timeline's effective_clip_duration
read it as raw seconds, so at 120 BPM a MIDI clip rendered ~2x too long. The old
backend-snapshot display had hidden this by forcing timeline_duration in beats.

Root fix — make the domain explicit and unforgeable:
- `duration` is now a private field. Reading it in the wrong unit is impossible
  because access goes through typed accessors: AudioClip::content_duration() ->
  ClipDuration (a Seconds|Beats enum tagged by clip_type) and
  set_content_duration(). serde still serializes the private field, so the .beam
  format is unchanged (bare number).
- ClipDuration::to_seconds(tempo_map) for display/sizing; ::native() for code
  that already works in the clip's native domain (trim math shares it).
- get_clip_duration + the timeline-endpoint calc go through to_seconds, so MIDI
  is converted correctly; effective_clip_duration delegates to get_clip_duration.
- Recording mirrors (audio/MIDI progress + finalize) write via set_content_duration
  (debug-asserts the value's domain matches the clip type).

Every former raw read/write of the field (core actions, timeline, piano roll,
infopanel, asset library, recording handlers) now goes through the accessors.
Whole workspace compiles; 299 core tests pass.
2026-07-11 19:23:37 -04:00
Skyler Lehmkuhl c747126759 Timeline: display audio/MIDI clips from the doc, not a backend snapshot
The timeline was the only place that reconstructed audio-layer clip instances
from a backend snapshot (build_audio_clip_cache) instead of reading the
document like every other layer type. But the document is the actual source of
truth: clip actions mutate *Layer::clip_instances, it's what persists to .beam,
and it drives the backend on load. The snapshot is downstream of it.

That dual source caused the second-recording preview bug: a recording clip
lives only in the document (its backend clip has a temporary pool index of 0,
so the snapshot can't represent it). layer_clips() only fell back to the doc
when the snapshot cache was *empty*, so the first recording previewed but the
second — once the layer already had a finalized clip — was dropped and showed
as zero-length until finalized.

Fix: make layer_clips() read <layer>.clip_instances for audio too, and delete
build_audio_clip_cache + the audio_cache plumbing threaded through ~7 methods
and ~25 call sites. Recording clips grow via the existing RecordingProgress /
MidiRecordingProgress mirror to the doc; finalized clips come from the actions;
both states now live in one place.

Root fix this exposed: get_clip_duration() wrapped every audio clip's duration
as Seconds, but MIDI clips store their duration in BEATS (they share AudioClip
with sampled clips). The snapshot had masked this by always forcing a MIDI
clip's timeline_duration; reading from the doc requires the value to be right,
so get_clip_duration now converts a MIDI clip's beats duration to seconds.

Net -120 lines. Whole workspace compiles; 299 core tests pass. The piano roll
still uses the snapshot for its own MIDI editor (separate pane, out of scope).
2026-07-11 17:07:55 -04:00
Skyler Lehmkuhl 64bf9bb431 Type the rest of the audio-controller boundary (no more bare-f64 wrapping)
Push Beats/Seconds through the remaining controller methods that took a bare
f64 and let the audio thread wrap it in a newtype, so the caller's domain is
now compiler-checked (the seam that hid the recording bug):

- seek -> Seconds
- set_trim_start/set_trim_end -> Seconds / Option<Seconds> (metatrack, always seconds)
- add_midi_note, add_loaded_midi_clip, update_midi_clip_notes -> Beats
- add_automation_point, remove_automation_point, automation_add_keyframe,
  automation_remove_keyframe -> Beats

Command enums stay raw f64 transport; only the public signatures + call sites
change. No behavior change — every caller already passed the right domain, this
just makes it enforced.

Two deliberate exceptions, documented in place:
- trim_clip stays f64: the TrimClip handler interprets it as Seconds for a
  sampled-audio clip but Beats for a MIDI clip, so no single newtype fits;
  callers pass the clip's own trim value, which matches its content domain.
- The piano-roll MIDI note model stays f64 internally (a beats-only subsystem
  with no seconds anywhere); it's converted to Beats at the update_midi_clip_notes
  boundary in UpdateMidiNotesAction, same as trim_start f64 -> Seconds at add_audio_clip.
2026-07-11 14:33:22 -04:00
Skyler LehmkuhlandClaude Opus 4.8 b5766672ee Fix recording start position: pass beats, not seconds, to the backend
The reported bug (a second recording lands early and overlaps the first)
survived the timeline type refactor: start_recording/create_midi_clip/
start_midi_recording took f64 and wrapped Beats(x) internally, so the type
boundary stopped at the method and the timeline handed them *shared.playback_time
(seconds). At 120 BPM a 5s playhead (=10 beats) was recorded at beat 5 = 2.5s.

Type all three backend methods to take Beats so the caller must convert; the
timeline now converts the seconds playhead once (start_beats) and passes it to
every recording command and the placeholder clip. TUI debug caller updated.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-11 14:10:44 -04:00
Skyler Lehmkuhl 0050c18623 Timeline types stage 2: fix editor seconds↔beats at every clip boundary
Thread Beats/Seconds through the editor now that lightningbeam-core is typed.
The timeline UI is seconds-domain (pixels_per_second, viewport_start_time,
playback_time, drag_offset), while ClipInstance.timeline_start/duration/
loop_before are beats — the compiler flagged every place the two were mixed.

Fixes the reported bugs and the whole class behind them:
- Recording placement (audio + MIDI + webcam): the new clip's timeline_start
  was written from playback_time (seconds) into a beats field, so a second
  recording landed at the wrong time. Now converted via the tempo map.
- Drag/move: introduce snapped_move_offset -> Beats (snap in the seconds/pixel
  domain, express the anchor's movement in beats) and moved_start(); the group
  clamp, live preview, and commit all use one uniform beats offset instead of
  adding a seconds delta to a beats position.
- Trim/loop drag preview + commit: overlap limits come from the timeline
  (beats) but trims are content seconds — converted at the boundary.
- Drop (asset drag, stage + timeline), paste, duplicate, split-at-playhead:
  all convert the seconds drop/playhead position to beats before placing.
- Stage playback gates + clip-local time remap: compared seconds playback_time
  against beats timeline_start; now both in seconds.
- Piano roll / infopanel / effect export: clip_dur is Seconds; effect and
  waveform data converted at use.

Core API refinement (motivated by the above): find_max_trim_extend_left/right
now return Seconds (the content-seconds gap) instead of raw Beats, since every
trim caller wants seconds; loop-extend callers convert to beats. Added a
beats_to_x() timeline helper.

Whole workspace compiles; 299 core tests pass.
2026-07-11 14:10:38 -04:00
Skyler Lehmkuhl 053a77cfa1 Timeline types stage 1: make lightningbeam-core Beats/Seconds-typed
Type ClipInstance.timeline_start/timeline_duration/loop_before as Beats and
thread Beats/Seconds through core so the compiler catches the seconds-vs-beats
mismatches behind the audio-clip placement/drag/trim bugs.

Fixes latent mixups surfaced by the types:
- add/remove/split clip instance: the audio "effective duration" fallback was
  the content-seconds span treated as beats (clips stopped early off 60 BPM);
  now converted via the tempo map at the clip's start.
- trim validation: extend-left/right clamped a content-seconds delta against a
  timeline-beats gap (and moved trim_start + timeline_start by the same raw
  amount, assuming 1:1). Now the gap is converted to content seconds and the
  timeline moves by the beats-equivalent.
- split content-split point mixed beats into a seconds trim value.
- set_keyframe: visibility-start fallback returned beats where seconds expected.
- hit_test: timeline_time (s) compared against beats without conversion.

Typed backend boundaries that were passing beats/seconds as bare f64:
add_audio_clip (start/dur Beats, offset Seconds), move_clip/extend_clip (Beats),
set_offset (Seconds). Command enum transport stays f64.

Serialization is unchanged (Beats/Seconds are #[serde(transparent)]).
lightningbeam-core builds; 299 core tests pass. The editor call sites
(recording/drop/paste/drag placement) are updated in stage 2.
2026-07-10 09:36:07 -04:00
Skyler Lehmkuhl 0eff5f7f33 Release 1.0.8-alpha 2026-07-09 18:26:37 -04:00
Skyler Lehmkuhl b6f43d2e72 Bump version to 1.0.8-alpha 2026-07-09 18:26:37 -04:00
Skyler LehmkuhlandClaude Opus 4.8 8fbb6d65c0 Prompt to save on quit too; unify with the switch prompt
Closing the window with unsaved changes was a silent data-loss path — and worse,
a clean exit deletes the recovery file, removing the safety net too.

Fold quitting into the same unsaved-changes flow as file switches: one
PendingAction enum (NewFile / Open / Quit), one modal, one do_action, one
after_save handler. render_unsaved_prompt now also intercepts the window-close
request (CancelClose + queue a Quit prompt); Save & Quit saves then closes,
Discard & Quit closes now, Cancel keeps the window open. confirmed_close lets the
final programmatic close through instead of re-intercepting it.

Replaces the near-duplicate close-prompt/switch-prompt code with a single path.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 18:17:37 -04:00
Skyler Lehmkuhl 6aece26a8b Prompt to save unsaved changes before switching files
New File / Open / Open Recent previously discarded unsaved work with no warning
(three // TODO: Prompt to save markers). They now route through request_switch,
which shows a Save / Don't Save / Cancel modal when the document is modified:
  • Save  — saves first (Save As for untitled/recovered docs), then switches once
    the background save completes (switch_after_save).
  • Don't Save — switches and discards.
  • Cancel — stays put.

"Modified" is tracked without hooking every edit site: current epoch vs a
saved_epoch baseline (rebased on manual save / new / load), plus a media_modified
flag for imports/recordings that don't bump the action epoch. Recovered documents
count as modified until given a real home, so switching away from unrecovered work
also prompts.
2026-07-09 18:17:27 -04:00
Skyler Lehmkuhl ef2b0822bd Autosave: keep recovery files out of Recent Files
Recovering a file loaded it through the normal load path, which added it to
Recent Files — so an internal recovered-*.beam in the app data dir showed up in
the Recent list (and could even be auto-reopened as "last session").

Skip add_recent_file for recovery paths on load, and clean any that older builds
already leaked into Recent at startup (before the auto-reopen check reads it).
2026-07-09 18:05:46 -04:00
Skyler Lehmkuhl 5f09222f3f Autosave: configurable interval + startup logging for testing
- LB_AUTOSAVE_SECS overrides the 45s autosave interval (e.g. =5) so the recovery
  flow can be exercised without a long wait.
- Log the session's recovery file path at startup so it's easy to find.
2026-07-09 17:43:27 -04:00
Skyler Lehmkuhl b0e965b1c2 Crash recovery: restore prompt for leftover recovery files
Second half of autosave/recovery — the read/restore side.

At startup, scan the recovery dir for session-*.beam files. Since a clean exit
deletes this session's file (on_exit), any leftover means a previous session
crashed or was killed with unsaved work. Offer the newest via a modal:
  • Recover — rename it out of the session-* namespace (to recovered-*) and open
    it as the current file. It's renamed, not deleted, because recovered raster
    keyframes page in from it on demand; renaming also stops it being re-offered.
  • Discard — delete it.
  • Later — keep it for next launch, stop prompting this session.

Because a recovered file lives in the app data dir, Save behaves as Save As for
it (both the menu action and the Save-As default directory skip recovery paths),
so the work lands where the user wants rather than back in the data dir.

recovered-* files older than a week are garbage-collected at startup.
2026-07-09 17:29:30 -04:00
Skyler Lehmkuhl 6596acb3db Crash recovery: background autosave to a per-session recovery file
First half of the autosave/recovery feature — the write side.

Every ~45s while the document is dirty, write the full current state into a
per-session recovery .beam in the app data dir (directories::ProjectDirs data
dir + /recovery/session-<uuid>.beam). Fully background: reuses the existing file
worker, so the pool serialization / encode / DB write all happen off the UI
thread. The only UI-thread cost is one document clone — and build_save_command
now stamps the UI layout onto the *snapshot clone* rather than the live document
(the old prepare_document_for_save mutated live state via Arc::make_mut, which
could deep-clone the whole document mid-frame). Removed that dead helper.

Dirtiness is tracked centrally via ActionExecutor::epoch() (now also bumped on
undo/redo, not just execute) plus a pending_event flag set by non-action changes
(imports, finished recordings). The baseline is rebased on new/load/manual-save
so a freshly-loaded or just-saved project stays quiet. Idle-after-edit still gets
one snapshot via a single request_repaint_after wakeup; completion is polled
lazily (no forced repaints during the write).

on_exit deletes the session's recovery file, so a leftover file on next launch
means an unclean shutdown — the hook the recovery prompt (next commit) keys on.
2026-07-09 17:20:54 -04:00
Skyler Lehmkuhl d6b86a14b1 Save: skip re-encoding unchanged raster keyframes
save_beam re-encoded every resident raster keyframe to PNG (+ proxy) on every
save, even untouched frames — the dominant per-save cost for painting/animation
projects (the code noted this as deferred "Phase 3").

The infrastructure to do it incrementally already exists: kf.dirty means "current
pixels not yet in the container" (set on any edit, cleared on a successful save,
per main.rs), and it's preserved in the document clone the save worker receives.
Gate the encode on it: a clean keyframe already stored keeps its full + proxy rows
untouched; only dirty (or not-yet-stored) frames are re-encoded. Media blobs were
already incremental; this closes the raster gap.

No new data-loss risk: the mid-save-edit race (edit between the document clone and
save completion) is pre-existing and identical to the old full-write path.
2026-07-09 13:58:34 -04:00
Skyler Lehmkuhl a2839f80b1 Clean up build warnings 2026-07-09 13:24:32 -04:00
Skyler Lehmkuhl 6e6feaddf5 Fix FLAC export end-to-end (real backend path) + smart tag defaults
The prior audio-tags commit put real FLAC + metadata into export/audio_exporter.rs
— which turned out to be dead code (declared, never called; whole file was
EngineController::start_export_audio → daw-backend's export_audio, which still
routed FLAC to the erroring hound stub — hence "not implemented in daw-backend".

Move the work to where export actually happens:
- daw-backend/src/audio/export.rs: real ffmpeg FLAC (16-bit S16 / 24-bit S32,
  skipping the trailing empty flush packet the FLAC muxer rejects); apply_metadata
  on MP3/AAC/FLAC output; RIFF LIST/INFO chunk appended to WAV. New metadata field
  on the backend ExportSettings, threaded from the UI in run_audio_export. Tests
  assert real fLaC magic + round-tripped tags, and a valid WAV INFO chunk.
- Delete the dead export/audio_exporter.rs (removes the duplicate FLAC impl).

Smart tag defaults (filled only when empty, never clobbering edits):
- Year → current civil year, computed from the system clock with i64 math (no
  date crate; correct past 2038/2106 — tests cover post-i32/u32 timestamps).
- Artist → last-used value, else the OS username ($USER/%USERNAME%).
- Album → last-used value.
Last-used Artist/Album persist in AppConfig and prefill next export.
2026-07-09 13:09:54 -04:00
Skyler Lehmkuhl 15bdf80ec1 Audio export: real FLAC + tag metadata for all formats
- FLAC is now real FLAC via ffmpeg, not WAV bytes in a .flac file. 16-bit uses
  S16, 24-bit uses S32 (ffmpeg's flac encoder emits bits_per_raw_sample=24).
  The flush emits a trailing empty packet that the FLAC muxer rejects as
  "invalid data" — it's skipped.

- Tag metadata (title/artist/album/genre/year/track/comment) written into every
  format via each container's native tags: ID3v2 (MP3), MP4 atoms (M4A), Vorbis
  comments (FLAC) set through ffmpeg's output metadata; RIFF LIST/INFO appended
  to the hound-written WAV (with a fixed-up RIFF size). New AudioMetadata type
  on AudioExportSettings; dialog gains a Tags section and defaults Title to the
  project name.

Tests: FLAC is a real fLaC container with round-tripped tags; WAV keeps a valid
RIFF with a working INFO chunk.
2026-07-09 12:52:37 -04:00
Skyler Lehmkuhl 6b8a1f1386 SVG export: emit text layers as real glyph outlines
SVG export silently dropped Text layers (they fell through the layer_to_svg
catch-all) while the dialog implied only raster/video/effect were excluded, so
title/caption text vanished from a "lossless" export with a success message.

Emit text as actual glyph-outline <path>s: lay the text out with the same
parley path the renderer uses, then extract each positioned glyph's outline
with skrifa (an OutlinePen that maps points into document space — Y flip,
synthetic-italic skew, variable-font normalized coords). Result is
font-independent and needs no <text>/@font-face. Vello rasterizes glyphs on the
GPU and doesn't expose the path, but the skrifa outline API it uses is directly
callable and parley's glyph IDs are real font GIDs, so the outlines match.

Synthetic bold is not applied (rare). Adds a skrifa dep pinned to parley's 0.43.
2026-07-09 07:10:59 -04:00
Skyler Lehmkuhl 53ffb7d528 Export honesty: real lossy WebP, working ProRes, VP8+audio container
Three cases where an export produced something that didn't match what the UI
offered:

- WebP quality slider was a no-op: image 0.25's WebP encoder is lossless-only,
  so the slider did nothing and files were needlessly large. Encode lossy WebP
  via ffmpeg's libwebp instead (already linked); the quality knob is now real
  and alpha is preserved as YUVA420P. Test asserts a lossy VP8 chunk + that
  quality changes file size.

- ProRes 422 always failed to open: the SDR path fed prores_ks 8-bit YUV420P,
  but it requires 10-bit 4:2:2. Add a CpuYuv422P10Converter (RGBA→YUV422P10LE,
  BT.709) and route ProRes through the existing async pipeline in CPU mode;
  setup_video_encoder now emits YUV422P10LE + prores_ks HQ profile and
  encode_frame handles 4:2:2 chroma. Test guards that the encoder opens.

- VP8+audio failed at mux: the parallel path wrote the temp video to a
  hardcoded .mp4, which VP8 can't live in. Derive the temp container from the
  codec (VP8/VP9 → .webm).
2026-07-09 06:58:04 -04:00
Skyler LehmkuhlandClaude Opus 4.8 c373af461e Add animated GIF export
New export format alongside audio/image/video/SVG. GIF is multi-frame like
video but palette-quantized with no audio, so it reuses the per-frame RGBA
render/readback path (render_frame_to_gpu_rgba) and streams frames to a
background encoder.

- core: GifExportSettings (resolution, framerate, loop, transparency, fit,
  time range) with centisecond-quantized frame delay + tests.
- gif_exporter: encoder pipeline. Per-frame NeuQuant quantization is the
  dominant cost and is per-frame independent, so it's fanned out across a
  worker pool (cores-1, capped 8); a writer thread reorders and LZW-encodes
  sequentially. Uses the `gif` crate directly (already resolved via `image`).
- orchestrator: start_gif_export + render_next_gif_frame (one frame per egui
  update), wired into is_exporting/has_pending_progress/cancel.
- dialog: GIF tab + settings; main.rs: handle ExportResult::Gif and pump frames.
- Cargo: opt-level=3 for gif/color_quant/weezl in the dev profile so debug
  builds aren't crippled by unoptimized NeuQuant loops.

Together these cut a 10s GIF export from ~1:43 to ~3s.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 06:02:47 -04:00
Skyler Lehmkuhl 6e361aa30c Reset audio backend on new file / project load
The backend's Command::Reset (full teardown: rebuilds Project, audio/buffer
pools, ID counters) was never invoked from the UI. New File and project loads
only cleared app-side maps, so the previous file's tracks and loaded
instruments stayed resident in the backend and kept getting mixed on every
audio callback.

Add a reset_audio_backend() helper (controller.reset() + clear app-side track
maps and backend-derived caches) and call it in the three teardown paths:
NewFile, create_new_project_with_focus, and apply_loaded_project. Also drops a
duplicate layer_to_track_map.clear() in the NewFile handler.

Race-free: the audio thread drains all command_tx commands before any query_tx
queries each callback, so Reset (a command) runs before the track/pool rebuild
(queries), even though they travel on separate channels.
2026-07-09 06:01:34 -04:00
Skyler LehmkuhlandClaude Opus 4.8 bb6b6fa9e3 Mobile: address code-review findings
Fixes from a review of the mobile-UI branch.

- Guard the inspector size clamps so min<=max (f32::clamp panics otherwise) and set a
  window min_inner_size; prevents a crash / degenerate layout at small sizes. Same
  small-size guards for the piano-roll landscape toggle bar and the intent grid.
- Landscape 2->1 edge reveal: snap to fullscreen at frac>=0.5 (the preview's phase
  boundary) instead of COLLAPSE_HI, so releasing mid-drag no longer jumps backward.
  Both edges.
- Gate the double-tap-drag marquee to mobile so it can't hijack a desktop Brush/Draw
  drag.
- Timeline mobile long-press: request a repaint while counting down so it fires even
  when the finger is held perfectly still.
- Landscape folded top bar: lay the filename+search+overflow cluster out within a
  reserved center span (gutters for the pane's own label/buttons) and elide the
  filename, so it can't overlap or overflow the header.
- Node editor connect/disconnect: assert + document the top-level-graph assumption.
- Palette search field focuses only when unfocused (no per-frame focus stomp); reset
  the inspector tap-anchor on orientation change; remove stale main.rs.backup.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 01:55:40 -04:00
Skyler Lehmkuhl 9646eef487 Mobile: hide the desktop menu bar
Gate the top menu bar on !mobile_active(). Its commands are all reachable from the
mobile shell (⌕ command palette, ⋯ overflow, and the stage/timeline context menus),
so the desktop menu bar is redundant on mobile and just wastes a strip of vertical
space. Desktop unchanged.
2026-07-03 01:08:56 -04:00
Skyler Lehmkuhl 6f67ddb709 Mobile P7: landscape / orientation support
Make the phone shell orientation-aware (portrait vs landscape). Orientation is
aspect-based (rotation = a resize the shell re-lays-out each frame); LB_MOBILE_UI=2
opens a landscape dev window. `SharedPaneState.is_portrait` is published to panes.

- Stack caps at 2 panes in landscape (max_panes through the R1–R6 drag ops), with a
  per-frame clamp so rotating while 3 are open drops to 2.
- Edge drags are a continuous full-height reveal instead of stalling at the capped
  trigger: 1-pane → split → next-pane-fullscreen, and (landscape 2-pane) a two-phase
  slide-then-collapse to 1 pane. Both top and bottom edges, mirrored. Release snaps to
  stay / split / fullscreen. Dividers resize and collapse-to-1 at the extremes.
- Inspector becomes a right-side vertical column in landscape (inspector_width_frac,
  left-edge horizontal resize); portrait keeps the bottom sheet.
- Piano roll: vertical "Synthesia" view in portrait; landscape shows a Keys/Notes
  segmented toggle over the conventional horizontal roll / full keyboard.
- Start screen reflows to 2 rows × 3 with the recent list beside it in landscape.
- Landscape headers are shorter (52→34px) and the top bar folds into the middle of the
  top pane header (no separate band), reclaiming vertical space.

All gated to mobile; desktop unchanged (is_portrait defaults true).
2026-07-03 01:07:58 -04:00
Skyler Lehmkuhl 2cbc35f181 Mobile context-menu coverage + z-order
Hook up menu-bar actions that lacked a mobile affordance, and implement z-order.

- Stage/object long-press menu (stage.rs): add Paste (on clip, geometry, and
  empty stage) and Send to Back / Bring to Front on the selection.
- Timeline long-press menu (timeline.rs): the timeline had no mobile context
  menu — add one via manual long-press detection. Clip actions (Split,
  Duplicate, Cut, Copy, Paste, Delete) on a clip; animation actions (New/Blank
  keyframe, Add keyframe at playhead, Duplicate keyframe, Delete frame, Add
  motion/shape tween) on an empty lane. Gate the desktop right-click menu to
  !is_mobile so mobile shows only the long-press menu.
- Implement Send to Back / Bring to Front (were // TODO no-ops): new undoable
  ReorderClipInstancesAction in lightningbeam-core reorders the selected
  instances within their layer's clip_instances Vec (stacking order; last =
  on top; geometry stays flattened underneath). Wired via handle_menu_action.
2026-07-02 10:07:53 -04:00
Skyler Lehmkuhl 4f66ddb515 P6b: mobile node editor — Focus & Patch views
Replace the desktop node-graph canvas with touch-native views on mobile
(wireframe Plate 07), gated on is_mobile in NodeGraphPane::render_content; the
desktop draw_graph_editor path is untouched. New submodule
panes/node_graph/mobile.rs.

Focus view:
- The focused module's parameters as touch controls (slider / dropdown / field
  by the desktop widget rule, with a visible slider rail); editing mutates the
  graph ValueType so the existing check_parameter_changes dispatches
  SetParameterAction.
- A full-width minimap strip (tap the nearest node to focus it), travel chips
  naming connected endpoints (tap to jump), and an Add-node picker that creates
  the frontend node + AddNodeAction and focuses it.
- Bespoke nodes (Sampler/Script/Sequencer/AmpSim/Oscilloscope) render their
  existing desktop bottom_ui; sampler/script-sample loads are wired (other
  custom interactions are a case-by-case follow-up).

Patch view:
- Per-section egui::Grid so input/output port arrows align in a column. Each
  port's Lucide direction arrow (from-line/to-line, tinted by DataType) is
  clickable to arm a cable; a compatibility-filtered picker completes it
  (ConnectAction). Cable chips (remote-node · remote-port) tap to disconnect
  (DisconnectAction). Parallel cables allowed.

Also: add ARROW_RIGHT_FROM_LINE / ARROW_RIGHT_TO_LINE to mobile/icons.rs
(codepoints extracted from lucide.ttf via ttx).
2026-07-02 09:26:11 -04:00
Skyler Lehmkuhl b14972f657 P6a: mobile music surface (keyboard-primary instrument pane)
The mobile Piano Roll becomes a unified, keyboard-primary instrument surface
(wireframe Plate 04/08): a playable keyboard as the base, revealing a
Synthesia-style falling-notes roll above it when the pane is tall enough.

- Shared keyboard geometry (panes/keyboard_layout.rs): width-driven, pan-aware
  pitch->x, so the roll's note columns stay aligned with the Virtual Piano keys.
  Shared keyboard_octave + keyboard_pan_x in SharedPaneState.
- Piano Roll vertical mode (is_mobile): notes as columns falling toward an amber
  now-line by the keys, tempo-map converted (beats->seconds) so onsets cross the
  line exactly when they sound. Vertical drag scrubs the timeline; horizontal
  drag smoothly scrolls the keys (snaps to nearest key on release). Long-press
  creates a note (drag to size) or resizes an existing one; pan suppresses it.
  The keyboard is embedded (reuses Virtual Piano render + MIDI); the standalone
  VirtualPiano stack slot is removed. show_roll is driven by the snapped pane
  size-class so the keyboard<->roll reveal lands on a stack snap point.
- Virtual Piano: renders via the shared layout on mobile, colors playback_notes
  like pressed keys, gates note-on/glissando to presses that start on the keys
  (never gating release), and hides QWERTY hints on mobile.
- Transport formats by document.timeline_mode (Measures->bar.beat.tick,
  Frames->MM:SS:FF, Seconds->MM:SS.mmm) — per project type, like desktop.
- In-pane instrument header (name + Presets + REC). Recording is driven from the
  app each frame (not the Timeline pane's render) so REC works regardless of
  visible panes, and stopping playback stops recording.
- Compose/Record intent opens Timeline + instrument pane; mobile central panel is
  full-bleed (no inner margin) so panes sit flush.
- phone-ui-sketches.html: inst-bar moved to the top of the music surface.
2026-07-02 07:50:37 -04:00
Skyler Lehmkuhl 77eb2c2d33 Fix oscillator/synth phase wraparound drift
Replace conditional-subtraction phase wrapping with a single stable wrap:
- OscillatorNode: `(phase + freq_mod/sr).rem_euclid(1.0)` — also wraps correctly
  when FM drives freq_mod negative (the old `if >= 1.0` wouldn't).
- SynthVoice: `(phase + frequency/sr).fract()`.
Repeated `if phase >= 1.0 { phase -= 1.0 }` accumulates f32 rounding error over
long-held notes, drifting the timbre.
2026-07-02 01:15:45 -04:00
Skyler Lehmkuhl 4f58edf436 P5 follow-ups: double-tap priority, inspector dismiss, breadcrumb path
- Mobile double-tap is now a single tool-independent priority chain: object →
  enter (movie clip or group); empty inside a clip → exit one level; empty at
  root → zoom-to-fit. Desktop keeps its own select-tool double-click (gated).
- Inspector "tap outside to dismiss" now only HIDES the sheet (with a dismissed
  flag reset on selection change) instead of clearing the selection — the earlier
  clear clobbered the selection before menu/omnibutton actions ran, breaking
  Group/Convert/Cut/Copy. Delete also clears focus so it dismisses the inspector.
- Breadcrumb shows the full editing path (Scene 1 › … › current) via a new
  SharedPaneState.editing_clip_path / EditingContext::clip_path(); each ancestor
  crumb jumps to that level (pending_exit_to_depth → EditingContext::exit_to_depth).
- Remove the "Vello Stage" debug overlay; move the breadcrumb up to the top-left.
2026-07-02 01:14:38 -04:00
Skyler Lehmkuhl 01b20165cc P5 mobile gestures + long-press context menus
Gestures (Stage + Timeline):
- Pinch-zoom via zoom_delta() (touch pinch + Ctrl+wheel), unified with the raw-wheel
  path so Ctrl+wheel zooms exactly once; plain wheel zoom + trackpad pan preserved.
- Double-tap empty → zoom-to-fit (Stage: artboard via zoom_to_fit; Timeline: new
  fit_to_project over the full duration).
- Double-tap-drag on empty → transient marquee regardless of the active tool.

Long-press context menu: a shared SharedPaneState.mobile_context_menu that panes
populate with (label, MenuAction) items on secondary_clicked(); the mobile shell
renders one persistent popup (styled like the timeline menu) and dispatches via
pending_menu_actions. Stage offers Cut/Copy/Duplicate/Delete for clip instances and
Cut/Copy/Convert-to-movie-clip/Delete for geometry.

Fixes surfaced along the way:
- Geometry delete now frees selected fills (free_fill) and GCs isolated vertices
  (new VectorGraph::gc_isolated_vertices) — no more orphaned fills / phantom snap
  points; applies to the Delete key too.
- clipboard_delete_selection clears focus so deleting dismisses the mobile inspector.
- Mobile inspector: appears on pointer release (not press) so drags aren't
  interrupted; reflows only when the tapped point is actually behind the sheet; taps
  outside the sheet dismiss it; rounded-corner border no longer detaches.
2026-07-02 00:11:49 -04:00
Skyler Lehmkuhl 4b2802076b Touch-friendly egui widgets on mobile; egui-based inspector header
Add mobile::apply_touch_style(ctx) — applied every frame when mobile is active —
enlarging egui's global spacing/sizing (interact_size, button padding, slider
width/rail, combo width/height, icon sizes, scrollbar, body/button text) so the
standard widgets in panes and dialogs are finger-sized. Desktop is untouched.

Rework the mobile inspector header into a single row using real egui widgets:
title (left, truncating) + Timeline/Nodes jump buttons + ✕ close, laid out with
egui layouts so they inherit the touch sizing and theme visuals instead of being
hand-painted.
2026-07-01 07:28:13 -04:00
Skyler Lehmkuhl 943ff7c15f Unify colors via theme CSS variables; theme egui visuals
Add Theme::var(name, ctx) (CSS custom-property getter) and Theme::apply_to_egui(ctx)
which maps the palette onto egui's global Visuals so standard widgets share the
theme colors. Add a mobile::palette::Palette built from the theme each frame and
replace the duplicated per-file C_* color constants across all mobile modules
(omni, topbar, stack, inspector, transport, intent, shell) with it. Add --scrim
and --accent-* category vars to styles.css. Apply the theme visuals every frame in
update(). Mobile and the main UI now share one CSS-variable-driven palette that
responds to light/dark/user themes.
2026-07-01 07:08:00 -04:00
Skyler Lehmkuhl f13a127c9d Fit modal dialogs to the phone screen on mobile
Add mobile::dialog_width(ctx, desired) — a min()-clamp that's a no-op on wide
desktop screens. Clamp the Export and Export Progress modals and the Sample
Import window to it. Render Preferences as an egui::Modal (dim backdrop, centered,
no title bar) with a screen-fit scroll height when mobile_active(); desktop keeps
its window. Extracted the preferences body into render_body() shared by both paths.
2026-07-01 06:28:04 -04:00
Skyler Lehmkuhl a0ac4f2d35 Add mobile top bar: filename + command palette (⌕) + overflow (⋯)
Reserve a slim top bar in the mobile shell showing the project filename (or
"Lightningbeam" when unsaved) on the left, and ⌕/⋯ on the right. ⋯ opens a
curated overflow sheet (Save/Save As/Open/New/Import/Export/Undo/Redo/
Preferences); ⌕ opens a command palette that searches the whole menu tree
(flattened from MenuItemDef::menu_structure()). Both dispatch MenuActions.
Completes the P4 omnibutton + global menu.
2026-07-01 06:09:26 -04:00
Skyler Lehmkuhl b8419778a5 Add omnibutton FAB (P4); fix Stage playback freeze when timeline hidden
Omnibutton (mobile/omni.rs): a context FAB whose radial holds the active layer's
drawing tools laid out in a staggered inner/outer arc, plus a "+New" petal
(create Vector/Audio/MIDI/Raster/Video layer, Group, Import, and Split/Duplicate
when a clip is selected — dispatched as MenuActions) and a "more" petal that
opens a full-tools grid when the layer has extra tools. Contextual: the tool ring
only appears when the Stage is in the visible window; off-Stage the FAB is a
"+New" create button. Tools/creates use Lucide icons. Pane-internal adds
(nodes/notes/instruments) deferred to P6.

Playback fix: document.current_time (read by the renderer for animation eval and
video-frame decode) was only synced from the audio playback position inside
TimelinePane::render_content. In the mobile shell, panes render on demand, so with
the timeline off-screen current_time went stale and the Stage froze during
playback. Move the sync into the per-frame block in update() so it runs regardless
of which panes are visible.
2026-07-01 05:42:53 -04:00
Skyler Lehmkuhl 08b6aa0139 Compress mobile layer headers to a swatch; conditional inspector reflow
- Add `is_mobile` to SharedPaneState (set in build_frame). On mobile the timeline
  layer-header column collapses to a minimal type-colored swatch (1:2 w:h, ~30px),
  brighter/outlined when active/selected; tapping it selects the layer (handled by
  the existing header-column input path, which now uses the narrower width).
  Desktop headers unchanged.
- Inspector reflow: the sheet overlaps the stack by default, but when the selected
  pane would be covered by the sheet, the stack reflows (renders above the sheet)
  so it stays visible. Restore on dismiss is automatic since reflow only changes
  the render rect; manual divider moves while the sheet is up persist. Adds
  stack::pane_bottom_in and inspector::target_slot.
2026-07-01 01:14:37 -04:00
Skyler LehmkuhlandClaude Opus 4.8 87263489c0 Add mobile selection inspector sheet (P3); editable layer properties
- New mobile/inspector.rs: when something is selected/focused, a bottom sheet
  overlays the lower stack (no reflow) above the transport, showing the object's
  properties by reusing InfopanelPane full-bleed. Header shows a title + ✕ to
  deselect; jump-to chips (Timeline, Nodes) reframe the stack to that surface
  with the selection kept. Grab handle resizes the sheet.
- Make the Infopanel Layer section editable (benefits desktop too): Name (text,
  commit on Enter/blur), Opacity and Volume sliders (live preview, single-undo
  on release), and Mute/Solo/Lock toggles. Backs the plan to reduce mobile layer
  headers to a minimal swatch.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-30 22:16:14 -04:00
Skyler Lehmkuhl f2cb516e8a Add mobile new-file intent picker (P2)
When LB_MOBILE_UI is set, the desktop start screen is replaced by a phone
intent picker: a 2x3 grid of icon cards (Draw / Animate / Compose / Record /
Edit video / Blank) taking the top ~2/3, and a scrollable Recent-projects list
in the bottom ~1/3.

Each intent reuses EditorApp::create_new_project_with_focus and then sets the
initial stack window (e.g. Draw -> fullscreen Stage, Compose -> Timeline +
Piano Roll + Keys). Recent rows load the project and enter the editor. Cards are
icon-only (Lucide glyph + label) for legibility on a phone. Adds the intent
icons to the Lucide set.
2026-06-30 22:16:09 -04:00
Skyler Lehmkuhl b25e639a1c Linked-divider preset snapping + animated transitions for the stack
Rework 3-pane divider behavior and animate every layout change:

- All transitions now ease over ~100ms via a LayoutAnim between two full stack
  configs (resize, slide, collapse, fullscreen) instead of jumping; edge
  transitions continue from the drag's progress.
- 3-pane dividers are linked along a single path parameter through the three
  presets ([.5,.25,.25] / even / [.25,.25,.5]) so both dividers move together
  and reach their snaps simultaneously. Over-grow past the extreme preset is
  anchored to the path endpoint so the non-dragged divider stays continuous.
- Growing a pane past ~66% collapses the window to 2 panes (dropping the
  opposite-end pane); the surviving divider snaps to the nearest 2-pane preset
  (1/4, 1/2, 3/4) based on the drop position. Dragging to the slide extreme
  still slides the window.
- 2-pane snaps to 1/4, 1/2, 3/4.
2026-06-30 02:07:31 -04:00
Skyler Lehmkuhl 01fe14f197 Ease divider snap into place over ~100ms
After releasing a divider, the boundary now eases (cubic ease-out, ~100ms) from
where the finger lifted to the snapped fraction instead of jumping. Starting a
new drag cancels an in-flight ease; membership changes still apply instantly.
2026-06-30 01:39:53 -04:00
Skyler LehmkuhlandClaude Opus 4.8 3b39e80e40 Add intermediate divider snapping (uneven pane sizes)
Dragging a divider now resizes its two adjacent panes live and, on release,
snaps the boundary to the nearest of 1/4, 1/3, 1/2, 2/3, 3/4 — so one pane can
be made dominant within a 2- or 3-pane window. Dragging far enough to squeeze a
pane past the collapse threshold still triggers the membership transition
(slide/shrink per R1-R6), after which sizing resets to even.

MobileState gains a `weights: [f32;3]` (normalized on use); config_rects is
weight-aware; edge drags keep animating toward the even-split target.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-30 01:18:13 -04:00
Skyler Lehmkuhl 0e3c437d50 Round the top corners of stack pane headers
Each header now has rounded top corners (square at the bottom where it meets
the pane content) so it reads as a tab atop the pane.
2026-06-30 01:02:36 -04:00
Skyler Lehmkuhl 76e7963f03 Add Lucide icon font for the mobile UI
Bundle Lucide (ISC license) at assets/fonts/lucide.ttf and register it as the
egui font family "lucide" via mobile/icons.rs::install (called in EditorApp::new).
Icons are drawn as text with icons::font(size) + PUA codepoint constants.

Switch the stack headers (grip, maximize/minimize, node⇄instrument), the footer
chevron, and the transport play/pause to Lucide glyphs instead of relying on
egui's limited built-in emoji-icon-font.
2026-06-30 01:02:03 -04:00
Skyler Lehmkuhl 597697d0a6 Taller stack headers, fullscreen toggle, icon-font glyphs
- Double header height (52px) so the drag targets are easy to grab; footer
  stays compact (28px).
- Add a fullscreen button on the right of each header that collapses the
  window to that single pane; dragging the sole pane's header down or the
  footer up splits it with the adjacent pane (count can now be 1). The button
  toggles back to a 2-pane split.
- Use egui's bundled emoji-icon-font glyphs (⛶ fullscreen / ▣ restore) instead
  of hand-drawn primitives.
- Cap the drag-to-commit distance (TRIGGER_MAX) so transitions don't require
  dragging half the screen.
2026-06-30 00:33:47 -04:00
Skyler LehmkuhlandClaude Opus 4.8 0c59ed8b4b Fix stack overflow at list ends; full-height drag headers
- Fix panic "attempt to subtract with overflow" when sliding to the end:
  the R-ops used then_some(), which eagerly evaluates top-1 even when the
  guard is false. Switch to lazy .then(|| ...).
- Replace the thin divider/edge grab bars with full-width header bars: each
  band has a labeled header (top of band) that is its drag handle, plus a
  reserved bottom footer for the BottomEdge "pull up for more" handle. Band 0's
  header = TopEdge, band i's header = the divider above it, footer = BottomEdge.
  The Node/Instrument ⇄ toggle lives in that band's header.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-30 00:13:08 -04:00
Skyler Lehmkuhl 79f063d00c Replace mobile tabbed shell with vertical sliding-window stack
Per design feedback, drop the top-tabs + single-ribbon model. The mobile UI
is now one vertical stack of all panes in a fixed order (Outliner, Asset
Library, Stage, Timeline, Piano Roll, Virtual Piano, Node/Instrument, Script
editor) with a window of 2-3 consecutive panes visible at a time.

Dragging the dividers between panes and the top/bottom screen edges grows,
shrinks, or slides the window via a small state machine (R1-R6 in stack.rs),
with continuous interpolation during the drag and snap-on-release. The
Node/Instrument band toggles between the node editor and the preset browser.
The transport stays pinned as the bottom floor.

Each visible band reuses PaneInstance::render_content full-bleed (surface.rs).
Removes topbar.rs and ribbon.rs; rewrites mod.rs state (window_top,
window_count, show_instruments, drag); adds stack.rs.
2026-06-30 00:12:57 -04:00
Skyler LehmkuhlandClaude Opus 4.8 5ee2df5db7 Add mobile UI shell scaffold behind LB_MOBILE_UI
New src/mobile/ module renders a phone-style shell: top surface tabs
(Stage/Time/Nodes/Mixer/Tree), a single full-bleed hero pane reusing the
existing PaneInstance renderers, a resizable timeline ribbon (peek/half/full
snap tiers riding above the floor), and a fixed transport bar wired to the
audio controller (play/pause, timecode, project scrub).

Gated entirely on the LB_MOBILE_UI env var: when set, main() opens a
phone-aspect window and update() routes the central panel through
render_mobile_shell instead of render_layout_node, sharing the same
build_frame context and post-render drain. Desktop is unchanged when unset.

Tabs mirror the pane list; per the wireframe the Toolbar and Infopanel do
not become tabs (they become the omnibutton and inspector in later phases),
and the Nodes surface is a placeholder pending the focus/patch rework.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-29 22:40:54 -04:00
Skyler Lehmkuhl da0b39fef0 Refactor RenderContext construction into EditorApp::build_frame
Extract the ~80-field SharedPaneState/RenderContext literal from update()
into EditorApp::build_frame, returning a FrameBundle that also carries the
layout-editing borrows (current_layout, drag_state, etc.). Per-frame locals
move into a FrameScratch struct so the bundle can borrow both self and the
scratch under one lifetime.

This is a behavior-preserving refactor that gives the upcoming mobile UI
path a single shared construction site for SharedPaneState instead of
duplicating the literal.
2026-06-29 21:42:40 -04:00
Skyler Lehmkuhl fd582828c2 Add text layers
Introduce editable text layers: a resizable text box with editable text,
font size, color, font family, and alignment.

Core:
- New TextLayer/TextContent (text_layer.rs), wired into AnyLayer/LayerType
  and all the exhaustive match sites; structured so content can be keyframed
  later via content_at().
- fonts.rs: thread-local parley FontContext with three bundled fonts
  (Liberation Sans/Serif/Mono, SIL OFL), system-font enumeration consolidated
  to base families, document-embedded fonts, glyph/caret/selection geometry,
  and a background preloader for the picker fonts.
- Rendering via parley layout + Scene::draw_glyphs (renderer.rs); text
  composites through the vector path.
- Actions: CreateTextClipAction (vector-layer branch, undoable),
  SetTextContentAction, ResizeTextBoxAction.
- .beam font embedding: MediaKind::Font rows (content-hash dedupe) written on
  save and registered on load, with bundled-default fallback.
- VectorClip content bounds include text boxes so text-only clips are
  selectable/draggable.

Editor:
- Text tool: click empty/raster/video to create a top-level text layer, or a
  vector layer to create+enter a clip containing the text; click an existing
  box to edit it.
- Hybrid in-place editing: a hidden egui TextEdit drives input/IME/caret while
  the text and caret/selection render in Vello; empty just-created layers are
  removed on commit.
- Selection outline + 8 resize handles (re-wrap text) with hover cursors;
  factored the corner/edge resize-cursor mapping shared with the Transform tool.
- Info panel: edit text, size, color, alignment, box size, and a font-family
  picker that previews each entry in its own font (fonts preloaded in the
  background to avoid hitches).

Deps: add parley (git, pinned to match vello's peniko); bundle Liberation
fonts under lightningbeam-core/assets/fonts. Gitignore the local
.cargo/config.toml used to select a machine's ffmpeg.
2026-06-27 18:14:47 -04:00
Skyler Lehmkuhl 609b80336b Release 1.0.7-alpha 2026-06-26 21:55:08 -04:00
Skyler Lehmkuhl 58a3c829d7 Bump version to 1.0.7-alpha 2026-06-26 21:54:50 -04:00
Skyler LehmkuhlandClaude Opus 4.8 9717289271 Implement layer visibility toggle; log export color range
- Wire MenuAction::ToggleLayerVisibility (was a stub) to flip the active
  layer's `visible` flag via SetLayerPropertiesAction (undoable). This is
  what the SVG-export visibility fix depends on, and the "Hide/Show Layer"
  menu item now works.
- Log the resolved color range in the zero-copy H.264 path to diagnose
  whether `full_range` reaches the encoder (the VAAPI driver may still omit
  the SPS VUI full_range flag).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 21:38:07 -04:00
Skyler LehmkuhlandClaude Opus 4.8 b301c63387 Address code-review findings across export, decode, and data model
Export correctness:
- Honor the user's color-range (Limited/Full) on the software encode path:
  thread full_range through gpu_yuv (new shader range uniform), the CPU
  swscale fallback (sws_setColorspaceDetails → BT.709 + range, fixing the
  BT.601 hue/level shift on odd-width exports), and the encoder color tags.
- Reject HDR + WebM up front with a clear message and log the forced HEVC
  override instead of producing an unplayable file.
- Delete dead render_frame_to_rgba_hdr (hardcoded Stretch; live HDR path
  already honors the fit mode).

Decode/playback (video.rs):
- Drain the decoder at EOF (send_eof + flush) so the final B-frame-delayed
  frames render instead of erroring; per-frame logic extracted to a helper.
- Missing-PTS frames continue monotonically rather than snapping to ts=0.
- Force exact thumbnail width so sub-128px sources aren't shown stretched.

Resource leaks (gpu-video-encoder):
- dmabuf import_raw: RAII guard frees the duped fd + partial VkImages/memory
  on every error path.
- vaapi alloc: free device/frames-ctx/AVFrames on the unexpected-DRM path.

Data model / robustness:
- collapse_boundary_spikes requires a full curve reversal (all control
  points) so it no longer deletes a real lens/sliver and drops the fill.
- Export audio spin-wait ignores a stale `finished` flag when a forward
  seek is pending (was rendering silence over real audio).
- RasterDiff apply_before/after take current dims and skip on a post-resize
  mismatch.
- beam_archive read_media_full caps the preallocation from untrusted total_len.

UI/visual:
- SVG export skips hidden layers/empty groups; import folds fill-opacity into
  gradients and surfaces failures as a notification.
- Active raster-layer border uses playback_time + overlay_transform.
- gpu_brush remove_layer_texture also evicts the stale low-res proxy.
- ensure_raster_resident_for_undo registers faulted frames in the LRU so
  resident RAM stays bounded.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 17:47:32 -04:00
Skyler Lehmkuhl 1fa4d744be Add SVG vector import and export
Export (lightningbeam-core/svg_export.rs): document_to_svg walks vector
layers/groups at a given frame and emits <path> per fill (solid or
gradient via <defs>) and per stroked edge. Wired into the export dialog
as an "SVG" tab; written synchronously. Raster/video/effect layers are
skipped (vector-only, lossless), structured for a later rasterize pass.

Import (lightningbeam-editor/svg_import.rs): import_svg parses via usvg,
bakes each path's absolute transform into geometry, converts segments to
cubic edges, and maps solid/linear/radial paint to ShapeColor/
ShapeGradient. .svg is detected in the Ctrl+I Import handler and added as
a new vector layer (keyframe at the playhead). file_types gains
FileType::Vector + VECTOR_EXTENSIONS.

Tests: svg_export::export_tests (core) and svg_import::tests (editor).
2026-06-26 16:40:39 -04:00
Skyler Lehmkuhl 5869e3ced1 raster: info-panel size + "Layer to document size" (scale/expand-crop)
Resizing the document leaves raster layers as-is (canvas keeps its old pixel size,
anchored top-left). To reconcile, the info panel now shows the active raster
layer's canvas size — driven by the *active* layer, not selection focus, since
painting doesn't focus the layer — and, when it differs from the document, a
Scale / Expand-Crop toggle + a "Layer to document size" button.

- RasterKeyframe::resize_to(w, h, mode): always applies the new declared size;
  resamples (Lanczos3) when Scale, top-left pad/trim when Canvas, and only touches
  the buffer when pixels are resident (a blank canvas just takes the new size).
  Sets texture_dirty so the stage's dirty-scan refreshes the GPU texture.
- ResizeRasterLayerAction resizes every keyframe with undo, holding a (read-only)
  RasterStore so paged-out keyframes are loaded one at a time rather than bulk.

Resized keyframes stay resident + dirty and persist on the next full save (no
incremental store write to page them back out). Scale is lossy/compounds;
Expand-Crop is lossless.
2026-06-26 15:40:23 -04:00
Skyler Lehmkuhl 69939c066d stage: dashed black/yellow border around the active raster layer
Outline the active raster layer's canvas bounds (document space) so its size is
visible, especially when it differs from the document after a resize. Two strokes
sharing one dash pattern, the yellow offset by a dash to fill the black's gaps -
interlocking marching-ants. Sizes divided by zoom so the dashes stay ~constant on
screen.
2026-06-26 15:00:31 -04:00
Skyler Lehmkuhl 5bc117c518 export: add Fit mode to image export too
ImageExportSettings gains `fit: ExportFitMode` (default Letterbox) + a "Fit"
dropdown in advanced image settings; the image render path uses it instead of the
hardcoded Letterbox. Image export supports a resolution override, so the mode
matters when the override aspect differs from the document.
2026-06-26 14:42:05 -04:00
Skyler LehmkuhlandClaude Opus 4.8 fffcf0679c aspect ratio: unify video placement + add export fit modes
A) Imported video had a different aspect ratio depending on how it was placed:
direct import used a uniform scale + center (preserve aspect), while the
asset-library timeline drag used an independent scale_x/scale_y (stretch to fill).
Add Transform::fit_centered (uniform scale, centered, aspect-preserving) and route
both paths through it, so a clip looks identical however it's added.

B) Exported video was stretched when the export resolution's aspect differed from
the document's (base_transform was always scale_non_uniform). Add
ExportFitMode {Stretch, Letterbox (default), Crop} on VideoExportSettings + a "Fit"
dropdown in advanced export settings, and a shared export_base_transform() helper:
Letterbox = uniform fit centered (black bars), Crop = uniform fill centered (trim),
Stretch = the old distort-to-fill. Threaded through the software, HDR, and
zero-copy export render paths (image export is doc-sized → identity).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 06:54:49 -04:00
Skyler LehmkuhlandClaude Opus 4.8 02566d571b video: fix sped-up + jerky 4K playback (frame-index cache + request-based seek)
Two bugs made 4K (and any) video playback wrong:

1. Sped-up playback. The VideoManager frame cache was keyed by milliseconds, but
   GPU (hardware-decoded) frames bypass the decoder's internal cache. A UI that
   refreshes finer than the video frame rate (a 60Hz canvas on a 30fps clip)
   therefore missed the cache on every sub-frame request and decoded the NEXT
   frame each time — advancing the video ~2x faster than the clock, and racing the
   decoder toward EOF. Key the cache on the video frame index (round(ts·fps))
   instead, so all requests within one frame share an entry and each frame decodes
   exactly once → correct speed.

2. Periodic seek/jerk. The seek decision compared the rounded request frame_ts to
   the decoded frame's exact PTS, which sit on slightly different grids — so
   frame_ts landed ~1 frame "behind" the just-decoded PTS every ~10 frames and
   falsely read as a backward seek (40ms seek + GOP re-decode). Track the previous
   request (last_requested_ts), which is strictly monotonic during forward
   playback, and detect backward from that instead. Real scrubs still seek.

Per-frame HW decode is ~3-5ms; both bugs were spurious decode/seek work on top.
Keeps a gated LB_VIDEO_DEBUG [Video Seek?] diagnostic.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 06:27:01 -04:00
Skyler LehmkuhlandClaude Opus 4.8 701b57bfe8 video: thumbnails force CPU frames (fix black thumbs + decoder thrash)
The asset-library thumbnail called VideoManager::get_frame, which honors the
render-pass hardware flag — left ON by the preview, so the thumbnail got a GPU
frame with empty rgba_data → an all-black thumbnail. The thumbnail is also the
only consumer that requests a fixed low timestamp (1.0s) on the shared per-clip
decoder, so when it re-decodes during playback it yanks the decoder back to ~1s;
the next playback frame (6.x) is then ">2s forward" and re-seeks to the keyframe
+ re-decodes the whole GOP (the jerk: per-frame decode is ~5ms, but these seeks
cost 40ms + N-frame catch-up).

Add VideoManager::get_frame_cpu (forces want_gpu=false regardless of the render
flag); the thumbnail uses it. Now it produces a real RGBA thumbnail that the
editor texture-caches once, instead of re-decoding black frames.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 05:39:35 -04:00
Skyler LehmkuhlandClaude Opus 4.8 ca9a70e10a export: run the zero-copy H.264 encoder on the shared device (Stage 3c-export pt 2)
Makes the common Linux H.264 export fully GPU-resident: decode (HW NV12) →
composite → VAAPI encode all on one device, no CPU round-trips.

- gpu-video-encoder: ZeroCopyEncoder now holds wgpu (device,queue,adapter) handles
  instead of owning a DrmDevice. New `new_on_device(device,queue,adapter,...)` runs
  the RGBA→NV12 render + DMA-BUF import on a passed device; `new` keeps building its
  own. The encoder only *imports* VAAPI surfaces (not export), so the shared
  import-capable device works directly.
- editor: stash the shared device handles on EditorApp (set in the creation closure
  from the eframe render_state when the shared device is active) and thread them
  through start_video_export / start_video_with_audio_export → try_build_zero_copy,
  which uses new_on_device when available. ZeroCopyVideo carries on_shared_device →
  the export composite uses hardware_ok=true (consuming HW-decoded GPU frames from
  pt 1) only then.

Falls back to the own-device encoder (decode downloads to CPU) when no shared
device. Tradeoff: the export now shares the GPU with the UI thread (was a separate
device); acceptable for the GPU-resident-decode win. Compiles; crate tests build.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 05:18:23 -04:00
Skyler LehmkuhlandClaude Opus 4.8 bb3369b709 export: GPU-resident decode for software + HDR export (Stage 3c-export pt 1)
The software and HDR export paths already composite on the shared device (the
eframe device, via render_next_video_frame), so they can consume the same
hardware-decoded NV12 GPU frames the preview uses — no CPU download/upload:

- ExportGpuResources gains the Nv12BlitPipeline; the export compositor's Video arm
  branches on inst.gpu (NV12 blit, mirroring stage.rs) vs the RGBA upload path.
- render_frame_to_gpu_rgba takes a hardware_ok flag: true for the software video +
  image export (shared device), false for the zero-copy path (own device, must
  download). render_frame_to_yuv10_hdr sets it true.

Drops the 4K software/HDR-export decode wall (HW decode + GPU composite, no
per-frame RGBA upload). The common Linux H.264 zero-copy path is unchanged
(separate device) — that's pt 2. Falls back to software when no shared device /
importer (flag is harmless then: get_frame returns CPU anyway). Compiles.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 05:07:02 -04:00
Skyler LehmkuhlandClaude Opus 4.8 33dec6f327 export: 10-bit HDR video frame path + UI (Stage B pt 2)
Wire HDR frame production end-to-end (encoder side was pt 1):
- linear_to_pq.wgsl: linear scene HDR (BT.709, white=1.0) → BT.2020 primaries →
  PQ (203-nit) or HLG OETF → gamma-encoded R'G'B'. Inverse of the nv12 decode, so
  a decode→encode round-trip is the identity.
- hdr_frame.rs (isolated module): runs that pass into an Rgba16Float target, does a
  synchronous readback (f16-decoded on CPU), then BT.2020 R'G'B'→Y'CbCr limited
  4:2:0 10-bit pack → YUV420P10LE planes. Rgba16Float avoids the 16BIT_NORM device
  feature dependency.
- video_exporter::render_frame_to_yuv10_hdr: composite + HDR encode, returning
  10-bit planes; lazily builds the pipeline.
- orchestrator: HDR uses a synchronous 1-frame-per-call path (the async RGBA
  pipeline is 8-bit only); zero-copy is skipped for HDR.
- dialog: "Dynamic range" dropdown (SDR / HDR10 PQ / HLG).

Software HEVC Main10 path; favors correctness over throughput. Compiles; runtime
verification needs a GPU + HDR-capable player.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 04:47:35 -04:00
Skyler LehmkuhlandClaude Opus 4.8 41e4f3b12b export: HDR encoder scaffolding — 10-bit HEVC + BT.2020/PQ/HLG tags (Stage B pt 1)
Settings + encoder side of HDR video export (frame data still SDR until pt 2):
- core: HdrExportMode {Sdr (default), Pq, Hlg} on VideoExportSettings (serde
  default), with transfer-name helpers.
- setup_video_encoder takes the mode: HDR → YUV420P10LE, BT.2020 NCL matrix,
  limited range, color_primaries=bt2020, color_trc=smpte2084/arib-std-b67,
  profile=main10. SDR path unchanged (8-bit full-range BT.709).
- run_video_encoder forces HEVC when HDR is selected (the only 10-bit codec wired
  up). encode_frame is parameterized by pixel format and now copies planes
  row-by-row honoring stride (10-bit / non-aligned widths can have row padding).

Dormant: no UI exposes the mode yet and the frame data is still 8-bit SDR, so
selecting HDR is not yet wired. The render→PQ/HLG 10-bit frame path is pt 2.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 04:32:32 -04:00
Skyler LehmkuhlandClaude Opus 4.8 28b14b2ad0 hw: surface import_raw failures (diagnose washed-out 10-bit HDR)
A failed DMA-BUF import returned None silently → core falls back to software,
whose RGBA path does no BT.2020→709 gamut conversion, so HDR clips render washed
out. The detection log fires before import_raw, so it didn't reveal this. Log the
actual import error (with ten_bit) instead of swallowing it, to confirm whether
10-bit P010 import is failing.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 03:59:39 -04:00
Skyler LehmkuhlandClaude Opus 4.8 7c2ac0e4d8 hw: propagate stream colour tags to VAAPI frames (fixes washed-out HDR)
Symptom: properly-converted BT.2020 PQ/HLG clips rendered progressively
desaturated vs the SDR reference — the signature of the transfer/primaries tags
not reaching the NV12→RGB shader, so HDR code values were decoded as plain
sRGB/BT.709 (no gamut expansion, wrong EOTF).

VAAPI hardware-decoded frames frequently leave color_trc/color_primaries/
colorspace/color_range unspecified — the authoritative values live on the codec
context (parsed from the bitstream), which the importer never sees. Before
importing, copy any unspecified colour field from the codec context onto the
frame, so the importer detects PQ/HLG + BT.2020 correctly.

Also add a one-time importer log (LB_VIDEO_DEBUG) of the detected
ten_bit/full_range/colorspace/primaries/trc to confirm what's picked up.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 03:35:16 -04:00
Skyler LehmkuhlandClaude Opus 4.8 83410bd4b4 fix: P010 plane textures are sample-only (R16 isn't renderable)
R16Unorm/Rg16Unorm aren't renderable, but the import gave every plane texture
RENDER_ATTACHMENT/COLOR_ATTACHMENT usage (needed only for the encoder's RGBA→NV12
write path) — so create_view panicked on 10-bit decode ("R16Unorm is not
renderable"). Gate the render-target usage (vk COLOR_ATTACHMENT, hal COLOR_TARGET,
wgpu RENDER_ATTACHMENT) on 8-bit; 16-bit P010 planes are sample-only
(TEXTURE_BINDING/RESOURCE + COPY_SRC), which is all the decode path needs.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 03:20:27 -04:00
Skyler LehmkuhlandClaude Opus 4.8 6c8cb5b9e0 hw: P010 (10-bit) DMA-BUF import for real HDR video
10/12-bit HDR decodes to P010-style VAAPI surfaces (16-bit planes), which the
8-bit NV12 import couldn't handle — real HDR clips fell back to software (losing
the HDR). Import them as R16/Rg16 plane textures:

- dmabuf::Nv12DmaBuf gains `ten_bit`; import_raw picks R16_UNORM/R16G16_UNORM (vk)
  + R16Unorm/Rg16Unorm (wgpu) when set, else the existing R8/Rg8.
- hw_video.rs detects 10-bit from the hw frames context sw_format (P010/P012/P016)
  and sets it. The NV12→RGB shader is unchanged: it samples normalized floats, and
  the limited/full de-quant lands at the same values regardless of bit depth.
- vk_device requests TEXTURE_FORMAT_16BIT_NORM when the adapter supports it (R16/
  Rg16 need it); absent → 10-bit falls back to software, 8-bit unaffected.

Pairs with the PQ/HLG/BT.2020 colour math so HDR10/HLG clips now reach the GPU
path end-to-end. NV12 callers (encoder, decode primitive) pass ten_bit=false.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 03:16:28 -04:00
Skyler Lehmkuhl b76eefb404 hdr: per-document Clip vs Highlight-rolloff output mode (Stage A pt 2)
Add a per-document HDR→SDR mapping applied at the final linear→sRGB encode, so
super-white (HDR) video highlights can be recovered instead of hard-clipped:

- core: HdrOutputMode {Clip (default), HighlightRolloff} on Document (serde
  default), with a SetDocumentPropertiesAction variant for undoable edits.
- shaders: a fs_main_rolloff entry point (preview linear_to_srgb.wgsl + the export
  inline shader) applying a C1 highlight knee — identity below 0.8, smooth rolloff
  [0.8,∞)→[0.8,1). SDR below the knee is untouched; Clip stays the historical path.
- preview (stage.rs) and both export encodes (video_exporter.rs) pick the pipeline
  variant from document.hdr_output_mode — one value per frame, so no per-pixel
  uniform; mirrors the existing fs_main_straight pattern.
- UI: an "HDR output" dropdown in the Document section of the info panel.

Default (Clip) is bit-identical to previous behaviour. Completes Stage A:
HDR-correct input (pt 1) + SDR-safe output mapping. HDR export (10-bit P010/PQ)
and HDR display remain Stages B/C.
2026-06-26 03:01:15 -04:00
Skyler Lehmkuhl ff490ab9ae nv12: HDR-correct input — PQ/HLG EOTF + BT.2020→709 gamut (Stage A pt 1)
Decode HDR video into the linear compositor correctly instead of approximating
everything as sRGB/BT.709:

- Read the frame's color_trc and color_primaries in the importer → VideoTransfer
  {Gamma,Pq,Hlg} + VideoPrimaries {Bt709,Bt2020} on GpuVideoFrame.
- nv12_blit.wgsl: branch the EOTF — sRGB gamma (SDR), SMPTE2084 PQ (normalized so
  203-nit graphics white = 1.0; highlights exceed 1.0), or HLG inverse-OETF
  (reference white ≈ 1.0). Then BT.2020→BT.709 primaries in linear light when
  wide-gamut, clamping out-of-709 colours.

Establishes the white=1.0 scene-linear convention: SDR content is unchanged
(stays in [0,1]); HDR video carries super-white highlights through compositing.
SDR-output mapping (clip default vs highlight rolloff) is Part 2. HLG's display
OOTF is omitted (scene-referred) — approximate but reasonable for SDR-out.
2026-06-26 02:47:09 -04:00
Skyler LehmkuhlandClaude Opus 4.8 6348e57de0 nv12: convert with the source colorspace matrix (not hardcoded BT.709)
The NV12→RGB pass hardcoded BT.709, so SD (BT.601) clips had slightly wrong hues.
Read each frame's AVColorSpace in the importer and derive the Y'CbCr→R'G'B'
matrix (BT.709/601/240M/2020; Unspecified guessed by height like swscale/players),
carry the four coefficients on GpuVideoFrame, and apply them in the shader.

- core: GpuVideoFrame.coeffs + ycbcr_coeffs(kr, kb) helper.
- hw_video.rs: map AVColorSpace → (kr, kb) → coeffs.
- nv12_blit{.rs,.wgsl}: uniform grows to 80 bytes (adds a coeffs vec4); the matrix
  multiply uses params.coeffs instead of literals.

BT.2020's transfer is still approximated as sRGB. The DRM-modifier-without-SAMPLED case stays a graceful software fallback.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 02:32:57 -04:00
Skyler Lehmkuhl 1c537d99da fix: nv12_blit uniform size mismatch (64 vs 80 bytes)
The WGSL struct trailed `full_range: u32` with `_pad: vec3<u32>`, but vec3 has
16-byte alignment so the struct rounded up to 80 bytes while the Rust-side
Nv12Params (BlitTransform + u32 + [u32;3]) is 64 — wgpu rejected the draw
("Buffer is bound with size 64 where the shader expects 80"). Pack the flag as a
single `flags: vec4<u32>` (.x = full_range) so both sides are 64 bytes.
2026-06-26 02:26:51 -04:00
Skyler Lehmkuhl 1848c920d9 editor: wire hardware video decode + NV12 preview compositing (Stage 3c-preview)
Make the dormant core HW-decode engine live for the preview path:

- hw_video.rs: editor's HwVideoImporter — maps a decoded VAAPI surface to a
  DRM-PRIME DMA-BUF and imports it as wgpu NV12 plane textures on the *shared*
  device (the only one with the import extensions). install() creates the VAAPI
  device and injects it + the importer into the VideoManager.
- main.rs: track whether the shared device is actually in use; only then (Linux,
  not LB_NO_SHARED_DEVICE) install hardware decode, using the CreationContext's
  shared device + adapter.
- nv12_blit.rs + nv12_blit.wgsl: NV12 plane textures → BT.709 → sRGB-encoded →
  linear, written straight into the Rgba16Float HDR layer (no CPU upload). Colour
  math mirrors the software path so HW/SW video match; honours full_range.
- stage.rs: the preview Video arm branches on inst.gpu (NV12 blit) vs rgba_data
  (existing upload+blit_straight); sets render_hardware_ok = !cpu_renderer so the
  CPU fallback still gets software frames.
- video_exporter.rs: sets render_hardware_ok(false) before both compositing
  passes — export composites on the encoder's separate device, so a hardware
  decoder downloads to CPU instead (export stays software, correct).
- dmabuf.rs: imported plane textures now also carry SAMPLED/TEXTURE_BINDING so
  they can be sampled by the NV12 blit (they were render-target-only); into_planes
  hands the textures to the longer-lived GpuVideoFrame.
- video.rs: cache-key the GPU/CPU representation on want_gpu (HW-configured AND
  render_hardware_ok) so software-only decode keeps a single cache entry.

Preview only this pass; export GPU-residency is the 3c-export follow-up. Untested
at runtime here (no GPU/display in container) — both crates compile.
2026-06-26 02:21:22 -04:00
Skyler Lehmkuhl 863edc80fc core: hardware video decode engine in VideoDecoder (Stage 3b)
Extend the existing VideoDecoder with an optional hardware path, reusing its
demux/seek/keyframe/blob engine (no duplication):

- GpuVideoFrame (NV12 plane wgpu textures) + HwVideoImporter trait (editor
  implements the DMA-BUF import; the AVFrame crosses as an opaque pointer so
  core needn't reference the GPU crate) + HwDeviceHandle (opaque AVBufferRef).
- VideoManager::set_hardware_decode injects the VAAPI device + importer; each
  decoder attaches hw_device_ctx + a get_format(VAAPI) callback before opening,
  decodes into VAAPI surfaces, and imports them (no CPU copy).
- get_frame returns DecodedFrame::{Cpu,Gpu}; VideoFrame/VideoRenderInstance gain
  an optional `gpu`. The frame cache budgets GPU frames as ~w*h*3/2 and keys on
  whether the consumer wanted GPU.
- A hardware decoder serving a CPU consumer (export, render_hardware_ok=false)
  downloads the surface via av_hwframe_transfer_data then swscales — so export
  stays software/correct and only the preview goes GPU-resident. HW init or
  import failure falls back to software per clip.

Dormant until the editor injects an importer (next): no importer => software,
unchanged.
2026-06-26 02:06:31 -04:00
Skyler Lehmkuhl 7909b51df1 gpu-video-encoder: decouple dmabuf import from DrmDevice (Stage 3b foundation)
import_raw now takes (&wgpu::Device, &wgpu::Adapter) and extracts the raw Vulkan
handles via as_hal, instead of taking the crate's own DrmDevice. This lets a
VAAPI surface be imported onto ANY DMA-BUF-import-capable wgpu device — the
encoder/decoder's own device today, and the editor's shared device (Stage 3a)
next, so hardware-decoded frames are usable by the preview compositor.

Encoder/decoder pass their DrmDevice's device+adapter; round-trip decode test
still passes.
2026-06-26 01:21:08 -04:00
Skyler Lehmkuhl ca612d7807 editor: run on a shared VAAPI-capable wgpu device (Stage 3a)
Foundation for hardware video decode in BOTH preview and export: wgpu textures
can't cross devices, and a hardware-decoded frame is a DMA-BUF-imported texture
that needs the import extensions (only addable via wgpu-hal device_from_raw). So
eframe + the compositor + decode + encode must share ONE custom device.

- vk_device::create_windowed(): the existing import-capable DrmDevice plus
  VK_KHR_swapchain (the WSI surface instance extensions are already enabled by
  Instance::init), for use as the editor's main device.
- main.rs: on Linux, build the shared device and inject it into eframe via
  WgpuSetup::Existing (the egui fork supports it); fall back to wgpu's normal
  device + software decode on any failure, on other platforms, or via
  LB_NO_SHARED_DEVICE. The DrmDevice's wgpu handles are cloned into eframe
  (Arc-backed), so the VkDevice persists with them.

Runtime-verified: the editor launches and renders identically (canvas/vello,
video, panels) on the shared device, and the env-var fallback works.
2026-06-26 01:11:41 -04:00
Skyler LehmkuhlandClaude Opus 4.8 255e16434e gpu-video-encoder: VAAPI hardware decode → wgpu texture (Stage 2)
Headless decode primitive, the mirror of the encoder: VaapiDecoder opens a file,
hardware-decodes H.264 into VAAPI NV12 surfaces (hw_device_ctx + a get_format
callback selecting AV_PIX_FMT_VAAPI), maps each surface to a DRM-PRIME DMA-BUF,
and imports it as two wgpu plane textures via the existing dmabuf::import_raw —
the same path the encoder uses, in the read direction. Frames stay GPU-resident
(no CPU copy).

Validated by a round-trip test: encode solid gray with ZeroCopyEncoder, decode
it back, read the Y plane (mean ≈ 128). All 9 crate tests pass on the container's
Intel GPU.

Next (Stage 3): wire this into VideoManager/get_frame so the compositor consumes
a GPU texture directly (no write_texture upload), with software decode fallback.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 00:46:53 -04:00
Skyler Lehmkuhl 9411145ce9 export: H.264 color range toggle (fix dark/oversaturated output)
The zero-copy VAAPI encoder emitted full-range BT.709 NV12 but wrote no color
tags, so players assumed limited range and stretched it — the H.264 output
looked dark and oversaturated (preview and VP9/software were fine).

- Rgba2Nv12 takes `full_range` and applies the matching Y/chroma scale+offset
  (limited 16-235 / full 0-255) via a uniform; the encoder sets color_range +
  bt709 colorspace/primaries/transfer tags to match. ffprobe-confirmed.
- New ColorRange { Limited, Full } on VideoExportSettings (default Limited, the
  universally-correct choice; serde(default) so saved settings still load),
  surfaced as a "Color range" dropdown in advanced export settings for H.264.

The swscale software fallback still emits Limited regardless of the toggle
(Full only affects the VAAPI zero-copy path).
2026-06-26 00:38:19 -04:00
Skyler Lehmkuhl f1fba186c1 video: decode at the consumer's target resolution (Stage 1)
The decoder's output size was frozen to the document size at import, and export
reused that decoder — so exporting above document res upscaled the video (real
source detail discarded) and a document resize never re-targeted the decode.

Decode size is now chosen per get_frame call: VideoDecoder::get_frame and
VideoManager::get_frame take a target (w, h), capped to native (never upscale),
with the swscale context and frame caches keyed on the output size so preview
(preview res) and an in-progress export (export res) don't collide. The renderer
derives the target from the document->output base_transform, so export decodes
at export res (full detail) and the canvas at preview res. Thumbnails/asset
library pass small targets.
2026-06-26 00:36:35 -04:00
Skyler Lehmkuhl aa7d3a3bf4 export: cache the static background + bilinear video, add render profiling
The export render bucket was dominated by re-rendering the static document
background through Vello every frame and by nearest-sampling the video on
upscale.

- Background cache: render the (static) background through Vello once, snapshot
  the composited HDR accumulator, and restore it with a single texture copy on
  every later frame instead of a Vello render + sRGB-convert + composite (+2
  submits). Invalidated on resize. background-render 3.6ms -> 0.56ms (1080p),
  7.5ms -> ~0.5ms (4K).
- blit_straight now uses the bilinear sampler — video frames are scaled to the
  output size, and nearest made that blocky. Fixes export and live preview.
- LB_RENDER_PROFILE: gated per-frame timing split (build/decode vs composite/
  upload vs srgb, and background vs layers) used to find all of the above. Kept
  as a debug aid for the remaining decode stages.

Net: export render ~12.8ms -> ~7.4ms/frame on a 1080p video clip.
2026-06-25 23:30:51 -04:00
Skyler Lehmkuhl 7525a604f2 video: reuse the swscale context + gate per-frame decode tracing
get_frame rebuilt the RGBA swscale context on every decoded frame and printed
[Video Timing] lines unconditionally. A stream's frames share one input
format/size, so build the scaler once (keyed on format+dims, rebuilt only if
they change) and reuse it; gate the per-frame traces behind LB_VIDEO_DEBUG.

Cuts export wall time ~10% on a 1080p video clip (the scaler rebuild was the
bulk of the per-frame "scale" cost; it's now ~0ms). SwsContext is !Send, so the
cached scaler is wrapped in a SendScaler — sound because a VideoDecoder is only
ever touched under the VideoManager mutex (same invariant as its decoder/input).
2026-06-25 22:44:25 -04:00
Skyler Lehmkuhl a933fc3ca8 Release 1.0.6-alpha 2026-06-25 21:27:57 -04:00
Skyler LehmkuhlandClaude Opus 4.8 e7c239f203 ci: enable VAAPI in the from-source ffmpeg build
The libva guard fired: the release ffmpeg had no h264_vaapi. ffmpeg-sys-next
configures with --disable-autodetect and only passes --enable-vaapi when its
build-vaapi feature is set; ffmpeg-next 8.0 doesn't forward it, so installing
libva-dev alone did nothing.

Inject a direct ffmpeg-sys-next dependency with the build-vaapi feature
(Linux only) in both the GitHub Actions and container build paths. With it,
FFmpeg gets --enable-vaapi (and fails loudly if libva-dev is missing rather
than silently shipping software-only).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-25 21:27:06 -04:00
Skyler LehmkuhlandClaude Opus 4.8 7ebd64391c editor: gate zero-copy VAAPI export to Linux (fix macOS/Windows build)
gpu_video_encoder's encoder/vaapi/vk_device/dmabuf modules are #[cfg(linux)]
(VAAPI is Linux-only), but the editor referenced them unconditionally, so
macOS/Windows failed to compile (cannot find `encoder` in `gpu_video_encoder`).

Gate the zero-copy path (ZeroCopyVideo, try_build_zero_copy,
run_zerocopy_video_export, and the branches in start_video_export /
start_video_with_audio_export) behind cfg(target_os = "linux"). Factor the
software encoder-thread spawn into spawn_software_video so both the None arm
and the non-Linux path share it without duplication. Non-Linux always uses
the software path.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-25 21:27:06 -04:00
Skyler LehmkuhlandClaude Opus 4.8 05b5bf5f85 editor: zero-copy H.264 for video-only export too
Video-only (no-audio) H.264 export now uses the same background-thread zero-copy
VAAPI path as video+audio, instead of the software encoder. It writes the output
.mp4 directly (no mux step) and reports through the single-export progress
channel; completion clears that channel so the dialog closes cleanly.

Factored the encoder/renderer/resources setup shared by both entry points into
ExportOrchestrator::try_build_zero_copy. start_video_export gains the document/
video_manager/raster_store/container_path inputs to seed the off-thread render
from a Document snapshot. Non-H264 / non-VAAPI still falls back to software.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-25 20:55:43 -04:00
Skyler Lehmkuhl d6506c2f22 Release 1.0.6-alpha 2026-06-25 18:38:13 -04:00
Skyler Lehmkuhl 5bed2e8adb Bump version to 1.0.6-alpha 2026-06-25 18:37:55 -04:00
Skyler Lehmkuhl 911d896610 packaging: build ffmpeg with VAAPI and declare libva runtime deps
The Linux release ffmpeg is built statically from source, and ffmpeg only
autodetects --enable-vaapi when libva headers are present at configure time.
Neither build path installed them, so every release shipped a static ffmpeg
with no h264_vaapi encoder -- the zero-copy export silently fell back to
software 100% of the time.

- Containerfile + build.yml: install libva-dev + libdrm-dev so the from-source
  ffmpeg gets VAAPI.
- build.yml: assert the release binary links libva, so a missing dep can't
  silently regress to a software-only build again.
- deb/rpm: libva (libva2/libva-drm2/libdrm2, libva/libdrm) is a hard runtime
  dep -- the vaapi-enabled ffmpeg DT_NEEDEDs it, so the app won't launch
  without it. The VA driver is a soft recommends (absent it, export falls back
  to software): va-driver-all (deb), intel-media-driver/mesa-va-drivers (rpm).

build.rs needs no change: releases link ffmpeg statically (its bundling path
is skipped) and the AppImage is thin, taking libva from the host like libvulkan.
2026-06-25 18:28:43 -04:00
Skyler Lehmkuhl ecfa192245 editor: run zero-copy H.264 export on a background thread
The zero-copy VAAPI export previously rendered one frame per egui repaint on
the UI thread, which pinned throughput to the 60Hz vsync of the present loop
(measured exactly 16ms/frame) -- so the near-free hardware encode bought
nothing. Because the export runs on its own VAAPI device (independent of
eframe), it can run entirely off the UI thread.

- run_zerocopy_video_export: a background thread owning the encoder + its own
  vello renderer/device, a Document snapshot (Document is Clone+Send; the UI
  keeps the live one), its own ImageCache, and a RasterStore clone. Renders +
  hardware-encodes every frame and reports through the same video_progress
  channel the software encoder thread uses.
- start_video_with_audio_export takes the document/video_manager/raster_store/
  container_path to seed the thread; video_state is None for this path.
- Throttle export-time UI repaints (~6Hz) and the thread's progress sends so
  the render thread keeps the cores; the breakdown print stays.
- cancel() tears down parallel_export (detaches threads, removes temp files)
  so the progress dialog dismisses; the call site closes the dialog.
- Gate the progress poll loop on has_pending_progress() so it stops once the
  export ends instead of polling/logging every repaint forever; the single
  export path clears its channel on the terminal event.

Vsync overhead is gone (0.1ms/frame); export is now render-bound (~11ms/frame
Vello scene-build). ~1:50 -> ~56s (~2x) on the validation clip.
2026-06-25 18:15:39 -04:00
Skyler Lehmkuhl 2bce5e93a6 gpu-video-encoder: VAAPI driver retry, Vello-capable device, Send
Three fixes found while running the zero-copy export on real Intel hardware:

- vaapi::create_device() retries LIBVA_DRIVER_NAME in order iHD -> auto ->
  i965 -> radeonsi. libva was auto-selecting the legacy i965 driver, which
  fails on newer Intel GPUs; the modern iHD (intel-media-driver) is needed.
  encoder.rs now builds its hwdevice through this helper.
- vk_device: request the adapter's full limits instead of downlevel_defaults.
  Vello's compute pipelines need max_storage_buffers_per_shader_stage >= 5
  (downlevel caps at 4), which panicked Vello's shader init on the export
  device. This device only ever runs on a real VAAPI GPU.
- ZeroCopyEncoder: unsafe impl Send. It owns its FFmpeg/Vulkan handles
  exclusively and is only moved (onto the export thread), never shared.
2026-06-25 18:15:05 -04:00
Skyler Lehmkuhl 3e4f29c297 Wire zero-copy VAAPI H.264 into video+audio export
When exporting H.264 with audio, try the gpu-video-encoder ZeroCopyEncoder:
render each frame to RGBA and hardware-encode it into a VAAPI surface
inline, on the encoder's own VAAPI-capable wgpu device — no GPU->CPU
readback, no swscale, no software-encoder thread. Falls back to the
existing software path verbatim when VAAPI/the device is unavailable
(non-Linux, non-H264, or init failure), so it's additive.

- VideoExportState gains zero_copy: Option<ZeroCopyVideo> (encoder + its own
  vello renderer + ExportGpuResources + a reused RGBA target, all on the
  encoder's device).
- start_video_with_audio_export builds it for H.264 and skips spawning the
  software encoder thread when present.
- render_next_video_frame routes to a zero-copy arm that reuses
  render_frame_to_gpu_rgba on the encoder's device, then encode_rgba; on the
  last frame finish() writes the temp .mp4 and sets video_progress=Complete
  so the existing mux runs. video_thread=None makes the mux join a no-op.

Separate export device (vs modifying the eframe device) keeps this contained
to export. Video-only export stays on the software path for now. Runtime
verification (an actual H.264 export) is pending — cannot run the editor in
the dev container.
2026-06-25 15:44:50 -04:00
Skyler Lehmkuhl a00e73c4b3 gpu-video-encoder: mux the zero-copy encode into a container file
ZeroCopyEncoder::new now takes an output path and writes a real container
(format inferred from the extension, e.g. .mp4): create an output format
context, add the h264 stream from the encoder, write header; encode_rgba
rescales each packet's ts and av_interleaved_write_frame's it; finish
flushes + writes the trailer + closes. Sets AV_CODEC_FLAG_GLOBAL_HEADER for
mp4/mov so SPS/PPS land in extradata. This lets the editor's existing
mux_video_and_audio consume the temp video file unchanged.

The zerocopy_encode test now writes a .mp4 and ffprobe-verifies the codec,
dimensions, and frame count. Also let wgpu own the imported plane-image
destruction via texture_from_raw drop callbacks (clears two warnings).
2026-06-25 15:43:39 -04:00
Skyler Lehmkuhl ba897eaea2 gpu-video-encoder: complete zero-copy H.264 encode pipeline
Build the full end-to-end zero-copy encoder, validated on Intel/VAAPI:

- render_nv12: fragment-shader RGBA->NV12 that renders luma/chroma into
  the imported R8/RG8 plane render targets (compute storage can't write
  the DMA-BUF-backed planes; render attachments can).
- dmabuf: import_raw imports an NV12 DMA-BUF by explicit layout; the two
  plane images + shared memory are now destroyed by wgpu via texture_from_raw
  drop callbacks (Arc MemoryGuard frees the memory once both images are
  gone, in wgpu's wait-idle'd deferred pass) -- fixes the teardown segfault.
- encoder::ZeroCopyEncoder: renders an RGBA texture straight into a pooled
  VAAPI surface (imports cached by VASurface id) and encodes with h264_vaapi.
  encode_rgba + finish; the caller renders on device().

Tests: real-frame render into the surface matches the CPU NV12 reference,
and a 30-frame encode produces valid H.264 (ffprobe-verified) with clean
teardown. Not yet wired into the editor.
2026-06-23 19:28:57 -04:00
Skyler Lehmkuhl 5917ce7921 Add gpu-video-encoder crate: zero-copy VAAPI encode (validated)
New workspace crate isolating the unsafe GPU<->encoder interop for
zero-copy hardware video encoding. Every link is validated by a test on
real Intel/Mesa/iHD hardware:

- nv12: GPU RGBA->NV12 compute (BT.709 full-range), byte-exact vs a CPU
  reference.
- vaapi: VAAPI hwcontext + h264_vaapi encode (CPU-fed NV12 -> valid H.264),
  and DRM-PRIME surface layout probing.
- vk_device: a custom wgpu Vulkan device that adds
  VK_EXT_image_drm_format_modifier (+ external-memory fd/dma-buf) via the
  wgpu-hal device-from-raw path, so a tiled VAAPI surface can be imported.
- dmabuf: import a VAAPI NV12 surface's tiled DMA-BUF as two aliasing wgpu
  textures (Y=R8, UV=RG8) at the plane offsets.
- zerocopy test: render values via Vulkan straight into the VAAPI surface
  and read them back 100% correct -- proving the GPU writes into the
  encoder surface with no CPU copy.

Not yet wired into the editor; real-frame render + encode-from-surface +
fallback wiring follow. Linux-only (libva); other platforms fall back.
2026-06-23 19:07:37 -04:00
Skyler Lehmkuhl da65b63bdf Repair test suite + fix sample key-range overlap bug
The suite had accumulated breakage from prior refactors:
- selection unification: rewrite the integration tests for the single
  unified clip_instances collection (shapes+clips are one set now).
- tempo-map: thread a TempoMap (constant 60 BPM = identity) into the
  clip remap_time tests so the second-based expectations hold.
- drop two dead rgba_to_yuv420p tests that asserted tight plane sizes
  incompatible with the function's 16-macroblock alignment.
- ignore the WIP theme var() cascade test (theme system not wired up).

Also a real bug the tests caught: auto_key_ranges produced overlapping
sample key ranges (the midpoint key mapped to both adjacent samples).
Start each range one past the previous midpoint.
2026-06-23 19:07:06 -04:00
Skyler Lehmkuhl 2564d807a0 Convert export frames RGBA->YUV420p on the GPU
The export read back 8MB RGBA per frame and ran swscale RGBA->YUV420p on
the UI thread (~6ms/frame). Add a tight GPU compute converter (gpu_yuv,
BT.709 full-range matching the encoder tags) and wire it into the
triple-buffered ReadbackPipeline: render to RGBA, convert on the GPU, read
back ~3MB of planar YUV, and skip the CPU pass. Gated on a runtime check
that the encoder's YUV420P plane strides are tight (no linesize padding),
with the swscale path as fallback for other dimensions; LB_DISABLE_GPU_YUV
forces the CPU path. Includes a CPU reference + unit tests for the packing.

Also guard render_next_video_frame against re-initializing/re-emitting
"Complete" every frame after the render finishes while the encoder/mux
drains (the completion nulled gpu_resources but left video_state set).
2026-06-23 19:06:47 -04:00
Skyler Lehmkuhl 70ac0cde00 Fix audio export hang when a video's audio is shorter than the video
Offline export blocks each streaming source until decoded frames are
available. For a video whose audio track ends before the video (or a
container like WebM/Opus with no exact stream duration), the tail chunks
wait for frames that never arrive — the 10s safety valve fires per chunk,
so the export appears to hang indefinitely.

Add a `finished` flag to ReadAheadBuffer, set when the disk reader hits
EOF (cleared on seek). The export-mode wait now breaks immediately once
the source is finished and the requested frames aren't present, rendering
silence for the missing tail instead of timing out chunk-by-chunk. Only
the export path reads the flag, so playback is unaffected.
2026-06-23 19:06:21 -04:00
Skyler LehmkuhlandClaude Opus 4.8 5844a0f070 Composite grouped/nested video on the GPU path
Imported video is a Group[Video, Audio] that rendered as a Vello-baked
Vector layer, re-uploading the full frame to Vello's image atlas every
frame (~17ms/frame at 1080p, hitting playback and export alike). Extract
video frames out of the Group/clip scene recursion into
VideoRenderInstances so they composite via the GPU Video path; mixed
video+vector containers fall back to Vello (correct, unaccelerated).

Also route video through hardware sRGB decode: upload raw sRGB bytes to an
Rgba8UnormSrgb texture and blit with a non-unpremultiplying shader variant
(blit_straight), removing the per-frame per-pixel CPU sRGB->linear pass.
Add an F3 GPU-timestamp timer and a per-frame video texture cache.

Drops the live composite of a 1080p video from ~17ms to ~2-3ms.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 17:38:30 -04:00
Skyler Lehmkuhl ce151ffd61 Pack video into .beam and stream frames + audio from the blob
Video was the only media type always kept external (VideoClip.file_path),
so a project with video wasn't self-contained. Now video packs into the
SQLite container under the same large-media policy as audio (pack < 2 GB
unless the user chose Reference), and both the frames and the embedded audio
track decode by streaming directly from the blob — no temp files.

- New crate ffmpeg-blob-io: an AVIOContext-over-Read+Seek shim (BlobInput)
  that lets ffmpeg demux from an arbitrary byte source. Isolates all the
  unsafe FFI + ffmpeg ABI coupling (version-pinned =8.0.0/=8.0.1). Manual
  Drop teardown order; AVSEEK_SIZE restores the read position (FFmpeg assumes
  a size query doesn't move it — required for MP4 moov-at-end).
- Schema/save/load: VideoClip.media_id; save_beam packs/references video as
  MediaKind::Video (keyed by clip id); load resolves packed vs referenced and
  reports missing sources. A packed clip points its linked video-audio pool
  entry's media_id at the video row so the audio streams from the same blob.
- Frames: video.rs VideoSource{Path,Packed} threaded through new/seek/scan/
  probe/thumbnails (a fresh BlobReader per open); editor builds the source
  from current_file_path (now set before register_loaded_videos).
- Audio: VideoAudioReader::open_source via BlobInput; the disk_reader
  StreamSource block on packed video-audio is removed; the engine's existing
  factory activation routes it unchanged.

Tests: ffmpeg-blob-io AVIO unit tests (WAV via Cursor, seek, open/drop loop);
core packed_video_stream (blob->AVIO->Input) and beam_archive video round-trip;
daw-backend open_source test (compiles; links/runs only off-container).
Runtime-verified: a packed video plays frames + audio after the source file
is removed.
2026-06-22 09:17:10 -04:00
Skyler Lehmkuhl 34eee3a620 Fix .beam save quirks: real sample rate, drop dead fields
Address the code smells flagged in the .beam format spec:

- Write the project's actual sample rate on save instead of a hardcoded 48000
  (add AudioProject::sample_rate()).
- Remove the vestigial RasterKeyframe.media_path field (it was only used by the
  legacy ZIP loader, which now derives "media/raster/<id>.png" from the keyframe
  id) and the dead buffer_path_at_time accessor. Backward-compatible: older files
  carrying media_path deserialize fine (the field is ignored).
- Drop the unused SaveSettings fields auto_embed_threshold_bytes / force_embed_all
  / force_link_all; only large_media_mode was ever consulted. Un-prefix the now-used
  `settings` parameter.

Update BEAM_FILE_FORMAT.md to match. The remaining notes (reserved MediaKind::Video,
exact-match version check) are design choices, left as-is.
2026-06-21 23:21:48 -04:00
Skyler Lehmkuhl 5f0d5354ed Document the .beam SQLite format and port the inspector
The .beam container moved from ZIP to SQLite, but the docs/tooling still
described the old ZIP format.

- Rewrite BEAM_FILE_FORMAT.md as a normative spec of the current SQLite
  container: file-magic identification, the four-table schema, the two version
  numbers, the media model (kinds, packed/referenced storage, 4 MiB chunking),
  derived media-id formulas, project.json top-level + key entities, save/load
  semantics, the legacy-ZIP format + migration, large-media policy, conformance
  and security sections, and known quirks.
- Port beam_inspector.py to read SQLite (auto-detecting container by magic,
  with the legacy ZIP path preserved): a --media store view, packed/referenced
  storage detection, and chunk-reassembling media extraction.
- Update beam_inspector_README.md to match.
2026-06-21 23:08:15 -04:00
Skyler LehmkuhlandClaude Opus 4.8 bf4331eed4 docs: correct branch references to main (not master)
The primary branch is main; an earlier commit mistakenly wrote master.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-21 21:19:53 -04:00
Skyler LehmkuhlandClaude Opus 4.8 273862c882 release scripts: push the release branch to both forges
Push to the 'all' remote (GitHub + Gitea pushurls) instead of origin so
releases are mirrored to Gitea too. CI still triggers via the GitHub pushurl.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-21 18:38:33 -04:00
Skyler LehmkuhlandClaude Opus 4.8 a3f18bdab6 Remove the legacy Tauri backend (src-tauri)
The shipping product is the pure-Rust app in lightningbeam-ui/; the old
JavaScript UI in src/ is browser-only (window.__TAURI__ is shimmed by
src/tauri_polyfill.js), so the src-tauri Tauri backend is dead. It also no
longer compiled (mid-refactor: missing video_server module, handler list
referencing deleted commands), and CI only ever built lightningbeam-ui.

- Delete src-tauri/ entirely (commands, native renderer/render-window,
  websocket frame streamers, Tauri config, generated schemas, icons).
- Relocate icon.icns into lightningbeam-ui/lightningbeam-editor/assets/icons/
  (the only src-tauri asset still needed) and repoint the editor's window-icon
  include_bytes! at assets/icons/256x256.png (was src-tauri/icons/icon.png).
- CI/packaging: drop the redundant icon-copy steps (PNGs are committed in the
  editor assets) and point macOS bundling at the relocated icns.
- package.json: drop @tauri-apps/* deps and the tauri script.
- Docs/.gitignore: drop src-tauri references.

daw-backend/ (shared audio engine) and the top-level WASM lightningbeam-core/
are untouched. Editor builds clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-21 18:25:39 -04:00
Skyler LehmkuhlandClaude Opus 4.8 2c40858663 docs: point branch references at master
rust-ui is being merged into master and retired as the primary branch.
Update README, ARCHITECTURE, and CONTRIBUTING to reference master.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-21 18:13:02 -04:00
Skyler LehmkuhlandClaude Opus 4.8 149760e9c0 CI: build NeuralAudio with Ninja on Windows
cmake-rs 0.1.54 panics with "unsupported or unknown VisualStudio version: 18.0"
because the windows-latest runner now ships Visual Studio 18 (2026), which the
crate's VS-generator detection doesn't recognize.

Install Ninja and set CMAKE_GENERATOR=Ninja for the Windows build so the cmake
crate skips VS-version detection and drives cl.exe (from the active MSVC env)
directly. build.rs already searches the single-config (non-Release) output dirs,
so no linking changes are needed.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-21 17:18:41 -04:00
Skyler LehmkuhlandClaude Opus 4.8 1cb821f05b CI: build Windows under pwsh so MSVC's linker is used
Git for Windows puts its usr\bin on PATH ahead of the MSVC tools, so under
Git Bash rustc picked up coreutils link.exe instead of MSVC link.exe and
every link (even host build scripts like proc-macro2/serde) failed with
"/usr/bin/link: extra operand".

Split the build step: non-Windows keeps the bash script (needs --target
handling); Windows builds under pwsh, where the MSVC environment from
msvc-dev-cmd stays at the front of PATH.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-21 17:03:43 -04:00
Skyler LehmkuhlandClaude Opus 4.8 8223593649 CI: activate MSVC dev environment for the Windows build
The cmake crate building nam-ffi/NeuralAudio panicked with "couldn't determine
visual studio generator" because the Windows job never ran vcvars, so
cmake-rs had no VisualStudioVersion to detect the VS generator from.

Add an ilammy/msvc-dev-cmd step (x64) after the Windows dependency install; it
runs vcvars and exports the env to later steps so the C++ build can configure.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-21 16:49:08 -04:00
Skyler Lehmkuhl 83057b754a Clean up build warnings
Resolve all compiler warnings across daw-backend, lightningbeam-core, and
lightningbeam-editor:

- Delete dead code: the superseded CPU raster tools in raster_tool.rs
  (EffectBrush/Smudge/Gradient/Transform/Warp/Liquify/Selection — replaced by
  the GPU path), plus orphaned helpers and never-read struct fields.
- Mechanical fixes: drop unused imports/variables/mut, underscore unused params,
  `drop(&x)` -> `let _ = x`, deprecated egui::Rounding -> CornerRadius, snake_case
  rename, elided-lifetime Cow<'_, [u8]>.
- Keep the WIP CSS theming system (theme.rs/theme_render.rs) under
  #[allow(dead_code)] rather than deleting it.

Editor checks warning-free; 293 core tests pass.
2026-06-21 16:48:59 -04:00
Skyler Lehmkuhl f0929e2b6d Release 1.0.5-alpha 2026-06-21 16:14:44 -04:00
Skyler Lehmkuhl 3c3a482e2e Bump version to 1.0.5-alpha 2026-06-21 16:14:44 -04:00
Skyler Lehmkuhl 5fd04b5dd5 Lock editing on tween in-between frames
Block geometry/clip edits on frames that fall strictly inside a tween span,
where an edit would silently mutate the bracketing keyframe instead:

- Shape tweens: gate vector editing (vertices, curves, DCEL hits) and all
  geometry tools in stage.rs behind VectorLayer::is_tween_inbetween.
- Motion tweens: block selecting/dragging/transforming clip instances whose
  transform is mid-tween, via AnimationData::is_object_tweened_at.

Also: inserting a keyframe mid-tween now captures the interpolated geometry
shown at that frame (not the left keyframe's) and inherits the shape tween,
so the new keyframe continues morphing toward the right keyframe.
2026-06-21 16:01:47 -04:00
Skyler Lehmkuhl a1acecf396 Implement shape tweens (same-topology lerp)
`tween_after == Shape` was stored on keyframes but never read. Now the
render path morphs geometry across a shape-tween span:

- VectorGraph::interpolated(other, t): same-topology lerp of vertex
  positions, edge curves, stroke widths and stroke/fill colours. Returns
  None when topology differs (counts, deleted flags, edge endpoints, fill
  boundaries), so the caller holds the source keyframe.
- VectorLayer::tweened_graph_at(time): returns an owned morphed graph for
  a shape-tween span whose two keyframes share topology, else borrows the
  held keyframe. Editing still uses graph_at_time (the held keyframe).
- Renderer (Vello + CPU paths) renders via tweened_graph_at.
- SetTweenAction + wired the previously-stubbed "Add Shape Tween" menu.

The typical workflow — keyframe, duplicate it (same topology), move
vertices, Add Shape Tween — now morphs between the two. Non-matching
topology falls back to a hold.
2026-06-21 15:46:53 -04:00
Skyler Lehmkuhl 1dd5de4617 Render clip instances on top of a layer's loose shapes
Within a vector layer, groups and movie clips (clip instances) were drawn
before the layer's own VectorGraph, so they appeared underneath the loose
shapes. Draw the loose shapes first and the clip instances on top, in both
the Vello and CPU render paths.
2026-06-21 15:23:54 -04:00
Skyler Lehmkuhl 0d1f62ccce Fix motion-tween first-keyframe: anchor the clip's start
Creating the first transform keyframe for a clip instance at frame N left
the curve with a single keyframe, which Hold-extrapolates backward — so
moving it at frame N also moved it on every earlier frame (frame 1).

When SetKeyframeAction creates a brand-new curve for a clip instance and
the clip already existed before `time`, also anchor a keyframe at the
clip's start (its group visibility start, or timeline_start for movie
clips) with the original value. Earlier frames now hold the original
position and the move produces a proper tween from start to N.

Also capture the clip instance's actual on-stage value when keying (its
base transform), instead of a generic 0/identity default, so a new
keyframe doesn't snap the clip to the origin.

Adds VectorLayer::group_visibility_start and tests covering the anchor and
the no-double-anchor case (keying at the clip's own start).
2026-06-21 15:18:15 -04:00
Skyler Lehmkuhl 87bcffd427 Collapse boundary spikes in region cut; embed dump regression fixtures
A dense self-intersecting freehand lasso leaves clusters of near-coincident
duplicate sub-pixel edges (split products the coincident-edge dedupe can't
reach). The planar face trace bounces back and forth across them, producing
a degenerate "spike" boundary (an edge used twice). Add
`collapse_boundary_spikes`, run on each traced face before it becomes a
fill: it removes consecutive out-and-back entries (where the boundary
returns to where it started) until the loop is simple.

Embed the captured region-select dumps as committed fixtures under
tests/region_dumps/ (replayed by `dumped_region_selects_are_valid`) so the
regression survives /tmp being cleared. dump3 is the boundary-spike repro;
it fails this test without the collapse and passes with it. Loosen the
boundary-connectivity test tolerance to 1e-2 (above sub-micropixel float
drift, far below any real gap).
2026-06-21 15:02:30 -04:00
Skyler Lehmkuhl 39978e59b3 Unify selection systems and make region/lasso cut robust
Collapse the two parallel selection systems into one. The RegionSelect
tool (rect + lasso) now cuts the geometry along the region outline and
selects the resulting sub-pieces into the standard `Selection` ID-sets,
exactly like every other tool. The vestigial floating `RegionSelection`
(drag never wired; commit/delete/copy were stubbed) and all its plumbing
are removed, so Group, Convert-to-Movie-Clip, Delete, and Properties all
operate uniformly from lasso, rect, marquee, and click selections.

Region cutting is reworked onto a robust planar arrangement:

- Replace fragile incremental "split a fill by one cut edge" logic with
  planar face re-tracing (`retrace_fills_after_cut` + `trace_faces`),
  which correctly handles arbitrary holed/concave fills.
- `extract_subgraph` no longer frees vertices still referenced by kept
  boundary edges (fixed Group leaving freed-but-referenced vertices that
  a later alloc reused and corrupted).
- `split_fill_by_*` direction fix (was producing disconnected boundaries
  rendered as stray diagonals).
- `fill_interior_point` (area-centroid + inward-step fallback) for
  reliable inside/outside classification of non-convex pieces.
- Coincident-edge dedupe + degenerate-fill removal (edge-adjacent shapes
  no longer make zero-area sliver fills).
- Dangling-edge pruning, near-coincident endpoint welding, induced-
  subgraph expansion, and tracking of `split_edge` sub-edges, so
  self-intersecting freehand lassos cut correctly.

Region-select capture is available behind LIGHTNINGBEAM_DUMP_REGION=1 for
turning a misbehaving cut into a deterministic test. Extensive regression
tests added in vector_graph/tests/region_cut_select.rs.
2026-06-21 14:47:11 -04:00
Skyler Lehmkuhl 0d253d9629 Motion tweens: implement Group + Convert to Movie Clip for DCEL geometry
Both actions were DCEL-stubs (no-ops). They now extract the selected geometry from a
vector layer's active keyframe into a new VectorClip (group vs movie clip) and place a
ClipInstance in its place (identity transform → renders where the geometry was), which
the existing transform-animation system can motion-tween.

- Shared `clip_from_geometry::extract_geometry_to_clip` (+ undo) does the work; the
  actions are thin wrappers. Undo snapshots the source graph + removes the clip/instance.
- `extract_subgraph` now DERIVES shared-fill boundary edges internally (an inside edge
  still used by a non-extracted fill must be duplicated, not moved) and unions them with
  the caller's `explicit_boundary` — so a plain geometry selection needs no boundary
  analysis (the selection already includes fill boundary edges via `select_fill`). The
  region-select caller keeps passing its lasso boundary.
- Handlers: Group / Convert to Movie Clip on a geometry selection now build these actions
  from `selected_fills`/`selected_edges`.

Next: shape tweens (same-topology lerp).
2026-06-21 09:12:46 -04:00
Skyler Lehmkuhl 0914818808 docs: export now ~1.74x realtime (4x win); GPU-bound on composite, CPU wins won't help 2026-06-21 09:12:30 -04:00
Skyler Lehmkuhl b292e0e6e6 docs: export-speed audit findings + #1/#2a done, remaining wins noted 2026-06-21 01:35:41 -04:00
Skyler Lehmkuhl 4e9cacb789 Export speed #2: cache the RGBA→YUV swscale context across frames
CpuYuvConverter::convert rebuilt the swscale context + both ffmpeg frames on every
call (per output frame), despite the converter persisting for the whole export. Now
the scaler + reusable source/dest frames are built once in new() and reused each
convert(). (convert is &mut self; the caller already held it mutably.)
2026-06-21 01:34:28 -04:00
Skyler Lehmkuhl 0a0d7cd0a9 Export speed #1: reuse the Vello renderer + ImageCache across frames
The export pump built a fresh `vello::Renderer` (full wgpu pipeline init, ~tens of ms)
AND an empty `ImageCache` on every egui repaint — i.e. per output frame. That was the
dominant per-frame cost (and the code comment already flagged it). Now the renderer +
image cache are built once on the first export pump, reused for every frame, and
dropped when the export finishes.

Also fixes a latent bug: the throwaway export ImageCache had no container path, so with
Phase 4 Tier 1 (lazy image bytes) images stored only in the container wouldn't render
in exports. The persistent cache now gets the container path.

Audit found the original "per-frame seek" theory was wrong — export decodes the source
sequentially; readback is already async/triple-buffered. Remaining wins: cache swscale
contexts (rebuilt per frame), GPU YUV conversion, decouple from the repaint cadence.
2026-06-21 01:29:54 -04:00
Skyler Lehmkuhl 5f3cb41c18 docs: mark Phase 3/3.5/4 done in plan checklist; flag stale JS-era TODO entries 2026-06-21 01:22:17 -04:00
Skyler Lehmkuhl 6a788a432e docs: Phase 4 done (image asset paging: Tier 1/2 + prefetch) 2026-06-21 01:12:57 -04:00
Skyler Lehmkuhl 0883c77e2b Phase 4: prefetch upcoming images during playback
`assets_needed_at(document, time)` (core) enumerates the image asset ids referenced by
the visible vector layers' active keyframes at a time (top-level + group children).
During playback the stage decodes the images needed ~0.5s ahead into the bounded
ImageCache, so a keyframe that swaps image fills doesn't hitch when the playhead
reaches it. Gated on is_playing; nested clip-instance recursion + background decode
are refinements.

Completes Phase 4 (image asset paging: Tier 2 decoded-cache LRU, Tier 1 lazy bytes,
playback prefetch).
2026-06-21 01:12:37 -04:00
Skyler Lehmkuhl 3d0a334014 Phase 4 Tier 1: lazy image-asset bytes paged from the container
Project load no longer eager-reads all image bytes — `ImageAsset.data` stays empty
and the renderer's ImageCache pages compressed bytes from the `.beam` on a decode
miss (read_packed_media_readonly by asset id), decoding into the byte-bounded Tier-2
cache. Result: instant load, and compressed bytes don't accumulate on the heap.

- ImageCache: `container_path` + `resolve_bytes` (asset.data if resident — fresh
  import or old base64 project — else page from the container); decoders take `&[u8]`
  and use the decoded dimensions.
- Container path threaded App.current_file_path → SharedPaneState → VelloRenderContext,
  set on the cache each prepare.
- load_beam_sqlite drops the 3.5b eager read.

(Refinement: a persistent read connection instead of open-per-miss.)
2026-06-21 01:12:05 -04:00
Skyler Lehmkuhl d05cbfcde5 docs: Phase 4 Tier 2 (decoded ImageCache LRU) done; note Tier 1 + prefetch 2026-06-21 00:55:26 -04:00
Skyler Lehmkuhl fcc8102a9d Phase 4a: bound the decoded ImageCache (usage-LRU byte budget)
The decoded-image cache (peniko ImageBrush + tiny-skia Pixmap, ~w·h·4 each) was
unbounded — the main asset-memory cost. Now capped at 256 MB with usage-LRU eviction:
every get_or_decode bumps the asset's recency, and inserts past the budget evict the
least-recently-used (a miss re-decodes from the resident asset.data). Images actually
rendered each frame stay resident; unused ones age out under pressure. invalidate/clear
keep the lru + byte accounting in sync.

Next (4b): lazy-load asset.data from the container instead of eager on project open.
2026-06-21 00:52:56 -04:00
Skyler Lehmkuhl 7a150fb5c5 docs: mark Phase 3.5 (image textures in vector scenes) done 2026-06-21 00:46:22 -04:00
Skyler Lehmkuhl 2f3b0d7790 Phase 3.5b: persist image assets in the .beam container
Image asset bytes are now stored as MediaKind::ImageAsset rows in the SQLite
container (chunked, kept-in-place on re-save) instead of base64-embedded in the
project JSON — the pageable storage Phase 4 needs.

- ImageAsset.data is `#[serde(default, skip_serializing)]`: never written to JSON,
  but still deserialized for old projects (base64) which then migrate to the
  container on the next save.
- save_beam writes each asset's bytes (keyed by asset id; ext from the source path),
  keeping an existing row when bytes aren't resident; live_media covers them so orphan
  cleanup doesn't drop them.
- load_beam_sqlite eager-reads the bytes back into `data` (Phase 4 makes this lazy +
  LRU). Old base64 projects keep their JSON-deserialized data (no container row).
2026-06-21 00:44:18 -04:00
Skyler Lehmkuhl aad2d5c515 Onion/image: make Image a fill-type tab (None | Solid | Gradient | Image)
Image fill is now a tab in the Fill type row rather than a separate dropdown. When
Image is active, an asset-picker combo selects which image; switching to None/Solid/
Gradient clears the image fill (it otherwise overrides them). The Image tab only
appears when there are imported image assets.
2026-06-21 00:37:33 -04:00
Skyler Lehmkuhl 6fc3a131a6 Phase 3.5a: SetImageFillAction + Info-Panel image-fill picker
- SetImageFillAction (core): set/clear `image_fill` on the selected VectorGraph fills,
  with per-fill undo (mirrors SetFillPaintAction). Image takes render priority; clearing
  reveals the colour/gradient underneath.
- Info Panel Shape section: an "Image:" combo listing the document's image assets (+ None)
  for the selected fill(s), showing the current assignment. Assign/clear pushes the action.

This lets an existing shape be given (or cleared of) an image fill, complementing the
import/drop placement. Next: 3.5b — persist image assets in the .beam container.
2026-06-21 00:30:01 -04:00
Skyler Lehmkuhl 659bc5fb02 Fix image-fill mapping: anchor to the fill's bounding box
The renderer painted the image brush at its native origin (0,0) with no brush
transform, so an image-filled rect drawn anywhere but the world origin only showed
the overlapping corner of the image. Both render paths now map the image's native
pixel space onto the fill's bounding box (Vello brush_transform; tiny-skia Pattern
transform) — 1:1 for an image-sized rectangle, stretch-to-bbox for arbitrary shapes.
2026-06-21 00:23:07 -04:00
Skyler Lehmkuhl 6c9fcb1921 Phase 3.5a: place imported images on the canvas (image-filled rect)
Replaces the DCEL "not yet supported" stubs so importing/dropping an image actually
puts it in the vector scene.

- AddShapeAction gains an `image_fill` + `AddShapeAction::image_rect(...)` constructor:
  a borderless rectangle (invisible edges) whose enclosed region is paint-bucketed and
  tagged with an image asset id. The renderer already prioritises `image_fill`.
- Direct import (auto_place_asset): an imported image is placed centered on the canvas
  at native size on a vector layer.
- Drag from the asset library onto the stage: image-filled rect at the drop point
  (centered), native size, using the asset's dimensions.

Next: SetImageFillAction + an Info-Panel image-fill picker for existing shapes; then
3.5b container persistence.
2026-06-21 00:22:17 -04:00
Skyler Lehmkuhl aea26f6192 docs: add Phase 3.5 (image textures in vector scenes; fixes DCEL-broken image import) 2026-06-21 00:02:47 -04:00
Skyler Lehmkuhl c936078850 docs: add 'fix animation tweens' (low pri); mark raster-keyframe-UI bugs done 2026-06-20 23:54:46 -04:00
Skyler Lehmkuhl 7445ee919f Onion skin settings: move from floating window to the Info Panel
The standalone egui window didn't fit the UI. Replaced it with a collapsible
"Onion Skin" section at the bottom of the Info Panel (Enabled checkbox + frames
before/after + opacity), available regardless of selection. SharedPaneState carries
a mutable `onion_skin` ref for the controls (distinct from the gated `onion` copy
used by rendering).
2026-06-20 23:49:38 -04:00
Skyler LehmkuhlandClaude Opus 4.8 10b4aa481e Onion skinning: vector-layer ghosts (tinted)
- Core compositor gains an optional screen-blend tint per CompositorLayer
  ([0,0,0,0] default = no-op, so existing compositing is unaffected);
  CompositorLayer::with_tint sets it — giving the Vello/vector path a tint hook.
- For the active VECTOR layer with onion on, build ghost scenes at each neighbouring
  keyframe's time via render_layer_isolated (reusing the prepare's image cache), then
  render each scene → sRGB → linear → composite with warm/cool tint + opacity falloff,
  behind the current frame. Off during playback; active layer only.

Completes onion skinning for all layer types (raster + vector).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 23:49:33 -04:00
Skyler LehmkuhlandClaude Opus 4.8 c2c7aefad1 Onion skin: settings window (frames before/after + opacity)
A small 'Onion Skin' egui window (shown while onion skinning is enabled) with
DragValues for frames_before/after (0..=5) and an opacity slider, rendered next to
the F3 debug overlay. Lets the user tune the configurable settings.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 23:25:43 -04:00
Skyler LehmkuhlandClaude Opus 4.8 78109cda93 Fix onion ghosts: show on blank cels + fault in on seek
- Removed the early `continue` that skipped a layer with no resident content — it
  also skipped the active raster layer's onion ghosts when the current cel was blank
  (the exact case you trace a new cel from neighbours). Each render arm already
  guards its own empty case, so the skip was redundant.
- Ghost texture resolution now falls through cache → resident raw_pixels (upload) →
  in-memory proxy → request fault-in, so neighbours that were paged out (e.g. after a
  seek, or saved-this-session with no decoded proxy) page in and ghost in, instead of
  silently rendering nothing.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 23:18:24 -04:00
Skyler LehmkuhlandClaude Opus 4.8 4dc937f9c0 Onion tint: screen-blend instead of multiply (so outlines tint too)
Multiplicative tint left blacks black, so outlines (the main thing to ghost in line
art) never picked up the warm/cool color. Switched the canvas-blit tint to a screen
blend (out = base + tint - base*tint): black → tint color, white unchanged, and a
clean no-op at tint=(0,0,0) for all normal blits. Reverted the default .w slots to 0.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 23:06:05 -04:00
Skyler Lehmkuhl 53cae1bfe5 Onion skinning (raster): toggle + tinted ghosts of the active layer
- OnionSkinSettings (editor view state): enabled, frames_before/after (default 2/2),
  opacity (0.35), warm past / cool future tints, linear falloff. Threaded App →
  SharedPaneState (gated off during playback) → VelloRenderContext.
- Toggle: View ▸ Onion Skinning + the `O` shortcut (AppAction::ToggleOnionSkin).
- Tint: packed an RGB multiply into the canvas-blit matrix uniform's unused .w slots
  (1,1,1 = no tint for all normal blits); BlitTransform::with_tint. Shader multiplies.
- Render: for the ACTIVE raster layer only, blit the N neighbouring keyframes (full
  texture if resident, else the low-res proxy — uploaded on demand) tinted + faint,
  composited behind the current frame. Off during playback.

Next: a settings panel (frame count/opacity) and vector-layer ghosts.
2026-06-20 23:05:57 -04:00
Skyler Lehmkuhl f585c370e8 docs: mark Phase 3e (playback prefetch) done 2026-06-20 22:46:23 -04:00
Skyler Lehmkuhl ed022995bd Keyframe diamonds: pointing-hand cursor + prefetch during playback
- Pointing-hand cursor when hovering a clickable keyframe diamond.
- Prefetch (Phase 3e, playback only): each update during playback, page in the next
  few upcoming keyframes (PREFETCH_AHEAD=4) per raster layer that aren't resident, via
  the existing async worker. Their full pixels land before the playhead reaches them,
  so playback shows full frames instead of the low-res proxy on every frame (the
  proxy→full pop was the "flicker"). Reactive faults still cover scrubbing.
2026-06-20 22:45:50 -04:00
Skyler Lehmkuhl 3188fc8bb6 Timeline: click a keyframe diamond to snap the playhead to it
render_layers now records each drawn keyframe diamond's screen rect + exact time in
`keyframe_diamond_hits`; handle_input hit-tests a click against them and sets the
playhead (and seeks the audio controller) to the keyframe's exact time. Uses the
previous frame's rects — diamonds don't move between frames, so the click lands
right — which sidesteps the input-before-render ordering and the drag/scroll Y math.
Works for both raster and vector keyframes.
2026-06-20 22:44:41 -04:00
Skyler LehmkuhlandClaude Opus 4.8 2cbaf67583 Raster keyframe timeline UI: display + explicit creation + no lazy create
Make raster layers behave like vector on the timeline.

- Timeline: draw a diamond per `RasterKeyframe` (mirrors the vector keyframe block).
- New Keyframe (K / menu): on a raster layer, insert a BLANK cel at the playhead via
  a new undoable `AddRasterKeyframeAction` (+ `RasterLayer::insert_blank_keyframe_at`
  / `remove_keyframe`). Vector path unchanged.
- Stop lazy creation: paint tools now edit the ACTIVE keyframe (at-or-before the
  playhead) instead of creating one. The brush captures the active keyframe's exact
  time; `RasterStroke`/`RasterFillAction` resolve via `keyframe_at_mut` (error if
  none); the tool-site `ensure_keyframe_at` blocks (brush/fill/bucket/wand/quick-
  select/floating-lift) are removed — each read already bails when no keyframe exists.
  New layers still seed a keyframe at the playhead, so there's normally one to paint
  into; painting before the first keyframe is now a no-op (as intended).

Next: onion skinning.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 22:22:02 -04:00
Skyler Lehmkuhl 31e23b0fc7 Fix 3d: stroke vanished on commit (establish full buffer on first execute)
The brush commits via a GPU-canvas readback and relies on the action's first
execute() to SET raw_pixels from that readback — at that point raw_pixels is empty
(new keyframe) or the pre-stroke state, never something a dirty-rect diff can stamp
onto. My initial diff-only execute skipped (to avoid corruption), so the stroke
disappeared.

Fix: the action keeps the full post-edit buffer ONLY for the first execute (the
commit), assigning raw_pixels outright exactly like the old code; it's taken/dropped
immediately, so the action sitting in the undo stack still retains just the small
diff. Redo replays via the diff onto the now-resident base.

Also harden the diff itself for the blank-base case: `before_blank` lets apply_after
build from a transparent buffer (redo of a first stroke after undo-to-blank) and
apply_before restore to empty; the resident-base skip is kept only for non-blank
bases (faulted in before undo/redo). Tests cover commit/redo from empty.
2026-06-20 21:44:26 -04:00
Skyler Lehmkuhl c627533185 docs: mark Phase 3d (raster undo dirty-rect diffs) done 2026-06-20 21:31:57 -04:00
Skyler Lehmkuhl aae51e3b3c Phase 3d: dirty-rect diffs for raster undo (bound undo-history RAM)
`RasterStrokeAction`/`RasterFillAction` stored the whole before+after RGBA frame
(~16 MB/action at 1080p → up to ~1.6 GB at the 100-action cap). They now store a
`RasterDiff` — only the changed bounding box's pixels before and after — computed
once in `new()` from the full buffers, which are then dropped. A brush dab shrinks
from ~16 MB to tens of KB; a full-canvas fill is unchanged (its bbox is the frame).

Paging interaction: a diff overwrites just the bbox, so the keyframe's pixels must
be resident when undo/redo applies. A clean evicted frame's container bytes equal
its current logical state, so the editor faults the target frame in (synchronously)
before undo/redo via a new `Action::raster_resident_hint` + `peek_undo/redo_raster_hint`.
Dirty frames are never evicted, so they're already resident. If a base is somehow
not resident the apply is skipped (logged), never resized-and-corrupted.

Unit tests cover exact before/after round-trip, blank-first-stroke, no-op, and the
non-resident-base skip.
2026-06-20 21:31:38 -04:00
Skyler Lehmkuhl 4cb43d670b docs: add Phase 3e (prefetch raster frames) to the plan 2026-06-20 21:18:32 -04:00
Skyler Lehmkuhl a35cc6fa9f Bilinear-sample upscaled raster proxies (smooth, not blocky)
The canvas blit used a nearest sampler, so the upscaled low-res proxy looked
blocky. Added a Linear sampler + `CanvasBlitPipeline::blit_smooth`; the raster
render uses it only for the proxy path (full-res canvas stays nearest/crisp). The
bind-group layout already declares the canvas texture filterable, so no layout
change was needed.
2026-06-20 21:14:47 -04:00
Skyler Lehmkuhl 3c302f0215 docs: mark Phase 3a-3 (image proxy) done 2026-06-20 21:09:30 -04:00
Skyler LehmkuhlandClaude Opus 4.8 1bfd09f151 Phase 3a-3: low-res image proxy for cold-scrub raster frames
Scrubbing onto a paged-out raster keyframe flashed blank for the 1-2 frames its
full pixels took to page in. Now a low-res proxy is shown in that gap.

- core: `MediaKind::RasterProxy` (id derived from the keyframe id via
  `raster_proxy_media_id`); `brush_engine::encode_raster_proxy_png` downscales a full
  RGBA buffer to a ≤192px-long-edge PNG. Save writes a proxy beside each resident
  frame's full PNG (paged-out frames keep their existing proxy row, like the full).
  Load eagerly decodes proxies (small) into `RasterKeyframe::proxy`.
- editor: a separate `proxy_layer_cache` in the GPU brush (own recency LRU, budget 64
  since each is ~1/100th a full frame) + `ensure_proxy_texture`/`get_proxy_texture`.
  The raster render, when the full texture isn't resident, blits the proxy mapped to
  the keyframe's FULL logical dims so it upscales via the sampler. F3 VRAM figure now
  includes proxy textures.

When the full pixels land (async fault-in), the full path takes over automatically.
Proxies only exist after a save+reload; freshly-painted unsaved frames stay resident
so they need none.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 20:05:46 -04:00
Skyler Lehmkuhl a1e3cc841f docs: mark Phase 3c (raster GPU cache bound) done 2026-06-20 19:16:13 -04:00
Skyler Lehmkuhl 17d7395229 Phase 3c: bound the raster-layer GPU texture cache + show VRAM in F3
`raster_layer_cache` (one ~w·h·16-byte Rgba16Float CanvasPair per keyframe) had no
size cap — scrubbing a long timeline grew VRAM without bound (~33 MB/frame at 1080p),
the largest unbounded consumer. Added a recency LRU (RASTER_LAYER_CACHE_MAX = 12):
`ensure_layer_texture` bumps the frame to most-recent and evicts the oldest past the
budget; the shown frame (and any rendered this pass) is always most-recent so it's
never the victim. Evicted textures re-upload cheaply from the resident/faulted-in
pixels on revisit. `remove_layer_texture` keeps the LRU in sync.

F3 debug overlay now reports the tracked VRAM (raster cache MB + frame count), pushed
from the GPU brush whenever the cache changes (wgpu exposes no allocator query).
2026-06-20 19:15:16 -04:00
Skyler Lehmkuhl 62d6cd0c84 docs: mark Phase 3a-1/3a-2/3b done; note deferred raster-keyframe-UI bugs 2026-06-20 18:46:46 -04:00
Skyler Lehmkuhl d001ca1083 Fix save crash on zero/sparse-audio projects (phantom pool placeholder)
`AudioPool::load_from_serialized` sizes the slot Vec by pool_index and fills gaps
with empty `AudioFile::new(PathBuf::new(), …)` placeholders. Two bugs let a
placeholder reach the next save and abort it with "Is a directory":

- Off-by-one: `entries.max().unwrap_or(0) + 1` made an *empty* pool length 1, so a
  project with no audio still got one placeholder. Size by `max(pool_index + 1)`
  → empty entries yield length 0.
- `serialize()` emitted placeholder slots: an empty path round-trips to
  `relative_path = Some("")`, which `save_beam` resolves to the project directory
  (`join("")`) and tries to read as media. Skip empty-path / no-packed-media slots.
- Defense in `save_beam`: gate referenced-media packing on `full.is_file()` (not
  `exists()`), so any blank/dir path falls through to embedded data instead of
  reading a directory.

Pre-existing; surfaced by a save → reload → save cycle on a raster-only project.
2026-06-20 18:46:19 -04:00
Skyler LehmkuhlandClaude Opus 4.8 39dc402ba3 Phase 3b: bound resident raster pixels with an eviction LRU
Scrubbing a large paint project no longer accumulates every visited frame in RAM.
A fault-in-recency LRU keeps the most-recently-paged-in RASTER_RESIDENT_MAX (12)
keyframes resident and drops the pixels of older *clean* ones (re-arming their
fault-in so they re-page on revisit). The shown frame is always the most-recent
fault-in, so it's never evicted.

Data-loss safety: a new `dirty` flag marks any keyframe whose `raw_pixels` were
mutated by editing (stroke/fill/paint-bucket/floating-lift + their undo/redo) and
is NOT yet in the container. Dirty keyframes are NEVER evicted — they're only
unpinned from the LRU. The flag is cleared on a successful save, which also re-arms
the LRU for the now-clean resident frames so the bound still applies to frames
edited this session.

Also: the save loop now walks all layers (incl. nested) to match the load path's
recursive fault-in arming — evicted frames keep their existing container row
(media_exists), and nested raster keyframes are persisted + covered by live_media.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 17:56:37 -04:00
Skyler LehmkuhlandClaude Opus 4.8 2e07a88905 Phase 3a-2: async raster page-in (no UI block)
The fault-in drain no longer decodes on the UI thread. It now:
- dispatches each newly-requested keyframe's page-in to a background thread
  (deduped via an in-flight set, store cloned per request so path changes are
  picked up), and
- applies completed results from a channel at the top of update(), keeping the UI
  ticking while loads are outstanding.

Cold scrubs no longer freeze. The brief blank gap before a frame lands is removed
by the image proxy (3a-3); eviction to bound RAM while scrubbing is 3b.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 17:00:04 -04:00
Skyler Lehmkuhl 4228864259 Phase 3a-1: lazy fault-in of raster keyframe pixels
Raster keyframes are no longer eagerly decoded at load — `raw_pixels` stays empty
and is paged in on demand from the project container, so a big paint project opens
instantly and only touched frames hit RAM.

- core: `read_packed_media_readonly` (fresh read-only connection, can't conflict
  with an in-place save) + `RasterStore` (holds the container path; `load_pixels`
  reads+decodes a keyframe's PNG by id). `load_beam_sqlite` stops eager-decoding and
  instead marks every raster keyframe `needs_fault_in` (recursively, incl. nested);
  a freshly-created keyframe stays false (blank-resident, nothing to page). Added
  `Document::all_layers_mut`.
- editor: the canvas records a fault-in request when it needs a paged-out keyframe
  (empty pixels && needs_fault_in); the App drains the sink at the top of update(),
  pages the pixels in via the store, clears the flag, and repaints. Store path is set
  on load and after save. Export faults in synchronously per frame.

Cold-scrub still shows a 1-frame gap and the page-in is synchronous; the image proxy
(3a-2) and async load (3a-3) remove those next.
2026-06-19 16:59:46 -04:00
Skyler Lehmkuhl 6d386a884e Phase 5: fix broken unit tests; cargo test --lib green again
The lib unit tests had gone stale (time values became newtypes) and no longer
compiled. Updated the test code to the current API and fixed the few real issues
the now-running tests surfaced.

Test-only:
- Wrap raw f64 time literals in Beats(...) where the API now takes Beats
  (automation.rs); pass &TempoMap / Beats where signatures changed (clip.rs,
  effect_layer.rs).
- shape.rs: assert the documented no-fill default (fill_color None) instead of Some.
- add_clip_instance / trim_clip_instances tests: register a vector clip with the
  test's clip_id so the action's get_clip_duration lookup succeeds.

Production fix (delete_folder.rs):
- DeleteFolderAction(MoveToParent) reparented child subfolders to the deleted
  folder's parent but never restored them on undo, orphaning them. Track the moved
  subfolder ids and restore their parent on rollback.

Result: daw-backend lib 17 passed; lightningbeam-core lib 264 passed.
2026-06-19 16:45:23 -04:00
Skyler Lehmkuhl 4ad95e6755 Downmix surround to stereo + reload video audio via FFmpeg
Surround → stereo downmix:
- render_from_file folds multichannel sources (5.1/7.1/…) down to stereo with
  proper coefficients (full level for the matching front channel, 1/√2 for centre
  + each surround, LFE dropped), normalized per row to avoid clipping (matching
  ffmpeg's default). Applied uniformly to both the direct-copy and sinc-resample
  paths and to every storage type (PCM, compressed, video audio), only when
  dst==2 && src>2; unknown layouts fall back to front L/R. Previously it just took
  FL/FR, dropping centre dialog + surrounds.

Proper video-audio reload:
- A video's audio track is now stored as a path reference to the video (never
  packed/embedded as audio media) and re-probed via FFmpeg on load into a
  streaming VideoAudio entry, so multichannel audio survives reload (the old
  Symphonia reconstitution collapsed it, breaking the downmix). Driven by a new
  AudioPoolEntry.is_video_audio flag across serialize / save_beam / load. Also
  removes the decode-whole-video-to-RAM + temp-file path on load.

Fix video scaling:
- Any video with dimensions larger than the stage was being scaled down into the corner incorrectly; we now bake the frame-clip scale into the instance transform.
2026-06-17 18:30:42 -04:00
Skyler LehmkuhlandClaude Opus 4.8 097345be76 Fix video thumbnail strip bugs + persist thumbnails (resumable)
Thumbnail rendering fixes:
- Strip now tiles from each clip's true (unclamped) origin and draws only the
  tiles intersecting the visible rect, so it scrolls correctly and shows the
  right frames when a clip is scrolled partly off the left. Both render sites
  (collapsed group + expanded track) share one draw_video_thumbnail_strip helper.
- On-clip strip no longer freezes on the first thumbnail: get_thumbnail_at now
  returns the actual thumbnail timestamp and the GPU texture cache keys on it, so
  tiles refresh as closer thumbnails finish generating.
- Hover preview derives content time from the clip's true origin too (matches the
  strip when scrolled off-screen).
- insert_thumbnail keeps the cache sorted + deduped (fixes a latent unsorted
  binary_search bug, and makes concurrent restore + resume race-safe).

Thumbnail persistence (mirrors waveform persistence):
- MediaKind::Thumbnail rows, keyed by thumbnail_media_id(clip_id) (clip id XOR a
  sentinel). Each clip's thumbnails PNG-encoded into one opaque LBTN blob (editor
  owns the format), snapshotted cheaply (Arc clones) and encoded off the UI thread.
- Save writes the packs (kept in place on re-save); load reads them into
  LoadedProject.thumbnail_blobs; the editor decodes + inserts them on a background
  thread, so reload shows thumbnails instantly with no re-decode (even if the
  source video file is missing).
- Partial sets are persisted with a complete flag and RESUMED on load:
  generate_keyframe_thumbnails takes a should_skip predicate so a save made
  mid-generation continues from where it left off instead of redoing the work.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 15:36:56 -04:00
Skyler LehmkuhlandClaude Opus 4.8 c784816615 Phase 2: bound video frame cache + stream the export mux
- VideoManager.frame_cache: unbounded HashMap (grew per distinct frame during
  playback) -> LruCache evicted by a 256MB byte budget. Byte-budget rather than
  frame count is robust across resolutions (a 4K frame is ~33MB vs ~2MB at
  800x600). unload_video pops per-clip keys (LruCache has no retain).
- mux_video_and_audio: stream-merge the two inputs by PTS with one pending
  packet per stream (O(1) memory) instead of collecting every packet into Vecs
  first (O(duration)). Output is byte-identical.
- export AAC: sanitize the planar-f32 path (non-finite -> 0, finite clamped to
  [-1,1]) like the integer paths, with a one-time warning. A stray NaN/Inf
  render sample no longer fails the whole export.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 14:30:32 -04:00
Skyler Lehmkuhl 3d7cff9ad0 Stream audio & video from .beam container; waveform LOD pyramid + persistence
Migrate the .beam container to SQLite and stream media from it instead of
decoding whole files into RAM on import/load.

Container & large files:
- SQLite .beam container (beam_archive) with in-place transactional saves and an
  incremental BlobReader; supports both packed (chunked blobs) and referenced
  (external path) media, with a user preference + first-import prompt for files
  over the large-media threshold.

Audio streaming:
- Stream packed compressed audio on load via an inversion-of-control blob factory
  (AudioBlobSourceFactory): daw-backend defines the trait, core implements it
  over BlobReader, so the audio engine stays container-agnostic.
- Bulk-activate disk streaming for all loaded clips after SetProject.
- Sample-accurate compressed seek (SeekMode::Accurate; Coarse mislands on VBR).

Video:
- Video frames decoded/streamed on demand; thumbnails generated asynchronously
  on a dedicated decoder so import/load never blocks the UI.
- The video's audio track is streamed on demand via an ffmpeg VideoAudioReader
  as a separate editable AudioClip (no /tmp WAV extraction).

Waveform overview:
- Streaming min/max LOD pyramid (waveform_pyramid), bounded memory, configurable
  floor B; serialized into the container and restored on load (or generated in
  the background from the packed blob when absent), so no re-decode on reload.
- GPU min/max upload path; integer-LOD textureLoad fixes zoom-dependent wobble.
2026-06-17 13:52:38 -04:00
Skyler Lehmkuhl 83609cc9dc Fix video export resolution scaling and post-export UI hang
- Scale the document to the selected output resolution. It was rendered
  at document size regardless of the export dimensions, so picking a
  different resolution didn't scale the stage.
- Run the audio+video mux on a background thread instead of the UI
  thread, keeping the app responsive (showing "Finalizing") during the
  re-mux pass.
- Send desktop notifications fire-and-forget. notify_rust's show() is a
  synchronous D-Bus call that blocked the UI for the full service
  activation timeout (~25s) when no notification daemon is running.
2026-06-16 08:35:52 -04:00
Skyler Lehmkuhl 318720f89d Fix gamma handling and improve brush canvas performance
Color correctness:
- Unpremultiply before the sRGB OETF on the display and export blits;
  encoding premultiplied color corrupted antialiased/transparent edges.
- Tag exported video as full-range BT.709 (matrix/primaries/transfer).
- Run perception effects (invert, brightness/contrast, hue/saturation)
  in gamma space to match standard editors.
- Interpolate gradients in gamma space across the raster and vector paths.
- Render effect thumbnails in the same linear space as the live pipeline.

Brush performance:
- Store the raster canvas as Rgba16Float (no shadow banding from 8-bit
  linear), with an incremental per-tile ping-pong sync replacing the
  per-frame full-canvas copy.
- Do the linear->sRGB readback conversion on the GPU and reuse a cached
  scratch texture, dropping a ~110ms-per-stroke CPU decode.

Cleanup:
- Single COLOR_WGSL prelude and shared CPU sRGB scalars instead of ~8
  duplicated copies of the transfer functions.
- Shared compute-pipeline builder; smudge folded onto the tile-sync path.
2026-06-16 08:32:39 -04:00
Skyler Lehmkuhl 327e40026a Release 1.0.4-alpha 2026-06-02 15:11:39 -04:00
Skyler Lehmkuhl 7257cdf9c4 update release script 2026-06-02 15:11:35 -04:00
Skyler Lehmkuhl d6c6c0d72d update changelog 2026-06-02 15:09:24 -04:00
Skyler Lehmkuhl 398457093a Release 1.0.4-alpha 2026-06-02 14:37:07 -04:00
Skyler Lehmkuhl d7de5ce3f1 Bump version to 1.0.4-alpha 2026-06-02 14:37:07 -04:00
Skyler Lehmkuhl 2a0c7da5ea fix build issues 2026-06-02 13:52:32 -04:00
Skyler Lehmkuhl 37f4abd1f5 fix build issues 2026-06-02 13:41:10 -04:00
Skyler Lehmkuhl a36553ccbb fix build issues 2026-06-02 13:23:30 -04:00
Skyler Lehmkuhl 47a6569fe0 Bump version to 1.0.4-alpha 2026-06-02 13:11:47 -04:00
Skyler Lehmkuhl 73d5d554c7 Merge branch 'release' of github.com:skykooler/Lightningbeam into release 2026-06-02 13:11:15 -04:00
Skyler Lehmkuhl 45955dbbec Bump version to 1.0.4-alpha 2026-06-02 13:10:52 -04:00
Skyler Lehmkuhl b4e5469b51 Release 1.0.4-alpha 2026-06-02 13:10:52 -04:00
Skyler Lehmkuhl 54d5764bd0 Make beats canonical representation rather than seconds 2026-06-02 13:06:36 -04:00
Skyler Lehmkuhl f372a84313 Massive tempo refactor - make beats canonical time rep and allow them to be non constant 2026-04-02 10:26:01 -04:00
Skyler Lehmkuhl ae146533d9 Update automation lanes too 2026-04-01 10:17:52 -04:00
Skyler Lehmkuhl 3fc4773ec3 Fix remaining sites that weren't updating properly on BPM changes 2026-04-01 09:33:35 -04:00
Skyler Lehmkuhl cfb8e4462b All events now have three time references for seconds, measures/beats, frames 2026-03-30 10:15:55 -04:00
Skyler Lehmkuhl 65a550d8f4 Add piano roll note snapping 2026-03-24 19:24:24 -04:00
Skyler Lehmkuhl 123fe3f21a Tweak automation lane appearance 2026-03-23 23:37:15 -04:00
Skyler Lehmkuhl fa40173562 Add automatable volume and pan control to default instruments 2026-03-23 23:27:05 -04:00
Skyler Lehmkuhl 434b488a4c Merge branch 'rust-ui' of https://git.skyler.io/skyler/Lightningbeam into rust-ui 2026-03-22 18:16:25 -04:00
Skyler Lehmkuhl f16e651610 work on vector graph 2026-03-22 18:16:17 -04:00
Skyler Lehmkuhl 0d7f15853c Set default timeline mode based on activity 2026-03-20 21:05:00 -04:00
Skyler Lehmkuhl 121fa3a50a Add count-in 2026-03-20 20:51:50 -04:00
Skyler Lehmkuhl c938ea44b0 Add metronome 2026-03-19 01:16:26 -04:00
Skyler Lehmkuhl 84a1a98452 Snap to beats in measures mode 2026-03-19 00:47:15 -04:00
Skyler Lehmkuhl 164ed2ba73 Add velocity and modulation editing 2026-03-18 23:35:18 -04:00
Skyler Lehmkuhl 6b6ae230a1 Add pitch bend support 2026-03-18 23:11:24 -04:00
Skyler Lehmkuhl 4f3da810d0 Add automation inputs for audio graphs 2026-03-18 11:25:48 -04:00
Skyler Lehmkuhl 8acac71d86 Merge branch 'rust-ui' of https://git.skyler.io/skyler/Lightningbeam into rust-ui 2026-03-13 18:53:37 -04:00
Skyler Lehmkuhl c9a9c2c5f0 rewrite vector backend again 2026-03-13 18:53:33 -04:00
Skyler Lehmkuhl d7a29ee1dc Double CPU performance by using tiny-skia instead of vello CPU 2026-03-13 18:52:37 -04:00
Skyler Lehmkuhl be8514e2e6 Fix midi tracks recording previews 2026-03-11 12:53:26 -04:00
Skyler Lehmkuhl 3bc980d08d Use audio engine as source of truth for audio tracks 2026-03-11 12:37:31 -04:00
Skyler Lehmkuhl b8f847e167 Add drawing tablet input support 2026-03-11 10:58:30 -04:00
Skyler Lehmkuhl f72c2c5dbd Release 1.0.3-alpha 2026-03-10 21:43:26 -04:00
Skyler Lehmkuhl e388902743 Bump version to 1.0.3-alpha 2026-03-10 21:42:12 -04:00
Skyler Lehmkuhl ce7ed2586f Support Vello CPU fallback on systems with older GPUs 2026-03-10 21:39:01 -04:00
Skyler Lehmkuhl 7a3f522735 Give metatracks explicit node graphs 2026-03-10 20:20:46 -04:00
Skyler Lehmkuhl f9b62bb090 Add frames timeline mode 2026-03-10 15:54:54 -04:00
Skyler Lehmkuhl 4118c75b86 Performance tweaks 2026-03-10 03:24:03 -04:00
Skyler Lehmkuhl ac2b4ff8ab Improve idle performance 2026-03-10 02:41:44 -04:00
Skyler Lehmkuhl 26f06da5bf Add gradient support to vector graphics 2026-03-10 00:57:47 -04:00
Skyler Lehmkuhl 8bd65e5904 Address Mac build failures 2026-03-09 22:03:51 -04:00
Skyler Lehmkuhl 0ae97f9562 Address Mac build failures 2026-03-09 14:36:54 -04:00
Skyler Lehmkuhl 0066dffc81 Address Mac and Windows build failures 2026-03-09 14:15:08 -04:00
Skyler Lehmkuhl 42679cb02a Release 0.7.14-alpha 2025-01-23 16:43:22 -05:00
Skyler Lehmkuhl 42bdab988d Release 0.7.13-alpha 2025-01-23 05:28:04 -05:00
Skyler Lehmkuhl e9455c2ef2 Release 0.7.12-alpha 2025-01-18 00:43:54 -05:00
Skyler Lehmkuhl 73fd191a28 Release 0.7.13-alpha 2025-01-18 00:31:57 -05:00
Skyler Lehmkuhl f79439ced3 Release 0.7.11-alpha 2025-01-16 21:42:24 -05:00
Skyler Lehmkuhl bfc8be4058 Release 0.7.10-alpha 2025-01-15 21:25:26 -05:00
Skyler Lehmkuhl 25248f5088 Merge branch 'main' into release 2025-01-15 21:15:49 -05:00
Skyler Lehmkuhl b6c72f3175 0.7.9-alpha: Merge branch 'main' into release 2025-01-14 20:02:18 -05:00
Skyler Lehmkuhl 6d04143606 0.7.8-alpha: Merge branch 'main' into release 2025-01-14 02:12:03 -05:00
Skyler Lehmkuhl 3f0fcbb626 0.7.7-alpha: Merge branch 'main' into release 2025-01-13 22:35:01 -05:00
Skyler Lehmkuhl 9b9a61f2a0 0.7.6-alpha: Merge branch 'main' into release 2025-01-13 17:40:13 -05:00
Skyler Lehmkuhl ea47f1d1c8 Merge branch 'main' into release 2025-01-12 23:26:20 -05:00
Skyler Lehmkuhl 6bbc660019 Merge branch 'main' into release 2025-01-12 14:41:18 -05:00
Skyler Lehmkuhl 51bed98b0b Merge branch 'main' into release 2025-01-12 13:43:22 -05:00
Skyler Lehmkuhl fc82d1e1be Merge branch 'main' into release 2025-01-12 02:56:49 -05:00
Skyler Lehmkuhl 1871bb713c Merge branch 'main' into release 2025-01-10 20:17:16 -05:00
Skyler Lehmkuhl e65aac496c Merge branch 'main' into release 2025-01-10 19:37:47 -05:00
skykooler 3db3eaef67 Fix multiline release notes 2025-01-08 05:51:57 -05:00
skykooler 82733268c5 Don't use deprecated commands 2025-01-08 05:43:36 -05:00
skykooler c6206b87bd Add output to extract changelog job 2025-01-08 05:39:13 -05:00
skykooler 822012b17b Debug better 2025-01-08 05:32:54 -05:00
skykooler 10b69837c3 Set version in changelog extraction step 2025-01-08 05:30:07 -05:00
skykooler a07b9bae76 Debug release notes extraction 2025-01-08 05:25:43 -05:00
338 changed files with 54790 additions and 22605 deletions
+95 -22
View File
@@ -14,7 +14,7 @@ jobs:
fail-fast: false
matrix:
include:
- platform: ubuntu-22.04
- platform: ubuntu-24.04
target: ''
artifact-name: linux-x86_64
- platform: macos-latest
@@ -54,6 +54,27 @@ jobs:
with:
targets: ${{ matrix.target != '' && matrix.target || '' }}
# A [patch.crates-io] whose version doesn't satisfy the dependency requirement is silently
# IGNORED by cargo: it warns "patch ... was not used in the crate graph" and builds against the
# real crates.io crate instead. That's how a stale egui fork got us a `cannot find type
# CursorImage` error four minutes into the build, in a file that had nothing to do with the
# cause. Fail here instead, with the actual reason.
- name: Verify egui fork patch applies
shell: bash
working-directory: ./lightningbeam-ui
run: |
unused=$(cargo metadata --format-version 1 2>&1 >/dev/null | grep "was not used in the crate graph" || true)
if [ -n "$unused" ]; then
echo "::error::The egui fork's [patch.crates-io] entries are being ignored — cargo is building against stock crates.io egui, not the fork."
echo "$unused"
echo ""
echo "The fork's version must SATISFY the requirement in lightningbeam-ui/Cargo.toml."
echo "Fork workspace version: $(grep -m1 '^version' ../egui-fork/Cargo.toml)"
echo "Required by us: $(grep -m1 '^eframe' Cargo.toml)"
exit 1
fi
echo "egui fork patch applies cleanly."
- name: Rust cache
uses: swatinem/rust-cache@v2
with:
@@ -62,7 +83,7 @@ jobs:
# ── Linux dependencies ──
- name: Install dependencies (Linux)
if: matrix.platform == 'ubuntu-22.04'
if: matrix.platform == 'ubuntu-24.04'
run: |
sudo apt-get update
sudo apt-get install -y \
@@ -71,10 +92,11 @@ jobs:
libx11-dev libxkbcommon-dev libxcb-shape0-dev libxcb-xfixes0-dev \
libxdo-dev libglib2.0-dev libgtk-3-dev libvulkan-dev \
yasm libx264-dev libx265-dev libvpx-dev libmp3lame-dev libopus-dev \
libva-dev libdrm-dev \
libpulse-dev squashfs-tools dpkg rpm
- name: Install cargo packaging tools (Linux)
if: matrix.platform == 'ubuntu-22.04'
if: matrix.platform == 'ubuntu-24.04'
uses: taiki-e/install-action@v2
with:
tool: cargo-deb,cargo-generate-rpm
@@ -88,7 +110,20 @@ jobs:
- name: Install dependencies (Windows)
if: matrix.platform == 'windows-latest'
shell: pwsh
run: choco install cmake llvm --installargs 'ADD_CMAKE_TO_PATH=System' -y
run: |
choco install cmake llvm --installargs 'ADD_CMAKE_TO_PATH=System' -y
# Ninja: build NeuralAudio with it instead of a Visual Studio generator,
# so the cmake crate doesn't need to recognize the runner's VS version.
choco install ninja -y
# Activate the MSVC developer environment (runs vcvars) so the cmake crate
# building nam-ffi/NeuralAudio can determine the Visual Studio generator.
# Without this, cmake-rs panics with "couldn't determine visual studio generator".
- name: Set up MSVC developer environment (Windows)
if: matrix.platform == 'windows-latest'
uses: ilammy/msvc-dev-cmd@v1
with:
arch: x64
# ── Common build steps ──
- name: Extract version
@@ -104,6 +139,19 @@ jobs:
run: |
sed -i.bak 's/ffmpeg-next = { version = "8.0", features = \["static"\] }/ffmpeg-next = { version = "8.0", features = ["build", "static"] }/' lightningbeam-ui/lightningbeam-editor/Cargo.toml
# ffmpeg-sys-next configures FFmpeg with --disable-autodetect and only passes --enable-vaapi
# when its build-vaapi feature is set; ffmpeg-next 8.0 doesn't forward it, so depend on the
# sys crate directly. Linux only (the feature is a no-op elsewhere and we only ship VAAPI on
# Linux). With it set, a missing libva-dev makes FFmpeg configure fail loudly instead of
# silently shipping a software-only build.
- name: Enable VAAPI in FFmpeg build (Linux)
if: matrix.platform == 'ubuntu-24.04'
shell: bash
run: |
sed -i '/^ffmpeg-next = /a ffmpeg-sys-next = { version = "8.0", features = ["build-vaapi"] }' \
lightningbeam-ui/lightningbeam-editor/Cargo.toml
grep -n 'ffmpeg-sys-next' lightningbeam-ui/lightningbeam-editor/Cargo.toml
- name: Setup FFmpeg (Windows)
if: matrix.platform == 'windows-latest'
shell: pwsh
@@ -117,14 +165,6 @@ jobs:
# LLVM/libclang for bindgen
echo "LIBCLANG_PATH=C:\Program Files\LLVM\bin" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append
- name: Setup icons
shell: bash
run: |
mkdir -p lightningbeam-ui/lightningbeam-editor/assets/icons
cp -f src-tauri/icons/32x32.png lightningbeam-ui/lightningbeam-editor/assets/icons/
cp -f src-tauri/icons/128x128.png lightningbeam-ui/lightningbeam-editor/assets/icons/
cp -f src-tauri/icons/icon.png lightningbeam-ui/lightningbeam-editor/assets/icons/256x256.png
- name: Stage factory presets
shell: bash
run: |
@@ -135,7 +175,7 @@ jobs:
rm -f lightningbeam-ui/lightningbeam-editor/assets/presets/README.md
- name: Inject preset entries into RPM metadata (Linux)
if: matrix.platform == 'ubuntu-22.04'
if: matrix.platform == 'ubuntu-24.04'
shell: bash
run: |
cd lightningbeam-ui
@@ -161,6 +201,7 @@ jobs:
echo "MACOSX_DEPLOYMENT_TARGET=11.0" >> "$GITHUB_ENV"
- name: Build release binary
if: matrix.platform != 'windows-latest'
shell: bash
env:
FFMPEG_STATIC: "1"
@@ -172,6 +213,23 @@ jobs:
fi
cargo build --release --bin lightningbeam-editor $TARGET_FLAG
# Windows must build under pwsh, not Git Bash: Git for Windows puts its
# usr\bin on PATH ahead of the MSVC tools, so its coreutils `link.exe`
# shadows MSVC's linker and rustc fails with "extra operand". pwsh keeps
# the MSVC environment (set by msvc-dev-cmd) at the front of PATH.
- name: Build release binary (Windows)
if: matrix.platform == 'windows-latest'
shell: pwsh
env:
FFMPEG_STATIC: "1"
# Force Ninja for the cmake crate (nam-ffi/NeuralAudio): cmake-rs 0.1.54
# panics on "unknown VisualStudio version: 18.0" when it auto-detects the
# runner's VS generator. Ninja sidesteps that lookup entirely.
CMAKE_GENERATOR: Ninja
run: |
cd lightningbeam-ui
cargo build --release --bin lightningbeam-editor
- name: Copy cross-compiled binary to release dir
if: matrix.target != ''
shell: bash
@@ -179,6 +237,20 @@ jobs:
mkdir -p lightningbeam-ui/target/release
cp lightningbeam-ui/target/${{ matrix.target }}/release/lightningbeam-editor lightningbeam-ui/target/release/
# Guard: the zero-copy export needs the static ffmpeg to have h264_vaapi, which only
# happens if libva headers were present at ffmpeg configure time. ffmpeg autodetects it,
# so a missing libva-dev silently ships a software-only build. A vaapi-enabled binary
# links libva — assert that, so the dep can never regress unnoticed.
- name: Verify VAAPI is compiled in (Linux)
if: matrix.platform == 'ubuntu-24.04'
shell: bash
run: |
if ! ldd lightningbeam-ui/target/release/lightningbeam-editor | grep -q 'libva\.so'; then
echo "::error::Release binary does not link libva — ffmpeg was built without VAAPI (is libva-dev installed?)."
exit 1
fi
echo "VAAPI OK: binary links libva."
# ── Stage presets next to binary for packaging ──
- name: Stage presets in target dir
shell: bash
@@ -190,7 +262,7 @@ jobs:
# Linux Packaging
# ══════════════════════════════════════════════
- name: Build .deb package
if: matrix.platform == 'ubuntu-22.04'
if: matrix.platform == 'ubuntu-24.04'
shell: bash
run: |
cd lightningbeam-ui
@@ -206,14 +278,15 @@ jobs:
rm -rf "$WORK"
- name: Build .rpm package
if: matrix.platform == 'ubuntu-22.04'
if: matrix.platform == 'ubuntu-24.04'
shell: bash
run: |
cd lightningbeam-ui
cargo generate-rpm -p lightningbeam-editor
RPM_VERSION=$(grep '^version' lightningbeam-editor/Cargo.toml | sed 's/.*"\(.*\)"/\1/' | tr '-' '~')
cargo generate-rpm -p lightningbeam-editor --set-metadata="version = \"$RPM_VERSION\""
- name: Build AppImage
if: matrix.platform == 'ubuntu-22.04'
if: matrix.platform == 'ubuntu-24.04'
shell: bash
run: |
cd lightningbeam-ui
@@ -259,7 +332,7 @@ jobs:
chmod +x "Lightningbeam_Editor-${VERSION}-x86_64.AppImage"
- name: Upload .deb
if: matrix.platform == 'ubuntu-22.04'
if: matrix.platform == 'ubuntu-24.04'
uses: actions/upload-artifact@v4
with:
name: deb-package
@@ -267,7 +340,7 @@ jobs:
if-no-files-found: error
- name: Upload .rpm
if: matrix.platform == 'ubuntu-22.04'
if: matrix.platform == 'ubuntu-24.04'
uses: actions/upload-artifact@v4
with:
name: rpm-package
@@ -275,7 +348,7 @@ jobs:
if-no-files-found: error
- name: Upload AppImage
if: matrix.platform == 'ubuntu-22.04'
if: matrix.platform == 'ubuntu-24.04'
uses: actions/upload-artifact@v4
with:
name: appimage
@@ -295,7 +368,7 @@ jobs:
mkdir -p "$APP/Contents/Resources/presets"
cp lightningbeam-ui/target/release/lightningbeam-editor "$APP/Contents/MacOS/"
cp src-tauri/icons/icon.icns "$APP/Contents/Resources/lightningbeam-editor.icns"
cp lightningbeam-ui/lightningbeam-editor/assets/icons/icon.icns "$APP/Contents/Resources/lightningbeam-editor.icns"
cp -r lightningbeam-ui/lightningbeam-editor/assets/presets/* "$APP/Contents/Resources/presets/"
cat > "$APP/Contents/Info.plist" << EOF
@@ -380,7 +453,7 @@ jobs:
release:
needs: build
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
permissions:
contents: write
steps:
+4 -3
View File
@@ -28,8 +28,6 @@ dist-ssr
.gitignore
# Build
src-tauri/gen
src-tauri/target
lightningbeam-core/target
daw-backend/target
target/
@@ -40,4 +38,7 @@ packaging/AppDir/
packaging/squashfs-root/
# Wrapper script (generated, not needed with static FFmpeg)
lightningbeam-ui/lightningbeam-editor/debian/
lightningbeam-ui/lightningbeam-editor/debian/
# Personal working notes (not version-controlled)
TODO.md
+2 -3
View File
@@ -52,7 +52,7 @@ Lightningbeam is a 2D multimedia editor combining vector animation, audio produc
Lightningbeam is undergoing a rewrite from a Tauri/JavaScript prototype to pure Rust. The original architecture hit IPC bandwidth limitations when streaming decoded video frames. The new Rust UI eliminates this bottleneck by handling all rendering natively.
**Current Status**: Active development on the `rust-ui` branch. Core UI, tools, and undo system are implemented. Audio integration in progress.
**Current Status**: Active development on the `main` branch. Core UI, tools, undo system, and audio integration are implemented.
## Technology Stack
@@ -486,8 +486,7 @@ lightningbeam-2/
│ ├── synth/ # Synthesizers
│ └── midi/ # MIDI handling
│
├── src-tauri/ # Legacy Tauri backend
├── src/ # Legacy JavaScript frontend
├── src/ # Legacy JavaScript frontend (browser-only)
├── CONTRIBUTING.md # Contributor guide
├── ARCHITECTURE.md # This file
├── README.md # Project overview
+484
View File
@@ -0,0 +1,484 @@
# `.beam` File Format Specification
**Status:** Normative.
**Container schema version:** `1` (`meta.schema_version`).
**Project payload version:** `1.0.0` (`BeamProject.version` / `meta.version`).
**Last updated:** 2026-06-21.
This document specifies the on-disk format of Lightningbeam `.beam` project files
precisely enough that an independent implementation can read and write them. It
describes the **current** format — a SQLite database — and the **legacy** format
(a ZIP archive) that current readers still accept and migrate.
> An earlier revision of this document described the ZIP container as the current
> format. That is now historical; see [§11 Legacy ZIP format](#11-legacy-zip-format-pre-sqlite).
## 1. Notational conventions
The key words **MUST**, **MUST NOT**, **SHOULD**, **SHOULD NOT**, and **MAY** are
to be interpreted as described in RFC 2119.
Byte sizes use binary units: `KiB = 1024`, `MiB = 1024²`, `GiB = 1024³`.
"UUID" means an RFC 4122 128-bit identifier. Unless stated otherwise, a UUID is
serialized in JSON as its canonical hyphenated lowercase string, and stored in
SQLite as its 16 raw bytes in **network (big-endian) byte order** — i.e. the byte
sequence returned by `Uuid::as_bytes`, most significant byte first.
## 2. Overview
A `.beam` file is a **single SQLite 3 database** (default rollback journal; no WAL,
no special pragmas) containing:
- one JSON document, `project.json`, holding all project state that is small and
structural (the document/scene tree, audio project, asset metadata); and
- zero or more **media** items (audio, raster frames, image assets, and derived
blobs such as waveforms and thumbnails), each either **packed** into the database
in chunks or **referenced** by an external file path.
The design goals are: a single beginner-friendly file (no project folder);
streaming reads of large media via SQLite blob I/O; transactional, crash-safe,
**in-place** saves that do not rewrite unchanged media; and inspectability with the
ordinary `sqlite3` CLI.
## 3. File identification
A reader MUST determine the container type from the first 16 bytes of the file:
- If the first 16 bytes equal the ASCII string `SQLite format 3\0` (i.e.
`53 51 4C 69 74 65 20 66 6F 72 6D 61 74 20 33 00`), the file is a SQLite
`.beam` and MUST be read per [§4](#4-container-the-sqlite-schema)–[§10](#10-load-semantics).
- Otherwise the file is treated as a [legacy ZIP `.beam`](#11-legacy-zip-format-pre-sqlite)
(ZIP local-file-header magic `50 4B 03 04`).
The `.beam` extension is used for both container types; the magic bytes — not the
extension — are authoritative.
## 4. Container: the SQLite schema
A conforming SQLite `.beam` MUST contain exactly these four tables (DDL as created;
column order and types are normative):
```sql
CREATE TABLE media (
id BLOB PRIMARY KEY, -- 16-byte UUID (big-endian)
kind INTEGER NOT NULL, -- MediaKind (§6.1)
codec TEXT NOT NULL, -- original codec/container, e.g. "flac","mp3","png"
storage INTEGER NOT NULL, -- MediaStorage (§6.2): 0=Packed, 1=Referenced
ext_path TEXT, -- external path, set iff storage=Referenced
total_len INTEGER NOT NULL DEFAULT 0, -- payload length in bytes (packed); 0 if referenced
channels INTEGER, -- audio: channel count (nullable)
sample_rate INTEGER, -- audio: sample rate in Hz (nullable)
width INTEGER, -- visual media: pixel width (nullable)
height INTEGER -- visual media: pixel height (nullable)
);
CREATE TABLE media_chunk (
id INTEGER PRIMARY KEY, -- rowid (used as the handle for blob streaming)
media_id BLOB NOT NULL, -- → media.id
chunk_index INTEGER NOT NULL, -- 0-based ordinal of this chunk
bytes BLOB NOT NULL, -- chunk payload
UNIQUE (media_id, chunk_index)
);
CREATE TABLE project_json (
id INTEGER PRIMARY KEY CHECK (id = 0), -- exactly one row, id 0
data TEXT NOT NULL -- the serialized BeamProject (§8)
);
CREATE TABLE meta (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
```
There is no foreign-key constraint between `media_chunk.media_id` and `media.id`;
referential integrity is maintained by the writer. A reader MUST NOT assume SQLite
enforces it.
### 4.1 The `meta` table
Defined keys (all values are strings):
| Key | Value | Meaning |
|------------------|--------------------|---------|
| `schema_version` | `"1"` | Container schema version. Set once at creation. |
| `version` | `"1.0.0"` | Project payload version (mirrors `project.json`'s `version`). |
| `created` | RFC 3339 timestamp | Creation time. Preserved across in-place re-saves. |
| `modified` | RFC 3339 timestamp | Last save time. Updated on every save. |
Writers MAY add additional keys; readers MUST ignore unknown keys.
### 4.2 Two independent version numbers
The format carries **two** version numbers with different compatibility rules:
- **`meta.schema_version`** (`INTEGER`, currently `1`) — versions the SQLite
container/table layout. A reader MUST reject a file whose `schema_version` is
**greater** than the highest it supports, and SHOULD accept any value less than
or equal to its maximum (forward-compatible for older files).
- **`BeamProject.version`** / `meta.version` (currently `"1.0.0"`) — versions the
`project.json` payload. The current implementation requires **exact string
equality** and rejects any other value. A future revision MAY relax this to a
semantic-version range; until then, writers MUST emit exactly `"1.0.0"` and
readers reject anything else.
These two numbers are orthogonal and MUST both be checked.
## 5. UUIDs and identity
Every media item is identified by a UUID. In `project.json` UUIDs appear as
canonical strings; in the `media`/`media_chunk` tables they appear as 16 raw
big-endian bytes (`media.id`, `media_chunk.media_id`). A reader MUST treat the two
representations as equal by their 128-bit value.
`media_chunk.id` is the SQLite rowid and is the handle a reader uses to open a blob
for streaming (`sqlite3_blob_open` on table `media_chunk`, column `bytes`). It has
no meaning beyond row identity and MUST NOT be relied upon to be stable across
re-saves.
## 6. Media model
### 6.1 `MediaKind` (`media.kind`)
| Value | Kind | `codec` examples | Notes |
|-------|---------------|------------------|-------|
| `0` | `Audio` | `flac`, `mp3`, `wav`, `ogg`, `opus`, `aac`, `m4a`, `alac`, `caf`, `aiff` | Source audio for a pool entry. |
| `1` | `Video` | `mp4`, `mov`, … | A video clip's container bytes, keyed by the clip id. Packed under the large-media policy (referenced above 2 GiB unless `Pack`). Frames **and** the embedded audio stream are decoded directly from this blob. |
| `2` | `Raster` | `png` | Full-resolution pixels of a raster keyframe (PNG-encoded RGBA). |
| `3` | `ImageAsset` | `png`, `jpg`, … | An imported image asset's original bytes. |
| `4` | `Waveform` | `lbwf` | Precomputed waveform LOD pyramid for an audio item. Opaque blob owned by `daw_backend::audio::waveform_pyramid`. |
| `5` | `Thumbnail` | `lbtn` | A pack of precomputed video thumbnails for a clip. Opaque blob owned by the editor. |
| `6` | `RasterProxy` | `png` | Low-resolution PNG proxy of a raster keyframe, shown during cold scrubs while full-res pages in. |
A reader MUST reject a `kind` value it does not recognise only if it needs that
item; unknown kinds MAY otherwise be ignored.
### 6.2 `MediaStorage` (`media.storage`)
| Value | Storage | Bytes location | `total_len` | `ext_path` |
|-------|--------------|----------------|-------------|------------|
| `0` | `Packed` | `media_chunk` rows in this DB | payload length | `NULL` |
| `1` | `Referenced` | external file at `ext_path` | `0` | path string |
### 6.3 Packed storage and chunking
Packed bytes are split into chunks of **`CHUNK_SIZE = 4 MiB`** and stored one chunk
per `media_chunk` row, ordered by `chunk_index` ascending starting at `0`. The
writer MUST:
1. set `media.total_len` to the exact total byte length of the payload;
2. write `ceil(total_len / CHUNK_SIZE)` chunk rows (zero rows iff `total_len == 0`);
3. make every chunk exactly `CHUNK_SIZE` bytes **except the last**, which holds the
remainder `total_len − (n−1)·CHUNK_SIZE`.
Because chunk lengths are fully determined by `total_len` and `CHUNK_SIZE`, a reader
performing random access MUST compute, for a byte offset `pos < total_len`:
```
chunk_index = pos / CHUNK_SIZE
offset_in_chunk = pos % CHUNK_SIZE
chunk_len = min(CHUNK_SIZE, total_len − chunk_index·CHUNK_SIZE)
```
and read from the row with that `chunk_index`. A reader MAY stream the whole payload
by concatenating chunk `bytes` in `chunk_index` order. The chunk size MAY differ in
files written by other tools; a robust reader SHOULD derive chunk boundaries from
actual row lengths rather than assuming 4 MiB. (The reference reader assumes uniform
`CHUNK_SIZE` except for the last chunk; writers targeting it MUST keep chunks
uniform.)
### 6.4 Referenced storage
A referenced item stores only `ext_path` (with `total_len = 0` and no chunk rows).
The path is resolved relative to the directory containing the `.beam` file unless it
is absolute. If the file is absent at load time, the item is reported as a *missing
file* ([§10.4](#104-missing-referenced-files)) — this is non-fatal.
## 7. Derived media IDs
Three media kinds are keyed by UUIDs **derived** from another id rather than by an
independent random UUID. A reader/writer MUST compute them exactly as follows
(`from_u128` constructs a UUID from a 128-bit big-endian integer):
| Kind | Derived from | Formula |
|---------------|---------------------|---------|
| `Waveform` | audio pool **index** `i` (`usize`) | `from_u128((0x4C42_5746 << 96) \| (i as u128))` — high 32 bits = `0x4C425746` ("LBWF"), low 96 bits = the pool index. |
| `Thumbnail` | video clip UUID `c` | `from_u128(c.as_u128() ^ 0x4C42_544E_4C42_544E_4C42_544E_4C42_544E)` — full-width XOR with "LBTN" repeated 4×. |
| `RasterProxy` | raster keyframe UUID `k` | `from_u128(k.as_u128() ^ 0x4C42_5058_4C42_5058_4C42_5058_4C42_5058)` — full-width XOR with "LBPX" repeated 4×. |
The full-resolution `Raster` row is keyed by the keyframe's **own** UUID (no
derivation); an `ImageAsset` row is keyed by the asset's own UUID; a packed `Audio`
row is keyed by the pool entry's `media_id`.
> Note the asymmetry: the waveform id ORs the pool index into the high bits, while
> thumbnail/proxy ids XOR a 128-bit sentinel with a source UUID. This is intentional
> (waveforms are keyed by *index*, not by a UUID) but is a sharp edge for
> implementers.
## 8. `project.json`
`project_json.data` is a UTF-8 JSON document: the serde serialization of a
`BeamProject`. This section specifies the top-level structure and the entities a
reader needs to resolve media; the deep UI/scene tree is defined by the
corresponding Rust types (serde field names match struct field names unless a
`#[serde(rename)]` is noted) and is intentionally **not** enumerated exhaustively
here.
### 8.1 `BeamProject` (root)
| Field | Type | Notes |
|-----------------|---------------------------|-------|
| `version` | string | MUST be `"1.0.0"`. |
| `created` | string (RFC 3339) | |
| `modified` | string (RFC 3339) | |
| `ui_state` | `Document` | The scene/document tree (§8.2). |
| `audio_backend` | `SerializedAudioBackend` | Audio engine state (§8.3). |
### 8.2 `Document` (top-level fields)
Collections that carry media linkage are **bold**:
- `id: Uuid`, `name: string`, `background_color`, `width: f64`, `height: f64`,
`framerate: f64`, `duration: f64`
- `time_signature`, `master_layer`, `timeline_mode` — all `#[serde(default)]`
- `root: GraphicsObject` — the layer tree; raster keyframes live here and inside
nested group/clip layers
- **`image_assets: map<Uuid, ImageAsset>`** — keyed by asset UUID (= the media id)
- **`video_clips: map<Uuid, VideoClip>`** — when `VideoClip.media_id` is set the
video is packed (a `Video` media row at the clip id); otherwise `file_path` points
at the external video file. Thumbnails are derived media (§7)
- `vector_clips`, `audio_clips`, `instance_groups`, `effect_definitions`,
`script_definitions`, the various `*_folders` asset trees — structural, no direct
media-row linkage
- `ui_layout`, `ui_layout_base` — `Option`, skipped when `None`
- `current_time`, `layer_to_clip_map` — `#[serde(skip)]` (not persisted)
`RasterKeyframe` (within the layer tree) has `id: Uuid` (= its full-res `Raster`
media id and the seed for its `RasterProxy` id), `time`, `width`, `height`,
`tween_after`, and `stroke_log`. Pixel buffers are `#[serde(skip)]` and faulted in
from media rows. (The legacy ZIP entry path `media/raster/<id>.png` is derived from
`id`; older files may also carry a now-ignored `media_path` field.)
### 8.3 `SerializedAudioBackend`
| Field | Type | Notes |
|----------------------|---------------------|-------|
| `sample_rate` | `u32` | The project's system sample rate (mirrors `AudioProject.sample_rate`). Per-file rates are on each `AudioPoolEntry.sample_rate`. |
| `project` | `AudioProject` | Tracks + MIDI clip pool (§8.4). |
| `audio_pool_entries` | `[AudioPoolEntry]` | Audio source registry (§8.5). |
| `layer_to_track_map` | `map<Uuid, u32>` | UI layer UUID → engine track id. `#[serde(default)]`. |
### 8.4 `AudioProject` (top-level fields)
`tracks: map<TrackId, TrackNode>`, `root_tracks: [TrackId]`, `next_track_id`,
`sample_rate: u32`, `midi_clip_pool`, `next_midi_clip_instance_id`. DSP graphs are
not serialized; they are rebuilt on load.
### 8.5 `AudioPoolEntry` (media linkage)
| Field | Type | Role |
|-----------------|----------------------------|------|
| `pool_index` | `usize` | Stable index; seeds the `Waveform` media id (§7). |
| `name` | string | |
| `media_id` | `Option<string>` (UUID) | Set ⇔ audio bytes are **packed** in this DB under that id. `#[serde(default, skip_serializing_if=None)]`. |
| `relative_path` | `Option<string>` | Set ⇔ audio is **referenced** (external file) or missing. |
| `embedded_data` | `Option<EmbeddedAudioData>`| Legacy/inline: `{ data_base64, format }`. Used when bytes are neither packed nor referenced. |
| `sample_rate` | `u32` | Authoritative sample rate. |
| `channels` | `u32` | Channel count. |
| `duration` | `f64` | Seconds. |
| `is_video_audio`| `bool` | If set, the entry is the audio track of a video. Referenced when the video is external; when the video is **packed**, `media_id` points at the video's `Video` row and the audio streams from that same blob. `#[serde(default, skip_if=false)]`. |
| `waveform_blob` | (transient) | `#[serde(skip)]`; carries waveform bytes in memory only. |
### 8.6 Media linkage summary
| Media kind | Referenced from `project.json` by | Media-row id |
|--------------------|-----------------------------------|--------------|
| Audio (packed) | `AudioPoolEntry.media_id` | that UUID |
| Audio (referenced) | `AudioPoolEntry.relative_path` | — (external) |
| Audio (embedded) | `AudioPoolEntry.embedded_data` | — (inline base64) |
| Raster (full) | `RasterKeyframe.id` | that UUID |
| Raster proxy | derived from `RasterKeyframe.id` | §7 |
| Image asset | `Document.image_assets` key / `ImageAsset.id` | that UUID |
| Video (packed) | `VideoClip.media_id` (= clip id) | that UUID |
| Video (referenced) | `VideoClip.file_path` | — (external) |
| Video thumbnails | derived from `video_clips` key | §7 |
| Waveform | derived from `AudioPoolEntry.pool_index` | §7 |
## 9. Save semantics
A conforming writer MUST perform all media, `project.json`, and `meta` writes for a
save inside **one** SQLite transaction.
### 9.1 In-place vs. create
- If the target path exists **and** is already a SQLite `.beam`, the writer opens it
and writes in place. Unchanged packed media MUST NOT be rewritten (§9.3); this is
the central performance/crash-safety property, and writers MUST NOT use a
copy-to-temp-and-rename flow for in-place saves.
- Otherwise (new file, or migrating a legacy ZIP), the writer creates a fresh DB at
`<path>.beam.tmp`, writes everything, commits, then atomically `rename`s it over
the target.
### 9.2 Order of operations within the transaction
1. Audio pool entries → `Audio` (+ `Waveform`) media rows.
2. Raster keyframes → `Raster` (+ `RasterProxy`) media rows.
3. Video thumbnail packs → `Thumbnail` media rows.
4. Video clips → `Video` media rows (packed/referenced per the large-media policy);
when a clip is packed, its linked video-audio pool entry's `media_id` is set to
the clip's `Video` row so the audio streams from the same blob.
5. Image assets → `ImageAsset` media rows.
6. **Garbage-collect**: delete every `media` row (and its chunks) whose id is **not**
in the set of live ids accumulated in steps 1–5.
7. Write `project.json` and the `meta` keys (`version`, `created`, `modified`).
8. Commit; then (create path only) rename the temp file over the target.
### 9.3 Packed vs. referenced decision (audio)
For each audio pool entry, in order:
- If a packed row for its `media_id` already exists in the archive, keep it untouched
(do not rewrite the bytes) and keep the entry packed.
- Else if its external file resolves and exists: store **referenced** if the entry is
video audio, *or* the file is `≥ LARGE_MEDIA_THRESHOLD` (2 GiB) and the large-media
mode is not `Pack`; otherwise **pack** it (streamed from disk chunk-by-chunk).
- Else if it has `embedded_data`: base64-decode and pack it.
- Else: leave its references as-is (it will be reported missing on load).
Raster, image, and thumbnail media follow the same "write if present, else keep the
existing row" rule so that paged-out content survives a save without being held in
memory.
## 10. Load semantics
### 10.1 Dispatch and version checks
Open the file, read `project.json`, parse `BeamProject`. Reject unless
`version == "1.0.0"` (§4.2). The container's `schema_version` is verified on open
(`≤` the reader's maximum).
### 10.2 Audio resolution
Per pool entry with a `media_id`: look up the media row. If its `codec` is a
**streamable** audio codec (`mp3`, `flac`, `ogg`/`oga`, `wav`/`wave`, `aiff`/`aif`,
`aac`, `m4a`, `opus`, `alac`, `caf`), the bytes are **streamed lazily** from the blob
at playback time (the entry keeps `media_id`, with `embedded_data`/`path` cleared).
Otherwise the bytes are read eagerly into `embedded_data`. A precomputed `Waveform`
blob, if present, is read into the entry.
### 10.3 Visual media paging
- **Raster** full-res pixels are **not** eagerly decoded; each keyframe is flagged
for fault-in and its pixels are paged from its `Raster` row on demand. Its
`RasterProxy` PNG **is** read and decoded eagerly so cold scrubs show a low-res
frame immediately.
- **Image assets** are **not** eagerly read; they page from their `ImageAsset` rows
on demand.
- **Thumbnail** packs are read eagerly per video clip.
### 10.4 Missing referenced files
A pool entry that is neither packed nor embedded, whose `relative_path` resolves to a
non-existent file, MUST be reported as a missing file (non-fatal). The host
application prompts the user to relocate it.
## 11. Legacy ZIP format (pre-SQLite)
Files whose magic is not `SQLite format 3\0` are read as a ZIP archive with this
internal layout:
- `project.json` — the same serialized `BeamProject` (`version` must be `"1.0.0"`).
- `media/audio/<name>.<ext>` — audio source files. The codec is taken from the
extension. **FLAC entries are decoded to PCM `f32` and re-encoded in memory as
IEEE-float WAV (WAV format tag 3)** before being base64-embedded; other formats are
embedded as-is. The entry's `relative_path` is cleared after extraction.
- `media/raster/<uuid>.png` — raster keyframe pixels, named `media/raster/<id>.png`
after the keyframe's `id`.
A reader MUST NOT modify a legacy ZIP on open; it loads into memory only. **The next
save migrates the project to SQLite** (the save sees a non-SQLite target, so it takes
the create-and-rename path and writes a fresh `.beam` database).
> Known limitation of the legacy reader: raster pixels are loaded only for
> **top-level** layers; raster keyframes nested inside groups/clips are not populated
> from a ZIP. The SQLite path recurses correctly. Re-saving to SQLite is the remedy.
## 12. Large-media policy
- `LARGE_MEDIA_THRESHOLD = 2 GiB`. Files at or above it trigger the packed-vs-
referenced decision below; smaller files are always packed (unless video audio,
which is always referenced).
- `LargeMediaMode` ∈ `{ Ask, Pack, Reference }`:
- `Pack` — pack large files into the database.
- `Reference` — store large files by external path.
- `Ask` (default) — prompt the user on the first large import, then persist their
choice; treated as `Reference` at save time until answered.
- **The chosen mode is an application preference, not part of the `.beam` file.** It
is stored in the editor's `config.json` (`AppConfig.large_media_default`) under the
platform config directory, not in the project. Readers/writers of the format need
not consult it except to drive the packed/referenced save decision.
## 13. Conformance summary
A conforming **reader** MUST:
1. dispatch on the 16-byte magic (§3);
2. reject `schema_version` greater than supported and `version != "1.0.0"` (§4.2);
3. resolve packed media via `media`/`media_chunk` (§6.3) and referenced media
relative to the file (§6.4), reporting missing referenced files non-fatally;
4. compute derived media ids exactly as in §7.
A conforming **writer** MUST:
1. produce the four tables of §4 with `schema_version="1"` and `version="1.0.0"`;
2. store UUIDs as 16 big-endian bytes and chunk packed media at a uniform size with a
remainder final chunk, setting `total_len` correctly (§6.3);
3. perform each save in a single transaction and garbage-collect orphaned media (§9),
and prefer in-place writes that do not rewrite unchanged packed media.
## 14. Security considerations
- **Path traversal:** referenced media and legacy ZIP entries carry filesystem paths.
Readers SHOULD resolve relative paths against the project directory and SHOULD
reject or sandbox paths that escape it (`..`, absolute paths) when opening
untrusted files.
- **Resource limits:** `project.json` and packed blobs are attacker-controllable in
an untrusted file. Readers SHOULD bound JSON size and avoid loading entire large
blobs into memory (stream via §6.3) to resist memory-exhaustion.
- **Decoder safety:** audio/image bytes are handed to media decoders (Symphonia,
image, FFmpeg); keep those dependencies current, as they parse untrusted input.
- **Legacy ZIP bombs:** the ZIP path SHOULD enforce sane decompression-ratio/size
limits.
## 15. Non-normative notes / known quirks
These reflect the current reference implementation and are flagged for implementers
and future spec revisions:
- The project `version` check is exact-match with no compatibility window; a future
revision should define semantic-version tolerance before bumping it.
(Earlier revisions of this section flagged a hardcoded save sample rate, a vestigial
`RasterKeyframe.media_path` field, and unused `SaveSettings` fields; these have since
been fixed/removed.)
## 16. Inspecting a `.beam` file
Because the container is plain SQLite, any `.beam` (SQLite variant) can be inspected
with standard tooling, e.g.:
```sh
sqlite3 project.beam '.tables'
sqlite3 project.beam 'SELECT key,value FROM meta;'
sqlite3 project.beam 'SELECT hex(id),kind,codec,storage,total_len FROM media;'
sqlite3 project.beam 'SELECT data FROM project_json;' | jq .
```
## 17. References
- Container: `lightningbeam-ui/lightningbeam-core/src/beam_archive.rs`
- Save/load orchestration & `BeamProject`: `lightningbeam-ui/lightningbeam-core/src/file_io.rs`
- Audio pool entry: `daw-backend/src/audio/pool.rs`
- Document / scene tree: `lightningbeam-ui/lightningbeam-core/src/document.rs`
- RFC 2119 (requirement keywords), RFC 4122 (UUID), RFC 3339 (timestamps)
+7 -9
View File
@@ -122,25 +122,23 @@ lightningbeam-2/
│ │ ├── track.rs # Track management
│ │ └── project.rs # Project state
│ └── effects/ # Audio effects
├── src-tauri/ # Legacy Tauri backend
└── src/ # Legacy JavaScript frontend
└── src/ # Legacy JavaScript frontend (browser-only)
```
## Making Changes
### Branching Strategy
- `main` - Stable branch
- `rust-ui` - Active development branch for Rust UI rewrite
- Feature branches - Create from `rust-ui` for new features
- `main` - Main development branch
- Feature branches - Create from `main` for new features
### Before You Start
1. Check existing issues or create a new one to discuss your change
2. Make sure you're on the latest `rust-ui` branch:
2. Make sure you're on the latest `main` branch:
```bash
git checkout rust-ui
git pull origin rust-ui
git checkout main
git pull origin main
```
3. Create a feature branch:
```bash
@@ -241,7 +239,7 @@ this solution.
### Pull Request Process
1. Push your branch to GitHub or Gitea
2. Open a pull request against `rust-ui` branch
2. Open a pull request against `main` branch
- GitHub: https://github.com/skykooler/lightningbeam
- Gitea: https://git.skyler.io/skyler/lightningbeam
3. Provide a clear description of:
+142
View File
@@ -1,3 +1,145 @@
# 1.0.10-alpha:
Changes:
- Cycle recording: highlight a range on the timeline ruler (the cycle strip, shown when looping is armed) and the transport loops it. Recording round the loop turns each pass into a separate take you can choose between afterwards, and recording again over the same region adds more takes rather than stacking a second clip on top. Starting playback from outside the region jumps to its start
- Takes: a "Take N/M" badge on the clip picks which take plays. Splitting a clip lets each half play a different take, so you can comp a part together from the best bits of several passes. Right-click a clip to delete the take that's playing or to delete all the unused ones; double-click a take in the list to rename it
- MIDI cycle recording can either merge every pass into one clip (the default — earlier passes play back as you record, so you can layer a hi-hat over a kick) or keep each pass as a separate take, like audio does. Set it in Preferences → Audio
- Painting: every colour-using tool (brush, paint bucket, eyedropper) now shares one Foreground/Background swatch row, and the eyedropper has an explicit toggle for which of the two it fills
- Painting: the effect brushes (dodge/burn, sponge, blur, smudge, clone stamp, healing brush, pattern stamp) were stuck on a single fixed brush shape. They now each have their own size, strength, hardness and spacing, and can use any brush from the library
- Tablet: stylus barrel buttons now work, with actions you can bind in Preferences (Pan, Eyedropper, or Eraser). Middle-mouse panning added too
- Timeline: raster and text layers get an opacity slider; each layer row now shows only the controls that mean anything for it (volume for audio, opacity for raster/text, both for vector and video), and layers gain a visibility (eye) toggle
- The stage gains undo/redo buttons, sized for touch and tablet use
Bugfixes:
- Splitting an audio clip made it play back at the wrong length (a clip split at 1 second cut off after half a second at 120 BPM)
- Trimmed MIDI clips were the wrong length on the timeline at any tempo other than 60 BPM
- The paint bucket always filled with the background colour, whatever the brush was set to
- Where an eyedropper sample landed (foreground or background) depended on which colour picker you had opened last
- Stylus barrel buttons were silently ignored on Wayland
- The opacity slider on a raster layer actually changed its volume, which means nothing on a raster layer
- Tool cursors lagged behind the pointer while drawing; they're now drawn by the system rather than into the canvas
- Colour picker popups wouldn't close when you dragged on the stage, so drawing left one hanging open, and clicking inside a picker's own hue slider closed it
- The toolbar could not be scrolled when the pane was too short to show every tool
# 1.0.9-alpha:
Bugfixes:
- Fix audio recording placement: a second recording landed at the wrong spot (and clicking/dragging clips was similarly off) at any tempo other than 60 BPM — recordings now start exactly at the playhead at any tempo
- While recording a second audio clip, the live bar showed as a zero-length clip until you stopped; it now grows as you record
- MIDI clips were drawn with the wrong length (their end grew too fast) at tempos other than 120 BPM
- Recording a MIDI clip didn't mark the project as having unsaved changes, so closing or starting a new file didn't prompt to save
- Audio and MIDI recording can now be undone (and redone)
# 1.0.8-alpha:
Changes:
- Mobile/touch UI (experimental, testing only — not built or packaged for mobile yet; enabled on desktop with the LB_MOBILE_UI environment variable): work-in-progress phone-friendly interface with a vertical sliding-window pane stack you drag to reveal panes, a new-file intent picker, a selection inspector sheet, a keyboard-primary music surface, a Focus/Patch node editor, long-press context menus, a command palette, and landscape/orientation support
- Text layers: add and edit text with a chosen font; non-bundled fonts are embedded in the project so it renders on machines that lack them
- Animated GIF export (parallel palette encoding)
- Audio tag metadata (title, artist, album, genre, year, track, comment) is written into exports — ID3v2 for MP3, iTunes/MP4 atoms for AAC, Vorbis comments for FLAC, RIFF INFO for WAV — with sensible defaults (year, artist/album remembered between exports)
- Lossy WebP image export, so the quality control now actually applies
- SVG export now includes text layers, as real font-independent glyph outlines
- Crash recovery: the editor autosaves your work to a recovery file in the background and offers to restore it after an unclean shutdown
- Prompt to save unsaved changes before starting a new file, opening another, or quitting
- Faster saves on painting projects: unchanged raster frames are no longer re-encoded every save
Bugfixes:
- FLAC export previously wrote a WAV file with a .flac extension; it now encodes real (compressed) FLAC
- ProRes 422 export always failed; it now encodes 10-bit 4:2:2 correctly
- Fix VP8 video export with audio (muxed into WebM instead of an incompatible container)
- The WebP "Quality" slider had no effect
- Starting a new file now fully resets the audio engine, so instruments and voices from the previous project no longer linger
- Fix oscillator/synth phase drift over long playback
# 1.0.7-alpha:
Changes:
- HDR video support: PQ/HLG/BT.2020 video is now read correctly (decoded to scene-linear), with a per-document output mode (clip vs highlight rolloff) and 10-bit HDR export (HEVC Main10, PQ or HLG)
- Hardware-accelerated video decode (VAAPI) for both playback and export, including a GPU NV12 preview path; the editor now runs on a shared VAAPI-capable GPU device so decode → composite → encode stay GPU-resident
- SVG import and export for vector layers: export the current frame to .svg, and import .svg as a new vector layer (Ctrl+I)
- Export fit modes: choose Stretch, Letterbox, or Crop when the export resolution's aspect ratio differs from the document (video and image export)
- Videos imported directly and dragged in from the asset library now use the same placement, so they no longer end up with different aspect ratios
- Resizing the document now leaves raster layers untouched; the Info Panel shows the active raster layer's size and a "Layer to document size" button (scale or expand/crop)
- The active raster layer now shows a dashed outline on the canvas
- H.264 export gained a color-range option (Limited/TV or Full/PC)
- Hide/Show Layer now works
Bugfixes:
- Fix sped-up and jerky 4K video playback (frame-index frame cache + request-based seeking)
- Fix washed-out HDR/10-bit video (propagate stream color tags to hardware frames, P010 import)
- Fix the final frame(s) of a clip occasionally failing to render at the end of the stream
- Fix the CPU export color path producing shifted colors on unusual resolutions (BT.709 + honor the chosen range)
- Fix fills occasionally vanishing after a paint-bucket or lasso cut
- Fix silent gaps in exported audio
- Fix black video thumbnails and decoder thrashing
- Fix file-descriptor and GPU-memory leaks on hardware-import error paths
- SVG export now omits hidden layers; SVG import respects gradient opacity
- Fix the macOS/Windows build (hardware export is Linux-only)
# 1.0.6-alpha:
Changes:
- Hardware-accelerated H.264 video export: each frame is rendered and encoded on the GPU (zero-copy VAAPI), roughly 2x faster, with automatic fallback to software encoding when hardware acceleration isn't available (Linux, Intel/AMD only for now)
- Video export now runs on a background thread, so the UI stays responsive during export and edits made while exporting no longer affect the output
- Grouped and nested video clips now composite on the GPU path
- Video is now packed into and streamed from the .beam project container
Bugfixes:
- Fix an export hang when a video's audio track is shorter than the video
- Fix a sample key-range overlap bug in instruments
# 1.0.5-alpha:
Changes:
- Add shape tweens (morph vector geometry between keyframes)
- Add motion tweens for groups and movie clips
- Group geometry and Convert to Movie Clip now work on DCEL vector shapes
- Region/lasso select now cuts the shape and feeds the normal selection, so Group, Convert, Delete and Properties all work from a lasso (hold shift to add to the selection)
- Clip instances now draw on top of a layer's loose shapes
- Add onion skinning for raster and vector layers, with tinted ghosts and settings in the Info Panel
- Images can now fill vector shapes (None / Solid / Gradient / Image fill types)
- Imported images can be placed on the canvas
- Add a raster keyframe timeline UI with explicit keyframe creation; click a keyframe diamond to snap the playhead to it
- Stream audio, video and images to and from the project file instead of holding them in memory, supporting arbitrarily long media
- Persist (and resume) waveforms and video thumbnails in the project file
- Use low-res proxies for fast cold scrubbing of raster frames
- Bound memory use for raster pixels, GPU textures, video frames and decoded images on large projects
- Video export is roughly 4x faster
- Downmix surround video audio to stereo
Bugfixes:
- Fix video export resolution scaling and a post-export UI hang
- Fix gamma handling and improve brush canvas performance
- Fix a save crash on projects with zero or sparse audio
- Fix raster strokes vanishing when committed
- Fix image fill mapping (anchor to the fill's bounding box)
- Fix video thumbnail strip bugs
# 1.0.4-alpha:
Changes:
- Beats are now the canonical time representation (replacing seconds)
- Tempo can now be non-constant (variable BPM)
- All events now have time references in seconds, measures/beats, and frames
- Add piano roll note snapping
- Snap to beats in measures mode
- Add velocity and modulation editing
- Add pitch bend support
- Add automation inputs for audio graphs
- Add automatable volume and pan controls to default instruments
- Add count-in and metronome
- Add drawing tablet input support
- Set default timeline mode based on activity
- Tweaked automation lane appearance
- Double CPU rendering performance by switching to tiny-skia
Bugfixes:
- Fix MIDI track recording previews
- Fix timeline elements not updating on BPM changes
# 1.0.3-alpha:
Changes:
- Add gradient support to vector graphics
- Add "frames" timeline mode
- Reduce CPU usage at idle
- Allow group tracks' audio node graphs to be edited
Bugfixes:
- Support Vello CPU fallback on systems with older GPUs
# 1.0.2-alpha:
Changes:
- All vector shapes on a layer go into a unified shape rather than separate shapes
+14 -6
View File
@@ -48,7 +48,7 @@ A free and open-source 2D multimedia editor combining vector animation, audio pr
## Project Status
Lightningbeam is under active development on the `rust-ui` branch. The project has been rewritten from a Tauri/JavaScript prototype to a pure Rust application to eliminate IPC bottlenecks and achieve better performance for real-time video and audio processing.
Lightningbeam is developed on the `main` branch. The project has been rewritten from a Tauri/JavaScript prototype to a pure Rust application to eliminate IPC bottlenecks and achieve better performance for real-time video and audio processing.
**Current Status:**
- ✅ Core UI panes (Stage, Timeline, Asset Library, Info Panel, Toolbar)
@@ -58,13 +58,21 @@ Lightningbeam is under active development on the `rust-ui` branch. The project h
- ✅ Audio engine with node graph processing
- ✅ GPU waveform rendering with mipmaps
- ✅ Video decoding integration
- 🚧 Export system (in progress)
- 🚧 Node editor UI (planned)
- 🚧 Piano roll editor (planned)
- ✅ Export system (video, image, audio, animated GIF, SVG)
- ✅ Node editor UI
- 🚧 Piano roll editor (in progress)
## Getting Started
### Prerequisites
### Download a prebuilt release
If you don't want to build from source, prebuilt binaries for each release are on the
[GitHub releases page](https://github.com/skykooler/lightningbeam/releases). Download the build for
your platform and run it directly.
### Building from source
#### Prerequisites
- Rust (stable toolchain via [rustup](https://rustup.rs/))
- System dependencies:
@@ -74,7 +82,7 @@ Lightningbeam is under active development on the `rust-ui` branch. The project h
See [docs/BUILDING.md](docs/BUILDING.md) for detailed setup instructions.
### Building and Running
#### Building and Running
```bash
# Clone the repository
+701
View File
@@ -0,0 +1,701 @@
#!/usr/bin/env python3
"""
Lightningbeam .beam File Inspector
A command-line tool to inspect .beam project files.
"""
import argparse
import json
import sqlite3
import sys
import uuid as uuidlib
import zipfile
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, List, Optional
# First 16 bytes of any SQLite 3 database.
SQLITE_MAGIC = b"SQLite format 3\x00"
# media.kind values (see BEAM_FILE_FORMAT.md §6.1).
MEDIA_KIND_NAMES = {
0: "Audio", 1: "Video", 2: "Raster", 3: "ImageAsset",
4: "Waveform", 5: "Thumbnail", 6: "RasterProxy",
}
# media.storage values (§6.2).
MEDIA_STORAGE_NAMES = {0: "Packed", 1: "Referenced"}
def _is_sqlite(path: Path) -> bool:
"""True if the file begins with the SQLite 3 header magic."""
try:
with open(path, "rb") as f:
return f.read(16) == SQLITE_MAGIC
except OSError:
return False
def _human_size(n: int) -> str:
f = float(n)
for unit in ("B", "KiB", "MiB", "GiB", "TiB"):
if f < 1024 or unit == "TiB":
return f"{f:.0f} {unit}" if unit == "B" else f"{f:.1f} {unit}"
f /= 1024
return f"{n} B"
class BeamInspector:
"""Inspector for .beam project files (SQLite container, or legacy ZIP)."""
def __init__(self, beam_file: Path):
self.beam_file = beam_file
self.project_data: Optional[Dict[str, Any]] = None
# SQLite (current) vs ZIP (legacy) container.
self.is_sqlite = _is_sqlite(beam_file)
# Populated for SQLite files by load():
self.meta: Dict[str, str] = {}
self.media: List[Dict[str, Any]] = [] # rows from the media table
self.media_by_id: Dict[str, Dict[str, Any]] = {} # uuid-string -> row
def _connect(self) -> sqlite3.Connection:
"""Open the SQLite container read-only."""
uri = self.beam_file.resolve().as_uri() + "?mode=ro"
return sqlite3.connect(uri, uri=True)
def load(self) -> bool:
"""Load and parse the .beam file (container-agnostic)."""
try:
if self.is_sqlite:
return self._load_sqlite()
return self._load_zip()
except Exception as e:
print(f"Error loading .beam file: {e}", file=sys.stderr)
return False
def _load_zip(self) -> bool:
with zipfile.ZipFile(self.beam_file, 'r') as zip_ref:
with zip_ref.open('project.json') as f:
self.project_data = json.load(f)
return True
def _load_sqlite(self) -> bool:
con = self._connect()
try:
cur = con.cursor()
row = cur.execute("SELECT data FROM project_json WHERE id = 0").fetchone()
if not row:
raise ValueError("archive has no project.json row")
self.project_data = json.loads(row[0])
self.meta = {k: v for (k, v) in cur.execute("SELECT key, value FROM meta")}
for (idb, kind, codec, storage, ext_path, total_len,
channels, sample_rate, width, height) in cur.execute(
"SELECT id, kind, codec, storage, ext_path, total_len, "
"channels, sample_rate, width, height FROM media"
):
uid = str(uuidlib.UUID(bytes=bytes(idb)))
info = {
"uuid": uid,
"kind": kind,
"codec": codec,
"storage": storage,
"ext_path": ext_path,
"total_len": total_len or 0,
"channels": channels,
"sample_rate": sample_rate,
"width": width,
"height": height,
}
self.media.append(info)
self.media_by_id[uid] = info
finally:
con.close()
return True
def show_info(self):
"""Display basic project information."""
if not self.project_data:
return
print("=" * 60)
print("PROJECT INFORMATION")
print("=" * 60)
print(f"Container: {'SQLite' if self.is_sqlite else 'Legacy ZIP'}")
if self.is_sqlite:
print(f"Schema Ver: {self.meta.get('schema_version', 'Unknown')}")
print(f"Version: {self.project_data.get('version', 'Unknown')}")
print(f"Created: {self.project_data.get('created', 'Unknown')}")
print(f"Modified: {self.project_data.get('modified', 'Unknown')}")
ui_state = self.project_data.get('ui_state', {})
print(f"\nProject Name: {ui_state.get('name', 'Unnamed')}")
print(f"ID: {ui_state.get('id', 'Unknown')}")
print(f"Dimensions: {ui_state.get('width', 0):.0f} x {ui_state.get('height', 0):.0f}")
print(f"Framerate: {ui_state.get('framerate', 0):.1f} fps")
print(f"Duration: {ui_state.get('duration', 0):.2f} seconds")
bg = ui_state.get('background_color', {})
print(f"Background: rgba({bg.get('r', 0)}, {bg.get('g', 0)}, {bg.get('b', 0)}, {bg.get('a', 255)})")
audio_backend = self.project_data.get('audio_backend', {})
print(f"\nSample Rate: {audio_backend.get('sample_rate', 0)} Hz")
def show_clips(self):
"""Display clips information."""
if not self.project_data:
return
ui_state = self.project_data.get('ui_state', {})
vector_clips = ui_state.get('vector_clips', {})
video_clips = ui_state.get('video_clips', {})
audio_clips = ui_state.get('audio_clips', {})
print("\n" + "=" * 60)
print("CLIPS")
print("=" * 60)
print(f"Vector Clips: {len(vector_clips)}")
print(f"Video Clips: {len(video_clips)}")
print(f"Audio Clips: {len(audio_clips)}")
if vector_clips:
print("\nVector Clips:")
for clip_id, clip in vector_clips.items():
print(f" - {clip.get('name', 'Unnamed')} (ID: {clip_id[:8]}...)")
if video_clips:
print("\nVideo Clips:")
for clip_id, clip in video_clips.items():
print(f" - {clip.get('name', 'Unnamed')} (ID: {clip_id[:8]}...)")
if audio_clips:
print("\nAudio Clips:")
for clip_id, clip in audio_clips.items():
print(f" - {clip.get('name', 'Unnamed')} (ID: {clip_id[:8]}...)")
def show_layers(self):
"""Display layer hierarchy."""
if not self.project_data:
return
ui_state = self.project_data.get('ui_state', {})
root = ui_state.get('root', {})
print("\n" + "=" * 60)
print("LAYER HIERARCHY")
print("=" * 60)
def print_layer(layer: Dict[str, Any], indent: int = 0):
# Handle case where layer might not be a dictionary
if not isinstance(layer, dict):
prefix = " " * indent
print(f"{prefix}- ERROR: Layer is {type(layer).__name__}, not a dict: {repr(layer)[:50]}")
return
layer_type = layer.get('type', 'Unknown')
layer_name = layer.get('name', 'Unnamed')
layer_id = layer.get('id', 'Unknown')
prefix = " " * indent
# Handle layer_id that might not be a string
id_str = layer_id[:8] + "..." if isinstance(layer_id, str) and len(layer_id) > 8 else str(layer_id)
print(f"{prefix}- [{layer_type}] {layer_name} (ID: {id_str})")
# Recursively print children
children = layer.get('children', [])
for child in children:
print_layer(child, indent + 1)
print_layer(root)
def show_tracks(self):
"""Display audio tracks information."""
if not self.project_data:
return
audio_backend = self.project_data.get('audio_backend', {})
project = audio_backend.get('project', {})
tracks_dict = project.get('tracks', {})
root_tracks = project.get('root_tracks', [])
master_track = project.get('master_track', {})
print("\n" + "=" * 60)
print("AUDIO TRACKS")
print("=" * 60)
print(f"Total Tracks: {len(tracks_dict)}")
# Iterate through root_tracks in order
for track_id in root_tracks:
track_id_str = str(track_id)
if track_id_str not in tracks_dict:
print(f"\n Track {track_id}: ERROR - Track ID not found in tracks dict")
continue
track_node = tracks_dict[track_id_str]
# TrackNode is an enum with variants like {"Audio": {...}} or {"Midi": {...}}
if not isinstance(track_node, dict):
print(f"\n Track {track_id}: ERROR - Track node is {type(track_node).__name__}, not a dict")
continue
# Extract the variant (Audio, Midi, or Group)
if len(track_node) != 1:
print(f"\n Track {track_id}: ERROR - Track node has unexpected structure")
continue
track_type, track_data = list(track_node.items())[0]
if not isinstance(track_data, dict):
print(f"\n Track {track_id}: ERROR - Track data is {type(track_data).__name__}, not a dict")
continue
track_name = track_data.get('name', f'Track {track_id}')
muted = track_data.get('muted', False)
solo = track_data.get('solo', False)
volume = track_data.get('volume', 1.0)
pan = track_data.get('pan', 0.0)
status = []
if muted:
status.append('MUTED')
if solo:
status.append('SOLO')
status_str = f" [{', '.join(status)}]" if status else ""
print(f"\n Track {track_id}: {track_name}{status_str}")
print(f" Type: {track_type}")
print(f" Volume: {volume:.2f}")
print(f" Pan: {pan:.2f}")
if track_type == "Midi":
print(f" Instrument: {track_data.get('instrument', 'Unknown')}")
notes = track_data.get('notes', [])
print(f" Notes: {len(notes)}")
preset = track_data.get('instrument_graph_preset')
if preset:
nodes = preset.get('nodes', [])
conns = preset.get('connections', [])
print(f" Graph: {len(nodes)} nodes, {len(conns)} connections")
else:
print(f" Graph: (no preset saved)")
elif track_type == "Audio":
clips = track_data.get('clips', [])
print(f" Clips: {len(clips)}")
preset = track_data.get('effects_graph_preset')
if preset:
nodes = preset.get('nodes', [])
conns = preset.get('connections', [])
print(f" Graph: {len(nodes)} nodes, {len(conns)} connections")
else:
print(f" Graph: (no preset saved)")
print(f"\nMaster Track:")
print(f" Volume: {master_track.get('volume', 1.0):.2f}")
def show_graphs(self):
"""Display detailed node graph information for all tracks."""
if not self.project_data:
return
audio_backend = self.project_data.get('audio_backend', {})
project = audio_backend.get('project', {})
tracks_dict = project.get('tracks', {})
print("\n" + "=" * 60)
print("NODE GRAPHS")
print("=" * 60)
for track_id_str, track_node in tracks_dict.items():
if not isinstance(track_node, dict) or len(track_node) != 1:
continue
track_type, track_data = list(track_node.items())[0]
track_name = track_data.get('name', f'Track {track_id_str}')
# Get the appropriate preset
if track_type == "Audio":
preset = track_data.get('effects_graph_preset')
graph_label = "Effects Graph"
elif track_type == "Midi":
preset = track_data.get('instrument_graph_preset')
graph_label = "Instrument Graph"
else:
continue
print(f"\n Track {track_id_str}: {track_name} ({track_type}) - {graph_label}")
if not preset:
print(f" ** NO PRESET SAVED **")
continue
nodes = preset.get('nodes', [])
connections = preset.get('connections', [])
output_node = preset.get('output_node')
midi_targets = preset.get('midi_targets', [])
metadata = preset.get('metadata', {})
if metadata:
print(f" Preset Name: {metadata.get('name', 'Unknown')}")
print(f" Nodes ({len(nodes)}):")
for i, node in enumerate(nodes):
node_type = node.get('node_type', '?')
node_name = node.get('name', node_type)
params = node.get('parameters', {})
pos_x = node.get('position_x', 0)
pos_y = node.get('position_y', 0)
markers = []
if output_node is not None and i == output_node:
markers.append("OUTPUT")
if i in midi_targets:
markers.append("MIDI TARGET")
marker_str = f" [{', '.join(markers)}]" if markers else ""
print(f" [{i}] {node_type}{marker_str} (name={node_name}, pos={pos_x:.0f},{pos_y:.0f})")
if params:
for param_name, param_val in params.items():
print(f" {param_name} = {param_val}")
print(f" Connections ({len(connections)}):")
for conn in connections:
src = conn.get('from_node', '?')
src_port = conn.get('from_output', '?')
dst = conn.get('to_node', '?')
dst_port = conn.get('to_input', '?')
print(f" [{src}]:{src_port} -> [{dst}]:{dst_port}")
# Also show layer_to_track_map if present
track_map = audio_backend.get('layer_to_track_map', {})
if track_map:
print(f"\n Layer-to-Track Mapping ({len(track_map)} entries):")
for layer_id, track_id in track_map.items():
print(f" {layer_id[:8]}... -> Track {track_id}")
else:
print(f"\n Layer-to-Track Mapping: (none saved)")
def show_audio_pool(self):
"""Display audio pool entries."""
if not self.project_data:
return
audio_backend = self.project_data.get('audio_backend', {})
pool_entries = audio_backend.get('audio_pool_entries', [])
print("\n" + "=" * 60)
print("AUDIO POOL")
print("=" * 60)
print(f"Total Entries: {len(pool_entries)}")
for entry in pool_entries:
pool_index = entry.get('pool_index', '?')
name = entry.get('name', 'Unnamed')
relative_path = entry.get('relative_path')
media_id = entry.get('media_id')
channels = entry.get('channels', 0)
sample_rate = entry.get('sample_rate', 0)
has_embedded = entry.get('embedded_data') is not None
# Storage precedence matches the loader (§8.5/§9.3):
# packed (media_id) > external (relative_path) > embedded > unresolved.
row = self.media_by_id.get(media_id) if media_id else None
if media_id:
size = f", {_human_size(row['total_len'])}" if row else ""
codec = f", {row['codec']}" if row else ""
storage_type = f"Packed in DB{codec}{size}"
elif relative_path and not self.is_sqlite and relative_path.startswith("media/audio/"):
# Legacy ZIP: media/audio/* lives inside the archive, not external.
storage_type = "Embedded (in ZIP)"
elif relative_path:
storage_type = "External reference"
elif has_embedded:
storage_type = "Embedded (inline base64)"
else:
storage_type = "Unresolved (missing)"
print(f"\n [{pool_index}] {name}")
if media_id:
print(f" Media ID: {media_id}")
print(f" Path: {relative_path if relative_path else 'N/A'}")
print(f" Storage: {storage_type}")
print(f" Channels: {channels}")
print(f" Sample Rate: {sample_rate} Hz")
def show_media(self):
"""Display the SQLite media store (the `media` table)."""
if not self.is_sqlite:
print("\n(media table view applies to SQLite .beam files; "
"use --zip for legacy archives)", file=sys.stderr)
return
print("\n" + "=" * 60)
print("MEDIA STORE")
print("=" * 60)
print(f"Total media rows: {len(self.media)}")
# Summary by kind.
by_kind: Dict[str, List[Dict[str, Any]]] = {}
for m in self.media:
by_kind.setdefault(MEDIA_KIND_NAMES.get(m["kind"], f"Kind {m['kind']}"), []).append(m)
if by_kind:
print("\nBy kind:")
for kind_name, rows in sorted(by_kind.items()):
packed = sum(r["total_len"] for r in rows if r["storage"] == 0)
print(f" {kind_name:<12} {len(rows):>4} ({_human_size(packed)} packed)")
print(f"\n{'Kind':<12} {'Storage':<11} {'Codec':<6} {'Size':>10} UUID / details")
print("-" * 78)
for m in self.media:
kind = MEDIA_KIND_NAMES.get(m["kind"], f"Kind {m['kind']}")
storage = MEDIA_STORAGE_NAMES.get(m["storage"], f"Stor {m['storage']}")
size = _human_size(m["total_len"]) if m["storage"] == 0 else "-"
detail = m["uuid"]
extra = []
if m["channels"] is not None:
extra.append(f"{m['channels']}ch@{m['sample_rate']}Hz")
if m["width"] is not None:
extra.append(f"{m['width']}x{m['height']}")
if m["storage"] == 1 and m["ext_path"]:
extra.append(f"-> {m['ext_path']}")
if extra:
detail += " " + " ".join(extra)
print(f"{kind:<12} {storage:<11} {m['codec']:<6} {size:>10} {detail}")
def show_container(self):
"""Show whichever container structure applies to this file."""
if self.is_sqlite:
self.show_media()
else:
self.show_zip_structure()
def show_zip_structure(self):
"""Display the ZIP file structure."""
if self.is_sqlite:
print("\n(this is a SQLite .beam; use --media for the media store)",
file=sys.stderr)
return
print("\n" + "=" * 60)
print("ZIP ARCHIVE STRUCTURE")
print("=" * 60)
try:
with zipfile.ZipFile(self.beam_file, 'r') as zip_ref:
total_size = 0
compressed_size = 0
print(f"{'File':<40} {'Size':>12} {'Compressed':>12} {'Method':<10}")
print("-" * 80)
for info in zip_ref.infolist():
size = info.file_size
comp_size = info.compress_size
method = "DEFLATE" if info.compress_type == 8 else "STORED" if info.compress_type == 0 else f"Type {info.compress_type}"
total_size += size
compressed_size += comp_size
print(f"{info.filename:<40} {size:>12,} {comp_size:>12,} {method:<10}")
print("-" * 80)
print(f"{'TOTAL':<40} {total_size:>12,} {compressed_size:>12,}")
if total_size > 0:
ratio = (1 - compressed_size / total_size) * 100
print(f"\nCompression Ratio: {ratio:.1f}%")
except Exception as e:
print(f"Error reading ZIP structure: {e}", file=sys.stderr)
def extract_json(self, output_path: Optional[Path] = None):
"""Extract project.json to a file or stdout."""
try:
if self.is_sqlite:
con = self._connect()
try:
row = con.execute("SELECT data FROM project_json WHERE id = 0").fetchone()
finally:
con.close()
if not row:
raise ValueError("archive has no project.json row")
json_data = row[0].encode("utf-8") if isinstance(row[0], str) else row[0]
else:
with zipfile.ZipFile(self.beam_file, 'r') as zip_ref:
json_data = zip_ref.read('project.json')
if output_path:
output_path.write_bytes(json_data)
print(f"Extracted project.json to: {output_path}")
else:
data = json.loads(json_data)
print(json.dumps(data, indent=2))
except Exception as e:
print(f"Error extracting project.json: {e}", file=sys.stderr)
def extract_media(self, output_dir: Path):
"""Extract all media to a directory.
SQLite: each packed media row is reassembled from its chunks and written
as ``<uuid>.<codec>``; referenced rows are reported, not copied.
ZIP (legacy): the ``media/`` entries are extracted preserving paths.
"""
try:
if self.is_sqlite:
self._extract_media_sqlite(output_dir)
else:
self._extract_media_zip(output_dir)
except Exception as e:
print(f"Error extracting media: {e}", file=sys.stderr)
def _extract_media_sqlite(self, output_dir: Path):
con = self._connect()
try:
rows = con.execute(
"SELECT id, kind, codec, storage, ext_path, total_len FROM media"
).fetchall()
if not rows:
print("No media rows found in archive.")
return
output_dir.mkdir(parents=True, exist_ok=True)
written = 0
for (idb, kind, codec, storage, ext_path, total_len) in rows:
uid = str(uuidlib.UUID(bytes=bytes(idb)))
kind_name = MEDIA_KIND_NAMES.get(kind, f"kind{kind}")
if storage == 1: # Referenced
print(f"Referenced (not copied): {uid} [{kind_name}] -> {ext_path}")
continue
chunks = con.execute(
"SELECT bytes FROM media_chunk WHERE media_id = ? ORDER BY chunk_index",
(idb,),
).fetchall()
data = b"".join(bytes(c[0]) for c in chunks)
out = output_dir / f"{uid}.{codec}"
out.write_bytes(data)
print(f"Extracted: {out.name} [{kind_name}] {_human_size(len(data))}")
written += 1
print(f"\nExtracted {written} packed media item(s) to: {output_dir}")
finally:
con.close()
def _extract_media_zip(self, output_dir: Path):
with zipfile.ZipFile(self.beam_file, 'r') as zip_ref:
media_files = [f for f in zip_ref.namelist() if f.startswith('media/')]
if not media_files:
print("No media files found in archive.")
return
output_dir.mkdir(parents=True, exist_ok=True)
for media_file in media_files:
output_path = output_dir / media_file
output_path.parent.mkdir(parents=True, exist_ok=True)
with zip_ref.open(media_file) as source:
output_path.write_bytes(source.read())
print(f"Extracted: {media_file}")
print(f"\nExtracted {len(media_files)} media file(s) to: {output_dir}")
def main():
parser = argparse.ArgumentParser(
description="Inspect Lightningbeam .beam project files",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
%(prog)s project.beam # Show all information
%(prog)s project.beam --info # Show only basic info
%(prog)s project.beam --tracks # Show only tracks
%(prog)s project.beam --media # Show the SQLite media store
%(prog)s project.beam --zip # Show legacy ZIP structure
%(prog)s project.beam --extract-json # Print project.json to stdout
%(prog)s project.beam --extract-json out.json # Save project.json
%(prog)s project.beam --extract-media ./media # Extract media files
Handles both current SQLite .beam files and legacy ZIP .beam files
(detected automatically by the file's magic bytes).
"""
)
parser.add_argument('beam_file', type=Path, help='.beam file to inspect')
parser.add_argument('--info', action='store_true', help='Show project information')
parser.add_argument('--clips', action='store_true', help='Show clips')
parser.add_argument('--layers', action='store_true', help='Show layer hierarchy')
parser.add_argument('--tracks', action='store_true', help='Show audio tracks')
parser.add_argument('--graphs', action='store_true', help='Show node graph details for all tracks')
parser.add_argument('--pool', action='store_true', help='Show audio pool')
parser.add_argument('--media', action='store_true', help='Show the SQLite media store')
parser.add_argument('--zip', action='store_true', help='Show legacy ZIP structure')
parser.add_argument('--extract-json', nargs='?', const=True, metavar='OUTPUT',
help='Extract project.json (to file or stdout)')
parser.add_argument('--extract-media', type=Path, metavar='DIR',
help='Extract media files to directory')
args = parser.parse_args()
# Validate input file
if not args.beam_file.exists():
print(f"Error: File not found: {args.beam_file}", file=sys.stderr)
sys.exit(1)
if not args.beam_file.suffix == '.beam':
print(f"Warning: File does not have .beam extension: {args.beam_file}", file=sys.stderr)
# Create inspector
inspector = BeamInspector(args.beam_file)
# Handle extract operations (don't need to load project.json)
if args.extract_json:
if args.extract_json is True:
inspector.extract_json()
else:
inspector.extract_json(Path(args.extract_json))
return
if args.extract_media:
inspector.extract_media(args.extract_media)
return
# Load the beam file
if not inspector.load():
sys.exit(1)
# If no specific flags, show everything
show_all = not any([args.info, args.clips, args.layers, args.tracks,
args.graphs, args.pool, args.media, args.zip])
if show_all or args.info:
inspector.show_info()
if show_all or args.clips:
inspector.show_clips()
if show_all or args.layers:
inspector.show_layers()
if show_all or args.tracks:
inspector.show_tracks()
if show_all or args.graphs:
inspector.show_graphs()
if show_all or args.pool:
inspector.show_audio_pool()
if show_all:
# Show whichever container structure applies to this file.
inspector.show_container()
elif args.media:
inspector.show_media()
elif args.zip:
inspector.show_zip_structure()
if __name__ == '__main__':
main()
+210
View File
@@ -0,0 +1,210 @@
# Lightningbeam .beam File Inspector
A Python command-line tool to inspect and analyze `.beam` project files.
Handles **both** container formats automatically (detected by the file's magic
bytes): the current **SQLite** `.beam` and the **legacy ZIP** `.beam`. See
[BEAM_FILE_FORMAT.md](./BEAM_FILE_FORMAT.md) for the format specification.
## Features
- **Project Information**: Container type, schema version, metadata, dimensions, framerate, duration, background color
- **Clips Analysis**: List all vector, video, and audio clips
- **Layer Hierarchy**: Display the complete layer tree structure
- **Audio Tracks**: Show all audio/MIDI tracks with their settings
- **Audio Pool**: List all audio files and their storage details
- **Media Store** (SQLite): List the `media` table — kinds, storage, codecs, sizes
- **ZIP Structure** (legacy): Examine the internal ZIP archive structure and compression
- **Extraction**: Extract `project.json` or media files
## Installation
The tool requires Python 3.6+ with no external dependencies (uses only the standard
library; `sqlite3` ships with Python).
```bash
chmod +x beam_inspector.py
```
## Usage
### Show All Information
```bash
./beam_inspector.py project.beam
```
### Show Specific Sections
```bash
# Basic project info only
./beam_inspector.py project.beam --info
# Audio tracks only
./beam_inspector.py project.beam --tracks
# Audio pool entries
./beam_inspector.py project.beam --pool
# Layer hierarchy
./beam_inspector.py project.beam --layers
# Clips summary
./beam_inspector.py project.beam --clips
# Media store (SQLite files): the media table — kinds, storage, codecs, sizes
./beam_inspector.py project.beam --media
# ZIP archive structure (legacy ZIP files only)
./beam_inspector.py project.beam --zip
```
When run with no section flags, the tool shows everything and automatically
picks the media-store view (SQLite) or ZIP-structure view (legacy) for the file.
### Extract Files
```bash
# Print project.json to stdout (pretty-printed)
./beam_inspector.py project.beam --extract-json
# Save project.json to a file
./beam_inspector.py project.beam --extract-json output.json
# Extract all media files to a directory
./beam_inspector.py project.beam --extract-media ./extracted_media
```
## Example Output
```
============================================================
PROJECT INFORMATION
============================================================
Container: SQLite
Schema Ver: 1
Version: 1.0.0
Created: 2025-12-01T12:00:00Z
Modified: 2025-12-01T12:30:00Z
Project Name: My Animation
ID: 550e8400-e29b-41d4-a716-446655440000
Dimensions: 1920 x 1080
Framerate: 60.0 fps
Duration: 10.00 seconds
Background: rgba(255, 255, 255, 255)
Sample Rate: 48000 Hz
============================================================
AUDIO TRACKS
============================================================
Total Tracks: 2
Track 0: Piano [SOLO]
Type: Midi
Volume: 0.80
Pan: 0.00
Instrument: Piano
Notes: 24
Track 1: Background Music
Type: Audio
Volume: 0.60
Pan: 0.00
Clips: 3
Master Track:
Volume: 1.00
============================================================
AUDIO POOL
============================================================
Total Entries: 2
[0] C2.mp3
Media ID: e7e555a6-85f1-4faa-bfd4-c6e4b790986a
Path: N/A
Storage: Packed in DB, mp3, 412.0 KiB
Channels: 2
Sample Rate: 44100 Hz
[1] Background.flac
Media ID: a18c0e22-1d3b-4c77-9f0a-2b5e6c4d8e10
Path: N/A
Storage: Packed in DB, flac, 6.4 MiB
Channels: 2
Sample Rate: 48000 Hz
```
## Understanding the Output
### Storage Types
- **Packed in DB**: Audio bytes are chunked into the SQLite `media` table (the entry's `media_id` resolves to a packed row). Current default for most audio.
- **External reference**: File is referenced from the filesystem by `relative_path` (e.g. large media or video audio).
- **Embedded (inline base64)**: Bytes stored directly in `project.json` (`embedded_data`) — legacy/fallback.
- **Embedded (in ZIP)**: Legacy ZIP files only — bytes stored inside the archive under `media/audio/`.
- **Unresolved (missing)**: No packed row, external file, or embedded data — reported as a missing file on load.
### Track Types
- **Audio**: Traditional audio track with clips from the audio pool
- **Midi**: MIDI track with note events and virtual instrument
### Layer Types
Based on the `AnyLayer` enum:
- **Group**: Container for other layers
- **Vector**: Vector graphics layer
- **Video**: Video clip layer
- **Audio**: Audio waveform layer
- **Image**: Raster image layer
- **Text**: Text layer
## Advanced Usage
### Combine with Other Tools
```bash
# Pretty-print and page through JSON
./beam_inspector.py project.beam --extract-json | less
# Search for specific content in JSON
./beam_inspector.py project.beam --extract-json | grep "sample_rate"
# Count total audio files
./beam_inspector.py project.beam --pool | grep "^\[" | wc -l
# Extract and process media files
# SQLite: writes flat <uuid>.<codec> files; ZIP: preserves media/ paths
./beam_inspector.py project.beam --extract-media /tmp/media
ls -lh /tmp/media/
```
### Scripting
```python
from beam_inspector import BeamInspector
from pathlib import Path
inspector = BeamInspector(Path("project.beam"))
if inspector.load():
# Access parsed data
version = inspector.project_data['version']
tracks = inspector.project_data['audio_backend']['project']['tracks']
print(f"Found {len(tracks)} tracks in version {version}")
```
## Troubleshooting
### "Error loading .beam file"
- Ensure the file is a valid SQLite database (current) or ZIP archive (legacy)
- Check that `project.json` exists (the `project_json` table for SQLite, or a top-level entry for ZIP)
- Verify the JSON is well-formed
### "File not found"
- Provide the full path to the .beam file
- Check file permissions
### Missing media files
- External references may point to files that don't exist
- Use `--extract-media` to see what's actually in the archive
- Check the `relative_path` values in `--pool` output
## See Also
- [BEAM_FILE_FORMAT.md](./BEAM_FILE_FORMAT.md) - Complete .beam file format specification
- [Lightningbeam Documentation](./README.md) - Main project documentation
+13 -13
View File
@@ -1,34 +1,34 @@
#!/bin/bash
# Ensure the script stops on error
set -e
# Check if a version argument was passed
if [ -z "$1" ]; then
echo "Usage: ./create-release.sh <version>"
echo "Usage: ./create_release.sh <version>"
exit 1
fi
VERSION=$1
RELEASE_BRANCH="release"
MAIN_BRANCH="main"
CONFIG_FILE="src-tauri/tauri.conf.json"
MAIN_BRANCH=$(git rev-parse --abbrev-ref HEAD)
CARGO_TOML="lightningbeam-ui/lightningbeam-editor/Cargo.toml"
echo "Updating version to $VERSION in $CONFIG_FILE..."
jq --arg version "$VERSION" '.version = $version' $CONFIG_FILE > tmp.json && mv tmp.json $CONFIG_FILE
echo "Updating version to $VERSION in $CARGO_TOML..."
sed -i "0,/^version = .*/s/^version = .*/version = \"$VERSION\"/" "$CARGO_TOML"
echo "Committing to main..."
git add $CONFIG_FILE
git commit -m "Bump version to $VERSION"
echo "Committing to $MAIN_BRANCH..."
git add "$CARGO_TOML" Changelog.md
git diff --cached --quiet || git commit -m "Bump version to $VERSION"
echo "Checking out the release branch..."
git checkout $RELEASE_BRANCH
echo "Merging the main branch into $RELEASE_BRANCH..."
echo "Merging $MAIN_BRANCH into $RELEASE_BRANCH..."
git merge $MAIN_BRANCH --no-ff -m "Release $VERSION"
echo "Pushing changes to the release branch..."
git push origin $RELEASE_BRANCH
echo "Pushing $RELEASE_BRANCH..."
# Push to the 'all' remote so the release branch lands on both GitHub and Gitea.
# CI (GitHub Actions) still triggers via the GitHub pushurl.
git push all $RELEASE_BRANCH
git checkout $MAIN_BRANCH
+624 -113
View File
File diff suppressed because it is too large Load Diff
+3
View File
@@ -23,6 +23,8 @@ memmap2 = "0.9"
# Audio export
hound = "3.5"
ffmpeg-next = "8.0" # For MP3/AAC encoding
# AVIO-over-Read+Seek shim: stream a packed video's audio track from the SQLite blob.
ffmpeg-blob-io = { path = "../ffmpeg-blob-io" }
# Node-based audio graph dependencies
dasp_graph = "0.11"
@@ -35,6 +37,7 @@ dasp_peak = "0.11"
dasp_rms = "0.11"
petgraph = "0.6"
serde_json = "1.0"
zip = "0.6"
# BeamDSP scripting engine
beamdsp = { path = "../lightningbeam-ui/beamdsp" }
+38 -45
View File
@@ -1,5 +1,6 @@
/// Automation system for parameter modulation over time
use serde::{Deserialize, Serialize};
use crate::time::Beats;
/// Unique identifier for automation lanes
pub type AutomationLaneId = u32;
@@ -35,17 +36,13 @@ pub enum CurveType {
/// A single automation point
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct AutomationPoint {
/// Time in seconds
pub time: f64,
/// Parameter value (normalized 0.0 to 1.0, or actual value depending on parameter)
pub time: Beats,
pub value: f32,
/// Curve type to next point
pub curve: CurveType,
}
impl AutomationPoint {
/// Create a new automation point
pub fn new(time: f64, value: f32, curve: CurveType) -> Self {
pub fn new(time: Beats, value: f32, curve: CurveType) -> Self {
Self { time, value, curve }
}
}
@@ -93,8 +90,7 @@ impl AutomationLane {
}
}
/// Remove point at specific time
pub fn remove_point_at_time(&mut self, time: f64, tolerance: f64) -> bool {
pub fn remove_point_at_time(&mut self, time: Beats, tolerance: Beats) -> bool {
if let Some(idx) = self.points.iter().position(|p| (p.time - time).abs() < tolerance) {
self.points.remove(idx);
true
@@ -113,8 +109,7 @@ impl AutomationLane {
&self.points
}
/// Get value at a specific time with interpolation
pub fn evaluate(&self, time: f64) -> Option<f32> {
pub fn evaluate(&self, time: Beats) -> Option<f32> {
if !self.enabled || self.points.is_empty() {
return None;
}
@@ -148,14 +143,12 @@ impl AutomationLane {
}
}
/// Interpolate between two automation points based on curve type
fn interpolate(p1: &AutomationPoint, p2: &AutomationPoint, time: f64) -> f32 {
// Calculate normalized position between points (0.0 to 1.0)
fn interpolate(p1: &AutomationPoint, p2: &AutomationPoint, time: Beats) -> f32 {
let t = if p2.time == p1.time {
0.0
0.0f64
} else {
((time - p1.time) / (p2.time - p1.time)) as f32
};
(time - p1.time) / (p2.time - p1.time)
} as f32;
// Apply curve
let curved_t = match p1.curve {
@@ -196,22 +189,22 @@ mod tests {
fn test_add_points_sorted() {
let mut lane = AutomationLane::new(0, ParameterId::TrackVolume);
lane.add_point(AutomationPoint::new(2.0, 0.5, CurveType::Linear));
lane.add_point(AutomationPoint::new(1.0, 0.3, CurveType::Linear));
lane.add_point(AutomationPoint::new(3.0, 0.8, CurveType::Linear));
lane.add_point(AutomationPoint::new(Beats(2.0), 0.5, CurveType::Linear));
lane.add_point(AutomationPoint::new(Beats(1.0), 0.3, CurveType::Linear));
lane.add_point(AutomationPoint::new(Beats(3.0), 0.8, CurveType::Linear));
assert_eq!(lane.points().len(), 3);
assert_eq!(lane.points()[0].time, 1.0);
assert_eq!(lane.points()[1].time, 2.0);
assert_eq!(lane.points()[2].time, 3.0);
assert_eq!(lane.points()[0].time, Beats(1.0));
assert_eq!(lane.points()[1].time, Beats(2.0));
assert_eq!(lane.points()[2].time, Beats(3.0));
}
#[test]
fn test_replace_point_at_same_time() {
let mut lane = AutomationLane::new(0, ParameterId::TrackVolume);
lane.add_point(AutomationPoint::new(1.0, 0.3, CurveType::Linear));
lane.add_point(AutomationPoint::new(1.0, 0.5, CurveType::Linear));
lane.add_point(AutomationPoint::new(Beats(1.0), 0.3, CurveType::Linear));
lane.add_point(AutomationPoint::new(Beats(1.0), 0.5, CurveType::Linear));
assert_eq!(lane.points().len(), 1);
assert_eq!(lane.points()[0].value, 0.5);
@@ -221,59 +214,59 @@ mod tests {
fn test_linear_interpolation() {
let mut lane = AutomationLane::new(0, ParameterId::TrackVolume);
lane.add_point(AutomationPoint::new(0.0, 0.0, CurveType::Linear));
lane.add_point(AutomationPoint::new(1.0, 1.0, CurveType::Linear));
lane.add_point(AutomationPoint::new(Beats(0.0), 0.0, CurveType::Linear));
lane.add_point(AutomationPoint::new(Beats(1.0), 1.0, CurveType::Linear));
assert_eq!(lane.evaluate(0.0), Some(0.0));
assert_eq!(lane.evaluate(0.5), Some(0.5));
assert_eq!(lane.evaluate(1.0), Some(1.0));
assert_eq!(lane.evaluate(Beats(0.0)), Some(0.0));
assert_eq!(lane.evaluate(Beats(0.5)), Some(0.5));
assert_eq!(lane.evaluate(Beats(1.0)), Some(1.0));
}
#[test]
fn test_step_interpolation() {
let mut lane = AutomationLane::new(0, ParameterId::TrackVolume);
lane.add_point(AutomationPoint::new(0.0, 0.5, CurveType::Step));
lane.add_point(AutomationPoint::new(1.0, 1.0, CurveType::Step));
lane.add_point(AutomationPoint::new(Beats(0.0), 0.5, CurveType::Step));
lane.add_point(AutomationPoint::new(Beats(1.0), 1.0, CurveType::Step));
assert_eq!(lane.evaluate(0.0), Some(0.5));
assert_eq!(lane.evaluate(0.5), Some(0.5));
assert_eq!(lane.evaluate(0.99), Some(0.5));
assert_eq!(lane.evaluate(1.0), Some(1.0));
assert_eq!(lane.evaluate(Beats(0.0)), Some(0.5));
assert_eq!(lane.evaluate(Beats(0.5)), Some(0.5));
assert_eq!(lane.evaluate(Beats(0.99)), Some(0.5));
assert_eq!(lane.evaluate(Beats(1.0)), Some(1.0));
}
#[test]
fn test_evaluate_outside_range() {
let mut lane = AutomationLane::new(0, ParameterId::TrackVolume);
lane.add_point(AutomationPoint::new(1.0, 0.5, CurveType::Linear));
lane.add_point(AutomationPoint::new(2.0, 1.0, CurveType::Linear));
lane.add_point(AutomationPoint::new(Beats(1.0), 0.5, CurveType::Linear));
lane.add_point(AutomationPoint::new(Beats(2.0), 1.0, CurveType::Linear));
// Before first point
assert_eq!(lane.evaluate(0.0), Some(0.5));
assert_eq!(lane.evaluate(Beats(0.0)), Some(0.5));
// After last point
assert_eq!(lane.evaluate(3.0), Some(1.0));
assert_eq!(lane.evaluate(Beats(3.0)), Some(1.0));
}
#[test]
fn test_disabled_lane() {
let mut lane = AutomationLane::new(0, ParameterId::TrackVolume);
lane.add_point(AutomationPoint::new(0.0, 0.5, CurveType::Linear));
lane.add_point(AutomationPoint::new(Beats(0.0), 0.5, CurveType::Linear));
lane.enabled = false;
assert_eq!(lane.evaluate(0.0), None);
assert_eq!(lane.evaluate(Beats(0.0)), None);
}
#[test]
fn test_remove_point() {
let mut lane = AutomationLane::new(0, ParameterId::TrackVolume);
lane.add_point(AutomationPoint::new(1.0, 0.5, CurveType::Linear));
lane.add_point(AutomationPoint::new(2.0, 0.8, CurveType::Linear));
lane.add_point(AutomationPoint::new(Beats(1.0), 0.5, CurveType::Linear));
lane.add_point(AutomationPoint::new(Beats(2.0), 0.8, CurveType::Linear));
assert!(lane.remove_point_at_time(1.0, 0.001));
assert!(lane.remove_point_at_time(Beats(1.0), Beats(0.001)));
assert_eq!(lane.points().len(), 1);
assert_eq!(lane.points()[0].time, 2.0);
assert_eq!(lane.points()[0].time, Beats(2.0));
}
}
+40 -76
View File
@@ -1,5 +1,7 @@
use std::sync::Arc;
use serde::{Serialize, Deserialize};
use crate::time::{Beats, Seconds};
use crate::tempo_map::TempoMap;
/// Audio clip instance ID type
pub type AudioClipInstanceId = u32;
@@ -9,38 +11,31 @@ pub type ClipId = AudioClipInstanceId;
/// Audio clip instance that references content in the AudioClipPool
///
/// This represents a placed instance of audio content on the timeline.
/// The actual audio data is stored in the AudioClipPool and referenced by `audio_pool_index`.
///
/// ## Timing Model
/// - `internal_start` / `internal_end`: Define the region of the source audio to play (trimming)
/// - `external_start` / `external_duration`: Define where the clip appears on the timeline and how long
/// - `internal_start` / `internal_end`: Region of the source audio to play (seconds — audio file seek positions)
/// - `external_start` / `external_duration`: Where the clip appears on the timeline (**beats**)
///
/// ## Looping
/// If `external_duration` is greater than `internal_end - internal_start`,
/// the clip will seamlessly loop back to `internal_start` when it reaches `internal_end`.
/// If `external_duration_secs(bpm)` > `internal_end - internal_start`, the clip loops.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AudioClipInstance {
pub id: AudioClipInstanceId,
pub audio_pool_index: usize,
/// Start position within the audio content (seconds)
pub internal_start: f64,
/// End position within the audio content (seconds)
pub internal_end: f64,
/// Start position within the audio content
pub internal_start: Seconds,
/// End position within the audio content
pub internal_end: Seconds,
/// Start position on the timeline (seconds)
pub external_start: f64,
/// Duration on the timeline (seconds) - can be longer than internal duration for looping
pub external_duration: f64,
/// Start position on the timeline
pub external_start: Beats,
/// Duration on the timeline
pub external_duration: Beats,
/// Clip-level gain
pub gain: f32,
/// Per-instance read-ahead buffer for compressed audio streaming.
/// Each clip instance gets its own buffer so multiple instances of the
/// same file (on different tracks or at different positions) don't fight
/// over a single target_frame.
#[serde(skip)]
pub read_ahead: Option<Arc<super::disk_reader::ReadAheadBuffer>>,
}
@@ -49,14 +44,13 @@ pub struct AudioClipInstance {
pub type Clip = AudioClipInstance;
impl AudioClipInstance {
/// Create a new audio clip instance
pub fn new(
id: AudioClipInstanceId,
audio_pool_index: usize,
internal_start: f64,
internal_end: f64,
external_start: f64,
external_duration: f64,
internal_start: Seconds,
internal_end: Seconds,
external_start: Beats,
external_duration: Beats,
) -> Self {
Self {
id,
@@ -70,80 +64,50 @@ impl AudioClipInstance {
}
}
/// Create a clip instance from legacy parameters (for backwards compatibility)
/// Maps old start_time/duration/offset to new timing model
pub fn from_legacy(
id: AudioClipInstanceId,
audio_pool_index: usize,
start_time: f64,
duration: f64,
offset: f64,
) -> Self {
Self {
id,
audio_pool_index,
internal_start: offset,
internal_end: offset + duration,
external_start: start_time,
external_duration: duration,
gain: 1.0,
read_ahead: None,
}
}
/// Check if this clip instance is active at a given timeline position
pub fn is_active_at(&self, time_seconds: f64) -> bool {
time_seconds >= self.external_start && time_seconds < self.external_end()
}
/// Get the end time of this clip instance on the timeline
pub fn external_end(&self) -> f64 {
pub fn external_end(&self) -> Beats {
self.external_start + self.external_duration
}
/// Get the end time of this clip instance on the timeline
/// (Alias for external_end(), for backwards compatibility)
pub fn end_time(&self) -> f64 {
self.external_end()
pub fn external_start_secs(&self, tempo_map: &TempoMap) -> Seconds {
tempo_map.beats_to_seconds(self.external_start)
}
/// Get the start time on the timeline
/// (Alias for external_start, for backwards compatibility)
pub fn start_time(&self) -> f64 {
self.external_start
pub fn external_end_secs(&self, tempo_map: &TempoMap) -> Seconds {
tempo_map.beats_to_seconds(self.external_end())
}
/// Get the internal (content) duration
pub fn internal_duration(&self) -> f64 {
pub fn external_duration_secs(&self, tempo_map: &TempoMap) -> Seconds {
tempo_map.beats_to_seconds(self.external_end()) - tempo_map.beats_to_seconds(self.external_start)
}
pub fn is_active_at(&self, time: Seconds, tempo_map: &TempoMap) -> bool {
time >= self.external_start_secs(tempo_map) && time < self.external_end_secs(tempo_map)
}
pub fn internal_duration(&self) -> Seconds {
self.internal_end - self.internal_start
}
/// Check if this clip instance loops
pub fn is_looping(&self) -> bool {
self.external_duration > self.internal_duration()
pub fn is_looping(&self, tempo_map: &TempoMap) -> bool {
self.external_duration_secs(tempo_map) > self.internal_duration()
}
/// Get the position within the audio content for a given timeline position
/// Returns None if the timeline position is outside this clip instance
/// Handles looping automatically
pub fn get_content_position(&self, timeline_pos: f64) -> Option<f64> {
if timeline_pos < self.external_start || timeline_pos >= self.external_end() {
/// Get the audio content position for a given timeline position. Handles looping.
pub fn get_content_position(&self, timeline_pos: Seconds, tempo_map: &TempoMap) -> Option<Seconds> {
let start_secs = self.external_start_secs(tempo_map);
let end_secs = self.external_end_secs(tempo_map);
if timeline_pos < start_secs || timeline_pos >= end_secs {
return None;
}
let relative_pos = timeline_pos - self.external_start;
let relative_pos = timeline_pos - start_secs;
let internal_duration = self.internal_duration();
if internal_duration <= 0.0 {
if internal_duration.0 <= 0.0 {
return None;
}
// Wrap around for looping
let content_offset = relative_pos % internal_duration;
Some(self.internal_start + content_offset)
}
/// Set clip gain
pub fn set_gain(&mut self, gain: f32) {
self.gain = gain.max(0.0);
}
+577 -25
View File
@@ -77,6 +77,12 @@ pub struct ReadAheadBuffer {
/// When true, `render_from_file` will block-wait for frames instead of
/// returning silence on buffer miss. Used during offline export.
export_mode: AtomicBool,
/// Set by the disk reader when the source reaches EOF (no more frames will
/// ever be decoded past the current valid range). Lets export-mode block-waits
/// give up immediately for frames past the end of the audio (e.g. a video whose
/// audio track is shorter than the video) instead of timing out per chunk.
/// Cleared on `reset` (a seek may decode fresh data again).
finished: AtomicBool,
}
// SAFETY: See the doc comment on ReadAheadBuffer for the full safety argument.
@@ -112,6 +118,7 @@ impl ReadAheadBuffer {
sample_rate,
target_frame: AtomicU64::new(0),
export_mode: AtomicBool::new(false),
finished: AtomicBool::new(false),
}
}
@@ -216,11 +223,24 @@ impl ReadAheadBuffer {
self.export_mode.load(Ordering::Acquire)
}
/// Mark that the source has reached EOF (set by the disk reader).
pub fn set_finished(&self, finished: bool) {
self.finished.store(finished, Ordering::Release);
}
/// True once the source hit EOF: no frames past the current valid range
/// will ever be decoded (until a `reset`/seek).
pub fn is_finished(&self) -> bool {
self.finished.load(Ordering::Acquire)
}
/// Reset the buffer to start at `new_start` with zero valid frames.
/// Called by the **disk reader thread** (producer) after a seek.
pub fn reset(&self, new_start: u64) {
self.valid_frames.store(0, Ordering::Release);
self.start_frame.store(new_start, Ordering::Release);
// A seek may decode fresh data past the previous EOF position.
self.finished.store(false, Ordering::Release);
}
/// Write interleaved samples into the buffer, extending the valid range.
@@ -307,23 +327,96 @@ impl ReadAheadBuffer {
// ---------------------------------------------------------------------------
/// Wraps a Symphonia decoder for streaming a single compressed audio file.
struct CompressedReader {
///
/// Public (like [`VideoAudioReader`]) only so integration tests can exercise it
/// directly; treat it as crate-internal.
pub struct CompressedReader {
format_reader: Box<dyn symphonia::core::formats::FormatReader>,
decoder: Box<dyn symphonia::core::codecs::Decoder>,
track_id: u32,
/// Current decoder position in frames.
current_frame: u64,
/// Frames still to drop from the front of decoded output, so that after a
/// (coarse) seek the next emitted sample lands exactly on the target frame.
pending_discard: u64,
sample_rate: u32,
channels: u32,
#[allow(dead_code)]
total_frames: u64,
/// Temporary decode buffer.
sample_buf: Option<SampleBuffer<f32>>,
}
/// A seekable byte stream for packed media held in the host's project container.
///
/// `daw-backend` stays container-agnostic: it never references the `.beam` SQLite
/// store directly. Instead the host (lightningbeam-core) implements this trait over
/// its incremental blob reader and installs a factory ([`AudioBlobSourceFactory`])
/// into the engine, so packed compressed audio can be stream-decoded without ever
/// being fully loaded into RAM.
pub trait MediaByteSource: std::io::Read + std::io::Seek + Send + Sync {
/// Total length of the stream in bytes (Symphonia needs this for seeking).
fn byte_len(&self) -> u64;
}
/// Opens fresh byte streams for packed media by id. Installed into the engine by
/// the host; invoked when activating a clip backed by container-packed audio.
/// (`Debug` so it can ride in the `Query` enum, which derives `Debug`.)
pub trait AudioBlobSourceFactory: Send + Sync + std::fmt::Debug {
/// Open a new independent reader for the packed media item `media_id`
/// (the UUID string stored on the audio pool entry).
fn open(&self, media_id: &str) -> Result<Box<dyn MediaByteSource>, String>;
}
/// Adapts a [`MediaByteSource`] to Symphonia's `MediaSource` (adds the seekable +
/// byte-length metadata Symphonia's probe/seek require).
struct SymphoniaByteSource(Box<dyn MediaByteSource>);
impl std::io::Read for SymphoniaByteSource {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
self.0.read(buf)
}
}
impl std::io::Seek for SymphoniaByteSource {
fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {
self.0.seek(pos)
}
}
impl symphonia::core::io::MediaSource for SymphoniaByteSource {
fn is_seekable(&self) -> bool {
true
}
fn byte_len(&self) -> Option<u64> {
Some(self.0.byte_len())
}
}
/// How to open a streaming audio source: a filesystem path (referenced media or a
/// video file) or a host-provided byte stream (container-packed media).
pub enum StreamOpen {
Path(PathBuf),
Source {
src: Box<dyn MediaByteSource>,
/// Codec/extension hint for the Symphonia probe (e.g. `"mp3"`, `"flac"`).
ext: Option<String>,
},
}
impl CompressedReader {
pub fn sample_rate(&self) -> u32 {
self.sample_rate
}
pub fn channels(&self) -> u32 {
self.channels
}
/// Total frames from the codec header (0 if the format doesn't report it).
pub fn total_frames(&self) -> u64 {
self.total_frames
}
/// Open a compressed audio file and prepare for streaming decode.
fn open(path: &Path) -> Result<Self, String> {
pub fn open(path: &Path) -> Result<Self, String> {
let file =
std::fs::File::open(path).map_err(|e| format!("Failed to open file: {}", e))?;
let mss = MediaSourceStream::new(Box::new(file), Default::default());
@@ -332,7 +425,21 @@ impl CompressedReader {
if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
hint.with_extension(ext);
}
Self::from_mss(mss, hint)
}
/// Open a compressed stream from a host-provided byte source (packed media).
pub fn open_source(src: Box<dyn MediaByteSource>, ext: Option<&str>) -> Result<Self, String> {
let mss = MediaSourceStream::new(Box::new(SymphoniaByteSource(src)), Default::default());
let mut hint = Hint::new();
if let Some(ext) = ext {
hint.with_extension(ext);
}
Self::from_mss(mss, hint)
}
/// Shared probe + decoder setup over an already-built media stream.
fn from_mss(mss: MediaSourceStream, hint: Hint) -> Result<Self, String> {
let probed = symphonia::default::get_probe()
.format(
&hint,
@@ -368,6 +475,7 @@ impl CompressedReader {
decoder,
track_id,
current_frame: 0,
pending_discard: 0,
sample_rate,
channels,
total_frames,
@@ -375,9 +483,17 @@ impl CompressedReader {
})
}
/// Seek to a specific frame. Returns the actual frame reached (may differ
/// for compressed formats that can only seek to keyframes).
fn seek(&mut self, target_frame: u64) -> Result<u64, String> {
/// Seek to `target_frame`, **sample-accurately**. Uses `SeekMode::Accurate`:
/// for an elementary stream like MP3 a *coarse* seek byte-estimates the
/// position and seeds the timestamp from that estimate — which for VBR (or a
/// file whose header padding the estimate ignores) lands off by up to ~1s.
/// Accurate mode instead counts frame *headers* (no decode) from a true anchor
/// (the current position, or a rewind to the start for backward seeks), so the
/// returned `actual_ts` is exact; the small residual to `target_frame` is then
/// dropped in `decode_next`. Container formats with seek tables (FLAC/OGG) seek
/// cheaply; a long MP3 walks headers from the anchor (I/O, not decode) — a
/// per-file seek index would make that O(1) (future work).
pub fn seek(&mut self, target_frame: u64) -> Result<u64, String> {
let seek_to = SeekTo::TimeStamp {
ts: target_frame,
track_id: self.track_id,
@@ -385,21 +501,23 @@ impl CompressedReader {
let seeked = self
.format_reader
.seek(SeekMode::Coarse, seek_to)
.seek(SeekMode::Accurate, seek_to)
.map_err(|e| format!("Seek failed: {}", e))?;
let actual_frame = seeked.actual_ts;
self.current_frame = actual_frame;
// Drop the frames between where the coarse seek landed and the target.
self.pending_discard = target_frame.saturating_sub(actual_frame);
// Reset the decoder after seeking.
self.decoder.reset();
Ok(actual_frame)
Ok(target_frame)
}
/// Decode the next chunk of audio into `out`. Returns the number of frames
/// decoded. Returns `Ok(0)` at end-of-file.
fn decode_next(&mut self, out: &mut Vec<f32>) -> Result<usize, String> {
pub fn decode_next(&mut self, out: &mut Vec<f32>) -> Result<usize, String> {
out.clear();
loop {
@@ -428,10 +546,22 @@ impl CompressedReader {
if let Some(ref mut buf) = self.sample_buf {
buf.copy_interleaved_ref(decoded);
let samples = buf.samples();
out.extend_from_slice(samples);
let frames = samples.len() / self.channels as usize;
self.current_frame += frames as u64;
return Ok(frames);
let ch = self.channels as usize;
let frames = samples.len() / ch;
// Drop leading frames for sample-accurate seek alignment.
let discard = self.pending_discard.min(frames as u64) as usize;
self.pending_discard -= discard as u64;
out.extend_from_slice(&samples[discard * ch..]);
let emitted = frames - discard;
self.current_frame += emitted as u64;
if emitted > 0 {
return Ok(emitted);
}
// Whole packet discarded for alignment — keep decoding so
// we never falsely report EOF (Ok(0)).
continue;
}
return Ok(0);
@@ -445,16 +575,428 @@ impl CompressedReader {
}
}
// ---------------------------------------------------------------------------
// VideoAudioReader
// ---------------------------------------------------------------------------
/// Streams the audio track out of a media file (a video container, or any audio
/// file) using FFmpeg, decoding on demand. Mirrors [`CompressedReader`]'s
/// interface so the disk reader can drive either through [`StreamSource`].
///
/// Seeking is **sample-accurate**: after `seek(target)`, the next `decode_next`
/// yields samples beginning at exactly `target`. FFmpeg's container seek only
/// lands at-or-before the target, so we decode forward and discard the leading
/// samples to hit the frame precisely — this keeps video audio frame-synced with
/// other (mmap/in-memory) clips.
///
/// Public (vs. the private `CompressedReader`) only so integration tests can
/// exercise it directly; treat it as crate-internal.
/// Adapts a host `MediaByteSource` (Read+Seek+Send+Sync) to the `ffmpeg-blob-io`
/// `BlobSource` (Read+Seek+Send) so a packed video can be demuxed from a blob.
struct ByteSourceAdapter(Box<dyn MediaByteSource>);
impl std::io::Read for ByteSourceAdapter {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
self.0.read(buf)
}
}
impl std::io::Seek for ByteSourceAdapter {
fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {
self.0.seek(pos)
}
}
/// A demuxer input for video-audio: a video file path, or a container blob streamed
/// via the AVIO shim. Both expose the same ffmpeg `Input`.
enum AudioInput {
Path(ffmpeg_next::format::context::Input),
Blob(ffmpeg_blob_io::BlobInput),
}
impl AudioInput {
fn get(&mut self) -> &mut ffmpeg_next::format::context::Input {
match self {
AudioInput::Path(i) => i,
AudioInput::Blob(b) => b.input_mut(),
}
}
}
pub struct VideoAudioReader {
input: AudioInput,
decoder: ffmpeg_next::decoder::Audio,
/// Built lazily from the first decoded frame's format/layout → interleaved f32.
resampler: Option<ffmpeg_next::software::resampling::Context>,
stream_index: usize,
/// Seconds per stream-timestamp unit.
time_base: f64,
sample_rate: u32,
channels: u32,
total_frames: u64,
/// Absolute frame index of the next sample `decode_next` will output.
current_frame: u64,
/// Frames still to drop from the front of decoded output (seek alignment).
pending_discard: u64,
/// When set, the next decoded frame establishes the discard needed to land on
/// this absolute target frame (sample-accurate seek).
align_to: Option<u64>,
}
impl VideoAudioReader {
pub fn sample_rate(&self) -> u32 {
self.sample_rate
}
pub fn channels(&self) -> u32 {
self.channels
}
/// Estimated total audio frames (from the stream/container duration).
pub fn total_frames(&self) -> u64 {
self.total_frames
}
/// Open the audio track of a video **file**.
pub fn open(path: &Path) -> Result<Self, String> {
ffmpeg_next::init().map_err(|e| e.to_string())?;
let input = ffmpeg_next::format::input(&path)
.map_err(|e| format!("Failed to open media: {}", e))?;
Self::from_input(AudioInput::Path(input))
}
/// Open the audio track of a video streamed from a **byte source** (a packed
/// `.beam` video blob), via the `ffmpeg-blob-io` AVIO shim. `ext` is a container
/// hint (e.g. `"mp4"`).
pub fn open_source(src: Box<dyn MediaByteSource>, ext: Option<&str>) -> Result<Self, String> {
ffmpeg_next::init().map_err(|e| e.to_string())?;
let blob = ffmpeg_blob_io::BlobInput::open(Box::new(ByteSourceAdapter(src)), ext)
.map_err(|e| format!("Failed to open packed video audio: {}", e))?;
Self::from_input(AudioInput::Blob(blob))
}
fn from_input(mut input: AudioInput) -> Result<Self, String> {
// Pull stream scalars + build the decoder inside a scope so the stream
// borrow of `input` ends before we use `input` again.
let (stream_index, time_base, stream_duration, decoder) = {
let stream = input
.get()
.streams()
.best(ffmpeg_next::media::Type::Audio)
.ok_or_else(|| "No audio stream found".to_string())?;
let stream_index = stream.index();
let time_base = f64::from(stream.time_base());
let stream_duration = stream.duration();
let ctx = ffmpeg_next::codec::context::Context::from_parameters(stream.parameters())
.map_err(|e| e.to_string())?;
let decoder = ctx.decoder().audio().map_err(|e| e.to_string())?;
(stream_index, time_base, stream_duration, decoder)
};
let sample_rate = decoder.rate();
let channels = decoder.channels() as u32;
let duration_secs = if stream_duration > 0 {
stream_duration as f64 * time_base
} else if input.get().duration() > 0 {
input.get().duration() as f64 / f64::from(ffmpeg_next::ffi::AV_TIME_BASE)
} else {
0.0
};
let total_frames = (duration_secs * sample_rate as f64).max(0.0) as u64;
Ok(Self {
input,
decoder,
resampler: None,
stream_index,
time_base,
sample_rate,
channels,
total_frames,
current_frame: 0,
pending_discard: 0,
align_to: None,
})
}
pub fn seek(&mut self, target_frame: u64) -> Result<u64, String> {
let seconds = target_frame as f64 / self.sample_rate.max(1) as f64;
let ts_av = (seconds * f64::from(ffmpeg_next::ffi::AV_TIME_BASE)) as i64;
// Seek to at-or-before the target (max_ts = ts_av) so we can decode
// forward to it exactly. ffmpeg-next's `seek` wants a bounded range.
self.input
.get()
.seek(ts_av, 0..(ts_av + 1))
.map_err(|e| format!("Seek failed: {}", e))?;
self.decoder.flush();
self.pending_discard = 0;
self.align_to = Some(target_frame);
self.current_frame = target_frame;
// We align to the exact frame below, so the effective position IS target.
Ok(target_frame)
}
pub fn decode_next(&mut self, out: &mut Vec<f32>) -> Result<usize, String> {
out.clear();
loop {
// Drain a decoded frame if one is ready.
let mut decoded = ffmpeg_next::frame::Audio::empty();
if self.decoder.receive_frame(&mut decoded).is_ok() {
self.ensure_layout(&mut decoded);
let n = self.emit(&decoded, out);
if n > 0 {
return Ok(n);
}
continue; // frame fully discarded by seek-alignment; keep going
}
// Read one packet (owned), releasing the `input` borrow before decoding.
let packet = self.input.get().packets().next().map(|(_, p)| p);
match packet {
Some(packet) => {
if packet.stream() == self.stream_index {
self.decoder
.send_packet(&packet)
.map_err(|e| e.to_string())?;
}
}
None => {
// EOF: flush and drain whatever remains.
let _ = self.decoder.send_eof();
let mut decoded = ffmpeg_next::frame::Audio::empty();
if self.decoder.receive_frame(&mut decoded).is_ok() {
self.ensure_layout(&mut decoded);
return Ok(self.emit(&decoded, out));
}
return Ok(0);
}
}
}
}
/// Decoders for some formats (e.g. raw mono WAV) leave the frame's channel
/// layout unset. The resampler needs a concrete layout that matches the
/// frame, so fill one in from the channel count when it's missing.
fn ensure_layout(&self, frame: &mut ffmpeg_next::frame::Audio) {
if frame.channel_layout().is_empty() {
frame.set_channel_layout(
ffmpeg_next::channel_layout::ChannelLayout::default(self.channels as i32),
);
}
}
/// Resample one decoded frame to interleaved f32, apply any pending
/// seek-alignment discard, append to `out`, return frames emitted.
fn emit(&mut self, frame: &ffmpeg_next::frame::Audio, out: &mut Vec<f32>) -> usize {
// `frame` already has a non-empty channel layout (set by `ensure_layout`
// before this call), so the resampler config and the actual frame agree
// — otherwise swr fails with AVERROR_INPUT_CHANGED.
if self.resampler.is_none() {
match ffmpeg_next::software::resampling::Context::get(
frame.format(),
frame.channel_layout(),
self.sample_rate,
ffmpeg_next::format::Sample::F32(ffmpeg_next::format::sample::Type::Packed),
frame.channel_layout(),
self.sample_rate,
) {
Ok(r) => self.resampler = Some(r),
Err(_) => return 0,
}
}
let mut resampled = ffmpeg_next::frame::Audio::empty();
if self
.resampler
.as_mut()
.unwrap()
.run(frame, &mut resampled)
.is_err()
{
return 0;
}
// The output is packed (interleaved) f32. Read it from the raw byte plane
// `data(0)` — its length is correct (`frames * channels * 4`), whereas
// `plane::<f32>(0)` is a known ffmpeg-next footgun that reports only
// `samples()` elements (ignoring channels) and would slice out of range
// for multi-channel audio.
let ch = self.channels.max(1) as usize;
let bytes = resampled.data(0);
let n_frames = (bytes.len() / 4) / ch;
if n_frames == 0 {
return 0;
}
// On the first frame after a seek, compute how many leading frames to
// drop so output begins exactly at the seek target.
if let Some(target) = self.align_to.take() {
let frame_start = self.pts_to_frame(frame.pts());
self.pending_discard = target.saturating_sub(frame_start);
}
let discard = (self.pending_discard.min(n_frames as u64)) as usize;
self.pending_discard -= discard as u64;
let start_byte = discard * ch * 4;
let end_byte = n_frames * ch * 4;
out.extend(
bytes[start_byte..end_byte]
.chunks_exact(4)
.map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])),
);
let emitted = n_frames - discard;
self.current_frame += emitted as u64;
emitted
}
/// Convert a stream PTS to an absolute audio frame index.
fn pts_to_frame(&self, pts: Option<i64>) -> u64 {
match pts {
Some(p) if p >= 0 => {
((p as f64 * self.time_base) * self.sample_rate as f64).round() as u64
}
_ => self.current_frame,
}
}
}
// ---------------------------------------------------------------------------
// StreamSource — dispatches the disk reader over either decoder backend.
// (Wired into the reader thread in a later step.)
// ---------------------------------------------------------------------------
/// Which decoder backend a streaming source uses.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SourceKind {
/// Symphonia, for compressed audio files (MP3, FLAC, OGG, …).
CompressedAudio,
/// FFmpeg, for the audio track of a video container.
VideoAudio,
}
/// A streaming audio source backing one active clip: either Symphonia
/// ([`CompressedReader`]) or FFmpeg ([`VideoAudioReader`]).
enum StreamSource {
Compressed(CompressedReader),
Video(VideoAudioReader),
}
impl StreamSource {
fn open(open: StreamOpen, kind: SourceKind) -> Result<Self, String> {
match (kind, open) {
(SourceKind::CompressedAudio, StreamOpen::Path(p)) => {
Ok(StreamSource::Compressed(CompressedReader::open(&p)?))
}
(SourceKind::CompressedAudio, StreamOpen::Source { src, ext }) => {
Ok(StreamSource::Compressed(CompressedReader::open_source(src, ext.as_deref())?))
}
(SourceKind::VideoAudio, StreamOpen::Path(p)) => {
Ok(StreamSource::Video(VideoAudioReader::open(&p)?))
}
(SourceKind::VideoAudio, StreamOpen::Source { src, ext }) => {
Ok(StreamSource::Video(VideoAudioReader::open_source(src, ext.as_deref())?))
}
}
}
fn sample_rate(&self) -> u32 {
match self {
StreamSource::Compressed(r) => r.sample_rate,
StreamSource::Video(r) => r.sample_rate,
}
}
fn channels(&self) -> u32 {
match self {
StreamSource::Compressed(r) => r.channels,
StreamSource::Video(r) => r.channels,
}
}
fn seek(&mut self, target_frame: u64) -> Result<u64, String> {
match self {
StreamSource::Compressed(r) => r.seek(target_frame),
StreamSource::Video(r) => r.seek(target_frame),
}
}
fn decode_next(&mut self, out: &mut Vec<f32>) -> Result<usize, String> {
match self {
StreamSource::Compressed(r) => r.decode_next(out),
StreamSource::Video(r) => r.decode_next(out),
}
}
fn total_frames(&self) -> u64 {
match self {
StreamSource::Compressed(r) => r.total_frames(),
StreamSource::Video(r) => r.total_frames(),
}
}
}
/// Decode a media source end-to-end and build its [`WaveformPyramid`] overview,
/// streaming — only one decode chunk plus the (bounded) pyramid are ever in
/// memory, never the full sample buffer. `floor_samples_per_texel` is the
/// finest-level resolution (see [`crate::audio::waveform_pyramid`]).
pub fn build_waveform_pyramid(
path: &Path,
kind: SourceKind,
floor_samples_per_texel: u32,
) -> Result<crate::audio::waveform_pyramid::WaveformPyramid, String> {
let src = StreamSource::open(StreamOpen::Path(path.to_path_buf()), kind)?;
build_pyramid_from_streamsource(src, floor_samples_per_texel)
}
/// Build a waveform pyramid from a host-provided byte source (container-packed
/// compressed audio) — the load-time counterpart of [`build_waveform_pyramid`]
/// for media that has no filesystem path.
pub fn build_waveform_pyramid_from_source(
src: Box<dyn MediaByteSource>,
ext: Option<&str>,
floor_samples_per_texel: u32,
) -> Result<crate::audio::waveform_pyramid::WaveformPyramid, String> {
let src = StreamSource::open(
StreamOpen::Source { src, ext: ext.map(|s| s.to_string()) },
SourceKind::CompressedAudio,
)?;
build_pyramid_from_streamsource(src, floor_samples_per_texel)
}
fn build_pyramid_from_streamsource(
mut src: StreamSource,
floor_samples_per_texel: u32,
) -> Result<crate::audio::waveform_pyramid::WaveformPyramid, String> {
use crate::audio::waveform_pyramid::WaveformPyramidBuilder;
let channels = src.channels();
let mut builder = WaveformPyramidBuilder::new(channels, floor_samples_per_texel);
builder.reserve_for_frames(src.total_frames());
let mut buf = Vec::new();
loop {
let frames = src.decode_next(&mut buf)?;
if frames == 0 {
break;
}
builder.push_interleaved(&buf);
}
Ok(builder.finish())
}
// ---------------------------------------------------------------------------
// DiskReaderCommand
// ---------------------------------------------------------------------------
/// Commands sent from the engine to the disk reader thread.
pub enum DiskReaderCommand {
/// Start streaming a compressed file for a clip instance.
/// Start streaming a file for a clip instance, using the decoder backend
/// selected by `kind` (compressed audio vs. a video's audio track). `open`
/// is either a filesystem path (referenced media / video) or a host-provided
/// byte stream (container-packed media).
ActivateFile {
reader_id: u64,
path: PathBuf,
open: StreamOpen,
kind: SourceKind,
buffer: Arc<ReadAheadBuffer>,
},
/// Stop streaming for a clip instance.
@@ -529,7 +1071,7 @@ impl DiskReader {
mut command_rx: rtrb::Consumer<DiskReaderCommand>,
running: Arc<AtomicBool>,
) {
let mut active_files: HashMap<u64, (CompressedReader, Arc<ReadAheadBuffer>)> =
let mut active_files: HashMap<u64, (StreamSource, Arc<ReadAheadBuffer>)> =
HashMap::new();
let mut decode_buf = Vec::with_capacity(8192);
@@ -539,18 +1081,19 @@ impl DiskReader {
match cmd {
DiskReaderCommand::ActivateFile {
reader_id,
path,
open,
kind,
buffer,
} => match CompressedReader::open(&path) {
} => match StreamSource::open(open, kind) {
Ok(reader) => {
eprintln!("[DiskReader] Activated reader={}, ch={}, sr={}, path={:?}",
reader_id, reader.channels, reader.sample_rate, path);
eprintln!("[DiskReader] Activated reader={}, kind={:?}, ch={}, sr={}",
reader_id, kind, reader.channels(), reader.sample_rate());
active_files.insert(reader_id, (reader, buffer));
}
Err(e) => {
eprintln!(
"[DiskReader] Failed to open compressed file {:?}: {}",
path, e
"[DiskReader] Failed to open reader={} ({:?}): {}",
reader_id, kind, e
);
}
},
@@ -588,7 +1131,7 @@ impl DiskReader {
// If the target has jumped behind or far ahead of the buffer,
// seek the decoder and reset.
if target < buf_start || target > buf_end + reader.sample_rate as u64 {
if target < buf_start || target > buf_end + reader.sample_rate() as u64 {
buffer.reset(target);
let _ = reader.seek(target);
continue;
@@ -607,7 +1150,7 @@ impl DiskReader {
let buf_valid = buffer.valid_frames_count();
let buf_end = buf_start + buf_valid;
let prefetch_target =
target + (PREFETCH_SECONDS * reader.sample_rate as f64) as u64;
target + (PREFETCH_SECONDS * reader.sample_rate() as f64) as u64;
if buf_end >= prefetch_target {
continue; // Already filled far enough ahead.
@@ -615,7 +1158,12 @@ impl DiskReader {
// Decode more data into the buffer.
match reader.decode_next(&mut decode_buf) {
Ok(0) => {} // EOF
Ok(0) => {
// EOF: no more frames will be decoded for this buffer until a
// seek. Tell export-mode waiters so they stop blocking on
// past-the-end frames (e.g. video longer than its audio).
buffer.set_finished(true);
}
Ok(frames) => {
let was_empty = buffer.valid_frames_count() == 0;
buffer.write_samples(&decode_buf, frames);
@@ -649,3 +1197,7 @@ impl Drop for DiskReader {
}
}
}
// Tests for VideoAudioReader live in `daw-backend/tests/video_audio_stream.rs`
// (integration tests) so they build the lib in normal mode, independent of
// pre-existing breakage in the crate's `#[cfg(test)]` unit tests (automation.rs).
File diff suppressed because it is too large Load Diff
+307 -59
View File
@@ -2,6 +2,8 @@ use super::buffer_pool::BufferPool;
use super::pool::AudioPool;
use super::project::Project;
use crate::command::AudioEvent;
use crate::tempo_map::TempoMap;
use crate::time::Seconds;
use std::path::Path;
/// Render chunk size for offline export. Matches the real-time playback buffer size
@@ -42,10 +44,16 @@ pub struct ExportSettings {
pub bit_depth: u16,
/// MP3 bitrate in kbps (128, 192, 256, 320)
pub mp3_bitrate: u32,
/// Start time in seconds
pub start_time: f64,
/// End time in seconds
pub end_time: f64,
/// Start time
pub start_time: Seconds,
/// End time
pub end_time: Seconds,
/// Tempo map for beat-position scheduling
pub tempo_map: TempoMap,
/// Tag metadata as (ffmpeg-key, value) pairs (e.g. ("title", "…"), ("artist", "…")). Written to
/// the container's native tags: ID3v2 (MP3), MP4 atoms (M4A), Vorbis comments (FLAC), RIFF INFO
/// (WAV). Empty = no tags.
pub metadata: Vec<(String, String)>,
}
impl Default for ExportSettings {
@@ -56,12 +64,29 @@ impl Default for ExportSettings {
channels: 2,
bit_depth: 16,
mp3_bitrate: 320,
start_time: 0.0,
end_time: 60.0,
start_time: Seconds::ZERO,
end_time: Seconds(60.0),
tempo_map: TempoMap::constant(120.0),
metadata: Vec::new(),
}
}
}
/// Set tag metadata on an ffmpeg output context (before `write_header`). FFmpeg maps the standard
/// keys to each container's native tags.
fn apply_metadata(output: &mut ffmpeg_next::format::context::Output, metadata: &[(String, String)]) {
if metadata.is_empty() {
return;
}
let mut dict = ffmpeg_next::Dictionary::new();
for (k, v) in metadata {
if !v.is_empty() {
dict.set(k, v);
}
}
output.set_metadata(dict);
}
/// Export the project to an audio file
///
/// This performs offline rendering, processing the entire timeline
@@ -79,15 +104,15 @@ pub fn export_audio<P: AsRef<Path>>(
{
// Validate duration
let duration = settings.end_time - settings.start_time;
if duration <= 0.0 {
if duration <= Seconds::ZERO {
return Err(format!(
"Export duration is zero or negative (start={:.3}s, end={:.3}s). \
Check that the timeline has content.",
settings.start_time, settings.end_time
settings.start_time.seconds_to_f64(), settings.end_time.seconds_to_f64()
));
}
let total_frames = (duration * settings.sample_rate as f64).round() as usize;
let total_frames = (duration.seconds_to_f64() * settings.sample_rate as f64).round() as usize;
if total_frames == 0 {
return Err("Export would produce zero audio frames".to_string());
}
@@ -103,17 +128,21 @@ pub fn export_audio<P: AsRef<Path>>(
// Route to appropriate export implementation based on format.
// Ensure export mode is disabled even if an error occurs.
let result = match settings.format {
ExportFormat::Wav | ExportFormat::Flac => {
ExportFormat::Wav => {
let samples = render_to_memory(project, pool, settings, event_tx.as_mut().map(|tx| &mut **tx))?;
// Signal that rendering is done and we're now writing the file
if let Some(ref mut tx) = event_tx {
let _ = tx.push(AudioEvent::ExportFinalizing);
}
match settings.format {
ExportFormat::Wav => write_wav(&samples, settings, &output_path),
ExportFormat::Flac => write_flac(&samples, settings, &output_path),
_ => unreachable!(),
write_wav(&samples, settings, &output_path)
// hound writes no metadata; append a RIFF INFO chunk for tags.
.and_then(|_| append_wav_info_chunk(output_path.as_ref(), &settings.metadata))
}
ExportFormat::Flac => {
let samples = render_to_memory(project, pool, settings, event_tx.as_mut().map(|tx| &mut **tx))?;
if let Some(ref mut tx) = event_tx {
let _ = tx.push(AudioEvent::ExportFinalizing);
}
export_flac(&samples, settings, &output_path)
}
ExportFormat::Mp3 => {
export_mp3(project, pool, settings, output_path, event_tx)
@@ -148,11 +177,11 @@ pub fn render_to_memory(
{
// Calculate total number of frames
let duration = settings.end_time - settings.start_time;
let total_frames = (duration * settings.sample_rate as f64).round() as usize;
let total_frames = (duration.seconds_to_f64() * settings.sample_rate as f64).round() as usize;
let total_samples = total_frames * settings.channels as usize;
println!("Export: duration={:.3}s, total_frames={}, total_samples={}, channels={}",
duration, total_frames, total_samples, settings.channels);
duration.seconds_to_f64(), total_frames, total_samples, settings.channels);
let chunk_samples = EXPORT_CHUNK_FRAMES * settings.channels as usize;
@@ -178,15 +207,18 @@ pub fn render_to_memory(
pool,
&mut buffer_pool,
playhead,
&settings.tempo_map,
settings.sample_rate,
settings.channels,
false,
None, // export never runs with a recording in flight
);
// Calculate how many samples we actually need from this chunk
let remaining_time = settings.end_time - playhead;
let samples_needed = if remaining_time < chunk_duration {
let samples_needed = if remaining_time.seconds_to_f64() < chunk_duration {
// Calculate frames needed and ensure it's a whole number
let frames_needed = (remaining_time * settings.sample_rate as f64).round() as usize;
let frames_needed = (remaining_time.seconds_to_f64() * settings.sample_rate as f64).round() as usize;
let samples = frames_needed * settings.channels as usize;
// Ensure we don't exceed chunk size
samples.min(chunk_samples)
@@ -206,7 +238,7 @@ pub fn render_to_memory(
});
}
playhead += chunk_duration;
playhead = playhead + Seconds(chunk_duration);
}
println!("Export: rendered {} samples total", all_samples.len());
@@ -266,48 +298,174 @@ fn write_wav<P: AsRef<Path>>(
Ok(())
}
/// Write FLAC file using hound (FLAC is essentially lossless WAV)
fn write_flac<P: AsRef<Path>>(
/// Export real FLAC via ffmpeg from already-rendered interleaved f32 samples (Vorbis-comment
/// metadata). Replaces the former `write_flac`, which wrote WAV bytes to a `.flac` file. 16-bit
/// uses S16; 24-bit uses S32 (ffmpeg's flac encoder emits `bits_per_raw_sample = 24` for S32,
/// taking the top 24 bits).
fn export_flac<P: AsRef<Path>>(
samples: &[f32],
settings: &ExportSettings,
output_path: P,
) -> Result<(), String> {
// For now, we'll use hound to write a WAV-like FLAC file
// In the future, we could use a dedicated FLAC encoder
let spec = hound::WavSpec {
channels: settings.channels as u16,
sample_rate: settings.sample_rate,
bits_per_sample: settings.bit_depth,
sample_format: hound::SampleFormat::Int,
use ffmpeg_next as ffmpeg;
ffmpeg::init().map_err(|e| format!("Failed to initialize FFmpeg: {}", e))?;
let codec = ffmpeg::encoder::find(ffmpeg::codec::Id::FLAC)
.ok_or("FLAC encoder not found in this ffmpeg build")?;
let mut output = ffmpeg::format::output(&output_path)
.map_err(|e| format!("Failed to create output file: {}", e))?;
let channel_layout = match settings.channels {
1 => ffmpeg::channel_layout::ChannelLayout::MONO,
2 => ffmpeg::channel_layout::ChannelLayout::STEREO,
_ => return Err(format!("Unsupported channel count: {}", settings.channels)),
};
let mut writer = hound::WavWriter::create(output_path, spec)
.map_err(|e| format!("Failed to create FLAC file: {}", e))?;
// FLAC accepts packed S16 or S32; S32 → 24-bit output.
let use_24 = settings.bit_depth >= 24;
let sample_fmt = if use_24 {
ffmpeg::format::Sample::I32(ffmpeg::format::sample::Type::Packed)
} else {
ffmpeg::format::Sample::I16(ffmpeg::format::sample::Type::Packed)
};
// Write samples (same as WAV for now)
match settings.bit_depth {
16 => {
for &sample in samples {
let clamped = sample.max(-1.0).min(1.0);
let pcm_value = (clamped * 32767.0) as i16;
writer.write_sample(pcm_value)
.map_err(|e| format!("Failed to write sample: {}", e))?;
let mut encoder = ffmpeg::codec::Context::new_with_codec(codec)
.encoder()
.audio()
.map_err(|e| format!("Failed to create FLAC encoder: {}", e))?;
encoder.set_rate(settings.sample_rate as i32);
encoder.set_channel_layout(channel_layout);
encoder.set_format(sample_fmt);
encoder.set_time_base(ffmpeg::Rational(1, settings.sample_rate as i32));
let mut encoder = encoder.open_as(codec)
.map_err(|e| format!("Failed to open FLAC encoder: {}", e))?;
{
let mut stream = output.add_stream(codec)
.map_err(|e| format!("Failed to add stream: {}", e))?;
stream.set_parameters(&encoder);
}
apply_metadata(&mut output, &settings.metadata);
output.write_header()
.map_err(|e| format!("Failed to write FLAC header: {}", e))?;
let channels = settings.channels as usize;
let num_frames = samples.len() / channels;
let frame_size = if encoder.frame_size() > 0 { encoder.frame_size() as usize } else { 4096 };
let mut done = 0usize;
while done < num_frames {
let n = (num_frames - done).min(frame_size);
let mut frame = ffmpeg::frame::Audio::new(sample_fmt, n, channel_layout);
frame.set_rate(settings.sample_rate);
frame.set_pts(Some(done as i64)); // samples; the FLAC muxer requires PTS
let buf = frame.data_mut(0); // packed interleaved → plane 0
let base = done * channels;
if use_24 {
for i in 0..n * channels {
let s = samples[base + i].clamp(-1.0, 1.0);
let v = (s as f64 * 2_147_483_647.0) as i32; // full-scale S32; encoder takes top 24
buf[i * 4..i * 4 + 4].copy_from_slice(&v.to_le_bytes());
}
} else {
for i in 0..n * channels {
let s = samples[base + i].clamp(-1.0, 1.0);
let v = (s * 32767.0) as i16;
buf[i * 2..i * 2 + 2].copy_from_slice(&v.to_le_bytes());
}
}
24 => {
for &sample in samples {
let clamped = sample.max(-1.0).min(1.0);
let pcm_value = (clamped * 8388607.0) as i32;
writer.write_sample(pcm_value)
.map_err(|e| format!("Failed to write sample: {}", e))?;
}
encoder.send_frame(&frame).map_err(|e| format!("Failed to send FLAC frame: {}", e))?;
flac_write_packets(&mut encoder, &mut output)?;
done += n;
}
encoder.send_eof().map_err(|e| format!("Failed to flush FLAC encoder: {}", e))?;
flac_write_packets(&mut encoder, &mut output)?;
output.write_trailer().map_err(|e| format!("Failed to finalize FLAC: {}", e))?;
Ok(())
}
/// Drain encoded FLAC packets and write them (non-interleaved). Skips the trailing empty flush
/// packet, which the FLAC muxer otherwise rejects as "Invalid data". Rescales packet ts from the
/// encoder time base to the stream's.
fn flac_write_packets(
encoder: &mut ffmpeg_next::encoder::Audio,
output: &mut ffmpeg_next::format::context::Output,
) -> Result<(), String> {
let mut pkt = ffmpeg_next::Packet::empty();
let enc_tb = encoder.time_base();
let stream_tb = output.stream(0).map(|s| s.time_base()).unwrap_or(enc_tb);
while encoder.receive_packet(&mut pkt).is_ok() {
if pkt.size() == 0 {
continue;
}
_ => return Err(format!("Unsupported bit depth: {}", settings.bit_depth)),
pkt.set_stream(0);
pkt.rescale_ts(enc_tb, stream_tb);
pkt.write(output).map_err(|e| format!("Failed to write FLAC packet: {}", e))?;
}
Ok(())
}
/// Append a RIFF `LIST`/`INFO` metadata chunk to a finished WAV file (hound writes no tags), then
/// fix up the top-level RIFF size. Maps ffmpeg-style keys to RIFF INFO sub-chunk IDs. Trailing INFO
/// chunks are ignored by players that don't read them.
fn append_wav_info_chunk(path: &Path, metadata: &[(String, String)]) -> Result<(), String> {
use std::io::{Seek, SeekFrom, Write};
let riff_id = |key: &str| -> Option<&'static [u8; 4]> {
match key {
"title" => Some(b"INAM"),
"artist" => Some(b"IART"),
"album" => Some(b"IPRD"),
"genre" => Some(b"IGNR"),
"comment" => Some(b"ICMT"),
"date" => Some(b"ICRD"),
"track" => Some(b"ITRK"),
_ => None,
}
};
let mut info: Vec<u8> = Vec::new();
info.extend_from_slice(b"INFO");
for (key, val) in metadata {
if val.is_empty() {
continue;
}
let Some(id) = riff_id(key) else { continue };
let mut bytes = val.as_bytes().to_vec();
bytes.push(0); // NUL-terminate
if bytes.len() % 2 == 1 {
bytes.push(0); // pad to even
}
info.extend_from_slice(id);
info.extend_from_slice(&(bytes.len() as u32).to_le_bytes());
info.extend_from_slice(&bytes);
}
if info.len() <= 4 {
return Ok(()); // nothing but the "INFO" tag
}
writer.finalize()
.map_err(|e| format!("Failed to finalize FLAC file: {}", e))?;
let mut list: Vec<u8> = Vec::with_capacity(info.len() + 8);
list.extend_from_slice(b"LIST");
list.extend_from_slice(&(info.len() as u32).to_le_bytes());
list.extend_from_slice(&info);
let mut f = std::fs::OpenOptions::new()
.read(true)
.write(true)
.open(path)
.map_err(|e| format!("Failed to open WAV for tagging: {}", e))?;
let end = f.seek(SeekFrom::End(0)).map_err(|e| e.to_string())?;
if end % 2 == 1 {
f.write_all(&[0]).map_err(|e| e.to_string())?;
}
f.write_all(&list).map_err(|e| format!("Failed to write WAV tags: {}", e))?;
let new_len = f.seek(SeekFrom::End(0)).map_err(|e| e.to_string())?;
f.seek(SeekFrom::Start(4)).map_err(|e| e.to_string())?;
f.write_all(&((new_len - 8) as u32).to_le_bytes())
.map_err(|e| format!("Failed to update RIFF size: {}", e))?;
Ok(())
}
@@ -355,12 +513,13 @@ fn export_mp3<P: AsRef<Path>>(
stream.set_parameters(&encoder);
}
apply_metadata(&mut output, &settings.metadata);
output.write_header()
.map_err(|e| format!("Failed to write header: {}", e))?;
// Calculate rendering parameters
let duration = settings.end_time - settings.start_time;
let total_frames = (duration * settings.sample_rate as f64).round() as usize;
let total_frames = (duration.seconds_to_f64() * settings.sample_rate as f64).round() as usize;
let chunk_samples = EXPORT_CHUNK_FRAMES * settings.channels as usize;
let chunk_duration = EXPORT_CHUNK_FRAMES as f64 / settings.sample_rate as f64;
@@ -395,14 +554,17 @@ fn export_mp3<P: AsRef<Path>>(
pool,
&mut buffer_pool,
playhead,
&settings.tempo_map,
settings.sample_rate,
settings.channels,
false,
None, // export never runs with a recording in flight
);
// Calculate how many samples we need from this chunk
let remaining_time = settings.end_time - playhead;
let samples_needed = if remaining_time < chunk_duration {
((remaining_time * settings.sample_rate as f64) as usize * settings.channels as usize)
let samples_needed = if remaining_time.seconds_to_f64() < chunk_duration {
((remaining_time.seconds_to_f64() * settings.sample_rate as f64) as usize * settings.channels as usize)
.min(chunk_samples)
} else {
chunk_samples
@@ -443,7 +605,7 @@ fn export_mp3<P: AsRef<Path>>(
}
}
playhead += chunk_duration;
playhead = playhead + Seconds(chunk_duration);
}
// Encode any remaining samples as the final frame
@@ -522,12 +684,13 @@ fn export_aac<P: AsRef<Path>>(
stream.set_parameters(&encoder);
}
apply_metadata(&mut output, &settings.metadata);
output.write_header()
.map_err(|e| format!("Failed to write header: {}", e))?;
// Calculate rendering parameters
let duration = settings.end_time - settings.start_time;
let total_frames = (duration * settings.sample_rate as f64).round() as usize;
let total_frames = (duration.seconds_to_f64() * settings.sample_rate as f64).round() as usize;
let chunk_samples = EXPORT_CHUNK_FRAMES * settings.channels as usize;
let chunk_duration = EXPORT_CHUNK_FRAMES as f64 / settings.sample_rate as f64;
@@ -562,14 +725,17 @@ fn export_aac<P: AsRef<Path>>(
pool,
&mut buffer_pool,
playhead,
&settings.tempo_map,
settings.sample_rate,
settings.channels,
false,
None, // export never runs with a recording in flight
);
// Calculate how many samples we need from this chunk
let remaining_time = settings.end_time - playhead;
let samples_needed = if remaining_time < chunk_duration {
((remaining_time * settings.sample_rate as f64) as usize * settings.channels as usize)
let samples_needed = if remaining_time.seconds_to_f64() < chunk_duration {
((remaining_time.seconds_to_f64() * settings.sample_rate as f64) as usize * settings.channels as usize)
.min(chunk_samples)
} else {
chunk_samples
@@ -610,7 +776,7 @@ fn export_aac<P: AsRef<Path>>(
}
}
playhead += chunk_duration;
playhead = playhead + Seconds(chunk_duration);
}
// Encode any remaining samples as the final frame
@@ -660,14 +826,39 @@ fn convert_chunk_to_planar_i16(interleaved: &[f32], channels: u32) -> Vec<Vec<i1
planar
}
/// Convert a chunk of interleaved f32 samples to planar f32 format
/// Convert a chunk of interleaved f32 samples to planar f32 format.
///
/// Non-finite samples (NaN/±Inf) are replaced with `0.0` and finite samples are
/// clamped to `[-1.0, 1.0]`: the float encoders (e.g. AAC, which takes `fltp`)
/// reject a frame outright on "(near) NaN/+-Inf", failing the whole export, so we
/// sanitize here exactly as the integer paths already clamp.
fn convert_chunk_to_planar_f32(interleaved: &[f32], channels: u32) -> Vec<Vec<f32>> {
let num_frames = interleaved.len() / channels as usize;
let mut planar = vec![vec![0.0f32; num_frames]; channels as usize];
let mut non_finite = 0u64;
for (i, chunk) in interleaved.chunks(channels as usize).enumerate() {
for (ch, &sample) in chunk.iter().enumerate() {
planar[ch][i] = sample;
planar[ch][i] = if sample.is_finite() {
sample.clamp(-1.0, 1.0)
} else {
non_finite += 1;
0.0
};
}
}
if non_finite > 0 {
// One-time warning: we sanitized rather than failed, but a non-finite
// sample reaching here means something upstream (an effect, automation,
// or a source decode) produced NaN/Inf — worth chasing if audio is wrong.
use std::sync::atomic::{AtomicBool, Ordering};
static WARNED: AtomicBool = AtomicBool::new(false);
if !WARNED.swap(true, Ordering::Relaxed) {
eprintln!(
"⚠️ [EXPORT] sanitized {} non-finite (NaN/Inf) audio sample(s) in a chunk — \
check effects/automation/source decode",
non_finite
);
}
}
@@ -802,4 +993,61 @@ mod tests {
assert_eq!(ExportFormat::Wav.extension(), "wav");
assert_eq!(ExportFormat::Flac.extension(), "flac");
}
fn tagged_settings(format: ExportFormat) -> ExportSettings {
ExportSettings {
format,
sample_rate: 48000,
channels: 2,
bit_depth: 24,
mp3_bitrate: 192,
start_time: Seconds::ZERO,
end_time: Seconds(0.2), // tiny render
tempo_map: TempoMap::constant(120.0),
metadata: vec![
("title".to_string(), "Test Title".to_string()),
("artist".to_string(), "Test Artist".to_string()),
],
}
}
/// FLAC export must be a real FLAC container (not WAV bytes) carrying Vorbis-comment tags.
#[test]
fn flac_export_is_real_flac_with_tags() {
let settings = tagged_settings(ExportFormat::Flac);
let mut project = Project::new(48000);
let pool = AudioPool::new();
let path = std::env::temp_dir().join("lb_be_flac_test.flac");
export_audio(&mut project, &pool, &settings, &path, None).expect("FLAC export failed");
let bytes = std::fs::read(&path).unwrap();
assert_eq!(&bytes[0..4], b"fLaC", "not real FLAC (got {:?})", &bytes[0..4]);
let s = String::from_utf8_lossy(&bytes);
assert!(s.contains("Test Title"), "title tag missing from FLAC");
assert!(s.contains("Test Artist"), "artist tag missing from FLAC");
std::fs::remove_file(&path).ok();
}
/// WAV export keeps a valid RIFF container and gains a LIST/INFO tag chunk with a fixed-up size.
#[test]
fn wav_export_has_info_chunk() {
let settings = tagged_settings(ExportFormat::Wav);
let mut project = Project::new(48000);
let pool = AudioPool::new();
let path = std::env::temp_dir().join("lb_be_wav_test.wav");
export_audio(&mut project, &pool, &settings, &path, None).expect("WAV export failed");
let bytes = std::fs::read(&path).unwrap();
assert_eq!(&bytes[0..4], b"RIFF");
assert_eq!(&bytes[8..12], b"WAVE");
let riff_size = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]) as usize;
assert_eq!(riff_size, bytes.len() - 8, "RIFF size not fixed up after tagging");
let s = String::from_utf8_lossy(&bytes);
assert!(s.contains("LIST") && s.contains("INFO") && s.contains("INAM"),
"no RIFF INFO chunk");
assert!(s.contains("Test Title"), "title not in WAV INFO chunk");
std::fs::remove_file(&path).ok();
}
}
+13 -20
View File
@@ -90,8 +90,9 @@ impl Metronome {
self.last_beat = -1; // Reset beat tracking when disabled
self.click_position = 0; // Stop any playing click
} else {
// When enabling, don't trigger a click until the next beat
self.click_position = usize::MAX; // Set to max to prevent immediate click
// Reset beat tracking so the next beat boundary (including beat 0) fires a click
self.last_beat = -1;
self.click_position = self.high_click.len(); // Idle (past end, nothing playing)
}
}
@@ -106,7 +107,7 @@ impl Metronome {
pub fn process(
&mut self,
output: &mut [f32],
playhead_samples: u64,
playhead_samples: i64,
playing: bool,
sample_rate: u32,
channels: u32,
@@ -119,31 +120,23 @@ impl Metronome {
let frames = output.len() / channels as usize;
for frame in 0..frames {
let current_sample = playhead_samples + frame as u64;
let current_sample = playhead_samples + frame as i64;
// Calculate current beat number
let current_time_seconds = current_sample as f64 / sample_rate as f64;
let beats_per_second = self.bpm as f64 / 60.0;
let current_beat = (current_time_seconds * beats_per_second).floor() as i64;
// Check if we crossed a beat boundary
if current_beat != self.last_beat && current_beat >= 0 {
// Check if we crossed a beat boundary (including negative beats during count-in pre-roll)
if current_beat != self.last_beat {
self.last_beat = current_beat;
// Only trigger a click if we're not in the "just enabled" state
if self.click_position != usize::MAX {
// Determine which click to play
// Beat 1 of each measure gets the accent (high click)
let beat_in_measure = (current_beat as u32 % self.time_signature_numerator) as usize;
let is_first_beat = beat_in_measure == 0;
// Start playing the appropriate click
self.playing_high_click = is_first_beat;
self.click_position = 0; // Start from beginning of click
} else {
// We just got enabled - reset position but don't play yet
self.click_position = self.high_click.len(); // Set past end so no click plays
}
// Determine which click to play.
// Beat 0 of each measure gets the accent (high click).
// Use rem_euclid so negative beat numbers map correctly (e.g. -4 % 4 = 0).
let beat_in_measure = current_beat.rem_euclid(self.time_signature_numerator as i64) as usize;
self.playing_high_click = beat_in_measure == 0;
self.click_position = 0; // Start from beginning of click
}
// Continue playing click sample if we're currently in one
+57 -149
View File
@@ -1,8 +1,10 @@
use crate::time::Beats;
/// MIDI event representing a single MIDI message
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
pub struct MidiEvent {
/// Time position within the clip in seconds (sample-rate independent)
pub timestamp: f64,
/// Time position in beats (quarter-note beats)
pub timestamp: Beats,
/// MIDI status byte (includes channel)
pub status: u8,
/// First data byte (note number, CC number, etc.)
@@ -12,55 +14,28 @@ pub struct MidiEvent {
}
impl MidiEvent {
/// Create a new MIDI event
pub fn new(timestamp: f64, status: u8, data1: u8, data2: u8) -> Self {
Self {
timestamp,
status,
data1,
data2,
}
pub fn new(timestamp: Beats, status: u8, data1: u8, data2: u8) -> Self {
Self { timestamp, status, data1, data2 }
}
/// Create a note on event
pub fn note_on(timestamp: f64, channel: u8, note: u8, velocity: u8) -> Self {
Self {
timestamp,
status: 0x90 | (channel & 0x0F),
data1: note,
data2: velocity,
}
pub fn note_on(timestamp: Beats, channel: u8, note: u8, velocity: u8) -> Self {
Self { timestamp, status: 0x90 | (channel & 0x0F), data1: note, data2: velocity }
}
/// Create a note off event
pub fn note_off(timestamp: f64, channel: u8, note: u8, velocity: u8) -> Self {
Self {
timestamp,
status: 0x80 | (channel & 0x0F),
data1: note,
data2: velocity,
}
pub fn note_off(timestamp: Beats, channel: u8, note: u8, velocity: u8) -> Self {
Self { timestamp, status: 0x80 | (channel & 0x0F), data1: note, data2: velocity }
}
/// Check if this is a note on event (with non-zero velocity)
pub fn is_note_on(&self) -> bool {
(self.status & 0xF0) == 0x90 && self.data2 > 0
}
/// Check if this is a note off event (or note on with zero velocity)
pub fn is_note_off(&self) -> bool {
(self.status & 0xF0) == 0x80 || ((self.status & 0xF0) == 0x90 && self.data2 == 0)
}
/// Get the MIDI channel (0-15)
pub fn channel(&self) -> u8 {
self.status & 0x0F
}
/// Get the message type (upper 4 bits of status)
pub fn message_type(&self) -> u8 {
self.status & 0xF0
}
pub fn channel(&self) -> u8 { self.status & 0x0F }
pub fn message_type(&self) -> u8 { self.status & 0xF0 }
}
/// MIDI clip ID type (for clips stored in the pool)
@@ -69,179 +44,118 @@ pub type MidiClipId = u32;
/// MIDI clip instance ID type (for instances placed on tracks)
pub type MidiClipInstanceId = u32;
/// MIDI clip content - stores the actual MIDI events
///
/// This represents the content data stored in the MidiClipPool.
/// Events have timestamps relative to the start of the clip (0.0 = clip beginning).
/// MIDI clip content — stores the actual MIDI events.
/// `duration` is in beats.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct MidiClip {
pub id: MidiClipId,
pub events: Vec<MidiEvent>,
pub duration: f64, // Total content duration in seconds
/// Total content duration in beats
pub duration: Beats,
pub name: String,
}
impl MidiClip {
/// Create a new MIDI clip with content
pub fn new(id: MidiClipId, events: Vec<MidiEvent>, duration: f64, name: String) -> Self {
let mut clip = Self {
id,
events,
duration,
name,
};
// Sort events by timestamp
pub fn new(id: MidiClipId, events: Vec<MidiEvent>, duration: Beats, name: String) -> Self {
let mut clip = Self { id, events, duration, name };
clip.events.sort_by(|a, b| a.timestamp.partial_cmp(&b.timestamp).unwrap());
clip
}
/// Create an empty MIDI clip
pub fn empty(id: MidiClipId, duration: f64, name: String) -> Self {
Self {
id,
events: Vec::new(),
duration,
name,
}
pub fn empty(id: MidiClipId, duration: Beats, name: String) -> Self {
Self { id, events: Vec::new(), duration, name }
}
/// Add a MIDI event to the clip
pub fn add_event(&mut self, event: MidiEvent) {
self.events.push(event);
// Keep events sorted by timestamp
self.events.sort_by(|a, b| a.timestamp.partial_cmp(&b.timestamp).unwrap());
}
/// Get events within a time range (relative to clip start)
/// This is used by MidiClipInstance to fetch events for a given portion
pub fn get_events_in_range(&self, start: f64, end: f64) -> Vec<MidiEvent> {
self.events
.iter()
/// Get events within a beat range (relative to clip start)
pub fn get_events_in_range(&self, start: Beats, end: Beats) -> Vec<MidiEvent> {
self.events.iter()
.filter(|e| e.timestamp >= start && e.timestamp < end)
.copied()
.collect()
}
}
/// MIDI clip instance - a reference to MidiClip content with timeline positioning
/// MIDI clip instance — a reference to MidiClip content with timeline positioning.
///
/// ## Timing Model
/// - `internal_start` / `internal_end`: Define the region of the source clip to play (trimming)
/// - `external_start` / `external_duration`: Define where the instance appears on the timeline and how long
///
/// ## Looping
/// If `external_duration` is greater than `internal_end - internal_start`,
/// the instance will seamlessly loop back to `internal_start` when it reaches `internal_end`.
/// All timing fields are in beats.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct MidiClipInstance {
pub id: MidiClipInstanceId,
pub clip_id: MidiClipId, // Reference to MidiClip in pool
pub clip_id: MidiClipId,
/// Start position within the clip content (seconds)
pub internal_start: f64,
/// End position within the clip content (seconds)
pub internal_end: f64,
/// Start of the trimmed region within the clip content (beats)
pub internal_start: Beats,
/// End of the trimmed region within the clip content (beats)
pub internal_end: Beats,
/// Start position on the timeline (seconds)
pub external_start: f64,
/// Duration on the timeline (seconds) - can be longer than internal duration for looping
pub external_duration: f64,
/// Start position on the timeline (beats)
pub external_start: Beats,
/// Duration on the timeline (beats); > internal duration = looping
pub external_duration: Beats,
}
impl MidiClipInstance {
/// Create a new MIDI clip instance
pub fn new(
id: MidiClipInstanceId,
clip_id: MidiClipId,
internal_start: f64,
internal_end: f64,
external_start: f64,
external_duration: f64,
internal_start: Beats,
internal_end: Beats,
external_start: Beats,
external_duration: Beats,
) -> Self {
Self {
id,
clip_id,
internal_start,
internal_end,
external_start,
external_duration,
}
Self { id, clip_id, internal_start, internal_end, external_start, external_duration }
}
/// Create an instance that uses the full clip content (no trimming, no looping)
/// Create an instance covering the full clip with no trim
pub fn from_full_clip(
id: MidiClipInstanceId,
clip_id: MidiClipId,
clip_duration: f64,
external_start: f64,
clip_duration: Beats,
external_start: Beats,
) -> Self {
Self {
id,
clip_id,
internal_start: 0.0,
internal_start: Beats::ZERO,
internal_end: clip_duration,
external_start,
external_duration: clip_duration,
}
}
/// Get the internal (content) duration
pub fn internal_duration(&self) -> f64 {
self.internal_end - self.internal_start
}
pub fn internal_duration(&self) -> Beats { self.internal_end - self.internal_start }
pub fn external_end(&self) -> Beats { self.external_start + self.external_duration }
pub fn is_looping(&self) -> bool { self.external_duration > self.internal_duration() }
/// Get the end time on the timeline
pub fn external_end(&self) -> f64 {
self.external_start + self.external_duration
}
/// Check if this instance loops
pub fn is_looping(&self) -> bool {
self.external_duration > self.internal_duration()
}
/// Get the end time on the timeline (for backwards compatibility)
pub fn end_time(&self) -> f64 {
self.external_end()
}
/// Get the start time on the timeline (for backwards compatibility)
pub fn start_time(&self) -> f64 {
self.external_start
}
/// Check if this instance overlaps with a time range
pub fn overlaps_range(&self, range_start: f64, range_end: f64) -> bool {
/// Check if this instance overlaps with a beat range
pub fn overlaps_range(&self, range_start: Beats, range_end: Beats) -> bool {
self.external_start < range_end && self.external_end() > range_start
}
/// Get events that should be triggered in a given timeline range
///
/// This handles:
/// - Trimming (internal_start/internal_end)
/// - Looping (when external duration > internal duration)
/// - Time mapping from timeline to clip content
///
/// Returns events with timestamps adjusted to timeline time (not clip-relative)
/// Get events that should fire in a given beat range on the timeline.
/// Returns events with `timestamp` set to their global timeline beat position.
pub fn get_events_in_range(
&self,
clip: &MidiClip,
range_start_seconds: f64,
range_end_seconds: f64,
range_start: Beats,
range_end: Beats,
) -> Vec<MidiEvent> {
let mut result = Vec::new();
// Check if instance overlaps with the range
if !self.overlaps_range(range_start_seconds, range_end_seconds) {
if !self.overlaps_range(range_start, range_end) {
return result;
}
let internal_duration = self.internal_duration();
if internal_duration <= 0.0 {
if internal_duration <= Beats::ZERO {
return result;
}
// Calculate how many complete loops fit in the external duration
let num_loops = if self.external_duration > internal_duration {
(self.external_duration / internal_duration).ceil() as usize
} else {
@@ -251,24 +165,18 @@ impl MidiClipInstance {
let external_end = self.external_end();
for loop_idx in 0..num_loops {
let loop_offset = loop_idx as f64 * internal_duration;
let loop_offset = internal_duration * loop_idx as f64;
// Get events from the clip that fall within the internal range
for event in &clip.events {
// Skip events outside the trimmed region
// Use > (not >=) for internal_end so note-offs at the clip boundary are included
if event.timestamp < self.internal_start || event.timestamp > self.internal_end {
continue;
}
// Convert to timeline time
let relative_content_time = event.timestamp - self.internal_start;
let timeline_time = self.external_start + loop_offset + relative_content_time;
// Check if within current buffer range and instance bounds
// Use <= for external_end so note-offs at the clip boundary are included
if timeline_time >= range_start_seconds
&& timeline_time < range_end_seconds
if timeline_time >= range_start
&& timeline_time < range_end
&& timeline_time <= external_end
{
let mut adjusted_event = *event;
+2 -1
View File
@@ -1,6 +1,7 @@
use serde::{Serialize, Deserialize};
use std::collections::HashMap;
use super::midi::{MidiClip, MidiClipId, MidiEvent};
use crate::time::Beats;
/// Pool for storing MIDI clip content
/// Similar to AudioClipPool but for MIDI data
@@ -21,7 +22,7 @@ impl MidiClipPool {
/// Add a new clip to the pool with the given events and duration
/// Returns the ID of the newly created clip
pub fn add_clip(&mut self, events: Vec<MidiEvent>, duration: f64, name: String) -> MidiClipId {
pub fn add_clip(&mut self, events: Vec<MidiEvent>, duration: Beats, name: String) -> MidiClipId {
let id = self.next_id;
self.next_id += 1;
+3 -1
View File
@@ -15,11 +15,13 @@ pub mod recording;
pub mod sample_loader;
pub mod track;
pub mod waveform_cache;
pub mod waveform_pyramid;
pub use automation::{AutomationLane, AutomationLaneId, AutomationPoint, CurveType, ParameterId};
pub use buffer_pool::BufferPool;
pub use clip::{AudioClipInstance, AudioClipInstanceId, Clip, ClipId};
pub use engine::{Engine, EngineController};
pub use disk_reader::{AudioBlobSourceFactory, MediaByteSource};
pub use engine::{AudioClipSnapshot, Engine, EngineController};
pub use export::{export_audio, ExportFormat, ExportSettings};
pub use metronome::Metronome;
pub use midi::{MidiClip, MidiClipId, MidiClipInstance, MidiClipInstanceId, MidiEvent};
+242 -26
View File
@@ -1,6 +1,7 @@
use super::node_trait::AudioNode;
use super::types::{ConnectionError, SignalType};
use crate::audio::midi::MidiEvent;
use crate::time::Beats;
use petgraph::algo::has_path_connecting;
use petgraph::stable_graph::{NodeIndex, StableGraph};
use petgraph::visit::{EdgeRef, IntoEdgeReferences};
@@ -93,8 +94,8 @@ pub struct AudioGraph {
/// UI positions for nodes (node_index -> (x, y))
node_positions: std::collections::HashMap<u32, (f32, f32)>,
/// Current playback time (for automation nodes)
playback_time: f64,
/// Current playback time in beats (for automation nodes)
playback_time: Beats,
/// Project tempo (synced from Engine via SetTempo)
bpm: f32,
@@ -123,7 +124,7 @@ impl AudioGraph {
// Pre-allocate MIDI input buffers (max 128 events per port)
midi_input_buffers: (0..16).map(|_| Vec::with_capacity(128)).collect(),
node_positions: std::collections::HashMap::new(),
playback_time: 0.0,
playback_time: Beats::ZERO,
bpm: 120.0,
beats_per_bar: 4,
topo_cache: None,
@@ -193,6 +194,15 @@ impl AudioGraph {
self.graph.add_edge(from, to, Connection { from_port, to_port });
self.topo_cache = None;
// Auto-grow MixerNode: always keep one spare port beyond the connected count
let n_incoming = self.graph.edges_directed(to, petgraph::Direction::Incoming).count();
if let Some(graph_node) = self.graph.node_weight_mut(to) {
use crate::audio::node_graph::nodes::MixerNode;
if let Some(mixer) = graph_node.node.as_any_mut().downcast_mut::<MixerNode>() {
mixer.ensure_min_ports(n_incoming + 1);
}
}
Ok(())
}
@@ -204,12 +214,24 @@ impl AudioGraph {
to: NodeIndex,
to_port: usize,
) {
// Find and remove the edge
let mut did_remove = false;
if let Some(edge_idx) = self.graph.find_edge(from, to) {
let conn = &self.graph[edge_idx];
if conn.from_port == from_port && conn.to_port == to_port {
self.graph.remove_edge(edge_idx);
self.topo_cache = None;
did_remove = true;
}
}
// Shrink MixerNode back to n_remaining + 1 spare after a disconnect
if did_remove {
let n_remaining = self.graph.edges_directed(to, petgraph::Direction::Incoming).count();
if let Some(graph_node) = self.graph.node_weight_mut(to) {
use crate::audio::node_graph::nodes::MixerNode;
if let Some(mixer) = graph_node.node.as_any_mut().downcast_mut::<MixerNode>() {
mixer.resize(n_remaining + 1);
}
}
}
}
@@ -454,7 +476,7 @@ impl AudioGraph {
}
/// Process the graph and produce audio output
pub fn process(&mut self, output_buffer: &mut [f32], midi_events: &[MidiEvent], playback_time: f64) {
pub fn process(&mut self, output_buffer: &mut [f32], midi_events: &[MidiEvent], playback_time: Beats) {
// Update playback time
self.playback_time = playback_time;
@@ -463,6 +485,7 @@ impl AudioGraph {
for node in self.graph.node_weights_mut() {
if let Some(auto_node) = node.node.as_any_mut().downcast_mut::<AutomationInputNode>() {
auto_node.set_playback_time(playback_time);
auto_node.set_bpm(self.bpm as f64);
} else if let Some(beat_node) = node.node.as_any_mut().downcast_mut::<BeatNode>() {
beat_node.set_playback_time(playback_time);
beat_node.set_tempo(self.bpm, self.beats_per_bar);
@@ -716,6 +739,50 @@ impl AudioGraph {
self.graph.node_indices()
}
/// Reallocate a node's output buffers to match its current port list.
///
/// Must be called after `SubtrackInputsNode::update_subtracks` changes the port count,
/// since `GraphNode.output_buffers` was allocated at `add_node` time.
pub fn reallocate_node_output_buffers(&mut self, idx: NodeIndex, buffer_size: usize) {
if let Some(graph_node) = self.graph.node_weight_mut(idx) {
let outputs = graph_node.node.outputs();
graph_node.output_buffers.clear();
for port in outputs.iter() {
match port.signal_type {
super::types::SignalType::Audio => graph_node.output_buffers.push(vec![0.0; buffer_size * 2]),
super::types::SignalType::CV => graph_node.output_buffers.push(vec![0.0; buffer_size]),
super::types::SignalType::Midi => graph_node.output_buffers.push(vec![]),
}
}
self.topo_cache = None;
}
}
/// Remove all edges going OUT of a specific output port of a node.
pub fn disconnect_output_port(&mut self, node: NodeIndex, port: usize) {
let edges: Vec<_> = self.graph
.edges_directed(node, petgraph::Direction::Outgoing)
.filter(|e| e.weight().from_port == port)
.map(|e| e.id())
.collect();
for edge_id in edges {
self.graph.remove_edge(edge_id);
}
self.topo_cache = None;
}
/// Remove all edges going INTO a node (all input connections).
pub fn disconnect_all_inputs(&mut self, node: NodeIndex) {
let edges: Vec<_> = self.graph
.edges_directed(node, petgraph::Direction::Incoming)
.map(|e| e.id())
.collect();
for edge_id in edges {
self.graph.remove_edge(edge_id);
}
self.topo_cache = None;
}
/// Get all connections
pub fn connections(&self) -> impl Iterator<Item = (NodeIndex, NodeIndex, &Connection)> + '_ {
self.graph.edge_references().map(|e| (e.source(), e.target(), e.weight()))
@@ -787,7 +854,7 @@ impl AudioGraph {
/// Serialize the graph to a preset
pub fn to_preset(&self, name: impl Into<String>) -> crate::audio::node_graph::preset::GraphPreset {
use crate::audio::node_graph::preset::{GraphPreset, SerializedConnection, SerializedNode};
use crate::audio::node_graph::nodes::VoiceAllocatorNode;
use crate::audio::node_graph::nodes::{VoiceAllocatorNode, MixerNode, SubtrackInputsNode};
let mut preset = GraphPreset::new(name);
@@ -805,6 +872,19 @@ impl AudioGraph {
serialized.set_parameter(param.id, value);
}
// Save port count for dynamic-port nodes so they round-trip correctly
if node.node_type() == "Mixer" {
if let Some(mixer) = node.as_any().downcast_ref::<MixerNode>() {
serialized.num_ports = Some(mixer.num_inputs() as u32);
}
}
if node.node_type() == "SubtrackInputs" {
if let Some(si) = node.as_any().downcast_ref::<SubtrackInputsNode>() {
serialized.num_ports = Some(si.num_subtracks() as u32);
serialized.port_names = si.subtracks().iter().map(|(_, name)| name.clone()).collect();
}
}
// For VoiceAllocator nodes, serialize the template graph
if node.node_type() == "VoiceAllocator" {
// Downcast using safe Any trait
@@ -931,6 +1011,29 @@ impl AudioGraph {
}
}
// For AutomationInput nodes, serialize display name and keyframes
if node.node_type() == "AutomationInput" {
use crate::audio::node_graph::nodes::{AutomationInputNode, InterpolationType};
use crate::audio::node_graph::preset::SerializedKeyframe;
if let Some(auto_node) = node.as_any().downcast_ref::<AutomationInputNode>() {
serialized.automation_display_name = Some(auto_node.display_name().to_string());
serialized.automation_keyframes = auto_node.keyframes().iter().map(|kf| {
SerializedKeyframe {
time: kf.time.0,
value: kf.value,
interpolation: match kf.interpolation {
InterpolationType::Linear => "linear",
InterpolationType::Bezier => "bezier",
InterpolationType::Step => "step",
InterpolationType::Hold => "hold",
}.to_string(),
ease_out: kf.ease_out,
ease_in: kf.ease_in,
}
}).collect();
}
}
// For AmpSim nodes, serialize the model path
if node.node_type() == "AmpSim" {
use crate::audio::node_graph::nodes::AmpSimNode;
@@ -975,7 +1078,7 @@ impl AudioGraph {
}
/// Deserialize a preset into the graph
pub fn from_preset(preset: &crate::audio::node_graph::preset::GraphPreset, sample_rate: u32, buffer_size: usize, preset_base_path: Option<&std::path::Path>) -> Result<Self, String> {
pub fn from_preset(preset: &crate::audio::node_graph::preset::GraphPreset, sample_rate: u32, buffer_size: usize, preset_base_path: Option<&std::path::Path>, embedded_assets: Option<&std::collections::HashMap<String, Vec<u8>>>) -> Result<Self, String> {
use crate::audio::node_graph::nodes::*;
use petgraph::stable_graph::NodeIndex;
use std::collections::HashMap;
@@ -1002,17 +1105,51 @@ impl AudioGraph {
let mut graph = Self::new(sample_rate, buffer_size);
let mut index_map: HashMap<u32, NodeIndex> = HashMap::new();
// Pre-pass: compute required min port count for dynamic-port nodes from the connection list.
// This ensures old presets (without num_ports) still size correctly regardless of
// connection-restoration order.
let mut required_ports: HashMap<u32, usize> = HashMap::new();
for conn in &preset.connections {
let entry = required_ports.entry(conn.to_node).or_insert(0);
*entry = (*entry).max(conn.to_port + 2); // port N + 1 spare
}
// Create all nodes
for serialized_node in &preset.nodes {
// Create the node based on type
let mut node = crate::audio::node_graph::nodes::create_node(&serialized_node.node_type, sample_rate, buffer_size)
.ok_or_else(|| format!("Unknown node type: {}", serialized_node.node_type))?;
// Pre-size dynamic-port nodes before graph.add_node() so output buffers are
// allocated at the correct size. num_ports takes priority; fall back to
// connection-count inference so old presets without num_ports still work.
if serialized_node.node_type == "Mixer" {
use crate::audio::node_graph::nodes::MixerNode;
if let Some(mixer) = node.as_any_mut().downcast_mut::<MixerNode>() {
let from_conns = required_ports.get(&serialized_node.id).copied().unwrap_or(1);
let target = serialized_node.num_ports.map(|n| n as usize).unwrap_or(0).max(from_conns).max(1);
mixer.resize(target);
}
}
if serialized_node.node_type == "SubtrackInputs" {
use crate::audio::node_graph::nodes::SubtrackInputsNode;
if let Some(si) = node.as_any_mut().downcast_mut::<SubtrackInputsNode>() {
let from_conns = required_ports.get(&serialized_node.id).copied().unwrap_or(0);
let target = serialized_node.num_ports.map(|n| n as usize).unwrap_or(0).max(from_conns);
if target > 0 {
let subtracks = (0..target)
.map(|i| (0u32, format!("Subtrack {}", i + 1)))
.collect();
si.update_subtracks(subtracks, buffer_size);
}
}
}
// VoiceAllocator needs its template graph deserialized and set
if serialized_node.node_type == "VoiceAllocator" {
if let Some(ref template_preset) = serialized_node.template_graph {
if let Some(va) = node.as_any_mut().downcast_mut::<VoiceAllocatorNode>() {
let template_graph = Self::from_preset(template_preset, sample_rate, buffer_size, preset_base_path)?;
let template_graph = Self::from_preset(template_preset, sample_rate, buffer_size, preset_base_path, embedded_assets)?;
*va.template_graph_mut() = template_graph;
va.rebuild_voices();
}
@@ -1070,10 +1207,28 @@ impl AudioGraph {
sampler_node.set_sample(samples, embedded.sample_rate as f32);
}
} else if let Some(ref path) = file_path {
// Fall back to loading from file (resolve path relative to preset)
let resolved_path = resolve_sample_path(path);
if let Err(e) = sampler_node.load_sample_from_file(&resolved_path) {
eprintln!("Failed to load sample from {}: {}", resolved_path, e);
// Check embedded assets map first (from .lbins bundle)
let loaded = if let Some(assets) = embedded_assets {
if let Some(bytes) = assets.get(path.as_str()) {
match crate::audio::sample_loader::load_audio_from_bytes(bytes, path) {
Ok(data) => {
sampler_node.set_sample(data.samples, data.sample_rate as f32);
true
}
Err(e) => {
eprintln!("Failed to decode bundled sample {}: {}", path, e);
false
}
}
} else { false }
} else { false };
if !loaded {
// Fall back to loading from filesystem
let resolved_path = resolve_sample_path(path);
if let Err(e) = sampler_node.load_sample_from_file(&resolved_path) {
eprintln!("Failed to load sample from {}: {}", resolved_path, e);
}
}
}
}
@@ -1113,20 +1268,49 @@ impl AudioGraph {
);
}
} else if let Some(ref path) = layer.file_path {
// Fall back to loading from file (resolve path relative to preset)
let resolved_path = resolve_sample_path(path);
if let Err(e) = multi_sampler_node.load_layer_from_file(
&resolved_path,
layer.key_min,
layer.key_max,
layer.root_key,
layer.velocity_min,
layer.velocity_max,
layer.loop_start,
layer.loop_end,
layer.loop_mode,
) {
eprintln!("Failed to load sample layer from {}: {}", resolved_path, e);
// Check embedded assets map first (from .lbins bundle)
let loaded = if let Some(assets) = embedded_assets {
if let Some(bytes) = assets.get(path.as_str()) {
match crate::audio::sample_loader::load_audio_from_bytes(bytes, path) {
Ok(data) => {
multi_sampler_node.add_layer(
data.samples,
data.sample_rate as f32,
layer.key_min,
layer.key_max,
layer.root_key,
layer.velocity_min,
layer.velocity_max,
layer.loop_start,
layer.loop_end,
layer.loop_mode,
);
true
}
Err(e) => {
eprintln!("Failed to decode bundled sample layer {}: {}", path, e);
false
}
}
} else { false }
} else { false };
if !loaded {
// Fall back to loading from filesystem
let resolved_path = resolve_sample_path(path);
if let Err(e) = multi_sampler_node.load_layer_from_file(
&resolved_path,
layer.key_min,
layer.key_max,
layer.root_key,
layer.velocity_min,
layer.velocity_max,
layer.loop_start,
layer.loop_end,
layer.loop_mode,
) {
eprintln!("Failed to load sample layer from {}: {}", resolved_path, e);
}
}
}
}
@@ -1146,6 +1330,9 @@ impl AudioGraph {
let result = if let Some(bundled_name) = model_path.strip_prefix("bundled:") {
eprintln!("[AmpSim] Preset: loading bundled model {:?}", bundled_name);
amp_sim.load_bundled_model(bundled_name)
} else if let Some(bytes) = embedded_assets.and_then(|a| a.get(model_path.as_str())) {
eprintln!("[AmpSim] Preset: loading from bundle {:?}", model_path);
amp_sim.load_model_from_bytes(model_path, bytes)
} else {
let resolved_path = resolve_sample_path(model_path);
eprintln!("[AmpSim] Preset: loading from file {:?}", resolved_path);
@@ -1160,6 +1347,35 @@ impl AudioGraph {
}
}
// Restore AutomationInput display name and keyframes
if serialized_node.node_type == "AutomationInput" {
use crate::audio::node_graph::nodes::{AutomationInputNode, AutomationKeyframe, InterpolationType};
if let Some(graph_node) = graph.graph.node_weight_mut(node_idx) {
if let Some(auto_node) = graph_node.node.as_any_mut().downcast_mut::<AutomationInputNode>() {
if let Some(ref name) = serialized_node.automation_display_name {
auto_node.set_display_name(name.clone());
}
if !serialized_node.automation_keyframes.is_empty() {
auto_node.clear_keyframes();
for kf in &serialized_node.automation_keyframes {
auto_node.add_keyframe(AutomationKeyframe {
time: crate::time::Beats(kf.time),
value: kf.value,
interpolation: match kf.interpolation.as_str() {
"bezier" => InterpolationType::Bezier,
"step" => InterpolationType::Step,
"hold" => InterpolationType::Hold,
_ => InterpolationType::Linear,
},
ease_out: kf.ease_out,
ease_in: kf.ease_in,
});
}
}
}
}
}
// Restore position
graph.set_node_position(node_idx, serialized_node.position.0, serialized_node.position.1);
}
+192
View File
@@ -0,0 +1,192 @@
/// Load and save `.lbins` instrument bundle files.
///
/// A `.lbins` file is a ZIP archive with the following layout:
///
/// ```
/// instrument.lbins (ZIP)
/// ├── instrument.json ← GraphPreset JSON (existing schema)
/// ├── samples/
/// │ ├── kick.wav
/// │ └── snare.flac
/// └── models/
/// └── amp.nam
/// ```
///
/// All asset paths in `instrument.json` are ZIP-relative
/// (e.g. `"samples/kick.wav"`, `"models/amp.nam"`).
use std::collections::HashMap;
use std::io::{Read, Write};
use std::path::Path;
use crate::audio::node_graph::preset::{GraphPreset, SampleData};
/// Load a `.lbins` file.
///
/// Returns the deserialized `GraphPreset` together with a map of all
/// non-JSON entries keyed by their ZIP-relative path (e.g. `"samples/kick.wav"`).
pub fn load_lbins(path: &Path) -> Result<(GraphPreset, HashMap<String, Vec<u8>>), String> {
let file = std::fs::File::open(path)
.map_err(|e| format!("Failed to open .lbins file: {}", e))?;
let mut archive = zip::ZipArchive::new(file)
.map_err(|e| format!("Failed to read ZIP archive: {}", e))?;
// Read instrument.json first
let preset_json = {
let mut entry = archive
.by_name("instrument.json")
.map_err(|_| "Missing instrument.json in .lbins archive".to_string())?;
let mut buf = String::new();
entry
.read_to_string(&mut buf)
.map_err(|e| format!("Failed to read instrument.json: {}", e))?;
buf
};
let preset = GraphPreset::from_json(&preset_json)
.map_err(|e| format!("Failed to parse instrument.json: {}", e))?;
// Read all other entries into memory
let mut assets: HashMap<String, Vec<u8>> = HashMap::new();
for i in 0..archive.len() {
let mut entry = archive
.by_index(i)
.map_err(|e| format!("Failed to read ZIP entry {}: {}", i, e))?;
let entry_name = entry.name().to_string();
if entry_name == "instrument.json" || entry.is_dir() {
continue;
}
let mut bytes = Vec::new();
entry
.read_to_end(&mut bytes)
.map_err(|e| format!("Failed to read {}: {}", entry_name, e))?;
assets.insert(entry_name, bytes);
}
Ok((preset, assets))
}
/// Save a preset to a `.lbins` file.
///
/// Asset paths in `preset` are rewritten to ZIP-relative form
/// (`samples/<basename>` or `models/<basename>`).
/// If the path is already ZIP-relative (starts with `samples/` or `models/`)
/// it is used as-is. Absolute / relative filesystem paths are resolved
/// relative to `asset_base` (typically the directory that contained the
/// original `.json` preset) and then read from disk.
pub fn save_lbins(path: &Path, preset: &GraphPreset, asset_base: Option<&Path>) -> Result<(), String> {
let file = std::fs::File::create(path)
.map_err(|e| format!("Failed to create .lbins file: {}", e))?;
let mut zip = zip::ZipWriter::new(file);
let options = zip::write::FileOptions::default()
.compression_method(zip::CompressionMethod::Deflated);
// We'll build a rewritten copy of the preset while collecting assets
let mut rewritten = preset.clone();
// Map: original path → (zip_path, file_bytes)
let mut asset_map: HashMap<String, (String, Vec<u8>)> = HashMap::new();
// Helper: given an original asset path string and a subdirectory ("samples" or "models"),
// resolve the bytes and return the canonical ZIP-relative path.
let mut resolve_asset = |orig_path: &str, subdir: &str| -> Result<String, String> {
// Already a ZIP-relative path — no re-reading needed, caller stored bytes already
// or the asset will be provided by a prior pass. Just normalise the subdirectory.
if orig_path.starts_with(&format!("{}/", subdir)) {
return Ok(orig_path.to_string());
}
let basename = Path::new(orig_path)
.file_name()
.and_then(|n| n.to_str())
.ok_or_else(|| format!("Cannot determine filename for asset: {}", orig_path))?;
let zip_path = format!("{}/{}", subdir, basename);
if !asset_map.contains_key(orig_path) {
// Resolve to an absolute filesystem path
let fs_path = if Path::new(orig_path).is_absolute() {
std::path::PathBuf::from(orig_path)
} else if let Some(base) = asset_base {
base.join(orig_path)
} else {
std::path::PathBuf::from(orig_path)
};
let bytes = std::fs::read(&fs_path)
.map_err(|e| format!("Failed to read asset {}: {}", fs_path.display(), e))?;
asset_map.insert(orig_path.to_string(), (zip_path.clone(), bytes));
}
Ok(zip_path)
};
// Rewrite paths in all nodes
for node in &mut rewritten.nodes {
// Sample data paths
if let Some(ref mut sample_data) = node.sample_data {
match sample_data {
SampleData::SimpleSampler { ref mut file_path, .. } => {
if let Some(ref orig) = file_path.clone() {
if !orig.is_empty() {
match resolve_asset(orig, "samples") {
Ok(zip_path) => *file_path = Some(zip_path),
Err(e) => eprintln!("Warning: {}", e),
}
}
}
}
SampleData::MultiSampler { ref mut layers } => {
for layer in layers.iter_mut() {
if let Some(ref orig) = layer.file_path.clone() {
if !orig.is_empty() {
match resolve_asset(orig, "samples") {
Ok(zip_path) => layer.file_path = Some(zip_path),
Err(e) => eprintln!("Warning: {}", e),
}
}
}
}
}
}
}
// NAM model path
if let Some(ref orig) = node.nam_model_path.clone() {
if !orig.starts_with("bundled:") && !orig.is_empty() {
match resolve_asset(orig, "models") {
Ok(zip_path) => node.nam_model_path = Some(zip_path),
Err(e) => eprintln!("Warning: {}", e),
}
}
}
}
// Write all collected assets to the ZIP
for (_, (zip_path, bytes)) in &asset_map {
zip.start_file(zip_path, options)
.map_err(|e| format!("Failed to start ZIP entry {}: {}", zip_path, e))?;
zip.write_all(bytes)
.map_err(|e| format!("Failed to write {}: {}", zip_path, e))?;
}
// Write instrument.json last (after assets so paths are already rewritten)
let json = rewritten
.to_json()
.map_err(|e| format!("Failed to serialize preset: {}", e))?;
zip.start_file("instrument.json", options)
.map_err(|e| format!("Failed to start instrument.json entry: {}", e))?;
zip.write_all(json.as_bytes())
.map_err(|e| format!("Failed to write instrument.json: {}", e))?;
zip.finish()
.map_err(|e| format!("Failed to finalize ZIP: {}", e))?;
Ok(())
}
+1
View File
@@ -1,6 +1,7 @@
mod graph;
mod node_trait;
mod types;
pub mod lbins;
pub mod nodes;
pub mod preset;
@@ -75,6 +75,21 @@ impl AmpSimNode {
Ok(())
}
/// Load a .nam model from in-memory bytes (used when loading from a .lbins bundle).
/// `zip_path` is the ZIP-relative path stored back in `model_path` for serialization.
pub fn load_model_from_bytes(&mut self, zip_path: &str, bytes: &[u8]) -> Result<(), String> {
let basename = std::path::Path::new(zip_path)
.file_name()
.and_then(|n| n.to_str())
.unwrap_or(zip_path);
let mut model = nam_ffi::NamModel::from_bytes(basename, bytes)
.map_err(|e| format!("{}", e))?;
model.set_max_buffer_size(1024);
self.model = Some(model);
self.model_path = Some(zip_path.to_string());
Ok(())
}
/// Get the loaded model path (for preset serialization).
pub fn model_path(&self) -> Option<&str> {
self.model_path.as_deref()
@@ -1,5 +1,6 @@
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, SignalType};
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, ParameterUnit, SignalType};
use crate::audio::midi::MidiEvent;
use crate::time::Beats;
use serde::{Deserialize, Serialize};
use std::sync::{Arc, RwLock};
@@ -16,8 +17,7 @@ pub enum InterpolationType {
/// A single keyframe in an automation curve
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AutomationKeyframe {
/// Time in seconds (absolute project time)
pub time: f64,
pub time: Beats,
/// CV output value
pub value: f32,
/// Interpolation type to next keyframe
@@ -29,7 +29,7 @@ pub struct AutomationKeyframe {
}
impl AutomationKeyframe {
pub fn new(time: f64, value: f32) -> Self {
pub fn new(time: Beats, value: f32) -> Self {
Self {
time,
value,
@@ -47,8 +47,14 @@ pub struct AutomationInputNode {
keyframes: Vec<AutomationKeyframe>,
outputs: Vec<NodePort>,
parameters: Vec<Parameter>,
/// Shared playback time (set by the graph before processing)
playback_time: Arc<RwLock<f64>>,
/// Shared playback time in beats (set by the graph before processing)
playback_time: Arc<RwLock<Beats>>,
/// Current BPM (set by the graph before processing, used for per-sample beat advancement)
bpm: f64,
/// Minimum output value (for UI display range)
pub value_min: f32,
/// Maximum output value (for UI display range)
pub value_max: f32,
}
impl AutomationInputNode {
@@ -59,23 +65,34 @@ impl AutomationInputNode {
NodePort::new("CV Out", SignalType::CV, 0),
];
let parameters = vec![
Parameter::new(0, "Min", f32::NEG_INFINITY, f32::INFINITY, -1.0, ParameterUnit::Generic),
Parameter::new(1, "Max", f32::NEG_INFINITY, f32::INFINITY, 1.0, ParameterUnit::Generic),
];
Self {
name: name.clone(),
display_name: "Automation".to_string(),
keyframes: Vec::new(),
keyframes: vec![AutomationKeyframe::new(Beats::ZERO, 0.0)],
outputs,
parameters: Vec::new(),
playback_time: Arc::new(RwLock::new(0.0)),
parameters,
playback_time: Arc::new(RwLock::new(Beats::ZERO)),
bpm: 120.0,
value_min: -1.0,
value_max: 1.0,
}
}
/// Set the playback time (called by graph before processing)
pub fn set_playback_time(&mut self, time: f64) {
pub fn set_playback_time(&mut self, time: Beats) {
if let Ok(mut playback) = self.playback_time.write() {
*playback = time;
}
}
pub fn set_bpm(&mut self, bpm: f64) {
self.bpm = bpm;
}
/// Get the display name (shown in UI)
pub fn display_name(&self) -> &str {
&self.display_name
@@ -105,8 +122,7 @@ impl AutomationInputNode {
}
}
/// Remove keyframe at specific time (with tolerance)
pub fn remove_keyframe_at_time(&mut self, time: f64, tolerance: f64) -> bool {
pub fn remove_keyframe_at_time(&mut self, time: Beats, tolerance: Beats) -> bool {
if let Some(idx) = self.keyframes.iter().position(|kf| (kf.time - time).abs() < tolerance) {
self.keyframes.remove(idx);
true
@@ -115,10 +131,8 @@ impl AutomationInputNode {
}
}
/// Update an existing keyframe
pub fn update_keyframe(&mut self, keyframe: AutomationKeyframe) {
// Remove old keyframe at this time, then add new one
self.remove_keyframe_at_time(keyframe.time, 0.001);
self.remove_keyframe_at_time(keyframe.time, Beats(0.001));
self.add_keyframe(keyframe);
}
@@ -132,24 +146,20 @@ impl AutomationInputNode {
self.keyframes.clear();
}
/// Evaluate curve at a specific time
fn evaluate_at_time(&self, time: f64) -> f32 {
fn evaluate_at_time(&self, time: Beats) -> f32 {
if self.keyframes.is_empty() {
return 0.0;
}
// Before first keyframe
if time <= self.keyframes[0].time {
return self.keyframes[0].value;
}
// After last keyframe
let last_idx = self.keyframes.len() - 1;
if time >= self.keyframes[last_idx].time {
return self.keyframes[last_idx].value;
}
// Find bracketing keyframes
for i in 0..self.keyframes.len() - 1 {
let kf1 = &self.keyframes[i];
let kf2 = &self.keyframes[i + 1];
@@ -162,14 +172,12 @@ impl AutomationInputNode {
0.0
}
/// Interpolate between two keyframes
fn interpolate(&self, kf1: &AutomationKeyframe, kf2: &AutomationKeyframe, time: f64) -> f32 {
// Calculate normalized position between keyframes (0.0 to 1.0)
fn interpolate(&self, kf1: &AutomationKeyframe, kf2: &AutomationKeyframe, time: Beats) -> f32 {
let t = if kf2.time == kf1.time {
0.0
0.0f64
} else {
((time - kf1.time) / (kf2.time - kf1.time)) as f32
};
(time - kf1.time) / (kf2.time - kf1.time)
} as f32;
match kf1.interpolation {
InterpolationType::Linear => {
@@ -215,12 +223,20 @@ impl AudioNode for AutomationInputNode {
&self.parameters
}
fn set_parameter(&mut self, _id: u32, _value: f32) {
// No parameters
fn set_parameter(&mut self, id: u32, value: f32) {
match id {
0 => self.value_min = value,
1 => self.value_max = value,
_ => {}
}
}
fn get_parameter(&self, _id: u32) -> f32 {
0.0
fn get_parameter(&self, id: u32) -> f32 {
match id {
0 => self.value_min,
1 => self.value_max,
_ => 0.0,
}
}
fn process(
@@ -238,19 +254,17 @@ impl AudioNode for AutomationInputNode {
let output = &mut outputs[0];
let length = output.len();
// Get the starting playback time
let playhead = if let Ok(playback) = self.playback_time.read() {
*playback
} else {
0.0
Beats::ZERO
};
// Calculate time per sample
let sample_duration = 1.0 / sample_rate as f64;
// Advance per sample in beats: beats_per_sample = bpm / 60 / sample_rate
let beats_per_sample = self.bpm / 60.0 / sample_rate as f64;
// Evaluate curve for each sample
for i in 0..length {
let time = playhead + (i as f64 * sample_duration);
let time = playhead + Beats(i as f64 * beats_per_sample);
output[i] = self.evaluate_at_time(time);
}
}
@@ -274,7 +288,10 @@ impl AudioNode for AutomationInputNode {
keyframes: self.keyframes.clone(),
outputs: self.outputs.clone(),
parameters: self.parameters.clone(),
playback_time: Arc::new(RwLock::new(0.0)),
playback_time: Arc::new(RwLock::new(Beats::ZERO)),
bpm: self.bpm,
value_min: self.value_min,
value_max: self.value_max,
})
}
+19 -18
View File
@@ -1,5 +1,6 @@
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, ParameterUnit, SignalType};
use crate::audio::midi::MidiEvent;
use crate::time::Beats;
const PARAM_RESOLUTION: u32 = 0;
@@ -61,12 +62,12 @@ pub struct BeatNode {
bpm: f32,
beats_per_bar: u32,
resolution: BeatResolution,
/// Playback time in seconds, set by the graph before process()
playback_time: f64,
/// Playback time in beats, set by the graph before process()
playback_time: Beats,
/// Previous playback_time to detect paused state
prev_playback_time: f64,
/// Free-running time accumulator for when playback is stopped
free_run_time: f64,
prev_playback_time: Beats,
/// Free-running beat accumulator for when playback is stopped
free_run_time: Beats,
inputs: Vec<NodePort>,
outputs: Vec<NodePort>,
parameters: Vec<Parameter>,
@@ -92,16 +93,16 @@ impl BeatNode {
bpm: DEFAULT_BPM,
beats_per_bar: DEFAULT_BEATS_PER_BAR,
resolution: BeatResolution::Quarter,
playback_time: 0.0,
prev_playback_time: -1.0,
free_run_time: 0.0,
playback_time: Beats::ZERO,
prev_playback_time: Beats(-1.0),
free_run_time: Beats::ZERO,
inputs,
outputs,
parameters,
}
}
pub fn set_playback_time(&mut self, time: f64) {
pub fn set_playback_time(&mut self, time: Beats) {
self.playback_time = time;
}
@@ -169,8 +170,8 @@ impl AudioNode for BeatNode {
let base_time = if paused { self.free_run_time } else { self.playback_time };
for i in 0..len {
let time = base_time + i as f64 * sample_period;
let beat_pos = time * beats_per_second;
// base_time is already in beats; advance by beats_per_second per second
let beat_pos = base_time.0 + i as f64 * beats_per_second * sample_period;
// Beat subdivision phase: 0→1 sawtooth
let sub_phase = ((beat_pos * subs_per_beat) % 1.0) as f32;
@@ -188,13 +189,13 @@ impl AudioNode for BeatNode {
}
// Advance free-run time (always ticks, so it's ready when playback stops)
self.free_run_time += len as f64 * sample_period;
self.free_run_time += Beats(len as f64 * beats_per_second * sample_period);
}
fn reset(&mut self) {
self.playback_time = 0.0;
self.prev_playback_time = -1.0;
self.free_run_time = 0.0;
self.playback_time = Beats::ZERO;
self.prev_playback_time = Beats(-1.0);
self.free_run_time = Beats::ZERO;
}
fn node_type(&self) -> &str {
@@ -211,9 +212,9 @@ impl AudioNode for BeatNode {
bpm: self.bpm,
beats_per_bar: self.beats_per_bar,
resolution: self.resolution,
playback_time: 0.0,
prev_playback_time: -1.0,
free_run_time: 0.0,
playback_time: Beats::ZERO,
prev_playback_time: Beats(-1.0),
free_run_time: Beats::ZERO,
inputs: self.inputs.clone(),
outputs: self.outputs.clone(),
parameters: self.parameters.clone(),
@@ -1,14 +1,19 @@
use crate::audio::midi::MidiEvent;
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, SignalType};
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, ParameterUnit, SignalType};
const PARAM_PITCH_BEND_RANGE: u32 = 0;
/// MIDI to CV converter
/// Converts MIDI note events to control voltage signals
pub struct MidiToCVNode {
name: String,
note: u8, // Current MIDI note number
gate: f32, // Gate CV (1.0 when note on, 0.0 when off)
velocity: f32, // Velocity CV (0.0-1.0)
pitch_cv: f32, // Pitch CV (V/Oct: 0V = A4, ±1V per octave)
note: u8, // Current MIDI note number
gate: f32, // Gate CV (1.0 when note on, 0.0 when off)
velocity: f32, // Velocity CV (0.0-1.0)
pitch_cv: f32, // Pitch CV (V/Oct: 0V = A4, ±1V per octave), without bend
pitch_bend_range: f32, // Pitch bend range in semitones (default 2.0)
current_bend: f32, // Current pitch bend, normalised -1.0..=1.0 (0 = centre)
current_mod: f32, // Current modulation (CC1), 0.0..=1.0
inputs: Vec<NodePort>,
outputs: Vec<NodePort>,
parameters: Vec<Parameter>,
@@ -18,26 +23,41 @@ impl MidiToCVNode {
pub fn new(name: impl Into<String>) -> Self {
let name = name.into();
// MIDI input port for receiving MIDI through graph connections
let inputs = vec![
NodePort::new("MIDI In", SignalType::Midi, 0),
NodePort::new("Bend CV", SignalType::CV, 0), // External pitch bend in semitones
NodePort::new("Mod CV", SignalType::CV, 1), // External modulation 0.0..=1.0
];
let outputs = vec![
NodePort::new("V/Oct", SignalType::CV, 0), // V/Oct: 0V = A4, ±1V per octave
NodePort::new("V/Oct", SignalType::CV, 0), // V/Oct: 0V = A4, ±1V per octave (with bend applied)
NodePort::new("Gate", SignalType::CV, 1), // 1.0 = on, 0.0 = off
NodePort::new("Velocity", SignalType::CV, 2), // 0.0-1.0
NodePort::new("Bend", SignalType::CV, 3), // Total pitch bend in semitones (MIDI + CV)
NodePort::new("Mod", SignalType::CV, 4), // Total modulation 0.0..=1.0 (MIDI CC1 + CV)
];
let parameters = vec![
Parameter::new(
PARAM_PITCH_BEND_RANGE,
"Pitch Bend Range",
0.0, 48.0, 2.0,
ParameterUnit::Generic,
),
];
Self {
name,
note: 60, // Middle C
note: 60,
gate: 0.0,
velocity: 0.0,
pitch_cv: Self::midi_note_to_voct(60),
pitch_bend_range: 2.0,
current_bend: 0.0,
current_mod: 0.0,
inputs,
outputs,
parameters: vec![], // No user parameters
parameters,
}
}
@@ -48,6 +68,37 @@ impl MidiToCVNode {
// Standard V/Oct: 0V at A4, 1V per octave (12 semitones)
(note as f32 - 69.0) / 12.0
}
fn apply_midi_event(&mut self, event: &MidiEvent) {
let status = event.status & 0xF0;
match status {
0x90 if event.data2 > 0 => {
// Note on — reset per-note expression so previous note's bend doesn't bleed in
self.note = event.data1;
self.pitch_cv = Self::midi_note_to_voct(self.note);
self.velocity = event.data2 as f32 / 127.0;
self.gate = 1.0;
self.current_bend = 0.0;
self.current_mod = 0.0;
}
0x80 | 0x90 => {
// Note off (or note on with velocity 0)
if event.data1 == self.note {
self.gate = 0.0;
}
}
0xE0 => {
// Pitch bend: 14-bit value, center = 8192
let bend_raw = ((event.data2 as i16) << 7) | (event.data1 as i16);
self.current_bend = (bend_raw - 8192) as f32 / 8192.0;
}
0xB0 if event.data1 == 1 => {
// CC1 (modulation wheel)
self.current_mod = event.data2 as f32 / 127.0;
}
_ => {}
}
}
}
impl AudioNode for MidiToCVNode {
@@ -67,46 +118,27 @@ impl AudioNode for MidiToCVNode {
&self.parameters
}
fn set_parameter(&mut self, _id: u32, _value: f32) {
// No parameters
fn set_parameter(&mut self, id: u32, value: f32) {
if id == PARAM_PITCH_BEND_RANGE {
self.pitch_bend_range = value.clamp(0.0, 48.0);
}
}
fn get_parameter(&self, _id: u32) -> f32 {
0.0
fn get_parameter(&self, id: u32) -> f32 {
if id == PARAM_PITCH_BEND_RANGE {
self.pitch_bend_range
} else {
0.0
}
}
fn handle_midi(&mut self, event: &MidiEvent) {
let status = event.status & 0xF0;
match status {
0x90 => {
// Note on
if event.data2 > 0 {
// Velocity > 0 means note on
self.note = event.data1;
self.pitch_cv = Self::midi_note_to_voct(self.note);
self.velocity = event.data2 as f32 / 127.0;
self.gate = 1.0;
} else {
// Velocity = 0 means note off
if event.data1 == self.note {
self.gate = 0.0;
}
}
}
0x80 => {
// Note off
if event.data1 == self.note {
self.gate = 0.0;
}
}
_ => {}
}
self.apply_midi_event(event);
}
fn process(
&mut self,
_inputs: &[&[f32]],
inputs: &[&[f32]],
outputs: &mut [&mut [f32]],
midi_inputs: &[&[MidiEvent]],
_midi_outputs: &mut [&mut Vec<MidiEvent>],
@@ -115,52 +147,56 @@ impl AudioNode for MidiToCVNode {
// Process MIDI events from input buffer
if !midi_inputs.is_empty() {
for event in midi_inputs[0] {
let status = event.status & 0xF0;
match status {
0x90 if event.data2 > 0 => {
// Note on
self.note = event.data1;
self.pitch_cv = Self::midi_note_to_voct(self.note);
self.velocity = event.data2 as f32 / 127.0;
self.gate = 1.0;
}
0x80 | 0x90 => {
// Note off (or note on with velocity 0)
if event.data1 == self.note {
self.gate = 0.0;
}
}
_ => {}
}
self.apply_midi_event(event);
}
}
if outputs.len() < 3 {
if outputs.len() < 5 {
return;
}
// CV signals are mono
// Use split_at_mut to get multiple mutable references
let (pitch_and_rest, rest) = outputs.split_at_mut(1);
let (gate_and_rest, velocity_slice) = rest.split_at_mut(1);
// Read CV inputs (use first sample of buffer). NaN = unconnected port → treat as 0.
let bend_cv = inputs.get(0).and_then(|b| b.first().copied())
.filter(|v| v.is_finite()).unwrap_or(0.0);
let mod_cv = inputs.get(1).and_then(|b| b.first().copied())
.filter(|v| v.is_finite()).unwrap_or(0.0);
let pitch_out = &mut pitch_and_rest[0];
let gate_out = &mut gate_and_rest[0];
let velocity_out = &mut velocity_slice[0];
// Total bend in semitones: MIDI bend + CV bend
let bend_semitones = self.current_bend * self.pitch_bend_range + bend_cv;
// Total mod: MIDI CC1 + CV mod, clamped to 0..1
let total_mod = (self.current_mod + mod_cv).clamp(0.0, 1.0);
// Pitch output includes bend
let pitch_out_val = self.pitch_cv + bend_semitones / 12.0;
// Use split_at_mut to get multiple mutable references
let (v0, rest) = outputs.split_at_mut(1);
let (v1, rest) = rest.split_at_mut(1);
let (v2, rest) = rest.split_at_mut(1);
let (v3, v4_slice) = rest.split_at_mut(1);
let pitch_out = &mut v0[0];
let gate_out = &mut v1[0];
let velocity_out = &mut v2[0];
let bend_out = &mut v3[0];
let mod_out = &mut v4_slice[0];
let frames = pitch_out.len();
// Output constant CV values for the entire buffer
for frame in 0..frames {
pitch_out[frame] = self.pitch_cv;
gate_out[frame] = self.gate;
pitch_out[frame] = pitch_out_val;
gate_out[frame] = self.gate;
velocity_out[frame] = self.velocity;
bend_out[frame] = bend_semitones;
mod_out[frame] = total_mod;
}
}
fn reset(&mut self) {
self.gate = 0.0;
self.velocity = 0.0;
self.current_bend = 0.0;
self.current_mod = 0.0;
}
fn node_type(&self) -> &str {
@@ -174,10 +210,13 @@ impl AudioNode for MidiToCVNode {
fn clone_node(&self) -> Box<dyn AudioNode> {
Box::new(Self {
name: self.name.clone(),
note: 60, // Reset to middle C
gate: 0.0, // Reset gate
velocity: 0.0, // Reset velocity
pitch_cv: Self::midi_note_to_voct(60), // Reset pitch
note: 60,
gate: 0.0,
velocity: 0.0,
pitch_cv: Self::midi_note_to_voct(60),
pitch_bend_range: self.pitch_bend_range,
current_bend: 0.0,
current_mod: 0.0,
inputs: self.inputs.clone(),
outputs: self.outputs.clone(),
parameters: self.parameters.clone(),
+67 -56
View File
@@ -1,48 +1,74 @@
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, ParameterUnit, SignalType};
use crate::audio::midi::MidiEvent;
const PARAM_GAIN_1: u32 = 0;
const PARAM_GAIN_2: u32 = 1;
const PARAM_GAIN_3: u32 = 2;
const PARAM_GAIN_4: u32 = 3;
/// Mixer node - combines multiple audio inputs with independent gain controls
/// Mixer node — combines N audio inputs with independent gain controls.
///
/// The number of input ports is dynamic: one spare unconnected port is always present
/// beyond however many are currently wired, so users can keep patching in without
/// manually adding inputs. Port count is managed by `AudioGraph::connect` /
/// `AudioGraph::disconnect` calling `ensure_min_ports` / `resize`.
///
/// Gain values are stored separately from the port list so they survive resize
/// operations and can be set via `set_parameter` before the port is visible.
pub struct MixerNode {
name: String,
gains: [f32; 4],
/// Displayed input ports. Length = num_ports (connected + 1 spare).
inputs: Vec<NodePort>,
outputs: Vec<NodePort>,
/// Per-channel gains, indexed by port. May be longer than `inputs` if gains
/// were set before ports were created (handled gracefully).
gains: Vec<f32>,
/// Mirrored parameter list so `parameters()` stays in sync with `inputs`.
parameters: Vec<Parameter>,
}
impl MixerNode {
pub fn new(name: impl Into<String>) -> Self {
let name = name.into();
let mut node = Self {
name: name.into(),
inputs: Vec::new(),
outputs: vec![NodePort::new("Mixed Out", SignalType::Audio, 0)],
gains: Vec::new(),
parameters: Vec::new(),
};
node.resize(1); // start with one spare input
node
}
let inputs = vec![
NodePort::new("Input 1", SignalType::Audio, 0),
NodePort::new("Input 2", SignalType::Audio, 1),
NodePort::new("Input 3", SignalType::Audio, 2),
NodePort::new("Input 4", SignalType::Audio, 3),
];
/// Return the current number of input ports (connected + 1 spare).
pub fn num_inputs(&self) -> usize {
self.inputs.len()
}
let outputs = vec![
NodePort::new("Mixed Out", SignalType::Audio, 0),
];
/// Set the exact number of input ports.
///
/// Existing gain values are preserved. Truncates spare gains when shrinking,
/// but gain slots that have already been written survive a grow-shrink-grow cycle.
pub fn resize(&mut self, n: usize) {
let n = n.max(1); // always at least one spare
let parameters = vec![
Parameter::new(PARAM_GAIN_1, "Gain 1", 0.0, 2.0, 1.0, ParameterUnit::Generic),
Parameter::new(PARAM_GAIN_2, "Gain 2", 0.0, 2.0, 1.0, ParameterUnit::Generic),
Parameter::new(PARAM_GAIN_3, "Gain 3", 0.0, 2.0, 1.0, ParameterUnit::Generic),
Parameter::new(PARAM_GAIN_4, "Gain 4", 0.0, 2.0, 1.0, ParameterUnit::Generic),
];
self.inputs = (0..n)
.map(|i| NodePort::new(format!("Input {}", i + 1).as_str(), SignalType::Audio, i))
.collect();
Self {
name,
gains: [1.0, 1.0, 1.0, 1.0],
inputs,
outputs,
parameters,
// Extend gains with 1.0 for new slots; preserve existing values.
if self.gains.len() < n {
self.gains.resize(n, 1.0);
}
self.parameters = (0..n)
.map(|i| {
Parameter::new(i as u32, format!("Gain {}", i + 1).as_str(), 0.0, 2.0, 1.0, ParameterUnit::Generic)
})
.collect();
}
/// Ensure at least `n` input ports exist, growing if needed but never shrinking.
///
/// Called by `AudioGraph::connect` after adding a connection.
pub fn ensure_min_ports(&mut self, n: usize) {
if n > self.inputs.len() {
self.resize(n);
}
}
}
@@ -65,23 +91,17 @@ impl AudioNode for MixerNode {
}
fn set_parameter(&mut self, id: u32, value: f32) {
match id {
PARAM_GAIN_1 => self.gains[0] = value.clamp(0.0, 2.0),
PARAM_GAIN_2 => self.gains[1] = value.clamp(0.0, 2.0),
PARAM_GAIN_3 => self.gains[2] = value.clamp(0.0, 2.0),
PARAM_GAIN_4 => self.gains[3] = value.clamp(0.0, 2.0),
_ => {}
let idx = id as usize;
// Extend gains if this port hasn't been created yet (e.g. loaded from preset
// before connections are restored).
if idx >= self.gains.len() {
self.gains.resize(idx + 1, 1.0);
}
self.gains[idx] = value.clamp(0.0, 2.0);
}
fn get_parameter(&self, id: u32) -> f32 {
match id {
PARAM_GAIN_1 => self.gains[0],
PARAM_GAIN_2 => self.gains[1],
PARAM_GAIN_3 => self.gains[2],
PARAM_GAIN_4 => self.gains[3],
_ => 0.0,
}
self.gains.get(id as usize).copied().unwrap_or(1.0)
}
fn process(
@@ -97,32 +117,23 @@ impl AudioNode for MixerNode {
}
let output = &mut outputs[0];
// Audio signals are stereo (interleaved L/R)
let frames = output.len() / 2;
// Clear output buffer first
output.fill(0.0);
// Mix each input with its gain
for (input_idx, input) in inputs.iter().enumerate().take(4) {
if input_idx >= self.gains.len() {
break;
}
let gain = self.gains[input_idx];
for (input_idx, input) in inputs.iter().enumerate() {
let gain = self.gains.get(input_idx).copied().unwrap_or(1.0);
let input_frames = input.len() / 2;
let process_frames = frames.min(input_frames);
for frame in 0..process_frames {
output[frame * 2] += input[frame * 2] * gain; // Left
output[frame * 2] += input[frame * 2] * gain; // Left
output[frame * 2 + 1] += input[frame * 2 + 1] * gain; // Right
}
}
}
fn reset(&mut self) {
// No state to reset
// No per-frame state
}
fn node_type(&self) -> &str {
@@ -136,9 +147,9 @@ impl AudioNode for MixerNode {
fn clone_node(&self) -> Box<dyn AudioNode> {
Box::new(Self {
name: self.name.clone(),
gains: self.gains,
inputs: self.inputs.clone(),
outputs: self.outputs.clone(),
gains: self.gains.clone(),
parameters: self.parameters.clone(),
})
}
@@ -1,6 +1,7 @@
mod amp_sim;
pub mod bundled_models;
mod adsr;
mod subtrack_inputs;
mod arpeggiator;
mod audio_input;
mod audio_to_cv;
@@ -96,6 +97,7 @@ pub use vibrato::VibratoNode;
pub use vocoder::VocoderNode;
pub use voice_allocator::VoiceAllocatorNode;
pub use wavetable_oscillator::WavetableOscillatorNode;
pub use subtrack_inputs::SubtrackInputsNode;
/// Create a node instance by type name string.
///
@@ -152,6 +154,7 @@ pub fn create_node(node_type: &str, sample_rate: u32, buffer_size: usize) -> Opt
"Vibrato" => Box::new(VibratoNode::new("Vibrato")),
"AmpSim" => Box::new(AmpSimNode::new("Amp Sim")),
"AudioOutput" => Box::new(AudioOutputNode::new("Output")),
"SubtrackInputs" => Box::new(SubtrackInputsNode::new("Subtrack Inputs", vec![])),
_ => return None,
})
}
@@ -6,6 +6,7 @@ const PARAM_GAIN: u32 = 0;
const PARAM_ATTACK: u32 = 1;
const PARAM_RELEASE: u32 = 2;
const PARAM_TRANSPOSE: u32 = 3;
const PARAM_PITCH_BEND_RANGE: u32 = 4;
/// Loop playback mode
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
@@ -201,6 +202,7 @@ struct Voice {
layer_index: usize,
playhead: f32,
note: u8,
channel: u8, // MIDI channel this voice was activated on
velocity: u8,
is_active: bool,
@@ -221,11 +223,12 @@ enum EnvelopePhase {
}
impl Voice {
fn new(layer_index: usize, note: u8, velocity: u8) -> Self {
fn new(layer_index: usize, note: u8, channel: u8, velocity: u8) -> Self {
Self {
layer_index,
playhead: 0.0,
note,
channel,
velocity,
is_active: true,
envelope_phase: EnvelopePhase::Attack,
@@ -250,9 +253,14 @@ pub struct MultiSamplerNode {
// Parameters
gain: f32,
attack_time: f32, // seconds
release_time: f32, // seconds
transpose: i8, // semitones
attack_time: f32, // seconds
release_time: f32, // seconds
transpose: i8, // semitones
pitch_bend_range: f32, // semitones (default 2.0)
// Live MIDI state
bend_per_channel: [f32; 16], // Pitch bend per MIDI channel; ch0 = global broadcast
current_mod: f32, // MIDI CC1 modulation 0.0..=1.0
inputs: Vec<NodePort>,
outputs: Vec<NodePort>,
@@ -265,6 +273,8 @@ impl MultiSamplerNode {
let inputs = vec![
NodePort::new("MIDI In", SignalType::Midi, 0),
NodePort::new("Bend CV", SignalType::CV, 0), // External pitch bend in semitones
NodePort::new("Mod CV", SignalType::CV, 1), // External modulation 0.0..=1.0
];
let outputs = vec![
@@ -276,6 +286,7 @@ impl MultiSamplerNode {
Parameter::new(PARAM_ATTACK, "Attack", 0.001, 1.0, 0.01, ParameterUnit::Time),
Parameter::new(PARAM_RELEASE, "Release", 0.01, 5.0, 0.1, ParameterUnit::Time),
Parameter::new(PARAM_TRANSPOSE, "Transpose", -24.0, 24.0, 0.0, ParameterUnit::Generic),
Parameter::new(PARAM_PITCH_BEND_RANGE, "Pitch Bend Range", 0.0, 48.0, 2.0, ParameterUnit::Generic),
];
Self {
@@ -288,6 +299,9 @@ impl MultiSamplerNode {
attack_time: 0.01,
release_time: 0.1,
transpose: 0,
pitch_bend_range: 2.0,
bend_per_channel: [0.0; 16],
current_mod: 0.0,
inputs,
outputs,
parameters,
@@ -478,7 +492,9 @@ impl MultiSamplerNode {
}
/// Trigger a note
fn note_on(&mut self, note: u8, velocity: u8) {
fn note_on(&mut self, note: u8, channel: u8, velocity: u8) {
// Reset per-channel bend on note-on so a previous note's bend doesn't bleed in
self.bend_per_channel[channel as usize] = 0.0;
let transposed_note = (note as i16 + self.transpose as i16).clamp(0, 127) as u8;
if let Some(layer_index) = self.find_layer(transposed_note, velocity) {
@@ -496,7 +512,7 @@ impl MultiSamplerNode {
}
});
let voice = Voice::new(layer_index, note, velocity);
let voice = Voice::new(layer_index, note, channel, velocity);
if voice_index < self.voices.len() {
self.voices[voice_index] = voice;
@@ -547,6 +563,9 @@ impl AudioNode for MultiSamplerNode {
PARAM_TRANSPOSE => {
self.transpose = value.clamp(-24.0, 24.0) as i8;
}
PARAM_PITCH_BEND_RANGE => {
self.pitch_bend_range = value.clamp(0.0, 48.0);
}
_ => {}
}
}
@@ -557,13 +576,14 @@ impl AudioNode for MultiSamplerNode {
PARAM_ATTACK => self.attack_time,
PARAM_RELEASE => self.release_time,
PARAM_TRANSPOSE => self.transpose as f32,
PARAM_PITCH_BEND_RANGE => self.pitch_bend_range,
_ => 0.0,
}
}
fn process(
&mut self,
_inputs: &[&[f32]],
inputs: &[&[f32]],
outputs: &mut [&mut [f32]],
midi_inputs: &[&[MidiEvent]],
_midi_outputs: &mut [&mut Vec<MidiEvent>],
@@ -582,14 +602,32 @@ impl AudioNode for MultiSamplerNode {
// Process MIDI events
if !midi_inputs.is_empty() {
for event in midi_inputs[0].iter() {
if event.is_note_on() {
self.note_on(event.data1, event.data2);
} else if event.is_note_off() {
self.note_off(event.data1);
let status = event.status & 0xF0;
match status {
_ if event.is_note_on() => self.note_on(event.data1, event.status & 0x0F, event.data2),
_ if event.is_note_off() => self.note_off(event.data1),
0xE0 => {
// Pitch bend: 14-bit value, center = 8192; stored per-channel
let bend_raw = ((event.data2 as i16) << 7) | (event.data1 as i16);
let ch = (event.status & 0x0F) as usize;
self.bend_per_channel[ch] = (bend_raw - 8192) as f32 / 8192.0;
}
0xB0 if event.data1 == 1 => {
// CC1 (modulation wheel)
self.current_mod = event.data2 as f32 / 127.0;
}
_ => {}
}
}
}
// Read CV inputs. NaN = unconnected port → treat as 0.
let bend_cv = inputs.get(0).and_then(|b| b.first().copied())
.filter(|v| v.is_finite()).unwrap_or(0.0);
// Global bend (channel 0) applies to all voices; per-channel bend is added per-voice below.
let global_bend_norm = self.bend_per_channel[0];
let bend_per_channel = self.bend_per_channel;
// Extract parameters needed for processing
let gain = self.gain;
let attack_time = self.attack_time;
@@ -607,9 +645,12 @@ impl AudioNode for MultiSamplerNode {
let layer = &self.layers[voice.layer_index];
// Calculate playback speed
// Calculate playback speed (includes pitch bend)
// Channel-0 = global; voice's own channel bend is added on top.
let voice_bend_norm = global_bend_norm + bend_per_channel[voice.channel as usize];
let total_bend_semitones = voice_bend_norm * self.pitch_bend_range + bend_cv;
let semitone_diff = voice.note as i16 - layer.root_key as i16;
let speed = 2.0_f32.powf(semitone_diff as f32 / 12.0);
let speed = 2.0_f32.powf((semitone_diff as f32 + total_bend_semitones) / 12.0);
let speed_adjusted = speed * (layer.sample_rate / sample_rate as f32);
for frame in 0..frames {
@@ -765,6 +806,8 @@ impl AudioNode for MultiSamplerNode {
fn reset(&mut self) {
self.voices.clear();
self.bend_per_channel = [0.0; 16];
self.current_mod = 0.0;
}
fn node_type(&self) -> &str {
@@ -164,11 +164,11 @@ impl AudioNode for OscillatorNode {
output[frame * 2] = sample; // Left
output[frame * 2 + 1] = sample; // Right
// Update phase once per frame
self.phase += freq_mod / sample_rate_f32;
if self.phase >= 1.0 {
self.phase -= 1.0;
}
// Update phase once per frame. `rem_euclid(1.0)` gives a numerically stable
// wraparound into [0, 1): repeated conditional subtraction accumulates f32
// rounding error over long-held notes (timbre drift), and FM can drive
// `freq_mod` negative, which a one-sided `if >= 1.0` wouldn't wrap at all.
self.phase = (self.phase + freq_mod / sample_rate_f32).rem_euclid(1.0);
}
}
@@ -113,10 +113,8 @@ impl AudioNode for PanNode {
let frames_to_process = frames.min(output_frames);
for frame in 0..frames_to_process {
// Pan CV input: when connected, replaces parameter; when unconnected, uses parameter
// CV is in 0-1 range, mapped to -1 to +1 pan range
let cv_raw = cv_input_or_default(inputs, 1, frame, (self.pan + 1.0) * 0.5);
let pan = (cv_raw * 2.0 - 1.0).clamp(-1.0, 1.0);
// Pan CV input: -1..+1 directly (0 = center), defaults to parameter value when unconnected
let pan = cv_input_or_default(inputs, 1, frame, self.pan).clamp(-1.0, 1.0);
// Calculate gains using constant-power panning law
let angle = (pan + 1.0) * 0.5 * PI / 2.0;
@@ -1,5 +1,6 @@
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, ParameterUnit, SignalType, cv_input_or_default};
use crate::audio::midi::MidiEvent;
use crate::time::Beats;
const PARAM_MODE: u32 = 0;
const PARAM_STEPS: u32 = 1;
@@ -244,14 +245,14 @@ impl AudioNode for SequencerNode {
// Note-off for notes no longer active
for &note in &self.prev_active_notes {
if !new_notes.contains(&note) {
midi_outputs[0].push(MidiEvent::note_off(0.0, 0, note, 0));
midi_outputs[0].push(MidiEvent::note_off(Beats::ZERO, 0, note, 0));
}
}
// Note-on for newly active notes
for &note in &new_notes {
if !self.prev_active_notes.contains(&note) {
midi_outputs[0].push(MidiEvent::note_on(0.0, 0, note, self.velocity));
midi_outputs[0].push(MidiEvent::note_on(Beats::ZERO, 0, note, self.velocity));
}
}
@@ -0,0 +1,177 @@
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, SignalType};
use crate::audio::midi::MidiEvent;
use crate::audio::track::TrackId;
/// Subtrack inputs node for metatracks.
///
/// Exposes one output port per child track so users can route individual subtracks
/// independently in the mixing graph (e.g., for sidechain effects).
///
/// Audio is injected into pre-allocated per-slot buffers by the render system before
/// the graph is processed — no heap allocation occurs during audio rendering.
pub struct SubtrackInputsNode {
name: String,
/// Ordered list of (TrackId, display_name) for each subtrack slot.
/// TrackId is used by the render system to match the right buffer to the right slot.
subtracks: Vec<(TrackId, String)>,
/// Output port descriptors — rebuilt whenever subtracks changes.
outputs: Vec<NodePort>,
/// Pre-allocated audio buffers, one per subtrack slot (stereo interleaved, length = buffer_size * 2).
/// Filled by `inject_subtrack_audio` before graph processing; no alloc per frame.
buffers: Vec<Vec<f32>>,
/// The buffer size this node was last sized for.
buffer_size: usize,
}
impl SubtrackInputsNode {
pub fn new(name: impl Into<String>, subtracks: Vec<(TrackId, String)>) -> Self {
let outputs = Self::build_outputs(&subtracks);
let n = subtracks.len();
Self {
name: name.into(),
subtracks,
outputs,
buffers: vec![Vec::new(); n],
buffer_size: 0,
}
}
fn build_outputs(subtracks: &[(TrackId, String)]) -> Vec<NodePort> {
subtracks
.iter()
.enumerate()
.map(|(i, (_, name))| NodePort::new(name.as_str(), SignalType::Audio, i))
.collect()
}
/// Inject audio from a child track into its pre-allocated slot.
///
/// `idx` is the slot index (matching the order in `subtracks`).
/// Called by the render system once per child per frame — no allocation.
pub fn inject_subtrack_audio(&mut self, idx: usize, audio: &[f32]) {
if let Some(buf) = self.buffers.get_mut(idx) {
let len = buf.len().min(audio.len());
buf[..len].copy_from_slice(&audio[..len]);
// Zero any remaining samples if audio is shorter than the buffer
if audio.len() < buf.len() {
buf[audio.len()..].fill(0.0);
}
}
}
/// Rebuild ports and resize pre-allocated buffers.
///
/// Only reallocates when the subtrack list actually changes in size or content.
/// Pass `buffer_size` in frames (stereo buffers will be `buffer_size * 2` samples).
pub fn update_subtracks(&mut self, subtracks: Vec<(TrackId, String)>, buffer_size: usize) {
let n = subtracks.len();
self.outputs = Self::build_outputs(&subtracks);
self.subtracks = subtracks;
self.buffer_size = buffer_size;
// Resize buffers: keep existing allocations where possible
self.buffers.resize_with(n, Vec::new);
for buf in &mut self.buffers {
let target = buffer_size * 2; // stereo interleaved
if buf.len() != target {
buf.resize(target, 0.0);
}
}
}
/// Return the slot index for the given TrackId, or None if not found.
pub fn subtrack_index_for(&self, track_id: TrackId) -> Option<usize> {
self.subtracks.iter().position(|(id, _)| *id == track_id)
}
/// Return the number of subtrack slots.
pub fn num_subtracks(&self) -> usize {
self.subtracks.len()
}
/// Return the ordered subtrack list.
pub fn subtracks(&self) -> &[(TrackId, String)] {
&self.subtracks
}
}
impl AudioNode for SubtrackInputsNode {
fn category(&self) -> NodeCategory {
NodeCategory::Input
}
fn inputs(&self) -> &[NodePort] {
&[] // No inputs — audio is injected externally
}
fn outputs(&self) -> &[NodePort] {
&self.outputs
}
fn parameters(&self) -> &[Parameter] {
&[] // No user-facing parameters; port count is stored via num_ports in serialization
}
fn set_parameter(&mut self, _id: u32, _value: f32) {}
fn get_parameter(&self, _id: u32) -> f32 {
0.0
}
fn process(
&mut self,
_inputs: &[&[f32]],
outputs: &mut [&mut [f32]],
_midi_inputs: &[&[MidiEvent]],
_midi_outputs: &mut [&mut Vec<MidiEvent>],
_sample_rate: u32,
) {
// Copy each pre-filled buffer to its output port
for (i, output) in outputs.iter_mut().enumerate() {
if let Some(buf) = self.buffers.get(i) {
let len = output.len().min(buf.len());
if len > 0 {
output[..len].copy_from_slice(&buf[..len]);
}
if output.len() > len {
output[len..].fill(0.0);
}
} else {
output.fill(0.0);
}
}
}
fn reset(&mut self) {
for buf in &mut self.buffers {
buf.fill(0.0);
}
}
fn node_type(&self) -> &str {
"SubtrackInputs"
}
fn name(&self) -> &str {
&self.name
}
fn clone_node(&self) -> Box<dyn AudioNode> {
Box::new(Self {
name: self.name.clone(),
subtracks: self.subtracks.clone(),
outputs: self.outputs.clone(),
// Don't clone audio buffers; fresh node starts silent
buffers: vec![vec![0.0; self.buffer_size * 2]; self.subtracks.len()],
buffer_size: self.buffer_size,
})
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
@@ -11,6 +11,7 @@ struct VoiceState {
active: bool,
releasing: bool, // Note-off received, still processing (e.g. ADSR release)
note: u8,
note_channel: u8, // MIDI channel this voice was allocated on (0 = global/unset)
age: u32, // For voice stealing
pending_events: Vec<MidiEvent>, // MIDI events to send to this voice
}
@@ -21,6 +22,7 @@ impl VoiceState {
active: false,
releasing: false,
note: 0,
note_channel: 0,
age: 0,
pending_events: Vec::new(),
}
@@ -273,6 +275,7 @@ impl AudioNode for VoiceAllocatorNode {
self.voices[voice_idx].active = true;
self.voices[voice_idx].releasing = false;
self.voices[voice_idx].note = event.data1;
self.voices[voice_idx].note_channel = event.status & 0x0F;
self.voices[voice_idx].age = 0;
// Store MIDI event for this voice to process
@@ -295,10 +298,12 @@ impl AudioNode for VoiceAllocatorNode {
}
}
_ => {
// Other MIDI events (CC, pitch bend, etc.) - send to all active voices
// Route to matching-channel voices; channel 0 = global broadcast
let event_channel = event.status & 0x0F;
for voice_idx in 0..self.voice_count {
if self.voices[voice_idx].active {
self.voices[voice_idx].pending_events.push(*event);
let voice = &mut self.voices[voice_idx];
if voice.active && (event_channel == 0 || voice.note_channel == event_channel) {
voice.pending_events.push(*event);
}
}
}
@@ -343,7 +348,7 @@ impl AudioNode for VoiceAllocatorNode {
// Process this voice's graph with its MIDI events
// Note: playback_time is 0.0 since voice allocator doesn't track time
self.voice_instances[voice_idx].process(mix_slice, &midi_events, 0.0);
self.voice_instances[voice_idx].process(mix_slice, &midi_events, crate::time::Beats::ZERO);
// Auto-deactivate releasing voices that have gone silent
if voice_state.releasing {
@@ -100,6 +100,16 @@ fn default_version() -> u32 {
1
}
/// Serialized keyframe for AutomationInput nodes
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SerializedKeyframe {
pub time: f64,
pub value: f32,
pub interpolation: String,
pub ease_out: (f32, f32),
pub ease_in: (f32, f32),
}
/// Serialized node representation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SerializedNode {
@@ -131,6 +141,24 @@ pub struct SerializedNode {
/// For AmpSim nodes: path to the .nam model file
#[serde(skip_serializing_if = "Option::is_none")]
pub nam_model_path: Option<String>,
/// For dynamic-port nodes (Mixer, SubtrackInputs): saved port count so ports
/// round-trip correctly through save/load independent of connection order.
#[serde(skip_serializing_if = "Option::is_none")]
pub num_ports: Option<u32>,
/// For SubtrackInputs: ordered port names (one per subtrack slot).
/// Allows the UI to display actual track names on the node's output ports.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub port_names: Vec<String>,
/// For AutomationInput nodes: user-visible display name
#[serde(skip_serializing_if = "Option::is_none")]
pub automation_display_name: Option<String>,
/// For AutomationInput nodes: saved keyframes
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub automation_keyframes: Vec<SerializedKeyframe>,
}
/// Serialized group definition (frontend-only visual grouping, stored opaquely by backend)
@@ -227,6 +255,10 @@ impl SerializedNode {
sample_data: None,
script_source: None,
nam_model_path: None,
num_ports: None,
port_names: Vec::new(),
automation_display_name: None,
automation_keyframes: Vec::new(),
}
}
+336 -36
View File
@@ -2,6 +2,47 @@ use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::f32::consts::PI;
use serde::{Deserialize, Serialize};
use crate::time::Seconds;
/// Per-output-channel mix coefficients to fold a multichannel source down to
/// stereo, indexed `[out_channel(0=L,1=R)][src_channel]`.
///
/// Assumes the conventional interleave order for each channel count (FL, FR, FC,
/// LFE, BL, BR, SL, SR …). Uses standard ITU/AC-3-style coefficients: full level
/// for the matching front channel, `1/√2` (≈ −3 dB) for centre and each surround,
/// LFE dropped. Each row is then normalized so its absolute-coefficient sum ≤ 1,
/// which prevents clipping (matching FFmpeg's default `normalize` behaviour).
///
/// Returns `None` for layouts we don't special-case (caller falls back to taking
/// the front L/R pair).
fn stereo_downmix_matrix(src_channels: usize) -> Option<[Vec<f32>; 2]> {
const C: f32 = std::f32::consts::FRAC_1_SQRT_2; // ≈ 0.7071
// (L row, R row); each entry is the gain applied to that source channel.
let (l, r): (Vec<f32>, Vec<f32>) = match src_channels {
3 => (vec![1.0, 0.0, C], vec![0.0, 1.0, C]), // FL FR FC
4 => (vec![1.0, 0.0, C, 0.0], vec![0.0, 1.0, 0.0, C]), // quad: FL FR BL BR
5 => (vec![1.0, 0.0, C, C, 0.0], vec![0.0, 1.0, C, 0.0, C]), // FL FR FC BL BR
// 5.1: FL FR FC LFE BL BR (LFE dropped)
6 => (vec![1.0, 0.0, C, 0.0, C, 0.0], vec![0.0, 1.0, C, 0.0, 0.0, C]),
// 6.1: FL FR FC LFE BC SL SR (BC → both)
7 => (vec![1.0, 0.0, C, 0.0, C, C, 0.0], vec![0.0, 1.0, C, 0.0, C, 0.0, C]),
// 7.1: FL FR FC LFE BL BR SL SR
8 => (
vec![1.0, 0.0, C, 0.0, C, 0.0, C, 0.0],
vec![0.0, 1.0, C, 0.0, 0.0, C, 0.0, C],
),
_ => return None,
};
let normalize = |row: Vec<f32>| -> Vec<f32> {
let sum: f32 = row.iter().map(|c| c.abs()).sum();
if sum > 1.0 {
row.into_iter().map(|c| c / sum).collect()
} else {
row
}
};
Some([normalize(l), normalize(r)])
}
/// Windowed sinc interpolation for high-quality time stretching
/// This is stateless and can handle arbitrary fractional positions
@@ -82,6 +123,16 @@ pub enum AudioStorage {
decoded_frames: u64,
total_frames: u64,
},
/// Audio track of a video container, decoded on demand via FFmpeg
/// (`VideoAudioReader`). The source video file is `AudioFile::path`. Like
/// `Compressed`, playback is streamed through the disk reader and
/// `decoded_for_waveform` is filled progressively for the overview.
VideoAudio {
decoded_for_waveform: Vec<f32>,
decoded_frames: u64,
total_frames: u64,
},
}
/// Audio file stored in the pool
@@ -97,6 +148,10 @@ pub struct AudioFile {
pub original_format: Option<String>,
/// Original compressed file bytes (preserved across save/load to avoid re-encoding)
pub original_bytes: Option<Vec<u8>>,
/// When `Some`, this entry's bytes are packed in the project container (not on
/// disk at `path`); the disk reader opens them via the host's
/// `AudioBlobSourceFactory` using this media id. `None` ⇒ stream from `path`.
pub packed_media_id: Option<String>,
}
impl AudioFile {
@@ -111,6 +166,7 @@ impl AudioFile {
frames,
original_format: None,
original_bytes: None,
packed_media_id: None,
}
}
@@ -125,6 +181,7 @@ impl AudioFile {
frames,
original_format,
original_bytes: None,
packed_media_id: None,
}
}
@@ -157,6 +214,7 @@ impl AudioFile {
frames: total_frames,
original_format: Some("wav".to_string()),
original_bytes: None,
packed_media_id: None,
}
}
@@ -180,6 +238,35 @@ impl AudioFile {
frames: total_frames,
original_format,
original_bytes: None,
packed_media_id: None,
}
}
/// Create a placeholder AudioFile for a video's audio track. `path` is the
/// source video file; the audio is streamed on demand by the disk reader's
/// FFmpeg-backed `VideoAudioReader`. `packed_media_id` is `Some` when the video
/// bytes are packed in the `.beam` container (audio streams from the same blob
/// via the host factory); `None` when the audio comes from an external video file.
pub fn from_video_audio(
path: PathBuf,
channels: u32,
sample_rate: u32,
total_frames: u64,
packed_media_id: Option<String>,
) -> Self {
Self {
path,
storage: AudioStorage::VideoAudio {
decoded_for_waveform: Vec::new(),
decoded_frames: 0,
total_frames,
},
channels,
sample_rate,
frames: total_frames,
original_format: None,
original_bytes: None,
packed_media_id,
}
}
@@ -273,8 +360,8 @@ impl AudioFile {
}
written
}
AudioStorage::Compressed { .. } => {
// Compressed files are read through the disk reader
AudioStorage::Compressed { .. } | AudioStorage::VideoAudio { .. } => {
// Streamed through the disk reader, not via read_samples().
0
}
}
@@ -442,19 +529,20 @@ impl AudioClipPool {
}
/// Render audio from a file in the pool with high-quality windowed sinc interpolation
/// start_time_seconds: position in the audio file to start reading from (in seconds)
/// start_time: position in the audio file to start reading from (in seconds)
/// clip_read_ahead: per-clip-instance read-ahead buffer for compressed audio streaming
/// Returns the number of samples actually rendered
pub fn render_from_file(
&self,
pool_index: usize,
output: &mut [f32],
start_time_seconds: f64,
start_time: Seconds,
gain: f32,
engine_sample_rate: u32,
engine_channels: u32,
clip_read_ahead: Option<&super::disk_reader::ReadAheadBuffer>,
) -> usize {
let start_time_seconds = start_time.0;
let Some(audio_file) = self.files.get(pool_index) else {
return 0;
};
@@ -489,6 +577,27 @@ impl AudioClipPool {
// Spin-wait with small sleeps until the disk reader fills the buffer
let mut wait_iters = 0u64;
while !ra.has_range(src_start, frames_needed) {
// The source reached EOF and these frames are past the end of the
// audio (e.g. a video whose audio track is shorter than the video,
// or a container without exact stream duration). They will never
// arrive — stop waiting and let the render fill silence, instead of
// burning the 10s safety valve on every remaining chunk.
//
// BUT `finished` may be stale: we just moved the target with
// `set_target_frame`, and on a forward jump past the buffer the reader
// will reset()+seek() (clearing `finished`) on its next poll. The reader
// re-seeks when `target < buf_start || target > buf_end + sample_rate`
// (see disk_reader.rs), so only trust EOF when the target is inside the
// current window — otherwise a stale flag from the previous region would
// make us render silence over audio that's about to be decoded.
if ra.is_finished() {
let (buf_start, buf_end) = ra.snapshot();
let sr = audio_file.sample_rate as u64;
let seek_pending = src_start < buf_start || src_start > buf_end + sr;
if !seek_pending {
break;
}
}
std::thread::sleep(std::time::Duration::from_micros(100));
wait_iters += 1;
if wait_iters > 100_000 {
@@ -535,6 +644,15 @@ impl AudioClipPool {
let dst_channels = engine_channels as usize;
let output_frames = output.len() / dst_channels;
// Fold a multichannel source (5.1, 7.1, …) down to stereo with proper
// coefficients (centre + surrounds mixed in, LFE dropped) instead of just
// taking the front L/R pair. `None` ⇒ no downmix needed / unknown layout.
let downmix = if dst_channels == 2 && src_channels > 2 {
stereo_downmix_matrix(src_channels)
} else {
None
};
let src_start_position = start_time_seconds * audio_file.sample_rate as f64;
// Tell the disk reader where we're reading so it buffers the right region.
@@ -580,6 +698,15 @@ impl AudioClipPool {
sum += get_sample!(sf, src_ch);
}
sum / src_channels as f32
} else if let Some(ref mat) = downmix {
// Surround → stereo with proper coefficients.
let mut s = 0.0f32;
for (src_ch, &c) in mat[dst_ch].iter().enumerate() {
if c != 0.0 {
s += c * get_sample!(sf, src_ch);
}
}
s
} else {
get_sample!(sf, dst_ch % src_channels)
};
@@ -604,39 +731,45 @@ impl AudioClipPool {
break;
}
for dst_ch in 0..dst_channels {
let src_ch = if src_channels == dst_channels {
dst_ch
} else if src_channels == 1 {
0
} else if dst_channels == 1 {
usize::MAX // sentinel: average all channels below
} else {
dst_ch % src_channels
};
let sample = if src_ch == usize::MAX {
let mut sum = 0.0;
for ch in 0..src_channels {
let mut channel_samples = [0.0f32; KERNEL_SIZE];
for (j, i) in (-(HALF_KERNEL as i32)..(HALF_KERNEL as i32)).enumerate() {
let idx = src_frame + i;
if idx >= 0 && (idx as usize) < audio_file.frames as usize {
channel_samples[j] = get_sample!(idx as usize, ch);
}
}
sum += windowed_sinc_interpolate(&channel_samples, frac);
}
sum / src_channels as f32
} else {
// Sinc-interpolate a single source channel at the current position.
macro_rules! sinc_ch {
($ch:expr) => {{
let mut channel_samples = [0.0f32; KERNEL_SIZE];
for (j, i) in (-(HALF_KERNEL as i32)..(HALF_KERNEL as i32)).enumerate() {
let idx = src_frame + i;
if idx >= 0 && (idx as usize) < audio_file.frames as usize {
channel_samples[j] = get_sample!(idx as usize, src_ch);
channel_samples[j] = get_sample!(idx as usize, $ch);
}
}
windowed_sinc_interpolate(&channel_samples, frac)
}};
}
for dst_ch in 0..dst_channels {
let sample = if let Some(ref mat) = downmix {
// Surround → stereo: interpolate each contributing channel.
let mut s = 0.0f32;
for (ch, &c) in mat[dst_ch].iter().enumerate() {
if c != 0.0 {
s += c * sinc_ch!(ch);
}
}
s
} else if dst_channels == 1 {
let mut sum = 0.0;
for ch in 0..src_channels {
sum += sinc_ch!(ch);
}
sum / src_channels as f32
} else {
let src_ch = if src_channels == dst_channels {
dst_ch
} else if src_channels == 1 {
0
} else {
dst_ch % src_channels
};
sinc_ch!(src_ch)
};
output[output_frame * dst_channels + dst_ch] += sample * gain;
@@ -784,6 +917,25 @@ pub struct AudioPoolEntry {
pub channels: u32,
/// Embedded audio data (for files < 10MB)
pub embedded_data: Option<EmbeddedAudioData>,
/// Stable media id (UUID string) for the SQLite `.beam` container. When set,
/// the audio bytes live in the container's `media` table keyed by this id
/// (packed storage). `None` for referenced entries (use `relative_path`) or
/// legacy ZIP-loaded entries. Populated by the file_io save/load layer.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub media_id: Option<String>,
/// Transient carrier for this entry's serialized waveform-pyramid blob (LBWF
/// bytes). Never serialized into project.json — the bytes live in the
/// container's `media` table (kind `Waveform`). Set by the file_io save layer
/// (in) and load layer (out); `None` everywhere else.
#[serde(skip)]
pub waveform_blob: Option<Vec<u8>>,
/// This entry is a video container's audio track (`relative_path` points at the
/// video file). It is always stored as a path reference (never packed/embedded
/// — the `VideoClip` already references the file) and reloaded by re-probing
/// the video via FFmpeg, so multichannel (5.1/7.1) audio survives the round-trip
/// (Symphonia reconstitution would otherwise collapse it).
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub is_video_audio: bool,
}
impl AudioClipPool {
@@ -798,6 +950,66 @@ impl AudioClipPool {
let mut entries = Vec::new();
for (index, file) in self.files.iter().enumerate() {
// Skip placeholder pool slots: `load_from_serialized` resizes the pool to
// `max_index + 1` filled with empty `AudioFile::new(PathBuf::new(), …)` to
// cover index gaps (and creates one even when there are no entries at all).
// Such a slot has an empty path and no packed media — there's nothing to
// persist, and emitting it yields an entry whose empty `relative_path`
// resolves to the project directory itself (unreadable on the next save).
if file.path.as_os_str().is_empty() && file.packed_media_id.is_none() {
continue;
}
// Video's audio track: reference the video file (it's also referenced
// by the VideoClip) and re-probe it via FFmpeg on load. Never pack or
// embed it as audio media — that both wastes space and loses the 5.1+
// layout when Symphonia later decodes it.
if matches!(file.storage, AudioStorage::VideoAudio { .. }) {
let relative_path = pathdiff::diff_paths(&file.path, project_dir)
.map(|r| r.to_string_lossy().to_string())
.or_else(|| Some(file.path.to_string_lossy().to_string()));
entries.push(AudioPoolEntry {
pool_index: index,
is_video_audio: true,
waveform_blob: None,
name: file
.path
.file_name()
.map(|n| n.to_string_lossy().to_string())
.unwrap_or_else(|| format!("file_{}", index)),
relative_path,
duration: file.duration_seconds(),
sample_rate: file.sample_rate,
channels: file.channels,
embedded_data: None,
media_id: None,
});
continue;
}
// Packed-in-container streaming entry: its bytes already live in the
// `.beam` media table (kept in place across re-saves). Emit just the
// media id — no path, no embedded bytes, nothing to decode.
if let Some(media_id) = &file.packed_media_id {
entries.push(AudioPoolEntry {
pool_index: index,
is_video_audio: false,
waveform_blob: None,
name: file
.path
.file_name()
.map(|n| n.to_string_lossy().to_string())
.unwrap_or_else(|| format!("file_{}", index)),
relative_path: None,
duration: file.duration_seconds(),
sample_rate: file.sample_rate,
channels: file.channels,
embedded_data: None,
media_id: Some(media_id.clone()),
});
continue;
}
let file_path = &file.path;
let file_path_str = file_path.to_string_lossy();
@@ -828,6 +1040,8 @@ impl AudioClipPool {
let entry = AudioPoolEntry {
pool_index: index,
is_video_audio: false,
waveform_blob: None,
name: file_path
.file_name()
.map(|n| n.to_string_lossy().to_string())
@@ -837,6 +1051,7 @@ impl AudioClipPool {
sample_rate: file.sample_rate,
channels: file.channels,
embedded_data,
media_id: None,
};
entries.push(entry);
@@ -960,22 +1175,107 @@ impl AudioClipPool {
self.files.clear();
eprintln!("📊 [LOAD_SERIALIZED] Clear pool took {:.2}ms", clear_start.elapsed().as_secs_f64() * 1000.0);
// Find the maximum pool index to determine required size
let max_index = entries.iter()
.map(|e| e.pool_index)
// Size the pool to hold the highest pool_index (slots are addressed by index,
// so gaps are filled with placeholders). No entries → length 0, NOT 1: the old
// `max().unwrap_or(0) + 1` produced a spurious placeholder for an empty pool.
let pool_size = entries.iter()
.map(|e| e.pool_index + 1)
.max()
.unwrap_or(0);
// Ensure we have space for all entries
let resize_start = std::time::Instant::now();
self.files.resize(max_index + 1, AudioFile::new(PathBuf::new(), Vec::new(), 2, 44100));
eprintln!("📊 [LOAD_SERIALIZED] Resize pool to {} took {:.2}ms", max_index + 1, resize_start.elapsed().as_secs_f64() * 1000.0);
self.files.resize(pool_size, AudioFile::new(PathBuf::new(), Vec::new(), 2, 44100));
eprintln!("📊 [LOAD_SERIALIZED] Resize pool to {} took {:.2}ms", pool_size, resize_start.elapsed().as_secs_f64() * 1000.0);
for (i, entry) in entries.iter().enumerate() {
let entry_start = std::time::Instant::now();
eprintln!("📊 [LOAD_SERIALIZED] Processing entry {}/{}: '{}'", i + 1, entries.len(), entry.name);
let success = if let Some(ref embedded) = entry.embedded_data {
let success = if entry.is_video_audio && entry.media_id.is_some() {
// Packed video: the audio track lives in the same container blob as
// the video. Build a streaming VideoAudio entry from the saved
// metadata (no probe needed); playback opens the blob via the host
// factory at clip-activation time → VideoAudioReader::open_source.
let media_id = entry.media_id.clone().unwrap();
let total_frames = (entry.duration * entry.sample_rate as f64).ceil() as u64;
let file = AudioFile::from_video_audio(
PathBuf::new(),
entry.channels,
entry.sample_rate,
total_frames,
Some(media_id),
);
if entry.pool_index < self.files.len() {
self.files[entry.pool_index] = file;
true
} else {
false
}
} else if entry.is_video_audio {
// Re-probe the video's audio track via FFmpeg → a streaming
// VideoAudio entry (keeps full 5.1/7.1; no decode-to-RAM).
match entry.relative_path.as_ref() {
Some(rel) => {
let full = if std::path::Path::new(rel).is_absolute() {
PathBuf::from(rel)
} else {
project_dir.join(rel)
};
if full.exists() {
match crate::audio::disk_reader::VideoAudioReader::open(&full) {
Ok(reader) => {
let file = AudioFile::from_video_audio(
full,
reader.channels(),
reader.sample_rate(),
reader.total_frames(),
None,
);
if entry.pool_index < self.files.len() {
self.files[entry.pool_index] = file;
true
} else {
false
}
}
Err(e) => {
eprintln!("[AudioPool] Failed to reopen video audio {:?}: {}", full, e);
false
}
}
} else {
eprintln!("[AudioPool] Video file not found for audio: {:?}", full);
false
}
}
None => false,
}
} else if entry.media_id.is_some() && entry.embedded_data.is_none() {
// Packed-in-container streaming entry: build a Compressed placeholder
// backed by the host blob factory (opened at clip-activation time).
// No decode here — playback streams through the disk reader.
let media_id = entry.media_id.clone().unwrap();
let ext = std::path::Path::new(&entry.name)
.extension()
.and_then(|e| e.to_str())
.map(|s| s.to_lowercase());
let total_frames = (entry.duration * entry.sample_rate as f64).ceil() as u64;
let mut file = AudioFile::from_compressed(
PathBuf::from(&entry.name),
entry.channels,
entry.sample_rate,
total_frames,
ext,
);
file.packed_media_id = Some(media_id);
if entry.pool_index < self.files.len() {
self.files[entry.pool_index] = file;
true
} else {
false
}
} else if let Some(ref embedded) = entry.embedded_data {
// Load from embedded data
eprintln!("📊 [LOAD_SERIALIZED] Entry has embedded data (format: {})", embedded.format);
match Self::load_from_embedded_into_pool(self, entry.pool_index, embedded.clone(), &entry.name) {
+71 -57
View File
@@ -4,6 +4,8 @@ use super::midi::{MidiClip, MidiClipId, MidiClipInstance, MidiClipInstanceId, Mi
use super::midi_pool::MidiClipPool;
use super::pool::AudioClipPool;
use super::track::{AudioTrack, Metatrack, MidiTrack, RenderContext, TrackId, TrackNode};
use crate::tempo_map::TempoMap;
use crate::time::{Beats, Seconds};
use serde::{Serialize, Deserialize};
use std::collections::HashMap;
@@ -39,6 +41,11 @@ impl Project {
}
}
/// The project's system sample rate in Hz.
pub fn sample_rate(&self) -> u32 {
self.sample_rate
}
/// Generate a new unique track ID
fn next_id(&mut self) -> TrackId {
let id = self.next_track_id;
@@ -211,6 +218,11 @@ impl Project {
self.tracks.get_mut(&track_id)
}
/// Iterate over all tracks in the project.
pub fn track_iter(&self) -> impl Iterator<Item = (TrackId, &TrackNode)> {
self.tracks.iter().map(|(&id, node)| (id, node))
}
/// Get oscilloscope data from a node in a track's graph
pub fn get_oscilloscope_data(&self, track_id: TrackId, node_id: u32, sample_count: usize) -> Option<(Vec<f32>, Vec<f32>)> {
if let Some(TrackNode::Midi(track)) = self.tracks.get(&track_id) {
@@ -283,9 +295,9 @@ impl Project {
&mut self,
track_id: TrackId,
events: Vec<MidiEvent>,
duration: f64,
duration: Beats,
name: String,
external_start: f64,
external_start: Beats,
) -> Result<(MidiClipId, MidiClipInstanceId), &'static str> {
// Verify track exists and is a MIDI track
if !matches!(self.tracks.get(&track_id), Some(TrackNode::Midi(_))) {
@@ -318,11 +330,11 @@ impl Project {
/// Legacy method for backwards compatibility - creates clip and instance from old MidiClip format
pub fn add_midi_clip(&mut self, track_id: TrackId, clip: MidiClip) -> Result<MidiClipInstanceId, &'static str> {
self.add_midi_clip_at(track_id, clip, 0.0)
self.add_midi_clip_at(track_id, clip, Beats::ZERO)
}
/// Add a MIDI clip to the pool and create an instance at the given timeline position
pub fn add_midi_clip_at(&mut self, track_id: TrackId, clip: MidiClip, start_time: f64) -> Result<MidiClipInstanceId, &'static str> {
pub fn add_midi_clip_at(&mut self, track_id: TrackId, clip: MidiClip, start_time: Beats) -> Result<MidiClipInstanceId, &'static str> {
// Add the clip to the pool (it already has events and duration)
let duration = clip.duration;
let clip_id = clip.id;
@@ -356,27 +368,33 @@ impl Project {
}
}
/// Render all root tracks into the output buffer
/// Render all root tracks into the output buffer.
///
/// When `live_only` is true, MIDI tracks skip clip event collection and only process
/// their live MIDI queue (note-off tails + keyboard input). Audio tracks produce silence.
/// This lets the caller use the same group-hierarchy render path regardless of play state.
pub fn render(
&mut self,
output: &mut [f32],
audio_pool: &AudioClipPool,
buffer_pool: &mut BufferPool,
playhead_seconds: f64,
playhead_seconds: Seconds,
tempo_map: &TempoMap,
sample_rate: u32,
channels: u32,
live_only: bool,
recording_midi: Option<(TrackId, MidiClipId)>,
) {
output.fill(0.0);
let any_solo = self.any_solo();
// Create initial render context
let ctx = RenderContext::new(
playhead_seconds,
sample_rate,
channels,
output.len(),
);
let ctx = RenderContext {
live_only,
recording_midi,
..RenderContext::new(playhead_seconds, tempo_map, sample_rate, channels, output.len())
};
// Render each root track (index-based to avoid clone)
for i in 0..self.root_tracks.len() {
@@ -441,11 +459,15 @@ impl Project {
// Handle audio track vs MIDI track vs group track
match self.tracks.get_mut(&track_id) {
Some(TrackNode::Audio(track)) => {
// Audio tracks have no live input; skip in live_only mode.
if ctx.live_only {
return;
}
// Render audio track into a temp buffer for peak measurement
let mut track_buffer = buffer_pool.acquire();
track_buffer.resize(output.len(), 0.0);
track_buffer.fill(0.0);
track.render(&mut track_buffer, audio_pool, ctx.playhead_seconds, ctx.sample_rate, ctx.channels);
track.render(&mut track_buffer, audio_pool, ctx);
// Accumulate peak level for VU metering (max over meter interval)
let buffer_peak = track_buffer.iter().map(|s| s.abs()).fold(0.0f32, f32::max);
track.peak_level = track.peak_level.max(buffer_peak);
@@ -460,7 +482,7 @@ impl Project {
let mut track_buffer = buffer_pool.acquire();
track_buffer.resize(output.len(), 0.0);
track_buffer.fill(0.0);
track.render(&mut track_buffer, &self.midi_clip_pool, ctx.playhead_seconds, ctx.sample_rate, ctx.channels);
track.render(&mut track_buffer, &self.midi_clip_pool, ctx);
// Accumulate peak level for VU metering (max over meter interval)
let buffer_peak = track_buffer.iter().map(|s| s.abs()).fold(0.0f32, f32::max);
track.peak_level = track.peak_level.max(buffer_peak);
@@ -471,72 +493,75 @@ impl Project {
buffer_pool.release(track_buffer);
}
Some(TrackNode::Group(group)) => {
// Skip rendering if playhead is outside the metatrack's trim window
if !group.is_active_at_time(ctx.playhead_seconds) {
// Skip rendering if playhead is outside the metatrack's trim window.
// In live_only mode always render so note-off tails pass through the mixer.
if !ctx.live_only && !group.is_active_at_time(ctx.playhead_seconds) {
return;
}
// Read group properties and transform context (index-based child iteration to avoid clone)
// Read group properties and transform context before any mutable borrows
let num_children = group.children.len();
let this_group_is_soloed = group.solo;
let child_ctx = group.transform_context(ctx);
// Acquire a temporary buffer for the group mix
let mut group_buffer = buffer_pool.acquire();
group_buffer.resize(output.len(), 0.0);
group_buffer.fill(0.0);
// Recursively render all children into the group buffer
// If this group is soloed (or parent was soloed), children inherit that state
let children_parent_soloed = parent_is_soloed || this_group_is_soloed;
// Render each child into its own buffer and inject into SubtrackInputsNode.
// One pool buffer is reused per child (no extra allocation per frame).
for i in 0..num_children {
let child_id = match self.tracks.get(&track_id) {
Some(TrackNode::Group(g)) => g.children[i],
_ => break,
};
let mut child_buffer = buffer_pool.acquire();
child_buffer.resize(output.len(), 0.0);
child_buffer.fill(0.0);
self.render_track(
child_id,
&mut group_buffer,
&mut child_buffer,
audio_pool,
buffer_pool,
child_ctx,
any_solo,
children_parent_soloed,
);
}
// Route children's mix through metatrack's audio graph
if let Some(TrackNode::Group(group)) = self.tracks.get_mut(&track_id) {
// Inject children's mix into audio graph's input node
let node_indices: Vec<_> = group.audio_graph.node_indices().collect();
for node_idx in node_indices {
if let Some(graph_node) = group.audio_graph.get_graph_node_mut(node_idx) {
if graph_node.node.node_type() == "AudioInput" {
if let Some(input_node) = graph_node.node.as_any_mut()
.downcast_mut::<super::node_graph::nodes::AudioInputNode>()
{
input_node.inject_audio(&group_buffer);
// Inject into the SubtrackInputsNode slot for this child
if let Some(TrackNode::Group(group)) = self.tracks.get_mut(&track_id) {
use super::node_graph::nodes::SubtrackInputsNode;
let node_indices: Vec<_> = group.audio_graph.node_indices().collect();
for node_idx in node_indices {
if let Some(gn) = group.audio_graph.get_graph_node_mut(node_idx) {
if gn.node.node_type() == "SubtrackInputs" {
if let Some(si) = gn.node.as_any_mut()
.downcast_mut::<SubtrackInputsNode>()
{
if let Some(slot) = si.subtrack_index_for(child_id) {
si.inject_subtrack_audio(slot, &child_buffer);
}
}
break;
}
}
}
}
// Process through the audio graph into a fresh buffer
buffer_pool.release(child_buffer);
}
// Process children's audio through the metatrack's mixing graph
if let Some(TrackNode::Group(group)) = self.tracks.get_mut(&track_id) {
let mut graph_output = buffer_pool.acquire();
graph_output.resize(output.len(), 0.0);
graph_output.fill(0.0);
group.audio_graph.process(&mut graph_output, &[], ctx.playhead_seconds);
group.audio_graph.process(&mut graph_output, &[], ctx.playhead_beats());
// Apply group volume and mix into output
for (out_sample, graph_sample) in output.iter_mut().zip(graph_output.iter()) {
*out_sample += graph_sample * group.volume;
}
buffer_pool.release(graph_output);
}
// Release children mix buffer back to pool
buffer_pool.release(group_buffer);
}
None => {}
}
@@ -620,23 +645,12 @@ impl Project {
}
}
/// Process live MIDI input from all MIDI tracks (called even when not playing)
pub fn process_live_midi(&mut self, output: &mut [f32], sample_rate: u32, channels: u32) {
// Process all MIDI tracks to handle queued live input events
for track in self.tracks.values_mut() {
if let TrackNode::Midi(midi_track) = track {
// Process only queued live events, not clips
midi_track.process_live_input(output, sample_rate, channels);
}
}
}
/// Send a live MIDI note on event to a track's instrument
/// Note: With node-based instruments, MIDI events are handled during the process() call
pub fn send_midi_note_on(&mut self, track_id: TrackId, note: u8, velocity: u8) {
// Queue the MIDI note-on event to the track's live MIDI queue
if let Some(TrackNode::Midi(track)) = self.tracks.get_mut(&track_id) {
let event = MidiEvent::note_on(0.0, 0, note, velocity);
let event = MidiEvent::note_on(Beats::ZERO, 0, note, velocity);
track.queue_live_midi(event);
}
}
@@ -645,7 +659,7 @@ impl Project {
pub fn send_midi_note_off(&mut self, track_id: TrackId, note: u8) {
// Queue the MIDI note-off event to the track's live MIDI queue
if let Some(TrackNode::Midi(track)) = self.tracks.get_mut(&track_id) {
let event = MidiEvent::note_off(0.0, 0, note, 0);
let event = MidiEvent::note_off(Beats::ZERO, 0, note, 0);
track.queue_live_midi(event);
}
}
+484 -67
View File
@@ -1,9 +1,65 @@
/// Audio recording system for capturing microphone input
use crate::audio::{ClipId, MidiClipId, TrackId};
use crate::io::{WavWriter, WaveformPeak};
use crate::time::{Beats, Seconds};
use std::collections::HashMap;
use std::path::PathBuf;
/// Cycle-recording bookkeeping attached to a recording that started with a cycle region armed.
///
/// Takes are sliced **geometrically** at stop, in exact `loop_len_frames` multiples — not at the
/// instant the wrap was detected. The playhead advances before the capture block in `process()`, so
/// the wrap instant isn't sample-exact against the buffer that was just captured, but the geometry
/// is. `wrap_count` therefore only decides *whether* this is a multi-take recording, never where the
/// cuts land.
#[derive(Debug, Clone, Copy)]
pub struct CycleRecordInfo {
/// Where the cycle region starts, in beats. Takes are laid down here, not at the punch-in point.
pub loop_start: Beats,
/// The cycle region's length in beats — what the take folder records as `recorded_loop_beats`.
pub loop_len_beats: Beats,
/// One cycle pass, in frames. The take size.
pub loop_len_frames: usize,
/// Frames between the region start and where capture actually began. Non-zero only for a
/// punch-in (record while already rolling); take 1 gets this much silence prepended so it still
/// spans the whole region.
pub lead_pad_frames: usize,
/// How many times the transport wrapped during this recording. Zero normally means the user
/// stopped before completing a pass, which stays an ordinary single recording — unless
/// `force_takes` says otherwise.
pub wrap_count: usize,
/// Cut takes even if the transport never wrapped.
///
/// Set when the region already holds takes: a further recording there is another take, however
/// short, and it gets padded out to the region like any partial pass. Without this a run that
/// stopped before the loop came round would land as a separate overlapping clip instead of
/// joining the take list.
///
/// The editor decides this at record start, because whether takes already exist is document
/// state the engine can't see.
pub force_takes: bool,
}
/// Min/max waveform peaks for a finished buffer of interleaved samples.
///
/// The live recording path builds its peaks incrementally as samples arrive; cycle takes don't
/// exist until the recording is sliced at stop, so they get theirs in one pass here.
pub fn compute_peaks(samples: &[f32], channels: u32, frames_per_peak: usize) -> Vec<WaveformPeak> {
let samples_per_peak = (frames_per_peak * channels.max(1) as usize).max(1);
samples
.chunks(samples_per_peak)
.map(|chunk| {
let mut min = 0.0f32;
let mut max = 0.0f32;
for s in chunk {
min = min.min(*s);
max = max.max(*s);
}
WaveformPeak { min, max }
})
.collect()
}
/// State of an active recording session
pub struct RecordingState {
/// Track being recorded to
@@ -18,8 +74,8 @@ pub struct RecordingState {
pub sample_rate: u32,
/// Number of channels
pub channels: u32,
/// Timeline start position in seconds
pub start_time: f64,
/// Timeline start position
pub start_time: Beats,
/// Total frames recorded
pub frames_written: usize,
/// Whether recording is currently paused
@@ -34,6 +90,8 @@ pub struct RecordingState {
pub frames_per_peak: usize,
/// All recorded audio data accumulated in memory (written to disk at finalization)
pub audio_data: Vec<f32>,
/// Cycle-recording bookkeeping, when a cycle region was armed at record start.
pub cycle: Option<CycleRecordInfo>,
}
impl RecordingState {
@@ -45,7 +103,7 @@ impl RecordingState {
writer: WavWriter,
sample_rate: u32,
channels: u32,
start_time: f64,
start_time: Beats,
_flush_interval_seconds: f64, // No longer used - kept for API compatibility
) -> Self {
// Calculate frames per waveform peak
@@ -68,9 +126,69 @@ impl RecordingState {
waveform_buffer: Vec::new(),
frames_per_peak,
audio_data: Vec::new(),
cycle: None,
}
}
/// Slice the recording into cycle takes: one per pass, each spanning the FULL cycle region.
///
/// Partial passes are padded with silence — the head of take 1 for a punch-in, the tail of the
/// last take when the user stops mid-pass — so every take is the same length and aligned to the
/// region. That uniformity is what makes comping-via-split work: take 1 on the left half and
/// take 3 on the right always line up.
///
/// Returns `None` if this wasn't a cycle recording or the transport never wrapped (an ordinary
/// single recording, which keeps the existing path untouched).
pub fn slice_takes(&self) -> Option<Vec<Vec<f32>>> {
let cycle = self.cycle?;
if (cycle.wrap_count == 0 && !cycle.force_takes) || cycle.loop_len_frames == 0 {
return None;
}
let ch = self.channels.max(1) as usize;
let take_len = cycle.loop_len_frames * ch;
let lead = cycle.lead_pad_frames * ch;
// The recording as positioned *within the region*: silence for the gap between the region
// start and the punch-in, then the captured audio. Slicing this at whole-take boundaries is
// the whole trick — take 1 comes out short-by-`lead` at the front, already padded.
let virtual_len = lead + self.audio_data.len();
let take_count = virtual_len.div_ceil(take_len);
let mut takes: Vec<Vec<f32>> = Vec::with_capacity(take_count);
for i in 0..take_count {
let mut take = vec![0.0f32; take_len];
let take_begin = i * take_len;
for slot in 0..take_len {
// Position in the virtual (lead-padded) buffer.
let v = take_begin + slot;
if v < lead {
continue; // still in the punch-in silence
}
match self.audio_data.get(v - lead) {
Some(s) => take[slot] = *s,
None => break, // past the end of capture; the rest stays silent
}
}
takes.push(take);
}
// A final take holding only a sliver of real audio is a stop artifact (the user hit stop a
// moment after the wrap), not a performance. Drop it — but only if it's actually a PARTIAL
// pass, and never the only take. A pass that filled the region is a real take no matter how
// short the region is.
const MIN_TAKE_SECONDS: f64 = 0.05;
if takes.len() > 1 {
let last_real_samples = virtual_len - (takes.len() - 1) * take_len;
let last_real_seconds = (last_real_samples / ch) as f64 / self.sample_rate as f64;
if last_real_samples < take_len && last_real_seconds < MIN_TAKE_SECONDS {
takes.pop();
}
}
Some(takes)
}
/// Add samples to the accumulation buffer
/// Returns true if a flush occurred
pub fn add_samples(&mut self, samples: &[f32]) -> Result<bool, std::io::Error> {
@@ -130,9 +248,9 @@ impl RecordingState {
}
}
/// Get current recording duration in seconds
pub fn duration(&self) -> f64 {
self.frames_written as f64 / self.sample_rate as f64
/// Get current recording duration
pub fn duration(&self) -> Seconds {
Seconds(self.frames_written as f64 / self.sample_rate as f64)
}
/// Finalize the recording and return the temp file path, waveform, and audio data
@@ -175,107 +293,406 @@ impl RecordingState {
/// Active MIDI note waiting for its noteOff event
#[derive(Debug, Clone)]
struct ActiveMidiNote {
/// MIDI note number (0-127)
note: u8,
/// Velocity (0-127)
velocity: u8,
/// Absolute time when note started (seconds)
start_time: f64,
start_time: Beats,
}
/// State of an active MIDI recording session
/// State of an active MIDI recording session.
pub struct MidiRecordingState {
/// Track being recorded to
pub track_id: TrackId,
/// MIDI clip ID
pub clip_id: MidiClipId,
/// Timeline start position in seconds
pub start_time: f64,
/// Currently active notes (noteOn without matching noteOff)
/// Maps note number to ActiveMidiNote
pub start_time: Beats,
active_notes: HashMap<u8, ActiveMidiNote>,
/// Completed notes ready to be added to clip
/// Format: (time_offset, note, velocity, duration)
pub completed_notes: Vec<(f64, u8, u8, f64)>,
/// Completed notes: (time_offset, note, velocity, duration) — all times in beats
pub completed_notes: Vec<(Beats, u8, u8, Beats)>,
/// The cycle region's length in beats, if one was armed at record start.
///
/// A cycle MIDI recording is anchored at the region start (`start_time == loop_start`), which is
/// what makes MERGE fall out for free: the transport always wraps back into the region, so every
/// note's offset already lands inside `[0, loop_len)` and successive passes overdub onto each
/// other with no folding needed.
pub cycle_loop_len: Option<Beats>,
/// Whether the transport actually came round. Distinct from `cycle_loop_len`, which only says a
/// region was armed: the clip only pins to the full region once a pass has completed, so until
/// then the bar still grows with the playhead.
pub wrapped: bool,
/// Cut takes even if the transport never wrapped — see [`CycleRecordInfo::force_takes`].
pub force_takes: bool,
/// Which cycle pass is currently being recorded (0-based). Bumped at each wrap.
current_pass: usize,
/// The pass each completed note belongs to, parallel to `completed_notes`.
///
/// Only meaningful in "separate takes" mode, where each pass becomes its own MIDI clip. Merge
/// mode ignores it — all passes fold into one clip, which is the whole point.
note_pass: Vec<usize>,
}
impl MidiRecordingState {
/// Create a new MIDI recording state
pub fn new(track_id: TrackId, clip_id: MidiClipId, start_time: f64) -> Self {
pub fn new(track_id: TrackId, clip_id: MidiClipId, start_time: Beats) -> Self {
Self {
track_id,
clip_id,
start_time,
active_notes: HashMap::new(),
completed_notes: Vec::new(),
cycle_loop_len: None,
wrapped: false,
force_takes: false,
current_pass: 0,
note_pass: Vec::new(),
}
}
/// Handle a MIDI note on event
pub fn note_on(&mut self, note: u8, velocity: u8, absolute_time: f64) {
// Store this note as active
self.active_notes.insert(note, ActiveMidiNote {
note,
velocity,
start_time: absolute_time,
});
/// Record a finished note, tagging it with the pass it was played in.
///
/// Every completion goes through here so `completed_notes` and `note_pass` can't drift apart.
fn push_completed(&mut self, note: &ActiveMidiNote, end_time: Beats) {
let note_start = note.start_time.max(self.start_time);
self.completed_notes.push((
note_start - self.start_time,
note.note,
note.velocity,
end_time - note_start,
));
self.note_pass.push(self.current_pass);
}
/// Handle a MIDI note off event
pub fn note_off(&mut self, note: u8, absolute_time: f64) {
// Find the matching noteOn
pub fn note_on(&mut self, note: u8, velocity: u8, absolute_time: Beats) {
self.active_notes.insert(note, ActiveMidiNote { note, velocity, start_time: absolute_time });
}
pub fn note_off(&mut self, note: u8, absolute_time: Beats) {
if let Some(active_note) = self.active_notes.remove(&note) {
// Calculate relative time offset and duration
let time_offset = active_note.start_time - self.start_time;
let duration = absolute_time - active_note.start_time;
eprintln!("[MIDI_RECORDING_STATE] Completing note {}: note_start={:.3}s, note_end={:.3}s, recording_start={:.3}s, time_offset={:.3}s, duration={:.3}s",
note, active_note.start_time, absolute_time, self.start_time, time_offset, duration);
// Add to completed notes
self.completed_notes.push((
time_offset,
active_note.note,
active_note.velocity,
duration,
));
if absolute_time <= self.start_time {
return;
}
self.push_completed(&active_note, absolute_time);
}
// If no matching noteOn found, ignore the noteOff
}
/// Get all completed notes
pub fn get_notes(&self) -> &[(f64, u8, u8, f64)] {
/// Completed notes grouped by cycle pass — one bucket per pass, in recording order.
///
/// Used by "separate takes" mode, where each pass becomes its own MIDI clip.
///
/// An *interior* pass in which nothing was played still yields an empty take, so take N in the
/// folder is always pass N on the transport — otherwise the numbering would silently shift and
/// "take 3" would stop meaning "the third time round". A *trailing* empty pass is dropped
/// though: that's what you get by hitting stop shortly after a wrap, and it's a stop artifact
/// rather than a take you played. (Same reasoning as the audio path's short-final-take rule.)
pub fn notes_by_pass(&self, passes: usize) -> Vec<Vec<(Beats, u8, u8, Beats)>> {
let mut buckets = vec![Vec::new(); passes.max(1)];
for (note, &pass) in self.completed_notes.iter().zip(self.note_pass.iter()) {
if let Some(bucket) = buckets.get_mut(pass) {
bucket.push(*note);
}
}
// Never drop the only take.
while buckets.len() > 1 && buckets.last().is_some_and(|b| b.is_empty()) {
buckets.pop();
}
buckets
}
/// How many cycle passes this recording covered (1 if the transport never wrapped).
pub fn pass_count(&self) -> usize {
self.current_pass + 1
}
pub fn get_notes(&self) -> &[(Beats, u8, u8, Beats)] {
&self.completed_notes
}
/// Get the number of completed notes
pub fn note_count(&self) -> usize {
self.completed_notes.len()
}
/// Get the note numbers of all currently held (active) notes
/// The still-held notes, given a provisional duration running to `current_time`.
///
/// These belong to whatever pass is in progress, so a per-pass view can append them as-is.
pub fn active_notes_with_provisional_end(&self, current_time: Beats) -> Vec<(Beats, u8, u8, Beats)> {
self.active_notes
.values()
.map(|active| {
let note_start = active.start_time.max(self.start_time);
(
note_start - self.start_time,
active.note,
active.velocity,
(current_time - note_start).max(Beats::ZERO),
)
})
.collect()
}
/// Get all completed notes plus currently-held notes with a provisional duration.
pub fn get_notes_with_active(&self, current_time: Beats) -> Vec<(Beats, u8, u8, Beats)> {
let mut notes = self.completed_notes.clone();
notes.extend(self.active_notes_with_provisional_end(current_time));
notes
}
pub fn active_note_numbers(&self) -> Vec<u8> {
self.active_notes.keys().copied().collect()
}
/// Close out all active notes at the given time
/// This should be called when stopping recording to end any held notes
pub fn close_active_notes(&mut self, end_time: f64) {
// Collect all active notes and close them
pub fn close_active_notes(&mut self, end_time: Beats) {
let active_notes: Vec<_> = self.active_notes.drain().collect();
for (_note_num, active_note) in active_notes {
// Calculate relative time offset and duration
let time_offset = active_note.start_time - self.start_time;
let duration = end_time - active_note.start_time;
// Add to completed notes
self.completed_notes.push((
time_offset,
active_note.note,
active_note.velocity,
duration,
));
self.push_completed(&active_note, end_time);
}
}
/// Handle a transport cycle wrap during MIDI recording.
///
/// Note times are stored as offsets from `start_time`, and the playhead jumps *backwards* at a
/// wrap — so a note still held across the boundary would otherwise get a nonsensical (negative)
/// duration, or never be closed at all. Write its note-off at `region_end` (exactly as
/// `close_active_notes` does when recording stops), then re-open it at `region_start` so a key
/// the player is still physically holding keeps being captured in the next pass. Mirrors the
/// way `handle_start_midi_recording` re-injects already-held notes at the recording start.
pub fn wrap_at_cycle(&mut self, region_end: Beats, region_start: Beats) {
// Snapshot the held notes (close_active_notes drains them and loses the velocities).
let held: Vec<(u8, u8)> = self
.active_notes
.values()
.map(|n| (n.note, n.velocity))
.collect();
// Close first, so a note held across the boundary has its tail attributed to the pass that's
// ending; then advance, so the re-opened half belongs to the pass that's beginning.
self.close_active_notes(region_end);
self.current_pass += 1;
for (note, velocity) in held {
self.note_on(note, velocity, region_start);
}
// A pass has completed, so from here the clip spans the whole region rather than however long
// the user happens to hold the record button.
self.cycle_loop_len = Some(region_end - region_start);
self.wrapped = true;
}
}
#[cfg(test)]
mod cycle_tests {
use super::*;
/// A recording state holding `audio_data`, armed for cycle recording. Mono, 100 Hz, so a frame
/// is a sample and 5 frames is 50 ms (exactly the min-take threshold).
fn rec_forced(audio: Vec<f32>, loop_len_frames: usize, lead_pad_frames: usize, wraps: usize) -> RecordingState {
let mut r = rec(audio, loop_len_frames, lead_pad_frames, wraps);
if let Some(c) = r.cycle.as_mut() {
c.force_takes = true;
}
r
}
fn rec(audio: Vec<f32>, loop_len_frames: usize, lead_pad_frames: usize, wraps: usize) -> RecordingState {
let mut r = RecordingState::new(
0,
0,
PathBuf::from("/dev/null"),
WavWriter::create(&PathBuf::from("/dev/null"), 100, 1).expect("wav writer"),
100,
1,
Beats(0.0),
1.0,
);
r.audio_data = audio;
r.cycle = Some(CycleRecordInfo {
loop_start: Beats(0.0),
loop_len_beats: Beats(4.0),
loop_len_frames,
lead_pad_frames,
wrap_count: wraps,
force_takes: false,
});
r
}
#[test]
fn no_wrap_is_not_a_cycle_recording() {
// Stopping before the transport ever wraps stays an ordinary single recording — the whole
// point of triggering on the wrap rather than on the cycle region merely existing.
let r = rec(vec![1.0; 10], 4, 0, 0);
assert!(r.slice_takes().is_none());
}
#[test]
fn force_takes_makes_a_partial_pass_a_take() {
// Recording over a region that already holds takes: this run is another take however short
// it ran, so it's cut and padded like any partial pass rather than landing as a separate
// overlapping clip. Two real frames of an 8-frame region -> one take, silence for the rest.
let takes = rec_forced(vec![1.0, 2.0], 8, 0, 0)
.slice_takes()
.expect("forced takes");
assert_eq!(takes.len(), 1);
assert_eq!(takes[0], vec![1.0, 2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]);
}
#[test]
fn takes_are_cut_at_exact_loop_multiples() {
// 12 frames of audio, 4-frame loop, started at the region start => 3 clean takes.
let audio: Vec<f32> = (1..=12).map(|i| i as f32).collect();
let takes = rec(audio, 4, 0, 2).slice_takes().expect("cycle takes");
assert_eq!(takes.len(), 3);
assert_eq!(takes[0], vec![1.0, 2.0, 3.0, 4.0]);
assert_eq!(takes[1], vec![5.0, 6.0, 7.0, 8.0]);
assert_eq!(takes[2], vec![9.0, 10.0, 11.0, 12.0]);
}
#[test]
fn punch_in_pads_the_head_of_take_one() {
// Punched in 2 frames into the region: take 1 gets 2 frames of silence at the FRONT so it
// still spans the whole region and lines up with every other take.
let audio: Vec<f32> = (1..=10).map(|i| i as f32).collect();
let takes = rec(audio, 4, 2, 2).slice_takes().expect("cycle takes");
assert_eq!(takes.len(), 3);
assert_eq!(takes[0], vec![0.0, 0.0, 1.0, 2.0]);
assert_eq!(takes[1], vec![3.0, 4.0, 5.0, 6.0]);
assert_eq!(takes[2], vec![7.0, 8.0, 9.0, 10.0]);
}
#[test]
fn stopping_mid_pass_pads_the_tail_of_the_last_take() {
// 13 frames, 8-frame loop => the second take holds 5 real frames (50 ms at 100 Hz, right at
// the keep threshold) and 3 of silence.
let audio: Vec<f32> = (1..=13).map(|i| i as f32).collect();
let takes = rec(audio, 8, 0, 1).slice_takes().expect("cycle takes");
assert_eq!(takes.len(), 2);
assert_eq!(takes[1], vec![9.0, 10.0, 11.0, 12.0, 13.0, 0.0, 0.0, 0.0]);
}
#[test]
fn every_take_is_the_same_length() {
// Uniform length is the invariant comping-via-split depends on.
let audio: Vec<f32> = (1..=23).map(|i| i as f32).collect();
let takes = rec(audio, 8, 3, 3).slice_takes().expect("cycle takes");
assert!(takes.iter().all(|t| t.len() == 8), "takes must be uniform");
}
#[test]
fn a_sliver_of_a_final_take_is_dropped() {
// Stopped 1 frame (10 ms at 100 Hz) after the wrap — below the 50 ms floor, so that stub of
// a take is a stop artifact and goes.
let audio: Vec<f32> = (1..=9).map(|i| i as f32).collect();
let takes = rec(audio, 8, 0, 1).slice_takes().expect("cycle takes");
assert_eq!(takes.len(), 1, "a 10ms tail take should be dropped");
assert_eq!(takes[0].len(), 8);
}
#[test]
fn a_full_final_take_is_never_dropped() {
// Regression: the sliver rule must only fire on a PARTIAL pass. A pass that filled the
// region is a real take however short the region is — an earlier version compared a full
// take's duration to the floor and silently ate it.
let audio: Vec<f32> = (1..=8).map(|i| i as f32).collect();
let takes = rec(audio, 4, 0, 1).slice_takes().expect("cycle takes");
assert_eq!(takes.len(), 2, "both passes filled the region");
assert_eq!(takes[1], vec![5.0, 6.0, 7.0, 8.0]);
}
}
#[cfg(test)]
mod midi_cycle_tests {
use super::*;
/// A MIDI recording anchored at the region start (beat 0), region 4 beats long.
fn rec() -> MidiRecordingState {
MidiRecordingState::new(0, 0, Beats(0.0))
}
/// One pass of the transport around a 4-beat region.
fn wrap(r: &mut MidiRecordingState) {
r.wrap_at_cycle(Beats(4.0), Beats(0.0));
}
#[test]
fn notes_are_bucketed_by_the_pass_they_were_played_in() {
let mut r = rec();
r.note_on(60, 100, Beats(1.0));
r.note_off(60, Beats(2.0)); // pass 0
wrap(&mut r);
r.note_on(62, 100, Beats(1.0));
r.note_off(62, Beats(2.0)); // pass 1
wrap(&mut r);
r.note_on(64, 100, Beats(1.0));
r.note_off(64, Beats(2.0)); // pass 2
assert_eq!(r.pass_count(), 3);
let by_pass = r.notes_by_pass(r.pass_count());
let pitches: Vec<Vec<u8>> = by_pass
.iter()
.map(|p| p.iter().map(|n| n.1).collect())
.collect();
assert_eq!(pitches, vec![vec![60], vec![62], vec![64]]);
}
#[test]
fn a_note_held_across_a_wrap_splits_between_the_two_passes() {
// The key is still down at the boundary: the sounding half belongs to the pass that's
// ending, and the re-opened half to the pass that's beginning. Getting the pass bump on the
// wrong side of close_active_notes would file the whole note under one pass.
let mut r = rec();
r.note_on(60, 100, Beats(3.0));
wrap(&mut r); // still held
r.note_off(60, Beats(1.0)); // released 1 beat into the next pass
assert_eq!(r.pass_count(), 2);
let by_pass = r.notes_by_pass(r.pass_count());
assert_eq!(by_pass[0].len(), 1, "the held half lands in the pass that ended");
assert_eq!(by_pass[1].len(), 1, "the re-opened half lands in the next pass");
// Pass 0's half runs from beat 3 to the region end at 4.
assert_eq!(by_pass[0][0].0, Beats(3.0));
assert_eq!(by_pass[0][0].3, Beats(1.0));
// Pass 1's half starts at the region start and runs to the release.
assert_eq!(by_pass[1][0].0, Beats(0.0));
assert_eq!(by_pass[1][0].3, Beats(1.0));
}
#[test]
fn a_silent_interior_pass_still_yields_an_empty_take() {
// Take N in the folder must be pass N on the transport, even if nothing was played — else
// the take numbering silently shifts under the user.
let mut r = rec();
r.note_on(60, 100, Beats(1.0));
r.note_off(60, Beats(2.0)); // pass 0
wrap(&mut r);
wrap(&mut r); // pass 1: played nothing
r.note_on(64, 100, Beats(1.0));
r.note_off(64, Beats(2.0)); // pass 2
let by_pass = r.notes_by_pass(r.pass_count());
assert_eq!(by_pass.len(), 3);
assert_eq!(by_pass[1].len(), 0, "the silent pass is still take 2");
assert_eq!(by_pass[2][0].1, 64);
}
#[test]
fn a_trailing_empty_pass_is_dropped() {
// Hitting stop shortly after a wrap leaves a pass you never played into. That's a stop
// artifact, not a take — unlike a silent pass in the middle, which was a deliberate rest.
let mut r = rec();
r.note_on(60, 100, Beats(1.0));
r.note_off(60, Beats(2.0)); // pass 0
wrap(&mut r);
r.note_on(62, 100, Beats(1.0));
r.note_off(62, Beats(2.0)); // pass 1
wrap(&mut r); // pass 2 begins... and the user hits stop
assert_eq!(r.pass_count(), 3);
let by_pass = r.notes_by_pass(r.pass_count());
assert_eq!(by_pass.len(), 2, "the empty trailing pass is not a take");
}
#[test]
fn an_empty_recording_still_yields_one_take() {
let mut r = rec();
wrap(&mut r);
wrap(&mut r);
assert_eq!(r.notes_by_pass(r.pass_count()).len(), 1);
}
}
+25 -35
View File
@@ -6,6 +6,7 @@ use symphonia::core::io::MediaSourceStream;
use symphonia::core::meta::MetadataOptions;
use symphonia::core::probe::Hint;
use std::fs::File;
use std::io::Cursor;
use std::path::Path;
/// Loaded audio sample data
@@ -20,33 +21,36 @@ pub struct SampleData {
/// Load an audio file and decode it to mono f32 samples
pub fn load_audio_file(path: impl AsRef<Path>) -> Result<SampleData, String> {
let path = path.as_ref();
// Open the file
let file = File::open(path)
.map_err(|e| format!("Failed to open file: {}", e))?;
// Create a media source stream
let file = File::open(path).map_err(|e| format!("Failed to open file: {}", e))?;
let mss = MediaSourceStream::new(Box::new(file), Default::default());
// Create a hint to help the format registry guess the format
let mut hint = Hint::new();
if let Some(extension) = path.extension() {
if let Some(ext_str) = extension.to_str() {
hint.with_extension(ext_str);
}
if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
hint.with_extension(ext);
}
decode_mss(mss, hint)
}
// Probe the media source for a format
let format_opts = FormatOptions::default();
let metadata_opts = MetadataOptions::default();
/// Load audio from an in-memory byte slice and decode it to mono f32 samples.
/// Supports WAV, FLAC, MP3, AAC, and any other format Symphonia recognises.
/// `filename_hint` is used to help Symphonia detect the format (e.g. "kick.wav").
pub fn load_audio_from_bytes(bytes: &[u8], filename_hint: &str) -> Result<SampleData, String> {
let cursor = Cursor::new(bytes.to_vec());
let mss = MediaSourceStream::new(Box::new(cursor), Default::default());
let mut hint = Hint::new();
if let Some(ext) = std::path::Path::new(filename_hint).extension().and_then(|e| e.to_str()) {
hint.with_extension(ext);
}
decode_mss(mss, hint)
}
/// Shared decode logic: probe `mss`, find the first audio track, decode to mono f32.
fn decode_mss(mss: MediaSourceStream, hint: Hint) -> Result<SampleData, String> {
let probed = symphonia::default::get_probe()
.format(&hint, mss, &format_opts, &metadata_opts)
.format(&hint, mss, &FormatOptions::default(), &MetadataOptions::default())
.map_err(|e| format!("Failed to probe format: {}", e))?;
let mut format = probed.format;
// Find the first audio track
let track = format
.tracks()
.iter()
@@ -56,47 +60,33 @@ pub fn load_audio_file(path: impl AsRef<Path>) -> Result<SampleData, String> {
let track_id = track.id;
let sample_rate = track.codec_params.sample_rate.unwrap_or(48000);
// Create a decoder for the track
let dec_opts = DecoderOptions::default();
let mut decoder = symphonia::default::get_codecs()
.make(&track.codec_params, &dec_opts)
.make(&track.codec_params, &DecoderOptions::default())
.map_err(|e| format!("Failed to create decoder: {}", e))?;
// Decode all packets
let mut all_samples = Vec::new();
loop {
// Get the next packet
let packet = match format.next_packet() {
Ok(packet) => packet,
Err(SymphoniaError::IoError(e)) if e.kind() == std::io::ErrorKind::UnexpectedEof => {
// End of stream
break;
}
Err(e) => {
return Err(format!("Error reading packet: {}", e));
}
Err(e) => return Err(format!("Error reading packet: {}", e)),
};
// Skip packets that don't belong to the selected track
if packet.track_id() != track_id {
continue;
}
// Decode the packet
let decoded = decoder
.decode(&packet)
.map_err(|e| format!("Failed to decode packet: {}", e))?;
// Convert to f32 samples and mix to mono
let samples = convert_to_mono_f32(&decoded);
all_samples.extend_from_slice(&samples);
all_samples.extend_from_slice(&convert_to_mono_f32(&decoded));
}
Ok(SampleData {
samples: all_samples,
sample_rate,
})
Ok(SampleData { samples: all_samples, sample_rate })
}
/// Convert an audio buffer to mono f32 samples
+399 -154
View File
@@ -1,11 +1,13 @@
use super::automation::{AutomationLane, AutomationLaneId, ParameterId};
use super::clip::{AudioClipInstance, AudioClipInstanceId};
use super::midi::{MidiClipInstance, MidiClipInstanceId, MidiEvent};
use super::midi::{MidiClipId, MidiClipInstance, MidiClipInstanceId, MidiEvent};
use super::midi_pool::MidiClipPool;
use super::node_graph::AudioGraph;
use super::node_graph::nodes::{AudioInputNode, AudioOutputNode};
use super::node_graph::preset::GraphPreset;
use super::pool::AudioClipPool;
use crate::tempo_map::TempoMap;
use crate::time::{Beats, Seconds};
use serde::{Serialize, Deserialize};
use std::collections::{HashMap, HashSet};
@@ -23,10 +25,12 @@ pub type Track = AudioTrack;
/// Rendering context that carries timing information through the track hierarchy
///
/// This allows metatracks to transform time for their children (time stretch, offset, etc.)
#[derive(Debug, Clone, Copy)]
pub struct RenderContext {
#[derive(Clone, Copy)]
pub struct RenderContext<'a> {
/// Current playhead position in seconds (in transformed time)
pub playhead_seconds: f64,
pub playhead_seconds: Seconds,
/// Tempo map for beat ↔ second conversion
pub tempo_map: &'a TempoMap,
/// Audio sample rate
pub sample_rate: u32,
/// Number of channels
@@ -35,34 +39,54 @@ pub struct RenderContext {
pub buffer_size: usize,
/// Accumulated time stretch factor (1.0 = normal, 0.5 = half speed, 2.0 = double speed)
pub time_stretch: f32,
/// When true: skip clip event collection; only render instrument state and live MIDI queue.
/// Used after pause/stop to route note-off tails through the normal group hierarchy
/// without re-triggering notes from clips at the paused position.
pub live_only: bool,
/// The MIDI recording in progress, if any: (track being recorded to, clip being recorded into).
///
/// On that track, every OTHER clip is silenced for the duration of the recording. You're playing
/// a part into this region — hearing what's already there (a previous take, say) fighting with
/// what you're playing now is just noise. The clip being recorded into is exempt, because in
/// merge mode that's exactly what you DO want to hear: the overdub you've been building up.
pub recording_midi: Option<(TrackId, MidiClipId)>,
}
impl RenderContext {
/// Create a new render context
impl<'a> RenderContext<'a> {
pub fn new(
playhead_seconds: f64,
playhead_seconds: Seconds,
tempo_map: &'a TempoMap,
sample_rate: u32,
channels: u32,
buffer_size: usize,
) -> Self {
Self {
playhead_seconds,
tempo_map,
sample_rate,
channels,
buffer_size,
time_stretch: 1.0,
live_only: false,
recording_midi: None,
}
}
/// Get the duration of the buffer in seconds
pub fn buffer_duration(&self) -> f64 {
self.buffer_size as f64 / (self.sample_rate as f64 * self.channels as f64)
pub fn buffer_duration(&self) -> Seconds {
Seconds(self.buffer_size as f64 / (self.sample_rate as f64 * self.channels as f64))
}
/// Get the end time of the buffer
pub fn buffer_end(&self) -> f64 {
pub fn buffer_end(&self) -> Seconds {
self.playhead_seconds + self.buffer_duration()
}
pub fn playhead_beats(&self) -> Beats {
self.tempo_map.seconds_to_beats(self.playhead_seconds)
}
pub fn buffer_end_beats(&self) -> Beats {
self.tempo_map.seconds_to_beats(self.buffer_end())
}
}
/// Node in the track hierarchy - can be an audio track, MIDI track, or a metatrack
@@ -165,14 +189,14 @@ pub struct Metatrack {
pub time_stretch: f32,
/// Pitch shift in semitones (for future implementation)
pub pitch_shift: f32,
/// Time offset in seconds (shift content forward/backward in time)
pub offset: f64,
/// Trim start: offset into the metatrack's internal content (seconds)
/// Time offset (shift content forward/backward in time)
pub offset: Seconds,
/// Trim start: offset into the metatrack's internal content
/// Children will see time starting from this point
pub trim_start: f64,
/// Trim end: offset into the metatrack's internal content (seconds)
pub trim_start: Seconds,
/// Trim end: offset into the metatrack's internal content
/// None means no end trim (play until content ends)
pub trim_end: Option<f64>,
pub trim_end: Option<Seconds>,
/// Automation lanes for this metatrack
pub automation_lanes: HashMap<AutomationLaneId, AutomationLane>,
next_automation_id: AutomationLaneId,
@@ -181,6 +205,10 @@ pub struct Metatrack {
pub audio_graph: AudioGraph,
/// Saved graph preset for serialization
audio_graph_preset: Option<GraphPreset>,
/// True while the mixing graph is still the auto-generated default (no user edits).
/// Used to auto-connect new subtracks and to prompt before loading a preset.
#[serde(default)]
pub graph_is_default: bool,
}
impl Clone for Metatrack {
@@ -201,15 +229,17 @@ impl Clone for Metatrack {
next_automation_id: self.next_automation_id,
audio_graph: default_audio_graph(), // Create fresh graph, not cloned
audio_graph_preset: self.audio_graph_preset.clone(),
graph_is_default: self.graph_is_default,
}
}
}
impl Metatrack {
/// Create a new metatrack with an audio graph (input → output)
/// Create a new metatrack. The mixing graph is set up later via `set_subtrack_graph`
/// once the child track list is known.
pub fn new(id: TrackId, name: String, sample_rate: u32) -> Self {
let default_buffer_size = 8192;
let audio_graph = Self::create_default_graph(sample_rate, default_buffer_size);
let audio_graph = Self::create_empty_graph(sample_rate, default_buffer_size);
Self {
id,
@@ -220,32 +250,244 @@ impl Metatrack {
solo: false,
time_stretch: 1.0,
pitch_shift: 0.0,
offset: 0.0,
trim_start: 0.0,
offset: Seconds::ZERO,
trim_start: Seconds::ZERO,
trim_end: None,
automation_lanes: HashMap::new(),
next_automation_id: 0,
audio_graph,
audio_graph_preset: None,
graph_is_default: true,
}
}
/// Create a default audio graph with AudioInput -> AudioOutput
fn create_default_graph(sample_rate: u32, buffer_size: usize) -> AudioGraph {
/// Minimal graph used before subtracks are known (just an AudioOutput node).
fn create_empty_graph(sample_rate: u32, buffer_size: usize) -> AudioGraph {
let mut graph = AudioGraph::new(sample_rate, buffer_size);
let input_node = Box::new(AudioInputNode::new("Audio Input"));
let input_id = graph.add_node(input_node);
graph.set_node_position(input_id, 100.0, 150.0);
let output_node = Box::new(AudioOutputNode::new("Audio Output"));
let output_id = graph.add_node(output_node);
graph.set_node_position(output_id, 500.0, 150.0);
graph.set_output_node(Some(output_id));
graph
}
let _ = graph.connect(input_id, 0, output_id, 0);
/// Build the default subtrack mixing graph: SubtrackInputs → Mixer → Gain → AudioOutput,
/// with an AutomationInput ("Volume", range 0..2) feeding the Gain's CV port.
///
/// Existing Volume keyframes are preserved across rebuilds so that adding/removing
/// a child track doesn't reset the automation.
///
/// `subtracks` is an ordered list of (backend TrackId, display name) for each child.
/// Replaces the current graph and marks `graph_is_default = true`.
pub fn set_subtrack_graph(
&mut self,
subtracks: Vec<(TrackId, String)>,
sample_rate: u32,
buffer_size: usize,
) {
use super::node_graph::nodes::{SubtrackInputsNode, MixerNode, GainNode, AutomationInputNode};
use super::node_graph::nodes::AutomationKeyframe;
use crate::time::Beats;
// Preserve existing Volume keyframes before rebuilding.
let existing_volume_kfs = self.get_volume_automation_keyframes();
let n = subtracks.len();
let mut graph = AudioGraph::new(sample_rate, buffer_size);
// SubtrackInputs node (N outputs, one per child)
let mut inputs_node = SubtrackInputsNode::new("Subtrack Inputs", subtracks);
let subtracks_copy = inputs_node.subtracks().to_vec();
inputs_node.update_subtracks(subtracks_copy, buffer_size);
let inputs_id = graph.add_node(Box::new(inputs_node));
graph.set_node_position(inputs_id, 100.0, 150.0);
// Mixer node
let mixer_node = Box::new(MixerNode::new("Mixer"));
let mixer_id = graph.add_node(mixer_node);
graph.set_node_position(mixer_id, 330.0, 150.0);
// Gain node — group volume control
let gain_id = graph.add_node(Box::new(GainNode::new("Volume")));
graph.set_node_position(gain_id, 520.0, 150.0);
// AutomationInput — drives the Gain's CV port
let mut auto_node = AutomationInputNode::new("Volume CV");
auto_node.set_display_name("Volume".to_string());
auto_node.value_min = 0.0;
auto_node.value_max = 2.0;
auto_node.clear_keyframes();
if existing_volume_kfs.is_empty() {
auto_node.add_keyframe(AutomationKeyframe::new(Beats::ZERO, 1.0));
} else {
for kf in existing_volume_kfs {
auto_node.add_keyframe(kf);
}
}
let auto_id = graph.add_node(Box::new(auto_node));
graph.set_node_position(auto_id, 520.0, 320.0);
// AudioOutput node
let output_node = Box::new(AudioOutputNode::new("Audio Output"));
let output_id = graph.add_node(output_node);
graph.set_node_position(output_id, 720.0, 150.0);
// Connect SubtrackInputs[i] → Mixer[i] for each subtrack
for i in 0..n {
let _ = graph.connect(inputs_id, i, mixer_id, i);
}
let _ = graph.connect(mixer_id, 0, gain_id, 0); // Mixer → Gain audio
let _ = graph.connect(auto_id, 0, gain_id, 1); // AutomationInput → Gain CV
let _ = graph.connect(gain_id, 0, output_id, 0); // Gain → Audio Out
graph.set_output_node(Some(output_id));
graph
self.audio_graph = graph;
self.audio_graph_preset = None;
self.graph_is_default = true;
}
/// Extract Volume AutomationInput keyframes from the current graph (if any),
/// so they can be preserved across `set_subtrack_graph` rebuilds.
fn get_volume_automation_keyframes(&self) -> Vec<super::node_graph::nodes::AutomationKeyframe> {
use super::node_graph::nodes::AutomationInputNode;
for idx in self.audio_graph.node_indices() {
if let Some(node) = self.audio_graph.get_graph_node(idx) {
if node.node.node_type() == "AutomationInput" {
if let Some(auto_node) = node.node.as_any().downcast_ref::<AutomationInputNode>() {
return auto_node.keyframes().to_vec();
}
}
}
}
Vec::new()
}
/// Add a new subtrack port to the existing graph.
///
/// If `graph_is_default`: also connects the new port to a new Mixer input.
/// If the user has modified the graph: just adds the port (unconnected).
pub fn add_subtrack_to_graph(&mut self, track_id: TrackId, name: String, buffer_size: usize) {
use super::node_graph::nodes::SubtrackInputsNode;
// Find SubtrackInputs node index
let si_idx = self.audio_graph.node_indices()
.find(|&idx| self.audio_graph.get_graph_node(idx)
.map(|n| n.node.node_type() == "SubtrackInputs")
.unwrap_or(false));
let si_idx = match si_idx {
Some(idx) => idx,
None => return, // No subtrack graph set up yet
};
// Get current subtrack count (= new port index after adding)
let new_slot = {
let gn = self.audio_graph.get_graph_node_mut(si_idx).unwrap();
let si = gn.node.as_any_mut().downcast_mut::<SubtrackInputsNode>().unwrap();
let mut subtracks = si.subtracks().to_vec();
subtracks.push((track_id, name));
let n = subtracks.len();
si.update_subtracks(subtracks, buffer_size);
// Rebuild output buffers for the new port count
n - 1 // index of the newly added slot
};
// Reallocate GraphNode output buffers to match new port count
self.audio_graph.reallocate_node_output_buffers(si_idx, buffer_size);
if self.graph_is_default {
// Find the Mixer node and connect the new subtrack port to a new Mixer input
let mixer_idx = self.audio_graph.node_indices()
.find(|&idx| self.audio_graph.get_graph_node(idx)
.map(|n| n.node.node_type() == "Mixer")
.unwrap_or(false));
if let Some(mixer_idx) = mixer_idx {
// n_incoming after connecting = new_slot + 1; auto-grow handled by connect()
let _ = self.audio_graph.connect(si_idx, new_slot, mixer_idx, new_slot);
}
}
}
/// Remove a subtrack from the graph (by TrackId).
///
/// Always disconnects any connections from the removed port and removes the port.
/// If `graph_is_default`: also reshuffles Mixer connections to stay compact.
pub fn remove_subtrack_from_graph(&mut self, track_id: TrackId, buffer_size: usize) {
use super::node_graph::nodes::SubtrackInputsNode;
let si_idx = self.audio_graph.node_indices()
.find(|&idx| self.audio_graph.get_graph_node(idx)
.map(|n| n.node.node_type() == "SubtrackInputs")
.unwrap_or(false));
let si_idx = match si_idx {
Some(idx) => idx,
None => return,
};
// Find the slot index for this track
let slot = {
let gn = self.audio_graph.get_graph_node(si_idx).unwrap();
let si = gn.node.as_any().downcast_ref::<SubtrackInputsNode>().unwrap();
si.subtrack_index_for(track_id)
};
let slot = match slot {
Some(s) => s,
None => return,
};
// Remove all connections from this output port
self.audio_graph.disconnect_output_port(si_idx, slot);
// Update the SubtrackInputsNode's subtrack list
{
let gn = self.audio_graph.get_graph_node_mut(si_idx).unwrap();
let si = gn.node.as_any_mut().downcast_mut::<SubtrackInputsNode>().unwrap();
let mut subtracks = si.subtracks().to_vec();
subtracks.remove(slot);
si.update_subtracks(subtracks, buffer_size);
}
self.audio_graph.reallocate_node_output_buffers(si_idx, buffer_size);
if self.graph_is_default {
// Rebuild default Mixer connections (they've shifted after removal)
let mixer_idx = self.audio_graph.node_indices()
.find(|&idx| self.audio_graph.get_graph_node(idx)
.map(|n| n.node.node_type() == "Mixer")
.unwrap_or(false));
if let Some(mixer_idx) = mixer_idx {
// Clear all connections TO mixer
self.audio_graph.disconnect_all_inputs(mixer_idx);
// Get new subtrack count
let n = {
let gn = self.audio_graph.get_graph_node(si_idx).unwrap();
gn.node.as_any().downcast_ref::<SubtrackInputsNode>().unwrap().num_subtracks()
};
// Resize mixer and reconnect
{
let gn = self.audio_graph.get_graph_node_mut(mixer_idx).unwrap();
let mixer = gn.node.as_any_mut().downcast_mut::<super::node_graph::nodes::MixerNode>().unwrap();
mixer.resize(n + 1);
}
for i in 0..n {
let _ = self.audio_graph.connect(si_idx, i, mixer_idx, i);
}
}
}
}
/// Return the current ordered subtrack list from SubtrackInputsNode, or empty vec if none.
pub fn current_subtracks(&self) -> Vec<(TrackId, String)> {
use super::node_graph::nodes::SubtrackInputsNode;
for idx in self.audio_graph.node_indices().collect::<Vec<_>>() {
if let Some(gn) = self.audio_graph.get_graph_node(idx) {
if let Some(si) = gn.node.as_any().downcast_ref::<SubtrackInputsNode>() {
return si.subtracks().to_vec();
}
}
}
Vec::new()
}
/// Prepare for serialization by saving the audio graph as a preset
@@ -253,20 +495,42 @@ impl Metatrack {
self.audio_graph_preset = Some(self.audio_graph.to_preset("Metatrack Graph"));
}
/// Rebuild the audio graph from preset after deserialization
/// Rebuild the audio graph from preset after deserialization.
///
/// After loading, the caller must call `update_subtrack_ids` to re-associate
/// backend TrackIds with the SubtrackInputsNode's port slots.
pub fn rebuild_audio_graph(&mut self, sample_rate: u32, buffer_size: usize) -> Result<(), String> {
if let Some(preset) = &self.audio_graph_preset {
if !preset.nodes.is_empty() && preset.output_node.is_some() {
self.audio_graph = AudioGraph::from_preset(preset, sample_rate, buffer_size, None)?;
self.audio_graph = AudioGraph::from_preset(preset, sample_rate, buffer_size, None, None)?;
// graph_is_default remains as serialized (false for user-modified graphs)
} else {
self.audio_graph = Self::create_default_graph(sample_rate, buffer_size);
self.audio_graph = Self::create_empty_graph(sample_rate, buffer_size);
self.graph_is_default = true;
}
} else {
self.audio_graph = Self::create_default_graph(sample_rate, buffer_size);
self.audio_graph = Self::create_empty_graph(sample_rate, buffer_size);
self.graph_is_default = true;
}
Ok(())
}
/// Re-associate backend TrackIds with the SubtrackInputsNode's port slots after reload.
///
/// The preset stores placeholder TrackId=0 entries; this call fills in the real IDs.
pub fn update_subtrack_ids(&mut self, subtracks: Vec<(TrackId, String)>, buffer_size: usize) {
use super::node_graph::nodes::SubtrackInputsNode;
for idx in self.audio_graph.node_indices().collect::<Vec<_>>() {
if let Some(gn) = self.audio_graph.get_graph_node_mut(idx) {
if let Some(si) = gn.node.as_any_mut().downcast_mut::<SubtrackInputsNode>() {
si.update_subtracks(subtracks, buffer_size);
return;
}
}
}
}
/// Add an automation lane to this metatrack
pub fn add_automation_lane(&mut self, parameter_id: ParameterId) -> AutomationLaneId {
let lane_id = self.next_automation_id;
@@ -293,7 +557,7 @@ impl Metatrack {
}
/// Evaluate automation at a specific time and return effective parameters
pub fn evaluate_automation_at_time(&self, time: f64) -> (f32, f32, f64) {
pub fn evaluate_automation_at_time(&self, time: Beats) -> (f32, f32, Seconds) {
let mut volume = self.volume;
let mut time_stretch = self.time_stretch;
let mut offset = self.offset;
@@ -317,7 +581,7 @@ impl Metatrack {
}
ParameterId::TimeOffset => {
if let Some(automated_value) = lane.evaluate(time) {
offset = automated_value as f64;
offset = Seconds(automated_value as f64);
}
}
_ => {}
@@ -361,7 +625,7 @@ impl Metatrack {
/// Check whether this metatrack should produce audio at the given parent time.
/// Returns false if the playhead is outside the trim window.
pub fn is_active_at_time(&self, parent_playhead: f64) -> bool {
pub fn is_active_at_time(&self, parent_playhead: Seconds) -> bool {
let local_time = (parent_playhead - self.offset) * self.time_stretch as f64;
if local_time < self.trim_start {
return false;
@@ -380,7 +644,7 @@ impl Metatrack {
/// Time stretch affects how fast content plays: 0.5 = half speed, 2.0 = double speed
/// Offset shifts content forward/backward in time
/// Trim start offsets into the internal content
pub fn transform_context(&self, ctx: RenderContext) -> RenderContext {
pub fn transform_context<'a>(&self, ctx: RenderContext<'a>) -> RenderContext<'a> {
let mut transformed = ctx;
// Apply transformations in order:
@@ -396,7 +660,7 @@ impl Metatrack {
let stretched = adjusted_playhead * self.time_stretch as f64;
// 3. Add trim_start so children see time starting from the trim point
// If trim_start=2.0, children start seeing time 2.0 when parent reaches offset
// If trim_start=2.0s, children start seeing time 2.0s when parent reaches offset
transformed.playhead_seconds = stretched + self.trim_start;
// Accumulate time stretch for nested metatracks
@@ -439,6 +703,11 @@ pub struct MidiTrack {
/// Peak level of last render() call (for VU metering)
#[serde(skip, default)]
pub peak_level: f32,
/// True while the instrument graph is still the auto-generated default (no user edits).
/// Used to prompt before loading a preset.
#[serde(default)]
pub graph_is_default: bool,
}
impl Clone for MidiTrack {
@@ -457,6 +726,7 @@ impl Clone for MidiTrack {
live_midi_queue: Vec::new(), // Don't clone live MIDI queue
prev_active_instances: HashSet::new(),
peak_level: 0.0,
graph_is_default: self.graph_is_default,
}
}
}
@@ -485,6 +755,7 @@ impl MidiTrack {
live_midi_queue: Vec::new(),
prev_active_instances: HashSet::new(),
peak_level: 0.0,
graph_is_default: true,
}
}
@@ -496,7 +767,7 @@ impl MidiTrack {
/// Rebuild the instrument graph from preset after deserialization
pub fn rebuild_audio_graph(&mut self, sample_rate: u32, buffer_size: usize) -> Result<(), String> {
if let Some(preset) = &self.instrument_graph_preset {
self.instrument_graph = AudioGraph::from_preset(preset, sample_rate, buffer_size, None)?;
self.instrument_graph = AudioGraph::from_preset(preset, sample_rate, buffer_size, None, None)?;
} else {
// No preset - create default graph
self.instrument_graph = AudioGraph::new(sample_rate, buffer_size);
@@ -565,13 +836,13 @@ impl MidiTrack {
// Send note-off for all 128 possible MIDI notes to silence the instrument
let mut note_offs = Vec::new();
for note in 0..128 {
note_offs.push(MidiEvent::note_off(0.0, 0, note, 0));
note_offs.push(MidiEvent::note_off(Beats::ZERO, 0, note, 0));
}
// Create a silent buffer to process the note-offs
let buffer_size = 512 * 2; // stereo
let mut silent_buffer = vec![0.0f32; buffer_size];
self.instrument_graph.process(&mut silent_buffer, &note_offs, 0.0);
self.instrument_graph.process(&mut silent_buffer, &note_offs, Beats::ZERO);
}
/// Queue a live MIDI event (from virtual keyboard or MIDI controller)
@@ -584,77 +855,67 @@ impl MidiTrack {
self.live_midi_queue.clear();
}
/// Process only live MIDI input (queued events) without rendering clips
/// This is used when playback is stopped but we want to hear live input
pub fn process_live_input(
&mut self,
output: &mut [f32],
_sample_rate: u32,
_channels: u32,
) {
// Generate audio using instrument graph with live MIDI events
self.instrument_graph.process(output, &self.live_midi_queue, 0.0);
// Clear the queue after processing
self.live_midi_queue.clear();
// Apply track volume (no automation during live input)
for sample in output.iter_mut() {
*sample *= self.volume;
}
}
/// Render this MIDI track into the output buffer
/// Render this MIDI track into the output buffer.
///
/// When `ctx.live_only` is true, clip event collection is skipped and only the live MIDI
/// queue is processed. This lets note-off tails (and live keyboard input) route through
/// the normal group hierarchy without re-triggering notes from clips at the paused position.
pub fn render(
&mut self,
output: &mut [f32],
midi_pool: &MidiClipPool,
playhead_seconds: f64,
sample_rate: u32,
channels: u32,
ctx: RenderContext,
) {
let buffer_duration_seconds = output.len() as f64 / (sample_rate as f64 * channels as f64);
let buffer_end_seconds = playhead_seconds + buffer_duration_seconds;
// Collect MIDI events from all clip instances that overlap with current time range
let mut midi_events = Vec::new();
let mut currently_active = HashSet::new();
for instance in &self.clip_instances {
if instance.overlaps_range(playhead_seconds, buffer_end_seconds) {
currently_active.insert(instance.id);
}
// Get the clip content from the pool
if let Some(clip) = midi_pool.get_clip(instance.clip_id) {
let events = instance.get_events_in_range(
clip,
playhead_seconds,
buffer_end_seconds,
);
midi_events.extend(events);
}
}
// Send all-notes-off for clip instances that just became inactive
// (playhead exited the clip). This prevents stuck notes from malformed clips.
for prev_id in &self.prev_active_instances {
if !currently_active.contains(prev_id) {
for note in 0..128u8 {
midi_events.push(MidiEvent::note_off(playhead_seconds, 0, note, 0));
if !ctx.live_only {
let playhead_beats = ctx.playhead_beats();
let buffer_end_beats = ctx.buffer_end_beats();
// While recording into this track, every clip EXCEPT the one being recorded into is
// silenced. Otherwise a take folder already sitting in the cycle region would play its
// active take underneath you on every pass, fighting the part you're trying to record.
// The recording clip itself is exempt: in merge mode that's the overdub monitoring.
let muted_clip = match ctx.recording_midi {
Some((track_id, clip_id)) if track_id == self.id => Some(clip_id),
_ => None,
};
// Collect MIDI events from all clip instances that overlap with current beat range
let mut currently_active = HashSet::new();
for instance in &self.clip_instances {
if muted_clip.is_some_and(|recording| instance.clip_id != recording) {
continue;
}
if instance.overlaps_range(playhead_beats, buffer_end_beats) {
currently_active.insert(instance.id);
}
if let Some(clip) = midi_pool.get_clip(instance.clip_id) {
let events = instance.get_events_in_range(clip, playhead_beats, buffer_end_beats);
midi_events.extend(events);
}
break; // One round of all-notes-off is enough
}
// Send all-notes-off for clip instances that just became inactive
for prev_id in &self.prev_active_instances {
if !currently_active.contains(prev_id) {
for note in 0..128u8 {
midi_events.push(MidiEvent::note_off(playhead_beats, 0, note, 0));
}
break;
}
}
self.prev_active_instances = currently_active;
}
self.prev_active_instances = currently_active;
// Add live MIDI events (from virtual keyboard or MIDI controllers)
// This allows real-time input to be heard during playback/recording
midi_events.extend(self.live_midi_queue.drain(..));
// Generate audio using instrument graph
self.instrument_graph.process(output, &midi_events, playhead_seconds);
self.instrument_graph.process(output, &midi_events, ctx.playhead_beats());
// Evaluate and apply automation
let effective_volume = self.evaluate_automation_at_time(playhead_seconds);
// Evaluate and apply automation (skip automation in live_only mode — no playhead to evaluate at)
let effective_volume = if ctx.live_only { self.volume } else { self.evaluate_automation_at_time(ctx.playhead_beats()) };
// Apply track volume
for sample in output.iter_mut() {
@@ -663,7 +924,7 @@ impl MidiTrack {
}
/// Evaluate automation at a specific time and return the effective volume
fn evaluate_automation_at_time(&self, time: f64) -> f32 {
fn evaluate_automation_at_time(&self, time: Beats) -> f32 {
let mut volume = self.volume;
// Check for volume automation
@@ -715,6 +976,11 @@ pub struct AudioTrack {
/// Peak level of last render() call (for VU metering)
#[serde(skip, default)]
pub peak_level: f32,
/// True while the effects graph is still the auto-generated default (no user edits).
/// Used to prompt before loading a preset.
#[serde(default)]
pub graph_is_default: bool,
}
impl Clone for AudioTrack {
@@ -732,6 +998,7 @@ impl Clone for AudioTrack {
effects_graph: default_audio_graph(), // Create fresh graph, not cloned
clip_render_buffer: Vec::new(),
peak_level: 0.0,
graph_is_default: self.graph_is_default,
}
}
}
@@ -776,6 +1043,7 @@ impl AudioTrack {
effects_graph,
clip_render_buffer: Vec::new(),
peak_level: 0.0,
graph_is_default: true,
}
}
@@ -793,7 +1061,7 @@ impl AudioTrack {
if has_nodes && has_output {
// Valid preset - rebuild from it
self.effects_graph = AudioGraph::from_preset(preset, sample_rate, buffer_size, None)?;
self.effects_graph = AudioGraph::from_preset(preset, sample_rate, buffer_size, None, None)?;
} else {
// Empty or invalid preset - create default graph
self.effects_graph = Self::create_default_graph(sample_rate, buffer_size);
@@ -889,12 +1157,9 @@ impl AudioTrack {
&mut self,
output: &mut [f32],
pool: &AudioClipPool,
playhead_seconds: f64,
sample_rate: u32,
channels: u32,
ctx: RenderContext<'_>,
) -> usize {
let buffer_duration_seconds = output.len() as f64 / (sample_rate as f64 * channels as f64);
let buffer_end_seconds = playhead_seconds + buffer_duration_seconds;
let buffer_end = ctx.buffer_end();
// Split borrow: take clip_render_buffer out to avoid borrow conflict with &self methods
let mut clip_buffer = std::mem::take(&mut self.clip_render_buffer);
@@ -904,16 +1169,8 @@ impl AudioTrack {
// Render all active clip instances into the buffer
for clip in &self.clips {
// Check if clip overlaps with current buffer time range
if clip.external_start < buffer_end_seconds && clip.external_end() > playhead_seconds {
rendered += self.render_clip(
clip,
&mut clip_buffer,
pool,
playhead_seconds,
sample_rate,
channels,
);
if clip.external_start_secs(ctx.tempo_map) < buffer_end && clip.external_end_secs(ctx.tempo_map) > ctx.playhead_seconds {
rendered += self.render_clip(clip, &mut clip_buffer, pool, ctx);
}
}
@@ -931,13 +1188,13 @@ impl AudioTrack {
}
// Process through the effects graph (this will write to output buffer)
self.effects_graph.process(output, &[], playhead_seconds);
self.effects_graph.process(output, &[], ctx.playhead_beats());
// Put the buffer back for reuse next callback
self.clip_render_buffer = clip_buffer;
// Evaluate and apply automation
let effective_volume = self.evaluate_automation_at_time(playhead_seconds);
let effective_volume = self.evaluate_automation_at_time(ctx.playhead_beats());
// Apply track volume
for sample in output.iter_mut() {
@@ -948,7 +1205,7 @@ impl AudioTrack {
}
/// Evaluate automation at a specific time and return the effective volume
fn evaluate_automation_at_time(&self, time: f64) -> f32 {
fn evaluate_automation_at_time(&self, time: Beats) -> f32 {
let mut volume = self.volume;
// Check for volume automation
@@ -977,49 +1234,40 @@ impl AudioTrack {
clip: &AudioClipInstance,
output: &mut [f32],
pool: &AudioClipPool,
playhead_seconds: f64,
sample_rate: u32,
channels: u32,
ctx: RenderContext<'_>,
) -> usize {
let buffer_duration_seconds = output.len() as f64 / (sample_rate as f64 * channels as f64);
let buffer_end_seconds = playhead_seconds + buffer_duration_seconds;
let playhead = ctx.playhead_seconds;
let buffer_end = ctx.buffer_end();
let tempo_map = ctx.tempo_map;
let sample_rate = ctx.sample_rate;
let channels = ctx.channels;
// Determine the time range we need to render (intersection of buffer and clip external bounds)
let render_start_seconds = playhead_seconds.max(clip.external_start);
let render_end_seconds = buffer_end_seconds.min(clip.external_end());
let render_start = playhead.max(clip.external_start_secs(tempo_map));
let render_end = buffer_end.min(clip.external_end_secs(tempo_map));
// If no overlap, return early
if render_start_seconds >= render_end_seconds {
if render_start >= render_end {
return 0;
}
let internal_duration = clip.internal_duration();
if internal_duration <= 0.0 {
if internal_duration <= Seconds::ZERO {
return 0;
}
// Calculate combined gain
let combined_gain = clip.gain;
let mut total_rendered = 0;
// Process the render range sample by sample (or in chunks for efficiency)
// For looping clips, we need to handle wrap-around at the loop boundary
let samples_per_second = sample_rate as f64 * channels as f64;
// For now, render in a simpler way - iterate through the timeline range
// and use get_content_position for each sample position
let output_start_offset = ((render_start_seconds - playhead_seconds) * samples_per_second + 0.5) as usize;
let output_end_offset = ((render_end_seconds - playhead_seconds) * samples_per_second + 0.5) as usize;
let output_start_offset = ((render_start - playhead).0 * samples_per_second + 0.5) as usize;
let output_end_offset = ((render_end - playhead).0 * samples_per_second + 0.5) as usize;
if output_end_offset > output.len() || output_start_offset > output.len() {
return 0;
}
// If not looping, we can render in one chunk (more efficient)
if !clip.is_looping() {
// Simple case: no looping
let content_start = clip.get_content_position(render_start_seconds).unwrap_or(clip.internal_start);
if !clip.is_looping(tempo_map) {
let content_start = clip.get_content_position(render_start, tempo_map).unwrap_or(clip.internal_start);
let output_len = output.len();
let output_slice = &mut output[output_start_offset..output_end_offset.min(output_len)];
@@ -1033,23 +1281,20 @@ impl AudioTrack {
clip.read_ahead.as_deref(),
);
} else {
// Looping case: need to handle wrap-around at loop boundaries
// Render in segments, one per loop iteration
let mut timeline_pos = render_start_seconds;
// Looping case: handle wrap-around at loop boundaries
let mut timeline_pos = render_start;
let mut output_offset = output_start_offset;
while timeline_pos < render_end_seconds && output_offset < output.len() {
// Calculate position within the loop
let relative_pos = timeline_pos - clip.external_start;
let loop_offset = relative_pos % internal_duration;
let content_pos = clip.internal_start + loop_offset;
while timeline_pos < render_end && output_offset < output.len() {
let relative_pos = timeline_pos - clip.external_start_secs(tempo_map);
let loop_offset = relative_pos.0 % internal_duration.0;
let content_pos = clip.internal_start + Seconds(loop_offset);
// Calculate how much we can render before hitting the loop boundary
let time_to_loop_end = internal_duration - loop_offset;
let time_to_render_end = render_end_seconds - timeline_pos;
let time_to_loop_end = Seconds(internal_duration.0 - loop_offset);
let time_to_render_end = render_end - timeline_pos;
let chunk_duration = time_to_loop_end.min(time_to_render_end);
let chunk_samples = (chunk_duration * samples_per_second) as usize;
let chunk_samples = (chunk_duration.0 * samples_per_second) as usize;
let chunk_samples = chunk_samples.min(output.len() - output_offset);
if chunk_samples == 0 {
@@ -1070,7 +1315,7 @@ impl AudioTrack {
total_rendered += rendered;
output_offset += chunk_samples;
timeline_pos += chunk_duration;
timeline_pos = timeline_pos + chunk_duration;
}
}
+292
View File
@@ -0,0 +1,292 @@
//! Streaming min/max waveform LOD pyramid.
//!
//! A waveform pyramid is a tree of zoom levels. **Index = tree depth:**
//! `levels[0]` is the **root** (a single texel — the min/max envelope of the
//! whole file, lowest resolution); each deeper level is `BRANCH`× finer, and
//! `levels.last()` is the **floor** (one texel per `floor_samples_per_texel`
//! source frames — the finest *persisted* level). A node's children live at
//! `index + 1`, so the residency invariant ("a node is cleared only after its
//! children") reads straight off the index.
//!
//! Below the floor (finer than the floor bucket) is *not* stored; the caller
//! re-decodes the source window on demand for true per-sample detail.
//!
//! The builder is **streaming**: samples are pushed once, in order, and only the
//! finest level is accumulated (~`total_frames / floor` texels); the coarser
//! levels are derived by repeated `BRANCH:1` min/max reduction in [`finish`].
//! This yields the identical pyramid to an in-stream cascade (each parent = the
//! min/max of its children) without ever holding the full sample buffer.
//!
//! **Ragged edges are handled by reducing over available children:** a bucket
//! whose group is partial (1..BRANCH children, or `< floor` samples at the floor)
//! simply takes the min/max of what's there — no value padding. Padding to a
//! regular shape, if ever needed, is a GPU-texture/tile concern, not the data's.
//!
//! Each texel carries per-channel min/max for up to two channels
//! (`Lmin,Lmax,Rmin,Rmax`), matching the GPU waveform texture; mono mirrors the
//! left channel into the right.
//!
//! [`finish`]: WaveformPyramidBuilder::finish
/// Reduction factor between adjacent pyramid levels.
pub const BRANCH: u32 = 4;
/// Default finest-level resolution (source frames per floor texel). Trades
/// on-disk pyramid size against how soon zoom-in must re-decode the source.
pub const DEFAULT_FLOOR_SAMPLES_PER_TEXEL: u32 = 256;
/// One waveform texel: per-channel min/max (stereo; mono duplicates left→right).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Texel {
pub l_min: f32,
pub l_max: f32,
pub r_min: f32,
pub r_max: f32,
}
impl Texel {
const EMPTY: Texel = Texel {
l_min: f32::INFINITY,
l_max: f32::NEG_INFINITY,
r_min: f32::INFINITY,
r_max: f32::NEG_INFINITY,
};
#[inline]
fn include_sample(&mut self, l: f32, r: f32) {
self.l_min = self.l_min.min(l);
self.l_max = self.l_max.max(l);
self.r_min = self.r_min.min(r);
self.r_max = self.r_max.max(r);
}
#[inline]
fn include_texel(&mut self, c: &Texel) {
self.l_min = self.l_min.min(c.l_min);
self.l_max = self.l_max.max(c.l_max);
self.r_min = self.r_min.min(c.r_min);
self.r_max = self.r_max.max(c.r_max);
}
}
/// A built min/max LOD pyramid, **root-first**: `levels[0]` is the coarsest
/// (whole-file envelope), `levels.last()` is the finest persisted (floor).
#[derive(Clone, Debug)]
pub struct WaveformPyramid {
pub floor_samples_per_texel: u32,
pub branch: u32,
pub channels: u32,
pub total_frames: u64,
pub levels: Vec<Vec<Texel>>,
}
impl WaveformPyramid {
/// Coarsest level — a single texel (whole-file envelope), or empty if no
/// samples were pushed.
pub fn root(&self) -> &[Texel] {
self.levels.first().map_or(&[][..], |v| v)
}
/// Finest persisted level (`floor_samples_per_texel` frames per texel).
pub fn floor(&self) -> &[Texel] {
self.levels.last().map_or(&[][..], |v| v)
}
/// Number of levels (tree depth + 1).
pub fn depth(&self) -> usize {
self.levels.len()
}
/// Serialize to a compact binary blob (for persisting in the `.beam`
/// container). Header carries `B`/branch/channels/total_frames + per-level
/// lengths, then root-first texel data (`f32` min/max).
pub fn to_bytes(&self) -> Vec<u8> {
let total_texels: usize = self.levels.iter().map(|l| l.len()).sum();
let mut out = Vec::with_capacity(32 + self.levels.len() * 4 + total_texels * 16);
out.extend_from_slice(b"LBWF");
out.extend_from_slice(&1u32.to_le_bytes()); // format version
out.extend_from_slice(&self.floor_samples_per_texel.to_le_bytes());
out.extend_from_slice(&self.branch.to_le_bytes());
out.extend_from_slice(&self.channels.to_le_bytes());
out.extend_from_slice(&self.total_frames.to_le_bytes());
out.extend_from_slice(&(self.levels.len() as u32).to_le_bytes());
for level in &self.levels {
out.extend_from_slice(&(level.len() as u32).to_le_bytes());
}
for level in &self.levels {
for t in level {
out.extend_from_slice(&t.l_min.to_le_bytes());
out.extend_from_slice(&t.l_max.to_le_bytes());
out.extend_from_slice(&t.r_min.to_le_bytes());
out.extend_from_slice(&t.r_max.to_le_bytes());
}
}
out
}
/// Reconstruct from [`WaveformPyramid::to_bytes`].
pub fn from_bytes(data: &[u8]) -> Result<WaveformPyramid, String> {
let mut r = ByteReader::new(data);
if r.take(4)? != b"LBWF" {
return Err("Not a waveform pyramid blob".to_string());
}
let version = r.u32()?;
if version != 1 {
return Err(format!("Unsupported waveform pyramid version {}", version));
}
let floor_samples_per_texel = r.u32()?;
let branch = r.u32()?;
let channels = r.u32()?;
let total_frames = r.u64()?;
let num_levels = r.u32()? as usize;
let mut level_lens = Vec::with_capacity(num_levels);
for _ in 0..num_levels {
level_lens.push(r.u32()? as usize);
}
let mut levels = Vec::with_capacity(num_levels);
for &len in &level_lens {
let mut level = Vec::with_capacity(len);
for _ in 0..len {
level.push(Texel {
l_min: r.f32()?,
l_max: r.f32()?,
r_min: r.f32()?,
r_max: r.f32()?,
});
}
levels.push(level);
}
Ok(WaveformPyramid {
floor_samples_per_texel,
branch,
channels,
total_frames,
levels,
})
}
}
/// Minimal little-endian byte cursor for [`WaveformPyramid::from_bytes`].
struct ByteReader<'a> {
data: &'a [u8],
pos: usize,
}
impl<'a> ByteReader<'a> {
fn new(data: &'a [u8]) -> Self {
Self { data, pos: 0 }
}
fn take(&mut self, n: usize) -> Result<&'a [u8], String> {
let end = self.pos.checked_add(n).ok_or("overflow")?;
if end > self.data.len() {
return Err("Truncated waveform pyramid blob".to_string());
}
let s = &self.data[self.pos..end];
self.pos = end;
Ok(s)
}
fn u32(&mut self) -> Result<u32, String> {
Ok(u32::from_le_bytes(self.take(4)?.try_into().unwrap()))
}
fn u64(&mut self) -> Result<u64, String> {
Ok(u64::from_le_bytes(self.take(8)?.try_into().unwrap()))
}
fn f32(&mut self) -> Result<f32, String> {
Ok(f32::from_le_bytes(self.take(4)?.try_into().unwrap()))
}
}
/// Streaming builder for a [`WaveformPyramid`]. See the module docs.
pub struct WaveformPyramidBuilder {
floor: u32,
branch: u32,
channels: u32,
total_frames: u64,
floor_level: Vec<Texel>,
acc: Texel,
acc_count: u32,
}
impl WaveformPyramidBuilder {
pub fn new(channels: u32, floor_samples_per_texel: u32) -> Self {
Self {
floor: floor_samples_per_texel.max(1),
branch: BRANCH,
channels: channels.max(1),
total_frames: 0,
floor_level: Vec::new(),
acc: Texel::EMPTY,
acc_count: 0,
}
}
/// Pre-reserve the floor `Vec` from an estimated total frame count (e.g. the
/// probe's `total_frames`), to avoid reallocations during streaming. Purely a
/// hint — the final size is set by the actual number of frames pushed.
pub fn reserve_for_frames(&mut self, estimated_frames: u64) {
let est_texels = (estimated_frames / self.floor as u64).saturating_add(1);
self.floor_level.reserve(est_texels.min(usize::MAX as u64) as usize);
}
/// Push a block of interleaved samples (`channels` per frame). Partial
/// trailing frames (fewer than `channels`) are ignored.
pub fn push_interleaved(&mut self, samples: &[f32]) {
let ch = self.channels as usize;
for frame in samples.chunks_exact(ch) {
let l = frame[0];
let r = if ch >= 2 { frame[1] } else { l };
self.push_frame(l, r);
}
}
#[inline]
fn push_frame(&mut self, l: f32, r: f32) {
self.total_frames += 1;
self.acc.include_sample(l, r);
self.acc_count += 1;
if self.acc_count >= self.floor {
self.floor_level.push(std::mem::replace(&mut self.acc, Texel::EMPTY));
self.acc_count = 0;
}
}
/// Flush the trailing partial bucket and reduce up to the root.
pub fn finish(mut self) -> WaveformPyramid {
if self.acc_count > 0 {
self.floor_level.push(self.acc);
}
// Build finest-first by repeated BRANCH:1 reduction until one texel.
// The shape is fully determined by the floor texel count; the last group
// at each level may be ragged (1..BRANCH children) and reduces over what
// it has.
let mut levels = vec![std::mem::take(&mut self.floor_level)];
let branch = self.branch as usize;
while levels.last().map_or(0, |l| l.len()) > 1 {
let prev = levels.last().unwrap();
let mut next = Vec::with_capacity(prev.len().div_ceil(branch));
for chunk in prev.chunks(branch) {
let mut t = Texel::EMPTY;
for c in chunk {
t.include_texel(c);
}
next.push(t);
}
levels.push(next);
}
// Output is root-first (convention B): levels[0] = root, last = floor.
levels.reverse();
WaveformPyramid {
floor_samples_per_texel: self.floor,
branch: self.branch,
channels: self.channels,
total_frames: self.total_frames,
levels,
}
}
}
// Tests live in `daw-backend/tests/waveform_pyramid.rs` (integration tests) so
// they build the lib in normal mode, independent of the crate's pre-existing
// broken `#[cfg(test)]` unit tests (automation.rs).
+1 -1
View File
@@ -1,3 +1,3 @@
pub mod types;
pub use types::{AudioEvent, Command, MidiClipData, OscilloscopeData, Query, QueryResponse};
pub use types::{AudioEvent, Command, MidiClipData, OscilloscopeData, Query, QueryResponse, TrimRange};
+148 -42
View File
@@ -2,9 +2,26 @@ use crate::audio::{
AudioClipInstanceId, AutomationLaneId, ClipId, CurveType, MidiClip, MidiClipId,
MidiClipInstanceId, ParameterId, TrackId,
};
use crate::audio::midi::MidiEvent;
use crate::audio::buffer_pool::BufferPoolStats;
use crate::audio::node_graph::nodes::LoopMode;
use crate::io::WaveformPeak;
use crate::time::{Beats, Seconds};
/// A clip's internal (content) boundaries, tagged with the domain they're measured in.
///
/// A clip's content time is SECONDS for sampled audio but BEATS for MIDI — the same polymorphism
/// `ClipInstance::trim_start`/`trim_end` carry. Passing these as bare `f64`s meant the caller and
/// the engine could disagree about the unit with nothing to catch it: an audio trim of "1.0" was
/// once stored as `Beats(1.0)` for the clip's external duration, so a 1-second split played back as
/// half a second at 120 BPM. Tagging the domain makes that a type error instead of a bug report.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum TrimRange {
/// Sampled-audio content time.
Seconds { start: Seconds, end: Seconds },
/// MIDI content time.
Beats { start: Beats, end: Beats },
}
/// Commands sent from UI/control thread to audio thread
#[derive(Debug, Clone)]
@@ -17,7 +34,7 @@ pub enum Command {
/// Pause playback (maintains position)
Pause,
/// Seek to a specific position in seconds
Seek(f64),
Seek(Seconds),
// Track management commands
/// Set track volume (0.0 = silence, 1.0 = unity gain)
@@ -29,13 +46,12 @@ pub enum Command {
// Clip management commands
/// Move a clip to a new timeline position (track_id, clip_id, new_external_start)
MoveClip(TrackId, ClipId, f64),
/// Trim a clip's internal boundaries (track_id, clip_id, new_internal_start, new_internal_end)
/// This changes which portion of the source content is used
TrimClip(TrackId, ClipId, f64, f64),
MoveClip(TrackId, ClipId, Beats),
/// Trim a clip's internal boundaries — which portion of the source content is used.
TrimClip(TrackId, ClipId, TrimRange),
/// Extend/shrink a clip's external duration (track_id, clip_id, new_external_duration)
/// If duration > internal duration, the clip will loop
ExtendClip(TrackId, ClipId, f64),
ExtendClip(TrackId, ClipId, Beats),
// Metatrack management commands
/// Create a new metatrack with a name and optional parent group
@@ -51,15 +67,15 @@ pub enum Command {
SetTimeStretch(TrackId, f32),
/// Set metatrack time offset in seconds (track_id, offset)
/// Positive = shift content later, negative = shift earlier
SetOffset(TrackId, f64),
SetOffset(TrackId, Seconds),
/// Set metatrack pitch shift in semitones (track_id, semitones) - for future use
SetPitchShift(TrackId, f32),
/// Set metatrack trim start in seconds (track_id, trim_start)
/// Children won't hear content before this point
SetTrimStart(TrackId, f64),
SetTrimStart(TrackId, Seconds),
/// Set metatrack trim end in seconds (track_id, trim_end)
/// None means no end trim
SetTrimEnd(TrackId, Option<f64>),
SetTrimEnd(TrackId, Option<Seconds>),
// Audio track commands
/// Create a new audio track with a name and optional parent group
@@ -67,8 +83,10 @@ pub enum Command {
/// Add an audio file to the pool (path, data, channels, sample_rate)
/// Returns the pool index via an AudioEvent
AddAudioFile(String, Vec<f32>, u32, u32),
/// Add a clip to an audio track (track_id, pool_index, start_time, duration, offset)
AddAudioClip(TrackId, usize, f64, f64, f64),
/// Add a clip to an audio track (track_id, clip_id, pool_index, start_time, duration, offset)
/// The clip_id is pre-assigned by the caller (via EngineController::next_audio_clip_id())
/// (track, clip_id, pool_index, start_time [beats], duration [beats], offset [seconds])
AddAudioClip(TrackId, AudioClipInstanceId, usize, Beats, Beats, Seconds),
// MIDI commands
/// Create a new MIDI track with a name and optional parent group
@@ -76,14 +94,16 @@ pub enum Command {
/// Add a MIDI clip to the pool without placing it on a track
AddMidiClipToPool(MidiClip),
/// Create a new MIDI clip on a track (track_id, start_time, duration)
CreateMidiClip(TrackId, f64, f64),
CreateMidiClip(TrackId, Beats, Beats),
/// Add a MIDI note to a clip (track_id, clip_id, time_offset, note, velocity, duration)
AddMidiNote(TrackId, MidiClipId, f64, u8, u8, f64),
AddMidiNote(TrackId, MidiClipId, Beats, u8, u8, Beats),
/// Add a pre-loaded MIDI clip to a track (track_id, clip, start_time)
AddLoadedMidiClip(TrackId, MidiClip, f64),
AddLoadedMidiClip(TrackId, MidiClip, Beats),
/// Update MIDI clip notes (track_id, clip_id, notes: Vec<(start_time, note, velocity, duration)>)
/// NOTE: May need to switch to individual note operations if this becomes slow on clips with many notes
UpdateMidiClipNotes(TrackId, MidiClipId, Vec<(f64, u8, u8, f64)>),
UpdateMidiClipNotes(TrackId, MidiClipId, Vec<(Beats, u8, u8, Beats)>),
/// Replace all events in a MIDI clip (track_id, clip_id, events). Used for CC/pitch bend editing.
UpdateMidiClipEvents(TrackId, MidiClipId, Vec<MidiEvent>),
/// Remove a MIDI clip instance from a track (track_id, instance_id) - for undo/redo support
RemoveMidiClip(TrackId, MidiClipInstanceId),
/// Remove an audio clip instance from a track (track_id, instance_id) - for undo/redo support
@@ -97,9 +117,9 @@ pub enum Command {
/// Create a new automation lane on a track (track_id, parameter_id)
CreateAutomationLane(TrackId, ParameterId),
/// Add an automation point to a lane (track_id, lane_id, time, value, curve)
AddAutomationPoint(TrackId, AutomationLaneId, f64, f32, CurveType),
AddAutomationPoint(TrackId, AutomationLaneId, Beats, f32, CurveType),
/// Remove an automation point at a specific time (track_id, lane_id, time, tolerance)
RemoveAutomationPoint(TrackId, AutomationLaneId, f64, f64),
RemoveAutomationPoint(TrackId, AutomationLaneId, Beats, Beats),
/// Clear all automation points from a lane (track_id, lane_id)
ClearAutomationLane(TrackId, AutomationLaneId),
/// Remove an automation lane (track_id, lane_id)
@@ -107,9 +127,24 @@ pub enum Command {
/// Enable/disable an automation lane (track_id, lane_id, enabled)
SetAutomationLaneEnabled(TrackId, AutomationLaneId, bool),
// Transport cycle (loop) region
/// Set the cycle region the transport loops over, in beats (None clears it).
/// Authored in beats so it survives tempo changes.
SetLoopRegion(Option<(Beats, Beats)>),
/// Enable/disable wrapping at the cycle region's end.
SetLoopEnabled(bool),
/// How a cycle MIDI recording treats its passes.
///
/// `false` (default) = MERGE: every pass overdubs into one clip. `true` = SEPARATE TAKES: each
/// pass becomes its own MIDI clip, and the editor folds them into a take folder — the same shape
/// audio always gets.
SetCycleMidiSeparateTakes(bool),
// Recording commands
/// Start recording on a track (track_id, start_time)
StartRecording(TrackId, f64),
/// (track, start_time, force_takes — cut takes even if the transport never wraps, because the
/// region already holds takes and this is another one)
StartRecording(TrackId, Beats, bool),
/// Stop the current recording
StopRecording,
/// Pause the current recording
@@ -119,7 +154,8 @@ pub enum Command {
// MIDI Recording commands
/// Start MIDI recording on a track (track_id, clip_id, start_time)
StartMidiRecording(TrackId, MidiClipId, f64),
/// (track, clip, start_time, force_takes — see [`Command::StartRecording`])
StartMidiRecording(TrackId, MidiClipId, Beats, bool),
/// Stop the current MIDI recording
StopMidiRecording,
@@ -140,7 +176,8 @@ pub enum Command {
SetMetronomeEnabled(bool),
/// Set project tempo and time signature (bpm, (numerator, denominator))
SetTempo(f32, (u32, u32)),
/// Replace the entire tempo map (multi-entry variable tempo support)
SetTempoMap(crate::TempoMap),
// Node graph commands
/// Add a node to a track's instrument graph (track_id, node_type, position_x, position_y)
GraphAddNode(TrackId, String, f32, f32),
@@ -180,6 +217,26 @@ pub enum Command {
GraphSavePreset(TrackId, String, String, String, Vec<String>),
/// Load a preset into a track's graph (track_id, preset_path)
GraphLoadPreset(TrackId, String),
/// Load a .lbins instrument bundle into a track's graph (track_id, path)
GraphLoadLbins(TrackId, std::path::PathBuf),
/// Save a track's graph as a .lbins instrument bundle (track_id, path, preset_name, description, tags)
GraphSaveLbins(TrackId, std::path::PathBuf, String, String, Vec<String>),
// Metatrack subtrack graph commands
/// Replace a metatrack's mixing graph with the default SubtrackInputs→Mixer→Output layout.
/// (metatrack_id, ordered list of (child_track_id, display_name))
SetMetatrackSubtrackGraph(TrackId, Vec<(TrackId, String)>),
/// Add a new subtrack port to a metatrack's SubtrackInputsNode.
/// (metatrack_id, child_track_id, display_name)
AddMetatrackSubtrack(TrackId, TrackId, String),
/// Remove a subtrack port from a metatrack's SubtrackInputsNode.
/// (metatrack_id, child_track_id)
RemoveMetatrackSubtrack(TrackId, TrackId),
/// Re-associate backend TrackIds with SubtrackInputsNode slots after project reload.
/// (metatrack_id, ordered list of (child_track_id, display_name))
UpdateMetatrackSubtrackIds(TrackId, Vec<(TrackId, String)>),
/// Set or clear the graph_is_default flag on any track (track_id, value)
SetGraphIsDefault(TrackId, bool),
/// Save a VoiceAllocator's template graph as a preset (track_id, voice_allocator_id, preset_path, preset_name)
GraphSaveTemplatePreset(TrackId, u32, String, String),
@@ -210,9 +267,9 @@ pub enum Command {
// Automation Input Node commands
/// Add or update a keyframe on an AutomationInput node (track_id, node_id, time, value, interpolation, ease_out, ease_in)
AutomationAddKeyframe(TrackId, u32, f64, f32, String, (f32, f32), (f32, f32)),
AutomationAddKeyframe(TrackId, u32, Beats, f32, String, (f32, f32), (f32, f32)),
/// Remove a keyframe from an AutomationInput node (track_id, node_id, time)
AutomationRemoveKeyframe(TrackId, u32, f64),
AutomationRemoveKeyframe(TrackId, u32, Beats),
/// Set the display name of an AutomationInput node (track_id, node_id, name)
AutomationSetName(TrackId, u32, String),
@@ -244,7 +301,7 @@ pub enum Command {
#[derive(Debug, Clone)]
pub enum AudioEvent {
/// Current playback position in seconds
PlaybackPosition(f64),
PlaybackPosition(Seconds),
/// Playback has stopped (reached end of audio)
PlaybackStopped,
/// Audio buffer underrun detected
@@ -262,16 +319,45 @@ pub enum AudioEvent {
/// Recording started (track_id, clip_id, sample_rate, channels)
RecordingStarted(TrackId, ClipId, u32, u32),
/// Recording progress update (clip_id, current_duration)
RecordingProgress(ClipId, f64),
RecordingProgress(ClipId, Seconds),
/// Recording stopped (clip_id, pool_index, waveform)
RecordingStopped(ClipId, usize, Vec<WaveformPeak>),
/// A MIDI recording that wrapped the cycle region at least once, in SEPARATE TAKES mode.
///
/// One MIDI clip per pass, in recording order. (Merge mode emits the ordinary
/// `MidiRecordingStopped` instead — all passes are already folded into the one clip.)
MidiCycleRecordingStopped {
track_id: TrackId,
/// One pool MIDI clip per pass. The first is the clip the recording started on.
clip_ids: Vec<MidiClipId>,
/// Where the takes sit on the timeline — the cycle region's start.
loop_start: Beats,
/// The region's length in beats: every take spans exactly this.
loop_len_beats: Beats,
},
/// A recording that wrapped the cycle region at least once, and so became multi-take.
///
/// Each take spans the full region and they're all the same length (partial passes are padded
/// with silence), so the editor can promote the recording clip straight to a take folder.
CycleRecordingStopped {
clip_id: ClipId,
/// One entry per pass: (audio pool index, waveform peaks), in recording order.
takes: Vec<(usize, Vec<WaveformPeak>)>,
/// Where the takes sit on the timeline — the cycle region's start, not the punch-in point.
loop_start: Beats,
/// The region's length in beats (what the take folder stores as `recorded_loop_beats`).
loop_len_beats: Beats,
/// The same length in seconds — the take folder's content duration, which is seconds-domain
/// for audio.
loop_len_seconds: Seconds,
},
/// Recording error (error_message)
RecordingError(String),
/// MIDI recording stopped (track_id, clip_id, note_count)
MidiRecordingStopped(TrackId, MidiClipId, usize),
/// MIDI recording progress (track_id, clip_id, duration, notes)
/// Notes format: (start_time, note, velocity, duration)
MidiRecordingProgress(TrackId, MidiClipId, f64, Vec<(f64, u8, u8, f64)>),
/// Notes format: (start_time, note, velocity, duration) — all times in beats
MidiRecordingProgress(TrackId, MidiClipId, Beats, Vec<(Beats, u8, u8, Beats)>),
/// Project has been reset
ProjectReset,
/// MIDI note started playing (note, velocity)
@@ -286,8 +372,8 @@ pub enum AudioEvent {
GraphConnectionError(TrackId, String),
/// Graph state changed (for full UI sync)
GraphStateChanged(TrackId),
/// Preset fully loaded (track_id) - emitted after all nodes and samples are loaded
GraphPresetLoaded(TrackId),
/// Preset fully loaded (track_id, preset_name) - emitted after all nodes and samples are loaded
GraphPresetLoaded(TrackId, String),
/// Preset has been saved to file (track_id, preset_path)
GraphPresetSaved(TrackId, String),
/// Script compilation result (track_id, node_id, success, error, ui_declaration, source)
@@ -315,7 +401,7 @@ pub enum AudioEvent {
WaveformChunksReady {
pool_index: usize,
detail_level: u8,
chunks: Vec<(u32, (f64, f64), Vec<WaveformPeak>)>,
chunks: Vec<(u32, (Seconds, Seconds), Vec<WaveformPeak>)>,
},
/// An audio file has been imported and is ready for playback.
@@ -326,7 +412,7 @@ pub enum AudioEvent {
path: String,
channels: u32,
sample_rate: u32,
duration: f64,
duration: Seconds,
format: crate::io::audio_file::AudioFormat,
},
@@ -375,6 +461,8 @@ pub enum Query {
GetAutomationKeyframes(TrackId, u32),
/// Get the display name of an AutomationInput node (track_id, node_id)
GetAutomationName(TrackId, u32),
/// Get the value range (min, max) of an AutomationInput node (track_id, node_id)
GetAutomationRange(TrackId, u32),
/// Serialize audio pool for project saving (project_path)
SerializeAudioPool(std::path::PathBuf),
/// Load audio pool from serialized entries (entries, project_path)
@@ -398,14 +486,10 @@ pub enum Query {
/// Export audio to file (settings, output_path)
ExportAudio(crate::audio::ExportSettings, std::path::PathBuf),
/// Add a MIDI clip to a track synchronously (track_id, clip, start_time) - returns instance ID
AddMidiClipSync(TrackId, crate::audio::midi::MidiClip, f64),
AddMidiClipSync(TrackId, crate::audio::midi::MidiClip, Beats),
/// Add a MIDI clip instance to a track synchronously (track_id, instance) - returns instance ID
/// The clip must already exist in the MidiClipPool
AddMidiClipInstanceSync(TrackId, crate::audio::midi::MidiClipInstance),
/// Add an audio clip to a track synchronously (track_id, pool_index, start_time, duration, offset) - returns instance ID
AddAudioClipSync(TrackId, usize, f64, f64, f64),
/// Add an audio file to the pool synchronously (path, data, channels, sample_rate) - returns pool index
AddAudioFileSync(String, Vec<f32>, u32, u32),
/// Import an audio file synchronously (path) - returns pool index.
/// Does the same work as Command::ImportAudio (mmap for PCM, streaming
/// setup for compressed) but returns the real pool index in the response.
@@ -414,14 +498,27 @@ pub enum Query {
/// problem for very large files, switch to async import with event-based
/// pool index reconciliation.
ImportAudioSync(std::path::PathBuf),
/// Add the audio track of a video file as a streaming pool entry (FFmpeg,
/// decoded on demand — no extraction). Probes the audio track and returns
/// the pool index. Response: `AudioImportedSync`.
AddVideoAudioSync(std::path::PathBuf),
/// Get raw audio samples from pool (pool_index) - returns (samples, sample_rate, channels)
GetPoolAudioSamples(usize),
/// Get a clone of the current project for serialization
GetProject,
/// Set the project (replaces current project state)
SetProject(Box<crate::audio::project::Project>),
/// Install the host's packed-media byte-source factory (for streaming
/// container-packed audio on load). Sent before `SetProject` so bulk
/// activation can open packed sources.
SetBlobSourceFactory(std::sync::Arc<dyn crate::audio::disk_reader::AudioBlobSourceFactory>),
/// Duplicate a MIDI clip in the pool, returning the new clip's ID
DuplicateMidiClipSync(MidiClipId),
/// Get whether a track's graph is still the auto-generated default
GetGraphIsDefault(TrackId),
/// Get the pitch bend range (in semitones) for the instrument on a MIDI track.
/// Searches for MidiToCVNode (in VA templates) or MultiSamplerNode (direct).
GetPitchBendRange(TrackId),
}
/// Oscilloscope data from a node
@@ -434,16 +531,21 @@ pub struct OscilloscopeData {
}
/// MIDI clip data for serialization
///
/// `Beats`/`Seconds` are `#[serde(transparent)]`, so naming the domain here costs nothing on disk —
/// the `.beam` still holds a plain number.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct MidiClipData {
pub duration: f64,
/// MIDI content length is musical, so beats.
pub duration: Beats,
pub events: Vec<crate::audio::midi::MidiEvent>,
}
/// Automation keyframe data for serialization
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct AutomationKeyframeData {
pub time: f64,
/// Automation x-axes are all beats.
pub time: Beats,
pub value: f32,
pub interpolation: String,
pub ease_out: (f32, f32),
@@ -463,6 +565,8 @@ pub enum QueryResponse {
AutomationKeyframes(Result<Vec<AutomationKeyframeData>, String>),
/// Automation node name
AutomationName(Result<String, String>),
/// Automation node value range (min, max)
AutomationRange(Result<(f32, f32), String>),
/// Serialized audio pool entries
AudioPoolSerialized(Result<Vec<crate::audio::pool::AudioPoolEntry>, String>),
/// Audio pool loaded (returns list of missing pool indices)
@@ -478,17 +582,15 @@ pub enum QueryResponse {
/// Pool waveform data
PoolWaveform(Result<Vec<crate::io::WaveformPeak>, String>),
/// Pool file info (duration, sample_rate, channels)
PoolFileInfo(Result<(f64, u32, u32), String>),
PoolFileInfo(Result<(Seconds, u32, u32), String>),
/// Audio exported
AudioExported(Result<(), String>),
/// MIDI clip instance added (returns instance ID)
MidiClipInstanceAdded(Result<MidiClipInstanceId, String>),
/// Audio clip instance added (returns instance ID)
AudioClipInstanceAdded(Result<AudioClipInstanceId, String>),
/// Audio file added to pool (returns pool index)
AudioFileAddedSync(Result<usize, String>),
/// Audio file imported to pool (returns pool index)
AudioImportedSync(Result<usize, String>),
/// Packed-media byte-source factory installed
BlobSourceFactorySet(Result<(), String>),
/// Raw audio samples from pool (samples, sample_rate, channels)
PoolAudioSamples(Result<(Vec<f32>, u32, u32), String>),
/// Project retrieved
@@ -497,4 +599,8 @@ pub enum QueryResponse {
ProjectSet(Result<(), String>),
/// MIDI clip duplicated (returns new clip ID)
MidiClipDuplicated(Result<MidiClipId, String>),
/// Whether a track's graph is the auto-generated default
GraphIsDefault(bool),
/// Pitch bend range in semitones for the track's instrument
PitchBendRange(f32),
}
+4 -5
View File
@@ -113,11 +113,10 @@ impl SynthVoice {
// Simple sine wave
let sample = (self.phase * 2.0 * PI).sin() * (self.velocity as f32 / 127.0) * 0.3;
// Update phase
self.phase += self.frequency / sample_rate;
if self.phase >= 1.0 {
self.phase -= 1.0;
}
// Update phase. Use `.fract()` for a numerically stable wraparound: repeated
// conditional subtraction accumulates f32 rounding error over long-held notes,
// which drifts the timbre.
self.phase = (self.phase + self.frequency / sample_rate).fract();
self.age += 1;
+32 -127
View File
@@ -1,164 +1,69 @@
use crate::audio::midi::{MidiClip, MidiClipId, MidiEvent};
use crate::time::Beats;
use std::fs;
use std::path::Path;
/// Load a MIDI file and convert it to a MidiClip
/// Load a MIDI file and convert it to a MidiClip.
///
/// Event timestamps are stored as beat positions: `tick / ticks_per_beat`.
/// Tempo events in the MIDI file only affect wall-clock playback speed — not the
/// beat grid — so they are ignored here.
pub fn load_midi_file<P: AsRef<Path>>(
path: P,
clip_id: MidiClipId,
_sample_rate: u32,
) -> Result<MidiClip, String> {
// Read the MIDI file
let data = fs::read(path.as_ref()).map_err(|e| format!("Failed to read MIDI file: {}", e))?;
// Parse with midly
let smf = midly::Smf::parse(&data).map_err(|e| format!("Failed to parse MIDI file: {}", e))?;
// Convert timing to ticks per second
let ticks_per_beat = match smf.header.timing {
midly::Timing::Metrical(tpb) => tpb.as_int() as f64,
midly::Timing::Timecode(fps, subframe) => {
// For timecode, calculate equivalent ticks per second
// Timecode-based MIDI: treat subframes as ticks per beat
(fps.as_f32() * subframe as f32) as f64
}
};
// First pass: collect all events with their tick positions and tempo changes
#[derive(Debug)]
enum RawEvent {
Midi {
tick: u64,
channel: u8,
message: midly::MidiMessage,
},
Tempo {
tick: u64,
microseconds_per_beat: f64,
},
}
let mut events = Vec::new();
let mut max_tick = 0u64;
let mut raw_events = Vec::new();
let mut max_time_ticks = 0u64;
// Collect all events from all tracks with their absolute tick positions
for track in &smf.tracks {
let mut current_tick = 0u64;
for event in track {
current_tick += event.delta.as_int() as u64;
max_time_ticks = max_time_ticks.max(current_tick);
max_tick = max_tick.max(current_tick);
let timestamp = Beats(current_tick as f64 / ticks_per_beat);
match event.kind {
midly::TrackEventKind::Midi { channel, message } => {
raw_events.push(RawEvent::Midi {
tick: current_tick,
channel: channel.as_int(),
message,
});
}
midly::TrackEventKind::Meta(midly::MetaMessage::Tempo(tempo)) => {
raw_events.push(RawEvent::Tempo {
tick: current_tick,
microseconds_per_beat: tempo.as_int() as f64,
});
}
_ => {
// Ignore other meta events
}
}
}
}
// Sort all events by tick position
raw_events.sort_by_key(|e| match e {
RawEvent::Midi { tick, .. } => *tick,
RawEvent::Tempo { tick, .. } => *tick,
});
// Second pass: convert ticks to timestamps with proper tempo tracking
let mut events = Vec::new();
let mut microseconds_per_beat = 500000.0; // Default: 120 BPM
let mut last_tick = 0u64;
let mut accumulated_time = 0.0; // Time in seconds
for raw_event in raw_events {
match raw_event {
RawEvent::Tempo {
tick,
microseconds_per_beat: new_tempo,
} => {
// Update accumulated time up to this tempo change
let delta_ticks = tick - last_tick;
let delta_time = (delta_ticks as f64 / ticks_per_beat)
* (microseconds_per_beat / 1_000_000.0);
accumulated_time += delta_time;
last_tick = tick;
// Update tempo for future events
microseconds_per_beat = new_tempo;
}
RawEvent::Midi {
tick,
channel,
message,
} => {
// Calculate time for this event
let delta_ticks = tick - last_tick;
let delta_time = (delta_ticks as f64 / ticks_per_beat)
* (microseconds_per_beat / 1_000_000.0);
accumulated_time += delta_time;
last_tick = tick;
// Store timestamp in seconds (sample-rate independent)
let timestamp = accumulated_time;
match message {
midly::MidiMessage::NoteOn { key, vel } => {
let velocity = vel.as_int();
if velocity > 0 {
events.push(MidiEvent::note_on(
timestamp,
channel,
key.as_int(),
velocity,
));
} else {
events.push(MidiEvent::note_off(timestamp, channel, key.as_int(), 64));
let ch = channel.as_int();
match message {
midly::MidiMessage::NoteOn { key, vel } => {
let velocity = vel.as_int();
if velocity > 0 {
events.push(MidiEvent::note_on(timestamp, ch, key.as_int(), velocity));
} else {
events.push(MidiEvent::note_off(timestamp, ch, key.as_int(), 64));
}
}
}
midly::MidiMessage::NoteOff { key, vel } => {
events.push(MidiEvent::note_off(
timestamp,
channel,
key.as_int(),
vel.as_int(),
));
}
midly::MidiMessage::Controller { controller, value } => {
let status = 0xB0 | channel;
events.push(MidiEvent::new(
timestamp,
status,
controller.as_int(),
value.as_int(),
));
}
_ => {
// Ignore other MIDI messages
midly::MidiMessage::NoteOff { key, vel } => {
events.push(MidiEvent::note_off(timestamp, ch, key.as_int(), vel.as_int()));
}
midly::MidiMessage::Controller { controller, value } => {
let status = 0xB0 | ch;
events.push(MidiEvent::new(timestamp, status, controller.as_int(), value.as_int()));
}
_ => {}
}
}
_ => {} // Tempo and other meta events don't affect beat positions
}
}
}
// Calculate final clip duration
let final_delta_ticks = max_time_ticks - last_tick;
let final_delta_time =
(final_delta_ticks as f64 / ticks_per_beat) * (microseconds_per_beat / 1_000_000.0);
let duration_seconds = accumulated_time + final_delta_time;
// Create the MIDI clip (content only, positioning happens when creating instance)
let clip = MidiClip::new(clip_id, events, duration_seconds, "Imported MIDI".to_string());
let duration = Beats(max_tick as f64 / ticks_per_beat);
let clip = MidiClip::new(clip_id, events, duration, "Imported MIDI".to_string());
Ok(clip)
}
+183 -132
View File
@@ -6,6 +6,8 @@
pub mod audio;
pub mod command;
pub mod time;
pub mod tempo_map;
pub mod dsp;
pub mod effects;
pub mod io;
@@ -13,11 +15,13 @@ pub mod tui;
// Re-export commonly used types
pub use audio::{
AudioClipInstanceId, AudioPool, AudioTrack, AutomationLane, AutomationLaneId, AutomationPoint, BufferPool, Clip, ClipId, CurveType, Engine, EngineController,
AudioClipInstanceId, AudioClipSnapshot, AudioPool, AudioTrack, AutomationLane, AutomationLaneId, AutomationPoint, BufferPool, Clip, ClipId, CurveType, Engine, EngineController,
Metatrack, MidiClip, MidiClipId, MidiClipInstance, MidiClipInstanceId, MidiEvent, MidiTrack, ParameterId, PoolAudioFile, Project, RecordingState, RenderContext, Track, TrackId,
TrackNode,
};
pub use audio::node_graph::{GraphPreset, AudioGraph, PresetMetadata, SerializedConnection, SerializedNode};
pub use time::{Beats, ContentTime, Seconds};
pub use tempo_map::{TempoEntry, TempoInterpolation, TempoMap, beats_to_seconds_stack, seconds_to_beats_stack};
pub use command::{AudioEvent, Command, OscilloscopeData};
pub use command::types::AutomationKeyframeData;
pub use io::{load_midi_file, AudioFile, WaveformChunk, WaveformChunkKey, WaveformPeak, WavWriter};
@@ -41,6 +45,11 @@ pub struct AudioSystem {
pub event_rx: Option<rtrb::Consumer<AudioEvent>>,
/// Consumer for recording audio mirror (streams recorded samples to UI for live waveform)
recording_mirror_rx: Option<rtrb::Consumer<f32>>,
/// Producer end of the input ring-buffer. Taken into the closure when the
/// input stream is opened; `None` after `open_input_stream()` has been called.
input_tx: Option<rtrb::Producer<f32>>,
/// The live microphone/line-in stream. `None` until `open_input_stream()` is called.
input_stream: Option<cpal::Stream>,
}
impl AudioSystem {
@@ -85,7 +94,7 @@ impl AudioSystem {
// Create input ringbuffer for recording (large buffer for audio samples)
// Buffer size: 10 seconds of audio at 48kHz stereo = 48000 * 2 * 10 = 960000 samples
let input_buffer_size = (sample_rate * channels * 10) as usize;
let (mut input_tx, input_rx) = rtrb::RingBuffer::new(input_buffer_size);
let (input_tx, input_rx) = rtrb::RingBuffer::new(input_buffer_size);
// Create mirror ringbuffer for streaming recorded audio to UI (live waveform)
let (mirror_tx, mirror_rx) = rtrb::RingBuffer::new(input_buffer_size);
@@ -138,137 +147,8 @@ impl AudioSystem {
)
.map_err(|e| format!("Failed to build output stream: {e:?}"))?;
// Get input device
let input_device = match host.default_input_device() {
Some(device) => device,
None => {
eprintln!("Warning: No input device available, recording will be disabled");
// Start output stream and return without input
output_stream.play().map_err(|e| e.to_string())?;
// Spawn emitter thread if provided
if let Some(emitter) = event_emitter {
Self::spawn_emitter_thread(event_rx, emitter);
}
return Ok(Self {
controller,
stream: output_stream,
sample_rate,
channels,
event_rx: None, // No event receiver when audio device unavailable
recording_mirror_rx: None,
});
}
};
// Get input config using the device's default (most compatible)
let input_config = match input_device.default_input_config() {
Ok(config) => {
let cfg: cpal::StreamConfig = config.into();
cfg
}
Err(e) => {
eprintln!("Warning: Could not get input config: {}, recording will be disabled", e);
output_stream.play().map_err(|e| e.to_string())?;
if let Some(emitter) = event_emitter {
Self::spawn_emitter_thread(event_rx, emitter);
}
return Ok(Self {
controller,
stream: output_stream,
sample_rate,
channels,
event_rx: None,
recording_mirror_rx: None,
});
}
};
let input_sample_rate = input_config.sample_rate;
let input_channels = input_config.channels as u32;
let output_sample_rate = sample_rate;
let output_channels = channels;
let needs_resample = input_sample_rate != output_sample_rate || input_channels != output_channels;
if needs_resample {
eprintln!("[AUDIO] Input device: {}Hz {}ch -> resampling to {}Hz {}ch",
input_sample_rate, input_channels, output_sample_rate, output_channels);
}
// Build input stream with resampling if needed
let input_stream = match input_device
.build_input_stream(
&input_config,
move |data: &[f32], _: &cpal::InputCallbackInfo| {
if !needs_resample {
for &sample in data {
let _ = input_tx.push(sample);
}
} else {
// Resample: linear interpolation from input rate to output rate
let in_ch = input_channels as usize;
let out_ch = output_channels as usize;
let ratio = output_sample_rate as f64 / input_sample_rate as f64;
let in_frames = data.len() / in_ch;
let out_frames = (in_frames as f64 * ratio) as usize;
for i in 0..out_frames {
let src_pos = i as f64 / ratio;
let src_idx = src_pos as usize;
let frac = (src_pos - src_idx as f64) as f32;
for ch in 0..out_ch {
// Map output channel to input channel
let in_ch_idx = ch.min(in_ch - 1);
let s0 = if src_idx < in_frames {
data[src_idx * in_ch + in_ch_idx]
} else {
0.0
};
let s1 = if src_idx + 1 < in_frames {
data[(src_idx + 1) * in_ch + in_ch_idx]
} else {
s0
};
let _ = input_tx.push(s0 + frac * (s1 - s0));
}
}
}
},
|err| eprintln!("Input stream error: {}", err),
None,
) {
Ok(stream) => stream,
Err(e) => {
eprintln!("Warning: Could not build input stream: {}, recording will be disabled", e);
output_stream.play().map_err(|e| e.to_string())?;
if let Some(emitter) = event_emitter {
Self::spawn_emitter_thread(event_rx, emitter);
}
return Ok(Self {
controller,
stream: output_stream,
sample_rate,
channels,
event_rx: None,
recording_mirror_rx: None,
});
}
};
// Start both streams
// Start output stream
output_stream.play().map_err(|e| e.to_string())?;
input_stream.play().map_err(|e| e.to_string())?;
// Leak the input stream to keep it alive
Box::leak(Box::new(input_stream));
// Spawn emitter thread if provided, or store event_rx for manual polling
let event_rx_option = if let Some(emitter) = event_emitter {
@@ -278,6 +158,8 @@ impl AudioSystem {
Some(event_rx)
};
// Input stream is NOT opened here — call open_input_stream() when an
// audio input track is actually selected, to avoid constant ALSA wakeups.
Ok(Self {
controller,
stream: output_stream,
@@ -285,6 +167,8 @@ impl AudioSystem {
channels,
event_rx: event_rx_option,
recording_mirror_rx: Some(mirror_rx),
input_tx: Some(input_tx),
input_stream: None,
})
}
@@ -293,6 +177,99 @@ impl AudioSystem {
self.recording_mirror_rx.take()
}
/// Open the microphone/line-in input stream.
///
/// Call this as soon as an audio input track is selected so the stream is
/// ready before recording starts. The stream is opened with the same fixed
/// buffer size as the output stream to avoid ALSA spinning at high callback
/// rates with its tiny default buffer.
///
/// No-ops if the stream is already open.
pub fn open_input_stream(&mut self, buffer_size: u32) -> Result<(), String> {
if self.input_stream.is_some() {
return Ok(());
}
let mut input_tx = match self.input_tx.take() {
Some(tx) => tx,
None => return Err("Input ring-buffer already consumed".into()),
};
let host = cpal::default_host();
let input_device = host.default_input_device()
.ok_or("No input device available")?;
let default_cfg = input_device.default_input_config()
.map_err(|e| e.to_string())?;
let mut input_config: cpal::StreamConfig = default_cfg.into();
// Match the output buffer size so ALSA wakes up at the same rate as
// the output thread — prevents the ~750 wakeups/sec that the default
// 64-frame buffer causes.
if !cfg!(target_os = "windows") {
input_config.buffer_size = cpal::BufferSize::Fixed(buffer_size);
}
let input_sample_rate = input_config.sample_rate;
let input_channels = input_config.channels as u32;
let output_sample_rate = self.sample_rate;
let output_channels = self.channels;
let needs_resample = input_sample_rate != output_sample_rate
|| input_channels != output_channels;
if needs_resample {
eprintln!("[AUDIO] Input: {}Hz {}ch → resampling to {}Hz {}ch",
input_sample_rate, input_channels, output_sample_rate, output_channels);
}
let stream = input_device.build_input_stream(
&input_config,
move |data: &[f32], _: &cpal::InputCallbackInfo| {
if !needs_resample {
for &s in data { let _ = input_tx.push(s); }
} else {
let in_ch = input_channels as usize;
let out_ch = output_channels as usize;
let ratio = output_sample_rate as f64 / input_sample_rate as f64;
let in_frames = data.len() / in_ch;
let out_frames = (in_frames as f64 * ratio) as usize;
for i in 0..out_frames {
let src_pos = i as f64 / ratio;
let src_idx = src_pos as usize;
let frac = (src_pos - src_idx as f64) as f32;
for ch in 0..out_ch {
let ic = ch.min(in_ch - 1);
let s0 = data.get(src_idx * in_ch + ic).copied().unwrap_or(0.0);
let s1 = data.get((src_idx + 1) * in_ch + ic).copied().unwrap_or(s0);
let _ = input_tx.push(s0 + frac * (s1 - s0));
}
}
}
},
|err| eprintln!("Input stream error: {err}"),
None,
).map_err(|e| format!("Failed to build input stream: {e}"))?;
stream.play().map_err(|e| e.to_string())?;
self.input_stream = Some(stream);
Ok(())
}
/// Close the input stream (e.g. when the last audio input track is removed).
pub fn close_input_stream(&mut self) {
self.input_stream = None; // Drop stops the stream
}
/// Extract an [`InputStreamOpener`] that can be stored independently and
/// used to open the microphone/line-in stream on demand.
/// Returns `None` if called a second time.
pub fn take_input_opener(&mut self) -> Option<InputStreamOpener> {
self.input_tx.take().map(|tx| InputStreamOpener {
input_tx: tx,
sample_rate: self.sample_rate,
channels: self.channels,
})
}
/// Spawn a background thread to emit events from the ringbuffer
fn spawn_emitter_thread(mut event_rx: rtrb::Consumer<AudioEvent>, emitter: std::sync::Arc<dyn EventEmitter>) {
std::thread::spawn(move || {
@@ -308,3 +285,77 @@ impl AudioSystem {
});
}
}
/// Self-contained handle for opening the microphone/line-in stream on demand.
///
/// Obtained via [`AudioSystem::take_input_opener`]. Call [`open`](Self::open)
/// when the user selects an audio input track; store the returned
/// `cpal::Stream` to keep it alive (dropping it stops the stream).
pub struct InputStreamOpener {
input_tx: rtrb::Producer<f32>,
sample_rate: u32,
channels: u32,
}
impl InputStreamOpener {
/// Open and start the input stream with the given buffer size.
///
/// Uses the same `buffer_size` as the output stream so ALSA wakes up at
/// the same rate (~187/s at 256 frames) rather than the ~750/s it defaults
/// to with 64-frame buffers.
pub fn open(mut self, buffer_size: u32) -> Result<cpal::Stream, String> {
let host = cpal::default_host();
let device = host.default_input_device()
.ok_or("No input device available")?;
let default_cfg = device.default_input_config()
.map_err(|e| e.to_string())?;
let mut cfg: cpal::StreamConfig = default_cfg.into();
if !cfg!(target_os = "windows") {
cfg.buffer_size = cpal::BufferSize::Fixed(buffer_size);
}
let in_rate = cfg.sample_rate;
let in_ch = cfg.channels as u32;
let out_rate = self.sample_rate;
let out_ch = self.channels;
let needs_resample = in_rate != out_rate || in_ch != out_ch;
if needs_resample {
eprintln!("[AUDIO] Input: {}Hz {}ch → resampling to {}Hz {}ch",
in_rate, in_ch, out_rate, out_ch);
}
let stream = device.build_input_stream(
&cfg,
move |data: &[f32], _: &cpal::InputCallbackInfo| {
if !needs_resample {
for &s in data { let _ = self.input_tx.push(s); }
} else {
let ic = in_ch as usize;
let oc = out_ch as usize;
let ratio = out_rate as f64 / in_rate as f64;
let in_frames = data.len() / ic;
let out_frames = (in_frames as f64 * ratio) as usize;
for i in 0..out_frames {
let src = i as f64 / ratio;
let si = src as usize;
let f = (src - si as f64) as f32;
for ch in 0..oc {
let ich = ch.min(ic - 1);
let s0 = data.get(si * ic + ich).copied().unwrap_or(0.0);
let s1 = data.get((si + 1) * ic + ich).copied().unwrap_or(s0);
let _ = self.input_tx.push(s0 + f * (s1 - s0));
}
}
}
},
|err| eprintln!("Input stream error: {err}"),
None,
).map_err(|e| format!("Failed to build input stream: {e}"))?;
stream.play().map_err(|e| e.to_string())?;
Ok(stream)
}
}
+332
View File
@@ -0,0 +1,332 @@
//! TempoMap — beats ↔ seconds conversion with variable tempo support.
//!
//! Positions are stored in **beats** throughout the project; `TempoMap` converts
//! between beats and seconds at render / scheduling time.
//!
//! # Interpolation
//! Each `TempoEntry` has an `interpolation` field that controls how the BPM
//! changes between that entry and the next:
//! - `Step`: BPM is constant from this entry's beat until the next entry. Instant change.
//! - `Linear`: BPM linearly interpolates from this entry's BPM to the next entry's BPM
//! over the beat range. The seconds calculation uses the exact integral:
//! `Δt = (60 / slope) * ln(bpm_end / bpm_start)` where slope = (bpm_end - bpm_start) / span_beats.
//!
//! # Format
//! `entries` is a sorted `Vec<TempoEntry>` where the first entry must always
//! have `beat == 0.0`.
//!
//! # Sequential-access optimisation
//! An `AtomicUsize` caches the index of the last segment visited by
//! `beats_to_seconds`. When calls are in ascending order (the common case when
//! walking events in order) the scan starts from the cached index instead of
//! the beginning, giving amortised O(1) behaviour.
use serde::{Deserialize, Serialize};
use std::sync::atomic::{AtomicUsize, Ordering};
use crate::time::{Beats, Seconds};
/// How the BPM transitions from one `TempoEntry` to the next.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Default)]
pub enum TempoInterpolation {
/// BPM stays constant from this entry's beat until the next entry (instant change).
#[default]
Step,
/// BPM linearly interpolates from this entry's BPM to the next entry's BPM
/// over the beat span between the two entries.
Linear,
}
/// A single tempo segment: from `beat` onwards the tempo changes according to `interpolation`.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TempoEntry {
/// Start of this tempo segment in beats (quarter-note beats).
pub beat: f64,
/// Tempo at the start of this segment in beats per minute.
pub bpm: f64,
/// Cumulative seconds elapsed at the start of this segment.
/// **Derived** — not serialised; call [`TempoMap::rebuild_seconds`] after any
/// mutation or after deserialization.
#[serde(skip, default)]
pub seconds: f64,
/// How the BPM transitions from this entry to the next.
#[serde(default)]
pub interpolation: TempoInterpolation,
}
/// A piecewise tempo map used to convert between beats and seconds.
#[derive(Debug, Serialize, Deserialize)]
pub struct TempoMap {
/// Sorted list of tempo segments. Must always have at least one entry at beat 0.
pub entries: Vec<TempoEntry>,
/// Sequential-access cache: index of the last segment used by `beats_to_seconds`.
#[serde(skip, default)]
last_index: AtomicUsize,
}
impl Clone for TempoMap {
fn clone(&self) -> Self {
Self {
entries: self.entries.clone(),
last_index: AtomicUsize::new(self.last_index.load(Ordering::Relaxed)),
}
}
}
impl Default for TempoMap {
fn default() -> Self {
Self::constant(120.0)
}
}
// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------
/// Seconds elapsed traversing `span_beats` starting at `bpm_start`.
/// If `bpm_end` is `Some` (linear segment) and differs from `bpm_start`,
/// uses the exact logarithmic integral.
#[inline]
fn segment_duration(span_beats: f64, bpm_start: f64, bpm_end: Option<f64>) -> f64 {
match bpm_end {
None => span_beats * 60.0 / bpm_start,
Some(b1) if (b1 - bpm_start).abs() < 1e-9 => span_beats * 60.0 / bpm_start,
Some(b1) => {
// Linear BPM: BPM(b) = bpm_start + slope * (b - b_start)
// Δt = ∫₀^span 60 / BPM(b) db = (60/slope) * ln(b1/bpm_start)
let slope = (b1 - bpm_start) / span_beats;
(60.0 / slope) * (b1 / bpm_start).ln()
}
}
}
/// Beats elapsed given `delta_seconds` starting at `bpm_start`.
/// If `bpm_end` is `Some` (linear segment) and differs from `bpm_start`,
/// uses the exact exponential inverse.
#[inline]
fn segment_beats(delta_seconds: f64, span_beats: f64, bpm_start: f64, bpm_end: Option<f64>) -> f64 {
match bpm_end {
None => delta_seconds * bpm_start / 60.0,
Some(b1) if (b1 - bpm_start).abs() < 1e-9 => delta_seconds * bpm_start / 60.0,
Some(b1) => {
// Inverse of the logarithmic integral:
// b = b_start + (bpm_start / slope) * (exp(delta_t * slope / 60) - 1)
let slope = (b1 - bpm_start) / span_beats;
(bpm_start / slope) * ((delta_seconds * slope / 60.0).exp() - 1.0)
}
}
}
impl TempoMap {
/// Create a constant-tempo map.
pub fn constant(bpm: f64) -> Self {
Self {
entries: vec![TempoEntry { beat: 0.0, bpm, seconds: 0.0, interpolation: TempoInterpolation::Step }],
last_index: AtomicUsize::new(0),
}
}
/// Rebuild the `seconds` field on every entry from scratch.
/// **Must be called** after any mutation (add/remove/reorder entry) and
/// after deserialization.
pub fn rebuild_seconds(&mut self) {
let mut cumulative = 0.0_f64;
let n = self.entries.len();
for i in 0..n {
self.entries[i].seconds = cumulative;
if i + 1 < n {
let span = self.entries[i + 1].beat - self.entries[i].beat;
let bpm_end = if self.entries[i].interpolation == TempoInterpolation::Linear {
Some(self.entries[i + 1].bpm)
} else {
None
};
cumulative += segment_duration(span, self.entries[i].bpm, bpm_end);
}
}
self.last_index.store(0, Ordering::Relaxed);
}
/// Return the instantaneous BPM active at `beat`.
/// For linear segments, returns the interpolated value at that beat.
pub fn bpm_at(&self, beat: Beats) -> f64 {
let n = self.entries.len();
let idx = self.entries.partition_point(|e| e.beat <= beat.0).saturating_sub(1);
let idx = idx.min(n - 1);
let entry = &self.entries[idx];
if entry.interpolation == TempoInterpolation::Linear && idx + 1 < n {
let next = &self.entries[idx + 1];
let t = (beat.0 - entry.beat) / (next.beat - entry.beat);
entry.bpm + (next.bpm - entry.bpm) * t
} else {
entry.bpm
}
}
/// Convert beats to seconds using the tempo map.
///
/// Uses the sequential cache: if `beat` is at or after the last cached
/// segment, the scan starts there instead of from the beginning.
pub fn beats_to_seconds(&self, beat: Beats) -> Seconds {
Seconds(self.transform(beat.0))
}
/// Convert seconds to beats using binary search on the cached `seconds` offsets.
pub fn seconds_to_beats(&self, seconds: Seconds) -> Beats {
Beats(self.inverse_transform(seconds.0))
}
/// Global BPM — the BPM of the first entry (at beat 0).
pub fn global_bpm(&self) -> f64 {
self.entries[0].bpm
}
/// Set the global BPM (first entry). Rebuilds seconds.
pub fn set_global_bpm(&mut self, bpm: f64) {
self.entries[0].bpm = bpm;
self.rebuild_seconds();
}
/// Convert local beats to parent time units (raw `f64`).
///
/// At the root level the result is absolute seconds. Inside a nested
/// group the result is the *parent group's* beats.
pub fn transform(&self, beat: f64) -> f64 {
if beat <= 0.0 {
return 0.0;
}
let n = self.entries.len();
let cached = self.last_index.load(Ordering::Relaxed).min(n.saturating_sub(1));
let start = if beat >= self.entries[cached].beat { cached } else { 0 };
let mut idx = start;
while idx + 1 < n && self.entries[idx + 1].beat <= beat {
idx += 1;
}
self.last_index.store(idx, Ordering::Relaxed);
let entry = &self.entries[idx];
let beat_in_seg = beat - entry.beat;
if entry.interpolation == TempoInterpolation::Linear && idx + 1 < n {
let next = &self.entries[idx + 1];
let span = next.beat - entry.beat;
entry.seconds + segment_duration(beat_in_seg, entry.bpm, Some(entry.bpm + (next.bpm - entry.bpm) * beat_in_seg / span))
} else {
entry.seconds + beat_in_seg * 60.0 / entry.bpm
}
}
/// Inverse of [`transform`]: convert parent time units back to local beats.
pub fn inverse_transform(&self, parent_time: f64) -> f64 {
if parent_time <= 0.0 {
return 0.0;
}
let n = self.entries.len();
let idx = self.entries.partition_point(|e| e.seconds <= parent_time).saturating_sub(1);
let idx = idx.min(n - 1);
let entry = &self.entries[idx];
let delta_t = parent_time - entry.seconds;
if entry.interpolation == TempoInterpolation::Linear && idx + 1 < n {
let next = &self.entries[idx + 1];
let span = next.beat - entry.beat;
entry.beat + segment_beats(delta_t, span, entry.bpm, Some(next.bpm))
} else {
entry.beat + delta_t * entry.bpm / 60.0
}
}
/// Build a `TempoMap` from a list of `(beat, bpm)` keyframes (step interpolation).
/// Always inserts a beat-0 entry using the first keyframe's BPM (or 120.0 if empty).
pub fn from_keyframes(keyframes: &[(f64, f64)]) -> Self {
if keyframes.is_empty() {
return Self::constant(120.0);
}
let mut entries: Vec<TempoEntry> = keyframes
.iter()
.map(|&(beat, bpm)| TempoEntry { beat, bpm, seconds: 0.0, interpolation: TempoInterpolation::Step })
.collect();
entries.sort_by(|a, b| a.beat.partial_cmp(&b.beat).unwrap());
if entries[0].beat > 0.0 {
entries.insert(0, TempoEntry { beat: 0.0, bpm: entries[0].bpm, seconds: 0.0, interpolation: TempoInterpolation::Step });
}
let mut map = Self { entries, last_index: AtomicUsize::new(0) };
map.rebuild_seconds();
map
}
}
/// Convert local beats through a stack of tempo maps to absolute seconds.
pub fn beats_to_seconds_stack(beat: f64, stack: &[&TempoMap]) -> f64 {
let mut t = beat;
for tm in stack.iter().rev() {
t = tm.transform(t);
}
t
}
/// Inverse of [`beats_to_seconds_stack`]: absolute seconds → local beats.
pub fn seconds_to_beats_stack(seconds: f64, stack: &[&TempoMap]) -> f64 {
let mut t = seconds;
for tm in stack.iter() {
t = tm.inverse_transform(t);
}
t
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn constant_bpm_round_trip() {
let m = TempoMap::constant(120.0);
assert!((m.beats_to_seconds(Beats(2.0)).0 - 1.0).abs() < 1e-9);
assert!((m.seconds_to_beats(Seconds(1.0)).0 - 2.0).abs() < 1e-9);
}
#[test]
fn variable_tempo_step() {
let m = TempoMap::from_keyframes(&[(0.0, 120.0), (4.0, 60.0)]);
// Beat 0-4: 120 BPM → 4 beats = 2 seconds
assert!((m.beats_to_seconds(Beats(4.0)).0 - 2.0).abs() < 1e-9, "got {}", m.beats_to_seconds(Beats(4.0)).0);
// Beat 4-5: 60 BPM → 1 beat = 1 second
assert!((m.beats_to_seconds(Beats(5.0)).0 - 3.0).abs() < 1e-9);
assert!((m.seconds_to_beats(Seconds(3.0)).0 - 5.0).abs() < 1e-9);
}
#[test]
fn linear_interpolation_round_trip() {
// 120→240 BPM over 4 beats: slope = (240-120)/4 = 30 BPM/beat
// Δt = (60/30) * ln(240/120) = 2 * ln(2) ≈ 1.386s for beats 0-4
let mut m = TempoMap::constant(120.0);
m.entries.push(TempoEntry { beat: 4.0, bpm: 240.0, seconds: 0.0, interpolation: TempoInterpolation::Step });
m.entries[0].interpolation = TempoInterpolation::Linear;
m.rebuild_seconds();
let expected = 2.0 * std::f64::consts::LN_2;
let got = m.beats_to_seconds(Beats(4.0)).0;
assert!((got - expected).abs() < 1e-9, "got {got}, expected {expected}");
// Round-trip
let beats_back = m.seconds_to_beats(Seconds(expected)).0;
assert!((beats_back - 4.0).abs() < 1e-9, "round-trip got {beats_back}");
}
#[test]
fn stack_composition() {
let root = TempoMap::constant(120.0);
let group = TempoMap::constant(60.0);
let stack: Vec<&TempoMap> = vec![&root, &group];
let secs = beats_to_seconds_stack(2.0, &stack);
assert!((secs - 1.0).abs() < 1e-9, "got {secs}");
let beats = seconds_to_beats_stack(1.0, &stack);
assert!((beats - 2.0).abs() < 1e-9, "got {beats}");
}
#[test]
fn sequential_cache() {
let m = TempoMap::constant(120.0);
for i in 0..10 {
let secs = m.beats_to_seconds(Beats(i as f64));
assert!((secs.0 - i as f64 * 0.5).abs() < 1e-9);
}
}
}
+169
View File
@@ -0,0 +1,169 @@
/// Strongly-typed time units to prevent accidental beats/seconds confusion.
///
/// Convert between the two using `TempoMap::beats_to_seconds` / `TempoMap::seconds_to_beats`.
/// All internal scheduling and clip positions use `Beats`; only audio rendering
/// (sample offsets, file seeks) uses `Seconds`.
use serde::{Deserialize, Serialize};
use std::ops::{Add, AddAssign, Div, Mul, Neg, Rem, Sub, SubAssign};
/// A time position or duration expressed in **beats** (quarter-note beats).
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Default, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Beats(pub f64);
/// A time position or duration expressed in **seconds**.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Default, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Seconds(pub f64);
/// A time *inside a clip's own content*, in whatever unit that clip measures content in.
///
/// Clip content time is domain-polymorphic: SECONDS for sampled audio, video and vector, but BEATS
/// for MIDI (musical, so it survives tempo changes). `ClipInstance::trim_start`/`trim_end` are
/// content times, and storing them as bare `f64`s is what let a seconds delta get added to a MIDI
/// clip's beats trim — splitting a MIDI clip at beat 4 landed at beat 2 at 120 BPM.
///
/// This type is deliberately a **dead end**: it has no `.to_seconds()`, no `.to_beats()`, and no
/// arithmetic with `Seconds` or `Beats`. Content times can be compared and combined with each other
/// (that's domain-safe — both operands are in the same clip's domain), but the only way to get a
/// real timeline duration out is to resolve it against the clip that knows the domain, via
/// `AudioClip::resolve_content_time` / `Document::resolve_content_time`. So a passthrough costs
/// nothing, and mixing domains won't compile.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Default, Serialize, Deserialize)]
#[serde(transparent)]
pub struct ContentTime(pub f64);
impl ContentTime {
pub const ZERO: Self = Self(0.0);
pub fn max(self, other: Self) -> Self { Self(self.0.max(other.0)) }
pub fn min(self, other: Self) -> Self { Self(self.0.min(other.0)) }
/// The raw magnitude, with the domain discarded.
///
/// Only for code that is *already* working in this clip's content domain (trim arithmetic,
/// serialization, drawing a waveform whose x-axis is the clip's own content). If you are about
/// to combine this with a timeline position, resolve it against the clip instead.
pub fn raw(self) -> f64 { self.0 }
}
impl Add for ContentTime {
type Output = Self;
fn add(self, rhs: Self) -> Self { Self(self.0 + rhs.0) }
}
impl Sub for ContentTime {
type Output = Self;
fn sub(self, rhs: Self) -> Self { Self(self.0 - rhs.0) }
}
impl Rem for ContentTime {
type Output = Self;
fn rem(self, rhs: Self) -> Self { Self(self.0 % rhs.0) }
}
impl Beats {
pub const ZERO: Self = Self(0.0);
pub fn max(self, other: Self) -> Self { Self(self.0.max(other.0)) }
pub fn min(self, other: Self) -> Self { Self(self.0.min(other.0)) }
pub fn abs(self) -> Self { Self(self.0.abs()) }
pub fn ceil(self) -> Self { Self(self.0.ceil()) }
pub fn floor(self) -> Self { Self(self.0.floor()) }
pub fn beats_to_f64(self) -> f64 { self.0 }
}
impl Seconds {
pub const ZERO: Self = Self(0.0);
pub fn max(self, other: Self) -> Self { Self(self.0.max(other.0)) }
pub fn min(self, other: Self) -> Self { Self(self.0.min(other.0)) }
pub fn abs(self) -> Self { Self(self.0.abs()) }
pub fn seconds_to_f64(self) -> f64 { self.0 }
}
// --- Beats arithmetic ---
impl Add for Beats {
type Output = Self;
fn add(self, rhs: Self) -> Self { Self(self.0 + rhs.0) }
}
impl Sub for Beats {
type Output = Self;
fn sub(self, rhs: Self) -> Self { Self(self.0 - rhs.0) }
}
impl Mul<f64> for Beats {
type Output = Self;
fn mul(self, rhs: f64) -> Self { Self(self.0 * rhs) }
}
impl Div<f64> for Beats {
type Output = Self;
fn div(self, rhs: f64) -> Self { Self(self.0 / rhs) }
}
/// Beats / Beats = dimensionless ratio (f64)
impl Div<Beats> for Beats {
type Output = f64;
fn div(self, rhs: Beats) -> f64 { self.0 / rhs.0 }
}
impl Rem for Beats {
type Output = Self;
fn rem(self, rhs: Self) -> Self { Self(self.0 % rhs.0) }
}
impl Neg for Beats {
type Output = Self;
fn neg(self) -> Self { Self(-self.0) }
}
impl AddAssign for Beats {
fn add_assign(&mut self, rhs: Self) { self.0 += rhs.0; }
}
impl SubAssign for Beats {
fn sub_assign(&mut self, rhs: Self) { self.0 -= rhs.0; }
}
// --- Seconds arithmetic ---
impl Add for Seconds {
type Output = Self;
fn add(self, rhs: Self) -> Self { Self(self.0 + rhs.0) }
}
impl Sub for Seconds {
type Output = Self;
fn sub(self, rhs: Self) -> Self { Self(self.0 - rhs.0) }
}
impl Mul<f64> for Seconds {
type Output = Self;
fn mul(self, rhs: f64) -> Self { Self(self.0 * rhs) }
}
impl Div<f64> for Seconds {
type Output = Self;
fn div(self, rhs: f64) -> Self { Self(self.0 / rhs) }
}
/// Seconds / Seconds = dimensionless ratio (f64)
impl Div<Seconds> for Seconds {
type Output = f64;
fn div(self, rhs: Seconds) -> f64 { self.0 / rhs.0 }
}
impl Rem for Seconds {
type Output = Self;
fn rem(self, rhs: Self) -> Self { Self(self.0 % rhs.0) }
}
impl Neg for Seconds {
type Output = Self;
fn neg(self) -> Self { Self(-self.0) }
}
impl AddAssign for Seconds {
fn add_assign(&mut self, rhs: Self) { self.0 += rhs.0; }
}
impl SubAssign for Seconds {
fn sub_assign(&mut self, rhs: Self) { self.0 -= rhs.0; }
}
impl std::fmt::Display for Beats {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl std::fmt::Display for Seconds {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
+6 -6
View File
@@ -556,7 +556,7 @@ pub fn run_tui(
while let Ok(event) = rx.pop() {
match event {
AudioEvent::PlaybackPosition(pos) => {
app.update_playback_position(pos);
app.update_playback_position(pos.seconds_to_f64());
}
AudioEvent::PlaybackStopped => {
app.set_playing(false);
@@ -790,7 +790,7 @@ fn execute_command(
return Err("Usage: seek <seconds>".to_string());
}
let pos: f64 = parts[1].parse().map_err(|_| "Invalid position")?;
controller.seek(pos);
controller.seek(crate::Seconds(pos));
app.set_status(format!("Seeked to {:.2}s", pos));
}
"track" => {
@@ -830,7 +830,7 @@ fn execute_command(
app.next_clip_id += 1;
app.add_clip(track_id, clip_id, start_time, duration, format!("Clip {}", clip_id), Vec::new());
controller.create_midi_clip(track_id, start_time, duration);
controller.create_midi_clip(track_id, crate::Beats(start_time), crate::Beats(duration));
app.set_status(format!("Created MIDI clip on track {} at {:.2}s for {:.2}s", track_id, start_time, duration));
}
"loadmidi" => {
@@ -859,7 +859,7 @@ fn execute_command(
for event in &midi_clip.events {
let status = event.status & 0xF0;
let time_seconds = event.timestamp as f64 / sample_rate;
let time_seconds = event.timestamp.beats_to_f64() / sample_rate;
match status {
0x90 if event.data2 > 0 => {
@@ -878,11 +878,11 @@ fn execute_command(
}
// Add to local UI state with note data
app.add_clip(track_id, clip_id, start_time, duration, file_path.to_string(), notes);
app.add_clip(track_id, clip_id, start_time, duration.beats_to_f64(), file_path.to_string(), notes);
app.next_clip_id += 1;
// Send to audio engine with the start_time (clip content is separate from timeline position)
controller.add_loaded_midi_clip(track_id, midi_clip, start_time);
controller.add_loaded_midi_clip(track_id, midi_clip, crate::Beats(start_time));
app.set_status(format!("Loaded {} ({} events, {:.2}s) to track {} at {:.2}s",
file_path, event_count, duration, track_id, start_time));
@@ -0,0 +1,89 @@
//! Integration test for `CompressedReader::open_source` — decoding a streaming
//! audio source from an in-memory byte stream (the packed-in-container path)
//! rather than a filesystem path. Proves the `MediaByteSource` adapter feeds
//! Symphonia correctly (probe + decode + seekable byte length).
use std::io::{Cursor, Read, Seek, SeekFrom};
use daw_backend::audio::disk_reader::{CompressedReader, MediaByteSource};
/// A `MediaByteSource` over an in-memory buffer (stands in for core's BlobReader).
struct VecSource(Cursor<Vec<u8>>);
impl Read for VecSource {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
self.0.read(buf)
}
}
impl Seek for VecSource {
fn seek(&mut self, pos: SeekFrom) -> std::io::Result<u64> {
self.0.seek(pos)
}
}
impl MediaByteSource for VecSource {
fn byte_len(&self) -> u64 {
self.0.get_ref().len() as u64
}
}
/// Build a minimal PCM16 mono WAV byte buffer holding `frames` samples of a ramp.
fn make_wav(sample_rate: u32, frames: u32) -> Vec<u8> {
let channels: u16 = 1;
let bits: u16 = 16;
let block_align: u16 = channels * bits / 8;
let byte_rate: u32 = sample_rate * block_align as u32;
let data_len: u32 = frames * block_align as u32;
let mut v = Vec::new();
v.extend_from_slice(b"RIFF");
v.extend_from_slice(&(36 + data_len).to_le_bytes());
v.extend_from_slice(b"WAVE");
v.extend_from_slice(b"fmt ");
v.extend_from_slice(&16u32.to_le_bytes());
v.extend_from_slice(&1u16.to_le_bytes()); // PCM
v.extend_from_slice(&channels.to_le_bytes());
v.extend_from_slice(&sample_rate.to_le_bytes());
v.extend_from_slice(&byte_rate.to_le_bytes());
v.extend_from_slice(&block_align.to_le_bytes());
v.extend_from_slice(&bits.to_le_bytes());
v.extend_from_slice(b"data");
v.extend_from_slice(&data_len.to_le_bytes());
for i in 0..frames {
// A ramp from -16000..16000 so values are recognizable.
let s = (((i % 1000) as i32 - 500) * 32) as i16;
v.extend_from_slice(&s.to_le_bytes());
}
v
}
#[test]
fn open_source_decodes_in_memory_wav() {
let sample_rate = 8000;
let frames = 4096;
let bytes = make_wav(sample_rate, frames);
let src = Box::new(VecSource(Cursor::new(bytes)));
let mut reader = CompressedReader::open_source(src, Some("wav"))
.expect("open_source should probe the in-memory WAV");
assert_eq!(reader.sample_rate(), sample_rate);
assert_eq!(reader.channels(), 1);
// Decode the whole stream and count emitted frames.
let mut buf = Vec::new();
let mut decoded = 0usize;
loop {
let n = reader.decode_next(&mut buf).expect("decode_next");
if n == 0 {
break;
}
decoded += n;
}
// Should recover (approximately) all frames — codec frame counts can round.
assert!(
(decoded as i64 - frames as i64).abs() < 64,
"decoded {} vs expected {}",
decoded,
frames
);
}
+319
View File
@@ -0,0 +1,319 @@
//! Integration tests for `VideoAudioReader` (FFmpeg streaming audio source).
//!
//! These build the daw-backend lib in normal mode, so they're independent of
//! the crate's pre-existing broken `#[cfg(test)]` unit tests (automation.rs).
//! They synthesize a mono 32-bit-float WAV whose sample `i` has value `i/n`, so
//! a decoded sample's value identifies its frame index — letting us assert both
//! in-order decoding and **sample-accurate seeking** (the property video audio
//! needs to stay synced with other clips).
use daw_backend::audio::disk_reader::{
build_waveform_pyramid, CompressedReader, SourceKind, VideoAudioReader,
};
use std::io::Write;
use std::path::Path;
fn write_ramp_wav(path: &Path, n: u32, sample_rate: u32) {
let channels = 1u16;
let bytes_per_sample = 4u32;
let data_size = n * bytes_per_sample;
let mut buf: Vec<u8> = Vec::with_capacity(44 + data_size as usize);
buf.extend_from_slice(b"RIFF");
buf.extend_from_slice(&(36 + data_size).to_le_bytes());
buf.extend_from_slice(b"WAVE");
buf.extend_from_slice(b"fmt ");
buf.extend_from_slice(&16u32.to_le_bytes());
buf.extend_from_slice(&3u16.to_le_bytes()); // IEEE float
buf.extend_from_slice(&channels.to_le_bytes());
buf.extend_from_slice(&sample_rate.to_le_bytes());
buf.extend_from_slice(&(sample_rate * channels as u32 * bytes_per_sample).to_le_bytes());
buf.extend_from_slice(&((channels as u32 * bytes_per_sample) as u16).to_le_bytes());
buf.extend_from_slice(&32u16.to_le_bytes());
buf.extend_from_slice(b"data");
buf.extend_from_slice(&data_size.to_le_bytes());
for i in 0..n {
buf.extend_from_slice(&((i as f32) / (n as f32)).to_le_bytes());
}
let mut f = std::fs::File::create(path).unwrap();
f.write_all(&buf).unwrap();
}
/// Stereo ramp: frame `i` has left = `i/n`, right = `0.5 - i/n` (distinct per
/// channel), interleaved `[L0,R0,L1,R1,…]`. Exercises the channels>1 path.
fn write_stereo_ramp_wav(path: &Path, n: u32, sample_rate: u32) {
let channels = 2u16;
let bytes_per_sample = 4u32;
let data_size = n * channels as u32 * bytes_per_sample;
let mut buf: Vec<u8> = Vec::with_capacity(44 + data_size as usize);
buf.extend_from_slice(b"RIFF");
buf.extend_from_slice(&(36 + data_size).to_le_bytes());
buf.extend_from_slice(b"WAVE");
buf.extend_from_slice(b"fmt ");
buf.extend_from_slice(&16u32.to_le_bytes());
buf.extend_from_slice(&3u16.to_le_bytes()); // IEEE float
buf.extend_from_slice(&channels.to_le_bytes());
buf.extend_from_slice(&sample_rate.to_le_bytes());
buf.extend_from_slice(&(sample_rate * channels as u32 * bytes_per_sample).to_le_bytes());
buf.extend_from_slice(&((channels as u32 * bytes_per_sample) as u16).to_le_bytes());
buf.extend_from_slice(&32u16.to_le_bytes());
buf.extend_from_slice(b"data");
buf.extend_from_slice(&data_size.to_le_bytes());
for i in 0..n {
let l = i as f32 / n as f32;
let r = 0.5 - i as f32 / n as f32;
buf.extend_from_slice(&l.to_le_bytes());
buf.extend_from_slice(&r.to_le_bytes());
}
let mut f = std::fs::File::create(path).unwrap();
f.write_all(&buf).unwrap();
}
fn temp_path(tag: &str) -> std::path::PathBuf {
let mut p = std::env::temp_dir();
p.push(format!("lb_videoaudio_test_{}_{}.wav", std::process::id(), tag));
p
}
#[test]
fn decodes_samples_in_order() {
let n = 4000u32;
let sr = 8000u32;
let path = temp_path("seq");
write_ramp_wav(&path, n, sr);
let mut reader = VideoAudioReader::open(&path).unwrap();
assert_eq!(reader.channels(), 1);
assert_eq!(reader.sample_rate(), sr);
// Probe estimate (used by add_video_audio_sync) should be ~n frames.
let tf = reader.total_frames() as f64;
assert!(
(tf - n as f64).abs() < n as f64 * 0.1,
"total_frames {} not ~{}",
tf, n
);
let mut all = Vec::new();
let mut buf = Vec::new();
loop {
let frames = reader.decode_next(&mut buf).unwrap();
if frames == 0 {
break;
}
all.extend_from_slice(&buf);
}
// Allow a couple of priming/flush samples of slack at the very end.
assert!(all.len() + 4 >= n as usize, "decoded too few samples: {}", all.len());
for (i, &v) in all.iter().enumerate().take(n as usize) {
let expected = i as f32 / n as f32;
assert!((v - expected).abs() < 1e-3, "sample {} = {}, expected {}", i, v, expected);
}
let _ = std::fs::remove_file(&path);
}
/// CompressedReader (symphonia) must seek **sample-accurately** too, so compressed
/// audio stays frame-synced with video audio. Symphonia decodes WAV via the same
/// path; its coarse seek lands on packet boundaries, exercising the decode-discard.
#[test]
fn compressed_reader_seek_is_sample_accurate() {
let n = 4000u32;
let sr = 8000u32;
let path = temp_path("comp_seek");
write_ramp_wav(&path, n, sr);
let mut reader = CompressedReader::open(&path).unwrap();
assert_eq!(reader.channels(), 1);
assert_eq!(reader.sample_rate(), sr);
for &target in &[2000u64, 137, 3500, 0] {
let actual = reader.seek(target).unwrap();
assert_eq!(actual, target, "seek should report the exact target");
let mut buf = Vec::new();
let mut frames = 0;
for _ in 0..128 {
frames = reader.decode_next(&mut buf).unwrap();
if frames > 0 {
break;
}
}
assert!(frames > 0, "no samples after seek to {}", target);
let expected = target as f32 / n as f32;
assert!(
(buf[0] - expected).abs() < 1e-3,
"compressed seek to {}: first sample = {}, expected {}",
target, buf[0], expected
);
}
let _ = std::fs::remove_file(&path);
}
/// The decode→pyramid bridge should produce an envelope matching the signal,
/// through both reader backends (symphonia + ffmpeg), with bounded memory.
#[test]
fn waveform_pyramid_from_decode_matches_signal() {
let n = 5000u32;
let sr = 8000u32;
let path = temp_path("pyr");
write_ramp_wav(&path, n, sr); // ramp 0 .. (n-1)/n, all positive
for kind in [SourceKind::CompressedAudio, SourceKind::VideoAudio] {
let p = build_waveform_pyramid(&path, kind, 256).unwrap();
assert_eq!(p.channels, 1);
assert_eq!(p.root().len(), 1, "{:?}: root should be one texel", kind);
let root = p.root()[0];
assert!(root.l_min.abs() < 1e-2, "{:?}: root min {} ~ 0", kind, root.l_min);
let expected_max = (n - 1) as f32 / n as f32;
assert!(
(root.l_max - expected_max).abs() < 1e-2,
"{:?}: root max {} ~ {}", kind, root.l_max, expected_max
);
// Frame count is approximate across decoders (priming/resampler overhead);
// the envelope above is the real check. Just confirm it's about right.
assert!((p.total_frames as i64 - n as i64).abs() < 128, "{:?}: frames {}", kind, p.total_frames);
}
let _ = std::fs::remove_file(&path);
}
#[test]
fn decodes_stereo_interleaved() {
let n = 2000u32;
let sr = 8000u32;
let path = temp_path("stereo");
write_stereo_ramp_wav(&path, n, sr);
let mut reader = VideoAudioReader::open(&path).unwrap();
assert_eq!(reader.channels(), 2);
let mut all = Vec::new();
let mut buf = Vec::new();
loop {
let frames = reader.decode_next(&mut buf).unwrap();
if frames == 0 {
break;
}
// Each decode_next returns whole interleaved frames.
assert_eq!(buf.len() % 2, 0, "stereo decode returned a partial frame");
all.extend_from_slice(&buf);
}
// Interleaved L/R, ~n frames.
assert!(all.len() + 8 >= (n * 2) as usize, "decoded too few samples: {}", all.len());
for i in 0..n as usize {
let l = all[2 * i];
let r = all[2 * i + 1];
assert!((l - i as f32 / n as f32).abs() < 1e-3, "L[{}]={} expected {}", i, l, i as f32 / n as f32);
assert!(
(r - (0.5 - i as f32 / n as f32)).abs() < 1e-3,
"R[{}]={} expected {}", i, r, 0.5 - i as f32 / n as f32
);
}
let _ = std::fs::remove_file(&path);
}
#[test]
fn seek_is_sample_accurate() {
let n = 4000u32;
let sr = 8000u32;
let path = temp_path("seek");
write_ramp_wav(&path, n, sr);
let mut reader = VideoAudioReader::open(&path).unwrap();
for &target in &[2000u64, 137, 3500, 0] {
let actual = reader.seek(target).unwrap();
assert_eq!(actual, target);
// Pull the first non-empty decode after the seek.
let mut buf = Vec::new();
let mut frames = 0;
for _ in 0..64 {
frames = reader.decode_next(&mut buf).unwrap();
if frames > 0 {
break;
}
}
assert!(frames > 0, "no samples after seek to {}", target);
let expected = target as f32 / n as f32;
assert!(
(buf[0] - expected).abs() < 1e-3,
"after seek to {}: first sample = {}, expected {}",
target,
buf[0],
expected
);
// And the next few advance in order.
for k in 0..frames.min(8) {
let exp = (target as usize + k) as f32 / n as f32;
assert!((buf[k] - exp).abs() < 1e-3, "seek {}+{}: {} vs {}", target, k, buf[k], exp);
}
}
let _ = std::fs::remove_file(&path);
}
// ── Stage 3: stream video-audio from a byte source (packed .beam blob) ──────────
/// A `MediaByteSource` over an in-memory buffer (stands in for a SQLite BlobReader).
struct VecSource(std::io::Cursor<Vec<u8>>, u64);
impl std::io::Read for VecSource {
fn read(&mut self, b: &mut [u8]) -> std::io::Result<usize> { self.0.read(b) }
}
impl std::io::Seek for VecSource {
fn seek(&mut self, p: std::io::SeekFrom) -> std::io::Result<u64> { self.0.seek(p) }
}
impl daw_backend::audio::disk_reader::MediaByteSource for VecSource {
fn byte_len(&self) -> u64 { self.1 }
}
fn ramp_wav_bytes(n: u32, sample_rate: u32) -> Vec<u8> {
let channels = 1u16;
let bps = 4u32;
let data_size = n * bps;
let mut buf = Vec::with_capacity(44 + data_size as usize);
buf.extend_from_slice(b"RIFF");
buf.extend_from_slice(&(36 + data_size).to_le_bytes());
buf.extend_from_slice(b"WAVE");
buf.extend_from_slice(b"fmt ");
buf.extend_from_slice(&16u32.to_le_bytes());
buf.extend_from_slice(&3u16.to_le_bytes()); // IEEE float
buf.extend_from_slice(&channels.to_le_bytes());
buf.extend_from_slice(&sample_rate.to_le_bytes());
buf.extend_from_slice(&(sample_rate * channels as u32 * bps).to_le_bytes());
buf.extend_from_slice(&((channels as u32 * bps) as u16).to_le_bytes());
buf.extend_from_slice(&32u16.to_le_bytes());
buf.extend_from_slice(b"data");
buf.extend_from_slice(&data_size.to_le_bytes());
for i in 0..n {
buf.extend_from_slice(&((i as f32) / (n as f32)).to_le_bytes());
}
buf
}
#[test]
fn video_audio_open_source_streams_from_bytes() {
let sr = 8000;
let n = 4000;
let bytes = ramp_wav_bytes(n, sr);
let len = bytes.len() as u64;
let src = Box::new(VecSource(std::io::Cursor::new(bytes), len));
// Open the audio track by streaming from the byte source (no file path).
let mut reader = VideoAudioReader::open_source(src, Some("wav")).unwrap();
assert_eq!(reader.channels(), 1);
assert_eq!(reader.sample_rate(), sr);
let mut all: Vec<f32> = Vec::new();
let mut buf: Vec<f32> = Vec::new();
loop {
let frames = reader.decode_next(&mut buf).unwrap();
if frames == 0 {
break;
}
all.extend_from_slice(&buf);
}
assert!(all.len() as u32 >= n - 4, "decoded most of the ramp: {} of {}", all.len(), n);
// The ramp rises monotonically; sample 0 ≈ 0.0 and the last is near 1.0.
assert!(all[0].abs() < 1e-3, "first sample ~0, got {}", all[0]);
assert!(*all.last().unwrap() > 0.9, "last sample ~1.0, got {}", all.last().unwrap());
}
+135
View File
@@ -0,0 +1,135 @@
//! Integration tests for the streaming waveform LOD pyramid builder.
//!
//! Convention B: `levels[0]` is the root (coarsest), `levels.last()` the floor
//! (finest). Tests use the `.root()` / `.floor()` accessors so they don't depend
//! on the raw index ordering.
use daw_backend::audio::waveform_pyramid::{Texel, WaveformPyramid, WaveformPyramidBuilder};
fn build_mono(samples: &[f32], floor: u32) -> WaveformPyramid {
let mut b = WaveformPyramidBuilder::new(1, floor);
b.push_interleaved(samples);
b.finish()
}
#[test]
fn floor_level_min_max_per_bucket() {
// 8 samples, floor 4 → two floor texels covering [0..4) and [4..8).
let s: Vec<f32> = (0..8).map(|i| i as f32).collect();
let p = build_mono(&s, 4);
assert_eq!(p.floor().len(), 2);
assert_eq!(p.floor()[0], Texel { l_min: 0.0, l_max: 3.0, r_min: 0.0, r_max: 3.0 });
assert_eq!(p.floor()[1], Texel { l_min: 4.0, l_max: 7.0, r_min: 4.0, r_max: 7.0 });
// Root reduces the two floor texels into the envelope [0..8).
assert_eq!(p.root().len(), 1);
assert_eq!(p.root()[0], Texel { l_min: 0.0, l_max: 7.0, r_min: 0.0, r_max: 7.0 });
}
#[test]
fn partial_trailing_bucket_is_flushed() {
// 6 samples, floor 4 → texels [0..4) and a ragged [4..6).
let s: Vec<f32> = (0..6).map(|i| i as f32).collect();
let p = build_mono(&s, 4);
assert_eq!(p.floor().len(), 2);
assert_eq!(p.floor()[1], Texel { l_min: 4.0, l_max: 5.0, r_min: 4.0, r_max: 5.0 });
assert_eq!(p.total_frames, 6);
}
#[test]
fn multi_level_envelope_matches_global_min_max() {
let s: Vec<f32> = (0..1000).map(|i| ((i as f32) * 0.01).sin()).collect();
let g_min = s.iter().cloned().fold(f32::INFINITY, f32::min);
let g_max = s.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
let p = build_mono(&s, 16);
assert_eq!(p.root().len(), 1);
assert!((p.root()[0].l_min - g_min).abs() < 1e-6);
assert!((p.root()[0].l_max - g_max).abs() < 1e-6);
// Every level's overall min/max equals the global (extremes are lossless).
for level in &p.levels {
let lmin = level.iter().map(|t| t.l_min).fold(f32::INFINITY, f32::min);
let lmax = level.iter().map(|t| t.l_max).fold(f32::NEG_INFINITY, f32::max);
assert!((lmin - g_min).abs() < 1e-6);
assert!((lmax - g_max).abs() < 1e-6);
}
}
#[test]
fn levels_are_root_first_and_get_finer() {
let s: Vec<f32> = (0..1000).map(|i| i as f32).collect();
let p = build_mono(&s, 16);
// Root first, floor last; strictly finer (more texels) as depth increases.
assert_eq!(p.root().len(), 1);
assert!(p.depth() >= 3);
for w in p.levels.windows(2) {
assert!(w[1].len() >= w[0].len(), "deeper level should be finer");
}
// Floor has ceil(1000/16) = 63 texels.
assert_eq!(p.floor().len(), 63);
}
#[test]
fn stereo_channels_tracked_separately() {
// L ramps up, R ramps down; interleaved.
let n = 64;
let mut s = Vec::new();
for i in 0..n {
s.push(i as f32); // L
s.push(-(i as f32)); // R
}
let mut b = WaveformPyramidBuilder::new(2, 16);
b.push_interleaved(&s);
let p = b.finish();
assert_eq!(p.root().len(), 1);
assert_eq!(p.root()[0].l_min, 0.0);
assert_eq!(p.root()[0].l_max, (n - 1) as f32);
assert_eq!(p.root()[0].r_min, -((n - 1) as f32));
assert_eq!(p.root()[0].r_max, 0.0);
}
#[test]
fn pyramid_size_is_bounded() {
let n = 100_000usize;
let s: Vec<f32> = (0..n).map(|i| (i % 7) as f32).collect();
let floor = 256u32;
let p = build_mono(&s, floor);
let total: usize = p.levels.iter().map(|l| l.len()).sum();
let floor_texels = (n as u32).div_ceil(floor) as usize;
// Geometric bound: < floor_texels * branch/(branch-1) + small per-level slack.
let bound = floor_texels * 4 / 3 + p.depth() + 2;
assert!(total <= bound, "pyramid too big: {} > {}", total, bound);
}
#[test]
fn bytes_round_trip() {
let s: Vec<f32> = (0..3333).map(|i| ((i as f32) * 0.013).sin()).collect();
let p = build_mono(&s, 64);
let bytes = p.to_bytes();
let q = WaveformPyramid::from_bytes(&bytes).unwrap();
assert_eq!(p.floor_samples_per_texel, q.floor_samples_per_texel);
assert_eq!(p.branch, q.branch);
assert_eq!(p.channels, q.channels);
assert_eq!(p.total_frames, q.total_frames);
assert_eq!(p.levels, q.levels);
// Truncated/garbage input is rejected, not panicking.
assert!(WaveformPyramid::from_bytes(&bytes[..bytes.len() - 4]).is_err());
assert!(WaveformPyramid::from_bytes(b"nope").is_err());
}
#[test]
fn pushing_in_arbitrary_chunks_matches() {
// The streaming builder must be agnostic to how samples are chunked.
let s: Vec<f32> = (0..5000).map(|i| ((i * 13) % 97) as f32 - 48.0).collect();
let whole = build_mono(&s, 32);
let mut b = WaveformPyramidBuilder::new(1, 32);
b.reserve_for_frames(5000);
for chunk in s.chunks(37) {
b.push_interleaved(chunk);
}
let chunked = b.finish();
assert_eq!(whole.depth(), chunked.depth());
for (a, c) in whole.levels.iter().zip(chunked.levels.iter()) {
assert_eq!(a, c);
}
}
+287
View File
@@ -0,0 +1,287 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "aho-corasick"
version = "1.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301"
dependencies = [
"memchr",
]
[[package]]
name = "bindgen"
version = "0.72.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895"
dependencies = [
"bitflags",
"cexpr",
"clang-sys",
"itertools",
"proc-macro2",
"quote",
"regex",
"rustc-hash",
"shlex 1.3.0",
"syn",
]
[[package]]
name = "bitflags"
version = "2.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8"
[[package]]
name = "cc"
version = "1.2.63"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "556e016178bb5662a08681bbe0f00f8e17631781a4dfc8c45e466e4b185ec27f"
dependencies = [
"find-msvc-tools",
"shlex 2.0.1",
]
[[package]]
name = "cexpr"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766"
dependencies = [
"nom",
]
[[package]]
name = "cfg-if"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
[[package]]
name = "clang-sys"
version = "1.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b023947811758c97c59bf9d1c188fd619ad4718dcaa767947df1cadb14f39f4"
dependencies = [
"glob",
"libc",
"libloading",
]
[[package]]
name = "either"
version = "1.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719"
[[package]]
name = "ffmpeg-blob-io"
version = "0.1.0"
dependencies = [
"ffmpeg-next",
"ffmpeg-sys-next",
"libc",
]
[[package]]
name = "ffmpeg-next"
version = "8.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d658424d233cbd993a972dd73a66ca733acd12a494c68995c9ac32ae1fe65b40"
dependencies = [
"bitflags",
"ffmpeg-sys-next",
"libc",
]
[[package]]
name = "ffmpeg-sys-next"
version = "8.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9bca20aa4ee774fe384c2490096c122b0b23cf524a9910add0686691003d797b"
dependencies = [
"bindgen",
"cc",
"libc",
"num_cpus",
"pkg-config",
"vcpkg",
]
[[package]]
name = "find-msvc-tools"
version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
[[package]]
name = "glob"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280"
[[package]]
name = "hermit-abi"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c"
[[package]]
name = "itertools"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"
dependencies = [
"either",
]
[[package]]
name = "libc"
version = "0.2.186"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
[[package]]
name = "libloading"
version = "0.8.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"
dependencies = [
"cfg-if",
"windows-link",
]
[[package]]
name = "memchr"
version = "2.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6b947ae49db0d222b1dbc6b113ce7248a3fc3a6ca21b696717bfc000ba4484d8"
[[package]]
name = "minimal-lexical"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
[[package]]
name = "nom"
version = "7.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
dependencies = [
"memchr",
"minimal-lexical",
]
[[package]]
name = "num_cpus"
version = "1.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b"
dependencies = [
"hermit-abi",
"libc",
]
[[package]]
name = "pkg-config"
version = "0.3.33"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e"
[[package]]
name = "proc-macro2"
version = "1.0.106"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.45"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924"
dependencies = [
"proc-macro2",
]
[[package]]
name = "regex"
version = "1.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "regex-automata"
version = "0.4.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.8.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a"
[[package]]
name = "rustc-hash"
version = "2.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe"
[[package]]
name = "shlex"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
[[package]]
name = "shlex"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
[[package]]
name = "syn"
version = "2.0.117"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "unicode-ident"
version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "vcpkg"
version = "0.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
+22
View File
@@ -0,0 +1,22 @@
# Standalone crate (own workspace root) — depended on by daw-backend and
# lightningbeam-core via relative path, like daw-backend itself.
[workspace]
[package]
name = "ffmpeg-blob-io"
version = "0.1.0"
edition = "2021"
description = "Custom AVIOContext-over-Read+Seek shim for ffmpeg-next: lets a demuxer stream from an arbitrary byte source (e.g. a SQLite blob) instead of a file path. Isolates the unsafe FFI + ffmpeg ABI coupling."
# ABI-PINNED. This crate dereferences raw AVFormatContext / AVIOContext fields
# (`pb`, `flags`, `buffer`, `opaque`) and wraps the result back into ffmpeg-next's
# `Input`, so it MUST link the exact same libavformat ABI as the rest of the
# workspace. The `=` pins match what lightningbeam-core / daw-backend resolve;
# bump all three together when upgrading ffmpeg.
[dependencies]
ffmpeg-next = "=8.0.0"
ffmpeg-sys-next = "=8.0.1"
libc = "0.2"
[dev-dependencies]
ffmpeg-next = "=8.0.0"
+240
View File
@@ -0,0 +1,240 @@
//! Stream a demuxer from an arbitrary `Read + Seek` byte source via a custom
//! FFmpeg `AVIOContext`.
//!
//! `ffmpeg-next`'s high-level API can only open inputs by filesystem path. This
//! crate builds an `AVFormatContext` whose I/O is backed by a Rust reader (e.g. a
//! SQLite `BlobReader`), then hands back a normal [`ffmpeg_next::format::context::Input`]
//! that the rest of the codebase decodes exactly as a file-backed input.
//!
//! All of the `unsafe` FFI and ffmpeg ABI coupling lives here, isolated behind the
//! safe [`BlobInput`] type. See `BEAM_FILE_FORMAT.md` / `STREAMING_TO_DISK_PLAN.md`.
//!
//! # Safety model
//! - The reader is boxed and leaked to FFmpeg as the AVIO `opaque` pointer; the
//! read/seek callbacks reconstitute it as `&mut`. It is never aliased — only the
//! owning [`BlobInput`] (on one thread) drives it.
//! - [`BlobInput`] is `Send` but **not** `Sync`: the typical reader (`BlobReader`)
//! owns a `!Sync` SQLite connection. Each decoder / seek-reopen / off-thread scan
//! must construct its **own** `BlobInput` from a **fresh** reader.
//! - `Drop` tears down in the one correct order (Input first, then the AVIO buffer +
//! context, then the reader) so there is no use-after-free, double-free, or leak.
use std::io::{Read, Seek, SeekFrom};
use std::os::raw::{c_char, c_int, c_void};
use std::ptr;
use ffmpeg_next::format::context::Input;
use ffmpeg_sys_next as sys;
/// A byte source FFmpeg can stream from. Blanket-implemented for any
/// `Read + Seek + Send` (e.g. `std::io::Cursor`, a SQLite `BlobReader`).
pub trait BlobSource: Read + Seek + Send {}
impl<T: Read + Seek + Send> BlobSource for T {}
// Stable FFmpeg ABI constants (avoid depending on whether bindgen exported the
// corresponding `#define`s). These are fixed across the libavformat 58–61 ABIs.
const AVSEEK_SIZE: c_int = 0x10000;
const AVSEEK_FORCE: c_int = 0x20000;
const AVFMT_FLAG_CUSTOM_IO: c_int = 0x0080;
/// Size of the AVIO read buffer handed to FFmpeg. FFmpeg may grow/replace it.
const IO_BUFFER_SIZE: usize = 32 * 1024;
/// A demuxer input streaming from a boxed `Read + Seek` source.
///
/// Deref to [`Input`] for the usual ffmpeg-next decode API.
pub struct BlobInput {
// Dropped FIRST in `Drop` (avformat_close_input). `Option` so we can drop it
// explicitly before freeing the AVIO resources it points at.
input: Option<Input>,
// The custom AVIOContext. With AVFMT_FLAG_CUSTOM_IO set, avformat_close_input
// does NOT free this — we own it. Its `opaque` field is the boxed reader.
avio: *mut sys::AVIOContext,
}
// The reader is `Send` and never aliased; we manage its lifetime manually.
unsafe impl Send for BlobInput {}
// Intentionally NOT `Sync`: see the module-level safety notes.
impl BlobInput {
/// Open a demuxer over `src`.
///
/// `format_hint` is an optional container short-name / extension (e.g. `"mp4"`,
/// `"mov"`, `"matroska"`) passed to `av_find_input_format` to skip probe
/// ambiguity; `None` lets FFmpeg probe from the stream.
pub fn open(src: Box<dyn BlobSource>, format_hint: Option<&str>) -> Result<Self, String> {
ffmpeg_next::init().map_err(|e| format!("ffmpeg init failed: {e}"))?;
unsafe {
// 1. IO buffer, allocated with FFmpeg's allocator (freed with av_freep).
let buffer = sys::av_malloc(IO_BUFFER_SIZE) as *mut u8;
if buffer.is_null() {
return Err("av_malloc failed for AVIO buffer".into());
}
// 2. Box the reader and leak it as the opaque pointer. Double-box so the
// raw pointer is thin (a `*mut dyn` would be a fat pointer).
let opaque = Box::into_raw(Box::new(src)) as *mut c_void;
// 3. AVIOContext over our callbacks (read-only: write_flag = 0).
let avio = sys::avio_alloc_context(
buffer,
IO_BUFFER_SIZE as c_int,
0,
opaque,
Some(read_cb),
None,
Some(seek_cb),
);
if avio.is_null() {
sys::av_free(buffer as *mut c_void);
drop(Box::from_raw(opaque as *mut Box<dyn BlobSource>));
return Err("avio_alloc_context failed".into());
}
// 4. Format context wired to the custom IO.
let mut fmt = sys::avformat_alloc_context();
if fmt.is_null() {
destroy_io(avio);
return Err("avformat_alloc_context failed".into());
}
(*fmt).pb = avio;
(*fmt).flags |= AVFMT_FLAG_CUSTOM_IO;
// 5. Optional format hint.
let hint_cstr = format_hint.and_then(|s| std::ffi::CString::new(s).ok());
let infmt: *const sys::AVInputFormat = match &hint_cstr {
Some(c) => sys::av_find_input_format(c.as_ptr() as *const c_char),
None => ptr::null(),
};
// 6. Open. On failure avformat_open_input frees `fmt` itself (and, with
// CUSTOM_IO, leaves our pb), so we still own avio+buffer+reader.
let ret = sys::avformat_open_input(&mut fmt, ptr::null(), infmt, ptr::null_mut());
if ret < 0 {
destroy_io(avio);
return Err(format!("avformat_open_input failed (error {ret})"));
}
// 7. Probe streams. On failure close the now-open input, then free IO.
let ret = sys::avformat_find_stream_info(fmt, ptr::null_mut());
if ret < 0 {
sys::avformat_close_input(&mut fmt);
destroy_io(avio);
return Err(format!("avformat_find_stream_info failed (error {ret})"));
}
// 8. Hand ownership of `fmt` to ffmpeg-next's Input (closes on drop).
let input = Input::wrap(fmt);
Ok(BlobInput { input: Some(input), avio })
}
}
/// The underlying demuxer input.
pub fn input(&self) -> &Input {
self.input.as_ref().expect("BlobInput input present until drop")
}
/// The underlying demuxer input, mutably (for `seek`, `packets`, …).
pub fn input_mut(&mut self) -> &mut Input {
self.input.as_mut().expect("BlobInput input present until drop")
}
}
impl std::ops::Deref for BlobInput {
type Target = Input;
fn deref(&self) -> &Input {
self.input()
}
}
impl std::ops::DerefMut for BlobInput {
fn deref_mut(&mut self) -> &mut Input {
self.input_mut()
}
}
impl Drop for BlobInput {
fn drop(&mut self) {
unsafe {
// 1. Drop the Input first: avformat_close_input. With CUSTOM_IO this does
// NOT touch self.avio or its buffer.
self.input = None;
// 2..4. Free the AVIO buffer + context and reclaim the boxed reader.
if !self.avio.is_null() {
destroy_io(self.avio);
self.avio = ptr::null_mut();
}
}
}
}
/// Free a standalone custom AVIOContext: its (possibly reallocated) buffer, the
/// boxed reader behind `opaque`, then the context itself — in that order. Only
/// call when the owning AVFormatContext has already been closed (or never opened).
unsafe fn destroy_io(avio: *mut sys::AVIOContext) {
if avio.is_null() {
return;
}
// Reclaim the reader box *before* freeing the context (we need `opaque`).
let opaque = (*avio).opaque;
// Free the current IO buffer (FFmpeg may have replaced the original).
sys::av_freep(&mut (*avio).buffer as *mut _ as *mut c_void);
// Free the AVIOContext struct (nulls the local).
let mut avio = avio;
sys::avio_context_free(&mut avio);
// Drop the reader last — no callback can fire now.
if !opaque.is_null() {
drop(Box::from_raw(opaque as *mut Box<dyn BlobSource>));
}
}
/// FFmpeg read callback: fill `buf` from the Rust reader. Returns bytes read,
/// `AVERROR_EOF` at end of stream, or a negative error.
unsafe extern "C" fn read_cb(opaque: *mut c_void, buf: *mut u8, buf_size: c_int) -> c_int {
if opaque.is_null() || buf.is_null() || buf_size <= 0 {
return sys::AVERROR_EOF;
}
let reader = &mut *(opaque as *mut Box<dyn BlobSource>);
let slice = std::slice::from_raw_parts_mut(buf, buf_size as usize);
match reader.read(slice) {
Ok(0) => sys::AVERROR_EOF,
Ok(n) => n as c_int,
// AVERROR(EIO) == -EIO on Unix; a negative value signals a read error.
Err(_) => -(libc::EIO as c_int),
}
}
/// FFmpeg seek callback. Handles `SEEK_SET/CUR/END` and `AVSEEK_SIZE` (report total
/// length). Returns the new position, the size, or `-1` on error.
unsafe extern "C" fn seek_cb(opaque: *mut c_void, offset: i64, whence: c_int) -> i64 {
if opaque.is_null() {
return -1;
}
let reader = &mut *(opaque as *mut Box<dyn BlobSource>);
let whence = whence & !AVSEEK_FORCE;
if whence & AVSEEK_SIZE != 0 {
// Report total length WITHOUT moving the logical position. FFmpeg does not
// restore the position after an AVSEEK_SIZE query, so we must: measure by
// seeking to the end, then seek back. (Failing to restore corrupts reads of
// containers whose index lives at the end of the file, e.g. MP4 `moov`.)
let cur = match reader.stream_position() {
Ok(p) => p,
Err(_) => return -1,
};
let size = match reader.seek(SeekFrom::End(0)) {
Ok(s) => s,
Err(_) => return -1,
};
if reader.seek(SeekFrom::Start(cur)).is_err() {
return -1;
}
return size as i64;
}
let from = match whence {
libc::SEEK_SET => SeekFrom::Start(offset as u64),
libc::SEEK_CUR => SeekFrom::Current(offset),
libc::SEEK_END => SeekFrom::End(offset),
_ => return -1,
};
reader.seek(from).map(|n| n as i64).unwrap_or(-1)
}
+100
View File
@@ -0,0 +1,100 @@
//! Exercises the custom AVIO shim end to end against a hand-built WAV, fed through
//! an in-memory `Cursor` (a `Read + Seek` source). FFmpeg can only demux it by
//! calling our `read_cb`/`seek_cb`, so a successful open proves the shim works.
use ffmpeg_blob_io::BlobInput;
use std::io::Cursor;
/// Build a minimal 16-bit PCM WAV in memory.
fn make_wav(sample_rate: u32, channels: u16, samples: &[i16]) -> Vec<u8> {
let bits: u16 = 16;
let block_align: u16 = channels * (bits / 8);
let byte_rate: u32 = sample_rate * block_align as u32;
let data_len: u32 = (samples.len() * 2) as u32;
let mut v = Vec::new();
v.extend_from_slice(b"RIFF");
v.extend_from_slice(&(36 + data_len).to_le_bytes());
v.extend_from_slice(b"WAVE");
v.extend_from_slice(b"fmt ");
v.extend_from_slice(&16u32.to_le_bytes()); // fmt chunk size
v.extend_from_slice(&1u16.to_le_bytes()); // PCM
v.extend_from_slice(&channels.to_le_bytes());
v.extend_from_slice(&sample_rate.to_le_bytes());
v.extend_from_slice(&byte_rate.to_le_bytes());
v.extend_from_slice(&block_align.to_le_bytes());
v.extend_from_slice(&bits.to_le_bytes());
v.extend_from_slice(b"data");
v.extend_from_slice(&data_len.to_le_bytes());
for s in samples {
v.extend_from_slice(&s.to_le_bytes());
}
v
}
fn sample_wav() -> Vec<u8> {
let samples: Vec<i16> = (0..1600).map(|i| ((i % 100) as i16 - 50) * 200).collect();
make_wav(8000, 1, &samples)
}
#[test]
fn opens_from_reader_and_reports_stream() {
let input = BlobInput::open(Box::new(Cursor::new(sample_wav())), Some("wav"))
.expect("open WAV through the blob shim");
let stream = input
.streams()
.best(ffmpeg_next::media::Type::Audio)
.expect("an audio stream");
let ctx = ffmpeg_next::codec::context::Context::from_parameters(stream.parameters())
.expect("codec context");
let decoder = ctx.decoder().audio().expect("audio decoder");
assert_eq!(decoder.rate(), 8000, "sample rate read via AVIO");
assert_eq!(decoder.channels(), 1, "channel count read via AVIO");
}
#[test]
fn reads_packets_through_callbacks() {
let mut input = BlobInput::open(Box::new(Cursor::new(sample_wav())), Some("wav"))
.expect("open WAV");
let mut packets = 0usize;
let mut bytes = 0usize;
for (_stream, packet) in input.packets() {
packets += 1;
bytes += packet.size();
}
assert!(packets > 0, "demuxer produced packets via read_cb");
assert!(bytes > 0, "packets carried PCM payload");
}
#[test]
fn seek_then_read() {
let mut input = BlobInput::open(Box::new(Cursor::new(sample_wav())), Some("wav"))
.expect("open WAV");
// Seek back to the start (exercises seek_cb SEEK_SET + AVSEEK_SIZE).
input.seek(0, ..).expect("seek to start");
let got_packet = input.packets().next().is_some();
assert!(got_packet, "can still read after seek");
}
#[test]
fn open_drop_loop_is_clean() {
// Repeated open+drop surfaces double-free / leak in the Drop teardown
// (run under `RUSTFLAGS=-Zsanitizer=address` on nightly for full coverage).
for _ in 0..200 {
let input = BlobInput::open(Box::new(Cursor::new(sample_wav())), Some("wav"))
.expect("open WAV");
assert!(input.streams().count() >= 1);
drop(input);
}
}
#[test]
fn bad_format_hint_errors_without_leak() {
// Garbage bytes with a real hint: open should fail cleanly (error path frees
// buffer + avio + reader), not panic or leak.
let garbage = vec![0u8; 4096];
let res = BlobInput::open(Box::new(Cursor::new(garbage)), Some("wav"));
assert!(res.is_err(), "non-WAV bytes should fail to open as WAV");
}
+5
View File
@@ -15,3 +15,8 @@
# OS
.DS_Store
Thumbs.db
# Local, machine-specific cargo config (e.g. PKG_CONFIG_PATH for a local ffmpeg).
# CI/packaging build ffmpeg from source (see .github/workflows/build.yml), so this
# must never leak into a commit.
.cargo/config.toml
+494 -146
View File
File diff suppressed because it is too large Load Diff
+15
View File
@@ -4,6 +4,7 @@ members = [
"lightningbeam-editor",
"lightningbeam-core",
"beamdsp",
"gpu-video-encoder",
]
[workspace.dependencies]
@@ -23,6 +24,11 @@ vello = { git = "https://github.com/linebender/vello", branch = "main" }
wgpu = { version = "27", features = ["vulkan", "metal", "gles"] }
kurbo = { version = "0.12", features = ["serde"] }
peniko = "0.5"
# Text layout/shaping for text layers. Pinned to git main to match the peniko 0.5
# / skrifa 0.37 that vello's git-main resolves to — a released parley still pins
# peniko 0.4, which would split `peniko::Font` into two incompatible types at the
# vello `draw_glyphs` boundary.
parley = { git = "https://github.com/linebender/parley", branch = "main" }
# Windowing
winit = "0.30"
@@ -77,6 +83,15 @@ opt-level = 2
[profile.dev.package.cpal]
opt-level = 2
# GIF export: NeuQuant palette quantization is tight numeric loops that are punishingly slow
# unoptimized (10–30× in debug). Optimize the encoder crates even in dev builds.
[profile.dev.package.gif]
opt-level = 3
[profile.dev.package.color_quant]
opt-level = 3
[profile.dev.package.weezl]
opt-level = 3
# Use local egui fork with ibus/Wayland text input fix
[patch.crates-io]
egui = { path = "../../egui-fork/crates/egui" }
@@ -0,0 +1,20 @@
[package]
name = "gpu-video-encoder"
version = "0.1.0"
edition = "2021"
description = "Zero-copy GPU video encoding (RGBA->NV12 compute + hardware encoder interop). Unsafe FFI isolated here."
[dependencies]
wgpu = { workspace = true }
# Raw Vulkan access for the DMA-BUF import. Versions MUST match what wgpu links
# (wgpu-hal 27.0.4 / ash 0.38) so the hal/ash types unify across the boundary.
wgpu-hal = { version = "27", features = ["vulkan"] }
wgpu-types = "27"
ash = "0.38"
# Raw FFmpeg FFI for VAAPI hwcontext + hardware encode. Matches the editor's
# ffmpeg-next 8.0 / static link so cargo unifies to one libav* across the build.
ffmpeg-sys-next = { version = "8.0", features = ["static"] }
libc = "0.2"
[dev-dependencies]
pollster = "0.4"
@@ -0,0 +1,217 @@
//! VAAPI hardware video decode → wgpu textures. The mirror of [`crate::encoder`]: the codec
//! decodes into a VAAPI NV12 surface, which is mapped to a DRM-PRIME DMA-BUF and imported as two
//! wgpu plane textures via [`crate::dmabuf::import_raw`] — the exact same path the encoder uses,
//! in the read direction. Stays GPU-resident: no CPU frame copy.
use crate::dmabuf::{self, ImportedNv12, Nv12DmaBuf};
use crate::vk_device::{self, DrmDevice};
use ffmpeg_sys_next as ff;
use std::ffi::CString;
use std::path::Path;
use std::ptr;
#[inline]
fn averror(e: i32) -> i32 {
-e
}
/// `get_format` callback: pick VAAPI surfaces so the decoder outputs hardware frames. With
/// `hw_device_ctx` set, FFmpeg auto-allocates the matching frames context.
unsafe extern "C" fn get_vaapi_format(
_ctx: *mut ff::AVCodecContext,
mut fmts: *const ff::AVPixelFormat,
) -> ff::AVPixelFormat {
while *fmts != ff::AVPixelFormat::AV_PIX_FMT_NONE {
if *fmts == ff::AVPixelFormat::AV_PIX_FMT_VAAPI {
return ff::AVPixelFormat::AV_PIX_FMT_VAAPI;
}
fmts = fmts.add(1);
}
ff::AVPixelFormat::AV_PIX_FMT_NONE
}
/// Hardware decoder for a single video file/stream. Frames come back as importable NV12 textures
/// on [`Self::device`].
pub struct VaapiDecoder {
drm: DrmDevice,
hw_device: *mut ff::AVBufferRef,
fmt: *mut ff::AVFormatContext,
dec: *mut ff::AVCodecContext,
pkt: *mut ff::AVPacket,
frame: *mut ff::AVFrame,
stream_index: i32,
flushing: bool,
}
// Owns its FFmpeg/Vulkan handles exclusively; only moved, never shared (same as the encoder).
unsafe impl Send for VaapiDecoder {}
impl VaapiDecoder {
/// Open `input_path` and set up VAAPI hardware decoding of its best video stream.
pub fn new(input_path: &Path) -> Result<Self, String> {
let drm = vk_device::create()?;
unsafe {
let mut hw_device = crate::vaapi::create_device()?;
let cleanup_hw = |hw: *mut ff::AVBufferRef| {
let mut h = hw;
ff::av_buffer_unref(&mut h);
};
let path_c = CString::new(input_path.to_string_lossy().as_ref()).unwrap();
let mut fmt: *mut ff::AVFormatContext = ptr::null_mut();
if ff::avformat_open_input(&mut fmt, path_c.as_ptr(), ptr::null_mut(), ptr::null_mut()) < 0 {
cleanup_hw(hw_device);
return Err(format!("avformat_open_input {input_path:?} failed"));
}
if ff::avformat_find_stream_info(fmt, ptr::null_mut()) < 0 {
ff::avformat_close_input(&mut fmt);
cleanup_hw(hw_device);
return Err("avformat_find_stream_info failed".into());
}
let mut decoder: *const ff::AVCodec = ptr::null();
let stream_index = ff::av_find_best_stream(
fmt,
ff::AVMediaType::AVMEDIA_TYPE_VIDEO,
-1,
-1,
&mut decoder,
0,
);
if stream_index < 0 || decoder.is_null() {
ff::avformat_close_input(&mut fmt);
cleanup_hw(hw_device);
return Err("no decodable video stream".into());
}
let dec = ff::avcodec_alloc_context3(decoder);
let stream = *(*fmt).streams.add(stream_index as usize);
if ff::avcodec_parameters_to_context(dec, (*stream).codecpar) < 0 {
ff::avcodec_free_context(&mut (dec as *mut _));
ff::avformat_close_input(&mut fmt);
cleanup_hw(hw_device);
return Err("avcodec_parameters_to_context failed".into());
}
(*dec).hw_device_ctx = ff::av_buffer_ref(hw_device);
(*dec).get_format = Some(get_vaapi_format);
if ff::avcodec_open2(dec, decoder, ptr::null_mut()) < 0 {
ff::avcodec_free_context(&mut (dec as *mut _));
ff::avformat_close_input(&mut fmt);
cleanup_hw(hw_device);
return Err("avcodec_open2 (vaapi decode) failed".into());
}
// `mut` only to satisfy the move into the struct; the binding above is consumed.
let _ = &mut hw_device;
Ok(Self {
drm,
hw_device,
fmt,
dec,
pkt: ff::av_packet_alloc(),
frame: ff::av_frame_alloc(),
stream_index,
flushing: false,
})
}
}
/// The wgpu device the decoded textures live on (the DMA-BUF-import device).
pub fn device(&self) -> &wgpu::Device {
&self.drm.device
}
pub fn queue(&self) -> &wgpu::Queue {
&self.drm.queue
}
/// Decode the next frame and import it as NV12 plane textures, or `Ok(None)` at end of stream.
pub fn next_frame(&mut self) -> Result<Option<ImportedNv12>, String> {
unsafe {
loop {
let r = ff::avcodec_receive_frame(self.dec, self.frame);
if r == 0 {
let imported = self.map_current();
ff::av_frame_unref(self.frame);
return imported.map(Some);
}
if r == ff::AVERROR_EOF {
return Ok(None);
}
if r != averror(libc::EAGAIN) {
return Err(format!("avcodec_receive_frame failed: {r}"));
}
if self.flushing {
return Ok(None); // already drained the flush
}
// Decoder wants more input: pump one packet (or signal EOF to flush).
let rp = ff::av_read_frame(self.fmt, self.pkt);
if rp < 0 {
self.flushing = true;
ff::avcodec_send_packet(self.dec, ptr::null());
continue;
}
if (*self.pkt).stream_index == self.stream_index {
let rs = ff::avcodec_send_packet(self.dec, self.pkt);
ff::av_packet_unref(self.pkt);
if rs < 0 && rs != averror(libc::EAGAIN) {
return Err(format!("avcodec_send_packet failed: {rs}"));
}
} else {
ff::av_packet_unref(self.pkt);
}
}
}
}
/// Map the just-decoded VAAPI surface (`self.frame`) to a DRM-PRIME DMA-BUF and import it.
unsafe fn map_current(&self) -> Result<ImportedNv12, String> {
let drm_f = ff::av_frame_alloc();
(*drm_f).format = ff::AVPixelFormat::AV_PIX_FMT_DRM_PRIME as i32;
let flags = ff::AV_HWFRAME_MAP_DIRECT as i32 | ff::AV_HWFRAME_MAP_READ as i32;
if ff::av_hwframe_map(drm_f, self.frame, flags) < 0 {
ff::av_frame_free(&mut (drm_f as *mut _));
return Err("av_hwframe_map failed".into());
}
let desc = (*drm_f).data[0] as *const ff::AVDRMFrameDescriptor;
let obj = &(*desc).objects[0];
let width = (*self.frame).width as u32;
let height = (*self.frame).height as u32;
// NV12: Y then UV — either as two layers (one plane each) or one layer with two planes.
let (y_pl, uv_pl) = if (*desc).nb_layers >= 2 {
(&(*desc).layers[0].planes[0], &(*desc).layers[1].planes[0])
} else {
(&(*desc).layers[0].planes[0], &(*desc).layers[0].planes[1])
};
let buf = Nv12DmaBuf {
fd: obj.fd,
size: obj.size as u64,
modifier: obj.format_modifier,
width,
height,
y_offset: y_pl.offset as u64,
y_pitch: y_pl.pitch as u64,
uv_offset: uv_pl.offset as u64,
uv_pitch: uv_pl.pitch as u64,
ten_bit: false,
};
let imported = dmabuf::import_raw(&self.drm.device, &self.drm.adapter, &buf);
ff::av_frame_free(&mut (drm_f as *mut _)); // the fd was dup'd into Vulkan
imported
}
}
impl Drop for VaapiDecoder {
fn drop(&mut self) {
unsafe {
ff::av_frame_free(&mut (self.frame as *mut _));
ff::av_packet_free(&mut (self.pkt as *mut _));
ff::avcodec_free_context(&mut (self.dec as *mut _));
if !self.fmt.is_null() {
ff::avformat_close_input(&mut self.fmt);
}
ff::av_buffer_unref(&mut self.hw_device);
}
}
}
@@ -0,0 +1,309 @@
//! Import a tiled VAAPI NV12 DMA-BUF as two wgpu textures (Y = R8, UV = RG8), aliasing
//! the one imported `VkDeviceMemory` at the plane offsets. Two single-format images are
//! used instead of one multi-planar image so each is an ordinary wgpu render target.
use crate::vaapi::MappedSurface;
use crate::vk_device::DrmDevice;
use ash::vk;
/// Plane layout for a single-object NV12/P010 DMA-BUF (the common VAAPI case).
#[derive(Clone, Copy)]
pub struct Nv12DmaBuf {
pub fd: i32,
pub size: u64,
pub modifier: u64,
pub width: u32,
pub height: u32,
pub y_offset: u64,
pub y_pitch: u64,
pub uv_offset: u64,
pub uv_pitch: u64,
/// True for 10/12/16-bit content (P010 etc.): planes are 16-bit (R16/Rg16) rather than 8-bit
/// (R8/Rg8). The sampled float is normalized either way, so the consumer needs no change.
pub ten_bit: bool,
}
/// Frees the shared imported `VkDeviceMemory` once both plane images are gone. Held by
/// both textures' drop callbacks (via `Arc`); the last one to run frees the memory —
/// after wgpu has destroyed the images, in its wait-idle'd deferred-destruction pass.
struct MemoryGuard {
device: ash::Device,
memory: vk::DeviceMemory,
}
impl Drop for MemoryGuard {
fn drop(&mut self) {
unsafe { self.device.free_memory(self.memory, None) };
}
}
/// Frees the duplicated dma-buf fd and any partially-created Vulkan objects when an import
/// errors out before ownership has been handed to wgpu/`MemoryGuard`. `commit()` disarms it on
/// the success path; `fd_consumed()` is called once `vkAllocateMemory` has taken the fd.
struct ImportGuard {
device: ash::Device,
fd: libc::c_int,
img_y: vk::Image,
img_uv: vk::Image,
memory: vk::DeviceMemory,
armed: bool,
}
impl ImportGuard {
fn fd_consumed(&mut self) {
self.fd = -1; // vkAllocateMemory owns the fd now; don't close it ourselves
}
fn commit(&mut self) {
self.armed = false;
}
}
impl Drop for ImportGuard {
fn drop(&mut self) {
if !self.armed {
return;
}
unsafe {
if self.img_uv != vk::Image::null() {
self.device.destroy_image(self.img_uv, None);
}
if self.img_y != vk::Image::null() {
self.device.destroy_image(self.img_y, None);
}
if self.memory != vk::DeviceMemory::null() {
self.device.free_memory(self.memory, None);
}
if self.fd >= 0 {
libc::close(self.fd);
}
}
}
}
/// A VAAPI surface imported as two wgpu plane textures. The underlying Vulkan image/
/// memory are destroyed by wgpu (via drop callbacks) when these textures drop.
pub struct ImportedNv12 {
y: wgpu::Texture,
uv: wgpu::Texture,
}
impl ImportedNv12 {
pub fn y(&self) -> &wgpu::Texture {
&self.y
}
pub fn uv(&self) -> &wgpu::Texture {
&self.uv
}
/// Consume into the `(Y, UV)` plane textures (for handing to a longer-lived owner).
pub fn into_planes(self) -> (wgpu::Texture, wgpu::Texture) {
(self.y, self.uv)
}
}
/// Convenience: map a freshly-allocated `MappedSurface` and import it onto `drm`.
pub fn import(drm: &DrmDevice, surf: &MappedSurface) -> Result<ImportedNv12, String> {
import_raw(
&drm.device,
&drm.adapter,
&Nv12DmaBuf {
fd: surf.fd,
size: surf.size,
modifier: surf.modifier,
width: surf.width,
height: surf.height,
y_offset: surf.y_offset,
y_pitch: surf.y_pitch,
uv_offset: surf.uv_offset,
uv_pitch: surf.uv_pitch,
ten_bit: false,
},
)
}
/// Import an NV12 DMA-BUF (described by `buf`) as two wgpu plane textures **on `device`**. The raw
/// Vulkan handles are extracted from `device`/`adapter` via `as_hal`, so this works with any
/// DMA-BUF-import-capable wgpu device — the encoder/decoder's own `DrmDevice` *or* the editor's
/// shared device. The fd is duplicated, so the caller keeps ownership of theirs.
pub fn import_raw(
device: &wgpu::Device,
adapter: &wgpu::Adapter,
buf: &Nv12DmaBuf,
) -> Result<ImportedNv12, String> {
use wgpu_hal::vulkan::Api as Vk;
unsafe {
let hal_device = device
.as_hal::<Vk>()
.ok_or("device is not Vulkan")?;
let raw_device = hal_device.raw_device().clone();
let raw_instance = adapter
.as_hal::<Vk>()
.ok_or("adapter is not Vulkan")?
.shared_instance()
.raw_instance()
.clone();
let instance = &raw_instance;
let dup_fd = libc::dup(buf.fd);
if dup_fd < 0 {
return Err("dup(dma-buf fd) failed".into());
}
// Owns the fd + any Vk objects created below until ownership transfers to wgpu; on any
// early `?`/return before that, its Drop frees them (was leaking on every failed import).
let mut guard = ImportGuard {
device: raw_device.clone(),
fd: dup_fd,
img_y: vk::Image::null(),
img_uv: vk::Image::null(),
memory: vk::DeviceMemory::null(),
armed: true,
};
// 16-bit-norm plane formats (P010) are NOT renderable, so the import is sample-only for
// those (decode path). 8-bit planes keep COLOR_ATTACHMENT for the encoder's RGBA→NV12 write.
let vk_usage = if buf.ten_bit {
vk::ImageUsageFlags::SAMPLED
| vk::ImageUsageFlags::TRANSFER_SRC
| vk::ImageUsageFlags::TRANSFER_DST
} else {
vk::ImageUsageFlags::COLOR_ATTACHMENT
| vk::ImageUsageFlags::SAMPLED
| vk::ImageUsageFlags::TRANSFER_SRC
| vk::ImageUsageFlags::TRANSFER_DST
};
let make_image = |format: vk::Format, w: u32, h: u32, pitch: u64| -> Result<vk::Image, String> {
let mut ext = vk::ExternalMemoryImageCreateInfo::default()
.handle_types(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT);
let plane_layouts = [vk::SubresourceLayout::default().offset(0).row_pitch(pitch)];
let mut drm_info = vk::ImageDrmFormatModifierExplicitCreateInfoEXT::default()
.drm_format_modifier(buf.modifier)
.plane_layouts(&plane_layouts);
let info = vk::ImageCreateInfo::default()
.image_type(vk::ImageType::TYPE_2D)
.format(format)
.extent(vk::Extent3D { width: w, height: h, depth: 1 })
.mip_levels(1)
.array_layers(1)
.samples(vk::SampleCountFlags::TYPE_1)
.tiling(vk::ImageTiling::DRM_FORMAT_MODIFIER_EXT)
.usage(vk_usage)
.sharing_mode(vk::SharingMode::EXCLUSIVE)
.initial_layout(vk::ImageLayout::UNDEFINED)
.push_next(&mut ext)
.push_next(&mut drm_info);
raw_device
.create_image(&info, None)
.map_err(|e| format!("vkCreateImage(modifier) failed: {e:?}"))
};
// 8-bit NV12 → R8/Rg8 planes; 10/12/16-bit P010-style → R16/Rg16 (sampled value is
// normalized either way, so the NV12→RGB consumer is unchanged).
let (vk_y, vk_uv) = if buf.ten_bit {
(vk::Format::R16_UNORM, vk::Format::R16G16_UNORM)
} else {
(vk::Format::R8_UNORM, vk::Format::R8G8_UNORM)
};
let (wgpu_y, wgpu_uv) = if buf.ten_bit {
(wgpu::TextureFormat::R16Unorm, wgpu::TextureFormat::Rg16Unorm)
} else {
(wgpu::TextureFormat::R8Unorm, wgpu::TextureFormat::Rg8Unorm)
};
let img_y = make_image(vk_y, buf.width, buf.height, buf.y_pitch)?;
guard.img_y = img_y;
let img_uv = make_image(vk_uv, buf.width / 2, buf.height / 2, buf.uv_pitch)?;
guard.img_uv = img_uv;
let fd_dev = ash::khr::external_memory_fd::Device::new(instance, &raw_device);
let mut fd_props = vk::MemoryFdPropertiesKHR::default();
fd_dev
.get_memory_fd_properties(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT, dup_fd, &mut fd_props)
.map_err(|e| format!("vkGetMemoryFdPropertiesKHR failed: {e:?}"))?;
let req_y = raw_device.get_image_memory_requirements(img_y);
let req_uv = raw_device.get_image_memory_requirements(img_uv);
let type_bits = fd_props.memory_type_bits & req_y.memory_type_bits & req_uv.memory_type_bits;
if type_bits == 0 {
return Err("no memory type compatible with dma-buf + both plane images".into());
}
let mem_type = type_bits.trailing_zeros();
let mut import_info = vk::ImportMemoryFdInfoKHR::default()
.handle_type(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT)
.fd(dup_fd);
let alloc = vk::MemoryAllocateInfo::default()
.allocation_size(buf.size)
.memory_type_index(mem_type)
.push_next(&mut import_info);
let memory = raw_device
.allocate_memory(&alloc, None)
.map_err(|e| format!("vkAllocateMemory(import dma-buf) failed: {e:?}"))?;
guard.fd_consumed(); // the import transferred fd ownership to Vulkan
guard.memory = memory;
raw_device
.bind_image_memory(img_y, memory, buf.y_offset)
.map_err(|e| format!("bind Y plane: {e:?}"))?;
raw_device
.bind_image_memory(img_uv, memory, buf.uv_offset)
.map_err(|e| format!("bind UV plane: {e:?}"))?;
// Shared guard: frees `memory` once both images' drop callbacks have run.
let mem_guard = std::sync::Arc::new(MemoryGuard { device: raw_device.clone(), memory });
// Match the Vulkan usage: 16-bit-norm planes (P010) are sample-only (not renderable).
let (hal_usage, wgpu_usage) = if buf.ten_bit {
(
wgpu_types::TextureUses::RESOURCE | wgpu_types::TextureUses::COPY_SRC,
wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_SRC,
)
} else {
(
wgpu_types::TextureUses::COLOR_TARGET
| wgpu_types::TextureUses::RESOURCE
| wgpu_types::TextureUses::COPY_SRC,
wgpu::TextureUsages::RENDER_ATTACHMENT
| wgpu::TextureUsages::TEXTURE_BINDING
| wgpu::TextureUsages::COPY_SRC,
)
};
let wrap = |img: vk::Image, format: wgpu::TextureFormat, w: u32, h: u32| -> wgpu::Texture {
// wgpu destroys the image (after wait-idle) when the texture drops; the
// captured Arc<MemoryGuard> frees the shared memory once both have run.
let dev = raw_device.clone();
let guard = mem_guard.clone();
let cb: wgpu_hal::DropCallback = Box::new(move || {
dev.destroy_image(img, None);
drop(guard);
});
let hal_desc = wgpu_hal::TextureDescriptor {
label: Some("vaapi-plane"),
size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage: hal_usage,
memory_flags: wgpu_hal::MemoryFlags::empty(),
view_formats: vec![],
};
let hal_tex = hal_device.texture_from_raw(img, &hal_desc, Some(cb));
device.create_texture_from_hal::<wgpu_hal::vulkan::Api>(
hal_tex,
&wgpu::TextureDescriptor {
label: Some("vaapi-plane"),
size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage: wgpu_usage,
view_formats: &[],
},
)
};
// Ownership of the images (→ texture drop callbacks) and memory (→ MemoryGuard) has now
// transferred to wgpu; disarm the cleanup guard so it doesn't double-free them.
guard.commit();
let y = wrap(img_y, wgpu_y, buf.width, buf.height);
let uv = wrap(img_uv, wgpu_uv, buf.width / 2, buf.height / 2);
drop(hal_device);
Ok(ImportedNv12 { y, uv })
}
}
@@ -0,0 +1,334 @@
//! End-to-end zero-copy H.264 encoder: render an RGBA wgpu texture straight into a VAAPI
//! NV12 surface (no CPU copy) and encode it with `h264_vaapi`. The caller renders frames
//! on [`ZeroCopyEncoder::device`] (the custom Vulkan device with DMA-BUF import enabled).
//!
//! Imports are cached by VASurface id, so the pooled surfaces are imported once each.
use crate::dmabuf::{self, ImportedNv12, Nv12DmaBuf};
use crate::render_nv12::Rgba2Nv12;
use crate::vk_device;
use ffmpeg_sys_next as ff;
use std::collections::HashMap;
use std::ffi::CString;
use std::path::Path;
use std::ptr;
#[inline]
fn averror(e: i32) -> i32 {
-e
}
pub struct ZeroCopyEncoder {
/// wgpu handles the NV12 render runs on — either an own `DrmDevice`'s (via `new`) or the
/// editor's shared device (via `new_on_device`). Cloned (Arc-backed) so the source can drop.
device: wgpu::Device,
queue: wgpu::Queue,
adapter: wgpu::Adapter,
renderer: Rgba2Nv12,
hw_device: *mut ff::AVBufferRef,
frames_ref: *mut ff::AVBufferRef,
enc: *mut ff::AVCodecContext,
pkt: *mut ff::AVPacket,
/// Output container (e.g. `.mp4`); packets are muxed into it directly.
oc: *mut ff::AVFormatContext,
enc_tb: ff::AVRational,
stream_tb: ff::AVRational,
width: u32,
height: u32,
pts: i64,
cache: HashMap<usize, ImportedNv12>,
}
// The encoder owns its FFmpeg contexts (raw `*mut`) and Vulkan/wgpu handles exclusively; it is
// never shared, only moved. Sending it to a dedicated export thread is sound.
unsafe impl Send for ZeroCopyEncoder {}
impl ZeroCopyEncoder {
/// Build a zero-copy `h264_vaapi` encoder writing to `output_path` (container inferred
/// from the extension, e.g. `.mp4`). `Err` if VAAPI/the device is unavailable.
#[allow(clippy::too_many_arguments)]
pub fn new(
width: u32,
height: u32,
framerate: i32,
bitrate_kbps: u32,
output_path: &Path,
full_range: bool,
) -> Result<Self, String> {
// Build a dedicated DMA-BUF-import device and run the encoder on it.
let drm = vk_device::create()?;
Self::new_on_device(
drm.device, drm.queue, drm.adapter,
width, height, framerate, bitrate_kbps, output_path, full_range,
)
}
/// Build the encoder running its NV12 render + DMA-BUF import on an existing wgpu device (the
/// editor's shared device), so decode→composite→encode stay GPU-resident on one device. The
/// device must have the DMA-BUF import extensions (a `DrmDevice` / `vk_device::create_windowed`).
#[allow(clippy::too_many_arguments)]
pub fn new_on_device(
device: wgpu::Device,
queue: wgpu::Queue,
adapter: wgpu::Adapter,
width: u32,
height: u32,
framerate: i32,
bitrate_kbps: u32,
output_path: &Path,
full_range: bool,
) -> Result<Self, String> {
let renderer = Rgba2Nv12::new(&device, full_range);
unsafe {
let mut hw_device = crate::vaapi::create_device()?;
let name = CString::new("h264_vaapi").unwrap();
let codec = ff::avcodec_find_encoder_by_name(name.as_ptr());
if codec.is_null() {
ff::av_buffer_unref(&mut hw_device);
return Err("h264_vaapi not found".into());
}
let enc = ff::avcodec_alloc_context3(codec);
(*enc).width = width as i32;
(*enc).height = height as i32;
(*enc).time_base = ff::AVRational { num: 1, den: framerate };
(*enc).framerate = ff::AVRational { num: framerate, den: 1 };
(*enc).pix_fmt = ff::AVPixelFormat::AV_PIX_FMT_VAAPI;
(*enc).bit_rate = (bitrate_kbps as i64) * 1000;
// Color signalling for the H.264 VUI. The Rgba2Nv12 shader produces BT.709 luma/chroma
// in the matching range; without these tags players assume limited range and a
// full-range stream looks dark + oversaturated.
(*enc).color_range = if full_range {
ff::AVColorRange::AVCOL_RANGE_JPEG
} else {
ff::AVColorRange::AVCOL_RANGE_MPEG
};
(*enc).colorspace = ff::AVColorSpace::AVCOL_SPC_BT709;
(*enc).color_primaries = ff::AVColorPrimaries::AVCOL_PRI_BT709;
(*enc).color_trc = ff::AVColorTransferCharacteristic::AVCOL_TRC_BT709;
let frames_ref = ff::av_hwframe_ctx_alloc(hw_device);
{
let fctx = (*frames_ref).data as *mut ff::AVHWFramesContext;
(*fctx).format = ff::AVPixelFormat::AV_PIX_FMT_VAAPI;
(*fctx).sw_format = ff::AVPixelFormat::AV_PIX_FMT_NV12;
(*fctx).width = width as i32;
(*fctx).height = height as i32;
(*fctx).initial_pool_size = 16;
}
if ff::av_hwframe_ctx_init(frames_ref) < 0 {
let mut fr = frames_ref;
ff::av_buffer_unref(&mut fr);
ff::avcodec_free_context(&mut (enc as *mut _));
ff::av_buffer_unref(&mut hw_device);
return Err("av_hwframe_ctx_init failed".into());
}
(*enc).hw_frames_ctx = ff::av_buffer_ref(frames_ref);
// Output container (format inferred from the path's extension).
let cleanup = |frames_ref: *mut ff::AVBufferRef, enc: *mut ff::AVCodecContext, hw: *mut ff::AVBufferRef| {
let mut fr = frames_ref;
ff::av_buffer_unref(&mut fr);
ff::avcodec_free_context(&mut (enc as *mut _));
let mut h = hw;
ff::av_buffer_unref(&mut h);
};
let path_c = CString::new(output_path.to_string_lossy().as_ref()).unwrap();
let mut oc: *mut ff::AVFormatContext = ptr::null_mut();
if ff::avformat_alloc_output_context2(&mut oc, ptr::null(), ptr::null(), path_c.as_ptr()) < 0
|| oc.is_null()
{
cleanup(frames_ref, enc, hw_device);
return Err(format!("avformat_alloc_output_context2 for {output_path:?} failed"));
}
// mp4/mov want SPS/PPS in extradata, not inline — set before opening the encoder.
if (*(*oc).oformat).flags & ff::AVFMT_GLOBALHEADER as i32 != 0 {
(*enc).flags |= ff::AV_CODEC_FLAG_GLOBAL_HEADER as i32;
}
if ff::avcodec_open2(enc, codec, ptr::null_mut()) < 0 {
ff::avformat_free_context(oc);
cleanup(frames_ref, enc, hw_device);
return Err("avcodec_open2(h264_vaapi) failed".into());
}
let stream = ff::avformat_new_stream(oc, codec);
if stream.is_null() {
ff::avformat_free_context(oc);
cleanup(frames_ref, enc, hw_device);
return Err("avformat_new_stream failed".into());
}
if ff::avcodec_parameters_from_context((*stream).codecpar, enc) < 0 {
ff::avformat_free_context(oc);
cleanup(frames_ref, enc, hw_device);
return Err("avcodec_parameters_from_context failed".into());
}
(*stream).time_base = (*enc).time_base;
if ff::avio_open(&mut (*oc).pb, path_c.as_ptr(), ff::AVIO_FLAG_WRITE as i32) < 0 {
ff::avformat_free_context(oc);
cleanup(frames_ref, enc, hw_device);
return Err(format!("avio_open {output_path:?} failed"));
}
if ff::avformat_write_header(oc, ptr::null_mut()) < 0 {
ff::avio_closep(&mut (*oc).pb);
ff::avformat_free_context(oc);
cleanup(frames_ref, enc, hw_device);
return Err("avformat_write_header failed".into());
}
// The muxer may rewrite the stream time_base in write_header.
let stream_tb = (*stream).time_base;
Ok(Self {
device,
queue,
adapter,
renderer,
hw_device,
frames_ref,
enc,
pkt: ff::av_packet_alloc(),
oc,
enc_tb: (*enc).time_base,
stream_tb,
width,
height,
pts: 0,
cache: HashMap::new(),
})
}
}
/// The wgpu device frames must be rendered on (so the RGBA texture is importable).
pub fn device(&self) -> &wgpu::Device {
&self.device
}
pub fn queue(&self) -> &wgpu::Queue {
&self.queue
}
/// Render `rgba` (an `Rgba8Unorm` texture on [`Self::device`], `TEXTURE_BINDING`)
/// into a VAAPI surface and encode it. Appends any produced packets internally.
pub fn encode_rgba(&mut self, rgba: &wgpu::Texture) -> Result<(), String> {
unsafe {
let surf = ff::av_frame_alloc();
if ff::av_hwframe_get_buffer(self.frames_ref, surf, 0) < 0 {
ff::av_frame_free(&mut (surf as *mut _));
return Err("av_hwframe_get_buffer failed".into());
}
let id = (*surf).data[3] as usize; // VASurfaceID
if !self.cache.contains_key(&id) {
let drm_f = ff::av_frame_alloc();
(*drm_f).format = ff::AVPixelFormat::AV_PIX_FMT_DRM_PRIME as i32;
let flags = ff::AV_HWFRAME_MAP_DIRECT as i32
| ff::AV_HWFRAME_MAP_READ as i32
| ff::AV_HWFRAME_MAP_WRITE as i32;
if ff::av_hwframe_map(drm_f, surf, flags) < 0 {
ff::av_frame_free(&mut (drm_f as *mut _));
ff::av_frame_free(&mut (surf as *mut _));
return Err("av_hwframe_map failed".into());
}
let desc = (*drm_f).data[0] as *const ff::AVDRMFrameDescriptor;
let obj = &(*desc).objects[0];
let y = &(*desc).layers[0].planes[0];
let uv = &(*desc).layers[1].planes[0];
let buf = Nv12DmaBuf {
fd: obj.fd,
size: obj.size as u64,
modifier: obj.format_modifier,
width: self.width,
height: self.height,
y_offset: y.offset as u64,
y_pitch: y.pitch as u64,
uv_offset: uv.offset as u64,
uv_pitch: uv.pitch as u64,
ten_bit: false,
};
let imported = match dmabuf::import_raw(&self.device, &self.adapter, &buf) {
Ok(i) => i,
Err(e) => {
ff::av_frame_free(&mut (drm_f as *mut _));
ff::av_frame_free(&mut (surf as *mut _));
return Err(e);
}
};
ff::av_frame_free(&mut (drm_f as *mut _)); // fd was dup'd into Vulkan
self.cache.insert(id, imported);
}
// Render RGBA -> NV12 directly into the surface planes.
let imp = self.cache.get(&id).unwrap();
let rgba_view = rgba.create_view(&Default::default());
let y_view = imp.y().create_view(&Default::default());
let uv_view = imp.uv().create_view(&Default::default());
let mut cmd = self.device.create_command_encoder(&Default::default());
self.renderer.convert(&self.device, &mut cmd, &rgba_view, &y_view, &uv_view);
self.queue.submit(Some(cmd.finish()));
let _ = self.device.poll(wgpu::PollType::wait_indefinitely());
// Encode the surface.
(*surf).pts = self.pts;
self.pts += 1;
let r = ff::avcodec_send_frame(self.enc, surf);
ff::av_frame_free(&mut (surf as *mut _));
if r < 0 {
return Err(format!("avcodec_send_frame failed: {r}"));
}
self.drain()
}
}
unsafe fn drain(&mut self) -> Result<(), String> {
loop {
let r = ff::avcodec_receive_packet(self.enc, self.pkt);
if r == averror(libc::EAGAIN) || r == ff::AVERROR_EOF {
break;
}
if r < 0 {
return Err(format!("avcodec_receive_packet failed: {r}"));
}
ff::av_packet_rescale_ts(self.pkt, self.enc_tb, self.stream_tb);
(*self.pkt).stream_index = 0;
// Takes ownership of the packet's buffer (unrefs it for us).
let w = ff::av_interleaved_write_frame(self.oc, self.pkt);
if w < 0 {
return Err(format!("av_interleaved_write_frame failed: {w}"));
}
}
Ok(())
}
/// Flush the encoder, write the container trailer, and close the output file.
pub fn finish(mut self) -> Result<(), String> {
unsafe {
ff::avcodec_send_frame(self.enc, ptr::null_mut());
self.drain()?;
if ff::av_write_trailer(self.oc) < 0 {
return Err("av_write_trailer failed".into());
}
ff::avio_closep(&mut (*self.oc).pb);
}
Ok(())
}
}
impl Drop for ZeroCopyEncoder {
fn drop(&mut self) {
unsafe {
self.cache.clear(); // frees imported Vulkan resources first
ff::av_packet_free(&mut (self.pkt as *mut _));
ff::avcodec_free_context(&mut (self.enc as *mut _));
let mut fr = self.frames_ref;
ff::av_buffer_unref(&mut fr);
ff::av_buffer_unref(&mut self.hw_device);
if !self.oc.is_null() {
// `finish` nulls pb via avio_closep; close here too if it wasn't called.
if !(*self.oc).pb.is_null() {
ff::avio_closep(&mut (*self.oc).pb);
}
ff::avformat_free_context(self.oc);
self.oc = ptr::null_mut();
}
}
}
}
@@ -0,0 +1,65 @@
//! Zero-copy GPU video encoding.
//!
//! Converts a rendered RGBA texture to the encoder's pixel format (NV12) on the GPU
//! and feeds it to a hardware video encoder without a CPU round-trip. All the unsafe
//! GPU↔encoder interop (Vulkan external memory / DMA-BUF → VAAPI on Linux, etc.) is
//! isolated in this crate.
//!
//! Status: scaffolding. Headless GPU probe + (next) NV12 compute live here first so
//! the GPU-side conversion can be validated against a CPU reference before any unsafe
//! interop is written. See `lightningbeam-ui/ZEROCOPY_GPU_ENCODE_PLAN.md`.
pub mod nv12;
/// Fragment-shader RGBA→NV12 conversion that renders into plane textures.
pub mod render_nv12;
/// VAAPI hardware encode (Linux-only; libva).
#[cfg(target_os = "linux")]
pub mod vaapi;
/// Custom Vulkan device with DMA-BUF import extensions (Linux).
#[cfg(target_os = "linux")]
pub mod vk_device;
/// Import a VAAPI NV12 DMA-BUF as wgpu textures (Linux).
#[cfg(target_os = "linux")]
pub mod dmabuf;
/// End-to-end zero-copy `h264_vaapi` encoder (Linux).
#[cfg(target_os = "linux")]
pub mod encoder;
/// VAAPI hardware decode → wgpu textures (Linux).
#[cfg(target_os = "linux")]
pub mod decoder;
#[cfg(test)]
mod probe_tests {
/// Confirm a headless GPU adapter is reachable (Vulkan on Linux/Intel). This gates
/// whether the GPU-side conversion can be tested on real hardware in this env.
#[test]
fn headless_adapter_available() {
let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {
backends: wgpu::Backends::VULKAN | wgpu::Backends::GL,
..Default::default()
});
let adapter = pollster::block_on(instance.request_adapter(
&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::HighPerformance,
force_fallback_adapter: false,
compatible_surface: None,
},
));
match adapter {
Ok(a) => {
let info = a.get_info();
eprintln!(
"[gpu-probe] adapter: {} | backend={:?} | type={:?} | driver={}",
info.name, info.backend, info.device_type, info.driver
);
}
Err(e) => panic!("no GPU adapter available headless: {e:?}"),
}
}
}
@@ -0,0 +1,207 @@
//! GPU RGBA→NV12 conversion (BT.709 full-range), the pixel format hardware video
//! encoders (VAAPI/QSV/NVENC/VideoToolbox) consume.
//!
//! NV12 layout (what this writes, tight-packed into a storage buffer):
//! - `[0, W*H)` Y plane, one byte/pixel, row stride `W`
//! - `[W*H, W*H + W*H/2)` UV plane, interleaved `U,V` at 4:2:0, row stride `W`
//! (`W/2` chroma columns × 2 bytes), `H/2` rows
//!
//! Same BT.709 full-range matrix as the editor's planar YUV420p path, so colors match.
//! Requires `W % 8 == 0 && H % 2 == 0` (the shader packs 4 bytes per `u32`).
/// `true` when [`Nv12Converter`] can handle these dimensions (else caller pads/falls back).
pub fn supports(width: u32, height: u32) -> bool {
width % 8 == 0 && height % 2 == 0 && width > 0 && height > 0
}
/// Tight NV12 byte length for `width`×`height`.
pub fn nv12_len(width: u32, height: u32) -> usize {
(width * height + width * (height / 2)) as usize
}
/// Compute pipeline: `Rgba8Unorm` texture → tight NV12 storage buffer.
pub struct Nv12Converter {
y_pipeline: wgpu::ComputePipeline,
uv_pipeline: wgpu::ComputePipeline,
bind_group_layout: wgpu::BindGroupLayout,
}
impl Nv12Converter {
pub fn new(device: &wgpu::Device) -> Self {
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("nv12_bgl"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::COMPUTE,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: false },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
],
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("nv12_pl"),
bind_group_layouts: &[&bind_group_layout],
push_constant_ranges: &[],
});
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("nv12_shader"),
source: wgpu::ShaderSource::Wgsl(SHADER.into()),
});
let mk = |entry: &str| {
device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("nv12_pipeline"),
layout: Some(&pipeline_layout),
module: &shader,
entry_point: Some(entry),
compilation_options: wgpu::PipelineCompilationOptions::default(),
cache: None,
})
};
Self {
y_pipeline: mk("y_main"),
uv_pipeline: mk("uv_main"),
bind_group_layout,
}
}
/// Record RGBA→NV12 into `encoder`. `out_buffer` must be `STORAGE | COPY_SRC` of at
/// least [`nv12_len`] bytes. Caller must ensure [`supports`]`(width, height)`.
pub fn convert(
&self,
device: &wgpu::Device,
encoder: &mut wgpu::CommandEncoder,
rgba_view: &wgpu::TextureView,
out_buffer: &wgpu::Buffer,
width: u32,
height: u32,
) {
debug_assert!(supports(width, height));
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("nv12_bg"),
layout: &self.bind_group_layout,
entries: &[
wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(rgba_view) },
wgpu::BindGroupEntry { binding: 1, resource: out_buffer.as_entire_binding() },
],
});
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("nv12_pass"),
timestamp_writes: None,
});
pass.set_bind_group(0, &bind_group, &[]);
let wg = 8u32;
// Y: one thread per 4 horizontal luma samples.
pass.set_pipeline(&self.y_pipeline);
pass.dispatch_workgroups(((width / 4) + wg - 1) / wg, (height + wg - 1) / wg, 1);
// UV: one thread per 4 interleaved UV bytes = 2 chroma columns; (W/4)×(H/2) threads.
pass.set_pipeline(&self.uv_pipeline);
pass.dispatch_workgroups(((width / 4) + wg - 1) / wg, ((height / 2) + wg - 1) / wg, 1);
}
}
/// CPU reference producing the exact bytes the shader should — used by tests to verify
/// the GPU output on real hardware.
pub fn cpu_reference(rgba: &[u8], width: u32, height: u32) -> Vec<u8> {
let w = width as usize;
let h = height as usize;
let mut out = vec![0u8; nv12_len(width, height)];
let to_byte = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
let px = |x: usize, y: usize| {
let i = (y * w + x) * 4;
[rgba[i] as f32 / 255.0, rgba[i + 1] as f32 / 255.0, rgba[i + 2] as f32 / 255.0]
};
// Y
for y in 0..h {
for x in 0..w {
let p = px(x, y);
out[y * w + x] = to_byte(0.2126 * p[0] + 0.7152 * p[1] + 0.0722 * p[2]);
}
}
// Interleaved UV (2x2 box average)
let y_size = w * h;
for cy in 0..h / 2 {
for cx in 0..w / 2 {
let mut acc = [0.0f32; 3];
for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] {
let p = px(2 * cx + dx, 2 * cy + dy);
acc[0] += p[0]; acc[1] += p[1]; acc[2] += p[2];
}
let a = [acc[0] / 4.0, acc[1] / 4.0, acc[2] / 4.0];
let u = -0.1146 * a[0] - 0.3854 * a[1] + 0.5000 * a[2] + 0.5;
let v = 0.5000 * a[0] - 0.4542 * a[1] - 0.0458 * a[2] + 0.5;
out[y_size + cy * w + 2 * cx] = to_byte(u);
out[y_size + cy * w + 2 * cx + 1] = to_byte(v);
}
}
out
}
const SHADER: &str = r#"
@group(0) @binding(0) var input_rgba: texture_2d<f32>;
@group(0) @binding(1) var<storage, read_write> out_buf: array<u32>;
fn to_byte(v: f32) -> u32 { return u32(clamp(v, 0.0, 1.0) * 255.0 + 0.5); }
// Y plane: pack 4 horizontal luma bytes.
@compute @workgroup_size(8, 8, 1)
fn y_main(@builtin(global_invocation_id) gid: vec3<u32>) {
let dims = textureDimensions(input_rgba);
let w = dims.x;
let h = dims.y;
let x4 = gid.x * 4u;
let y = gid.y;
if (x4 >= w || y >= h) { return; }
var packed: u32 = 0u;
for (var i = 0u; i < 4u; i = i + 1u) {
let c = textureLoad(input_rgba, vec2<u32>(x4 + i, y), 0).rgb;
let yy = 0.2126 * c.r + 0.7152 * c.g + 0.0722 * c.b;
packed = packed | (to_byte(yy) << (8u * i));
}
out_buf[(y * w + x4) / 4u] = packed;
}
// UV plane: each thread writes 4 interleaved bytes = U0 V0 U1 V1 for 2 chroma columns.
@compute @workgroup_size(8, 8, 1)
fn uv_main(@builtin(global_invocation_id) gid: vec3<u32>) {
let dims = textureDimensions(input_rgba);
let w = dims.x;
let h = dims.y;
let k = gid.x; // chroma-column pair index: covers columns 2k, 2k+1
let cy = gid.y;
if (k * 2u >= w / 2u || cy >= h / 2u) { return; }
let y_size = w * h;
var packed: u32 = 0u;
for (var j = 0u; j < 2u; j = j + 1u) {
let cx = 2u * k + j; // chroma column
let sx = 2u * cx;
let sy = 2u * cy;
let p00 = textureLoad(input_rgba, vec2<u32>(sx, sy), 0).rgb;
let p10 = textureLoad(input_rgba, vec2<u32>(sx + 1u, sy), 0).rgb;
let p01 = textureLoad(input_rgba, vec2<u32>(sx, sy + 1u), 0).rgb;
let p11 = textureLoad(input_rgba, vec2<u32>(sx + 1u, sy + 1u), 0).rgb;
let a = (p00 + p10 + p01 + p11) * 0.25;
let u = -0.1146 * a.r - 0.3854 * a.g + 0.5000 * a.b + 0.5;
let v = 0.5000 * a.r - 0.4542 * a.g - 0.0458 * a.b + 0.5;
packed = packed | (to_byte(u) << (16u * j)); // byte 0 or 2
packed = packed | (to_byte(v) << (16u * j + 8u)); // byte 1 or 3
}
// UV row stride is w bytes; this thread writes 4 bytes at column 4k.
out_buf[(y_size + cy * w + 4u * k) / 4u] = packed;
}
"#;
@@ -0,0 +1,189 @@
//! Fragment-shader RGBA→NV12 conversion that **renders** luma/chroma into the encoder
//! surface's plane textures (R8 Y, RG8 UV). Render targets (not compute storage) so it
//! works with the DMA-BUF-imported plane images, which aren't storage-writable.
//!
//! BT.709 matrix; the Y/chroma scale+offset are chosen by `full_range` — limited (TV, 16–235)
//! is the H.264 convention most players assume, full (PC, 0–255) needs the matching color tag.
/// Converts a bound RGBA texture into a Y plane (R8) and a UV plane (RG8) via two passes.
pub struct Rgba2Nv12 {
y_pipeline: wgpu::RenderPipeline,
uv_pipeline: wgpu::RenderPipeline,
bgl: wgpu::BindGroupLayout,
params_buf: wgpu::Buffer,
}
impl Rgba2Nv12 {
/// `full_range`: true → full/PC range (Y 0–255, no scaling); false → limited/TV range
/// (Y 16–235, chroma 16–240), the H.264 default. The encoder must tag the stream to match.
pub fn new(device: &wgpu::Device, full_range: bool) -> Self {
// (y_offset, y_scale, chroma_offset, chroma_scale). The shader applies these to the
// BT.709 luma/chroma dot products.
let params: [f32; 4] = if full_range {
[0.0, 1.0, 128.0 / 255.0, 1.0]
} else {
[16.0 / 255.0, 219.0 / 255.0, 128.0 / 255.0, 224.0 / 255.0]
};
let params_bytes: Vec<u8> = params.iter().flat_map(|f| f.to_le_bytes()).collect();
let params_buf = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("rgba2nv12_params"),
size: params_bytes.len() as u64,
usage: wgpu::BufferUsages::UNIFORM,
mapped_at_creation: true,
});
params_buf.slice(..).get_mapped_range_mut().copy_from_slice(&params_bytes);
params_buf.unmap();
let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("rgba2nv12_bgl"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: false },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
],
});
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("rgba2nv12_pl"),
bind_group_layouts: &[&bgl],
push_constant_ranges: &[],
});
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("rgba2nv12_shader"),
source: wgpu::ShaderSource::Wgsl(SHADER.into()),
});
let mk = |fs: &str, fmt: wgpu::TextureFormat| {
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("rgba2nv12_pipeline"),
layout: Some(&layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_main"),
buffers: &[],
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some(fs),
targets: &[Some(fmt.into())],
compilation_options: Default::default(),
}),
primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::TriangleList,
..Default::default()
},
depth_stencil: None,
multisample: Default::default(),
multiview: None,
cache: None,
})
};
Self {
y_pipeline: mk("y_fs", wgpu::TextureFormat::R8Unorm),
uv_pipeline: mk("uv_fs", wgpu::TextureFormat::Rg8Unorm),
bgl,
params_buf,
}
}
/// Record both plane passes. `y_view`/`uv_view` are the R8/RG8 plane render targets.
pub fn convert(
&self,
device: &wgpu::Device,
encoder: &mut wgpu::CommandEncoder,
rgba_view: &wgpu::TextureView,
y_view: &wgpu::TextureView,
uv_view: &wgpu::TextureView,
) {
let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("rgba2nv12_bg"),
layout: &self.bgl,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(rgba_view),
},
wgpu::BindGroupEntry {
binding: 1,
resource: self.params_buf.as_entire_binding(),
},
],
});
for (pipeline, view) in [(&self.y_pipeline, y_view), (&self.uv_pipeline, uv_view)] {
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("rgba2nv12_pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view,
resolve_target: None,
depth_slice: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
});
pass.set_pipeline(pipeline);
pass.set_bind_group(0, &bg, &[]);
pass.draw(0..3, 0..1);
}
}
}
const SHADER: &str = r#"
@group(0) @binding(0) var input_rgba: texture_2d<f32>;
// (y_offset, y_scale, chroma_offset, chroma_scale) — selects limited vs full range.
@group(0) @binding(1) var<uniform> params: vec4<f32>;
// Fullscreen triangle.
@vertex
fn vs_main(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4<f32> {
let x = f32((vi << 1u) & 2u);
let y = f32(vi & 2u);
return vec4<f32>(x * 2.0 - 1.0, 1.0 - y * 2.0, 0.0, 1.0);
}
fn load(p: vec2<i32>) -> vec3<f32> {
return textureLoad(input_rgba, p, 0).rgb;
}
// Y plane (full res): one luma byte per pixel.
@fragment
fn y_fs(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
let c = load(vec2<i32>(i32(pos.x), i32(pos.y)));
let luma = 0.2126 * c.r + 0.7152 * c.g + 0.0722 * c.b;
let y = params.x + params.y * luma;
return vec4<f32>(y, 0.0, 0.0, 1.0);
}
// UV plane (half res): 2x2 box-averaged chroma, interleaved into RG.
@fragment
fn uv_fs(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
let sx = 2 * i32(pos.x);
let sy = 2 * i32(pos.y);
let a = (load(vec2<i32>(sx, sy)) + load(vec2<i32>(sx + 1, sy))
+ load(vec2<i32>(sx, sy + 1)) + load(vec2<i32>(sx + 1, sy + 1))) * 0.25;
let cb = -0.1146 * a.r - 0.3854 * a.g + 0.5000 * a.b;
let cr = 0.5000 * a.r - 0.4542 * a.g - 0.0458 * a.b;
let u = params.z + params.w * cb;
let v = params.z + params.w * cr;
return vec4<f32>(u, v, 0.0, 1.0);
}
"#;
@@ -0,0 +1,521 @@
//! VAAPI hardware H.264 encoding (Linux/Intel/AMD).
//!
//! Level 1 (this module first): a CPU-fed encoder — upload NV12 frames to VAAPI
//! surfaces (`av_hwframe_transfer_data`) and encode with `h264_vaapi`. This proves the
//! encoder works and establishes the FFI scaffolding. Level 2 (zero-copy: GPU writes
//! NV12 straight into the VAAPI surface via DMA-BUF) builds on this.
//!
//! All `unsafe` FFmpeg FFI is contained here.
use ffmpeg_sys_next as ff;
use std::ffi::CString;
use std::ptr;
#[inline]
fn averror(e: i32) -> i32 {
-e
}
/// Create a VAAPI hwdevice on `/dev/dri/renderD128`, trying driver names in turn.
///
/// libva's auto-selection can pick a driver that doesn't support the GPU — notably it
/// chooses the legacy `i965` driver on newer Intel parts (Gen 11+) where the modern `iHD`
/// driver is required. Each `av_hwdevice_ctx_create` opens a fresh VADisplay, so
/// `LIBVA_DRIVER_NAME` is re-read per attempt. We try `iHD` first (modern Intel), then the
/// caller's original setting, then `i965` (older Intel) and `radeonsi` (AMD). On success the
/// working driver name is left in the env; on total failure the original value is restored.
pub fn create_device() -> Result<*mut ff::AVBufferRef, String> {
unsafe {
let node = CString::new("/dev/dri/renderD128").unwrap();
let original = std::env::var_os("LIBVA_DRIVER_NAME");
let attempts: [Option<&str>; 4] = [Some("iHD"), None, Some("i965"), Some("radeonsi")];
for drv in attempts {
match drv {
Some(d) => std::env::set_var("LIBVA_DRIVER_NAME", d),
// `None` = the caller's original setting (or libva auto if unset).
None => match &original {
Some(v) => std::env::set_var("LIBVA_DRIVER_NAME", v),
None => std::env::remove_var("LIBVA_DRIVER_NAME"),
},
}
let mut hw: *mut ff::AVBufferRef = ptr::null_mut();
if ff::av_hwdevice_ctx_create(
&mut hw,
ff::AVHWDeviceType::AV_HWDEVICE_TYPE_VAAPI,
node.as_ptr(),
ptr::null_mut(),
0,
) >= 0
{
return Ok(hw);
}
}
match &original {
Some(v) => std::env::set_var("LIBVA_DRIVER_NAME", v),
None => std::env::remove_var("LIBVA_DRIVER_NAME"),
}
Err("av_hwdevice_ctx_create(VAAPI) failed for all drivers (iHD/i965/radeonsi)".into())
}
}
/// Copy tight NV12 (`Y` then interleaved `UV`) into an AVFrame's planes, respecting
/// each plane's linesize (which FFmpeg may pad).
unsafe fn fill_nv12(frame: *mut ff::AVFrame, nv12: &[u8], width: u32, height: u32) {
let w = width as usize;
let h = height as usize;
// Y plane: h rows of w bytes.
let dst_y = (*frame).data[0];
let ls_y = (*frame).linesize[0] as usize;
for row in 0..h {
let src = &nv12[row * w..row * w + w];
ptr::copy_nonoverlapping(src.as_ptr(), dst_y.add(row * ls_y), w);
}
// UV plane: h/2 rows of w bytes (interleaved U,V), source offset starts at w*h.
let dst_uv = (*frame).data[1];
let ls_uv = (*frame).linesize[1] as usize;
let uv_off = w * h;
for row in 0..h / 2 {
let src = &nv12[uv_off + row * w..uv_off + row * w + w];
ptr::copy_nonoverlapping(src.as_ptr(), dst_uv.add(row * ls_uv), w);
}
}
/// A VAAPI NV12 surface mapped to a DMA-BUF, with its layout extracted for Vulkan import.
/// Keeps the FFmpeg handles alive; the `fd` stays valid until drop (dup it for Vulkan).
pub struct MappedSurface {
hw_device: *mut ff::AVBufferRef,
frames_ref: *mut ff::AVBufferRef,
surf: *mut ff::AVFrame,
drm: *mut ff::AVFrame,
pub width: u32,
pub height: u32,
pub fd: i32,
pub size: u64,
pub modifier: u64,
pub y_offset: u64,
pub y_pitch: u64,
pub uv_offset: u64,
pub uv_pitch: u64,
}
impl MappedSurface {
/// Allocate a VAAPI NV12 surface and map it to DRM-PRIME.
pub fn alloc(width: u32, height: u32) -> Result<Self, String> {
unsafe {
let mut hw_device: *mut ff::AVBufferRef = ptr::null_mut();
let node = CString::new("/dev/dri/renderD128").unwrap();
if ff::av_hwdevice_ctx_create(
&mut hw_device,
ff::AVHWDeviceType::AV_HWDEVICE_TYPE_VAAPI,
node.as_ptr(),
ptr::null_mut(),
0,
) < 0
{
return Err("av_hwdevice_ctx_create failed".into());
}
let frames_ref = ff::av_hwframe_ctx_alloc(hw_device);
if frames_ref.is_null() {
ff::av_buffer_unref(&mut hw_device);
return Err("av_hwframe_ctx_alloc failed".into());
}
{
let fctx = (*frames_ref).data as *mut ff::AVHWFramesContext;
(*fctx).format = ff::AVPixelFormat::AV_PIX_FMT_VAAPI;
(*fctx).sw_format = ff::AVPixelFormat::AV_PIX_FMT_NV12;
(*fctx).width = width as i32;
(*fctx).height = height as i32;
(*fctx).initial_pool_size = 4;
}
if ff::av_hwframe_ctx_init(frames_ref) < 0 {
let mut fr = frames_ref;
ff::av_buffer_unref(&mut fr);
ff::av_buffer_unref(&mut hw_device);
return Err("av_hwframe_ctx_init failed".into());
}
let surf = ff::av_frame_alloc();
if ff::av_hwframe_get_buffer(frames_ref, surf, 0) < 0 {
ff::av_frame_free(&mut (surf as *mut _));
let mut fr = frames_ref;
ff::av_buffer_unref(&mut fr);
ff::av_buffer_unref(&mut hw_device);
return Err("av_hwframe_get_buffer failed".into());
}
let drm = ff::av_frame_alloc();
(*drm).format = ff::AVPixelFormat::AV_PIX_FMT_DRM_PRIME as i32;
let flags = ff::AV_HWFRAME_MAP_DIRECT as i32
| ff::AV_HWFRAME_MAP_READ as i32
| ff::AV_HWFRAME_MAP_WRITE as i32;
if ff::av_hwframe_map(drm, surf, flags) < 0 {
ff::av_frame_free(&mut (drm as *mut _));
ff::av_frame_free(&mut (surf as *mut _));
let mut fr = frames_ref;
ff::av_buffer_unref(&mut fr);
ff::av_buffer_unref(&mut hw_device);
return Err("av_hwframe_map failed".into());
}
let desc = (*drm).data[0] as *const ff::AVDRMFrameDescriptor;
// Expect 1 object, 2 layers (Y=R8, UV=GR88).
if (*desc).nb_objects != 1 || (*desc).nb_layers != 2 {
let msg = format!(
"unexpected DRM layout: {} objects, {} layers",
(*desc).nb_objects, (*desc).nb_layers
);
// Free everything mapped/allocated above (this path was leaking the device,
// frames context, and both AVFrames on every odd-layout surface).
ff::av_frame_free(&mut (drm as *mut _));
ff::av_frame_free(&mut (surf as *mut _));
let mut fr = frames_ref;
ff::av_buffer_unref(&mut fr);
ff::av_buffer_unref(&mut hw_device);
return Err(msg);
}
let obj = &(*desc).objects[0];
let y = &(*desc).layers[0].planes[0];
let uv = &(*desc).layers[1].planes[0];
Ok(MappedSurface {
hw_device,
frames_ref,
surf,
drm,
width,
height,
fd: obj.fd,
size: obj.size as u64,
modifier: obj.format_modifier,
y_offset: y.offset as u64,
y_pitch: y.pitch as u64,
uv_offset: uv.offset as u64,
uv_pitch: uv.pitch as u64,
})
}
}
/// The underlying VASurface AVFrame (to hand to the encoder).
pub fn av_frame(&self) -> *mut ff::AVFrame {
self.surf
}
/// Read the surface back to tight CPU NV12 (for verifying what the GPU wrote).
pub fn readback_nv12(&self) -> Result<Vec<u8>, String> {
unsafe {
let sw = ff::av_frame_alloc();
(*sw).format = ff::AVPixelFormat::AV_PIX_FMT_NV12 as i32;
(*sw).width = self.width as i32;
(*sw).height = self.height as i32;
if ff::av_frame_get_buffer(sw, 0) < 0 {
ff::av_frame_free(&mut (sw as *mut _));
return Err("av_frame_get_buffer failed".into());
}
if ff::av_hwframe_transfer_data(sw, self.surf, 0) < 0 {
ff::av_frame_free(&mut (sw as *mut _));
return Err("av_hwframe_transfer_data (download) failed".into());
}
let w = self.width as usize;
let h = self.height as usize;
let mut out = vec![0u8; w * h + w * (h / 2)];
let ls_y = (*sw).linesize[0] as usize;
for row in 0..h {
let src = (*sw).data[0].add(row * ls_y);
ptr::copy_nonoverlapping(src, out.as_mut_ptr().add(row * w), w);
}
let ls_uv = (*sw).linesize[1] as usize;
let uv_off = w * h;
for row in 0..h / 2 {
let src = (*sw).data[1].add(row * ls_uv);
ptr::copy_nonoverlapping(src, out.as_mut_ptr().add(uv_off + row * w), w);
}
ff::av_frame_free(&mut (sw as *mut _));
Ok(out)
}
}
}
impl Drop for MappedSurface {
fn drop(&mut self) {
unsafe {
ff::av_frame_free(&mut (self.drm as *mut _));
ff::av_frame_free(&mut (self.surf as *mut _));
let mut fr = self.frames_ref;
ff::av_buffer_unref(&mut fr);
ff::av_buffer_unref(&mut self.hw_device);
}
}
}
/// Allocate one VAAPI NV12 surface, map it to a DRM-PRIME descriptor, and return a
/// human-readable dump of its DMA-BUF layout (object fds/size/modifier; layer fourcc;
/// per-plane object/offset/pitch). The format **modifier** decides the zero-copy path:
/// `0` = LINEAR (compute can write a linear NV12 buffer/image), anything else = tiled
/// (needs a GPU copy into the tiled surface, or a linear import VAAPI accepts).
pub fn probe_surface_drm(width: u32, height: u32) -> Result<String, String> {
unsafe {
let mut hw_device: *mut ff::AVBufferRef = ptr::null_mut();
let node = CString::new("/dev/dri/renderD128").unwrap();
if ff::av_hwdevice_ctx_create(
&mut hw_device,
ff::AVHWDeviceType::AV_HWDEVICE_TYPE_VAAPI,
node.as_ptr(),
ptr::null_mut(),
0,
) < 0
{
return Err("av_hwdevice_ctx_create(VAAPI) failed".into());
}
let frames_ref = ff::av_hwframe_ctx_alloc(hw_device);
if frames_ref.is_null() {
ff::av_buffer_unref(&mut hw_device);
return Err("av_hwframe_ctx_alloc failed".into());
}
{
let fctx = (*frames_ref).data as *mut ff::AVHWFramesContext;
(*fctx).format = ff::AVPixelFormat::AV_PIX_FMT_VAAPI;
(*fctx).sw_format = ff::AVPixelFormat::AV_PIX_FMT_NV12;
(*fctx).width = width as i32;
(*fctx).height = height as i32;
(*fctx).initial_pool_size = 2;
}
if ff::av_hwframe_ctx_init(frames_ref) < 0 {
let mut fr = frames_ref;
ff::av_buffer_unref(&mut fr);
ff::av_buffer_unref(&mut hw_device);
return Err("av_hwframe_ctx_init failed".into());
}
let surf = ff::av_frame_alloc();
if ff::av_hwframe_get_buffer(frames_ref, surf, 0) < 0 {
ff::av_frame_free(&mut (surf as *mut _));
let mut fr = frames_ref;
ff::av_buffer_unref(&mut fr);
ff::av_buffer_unref(&mut hw_device);
return Err("av_hwframe_get_buffer failed".into());
}
let drm = ff::av_frame_alloc();
(*drm).format = ff::AVPixelFormat::AV_PIX_FMT_DRM_PRIME as i32;
let flags = ff::AV_HWFRAME_MAP_DIRECT as i32
| ff::AV_HWFRAME_MAP_READ as i32
| ff::AV_HWFRAME_MAP_WRITE as i32;
let r = ff::av_hwframe_map(drm, surf, flags);
if r < 0 {
ff::av_frame_free(&mut (drm as *mut _));
ff::av_frame_free(&mut (surf as *mut _));
let mut fr = frames_ref;
ff::av_buffer_unref(&mut fr);
ff::av_buffer_unref(&mut hw_device);
return Err(format!("av_hwframe_map(DRM_PRIME) failed: {r}"));
}
let desc = (*drm).data[0] as *const ff::AVDRMFrameDescriptor;
let mut s = format!("VAAPI NV12 {width}x{height} surface as DRM-PRIME:\n");
s += &format!(" nb_objects = {}\n", (*desc).nb_objects);
for o in 0..(*desc).nb_objects as usize {
let obj = &(*desc).objects[o];
s += &format!(
" object[{o}]: fd={} size={} format_modifier=0x{:016x}{}\n",
obj.fd,
obj.size,
obj.format_modifier,
if obj.format_modifier == 0 { " (LINEAR)" } else { " (tiled)" },
);
}
s += &format!(" nb_layers = {}\n", (*desc).nb_layers);
for l in 0..(*desc).nb_layers as usize {
let lay = &(*desc).layers[l];
let f = lay.format;
let fourcc = [(f & 0xff) as u8, ((f >> 8) & 0xff) as u8, ((f >> 16) & 0xff) as u8, ((f >> 24) & 0xff) as u8];
s += &format!(
" layer[{l}]: format='{}' (0x{:08x}) nb_planes={}\n",
String::from_utf8_lossy(&fourcc),
f,
lay.nb_planes,
);
for p in 0..lay.nb_planes as usize {
let pl = &lay.planes[p];
s += &format!(
" plane[{p}]: object_index={} offset={} pitch={}\n",
pl.object_index, pl.offset, pl.pitch,
);
}
}
ff::av_frame_free(&mut (drm as *mut _));
ff::av_frame_free(&mut (surf as *mut _));
let mut fr = frames_ref;
ff::av_buffer_unref(&mut fr);
ff::av_buffer_unref(&mut hw_device);
Ok(s)
}
}
/// Encode NV12 frames with `h264_vaapi` and write the raw Annex-B H.264 to `out_path`.
/// Returns the number of encoded packets. `Err` (rather than panic) when VAAPI/the
/// encoder is unavailable, so callers can fall back.
pub fn encode_nv12_to_file(
width: u32,
height: u32,
frames: &[Vec<u8>],
framerate: i32,
out_path: &str,
) -> Result<usize, String> {
unsafe {
// 1. VAAPI device.
let mut hw_device: *mut ff::AVBufferRef = ptr::null_mut();
let node = CString::new("/dev/dri/renderD128").unwrap();
let r = ff::av_hwdevice_ctx_create(
&mut hw_device,
ff::AVHWDeviceType::AV_HWDEVICE_TYPE_VAAPI,
node.as_ptr(),
ptr::null_mut(),
0,
);
if r < 0 {
return Err(format!("av_hwdevice_ctx_create(VAAPI) failed: {r}"));
}
let cleanup_dev = |dev: *mut ff::AVBufferRef| {
let mut d = dev;
ff::av_buffer_unref(&mut d);
};
// 2. Encoder.
let name = CString::new("h264_vaapi").unwrap();
let codec = ff::avcodec_find_encoder_by_name(name.as_ptr());
if codec.is_null() {
cleanup_dev(hw_device);
return Err("encoder h264_vaapi not found in this FFmpeg build".into());
}
let enc = ff::avcodec_alloc_context3(codec);
if enc.is_null() {
cleanup_dev(hw_device);
return Err("avcodec_alloc_context3 failed".into());
}
(*enc).width = width as i32;
(*enc).height = height as i32;
(*enc).time_base = ff::AVRational { num: 1, den: framerate };
(*enc).framerate = ff::AVRational { num: framerate, den: 1 };
(*enc).pix_fmt = ff::AVPixelFormat::AV_PIX_FMT_VAAPI;
// 3. HW frames context (VAAPI surfaces with NV12 sw layout).
let frames_ref = ff::av_hwframe_ctx_alloc(hw_device);
if frames_ref.is_null() {
ff::avcodec_free_context(&mut (enc as *mut _));
cleanup_dev(hw_device);
return Err("av_hwframe_ctx_alloc failed".into());
}
{
let fctx = (*frames_ref).data as *mut ff::AVHWFramesContext;
(*fctx).format = ff::AVPixelFormat::AV_PIX_FMT_VAAPI;
(*fctx).sw_format = ff::AVPixelFormat::AV_PIX_FMT_NV12;
(*fctx).width = width as i32;
(*fctx).height = height as i32;
(*fctx).initial_pool_size = 8;
}
let r = ff::av_hwframe_ctx_init(frames_ref);
if r < 0 {
let mut fr = frames_ref;
ff::av_buffer_unref(&mut fr);
ff::avcodec_free_context(&mut (enc as *mut _));
cleanup_dev(hw_device);
return Err(format!("av_hwframe_ctx_init failed: {r}"));
}
(*enc).hw_frames_ctx = ff::av_buffer_ref(frames_ref);
// 4. Open.
let r = ff::avcodec_open2(enc, codec, ptr::null_mut());
if r < 0 {
let mut fr = frames_ref;
ff::av_buffer_unref(&mut fr);
ff::avcodec_free_context(&mut (enc as *mut _));
cleanup_dev(hw_device);
return Err(format!("avcodec_open2(h264_vaapi) failed: {r}"));
}
let mut out: Vec<u8> = Vec::new();
let pkt = ff::av_packet_alloc();
let mut count = 0usize;
// Drain helper: pull packets and append to `out`.
let drain = |enc: *mut ff::AVCodecContext, out: &mut Vec<u8>, count: &mut usize| -> Result<(), String> {
loop {
let r = ff::avcodec_receive_packet(enc, pkt);
if r == averror(libc::EAGAIN) || r == ff::AVERROR_EOF {
break;
}
if r < 0 {
return Err(format!("avcodec_receive_packet failed: {r}"));
}
let data = std::slice::from_raw_parts((*pkt).data, (*pkt).size as usize);
out.extend_from_slice(data);
*count += 1;
ff::av_packet_unref(pkt);
}
Ok(())
};
let mut err: Option<String> = None;
for (i, nv12) in frames.iter().enumerate() {
// Software NV12 frame.
let sw = ff::av_frame_alloc();
(*sw).format = ff::AVPixelFormat::AV_PIX_FMT_NV12 as i32;
(*sw).width = width as i32;
(*sw).height = height as i32;
if ff::av_frame_get_buffer(sw, 0) < 0 {
err = Some("av_frame_get_buffer(sw) failed".into());
ff::av_frame_free(&mut (sw as *mut _));
break;
}
fill_nv12(sw, nv12, width, height);
// VAAPI surface frame + upload.
let hw = ff::av_frame_alloc();
if ff::av_hwframe_get_buffer(frames_ref, hw, 0) < 0 {
err = Some("av_hwframe_get_buffer failed".into());
ff::av_frame_free(&mut (sw as *mut _));
ff::av_frame_free(&mut (hw as *mut _));
break;
}
if ff::av_hwframe_transfer_data(hw, sw, 0) < 0 {
err = Some("av_hwframe_transfer_data failed".into());
ff::av_frame_free(&mut (sw as *mut _));
ff::av_frame_free(&mut (hw as *mut _));
break;
}
(*hw).pts = i as i64;
let r = ff::avcodec_send_frame(enc, hw);
ff::av_frame_free(&mut (sw as *mut _));
ff::av_frame_free(&mut (hw as *mut _));
if r < 0 {
err = Some(format!("avcodec_send_frame failed: {r}"));
break;
}
if let Err(e) = drain(enc, &mut out, &mut count) {
err = Some(e);
break;
}
}
// Flush.
if err.is_none() {
ff::avcodec_send_frame(enc, ptr::null_mut());
if let Err(e) = drain(enc, &mut out, &mut count) {
err = Some(e);
}
}
// Cleanup.
ff::av_packet_free(&mut (pkt as *mut _));
let mut fr = frames_ref;
ff::av_buffer_unref(&mut fr);
ff::avcodec_free_context(&mut (enc as *mut _));
cleanup_dev(hw_device);
if let Some(e) = err {
return Err(e);
}
std::fs::write(out_path, &out).map_err(|e| format!("write {out_path}: {e}"))?;
Ok(count)
}
}
@@ -0,0 +1,168 @@
//! Custom wgpu Vulkan device that additionally enables `VK_EXT_image_drm_format_modifier`
//! (plus the external-memory extensions wgpu-hal already turns on), so we can import a
//! tiled VAAPI NV12 DMA-BUF as a Vulkan image. wgpu's safe API can't add arbitrary device
//! extensions, so we build the `VkDevice` ourselves and wrap it via `device_from_raw`.
//!
//! All `unsafe` is contained here. Returns owned handles the caller must keep alive
//! together (instance → adapter → device/queue).
use ash::vk;
use std::ffi::CStr;
/// A wgpu device/queue backed by a hand-built Vulkan device with DMA-BUF import enabled.
pub struct DrmDevice {
// Order matters for drop; wgpu handles refcount internally but we keep these owned.
pub device: wgpu::Device,
pub queue: wgpu::Queue,
pub adapter: wgpu::Adapter,
pub instance: wgpu::Instance,
/// The raw VkDevice (for the ash image-import calls in `dmabuf.rs`).
pub raw_device: ash::Device,
pub raw_physical_device: vk::PhysicalDevice,
pub raw_instance: ash::Instance,
}
/// Create a headless DMA-BUF-import device (encoder/decoder), or `Err` if Vulkan/the extension
/// isn't available (caller falls back).
pub fn create() -> Result<DrmDevice, String> {
unsafe { create_inner(false) }
}
/// Like [`create`] but also enables `VK_KHR_swapchain` so the device can present to a window —
/// for use as the editor's **shared** wgpu device (eframe + compositor + decode + encode all on
/// one device, so hardware-decoded DMA-BUF textures are usable by the preview compositor).
pub fn create_windowed() -> Result<DrmDevice, String> {
unsafe { create_inner(true) }
}
unsafe fn create_inner(windowed: bool) -> Result<DrmDevice, String> {
use wgpu_hal::vulkan::Api as Vk;
// Bring the HAL Instance trait into scope for `init` / `enumerate_adapters`.
use wgpu_hal::Instance as _;
// 1. HAL instance.
let hal_instance = wgpu_hal::vulkan::Instance::init(&wgpu_hal::InstanceDescriptor {
name: "gpu-video-encoder",
flags: wgpu::InstanceFlags::empty(),
memory_budget_thresholds: Default::default(),
backend_options: Default::default(),
})
.map_err(|e| format!("vulkan instance init failed: {e:?}"))?;
let ash_instance = hal_instance.shared_instance().raw_instance().clone();
// 2. Pick an adapter (prefer the integrated/discrete GPU).
let mut exposed_adapters = hal_instance.enumerate_adapters(None);
if exposed_adapters.is_empty() {
return Err("no Vulkan adapters".into());
}
// Prefer a real GPU over CPU/llvmpipe.
exposed_adapters.sort_by_key(|a| match a.info.device_type {
wgpu::DeviceType::DiscreteGpu => 0,
wgpu::DeviceType::IntegratedGpu => 1,
_ => 2,
});
let exposed = exposed_adapters.into_iter().next().unwrap();
let phys = exposed.adapter.raw_physical_device();
// 3. Queue family with graphics + compute.
let qf_props = ash_instance.get_physical_device_queue_family_properties(phys);
let family_index = qf_props
.iter()
.position(|p| {
p.queue_flags
.contains(vk::QueueFlags::GRAPHICS | vk::QueueFlags::COMPUTE)
})
.ok_or("no graphics+compute queue family")? as u32;
// 4. Extensions: what wgpu-hal wants + DRM modifier import set.
let mut ext_names: Vec<&'static CStr> =
exposed.adapter.required_device_extensions(exposed.features);
// Only the genuine extensions; external_memory / bind_memory2 / ycbcr / format_list
// are core in Vulkan 1.1+ (this device is 1.3) so they need no enabling.
let mut extra: Vec<&'static CStr> = vec![
ash::ext::image_drm_format_modifier::NAME,
ash::khr::external_memory_fd::NAME,
ash::ext::external_memory_dma_buf::NAME,
ash::ext::queue_family_foreign::NAME,
];
// Presentation (windowed shared device only): the WSI surface instance extensions are already
// enabled by `Instance::init`; the device needs the swapchain extension to present.
if windowed {
extra.push(ash::khr::swapchain::NAME);
}
for e in extra {
if !ext_names.contains(&e) {
ext_names.push(e);
}
}
let ext_ptrs: Vec<*const i8> = ext_names.iter().map(|c| c.as_ptr()).collect();
// 5. Enable all supported physical-device features (so wgpu has what it needs) plus
// sampler YCbCr conversion (required for the NV12 multi-planar image).
let supported = ash_instance.get_physical_device_features(phys);
let mut ycbcr =
vk::PhysicalDeviceSamplerYcbcrConversionFeatures::default().sampler_ycbcr_conversion(true);
let priorities = [1.0f32];
let queue_info = vk::DeviceQueueCreateInfo::default()
.queue_family_index(family_index)
.queue_priorities(&priorities);
let queue_infos = [queue_info];
let create_info = vk::DeviceCreateInfo::default()
.queue_create_infos(&queue_infos)
.enabled_extension_names(&ext_ptrs)
.enabled_features(&supported)
.push_next(&mut ycbcr);
let ash_device = ash_instance
.create_device(phys, &create_info, None)
.map_err(|e| format!("vkCreateDevice failed: {e:?}"))?;
// 6. Wrap the raw device into a hal OpenDevice, then a wgpu device.
let open_device = exposed
.adapter
.device_from_raw(
ash_device.clone(),
None,
&ext_names,
exposed.features,
&wgpu::MemoryHints::default(),
family_index,
0,
)
.map_err(|e| format!("device_from_raw failed: {e:?}"))?;
let raw_physical_device = phys;
let wgpu_instance = wgpu::Instance::from_hal::<Vk>(hal_instance);
let wgpu_adapter = wgpu_instance.create_adapter_from_hal::<Vk>(exposed);
let (device, queue) = wgpu_adapter
.create_device_from_hal::<Vk>(
open_device,
&wgpu::DeviceDescriptor {
label: Some("drm-import-device"),
// R16/Rg16 plane textures for P010 (10-bit HDR) import need this; request it only
// when the adapter supports it (else 10-bit falls back to software decode).
required_features: wgpu_adapter.features()
& wgpu::Features::TEXTURE_FORMAT_16BIT_NORM,
// Vello's compute pipelines need more than downlevel limits (e.g.
// max_storage_buffers_per_shader_stage >= 5). This device only ever runs on a
// real VAAPI-capable GPU, so request the adapter's full limits.
required_limits: wgpu_adapter.limits(),
..Default::default()
},
)
.map_err(|e| format!("create_device_from_hal failed: {e:?}"))?;
Ok(DrmDevice {
device,
queue,
adapter: wgpu_adapter,
instance: wgpu_instance,
raw_device: ash_device,
raw_physical_device,
raw_instance: ash_instance,
})
}
@@ -0,0 +1,91 @@
//! Round-trip: encode solid frames with the zero-copy encoder, then hardware-decode them back
//! into a wgpu texture and read the Y plane. Verifies the VAAPI decode → DMA-BUF → wgpu import
//! path produces real pixels on the GPU. Skips when VAAPI is unavailable.
#![cfg(target_os = "linux")]
use gpu_video_encoder::decoder::VaapiDecoder;
use gpu_video_encoder::encoder::ZeroCopyEncoder;
#[test]
fn vaapi_decode_roundtrip() {
// 256-wide so the R8 Y readback row (256 B) is already 256-aligned.
let (w, h) = (256u32, 256u32);
let out = std::env::temp_dir().join("gpu_video_encoder_decode_rt.mp4");
let _ = std::fs::remove_file(&out);
// --- Encode 10 frames of solid mid-gray. Full range → Y == luma ≈ 128. ---
{
let mut enc = match ZeroCopyEncoder::new(w, h, 30, 4000, &out, true) {
Ok(e) => e,
Err(e) => {
eprintln!("[decode-rt] encode unavailable, skipping: {e}");
return;
}
};
let device = enc.device();
let src = device.create_texture(&wgpu::TextureDescriptor {
label: Some("gray"),
size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
let gray = vec![128u8; (w * h * 4) as usize];
enc.queue().write_texture(
wgpu::TexelCopyTextureInfo { texture: &src, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
&gray,
wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(w * 4), rows_per_image: Some(h) },
wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
);
for _ in 0..10 {
enc.encode_rgba(&src).expect("encode_rgba");
}
enc.finish().expect("finish");
}
// --- Decode it back on the GPU. ---
let mut dec = match VaapiDecoder::new(&out) {
Ok(d) => d,
Err(e) => {
eprintln!("[decode-rt] decode unavailable, skipping: {e}");
return;
}
};
let frame = dec.next_frame().expect("next_frame").expect("expected at least one frame");
assert_eq!(frame.y().width(), w, "decoded Y width");
assert_eq!(frame.y().height(), h, "decoded Y height");
// Read back the Y plane (R8) and check it's ≈ the gray we encoded.
let device = dec.device();
let buf = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("y_readback"),
size: (w * h) as u64,
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
mapped_at_creation: false,
});
let mut cmd = device.create_command_encoder(&Default::default());
cmd.copy_texture_to_buffer(
wgpu::TexelCopyTextureInfo { texture: frame.y(), mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
wgpu::TexelCopyBufferInfo {
buffer: &buf,
layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(w), rows_per_image: Some(h) },
},
wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
);
dec.queue().submit(Some(cmd.finish()));
buf.slice(..).map_async(wgpu::MapMode::Read, |_| {});
let _ = device.poll(wgpu::PollType::wait_indefinitely());
let data = buf.slice(..).get_mapped_range();
let mean = data.iter().map(|&b| b as f64).sum::<f64>() / data.len() as f64;
eprintln!("[decode-rt] decoded {w}x{h}, mean Y = {mean:.1}");
assert!(
(mean - 128.0).abs() < 12.0,
"mean Y {mean} not ≈ 128 — decode produced wrong pixels"
);
eprintln!("[decode-rt] ✅ VAAPI decode → wgpu texture verified");
}
@@ -0,0 +1,42 @@
//! Step 1 of zero-copy: the custom Vulkan device with DMA-BUF import extensions builds
//! and can do a trivial GPU op. Skips (passes) when Vulkan is unavailable.
#![cfg(target_os = "linux")]
#[test]
fn drm_device_creates_and_works() {
let dev = match gpu_video_encoder::vk_device::create() {
Ok(d) => d,
Err(e) => {
eprintln!("[drm-device] unavailable, skipping: {e}");
return;
}
};
eprintln!("[drm-device] created custom Vulkan device OK");
// Trivial sanity op: write+read a small buffer, proving the wrapped device is usable.
let data: Vec<u8> = (0..256u32).map(|i| i as u8).collect();
let src = wgpu::util::DeviceExt::create_buffer_init(
&dev.device,
&wgpu::util::BufferInitDescriptor {
label: Some("src"),
contents: &data,
usage: wgpu::BufferUsages::COPY_SRC,
},
);
let dst = dev.device.create_buffer(&wgpu::BufferDescriptor {
label: Some("dst"),
size: 256,
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
mapped_at_creation: false,
});
let mut enc = dev.device.create_command_encoder(&Default::default());
enc.copy_buffer_to_buffer(&src, 0, &dst, 0, 256);
dev.queue.submit(Some(enc.finish()));
let slice = dst.slice(..);
slice.map_async(wgpu::MapMode::Read, |_| {});
let _ = dev.device.poll(wgpu::PollType::wait_indefinitely());
let got = slice.get_mapped_range().to_vec();
assert_eq!(got, data, "round-trip through custom device failed");
eprintln!("[drm-device] buffer round-trip OK on custom device");
}
@@ -0,0 +1,117 @@
//! Real-hardware test: run the RGBA→NV12 compute on the GPU and check it byte-matches
//! the CPU reference. Skips (passes) if no GPU adapter is available.
use gpu_video_encoder::nv12::{cpu_reference, nv12_len, Nv12Converter};
fn device_queue() -> Option<(wgpu::Device, wgpu::Queue)> {
let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {
backends: wgpu::Backends::VULKAN | wgpu::Backends::GL,
..Default::default()
});
let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::HighPerformance,
force_fallback_adapter: false,
compatible_surface: None,
}))
.ok()?;
pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
label: Some("nv12-test"),
required_features: wgpu::Features::empty(),
required_limits: wgpu::Limits::downlevel_defaults(),
..Default::default()
}))
.ok()
}
/// A deterministic, varied RGBA pattern so luma and 2x2 chroma subsampling are exercised.
fn pattern(w: u32, h: u32) -> Vec<u8> {
let mut v = Vec::with_capacity((w * h * 4) as usize);
for y in 0..h {
for x in 0..w {
v.push(((x * 37 + y * 11) % 256) as u8); // R
v.push(((x * 5 + y * 53) % 256) as u8); // G
v.push(((x * 97 + y * 17) % 256) as u8); // B
v.push(255);
}
}
v
}
#[test]
fn gpu_nv12_matches_cpu_reference() {
let Some((device, queue)) = device_queue() else {
eprintln!("[gpu_nv12] no GPU adapter; skipping");
return;
};
let (w, h) = (64u32, 16u32);
let rgba = pattern(w, h);
// Source RGBA texture.
let tex = device.create_texture(&wgpu::TextureDescriptor {
label: Some("src_rgba"),
size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture: &tex,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
&rgba,
wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(w * 4), rows_per_image: Some(h) },
wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
);
let view = tex.create_view(&Default::default());
let len = nv12_len(w, h) as u64;
let out = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("nv12_out"),
size: len,
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
mapped_at_creation: false,
});
let staging = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("nv12_staging"),
size: len,
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
mapped_at_creation: false,
});
let conv = Nv12Converter::new(&device);
let mut enc = device.create_command_encoder(&Default::default());
conv.convert(&device, &mut enc, &view, &out, w, h);
enc.copy_buffer_to_buffer(&out, 0, &staging, 0, len);
queue.submit(Some(enc.finish()));
let slice = staging.slice(..);
slice.map_async(wgpu::MapMode::Read, |_| {});
let _ = device.poll(wgpu::PollType::wait_indefinitely());
let gpu = slice.get_mapped_range().to_vec();
let cpu = cpu_reference(&rgba, w, h);
assert_eq!(gpu.len(), cpu.len(), "length mismatch");
// Allow ±1 for rounding differences between GPU and CPU float paths.
let mut max_diff = 0i32;
let mut nbad = 0;
for (i, (g, c)) in gpu.iter().zip(cpu.iter()).enumerate() {
let d = (*g as i32 - *c as i32).abs();
max_diff = max_diff.max(d);
if d > 1 {
nbad += 1;
if nbad <= 8 {
eprintln!("[gpu_nv12] byte {i}: gpu={g} cpu={c} (diff {d})");
}
}
}
eprintln!("[gpu_nv12] {}x{} NV12, max byte diff = {max_diff}", w, h);
assert_eq!(nbad, 0, "{nbad} bytes differ from CPU reference by >1");
}
@@ -0,0 +1,66 @@
//! Level-1 spike: prove `h264_vaapi` encodes NV12 in this environment. Skips (passes)
//! when VAAPI isn't available so it's a no-op on CI/macOS/Windows.
#![cfg(target_os = "linux")]
use gpu_video_encoder::nv12::{cpu_reference, nv12_len};
use gpu_video_encoder::vaapi::encode_nv12_to_file;
/// A moving-gradient RGBA pattern → NV12 via the CPU reference, so we feed valid frames.
fn nv12_frames(w: u32, h: u32, n: usize) -> Vec<Vec<u8>> {
(0..n)
.map(|f| {
let mut rgba = Vec::with_capacity((w * h * 4) as usize);
for y in 0..h {
for x in 0..w {
rgba.push(((x + f as u32 * 4) % 256) as u8);
rgba.push(((y + f as u32 * 2) % 256) as u8);
rgba.push(((x + y) % 256) as u8);
rgba.push(255);
}
}
let v = cpu_reference(&rgba, w, h);
assert_eq!(v.len(), nv12_len(w, h));
v
})
.collect()
}
#[test]
fn vaapi_surface_drm_layout() {
match gpu_video_encoder::vaapi::probe_surface_drm(1920, 1088) {
Ok(s) => eprintln!("[vaapi-drm]\n{s}"),
Err(e) => eprintln!("[vaapi-drm] unavailable, skipping: {e}"),
}
}
#[test]
fn vaapi_h264_encode_smoke() {
let (w, h) = (320u32, 240u32);
let frames = nv12_frames(w, h, 30);
let out = std::env::temp_dir().join("gpu_video_encoder_vaapi_smoke.h264");
let out_str = out.to_str().unwrap();
match encode_nv12_to_file(w, h, &frames, 30, out_str) {
Ok(packets) => {
let meta = std::fs::metadata(&out).expect("output file missing");
eprintln!(
"[vaapi] encoded {} packets, {} bytes -> {}",
packets,
meta.len(),
out_str
);
assert!(packets > 0, "no packets produced");
assert!(meta.len() > 0, "empty output file");
// First frame should be an IDR; Annex-B starts with a start code.
let head = std::fs::read(&out).unwrap();
assert!(
head.starts_with(&[0, 0, 0, 1]) || head.starts_with(&[0, 0, 1]),
"output is not Annex-B H.264 (no start code)"
);
}
Err(e) => {
eprintln!("[vaapi] unavailable, skipping: {e}");
}
}
}
@@ -0,0 +1,169 @@
//! End-to-end zero-copy proof: import a VAAPI NV12 surface as wgpu textures, render
//! known values into them via Vulkan, read the surface back, and verify the bytes —
//! proving the GPU wrote straight into the encoder's surface with no CPU upload.
#![cfg(target_os = "linux")]
use gpu_video_encoder::{dmabuf, nv12, render_nv12, vaapi, vk_device};
/// Render a real RGBA frame into the VAAPI surface (zero-copy) and verify the surface's
/// NV12 matches the CPU reference for that frame.
#[test]
fn zerocopy_real_frame_render() {
let drm = match vk_device::create() {
Ok(d) => d,
Err(e) => {
eprintln!("[zerocopy-real] no Vulkan, skipping: {e}");
return;
}
};
let (w, h) = (640u32, 480u32);
let surf = match vaapi::MappedSurface::alloc(w, h) {
Ok(s) => s,
Err(e) => {
eprintln!("[zerocopy-real] no VAAPI, skipping: {e}");
return;
}
};
let imported = dmabuf::import(&drm, &surf).expect("import");
// A varied RGBA pattern.
let mut rgba = Vec::with_capacity((w * h * 4) as usize);
for y in 0..h {
for x in 0..w {
rgba.push(((x * 3 + y) % 256) as u8);
rgba.push(((x + y * 2) % 256) as u8);
rgba.push(((x * 2 + y * 3) % 256) as u8);
rgba.push(255);
}
}
let src = drm.device.create_texture(&wgpu::TextureDescriptor {
label: Some("rgba_src"),
size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
drm.queue.write_texture(
wgpu::TexelCopyTextureInfo { texture: &src, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
&rgba,
wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(w * 4), rows_per_image: Some(h) },
wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
);
let conv = render_nv12::Rgba2Nv12::new(&drm.device, true);
let src_view = src.create_view(&Default::default());
let y_view = imported.y().create_view(&Default::default());
let uv_view = imported.uv().create_view(&Default::default());
let mut enc = drm.device.create_command_encoder(&Default::default());
conv.convert(&drm.device, &mut enc, &src_view, &y_view, &uv_view);
drm.queue.submit(Some(enc.finish()));
let _ = drm.device.poll(wgpu::PollType::wait_indefinitely());
let got = surf.readback_nv12().expect("readback");
let want = nv12::cpu_reference(&rgba, w, h);
assert_eq!(got.len(), want.len());
let mut max_diff = 0i32;
let mut nbad = 0;
for (g, c) in got.iter().zip(want.iter()) {
let d = (*g as i32 - *c as i32).abs();
max_diff = max_diff.max(d);
if d > 2 {
nbad += 1;
}
}
eprintln!("[zerocopy-real] {}x{} real-frame render, max diff={max_diff}, bad={nbad}/{}", w, h, got.len());
assert!(nbad * 100 < got.len(), "too many bytes differ from CPU NV12 reference");
eprintln!("[zerocopy-real] ✅ real RGBA frame rendered into VAAPI surface, NV12 matches reference");
}
#[test]
fn zerocopy_render_into_vaapi_surface() {
let drm = match vk_device::create() {
Ok(d) => d,
Err(e) => {
eprintln!("[zerocopy] no Vulkan device, skipping: {e}");
return;
}
};
let surf = match vaapi::MappedSurface::alloc(640, 480) {
Ok(s) => s,
Err(e) => {
eprintln!("[zerocopy] no VAAPI surface, skipping: {e}");
return;
}
};
eprintln!(
"[zerocopy] surface: modifier=0x{:016x} y(off={},pitch={}) uv(off={},pitch={}) size={}",
surf.modifier, surf.y_offset, surf.y_pitch, surf.uv_offset, surf.uv_pitch, surf.size
);
let imported = match dmabuf::import(&drm, &surf) {
Ok(i) => i,
Err(e) => panic!("dma-buf import failed: {e}"),
};
eprintln!("[zerocopy] imported surface as wgpu Y(R8) + UV(RG8) textures");
// Render known constants via clear: Y=0.5(->128), U=0.25(->64), V=0.75(->191).
let y_view = imported.y().create_view(&Default::default());
let uv_view = imported.uv().create_view(&Default::default());
let mut enc = drm.device.create_command_encoder(&Default::default());
{
enc.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("clear-y"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &y_view,
resolve_target: None,
depth_slice: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color { r: 0.5, g: 0.0, b: 0.0, a: 0.0 }),
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
});
enc.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("clear-uv"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &uv_view,
resolve_target: None,
depth_slice: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color { r: 0.25, g: 0.75, b: 0.0, a: 0.0 }),
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
});
}
drm.queue.submit(Some(enc.finish()));
let _ = drm.device.poll(wgpu::PollType::wait_indefinitely());
// Read the VAAPI surface back and check what the GPU wrote.
let nv12 = surf.readback_nv12().expect("readback");
let (w, h) = (640usize, 480usize);
let y_plane = &nv12[..w * h];
let uv_plane = &nv12[w * h..];
let near = |v: u8, t: i32| (v as i32 - t).abs() <= 3;
let y_ok = y_plane.iter().filter(|&&v| near(v, 128)).count();
let u_ok = uv_plane.iter().step_by(2).filter(|&&v| near(v, 64)).count();
let v_ok = uv_plane.iter().skip(1).step_by(2).filter(|&&v| near(v, 191)).count();
eprintln!(
"[zerocopy] Y~128: {}/{}, U~64: {}/{}, V~191: {}/{}",
y_ok, w * h, u_ok, uv_plane.len() / 2, v_ok, uv_plane.len() / 2
);
let frac = |ok: usize, n: usize| ok as f64 / n as f64;
assert!(frac(y_ok, w * h) > 0.98, "Y plane not the rendered value (sample {:?})", &y_plane[..8]);
assert!(frac(u_ok, uv_plane.len() / 2) > 0.98, "U not rendered value");
assert!(frac(v_ok, uv_plane.len() / 2) > 0.98, "V not rendered value");
eprintln!("[zerocopy] ✅ GPU rendered straight into the VAAPI surface (verified via readback)");
}
@@ -0,0 +1,76 @@
//! Capstone: encode RGBA frames fully zero-copy (GPU render → VAAPI surface → h264_vaapi)
//! and verify the output is real H.264. Skips when VAAPI is unavailable.
#![cfg(target_os = "linux")]
use gpu_video_encoder::encoder::ZeroCopyEncoder;
#[test]
fn zerocopy_encode_h264() {
let (w, h) = (640u32, 480u32);
let out = std::env::temp_dir().join("gpu_video_encoder_zerocopy.mp4");
let _ = std::fs::remove_file(&out);
let mut enc = match ZeroCopyEncoder::new(w, h, 30, 4000, &out, false) {
Ok(e) => e,
Err(e) => {
eprintln!("[zc-encode] unavailable, skipping: {e}");
return;
}
};
// Build one reusable RGBA source texture; update it per frame with a moving pattern.
let device = enc.device();
let src = device.create_texture(&wgpu::TextureDescriptor {
label: Some("rgba"),
size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
let n = 30;
for f in 0..n {
let mut rgba = Vec::with_capacity((w * h * 4) as usize);
for y in 0..h {
for x in 0..w {
rgba.push(((x + f * 8) % 256) as u8);
rgba.push(((y + f * 4) % 256) as u8);
rgba.push(((x + y) % 256) as u8);
rgba.push(255);
}
}
enc.queue().write_texture(
wgpu::TexelCopyTextureInfo { texture: &src, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
&rgba,
wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(w * 4), rows_per_image: Some(h) },
wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
);
enc.encode_rgba(&src).expect("encode_rgba");
}
enc.finish().expect("finish");
let meta = std::fs::metadata(&out).expect("output .mp4 missing");
eprintln!("[zc-encode] {} frames -> {} bytes mp4 at {}", n, meta.len(), out.display());
assert!(meta.len() > 1000, "implausibly small output");
// ffprobe-verify the container: H.264 stream, right dims, ~n frames.
let o = std::process::Command::new("ffprobe")
.args([
"-hide_banner", "-v", "error", "-count_frames",
"-show_entries", "stream=codec_name,width,height,nb_read_frames",
"-of", "default=noprint_wrappers=1",
])
.arg(&out)
.output()
.expect("run ffprobe");
let s = String::from_utf8_lossy(&o.stdout);
eprintln!("[zc-encode] ffprobe:\n{s}");
assert!(s.contains("codec_name=h264"), "ffprobe didn't see H.264");
assert!(s.contains(&format!("width={w}")), "wrong width");
assert!(s.contains(&format!("height={h}")), "wrong height");
assert!(s.contains(&format!("nb_read_frames={n}")), "expected {n} frames");
eprintln!("[zc-encode] ✅ zero-copy H.264 mp4 encode verified");
}
+17 -1
View File
@@ -18,6 +18,12 @@ bytemuck = { version = "1.14", features = ["derive"] }
kurbo = { workspace = true }
vello = { workspace = true }
# Text layout/shaping (text layers)
parley = { workspace = true }
# Glyph outline extraction for lossless text→SVG export. Pinned to the version parley resolves
# (0.43) so glyph IDs / normalized coords from parley layouts match this outliner.
skrifa = "0.43"
# Image decoding for image fills
image = { workspace = true }
@@ -29,6 +35,8 @@ daw-backend = { path = "../../daw-backend" }
# Video decoding
ffmpeg-next = "8.0"
# AVIO-over-Read+Seek shim: decode packed video by streaming from the SQLite blob.
ffmpeg-blob-io = { path = "../../ffmpeg-blob-io" }
lru = "0.12"
# File I/O
@@ -36,6 +44,9 @@ zip = "0.6"
chrono = "0.4"
base64 = "0.21"
pathdiff = "0.2"
# .beam container: SQLite database file. `bundled` compiles SQLite from source
# (no system dependency); `blob` enables incremental blob I/O for streaming.
rusqlite = { version = "0.31", features = ["bundled", "blob"] }
# Audio encoding for embedded files
flacenc = "0.4" # For FLAC encoding (lossless)
@@ -66,5 +77,10 @@ windows-sys = { version = "0.60", features = [
"Win32_System_Memory",
] }
[dependencies.tiny-skia]
version = "0.11"
[dev-dependencies]
tiny-skia = "0.11"
# For the packed-video streaming integration test (blob -> AVIO -> ffmpeg Input).
ffmpeg-blob-io = { path = "../../ffmpeg-blob-io" }
ffmpeg-next = "8.0"
@@ -0,0 +1,14 @@
Bundled fonts for Lightningbeam text layers
===========================================
These are the Liberation fonts, used as the built-in serif / sans-serif / monospaced
families so text renders deterministically without depending on system fonts:
LiberationSans-Regular.ttf
LiberationSerif-Regular.ttf
LiberationMono-Regular.ttf
License: SIL Open Font License, Version 1.1.
Copyright (c) Red Hat, Inc., with Reserved Font Name "Liberation".
Full license text: https://openfontlicense.org/ (also distributed with the Liberation
fonts package as its OFL.txt / LICENSE).
@@ -37,18 +37,123 @@ pub struct BackendContext<'a> {
/// Audio engine controller (optional - may not be initialized)
pub audio_controller: Option<&'a mut daw_backend::EngineController>,
/// Mapping from document layer UUIDs to backend track IDs
/// Mapping from all document layer/clip/group UUIDs to backend track IDs.
/// Covers audio layers, MIDI layers, group layers, and vector clip metatracks.
pub layer_to_track_map: &'a HashMap<Uuid, daw_backend::TrackId>,
/// Mapping from document clip instance UUIDs to backend clip instance IDs
pub clip_instance_to_backend_map: &'a mut HashMap<Uuid, BackendClipInstanceId>,
/// Mapping from movie clip UUIDs to backend metatrack (group track) TrackIds
pub clip_to_metatrack_map: &'a HashMap<Uuid, daw_backend::TrackId>,
// Future: pub video_controller: Option<&'a mut VideoController>,
}
impl BackendContext<'_> {
/// Hand a clip instance to the audio engine and record it in the instance→backend map.
///
/// Take folders are resolved through the instance's `active_take`, so the backend gets whichever
/// take is selected. Returns the backend track and instance IDs, or `None` when there's nothing
/// to sync yet (a recording in progress, or an empty take folder).
///
/// Lives here rather than in any one action because more than one action needs it: adding an
/// instance, and switching a take folder's active take (which is a remove + re-add, there being
/// no in-place pool-swap command). Keeping one implementation keeps the trim/duration
/// conversions — the easy thing to get subtly wrong, since `trim_*` is SECONDS while
/// `timeline_*` is BEATS — from drifting between copies.
pub fn add_clip_instance(
&mut self,
document: &Document,
layer_id: &Uuid,
instance: &crate::clip::ClipInstance,
) -> Result<Option<(daw_backend::TrackId, BackendClipInstanceId)>, String> {
use crate::clip::ResolvedContent;
let clip = document
.get_audio_clip(&instance.clip_id)
.ok_or_else(|| format!("Audio clip {} not found", instance.clip_id))?;
let track_id = *self
.layer_to_track_map
.get(layer_id)
.ok_or_else(|| format!("Layer {} not mapped to backend track", layer_id))?;
let resolved = instance.resolve(clip);
let content = clip.content_duration();
let internal_start = instance.trim_start;
let internal_end = instance
.trim_end
.unwrap_or(daw_backend::ContentTime(content.native()));
let start_time = instance.timeline_start;
// How long the clip occupies the timeline, in BEATS. `effective_duration_beats` resolves the
// content window in the clip's own domain — beats content carries over directly, wall-clock
// content converts at the clip's position — so neither kind can be read as the other here.
let effective_duration = instance.effective_duration_beats(content, document.tempo_map());
let controller = self
.audio_controller
.as_mut()
.ok_or_else(|| "Audio controller not available".to_string())?;
let backend_id = match resolved {
ResolvedContent::Midi { midi_clip_id } => {
use daw_backend::command::{Query, QueryResponse};
// MIDI content time IS beats, so the trims carry straight over.
let midi_instance = daw_backend::MidiClipInstance::new(
0, // assigned by the backend
midi_clip_id,
daw_backend::Beats(internal_start.raw()),
daw_backend::Beats(internal_end.raw()),
start_time,
effective_duration,
);
match controller
.send_query(Query::AddMidiClipInstanceSync(track_id, midi_instance))?
{
QueryResponse::MidiClipInstanceAdded(Ok(id)) => BackendClipInstanceId::Midi(id),
QueryResponse::MidiClipInstanceAdded(Err(e)) => return Err(e),
_ => return Err("Unexpected query response".to_string()),
}
}
ResolvedContent::Audio { audio_pool_index } => {
// Sampled-audio content time is SECONDS; the backend's start/duration are BEATS.
let id = controller.add_audio_clip(
track_id,
audio_pool_index,
start_time,
effective_duration,
daw_backend::Seconds(internal_start.raw()),
);
BackendClipInstanceId::Audio(id)
}
// Nothing to sync until it has content.
ResolvedContent::Recording => return Ok(None),
};
self.clip_instance_to_backend_map
.insert(instance.id, backend_id);
Ok(Some((track_id, backend_id)))
}
/// Remove a clip instance's backend clip and drop it from the instance→backend map.
pub fn remove_clip_instance(
&mut self,
track_id: daw_backend::TrackId,
backend_id: BackendClipInstanceId,
instance_id: Uuid,
) {
if let Some(controller) = self.audio_controller.as_mut() {
match backend_id {
BackendClipInstanceId::Midi(id) => controller.remove_midi_clip(track_id, id),
BackendClipInstanceId::Audio(id) => controller.remove_audio_clip(track_id, id),
}
}
self.clip_instance_to_backend_map.remove(&instance_id);
}
}
/// Action trait for undo/redo operations
///
/// Each action must be able to execute (apply changes) and rollback (undo changes).
@@ -73,6 +178,15 @@ pub trait Action: Send {
/// Get a human-readable description of this action (for UI display)
fn description(&self) -> String;
/// For raster actions that store dirty-rect diffs: the `(layer_id, time)` of the
/// keyframe whose full pixels must be resident before `execute`/`rollback` can
/// apply the diff. The editor faults the frame in (synchronously) before undo/redo
/// so a paged-out clean frame is restored to its container state first. Non-raster
/// actions (and full-buffer ones) return `None`.
fn raster_resident_hint(&self) -> Option<(Uuid, f64)> {
None
}
/// Execute backend operations after document changes
///
/// Called AFTER execute() succeeds. If this returns an error, execute()
@@ -111,6 +225,28 @@ pub trait Action: Send {
fn midi_notes_after_rollback(&self) -> Option<(u32, &[(f64, u8, u8, f64)])> {
None
}
/// Return full MIDI event data (CC, pitch bend, etc.) reflecting the state after execute/redo.
/// Used to keep the frontend MIDI event cache in sync after undo/redo.
fn midi_events_after_execute(&self) -> Option<(u32, &[daw_backend::audio::midi::MidiEvent])> {
None
}
/// Return full MIDI event data reflecting the state after rollback/undo.
fn midi_events_after_rollback(&self) -> Option<(u32, &[daw_backend::audio::midi::MidiEvent])> {
None
}
/// Return MIDI event data for multiple clips after execute/redo (e.g. BPM change).
/// Each element is (midi_clip_id, events). Default: empty.
fn all_midi_events_after_execute(&self) -> Vec<(u32, Vec<daw_backend::audio::midi::MidiEvent>)> {
Vec::new()
}
/// Return MIDI event data for multiple clips after rollback/undo.
fn all_midi_events_after_rollback(&self) -> Vec<(u32, Vec<daw_backend::audio::midi::MidiEvent>)> {
Vec::new()
}
}
/// Action executor that wraps the document and manages undo/redo
@@ -207,6 +343,24 @@ impl ActionExecutor {
Ok(())
}
/// Register an action whose effect has **already been applied** to the document (and backend)
/// outside the executor — e.g. a recording, which streams its content into the document live
/// over time and can't be applied by a single synchronous `execute()`.
///
/// Unlike `execute`, this does NOT run `execute()`/`execute_backend()` (the effect is already
/// present). It clears the redo stack, bumps the epoch (so the document reads as modified), and
/// pushes the action so it becomes undoable: undo runs `rollback`/`rollback_backend` to remove
/// the content, redo runs `execute`/`execute_backend` to bring it back. The action must be
/// constructed already in its post-execute state (see e.g. `AddClipInstanceAction::already_applied`).
pub fn push_applied(&mut self, action: Box<dyn Action>) {
self.redo_stack.clear();
self.epoch = self.epoch.wrapping_add(1);
self.undo_stack.push(action);
if self.undo_stack.len() > self.max_undo_depth {
self.undo_stack.remove(0);
}
}
/// Undo the last action
///
/// Returns Ok(true) if an action was undone, Ok(false) if undo stack is empty,
@@ -218,6 +372,7 @@ impl ActionExecutor {
Ok(()) => {
// Move to redo stack
self.redo_stack.push(action);
self.epoch = self.epoch.wrapping_add(1);
Ok(true)
}
Err(e) => {
@@ -242,6 +397,7 @@ impl ActionExecutor {
Ok(()) => {
// Move back to undo stack
self.undo_stack.push(action);
self.epoch = self.epoch.wrapping_add(1);
Ok(true)
}
Err(e) => {
@@ -270,6 +426,18 @@ impl ActionExecutor {
self.undo_stack.last().map(|a| a.description())
}
/// `(layer_id, time)` of the raster keyframe the next undo needs resident, if any.
/// The editor faults it in before calling `undo()` so a paged-out clean frame is
/// restored to its container state, giving the diff a correct base to apply onto.
pub fn peek_undo_raster_hint(&self) -> Option<(Uuid, f64)> {
self.undo_stack.last().and_then(|a| a.raster_resident_hint())
}
/// `(layer_id, time)` of the raster keyframe the next redo needs resident, if any.
pub fn peek_redo_raster_hint(&self) -> Option<(Uuid, f64)> {
self.redo_stack.last().and_then(|a| a.raster_resident_hint())
}
/// Get MIDI cache data from the last action on the undo stack (after redo).
/// Returns the notes reflecting execute state.
pub fn last_undo_midi_notes(&self) -> Option<(u32, &[(f64, u8, u8, f64)])> {
@@ -282,6 +450,26 @@ impl ActionExecutor {
self.redo_stack.last().and_then(|a| a.midi_notes_after_rollback())
}
/// Get full MIDI event data from the last action on the undo stack (after redo).
pub fn last_undo_midi_events(&self) -> Option<(u32, &[daw_backend::audio::midi::MidiEvent])> {
self.undo_stack.last().and_then(|a| a.midi_events_after_execute())
}
/// Get full MIDI event data from the last action on the redo stack (after undo).
pub fn last_redo_midi_events(&self) -> Option<(u32, &[daw_backend::audio::midi::MidiEvent])> {
self.redo_stack.last().and_then(|a| a.midi_events_after_rollback())
}
/// Get multi-clip MIDI event data from the last undo stack action (after redo).
pub fn last_undo_all_midi_events(&self) -> Vec<(u32, Vec<daw_backend::audio::midi::MidiEvent>)> {
self.undo_stack.last().map(|a| a.all_midi_events_after_execute()).unwrap_or_default()
}
/// Get multi-clip MIDI event data from the last redo stack action (after undo).
pub fn last_redo_all_midi_events(&self) -> Vec<(u32, Vec<daw_backend::audio::midi::MidiEvent>)> {
self.redo_stack.last().map(|a| a.all_midi_events_after_rollback()).unwrap_or_default()
}
/// Get the description of the next action to redo
pub fn redo_description(&self) -> Option<String> {
self.redo_stack.last().map(|a| a.description())
@@ -383,6 +571,7 @@ impl ActionExecutor {
// Move to redo stack
self.redo_stack.push(action);
self.epoch = self.epoch.wrapping_add(1);
Ok(true)
} else {
@@ -420,6 +609,7 @@ impl ActionExecutor {
// Move back to undo stack
self.undo_stack.push(action);
self.epoch = self.epoch.wrapping_add(1);
Ok(true)
} else {
@@ -47,6 +47,31 @@ impl AddClipInstanceAction {
}
}
/// Construct the action in its **already-applied** state: the clip instance is already in the
/// document and its backend clip already exists (e.g. a finished recording). Pair with
/// `ActionExecutor::push_applied` so the recording becomes undoable without re-adding anything.
/// Undo will `rollback`/`rollback_backend` (removing the clip from doc + backend via the seeded
/// ids); redo re-adds it via the normal `execute`/`execute_backend` path.
pub fn already_applied(
layer_id: Uuid,
clip_instance: ClipInstance,
backend_track_id: daw_backend::TrackId,
backend_id: crate::action::BackendClipInstanceId,
) -> Self {
let (backend_midi_instance_id, backend_audio_instance_id) = match backend_id {
crate::action::BackendClipInstanceId::Midi(id) => (Some(id), None),
crate::action::BackendClipInstanceId::Audio(id) => (None, Some(id)),
};
Self {
layer_id,
clip_instance,
executed: true, // already present in the document
backend_track_id: Some(backend_track_id),
backend_midi_instance_id,
backend_audio_instance_id,
}
}
/// Get the ID of the clip instance that will be/was added
pub fn clip_instance_id(&self) -> Uuid {
self.clip_instance.id
@@ -60,13 +85,15 @@ impl AddClipInstanceAction {
impl Action for AddClipInstanceAction {
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
// Calculate the clip's effective duration
let clip_duration = document.get_clip_duration(&self.clip_instance.clip_id)
// Calculate the clip's effective duration in BEATS for overlap testing.
// `get_clip_duration` is the content length in seconds; the placement span
// must be beats (the timeline is beats-domain), so convert via the clip's
// typed helper rather than treating the seconds span as beats.
// The clip's content duration in ITS OWN domain, so the trims resolve correctly for MIDI.
let clip_content = document.clip_trim_duration(&self.clip_instance.clip_id)
.ok_or_else(|| format!("Clip {} not found", self.clip_instance.clip_id))?;
let trim_start = self.clip_instance.trim_start;
let trim_end = self.clip_instance.trim_end.unwrap_or(clip_duration);
let effective_duration = trim_end - trim_start;
let effective_duration = self.clip_instance
.effective_duration_beats(clip_content, document.tempo_map());
// Auto-adjust position for audio/video layers to avoid overlaps
let adjusted_start = document.find_nearest_valid_position(
@@ -104,7 +131,7 @@ impl Action for AddClipInstanceAction {
AnyLayer::Group(_) => {
return Err("Cannot add clip instances directly to group layers".to_string());
}
AnyLayer::Raster(_) => {
AnyLayer::Raster(_) | AnyLayer::Text(_) => {
return Err("Cannot add clip instances directly to group layers".to_string());
}
}
@@ -145,8 +172,8 @@ impl Action for AddClipInstanceAction {
AnyLayer::Group(_) => {
// Group layers don't have clip instances, nothing to rollback
}
AnyLayer::Raster(_) => {
// Raster layers don't have clip instances, nothing to rollback
AnyLayer::Raster(_) | AnyLayer::Text(_) => {
// Raster/text layers don't have clip instances, nothing to rollback
}
}
self.executed = false;
@@ -170,105 +197,23 @@ impl Action for AddClipInstanceAction {
return Ok(());
}
// Look up the clip from the document
let clip = document
.get_audio_clip(&self.clip_instance.clip_id)
.ok_or_else(|| "Audio clip not found".to_string())?;
// Look up backend track ID from layer mapping
let backend_track_id = backend
.layer_to_track_map
.get(&self.layer_id)
.ok_or_else(|| format!("Layer {} not mapped to backend track", self.layer_id))?;
// Get audio controller
let controller = backend
.audio_controller
.as_mut()
.ok_or_else(|| "Audio controller not available".to_string())?;
// Handle different clip types
use crate::clip::AudioClipType;
match &clip.clip_type {
AudioClipType::Midi { midi_clip_id } => {
// Create a MIDI clip instance referencing the existing clip in the backend pool
// No need to add to pool again - it was added during MIDI import
use daw_backend::command::{Query, QueryResponse};
// Calculate internal start/end from trim parameters
let internal_start = self.clip_instance.trim_start;
let internal_end = self.clip_instance.trim_end.unwrap_or(clip.duration);
let external_start = self.clip_instance.timeline_start;
// Calculate external duration (for looping if timeline_duration is set)
let external_duration = self.clip_instance.timeline_duration
.unwrap_or(internal_end - internal_start);
// Create MidiClipInstance
let instance = daw_backend::MidiClipInstance::new(
0, // Instance ID will be assigned by backend
*midi_clip_id,
internal_start,
internal_end,
external_start,
external_duration,
);
// Send query to add instance and get instance ID
let query = Query::AddMidiClipInstanceSync(*backend_track_id, instance);
match controller.send_query(query)? {
QueryResponse::MidiClipInstanceAdded(Ok(instance_id)) => {
self.backend_track_id = Some(*backend_track_id);
self.backend_midi_instance_id = Some(instance_id);
// Add to global clip instance mapping
backend.clip_instance_to_backend_map.insert(
self.clip_instance.id,
crate::action::BackendClipInstanceId::Midi(instance_id)
);
Ok(())
}
QueryResponse::MidiClipInstanceAdded(Err(e)) => Err(e),
_ => Err("Unexpected query response".to_string()),
// Add via the shared BackendContext helper — the same one SetActiveTakeAction uses, so
// the trim/duration conversions (and take-folder resolution) live in exactly one place.
if let Some((track_id, backend_id)) =
backend.add_clip_instance(document, &self.layer_id, &self.clip_instance)?
{
self.backend_track_id = Some(track_id);
match backend_id {
crate::action::BackendClipInstanceId::Midi(id) => {
self.backend_midi_instance_id = Some(id)
}
}
AudioClipType::Sampled { audio_pool_index } => {
// For sampled audio, send AddAudioClipSync query
use daw_backend::command::{Query, QueryResponse};
let internal_start = self.clip_instance.trim_start;
let internal_end = self.clip_instance.trim_end.unwrap_or(clip.duration);
let effective_duration = self.clip_instance.timeline_duration
.unwrap_or(internal_end - internal_start);
let start_time = self.clip_instance.timeline_start;
let query =
Query::AddAudioClipSync(*backend_track_id, *audio_pool_index, start_time, effective_duration, internal_start);
match controller.send_query(query)? {
QueryResponse::AudioClipInstanceAdded(Ok(instance_id)) => {
self.backend_track_id = Some(*backend_track_id);
self.backend_audio_instance_id = Some(instance_id);
// Add to global clip instance mapping
backend.clip_instance_to_backend_map.insert(
self.clip_instance.id,
crate::action::BackendClipInstanceId::Audio(instance_id)
);
Ok(())
}
QueryResponse::AudioClipInstanceAdded(Err(e)) => Err(e),
_ => Err("Unexpected query response".to_string()),
crate::action::BackendClipInstanceId::Audio(id) => {
self.backend_audio_instance_id = Some(id)
}
}
AudioClipType::Recording => {
// Recording clips are not synced to backend until finalized
Ok(())
}
}
Ok(())
}
fn rollback_backend(&mut self, backend: &mut BackendContext, _document: &Document) -> Result<(), String> {
@@ -309,8 +254,11 @@ mod tests {
let layer_id = layer.layer.id;
document.root_mut().add_child(AnyLayer::Vector(layer));
// Create a clip instance (using a fake clip_id since we're just testing the action)
// Register a vector clip so get_clip_duration succeeds
let clip_id = Uuid::new_v4();
let clip = crate::clip::VectorClip::with_id(clip_id, "Test Clip", 100.0, 100.0, 5.0);
document.vector_clips.insert(clip_id, clip);
let clip_instance = ClipInstance::new(clip_id);
let instance_id = clip_instance.id;
@@ -159,7 +159,7 @@ mod tests {
fn test_add_effect() {
let (mut document, layer_id, def) = create_test_setup();
let instance = def.create_instance(0.0, 10.0);
let instance = def.create_instance(daw_backend::Beats(0.0), daw_backend::Beats(10.0));
let instance_id = instance.id;
let mut action = AddEffectAction::new(layer_id, instance);
@@ -181,7 +181,7 @@ mod tests {
fn test_add_effect_rollback() {
let (mut document, layer_id, def) = create_test_setup();
let instance = def.create_instance(0.0, 10.0);
let instance = def.create_instance(daw_backend::Beats(0.0), daw_backend::Beats(10.0));
let mut action = AddEffectAction::new(layer_id, instance);
action.execute(&mut document).unwrap();
@@ -201,19 +201,19 @@ mod tests {
let (mut document, layer_id, def) = create_test_setup();
// Add first effect
let instance1 = def.create_instance(0.0, 10.0);
let instance1 = def.create_instance(daw_backend::Beats(0.0), daw_backend::Beats(10.0));
let id1 = instance1.id;
let mut action1 = AddEffectAction::new(layer_id, instance1);
action1.execute(&mut document).unwrap();
// Add second effect
let instance2 = def.create_instance(0.0, 10.0);
let instance2 = def.create_instance(daw_backend::Beats(0.0), daw_backend::Beats(10.0));
let id2 = instance2.id;
let mut action2 = AddEffectAction::new(layer_id, instance2);
action2.execute(&mut document).unwrap();
// Insert third effect at index 1 (between first and second)
let instance3 = def.create_instance(0.0, 10.0);
let instance3 = def.create_instance(daw_backend::Beats(0.0), daw_backend::Beats(10.0));
let id3 = instance3.id;
let mut action3 = AddEffectAction::at_index(layer_id, instance3, 1);
action3.execute(&mut document).unwrap();
@@ -138,6 +138,7 @@ impl Action for AddLayerAction {
AnyLayer::Effect(_) => "Add effect layer",
AnyLayer::Group(_) => "Add group layer",
AnyLayer::Raster(_) => "Add raster layer",
AnyLayer::Text(_) => "Add text layer",
}
.to_string()
}
@@ -0,0 +1,52 @@
//! Add a blank raster keyframe at the playhead (the explicit "New Keyframe" command
//! for raster layers — mirrors `SetKeyframeAction` for vector, but inserts an empty
//! cel rather than copying the current graph).
use crate::action::Action;
use crate::document::Document;
use crate::layer::AnyLayer;
use uuid::Uuid;
pub struct AddRasterKeyframeAction {
layer_id: Uuid,
time: f64,
width: u32,
height: u32,
/// Id of the keyframe created by the last `execute` (so `rollback` can remove
/// exactly that one). `None` if a keyframe already existed at `time` (no-op).
created_id: Option<Uuid>,
}
impl AddRasterKeyframeAction {
pub fn new(layer_id: Uuid, time: f64, width: u32, height: u32) -> Self {
Self { layer_id, time, width, height, created_id: None }
}
}
impl Action for AddRasterKeyframeAction {
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
let layer = document
.get_layer_mut(&self.layer_id)
.ok_or_else(|| format!("Layer {} not found", self.layer_id))?;
let rl = match layer {
AnyLayer::Raster(rl) => rl,
_ => return Err("Not a raster layer".to_string()),
};
// Inserts a blank cel only if one doesn't already exist at this time.
self.created_id = rl.insert_blank_keyframe_at(self.time, self.width, self.height);
Ok(())
}
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
if let Some(id) = self.created_id.take() {
if let Some(AnyLayer::Raster(rl)) = document.get_layer_mut(&self.layer_id) {
rl.remove_keyframe(id);
}
}
Ok(())
}
fn description(&self) -> String {
"New keyframe".to_string()
}
}
@@ -1,17 +1,20 @@
//! Add shape action — inserts strokes into the DCEL.
//! Add shape action — inserts strokes into the VectorGraph.
//!
//! Converts a BezPath into cubic segments and inserts them via
//! `Dcel::insert_stroke()`. Undo is handled by snapshotting the DCEL.
//! `VectorGraph::insert_stroke()`. Undo is handled by snapshotting the graph.
use crate::action::Action;
use crate::dcel::{bezpath_to_cubic_segments, Dcel, FaceId, DEFAULT_SNAP_EPSILON};
use crate::vector_graph::bezpath_to_cubic_segments;
use crate::document::Document;
use crate::layer::AnyLayer;
use crate::shape::{ShapeColor, StrokeStyle};
use kurbo::BezPath;
use crate::shape::{FillRule, ShapeColor, StrokeStyle};
use crate::vector_graph::VectorGraph;
use kurbo::{BezPath, Shape as _};
use uuid::Uuid;
/// Action that inserts a drawn path into a vector layer's DCEL keyframe.
const DEFAULT_SNAP_EPSILON: f64 = 0.5;
/// Action that inserts a drawn path into a vector layer's VectorGraph keyframe.
pub struct AddShapeAction {
layer_id: Uuid,
time: f64,
@@ -20,9 +23,12 @@ pub struct AddShapeAction {
stroke_color: Option<ShapeColor>,
fill_color: Option<ShapeColor>,
is_closed: bool,
/// When set, the enclosed region is filled with this image asset (instead of a
/// solid colour). The renderer prioritises `image_fill` over colour/gradient.
image_fill: Option<Uuid>,
description_text: String,
/// Snapshot of the DCEL before insertion (for undo).
dcel_before: Option<Dcel>,
/// Snapshot of the graph before insertion (for undo).
graph_before: Option<VectorGraph>,
}
impl AddShapeAction {
@@ -43,8 +49,40 @@ impl AddShapeAction {
stroke_color,
fill_color,
is_closed,
image_fill: None,
description_text: "Add shape".to_string(),
dcel_before: None,
graph_before: None,
}
}
/// A borderless, axis-aligned rectangle filled with an image asset — the result
/// of importing/dropping an image onto a vector layer.
pub fn image_rect(
layer_id: Uuid,
time: f64,
x: f64,
y: f64,
w: f64,
h: f64,
asset_id: Uuid,
) -> Self {
let mut path = BezPath::new();
path.move_to((x, y));
path.line_to((x + w, y));
path.line_to((x + w, y + h));
path.line_to((x, y + h));
path.close_path();
Self {
layer_id,
time,
path,
stroke_style: None, // invisible edges — just the image
stroke_color: None,
fill_color: None,
is_closed: true,
image_fill: Some(asset_id),
description_text: "Add image".to_string(),
graph_before: None,
}
}
@@ -52,6 +90,12 @@ impl AddShapeAction {
self.description_text = desc.into();
self
}
/// Fill the created region with an image asset (image takes render priority).
pub fn with_image_fill(mut self, asset_id: Uuid) -> Self {
self.image_fill = Some(asset_id);
self
}
}
impl Action for AddShapeAction {
@@ -66,10 +110,10 @@ impl Action for AddShapeAction {
};
let keyframe = vl.ensure_keyframe_at(self.time);
let dcel = &mut keyframe.dcel;
let graph = &mut keyframe.graph;
// Snapshot for undo
self.dcel_before = Some(dcel.clone());
self.graph_before = Some(graph.clone());
let subpaths = bezpath_to_cubic_segments(&self.path);
@@ -77,41 +121,36 @@ impl Action for AddShapeAction {
if segments.is_empty() {
continue;
}
let result = dcel.insert_stroke(
let _new_edges = graph.insert_stroke(
segments,
self.stroke_style.clone(),
self.stroke_color.clone(),
DEFAULT_SNAP_EPSILON,
);
// Apply fill to new faces if this is a closed shape with fill
if self.is_closed {
if let Some(ref fill) = self.fill_color {
if !result.new_faces.is_empty() {
for face_id in &result.new_faces {
dcel.face_mut(*face_id).fill_color = Some(fill.clone());
}
} else if let Some(&first_edge) = result.new_edges.first() {
// Closed shape in F0 — no face was auto-created.
// One half-edge of the first new edge is on the interior cycle.
// Pick the side with positive signed area (CCW winding).
let [he_a, he_b] = dcel.edge(first_edge).half_edges;
let interior_he = if dcel.cycle_signed_area(he_a) > 0.0 {
he_a
} else {
he_b
};
if dcel.half_edge(interior_he).face == FaceId(0) {
let face_id = dcel.create_face_at_cycle(interior_he);
dcel.face_mut(face_id).fill_color = Some(fill.clone());
// Apply fill if this is a closed shape with a colour and/or image fill.
if self.is_closed && (self.fill_color.is_some() || self.image_fill.is_some()) {
// Compute centroid of the path's bounding box and paint-bucket fill.
let bbox = self.path.bounding_box();
let centroid = kurbo::Point::new(
(bbox.x0 + bbox.x1) / 2.0,
(bbox.y0 + bbox.y1) / 2.0,
);
// paint_bucket needs a colour; an image-only fill uses a placeholder
// that the image overrides (cleared below).
let color = self.fill_color.clone().unwrap_or_else(|| ShapeColor::rgba(255, 255, 255, 255));
if let Some(fid) = graph.paint_bucket(centroid, color, FillRule::NonZero, 0.0) {
if let Some(asset_id) = self.image_fill {
let fill = graph.fill_mut(fid);
fill.image_fill = Some(asset_id);
if self.fill_color.is_none() {
fill.color = None; // image-only: don't double-paint a colour
}
}
}
}
}
dcel.rebuild_spatial_index();
Ok(())
}
@@ -126,10 +165,10 @@ impl Action for AddShapeAction {
};
let keyframe = vl.ensure_keyframe_at(self.time);
keyframe.dcel = self
.dcel_before
keyframe.graph = self
.graph_before
.take()
.ok_or_else(|| "No DCEL snapshot for undo".to_string())?;
.ok_or_else(|| "No graph snapshot for undo".to_string())?;
Ok(())
}
@@ -0,0 +1,141 @@
//! Append freshly-recorded takes to an existing take folder.
//!
//! Cycle-recording over a region that already holds a take folder should *add* to that folder, not
//! drop a second clip on top of it. Otherwise the takes from your second attempt are stranded in a
//! separate, overlapping clip and you can't audition them against the first.
//!
//! The recorded content already exists in the backend pools by the time this runs (the engine put it
//! there at stop), so this action only touches the document — plus the one backend clip the instance
//! plays, which has to be repointed at the newly-active take.
use crate::action::{Action, BackendClipInstanceId, BackendContext};
use crate::clip::AudioTake;
use crate::document::Document;
use crate::layer::AnyLayer;
use uuid::Uuid;
/// Action that appends takes to an instance's take list and selects the last of them.
pub struct AppendTakesAction {
layer_id: Uuid,
/// The instance whose take list is being extended (and whose active take changes).
instance_id: Uuid,
/// The takes to add, in recording order.
new_takes: Vec<AudioTake>,
// Stored during execute for rollback.
old_take_count: usize,
old_active_take: Option<usize>,
executed: bool,
}
impl AppendTakesAction {
pub fn new(layer_id: Uuid, instance_id: Uuid, new_takes: Vec<AudioTake>) -> Self {
Self {
layer_id,
instance_id,
new_takes,
old_take_count: 0,
old_active_take: None,
executed: false,
}
}
/// Swap the instance's backend clip to whatever take the document now says is active.
///
/// Same remove + re-add as `SetActiveTakeAction` — there's no in-place pool-swap command.
fn resync(&self, backend: &mut BackendContext, document: &Document) -> Result<(), String> {
let instance = document
.get_layer(&self.layer_id)
.and_then(|l| match l {
AnyLayer::Audio(al) => al.clip_instances.iter().find(|ci| ci.id == self.instance_id),
_ => None,
})
.cloned()
.ok_or_else(|| format!("Clip instance {} not found", self.instance_id))?;
let existing: Option<BackendClipInstanceId> = backend
.clip_instance_to_backend_map
.get(&self.instance_id)
.copied();
let track_id = backend.layer_to_track_map.get(&self.layer_id).copied();
if let (Some(backend_id), Some(track_id)) = (existing, track_id) {
backend.remove_clip_instance(track_id, backend_id, self.instance_id);
}
backend.add_clip_instance(document, &self.layer_id, &instance)?;
Ok(())
}
}
impl Action for AppendTakesAction {
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
let layer = document
.get_layer_mut(&self.layer_id)
.ok_or_else(|| format!("Layer {} not found", self.layer_id))?;
let AnyLayer::Audio(audio_layer) = layer else {
return Err("Takes only exist on audio layers".to_string());
};
let instance = audio_layer
.clip_instances
.iter_mut()
.find(|ci| ci.id == self.instance_id)
.ok_or_else(|| format!("Clip instance {} not found", self.instance_id))?;
// Only record the pre-state on the first execute; a redo must not overwrite it with the
// post-state left behind by the previous run.
if !self.executed {
self.old_take_count = instance.takes.len();
self.old_active_take = instance.active_take;
}
// Number the new takes on from what's already there. Existing names are left alone — the
// user may well have renamed them, and renumbering would clobber that.
let base = instance.takes.len();
for (i, take) in self.new_takes.iter().enumerate() {
let mut take = take.clone();
if take.name.is_empty() {
take.name = format!("Take {}", base + i + 1);
}
instance.takes.push(take);
}
// Land on the take just recorded, GarageBand-style.
instance.active_take = Some(instance.takes.len() - 1);
self.executed = true;
Ok(())
}
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
if let Some(AnyLayer::Audio(audio_layer)) = document.get_layer_mut(&self.layer_id) {
if let Some(instance) = audio_layer
.clip_instances
.iter_mut()
.find(|ci| ci.id == self.instance_id)
{
instance.takes.truncate(self.old_take_count);
instance.active_take = self.old_active_take;
}
}
Ok(())
}
fn description(&self) -> String {
format!("Record {} take(s)", self.new_takes.len())
}
fn execute_backend(
&mut self,
backend: &mut BackendContext,
document: &Document,
) -> Result<(), String> {
self.resync(backend, document)
}
fn rollback_backend(
&mut self,
backend: &mut BackendContext,
document: &Document,
) -> Result<(), String> {
self.resync(backend, document)
}
}
@@ -0,0 +1,77 @@
//! Change BPM / Tempo action
//!
//! Atomically swaps the document `TempoMap`, sending the new map to the engine.
//! All clip and note positions are stored in **beats** so no position rescaling
//! is required — only the TempoMap entry changes.
use crate::action::{Action, BackendContext};
use crate::document::Document;
use crate::tempo_map::TempoMap;
/// Action that changes the global BPM by replacing the tempo map.
#[derive(Clone)]
pub struct ChangeBpmAction {
old_map: TempoMap,
new_map: TempoMap,
}
impl ChangeBpmAction {
/// Build the action from the current document state and a desired new BPM.
pub fn new(new_bpm: f64, document: &Document) -> Self {
let old_map = document.tempo_map().clone();
let mut new_map = old_map.clone();
new_map.set_global_bpm(new_bpm);
Self { old_map, new_map }
}
/// Build from explicit old/new maps (used when the map already changed in-place,
/// e.g., after live drag preview; the caller provides start and end states).
pub fn from_maps(old_map: TempoMap, new_map: TempoMap) -> Self {
Self { old_map, new_map }
}
pub fn new_bpm(&self) -> f64 { self.new_map.global_bpm() }
pub fn old_bpm(&self) -> f64 { self.old_map.global_bpm() }
}
impl Action for ChangeBpmAction {
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
*document.tempo_map_mut() = self.new_map.clone();
Ok(())
}
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
*document.tempo_map_mut() = self.old_map.clone();
Ok(())
}
fn description(&self) -> String {
"Change BPM".to_string()
}
fn execute_backend(
&mut self,
backend: &mut BackendContext,
_document: &Document,
) -> Result<(), String> {
let controller = match backend.audio_controller.as_mut() {
Some(c) => c,
None => return Ok(()),
};
controller.set_tempo_map(self.new_map.clone());
Ok(())
}
fn rollback_backend(
&mut self,
backend: &mut BackendContext,
_document: &Document,
) -> Result<(), String> {
let controller = match backend.audio_controller.as_mut() {
Some(c) => c,
None => return Ok(()),
};
controller.set_tempo_map(self.old_map.clone());
Ok(())
}
}
@@ -0,0 +1,54 @@
//! Change FPS action
//!
//! Atomically changes the document framerate.
//! All clip positions are stored in **beats** so no position rescaling is
//! required — only the framerate field changes.
use crate::action::{Action, BackendContext};
use crate::document::Document;
/// Action that changes the document framerate.
pub struct ChangeFpsAction {
old_fps: f64,
new_fps: f64,
}
impl ChangeFpsAction {
/// Build the action from old and new framerates.
pub fn new(old_fps: f64, new_fps: f64, _document: &Document) -> Self {
Self { old_fps, new_fps }
}
}
impl Action for ChangeFpsAction {
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
document.framerate = self.new_fps;
Ok(())
}
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
document.framerate = self.old_fps;
Ok(())
}
fn description(&self) -> String {
"Change FPS".to_string()
}
fn execute_backend(
&mut self,
_backend: &mut BackendContext,
_document: &Document,
) -> Result<(), String> {
// FPS does not affect audio scheduling — nothing to do in the backend.
Ok(())
}
fn rollback_backend(
&mut self,
_backend: &mut BackendContext,
_document: &Document,
) -> Result<(), String> {
Ok(())
}
}
@@ -0,0 +1,126 @@
//! Shared logic for the "Group" and "Convert to Movie Clip" actions: extract the
//! selected DCEL geometry from a vector layer's active keyframe into a new `VectorClip`
//! and drop a `ClipInstance` in its place (so it can then be motion-tweened).
//!
//! A *group* (`is_group = true`) is a static container; a *movie clip* (`is_group =
//! false`) has its own timeline. Both are tweenable via the clip instance's transform.
//!
//! Both the Select tool and the (cut-and-select) RegionSelect tool populate the same
//! `Selection` ID sets, so a single entry point — [`extract_geometry_to_clip`] — handles
//! Group and Convert-to-Movie-Clip from whatever is selected.
use std::collections::HashSet;
use crate::clip::{ClipInstance, VectorClip};
use crate::document::Document;
use crate::layer::{AnyLayer, ShapeKeyframe, VectorLayer};
use crate::object::Transform;
use crate::vector_graph::{EdgeId, FillId, VectorGraph};
use uuid::Uuid;
/// Build a clip holding `sub_graph` and place a `ClipInstance` (with `transform`) on the
/// layer. Shared by both extraction paths. Does **not** touch the source graph — the
/// caller is responsible for having removed the moved geometry first.
fn assemble_clip_from_graph(
document: &mut Document,
layer_id: Uuid,
time: f64,
sub_graph: VectorGraph,
transform: Transform,
clip_id: Uuid,
instance_id: Uuid,
is_group: bool,
clip_name: &str,
) {
let (doc_w, doc_h, doc_dur) = (document.width, document.height, document.duration.max(1.0));
// A vector layer whose single keyframe holds the extracted graph (in the source's
// coordinate space, so an identity/translation placement renders it in place).
let mut inner = VectorLayer::new("Layer 1");
let mut kf = ShapeKeyframe::new(0.0);
kf.graph = sub_graph;
inner.keyframes.push(kf);
let mut clip = VectorClip::with_id(clip_id, clip_name, doc_w, doc_h, doc_dur);
clip.is_group = is_group;
clip.layers.add_root(AnyLayer::Vector(inner));
document.add_vector_clip(clip);
let mut instance = ClipInstance::with_id(instance_id, clip_id);
instance.transform = transform;
if let Some(AnyLayer::Vector(vl)) = document.get_layer_mut(&layer_id) {
// Groups gate visibility by the active keyframe's clip_instance_ids; movie
// clips render unconditionally.
if is_group {
if let Some(kf) = vl.keyframe_at_mut(time) {
kf.clip_instance_ids.push(instance_id);
}
}
vl.clip_instances.push(instance);
}
}
/// Extract the selected geometry into a new clip + place a `ClipInstance`. Returns the
/// pre-extraction graph snapshot for undo. `clip_id`/`instance_id` are caller-provided
/// so undo/redo is stable. The selection sets come straight from the editor selection
/// (`select_fill` already includes each fill's boundary edges); `extract_subgraph`
/// derives which of those edges are shared with non-selected shapes.
pub fn extract_geometry_to_clip(
document: &mut Document,
layer_id: Uuid,
time: f64,
fills: &HashSet<FillId>,
edges: &HashSet<EdgeId>,
clip_id: Uuid,
instance_id: Uuid,
is_group: bool,
clip_name: &str,
) -> Result<VectorGraph, String> {
if fills.is_empty() && edges.is_empty() {
return Err("No geometry selected".to_string());
}
// 1. Extract from the source graph (extract_subgraph removes the moved geometry).
let (graph_before, sub_graph) = {
let layer = document.get_layer_mut(&layer_id).ok_or("Layer not found")?;
let vl = match layer {
AnyLayer::Vector(vl) => vl,
_ => return Err("Not a vector layer".to_string()),
};
let graph = vl.graph_at_time_mut(time).ok_or("No keyframe at time")?;
let before = graph.clone();
// No explicit cut boundary — extract_subgraph derives shared-fill boundaries.
let (sub, _, _) = graph.extract_subgraph(edges, fills, &HashSet::new());
(before, sub)
};
// 2 & 3. Build the clip + place an identity-transform instance (geometry stays put).
assemble_clip_from_graph(
document, layer_id, time, sub_graph, Transform::default(),
clip_id, instance_id, is_group, clip_name,
);
Ok(graph_before)
}
/// Reverse `extract_geometry_to_clip`: remove the clip + instance and restore the graph.
pub fn undo_extract_geometry(
document: &mut Document,
layer_id: Uuid,
time: f64,
clip_id: Uuid,
instance_id: Uuid,
graph_before: &VectorGraph,
) {
document.vector_clips.remove(&clip_id);
document.rebuild_layer_to_clip_map();
if let Some(AnyLayer::Vector(vl)) = document.get_layer_mut(&layer_id) {
vl.clip_instances.retain(|ci| ci.id != instance_id);
if let Some(kf) = vl.keyframe_at_mut(time) {
kf.clip_instance_ids.retain(|id| *id != instance_id);
}
if let Some(graph) = vl.graph_at_time_mut(time) {
*graph = graph_before.clone();
}
}
}
@@ -1,55 +1,57 @@
//! Convert to Movie Clip action — STUB: needs DCEL rewrite
//! Convert to Movie Clip — extract selected geometry into a movie-clip `VectorClip`
//! (its own timeline) + a `ClipInstance` that can be motion-tweened.
use std::collections::HashSet;
use crate::action::Action;
use crate::clip::ClipInstance;
use crate::actions::clip_from_geometry::{extract_geometry_to_clip, undo_extract_geometry};
use crate::document::Document;
use crate::vector_graph::{EdgeId, FillId, VectorGraph};
use uuid::Uuid;
/// Action that converts selected items to a Movie Clip
/// TODO: Rewrite for DCEL
#[allow(dead_code)]
pub struct ConvertToMovieClipAction {
layer_id: Uuid,
time: f64,
shape_ids: Vec<Uuid>,
clip_instance_ids: Vec<Uuid>,
fills: Vec<FillId>,
edges: Vec<EdgeId>,
clip_id: Uuid,
instance_id: Uuid,
created_clip_id: Option<Uuid>,
removed_clip_instances: Vec<ClipInstance>,
graph_before: Option<VectorGraph>,
}
impl ConvertToMovieClipAction {
pub fn new(
layer_id: Uuid,
time: f64,
shape_ids: Vec<Uuid>,
clip_instance_ids: Vec<Uuid>,
fills: Vec<FillId>,
edges: Vec<EdgeId>,
clip_id: Uuid,
instance_id: Uuid,
) -> Self {
Self {
layer_id,
time,
shape_ids,
clip_instance_ids,
instance_id,
created_clip_id: None,
removed_clip_instances: Vec::new(),
}
Self { layer_id, time, fills, edges, clip_id, instance_id, graph_before: None }
}
}
impl Action for ConvertToMovieClipAction {
fn execute(&mut self, _document: &mut Document) -> Result<(), String> {
let _ = (&self.layer_id, self.time, &self.shape_ids, &self.clip_instance_ids, self.instance_id);
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
let fills: HashSet<FillId> = self.fills.iter().copied().collect();
let edges: HashSet<EdgeId> = self.edges.iter().copied().collect();
let before = extract_geometry_to_clip(
document, self.layer_id, self.time, &fills, &edges,
self.clip_id, self.instance_id, false, "Movie Clip",
)?;
self.graph_before = Some(before);
Ok(())
}
fn rollback(&mut self, _document: &mut Document) -> Result<(), String> {
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
if let Some(before) = &self.graph_before {
undo_extract_geometry(document, self.layer_id, self.time, self.clip_id, self.instance_id, before);
}
Ok(())
}
fn description(&self) -> String {
let count = self.shape_ids.len() + self.clip_instance_ids.len();
format!("Convert {} object(s) to Movie Clip", count)
"Convert to Movie Clip".to_string()
}
}
@@ -0,0 +1,133 @@
//! Create-text-clip action
//!
//! Used by the text tool when the active layer is a **vector** layer: it creates a
//! VectorClip containing a single text layer, registers it, and places a clip
//! instance in the parent vector layer. The editor then enters that clip so the
//! text is directly editable. All of this is one undoable step so undo never
//! leaves an orphan clip.
use crate::action::Action;
use crate::clip::{ClipInstance, VectorClip};
use crate::document::Document;
use crate::layer::AnyLayer;
use crate::text_layer::TextLayer;
use uuid::Uuid;
/// Minimum clip duration (seconds) when the document has no duration set yet.
const FALLBACK_DURATION: f64 = 10.0;
pub struct CreateTextClipAction {
/// The vector layer to place the clip instance in.
parent_layer_id: Uuid,
/// The text layer to embed (its id is stable across redo).
text_layer: TextLayer,
/// Instance position in the parent layer's space.
position: (f64, f64),
// Assigned on first execute; reused on redo so ids are stable.
clip_id: Option<Uuid>,
instance_id: Option<Uuid>,
executed: bool,
}
impl CreateTextClipAction {
pub fn new(parent_layer_id: Uuid, text_layer: TextLayer, position: (f64, f64)) -> Self {
Self {
parent_layer_id,
text_layer,
position,
clip_id: None,
instance_id: None,
executed: false,
}
}
/// Preset the clip + instance ids (so the caller knows them up-front for
/// entering the clip immediately after execute). Ids stay stable across redo.
pub fn with_ids(mut self, clip_id: Uuid, instance_id: Uuid) -> Self {
self.clip_id = Some(clip_id);
self.instance_id = Some(instance_id);
self
}
/// The vector clip id (after execute).
pub fn clip_id(&self) -> Option<Uuid> {
self.clip_id
}
/// The clip instance id placed in the parent layer (after execute).
pub fn instance_id(&self) -> Option<Uuid> {
self.instance_id
}
/// The embedded text layer's id.
pub fn text_layer_id(&self) -> Uuid {
self.text_layer.layer.id
}
}
impl Action for CreateTextClipAction {
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
let clip_id = self.clip_id.unwrap_or_else(Uuid::new_v4);
self.clip_id = Some(clip_id);
let instance_id = self.instance_id.unwrap_or_else(Uuid::new_v4);
self.instance_id = Some(instance_id);
let duration = if document.duration > 0.0 { document.duration } else { FALLBACK_DURATION };
// Build the clip with the text layer as its single root layer.
let mut clip = VectorClip::with_id(
clip_id,
"Text",
self.text_layer.box_width.max(1.0),
self.text_layer.box_height.max(1.0),
duration,
);
// A movie clip (not keyframe-gated) so the text persists across the timeline.
clip.is_group = false;
clip.layers.add_root(AnyLayer::Text(self.text_layer.clone()));
// Registers the clip and its layers in layer_to_clip_map for O(1) lookup.
document.add_vector_clip(clip);
// Place an instance of the clip in the parent vector layer.
let layer = document
.get_layer_mut(&self.parent_layer_id)
.ok_or_else(|| format!("Parent layer {} not found", self.parent_layer_id))?;
let AnyLayer::Vector(vector_layer) = layer else {
return Err("Text clip can only be created inside a vector layer".to_string());
};
let mut instance = ClipInstance::with_id(instance_id, clip_id);
instance.transform.x = self.position.0;
instance.transform.y = self.position.1;
vector_layer.clip_instances.push(instance);
self.executed = true;
Ok(())
}
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
if !self.executed {
return Ok(());
}
// Remove the clip instance from the parent layer.
if let (Some(instance_id), Some(AnyLayer::Vector(vector_layer))) =
(self.instance_id, document.get_layer_mut(&self.parent_layer_id))
{
vector_layer.clip_instances.retain(|ci| ci.id != instance_id);
}
// Remove the clip and its layer_to_clip_map registrations.
if let Some(clip_id) = self.clip_id {
if let Some(clip) = document.vector_clips.remove(&clip_id) {
for node in &clip.layers.roots {
document.layer_to_clip_map.remove(&node.data.id());
}
}
}
self.executed = false;
Ok(())
}
fn description(&self) -> String {
"Add text".to_string()
}
}
@@ -37,6 +37,9 @@ pub struct DeleteFolderAction {
/// Asset IDs that were deleted (for DeleteRecursive strategy)
deleted_asset_ids: Vec<Uuid>,
/// Subfolder IDs that were reparented to the deleted folder's parent (for MoveToParent strategy)
moved_subfolder_ids: Vec<Uuid>,
}
impl DeleteFolderAction {
@@ -55,6 +58,7 @@ impl DeleteFolderAction {
removed_folders: Vec::new(),
moved_asset_ids: Vec::new(),
deleted_asset_ids: Vec::new(),
moved_subfolder_ids: Vec::new(),
}
}
}
@@ -130,6 +134,7 @@ impl Action for DeleteFolderAction {
for subfolder_id in subfolder_ids {
if let Some(subfolder) = tree.folders.get_mut(&subfolder_id) {
subfolder.parent_id = parent_id;
self.moved_subfolder_ids.push(subfolder_id);
}
}
}
@@ -259,6 +264,13 @@ impl Action for DeleteFolderAction {
tree.add_folder(folder.clone());
}
// Restore reparented subfolders back under the deleted folder
for subfolder_id in &self.moved_subfolder_ids {
if let Some(subfolder) = tree.folders.get_mut(subfolder_id) {
subfolder.parent_id = Some(self.folder_id);
}
}
match self.strategy {
DeleteStrategy::MoveToParent => {
// Restore folder_id for moved assets
@@ -312,6 +324,7 @@ impl Action for DeleteFolderAction {
self.removed_folders.clear();
self.moved_asset_ids.clear();
self.deleted_asset_ids.clear();
self.moved_subfolder_ids.clear();
Ok(())
}
@@ -1,56 +1,58 @@
//! Group action — STUB: needs DCEL rewrite
//! Group action — extract selected geometry into a group `VectorClip` + a `ClipInstance`.
use std::collections::HashSet;
use crate::action::Action;
use crate::clip::ClipInstance;
use crate::actions::clip_from_geometry::{extract_geometry_to_clip, undo_extract_geometry};
use crate::document::Document;
use crate::vector_graph::{EdgeId, FillId, VectorGraph};
use uuid::Uuid;
/// Action that groups selected shapes and/or clip instances into a VectorClip
/// TODO: Rewrite for DCEL (group DCEL faces/edges into a sub-clip)
#[allow(dead_code)]
/// Groups the selected DCEL geometry (fills/edges) of a vector layer's active keyframe
/// into a new group clip, placing a clip instance in its place (which can be tweened).
pub struct GroupAction {
layer_id: Uuid,
time: f64,
shape_ids: Vec<Uuid>,
clip_instance_ids: Vec<Uuid>,
fills: Vec<FillId>,
edges: Vec<EdgeId>,
clip_id: Uuid,
instance_id: Uuid,
created_clip_id: Option<Uuid>,
removed_clip_instances: Vec<ClipInstance>,
graph_before: Option<VectorGraph>,
}
impl GroupAction {
pub fn new(
layer_id: Uuid,
time: f64,
shape_ids: Vec<Uuid>,
clip_instance_ids: Vec<Uuid>,
fills: Vec<FillId>,
edges: Vec<EdgeId>,
clip_id: Uuid,
instance_id: Uuid,
) -> Self {
Self {
layer_id,
time,
shape_ids,
clip_instance_ids,
instance_id,
created_clip_id: None,
removed_clip_instances: Vec::new(),
}
Self { layer_id, time, fills, edges, clip_id, instance_id, graph_before: None }
}
}
impl Action for GroupAction {
fn execute(&mut self, _document: &mut Document) -> Result<(), String> {
let _ = (&self.layer_id, self.time, &self.shape_ids, &self.clip_instance_ids, self.instance_id);
// TODO: Implement DCEL-aware grouping
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
let fills: HashSet<FillId> = self.fills.iter().copied().collect();
let edges: HashSet<EdgeId> = self.edges.iter().copied().collect();
let before = extract_geometry_to_clip(
document, self.layer_id, self.time, &fills, &edges,
self.clip_id, self.instance_id, true, "Group",
)?;
self.graph_before = Some(before);
Ok(())
}
fn rollback(&mut self, _document: &mut Document) -> Result<(), String> {
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
if let Some(before) = &self.graph_before {
undo_extract_geometry(document, self.layer_id, self.time, self.clip_id, self.instance_id, before);
}
Ok(())
}
fn description(&self) -> String {
let count = self.shape_ids.len() + self.clip_instance_ids.len();
format!("Group {} objects", count)
"Group".to_string()
}
}
@@ -9,8 +9,9 @@ use crate::layer::AnyLayer;
use std::collections::HashMap;
use uuid::Uuid;
/// Per-instance loop change: (instance_id, old_timeline_duration, new_timeline_duration, old_loop_before, new_loop_before)
pub type LoopEntry = (Uuid, Option<f64>, Option<f64>, Option<f64>, Option<f64>);
/// Per-instance loop change: (instance_id, old_timeline_duration, new_timeline_duration, old_loop_before, new_loop_before).
/// All durations/offsets are in beats.
pub type LoopEntry = (Uuid, Option<daw_backend::Beats>, Option<daw_backend::Beats>, Option<daw_backend::Beats>, Option<daw_backend::Beats>);
/// Action that changes the loop duration of clip instances
pub struct LoopClipInstancesAction {
@@ -37,6 +38,7 @@ impl Action for LoopClipInstancesAction {
AnyLayer::Effect(el) => &mut el.clip_instances,
AnyLayer::Group(_) => continue,
AnyLayer::Raster(_) => continue,
AnyLayer::Text(_) => continue,
};
for (instance_id, _old_dur, new_dur, _old_lb, new_lb) in loops {
@@ -61,6 +63,7 @@ impl Action for LoopClipInstancesAction {
AnyLayer::Effect(el) => &mut el.clip_instances,
AnyLayer::Group(_) => continue,
AnyLayer::Raster(_) => continue,
AnyLayer::Text(_) => continue,
};
for (instance_id, old_dur, _new_dur, old_lb, _new_lb) in loops {
@@ -88,7 +91,7 @@ impl Action for LoopClipInstancesAction {
impl LoopClipInstancesAction {
fn sync_backend(&self, backend: &mut crate::action::BackendContext, document: &Document, rollback: bool) -> Result<(), String> {
use crate::clip::AudioClipType;
use crate::clip::ResolvedContent;
let controller = match backend.audio_controller.as_mut() {
Some(c) => c,
@@ -125,19 +128,22 @@ impl LoopClipInstancesAction {
(new_dur, new_lb)
};
let content_window = {
let trim_end = instance.trim_end.unwrap_or(clip.duration);
(trim_end - instance.trim_start).max(0.0)
};
let right_duration = target_duration.unwrap_or(content_window);
let left_duration = target_loop_before.unwrap_or(0.0);
// Natural content length as a beats span (the fallback when no explicit
// timeline_duration is set). Resolved in the clip's own domain, so MIDI's beats
// content carries over directly rather than being read as seconds.
let content_window_beats = instance.effective_duration_beats(
clip.content_duration(),
document.tempo_map(),
);
let right_duration = target_duration.unwrap_or(content_window_beats);
let left_duration = target_loop_before.unwrap_or(daw_backend::Beats::ZERO);
let external_duration = left_duration + right_duration;
let external_start = instance.timeline_start - left_duration;
let get_backend_clip_id = |inst_id: &Uuid| -> Result<u32, String> {
match &clip.clip_type {
AudioClipType::Midi { midi_clip_id } => Ok(*midi_clip_id),
AudioClipType::Sampled { .. } => {
match &instance.resolve(clip) {
ResolvedContent::Midi { midi_clip_id } => Ok(*midi_clip_id),
ResolvedContent::Audio { .. } => {
let backend_id = backend.clip_instance_to_backend_map.get(inst_id)
.ok_or_else(|| format!("Clip instance {} not mapped to backend", inst_id))?;
match backend_id {
@@ -145,7 +151,7 @@ impl LoopClipInstancesAction {
_ => Err("Expected audio instance ID for sampled clip".to_string()),
}
}
AudioClipType::Recording => Err("Cannot sync recording clip".to_string()),
ResolvedContent::Recording => Err("Cannot sync recording clip".to_string()),
}
};
@@ -0,0 +1,419 @@
//! Take management: delete and rename the takes on a clip instance.
//!
//! Takes live on the INSTANCE, so both of these are naturally scoped to the one the user clicked —
//! deleting a take from one half of a comped split leaves the other half's list alone.
use crate::action::{Action, BackendClipInstanceId, BackendContext};
use crate::clip::{AudioTake, ClipInstance};
use crate::document::Document;
use crate::layer::AnyLayer;
use uuid::Uuid;
/// The instance a take action targets, looked up mutably.
fn instance_mut<'a>(
document: &'a mut Document,
layer_id: &Uuid,
instance_id: &Uuid,
) -> Result<&'a mut ClipInstance, String> {
let layer = document
.get_layer_mut(layer_id)
.ok_or_else(|| format!("Layer {} not found", layer_id))?;
let AnyLayer::Audio(audio_layer) = layer else {
return Err("Takes only exist on audio layers".to_string());
};
audio_layer
.clip_instances
.iter_mut()
.find(|ci| ci.id == *instance_id)
.ok_or_else(|| format!("Clip instance {} not found", instance_id))
}
/// Swap an instance's backend clip to whatever take the document now says is active.
///
/// The same remove + re-add as `SetActiveTakeAction` — there's no in-place pool-swap command.
fn resync(
backend: &mut BackendContext,
document: &Document,
layer_id: &Uuid,
instance_id: &Uuid,
) -> Result<(), String> {
let instance = document
.get_layer(layer_id)
.and_then(|l| match l {
AnyLayer::Audio(al) => al.clip_instances.iter().find(|ci| ci.id == *instance_id),
_ => None,
})
.cloned()
.ok_or_else(|| format!("Clip instance {} not found", instance_id))?;
let existing: Option<BackendClipInstanceId> = backend
.clip_instance_to_backend_map
.get(instance_id)
.copied();
let track_id = backend.layer_to_track_map.get(layer_id).copied();
if let (Some(backend_id), Some(track_id)) = (existing, track_id) {
backend.remove_clip_instance(track_id, backend_id, *instance_id);
}
backend.add_clip_instance(document, layer_id, &instance)?;
Ok(())
}
/// Remove a take from an instance's take list.
///
/// The take's recorded audio/MIDI stays in the backend pool — undo has to be able to put it back,
/// and other instances (the other half of a split, say) may still be playing it.
pub struct DeleteTakeAction {
layer_id: Uuid,
instance_id: Uuid,
take_index: usize,
// Stored during execute for rollback.
removed: Option<AudioTake>,
old_active_take: Option<usize>,
}
impl DeleteTakeAction {
pub fn new(layer_id: Uuid, instance_id: Uuid, take_index: usize) -> Self {
Self {
layer_id,
instance_id,
take_index,
removed: None,
old_active_take: None,
}
}
}
impl Action for DeleteTakeAction {
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
let instance = instance_mut(document, &self.layer_id, &self.instance_id)?;
if self.take_index >= instance.takes.len() {
return Err(format!("Take {} does not exist", self.take_index + 1));
}
// An instance with no takes at all would fall back to the clip's own content, which for a
// cycle recording is a take we may just have deleted. Refuse rather than strand it.
if instance.takes.len() == 1 {
return Err("Can't delete the only take".to_string());
}
self.old_active_take = instance.active_take;
self.removed = Some(instance.takes.remove(self.take_index));
// Everything above the removed take shifts down one, so the selection has to move with it.
// Deleting the *active* take lands on the one that took its place (or the new last take, if
// it was at the end) — that keeps the clip sounding rather than silently picking take 1.
let active = instance.active_take.unwrap_or(0);
instance.active_take = Some(if active > self.take_index {
active - 1
} else if active == self.take_index {
self.take_index.min(instance.takes.len() - 1)
} else {
active
});
Ok(())
}
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
let Some(take) = self.removed.take() else {
return Ok(());
};
let instance = instance_mut(document, &self.layer_id, &self.instance_id)?;
let at = self.take_index.min(instance.takes.len());
instance.takes.insert(at, take);
instance.active_take = self.old_active_take;
Ok(())
}
fn description(&self) -> String {
format!("Delete take {}", self.take_index + 1)
}
fn execute_backend(
&mut self,
backend: &mut BackendContext,
document: &Document,
) -> Result<(), String> {
resync(backend, document, &self.layer_id, &self.instance_id)
}
fn rollback_backend(
&mut self,
backend: &mut BackendContext,
document: &Document,
) -> Result<(), String> {
resync(backend, document, &self.layer_id, &self.instance_id)
}
}
/// Throw away every take except the one that's playing.
///
/// The tidy-up once you've picked your keeper. Scoped to this instance, so on a comped split it
/// prunes the half you clicked and leaves the other half's alternatives intact.
pub struct DeleteUnusedTakesAction {
layer_id: Uuid,
instance_id: Uuid,
// Stored during execute for rollback.
old_takes: Vec<AudioTake>,
old_active_take: Option<usize>,
}
impl DeleteUnusedTakesAction {
pub fn new(layer_id: Uuid, instance_id: Uuid) -> Self {
Self {
layer_id,
instance_id,
old_takes: Vec::new(),
old_active_take: None,
}
}
}
impl Action for DeleteUnusedTakesAction {
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
let instance = instance_mut(document, &self.layer_id, &self.instance_id)?;
if instance.takes.len() < 2 {
return Err("Nothing to delete".to_string());
}
let keep = instance.active_take_index();
self.old_takes = instance.takes.clone();
self.old_active_take = instance.active_take;
let kept = instance.takes.remove(keep);
instance.takes.clear();
instance.takes.push(kept);
instance.active_take = Some(0);
Ok(())
}
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
let instance = instance_mut(document, &self.layer_id, &self.instance_id)?;
instance.takes = std::mem::take(&mut self.old_takes);
instance.active_take = self.old_active_take;
Ok(())
}
fn description(&self) -> String {
"Delete unused takes".to_string()
}
// The take that plays doesn't change, so the backend clip is already correct.
}
/// Rename a take. Document-only — which take *plays* doesn't change, so the backend is untouched.
pub struct RenameTakeAction {
layer_id: Uuid,
instance_id: Uuid,
take_index: usize,
new_name: String,
old_name: String,
}
impl RenameTakeAction {
pub fn new(layer_id: Uuid, instance_id: Uuid, take_index: usize, new_name: String) -> Self {
Self {
layer_id,
instance_id,
take_index,
new_name,
old_name: String::new(),
}
}
}
impl Action for RenameTakeAction {
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
let instance = instance_mut(document, &self.layer_id, &self.instance_id)?;
let take = instance
.takes
.get_mut(self.take_index)
.ok_or_else(|| format!("Take {} does not exist", self.take_index + 1))?;
self.old_name = std::mem::replace(&mut take.name, self.new_name.clone());
Ok(())
}
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
let instance = instance_mut(document, &self.layer_id, &self.instance_id)?;
if let Some(take) = instance.takes.get_mut(self.take_index) {
take.name = self.old_name.clone();
}
Ok(())
}
fn description(&self) -> String {
format!("Rename take to \"{}\"", self.new_name)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::clip::TakeContent;
use crate::layer::AudioLayer;
/// A document with one audio layer holding one instance with 4 takes (pools 10..13).
fn doc_with_takes() -> (Document, Uuid, Uuid) {
let mut document = Document::new("Test");
let clip = crate::clip::AudioClip::new_sampled("Cycle rec", 10, 2.0);
let clip_id = document.add_audio_clip(clip);
let mut instance = ClipInstance::new(clip_id);
instance.takes = (10..14)
.map(|pool| AudioTake {
name: format!("Take {}", pool - 9),
content: TakeContent::Audio { audio_pool_index: pool },
})
.collect();
let instance_id = instance.id;
let mut layer = AudioLayer::new("Layer");
layer.clip_instances.push(instance);
let layer_id = document.root.add_child(AnyLayer::Audio(layer));
(document, layer_id, instance_id)
}
fn takes_of(document: &Document, layer_id: &Uuid, instance_id: &Uuid) -> ClipInstance {
let AnyLayer::Audio(al) = document.get_layer(layer_id).unwrap() else { panic!() };
al.clip_instances.iter().find(|ci| ci.id == *instance_id).unwrap().clone()
}
#[test]
fn deleting_a_take_below_the_active_one_shifts_the_selection_down() {
// Everything above the removed take shifts down one, so a selection above it has to move
// with it — otherwise the instance silently starts playing a different take.
let (mut document, layer_id, instance_id) = doc_with_takes();
{
let AnyLayer::Audio(al) = document.get_layer_mut(&layer_id).unwrap() else { panic!() };
al.clip_instances[0].active_take = Some(3); // playing pool 13
}
DeleteTakeAction::new(layer_id, instance_id, 1)
.execute(&mut document)
.expect("delete");
let inst = takes_of(&document, &layer_id, &instance_id);
assert_eq!(inst.takes.len(), 3);
assert_eq!(inst.active_take, Some(2), "index shifted down with the take");
assert_eq!(
inst.takes[inst.active_take_index()].content,
TakeContent::Audio { audio_pool_index: 13 },
"still playing the same take it was",
);
}
#[test]
fn deleting_the_active_take_lands_on_its_replacement() {
// Deleting what you're listening to should hand you the take that took its place, not
// silently jump you back to take 1.
let (mut document, layer_id, instance_id) = doc_with_takes();
{
let AnyLayer::Audio(al) = document.get_layer_mut(&layer_id).unwrap() else { panic!() };
al.clip_instances[0].active_take = Some(1); // playing pool 11
}
DeleteTakeAction::new(layer_id, instance_id, 1)
.execute(&mut document)
.expect("delete");
let inst = takes_of(&document, &layer_id, &instance_id);
assert_eq!(inst.active_take, Some(1));
assert_eq!(
inst.takes[1].content,
TakeContent::Audio { audio_pool_index: 12 },
"the take that slid into the deleted one's place",
);
}
#[test]
fn deleting_the_last_take_in_the_list_steps_back() {
let (mut document, layer_id, instance_id) = doc_with_takes();
{
let AnyLayer::Audio(al) = document.get_layer_mut(&layer_id).unwrap() else { panic!() };
al.clip_instances[0].active_take = Some(3);
}
DeleteTakeAction::new(layer_id, instance_id, 3)
.execute(&mut document)
.expect("delete");
let inst = takes_of(&document, &layer_id, &instance_id);
assert_eq!(inst.active_take, Some(2), "there is no take 4 to land on");
}
#[test]
fn the_only_take_cannot_be_deleted() {
let (mut document, layer_id, instance_id) = doc_with_takes();
{
let AnyLayer::Audio(al) = document.get_layer_mut(&layer_id).unwrap() else { panic!() };
al.clip_instances[0].takes.truncate(1);
}
assert!(DeleteTakeAction::new(layer_id, instance_id, 0)
.execute(&mut document)
.is_err());
}
#[test]
fn undoing_a_delete_puts_the_take_back_where_it_was() {
let (mut document, layer_id, instance_id) = doc_with_takes();
{
let AnyLayer::Audio(al) = document.get_layer_mut(&layer_id).unwrap() else { panic!() };
al.clip_instances[0].active_take = Some(2);
}
let mut action = DeleteTakeAction::new(layer_id, instance_id, 1);
action.execute(&mut document).expect("delete");
action.rollback(&mut document).expect("undo");
let inst = takes_of(&document, &layer_id, &instance_id);
assert_eq!(inst.takes.len(), 4);
assert_eq!(
inst.takes[1].content,
TakeContent::Audio { audio_pool_index: 11 },
"restored at its original index",
);
assert_eq!(inst.active_take, Some(2), "and the selection with it");
}
#[test]
fn deleting_unused_takes_keeps_the_one_thats_playing() {
let (mut document, layer_id, instance_id) = doc_with_takes();
{
let AnyLayer::Audio(al) = document.get_layer_mut(&layer_id).unwrap() else { panic!() };
al.clip_instances[0].active_take = Some(2); // pool 12 — the keeper
}
let mut action = DeleteUnusedTakesAction::new(layer_id, instance_id);
action.execute(&mut document).expect("prune");
let inst = takes_of(&document, &layer_id, &instance_id);
assert_eq!(inst.takes.len(), 1);
assert_eq!(inst.active_take, Some(0));
assert_eq!(
inst.takes[0].content,
TakeContent::Audio { audio_pool_index: 12 },
"the take that was playing survives, and nothing else",
);
action.rollback(&mut document).expect("undo");
let inst = takes_of(&document, &layer_id, &instance_id);
assert_eq!(inst.takes.len(), 4);
assert_eq!(inst.active_take, Some(2), "back to what was playing before");
}
#[test]
fn renaming_a_take_round_trips() {
let (mut document, layer_id, instance_id) = doc_with_takes();
let mut action =
RenameTakeAction::new(layer_id, instance_id, 2, "The good one".to_string());
action.execute(&mut document).expect("rename");
assert_eq!(takes_of(&document, &layer_id, &instance_id).takes[2].name, "The good one");
action.rollback(&mut document).expect("undo");
assert_eq!(takes_of(&document, &layer_id, &instance_id).takes[2].name, "Take 3");
}
}
@@ -4,13 +4,20 @@
//! through the action system.
pub mod add_clip_instance;
pub mod change_bpm;
pub mod change_fps;
pub mod add_effect;
pub mod add_layer;
pub mod add_shape;
pub mod modify_shape_path;
pub mod move_clip_instances;
pub mod reorder_clip_instances;
pub mod paint_bucket;
pub mod remove_effect;
pub mod set_cycle_region;
pub mod append_takes;
pub mod manage_takes;
pub mod set_active_take;
pub mod set_document_properties;
pub mod set_instance_properties;
pub mod set_layer_properties;
@@ -23,25 +30,40 @@ pub mod rename_folder;
pub mod delete_folder;
pub mod move_asset_to_folder;
pub mod update_midi_notes;
pub mod update_midi_events;
pub mod loop_clip_instances;
pub mod remove_clip_instances;
pub mod set_keyframe;
pub mod set_tween;
pub mod group_shapes;
pub mod convert_to_movie_clip;
pub mod region_split;
pub mod toggle_group_expansion;
pub mod group_layers;
pub mod clip_from_geometry;
pub mod raster_diff;
pub mod raster_stroke;
pub mod raster_fill;
pub mod add_raster_keyframe;
pub mod resize_raster_layer;
pub mod move_layer;
pub mod set_fill_paint;
pub mod set_image_fill;
pub mod create_text_clip;
pub mod set_text_content;
pub mod resize_text_box;
pub use add_clip_instance::AddClipInstanceAction;
pub use set_cycle_region::SetCycleRegionAction;
pub use append_takes::AppendTakesAction;
pub use manage_takes::{DeleteTakeAction, DeleteUnusedTakesAction, RenameTakeAction};
pub use set_active_take::SetActiveTakeAction;
pub use add_effect::AddEffectAction;
pub use add_layer::AddLayerAction;
pub use add_shape::AddShapeAction;
pub use modify_shape_path::ModifyDcelAction;
pub use modify_shape_path::ModifyGraphAction;
pub use move_clip_instances::MoveClipInstancesAction;
pub use reorder_clip_instances::ReorderClipInstancesAction;
pub use paint_bucket::PaintBucketAction;
pub use remove_effect::RemoveEffectAction;
pub use set_document_properties::SetDocumentPropertiesAction;
@@ -56,9 +78,11 @@ pub use rename_folder::RenameFolderAction;
pub use delete_folder::{DeleteFolderAction, DeleteStrategy};
pub use move_asset_to_folder::MoveAssetToFolderAction;
pub use update_midi_notes::UpdateMidiNotesAction;
pub use update_midi_events::UpdateMidiEventsAction;
pub use loop_clip_instances::LoopClipInstancesAction;
pub use remove_clip_instances::RemoveClipInstancesAction;
pub use set_keyframe::SetKeyframeAction;
pub use set_tween::SetTweenAction;
pub use group_shapes::GroupAction;
pub use convert_to_movie_clip::ConvertToMovieClipAction;
pub use region_split::RegionSplitAction;
@@ -66,5 +90,13 @@ pub use toggle_group_expansion::ToggleGroupExpansionAction;
pub use group_layers::GroupLayersAction;
pub use raster_stroke::RasterStrokeAction;
pub use raster_fill::RasterFillAction;
pub use add_raster_keyframe::AddRasterKeyframeAction;
pub use resize_raster_layer::ResizeRasterLayerAction;
pub use move_layer::MoveLayerAction;
pub use set_fill_paint::SetFillPaintAction;
pub use set_image_fill::SetImageFillAction;
pub use change_bpm::ChangeBpmAction;
pub use change_fps::ChangeFpsAction;
pub use create_text_clip::CreateTextClipAction;
pub use set_text_content::SetTextContentAction;
pub use resize_text_box::ResizeTextBoxAction;
@@ -1,45 +1,45 @@
//! Modify DCEL action — snapshot-based undo for DCEL editing
//! Modify graph action — snapshot-based undo for VectorGraph editing
use crate::action::Action;
use crate::dcel::Dcel;
use crate::vector_graph::VectorGraph;
use crate::document::Document;
use crate::layer::AnyLayer;
use uuid::Uuid;
/// Action that captures a before/after DCEL snapshot for undo/redo.
/// Action that captures a before/after VectorGraph snapshot for undo/redo.
///
/// Used by vertex editing, curve editing, and control point editing.
/// The caller provides both snapshots (taken before and after the edit).
pub struct ModifyDcelAction {
pub struct ModifyGraphAction {
layer_id: Uuid,
time: f64,
dcel_before: Option<Dcel>,
dcel_after: Option<Dcel>,
graph_before: Option<VectorGraph>,
graph_after: Option<VectorGraph>,
description_text: String,
}
impl ModifyDcelAction {
impl ModifyGraphAction {
pub fn new(
layer_id: Uuid,
time: f64,
dcel_before: Dcel,
dcel_after: Dcel,
graph_before: VectorGraph,
graph_after: VectorGraph,
description: impl Into<String>,
) -> Self {
Self {
layer_id,
time,
dcel_before: Some(dcel_before),
dcel_after: Some(dcel_after),
graph_before: Some(graph_before),
graph_after: Some(graph_after),
description_text: description.into(),
}
}
}
impl Action for ModifyDcelAction {
impl Action for ModifyGraphAction {
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
let dcel_after = self.dcel_after.as_ref()
.ok_or("ModifyDcelAction: no dcel_after snapshot")?
let graph_after = self.graph_after.as_ref()
.ok_or("ModifyGraphAction: no graph_after snapshot")?
.clone();
let layer = document.get_layer_mut(&self.layer_id)
@@ -47,7 +47,7 @@ impl Action for ModifyDcelAction {
if let AnyLayer::Vector(vl) = layer {
if let Some(kf) = vl.keyframe_at_mut(self.time) {
kf.dcel = dcel_after;
kf.graph = graph_after;
Ok(())
} else {
Err(format!("No keyframe at time {}", self.time))
@@ -58,8 +58,8 @@ impl Action for ModifyDcelAction {
}
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
let dcel_before = self.dcel_before.as_ref()
.ok_or("ModifyDcelAction: no dcel_before snapshot")?
let graph_before = self.graph_before.as_ref()
.ok_or("ModifyGraphAction: no graph_before snapshot")?
.clone();
let layer = document.get_layer_mut(&self.layer_id)
@@ -67,7 +67,7 @@ impl Action for ModifyDcelAction {
if let AnyLayer::Vector(vl) = layer {
if let Some(kf) = vl.keyframe_at_mut(self.time) {
kf.dcel = dcel_before;
kf.graph = graph_before;
Ok(())
} else {
Err(format!("No keyframe at time {}", self.time))
@@ -6,13 +6,15 @@ use crate::action::Action;
use crate::clip::ClipInstance;
use crate::document::Document;
use crate::layer::AnyLayer;
use daw_backend::Beats;
use std::collections::HashMap;
use uuid::Uuid;
/// Action that moves clip instances to new timeline positions
pub struct MoveClipInstancesAction {
/// Map of layer IDs to vectors of (clip_instance_id, old_timeline_start, new_timeline_start)
layer_moves: HashMap<Uuid, Vec<(Uuid, f64, f64)>>,
/// Map of layer IDs to vectors of (clip_instance_id, old_timeline_start, new_timeline_start).
/// Timeline positions are in beats.
layer_moves: HashMap<Uuid, Vec<(Uuid, Beats, Beats)>>,
}
impl MoveClipInstancesAction {
@@ -20,8 +22,8 @@ impl MoveClipInstancesAction {
///
/// # Arguments
///
/// * `layer_moves` - Map of layer IDs to vectors of (clip_instance_id, old_timeline_start, new_timeline_start)
pub fn new(layer_moves: HashMap<Uuid, Vec<(Uuid, f64, f64)>>) -> Self {
/// * `layer_moves` - Map of layer IDs to vectors of (clip_instance_id, old_timeline_start, new_timeline_start) in beats
pub fn new(layer_moves: HashMap<Uuid, Vec<(Uuid, Beats, Beats)>>) -> Self {
Self { layer_moves }
}
}
@@ -42,7 +44,7 @@ impl Action for MoveClipInstancesAction {
// Check if this instance is in a group
if let Some(group) = document.find_group_for_instance(instance_id) {
let offset = new_start - old_start;
let offset = *new_start - *old_start;
// Add all group members to the move list
for (member_layer_id, member_instance_id) in group.get_members() {
@@ -58,6 +60,7 @@ impl Action for MoveClipInstancesAction {
AnyLayer::Effect(el) => &el.clip_instances,
AnyLayer::Group(_) => &[],
AnyLayer::Raster(_) => &[],
AnyLayer::Text(_) => &[],
};
if let Some(instance) = clip_instances.iter().find(|ci| ci.id == *member_instance_id) {
@@ -76,7 +79,7 @@ impl Action for MoveClipInstancesAction {
}
// Auto-adjust moves to avoid overlaps
let mut adjusted_moves: HashMap<Uuid, Vec<(Uuid, f64, f64)>> = HashMap::new();
let mut adjusted_moves: HashMap<Uuid, Vec<(Uuid, Beats, Beats)>> = HashMap::new();
for (layer_id, moves) in &expanded_moves {
let layer = document.get_layer(layer_id)
@@ -97,12 +100,13 @@ impl Action for MoveClipInstancesAction {
AnyLayer::Effect(el) => &el.clip_instances,
AnyLayer::Group(_) => &[],
AnyLayer::Raster(_) => &[],
AnyLayer::Text(_) => &[],
};
let group: Vec<(Uuid, f64, f64)> = moves.iter().filter_map(|(id, old_start, _)| {
let group: Vec<(Uuid, Beats, Beats)> = moves.iter().filter_map(|(id, old_start, _)| {
let inst = clip_instances.iter().find(|ci| &ci.id == id)?;
let dur = document.get_clip_duration(&inst.clip_id)?;
let eff = inst.trim_end.unwrap_or(dur) - inst.trim_start;
let dur = document.clip_trim_duration(&inst.clip_id)?;
let eff = inst.effective_duration_beats(dur, document.tempo_map());
Some((*id, *old_start, eff))
}).collect();
@@ -110,7 +114,7 @@ impl Action for MoveClipInstancesAction {
let clamped = document.clamp_group_move_offset(layer_id, &group, desired_offset);
for (instance_id, old_start, _) in moves {
adjusted_layer_moves.push((*instance_id, *old_start, (*old_start + clamped).max(0.0)));
adjusted_layer_moves.push((*instance_id, *old_start, (*old_start + clamped).max(Beats::ZERO)));
}
adjusted_moves.insert(*layer_id, adjusted_layer_moves);
@@ -132,6 +136,7 @@ impl Action for MoveClipInstancesAction {
AnyLayer::Effect(el) => &mut el.clip_instances,
AnyLayer::Group(_) => continue,
AnyLayer::Raster(_) => continue,
AnyLayer::Text(_) => continue,
};
// Update timeline_start for each clip instance
@@ -159,6 +164,7 @@ impl Action for MoveClipInstancesAction {
AnyLayer::Effect(el) => &mut el.clip_instances,
AnyLayer::Group(_) => continue,
AnyLayer::Raster(_) => continue,
AnyLayer::Text(_) => continue,
};
// Restore original timeline_start for each clip instance
@@ -184,7 +190,7 @@ impl Action for MoveClipInstancesAction {
fn execute_backend(&mut self, backend: &mut crate::action::BackendContext, document: &Document) -> Result<(), String> {
use crate::layer::AnyLayer;
use crate::clip::AudioClipType;
use crate::clip::ResolvedContent;
// Get audio controller
let controller = match backend.audio_controller.as_mut() {
@@ -203,10 +209,11 @@ impl Action for MoveClipInstancesAction {
for (instance_id, _old_start, new_start) in moves {
if let Some(instance) = vl.clip_instances.iter().find(|ci| ci.id == *instance_id) {
// Check if this clip has a metatrack
if let Some(&metatrack_id) = backend.clip_to_metatrack_map.get(&instance.clip_id) {
controller.set_offset(metatrack_id, *new_start);
controller.set_trim_start(metatrack_id, instance.trim_start);
controller.set_trim_end(metatrack_id, instance.trim_end);
if let Some(&metatrack_id) = backend.layer_to_track_map.get(&instance.clip_id) {
controller.set_offset(metatrack_id, document.tempo_map().beats_to_seconds(*new_start));
// A vector clip's content is wall-clock, so its content times ARE seconds.
controller.set_trim_start(metatrack_id, daw_backend::Seconds(instance.trim_start.raw()));
controller.set_trim_end(metatrack_id, instance.trim_end.map(|t| daw_backend::Seconds(t.raw())));
}
}
}
@@ -240,12 +247,12 @@ impl Action for MoveClipInstancesAction {
.ok_or_else(|| format!("Audio clip {} not found", instance.clip_id))?;
// Handle move based on clip type
match &clip.clip_type {
AudioClipType::Midi { midi_clip_id } => {
match &instance.resolve(clip) {
ResolvedContent::Midi { midi_clip_id } => {
// For MIDI: move_clip expects the pool clip ID
controller.move_clip(*track_id, *midi_clip_id, *new_start);
}
AudioClipType::Sampled { .. } => {
ResolvedContent::Audio { .. } => {
// For sampled audio: move_clip expects the instance ID
let backend_instance_id = backend.clip_instance_to_backend_map.get(instance_id)
.ok_or_else(|| format!("Clip instance {} not mapped to backend", instance_id))?;
@@ -257,7 +264,7 @@ impl Action for MoveClipInstancesAction {
_ => return Err("Expected audio instance ID for sampled clip".to_string()),
}
}
AudioClipType::Recording => {
ResolvedContent::Recording => {
// Recording clips cannot be moved - skip
}
}
@@ -269,7 +276,7 @@ impl Action for MoveClipInstancesAction {
fn rollback_backend(&mut self, backend: &mut crate::action::BackendContext, document: &Document) -> Result<(), String> {
use crate::layer::AnyLayer;
use crate::clip::AudioClipType;
use crate::clip::ResolvedContent;
// Get audio controller
let controller = match backend.audio_controller.as_mut() {
@@ -287,10 +294,11 @@ impl Action for MoveClipInstancesAction {
if let AnyLayer::Vector(vl) = layer {
for (instance_id, old_start, _new_start) in moves {
if let Some(instance) = vl.clip_instances.iter().find(|ci| ci.id == *instance_id) {
if let Some(&metatrack_id) = backend.clip_to_metatrack_map.get(&instance.clip_id) {
controller.set_offset(metatrack_id, *old_start);
controller.set_trim_start(metatrack_id, instance.trim_start);
controller.set_trim_end(metatrack_id, instance.trim_end);
if let Some(&metatrack_id) = backend.layer_to_track_map.get(&instance.clip_id) {
controller.set_offset(metatrack_id, document.tempo_map().beats_to_seconds(*old_start));
// A vector clip's content is wall-clock, so its content times ARE seconds.
controller.set_trim_start(metatrack_id, daw_backend::Seconds(instance.trim_start.raw()));
controller.set_trim_end(metatrack_id, instance.trim_end.map(|t| daw_backend::Seconds(t.raw())));
}
}
}
@@ -324,12 +332,12 @@ impl Action for MoveClipInstancesAction {
.ok_or_else(|| format!("Audio clip {} not found", instance.clip_id))?;
// Handle move based on clip type (restore old position)
match &clip.clip_type {
AudioClipType::Midi { midi_clip_id } => {
match &instance.resolve(clip) {
ResolvedContent::Midi { midi_clip_id } => {
// For MIDI: move_clip expects the pool clip ID
controller.move_clip(*track_id, *midi_clip_id, *old_start);
}
AudioClipType::Sampled { .. } => {
ResolvedContent::Audio { .. } => {
// For sampled audio: move_clip expects the instance ID
let backend_instance_id = backend.clip_instance_to_backend_map.get(instance_id)
.ok_or_else(|| format!("Clip instance {} not mapped to backend", instance_id))?;
@@ -341,7 +349,7 @@ impl Action for MoveClipInstancesAction {
_ => return Err("Expected audio instance ID for sampled clip".to_string()),
}
}
AudioClipType::Recording => {
ResolvedContent::Recording => {
// Recording clips cannot be moved - skip
}
}
@@ -369,15 +377,15 @@ mod tests {
let mut vector_layer = VectorLayer::new("Layer 1");
let mut clip_instance = ClipInstance::new(clip_id);
clip_instance.timeline_start = 1.0; // Start at 1 second
clip_instance.timeline_start = Beats(1.0); // Start at beat 1
let instance_id = clip_instance.id;
vector_layer.clip_instances.push(clip_instance);
let layer_id = document.root.add_child(AnyLayer::Vector(vector_layer));
// Create move action: move from 1.0 to 5.0 seconds
// Create move action: move from beat 1 to beat 5
let mut layer_moves = HashMap::new();
layer_moves.insert(layer_id, vec![(instance_id, 1.0, 5.0)]);
layer_moves.insert(layer_id, vec![(instance_id, Beats(1.0), Beats(5.0))]);
let mut action = MoveClipInstancesAction::new(layer_moves);
@@ -391,7 +399,7 @@ mod tests {
.iter()
.find(|ci| ci.id == instance_id)
.unwrap();
assert_eq!(instance.timeline_start, 5.0);
assert_eq!(instance.timeline_start, Beats(5.0));
}
// Rollback
@@ -404,7 +412,7 @@ mod tests {
.iter()
.find(|ci| ci.id == instance_id)
.unwrap();
assert_eq!(instance.timeline_start, 1.0);
assert_eq!(instance.timeline_start, Beats(1.0));
}
}
}

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