# SPDX-License-Identifier: MIT """A disc image: a CUE sheet and its BIN files, as raw 2,352-byte sectors. A Redump image has one BIN per track. The data track's file starts at its index 1; an audio track's file starts with its pregap (``INDEX 00``) and gives ``INDEX 01`` two seconds in. Laid end to end the files are the disc from absolute time 00:02:00 on, so a sector's place is its **LBA**: 0 at 00:02:00, and the first track's pregap (LBA -150 to -1) is not in any file and reads as zeros. Only what the CUE sheet says is used (CDRWIN's manual, Appendix A: ``FILE``, ``TRACK``, ``INDEX``, ``PREGAP``); ``MODE1/2352``, ``MODE2/2352`` and ``AUDIO`` tracks, raw sectors only. No subcode: R-W is not in a BIN/CUE. """ from __future__ import annotations import re import zipfile from dataclasses import dataclass from pathlib import Path SECTOR_SIZE = 2352 PREGAP = 150 # the two seconds before LBA 0 AUDIO = 0 MODE1 = 1 MODE2 = 2 @dataclass class Track: number: int kind: int # AUDIO, MODE1 or MODE2 start: int # LBA of index 1 pregap: int # LBA of index 0 (= start when the sheet gives none) end: int = 0 # LBA after its last sector def msf_to_frames(text: str) -> int: minutes, seconds, frames = (int(part) for part in text.split(":")) return (minutes * 60 + seconds) * 75 + frames def bcd(value: int) -> int: return ((value // 10) << 4) | (value % 10) def lba_to_msf(lba: int) -> tuple[int, int, int]: """Absolute time of ``lba``: minutes, seconds, frames (LBA 0 is 00:02:00).""" frames = lba + PREGAP return frames // 4500, (frames // 75) % 60, frames % 75 class Disc: """The tracks and the sectors. ``Disc.open(path)`` takes a ``.cue``, or a zip of a CUE and its BINs, which is unpacked beside ``cache`` first.""" def __init__(self, tracks: list[Track], spans: list[tuple[int, int, Path]]) -> None: self.tracks = tracks #: (first LBA, LBA after the last, file) for each BIN, in order. self._spans = spans self._files: dict[Path, object] = {} #: LBA of the lead-out: the disc's length. self.end = tracks[-1].end def __getstate__(self) -> dict[str, object]: """Without the open files: a saved machine opens them again when it reads.""" return {**self.__dict__, "_files": {}} @classmethod def open(cls, path: str | Path, cache: str | Path | None = None) -> Disc: path = Path(path) if path.suffix.lower() == ".zip": folder = Path(cache) if cache is not None else path.with_suffix("") folder = folder / path.stem if cache is not None else folder with zipfile.ZipFile(path) as archive: names = [name for name in archive.namelist() if not name.endswith("/")] if not all((folder / name).exists() for name in names): folder.mkdir(parents=True, exist_ok=True) archive.extractall(folder) sheets = sorted(folder.rglob("*.cue")) if not sheets: raise ValueError(f"{path}: no CUE sheet inside") path = sheets[0] return cls.from_cue(path) @classmethod def from_cue(cls, path: Path) -> Disc: tracks: list[Track] = [] spans: list[tuple[int, int, Path]] = [] position = 0 # LBA at which the current file starts file_length = 0 current: Track | None = None for line in path.read_text(encoding="utf-8", errors="replace").splitlines(): words = line.split() if not words: continue keyword = words[0].upper() if keyword == "FILE": match = re.search(r'"(.*)"', line) name = match.group(1) if match else words[1] if words[-1].upper() != "BINARY": raise ValueError(f"{path}: only BINARY files are read ({name})") position += file_length file = path.parent / name file_length = file.stat().st_size // SECTOR_SIZE spans.append((position, position + file_length, file)) elif keyword == "TRACK": kinds = {"AUDIO": AUDIO, "MODE1/2352": MODE1, "MODE2/2352": MODE2} if words[2].upper() not in kinds: raise ValueError(f"{path}: track type {words[2]} is not read") current = Track(int(words[1]), kinds[words[2].upper()], -1, -1) tracks.append(current) elif keyword == "INDEX" and current is not None: at = position + msf_to_frames(words[2]) if int(words[1]) == 0: current.pregap = at elif int(words[1]) == 1: current.start = at if current.pregap < 0: current.pregap = at elif keyword == "PREGAP": raise ValueError(f"{path}: PREGAP (silence not in the file) is not read") if not tracks or any(track.start < 0 for track in tracks): raise ValueError(f"{path}: a track has no INDEX 01") total = position + file_length for track, following in zip(tracks, [*tracks[1:], None], strict=True): track.end = following.pregap if following is not None else total return cls(tracks, spans) def track_at(self, lba: int) -> int: """Index into :attr:`tracks` of the track ``lba`` is in (its pregap included); ``len(tracks)`` past the end.""" for index, track in enumerate(self.tracks): if lba < track.end: return index return len(self.tracks) def read_sector(self, lba: int) -> bytes: """The 2,352 bytes at ``lba``; zeros outside the files.""" for first, after, file in self._spans: if first <= lba < after: handle = self._files.get(file) if handle is None: handle = self._files[file] = file.open("rb") handle.seek((lba - first) * SECTOR_SIZE) # type: ignore[attr-defined] data = handle.read(SECTOR_SIZE) # type: ignore[attr-defined] return data.ljust(SECTOR_SIZE, b"\x00") return bytes(SECTOR_SIZE)