fix: cap CD audio extraction and harden sheet parsing (code-review pass)

Bound track counts, dedupe ranges and map cue FILE names to the file on
disk so a small sheet cannot write unbounded FLACs. Reject malformed
numbers and oversized sheets, sanitise CD-Text, catch encoder start and
upload rejection errors, and plan tracks before promoting a lone CHD.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Georges-Antoine Assi
2026-09-26 12:54:44 -04:00
parent bfb3addda4
commit ae7b8a502b
10 changed files with 371 additions and 62 deletions

View File

@@ -26,7 +26,7 @@ from handler.cd_audio import (
)
from handler.database import db_rom_handler
from handler.filesystem import fs_rom_handler
from handler.rom_upload import CATEGORY_UPLOAD_FOLDERS
from handler.rom_upload import CATEGORY_UPLOAD_FOLDERS, UploadRejectedException
from logger.formatter import BLUE
from logger.formatter import highlight as hl
from logger.logger import log
@@ -148,6 +148,7 @@ async def get_rom_cd_audio_status(
"/{id}/soundtracks/cd-audio",
[Scope.ROMS_WRITE],
responses={
status.HTTP_400_BAD_REQUEST: {},
status.HTTP_404_NOT_FOUND: {},
status.HTTP_409_CONFLICT: {},
status.HTTP_503_SERVICE_UNAVAILABLE: {},
@@ -172,6 +173,10 @@ async def extract_rom_cd_audio(
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(exc)
) from exc
except UploadRejectedException as exc:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)
) from exc
except (CdAudioNeedsFolderException, RomAlreadyExistsException) as exc:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT, detail=str(exc)

View File

