scarletbook-rs
A clean-room, permissively licensed Rust library for reading Super Audio CD (Scarletbook) disc images, written only from the specifications and conformance corpus of aclater/sacd-spec.
Work in progress, built in stages (one pull request each): TOC and sector detection, audio sector multiplexing, DST decoding, C FFI. The clean-room record is in CLEANROOM.md; before contributing, read CONTRIBUTING.md, which explains the clean-room rule. Changes are listed in CHANGELOG.md, and vulnerabilities are reported as described in SECURITY.md.
Installing
The crates are on crates.io: scarletbook (the
reader), scarletbook-pcm (DSD to PCM) and
scarletbook-ffi (the C ABI, from 0.5.8, for Rust programs
that build the C library themselves; C users take the release assets).
use ;
use ;
Byte stability. While the version is 0.x, a new 0.5.y release may change the PCM bytes
that scarletbook-pcm (and the C library's sb_pcm_*) produce; the decoded DSD bytes are
fixed by the specification. Cargo treats 0.5.y as compatible with 0.5.x, so a plain
scarletbook-pcm = "0.5" picks up such changes on cargo update. A consumer that needs the
same PCM bytes across builds (stored hashes, reproducible files) pins the exact version:
= "=0.5.9"
Layout
| Path | Content |
|---|---|
crates/scarletbook |
the library (#![deny(unsafe_code)], with one run-time dispatch module as the exception; no I/O beyond the reader it is given) |
crates/scarletbook-pcm |
DSD64 to 24-bit PCM conversion (88.2, 176.4 and 352.8 kHz), deterministic per frame; independent of the reader; see its README |
crates/scarletbook-ffi |
the C ABI (include/scarletbook.h, generated by cbindgen; libscarletbook_ffi.{a,so,dylib}, scarletbook_ffi.dll); see C library |
crates/scarletbook-bench |
bench, the benchmark program of sacd-spec benchmarks/README.md |
crates/scarletbook-conformance |
the corpus runner and scarletbook-toc, which prints a TOC as manifest-shaped JSON |
corpus/ |
the sacd-spec conformance corpus, copied unchanged (CC0-1.0) |
fuzz/ |
cargo-fuzz targets, seeded from the corpus |
Using the library
use ;
use ;
let mut disc = open?;
for frame in disc.track_audio?
// Any frame range [first, end) of an area's timeline, pauses included: here the whole area,
// then track 2 with the pause after it.
let area = disc.toc.area.ok_or?;
let playtime = area.playtime_frames;
for frame in disc.range_audio?
let = disc.track_range_with_pause?;
for frame in disc.range_audio?
Stored content (DSDIFF passthrough)
To copy DST frames unchanged (for example into a DSDIFF file), read positions without decoding them (specification 4, 4.6.1):
use FrameContent;
// A track's or range's positions as stored: DST bytes, plain DSD bytes, or missing.
let mut frames = disc.range_frames?;
while let Some = frames.next
let missing = frames.missing_frames;
// Every accepted frame of the area, in frame number order, frames past the play time
// included; positions not listed are missing.
for frame in disc.stored_frame_list?
Disc::track_frames does the same for a track. Positions, missing frames and malformed
sectors are exactly those of the decoded reads; invalid DST frames show only when decoded.
In C: sb_raw_frames_open, sb_raw_frames_read, sb_raw_frames_read_dst_equivalent and
sb_stored_frame_list_open, with caller buffers of at most SB_MAX_FRAME_BYTES.
DSF and DSDIFF files
scarletbook::output (the default output feature) lays out a track, a track with pause or
any frame range as a DSF file, with an ID3v2.4 tag, or a DSDIFF file, with plain DSD or the
DST frames unchanged, markers and text, or as an edited master (specification 8). The file's
size and every byte that isn't audio come from the TOC alone, so a filesystem can list the
file before reading any audio, and produce any byte range of it:
use ;
let = disc.track_range_with_pause?;
let layout = disc.output_layout?;
let size = layout.size;
let mut buf = vec!;
let n = layout.read_at?;
// Or with positions from a cache of your own:
let needed = layout.positions_for;
let n = layout.fill?;
A DST file's size needs the frames' lengths too: DstLengths::scan reads them without
decoding (they can be saved and loaded), and Disc::output_layout_dst lays the file out
from them. Every point where the formats allow more than one valid output (8.6, "writer's
choices") is a field of OutputOptions with a documented default; TagSet::from_toc gives
the tag items, which the caller may change. In C: sb_output_options_*, sb_tags_*,
sb_dst_lengths_* and sb_output_layout_* (see Output files).
The departures from the DSDIFF document that some existing programs make (8.7: D1, CMPR's
size counting its pad byte; D2, text as ISO 8859-1) are made only when named, in
OutputOptions::dsdiff_departures or with SB_OUTPUT_OPTION_DSDIFF_DEPARTURE_D1 and _D2.
A file written with one is not a conforming DSDIFF file.
An area's tracks as separate files take no writer of their own, only a loop over these
calls: use Disc::continue_range_audio from track to track, since a plain range_audio per
track rescans the area (more than 2x slower measured on a 16-track stereo area). That
sequential loop gains nothing over one file. Workers gain on real storage, in two forms:
- Seek index first: the bytes are exact.
- Speculative with a verifying pass: the bytes are provisional when written (specification 4, 4.2 item 8). They are exact only once the pass is complete and every reading is exact or confirmed, and any other reading's file is rewritten.
Workers reading speculatively with no verifying pass are a speed figure only: nothing
establishes their bytes, and matching hashes on some images don't. The scarletbook::output
documentation has the code for each form. The figures are on
#202: they come from one machine, so
measure on yours.
Seeking within an area
A range far into an area normally costs a scan of the area up to it: which frames a range holds depends on every audio sector before it (specification 4, 4.5), so an exact reader cannot skip ahead without having read them once. A seek index keeps the reading state every 64 sectors, so that once it covers a range, opening that range reads only a few dozen sectors before the range's own, wherever it lies (specification 4, 4.2 item 7). It is off by default:
use ;
disc.enable_seek_index?;
// Reads build it as they go; or build it at once, in steps (one pass over the area):
while !disc.extend_seek_index?
// Every track and range cursor of the area now starts from it, with the same frames,
// counts and warnings as without it.
let audio = disc.range_audio?;
// Keep it for the next time this image is opened (about 24 bytes per 64 sectors).
let saved: = disc.seek_index.map.unwrap_or_default;
// ... later: from_bytes checks the bytes, set_seek_index the area.
let index = from_bytes?;
disc.set_seek_index?;
A saved index is checked for safety (bounds, invariants, checksum, the area and image size
it belongs to) and, as it is used, against the image's sectors (a digest per checkpoint):
a mismatched index is discarded with a warning in the log and the area scanned from its
start. It is not proof against an index forged to match: keep it with the image it
describes. Every disc of one image (Disc::share, or clone of a disc read through a
ReadAtReader) uses and grows the same index, so to build it in the background, call
extend_seek_index on a clone in another thread while the others read; AreaIndex::merge
joins indexes kept apart, for example one loaded and one built.
A first seek into an area without a seek index still reads the area up to the range, which
over a network share can take seconds. A caller that accepts provisional positions can opt in
to provisional reading (specification 4, 4.2 item 8): disc.set_seek_policy(slot, SeekPolicy::Speculative(SpeculativeOptions::new())) makes far ranges start after a short
search of the frame timecodes, a few small reads wherever the range lies, and read the range
in reads sized to it (one for a range of up to 1 MiB). Their positions are
marked provisional (speculation()): they equal a straight read on well-formed discs, but no
reader can know that without reading the sectors before the range, and on hostile images they
can differ (see SeekPolicy). Their malformed counts begin at the provisional start
(counts_from()). With a seek index enabled for the area, each provisional reading is
checked once the index reaches it (build it with disc.verify_speculation(slot, sectors),
for example on a clone in another thread): confirmed, or refuted with the frame from which its
positions are exact; the cursor's speculation() and disc.take_seek_events(slot) report it,
so that a caller can drop and re-read what it served. A provisional reading the library has
its own reasons to doubt is marked suspect (suspect(): an area whose TOC places its
audio past the image's end or over the other area's sectors, or frame numbers that decreased
between the sectors its search read; 4.2 item 8), and
SpeculativeOptions::with_exact_when_suspect(true) reads those exactly instead. The mark is
informative: it does not change how the reading is settled.
The seek index also keeps seek hints (the locator samples of specification 4, 4.2 item 8):
sectors its cursors read with the frame number of their first frame record, every 8 frames,
at most 2 048 (8 bytes each, IndexOptions::with_hints). They are saved with the index
(AreaIndex::to_bytes), so that after a remount or a restart a provisional reading near a
range read before begins at the hint below it and reads through the hint past it: one read
call, the range's sectors and a few more, with no search and no pass from the area's start.
Its positions are provisional all the same; a hint only chooses where to begin. A hint whose
sector no longer has its frame record (a stale index, or one of another image) is dropped
with a warning, and the cursor searches instead; an index saved by a disc carries a
fingerprint of its TOC, and a disc with another TOC refuses it (Disc::set_seek_index). With
a complete saved index, an exact read starts with one read sized to the range.
When a pass (disc.verify_speculation) has confirmed a provisional reading, the index keeps
that confirmation with the hint (4.2 item 9): after a remount, a reading from that hint for
the same or a later first frame is reported confirmed at once, still in one read call, if the
index is bound to the disc (key and TOC fingerprint) and the hint's sector has the bytes the
pass read. AreaIndex::without_checkpoints keeps only the hints, confirmations and
fingerprint: a few kilobytes per area to save, for a caller that keeps many discs. Saved
confirmations, like saved exact checkpoints, are trusted for any image whose TOC fingerprint
and key match, so a re-rip with different audio bytes would get confirmed readings that
differ: key saved indexes by the image file's identity (path, size and modification time, or
a content hash) as well.
Features: parallel decodes DST frames on rayon's thread pool, ahead of the caller: the
current pool by default, or the pool chosen for a cursor with
TrackAudioCursor::set_decode_on(DecodeOn::Pool(pool)), whichever thread reads it
(DecodeOn::CallingThread keeps a cursor off every pool).
With parallel, rayon 1 is part of the public Rust API, and that is a stated decision (#39):
DecodeOn::Pool takes an Arc<rayon::ThreadPool>, not a wrapper of this library's. rayon 1 is
stable, and a wrapper would add interface for a problem that may never come. The cost is that a
rayon 2 would need a new major version of scarletbook. A program's pool must come from rayon 1.
C library
struct SbDisc *disc;
if ;
sb_build_info() says how the loaded library was built, for logs and bug reports: a
static string of key=value pairs naming its version, target, profile, features, target
CPU features, compiler and commit.
The conventions (status codes, copy-out strings, handle lifetimes, threads) are stated
at the top of crates/scarletbook-ffi/include/scarletbook.h;
crates/scarletbook-ffi/examples/smoke.c is a complete program. Calls return an
SbStatus, an int32_t; every struct field is a fixed-width integer (flags are uint8_t,
1 or 0) or, in SbWarning, a string pointer; and no struct has padding, so the layouts
stated in the header hold on every target. Regenerate the header with
cbindgen --config cbindgen.toml --crate scarletbook-ffi --output include/scarletbook.h
in crates/scarletbook-ffi (cbindgen 0.29.4; CI checks the committed header).
Beyond SbDiscInfo, SbAreaInfo and the strings, the master TOC's genres
(sb_disc_genre), text channels with their language codes as stored and character set
codes (sb_disc_text_channel_count, sb_disc_text_channel), catalogue numbers as stored,
padding kept (sb_disc_catalog_number_stored), and manufacturer data
(sb_disc_manufacturer) have calls of their own, as do an area's version, maximum
available channels, mute flags, track attribute and offset, and text channels
(sb_area_details, sb_area_text_channel). The area play time and each track's start and
duration are also given as their stored timecode bytes (SbTimecode:
sb_area_playtime_stored, sb_track_timecodes_stored), before any clamping and whatever
their range, beside the frame counts of SbAreaInfo and SbTrackInfo.
sb_disc_read_sectors(disc, lsn, count, buf, cap) copies the 2048-byte user data of
logical sectors [lsn, lsn + count), whatever the image's stored sector size (2048, 2054
or 2064 bytes): the bytes a 2048-byte-sector copy of the image holds there, for example to
digest the TOC sectors or write such a copy. A range reaching past the last sector fails
whole with SB_STATUS_SECTOR_RANGE_INVALID, writing nothing.
Seeking
A seek index (see Seeking within an area) is a handle of its
own, SbSeekIndex, tied to an area and image size rather than to a disc handle, so it can
be built on one disc handle and used on another of the same image:
SbSeekIndex *index = NULL;
;
uint8_t complete = 0;
while
SbTrackAudio *audio = NULL;
; /* same frames, few reads */
/* ... sb_track_audio_read ... then hand its new checkpoints back: */
;
size_t len = 0;
; /* SB_STATUS_BUFFER_TOO_SMALL, *len set */
/* ... sb_seek_index_save(index, buf, len, &len); later
sb_seek_index_load(disc, slot, buf, len, SB_SEEK_DEFAULT_INLINE_BUDGET, &index) */
sb_range_audio_open_next_indexed and sb_raw_frames_open_next_indexed continue a handle
through an index; sb_seek_index_merge joins indexes built apart.
A disc can also keep the index itself: after sb_disc_seek_index_enable (or
sb_disc_seek_index_set with a loaded one), every handle opened through the disc or any of
its clones (sb_disc_clone) starts from it, and reads build it, with no _indexed calls.
The disc and its clones keep one index, so sb_disc_seek_index_extend on a clone in a
thread of its own builds it for all of them; sb_disc_seek_index_get copies it out to
save. Loaded bytes are checked
before use, and an index that does not match the image's sectors is discarded as it is used
(a warning in the log, then a scan from the area's first sector).
Provisional reading (cold seeks, specification 4, 4.2 item 8) is opt-in per disc handle:
sb_disc_seek_policy_set(disc, slot, SB_SEEK_POLICY_SPECULATIVE, SB_SEEK_DEFAULT_MIN_GAP).
After a handle's first read, sb_track_audio_speculation says whether its positions are
provisional (SbSpeculation), and sb_track_audio_suspect whether the library has reasons
of its own to doubt that reading (SB_SUSPECT_*, an informative mark;
SB_SEEK_POLICY_SPECULATIVE_EXACT_WHEN_SUSPECT reads those exactly instead). With a seek index kept, sb_disc_seek_verify (on a clone in a
thread of its own) checks provisional readings, and sb_disc_seek_event_next returns each
verdict once: confirmed, or refuted with the frame from which the positions are exact
(exact_from; re-read the positions below it with SB_SEEK_POLICY_EXACT for those of a
straight read). A disc that keeps a seek index of the area hands each reading through it to
that index, also for ranges opened with an index of the caller's.
Output files
The DSF and DSDIFF layouts of DSF and DSDIFF files:
SbOutputOptions *opts = NULL;
;
; /* each writer's choice */
SbOutputLayout *layout = NULL;
;
SbOutputLayoutInfo info;
; /* info.size, from the TOC */
size_t n = 0;
; /* any byte range */
/* or sb_output_layout_positions + sb_output_layout_fill with positions you hold */
For DST passthrough, sb_dst_lengths_scan (or sb_dst_lengths_load) and
sb_output_layout_new_dst. For gapless DSF files of consecutive ranges (specification 8,
8.2.7), sb_output_dsf_chain_plan, then each file with SB_OUTPUT_OPTION_DSF_CHAIN_FIRST
and SB_OUTPUT_OPTION_DSF_CHAIN_END set to its entry's chain_first and chain_end. Tag items: sb_tags_from_toc, sb_tags_set, sb_tags_push,
sb_tags_remove, then sb_output_options_set_tags. An area whose loudspeaker layout is
unspecified is refused for DSF with SB_STATUS_OUTPUT_LAYOUT_UNSPECIFIED unless a channel
type is given, and an edited master that 8.4.11 excludes with SB_STATUS_NOT_EDITED_MASTER.
Parallel decoding
Track and range audio handles decode on the calling thread unless given a pool of decoding threads:
struct SbPool *pool;
; /* 0: one thread per logical CPU */
;
; /* continuations keep it */
; /* reference-counted: the handle keeps it alive */
while
;
The calling thread still reads the disc (read callbacks run there) and receives the frames
in order, while the pool decodes DST frames ahead of it; the output is exactly that of the
calling thread. A handle holds at most 16 x threads frames ahead, never more than 512
(about 48 MB at most). A pool may be shared by handles of several discs read on several
threads. The library creates no global pool; the log callback is also called from the
pool's threads (see sb_disc_set_log).
To read one image on several threads at once (for example several tracks of one disc),
give each thread a clone of the disc: sb_disc_clone(disc, ©) shares the parsed TOC
and reads the same file or memory at a position of its own, and a track handle opened from
any clone may be read through any other. A disc opened with read and seek callbacks cannot
be cloned that way: open it with a positional read callback instead
(sb_disc_open_callbacks_at, called with an offset, possibly from several threads at once),
or give each clone read and seek callbacks of its own (sb_disc_clone_callbacks).
Stored and decoded frames in one pass
A track or range audio handle can also give each position's stored content, as
sb_raw_frames_read gives it, next to its decoded audio, from one read of the area's
sectors (for example to write a file of the stored DST frames and decoded files at once):
;
; /* optional, as for any handle */
; /* before the first read */
uint8_t raw;
SbRawFrameInfo ri;
while
The decoding runs where the handle decodes, with the same frames held ahead; the frames, statuses, kinds and counts are those of the two separate handles, and each audio sector is read once.
Cancelling and progress
A conversion running on a worker thread can be stopped and followed from another thread, through two small handles made for that, which several threads may use at once:
SbCancel *token = NULL;
; /* on the disc's thread: shared by its clones */
SbProgress *progress = NULL;
; /* on the handle's thread, before reading */
/* worker thread: while (sb_track_audio_read(audio, disc, ...) == SB_STATUS_OK) {...} */
/* other thread: */
uint64_t read, expected;
; /* sectors read, sectors expected */
; /* e.g. on Ctrl-C */
While cancellation is requested, every call that reads audio sectors through the disc or
its clones returns SB_STATUS_CANCELLED, distinct from SB_STATUS_IO: at once for a call
that starts then, after at most 32 more sectors for one in progress (or, during the reads
sized to the range after a provisional start or a resume from a seek index, after the read
in progress, of at most 512 sectors, 1 MiB),
the scan before a range's first frame included, whatever the disc reads through (a file, memory or
callbacks). The request is sticky: it holds for the disc and its clones until
sb_cancel_withdraw (a disc opened afresh has a token of its own). The handles keep their
state: after sb_cancel_withdraw they continue exactly where they stopped; or free them. sb_progress_get gives the sectors a handle has read
(exact, updated at least every 32 sectors, or every read of at most 512 sized to a
range after a provisional start or a resume from a seek index, also during the scan before
its first frame)
and the sectors it expects to read (an estimate, equal to the count read once done), for
track, range and raw frames handles. Neither handle borrows the disc or the handle it came
from, so polling it never collides with the reading thread; free each with its _free.
DSD to PCM
The library also converts the decoded DSD64 audio to 24-bit PCM (crate
scarletbook-pcm) at 88.2, 176.4 or 352.8 kHz, through a converter handle that belongs
to no disc:
SbPcmConverter *conv = NULL;
;
uint32_t spf; /* output samples per channel per frame */
; /* 1176, 2352 or 4704 */
/* prev, cur, next: frames f - 1, f, f + 1 of the area from sb_track_audio_read (prev NULL
* at the area's first frame, next NULL at its last); each channels x 4704 bytes. */
uint64_t clipped;
;
;
A frame is 4704 bytes per channel, 37 632 one-bit samples (1/75 s). sb_pcm_convert_run
converts a run of whole frames (one frame, or a whole area with both neighbours NULL) into
frames x spf x channels interleaved samples of 4 bytes (SB_PCM_S32, an int32_t
sign-extended from 24 bits) or 3 (SB_PCM_S24LE, the layout of 24-bit WAV and FLAC); with
out NULL or too short it returns SB_STATUS_BUFFER_TOO_SMALL and writes nothing. The
cutoffs are SB_PCM_CUTOFF_DEFAULT (passband to 40 kHz), SB_PCM_CUTOFF_LOW (30 kHz) and
SB_PCM_CUTOFF_WIDE (80 kHz, at 176.4 and 352.8 kHz only); the gain is -120 to +24 dB, and
clipped (or NULL) receives the samples of each channel clamped to 24 bits.
The output depends only on the input bits: frame f converted with frames f - 1 and f + 1 as neighbours is byte for byte frame f of a conversion of the whole area. So frames can be converted in any order, on any number of threads (one converter each), and a seek needs only the frames around it. The filters, their measured response and the throughput are in the crate's README.
From Python, with the bindings of "Using from Python (ctypes)" below:
, = ,
# SB_PCM_CUTOFF_DEFAULT
, = ,
# SB_PCM_S24LE
Release assets
Each release carries the C library as scarletbook-ffi-<version>-<target>.tar.gz, with a
SHA-256 file scarletbook-ffi-<version>-<target>.tar.gz.sha256. Every one is built and
tested on its platform (.github/workflows/clib.yml): a C program linked statically and
dynamically, and Python's ctypes, decode a corpus image and compare TOC and audio with the
conformance manifest.
<target> |
Runs on | Built in |
|---|---|---|
x86_64-unknown-linux-gnu |
glibc 2.17 or later (manylinux2014) | manylinux2014 image |
aarch64-unknown-linux-gnu |
glibc 2.17 or later (manylinux2014) | manylinux2014 image |
x86_64-unknown-linux-musl |
musl 1.2 or later (musllinux_1_2), with libgcc_s.so.1 |
musllinux_1_2 image |
aarch64-unknown-linux-musl |
musl 1.2 or later (musllinux_1_2), with libgcc_s.so.1 |
musllinux_1_2 image |
x86_64-apple-darwin |
macOS 10.12 or later | MACOSX_DEPLOYMENT_TARGET=10.12 |
aarch64-apple-darwin |
macOS 11.0 or later | MACOSX_DEPLOYMENT_TARGET=11.0 |
x86_64-pc-windows-gnu |
Windows 10 or later; links with a UCRT MinGW-w64 GCC (MSYS2 UCRT64 or equivalent) | MinGW-w64 target |
x86_64-unknown-linux-gnu-v3 |
as x86_64-unknown-linux-gnu, on an x86-64-v3 CPU only |
manylinux2014 image, -C target-cpu=x86-64-v3 |
x86_64-unknown-linux-musl-v3 |
as x86_64-unknown-linux-musl, on an x86-64-v3 CPU only |
musllinux_1_2 image, -C target-cpu=x86-64-v3 |
The two -v3 archives are the x86_64 Linux libraries built a second time for
microarchitecture level x86-64-v3 of the x86-64 psABI: the v3 archive is compiled entirely
for x86-64-v3, every crate of it. They have the same ABI, header and packaging as the
baseline archives next to them, which stay built for the baseline x86-64 level; only the
instructions differ. They are meant for benchmarks and for consumers who build per CPU
(#146).
They need x86-64-v3: AVX, AVX2, BMI1, BMI2, F16C, FMA, LZCNT, MOVBE and OSXSAVE, on
top of the x86-64-v2 features (CMPXCHG16B, LAHF/SAHF, POPCNT, SSE3, SSE4.1, SSE4.2,
SSSE3). On a CPU without one of them the library fails with an illegal instruction
(SIGILL), possibly not when it is loaded but on the first call that uses it, so check before
you load it, never after: a program that picks an archive at run time loads the -v3 one
only if the CPU reports every feature of the level and the operating system has enabled
the AVX state (CPUID's OSXSAVE bit and XGETBV's XMM and YMM bits, or every one of avx avx2 bmi1 bmi2 f16c fma abm movbe xsave cx16 lahf_lm popcnt sse4_1 sse4_2 ssse3 in Linux's
/proc/cpuinfo flags, where LZCNT is abm), and the baseline archive otherwise. glibc 2.33
and later report the level itself: ld.so --help lists x86-64-v3 (supported, searched).
sb_build_info() tells which one is loaded: the -v3 library's target-features include
avx2, bmi2, fma, lzcnt and movbe and the rest of the level, the baseline one's are
fxsr,sse,sse2. In both, target is the triple without -v3.
The glibc builds are linked against glibc 2.17 itself, inside the manylinux2014 image, and
the build fails if the shared library asks for a newer glibc symbol version. The
macOS minimums are Rust's own for those targets. The Windows build uses Rust's MinGW-w64
target because its static library (libscarletbook_ffi.a) and import library
(libscarletbook_ffi.dll.a) are in the format MinGW-w64 GCC links; the DLL exports every
sb_* function (checked in CI) and depends only on Windows system DLLs. It uses the
Universal C Runtime (UCRT, api-ms-win-crt-*.dll, part of Windows 10 and later), so link
the static library with a UCRT MinGW-w64 toolchain (MSYS2 UCRT64 or equivalent); there is
no msvcrt variant.
Runtime dependencies on Linux: the shared libraries need libgcc_s.so.1 (the unwinder) as
well as the C library. glibc systems have it as part of GCC's runtime (manylinux allows
it); on Alpine and other musl systems it is the libgcc package (apk add libgcc). The
static libraries list it in native-static-libs.txt (-lgcc_s).
Intel CET on x86-64 Linux: the shared library and every object in the static library, of
the -v3 archives too, carry the shadow stack (SHSTK) property (readelf -n shows
x86 feature: SHSTK; checked in CI), so a program built with -fcf-protection stays SHSTK-marked when it links either one, and
glibc with shadow stacks enabled loads it. The libraries carry no unwinder of their own: a
panic caught at the C boundary unwinds through the system libgcc_s, which keeps the shadow
stack in step on distributions that enable it (for example Fedora 44's libgcc 16.2.1 is
itself marked IBT and SHSTK). Shadow stacks are enabled per thread by glibc; musl has no
shadow-stack support today, so on musl systems the mark only matters if the library ends up
in a glibc program. They are not marked for indirect branch tracking
(IBT): stable Rust's precompiled standard library has no ENDBR64 instructions, so a
program that links the static library loses its IBT mark. Do not force it back with
-Wl,-z,ibt. Linux does not enforce IBT in user space today. IBT marking waits for a
stable cf-protection option in rustc and a standard library built with it (issue #125).
The PyPA build images are pinned by digest; .github/workflows/clib.yml says how to move
to newer ones.
An archive unpacks to:
scarletbook-ffi-<version>-<target>/ (scarletbook-ffi-<version>-<target>-v3/ for a -v3 archive)
include/scarletbook.h
lib/libscarletbook_ffi.a static library (every target)
lib/libscarletbook_ffi.so shared library (Linux)
lib/libscarletbook_ffi.dylib shared library (macOS)
lib/scarletbook_ffi.dll shared library (Windows) ...
lib/libscarletbook_ffi.dll.a ... and its import library
native-static-libs.txt system libraries to link after the static library
README.txt, LICENSE-MIT, LICENSE-APACHE
Verifying a download
The attestation (a signed SLSA build provenance statement naming the workflow run and commit that built the file) exists once the repository is public; until then releases are published without one.
Linking
# Static: the archive, then the system libraries it needs.
# Shared: ship the library next to the program, or set an rpath.
The Linux shared library has the SONAME libscarletbook_ffi.so and the macOS one the
install name @rpath/libscarletbook_ffi.dylib, so a program finds them through its rpath
(-Wl,-rpath,@loader_path on macOS). The SONAME is unversioned, since integrators ship the
library with their program; to be revisited at 1.0. With MinGW-w64 GCC,
-lscarletbook_ffi picks the import library (.dll.a), so the program needs
scarletbook_ffi.dll at run time; link the static library by its path instead to avoid
that.
Using from Python (ctypes)
The library loads with Python's ctypes; there are no variadic functions, and every
type has a fixed ctypes counterpart. Check the ABI version first: the bindings below are
written for SB_ABI_VERSION 2, and a library of another ABI version must not be used
with them (see "ABI compatibility"). Give every function its argtypes and restype:
without them ctypes passes and returns C int, which truncates pointers and 64-bit values.
= # .dylib on macOS, scarletbook_ffi.dll on Windows
= 2 # the SB_ABI_VERSION of the header these bindings follow
, = ,
# The structs, field for field as in scarletbook.h (flags are uint8_t, 1 or 0).
=
=
=
=
=
=
=
=
# language: the code's two bytes as stored
=
=
# The layout of sb_disc_toc (format 1.0); see "The whole TOC in one call" below.
=
=
=
=
=
=
=
# DSF and DSDIFF output; see "Output files".
=
=
= +
=
=
=
# Handles are opaque pointers; SbStatus is an int32_t (0 OK, 1 END, 2 ABSENT, negative:
# failure); size_t is only the length of a buffer of yours.
, , , , = , , , ,
=
, = ,
The other functions bind the same way from their declarations in scarletbook.h. Then:
"""Raises on a failure, with the calling thread's error message."""
return
"""A disc string (SbDiscString), or None when absent: size it, then copy it."""
=
# SB_STATUS_ABSENT
return None
=
return # may contain U+0000: use the length, not the NUL
=
# a UTF-8 path
=
= # SB_DISC_STRING_ALBUM_TITLE
=
# 2-channel area, track 1
=
=
= # interleaved DSD, channels x 4704 bytes
ctypes releases the GIL for each call, so conversions on several Python threads run in
parallel: give each thread its own disc (or a clone of one, sb_disc_clone) and handles
(a handle may move between threads but not be used by two at once; an SbPool,
SbCancel or SbProgress may be shared), and read sb_last_error_message()
on the thread whose call failed, before that thread's next call, as check does. Every
handle has its _free function; nothing else needs freeing (the strings the library
returns are static or copied into your buffers). Callbacks (sb_disc_open_callbacks,
sb_disc_set_log) are ctypes.CFUNCTYPE objects: keep a reference to them until the disc
is freed, and catch every exception inside them: ctypes only prints it, and the library then gets
an unspecified value (for a read callback, return -1 instead). A log callback can be
called from a pool's threads (see sb_disc_set_log).
.github/scripts/clib-smoke.py checks the first block above against the header and runs it.
The whole TOC in one call
Reading a TOC field by field takes about 100 to 160 calls for a typical disc. From Python,
each call costs far more than the library spends on it. sb_disc_toc writes the whole TOC
into one buffer instead: what the disc, area, track, string, genre, text channel,
timecode and warning queries return, in a fixed, versioned layout (#132). It does no I/O,
since it uses the TOC parsed at open.
- Layout.
SbTocHeadersits at offset 0. It gives the offset of theSbTocDiscrecord, of theSbTocArearecords (insb_disc_areaorder) and of theSbTocWarningrecords, with each kind's record size. Each area'stracks_offsetpoints to itsSbTocTrackrecords, in track number order. Strings areSbTocStrrefs (offset,length) into the string area at the end. Each string is followed by a NUL thatlengthdoes not count.offset == SB_TOC_ABSENT(0xFFFFFFFF) marks an absent string, where the per-field call would returnSB_STATUS_ABSENT. - Byte order and alignment. Every integer is little-endian on every host. Every
field sits at a fixed offset that is a multiple of its size, and every record size is a
multiple of 8. So a buffer aligned to 8 bytes can be read through the structs on a
little-endian host, or parsed with
struct.unpack_from("<...")anywhere. - Versions. The header carries the magic
SBTOC\0\0\0,major(SB_TOC_MAJOR, 1) andminor(SB_TOC_MINOR, 0). Refuse any other major version. A minor version only appends fields to the end of records, so step through records by the header's record sizes, not bysizeof. The format 1.0 sizes are 56, 256, 152, 168 and 24 bytes (header, disc, area, track, warning). - Size.
flagsmust be 0.*lenreceives the layout's size. If the buffer is NULL or smaller than that, the call writes nothing and returnsSB_STATUS_BUFFER_TOO_SMALL. The recommended single-call pattern is to pass a 64 KiB buffer, which is enough for typical discs (a few KB), and to call again with*lenbytes only when that is too small. A disc of 2 x 255 titled tracks needs about 97 KB.
= # reuse it from disc to disc
=
=
# SB_STATUS_BUFFER_TOO_SMALL
=
=
=
= # create_string_buffer memory is malloc'd: 8-aligned
return None
=
= # SB_DISC_STRING_ALBUM_TITLE
=
=
= # SB_TRACK_STRING_TITLE
The overlay above assumes a little-endian host. On any host, struct.unpack_from("<I", raw, offset) reads the same fields at the offsets documented in scarletbook.h.
ABI compatibility
The ABI is everything scarletbook.h declares (functions and their signatures, struct
layouts, enum names and values, macros) and the behaviour the header documents.
SB_ABI_VERSION in the header, and sb_abi_version() in the library, number its breaking
changes:
- Additions keep
SB_ABI_VERSION: new functions, new types, new enum values (status codes included: treat a status you do not know as a failure) and new macros. A program built against an older header keeps working with the newer library. - Breaking changes increment
SB_ABI_VERSIONby one: removing or renaming a declaration, changing a signature, changing a struct's layout (adding a field included: callers allocate the structs), changing an enum value, or changing documented behaviour incompatibly. The check below compares declarations as text, so it also counts renaming a parameter and reordering existing declarations as breaking; avoid both. - Comments and documentation fixes that do not change behaviour are not ABI changes.
Releases follow this:
- a patch release (
x.y.Z) does not change the ABI; - a minor release (
x.Y.0) may add to it, never break it; - only a major release (
X.0.0) may break it, and then incrementsSB_ABI_VERSION.
While the version is 0.y.z, as in Cargo, the y step is the major one and the z step
the minor one, so there are no patch releases before 1.0.
The -v3 archives of a release carry the same ABI as its baseline archives, at the same
SB_ABI_VERSION and sb_version(); they differ only in the instruction set (see
"Release assets"), which the ABI does not cover. A program can switch between the two
without rebuilding, but must check the CPU before it loads the -v3 library.
A program checks sb_abi_version() == SB_ABI_VERSION before using the library. Since
additions keep SB_ABI_VERSION, a program that needs a function added in a later minor
release also checks sb_version(): the library must be at least that release. A program
that loads the library at run time can look the symbol up instead.
SB_ABI_VERSION |
First release |
|---|---|
| 1 | 0.1.0 to 0.3.0 (additions only in 0.3.0) |
| 2 | 0.4.0 (additions in 0.4.1, 0.5.0, 0.5.1, 0.5.2, 0.5.3 and 0.5.4) |
CI enforces this. crates/scarletbook-ffi/abi/abi-N.txt is the baseline of ABI version N:
the header's declarations without comments or layout. .github/scripts/abi-check.py
compares the header with the baseline of its SB_ABI_VERSION and says which case applies:
- a pure addition fails with "additive change: regenerate the baseline with --write". Run
python3 .github/scripts/abi-check.py --writein the same commit, so the baseline always matches the header onmain; - anything else fails with "breaking change: bump SB_ABI_VERSION and add abi-(N+1).txt".
Increment
SB_ABI_VERSIONincrates/scarletbook-ffi/src/lib.rs, regenerate the header with cbindgen (see above; editing the header alone fails CI's--verify), run--writeto add the new baseline, and add a row to the table.
On a pull request, CI also classifies the header against the base branch's baseline of the
same version, so rewriting the baseline by hand does not hide a breaking change, and fails
if a baseline of an earlier version is edited, moved or removed.
.github/scripts/abi-check-test.py tests the check. A behaviour change that leaves the
declarations alone is invisible to it: bump SB_ABI_VERSION in src/lib.rs by hand,
regenerate the header (it then differs only in that line) and run --write.
From ABI 1 to ABI 2
ABI 2 (0.4.0) removes the declarations whose size or layout C leaves to the compiler, so
that every struct is the same on every target and every binding (ctypes, cffi, other
languages) can follow the header exactly. No function was added, removed or renamed. A C
program that uses the header's names needs changes only where it writes enum SbStatus
or passes a bool * for complete, then recompiles; a binding that spells out the types
follows every point:
- Status. Functions return
SbStatus, now anint32_t(in C23 and C++, an enumeration withint32_tas its underlying type) instead ofenum SbStatus. TheSB_STATUS_*values are unchanged. Declare variables asSbStatus, notenum SbStatus; in ctypes,restype = c_int32. The other enumerations (SbSlot,SbFrameStatus,SbFrameKind,SbDiscString,SbAreaString,SbTrackString) are likewiseuint32_t, as their arguments and fields already were. - Flags.
SbDiscInfo.hybrid,SbDiscInfo.manufacturer_sector,SbTrackInfo.has_genreand the*completeout-parameter ofsb_seek_index_extend,sb_seek_index_frontierandsb_disc_seek_index_extendareuint8_t(1 or 0) instead ofbool; pass auint8_t *forcomplete. The header no longer includes<stdbool.h>. - Sizes.
SbFrameInfo.sizeandSbRawFrameInfo.sizeareuint32_t(at mostSB_MAX_FRAME_BYTES) instead ofsize_t. Theinline_budgetarguments ofsb_seek_index_new,sb_seek_index_loadandsb_disc_seek_index_enable, andsb_seek_index_memory's*bytes, areuint64_t, and so isSB_SEEK_DEFAULT_INLINE_BUDGET.size_tremains only for the lengths of caller buffers. - Layouts. No struct has padding.
SbDiscInfostarts withsectors(32 bytes, was 40);SbTrackInfoends withuint8_t reserved[3](still 28 bytes);SbWarningislsn,slot,track,code(still 24 bytes on 64-bit targets);SbFrameInfois 16 bytes (was 24) andSbRawFrameInfo12 (was 16). Code that names the fields needs no change; a binding that lists them follows the new order. sb_dst_decoderefuses a frame longer thanSB_MAX_FRAME_BYTES(65 536 bytes, the reassembly limit of specification 4, 4.4.3) withSB_STATUS_INVALID_ARGUMENT, before reading it, instead of decoding it with memory proportional to its length. Frames fromsb_raw_frames_readare never longer.
The check sb_abi_version() == SB_ABI_VERSION refuses a library of the other ABI either
way round.
Stability
From 1.0, the Rust API of scarletbook and scarletbook-pcm and the C ABI of
scarletbook-ffi follow Semantic Versioning: they stay
compatible within a major version, by the rules of
Cargo's SemVer reference, and every
breaking change is listed in CHANGELOG.md. What counts as a breaking change of
the C ABI is in ABI compatibility.
Before 1.0, as in Cargo, the y step of 0.y.z is the major one and may break the API, and
the z step is the minor one and may only add to it. The interface is not frozen yet:
#39 tracks the changes planned before
1.0.
Not covered:
- items marked
#[doc(hidden)]; - the
fuzzingfeature ofscarletbook-ffi, which exists for the fuzz targets; - the Rust items of
scarletbook-ffi, whose interface is the C ABI; scarletbook-benchandscarletbook-conformance, which are not published.
Versions
Every crate of the workspace shares one version, so a breaking change in one crate raises the version of them all, including crates that did not change. Whether this stays so after 1.0 is still to be decided (#39).
Minimum supported Rust version
The minimum supported Rust version (MSRV) is 1.85, declared as rust-version in
Cargo.toml.
- When it can rise: only in a release that changes the
yofx.y.z, so0.Y.0before 1.0 andx.Y.0from 1.0. It never rises in a release that changes onlyz. - How far it can rise: only to a Rust release at least 12 months old, so that every Rust release of the last 12 months stays supported. The MSRV does not rise without a reason, such as a feature the code needs.
- How you hear of it: the rise is listed under "Changed" in CHANGELOG.md.
CI's msrv job checks scarletbook, scarletbook-pcm and scarletbook-ffi with all features
on this version, using the repository's Cargo.lock. It does not check the lowest dependency
versions that the crates declare, and it does not run the tests on this version.
Benchmarks
bench implements the interface of sacd-spec benchmarks/README.md:
bench dsf is outside that interface (#202): it writes an area's whole play range as one
DSF file through output::Layout, to time the output path, read and write included:
--via stream (the default) reads the area once, in order, and fills --chunk bytes
(default 4 MiB) per Layout::fill call; --via read-at makes one Layout::read_at call
per chunk, as a filesystem serving the file would, with the area's seek index enabled;
--via parallel (Unix) reads the area on the calling thread and has --threads workers
fill whole DSF rows, about --chunk bytes at a time, and write each piece at its offset
with write_at: a prototype of a parallel writer built on the public Layout API (#224).
bench realtime is outside it too (#255): what a real-time player needs from one thread. It
prints the mean real-time factor, the slowest 1-second window, the 99.9th percentile and
slowest frame times, the frames over 6.7 ms (half a frame period), and the median and slowest
time from a seek to its first frame, with a complete seek index. Put the image in the page
cache first and pin the process to one core:
bench open and bench first are outside it too (#224). They time what takes far less than
starting a process, so they time it inside the process, --iterations times (default 100, at
most 1,000,000), and print the median, fastest and slowest time in microseconds. open times
opening an image up to its parsed TOC. first times the first --bytes (default 128 KiB) of a
track's decoded audio, by default the area's middle track, on a disc already open with a complete
seek index:
The image stays in the page cache unless --evict PROGRAM is given. PROGRAM IMAGE then runs,
untimed, before each iteration, and its failure fails the run. benchmarks/evict.py evicts the
image without privileges and fails if any page stays cached, as it does on tmpfs.
Pushing a version tag (v0.1.0, matching the crate version) runs the release workflow:
it publishes bench-<version>-x86_64-linux.tar.gz (generic x86-64, cargo profile dist),
after the correctness gate has passed on that very build, and two labelled builds,
bench-<version>-x86-64-v3-linux.tar.gz (-C target-cpu=x86-64-v3, not a benchmark asset)
and bench-<version>-x86_64-linux-znver5.tar.gz (AMD Zen 5), each with a SHA-256 checksum and, from 0.2.0, a signed
build provenance attestation:
The release also publishes a benchmark kit for consumers who time scarletbook on their own
machines (#224, #226): scarletbook-benchkit-<version>-x86_64-linux.tar.gz and its
-v3 twin, with statically linked bench, scarletbook-synth and the scarletbook-pcm
callpattern example, a run list of the cases and a reference runner. What a runner
executes and what it sends back: benchmarks/README.md.
Measuring performance
scarletbook-seekcost IMAGE (in scarletbook-conformance) measures what opening a frame
range costs against where it starts, without and with a seek index, and the index's build
time and size. On a 50-minute 2-channel DST image (scarletbook-synth --minutes 50 --area 2ch --kind dst) a 14-frame range at 99 % of the area reads 470 272 sectors (146 ms from the
page cache) without an index and 64 sectors (2.4 ms) with one; the index (K = 64) takes one
pass to build (162 ms) and 178 KB saved. Its second table measures cold seeks by provisional reading (no index;
SeekPolicy::Speculative): on the same image, 2 to 4 read calls and 42 to 52 sectors
wherever the range lies, 1.8 to 2.9 ms in its network model (0.5 ms per read call, 110 MB/s),
with the same frames as exact reads on that well-formed image. Its third table opens the
disc afresh for each of 200 positions (--positions), as a consumer that seeks cold sees it:
on an area of uneven bit rate (scarletbook-synth ... --dst-frames uneven), a provisional
start costs 3.5 read calls and 112 KiB on average up to the range's first frame (at most 5
and 160 KiB; it also prints the 50th to 99th percentiles), and 3.7 read calls and 131 KiB
for the 14-frame range decoded.
Through the C interface, python3 .github/scripts/clib-seekcost.py PACKAGE_DIR IMAGE opens the
image with sb_disc_open_callbacks (counting read calls and bytes in the callbacks, 64 KiB per
read call) and decodes the same ranges cold, exact and provisional: on the same image, 4 to 7
read calls (164 to 285 KB, 3.5 to 5.6 ms modelled) for a provisional range anywhere in the area,
against up to 14 696 read calls (963 MB) for an exact one at 99 %.
Three criterion benchmarks track the decoder and the TOC between releases:
dst_framesreports the time per frame and symbols per second (37 632 x channels per frame) for two sets, per channel count:corpus/Nch, every coded DST frame of the corpus imagesdst-*.isothat decodes; andstress/Nch-LAYOUT, 2- and 6-channel frames generated at start-up by the annex 5.A encoder ofcrates/scarletbook/tests/common/dst_enc.rsfrom a seeded sigma-delta signal (order-128 filters, order-32 filters, and a layout with several filter and ptable segments). The stress frames are identical on every run.pipelinereads every track of a 2-channel and a 6-channel area of small synthetic images (plain DSD, DST, DST in 2064-byte sectors) on one thread.toc_readopens a disc and reads its whole TOC, as a consumer listing a library does (#132):c/IMAGEthroughsb_disc_open_callbacks_atover the image in memory and every TOC query of the C interface (disc, areas, tracks, strings, genres, text channels, timecodes, warnings),rust/IMAGEthe same throughDisc::open. The images are the corpus images with the most text and tracks and a synthetic disc of 2 x 255 tracks.SCARLETBOOK_PERF_BENCH=listprints the calls, read callbacks and bytes read per disc.
decode_pool (in scarletbook-ffi, not criterion) decodes every track of an area on a
pool the way a consumer of the C interface does, and prints wall and CPU time per round
(#146): rust-install (TrackAudio inside pool.install, as bench decode),
rust-pool (DecodeOn::Pool, the caller outside the pool), c-read
(sb_track_audio_set_pool and sb_track_audio_read into one caller buffer per frame) and
c-stored (sb_track_audio_read_with_stored), into a null sink or the raw output of
bench decode --sink raw:
The scripts in perf/ need Linux and perf:
| Script | What it does |
|---|---|
perf/cycles-per-symbol.sh [NAME...] |
cycles, instructions, IPC per decoded symbol and ms per frame for dst_frames benchmarks, from perf stat |
perf/flamegraph.sh NAME [OUT.svg] |
perf record and inferno (cargo install --locked inferno --version 0.12.8) flame graph of DstDecoder::decode |
perf/dispatch-inlining.sh |
disassembles the core crate's run-time dispatch (dispatch.rs) in a generic x86-64 build and fails if a dispatched function lost its AVX2 or BMI hot loop (or a generic one gained it); CI runs it on the release libscarletbook_ffi.so |
perf/compare.sh REV_A REV_B [FILTER] |
builds two revisions (. is the working tree) into separate target directories, runs dst_frames alternately, pinned, and prints per-benchmark and per-group changes |
perf/build-configs.sh |
builds bench in several release configurations (LTO, codegen units, PGO) for generic x86-64, x86-64-v3 and znver5, and times single-thread decoding on synthetic images, alternately, pinned, best of several rounds |
perf/pgo.sh TARGET_DIR |
a deterministic profile-guided build of bench (needs rustup component add llvm-tools-preview) |
Pinning: run on an otherwise idle machine and pin to one CPU (the scripts use taskset,
CPU 2 by default; set CPU=). Turbo and frequency scaling still move results by a few
per cent between sessions, so compare only figures taken in one session, alternately, as
compare.sh does. RUSTFLAGS="-C target-cpu=znver5" builds for the measuring machine's CPU.
Which figures count: these benchmarks are for development and catch regressions; the corpus
frames are small test streams and the stress frames are synthetic. The figures against the
targets come only from the benchmark rounds on real discs recorded in sacd-spec
benchmarks/README.md. CI compiles the benchmarks and times one small subset, to catch
regressions: .github/workflows/bench-regress.yml builds bench and callpattern from the
base and from the head, times single-threaded DST decoding, plain DSD to DSF and DSD to PCM
alternately on one runner, and fails when the median of the per-round ratios head / base of
CPU time exceeds 1.15 (.github/scripts/bench-regress.py, #226). It runs on pull requests that
touch the library sources or build settings, on main (against the previous main) and nightly
(against the latest release), and is informational, not a required check.
Minimum supported Rust version: 1.85 (see Stability).
Licence
Licensed under either of
- Apache License, Version 2.0 (LICENSE-APACHE)
- MIT license (LICENSE-MIT)
at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.