scarletbook 1.0.0

Clean-room reader for Super Audio CD (Scarletbook) disc images
Documentation

scarletbook-rs

CI Coverage CodeQL Fuzzing Licence: MIT OR Apache-2.0 MSRV 1.85 OpenSSF Scorecard SLSA Build L2

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.

Quick start

Both examples read a small synthetic image from this repository's conformance corpus, full-text.iso (1.1 MB, CC0-1.0, corpus/LICENSE): a stereo area with three tracks of one or two frames each, and every text field filled in. It holds generated test signals, no real audio. Every command below was run against v0.7.0 on 2026-11-23; 1.0.0 has the same interface, so it changes nothing they use.

Rust

cargo new quickstart && cd quickstart
cargo add scarletbook@=1.0.0
curl -fsSLO https://raw.githubusercontent.com/aclater/scarletbook-rs/v1.0.0/corpus/images/full-text.iso
cat > src/main.rs <<'EOF'
use std::{fs::File, io::BufReader};

use scarletbook::Disc;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let disc = Disc::open(BufReader::new(File::open("full-text.iso")?))?;
    let toc = disc.toc();
    let album = toc.master.text.album_title.as_deref().unwrap_or("(untitled)");
    println!("album: {album:?}");
    for area in &toc.areas {
        println!("{:?} area: {} channels, {} tracks", area.slot, area.channel_count, area.tracks.len());
        for track in &area.tracks {
            let title = track.text.title.as_deref().unwrap_or("(untitled)");
            println!("  track {}: {} frames, {title:?}", track.number, track.duration_frames);
        }
    }
    Ok(())
}
EOF
cargo run
album: "Album title"
TwoChannel area: 2 channels, 3 tracks
  track 1: 1 frames, "Title 1"
  track 2: 1 frames, "Title 2"
  track 3: 2 frames, "Track 3 title, second item"

The =1.0.0 pin is the one recommended under Installing; a frame is 1/75 s. {:?} quotes a string and escapes control characters, including U+007F and U+0080 to U+009F, while keeping other text (Japanese, say) readable, which escape_default() would turn into \u{..} escapes. For audio, see Using the library.

C

On x86_64 Linux with glibc 2.17 or later and a C compiler. The archive's name and the checks are those of Release assets and Verifying a download.

mkdir quickstart-c && cd quickstart-c
gh release download v1.0.0 -R aclater/scarletbook-rs -p 'scarletbook-ffi-1.0.0-x86_64-unknown-linux-gnu.tar.gz*'
sha256sum -c scarletbook-ffi-1.0.0-x86_64-unknown-linux-gnu.tar.gz.sha256
gh attestation verify scarletbook-ffi-1.0.0-x86_64-unknown-linux-gnu.tar.gz -R aclater/scarletbook-rs \
  --signer-workflow aclater/scarletbook-rs/.github/workflows/release.yml --source-ref refs/tags/v1.0.0
tar xzf scarletbook-ffi-1.0.0-x86_64-unknown-linux-gnu.tar.gz
curl -fsSLO https://raw.githubusercontent.com/aclater/scarletbook-rs/v1.0.0/corpus/images/full-text.iso
cat > toc.c <<'EOF'
#include <stdio.h>
#include "scarletbook.h"

/* Prints len bytes, escaping every byte outside 0x20 to 0x7E (a UTF-8 letter becomes \xNN bytes). */
static void put(const char *s, size_t len) {
    for (size_t i = 0; i < len; i++) {
        unsigned char c = (unsigned char)s[i];
        if (c >= 0x20 && c <= 0x7E) putchar(c); else printf("\\x%02X", c);
    }
}

int main(void) {
    struct SbDisc *disc = NULL;
    struct SbDiscInfo info;
    char title[256];
    size_t len = 0;

    if (sb_abi_version() != SB_ABI_VERSION) return 1;  /* header and library must agree */
    if (sb_disc_open_file("full-text.iso", &disc) != SB_STATUS_OK) {
        fprintf(stderr, "%s\n", sb_last_error_message());
        return 1;
    }
    sb_disc_info(disc, &info);
    if (sb_disc_string(disc, SB_DISC_STRING_ALBUM_TITLE, title, sizeof title, &len) == SB_STATUS_OK)
        { printf("ABI %u, album: ", sb_abi_version()); put(title, len); putchar('\n'); }
    for (uint32_t a = 0; a < info.area_count; a++) {
        struct SbAreaInfo area;
        sb_disc_area(disc, a, &area);
        printf("area slot %u: %u channels, %u tracks\n", area.slot, area.channel_count, area.track_count);
        for (uint32_t t = 1; t <= area.track_count; t++) {
            struct SbTrackInfo track;
            sb_track_info(disc, area.slot, t, &track);
            printf("  track %u: %u frames, ", t, track.duration_frames);
            if (sb_track_string(disc, area.slot, t, SB_TRACK_STRING_TITLE, title, sizeof title, &len) == SB_STATUS_OK)
                put(title, len);
            putchar('\n');
        }
    }
    sb_disc_free(disc);
    return 0;
}
EOF
P=scarletbook-ffi-1.0.0-x86_64-unknown-linux-gnu
cc -std=c99 -Wall -Wextra -pedantic -I$P/include toc.c -L$P/lib -lscarletbook_ffi -Wl,-rpath,'$ORIGIN/'$P/lib -o toc
./toc
ABI 2, album: Album title
area slot 0: 2 channels, 3 tracks
  track 1: 1 frames, Title 1
  track 2: 1 frames, Title 2
  track 3: 2 frames, Track 3 title, second item

Titles and other text come from the disc and can hold control characters (U+007F, U+0080 to U+009F, and U+009B starts a control sequence on some terminals), so both examples escape what they print; code of yours should do the same, as the docs of DiscText and of sb_disc_string say.