@@ -16,6 +16,8 @@ from handler.rom_files import refresh_rom_files
from handler.rom_upload import (
CATEGORY_UPLOAD_FOLDERS,
UploadConflictException,
UploadRejectedException,
assert_promotable,
move_into_place,
prepare_upload_destination,
staging_path,
@@ -30,9 +32,14 @@ from utils.chd_cdrom import (
audio_tracks,
load_libchdr,
)
from utils.cue_sheet import AudioTrackRange, audio_track_ranges, parse_cue_sheet
from utils.cue_sheet import (
MAX_TRACKS,
AudioTrackRange,
audio_track_ranges,
parse_cue_sheet,
)
from utils.gdi_sheet import gdi_audio_ranges, parse_gdi_sheet
from utils.m3u import disc_number, listing_playlist
from utils.m3u import disc_number
FLAC_BINARY = "flac"
READ_CHUNK_BYTES = 1024 * 1024
@@ -40,6 +47,8 @@ READ_CHUNK_BYTES = 1024 * 1024
ENCODE_TIMEOUT_SECONDS = 600
# Sheets (.cue, Dreamcast .gdi) point at separate track files; a CHD holds them.
DISC_IMAGE_EXTENSIONS = (".cue", ".gdi", ".chd")
# A 99-track sheet with full CD-Text is a few tens of KiB.
MAX_SHEET_BYTES = 1024 * 1024
PcmChunks = Generator[bytes, None, None]
@@ -94,7 +103,10 @@ def track_prefixes(images: list[Path]) -> dict[Path, str]:
def _read_sheet(path: Path) -> str:
raw = path.read_bytes()
with path.open("rb") as sheet:
raw = sheet.read(MAX_SHEET_BYTES + 1)
if len(raw) > MAX_SHEET_BYTES:
raise CdAudioEncodeException(f"{path.name} is too large to be a disc sheet")
try:
return raw.decode("utf-8-sig")
except UnicodeDecodeError:
@@ -154,19 +166,37 @@ def _sheet_sources(sheet_path: Path) -> list[AudioSource]:
else:
cue_tracks = parse_cue_sheet(text)
located = _locate_files(sheet_path.parent, {t.file_name for t in cue_tracks})
# FILE names differing only in case open one file, so they share its
# layout rather than each spanning the whole of it.
cue_tracks = [
(
dataclasses.replace(track, file_name=located[track.file_name].name)
if track.file_name in located
else track
)
for track in cue_tracks
]
located = {path.name: path for path in located.values()}
ranges = audio_track_ranges(cue_tracks, _file_sizes(located))
return [
AudioSource(
number=track.number,
big_endian=track.big_endian,
title=track.title,
performer=track.performer,
pcm=functools.partial(
_bin_pcm, located[track.file_name], track.offset, track.length
),
sources: list[AudioSource] = []
# Lines pointing at the same samples would write the same audio again.
seen: set[tuple[Path, int]] = set()
for track in ranges:
path = located[track.file_name]
key = (path.resolve(), track.offset)
if key in seen:
continue
seen.add(key)
sources.append(
AudioSource(
number=track.number,
big_endian=track.big_endian,
title=track.title,
performer=track.performer,
pcm=functools.partial(_bin_pcm, path, track.offset, track.length),
)
)
for track in ranges
]
return sources
def _chd_sources(lib: ctypes.CDLL, chd_path: Path) -> list[AudioSource]:
@@ -239,12 +269,17 @@ async def encode_track(source: AudioSource, output: Path, album: str | None) ->
Raises:
CdAudioEncodeException: The image couldn't be read, or flac failed.
"""
process = await asyncio.create_subprocess_exec(
*_encode_args(source, album, output),
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.DEVNULL,
stderr=asyncio.subprocess.PIPE,
)
try:
process = await asyncio.create_subprocess_exec(
*_encode_args(source, album, output),
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.DEVNULL,
stderr=asyncio.subprocess.PIPE,
)
except (OSError, ValueError) as exc:
raise CdAudioEncodeException(
f"Could not start flac for track {source.number}"
) from exc
assert process.stdin is not None and process.stderr is not None
try:
await asyncio.wait_for(
@@ -322,7 +357,13 @@ def _disc_sources(images: list[RomFile], lib: ctypes.CDLL | None) -> list[AudioS
raise CdAudioEncodeException(f"Could not read {path.name}") from exc
if sources:
break
return sources
# Track numbers name the output files, so each is taken once, within the
# range a real disc can hold.
by_number: dict[int, AudioSource] = {}
for source in sources:
if 1 <= source.number <= MAX_TRACKS:
by_number.setdefault(source.number, source)
return list(by_number.values())
def _plan_tracks(
@@ -394,6 +435,8 @@ async def extract_cd_audio(rom: Rom) -> CdAudioExtraction:
CdAudioNeedsFolderException: A sheet, or a disc an .m3u lists, sits loose
in the platform folder.
CdAudioEncodeException: A track couldn't be encoded.
UploadRejectedException: A track's file name can't go in the soundtrack
folder, such as one the scanner excludes.
"""
if shutil.which(FLAC_BINARY) is None:
raise CdAudioUnavailableException("The flac encoder is not installed")
@@ -404,31 +447,26 @@ async def extract_cd_audio(rom: Rom) -> CdAudioExtraction:
return result
lib = load_libchdr()
lone = rom.has_simple_single_file
# A CHD is self-contained, but a lone sheet would leave its tracks behind.
if lone and not discs[0][0].file_name.lower().endswith(".chd"):
raise CdAudioNeedsFolderException(
"Move the disc into a folder of its own to extract its audio"
)
planned = await asyncio.to_thread(_plan_tracks, discs, lib)
# Nothing to write, so a lone disc stays where it is.
if not planned:
return result
if rom.has_simple_single_file:
[[image]] = discs
# A CHD is self-contained, but a lone sheet would leave its tracks behind.
if not image.file_name.lower().endswith(".chd"):
raise CdAudioNeedsFolderException(
"Move the disc into a folder of its own to extract its audio"
)
if lib is None:
raise CdAudioUnavailableException(
"Reading CHD images needs libchdr, which is not installed"
)
disc = fs_rom_handler.validate_path(image.full_path)
playlist = await asyncio.to_thread(listing_playlist, disc)
if playlist:
raise CdAudioNeedsFolderException(
f"{playlist} lists this disc, so moving it would break the "
"playlist. Move the set into a folder of its own to extract "
"its audio"
)
if lone:
try:
await asyncio.to_thread(assert_promotable, rom)
except UploadRejectedException as exc:
raise CdAudioNeedsFolderException(str(exc)) from exc
rom = await promote_single_file_to_folder(rom)
discs = _discs(rom)
planned = await asyncio.to_thread(_plan_tracks, _discs(rom), lib)
folder = CATEGORY_UPLOAD_FOLDERS[RomFileCategory.SOUNDTRACK]
planned = await asyncio.to_thread(_plan_tracks, discs, lib)
try:
for track in planned:
try:

View File

@@ -13,6 +13,7 @@ from fastapi.testclient import TestClient
from handler import cd_audio
from handler.database import db_rom_handler
from handler.filesystem import fs_rom_handler
from models.platform import Platform
from models.rom import Rom, RomFile, RomFileCategory, TrackMeta
from models.user import User
@@ -807,3 +808,175 @@ def test_falls_back_to_the_chd_when_the_sheet_lost_its_tracks(
"Disc - Track 02.flac",
"Disc - Track 03.flac",
]
def _add_sheet_rom(
admin_user: User,
platform: Platform,
real_library: Path,
contents: dict[str, bytes],
) -> Rom:
fs_path = f"{platform.slug}/roms/Disc Game"
folder = real_library / fs_path
folder.mkdir(parents=True)
for name, data in contents.items():
(folder / name).write_bytes(data)
return _add_disc_rom(
admin_user,
platform,
"Disc Game",
{name: len(data) for name, data in contents.items()},
fs_path,
)
def test_reads_a_file_named_in_several_cases_once(
client: TestClient,
access_token: str,
admin_user: User,
platform: Platform,
real_library: Path,
):
names = ["Track.bin", "TRACK.BIN", "track.bin"]
sheet = "".join(
f'FILE "{name}" BINARY\n TRACK {number:02d} AUDIO\n'
f" INDEX 01 00:00:{(number - 2) * 25:02d}\n"
for number, name in enumerate(names, 2)
)
rom = _add_sheet_rom(
admin_user,
platform,
real_library,
{"Disc.cue": sheet.encode(), "Track.bin": _tone(TRACK_2_SECTORS)},
)
response = client.post(
f"/api/roms/{rom.id}/soundtracks/cd-audio", headers=_auth(access_token)
)
assert response.status_code == status.HTTP_200_OK
durations = [
meta.duration_seconds
for meta in _soundtrack_metas(rom.id).values()
if meta is not None and meta.duration_seconds is not None
]
# Split three ways rather than each spanning the whole file.
assert sum(durations) == pytest.approx(
TRACK_2_SECTORS / SECTORS_PER_SECOND, abs=0.02
)
def test_takes_each_gdi_track_file_and_number_once(
client: TestClient,
access_token: str,
admin_user: User,
platform: Platform,
real_library: Path,
):
sheet = (
"5\n2 150 0 2352 track02.raw 0\n3 300 0 2352 TRACK02.RAW 0\n"
"4 450 0 2352 track02.raw 0\n0 600 0 2352 track05.raw 0\n"
"100 750 0 2352 track06.raw 0\n"
)
tone = _tone(TRACK_3_SECTORS)
rom = _add_sheet_rom(
admin_user,
platform,
real_library,
{
"disc.gdi": sheet.encode(),
"track02.raw": tone,
"track05.raw": tone,
"track06.raw": tone,
},
)
response = client.get(
f"/api/roms/{rom.id}/soundtracks/cd-audio", headers=_auth(access_token)
)
assert response.json() == {"tracks": 1, "extracted": 0}
def test_refuses_a_sheet_too_large_to_be_one(
client: TestClient,
access_token: str,
admin_user: User,
platform: Platform,
real_library: Path,
):
rom = _add_sheet_rom(
admin_user,
platform,
real_library,
{"Disc.cue": b"REM" + b" " * cd_audio.MAX_SHEET_BYTES},
)
response = client.get(
f"/api/roms/{rom.id}/soundtracks/cd-audio", headers=_auth(access_token)
)
assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR
def test_reports_a_track_name_the_scanner_would_ignore(
client: TestClient,
access_token: str,
cd_rom: Rom,
real_library: Path,
monkeypatch: pytest.MonkeyPatch,
):
monkeypatch.setattr(
fs_rom_handler,
"is_excluded_multi_part",
lambda file_name, cnfg=None: file_name.endswith(".flac"),
)
response = client.post(
f"/api/roms/{cd_rom.id}/soundtracks/cd-audio", headers=_auth(access_token)
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert not (real_library / cd_rom.full_path / "soundtrack").exists()
def test_leaves_a_lone_disc_without_audio_where_it_is(
client: TestClient,
access_token: str,
admin_user: User,
platform: Platform,
real_library: Path,
tmp_path: Path,
):
fs_path = f"{platform.slug}/roms"
(real_library / fs_path).mkdir(parents=True)
(tmp_path / "Data.cue").write_text(
'FILE "Data.bin" BINARY\n TRACK 01 MODE2/2352\n INDEX 01 00:00:00\n'
)
# libchdr can't open a CHD of a single hunk, so the track spans several.
(tmp_path / "Data.bin").write_bytes(b"\x01" * AUDIO_SECTOR * 300)
chd = real_library / fs_path / "Data Game.chd"
_create_chd(tmp_path / "Data.cue", chd)
rom = _add_disc_rom(
admin_user, platform, chd.name, {chd.name: chd.stat().st_size}, fs_path
)
response = client.post(
f"/api/roms/{rom.id}/soundtracks/cd-audio", headers=_auth(access_token)
)
assert response.json() == {"extracted": [], "skipped": []}
assert chd.is_file()
assert not (real_library / fs_path / "Data Game").exists()
async def test_reports_a_track_flac_cannot_be_started_for(tmp_path: Path):
def silence() -> Generator[bytes, None, None]:
yield b"\0" * 4
source = cd_audio.AudioSource(
number=2, big_endian=False, title="Open\0ing", performer=None, pcm=silence
)
with pytest.raises(cd_audio.CdAudioEncodeException):
await cd_audio.encode_track(source, tmp_path / "Track 02.flac", None)

View File

@@ -35,7 +35,17 @@ def test_parses_a_legacy_track_entry():
)
@pytest.mark.parametrize("text", ["", "TRACK:x TYPE:AUDIO FRAMES:1", "TYPE:AUDIO"])
@pytest.mark.parametrize(
"text",
[
"",
"TRACK:x TYPE:AUDIO FRAMES:1",
"TYPE:AUDIO",
"TRACK:2 TYPE:AUDIO FRAMES:-4",
"TRACK:2 TYPE:AUDIO FRAMES:4 PREGAP:-150 PGTYPE:VAUDIO",
"TRACK:2 TYPE:AUDIO FRAMES:4 PAD:-100",
],
)
def test_rejects_a_malformed_entry(text):
assert parse_track_metadata(text) is None

View File

@@ -154,3 +154,55 @@ def test_ignores_malformed_lines():
)
assert [(t.number, t.indexes) for t in tracks] == [(2, {1: SECOND})]
def test_skips_a_file_with_an_empty_name():
tracks = parse_cue_sheet(
'FILE "" BINARY\n TRACK 01 AUDIO\n INDEX 01 00:00:00\n'
)
assert audio_track_ranges(tracks, {}) == []
def test_skips_numbers_int_cannot_take():
tracks = parse_cue_sheet(
'FILE "Track.bin" BINARY\n'
" TRACK ² AUDIO\n"
f" TRACK {'1' * 5000} AUDIO\n"
" TRACK 02 AUDIO\n"
f" INDEX 01 {'1' * 5000}:00:00\n"
" INDEX ¹ 00:01:00\n"
" INDEX 01 00:02:00\n"
)
assert [(t.number, t.indexes) for t in tracks] == [(2, {1: 2 * SECOND})]
def test_strips_control_characters_from_cd_text():
tracks = parse_cue_sheet(
'FILE "Track.bin" BINARY\n'
" TRACK 01 AUDIO\n"
' TITLE "Open\x00ing"\n'
' PERFORMER "\x01"\n'
)
assert tracks[0].title == "Opening"
assert tracks[0].performer is None
def test_stops_measuring_where_a_track_starts_before_the_last():
tracks = parse_cue_sheet(
'FILE "Game.bin" BINARY\n'
" TRACK 01 AUDIO\n"
" INDEX 01 00:00:00\n"
" TRACK 02 AUDIO\n"
" INDEX 01 00:02:00\n"
" TRACK 03 AUDIO\n"
" INDEX 01 00:00:00\n"
" TRACK 04 AUDIO\n"
" INDEX 01 00:02:00\n"
)
ranges = audio_track_ranges(tracks, {"Game.bin": 10 * SECOND * AUDIO_SECTOR})
assert [(r.number, r.offset) for r in ranges] == [(1, 0)]

View File

@@ -53,3 +53,11 @@ def test_takes_each_audio_track_as_its_whole_file():
def test_skips_audio_tracks_missing_from_disk():
assert gdi_audio_ranges(parse_gdi_sheet(GDI_SHEET), {}) == []
def test_skips_a_line_with_a_number_int_cannot_take():
tracks = parse_gdi_sheet(
f"2\n{'1' * 5000} 0 0 2352 a.raw 0\n2 450 0 2352 t.raw 0\n"
)
assert [t.number for t in tracks] == [2]

View File

@@ -7,6 +7,8 @@ from collections.abc import Iterator
from dataclasses import dataclass
from pathlib import Path
from utils.cue_sheet import MAX_TRACKS
# A CD frame in a CHD: one raw sector followed by its subcode.
SECTOR_BYTES = 2352
FRAME_BYTES = SECTOR_BYTES + 96
@@ -51,18 +53,21 @@ def parse_track_metadata(text: str) -> ChdTrack | None:
token.split(":", 1) for token in text.strip("\0 ").split() if ":" in token
)
try:
pregap = int(fields.get("PREGAP", "0"))
return ChdTrack(
track = ChdTrack(
number=int(fields["TRACK"]),
type=fields["TYPE"].upper(),
frames=int(fields["FRAMES"]),
pregap=pregap,
pregap=int(fields.get("PREGAP", "0")),
# A 'V' pregap type means the pregap's frames are in the image.
pregap_stored=fields.get("PGTYPE", "").upper().startswith("V"),
pad=int(fields.get("PAD", "0")),
)
except KeyError, ValueError:
return None
# A negative count would move later tracks back over earlier ones.
if min(track.frames, track.pregap, track.pad) < 0:
return None
return track
def audio_tracks(tracks: list[ChdTrack]) -> list[ChdAudioTrack]:
@@ -164,10 +169,17 @@ class ChdImage:
for tag in TRACK_METADATA_TAGS:
found: list[ChdTrack] = []
index = 0
while not self._lib.chd_get_metadata(
# Each lookup walks the metadata chain from its start, so a crafted
# image with endless entries is cut off where a real disc must end.
while index < MAX_TRACKS and not self._lib.chd_get_metadata(
self._handle, tag, index, buffer, len(buffer), length, None, None
):
track = parse_track_metadata(buffer.value.decode("ascii", "replace"))
# libchdr doesn't NUL-terminate, so a shorter entry would
# otherwise carry the tail of the one read before it.
raw = buffer.raw[: min(length.value, len(buffer))]
track = parse_track_metadata(
raw.split(b"\0", 1)[0].decode("ascii", "replace")
)
if track:
found.append(track)
index += 1

View File

@@ -5,6 +5,8 @@ from collections.abc import Mapping
from dataclasses import dataclass, field
FRAMES_PER_SECOND = 75
# Red Book numbers a disc's tracks 1 to 99.
MAX_TRACKS = 99
# Bytes per sector for each track mode a raw image can hold.
SECTOR_SIZES = {
@@ -21,8 +23,13 @@ SECTOR_SIZES = {
# FILE types holding raw sectors; WAVE, MP3 and AIFF tracks are already audio.
RAW_FILE_TYPES = {"BINARY": False, "MOTOROLA": True}
_FILE_REGEX = re.compile(r'^(?:"(?P<quoted>[^"]*)"|(?P<bare>\S+))\s+(?P<type>\S+)$')
_MSF_REGEX = re.compile(r"^(\d+):(\d{1,2}):(\d{1,2})$")
_FILE_REGEX = re.compile(r'^(?:"(?P<quoted>[^"]+)"|(?P<bare>\S+))\s+(?P<type>\S+)$')
# ASCII digits of bounded length, so int() never meets a superscript or a
# number past its digit limit.
_NUMBER_REGEX = re.compile(r"\d{1,3}", re.ASCII)
_MSF_REGEX = re.compile(r"^(\d{1,4}):(\d{1,2}):(\d{1,2})$", re.ASCII)
# Control characters would reach flac's argv, where a NUL can't go.
_CONTROL_REGEX = re.compile(r"[\x00-\x1f\x7f]")
@dataclass
@@ -49,11 +56,11 @@ class AudioTrackRange:
performer: str | None
def _unquote(value: str) -> str:
def _cd_text(value: str) -> str | None:
value = value.strip()
if len(value) >= 2 and value[0] == value[-1] == '"':
return value[1:-1]
return value
value = value[1:-1]
return _CONTROL_REGEX.sub("", value) or None
def _msf_to_frames(value: str) -> int | None:
@@ -90,7 +97,7 @@ def parse_cue_sheet(text: str) -> list[CueTrack]:
file_type = match.group("type").upper()
elif keyword == "TRACK" and file_name:
number, _, mode = rest.partition(" ")
if number.isdigit():
if _NUMBER_REGEX.fullmatch(number):
tracks.append(
CueTrack(
number=int(number),
@@ -102,10 +109,10 @@ def parse_cue_sheet(text: str) -> list[CueTrack]:
elif keyword == "INDEX" and tracks:
index, _, position = rest.partition(" ")
frames = _msf_to_frames(position)
if index.isdigit() and frames is not None:
if _NUMBER_REGEX.fullmatch(index) and frames is not None:
tracks[-1].indexes[int(index)] = frames
elif keyword in ("TITLE", "PERFORMER") and tracks:
setattr(tracks[-1], keyword.lower(), _unquote(rest) or None)
setattr(tracks[-1], keyword.lower(), _cd_text(rest))
return tracks
@@ -140,9 +147,10 @@ def audio_track_ranges(
break
if position:
previous = file_tracks[position - 1]
if previous.mode not in SECTOR_SIZES:
break
sectors = min(track.indexes.values()) - min(previous.indexes.values())
# A region opening before the last one would replay its audio.
if previous.mode not in SECTOR_SIZES or sectors < 0:
break
region_starts.append(
region_starts[-1] + sectors * SECTOR_SIZES[previous.mode]
)

View File

@@ -10,10 +10,11 @@ AUDIO_TRACK_TYPE = 0
AUDIO_SECTOR_BYTES = 2352
# "<track> <lba> <type> <sector size> <file> <offset>", the file quoted when it
# has spaces.
# has spaces. Numbers are ASCII and bounded so int() always takes them.
_LINE_REGEX = re.compile(
r'^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(?:"(?P<quoted>[^"]+)"|(?P<bare>\S+))'
r"\s+-?\d+\s*$"
r"^\s*(\d{1,3})\s+(\d{1,9})\s+(\d{1,3})\s+(\d{1,5})\s+"
r'(?:"(?P<quoted>[^"]+)"|(?P<bare>\S+))\s+-?\d+\s*$',
re.ASCII,
)

View File

@@ -207,6 +207,8 @@ async function extractCdAudio() {
snackbar.error(
t("rom.soundtrack-cd-audio-failed", { error: errorMessage(error) }),
);
// The tracks written before the failure are registered all the same.
await refetchRom(romId);
} finally {
extractingCdAudio.value = false;
}