SPB Git

Repository Public

recording.md 12.6 KB 143 lines markdown

1# Recording and export23ORIX DJ records its master output to disk and exports takes to common audio formats. Recording and export are two separate steps: a recording always produces a raw 32-bit float CAF file, and nothing is converted until the user exports a take. This document describes the pipeline, its behaviour under overload and low disk space, export and its validation, and what happens to a recording that was interrupted.45Sources:67- [`Recorder.swift`](../../Packages/ORIXDJCore/Sources/ORIXDJEngine/Recorder.swift) (`Recorder`, `AudioExporter`, `AudioFileFormat`, `ExportOptions`, `ExportReport`)8- [`RenderCore.swift`](../../Packages/ORIXDJCore/Sources/ORIXDJEngine/RenderCore.swift) (`AudioRing`, the `record` event, the tap in `renderChunk`)9- [`Session.swift`](../../Packages/ORIXDJCore/Sources/ORIXDJEngine/Session.swift) (`SessionDirectories.recordings`, `DJSession.recorder`)10- [`RecordingController.swift`](../../App/Sources/Features/Recording/RecordingController.swift), [`RecordingView.swift`](../../App/Sources/Features/Recording/RecordingView.swift)11- Test: `recordingIsBitAccurateAndExportsValidate` in [`SessionTests.swift`](../../Packages/ORIXDJCore/Tests/ORIXDJEngineTests/SessionTests.swift)1213## Pipeline1415```mermaid16flowchart LR17    M["Master bus after limiter (render thread)"] -->|"AudioRing.write, per chunk"| R["Lock-free stereo ring (8 s rounded up to a power of two)"]18    R -->|"read every 40 ms, 16384 frames at a time"| W["Writer: recorder queue, utility QoS"]19    W -->|"AVAudioFile.write"| C["Recordings/In Progress/name.caf (float32, stereo)"]20    C -->|"user action: Export"| X["AudioExporter.export: trim, fades, gain"]21    X --> O["WAV, AIFF, AAC, ALAC or FLAC file"]22    O --> V["Reopen and compare length: ExportReport.validated"]23    C -->|"next launch"| T["Take list, flagged recovered if never closed"]24```2526### What is recorded2728The tap is in `RenderCore.renderChunk`, after the master rack, the master volume and the limiter, and before the cue blend. The take is therefore exactly what goes to the master output pair: it includes the limiter when it is on, and it never contains the headphone cue. See [mixer.md](mixer.md) for the signal path.2930### Render side3132`DJSession` creates one `Recorder` for its engine. `Recorder.start` calls `DJEngine.setRecordTap(true)`, which resets the ring's read position and pushes a `record` event; the render thread sets its `recording` flag when it applies the event and resets `recordedFrames` and `recordOverruns`.3334While the flag is set, each rendered chunk (at most 64 frames) is copied into `RenderCore.recordRing` with `AudioRing.write`. The ring is a pair of preallocated float arrays with atomic read and write indices: one writer (the render thread), one reader (the recorder queue), no lock. Its capacity is `sampleRate * 8` frames rounded up to a power of two, which is 524 288 frames at 44.1 and 48 kHz (about 10.9 s at 48 kHz) and 1 048 576 frames at 88.2 and 96 kHz.3536### Writer side3738`Recorder` runs a `DispatchSourceTimer` on the serial queue `ai.spboucher.orix.dj.recorder` (QoS utility) that fires every 40 ms. Each firing calls `drain`, which reads the ring in blocks of up to 16 384 frames into a scratch buffer, de-interleaves them into an `AVAudioPCMBuffer` and appends them with `AVAudioFile.write(from:)` until the ring is empty. After each write it updates `RecordingStatus.duration` and `bytesWritten` (file length × 8 bytes per frame).3940### The file on disk4142| Property | Value |43|---|---|44| Location | `<session root>/Recordings/In Progress/<name>.caf` |45| Name | given by the caller; the application uses `ORIX DJ yyyy-MM-dd HH.mm.ss`. `/` and `:` are replaced by `-`. |46| Container | Core Audio Format (CAF) |47| Sample format | linear PCM, 32-bit float, little endian, 2 channels, interleaved in the file |48| Sample rate | the engine's sample rate |49| Size | 8 bytes per frame: 23.04 MB per minute at 48 kHz, 21.17 MB per minute at 44.1 kHz |5051Float PCM is used so that the take is the engine output without requantisation, and CAF because its audio data can still be read when the file was not closed properly (see Recovery below).5253The raw take stays in `In Progress` after a normal stop. The code does not move or convert it; the header comment of `Recorder.swift` saying that the take "is converted to the chosen format when it stops" does not match the implementation, in which conversion only happens on export.5455### Start conditions and stop5657`start` throws `alreadyRecording` if a take is open, `io` if the folder or file cannot be created, and `lowDiskSpace` if the destination volume has less than `Recorder.minimumFreeBytes` (500 MB) available. In the application, recording starts only from the Record button of the Recording screen or its shortcut (`AppModel.startRecording`); nothing starts it implicitly, and the debug-only `-ORIXRecordDemo` launch argument is the single exception.5859`stop` closes the tap with a `record` event, cancels the timer, waits 60 ms when the device is running (or renders 512 frames when offline) so that the render thread sees the event, performs a final `drain`, and releases the `AVAudioFile`, which finalises the CAF header. It returns the URL of the take.6061## Overflow and low disk space6263**Writer too slow.** If the ring does not have room for a chunk, `AudioRing.write` writes nothing and returns `false`; the render thread drops that chunk and increments `recordOverruns`. The render thread never waits for the disk. Each overrun is a gap of up to 64 frames in the take: the audio after the gap follows directly, so the take becomes shorter than real time. The count is shown live as "Gaps" on the Recording screen, with the warning "gaps in this take: the disk could not keep up" when it is above zero. With the ring sizes above, the writer has to be stalled for more than about 10 s before this happens. The overrun counter restarts at zero with each take. No test forces an overrun; the behaviour is described from the code.6465**Disk filling up.** Every 2 s `drain` reads the free space of the volume. Below half of `minimumFreeBytes` (250 MB) it sets `stoppedReason` to "Recording stopped: the disk is almost full.", clears `isRecording` and closes the tap, leaving room to close the file.6667**Write error.** If `AVAudioFile.write` throws, the reason is stored in `stoppedReason`, recording stops and the tap is closed.6869In both automatic-stop cases the file object stays open until `Recorder.stop()` is called. The Recording screen calls it when it observes the stop; if that screen is not open, the file is released when the recorder is deallocated at exit. This path has not been tested.7071## Recording status in the interface7273`AppModel` polls `Recorder.currentStatus` and exposes it as `model.recording`. `RecordingView.swift` shows the state (READY / RECORDING), elapsed time, live master peaks, size written, free space, the gap count, any stop reason, and the destination path. The transport panel states that the recording "captures the master output as 32-bit float audio".7475## Export7677Export is an explicit action on a selected take. `RecordingController` builds an `ExportOptions` from the editor (trim handles on a peak overview of the take, fade-in and fade-out in seconds, gain in dB or Normalise, format, file name), asks for a destination with a save panel and runs `AudioExporter.export` on a background task with a progress read-out.7879### Processing8081`AudioExporter.export(source:to:options:progress:)` reads the source in blocks of 65 536 frames and, per sample:82831. keeps only the selected range (`options.range`, in seconds; the editor enforces a minimum of 50 ms);842. applies the gain: either `gainDB`, or when `normalizePeakDB` is set, the gain that brings the peak of the selected range to that level (the peak is found by a first pass over the file with `AudioExporter.peak`). The editor's Normalise option uses −1 dBFS;853. applies a linear fade-in over the first `fadeIn` seconds and a linear fade-out over the last `fadeOut` seconds;864. counts samples whose magnitude is at or above full scale (`clippedSamples`) and tracks the output peak.8788The exporter does not resample: the output has the sample rate of the take. It writes two channels. It applies no dither and no limiter of its own; the conversion from float to the target sample format is done by `AVAudioFile`. `ExportOptions` has `title` and `artist` fields, but the export function does not use them: no metadata is written.8990### Formats9192`AudioFileFormat` lists seven formats, all offered in the editor:9394| Case | Extension | Settings passed to `AVAudioFile` | Lossless |95|---|---|---|---|96| `wav24` (default) | `wav` | linear PCM, 24-bit integer, little endian | yes |97| `wav16` | `wav` | linear PCM, 16-bit integer, little endian | yes |98| `aiff24` | `aiff` | linear PCM, 24-bit integer, big endian | yes |99| `aiff16` | `aiff` | linear PCM, 16-bit integer, big endian | yes |100| `m4aAAC` | `m4a` | MPEG-4 AAC, 256 kbit/s | no |101| `m4aALAC` | `m4a` | Apple Lossless, 24-bit hint | yes |102| `flac` | `flac` | FLAC, 24-bit | yes |103104There is no MP3 export.105106### Validation107108After the last block the writer is released so that the file header is finalised, and the result is reopened with `AVAudioFile(forReading:)`. `ExportReport.validated` is true when the reopened length equals the number of frames written; for AAC, which pads to whole packets, a difference of less than 4096 frames is accepted. This validates that the file can be opened and has the expected length. It does not compare sample values.109110The report (`ExportReport`) is shown in the interface: format, duration and frame count, sample rate, peak in dBFS, clipped samples, applied gain, file size and the validated flag. When samples are clipped the interface says how many and suggests lowering the gain or using Normalise. An empty range throws `RecorderError.empty`.111112### What the test verifies113114`recordingIsBitAccurateAndExportsValidate` runs offline with the limiter off:115116- the CAF take equals the rendered master output sample for sample (maximum error required to be exactly 0 over 90 000 frames), with zero overruns;117- starting a second recording throws `alreadyRecording`;118- for each of the seven formats, an export of a 1 s range with 0.1 s fades validates, has 48 000 frames, no clipped sample, and starts in silence; for the lossless formats the samples in the middle match the source within 1/16 384 (16-bit formats) or 1/4 000 000 (the others);119- normalising to −1 dBFS gives a peak within 0.01 dB of −1;120- a +30 dB gain is reported as clipped samples; an out-of-range selection throws `empty`.121122Not verified: recording on a live device over a long duration, recording to a slow or external disk, and exported files in third-party software.123124## Recovery of interrupted recordings125126If the application quits unexpectedly while recording (crash, forced quit, power loss), the CAF file in `In Progress` was never closed. Two mechanisms make it usable afterwards.1271281. `Recorder.recoverableTakes(in:)` lists every `.caf` file larger than 4096 bytes in `Recordings/In Progress`, sorted by name. Since normally stopped takes also stay in that folder, this list is simply the list of all raw takes.1292. `RecordingFiles.scan` (in `RecordingController.swift`) opens each of them with `AVAudioFile` and keeps those with a non-zero length. It marks a take as `recovered` when `RecordingFiles.isUnclosedCAF` finds that the CAF `data` chunk was never finalised: the chunk size is still −1 ("unknown"), or the chunk does not reach the end of the file. The check walks the chunk headers from byte 8.130131A recovered take appears in the take list with a bandage icon and the label "recovered"; selecting it shows "Recovered take: the session that recorded it ended unexpectedly. Everything written before that moment is here; export it to keep it." It can be exported like any other take. What is in the file is everything the writer had appended before the interruption; audio still in the ring or in the writer's buffer at that moment (the writer runs every 40 ms) is lost.132133This relies on `AVAudioFile` reading a CAF whose data chunk size is unknown. The `recovered` flag logic and that reading path are not covered by a test in the package; the package test only checks that `recoverableTakes` returns a normally closed take.134135Deleting a take from the interface moves the CAF to the Trash after confirmation; exported files are not touched. The take list also shows exported files found in the `Recordings` folder, with buttons to reveal them in Finder or add them to the library ([persistence.md](persistence.md)).136137## Related138139- Signal path up to the tap: [mixer.md](mixer.md)140- Queues and real-time rules: [audio-engine.md](audio-engine.md)141- Memory and CPU figures: [performance.md](../development/performance.md)142- Test suites: [testing.md](../development/testing.md)143
Files main
Menu

Theme