scarletbook 1.0.1

Clean-room reader for Super Audio CD (Scarletbook) disc images
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
// SPDX-License-Identifier: MIT OR Apache-2.0

//! DSDIFF (specification 8, 8.4).

use std::ops::Range;

use super::markers::{self, Markers};
use super::tags::{ArtistTitleSource, TagItem, TagSet};
use super::{Checked, Layout, OutputOptions, Part, RegionKind, SourceTrack};
use super::{Tags, dsdiff_text};
use crate::audio::FRAME_BYTES_PER_CHANNEL;
use crate::error::Error;
use crate::toc::{Area, LoudspeakerLayout, Toc};

/// The sample rate written (8.1 item 4, 8.4.3).
const SAMPLE_RATE: u32 = 2_822_400;

/// Frames per hour, the hours unit of a DSDIFF time (8.4.7 item 1).
const FRAMES_PER_HOUR: u64 = 270_000;

/// The largest `A + N` an absolute start time allows (8.4.8): every time stays below 24 hours.
pub(super) const MAX_TIME_FRAMES: u64 = 6_479_999;

/// A chunk of the property chunk (specification 8, 8.4.3), for
/// [`OutputOptions::dsdiff_property_order`] (writer's choice W14).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum PropertyChunk {
    /// `FS  `, the sample rate.
    SampleRate,
    /// `CHNL`, the channels.
    Channels,
    /// `CMPR`, the compression type.
    CompressionType,
    /// `ABSS`, the absolute start time (written when [`OutputOptions::dsdiff_absolute_start`]
    /// is set).
    AbsoluteStartTime,
    /// `LSCO`, the loudspeaker configuration (written as W15 and W16 say).
    LoudspeakerConfiguration,
}

impl PropertyChunk {
    /// The order of the table of 8.4.3, the default.
    pub const TABLE_ORDER: [PropertyChunk; 5] = [
        PropertyChunk::SampleRate,
        PropertyChunk::Channels,
        PropertyChunk::CompressionType,
        PropertyChunk::AbsoluteStartTime,
        PropertyChunk::LoudspeakerConfiguration,
    ];
}

/// Appends a chunk: its ID, its data size `D` (u64, most significant byte first), its data,
/// and a pad byte 0x00 when `D` is odd (8.4.1 item 1).
pub(super) fn chunk(out: &mut Vec<u8>, id: &[u8; 4], data: &[u8]) {
    chunk_head(out, id, data.len() as u64);
    out.extend_from_slice(data);
    if data.len() % 2 == 1 {
        out.push(0);
    }
}

/// Appends a chunk's ID and data size `d`.
pub(super) fn chunk_head(out: &mut Vec<u8>, id: &[u8; 4], d: u64) {
    out.extend_from_slice(id);
    out.extend_from_slice(&d.to_be_bytes());
}

/// The space a chunk of data size `d` occupies (8.4.1 item 1).
pub(super) fn occupied(d: u64) -> u64 {
    12 + d + d % 2
}

/// A DSDIFF time of frame `g`: hours, minutes, seconds, samples (8.4.7 item 1).
pub(super) fn time(g: u64) -> (u16, u8, u8, u32) {
    // `g` is at most `MAX_TIME_FRAMES`, so the hours are below 24.
    ((g / FRAMES_PER_HOUR) as u16, (g / 4500 % 60) as u8, (g / 75 % 60) as u8, (g % 75 * 37_632) as u32)
}