gh attestation verify prints nothing when it succeeds (a non-zero exit status is a failure). The program records libscarletbook_ffi.so.2, the library's name for C ABI 2, and finds it through the rpath, so it runs from this directory without the link. To ship it, copy lib/libscarletbook_ffi.so.2 next to the program, as Linking says. See C library for the rest of the API, and Migrating to 0.7.0 and Migrating to 0.6.0 from an earlier release.

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).

cargo add scarletbook
cargo add scarletbook-pcm   # only for PCM output
use std::{fs::File, io::BufReader};
use scarletbook::{Disc, Slot};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut disc = Disc::open(BufReader::new(File::open("disc.iso")?))?;
    let mut bytes = 0;
    for frame in disc.track_audio(Slot::TwoChannel, 1)? {
        bytes += frame?.data.len(); // interleaved DSD, DST already decoded
    }
    println!("track 1: {bytes} bytes of DSD");
    Ok(())
}

Byte stability. scarletbook-pcm stays at 0.7.0 from 1.0.0 (outside the 1.0 freeze, see Stability). While its version is 0.x, a new 0.7.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.7.y as compatible with 0.7.x, so a plain scarletbook-pcm = "0.7" 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:

scarletbook-pcm = "=0.7.0"

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
cargo test --workspace                      # includes every corpus case
cargo run -p scarletbook-conformance --bin scarletbook-toc -- corpus/images/hostile-base.iso

Using the library

use std::{fs::File, io::BufReader};
use scarletbook::{Disc, Slot};

let mut disc = Disc::open(BufReader::new(File::open("disc.iso")?))?;
for frame in disc.track_audio(Slot::TwoChannel, 1)? {
    let frame = frame?; // C x 4704 bytes of interleaved DSD, DST already decoded
}
// 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(Slot::TwoChannel).ok_or(scarletbook::Error::NoSuchArea(Slot::TwoChannel))?;
let playtime = area.playtime_frames();
for frame in disc.range_audio(Slot::TwoChannel, 0, playtime)? {
    let frame = frame?;
}
let (first, end) = disc.track_range_with_pause(Slot::TwoChannel, 2)?;
for frame in disc.range_audio(Slot::TwoChannel, first, end)? {
    let frame = frame?;
}

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 scarletbook::FrameContent;

// A track's or range's positions as stored: DST bytes, plain DSD bytes, or missing.
let mut frames = disc.range_frames(Slot::TwoChannel, first, end)?;
while let Some(frame) = frames.next() {
    let frame = frame?;
    match &frame.content {
        FrameContent::Dst(bytes) => { /* the DST frame as stored */ }
        FrameContent::Dsd(bytes) => { /* C x 4704 plain bytes */ }
        FrameContent::Missing => { /* no frame: decoded reads fill it with 0x69 */ }
    }
    // Or one DST frame for every position, plain and missing ones included, that decodes
    // to exactly the position's audio.
    let dst = frames.dst_equivalent(&frame.content);
}
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(Slot::TwoChannel)? {
    let frame = frame?;
}

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 scarletbook::output::{Format, OutputOptions};

let (first, end) = disc.track_range_with_pause(Slot::TwoChannel, 1)?;
let layout = disc.output_layout(Slot::TwoChannel, first, end, Format::Dsf, &OutputOptions::default())?;
let size = layout.size();
let mut buf = vec![0; 65_536];
let n = layout.read_at(&mut disc, offset, &mut buf)?;
// Or with positions from a cache of your own:
let needed = layout.positions_for(offset..offset + buf.len() as u64);
let n = layout.fill(offset, &mut buf, &mut my_source)?;

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 scarletbook::{AreaIndex, IndexOptions};

disc.enable_seek_index(Slot::TwoChannel, IndexOptions::new())?;
// Reads build it as they go; or build it at once, in steps (one pass over the area):
while !disc.extend_seek_index(Slot::TwoChannel, 64 * 1024)? {}
// 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(Slot::TwoChannel, first, end)?;
// Keep it for the next time this image is opened (about 24 bytes per 64 sectors).
let saved: Vec<u8> = disc.seek_index(Slot::TwoChannel).map(|i| i.to_bytes()).unwrap_or_default();
// ... later: from_bytes checks the bytes, set_seek_index the area.
let index = AreaIndex::from_bytes(area, disc.toc().sectors, &saved, scarletbook::seek::DEFAULT_INLINE_BUDGET)?;
disc.set_seek_index(Slot::TwoChannel, 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 (claim_lsn()). 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

#include "scarletbook.h"
struct SbDisc *disc;
if (sb_disc_open_file("disc.iso", &disc) != SB_STATUS_OK) puts(sb_last_error_message());

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), a string pointer in SbWarning or a double in SbAreaCapacity; 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_area_capacity gives what an area's TOC claims against the audio sectors the image holds (SbAreaCapacity: the sectors present, the play time and largest track end, the capacity of specification 4, 4.8, the most plain DSD frames those sectors can carry, and frames per sector), for a plausibility check whose threshold the caller chooses; it reads nothing.

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;
sb_seek_index_new(disc, slot, SB_SEEK_DEFAULT_INTERVAL, SB_SEEK_DEFAULT_INLINE_BUDGET, &index);
uint8_t complete = 0;
while (sb_seek_index_extend(disc, index, 65536, &complete) == SB_STATUS_OK && !complete) {}
SbTrackAudio *audio = NULL;
sb_range_audio_open_indexed(disc, slot, first, end, index, &audio); /* same frames, few reads */
/* ... sb_track_audio_read ... then hand its new checkpoints back: */
sb_track_audio_absorb(audio, index);
size_t len = 0;
sb_seek_index_save(index, NULL, 0, &len);  /* 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;
sb_output_options_new(&opts);
sb_output_options_set(opts, SB_OUTPUT_OPTION_ID3_FOOTER, 0);  /* each writer's choice */
SbOutputLayout *layout = NULL;
sb_output_layout_new(disc, slot, first, end, SB_OUTPUT_FORMAT_DSF, opts, &layout);
SbOutputLayoutInfo info;
sb_output_layout_info(layout, &info);                        /* info.size, from the TOC */
size_t n = 0;
sb_output_layout_read(layout, disc, offset, buf, len, &n);   /* 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;
sb_pool_new(4, &pool);                 /* 0: one thread per logical CPU */
sb_range_audio_open(disc, slot, 0, playtime, &audio);
sb_track_audio_set_pool(audio, pool);  /* continuations keep it */
sb_pool_free(pool);                    /* reference-counted: the handle keeps it alive */
while (sb_track_audio_read(audio, disc, buf, cap, &fi) == SB_STATUS_OK) { /* in order */ }
sb_track_audio_free(audio);

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, &copy) 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):

