diff --git a/lib/src/parsers/containers/mp4.dart b/lib/src/parsers/containers/mp4.dart index 572ab7e..b9b7252 100644 --- a/lib/src/parsers/containers/mp4.dart +++ b/lib/src/parsers/containers/mp4.dart @@ -73,6 +73,7 @@ final supportedBox = [ "stbl", "stsd", "mp4a", + "alac", ]; /// @@ -100,6 +101,11 @@ final supportedBox = [ /// - Normal boxes are at least 8 bytes; large-size boxes are at least 16. /// - Child boxes, including size-zero boxes, must end inside their parent. /// This gives every traversal a finite, forward-only boundary. +/// - A header that breaks these rules ends its scope: the rest of the parent +/// is skipped and what was read before it is kept. Taggers and rippers +/// append non-box bytes after `mdat` (e.g. a 256-byte `RLTP=…` trailer), +/// which must not reject a file whose `moov` is intact. Only a file whose +/// top level breaks before any `moov` is rejected. /// - `meta` may contain either a 4-byte version/flags field or child boxes /// directly; both layouts occur in valid MP4-family files in the wild. /// @@ -119,9 +125,17 @@ class MP4Parser extends TagParser { buffer = Buffer(randomAccessFile: reader); final int fileEnd = reader.lengthSync(); + bool hasMovie = false; while (buffer.fileCursor < fileEnd) { - final BoxHeader box = _readBox(buffer, limit: fileEnd); + final BoxHeader? box = _tryReadBox(buffer, limit: fileEnd); + + if (box == null) { + // Trailing bytes that are not a box: keep the metadata already read. + if (hasMovie) break; + _malformed('MP4 box exceeds its parent boundary'); + } + if (box.type == "moov") hasMovie = true; if (supportedBox.contains(box.type)) { processBox(buffer, box); @@ -145,23 +159,21 @@ class MP4Parser extends TagParser { /// [limit] is the absolute end of the current parent scope. Validating /// against it before reading a payload prevents malformed child sizes from /// seeking into a sibling box or beyond the file. - BoxHeader _readBox(Buffer buffer, {required int limit}) { + /// + /// Returns null when the bytes at the cursor cannot be a box of this scope: + /// fewer than 8 bytes left, an all-zero type, a size smaller than its + /// header or past [limit]. The cursor is then left inside the scope and the + /// caller skips to [limit]. + BoxHeader? _tryReadBox(Buffer buffer, {required int limit}) { final int start = buffer.fileCursor; - _requireBytes(start, 8, limit); + if (start < 0 || start + 8 > limit) return null; final Uint8List headerBytes = buffer.read(8); final ByteData parser = ByteData.sublistView(headerBytes); final int declaredSize = parser.getUint32(0); final Uint8List boxNameBytes = headerBytes.sublist(4); - // throw error if we don't have a correct box name - if (boxNameBytes[0] == 0 && - boxNameBytes[1] == 0 && - boxNameBytes[2] == 0 && - boxNameBytes[3] == 0) { - throw MetadataParserException( - track: File(""), message: "Malformed MP4 file"); - } + if (boxNameBytes.every((int byte) => byte == 0)) return null; int headerSize = 8; int size = declaredSize; @@ -171,17 +183,12 @@ class MP4Parser extends TagParser { // the containing box is the only legal EOF, so use its boundary. size = limit - start; } else if (declaredSize == 1) { - _requireBytes(buffer.fileCursor, 8, limit); + if (buffer.fileCursor + 8 > limit) return null; size = getUint64BE(buffer.read(8)); headerSize = 16; } - if (size < headerSize) { - _malformed('MP4 box size is smaller than its header'); - } - if (size > limit - start) { - _malformed('MP4 box exceeds its parent boundary'); - } + if (size < headerSize || size > limit - start) return null; return BoxHeader( start: start, @@ -316,27 +323,9 @@ class MP4Parser extends TagParser { } } } else if (box.type == "----") { - final BoxHeader mean = _readBox(buffer, limit: box.end); - String.fromCharCodes(buffer.read(mean.payloadSize)); // mean value - - final BoxHeader name = _readBox(buffer, limit: box.end); - - final nameValue = - String.fromCharCodes(buffer.read(name.payloadSize).sublist(4)); - final BoxHeader dataBox = _readBox(buffer, limit: box.end); - final Uint8List data = buffer.read(dataBox.payloadSize); - final finalValue = String.fromCharCodes(data.sublist(8)); - - switch (nameValue) { - case "iTunes_CDDB_TrackNumber": - tags.trackNumber = int.parse(finalValue); - break; - // case "iTunes_CDDB_TrackNumber": - // tags.trackNumber = int.parse(finalValue); - // break; - default: - } - } else if (box.type == "mp4a") { + _parseFreeformBox(buffer, box); + } else if (box.type == "mp4a" || box.type == "alac") { + // Both are audio sample entries: the sample rate sits at the same place. final Uint8List bytes = buffer.read(box.payloadSize); // tags.bitrate = timeScale; @@ -356,6 +345,33 @@ class MP4Parser extends TagParser { } } + /// Parse an iTunes freeform `----` box: `mean`, `name` then `data`. + /// + /// A malformed child only drops this box; the caller moves to its end. + void _parseFreeformBox(Buffer buffer, BoxHeader box) { + final BoxHeader? mean = _tryReadBox(buffer, limit: box.end); + if (mean == null) return; + buffer.skip(mean.payloadSize); + + final BoxHeader? name = _tryReadBox(buffer, limit: box.end); + if (name == null || name.payloadSize < 4) return; + final String nameValue = + String.fromCharCodes(buffer.read(name.payloadSize).sublist(4)); + + final BoxHeader? dataBox = _tryReadBox(buffer, limit: box.end); + if (dataBox == null || dataBox.payloadSize < 8) return; + final Uint8List data = buffer.read(dataBox.payloadSize); + final String finalValue = String.fromCharCodes(data.sublist(8)); + + switch (nameValue) { + case "iTunes_CDDB_TrackNumber": + final int? trackNumber = int.tryParse(finalValue.trim()); + if (trackNumber != null) tags.trackNumber = trackNumber; + break; + default: + } + } + /// Ensure a fixed-size field is completely inside [box]'s payload. void _requirePayloadBytes(Buffer buffer, BoxHeader box, int length) { _requireBytes(buffer.fileCursor, length, box.end); @@ -519,7 +535,14 @@ class MP4Parser extends TagParser { } while (buffer.fileCursor < box.end) { - final BoxHeader child = _readBox(buffer, limit: box.end); + final BoxHeader? child = _tryReadBox(buffer, limit: box.end); + + if (child == null) { + // Not a box of this scope: skip the rest of the parent and keep the + // children already read. + buffer.setPositionSync(box.end); + break; + } if (supportedBox.contains(child.type)) { processBox(buffer, child); diff --git a/lib/src/writers/mp4_writer.dart b/lib/src/writers/mp4_writer.dart index ad29d17..7a484f5 100644 --- a/lib/src/writers/mp4_writer.dart +++ b/lib/src/writers/mp4_writer.dart @@ -62,6 +62,9 @@ class Mp4Writer extends BaseMetadataWriter { mp4metadata = metadata; final reader = source.openSync(); final List<_TopLevelBox> boxes = <_TopLevelBox>[]; + // Non-box bytes after the last box (some taggers append a text trailer + // after `mdat`); copied unchanged, as the reader skips them. + Uint8List trailingBytes = Uint8List(0); try { final lengthFile = reader.lengthSync(); @@ -69,11 +72,18 @@ class Mp4Writer extends BaseMetadataWriter { while (reader.positionSync() < lengthFile) { final int boxStart = reader.positionSync(); final Uint8List headerBytes = reader.readSync(8); - final BoxHeader box = _readBox(headerBytes); - final int bodyLength = box.size - 8; - - if (bodyLength > lengthFile - reader.positionSync()) { - throw const FormatException("MP4 box extends beyond the file"); + final BoxHeader? box = _tryReadBox(headerBytes); + final int bodyLength = (box?.size ?? 0) - 8; + + if (box == null || bodyLength > lengthFile - reader.positionSync()) { + if (boxes.any((_TopLevelBox box) => box.header.type == "moov")) { + reader.setPositionSync(boxStart); + trailingBytes = reader.readSync(lengthFile - boxStart); + break; + } + throw FormatException(box == null + ? "Malformed MP4 box header" + : "MP4 box extends beyond the file"); } final Uint8List boxData = reader.readSync(bodyLength); @@ -128,6 +138,7 @@ class Mp4Writer extends BaseMetadataWriter { outputBuilder.add(_serializeBox(box.header.type, outputData)); } + outputBuilder.add(trailingBytes); destination.writeAsBytesSync(outputBuilder.takeBytes()); } @@ -474,6 +485,16 @@ class Mp4Writer extends BaseMetadataWriter { return tagBuilder.toBytes(); } + /// Same as [_readBox], but returns null when [headerBytes] cannot be a box + /// header (for instance, a text trailer appended after the last box). + BoxHeader? _tryReadBox(Uint8List headerBytes) { + try { + return _readBox(headerBytes); + } on FormatException { + return null; + } + } + /// A box (or atom) header uses 8 bytes /// /// [0...3] -> box size (header + body) diff --git a/test/mp4/mp4_test.dart b/test/mp4/mp4_test.dart index 64df20e..cd2bfde 100644 --- a/test/mp4/mp4_test.dart +++ b/test/mp4/mp4_test.dart @@ -4,6 +4,7 @@ import 'dart:typed_data'; import 'package:audio_metadata_reader/src/metadata/base.dart'; import 'package:audio_metadata_reader/src/parser.dart'; +import 'package:audio_metadata_reader/src/parsers/tags/tag_parser.dart'; import 'package:audio_metadata_reader/src/utils/metadata_parser_exception.dart'; import 'package:test/test.dart'; @@ -31,6 +32,19 @@ void main() { expect(result.genres.length, equals(1)); expect(result.genres.first, equals("Rock")); }); + test("Read the sample rate of an ALAC (Apple Lossless) file", () { + // ALAC audio is described by an `alac` sample entry instead of `mp4a` + // (AAC). Both share the same AudioSampleEntry layout, so the sample rate + // sits at the same place. The fixture is generated once with ffmpeg: + // + // ffmpeg -f lavfi -i anullsrc=r=48000:cl=stereo -t 1 -c:a alac \ + // -metadata title="ALAC title" test/mp4/track_alac.m4a + final File track = File('./test/mp4/track_alac.m4a'); + final AudioMetadata result = readMetadata(track, getImage: false); + + expect(result.title, equals("ALAC title")); + expect(result.sampleRate, equals(48000)); + }); test("Parse MP4 file and the cover", () { final track = File('./test/mp4/track.m4a'); final result = readMetadata(track, getImage: true); @@ -143,14 +157,16 @@ void main() { expect(() => readMetadata(file, getImage: false), returnsNormally); }); - test("Reject a child box that exceeds its parent boundary", () { + test("Skip a child box that exceeds its parent boundary", () { // The `free` header declares 16 bytes, but only its 8-byte header fits in - // `moov`. A parser must not treat bytes after `moov` as this child's data. + // `moov`. The parser must not read bytes after `moov` as this child's + // data: it drops the rest of `moov` and keeps what it read before. final File file = createTemporaryFile( 'mp4_child_exceeds_parent.m4a', Uint8List.fromList([ ..._fileTypeBox(), ..._makeBox('moov', [ + ..._metadataBox({'\u00a9nam': 'Title'}), ..._u32(16), ...ascii.encode('free'), ]), @@ -158,6 +174,81 @@ void main() { ); addTearDown(() => file.deleteSync()); + expect(readMetadata(file, getImage: false).title, 'Title'); + }); + + test("Keep the tags read before a malformed tag box", () { + final File file = createTemporaryFile( + 'mp4_malformed_tag.m4a', + Uint8List.fromList([ + ..._fileTypeBox(), + ..._makeBox('moov', [ + ..._metadataBox( + {'\u00a9nam': 'Title', '\u00a9ART': 'Artist'}, + // A tag header whose size runs past `ilst`. + trailer: [..._u32(4096), 0xa9, ...ascii.encode('alb')], + ), + ]), + ]), + ); + addTearDown(() => file.deleteSync()); + + final AudioMetadata result = readMetadata(file, getImage: false); + expect(result.title, 'Title'); + expect(result.artist, 'Artist'); + expect(result.album, isNull); + }); + + test( + "Parse an M4A whose audio is followed by bytes that are not a box", + () { + // Layout of iTunes-style ALAC files seen in the wild: ftyp, moov + // (udta > meta > hdlr + ilst, then free), free, mdat, then a 256-byte + // `RLTP=…|` text trailer padded with zeros. The trailer reads as a box + // of 1,380,734,032 bytes (`RLTP`) typed `=0|4`, far past the file end. + final Uint8List trailer = Uint8List(256) + ..setAll(0, ascii.encode('RLTP=0|4|||43||Cold|/0|60:-1:100:24:0::0|')); + final File file = createTemporaryFile( + 'mp4_trailing_non_box_bytes.m4a', + Uint8List.fromList([ + ..._fileTypeBox(), + ..._makeBox('moov', [ + ..._makeBox('mvhd', _movieHeader(timeScale: 44100, units: 441000)), + ..._metadataBox( + { + '\u00a9nam': 'Soy El Mismo', + '\u00a9ART': 'Artist', + '\u00a9alb': 'Album', + }, + trailer: _makeBox('free', List.filled(32, 0)), + ), + ]), + ..._makeBox('free', List.filled(64, 0)), + ..._makeBox('mdat', List.filled(1024, 0x55)), + ...trailer, + ]), + ); + addTearDown(() => file.deleteSync()); + + final AudioMetadata result = readMetadata(file, getImage: false); + expect(result.title, 'Soy El Mismo'); + expect(result.artist, 'Artist'); + expect(result.album, 'Album'); + expect(result.duration, const Duration(seconds: 10)); + }, + ); + + test("Reject a file whose top level breaks before any moov box", () { + final File file = createTemporaryFile( + 'mp4_garbage_before_moov.m4a', + Uint8List.fromList([ + ..._fileTypeBox(), + ...ascii.encode('RLTP=0|4|||43||'), + ...List.filled(64, 0), + ]), + ); + addTearDown(() => file.deleteSync()); + expect( () => readMetadata(file, getImage: false), throwsA(isA()), @@ -165,6 +256,59 @@ void main() { }); } +/// `udta` > `meta` (full box) > `hdlr` + `ilst` holding text [tags], with +/// [trailer] appended after `ilst` inside `meta`, or inside `ilst` when it is +/// not a complete box list (see the tests). +Uint8List _metadataBox(Map tags, + {List trailer = const []}) { + final BytesBuilder items = BytesBuilder(); + for (final entry in tags.entries) { + final Uint8List dataBox = _makeBox('data', [ + ..._u32(1), // UTF-8 text + ..._u32(0), // locale + ...utf8.encode(entry.value), + ]); + items.add(_makeRawTypeBox(entry.key, dataBox)); + } + final bool trailerIsBoxList = trailer.isEmpty || + ByteData.sublistView(Uint8List.fromList(trailer)).getUint32(0) == + trailer.length; + if (!trailerIsBoxList) items.add(trailer); + final Uint8List hdlr = _makeBox('hdlr', [ + ..._u32(0), + ..._u32(0), + ...ascii.encode('mdir'), + ...ascii.encode('appl'), + ..._u32(0), + ..._u32(0), + 0, + ]); + final Uint8List meta = _makeBox('meta', [ + ..._u32(0), // version + flags + ...hdlr, + ..._makeBox('ilst', items.toBytes()), + if (trailerIsBoxList) ...trailer, + ]); + return _makeBox('udta', meta); +} + +/// A box whose type may hold the `©` byte (0xA9), as iTunes tags do. +Uint8List _makeRawTypeBox(String type, List payload) { + return Uint8List.fromList([ + ..._u32(payload.length + 8), + ...type.codeUnits.map((int unit) => unit & 0xff), + ...payload, + ]); +} + +/// A version 0 `mvhd` payload (100 bytes) with the given duration. +Uint8List _movieHeader({required int timeScale, required int units}) { + final ByteData data = ByteData(100); + data.setUint32(12, timeScale); + data.setUint32(16, units); + return data.buffer.asUint8List(); +} + File _copyTrackWithFinalZeroSizedFreeBox() { final File fixture = File('./test/mp4/track.m4a'); final BytesBuilder bytes = BytesBuilder(copy: false) diff --git a/test/mp4/track_alac.m4a b/test/mp4/track_alac.m4a new file mode 100644 index 0000000..b530264 Binary files /dev/null and b/test/mp4/track_alac.m4a differ diff --git a/test/writers/mp4_writer_test.dart b/test/writers/mp4_writer_test.dart index 490a10f..20ba45c 100644 --- a/test/writers/mp4_writer_test.dart +++ b/test/writers/mp4_writer_test.dart @@ -57,6 +57,26 @@ void main() { contains('deliberately much longer')); }); + test('keeps non-box bytes that follow the last box', () { + final Directory directory = Directory.systemTemp.createTempSync(); + addTearDown(() => directory.deleteSync(recursive: true)); + + // Some taggers append a 256-byte `RLTP=…` text trailer after `mdat`. + final Uint8List trailer = Uint8List(256) + ..setAll(0, ascii.encode('RLTP=0|4|||43||Cold|/0|60:-1:100|')); + final File target = File('${directory.path}/writer_trailer.m4a') + ..writeAsBytesSync([ + ...File('test/mp4/writer_source.m4a').readAsBytesSync(), + ...trailer, + ]); + + Mp4Writer().write(target, Mp4Metadata(title: 'Edited title')); + + final Uint8List after = target.readAsBytesSync(); + expect(after.sublist(after.length - trailer.length), equals(trailer)); + expect(readMetadata(target, getImage: false).title, 'Edited title'); + }); + test('keeps siblings after a full-box meta atom aligned', () { final Directory directory = Directory.systemTemp.createTempSync(); addTearDown(() => directory.deleteSync(recursive: true));