/// The channel IDs and `LSCO` value of the area (8.4.4), or of an unspecified layout from
/// the options (W15).
fn channels(area: &Area, options: &OutputOptions) -> Result<(Vec<[u8; 4]>, Option<u16>), Error> {
    let lsco = |v| options.dsdiff_loudspeaker_configuration.then_some(v);
    Ok(match area.loudspeaker_layout() {
        LoudspeakerLayout::Stereo => (vec![*b"SLFT", *b"SRGT"], lsco(0)),
        LoudspeakerLayout::ThreeTwo => (vec![*b"MLFT", *b"MRGT", *b"C   ", *b"LS  ", *b"RS  "], lsco(3)),
        LoudspeakerLayout::FivePointOne => {
            (vec![*b"MLFT", *b"MRGT", *b"C   ", *b"LFE ", *b"LS  ", *b"RS  "], lsco(4))
        }
        LoudspeakerLayout::Unspecified { channels, .. } => {
            let numbers: Vec<u16> = match &options.dsdiff_unspecified_channel_numbers {
                Some(n) => n.clone(),
                None => (0..u16::from(channels)).collect(),
            };
            if numbers.len() != usize::from(channels) {
                return Err(Error::InvalidArgument("give one DSDIFF channel number per channel"));
            }
            let mut seen = [false; 1000];
            let mut ids = Vec::with_capacity(numbers.len());
            for n in numbers {
                let slot = seen
                    .get_mut(usize::from(n))
                    .ok_or(Error::InvalidArgument("DSDIFF channel numbers are 0 to 999"))?;
                if std::mem::replace(slot, true) {
                    return Err(Error::InvalidArgument("DSDIFF channel numbers must be distinct"));
                }
                let d = |p: u16| b'0' + (n / p % 10) as u8;
                ids.push([b'C', d(100), d(10), d(1)]);
            }
            (ids, options.dsdiff_unspecified_loudspeaker_configuration.then_some(65_535))
        }
    })
}

/// A departure from the DSDIFF document (specification 8, 8.7, at sacd-spec `e069569`), for
/// [`OutputOptions::dsdiff_departures`].
///
/// **A file written with a departure is not a conforming DSDIFF file.** It does not conform to
/// the DSDIFF document or to specification 8. Some existing programs write such files;
/// specification 8 defines the departures byte for byte only so that a writer asked to
/// reproduce those files does so knowingly and the same way as others. None is made unless
/// it is named.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[non_exhaustive]
pub enum DsdiffDeparture {
    /// D1, the `CMPR` size counts the pad byte: with plain DSD, `CMPR` is written with
    /// `D = 20` instead of 19. The pad byte 0x00 after the compression name is still
    /// written, now counted, so the chunk still occupies 32 bytes and no other size changes.
    /// With DST, `D` is 16 and nothing changes.
    D1,
    /// D2, DSDIFF text as ISO 8859-1: in `DIAR`, `DITI`, marker text and comment text, a
    /// code point from U+0020 to U+007E or from U+00A0 to U+00FF is written as the one byte
    /// of the same value, and every other code point is removed, whatever
    /// [`OutputOptions::dsdiff_text_replacement`] says. Text lengths `k` count the bytes
    /// written; the pad byte after odd text and W22 are unchanged. The bytes of a custom
    /// [`super::Marker`]'s text may then also be 0xA0 to 0xFF. `EMID` and chunk IDs are
    /// unchanged: still bytes 0x20 to 0x7E.
    D2,
}

/// The compression type of plain DSD (8.4.3).
const CMPR_DSD: (&[u8; 4], &[u8]) = (b"DSD ", b"not compressed");

/// The compression type of DST (8.4.3).
const CMPR_DST: (&[u8; 4], &[u8]) = (b"DST ", b"DST Encoded");

