fix(audiobook): use music-metadata for audiobook chapters (#6686)

Replace the custom MP4 chapter reader introduced in #6327 with chapter data from music-metadata 12.1.0. Preserve chapter normalization, duration clamping, labels, and the single-chapter fallback.

Fixes #6262.

Co-authored-by: Borewit <borewit@users.noreply.github.com>
This commit is contained in:
Borewit 2026-10-09 10:18:22 +02:00 • committed by GitHub
parent ef0b3e10b7
commit 44803443a6
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
9 changed files with 79 additions and 838 deletions

View file

@ -189,7 +189,7 @@
"marked": "^15.0.12",
"marked-footnote": "^1.4.0",
"marked-katex-extension": "^5.1.10",
"music-metadata": "^11.14.0",
"music-metadata": "12.1.0",
"nanoid": "^5.1.6",
"next": "16.3.8",
"nunjucks": "^3.2.4",

View file

@ -1,15 +1,14 @@
// @vitest-environment node
import { readFile } from 'node:fs/promises';
import { parseBlob } from 'music-metadata';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { buildAudiobookChapters, parseAudiobookFile } from '@/services/audiobook/metadata';
import { readMp4Chapters } from '@/services/audiobook/mp4Chapters';
vi.mock('music-metadata', () => ({ parseBlob: vi.fn() }));
vi.mock('@/services/audiobook/mp4Chapters', () => ({ readMp4Chapters: vi.fn() }));
beforeEach(() => {
vi.mocked(parseBlob).mockReset();
vi.mocked(readMp4Chapters).mockReset().mockResolvedValue([]);
});
const audioWithoutChapters = (duration: number) => ({
@ -125,12 +124,18 @@ describe('parseAudiobookFile', () => {
});
});
it('uses the MP4 chapter reader when music-metadata returns no chapters', async () => {
vi.mocked(parseBlob).mockResolvedValue(audioWithoutChapters(90));
vi.mocked(readMp4Chapters).mockResolvedValue([
{ title: 'Opening Credits', start: 0, timeScale: 1_000 },
{ title: 'Chapter 1', start: 30_000, timeScale: 1_000 },
]);
it('uses the chapter list returned by music-metadata', async () => {
const metadata = audioWithoutChapters(90);
vi.mocked(parseBlob).mockResolvedValue({
...metadata,
format: {
...metadata.format,
chapters: [
{ title: 'Opening Credits', start: 0, timeScale: 1_000 },
{ title: 'Chapter 1', start: 30_000, timeScale: 1_000 },
],
},
});
const file = new File(['audio'], 'book.m4b');
await expect(parseAudiobookFile(file, 'audio-0')).resolves.toMatchObject({
@ -139,16 +144,22 @@ describe('parseAudiobookFile', () => {
{ label: 'Chapter 1', start: 30, end: 90 },
],
});
expect(readMp4Chapters).toHaveBeenCalledWith(file);
expect(parseBlob).toHaveBeenCalledWith(file, {
duration: true,
includeChapters: true,
skipCovers: true,
});
});
it('keeps the embedded title when every MP4 chapter is rejected', async () => {
vi.mocked(parseBlob).mockResolvedValue(audioWithoutChapters(90));
// A trailing marker sample at the very end of the audio yields no usable
// chapter, so the single full-file chapter must still carry the title.
vi.mocked(readMp4Chapters).mockResolvedValue([
{ title: 'End Credits', start: 90_000, timeScale: 1_000 },
]);
const metadata = audioWithoutChapters(90);
vi.mocked(parseBlob).mockResolvedValue({
...metadata,
format: {
...metadata.format,
chapters: [{ title: 'End Credits', start: 90_000, timeScale: 1_000 }],
},
});
await expect(
parseAudiobookFile(new File(['audio'], 'My Audiobook.m4b'), 'audio-0'),
@ -157,15 +168,15 @@ describe('parseAudiobookFile', () => {
});
});
it('keeps the single full-file chapter when the MP4 chapter fallback fails', async () => {
it('keeps a full-file chapter without reading the source again when no chapters are returned', async () => {
vi.mocked(parseBlob).mockResolvedValue(audioWithoutChapters(90));
vi.mocked(readMp4Chapters).mockRejectedValue(new RangeError('Offset is outside the bounds'));
const file = new File([new Uint8Array(64)], 'book.m4b');
const slice = vi.spyOn(file, 'slice');
await expect(
parseAudiobookFile(new File(['audio'], 'book.m4b'), 'audio-0'),
).resolves.toMatchObject({
await expect(parseAudiobookFile(file, 'audio-0')).resolves.toMatchObject({
chapters: [{ label: 'The Book', start: 0, end: 90 }],
});
expect(slice).not.toHaveBeenCalled();
});
it('rejects audio whose duration cannot be determined', async () => {
@ -185,3 +196,25 @@ describe('parseAudiobookFile', () => {
);
});
});
// Real AAC excerpts exercise the actual parser without mocking its chapter output.
describe('parseAudiobookFile chapter integration', () => {
for (const fixture of ['chapters-leading.m4b', 'chapters-trailing.m4b', 'chapters-nero.m4b']) {
it(`imports ${fixture} through music-metadata`, async () => {
// Delegate to the actual parser so the fixture determines the chapter output.
const actual = await vi.importActual<typeof import('music-metadata')>('music-metadata');
vi.mocked(parseBlob).mockImplementation(actual.parseBlob);
const bytes = await readFile(
new URL(`../fixtures/data/audiobook/${fixture}`, import.meta.url),
);
const file = new File([new Uint8Array(bytes)], fixture, { type: 'audio/mp4' });
const metadata = await parseAudiobookFile(file, 'audiobook');
expect(metadata.duration).toBeCloseTo(10, 1);
expect(metadata.chapters.map(({ label, start, end }) => ({ label, start, end }))).toEqual([
{ label: 'Opening Credits', start: 0, end: 3 },
{ label: 'Chapter 1', start: 3, end: 7 },
{ label: 'Chapter 2', start: 7, end: metadata.duration },
]);
});
}
});

View file

@ -1,481 +0,0 @@
import { describe, expect, it, vi } from 'vitest';
import { MAX_CHAPTERS, readMp4Chapters } from '@/services/audiobook/mp4Chapters';
const concat = (...parts: Uint8Array[]) => {
const out = new Uint8Array(parts.reduce((sum, part) => sum + part.length, 0));
let offset = 0;
for (const part of parts) {
out.set(part, offset);
offset += part.length;
}
return out;
};
const u8 = (value: number) => Uint8Array.of(value);
const u16 = (value: number) => Uint8Array.of(value >> 8, value & 0xff);
const u32 = (value: number) => {
const out = new Uint8Array(4);
new DataView(out.buffer).setUint32(0, value);
return out;
};
const u64 = (value: number) => {
const out = new Uint8Array(8);
new DataView(out.buffer).setBigUint64(0, BigInt(value));
return out;
};
const ascii = (text: string) => new TextEncoder().encode(text);
const utf16be = (text: string) =>
concat(Uint8Array.of(0xfe, 0xff), ...[...text].map((char) => u16(char.charCodeAt(0))));
const box = (type: string, ...payload: Uint8Array[]) => {
const body = concat(...payload);
return concat(u32(8 + body.length), ascii(type), body);
};
const fullBox = (type: string, version: number, ...payload: Uint8Array[]) =>
box(type, u8(version), new Uint8Array(3), ...payload);
const ftyp = box('ftyp', ascii('M4B '), u32(0), ascii('M4B isom'));
const free = box('free', new Uint8Array(24));
const tkhd = (trackId: number, version: 0 | 1 = 0) =>
version === 1
? fullBox('tkhd', 1, u64(0), u64(0), u32(trackId), u32(0))
: fullBox('tkhd', 0, u32(0), u32(0), u32(trackId), u32(0));
const mdhd = (timeScale: number, version: 0 | 1 = 0) =>
version === 1
? fullBox('mdhd', 1, u64(0), u64(0), u32(timeScale), u64(0))
: fullBox('mdhd', 0, u32(0), u32(0), u32(timeScale), u32(0));
const hdlr = (handler: string) => fullBox('hdlr', 0, u32(0), ascii(handler), new Uint8Array(12));
const chapRef = (...trackIds: number[]) => box('tref', box('chap', ...trackIds.map(u32)));
const stts = (runs: [count: number, delta: number][]) =>
fullBox(
'stts',
0,
u32(runs.length),
...runs.flatMap(([count, delta]) => [u32(count), u32(delta)]),
);
const stsz = (sizes: number[]) => fullBox('stsz', 0, u32(0), u32(sizes.length), ...sizes.map(u32));
const stszFixed = (size: number, count: number) => fullBox('stsz', 0, u32(size), u32(count));
/** Builds a large stsz without spreading one argument per entry. */
const stszBulk = (count: number, size: number) => {
const entries = new Uint8Array(count * 4);
const view = new DataView(entries.buffer);
for (let i = 0; i < count; i++) view.setUint32(i * 4, size);
return fullBox('stsz', 0, u32(0), u32(count), entries);
};
const stsc = (runs: [firstChunk: number, samplesPerChunk: number][]) =>
fullBox(
'stsc',
0,
u32(runs.length),
...runs.flatMap(([first, perChunk]) => [u32(first), u32(perChunk), u32(1)]),
);
const stco = (offsets: number[], declared = offsets.length) =>
fullBox('stco', 0, u32(declared), ...offsets.map(u32));
const co64 = (offsets: number[]) => fullBox('co64', 0, u32(offsets.length), ...offsets.map(u64));
const textTrak = (
tables: Uint8Array[],
{ trackId = 2, version = 0 as 0 | 1, handler = 'text' as string | null, timeScale = 1_000 } = {},
) =>
box(
'trak',
tkhd(trackId, version),
box(
'mdia',
mdhd(timeScale, version),
...(handler ? [hdlr(handler)] : []),
box('minf', box('stbl', ...tables)),
),
);
const audioTrak = ({
trackId = 1,
refs = [2],
version = 0 as 0 | 1,
handler = 'soun',
tables = [] as Uint8Array[],
} = {}) =>
box(
'trak',
tkhd(trackId, version),
...(refs.length ? [chapRef(...refs)] : []),
box(
'mdia',
mdhd(44_100, version),
hdlr(handler),
...(tables.length ? [box('minf', box('stbl', ...tables))] : []),
),
);
const neroChpl = (entries: [start: number, title: string][]) =>
fullBox(
'chpl',
1,
u32(0),
u8(entries.length),
...entries.flatMap(([start, title]) => [u64(start), u8(title.length), ascii(title)]),
);
// Two samples share the first chunk and the third has its own, so sample
// offsets depend on stsc; the stts run of two exercises count > 1.
const samples = [
concat(u16(15), ascii('Opening Credits')),
concat(u16(9), ascii('Chapter 1')),
concat(u16(20), utf16be('Chapter 2')),
];
const audioBytes = new Uint8Array(1_000).fill(0xaa);
const mdatPayload = concat(audioBytes, samples[0]!, samples[1]!, audioBytes, samples[2]!);
const mdat = box('mdat', mdatPayload);
const chunkOffsetsIn = (mdatStart: number) => {
const first = mdatStart + 8 + audioBytes.length;
return [first, first + samples[0]!.length + samples[1]!.length + audioBytes.length];
};
const defaultTables = (chunkOffsets: number[], chunkBox = stco) => [
stts([
[1, 5_000],
[2, 30_000],
]),
stsz(samples.map((sample) => sample.length)),
stsc([
[1, 2],
[2, 1],
]),
chunkBox(chunkOffsets),
];
/** Assembles ftyp + mdat + moov, with moov's chunk offsets pointing into mdat. */
const buildFile = (
moovFor: (chunkOffsets: number[]) => Uint8Array<ArrayBuffer>,
{ layout = 'moov-at-end' as 'moov-at-end' | 'faststart', lead = new Uint8Array(0) } = {},
) => {
const head = concat(lead, ftyp);
if (layout === 'moov-at-end') {
return new Blob([head, mdat, moovFor(chunkOffsetsIn(head.length))]);
}
const moovLength = moovFor([0, 0]).length;
return new Blob([head, moovFor(chunkOffsetsIn(head.length + moovLength)), mdat]);
};
const chapterTrackMoov = (chunkOffsets: number[]) =>
box('moov', audioTrak(), textTrak(defaultTables(chunkOffsets)));
const expectedTrackChapters = [
{ title: 'Opening Credits', start: 0, timeScale: 1_000 },
{ title: 'Chapter 1', start: 5_000, timeScale: 1_000 },
{ title: 'Chapter 2', start: 35_000, timeScale: 1_000 },
];
describe('readMp4Chapters', () => {
it('reads the QuickTime chapter track when moov sits after mdat', async () => {
await expect(readMp4Chapters(buildFile(chapterTrackMoov))).resolves.toEqual(
expectedTrackChapters,
);
});
it('reads the QuickTime chapter track when moov precedes mdat', async () => {
await expect(
readMp4Chapters(buildFile(chapterTrackMoov, { layout: 'faststart' })),
).resolves.toEqual(expectedTrackChapters);
});
it('finds moov when padding precedes ftyp', async () => {
await expect(readMp4Chapters(buildFile(chapterTrackMoov, { lead: free }))).resolves.toEqual(
expectedTrackChapters,
);
});
it('reads 64-bit chunk offsets', async () => {
const file = buildFile((offsets) =>
box('moov', audioTrak(), textTrak(defaultTables(offsets, co64))),
);
await expect(readMp4Chapters(file)).resolves.toEqual(expectedTrackChapters);
});
it('reads version 1 tkhd and mdhd headers', async () => {
const file = buildFile((offsets) =>
box('moov', audioTrak({ version: 1 }), textTrak(defaultTables(offsets), { version: 1 })),
);
await expect(readMp4Chapters(file)).resolves.toEqual(expectedTrackChapters);
});
it('accepts a chapter track that omits hdlr', async () => {
const file = buildFile((offsets) =>
box('moov', audioTrak(), textTrak(defaultTables(offsets), { handler: null })),
);
await expect(readMp4Chapters(file)).resolves.toEqual(expectedTrackChapters);
});
it('reads a fixed-size sample table', async () => {
const fixed = [concat(u16(9), ascii('Chapter 1')), concat(u16(9), ascii('Chapter 2'))];
const payload = concat(audioBytes, ...fixed);
const tables = (offsets: number[]) => [
stts([[2, 10_000]]),
stszFixed(fixed[0]!.length, 2),
stsc([[1, 2]]),
stco(offsets),
];
const moovFor = (offsets: number[]) => box('moov', audioTrak(), textTrak(tables(offsets)));
const moovLength = moovFor([0]).length;
const start = ftyp.length + 8 + audioBytes.length;
const file = new Blob([ftyp, box('mdat', payload), moovFor([start])]);
expect(moovLength).toBeGreaterThan(0);
await expect(readMp4Chapters(file)).resolves.toEqual([
{ title: 'Chapter 1', start: 0, timeScale: 1_000 },
{ title: 'Chapter 2', start: 10_000, timeScale: 1_000 },
]);
});
it('clamps a corrupt chunk-offset count instead of throwing', async () => {
const file = buildFile((offsets) =>
box(
'moov',
audioTrak(),
textTrak([
stts([
[1, 5_000],
[2, 30_000],
]),
stsz(samples.map((sample) => sample.length)),
stsc([
[1, 2],
[2, 1],
]),
stco(offsets, 0xffffffff),
]),
),
);
await expect(readMp4Chapters(file)).resolves.toEqual(expectedTrackChapters);
});
it('keeps the chapters it could decode when one sample is unreadable', async () => {
const file = buildFile((offsets) =>
box(
'moov',
audioTrak(),
textTrak([
stts([
[1, 5_000],
[1, 30_000],
]),
// The second sample declares a zero length, so it cannot be decoded.
stsz([samples[0]!.length, 0]),
stsc([[1, 2]]),
stco([offsets[0]!]),
]),
),
);
await expect(readMp4Chapters(file)).resolves.toEqual([
{ title: 'Opening Credits', start: 0, timeScale: 1_000 },
{ title: '', start: 5_000, timeScale: 1_000 },
]);
});
it.each<{ name: string; runs: [number, number][] }>([
{
name: 'zero samples per chunk',
runs: [
[1, 0],
[2, 3],
],
},
{
name: 'zero first chunk',
runs: [
[0, 1],
[1, 3],
],
},
{
name: 'duplicate first chunks',
runs: [
[1, 1],
[1, 2],
],
},
{
name: 'descending first chunks',
runs: [
[2, 1],
[1, 2],
],
},
{
name: 'first chunk beyond the chunk table',
runs: [
[1, 1],
[0xffffffff, 1],
],
},
])('falls back to Nero chapters for $name', async ({ runs }) => {
const file = buildFile((offsets) =>
box(
'moov',
audioTrak(),
textTrak([
stts([[3, 5_000]]),
stsz(samples.map((sample) => sample.length)),
stsc(runs),
stco(offsets),
]),
box('udta', neroChpl([[0, 'Prelude']])),
),
);
await expect(readMp4Chapters(file)).resolves.toEqual([
{ title: 'Prelude', start: 0, timeScale: 10_000_000 },
]);
});
it('stops inspecting chunk runs once all declared samples have offsets', async () => {
const runs: [number, number][] = Array.from({ length: 100 }, (_, i) => [i + 1, 1]);
const table = stsc(runs);
const file = buildFile((offsets) =>
box(
'moov',
audioTrak(),
textTrak([
stts([[1, 5_000]]),
stsz([samples[0]!.length]),
table,
stco(Array.from({ length: runs.length }, () => offsets[0]!)),
]),
),
);
let tableReads = 0;
const getUint32 = DataView.prototype.getUint32;
const spy = vi.spyOn(DataView.prototype, 'getUint32').mockImplementation(function (
this: DataView,
offset: number,
littleEndian?: boolean,
) {
if (this.byteLength === table.length - 8) tableReads++;
return getUint32.call(this, offset, littleEndian);
});
try {
await expect(readMp4Chapters(file)).resolves.toEqual([expectedTrackChapters[0]]);
expect(tableReads).toBeLessThan(10);
} finally {
spy.mockRestore();
}
});
it('caps a runaway chapter count', async () => {
const many = Array.from({ length: MAX_CHAPTERS + 20 }, (_, i) =>
concat(u16(2), ascii(`C${i}`)),
);
const payload = concat(...many);
const start = ftyp.length + 8;
const moov = box(
'moov',
audioTrak(),
textTrak([
stts([[many.length, 1_000]]),
stsz(many.map((sample) => sample.length)),
stsc([[1, many.length]]),
stco([start]),
]),
);
const file = new Blob([ftyp, box('mdat', payload), moov]);
await expect(readMp4Chapters(file)).resolves.toHaveLength(MAX_CHAPTERS);
});
it('reads Nero chpl chapters in 100ns units', async () => {
const file = new Blob([
ftyp,
box('mdat', audioBytes),
box(
'moov',
audioTrak({ refs: [] }),
box(
'udta',
neroChpl([
[0, 'Prelude'],
[125_000_000, 'Chapter 1'],
]),
),
),
]);
await expect(readMp4Chapters(file)).resolves.toEqual([
{ title: 'Prelude', start: 0, timeScale: 10_000_000 },
{ title: 'Chapter 1', start: 125_000_000, timeScale: 10_000_000 },
]);
});
it('falls back to chpl when the chapter track yields no titles', async () => {
const chpl = box('udta', neroChpl([[0, 'Prelude']]));
const file = buildFile(() =>
box(
'moov',
audioTrak(),
textTrak([
stts([[1, 5_000]]),
stsz([samples[0]!.length]),
stsc([[1, 1]]),
// Offset past the end of the file, as a stale table would be.
stco([0xfffffff]),
]),
chpl,
),
);
await expect(readMp4Chapters(file)).resolves.toEqual([
{ title: 'Prelude', start: 0, timeScale: 10_000_000 },
]);
});
it('ignores a chapter reference that points at an audio track', async () => {
const file = buildFile((offsets) =>
box(
'moov',
// The reference names the audio track itself rather than the text track.
audioTrak({ refs: [1], tables: defaultTables(offsets) }),
box('udta', neroChpl([[0, 'Prelude']])),
),
);
await expect(readMp4Chapters(file)).resolves.toEqual([
{ title: 'Prelude', start: 0, timeScale: 10_000_000 },
]);
});
it('reads only the boxes it needs, not the whole moov', async () => {
// A long book's audio track carries a sample table for every frame.
const bigTables = [
stts([[50_000, 1_024]]),
stszBulk(50_000, 400),
stsc([[1, 50_000]]),
stco([0]),
];
const moovFor = (offsets: number[]) =>
box('moov', audioTrak({ tables: bigTables }), textTrak(defaultTables(offsets)));
const blob = buildFile(moovFor);
let bytesRead = 0;
const counting = {
size: blob.size,
slice: (start: number, end: number) => {
const part = blob.slice(start, end);
return {
arrayBuffer: async () => {
const buffer = await part.arrayBuffer();
bytesRead += buffer.byteLength;
return buffer;
},
};
},
} as unknown as Blob;
await expect(readMp4Chapters(counting)).resolves.toEqual(expectedTrackChapters);
expect(blob.size).toBeGreaterThan(200_000);
expect(bytesRead).toBeLessThan(16_000);
});
it('returns no chapters for files that are not MP4', async () => {
const mp3 = new Blob([ascii('ID3'), u8(4), new Uint8Array(64)]);
await expect(readMp4Chapters(mp3)).resolves.toEqual([]);
});
});

View file

@ -2,7 +2,6 @@ import type { IChapter } from 'music-metadata';
import type { AudiobookChapter } from '@/types/book';
import { getBaseFilename } from '@/utils/path';
import { readMp4Chapters } from './mp4Chapters';
type ChapterSource = Pick<IChapter, 'title' | 'start' | 'end' | 'timeScale'>;
@ -79,22 +78,11 @@ export const parseAudiobookFile = async (
throw new Error(`Could not determine the duration of ${file.name}`);
}
let sourceChapters: ChapterSource[] = metadata.format.chapters ?? [];
if (!sourceChapters.length) {
// music-metadata misses MP4 chapters when moov follows the audio, and
// never reads Nero chapters; see mp4Chapters.ts.
sourceChapters = await readMp4Chapters(file).catch((error) => {
console.warn(`Failed to read MP4 chapters from ${file.name}:`, error);
return [];
});
}
// The embedded title names the single chapter only when no chapter list
// survived, so a file whose chapters are all rejected keeps its title.
const chapters = buildAudiobookChapters(
fileId,
file.name,
duration,
sourceChapters,
metadata.format.chapters ?? [],
metadata.common.title,
);

View file

@ -1,305 +0,0 @@
// MP4 chapters live in one of two places, and music-metadata reads neither of
// them reliably:
//
// - A QuickTime chapter track, where the audio track points at a text track
// whose samples hold the titles. music-metadata pulls those titles out only
// while it streams past mdat, and only once it has parsed the tracks in
// moov, so a file that stores moov after the audio (what ffmpeg writes
// without -movflags +faststart) yields no chapters and no error. Tracked
// upstream as Borewit/music-metadata#2510.
// - A Nero chpl list in moov/udta, which music-metadata does not read at all.
//
// This reader finds moov wherever it sits, prefers the chapter track and falls
// back to chpl. It walks box headers straight off the file and reads only the
// handful of small boxes it needs, so a long book's per-frame sample tables are
// never pulled into memory.
//
// Every length here comes from the file, so each table's declared entry count
// is clamped to what its own box can hold, and a box that fails to parse leaves
// the other chapter source a chance to work.
export interface Mp4Chapter {
title: string;
start: number;
timeScale: number;
}
/** Offsets are absolute positions in the file. */
interface Box {
type: string;
start: number;
headerSize: number;
end: number;
}
/** Enough for the largest box header (64-bit size). */
const HEADER_BYTES = 16;
/** No real audiobook has more; a larger count means a table we misread. */
export const MAX_CHAPTERS = 1_000;
/** Chapter titles are short; anything larger is a bad sample size. */
const MAX_TITLE_BYTES = 64 * 1_024;
/** Upper bound on a single box payload we are willing to buffer. */
const MAX_BOX_BYTES = 8 * 1_024 * 1_024;
/** Nero chapter start times are in 100ns units. */
const NERO_TIME_SCALE = 10_000_000;
const readView = async (file: Blob, start: number, end: number) =>
new DataView(await file.slice(start, end).arrayBuffer());
const parseHeader = (view: DataView, start: number, limit: number): Box | null => {
if (view.byteLength < 8) return null;
let size = view.getUint32(0);
let headerSize = 8;
if (size === 1) {
if (view.byteLength < 16) return null;
size = Number(view.getBigUint64(8));
headerSize = 16;
} else if (size === 0) {
size = limit - start;
}
if (size < headerSize || start + size > limit) return null;
const type = String.fromCharCode(...new Uint8Array(view.buffer, view.byteOffset + 4, 4));
if (!/^[\x20-\x7e]{4}$/.test(type)) return null;
return { type, start, headerSize, end: start + size };
};
const readHeader = async (file: Blob, start: number, limit: number) =>
parseHeader(await readView(file, start, Math.min(start + HEADER_BYTES, limit)), start, limit);
async function* childBoxes(file: Blob, parent: Box) {
let at = parent.start + parent.headerSize;
while (at + 8 <= parent.end) {
const box = await readHeader(file, at, parent.end);
if (!box) return;
yield box;
at = box.end;
}
}
const findChild = async (file: Blob, parent: Box, type: string) => {
for await (const child of childBoxes(file, parent)) if (child.type === type) return child;
return undefined;
};
const findPath = async (file: Blob, parent: Box, path: string[]) => {
let box: Box | undefined = parent;
for (const type of path) {
if (!box) return undefined;
box = await findChild(file, box, type);
}
return box;
};
/** Reads a box's payload, refusing one whose declared length is implausible. */
const payloadView = async (file: Blob, box: Box) => {
const start = box.start + box.headerSize;
if (box.end - start > MAX_BOX_BYTES) return null;
return readView(file, start, box.end);
};
const findTopLevelBox = async (file: Blob, type: string) => {
for (let at = 0; at + 8 <= file.size; ) {
const box = await readHeader(file, at, file.size);
if (!box) return undefined;
if (box.type === type) return box;
at = box.end;
}
return undefined;
};
/** How many entries a table box can actually hold, whatever it claims. */
const tableCapacity = (view: DataView, headerBytes: number, width: number) =>
Math.max(0, Math.floor((view.byteLength - headerBytes) / width));
// --- QuickTime chapter track: audio trak -> tref/chap -> text trak samples ---
// tkhd and mdhd both put the field we want after version/flags and two
// timestamps, which are 32-bit in version 0 and 64-bit in version 1.
const fieldAfterTimestamps = (payload: DataView) =>
payload.getUint32(payload.getUint8(0) === 1 ? 20 : 12);
/** Writers that omit hdlr are accepted; one that claims another kind is not. */
const isTextTrack = async (file: Blob, trak: Box) => {
const hdlr = await findPath(file, trak, ['mdia', 'hdlr']);
if (!hdlr) return true;
const view = await payloadView(file, hdlr);
if (!view || view.byteLength < 12) return true;
const handler = String.fromCharCode(...new Uint8Array(view.buffer, view.byteOffset + 8, 4));
return handler === 'text' || handler === 'sbtl';
};
const findChapterTrack = async (file: Blob, traks: Box[]) => {
const trackIds = await Promise.all(
traks.map(async (trak) => {
const tkhd = await findChild(file, trak, 'tkhd');
const view = tkhd ? await payloadView(file, tkhd) : null;
return view && view.byteLength >= 16 ? fieldAfterTimestamps(view) : undefined;
}),
);
for (const trak of traks) {
const chap = await findPath(file, trak, ['tref', 'chap']);
const view = chap ? await payloadView(file, chap) : null;
if (!view) continue;
for (let at = 0; at + 4 <= view.byteLength; at += 4) {
const target = traks[trackIds.indexOf(view.getUint32(at))];
// A track referencing itself is a broken file, not a chapter list.
if (target && target !== trak && (await isTextTrack(file, target))) return target;
}
}
return undefined;
};
/** A title sample is a 16-bit length followed by the text itself. */
const decodeChapterText = (sample: DataView) => {
if (sample.byteLength < 2) return '';
const length = Math.min(sample.getUint16(0), sample.byteLength - 2);
const bytes = new Uint8Array(sample.buffer, sample.byteOffset + 2, length);
const utf16 = bytes[0] === 0xfe && bytes[1] === 0xff;
return new TextDecoder(utf16 ? 'utf-16be' : 'utf-8').decode(bytes);
};
/** An unreadable sample costs one title, not the whole chapter list. */
const readTitle = async (file: Blob, offset: number, size: number) => {
if (size < 2 || size > MAX_TITLE_BYTES) return '';
return decodeChapterText(await readView(file, offset, offset + size));
};
const readChapterTrack = async (file: Blob, trak: Box): Promise<Mp4Chapter[]> => {
const mdhd = await findPath(file, trak, ['mdia', 'mdhd']);
const stbl = await findPath(file, trak, ['mdia', 'minf', 'stbl']);
if (!mdhd || !stbl) return [];
const tables = new Map<string, Box>();
for await (const child of childBoxes(file, stbl)) tables.set(child.type, child);
const chunkBox = tables.get('stco') ?? tables.get('co64');
const sttsBox = tables.get('stts');
const stszBox = tables.get('stsz');
const stscBox = tables.get('stsc');
if (!chunkBox || !sttsBox || !stszBox || !stscBox) return [];
const [mdhdView, sttsView, stszView, stscView, chunkView] = await Promise.all([
payloadView(file, mdhd),
payloadView(file, sttsBox),
payloadView(file, stszBox),
payloadView(file, stscBox),
payloadView(file, chunkBox),
]);
if (!mdhdView || !sttsView || !stszView || !stscView || !chunkView) return [];
if (mdhdView.byteLength < 16 || stszView.byteLength < 12) return [];
const fixedSize = stszView.getUint32(4);
const declared = stszView.getUint32(8);
const sampleCount = Math.min(
declared,
MAX_CHAPTERS,
fixedSize ? declared : tableCapacity(stszView, 12, 4),
);
const sizeOf = (sample: number) => fixedSize || stszView.getUint32(12 + sample * 4);
const width = chunkBox.type === 'co64' ? 8 : 4;
const chunkCount = Math.min(chunkView.getUint32(4), tableCapacity(chunkView, 8, width));
const chunkOffsets = Array.from({ length: chunkCount }, (_, index) =>
width === 8
? Number(chunkView.getBigUint64(8 + index * 8))
: chunkView.getUint32(8 + index * 4),
);
// Expand the sample-to-chunk runs into a file offset per sample.
const offsets: number[] = [];
const chunkRuns = Math.min(stscView.getUint32(4), tableCapacity(stscView, 8, 12));
for (let run = 0; run < chunkRuns && offsets.length < sampleCount; run++) {
const at = 8 + run * 12;
const firstChunk = stscView.getUint32(at);
const samplesPerChunk = stscView.getUint32(at + 4);
const nextFirstChunk = run + 1 < chunkRuns ? stscView.getUint32(at + 12) : chunkCount + 1;
if (
samplesPerChunk === 0 ||
firstChunk < 1 ||
nextFirstChunk <= firstChunk ||
nextFirstChunk > chunkCount + 1
) {
return [];
}
for (let chunk = firstChunk; chunk < nextFirstChunk && offsets.length < sampleCount; chunk++) {
let offset = chunkOffsets[chunk - 1];
if (offset === undefined) break;
for (let i = 0; i < samplesPerChunk && offsets.length < sampleCount; i++) {
offsets.push(offset);
offset += sizeOf(offsets.length - 1);
}
}
}
// Expand the time-to-sample runs into a start time per sample. These are the
// chapter track's own media times; an edit list (elst) that shifts the track
// is ignored, as it is by music-metadata's reader.
const starts: number[] = [];
const timeRuns = Math.min(sttsView.getUint32(4), tableCapacity(sttsView, 8, 8));
let time = 0;
for (let run = 0; run < timeRuns && starts.length < sampleCount; run++) {
const at = 8 + run * 8;
const count = sttsView.getUint32(at);
const delta = sttsView.getUint32(at + 4);
for (let i = 0; i < count && starts.length < sampleCount; i++) {
starts.push(time);
time += delta;
}
}
const timeScale = fieldAfterTimestamps(mdhdView);
const chapters: Mp4Chapter[] = [];
for (let i = 0; i < Math.min(offsets.length, starts.length); i++) {
const title = await readTitle(file, offsets[i]!, sizeOf(i));
chapters.push({ title, start: starts[i]!, timeScale });
}
return chapters;
};
// --- Nero chapters: a flat list in moov/udta/chpl with the titles inline ---
const readNeroChapters = async (file: Blob, chpl: Box): Promise<Mp4Chapter[]> => {
const view = await payloadView(file, chpl);
if (!view || view.byteLength < 5) return [];
// Version 1 adds a reserved 32-bit field before the count.
let at = view.getUint8(0) ? 8 : 4;
if (at >= view.byteLength) return [];
const count = Math.min(view.getUint8(at), MAX_CHAPTERS);
at += 1;
const chapters: Mp4Chapter[] = [];
for (let i = 0; i < count && at + 9 <= view.byteLength; i++) {
const length = view.getUint8(at + 8);
if (at + 9 + length > view.byteLength) break;
const title = new TextDecoder().decode(
new Uint8Array(view.buffer, view.byteOffset + at + 9, length),
);
chapters.push({ title, start: Number(view.getBigUint64(at)), timeScale: NERO_TIME_SCALE });
at += 9 + length;
}
return chapters;
};
/**
* Reads chapters wherever moov sits in the file, preferring a QuickTime
* chapter track and falling back to a Nero `chpl` list. Returns an empty list
* for files that are not MP4.
*/
export const readMp4Chapters = async (file: Blob): Promise<Mp4Chapter[]> => {
const moov = await findTopLevelBox(file, 'moov');
if (!moov) return [];
const traks: Box[] = [];
for await (const box of childBoxes(file, moov)) {
if (box.type === 'trak') traks.push(box);
}
const chapterTrack = await findChapterTrack(file, traks);
// A malformed sample table must not hide a usable chpl list.
const trackChapters = chapterTrack
? await readChapterTrack(file, chapterTrack).catch(() => [])
: [];
if (trackChapters.some((chapter) => chapter.title)) return trackChapters;
const chpl = await findPath(file, moov, ['udta', 'chpl']);
if (!chpl) return trackChapters;
const neroChapters = await readNeroChapters(file, chpl).catch(() => []);
return neroChapters.length ? neroChapters : trackChapters;
};

40
pnpm-lock.yaml generated
View file

@ -358,8 +358,8 @@ importers:
specifier: ^5.1.10
version: 5.1.10(katex@0.16.45)(marked@15.0.12)
music-metadata:
specifier: ^11.14.0
version: 11.14.0
specifier: 12.1.0
version: 12.1.0
nanoid:
specifier: '>=5.1.16 <6'
version: 5.1.16
@ -4824,6 +4824,10 @@ packages:
resolution: {integrity: sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==}
engines: {node: '>=18'}
content-type@3.1.1:
resolution: {integrity: sha512-GW4qUsfFo59d0HbUibDlWv5wPz+vAAcaTWbKIuKCf0JkC7wWkSyf8f13IpXn5JkeMlB2P8iTSSIjwXljorg2vA==}
engines: {node: '>=22'}
convert-source-map@2.0.0:
resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==}
@ -5552,9 +5556,9 @@ packages:
resolution: {integrity: sha512-d+l3qxjSesT4V7v2fh+QnmFnUWv9lSpjarhShNTgBOfA0ttejbQUAlHLitbjkoRiDulW0OPoQPYIGhIC8ohejg==}
engines: {node: '>=18'}
file-type@21.3.4:
resolution: {integrity: sha512-Ievi/yy8DS3ygGvT47PjSfdFoX+2isQueoYP1cntFW1JLYAuS4GD7NUPGg4zv2iZfV52uDyk5w5Z0TdpRS6Q1g==}
engines: {node: '>=20'}
file-type@22.1.1:
resolution: {integrity: sha512-sEB0oStmeLGtpmSAD88RDNuLsvhv4iC3u0lE25CUvfCULvj49xoQ3l3K525Vn+ZzsZ6DOLajQCV6RmhwwhqiJg==}
engines: {node: '>=22'}
filelist@1.0.6:
resolution: {integrity: sha512-5giy2PkLYY1cP39p17Ech+2xlpTRL9HLspOfEgm0L6CwBXBTgsK5ou0JtzYuepxkaQ/tvhCFIJ5uXo0OrM2DxA==}
@ -6795,9 +6799,9 @@ packages:
ms@2.1.3:
resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}
music-metadata@11.14.0:
resolution: {integrity: sha512-RyOSq98kuVfXB1emJ+NjBF0av8Ph3oBuqNy+Z5sFFfLhjYrkBQEB53V8u+U0RNTVwNo20WoPUwNkfKwZfrOqmQ==}
engines: {node: '>=18'}
music-metadata@12.1.0:
resolution: {integrity: sha512-qKh935MzhY8MNtn+l9cTQldYyQuAWbtbV/hcclWL1jNoiig7CvCCVRpUI4Y4QD4VoV4nz/e07uxa0AUwNz5bvA==}
engines: {node: '>=22'}
mute-stream@2.0.0:
resolution: {integrity: sha512-WWdIxpyjEn+FhQJQQv9aQAYlHoNVdzIzUySNV1gHUPDSdZJ3yZn7pAAbQcV7B56Mvu881q9FZV+0Vx2xC44VWA==}
@ -8217,8 +8221,8 @@ packages:
engines: {node: '>=16.20.0'}
hasBin: true
uint8array-extras@1.5.0:
resolution: {integrity: sha512-rvKSBiC5zqCCiDZ9kAOszZcDvdAHwwIKJG33Ykj43OKcWsnmcBRL09YTU4nOeHZ8Y2a7l1MgTd08SBe9A8Qj6A==}
uint8array-extras@1.6.0:
resolution: {integrity: sha512-8iAasVS4wUx0gPLjH8Xtz2PeDzTSiy8QiLGu2DT3X5GU+egFEQhpnbtkehbAwjvDcxIERmCYcysiODFmE3Ud0Q==}
engines: {node: '>=18'}
underscore@1.13.8:
@ -13426,6 +13430,8 @@ snapshots:
content-type@2.0.0: {}
content-type@3.1.1: {}
convert-source-map@2.0.0: {}
cookie-signature@1.2.2: {}
@ -14210,12 +14216,12 @@ snapshots:
dependencies:
is-unicode-supported: 2.1.0
file-type@21.3.4:
file-type@22.1.1:
dependencies:
'@tokenizer/inflate': 0.4.1
strtok3: 10.3.5
token-types: 6.1.2
uint8array-extras: 1.5.0
uint8array-extras: 1.6.0
transitivePeerDependencies:
- supports-color
@ -15795,17 +15801,17 @@ snapshots:
ms@2.1.3: {}
music-metadata@11.14.0:
music-metadata@12.1.0:
dependencies:
'@borewit/text-codec': 0.2.2
'@tokenizer/token': 0.3.0
content-type: 2.0.0
content-type: 3.1.1
debug: 4.4.3(supports-color@8.1.1)
file-type: 21.3.4
file-type: 22.1.1
media-typer: 2.0.0
strtok3: 10.3.5
token-types: 6.1.2
uint8array-extras: 1.5.0
uint8array-extras: 1.6.0
win-guid: 0.2.1
transitivePeerDependencies:
- supports-color
@ -17333,7 +17339,7 @@ snapshots:
'@typescript/typescript-win32-arm64': 7.0.2
'@typescript/typescript-win32-x64': 7.0.2
uint8array-extras@1.5.0: {}
uint8array-extras@1.6.0: {}
underscore@1.13.8: {}