sb_range_audio_open(disc, slot, 0, playtime, &audio);
sb_track_audio_set_pool(audio, pool);   /* optional, as for any handle */
sb_track_audio_keep_stored(audio);      /* before the first read */
uint8_t raw[SB_MAX_FRAME_BYTES];
SbRawFrameInfo ri;
while (sb_track_audio_read_with_stored(audio, disc, buf, cap, &fi, raw, sizeof raw, &ri, 0)
       == SB_STATUS_OK) {
  /* buf: as sb_track_audio_read; raw[0 .. ri.size): as sb_raw_frames_read (1 for the last
     argument: as sb_raw_frames_read_dst_equivalent) */
}

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;
sb_disc_cancel_token(disc, &token);       /* on the disc's thread: shared by its clones */
SbProgress *progress = NULL;
sb_track_audio_progress(audio, &progress); /* 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;
sb_progress_get(progress, &read, &expected); /* sectors read, sectors expected */
sb_cancel_request(token);                  /* 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;
sb_pcm_converter_new(176400, SB_PCM_CUTOFF_DEFAULT, channels, 0.0 /* dB */, &conv);
uint32_t spf;                              /* output samples per channel per frame */
sb_pcm_samples_per_frame(conv, &spf);      /* 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[6];
sb_pcm_convert_run(conv, prev, cur, channels * 4704, next, SB_PCM_S24LE,
                   pcm, (size_t)spf * channels * 3, clipped);
sb_pcm_converter_free(conv);

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:

conv, spf = H(), C.c_uint32()
check(lib.sb_pcm_converter_new(176400, 0, 2, 0.0, C.byref(conv)))  # SB_PCM_CUTOFF_DEFAULT
check(lib.sb_pcm_samples_per_frame(conv, C.byref(spf)))
pcm, clipped = C.create_string_buffer(spf.value * 2 * 3), (C.c_uint64 * 6)()
check(lib.sb_pcm_convert_run(conv, prev, cur, len(cur), nxt, 1, pcm, len(pcm), clipped))  # SB_PCM_S24LE
lib.sb_pcm_converter_free(conv)

Rust and C names

Where the two interfaces name the same thing differently:

Rust C
Stored frames: TrackCursor, TrackFrames, Disc::track_frames, Disc::range_frames Raw frames: SbRawFrames, sb_raw_frames_*
Disc::stored_frame_list sb_stored_frame_list_open, which returns an SbRawFrames
Disc::share, Disc::share_with_log (a new reader) sb_disc_clone_callbacks, sb_disc_clone_callbacks_with_log (new read and seek callbacks)
claim() on a cursor, None for exact positions SbSpeculation.claim, 0 for exact positions
claim_lsn() on a cursor, None before the start is chosen and for exact positions SbSpeculation.lsn, 0 in those cases
Stored::Dsd, FrameKind::Dsd, FrameStatus::Dsd SB_FRAME_KIND_DSD

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 the following. This is the layout from 0.6.0 on, whose shared libraries are named after the C ABI (see "Linking"). An archive of 0.5.9 or earlier holds a single file lib/libscarletbook_ffi.so (SONAME libscarletbook_ffi.so) on Linux and lib/libscarletbook_ffi.dylib (install name @rpath/libscarletbook_ffi.dylib) on macOS, with no versioned name and no link.

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.2        shared library (Linux, 0.6.0 on) ...
  lib/libscarletbook_ffi.so          ... and a link to it, for the linker
  lib/libscarletbook_ffi.2.dylib     shared library (macOS, 0.6.0 on) ...
  lib/libscarletbook_ffi.dylib       ... and a link to it, for the linker
  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

sha256sum -c scarletbook-ffi-<version>-<target>.tar.gz.sha256      # macOS: shasum -a 256 -c
gh attestation verify scarletbook-ffi-<version>-<target>.tar.gz -R aclater/scarletbook-rs \
  --signer-workflow aclater/scarletbook-rs/.github/workflows/release.yml \
  --source-ref refs/tags/v<version>

The checksum detects a damaged download, not a replaced one: it is neither signed nor attested, so whoever could replace the archive could replace its .sha256 too. The attestation (a signed SLSA build provenance statement naming the workflow run and commit that built the file) is what shows the file came from this project's release. With --signer-workflow and --source-ref, gh accepts only a file built by the release workflow from the tag v<version>; without them, a file attested by any workflow run in the repository would pass. Releases from 0.2.0 carry the attestation.

Linking

# Static: the archive, then the system libraries it needs.
cc app.c -I$PKG/include $PKG/lib/libscarletbook_ffi.a $(cat $PKG/native-static-libs.txt)
# Shared: ship libscarletbook_ffi.so.2 (0.5.9 and earlier: libscarletbook_ffi.so) next to the
# program, or set an rpath.
cc app.c -I$PKG/include -L$PKG/lib -lscarletbook_ffi -Wl,-rpath,'$ORIGIN'

From 0.6.0 on, the shared library's name carries the C ABI version, SB_ABI_VERSION, not the crate version (see "ABI compatibility"). Releases up to 0.5.9 ship only the unversioned file, and a program records that name. From 0.6.0:

Name a program records The file Link for the linker
Linux SONAME libscarletbook_ffi.so.2 libscarletbook_ffi.so.2 libscarletbook_ffi.so
macOS install name @rpath/libscarletbook_ffi.2.dylib, compatibility version 2.0.0 libscarletbook_ffi.2.dylib libscarletbook_ffi.dylib
Windows scarletbook_ffi.dll (not versioned) scarletbook_ffi.dll libscarletbook_ffi.dll.a (import library)

-lscarletbook_ffi finds the unversioned link and the program records the versioned name, so the versioned file is the one to ship, found through the program's rpath (-Wl,-rpath,@loader_path on macOS). Copy it under that name; such a program does not need the link at run time. A program linked against a release before 0.6.0 recorded the unversioned name, so it does need the link, next to the library, until it is relinked. A library loaded by path, as with ctypes, loads under either name while the link is there. See Migrating to 0.6.0.

Windows has no SONAME: a program records the DLL's file name. scarletbook_ffi.dll keeps its name, because integrators ship it next to their program, so sb_abi_version() is the only check there. 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.

Only the release archives are named this way, by .github/scripts/clib-package.sh. A plain cargo build makes libscarletbook_ffi.so with no SONAME at all. To build one with the SONAME from source, for example for a system package, add what the script adds and install it under that name: cargo rustc --release -p scarletbook-ffi --lib -- -C link-arg=-Wl,-soname,libscarletbook_ffi.so.2.

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.

import ctypes as C

# libscarletbook_ffi.2.dylib on macOS, scarletbook_ffi.dll on Windows; before 0.6.0,
# libscarletbook_ffi.so and libscarletbook_ffi.dylib
lib = C.CDLL("/path/to/libscarletbook_ffi.so.2")

SB_ABI_VERSION = 2  # the SB_ABI_VERSION of the header these bindings follow
lib.sb_abi_version.argtypes, lib.sb_abi_version.restype = [], C.c_uint32
if lib.sb_abi_version() != SB_ABI_VERSION:
    raise ImportError(f"scarletbook C ABI {lib.sb_abi_version()}, these bindings need {SB_ABI_VERSION}")

# The structs, field for field as in scarletbook.h (flags are uint8_t, 1 or 0).
class SbDiscInfo(C.Structure):
    _fields_ = [("sectors", C.c_uint64), ("sector_size", C.c_uint32), ("version_major", C.c_uint8),
                ("version_minor", C.c_uint8), ("album_set_size", C.c_uint16),
                ("album_sequence_number", C.c_uint16), ("hybrid", C.c_uint8),
                ("manufacturer_sector", C.c_uint8), ("year", C.c_uint16), ("month", C.c_uint8),
                ("day", C.c_uint8), ("area_count", C.c_uint32), ("warning_count", C.c_uint32)]

class SbAreaInfo(C.Structure):
    _fields_ = [(name, C.c_uint32) for name in (
        "slot", "kind_channels", "toc_lsn", "toc_sectors", "channel_count", "area_config",
        "sample_frequency_code", "frame_format", "max_byte_rate", "playtime_frames",
        "audio_start_lsn", "audio_end_lsn", "track_count")]

class SbTrackInfo(C.Structure):
    _fields_ = [("number", C.c_uint32), ("start_lsn", C.c_uint32), ("length_sectors", C.c_uint32),
                ("start_frame", C.c_uint32), ("duration_frames", C.c_uint32),
                ("start_flags", C.c_uint8), ("duration_flags", C.c_uint8), ("has_genre", C.c_uint8),
                ("genre_category", C.c_uint8), ("genre_index", C.c_uint8), ("reserved", C.c_uint8 * 3)]

class SbWarning(C.Structure):
    _fields_ = [("lsn", C.c_int64), ("slot", C.c_int32), ("track", C.c_uint32), ("code", C.c_char_p)]

class SbFrameInfo(C.Structure):
    _fields_ = [("number", C.c_uint32), ("status", C.c_uint32), ("dst_rule", C.c_uint32),
                ("size", C.c_uint32)]

class SbTimecode(C.Structure):
    _fields_ = [("minutes", C.c_uint8), ("seconds", C.c_uint8), ("frames", C.c_uint8)]

class SbRawFrameInfo(C.Structure):
    _fields_ = [("number", C.c_uint32), ("kind", C.c_uint32), ("size", C.c_uint32)]

class SbGenre(C.Structure):
    _fields_ = [("category", C.c_uint8), ("index", C.c_uint8)]

class SbTextChannel(C.Structure):  # language: the code's two bytes as stored
    _fields_ = [("language", C.c_uint8 * 2), ("charset", C.c_uint8), ("reserved", C.c_uint8)]

class SbAreaDetails(C.Structure):
    _fields_ = [(name, C.c_uint8) for name in (
        "version_major", "version_minor", "max_available_channels", "mute_flags",
        "track_attribute", "track_offset", "text_channel_count", "text_charset")]

class SbAreaCapacity(C.Structure):  # frames_per_sector: inf when audio_sectors is 0
    _fields_ = [("audio_sectors", C.c_uint64), ("capacity", C.c_uint64), ("plain_frame_bound", C.c_uint64),
                ("frames_per_sector", C.c_double), ("playtime_frames", C.c_uint32), ("max_track_end", C.c_uint32),
                ("has_plain_frame_bound", C.c_uint8), ("reserved", C.c_uint8 * 7)]

# The layout of sb_disc_toc (format 1.0); see "The whole TOC in one call" below.
class SbTocStr(C.Structure):
    _fields_ = [("offset", C.c_uint32), ("length", C.c_uint32)]

class SbTocHeader(C.Structure):
    _fields_ = [("magic", C.c_uint8 * 8), ("major", C.c_uint16), ("minor", C.c_uint16), ("size", C.c_uint32),
                ("disc_offset", C.c_uint32), ("disc_record_size", C.c_uint16),
                ("area_record_size", C.c_uint16), ("track_record_size", C.c_uint16),
                ("warning_record_size", C.c_uint16), ("areas_offset", C.c_uint32),
                ("area_count", C.c_uint32), ("warnings_offset", C.c_uint32),
                ("warning_count", C.c_uint32), ("strings_offset", C.c_uint32),
                ("strings_size", C.c_uint32), ("reserved", C.c_uint32)]

class SbTocDisc(C.Structure):
    _fields_ = [("info", SbDiscInfo), ("album_genres", SbGenre * 4), ("disc_genres", SbGenre * 4),
                ("text_channel_count", C.c_uint8), ("text_charset", C.c_uint8), ("disc_flags", C.c_uint8),
                ("reserved", C.c_uint8), ("text_channels", SbTextChannel * 8), ("reserved2", C.c_uint32),
                ("strings", SbTocStr * 18), ("catalog_numbers_stored", SbTocStr * 2),
                ("manufacturer", SbTocStr)]

class SbTocArea(C.Structure):
    _fields_ = [("info", SbAreaInfo), ("details", SbAreaDetails), ("loudspeaker_layout", C.c_uint32),
                ("channel_speakers", C.c_uint8 * 6), ("playtime_stored", SbTimecode),
                ("reserved", C.c_uint8), ("reserved2", C.c_uint16), ("tracks_offset", C.c_uint32),
                ("strings", SbTocStr * 4), ("text_channels", SbTextChannel * 10)]

class SbTocTrack(C.Structure):
    _fields_ = [("info", SbTrackInfo), ("start_stored", SbTimecode), ("duration_stored", SbTimecode),
                ("reserved", C.c_uint8 * 2), ("strings", SbTocStr * 16), ("reserved2", C.c_uint32)]

class SbTocWarning(C.Structure):
    _fields_ = [("lsn", C.c_int64), ("slot", C.c_int32), ("track", C.c_uint32), ("code", SbTocStr)]

class SbSpeculation(C.Structure):
    _fields_ = [("claim", C.c_uint64), ("lsn", C.c_uint64), ("slot", C.c_uint32), ("state", C.c_uint32),
                ("first", C.c_uint32), ("last_returned", C.c_uint32), ("exact_from", C.c_uint32),
                ("reserved", C.c_uint32)]

# DSF and DSDIFF output; see "Output files".
class SbComment(C.Structure):
    _fields_ = [("text", C.c_char_p), ("year", C.c_uint32), ("kind", C.c_uint32), ("reference", C.c_uint32),
                ("month", C.c_uint8), ("day", C.c_uint8), ("hour", C.c_uint8), ("minutes", C.c_uint8)]

class SbMarker(C.Structure):
    _fields_ = [("text", C.c_char_p), ("frame", C.c_uint32), ("kind", C.c_uint32),
                ("track_flags", C.c_uint32), ("reserved", C.c_uint32)]

class SbOutputLayoutInfo(C.Structure):
    _fields_ = [("size", C.c_uint64), ("memory", C.c_uint64)] + [(name, C.c_uint32) for name in (
        "format", "slot", "first", "end", "channels", "source_track", "input", "regions")]

class SbOutputRegion(C.Structure):
    _fields_ = [("offset", C.c_uint64), ("len", C.c_uint64), ("kind", C.c_uint32), ("reserved", C.c_uint32)]

class SbPositionData(C.Structure):
    _fields_ = [("content", C.POINTER(C.c_uint8)), ("content_len", C.c_size_t),
                ("dst_equivalent", C.POINTER(C.c_uint8)), ("dst_equivalent_len", C.c_size_t),
                ("number", C.c_uint32), ("reserved", C.c_uint32)]

class SbDsfChainFile(C.Structure):
    _fields_ = [("byte_first", C.c_uint64), ("byte_end", C.c_uint64), ("first", C.c_uint32),
                ("end", C.c_uint32), ("chain_first", C.c_uint32), ("chain_end", C.c_uint32),
                ("status", C.c_int32), ("reserved", C.c_uint32)]

# 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.
H, S, P, U32, SIZE = C.c_void_p, C.c_int32, C.POINTER, C.c_uint32, C.c_size_t

def bind(name, restype, *argtypes):
    f = getattr(lib, name)
    f.restype, f.argtypes = restype, list(argtypes)

bind("sb_version", C.c_char_p)
bind("sb_build_info", C.c_char_p)
bind("sb_last_error_message", C.c_char_p)
bind("sb_status_name", C.c_char_p, C.c_int32)
bind("sb_disc_open_file", S, C.c_char_p, P(H))
bind("sb_disc_open_memory", S, C.c_char_p, SIZE, P(H))
bind("sb_disc_free", None, H)
bind("sb_disc_info", S, H, P(SbDiscInfo))
bind("sb_disc_string", S, H, U32, C.c_char_p, SIZE, P(SIZE))
bind("sb_disc_area", S, H, U32, P(SbAreaInfo))
bind("sb_area_loudspeaker_layout", S, H, U32, P(U32))
bind("sb_area_channel_speaker", S, H, U32, U32, P(U32))
bind("sb_disc_warning", S, H, U32, P(SbWarning))
bind("sb_disc_read_sectors", S, H, C.c_uint64, U32, C.c_char_p, SIZE)
bind("sb_disc_genre", S, H, U32, U32, P(SbGenre))
bind("sb_disc_text_channel_count", S, H, P(U32))
bind("sb_disc_text_channel", S, H, U32, P(SbTextChannel))
bind("sb_disc_catalog_number_stored", S, H, U32, C.c_char_p, SIZE, P(SIZE))
bind("sb_disc_manufacturer", S, H, C.c_char_p, SIZE, P(SIZE))
bind("sb_area_details", S, H, U32, P(SbAreaDetails))
bind("sb_area_capacity", S, H, U32, P(SbAreaCapacity))
bind("sb_area_text_channel", S, H, U32, U32, P(SbTextChannel))
bind("sb_track_info", S, H, U32, U32, P(SbTrackInfo))
bind("sb_area_playtime_stored", S, H, U32, P(SbTimecode))
bind("sb_track_timecodes_stored", S, H, U32, U32, P(SbTimecode), P(SbTimecode))
bind("sb_track_string", S, H, U32, U32, U32, C.c_char_p, SIZE, P(SIZE))
bind("sb_disc_toc", S, H, U32, C.c_char_p, SIZE, P(SIZE))
bind("sb_track_check", S, H, U32, U32)
bind("sb_track_audio_open", S, H, U32, U32, P(H))
bind("sb_track_audio_open_next", S, H, H, U32, U32, P(H))
bind("sb_track_audio_channels", U32, H)
bind("sb_track_audio_read", S, H, H, C.c_char_p, SIZE, P(SbFrameInfo))
bind("sb_track_audio_counts", S, H, P(C.c_uint64), P(C.c_uint64))
bind("sb_track_audio_free", None, H)
bind("sb_pool_new", S, U32, P(H))
bind("sb_pool_free", None, H)
bind("sb_track_audio_set_pool", S, H, H)
bind("sb_raw_frames_open", S, H, U32, U32, U32, P(H))
bind("sb_raw_frames_read", S, H, H, C.c_char_p, SIZE, P(SbRawFrameInfo))
bind("sb_raw_frames_free", None, H)
bind("sb_dst_decode", S, C.c_char_p, SIZE, U32, C.c_char_p, SIZE, P(U32))
bind("sb_pcm_converter_new", S, U32, U32, U32, C.c_double, P(H))
bind("sb_pcm_converter_free", None, H)
bind("sb_pcm_samples_per_frame", S, H, P(U32))
bind("sb_pcm_convert_run", S, H, C.c_char_p, C.c_char_p, SIZE, C.c_char_p, U32, C.c_void_p, SIZE,
     P(C.c_uint64))
bind("sb_disc_seek_policy_set", S, H, U32, U32, C.c_uint64)
bind("sb_track_audio_speculation", S, H, P(SbSpeculation))
bind("sb_raw_frames_speculation", S, H, P(SbSpeculation))
bind("sb_track_audio_suspect", S, H, P(U32))
bind("sb_raw_frames_suspect", S, H, P(U32))
bind("sb_disc_seek_verify", S, H, U32, C.c_uint64, P(C.c_uint8))
bind("sb_disc_seek_event_next", S, H, U32, P(SbSpeculation))
bind("sb_seek_index_verify", S, H, H, P(U32))
bind("sb_seek_index_event_next", S, H, P(SbSpeculation))
bind("sb_disc_cancel_token", S, H, P(H))
bind("sb_cancel_request", S, H)
bind("sb_cancel_withdraw", S, H)
bind("sb_cancel_requested", S, H, P(C.c_uint8))
bind("sb_cancel_free", None, H)
bind("sb_track_audio_progress", S, H, P(H))
bind("sb_raw_frames_progress", S, H, P(H))
bind("sb_progress_get", S, H, P(C.c_uint64), P(C.c_uint64))
bind("sb_progress_free", None, H)
bind("sb_track_audio_keep_stored", S, H)
bind("sb_track_audio_read_with_stored", S, H, H, C.c_char_p, SIZE, P(SbFrameInfo),
     C.c_char_p, SIZE, P(SbRawFrameInfo), C.c_uint8)
bind("sb_output_options_new", S, P(H))
bind("sb_output_options_free", None, H)
bind("sb_output_options_set", S, H, U32, C.c_int64)
bind("sb_output_options_set_string", S, H, U32, C.c_char_p)
bind("sb_output_options_set_order", S, H, U32, P(U32), SIZE)
bind("sb_output_options_set_id3_frame_order", S, H, C.c_char_p, SIZE)
bind("sb_output_options_set_channel_numbers", S, H, P(C.c_uint16), SIZE)
bind("sb_output_options_add_comment", S, H, P(SbComment))
bind("sb_output_options_clear_comments", S, H)
bind("sb_output_options_add_marker", S, H, P(SbMarker))
bind("sb_output_options_clear_markers", S, H)
bind("sb_output_options_set_tags", S, H, H)
bind("sb_output_options_set_raw_tag", S, H, C.c_char_p, SIZE)
bind("sb_tags_new", S, P(H))
bind("sb_tags_from_toc", S, H, U32, U32, H, P(H))
bind("sb_tags_set", S, H, U32, C.c_char_p)
bind("sb_tags_push", S, H, U32, C.c_char_p)
bind("sb_tags_remove", S, H, U32)
bind("sb_tags_set_custom", S, H, C.c_char_p, C.c_char_p)
bind("sb_tags_count", S, H, U32, P(U32))
bind("sb_tags_get", S, H, U32, U32, C.c_char_p, SIZE, P(SIZE))
bind("sb_tags_free", None, H)
bind("sb_dst_lengths_scan", S, H, U32, U32, U32, U32, P(H))
bind("sb_dst_lengths_load", S, H, U32, U32, U32, U32, P(U32), SIZE, P(H))
bind("sb_dst_lengths_get", S, H, P(U32), SIZE, P(SIZE))
bind("sb_dst_lengths_free", None, H)
bind("sb_output_layout_new", S, H, U32, U32, U32, U32, H, P(H))
bind("sb_output_layout_new_dst", S, H, H, H, P(H))
bind("sb_output_layout_info", S, H, P(SbOutputLayoutInfo))
bind("sb_output_layout_region", S, H, U32, P(SbOutputRegion))
bind("sb_output_layout_positions", S, H, C.c_uint64, C.c_uint64, P(U32), P(U32))
bind("sb_output_layout_read", S, H, H, C.c_uint64, C.c_char_p, SIZE, P(SIZE))
bind("sb_output_layout_fill", S, H, C.c_uint64, C.c_char_p, SIZE, P(SbPositionData), SIZE, P(SIZE))
bind("sb_output_layout_free", None, H)
bind("sb_output_dsf_chain_plan", S, H, U32, P(U32), SIZE, P(SbDsfChainFile), SIZE, P(SIZE))

The other functions bind the same way from their declarations in scarletbook.h. Then:

def check(status):
    """Raises on a failure, with the calling thread's error message."""
    if status < 0:
        raise RuntimeError(f"{lib.sb_status_name(status).decode()}: {lib.sb_last_error_message().decode()}")
    return status

def disc_string(disc, field):
    """A disc string (SbDiscString), or None when absent: size it, then copy it."""
    n = C.c_size_t()
    if lib.sb_disc_string(disc, field, None, 0, C.byref(n)) == 2:  # SB_STATUS_ABSENT
        return None
    buf = C.create_string_buffer(n.value + 1)
    check(lib.sb_disc_string(disc, field, buf, len(buf), C.byref(n)))
    return buf.raw[:n.value].decode()  # may contain U+0000: use the length, not the NUL

disc = H()
check(lib.sb_disc_open_file("disc.iso".encode(), C.byref(disc)))  # a UTF-8 path
try:
    info = SbDiscInfo()
    check(lib.sb_disc_info(disc, C.byref(info)))
    title = disc_string(disc, 0)  # SB_DISC_STRING_ALBUM_TITLE
    audio = H()
    check(lib.sb_track_audio_open(disc, 0, 1, C.byref(audio)))  # 2-channel area, track 1
    try:
        buf = C.create_string_buffer(lib.sb_track_audio_channels(audio) * 4704)
        frame = SbFrameInfo()
        while check(lib.sb_track_audio_read(audio, disc, buf, len(buf), C.byref(frame))) == 0:
            dsd = buf.raw[:frame.size]  # interleaved DSD, channels x 4704 bytes
    finally:
        lib.sb_track_audio_free(audio)
finally:
    lib.sb_disc_free(disc)

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. SbTocHeader sits at offset 0. It gives the offset of the SbTocDisc record, of the SbTocArea records (in sb_disc_area order) and of the SbTocWarning records, with each kind's record size. Each area's tracks_offset points to its SbTocTrack records, in track number order. Strings are SbTocStr refs (offset, length) into the string area at the end. Each string is followed by a NUL that length does not count. offset == SB_TOC_ABSENT (0xFFFFFFFF) marks an absent string, where the per-field call would return SB_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) and minor (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 by sizeof. The format 1.0 sizes are 56, 256, 152, 168 and 24 bytes (header, disc, area, track, warning).
  • Size. flags must be 0. *len receives the layout's size. If the buffer is NULL or smaller than that, the call writes nothing and returns SB_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 *len bytes only when that is too small. A disc of 2 x 255 titled tracks needs about 97 KB.
buf = C.create_string_buffer(64 * 1024)  # reuse it from disc to disc
n = C.c_size_t()
status = lib.sb_disc_toc(disc, 0, buf, len(buf), C.byref(n))
if status == -11:  # SB_STATUS_BUFFER_TOO_SMALL
    buf = C.create_string_buffer(n.value)
    status = lib.sb_disc_toc(disc, 0, buf, len(buf), C.byref(n))
check(status)
raw = memoryview(buf)[:n.value]

head = SbTocHeader.from_buffer(buf)  # create_string_buffer memory is malloc'd: 8-aligned
if bytes(head.magic) != b"SBTOC\0\0\0" or head.major != 1:
    raise RuntimeError("unknown sb_disc_toc layout")

def text(ref):
    return None if ref.offset == 0xFFFFFFFF else bytes(raw[ref.offset:ref.offset + ref.length]).decode()

d = SbTocDisc.from_buffer(buf, head.disc_offset)
album_title = text(d.strings[0])  # SB_DISC_STRING_ALBUM_TITLE
for i in range(head.area_count):
    a = SbTocArea.from_buffer(buf, head.areas_offset + i * head.area_record_size)
    for k in range(a.info.track_count):
        t = SbTocTrack.from_buffer(buf, a.tracks_offset + k * head.track_record_size)
        title = text(t.strings[0])  # 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

ABI 2 is the 1.0 ABI (#39, owner decision of 2026-11-06). 1.0.0 has SB_ABI_VERSION 2, and no ABI 3 is planned: no planned work needs an ABI 2 struct to grow, because new data comes through new functions and types. On Linux and macOS the shared library is named after this number (see "Linking"), so libscarletbook_ffi.so.2 and libscarletbook_ffi.2.dylib are the 1.0 names too.

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, sb_abi_version() in the library and the number in the shared library's name on Linux and macOS all 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_VERSION by 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 increments SB_ABI_VERSION and, with it, the number in the library's name, so libraries of two ABIs can sit side by side.

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, library name 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, 0.5.4 and 0.6.0); unchanged in 1.0.0, the 1.0 ABI

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 --write in the same commit, so the baseline always matches the header on main;
  • anything else fails with "breaking change: bump SB_ABI_VERSION and add abi-(N+1).txt". Increment SB_ABI_VERSION in crates/scarletbook-ffi/src/lib.rs, regenerate the header with cbindgen (see above; editing the header alone fails CI's --verify), run --write to 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 an int32_t (in C23 and C++, an enumeration with int32_t as its underlying type) instead of enum SbStatus. The SB_STATUS_* values are unchanged. Declare variables as SbStatus, not enum SbStatus; in ctypes, restype = c_int32. The other enumerations (SbSlot, SbFrameStatus, SbFrameKind, SbDiscString, SbAreaString, SbTrackString) are likewise uint32_t, as their arguments and fields already were.
  • Flags. SbDiscInfo.hybrid, SbDiscInfo.manufacturer_sector, SbTrackInfo.has_genre and the *complete out-parameter of sb_seek_index_extend, sb_seek_index_frontier and sb_disc_seek_index_extend are uint8_t (1 or 0) instead of bool; pass a uint8_t * for complete. The header no longer includes <stdbool.h>.
  • Sizes. SbFrameInfo.size and SbRawFrameInfo.size are uint32_t (at most SB_MAX_FRAME_BYTES) instead of size_t. The inline_budget arguments of sb_seek_index_new, sb_seek_index_load and sb_disc_seek_index_enable, and sb_seek_index_memory's *bytes, are uint64_t, and so is SB_SEEK_DEFAULT_INLINE_BUDGET. size_t remains only for the lengths of caller buffers.
  • Layouts. No struct has padding. SbDiscInfo starts with sectors (32 bytes, was 40); SbTrackInfo ends with uint8_t reserved[3] (still 28 bytes); SbWarning is lsn, slot, track, code (still 24 bytes on 64-bit targets); SbFrameInfo is 16 bytes (was 24) and SbRawFrameInfo 12 (was 16). Code that names the fields needs no change; a binding that lists them follows the new order.
  • sb_dst_decode refuses a frame longer than SB_MAX_FRAME_BYTES (65 536 bytes, the reassembly limit of specification 4, 4.4.3) with SB_STATUS_INVALID_ARGUMENT, before reading it, instead of decoding it with memory proportional to its length. Frames from sb_raw_frames_read are never longer.

The check sb_abi_version() == SB_ABI_VERSION refuses a library of the other ABI either way round.

Stability

1.0.0 freezes the interface: it is the 0.7 interface, with no API or ABI change (#39). From 1.0.0, the Rust API of scarletbook 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, so there is no breaking change without 2.0.0, and every breaking change is listed in CHANGELOG.md. A 1.y.z release may add to the interface (a minor release, 1.Y.0) or only fix it (a patch release, 1.y.Z); each release is checked with cargo semver-checks against the previous one (RELEASING.md).

The C library keeps SB_ABI_VERSION 2 and the library names libscarletbook_ffi.so.2 and libscarletbook_ffi.2.dylib throughout 1.x. What counts as a breaking change of the C ABI is in ABI compatibility.

scarletbook-pcm is outside this promise. It stays at 0.7.0, is not part of the 1.0 freeze, and is being deprecated (#398): DSD-to-PCM conversion moves to its consumers. Until then it follows Cargo's rules for 0.y.z (the y step may break it, the z step may only add). The sb_pcm_* functions of the C library are part of ABI 2 and stay in it, even once they are marked deprecated.

Before 1.0, as in Cargo, the y step of 0.y.z was the major one and could break the API. Coming from 0.6 or earlier, Migrating to 0.7.0 (and, before it, Migrating to 0.6.0) gives a before-and-after for each change; 0.7 to 1.0.0 needs only the version.

Not covered:

  • items marked #[doc(hidden)];
  • the fuzzing feature of scarletbook-ffi, which exists for the fuzz targets;
  • the Rust items of scarletbook-ffi, whose interface is the C ABI;
  • scarletbook-bench and scarletbook-conformance, which are not published.

Versions

scarletbook, scarletbook-ffi and the unpublished crates share the workspace version, so a breaking change in one raises the version of them all, including crates that did not change (#39, owner decision of 2026-11-06). scarletbook-pcm is the exception from 1.0.0: it keeps its own version, 0.7.0, outside the freeze (#398), and a release that leaves it unchanged does not publish it again.

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 y of x.y.z, so 0.Y.0 before 1.0 and x.Y.0 from 1.0. It never rises in a release that changes only z.
  • 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:

cargo build --release -p scarletbook-bench
target/release/bench decode disc.iso --area 2ch --threads 0 --sink hash   # or null, or raw DIR

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:

target/release/bench dsf disc.iso --area 2ch --threads 0 --out out.dsf   # or /dev/null
target/release/bench dsf disc.iso --area mc --threads 0 --out out.dsf --via read-at --chunk 131072

--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:

taskset -c 2 target/release/bench realtime disc.iso --area mc --seeks 200

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:

target/release/bench open disc.iso
target/release/bench first disc.iso --area 2ch --threads 1 --track 3
target/release/bench first disc.iso --area 2ch --threads 0 --iterations 15 --evict benchmarks/evict.py

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:

gh attestation verify bench-<version>-x86_64-linux.tar.gz -R aclater/scarletbook-rs \
  --signer-workflow aclater/scarletbook-rs/.github/workflows/release.yml \
  --source-ref refs/tags/v<version>

The checksum detects a damaged download, not a replaced one; the attestation, checked with both flags, shows that the release workflow built the file from the tag (see "Verifying a download" under "C library").

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:

cargo bench -p scarletbook --bench dst_frames             # DstDecoder::decode, one frame per iteration
cargo bench -p scarletbook --bench dst_frames -- stress/2ch
cargo bench -p scarletbook-conformance --bench pipeline   # Disc::open + TrackAudio, in-memory images
cargo bench -p scarletbook-ffi --bench toc_read           # open + every TOC query, one disc per iteration
  • dst_frames reports 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 images dst-*.iso that decodes; and stress/Nch-LAYOUT, 2- and 6-channel frames generated at start-up by the annex 5.A encoder of crates/scarletbook/tests/common/dst_enc.rs from 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.
  • pipeline reads 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_read opens a disc and reads its whole TOC, as a consumer listing a library does (#132): c/IMAGE through sb_disc_open_callbacks_at over the image in memory and every TOC query of the C interface (disc, areas, tracks, strings, genres, text channels, timecodes, warnings), rust/IMAGE the same through Disc::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=list prints 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:

scarletbook-synth dst50.iso --minutes 50 --area 2ch --kind dst
cargo bench -p scarletbook-ffi --bench decode_pool -- dst50.iso c-read --threads 0 --rounds 3 --sink raw /dev/shm/out

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

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.