/// Builds `PROP` (8.4.3) for compression `cmpr`.
fn property(area: &Area, options: &OutputOptions, n: u64, cmpr: (&[u8; 4], &[u8])) -> Result<Vec<u8>, Error> {
    let (ids, lsco) = channels(area, options)?;
    let order = options.dsdiff_property_order;
    let mut sorted = order;
    sorted.sort_by_key(|c| PropertyChunk::TABLE_ORDER.iter().position(|t| t == c));
    if sorted != PropertyChunk::TABLE_ORDER {
        return Err(Error::InvalidArgument("the property order must name each property chunk once"));
    }
    if let Some(a) = options.dsdiff_absolute_start {
        if u64::from(a) + n > MAX_TIME_FRAMES {
            return Err(Error::InvalidArgument(
                "the absolute start time plus the range must stay below 24 hours",
            ));
        }
    }
    let mut prop = b"SND ".to_vec();
    for c in order {
        match c {
            PropertyChunk::SampleRate => chunk(&mut prop, b"FS  ", &SAMPLE_RATE.to_be_bytes()),
            PropertyChunk::Channels => {
                let mut d = (ids.len() as u16).to_be_bytes().to_vec();
                ids.iter().for_each(|id| d.extend_from_slice(id));
                chunk(&mut prop, b"CHNL", &d);
            }
            PropertyChunk::CompressionType => {
                let mut d = cmpr.0.to_vec();
                d.push(cmpr.1.len() as u8);
                d.extend_from_slice(cmpr.1);
                // 8.7 D1: an odd `D` counts its pad byte (plain DSD, 19 to 20); the bytes
                // are the same, since `chunk` would otherwise add the pad uncounted.
                if options.departs(DsdiffDeparture::D1) && d.len() % 2 == 1 {
                    d.push(0);
                }
                chunk(&mut prop, b"CMPR", &d);
            }
            PropertyChunk::AbsoluteStartTime => {
                if let Some(a) = options.dsdiff_absolute_start {
                    let (h, m, s, samples) = time(u64::from(a));
                    let mut d = h.to_be_bytes().to_vec();
                    d.extend_from_slice(&[m, s]);
                    d.extend_from_slice(&samples.to_be_bytes());
                    chunk(&mut prop, b"ABSS", &d);
                }
            }
            PropertyChunk::LoudspeakerConfiguration => {
                if let Some(v) = lsco {
                    chunk(&mut prop, b"LSCO", &v.to_be_bytes());
                }
            }
        }
    }
    let mut out = Vec::new();
    chunk(&mut out, b"PROP", &prop);
    Ok(out)
}

/// A local chunk of a DSDIFF file whose position is the writer's choice (specification 8,
/// 8.4.2 item 2; W13), for [`OutputOptions::dsdiff_local_order`]. `FVER` is always first.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum LocalChunk {
    /// `PROP`, the property chunk; it must come before the sound data.
    Property,
    /// The sound data chunk, `DSD ` or `DST `.
    SoundData,
    /// `DSTI`, the DST sound index (written with DST sound data as
    /// [`OutputOptions::dsdiff_dst_index`] says).
    DstIndex,
    /// `DIIN`, the edited master information (written as
    /// [`OutputOptions::dsdiff_edited_master_info`] says).
    EditedMasterInfo,
    /// `COMT`, the comments (written when [`OutputOptions::dsdiff_comments`] has one).
    Comments,
}

impl LocalChunk {
    /// The default order: `PROP`, `COMT`, `DIIN`, the sound data, `DSTI`. Chunks added later take
    /// their place in it, so it is a slice.
    pub const DEFAULT_ORDER: &'static [LocalChunk] = &[
        LocalChunk::Property,
        LocalChunk::Comments,
        LocalChunk::EditedMasterInfo,
        LocalChunk::SoundData,
        LocalChunk::DstIndex,
    ];
}

/// A caller chunk of a DSDIFF file (specification 8, 8.4.2 item 5, at sacd-spec `e069569`;
/// 8.6 row 33): an ID and data bytes that the caller supplies, written after the last local
/// chunk as 8.4.1 item 1 says, with a pad byte 0x00, not counted in `D`, when `D` is odd.
/// Neither the DSDIFF document nor specification 8 defines its data, which is written as it
/// is. For example an `ID3 ` chunk holding an ID3 tag.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct CallerChunk {
    id: [u8; 4],
    data: Vec<u8>,
}

/// The IDs of the chunks specification 8 defines, which a caller chunk may not have
/// (8.4.2 item 5).
const RESERVED_IDS: [&[u8; 4]; 9] =
    [b"FRM8", b"FVER", b"PROP", b"DSD ", b"DST ", b"DSTI", b"COMT", b"DIIN", b"MANF"];

