Recording and export
ORIX 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.
Sources:
Recorder.swift(Recorder,AudioExporter,AudioFileFormat,ExportOptions,ExportReport)RenderCore.swift(AudioRing, therecordevent, the tap inrenderChunk)Session.swift(SessionDirectories.recordings,DJSession.recorder)RecordingController.swift,RecordingView.swift- Test:
recordingIsBitAccurateAndExportsValidateinSessionTests.swift
Pipeline
flowchart LR
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)"]
R -->|"read every 40 ms, 16384 frames at a time"| W["Writer: recorder queue, utility QoS"]
W -->|"AVAudioFile.write"| C["Recordings/In Progress/name.caf (float32, stereo)"]
C -->|"user action: Export"| X["AudioExporter.export: trim, fades, gain"]
X --> O["WAV, AIFF, AAC, ALAC or FLAC file"]
O --> V["Reopen and compare length: ExportReport.validated"]
C -->|"next launch"| T["Take list, flagged recovered if never closed"]
What is recorded
The 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 for the signal path.
Render side
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.
While 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.
Writer side
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).
The file on disk
| Property | Value |
|---|---|
| Location | <session root>/Recordings/In Progress/<name>.caf |
| Name | given by the caller; the application uses ORIX DJ yyyy-MM-dd HH.mm.ss. / and : are replaced by -. |
| Container | Core Audio Format (CAF) |
| Sample format | linear PCM, 32-bit float, little endian, 2 channels, interleaved in the file |
| Sample rate | the engine's sample rate |
| Size | 8 bytes per frame: 23.04 MB per minute at 48 kHz, 21.17 MB per minute at 44.1 kHz |
Float 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).
The 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.
Start conditions and stop
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.
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.
Overflow and low disk space
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.
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.
Write error. If AVAudioFile.write throws, the reason is stored in stoppedReason, recording stops and the tap is closed.
In 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.
Recording status in the interface
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".
Export
Export 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.
Processing
AudioExporter.export(source:to:options:progress:) reads the source in blocks of 65 536 frames and, per sample:
- keeps only the selected range (
options.range, in seconds; the editor enforces a minimum of 50 ms); - applies the gain: either
gainDB, or whennormalizePeakDBis 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 withAudioExporter.peak). The editor's Normalise option uses −1 dBFS; - applies a linear fade-in over the first
fadeInseconds and a linear fade-out over the lastfadeOutseconds; - counts samples whose magnitude is at or above full scale (
clippedSamples) and tracks the output peak.
The 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.
Formats
AudioFileFormat lists seven formats, all offered in the editor:
| Case | Extension | Settings passed to AVAudioFile |
Lossless |
|---|---|---|---|
wav24 (default) |
wav |
linear PCM, 24-bit integer, little endian | yes |
wav16 |
wav |
linear PCM, 16-bit integer, little endian | yes |
aiff24 |
aiff |
linear PCM, 24-bit integer, big endian | yes |
aiff16 |
aiff |
linear PCM, 16-bit integer, big endian | yes |
m4aAAC |
m4a |
MPEG-4 AAC, 256 kbit/s | no |
m4aALAC |
m4a |
Apple Lossless, 24-bit hint | yes |
flac |
flac |
FLAC, 24-bit | yes |
There is no MP3 export.
Validation
After 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.
The 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.
What the test verifies
recordingIsBitAccurateAndExportsValidate runs offline with the limiter off:
- 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;
- starting a second recording throws
alreadyRecording; - 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);
- normalising to −1 dBFS gives a peak within 0.01 dB of −1;
- a +30 dB gain is reported as clipped samples; an out-of-range selection throws
empty.
Not verified: recording on a live device over a long duration, recording to a slow or external disk, and exported files in third-party software.
Recovery of interrupted recordings
If 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.
Recorder.recoverableTakes(in:)lists every.caffile larger than 4096 bytes inRecordings/In Progress, sorted by name. Since normally stopped takes also stay in that folder, this list is simply the list of all raw takes.RecordingFiles.scan(inRecordingController.swift) opens each of them withAVAudioFileand keeps those with a non-zero length. It marks a take asrecoveredwhenRecordingFiles.isUnclosedCAFfinds that the CAFdatachunk 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.
A 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.
This 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.
Deleting 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).
Related
- Signal path up to the tap: mixer.md
- Queues and real-time rules: audio-engine.md
- Memory and CPU figures: performance.md
- Test suites: testing.md