Timecode signals
Pure encoders in src-tauri/crates/xhape-engine/src/ (xhape-core for timecode and the clock). They only build bits, bytes and samples; the transport decides when to send them. Frame math (Timecode <-> frame count, 29.97 drop-frame) is timecode.rs.
LTC (ltc.rs)
frame_bits builds the 80-bit SMPTE 12M word, bits[0] is sent first:
| Bits | Content |
|---|---|
| 0-3, 8-9 | Frame units, tens (BCD, least significant bit first) |
| 10 | Drop-frame flag (29.97 only) |
| 11 | Colour frame flag (always 0) |
| 16-19, 24-26 | Seconds units, tens |
| 32-35, 40-42 | Minutes units, tens |
| 48-51, 56-57 | Hours units, tens |
| 4, 12, ... 60 | The eight user-bit nibbles |
| 27 (59 at 25 fps) | Polarity correction: makes the number of ones even, so every frame starts with the same polarity |
| 64-79 | Sync word 0x3FFD |
LtcEncoder::encode_frame appends the biphase-mark samples of one word: a transition at the start of every cell and another in the middle of a 1. A frame lasts sample_rate / fps samples, rarely a whole number, so cell boundaries are computed from a running half-cell count with exact integer arithmetic and the remainder carries into the next frame (1000 frames of 29.97 fps at 48 kHz are exactly 1 601 600 samples).
LtcConfig: sample_rate, level (linear peak amplitude) and edge_samples (slew limit: samples an edge takes to swing between polarities, 0 is a hard square wave). max_frame_samples() gives the buffer size to reserve so the audio callback never allocates.
MTC (mtc.rs)
quarter_framesreturns the eightF1 nnmessages; the high nibble ofnnis the piece number, the low nibble is a nibble of the binary frames, seconds, minutes and hours. Piece 7 also carries the rate code (0 = 24, 1 = 25, 2 = 29.97 drop, 3 = 30).A group describes the frame at which piece 0 is sent; pieces follow every quarter frame, so it takes two frames and receivers add two frames once they have all eight.
full_framereturnsF0 7F 7F 01 01 hh mm ss ff F7with the rate code in bits 5-6 ofhh. It is meant for start and seek.MtcSchedulerdecides when each quarter frame goes out.resync(position)returns the full-frame message for a start or seek; quarter frames resume at the next group of eight (an even frame), because a receiver needs a group to begin at piece 0.poll(position, send)callssendfor every quarter frame whose time has come, and skips ahead to the next group if the caller stalls instead of flooding the port with stale pieces.
MIDI clock (midi_clock.rs, output/midi_clock.rs)
A project can also send MIDI clock to one port (Preferences > Outputs > MIDI clock; the project says whether, the computer says which port). Xhape only sends it. ClockScheduler is pure: told the transport state, a position in samples and the tempo, it says which messages are due: timing clocks (F8, 24 per quarter note), Start (FA), Continue (FB), Stop (FC) and Song Position Pointer (F2, in sixteenths, up to 16383, so about 34 minutes at 120 BPM). Each clock is due at a sample, and the next is a tick later than that one, not than the time it was sent, so nothing drifts; a scheduler that was not looked at for a quarter second starts over instead of sending a burst.
- Cue show (
Mode::Follow): the position is the transport's, extrapolated like MTC's. The clock counts from the start of the timeline at the active timeline's tempo (timeline.tempo.bpm, the one the metronome clicks at), runs while the transport plays, sends Stop on pause or stop, and on play or a locate sends the Song Position Pointer of the next sixteenth and Continue (Start at the very beginning). A tempo change moves the next clock only. - VJ show (
Mode::Free): the position is the time, so the clock runs all the time at the show's tempo (the Link session's while Link is on), and Start, Continue and Stop only follow the transport's state.
The tempo reaches the thread through SharedClock::clock_bpm, set when the output opens and by output_set_tempo. The thread is xhape-midi-clock; it parks until shortly before a clock is due and spins the rest, as xhape-mtc does, and a port that goes away is marked lost and opened again.
Transport (transport.rs)
The audio device's sample clock is the master. Transport holds the position as a sample count since the timeline origin; the output callback calls advance(samples) with what it produced, so playback, LTC and MTC share one clock and cannot drift apart. Nothing in it allocates or locks.
Clockconverts between samples and frames, MTC quarter frames (4 per frame) and LTC half cells (160 per frame). Every boundary is the exact fraction rounded to the nearest sample, so 1000 frames of 29.97 fps at 48 kHz are exactly 1 601 600 samples and errors never accumulate.Command:Play,Pause,Stop(back to the start),Seek(frame). A seek takes a frame count, like every position in the project; positions before the active timeline'stimecode.startgo to the start.- End of the show.
set_end(samples)gives the transport the latest end among all clips and cues. When playing reaches it, the transport stops by itself exactly likeStop: statestopped, back at the start (so the next Play runs the show again), epoch changed so LTC and MTC resync; thetransport-positionlane reports it as a state change, not as an error. The check runs once per audio buffer, so LTC can run on for less than one buffer past the end; there is no extra tail after the last item (the end is exact, and a later configurable tail can be added on top). A show with no end (no clips and no cues, or everything at the origin) never stops by itself, so the generators can run without a programme. A seek past the end goes to the end (playing from there stops at once). The end can change while playing:output_set_clipssends a new one with the clips, and an end that moved away is simply not reached. A clip's end uses its exact decoded length, shortened by itslengthwhen it has one; muted tracks count, so muting does not move the end of the show. The end comes fromCueList::end_samplesand travels inClipSet::with_end. epoch()changes whenever playback starts or the position jumps (start, stop, seek) but not on pause. Generators compare it with the last epoch they saw and callresync.LtcStreamplays LTC in step with the transport: silence until the next frame boundary, then one frame after another from a preallocated buffer, sofillis safe in the audio callback.
Timelines
A project can hold several timelines, each with its own frame rate, start and tracks, but one plays at a time: the output, the transport and every LTC and MTC signal run the active timeline, which the backend's Session keeps. live_cues, live_state, output_start and output_set_clips take the project but not a timeline: the backend picks the active one. The timeline_* commands (timeline_add, timeline_rename, timeline_remove, timeline_select, timeline_set_timecode, timeline_move) take the project the window shows, make it the document, do the work and answer with { project, active }. Changing the active timeline, removing one or changing its timecode is refused while the transport plays, and it closes the running output (the rate and the start are fixed when the output opens), so the window opens it again: the transport then stands at the start of the new timeline. timeline_move (reordering) is refused while the transport plays too, like changing the view, but it leaves the open output alone.
In Live, the next timeline is made ready when one ends. The window opens the output with advance set when the Live view is showing. When the show then runs to its end by itself (a stop from the user does not count: the transport counts those ends, see PositionReader::shows_ended), a lane of the output makes the following timeline the active one (Session::next_timeline) and emits the timeline-advanced event with the { project, active } it left. The window shows it and opens the output again for the new timeline, which is stopped at its start: it is never started for the user. After the last timeline nothing changes and the show stays where it ended.
Cues and the Live view (engine/cues.rs, live_commands.rs)
The Live view runs the timeline on stage, and the backend does all of its thinking; the UI only draws what it is sent. A cue is not stored in the project: every clip of an audio track and every note of a notes track is one, so the .xhape format does not change. CueList::build derives the list, ordered by frame (cues at the same frame keep the order of their tracks) and numbered from 1. A clip's length comes from its decoded audio, trimmed by its offset and length; a file that cannot be read gives a cue without length, never an error. Cue.frame is the absolute timecode frame, so the UI seeks to it as it is.
CueList::state_at(frame) gives the LiveState for a position. Each cue is pending, next (the first cue still to come, the one on standby), running (a clip from its first frame to the one before its end), done or muted (its track is muted, so it never plays or queues). The state also carries current (the sounding clip that started last, or else the last cue done), the countdown to the next cue and, for each running clip, the time elapsed, the time left and the progress. Every time is already written as timecode (; before the frames in drop-frame).
Notes are cues of kind note that carry their text (Cue.text; Cue.name is its first line). A note is on show from its frame for its length, or, without one, until the next note of its track that starts later, or to the end of the show. LiveState.notes lists those on show, with the time left of one that has a length, so the Live view can write them large for the operator. A note with a length also counts as running while it is on show. Notes of a muted track are neither shown nor queued. MIDI and OSC events are cues of kind midi and osc: Cue.action says what they send (noteOn, noteOff, controlChange, programChange, msc, sysEx, osc) and Cue.detail writes it in notation (C4 · ch 1 · vel 100, GO 12.5 · L2, /cue/1/start 1 0.5), which the UI shows next to the translated action. A note with a length is running for that long; the others are instant, so they go from next to done. Firing them is described below. Each video clip is a cue of kind video, named after the clip (or its video), running for as long as the clip shows. Each scene of a DMX track is a cue of kind dmx, named after the scene, with Cue.detail its channel count (3 ch); its length is its fade.
| Command | Arguments | Result |
|---|---|---|
live_cues | project | The Cue list. |
live_state | project, frame | The LiveState at that frame, for when no output runs and the playhead is parked in the window. |
live_search | project, query | The ids of the cues that match, best first (see Cue search). |
show_lock_get / show_lock_set | locked | Whether the show is locked; set answers with the state it is in (see Show lock). |
midi_panic | project | A PanicReport (see MIDI panic). |
With an output running, the xhape-live lane sends the same LiveState over its channel; the output keeps a cue list that output_start and output_set_clips rebuild, which the lane swaps in whole like the meters' state.
Cue search (cue_search.rs)
live_search(project, query) answers which cues of the active timeline the operator means, so the search field of the Live view only types the query and lists the ids it gets back. An empty query matches every cue in show order. A query that is a number (12 or #12) puts the cue with that number first; after it, and for any other query, come the cues (in show order) whose name, whole text, track name or notation (Cue.detail) contain the query in any letter case. Picking a result seeks to Cue.frame, the same as a double click on its row.
Show lock (session.rs, live_commands.rs)
The operator can lock the show from the Live bar. The lock is one flag of the backend Session (Session::show_lock): session state, off at start, never written to the project. While it is set, Session::ensure_editable fails with show.error.showLocked and so does everything that goes through it: every editing operation (the project, the timelines, imports), project_new, project_open, project_close, leaving the editor (window_close_editor) and restoring a recovery. That covers the shortcuts and the remote control too, since they reach the backend by the same commands. What the lock does not refuse is the show: starting the output (output_start only asks ensure_not_running, which the setlist's own execution lock also uses), the transport, going to a cue, GO, and saving. The window mirrors the flag: the Edit side of the view switch, the project menus, the timeline tabs and the editing keys are disabled while it is on. Locking is a click; unlocking needs a press and hold, so it cannot happen by accident.
MIDI panic (midi_panic.rs)
midi_panic(project) is the operator's last resort when a receiver is stuck (a lost Note Off after a cable drop, a synth latched by hand). The window stops the transport and then calls it. On each of the 16 channels it sends All Sound Off (CC 120), Reset All Controllers (CC 121) and All Notes Off (CC 123), 48 messages, to every MIDI port the project uses: the port of every MIDI track of every timeline (muted tracks too) and the MTC ports this machine assigned. Nothing is sent to a port the project does not use. The ports are opened for the burst, so it works with the output stopped; and because some systems let a port be opened once only, a request also raises a counter that the xhape-midi threads read in their loop (Sink::panic), so the ports a running output holds are silenced through the output's own connection. Nothing logs from that path. Each fire thread marks the port it holds (midi_panic::Served) while it lives, so a port the output holds is not opened a second time: it counts in sent and in via_output, and only a port that is neither held nor opens is in failed and named in the window. The command logs the PanicReport. The same panic runs from the remote control (ControlAction::Panic, /xhape/panic), the OSC API (/xhape/v1/panic) and Ctrl+Shift+P, each stopping the transport first. A setlist run keeps its own cue thread, which is not marked: its ports are opened for the burst like any other. The messages are pure (midi_panic::messages, midi_panic::ports) and tested with a recording port.
LTC to WAV (ltc_wav.rs, export_commands.rs)
File > Export > LTC to WAV… renders the LTC of the active timeline offline. ltc_export(project, path, options, on_progress) uses the same LtcStream as the output, started at the timeline origin, so the file is the signal Xhape would send frame for frame. It starts at the timeline's start timecode and runs for the whole timeline: up to the end of its last cue (CueList::end_samples), rounded up to a whole frame so the last word is complete, at the timeline's frame rate (29.97 drop-frame included). options (the export dialog) chooses the sample rate (44.1, 48 or 96 kHz), the bit depth (pcm16, pcm24 or float32, a IEEE float file with the fact chunk) and a pre-roll of 0 to 60 whole seconds of LTC before the timeline start (rounded up to a whole frame; it counts back from the start timecode and wraps across midnight). The defaults are 48 kHz, 24-bit and no pre-roll; anything out of range is refused (show.error.ltcOptions). The file is mono, at the level of the project's first LTC output (half scale when none is set or the project has none). It is written in pieces on the blocking pool, without touching a running output; on_progress receives the fraction done only when the render has lasted over a second. A timeline with no cues has no length (show.error.ltcEmpty), one over about 7.9 hours does not fit a WAV file (show.error.ltcTooLong), and a render that fails leaves no half-written file. The tests decode the frames back from the bits of the file and compare them with the timecode of each frame at every frame rate.
Cue sheet (cue_sheet.rs, export_commands.rs)
cue_sheet_export(project, scope, labels, path) writes the same cues as a file for people who do not look at Xhape. scope is active (the timeline the backend has active) or all. The extension of path picks the format: .html / .htm is a self-contained page (no scripts or outside files, light on white, one section per timeline with a page break between them when printed) and anything else is a CSV (UTF-8 with a byte order mark so Excel reads the accents, CRLF lines, one table with a timeline column). The sheet keeps the numbers of the Live list, so the number on paper is the one on screen, and leaves out cues on muted tracks (the numbers of those are skipped). A note shows its whole text, not only its first line. In the CSV, a text that starts with =, +, - or @ gets a leading ' so a spreadsheet shows it instead of running it; in the HTML everything typed is escaped. labels carries the words in the user's language (headers, cue kinds and actions, frame rates), because the backend writes the file; it runs on the blocking pool and never touches a running output.
Firing MIDI and OSC cues (fire.rs, midi_cue.rs, osc.rs, cue_routes.rs)
The events of the midi and osc tracks are fired from threads that are not the audio callback. Each MIDI port and each OSC destination the unmuted tracks of the active timeline use gets a thread (xhape-midi, xhape-osc) that reads the position the audio callback publishes, like xhape-mtc, and sleeps until the next event falls due (parking, then spinning the last 200 µs), so events are not quantised to the audio buffer. Tracks that share a port or destination share its thread and schedule.
Schedule<T>is the list of(sample, payload)of one destination, stable-sorted;Scheduler<T>walks it:resync(position),poll(position, send),next_due(). The scheduler is pure and tested without devices; the encoders (midi_cue::encode,osc::encode) are pure too.- No chase. On every change of the transport epoch (start, stop, seek; not pause) the schedule is re-armed at the new position: events before it never fire, one exactly at it fires, and after seeking back the events already fired fire again when reached. Pausing and resuming does not resync, so nothing fires twice.
- An event that is due while its thread runs late still fires, late. A send that fails is counted (
Faults.cue_errors) and the log lane reports it; nothing logs from these threads. - Hanging notes. The MIDI sink remembers the notes that are on, and sends a Note Off for each when the epoch changes, when playback stops or pauses, and when the output closes. A note with a
lengthhas its Note Off scheduled atat + length. - Edits while playing.
output_set_clipsalso replaces the schedules (Output::set_events), carrying on from the position, and opens a port or destination that is new. A track muted or left without an output goes quiet. - Audition. With
auditionset onoutput_startno cue thread is opened andset_eventsdoes nothing. - Timeline hand-over. The output is rebuilt for the next timeline, so its threads stop and release their notes.
- A MIDI port or OSC host that cannot be opened is a warning in
OutputInfo.warnings, with its state inOutputInfo.cues({ kind, target, ok }); the project still plays. OSC is UDP only for now, one connected socket per destination, resolved when the output opens (never from the firing thread). MIDI Show Control and the OSC message format are described in the track kinds of project-format.md.
Sending DMX (dmx.rs, cue_routes.rs)
The scenes of the dmx tracks are sent from a thread of their own, xhape-dmx, one for each destination the unmuted tracks of the active timeline use. Unlike the events above, DMX is a state: DmxPlan::frames(position) folds the scenes up to a position (each channel moves from where it is when a scene starts, and carries on with its own fade when a later scene does not name it; releaseOthers fades the channels the scene does not name to 0) and tracks that share a destination merge channel by channel, highest value wins. It is pure and tested without a socket.
- The thread follows the published position like
xhape-osc. While the transport plays it recomputes every 25 ms and sends a universe only when its values changed; so a fade goes out at up to 40 frames a second. - Seek, start and loop recompute the state at the new position, so locating in the middle of a fade is exact.
- Stop holds the last frame: the lights stay as they were, whatever position the transport returns to. A seek while stopped or paused recomputes it. The frame is repeated once a second (a node that lost it recovers), and nothing is sent after the output closes; to turn the lights off at the end of a show, end it with a scene that releases the others.
- Packets. Art-Net is
ArtDmx(OpCode0x5000, version 14, a sequence from 1 to 255, the 15-bit Port-Address as SubUni and Net, 512 channels). sACN is an E1.31 data packet (priority 100, a random source id for each socket, universeuniverse + 1). Both go over UDP from an unconnected socket, so a closed port is not an error; a destination is resolved when the output opens (never from the thread), and broadcast is allowed. - A destination that cannot be opened is a warning in
OutputInfo.warningsand an entry ofOutputInfo.cueswithkind: "dmx"; a send that fails is counted (Faults.cue_errors). Nothing logs fromxhape-dmx. - DMX is not sent in a setlist show (
show_events.rs) yet, and a destination edited while the output runs takes effect when it opens again (a new one is opened at once, as for OSC).
Metronome (engine/metronome.rs)
The metronome clicks on every beat of the active timeline's tempo, counted from the timeline origin; beat 0 of each bar is the accent (higher pitch). A click is a pure function of the transport position (a 30 ms decaying sine placed at round(beat * 60 / bpm * rate)), so it keeps no state: any buffer holds the clicks the grid puts in it, and a seek lands on the grid at once. It sounds only while the transport plays.
- Own output.
output.metronomenames a device, channels and level apart from the programme's (see project-format.md). The tempo and the click switch live in atomics (SharedMetronome) thatoutput_set_tempo(tempo)writes while the show runs, so an edit of the BPM, the beats per bar or the click switch is heard at once; the level and the device are fixed when the output opens (changing them reopens it). - Which stream plays it. No device is opened twice: on the programme's device the click is mixed in by the
Renderer(a metronome channel the programme also uses gets the click added; one it does not use carries the click alone); on the device of an own LTC stream it is written by that stream'sLtcFollower; on any other device a stream of its own (xhape-click) is a follower with no LTC outputs. If the device cannot be opened, the output still starts andwarningssays so;OutputInfo.metronomereports{ device, ok }. A click stream that fails while running setsPosition.metronomeLost. - Following the master. A follower reads the master's published position like LTC does, but starts the click over from it only when 10 ms or more away (an LTC frame, 40 ms, would be too coarse for a click). The two devices have independent clocks and no latency compensation, so the click can sit a few milliseconds off the music.
- A click and LTC on the same channel of one device: LTC wins.
Tempo detection (audio/tempo.rs)
audio_detect_bpm(asset) returns the BPM of an asset, or null when it is too short (under 4 s), silent, or shows no steady pulse. It uses the decoded audio when the cache already holds it, and otherwise decodes the file without keeping it, so asking for every song of a big show does not fill the memory. The UI asks for it after importing audio, and in the background, one song at a time, for the assets of an opened project that have none; the result is stored on the asset (assets[].bpm), so a project that was saved with it decodes nothing. A tempo found for an opened file is not an edit: it does not enter the undo history nor mark the document unsaved, and is written with the next save. The inspector can detect again, type another value, or copy it to the timeline's tempo.
The method: loudness every 512 samples, its rises (onset strength), a blur, the autocorrelation over 55 to 210 BPM weighted towards 120 BPM, and a refinement that slides a comb of beats over the onsets at 0.1 % steps. It reads at most 120 s from the middle of the audio. It finds the pulse of music that has one; the choice between a tempo and its double is made by the weighting towards 120 BPM, so an evenly spaced pulse at 174 BPM reads as 87. It was checked on synthetic drum patterns, not on a library of real recordings.
Defaults and open decisions
LtcConfig::default() is 48 kHz, level 0.5 (-6 dBFS) and a one-sample edge. These can become project settings later. With no offset set, frame N starts exactly where the transport reaches frame N. Each LTC and MTC output can run ahead of or behind the transport by an offset of its own (below).
Output and transport commands (output.rs, transport_commands/)
output_start(project, onPosition, onLevels, onLive) opens the devices project.output names and starts a stopped transport at project.timecode.start; it replaces a running output. TS wrappers are in src/transport/api.ts. The UI decides what project.output the backend sees: in the Edit view, a project with output.preview is sent with that device as its only output (no LTC or MTC), so auditioning never emits timecode; Live sends the project's outputs as they are.
| Command | Arguments | Result |
|---|---|---|
output_start | project (its active timeline plays), advance (hand over to the next timeline when the show ends), audition (Edit on a preview device: the MIDI and OSC cue tracks stay silent), onPosition, onLevels, onLive (channels, below) | OutputInfo: device, sampleRate, channels, ltc[] and mtc[] (one { …, ok } per output of the project, in its order), metronome, cues[], warnings. |
output_reconfigure | project, audition | { kind: "applied", info } after bringing the LTC and MTC outputs in line with the project without touching the programme's stream (works while playing), or { kind: "needsRestart" } with nothing changed. |
output_attach | setup (the requested timeline, timecode, effective outputs, advance and audition), onPosition, onLevels, onLive | Replaces the subscriptions on the running output without interrupting playback. Returns its info, position, timeline ID and start, and whether its settings match, or null when there is no running output. |
output_stop | Closes the devices. | |
transport_play / transport_pause / transport_stop | Stop goes back to the timeline start. Error if no output runs. | |
transport_seek | frame | Moves to a timecode given as a frame count. |
transport_position | Position (state, frame, positionSamples, deviceLost, ltcLost, mtcLost, metronomeLost, clockUnpaced) or null when no output runs. |
While an output runs it reports over three lanes, each with a thread of its own and the Channel that output_start or output_attach was given for it, about 30 times a second each:
| Lane | Thread | Channel | Sends |
|---|---|---|---|
| Position | xhape-position | onPosition: Channel<Position> | The initial Position for the subscriber, then updates when it changes. |
| Live | xhape-live | onLive: Channel<LiveState> | Where the show stands among its cues (see Cues and the Live view), initially and when it changes. |
| Levels | xhape-levels | onLevels: Channel<[{ id, peak }]> | The peak of each track since the previous message; silence once after the sound stops, then nothing. |
The lanes are independent, so a slow consumer of the meters never delays the timecode. A channel is ordered and goes only to its subscriber; the UI also drops messages from outputs it has replaced or closed.
Threads
No command runs on the main thread, which belongs to the window and its event loop. Tauri runs a command without async inline on that thread, so the small ones (transport_*, output_set_track_gain, output_set_tempo) are #[tauri::command(async)] and use the command thread pool; the heavy ones (output_start, output_stop, output_set_clips, output_reconfigure, project_*, devices_*, audio_analyze) use the blocking pool. The rest:
| Thread | Work |
|---|---|
xhape-audio | The audio callback: programme, LTC when it shares the device, position. Never allocates or waits. |
xhape-ltc | The LTC callback, when LTC plays on a device other than the programme's (it carries the metronome too when that device is the metronome's). Never allocates or waits. |
xhape-click | The metronome callback, when the metronome plays on a device nothing else uses. Never allocates or waits. |
xhape-mtc | MIDI Timecode quarter frames. |
xhape-midi-clock | MIDI clock: timing clocks, Start, Continue, Stop and Song Position (see MIDI clock). |
xhape-midi, xhape-osc | Fire the events of the MIDI and OSC tracks, one thread per port / destination (see Firing MIDI and OSC cues). |
xhape-dmx | Sends the lighting state of the DMX tracks over Art-Net or sACN, one thread per destination (see Sending DMX). |
xhape-position, xhape-live, xhape-levels | The three lanes above. |
xhape-advance | With advance on: sees the show end and makes the next timeline the active one. |
xhape-log | Writes the log for the output (see diagnostics.md): transport and device changes, and the fault counters. |
Nothing logs from xhape-audio, xhape-ltc, xhape-click, xhape-mtc, xhape-midi-clock, xhape-midi, xhape-osc or xhape-dmx: writing a file waits. Their error callbacks and send failures only bump atomic counters (SharedClock::faults: xruns, stream_errors, mtc_errors, cue_errors) and raise the lost flags, and the xhape-log lane turns the changes into log lines. A dropout (ErrorKind::Xrun) is counted and does not mark the device as lost; any other stream error does.
Commands that set the transport only enqueue a message for the audio callback, so two of them issued back to back from the UI are not guaranteed to run in order; the UI awaits the ones that depend on each other (Play waits for the output to open) and sends dragged seeks and faders one at a time, newest value last.
- The programme device is
output.audio's, or the system's default output when there is none (an emptydeviceName); a project written beforeoutput.audioexisted has it on the LTC device. It is the master: it carries the programme and the clock, and LTC too whenoutput.ltcnames the same device (compared by the device each hint opens, so an empty name and the default device's name are the same). Neither LTC nor MTC is needed to play the music. The stream opens at 48 kHz with the fewest channels that cover the highest channel used, in 32-bit float, else 32, 24 or 16-bit integer. The programme (below) uses the same stream. - LTC on its own device: when
output.ltcnames another device, a second stream (xhape-ltc) plays only LTC. Two devices have two sample clocks that drift apart, soLtcFollowerdoes not count samples against the transport: each callback reads the master's published position (try_load, never waiting; extrapolated with the wall clock like MTC) and plays LTC from there. It starts the LTC stream over at the master's position when the transport seeks, stops or resumes, or when the two differ by a frame or more, which at 50 ppm of clock difference is about every 13 minutes at 25 fps. That start-over costs one LTC frame of silence and a jump of a frame. The two devices' output delays are not measured, so LTC and the music can be offset by the difference between them (ms); the output'soffsetMs(see Latency offset) compensates it by hand. If the LTC device is missing or cannot be opened, the output still starts without LTC andwarningssays so (like MTC); if it fails while running, its bit ofPosition.ltcLostis set (see Lost outputs). - The audio device's sample clock is the master. The callback owns the
Transport, drains commands withtry_recv, renders LTC into its channel, advances the position and publishes it withtry_lock: it never allocates or waits. A reader holding the lock only makes it skip one update. - MTC runs on a thread that parks until shortly before each quarter frame is due (1 ms at most per park) and spins for the last 200 µs, so the message goes out when it falls due and not up to a timer tick later. It reads the published position and extrapolates with the wall clock (at most 100 ms), so quarter frames are not quantised to the audio buffer. It sends a full frame whenever the transport epoch changes. A missing MIDI port becomes a warning in
OutputInfo; the audio side still starts. Every MTC output has a thread of its own; two ports with the same name are told apart byportIndex. - The audio device always provides the clock, so an MTC-only project still opens one (the default output).
- A park can still overshoot by the system's timer resolution (about 15 ms on Windows unless it is raised), and a quarter frame that falls due in that time goes out late; the spin only removes the jitter of the last 200 µs.
- Each LTC output has its own level (
output.ltc[].level): one generator runs at full scale and every channel it is written to applies its output's level. - Latency offset. Each LTC and MTC output has an optional
offsetMs(whole ms, within ±1000, positive = emitted earlier). What goes out when the transport is at positionpis the timecode ofp + offset; the displayed time and the transport are untouched, and 0 or absent behaves as before.LtcStream::with_offsetandMtcScheduler::with_offsetapply it inside the generator, so seeks, stops and resumes (which allresync) and the follower's tracking need no special case. LTC before the timeline origin (a negative offset near 0) is silent until the timecode reaches it. A stream has one generator per distinct offset, so LTC outputs that share an offset share one; a device and channel listed twice plays once with the first output's level and offset, and a repeated MIDI port keeps the first entry's offset. The Setup dialog sends the typed text to theoutput_set_offsetcommand (kind, index, text); the backend parses it, checks the range, stores 0 as no offset and answers with the project, which the UI shows.
Programme audio (audio/, engine/mixer.rs)
The music is decoded once and mixed in the same callback that renders LTC, on the same clock.
- Decoding (
audio/decode.rs, symphonia: wav, aiff, flac, mp3, ogg): every file becomes stereo, 48 kHz (rubato's FFT resampler converts other rates), 16-bit. Mono plays on both sides; channels beyond two are dropped. Sixteen bits keeps a three minute song near 35 MB in memory, where 32-bit float would take 70 MB. - Peaks (
audio/peaks.rs): the min and max of every 10 ms as signed bytes, which is what the timeline draws. - Commands:
audio_analyze(asset)returns{ durationSeconds, sourceRate, peaksPerSecond, peaks }; the UI calls it on import and when a project opens, so clip lengths and waveforms are real. It first looks for the preview stored in the.xhape(peaks/, see project-format.md) and only decodes the asset (cached by asset id) when there is none or it was made from other audio; the result is kept for the next save. Opening a project whose previews are stored decodes nothing.output_set_clips(project)sends the current clips to a running output.output_startdecodes whatever has not been decoded yet. - Mixing (
mixer.rs): clips of tracks that are not muted, placed byClock::frames_to_samples(clip.start), withgainDbas10^(dB/20). The callback mixes in chunks of 256 frames held on the stack, adds the clips, clamps to -1..1 and writes left and right tooutput.audio.channels(one channel receives the mono sum); LTC then writes its own channel. A clip plays fromClock::frames_to_samples(start)up to itslength(or the end of its audio), reading its audio from theoffset;mixer::spangives that range and the cues use it too, so both agree. AfadeIn/fadeOutis a gain per sample shaped byfadeInCurve/fadeOutCurve(mixer::fade_shape; linear when absent): silent on the first sample of a fade in and the last of a fade out, whatever the curve. A clip'senvelopeis placed on the timeline when the programme is built (mixer::Envelope, points in samples from the audio file's origin, gains linear) and multiplies the fades and the clip gain per sample, with no allocation or lock in the callback: a binary search over at most 256 points. Segments run in dB, or in amplitude when a point is silence;holdsteps to the next point over 4 ms. Before the first point and after the last the gain is theirs. A clip whose audio cannot be read is skipped and reported inOutputInfo.warnings, never an error. - Track gain and levels (
mixer.rs): each track's clips are summed, multiplied by the track's fader (gainDbabsent is 0 dB,-60or less is silence) and added to the programme, so a clip sounds at track gain times clip gain. The fader lives in an atomic thatoutput_set_track_gain(trackId, gainDb)writes without rebuilding the programme; the callback ramps from the gain the last chunk ended on to the new one over the next 256-frame chunk, so a drag never clicks. After the gain the callback keeps the largest absolute sample of each track in an atomic (fetch_max, no locks, no allocation). The levels lane reads and resets those peaks every ~33 ms and sends them as[{ id, peak }]with linear amplitudes (the UI converts to dBFS); a muted track is not in the clip set and has no peak. Silence is sent once after the audio stops and not repeated. - Updating while running: the callback receives a new
Arc<ClipSet>through the same channel as transport commands and swaps it in.Outputkeeps every set it ever sent until it stops, so the callback is never the one to free memory. - Real-time check: every second the callback compares the audio it rendered with the wall clock; more than 1.5 times faster sets
Position.clockUnpaced, and the UI shows the clock lamp as faulty ("Not real time"). ALSA's null device ("Discard all samples") does exactly that and made the timecode run ~500 times too fast.
On Linux under WSLg only the null device exists until libasound2-plugins is installed, which gives ALSA a pulse and default device that reach WSLg's PulseAudio. The cpal PulseAudio host was tried and could not complete the handshake with WSLg's server, so it is not enabled.
Audio drivers. A project's output.driver names the audio API its devices open through (see docs/project-format.md). On Linux the build offers ALSA, PipeWire and JACK; on macOS and Windows the system's own API and JACK. When PipeWire is running it is the default driver, otherwise ALSA is. PipeWire links libpipewire-0.3 at start-up, so the deb and rpm declare it as a dependency; JACK loads libjack only when it is used. Names belong to one driver: a project that stored an ALSA device name and names no driver looks it up on the default driver, which is PipeWire on a PipeWire system, and shows it as not connected until the device is chosen again.
Lost outputs
A device or port that fails while the output runs is reported output by output. Position.ltcLost and Position.mtcLost are bitmasks: bit i is set when OutputInfo.ltc[i] (or .mtc[i]) is lost, so only the first 32 outputs of each kind have a bit. Position.metronomeLost covers the stream the click plays on and deviceLost the programme's own device; the LTC outputs and the click that play on the programme's stream are lost with it, so their bits (and metronomeLost) are set as well. Each stream and each MTC thread owns an atomic flag (Health in output.rs) that its error callback or send loop sets; PositionReader::position folds them into the masks, and the xhape-log lane logs each output that becomes lost and each that comes back. The UI shows the lamp, the faceplate tooltip and the Setup rows from the masks.
Detecting and recovering
- A stream is lost when its cpal error callback reports anything but a dropout, or when it stops calling back for a second (a watchdog on the stream's thread counts the callbacks, because some hosts never report an unplugged device). A MIDI port is lost when it refuses a message.
- The stream of an LTC or click device that is not the programme's is closed and opened again on its own thread once a second until its device is back; it follows the master's position, so nothing else needs to change. An MTC thread does the same with its port and sends a full frame when it is back. The other outputs keep running meanwhile.
- The programme's stream cannot be reopened in place (the
Rendererowns the transport's command receiver). Thexhape-devicelane looks for the device once a second whiledeviceLostis set and, when it is there, emitsoutput-device-back. The window reopens the output, which carries the playhead over and leaves it stopped: a show never resumes by itself.
Reconfiguring a running output
The command resolves the project's logical signals against the computer's saved routes before calling Output::reconfigure. Changes to physical routes or latency wait for pause/stop; a language-only preference change does not count as a hardware change. Changing whether Edit auditions through its preview requires a restart so that timecode and cue suppression stay consistent. Signal-only edits can reuse the existing branch reconfiguration.
Output::reconfigure compares the resolved output configuration with what runs. What the programme's stream is opened with (its device and channels, the LTC outputs on that same device, the metronome, the frame rate and start offset) is the MasterKey/ClickKey of the plan; if any of it differs the command answers needsRestart and the window reopens the output as for any other change, waiting for stop or pause when it is playing, and carrying the playhead over. Everything else is a branch with its own stop flag: one stream per other LTC device, one for a metronome device that carries nothing else, one thread per MIDI port. A branch that already does what the plan asks keeps running untouched; the ones nobody asks for any more are closed first (they may hold a device a new one needs) and the new ones opened. A branch that failed to open is tried again on every reconfiguration. The OutputInfo rows and the lost-output bits are rebuilt from the plan in current signal-list order. Project slot numbers and local routing keys remain stable when another output is removed. Unassigned LTC/MTC entries retain off-status rows and never open a device or port.
Per-track audio destinations
Audio and operator tracks now resolve to portable named destinations with installation-local hardware mappings. Programme remains the master clock interface. Named destinations share a callback with LTC and the metronome on the same physical device; secondary devices follow the clock with bounded resampling. Audio buses that collide with LTC are silenced, preserving timecode. Routing edits made during Play apply in the backend on pause/stop and preserve the exact parked sample position and paused state.
The independent onAudioRouting channel reports active/desired membership and dynamic health by output ID; unlike older LTC/MTC masks, it has no 32-output limit. Live only renders those reports. See audio-routing.md for persistence, preview, failure handling and validation.