impl CallerChunk {
    /// A chunk with ID `id` and data `data`.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidArgument`] if `id` is not 4 bytes from 0x20 to 0x7E with no space
    /// before a non-space (8.4.1 item 3), or is one of `FRM8`, `FVER`, `PROP`, `DSD `,
    /// `DST `, `DSTI`, `COMT`, `DIIN` and `MANF` (8.4.2 item 5).
    pub fn new(id: [u8; 4], data: Vec<u8>) -> Result<CallerChunk, Error> {
        if !id.iter().all(|b| (0x20..=0x7E).contains(b))
            || id.windows(2).any(|w| w[0] == b' ' && w[1] != b' ')
        {
            return Err(Error::InvalidArgument(
                "a chunk ID is 4 bytes 0x20 to 0x7E, with no space before a non-space",
            ));
        }
        if RESERVED_IDS.contains(&&id) {
            return Err(Error::InvalidArgument(
                "a caller chunk may not have the ID of a chunk specification 8 defines",
            ));
        }
        Ok(CallerChunk { id, data })
    }

    /// The ID.
    pub fn id(&self) -> [u8; 4] {
        self.id
    }

    /// The data, without the pad byte.
    pub fn data(&self) -> &[u8] {
        &self.data
    }
}

/// The sound data of a file, for [`assemble`].
pub(super) enum Sound {
    /// Plain DSD (8.4.5): data size `D`.
    Dsd(DsdData, u64),
    /// DST (8.4.6).
    Dst(super::dsdiff_dst::DstData),
}

