use std::io::{Read, Seek};
use crate::error::{Error, Slot, Warning, WarningCode};
use crate::image::{Image, MASTER_TOC_LSN, ReadOutcome, SECTOR_SIZE, SectorFormat};
use crate::log::{Log, sb_log};
use crate::text::{self, Charset};
pub const MAX_AREA_TOC_SECTORS: u16 = 128;
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Toc {
pub sector_format: SectorFormat,
pub sectors: u64,
pub master: MasterToc,
pub areas: Vec<Area>,
}
impl Toc {
pub fn area(&self, slot: Slot) -> Option<&Area> {
self.areas.iter().find(|a| a.slot == slot)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Version {
pub major: u8,
pub minor: u8,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Genre {
pub category: u8,
pub index: u8,
}
impl Genre {
fn parse(b: &[u8]) -> Genre {
Genre { category: byte(b, 0), index: byte(b, 3) }
}
pub fn name(self) -> Option<&'static str> {
if self.category != 1 {
return None;
}
GENERAL_GENRES.get(usize::from(self.index)).copied()
}
}
const GENERAL_GENRES: [&str; 30] = [
"not used",
"not defined",
"Adult Contemporary",
"Alternative Rock",
"Children's Music",
"Classical",
"Contemporary Christian",
"Country",
"Dance",
"Easy Listening",
"Erotic",
"Folk",
"Gospel",
"Hip Hop",
"Jazz",
"Latin",
"Musical",
"New Age",
"Opera",
"Operetta",
"Pop Music",
"Rap",
"Reggae",
"Rock Music",
"Rhythm & Blues",
"Sound Effects",
"Sound Track",
"Spoken Word",
"World Music",
"Blues",
];
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Date {
pub year: u16,
pub month: u8,
pub day: u8,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Locale {
pub language: String,
pub language_code: [u8; 2],
pub charset: u8,
}
impl Locale {
fn parse(b: &[u8]) -> Locale {
let code = [byte(b, 0), byte(b, 1)];
Locale { language: text::language(code), language_code: code, charset: byte(b, 2) }
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Timecode {
pub minutes: u8,
pub seconds: u8,
pub frames: u8,
}
impl Timecode {
pub fn frame_number(self) -> u32 {
(u32::from(self.minutes) * 60 + u32::from(self.seconds)) * 75 + u32::from(self.frames)
}
pub(crate) fn parse(b: &[u8]) -> Timecode {
Timecode { minutes: byte(b, 0), seconds: byte(b, 1), frames: byte(b, 2) }
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct AreaPointer {
pub toc1_lsn: u32,
pub toc2_lsn: u32,
pub toc_sectors: u16,
}
impl AreaPointer {
pub fn is_used(self) -> bool {
self.toc1_lsn != 0 && self.toc_sectors != 0
}
}
macro_rules! text_struct {
(
$(#[$meta:meta])* $name:ident, $(#[$imeta:meta])* $item:ident { $($(#[$fmeta:meta])* $field:ident = $key:literal => $variant:ident),* $(,)? }
) => {
$(#[$meta])*
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct $name {
$($(#[$fmeta])* pub $field: Option<String>,)*
}
$(#[$imeta])*
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum $item {
$($(#[$fmeta])* $variant,)*
}
impl $item {
pub const ALL: &'static [$item] = &[$($item::$variant),*];
pub fn name(self) -> &'static str {
match self { $($item::$variant => $key,)* }
}
}
impl $name {
pub fn get(&self, item: $item) -> Option<&str> {
match item { $($item::$variant => self.$field.as_deref(),)* }
}
fn slot(&mut self, item: $item) -> &mut Option<String> {
match item { $($item::$variant => &mut self.$field,)* }
}
pub fn iter(&self) -> impl Iterator<Item = ($item, &str)> + '_ {
$item::ALL.iter().filter_map(move |&i| self.get(i).map(|t| (i, t)))
}
pub fn is_empty(&self) -> bool {
self.iter().next().is_none()
}
}
};
}
text_struct! {
DiscText,
DiscTextItem {
album_title = "album_title" => AlbumTitle,
album_artist = "album_artist" => AlbumArtist,
album_publisher = "album_publisher" => AlbumPublisher,
album_copyright = "album_copyright" => AlbumCopyright,
album_title_phonetic = "album_title_phonetic" => AlbumTitlePhonetic,
album_artist_phonetic = "album_artist_phonetic" => AlbumArtistPhonetic,
album_publisher_phonetic = "album_publisher_phonetic" => AlbumPublisherPhonetic,
album_copyright_phonetic = "album_copyright_phonetic" => AlbumCopyrightPhonetic,
disc_title = "disc_title" => DiscTitle,
disc_artist = "disc_artist" => DiscArtist,
disc_publisher = "disc_publisher" => DiscPublisher,
disc_copyright = "disc_copyright" => DiscCopyright,
disc_title_phonetic = "disc_title_phonetic" => DiscTitlePhonetic,
disc_artist_phonetic = "disc_artist_phonetic" => DiscArtistPhonetic,
disc_publisher_phonetic = "disc_publisher_phonetic" => DiscPublisherPhonetic,
disc_copyright_phonetic = "disc_copyright_phonetic" => DiscCopyrightPhonetic,
}
}
text_struct! {
AreaText,
AreaTextItem {
description = "description" => Description,
copyright = "copyright" => Copyright,
description_phonetic = "description_phonetic" => DescriptionPhonetic,
copyright_phonetic = "copyright_phonetic" => CopyrightPhonetic,
}
}
text_struct! {
TrackText,
#[non_exhaustive]
TrackTextItem {
title = "title" => Title,
performer = "performer" => Performer,
songwriter = "songwriter" => Songwriter,
composer = "composer" => Composer,
arranger = "arranger" => Arranger,
message = "message" => Message,
extra_message = "extra_message" => ExtraMessage,
title_phonetic = "title_phonetic" => TitlePhonetic,
performer_phonetic = "performer_phonetic" => PerformerPhonetic,
songwriter_phonetic = "songwriter_phonetic" => SongwriterPhonetic,
composer_phonetic = "composer_phonetic" => ComposerPhonetic,
arranger_phonetic = "arranger_phonetic" => ArrangerPhonetic,
message_phonetic = "message_phonetic" => MessagePhonetic,
extra_message_phonetic = "extra_message_phonetic" => ExtraMessagePhonetic,
}
}
impl TrackTextItem {
pub fn from_type(t: u8) -> Option<TrackTextItem> {
let base = t & 0x7F;
if !(1..=7).contains(&base) {
return None;
}
let idx = usize::from(base - 1) + if t & 0x80 != 0 { 7 } else { 0 };
TrackTextItem::ALL.get(idx).copied()
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct MasterToc {
pub version: Version,
pub album_set_size: u16,
pub album_sequence_number: u16,
pub album_catalog_number: String,
pub album_catalog_number_stored: Vec<u8>,
pub album_genres: [Genre; 4],
pub two_channel: AreaPointer,
pub multichannel: AreaPointer,
pub disc_flags: u8,
pub disc_catalog_number: String,
pub disc_catalog_number_stored: Vec<u8>,
pub disc_genres: [Genre; 4],
pub date: Date,
pub text_channel_count: u8,
pub locales: Vec<Locale>,
pub text_charset: u8,
pub text: DiscText,
pub manufacturer: Option<Vec<u8>>,
}
impl MasterToc {
pub fn hybrid(&self) -> bool {
self.disc_flags & 0x80 != 0
}
pub fn pointer(&self, slot: Slot) -> AreaPointer {
match slot {
Slot::TwoChannel => self.two_channel,
Slot::Multichannel => self.multichannel,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum AreaKind {
TwoChannel,
Multichannel,
}
impl AreaKind {
pub fn signature(self) -> &'static str {
match self {
AreaKind::TwoChannel => "TWOCHTOC",
AreaKind::Multichannel => "MULCHTOC",
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Area {
pub slot: Slot,
pub kind: AreaKind,
pub version: Version,
pub toc_lsn: u32,
pub toc_sectors: u16,
pub max_byte_rate: u32,
pub sample_frequency_code: u8,
pub frame_format: u8,
pub channel_count: u8,
pub area_config: u8,
pub max_available_channels: u8,
pub area_mute_flags: u8,
pub track_attribute: u8,
pub playtime: Timecode,
pub track_offset: u8,
pub audio_start_lsn: u32,
pub audio_end_lsn: u32,
pub text_channel_count: u8,
pub locales: Vec<Locale>,
pub text_charset: u8,
pub text: AreaText,
pub tracks: Vec<Track>,
}
impl Area {
pub fn playtime_frames(&self) -> u32 {
self.playtime.frame_number()
}
pub fn track(&self, number: u32) -> Option<&Track> {
number.checked_sub(1).and_then(|i| self.tracks.get(i as usize))
}
pub fn loudspeaker_layout(&self) -> LoudspeakerLayout {
LoudspeakerLayout::new(self.channel_count, self.area_config)
}
pub fn channel_speakers(&self) -> Option<&'static [Speaker]> {
self.loudspeaker_layout().speakers()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum LoudspeakerLayout {
Stereo,
ThreeTwo,
FivePointOne,
#[non_exhaustive]
Unspecified {
channels: u8,
config: u8,
},
}
impl LoudspeakerLayout {
pub fn new(channels: u8, config: u8) -> Self {
match (channels, config & 0x07) {
(2, 0) => LoudspeakerLayout::Stereo,
(5, 3) => LoudspeakerLayout::ThreeTwo,
(6, 4) => LoudspeakerLayout::FivePointOne,
_ => LoudspeakerLayout::Unspecified { channels, config },
}
}
pub fn speakers(self) -> Option<&'static [Speaker]> {
use Speaker::*;
match self {
LoudspeakerLayout::Stereo => Some(&[FrontLeft, FrontRight]),
LoudspeakerLayout::ThreeTwo => {
Some(&[FrontLeft, FrontRight, Centre, SurroundLeft, SurroundRight])
}
LoudspeakerLayout::FivePointOne => {
Some(&[FrontLeft, FrontRight, Centre, LowFrequencyEffects, SurroundLeft, SurroundRight])
}
LoudspeakerLayout::Unspecified { .. } => None,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Speaker {
FrontLeft,
FrontRight,
Centre,
LowFrequencyEffects,
SurroundLeft,
SurroundRight,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Track {
pub number: u8,
pub start_lsn: u32,
pub length_sectors: u32,
pub start_frame: u32,
pub duration_frames: u32,
pub start_flags: u8,
pub duration_flags: u8,
pub isrc: Option<String>,
pub genre: Option<Genre>,
pub text: TrackText,
}
impl Track {
pub fn end_frame(&self) -> u32 {
self.start_frame.saturating_add(self.duration_frames)
}
}
fn byte(b: &[u8], at: usize) -> u8 {
b.get(at).copied().unwrap_or(0)
}
fn be16(b: &[u8], at: usize) -> u16 {
u16::from_be_bytes([byte(b, at), byte(b, at.saturating_add(1))])
}
fn be32(b: &[u8], at: usize) -> u32 {
let a = |i: usize| byte(b, at.saturating_add(i));
u32::from_be_bytes([a(0), a(1), a(2), a(3)])
}
fn sub(b: &[u8], at: usize, len: usize) -> &[u8] {
b.get(at..at.saturating_add(len)).unwrap_or(&[])
}
fn genres(b: &[u8], at: usize) -> [Genre; 4] {
std::array::from_fn(|i| Genre::parse(sub(b, at + 4 * i, 4)))
}
struct Warnings {
list: Vec<Warning>,
log: Log,
}
impl Warnings {
fn push(&mut self, w: Warning) {
sb_log!(&self.log, Warn, "warning: {w}");
self.list.push(w);
}
}
pub(crate) fn read_toc<R: Read + Seek>(
img: &mut Image<R>,
) -> Result<(Toc, Vec<Warning>, TocDigests, TocStored), Error> {
let log = img.log().clone();
sb_log!(
&log,
Info,
"reading the TOC: sector format {:?}, {} sectors ({} bytes)",
img.format(),
img.sector_count(),
img.len()
);
let mut warnings = Warnings { list: Vec::new(), log };
let (master, master_digest) = read_master(img, &mut warnings)?;
let mut areas = Vec::new();
let mut area_digests = Vec::new();
let mut stored = TocStored::default();
for slot in Slot::ALL {
let ptr = master.pointer(slot);
if !ptr.is_used() {
sb_log!(&warnings.log, Info, "area {slot}: slot unused");
continue;
}
if let Some((area, digest, timecodes)) = read_area(img, slot, ptr, &mut warnings)? {
area_digests.push(digest);
stored.track_timecodes.push((slot, timecodes));
sb_log!(
&warnings.log,
Info,
"area {slot}: {} area, {} channels, sample frequency code {}, audio LSN {}..={}, {} tracks, \
play time {} frames",
area.kind.signature(),
area.channel_count,
area.sample_frequency_code,
area.audio_start_lsn,
area.audio_end_lsn,
area.tracks.len(),
area.playtime_frames()
);
areas.push(area);
} else {
sb_log!(&warnings.log, Info, "area {slot}: skipped");
}
}
if areas.is_empty() {
sb_log!(&warnings.log, Info, "rejected: no audio areas");
return Err(Error::NoAudioAreas);
}
sb_log!(&warnings.log, Info, "TOC read: {} areas, {} warnings", areas.len(), warnings.list.len());
let digests = TocDigests { master: master_digest, areas: area_digests };
Ok((
Toc { sector_format: img.format(), sectors: img.sector_count(), master, areas },
warnings.list,
digests,
stored,
))
}
#[derive(Debug, Default)]
pub(crate) struct TocStored {
track_timecodes: Vec<(Slot, Vec<TrackTimecodes>)>,
}
type TrackTimecodes = (Timecode, Timecode);
impl TocStored {
pub(crate) fn track_timecodes(&self, slot: Slot, number: u32) -> Option<(Timecode, Timecode)> {
let (_, list) = self.track_timecodes.iter().find(|(s, _)| *s == slot)?;
list.get(usize::try_from(number).ok()?.checked_sub(1)?).copied()
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct TocDigests {
master: u64,
areas: Vec<u64>,
}
impl TocDigests {
pub(crate) fn of<R: Read + Seek>(img: &mut Image<R>, toc: &Toc) -> Result<Option<Self>, Error> {
let mut sector = vec![0u8; SECTOR_SIZE];
if img.read_into(u64::from(MASTER_TOC_LSN), &mut sector)? == ReadOutcome::OutOfRange {
return Ok(None);
}
let master = toc_digest(§or);
let mut areas = Vec::with_capacity(toc.areas.len());
for area in &toc.areas {
let Some(copy) = read_copy(img, area.toc_lsn, area.toc_sectors)? else { return Ok(None) };
areas.push(toc_digest(©));
}
Ok(Some(TocDigests { master, areas }))
}
}
fn toc_digest(bytes: &[u8]) -> u64 {
const K: u64 = 0x9e37_79b9_7f4a_7c15;
let mix = |h: u64, w: u64| (h ^ w).wrapping_mul(K).rotate_left(31);
let mut lanes: [u64; 4] = [0, 1, 2, 3];
let mut blocks = bytes.chunks_exact(32);
for block in &mut blocks {
for (lane, word) in lanes.iter_mut().zip(block.chunks_exact(8)) {
*lane = mix(*lane, u64::from_le_bytes(word.try_into().unwrap_or([0; 8])));
}
}
let mut h = lanes.iter().fold(bytes.len() as u64, |h, &lane| mix(h, lane));
for &b in blocks.remainder() {
h = mix(h, u64::from(b));
}
h ^= h >> 32;
h = h.wrapping_mul(K);
h ^ (h >> 29)
}
fn read_master<R: Read + Seek>(
img: &mut Image<R>,
warnings: &mut Warnings,
) -> Result<(MasterToc, u64), Error> {
let mut buf = vec![0u8; 10 * SECTOR_SIZE];
if img.read_into(u64::from(MASTER_TOC_LSN), &mut buf)? == ReadOutcome::OutOfRange {
sb_log!(&warnings.log, Info, "rejected: master TOC at LSN {MASTER_TOC_LSN} truncated");
return Err(Error::MasterTocTruncated);
}
let s0 = sub(&buf, 0, SECTOR_SIZE);
if sub(s0, 0, 8) != b"SACDMTOC" {
sb_log!(&warnings.log, Info, "rejected: no master TOC signature at LSN {MASTER_TOC_LSN}");
return Err(Error::NotScarletbook);
}
let version = Version { major: byte(s0, 8), minor: byte(s0, 9) };
if version.major > 1 {
sb_log!(&warnings.log, Info, "rejected: master TOC version {}.{}", version.major, version.minor);
return Err(Error::MasterTocVersionUnsupported { major: version.major, minor: version.minor });
}
sb_log!(
&warnings.log,
Info,
"master TOC at LSN {MASTER_TOC_LSN} used, version {}.{}",
version.major,
version.minor
);
if master_copies_differ(img, &buf) {
warnings.push(Warning::disc(WarningCode::MasterTocCopiesDiffer));
}
let text_channel_count = byte(s0, 128);
let locales =
(0..usize::from(text_channel_count.min(8))).map(|i| Locale::parse(sub(s0, 136 + 4 * i, 4))).collect();
let text_charset = byte(s0, 138);
let s1 = sub(&buf, SECTOR_SIZE, SECTOR_SIZE);
let mut disc_text = DiscText::default();
if sub(s1, 0, 8) == b"SACDText" {
let cs = Charset::from_code(text_charset);
for (i, &item) in DiscTextItem::ALL.iter().enumerate() {
let off = usize::from(be16(s1, 16 + 2 * i));
if off == 0 || off >= SECTOR_SIZE {
continue;
}
*disc_text.slot(item) = text::text_string(s1, off, cs);
}
} else if text_channel_count > 0 {
warnings.push(Warning::disc(WarningCode::MasterTextMissing));
}
let s9 = sub(&buf, 9 * SECTOR_SIZE, SECTOR_SIZE);
let manufacturer = if sub(s9, 0, 8) == b"SACD_Man" {
Some(sub(s9, 8, SECTOR_SIZE - 8).to_vec())
} else {
warnings.push(Warning::disc(WarningCode::ManufacturerMissing));
None
};
let pointer = |lsn1: usize, lsn2: usize, size: usize| AreaPointer {
toc1_lsn: be32(s0, lsn1),
toc2_lsn: be32(s0, lsn2),
toc_sectors: be16(s0, size),
};
let master = MasterToc {
version,
album_set_size: be16(s0, 16),
album_sequence_number: be16(s0, 18),
album_catalog_number: text::fixed_text(sub(s0, 24, 16)),
album_catalog_number_stored: text::fixed_bytes(sub(s0, 24, 16)).to_vec(),
album_genres: genres(s0, 40),
two_channel: pointer(64, 68, 84),
multichannel: pointer(72, 76, 86),
disc_flags: byte(s0, 80),
disc_catalog_number: text::fixed_text(sub(s0, 88, 16)),
disc_catalog_number_stored: text::fixed_bytes(sub(s0, 88, 16)).to_vec(),
disc_genres: genres(s0, 104),
date: Date { year: be16(s0, 120), month: byte(s0, 122), day: byte(s0, 123) },
text_channel_count,
locales,
text_charset,
text: disc_text,
manufacturer,
};
Ok((master, toc_digest(s0)))
}
const MASTER_TOC_COPIES: [u32; 2] = [520, 530];
fn master_copies_differ<R: Read + Seek>(img: &mut Image<R>, master: &[u8]) -> bool {
let mut copy = vec![0u8; master.len()];
MASTER_TOC_COPIES.iter().any(|&lsn| {
let differs = match img.read_into(u64::from(lsn), &mut copy) {
Ok(ReadOutcome::Ok) => Some(copy != master),
_ => None,
};
let outcome = match differs {
Some(true) => "differs from LSN 510",
Some(false) => "same as LSN 510",
None => "unreadable, not compared",
};
sb_log!(img.log(), Debug, "master TOC copy at LSN {lsn}: {outcome}");
differs == Some(true)
})
}
fn read_copy<R: Read + Seek>(img: &mut Image<R>, lsn: u32, sectors: u16) -> Result<Option<Vec<u8>>, Error> {
let mut buf = vec![0u8; usize::from(sectors) * SECTOR_SIZE];
Ok(match img.read_into(u64::from(lsn), &mut buf)? {
ReadOutcome::Ok => Some(buf),
ReadOutcome::OutOfRange => None,
})
}
#[derive(Default)]
struct Chain {
ttxt: Option<usize>,
igl: Option<usize>,
trl1: Option<usize>,
trl2: Option<usize>,
}
fn walk(z: &[u8]) -> Chain {
let e = z.len();
let mut chain = Chain::default();
let mut p = SECTOR_SIZE;
while p + 8 <= e {
match sub(z, p, 8) {
b"SACDTTxt" => {
chain.ttxt.get_or_insert(p);
p += SECTOR_SIZE;
}
b"SACD_IGL" => {
chain.igl = Some(p);
p += 2 * SECTOR_SIZE;
}
b"SACD_ACC" => p += 32 * SECTOR_SIZE,
b"SACDTRL1" => {
chain.trl1 = Some(p);
p += SECTOR_SIZE;
}
b"SACDTRL2" => {
chain.trl2 = Some(p);
p += SECTOR_SIZE;
}
_ => break,
}
}
chain
}
fn read_area<R: Read + Seek>(
img: &mut Image<R>,
slot: Slot,
ptr: AreaPointer,
warnings: &mut Warnings,
) -> Result<Option<(Area, u64, Vec<TrackTimecodes>)>, Error> {
let skip = |warnings: &mut Warnings, code| {
warnings.push(Warning::area(code, slot));
Ok(None)
};
let t = ptr.toc_sectors;
if t > MAX_AREA_TOC_SECTORS {
return skip(warnings, WarningCode::AreaTocTooLarge);
}
sb_log!(
img.log(),
Debug,
"area {slot}: TOC-1 at LSN {}, TOC-2 at LSN {}, {t} sectors",
ptr.toc1_lsn,
ptr.toc2_lsn
);
let toc1 = read_copy(img, ptr.toc1_lsn, t)?;
if toc1.is_none() {
warnings.push(Warning::area(WarningCode::AreaToc1Unreadable, slot));
}
let toc2 = if ptr.toc2_lsn != 0 {
let c = read_copy(img, ptr.toc2_lsn, t)?;
if c.is_none() {
warnings.push(Warning::area(WarningCode::AreaToc2Unreadable, slot));
}
c
} else {
None
};
let (z, toc_lsn) = match (toc1, toc2) {
(Some(a), b) => {
let other = match b {
Some(b) if b != a => {
warnings.push(Warning::area(WarningCode::AreaTocCopiesDiffer, slot));
"TOC-2 differs"
}
Some(_) => "TOC-2 identical",
None if ptr.toc2_lsn == 0 => "no TOC-2",
None => "TOC-2 unreadable",
};
sb_log!(img.log(), Info, "area {slot}: TOC-1 at LSN {} used ({other})", ptr.toc1_lsn);
(a, ptr.toc1_lsn)
}
(None, Some(b)) => {
sb_log!(img.log(), Info, "area {slot}: TOC-2 at LSN {} used (TOC-1 unreadable)", ptr.toc2_lsn);
(b, ptr.toc2_lsn)
}
(None, None) => return skip(warnings, WarningCode::AreaTocUnreadable),
};
let e = z.len();
let kind = match sub(&z, 0, 8) {
b"TWOCHTOC" => AreaKind::TwoChannel,
b"MULCHTOC" => AreaKind::Multichannel,
_ => return skip(warnings, WarningCode::AreaSignatureInvalid),
};
let chain = walk(&z);
let (Some(trl1), Some(trl2)) = (chain.trl1, chain.trl2) else {
return skip(warnings, WarningCode::AreaTrackListMissing);
};
let track_count = byte(&z, 69);
if let Some(g) = chain.igl {
if track_count >= 1 && g + 2 * SECTOR_SIZE > e {
return skip(warnings, WarningCode::AreaTocMalformed);
}
}
let audio_start_lsn = be32(&z, 72);
let audio_end_lsn = be32(&z, 76);
if audio_end_lsn < audio_start_lsn {
return skip(warnings, WarningCode::AreaAudioRangeReversed);
}
let text_charset = byte(&z, 90);
let cs = Charset::from_code(text_charset);
let text_channel_count = byte(&z, 80);
let locales =
(0..usize::from(text_channel_count.min(10))).map(|i| Locale::parse(sub(&z, 88 + 4 * i, 4))).collect();
let mut area_text = AreaText::default();
for (i, &item) in AreaTextItem::ALL.iter().enumerate() {
let off = usize::from(be16(&z, 144 + 2 * i));
if off != 0 && off < e {
*area_text.slot(item) = text::text_string(&z, off, cs);
}
}
let sample_frequency_code = byte(&z, 20);
if sample_frequency_code != 4 {
warnings.push(Warning::area(WarningCode::SampleFrequencyUnknown, slot));
}
let playtime = Timecode::parse(sub(&z, 64, 3));
let p_frames = playtime.frame_number();
let mut tracks = Vec::with_capacity(usize::from(track_count));
let mut timecodes = Vec::with_capacity(usize::from(track_count));
for i in 0..usize::from(track_count) {
let number = u8::try_from(i + 1).unwrap_or(u8::MAX);
let start_tc = Timecode::parse(sub(&z, trl2 + 8 + 4 * i, 3));
let dur_tc = Timecode::parse(sub(&z, trl2 + 1028 + 4 * i, 3));
timecodes.push((start_tc, dur_tc));
let (mut start_frame, mut duration_frames) = (start_tc.frame_number(), dur_tc.frame_number());
if start_frame + duration_frames > p_frames {
start_frame = start_frame.min(p_frames);
duration_frames = duration_frames.min(p_frames - start_frame);
warnings.push(Warning::track(WarningCode::TrackPastPlaytime, slot, number));
}
let start_lsn = be32(&z, trl1 + 8 + 4 * i);
if !(audio_start_lsn..=audio_end_lsn).contains(&start_lsn) {
warnings.push(Warning::track(WarningCode::TrackLsnOutsideArea, slot, number));
}
let (isrc, genre) = match chain.igl {
Some(g) => {
let isrc = text::fixed_text(sub(&z, g + 8 + 12 * i, 12));
((!isrc.is_empty()).then_some(isrc), Some(Genre::parse(sub(&z, g + 3072 + 4 * i, 4))))
}
None => (None, None),
};
let text = match chain.ttxt {
Some(b) => track_text(&z, b, i, cs, slot, number, warnings),
None => TrackText::default(),
};
tracks.push(Track {
number,
start_lsn,
length_sectors: be32(&z, trl1 + 1028 + 4 * i),
start_frame,
duration_frames,
start_flags: byte(&z, trl2 + 11 + 4 * i),
duration_flags: byte(&z, trl2 + 1031 + 4 * i),
isrc,
genre,
text,
});
}
let area = Area {
slot,
kind,
version: Version { major: byte(&z, 8), minor: byte(&z, 9) },
toc_lsn,
toc_sectors: t,
max_byte_rate: be32(&z, 16),
sample_frequency_code,
frame_format: byte(&z, 21) & 0x0F,
channel_count: byte(&z, 32),
area_config: byte(&z, 33),
max_available_channels: byte(&z, 34),
area_mute_flags: byte(&z, 35),
track_attribute: byte(&z, 48) & 0x0F,
playtime,
track_offset: byte(&z, 68),
audio_start_lsn,
audio_end_lsn,
text_channel_count,
locales,
text_charset,
text: area_text,
tracks,
};
Ok(Some((area, toc_digest(&z), timecodes)))
}
fn track_text(
z: &[u8],
b: usize,
i: usize,
cs: Charset,
slot: Slot,
number: u8,
warnings: &mut Warnings,
) -> TrackText {
let e = z.len();
let mut out = TrackText::default();
let offset = usize::from(be16(z, b + 8 + 2 * i));
if offset == 0 {
return out;
}
let mut q = b + offset;
if q + 4 > e {
warnings.push(Warning::track(WarningCode::TrackTextOffsetInvalid, slot, number));
return out;
}
let k = byte(z, q);
q += 4;
let mut warned_type = false;
for j in 0..k {
if q + 2 > e {
break;
}
let item_type = byte(z, q);
q += 2;
let bytes = text::string_bytes(z, q);
let r = bytes.len();
if r > 0 {
match TrackTextItem::from_type(item_type) {
Some(item) => *out.slot(item) = text::decode_string(bytes, cs),
None if !warned_type => {
warned_type = true;
warnings.push(Warning::track(WarningCode::TrackTextTypeUnknown, slot, number));
}
None => {}
}
}
if j + 1 < k {
let from = q + r;
q = z.get(from..).and_then(|rest| rest.iter().position(|&x| x != 0)).map_or(e, |n| from + n);
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn toc_digest_tells_small_changes_apart() {
let mut bytes: Vec<u8> = (0..2 * SECTOR_SIZE).map(|i| (i * 7 % 251) as u8).collect();
let mut seen = std::collections::HashSet::from([toc_digest(&bytes)]);
for i in (0..bytes.len()).step_by(61) {
bytes[i] ^= 1 << (i % 8);
assert!(seen.insert(toc_digest(&bytes)), "flip at byte {i}");
bytes[i] ^= 1 << (i % 8);
}
bytes.swap(0, 8);
assert!(seen.insert(toc_digest(&bytes)));
assert!(seen.insert(toc_digest(&bytes[..SECTOR_SIZE])));
assert!(seen.insert(toc_digest(&bytes[..SECTOR_SIZE + 5])));
assert!(seen.insert(toc_digest(&[])));
assert_ne!(toc_digest(&[0; SECTOR_SIZE]), toc_digest(&[0; SECTOR_SIZE + 1]));
}
#[test]
fn track_text_item_types() {
assert_eq!(TrackTextItem::from_type(0x01), Some(TrackTextItem::Title));
assert_eq!(TrackTextItem::from_type(0x07), Some(TrackTextItem::ExtraMessage));
assert_eq!(TrackTextItem::from_type(0x81), Some(TrackTextItem::TitlePhonetic));
assert_eq!(TrackTextItem::from_type(0x87), Some(TrackTextItem::ExtraMessagePhonetic));
for t in [0x00, 0x08, 0x41, 0x80, 0x88, 0xC1, 0xFF] {
assert_eq!(TrackTextItem::from_type(t), None, "{t:#x}");
}
}
#[test]
fn loudspeaker_layouts() {
use Speaker::*;
assert_eq!(LoudspeakerLayout::new(2, 0), LoudspeakerLayout::Stereo);
assert_eq!(LoudspeakerLayout::new(5, 3), LoudspeakerLayout::ThreeTwo);
assert_eq!(LoudspeakerLayout::new(6, 4), LoudspeakerLayout::FivePointOne);
assert_eq!(LoudspeakerLayout::Stereo.speakers(), Some(&[FrontLeft, FrontRight][..]));
assert_eq!(
LoudspeakerLayout::ThreeTwo.speakers(),
Some(&[FrontLeft, FrontRight, Centre, SurroundLeft, SurroundRight][..])
);
assert_eq!(
LoudspeakerLayout::FivePointOne.speakers(),
Some(&[FrontLeft, FrontRight, Centre, LowFrequencyEffects, SurroundLeft, SurroundRight][..])
);
for high in [0x08, 0x10, 0x80, 0xF8] {
assert_eq!(LoudspeakerLayout::new(2, high), LoudspeakerLayout::Stereo, "{high:#x}");
assert_eq!(LoudspeakerLayout::new(5, high | 3), LoudspeakerLayout::ThreeTwo, "{high:#x}");
assert_eq!(LoudspeakerLayout::new(6, high | 4), LoudspeakerLayout::FivePointOne, "{high:#x}");
}
let mut defined = 0;
for channels in 0..=u8::MAX {
for config in 0..=u8::MAX {
let layout = LoudspeakerLayout::new(channels, config);
if matches!((channels, config & 7), (2, 0) | (5, 3) | (6, 4)) {
defined += 1;
assert_eq!(layout.speakers().map(<[Speaker]>::len), Some(usize::from(channels)));
} else {
assert_eq!(layout, LoudspeakerLayout::Unspecified { channels, config });
assert_eq!(layout.speakers(), None);
}
}
}
assert_eq!(defined, 3 * 32);
}
#[test]
fn timecode_frame_numbers() {
let tc = Timecode { minutes: 255, seconds: 255, frames: 255 };
assert_eq!(tc.frame_number(), 1_166_880);
assert_eq!(Timecode { minutes: 0, seconds: 1, frames: 2 }.frame_number(), 77);
}
#[test]
fn walk_stops_and_records() {
let mut z = vec![0u8; 6 * SECTOR_SIZE];
z[2048..2056].copy_from_slice(b"SACDTTxt");
z[4096..4104].copy_from_slice(b"SACDTTxt");
z[6144..6152].copy_from_slice(b"SACDTRL1");
z[8192..8200].copy_from_slice(b"SACDTRL2");
z[10240..10248].copy_from_slice(b"SACD_IGL");
let c = walk(&z);
assert_eq!((c.ttxt, c.trl1, c.trl2, c.igl), (Some(2048), Some(6144), Some(8192), Some(10240)));
z[4096..4104].copy_from_slice(b"XXXXXXXX");
let c = walk(&z);
assert_eq!((c.ttxt, c.trl1), (Some(2048), None));
}
}