diff --git a/CHANGELOG.md b/CHANGELOG.md index b350a44..1a40cc8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,15 @@ instead of a dated snapshot. - `chd_read_header_core_file_callbacks` public API. - pkg-config file (`libchdr.pc`) installed alongside the library. - Unity-build script (`unity.c`). +- CD sector access by LBA: `chd_cd_open` parses the track metadata + into a TOC (`chd_cd_get_toc`), and `chd_cd_read_sector` reads user + data, raw sectors or subcode by LBA, handling track padding and + stored or unstored pregaps (#155). +- Embedded cue sheets: a CD CHD may carry its cue sheet as `CUES` + metadata (`CDROM_CUESHEET_METADATA_TAG`), which keeps the INDEX + 02+, CATALOG and ISRC entries CHDv5 track metadata drops. + `chd_cd_open` reads it into the TOC and `chd_cd_get_index` returns + any INDEX by track (#164). ### Changed @@ -64,6 +73,10 @@ instead of a dated snapshot. - `fseek` errors are now propagated as `CHDERR_READ_ERROR`. - Only reads as much header data as the declared header length. - Various memory and overflow bugs in hunk decoding (#132). +- CD track metadata gains bounded `CDROM_TRACK_METADATA_SCANF`, + `CDROM_TRACK_METADATA2_SCANF` and `GDROM_TRACK_METADATA_SCANF` + formats for `sscanf`, with `CD_METADATA_STRING_SIZE`; the + unbounded `*_FORMAT` macros overflow on crafted metadata (#165). ### Removed diff --git a/CMakeLists.txt b/CMakeLists.txt index 7c3ae2e..2bb3944 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -216,6 +216,7 @@ endif() set(CHDR_SOURCES src/libchdr_bitstream.c src/libchdr_cdrom.c + src/libchdr_cdrom_toc.c src/libchdr_chd.c src/libchdr_codec_avhuff.c src/libchdr_codec_cdfl.c diff --git a/README.md b/README.md index 940920a..6d20195 100644 --- a/README.md +++ b/README.md @@ -4,4 +4,14 @@ libchdr is a standalone library for reading MAME's CHDv1-v5 formats. The code is based off of MAME's old C codebase which read up to CHDv4 with OS-dependent features removed, and CHDv5 support backported from MAME's current C++ codebase. +## Embedded cue sheets + +CHDv5 track metadata has no room for INDEX 02 and later, CATALOG or ISRC, which some Saturn and Dreamcast titles rely on. libchdr reads the original cue sheet when it is stored in the CHD as `CUES` metadata, and exposes those entries through `chd_cd_get_toc()` and `chd_cd_get_index()` (see `include/libchdr/cdrom.h`). `chdman addmeta` writes only to uncompressed CHDs, so add the cue sheet before compressing: + + chdman createcd -c none -i game.cue -o tmp.chd + chdman addmeta -i tmp.chd --tag CUES --valuefile game.cue + chdman copy -i tmp.chd -o game.chd + +Other readers ignore the tag, so the result is still an ordinary CHDv5 file. + libchdr is licensed under the BSD 3-Clause (see [LICENSE.txt](LICENSE.txt)) and uses third party libraries that are each distributed under their own terms (see each library's license in [deps/](deps/)). diff --git a/include/libchdr/cdrom.h b/include/libchdr/cdrom.h index 680aa39..0dcf211 100644 --- a/include/libchdr/cdrom.h +++ b/include/libchdr/cdrom.h @@ -57,6 +57,88 @@ enum #define CD_FLAG_GDROM 0x00000001 /* disc is a GD-ROM, all tracks should be stored with GD-ROM metadata */ #define CD_FLAG_GDROMLE 0x00000002 /* legacy GD-ROM, with little-endian CDDA data */ +/*************************************************************************** + SECTOR ACCESS BY LBA + + A CD CHD stores tracks back to back as 2448-byte frames (2352 sector + bytes, 96 subcode bytes), each track padded to CD_TRACK_PADDING frames, + and the layout lives in per-track metadata. chd_cd_open() parses that + metadata into a TOC and chd_cd_read_sector() reads by LBA, so callers no + longer redo the hunk and padding arithmetic themselves (#155). + + LBAs follow MAME's logical addressing: LBA 0 is the start of track 1, + and pregaps and postgaps take up LBAs whether or not their sectors are + stored. Use msf_to_lba() / lba_to_msf() below to address by MSF. +***************************************************************************/ + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct _chd_cd_track chd_cd_track; +struct _chd_cd_track +{ + uint32_t number; /* track number, 1-based */ + uint32_t type; /* CD_TRACK_* */ + uint32_t subtype; /* CD_SUB_* */ + uint32_t datasize; /* sector bytes stored per frame */ + uint32_t subsize; /* subcode bytes stored per frame */ + uint32_t frames; /* frames stored, pregap included when pgdatasize != 0 */ + uint32_t pregap; /* pregap frames, INDEX 00 to INDEX 01 */ + uint32_t pgdatasize; /* non-zero when the pregap is stored in the CHD */ + uint32_t postgap; /* postgap frames, never stored */ + uint32_t logframeofs; /* LBA of INDEX 01 */ + uint32_t chdframeofs; /* first frame of the track within the CHD */ + char isrc[13]; /* from an embedded cue sheet, "" if none */ +}; + +typedef struct _chd_cd_toc chd_cd_toc; +struct _chd_cd_toc +{ + uint32_t numtracks; + uint32_t flags; /* CD_FLAG_* */ + uint32_t leadout; /* first LBA past the last track */ + char catalog[14]; /* from an embedded cue sheet, "" if none */ + chd_cd_track tracks[CD_MAX_TRACKS]; +}; + +/* what chd_cd_read_sector() returns, and how many bytes it writes */ +enum +{ + CHD_CD_READ_DATA = 0, /* 2048 bytes of user data; data tracks only */ + CHD_CD_READ_RAW, /* CD_MAX_SECTOR_DATA bytes as a .bin would hold them: + * audio little-endian, a cooked track's datasize + * bytes followed by zeros */ + CHD_CD_READ_SUBCODE /* CD_MAX_SUBCODE_DATA bytes, zeros if none stored */ +}; + +typedef struct _chd_cd chd_cd; + +/* Parse the track metadata of an open CD CHD. The handle borrows `chd`, + * which must outlive it. CHDERR_INVALID_METADATA when the track metadata is + * missing or inconsistent. */ +CHD_EXPORT chd_error chd_cd_open(chd_file *chd, chd_cd **cd); +CHD_EXPORT void chd_cd_close(chd_cd *cd); +CHD_EXPORT const chd_cd_toc *chd_cd_get_toc(const chd_cd *cd); + +/* Read one sector. Sectors of a pregap or postgap that the CHD does not + * store read as zeros. The last decoded hunk is kept, so reading the frames + * of a hunk in a row decodes it once. CHDERR_HUNK_OUT_OF_RANGE past the + * leadout; CHDERR_INVALID_PARAMETER for CHD_CD_READ_DATA on an audio or + * Mode 2 Form 2 track. */ +CHD_EXPORT chd_error chd_cd_read_sector(chd_cd *cd, uint32_t lba, void *buffer, uint32_t what); + +/* LBA of INDEX `index` (0-99) of track `track` (1-based). INDEX 01 is always + * known, INDEX 00 when the track has a pregap, and any other INDEX when an + * embedded cue sheet (CDROM_CUESHEET_METADATA_TAG) lists it; otherwise + * CHDERR_METADATA_NOT_FOUND. A cue sheet whose tracks do not match the + * CHD's is ignored as a whole, catalog and ISRCs included. */ +CHD_EXPORT chd_error chd_cd_get_index(const chd_cd *cd, uint32_t track, uint32_t index, uint32_t *lba); + +#ifdef __cplusplus +} +#endif + /*************************************************************************** FUNCTION PROTOTYPES ***************************************************************************/ diff --git a/include/libchdr/chd.h b/include/libchdr/chd.h index f07c374..161f391 100644 --- a/include/libchdr/chd.h +++ b/include/libchdr/chd.h @@ -248,6 +248,24 @@ extern "C" { #define GDROM_TRACK_METADATA_TAG CHD_MAKE_TAG('C', 'H', 'G', 'D') #define GDROM_TRACK_METADATA_FORMAT "TRACK:%d TYPE:%s SUBTYPE:%s FRAMES:%d PAD:%d PREGAP:%d PGTYPE:%s PGSUB:%s POSTGAP:%d" +/* The cue sheet a CD CHD was made from, as plain text. A libchdr extension, + * not written by chdman createcd: CHDv5 track metadata has no room for + * INDEX 02+, CATALOG or ISRC, and the cue sheet keeps them (#164). Add it to + * an uncompressed CHD, then compress - chdman addmeta cannot write to a + * compressed one: + * chdman createcd -c none -i game.cue -o tmp.chd + * chdman addmeta -i tmp.chd --tag CUES --valuefile game.cue + * chdman copy -i tmp.chd -o game.chd */ +#define CDROM_CUESHEET_METADATA_TAG CHD_MAKE_TAG('C','U','E','S') +/* Bounded variants of the three formats above, for sscanf(). The %s fields + * would overflow on a crafted CHD; every string target here must be + * char[CD_METADATA_STRING_SIZE]. The *_FORMAT macros stay unbounded on + * purpose: in printf a width pads rather than limits (#165). */ +#define CD_METADATA_STRING_SIZE 16 +#define CDROM_TRACK_METADATA_SCANF "TRACK:%d TYPE:%15s SUBTYPE:%15s FRAMES:%d" +#define CDROM_TRACK_METADATA2_SCANF "TRACK:%d TYPE:%15s SUBTYPE:%15s FRAMES:%d PREGAP:%d PGTYPE:%15s PGSUB:%15s POSTGAP:%d" +#define GDROM_TRACK_METADATA_SCANF "TRACK:%d TYPE:%15s SUBTYPE:%15s FRAMES:%d PAD:%d PREGAP:%d PGTYPE:%15s PGSUB:%15s POSTGAP:%d" + /* standard A/V metadata */ #define AV_METADATA_TAG CHD_MAKE_TAG('A','V','A','V') #define AV_METADATA_FORMAT "FPS:%d.%06d WIDTH:%d HEIGHT:%d INTERLACED:%d CHANNELS:%d SAMPLERATE:%d" diff --git a/src/libchdr_cdrom_toc.c b/src/libchdr_cdrom_toc.c new file mode 100644 index 0000000..a81dd84 --- /dev/null +++ b/src/libchdr_cdrom_toc.c @@ -0,0 +1,479 @@ +/* license:BSD-3-Clause + * copyright-holders:Aaron Giles, Romain Tisserand + * + * CD sector access by LBA: the track metadata parsing and frame offset + * arithmetic of MAME's cdrom_file (src/lib/util/cdrom.cpp), in C. + */ + +#include +#include +#include + +#include "../include/libchdr/cdrom.h" + +/* one INDEX line of an embedded cue sheet */ +struct cue_index +{ + uint8_t track; + uint8_t index; + int32_t ofs; /* frames from the track's INDEX 01 */ +}; + +struct _chd_cd +{ + chd_file * chd; + chd_cd_toc toc; + uint32_t framesperhunk; + uint32_t cachedhunk; /* hunk held in `hunk`, ~0 = none */ + uint8_t * hunk; + struct cue_index *indices; /* NULL without an embedded cue sheet */ + uint32_t numindices; +}; + +/* a cue sheet is text a few hundred bytes long; anything far larger is not + * one */ +#define CUESHEET_MAX_BYTES 65536 +/* the shortest INDEX line, "INDEX 01 00:00:00", is 17 bytes */ +#define CUESHEET_MAX_INDICES(len) ((len) / 17 + 1) + +static const struct +{ + const char *name; + uint32_t type; + uint32_t datasize; +} track_types[] = +{ + { "MODE1", CD_TRACK_MODE1, 2048 }, + { "MODE1/2048", CD_TRACK_MODE1, 2048 }, + { "MODE1_RAW", CD_TRACK_MODE1_RAW, 2352 }, + { "MODE1/2352", CD_TRACK_MODE1_RAW, 2352 }, + { "MODE2", CD_TRACK_MODE2, 2336 }, + { "MODE2/2336", CD_TRACK_MODE2, 2336 }, + { "MODE2_FORM1", CD_TRACK_MODE2_FORM1, 2048 }, + { "MODE2/2048", CD_TRACK_MODE2_FORM1, 2048 }, + { "MODE2_FORM2", CD_TRACK_MODE2_FORM2, 2324 }, + { "MODE2/2324", CD_TRACK_MODE2_FORM2, 2324 }, + { "MODE2_FORM_MIX", CD_TRACK_MODE2_FORM_MIX, 2336 }, + { "MODE2_RAW", CD_TRACK_MODE2_RAW, 2352 }, + { "MODE2/2352", CD_TRACK_MODE2_RAW, 2352 }, + { "CDI/2352", CD_TRACK_MODE2_RAW, 2352 }, + { "AUDIO", CD_TRACK_AUDIO, 2352 }, + { "CDG", CD_TRACK_AUDIO, 2352 } +}; + +/* 0 datasize = unknown type */ +static void type_info(const char *name, uint32_t *type, uint32_t *datasize) +{ + size_t i; + *type = CD_TRACK_MODE1; + *datasize = 0; + for (i = 0; i < sizeof(track_types) / sizeof(track_types[0]); i++) + if (strcmp(name, track_types[i].name) == 0) + { + *type = track_types[i].type; + *datasize = track_types[i].datasize; + return; + } +} + +static void subtype_info(const char *name, uint32_t *subtype, uint32_t *subsize) +{ + *subtype = CD_SUB_NONE; + *subsize = 0; + if (strcmp(name, "RW") == 0) + *subtype = CD_SUB_NORMAL; + else if (strcmp(name, "RW_RAW") == 0) + *subtype = CD_SUB_RAW; + if (*subtype != CD_SUB_NONE) + *subsize = CD_MAX_SUBCODE_DATA; +} + +/* NUL-terminated metadata entry; CHDERR_METADATA_NOT_FOUND past the last */ +static chd_error get_text_metadata(chd_file *chd, uint32_t tag, uint32_t index, char *out, uint32_t outlen) +{ + uint32_t len = 0; + chd_error err = chd_get_metadata(chd, tag, index, out, outlen - 1, &len, NULL, NULL); + if (err == CHDERR_NONE) + out[len < outlen - 1 ? len : outlen - 1] = 0; + return err; +} + +static chd_error parse_tracks(chd_file *chd, chd_cd_toc *toc) +{ + char meta[256]; + uint32_t i; + + for (i = 0; i < CD_MAX_TRACKS; i++) + { + chd_cd_track *track = &toc->tracks[i]; + char type[CD_METADATA_STRING_SIZE], subtype[CD_METADATA_STRING_SIZE]; + char pgtype[CD_METADATA_STRING_SIZE], pgsub[CD_METADATA_STRING_SIZE]; + int tracknum = -1, frames = 0, pregap = 0, postgap = 0, pad = 0; + uint32_t pgtrktype; + chd_error err; + + type[0] = subtype[0] = pgtype[0] = pgsub[0] = 0; + + err = get_text_metadata(chd, CDROM_TRACK_METADATA_TAG, i, meta, sizeof(meta)); + if (err == CHDERR_NONE) + { + if (sscanf(meta, CDROM_TRACK_METADATA_SCANF, &tracknum, type, subtype, &frames) != 4) + return CHDERR_INVALID_METADATA; + } + else if (err == CHDERR_METADATA_NOT_FOUND + && (err = get_text_metadata(chd, CDROM_TRACK_METADATA2_TAG, i, meta, sizeof(meta))) == CHDERR_NONE) + { + if (sscanf(meta, CDROM_TRACK_METADATA2_SCANF, &tracknum, type, subtype, &frames, + &pregap, pgtype, pgsub, &postgap) != 8) + return CHDERR_INVALID_METADATA; + } + else if (err == CHDERR_METADATA_NOT_FOUND) + { + err = get_text_metadata(chd, GDROM_OLD_METADATA_TAG, i, meta, sizeof(meta)); + if (err == CHDERR_NONE) + toc->flags |= CD_FLAG_GDROMLE; + else if (err == CHDERR_METADATA_NOT_FOUND) + err = get_text_metadata(chd, GDROM_TRACK_METADATA_TAG, i, meta, sizeof(meta)); + if (err == CHDERR_METADATA_NOT_FOUND) + break; + if (err != CHDERR_NONE) + return err; + if (sscanf(meta, GDROM_TRACK_METADATA_SCANF, &tracknum, type, subtype, &frames, + &pad, &pregap, pgtype, pgsub, &postgap) != 9) + return CHDERR_INVALID_METADATA; + toc->flags |= CD_FLAG_GDROM; + } + if (err != CHDERR_NONE) + return err; + + /* chdman writes tracks in order; anything else is not a layout we + * can place frames for */ + if (tracknum != (int)i + 1 || frames < 0 || pregap < 0 || postgap < 0) + return CHDERR_INVALID_METADATA; + + track->number = tracknum; + type_info(type, &track->type, &track->datasize); + if (track->datasize == 0) + return CHDERR_INVALID_METADATA; + subtype_info(subtype, &track->subtype, &track->subsize); + track->frames = frames; + track->pregap = pregap; + track->postgap = postgap; + track->pgdatasize = 0; + /* a 'V' pregap type means its sectors are stored in the CHD */ + if (pregap > 0 && pgtype[0] == 'V') + type_info(pgtype + 1, &pgtrktype, &track->pgdatasize); + if (track->pgdatasize != 0 && track->pregap > track->frames) + return CHDERR_INVALID_METADATA; + } + + /* shortcut: the pre-v3 binary CHCD layout and multi-session CHSS tags are + * not read; add them if an image that needs them turns up */ + toc->numtracks = i; + return i > 0 ? CHDERR_NONE : CHDERR_INVALID_METADATA; +} + +/* MAME's cdrom_file constructor: CHD frames are padded per track, logical + * LBAs skip pregaps that are not stored and count postgaps */ +static chd_error compute_offsets(chd_cd_toc *toc) +{ + uint64_t chdofs = 0, logofs = 0; + uint32_t i; + + for (i = 0; i < toc->numtracks; i++) + { + chd_cd_track *track = &toc->tracks[i]; + if (track->pgdatasize == 0) + logofs += track->pregap; + track->logframeofs = (uint32_t)logofs + (track->pgdatasize != 0 ? track->pregap : 0); + track->chdframeofs = (uint32_t)chdofs; + logofs += (uint64_t)track->frames + track->postgap; + chdofs += ((uint64_t)track->frames + CD_TRACK_PADDING - 1) / CD_TRACK_PADDING * CD_TRACK_PADDING; + if (logofs > UINT32_MAX || chdofs > UINT32_MAX) + return CHDERR_INVALID_METADATA; + } + toc->leadout = (uint32_t)logofs; + return CHDERR_NONE; +} + +/* Indices are kept relative to their track's INDEX 01, so they land on the + * CHD's own track starts whatever the cue's FILE layout: one BIN, or one per + * track as Redump has it. Returns 0 if the cue sheet is unusable. */ +static int parse_cuesheet_text(chd_cd *cd, char *text, uint32_t maxindices) +{ + chd_cd_toc *toc = &cd->toc; + uint32_t track = 0, first = 0, n = 0, i; + int32_t index1 = -1; + int file_since_index = 0, seen_index = 0; + char *line = text; + + while (line != NULL) + { + char *next = strchr(line, '\n'); + char keyword[16]; + unsigned num, m, s, f; + int used = 0; + + if (next != NULL) + *next++ = 0; + if (sscanf(line, " %15s %n", keyword, &used) != 1) + { + line = next; + continue; + } + line += used; + + if (strcmp(keyword, "CATALOG") == 0) + sscanf(line, "%13s", toc->catalog); + else if (strcmp(keyword, "ISRC") == 0 && track > 0) + sscanf(line, "%12s", toc->tracks[track - 1].isrc); + else if (strcmp(keyword, "FILE") == 0) + file_since_index = seen_index; + else if (strcmp(keyword, "TRACK") == 0) + { + if (sscanf(line, "%u", &num) != 1 || num != track + 1 || num > toc->numtracks + || (track > 0 && index1 < 0)) + return 0; + for (i = first; i < n; i++) + cd->indices[i].ofs -= index1; + track = num; + first = n; + index1 = -1; + file_since_index = seen_index = 0; + } + else if (strcmp(keyword, "INDEX") == 0) + { + /* a FILE between two indices of one track puts them in + * different files, and their distance is unknown */ + if (track == 0 || file_since_index || n == maxindices + || sscanf(line, "%u %u:%u:%u", &num, &m, &s, &f) != 4 + || num > 99 || m > 99 || s > 59 || f > 74) + return 0; + cd->indices[n].track = (uint8_t)track; + cd->indices[n].index = (uint8_t)num; + cd->indices[n].ofs = (int32_t)((m * 60 + s) * 75 + f); + if (num == 1) + index1 = cd->indices[n].ofs; + n++; + seen_index = 1; + } + line = next; + } + + if (track != toc->numtracks || index1 < 0) + return 0; + for (i = first; i < n; i++) + cd->indices[i].ofs -= index1; + cd->numindices = n; + return 1; +} + +/* Optional: a missing or unusable cue sheet leaves the TOC as the track + * metadata describes it. */ +static void parse_cuesheet(chd_cd *cd) +{ + uint32_t len = 0, t; + char dummy, *text; + + if (chd_get_metadata(cd->chd, CDROM_CUESHEET_METADATA_TAG, 0, &dummy, 0, &len, NULL, NULL) != CHDERR_NONE + || len == 0 || len > CUESHEET_MAX_BYTES) + return; + text = (char *)malloc(len + 1); + cd->indices = (struct cue_index *)malloc(CUESHEET_MAX_INDICES(len) * sizeof(*cd->indices)); + if (text != NULL && cd->indices != NULL + && chd_get_metadata(cd->chd, CDROM_CUESHEET_METADATA_TAG, 0, text, len, NULL, NULL, NULL) == CHDERR_NONE) + { + text[len] = 0; + if (parse_cuesheet_text(cd, text, CUESHEET_MAX_INDICES(len))) + { + free(text); + return; + } + } + free(text); + free(cd->indices); + cd->indices = NULL; + cd->numindices = 0; + cd->toc.catalog[0] = 0; + for (t = 0; t < cd->toc.numtracks; t++) + cd->toc.tracks[t].isrc[0] = 0; +} + +CHD_EXPORT chd_error chd_cd_open(chd_file *chd, chd_cd **cd) +{ + const chd_header *header; + chd_cd *result; + chd_error err; + + if (chd == NULL || cd == NULL) + return CHDERR_INVALID_PARAMETER; + *cd = NULL; + + header = chd_get_header(chd); + if (header->hunkbytes == 0 || header->hunkbytes % CD_FRAME_SIZE != 0) + return CHDERR_INVALID_FILE; + + result = (chd_cd *)calloc(1, sizeof(*result)); + if (result == NULL) + return CHDERR_OUT_OF_MEMORY; + result->chd = chd; + result->framesperhunk = header->hunkbytes / CD_FRAME_SIZE; + result->cachedhunk = ~0u; + + err = parse_tracks(chd, &result->toc); + if (err == CHDERR_NONE) + err = compute_offsets(&result->toc); + if (err == CHDERR_NONE) + parse_cuesheet(result); + if (err == CHDERR_NONE) + { + result->hunk = (uint8_t *)malloc(header->hunkbytes); + if (result->hunk == NULL) + err = CHDERR_OUT_OF_MEMORY; + } + if (err != CHDERR_NONE) + { + chd_cd_close(result); + return err; + } + *cd = result; + return CHDERR_NONE; +} + +CHD_EXPORT void chd_cd_close(chd_cd *cd) +{ + if (cd == NULL) + return; + free(cd->hunk); + free(cd->indices); + free(cd); +} + +CHD_EXPORT const chd_cd_toc *chd_cd_get_toc(const chd_cd *cd) +{ + return cd != NULL ? &cd->toc : NULL; +} + +CHD_EXPORT chd_error chd_cd_get_index(const chd_cd *cd, uint32_t track, uint32_t index, uint32_t *lba) +{ + const chd_cd_track *t; + uint32_t i; + + if (cd == NULL || lba == NULL || track == 0 || track > cd->toc.numtracks || index > 99) + return CHDERR_INVALID_PARAMETER; + t = &cd->toc.tracks[track - 1]; + + for (i = 0; i < cd->numindices; i++) + if (cd->indices[i].track == track && cd->indices[i].index == index) + { + int64_t value = (int64_t)t->logframeofs + cd->indices[i].ofs; + if (value < 0 || value > UINT32_MAX) + return CHDERR_INVALID_METADATA; + *lba = (uint32_t)value; + return CHDERR_NONE; + } + + if (index == 1) + *lba = t->logframeofs; + else if (index == 0 && t->pregap > 0) + *lba = t->logframeofs - t->pregap; + else + return CHDERR_METADATA_NOT_FOUND; + return CHDERR_NONE; +} + +/* where the 2048 user data bytes start in a stored sector, -1 = none */ +static int user_data_offset(uint32_t type) +{ + switch (type) + { + case CD_TRACK_MODE1: return 0; + case CD_TRACK_MODE1_RAW: return 16; + case CD_TRACK_MODE2: return 8; + case CD_TRACK_MODE2_FORM1: return 0; + case CD_TRACK_MODE2_FORM_MIX: return 8; + case CD_TRACK_MODE2_RAW: return 24; + default: return -1; + } +} + +CHD_EXPORT chd_error chd_cd_read_sector(chd_cd *cd, uint32_t lba, void *buffer, uint32_t what) +{ + static const uint32_t sizes[] = { 2048, CD_MAX_SECTOR_DATA, CD_MAX_SUBCODE_DATA }; + const chd_cd_track *track; + uint32_t t, offset, frame, hunknum; + const uint8_t *src; + int dataofs = 0; + + if (cd == NULL || buffer == NULL || what > CHD_CD_READ_SUBCODE) + return CHDERR_INVALID_PARAMETER; + if (lba >= cd->toc.leadout) + return CHDERR_HUNK_OUT_OF_RANGE; + + /* the track whose INDEX 00 is the last one at or before lba */ + for (t = cd->toc.numtracks - 1; t > 0; t--) + if (lba >= cd->toc.tracks[t].logframeofs - cd->toc.tracks[t].pregap) + break; + track = &cd->toc.tracks[t]; + + if (what == CHD_CD_READ_DATA && (dataofs = user_data_offset(track->type)) < 0) + return CHDERR_INVALID_PARAMETER; + + /* frame within the stored track; an unstored pregap or the postgap + * reads as silence */ + offset = lba - (track->logframeofs - track->pregap); + if (track->pgdatasize == 0 && offset < track->pregap) + { + memset(buffer, 0, sizes[what]); + return CHDERR_NONE; + } + frame = (track->pgdatasize == 0) ? offset - track->pregap : offset; + if (frame >= track->frames) + { + memset(buffer, 0, sizes[what]); + return CHDERR_NONE; + } + + frame += track->chdframeofs; + hunknum = frame / cd->framesperhunk; + if (hunknum != cd->cachedhunk) + { + chd_error err = chd_read(cd->chd, hunknum, cd->hunk); + cd->cachedhunk = (err == CHDERR_NONE) ? hunknum : ~0u; + if (err != CHDERR_NONE) + return err; + } + src = cd->hunk + (frame % cd->framesperhunk) * CD_FRAME_SIZE; + + switch (what) + { + case CHD_CD_READ_DATA: + memcpy(buffer, src + dataofs, 2048); + break; + + case CHD_CD_READ_RAW: + memcpy(buffer, src, track->datasize); + memset((uint8_t *)buffer + track->datasize, 0, CD_MAX_SECTOR_DATA - track->datasize); + /* CHDs hold CDDA big-endian, except legacy GD-ROMs */ + if (track->type == CD_TRACK_AUDIO && !(cd->toc.flags & CD_FLAG_GDROMLE)) + { + uint8_t *p = (uint8_t *)buffer; + uint32_t i; + for (i = 0; i < CD_MAX_SECTOR_DATA; i += 2) + { + uint8_t tmp = p[i]; + p[i] = p[i + 1]; + p[i + 1] = tmp; + } + } + break; + + case CHD_CD_READ_SUBCODE: + if (track->subsize != 0) + memcpy(buffer, src + CD_MAX_SECTOR_DATA, CD_MAX_SUBCODE_DATA); + else + memset(buffer, 0, CD_MAX_SUBCODE_DATA); + break; + } + return CHDERR_NONE; +} diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index ae2c0f8..67e6289 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -68,6 +68,20 @@ target_link_libraries(chdr-open-ownership PRIVATE chdr-static) chdr_test_defines(chdr-open-ownership) add_test(NAME open-ownership COMMAND chdr-open-ownership) +# The CD track metadata *_SCANF formats bound every string field (#165). +add_executable(chdr-metadata-scanf metadata_scanf.c) +target_link_libraries(chdr-metadata-scanf PRIVATE chdr-static) +chdr_test_defines(chdr-metadata-scanf) +add_test(NAME metadata-scanf COMMAND chdr-metadata-scanf) + +# Sector reads by LBA over a multi-track CD (#155). Its own directory, as the +# fixture keeps the BIN it was built from to compare against. +add_executable(chdr-cd-toc cd_toc.c) +target_link_libraries(chdr-cd-toc PRIVATE chdr-static) +chdr_test_defines(chdr-cd-toc) +add_test(NAME cd-toc + COMMAND chdr-cd-toc "${CMAKE_CURRENT_SOURCE_DIR}/corpus/cd") + # CHDs with a parent: seeds/ has none, and cannot (a child needs its parent, and # the workflows there open every file standalone), so COMPRESSION_PARENT would # otherwise go untested - including through the in-place CD spread, where a diff --git a/tests/cd_toc.c b/tests/cd_toc.c new file mode 100644 index 0000000..29f88f5 --- /dev/null +++ b/tests/cd_toc.c @@ -0,0 +1,179 @@ +/* license:BSD-3-Clause + * copyright-holders:Romain Tisserand + * + * chd_cd_open() / chd_cd_read_sector() against the three-track CD that + * tests/corpus/generate.sh builds (#155). Every LBA is read back and compared + * with the bytes its cue sheet puts there, so the pregap that is stored, the + * one that is not, and the per-track frame padding are all crossed. + * + * cuesheet.chd adds the cue sheet as CUES metadata (#164): its CATALOG, ISRC + * and INDEX 02 must come through, and cuesheet_bad.chd's mismatched cue must + * be ignored as a whole. + * + * Skips when the corpus is absent, as the other corpus tests do. + */ +#include +#include +#include + +#include +#include + +#define BIN_FRAMES 776 + +static int failures; + +static void check(int ok, const char *what, long value) +{ + if (!ok) + { + fprintf(stderr, "FAIL: %s (%ld)\n", what, value); + failures++; + } +} + +/* the .bin sector the cue sheet places at lba, -1 for an unstored pregap */ +static long bin_sector(uint32_t lba) +{ + if (lba < 675) + return lba; + if (lba < 825) + return -1; + return lba - 150; +} + +static chd_cd *open_cd(const char *dir, const char *name, chd_file **chd) +{ + char path[1024]; + chd_cd *cd = NULL; + + snprintf(path, sizeof(path), "%s/%s", dir, name); + if (chd_open(path, CHD_OPEN_READ, NULL, chd) != CHDERR_NONE) + { + check(0, name, 0); + return NULL; + } + check(chd_cd_open(*chd, &cd) == CHDERR_NONE, "chd_cd_open with a cue sheet", 0); + return cd; +} + +static void check_cuesheet(const char *dir) +{ + chd_file *chd = NULL; + chd_cd *cd; + uint32_t lba = 0; + + if ((cd = open_cd(dir, "cuesheet.chd", &chd)) != NULL) + { + const chd_cd_toc *toc = chd_cd_get_toc(cd); + check(strcmp(toc->catalog, "0123456789012") == 0, "catalog", 0); + check(toc->tracks[0].isrc[0] == 0 && strcmp(toc->tracks[1].isrc, "USRC17607839") == 0, "isrc", 0); + check(chd_cd_get_index(cd, 2, 2, &lba) == CHDERR_NONE && lba == 525, "track 2 INDEX 02", (long)lba); + check(chd_cd_get_index(cd, 2, 0, &lba) == CHDERR_NONE && lba == 300, "track 2 INDEX 00", (long)lba); + check(chd_cd_get_index(cd, 3, 1, &lba) == CHDERR_NONE && lba == 825, "track 3 INDEX 01", (long)lba); + check(chd_cd_get_index(cd, 3, 0, &lba) == CHDERR_NONE && lba == 675, "track 3 unstored INDEX 00", (long)lba); + check(chd_cd_get_index(cd, 1, 2, &lba) == CHDERR_METADATA_NOT_FOUND, "track 1 INDEX 02", 0); + check(chd_cd_get_index(cd, 4, 1, &lba) == CHDERR_INVALID_PARAMETER, "track past the last", 0); + chd_cd_close(cd); + } + if (chd != NULL) + chd_close(chd); + + chd = NULL; + if ((cd = open_cd(dir, "cuesheet_bad.chd", &chd)) != NULL) + { + const chd_cd_toc *toc = chd_cd_get_toc(cd); + check(toc->catalog[0] == 0 && toc->tracks[1].isrc[0] == 0, "mismatched cue ignored", 0); + check(chd_cd_get_index(cd, 2, 2, &lba) == CHDERR_METADATA_NOT_FOUND, "mismatched cue INDEX 02", 0); + check(chd_cd_get_index(cd, 2, 1, &lba) == CHDERR_NONE && lba == 450, "metadata INDEX 01 still known", (long)lba); + chd_cd_close(cd); + } + if (chd != NULL) + chd_close(chd); +} + +int main(int argc, char **argv) +{ + const char *dir = (argc > 1) ? argv[1] : "tests/corpus/cd"; + char path[1024]; + unsigned char *bin, sector[CD_MAX_SECTOR_DATA], zeros[CD_MAX_SECTOR_DATA]; + const chd_cd_toc *toc; + chd_file *chd = NULL; + chd_cd *cd = NULL; + chd_error err; + uint32_t lba; + FILE *f; + + snprintf(path, sizeof(path), "%s/multitrack.bin", dir); + f = fopen(path, "rb"); + if (f == NULL) + { + printf("multi-track CD not generated (%s) - skipping\n", path); + printf("run tests/corpus/generate.sh to build it\n"); + return 0; + } + bin = (unsigned char *)malloc((size_t)BIN_FRAMES * CD_MAX_SECTOR_DATA); + if (bin == NULL || fread(bin, CD_MAX_SECTOR_DATA, BIN_FRAMES, f) != BIN_FRAMES) + { + fprintf(stderr, "short read on %s\n", path); + return 1; + } + fclose(f); + + snprintf(path, sizeof(path), "%s/multitrack.chd", dir); + err = chd_open(path, CHD_OPEN_READ, NULL, &chd); + if (err != CHDERR_NONE) + { + fprintf(stderr, "open %s: %s\n", path, chd_error_string(err)); + return 1; + } + err = chd_cd_open(chd, &cd); + if (err != CHDERR_NONE) + { + fprintf(stderr, "chd_cd_open: %s\n", chd_error_string(err)); + return 1; + } + + toc = chd_cd_get_toc(cd); + check(toc->numtracks == 3, "numtracks", toc->numtracks); + check(toc->leadout == 926, "leadout", toc->leadout); + if (toc->numtracks == 3) + { + check(toc->tracks[0].type == CD_TRACK_MODE1_RAW && toc->tracks[0].frames == 300, "track 1 type/frames", toc->tracks[0].frames); + check(toc->tracks[0].logframeofs == 0 && toc->tracks[0].chdframeofs == 0, "track 1 offsets", toc->tracks[0].logframeofs); + check(toc->tracks[1].type == CD_TRACK_AUDIO && toc->tracks[1].frames == 375, "track 2 type/frames", toc->tracks[1].frames); + check(toc->tracks[1].pregap == 150 && toc->tracks[1].pgdatasize != 0, "track 2 stored pregap", toc->tracks[1].pregap); + check(toc->tracks[1].logframeofs == 450 && toc->tracks[1].chdframeofs == 300, "track 2 offsets", toc->tracks[1].logframeofs); + check(toc->tracks[2].frames == 101 && toc->tracks[2].pregap == 150 && toc->tracks[2].pgdatasize == 0, "track 3 unstored pregap", toc->tracks[2].frames); + check(toc->tracks[2].logframeofs == 825 && toc->tracks[2].chdframeofs == 676, "track 3 offsets (padding)", toc->tracks[2].chdframeofs); + } + + memset(zeros, 0, sizeof(zeros)); + for (lba = 0; lba < 926; lba++) + { + long s = bin_sector(lba); + const unsigned char *want = (s < 0) ? zeros : bin + (size_t)s * CD_MAX_SECTOR_DATA; + + err = chd_cd_read_sector(cd, lba, sector, CHD_CD_READ_RAW); + check(err == CHDERR_NONE && memcmp(sector, want, CD_MAX_SECTOR_DATA) == 0, "raw sector matches bin", (long)lba); + + err = chd_cd_read_sector(cd, lba, sector, CHD_CD_READ_DATA); + if (lba < 300) + check(err == CHDERR_NONE && memcmp(sector, want + 16, 2048) == 0, "mode 1 user data", (long)lba); + else + check(err == CHDERR_INVALID_PARAMETER, "user data refused on audio", (long)lba); + } + + check(chd_cd_read_sector(cd, 926, sector, CHD_CD_READ_RAW) == CHDERR_HUNK_OUT_OF_RANGE, "read past leadout", 926); + check(chd_cd_read_sector(cd, 0, sector, CHD_CD_READ_SUBCODE) == CHDERR_NONE && memcmp(sector, zeros, CD_MAX_SUBCODE_DATA) == 0, "no subcode reads as zeros", 0); + + check(toc->catalog[0] == 0, "no cue sheet, no catalog", 0); + chd_cd_close(cd); + chd_close(chd); + free(bin); + + check_cuesheet(dir); + if (failures == 0) + printf("cd toc: ok\n"); + return failures ? 1 : 0; +} diff --git a/tests/corpus/generate.sh b/tests/corpus/generate.sh index f2d83b6..792b69c 100755 --- a/tests/corpus/generate.sh +++ b/tests/corpus/generate.sh @@ -143,6 +143,62 @@ if [ -f "$PARENT/base.chd" ]; then fi fi +# ---- multi-track CD for tests/cd_toc.c -------------------------------------- +# +# One BIN, three tracks, each a different way of placing a track in a CHD: +# +# 01 MODE1/2352, 300 frames - a multiple of CD_TRACK_PADDING +# 02 AUDIO, INDEX 00 150 frames before INDEX 01: a pregap stored in the +# file (PGTYPE:VAUDIO), 375 frames in all, so padded by one +# 03 AUDIO, PREGAP 00:02:00: 150 frames of pregap that are not stored, +# then 101 frames, padded by three +# +# The BIN is kept next to the CHD: the test reads every LBA back and compares +# it with the bytes the cue sheet puts there. Outside seeds/ because it is +# not a CHD, and the workflows walking seeds/ open every file there. +CD="$(cd "$(dirname "$0")" && pwd)/cd" +mkdir -p "$CD" +dd if=/dev/urandom of="$CD/multitrack.bin" bs=2352 count=776 status=none +cat > "$CD/multitrack.cue" </dev/null 2>&1 || true + +# The same disc with its cue sheet embedded as CUES metadata, carrying what +# track metadata cannot: CATALOG, ISRC and an INDEX 02. addmeta only writes +# to an uncompressed CHD, hence the copy. cuesheet_bad.chd embeds a cue that +# lists two tracks for a three-track disc, which must be ignored. +cat > "$CD/cuesheet.cue" < "$TMP/bad.cue" +embed_cue () { + chdman createcd -f -c none -i "$CD/cuesheet.cue" -o "$TMP/cue.chd" >/dev/null 2>&1 && + chdman addmeta -i "$TMP/cue.chd" --tag CUES --valuefile "$1" >/dev/null 2>&1 && + chdman copy -f -i "$TMP/cue.chd" -o "$2" >/dev/null 2>&1 || true +} +embed_cue "$CD/cuesheet.cue" "$CD/cuesheet.chd" +embed_cue "$TMP/bad.cue" "$CD/cuesheet_bad.chd" + # CHDv3/v4 fixtures for tests/legacy_decode.c. chdman only writes v5, so these # come from mklegacy.py, which builds the older layouts directly. LEGACY="$(cd "$(dirname "$0")" && pwd)/legacy" diff --git a/tests/metadata_scanf.c b/tests/metadata_scanf.c new file mode 100644 index 0000000..f5b1398 --- /dev/null +++ b/tests/metadata_scanf.c @@ -0,0 +1,84 @@ +/* license:BSD-3-Clause + * copyright-holders:Romain Tisserand + * + * The CD track metadata formats carry %s fields, and the metadata string is + * whatever the CHD says it is. Scanned with the unbounded *_FORMAT macros an + * over-long TYPE writes past the caller's buffer (#165); the *_SCANF variants + * stop at CD_METADATA_STRING_SIZE - 1 characters. Needs no corpus. + */ +#include +#include + +#include + +struct guarded +{ + char str[CD_METADATA_STRING_SIZE]; + char canary[16]; +}; + +static int failures; + +static void check(int ok, const char *what) +{ + if (!ok) + { + fprintf(stderr, "FAIL: %s\n", what); + failures++; + } +} + +static void fill(struct guarded *g) +{ + memset(g->str, 0, sizeof(g->str)); + memset(g->canary, 0x5a, sizeof(g->canary)); +} + +static int intact(const struct guarded *g) +{ + size_t i; + for (i = 0; i < sizeof(g->canary); i++) + if ((unsigned char)g->canary[i] != 0x5a) + return 0; + return 1; +} + +int main(void) +{ + struct guarded type, subtype, pgtype, pgsub; + int track = 0, frames = 0, pad = 0, pregap = 0, postgap = 0; + + /* a well-formed CHT2 entry parses in full */ + fill(&type); fill(&subtype); fill(&pgtype); fill(&pgsub); + check(sscanf("TRACK:2 TYPE:AUDIO SUBTYPE:NONE FRAMES:1500 PREGAP:150 PGTYPE:VAUDIO PGSUB:RW POSTGAP:0", + CDROM_TRACK_METADATA2_SCANF, &track, type.str, subtype.str, &frames, + &pregap, pgtype.str, pgsub.str, &postgap) == 8, "CHT2 field count"); + check(track == 2 && frames == 1500 && pregap == 150 && postgap == 0, "CHT2 numbers"); + check(strcmp(type.str, "AUDIO") == 0 && strcmp(pgtype.str, "VAUDIO") == 0, "CHT2 strings"); + + /* the longest real value, MODE2_FORM_MIX, still fits */ + fill(&type); fill(&subtype); + check(sscanf("TRACK:1 TYPE:MODE2_FORM_MIX SUBTYPE:RW_RAW FRAMES:10", + CDROM_TRACK_METADATA_SCANF, &track, type.str, subtype.str, &frames) == 4, "CHTR field count"); + check(strcmp(type.str, "MODE2_FORM_MIX") == 0 && frames == 10, "CHTR longest type"); + + /* an over-long TYPE stops at the buffer, and the rest of the line no + * longer matches - so the field count tells the caller to reject it */ + fill(&type); fill(&subtype); + check(sscanf("TRACK:1 TYPE:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA SUBTYPE:NONE FRAMES:10", + CDROM_TRACK_METADATA_SCANF, &track, type.str, subtype.str, &frames) == 2, "overlong TYPE rejected"); + check(strlen(type.str) == CD_METADATA_STRING_SIZE - 1, "overlong TYPE truncated"); + check(intact(&type) && intact(&subtype), "CHTR canary"); + + /* every string field of the GD-ROM format is bounded too */ + fill(&type); fill(&subtype); fill(&pgtype); fill(&pgsub); + sscanf("TRACK:3 TYPE:MODE1_RAW SUBTYPE:NONE FRAMES:1 PAD:0 PREGAP:0 PGTYPE:MODE1 " + "PGSUB:BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB POSTGAP:0", + GDROM_TRACK_METADATA_SCANF, &track, type.str, subtype.str, &frames, + &pad, &pregap, pgtype.str, pgsub.str, &postgap); + check(intact(&type) && intact(&subtype) && intact(&pgtype) && intact(&pgsub), "CHGD canary"); + + if (failures == 0) + printf("metadata scanf bounds: ok\n"); + return failures ? 1 : 0; +} diff --git a/unity.c b/unity.c index dd2bd28..45c2f97 100644 --- a/unity.c +++ b/unity.c @@ -22,6 +22,7 @@ #include "src/libchdr_bitstream.c" #include "src/libchdr_cdrom.c" +#include "src/libchdr_cdrom_toc.c" #include "src/libchdr_chd.c" #include "src/libchdr_codec_cdfl.c" #include "src/libchdr_codec_cdlz.c"