/// Lays out a DSDIFF file: `FRM8`, `DSD `, `FVER`, then `PROP`, the sound data and `DSTI` in
/// the order of the options, then the caller chunks (8.4.2).
pub(super) fn assemble(
    layout: &mut Layout,
    toc: &Toc,
    area: &Area,
    options: &OutputOptions,
    sound: Sound,
) -> Result<(), Error> {
    let edited;
    let options = if options.dsdiff_edited_master {
        // 8.4.11: the area and range qualify, and the file has `ABSS`, `LSCO` and `DIIN`
        // with the program's markers.
        markers::check_edited_master(area, layout.first, layout.end)?;
        if matches!(options.dsdiff_markers, Markers::Custom(_)) {
            return Err(Error::InvalidArgument(
                "an edited master has the program's markers, not custom ones",
            ));
        }
        // `LSCO` is required (8.4.11 item 1; 8.6 row 16).
        if !options.dsdiff_loudspeaker_configuration {
            return Err(Error::InvalidArgument("an edited master has LSCO"));
        }
        // So is `EMID` (8.4.11 item 1; 8.4.8 and 8.6 row 24 as of sacd-spec e069569).
        if !options.dsdiff_edited_master_id_written {
            return Err(Error::InvalidArgument("an edited master has EMID"));
        }
        edited = OutputOptions {
            dsdiff_absolute_start: Some(options.dsdiff_absolute_start.unwrap_or(0)),
            dsdiff_edited_master_info: true,
            // W24: the artist and title the DSDIFF document recommends, unless the caller says no.
            dsdiff_artist_title: Some(options.dsdiff_artist_title.unwrap_or(true)),
            source_track: SourceTrack::None,
            ..options.clone()
        };
        &edited
    } else {
        options
    };
    // W26: the replacement is itself a text byte (8.4.9).
    if let Some(r) = options.dsdiff_text_replacement {
        markers::check_text(&[r])?;
    }
    let positions = u64::from(layout.end - layout.first);
    let cmpr = match sound {
        Sound::Dsd(..) => CMPR_DSD,
        Sound::Dst(_) => CMPR_DST,
    };
    let prop = property(area, options, positions, cmpr)?;
    let index = match &sound {
        Sound::Dst(_) if options.dsdiff_dst_index => Some(12 * positions),
        _ => None,
    };
    let diin = if options.dsdiff_edited_master_info {
        let source = if options.dsdiff_edited_master {
            None
        } else {
            layout.source.and_then(|n| area.track(u32::from(n)))
        };
        let list = match &options.dsdiff_markers {
            Markers::FromToc => markers::from_toc(area, layout.first, layout.end, source, options),
            Markers::Custom(list) => list.clone(),
        };
        // W24: the artist and title, from the file's tag items (8.4.8).
        let set = match &options.tags {
            Tags::FromToc if options.dsdiff_artist_title == Some(true) => {
                Some(TagSet::from_toc(toc, area, source, options))
            }
            Tags::Set(set) if options.dsdiff_artist_title == Some(true) => Some(set.clone()),
            _ => None,
        };
        let first = |item| set.as_ref().and_then(|s| s.get(item).first().map(String::as_str));
        // W24 (8.4.8 as of sacd-spec e069569): in a file with a source track, the track's
        // performer and title (3.8, types 0x02 and 0x01) may fill `DIAR` and `DITI`
        // instead; a file without one has no track strings.
        let pick = |track: TagItem, album: TagItem| {
            let track = || source.and_then(|_| first(track));
            match options.dsdiff_artist_title_source {
                ArtistTitleSource::Album => first(album),
                ArtistTitleSource::Track => track(),
                ArtistTitleSource::TrackThenAlbum => track().or_else(|| first(album)),
            }
        };
        let artist = pick(TagItem::Performer, TagItem::AlbumArtist);
        let title = pick(TagItem::TrackTitle, TagItem::Album);
        markers::diin(layout, &list, artist, title, options)?
    } else {
        None
    };
    let comt = dsdiff_text::comt(layout.channels, options)?;
    let written = |c: LocalChunk| match c {
        LocalChunk::Property | LocalChunk::SoundData => true,
        LocalChunk::Comments => comt.is_some(),
        LocalChunk::EditedMasterInfo => diin.is_some(),
        LocalChunk::DstIndex => index.is_some(),
    };
    let mut order: Vec<LocalChunk> = Vec::with_capacity(LocalChunk::DEFAULT_ORDER.len());
    for &c in &options.dsdiff_local_order {
        if order.contains(&c) {
            return Err(Error::InvalidArgument("the local chunk order must name each chunk once"));
        }
        order.push(c);
    }
    if LocalChunk::DEFAULT_ORDER.iter().any(|&c| written(c) && !order.contains(&c)) {
        return Err(Error::InvalidArgument("the local chunk order must name every chunk the file holds"));
    }
    order.retain(|&c| written(c));
    let at = |c| order.iter().position(|&x| x == c);
    if at(LocalChunk::Property) > at(LocalChunk::SoundData) {
        return Err(Error::InvalidArgument("the property chunk must come before the sound data"));
    }

    // The sound data chunk's header (and `FRTE`) and its data size `D`.
    let (sound_head, sound_d) = match &sound {
        Sound::Dsd(_, d) => {
            let mut h = b"DSD ".to_vec();
            h.extend_from_slice(&d.to_be_bytes());
            (h, *d)
        }
        Sound::Dst(dst) => (dst.head(), dst.data_size()),
    };
    let size_of = |c: LocalChunk| match c {
        LocalChunk::Property => prop.len() as u64,
        LocalChunk::Comments => comt.as_ref().map_or(0, |d| d.len() as u64),
        LocalChunk::EditedMasterInfo => diin.as_ref().map_or(0, |d| d.len() as u64),
        LocalChunk::SoundData => occupied(sound_d),
        LocalChunk::DstIndex => index.map_or(0, occupied),
    };
    // 8.4.2 item 5 (e069569): the caller chunks, after the last local chunk.
    let callers: u64 = options.dsdiff_caller_chunks.iter().map(|c| occupied(c.data.len() as u64)).sum();
    // `FRM8` data: the ID `DSD `, `FVER`, then the local chunks, caller chunks included
    // (8.4.2 item 4).
    let frm8 = 4 + 16 + order.iter().map(|&c| size_of(c)).sum::<u64>() + callers;
    let mut bytes = Vec::with_capacity(32 + prop.len());
    chunk_head(&mut bytes, b"FRM8", frm8);
    bytes.extend_from_slice(b"DSD ");
    chunk(&mut bytes, b"FVER", &0x0105_0000u32.to_be_bytes());
    // Where the sound data's first `DSTF` chunk begins, for the index.
    let mut units = 32;
    for &c in &order {
        match c {
            LocalChunk::SoundData => break,
            c => units += size_of(c),
        }
    }
    units += sound_head.len() as u64;
    for &c in &order {
        match c {
            LocalChunk::Property => bytes.extend_from_slice(&prop),
            LocalChunk::Comments => bytes.extend_from_slice(comt.as_deref().unwrap_or_default()),
            LocalChunk::EditedMasterInfo => bytes.extend_from_slice(diin.as_deref().unwrap_or_default()),
            LocalChunk::DstIndex => {
                if let Sound::Dst(dst) = &sound {
                    let entries = dst.index(units, options.dsdiff_dst_index_offset);
                    chunk(&mut bytes, b"DSTI", &entries);
                }
            }
            LocalChunk::SoundData => {
                bytes.extend_from_slice(&sound_head);
                let kind = if layout.regions.is_empty() { RegionKind::Header } else { RegionKind::Trailer };
                layout.push(kind, bytes.len() as u64, Part::Bytes(std::mem::take(&mut bytes)));
                let data = sound_d - (sound_head.len() as u64 - 12);
                match &sound {
                    Sound::Dsd(d, _) => layout.push(RegionKind::SoundData, data, Part::Dsd(d.clone())),
                    Sound::Dst(d) => layout.push(RegionKind::SoundData, data, Part::Dst(d.clone())),
                }
            }
        }
    }
    for c in &options.dsdiff_caller_chunks {
        chunk(&mut bytes, &c.id, &c.data);
    }
    if !bytes.is_empty() {
        layout.push(RegionKind::Trailer, bytes.len() as u64, Part::Bytes(bytes));
    }
    Ok(())
}

/// Builds the regions of a plain DSD DSDIFF file (8.4.2, 8.4.5).
pub(super) fn build_dsd(
    layout: &mut Layout,
    toc: &Toc,
    area: &Area,
    options: &OutputOptions,
) -> Result<(), Error> {
    let positions = u64::from(layout.end - layout.first);
    // Even, so no pad byte follows (8.4.5).
    let d = positions * u64::from(layout.channels) * FRAME_BYTES_PER_CHANNEL as u64;
    assemble(layout, toc, area, options, Sound::Dsd(DsdData { channels: layout.channels }, d))
}

/// Plain DSD sound data (8.4.5): the positions' content, in order, unchanged.
#[derive(Clone, Debug)]
pub(super) struct DsdData {
    channels: u8,
}

impl DsdData {
    fn frame(&self) -> u64 {
        u64::from(self.channels) * FRAME_BYTES_PER_CHANNEL as u64
    }

    /// The positions, relative to the range's first, that sound data bytes `range` read.
    pub(super) fn positions(&self, range: Range<u64>) -> Range<u32> {
        // Below `N`, a u32.
        (range.start / self.frame()) as u32..((range.end - 1) / self.frame() + 1) as u32
    }

    /// Fills `out` with sound data bytes from `offset`: byte `o mod 4704C` of the content of
    /// position `o / 4704C`.
    #[inline(always)]
    pub(super) fn fill(
        &self,
        offset: u64,
        out: &mut [u8],
        first: u32,
        source: &mut Checked<'_>,
    ) -> Result<(), Error> {
        let frame = self.frame();
        let mut done = 0;
        while done < out.len() {
            let o = offset + done as u64;
            let within = (o % frame) as usize;
            let content = source.content(first + (o / frame) as u32)?;
            let n = (content.len() - within).min(out.len() - done);
            out[done..done + n].copy_from_slice(&content[within..within + n]);
            done += n;
        }
        Ok(())
    }
}