diff --git a/CHANGELOG.md b/CHANGELOG.md index e5434da9..5618fcda 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - MP4 QuickTime metadata whose `meta` handler is `mdta` is read and written through its `keys` atom, in `moov/udta/meta` (where ffmpeg's `-movflags use_metadata_tags` writes it) and in `moov/meta` (where QuickTime and Apple devices write it). The handler and each key's namespace are checked first ([QTFF metadata handler atom](https://developer.apple.com/documentation/quicktime-file-format/metadata_handler_atom)). Apple's `com.apple.quicktime.*` keys that have a property (title, displayname, artist, album, comment, composer, copyright, description, encodedby, genre, publisher, year, software, keywords, artwork), ffmpeg's names (title, artist, album, album_artist, composer, date, comment, genre, copyright, description, grouping, lyrics, encoder, encoded_by, publisher, the five sort_* fields, category, keywords, track and disc as `n/m`, compilation, gapless_playback, podcast, rating) and every other name as a freeform field (com.apple.iTunes, or org.musicbrainz for the MusicBrainz names; another mean is written as `mean:name`) map to their properties, and a `udta`-namespace key to its atom. A set replaces every item its field was read from (keyed items, an iTunes atom a lenient writer such as mutagen added beside them, and items the reader could not take, such as a vinyl track `A1`) with one item at the field's key index, where the first one was; a field with no key gets one named the way the file names its keys. No iTunes atom is written into an `mdta` meta; one found there is kept until its field is set, and it wins over the keyed item because it is the newer edit. An unedited save writes every item back as it was, in order. A `moov/meta` beside `udta/meta` (an ffmpeg file that Apple software or ExifTool gave keys) is merged in and wins for the fields it declares, since QTFF gives metadata precedence over user data that declares the same information; AVFoundation reads it the same way. A set writes the new value where the winning value lives and drops the other meta's copy. A damaged `keys` atom maps nothing and is kept as it is. TagLib# and mutagen do not read keyed items. +- `AudibleFile` and `AudibleTag` read and write Audible `.aa` audiobooks: the text dictionary (title, author, narrator, provider, dates, descriptions, keywords, copyright, short and parent titles, product and title IDs, and any other key through `GetValue`/`SetValue`), the cover image, and the duration. A save rewrites the dictionary and moves every table-of-contents offset, the declared file size, and the cover position by the change in its size. The encrypted audio and the DRM keys are copied unchanged; `SetValue` refuses `codec`, `HeaderSeed`, `HeaderKey`, and `EncryptedBlocks`, and `Clear` keeps them. `MediaFormat.Audible` and `TagTypes.Audible` are new, and `.aa` is detected by its magic or extension. Edited `.aa` files have been checked with ffprobe, ffmpeg, and ExifTool, not with Audible's own apps, which may check a digest the file stores; keep a copy of the original or save to a new path. +- `.aax` opens as MP4 by extension as well as by content. `Mp4Tag` and `Mp4File` gain `Narrator` (`©nrt`), `ShortTitle` (`@sti`), `ParentTitle` (`@pti`), `ParentShortTitle` (`@PST`), `ParentProductId` (`@ppi`), `ProductId` (`prID`), `ReleaseDate` (`rldt`), and `ProductVersion` (`VERS`). An Audible `aavd` sample entry reports AAC. ### Fixed diff --git a/README.md b/README.md index b3bffc32..d1258bc7 100644 --- a/README.md +++ b/README.md @@ -26,6 +26,7 @@ See the [Migration Guide](docs/MIGRATION-FROM-TAGLIB.md) for detailed comparison - **Format Support**: - Audio: MP3 (ID3v1/ID3v2), FLAC, Ogg Vorbis, Ogg Opus, Ogg FLAC, WAV (RIFF INFO/ID3v2), AIFF (ID3v2), MP4/M4A (AAC/ALAC), ASF/WMA, DSF (DSD), DFF (DSDIFF), WavPack, Monkey's Audio (.ape), Musepack - Matroska/WebM (`.mkv`, `.mka`, `.mks`, `.mk3d`, `.webm`): tags, duration, audio and video properties, and pictures. Tag values can be saved. Picture attachments are read but not rewritten. + - Audible `.aa`: the text dictionary (title, author, narrator, dates, descriptions, and every other key by name), the cover image, and the duration. Dictionary edits can be saved; the encrypted audio, its DRM keys, and the cover are copied unchanged. Edited files have been checked with ffprobe, ffmpeg, and ExifTool, not with Audible's own apps, which may check a digest the file stores (the purpose of the `68ec733412b9` key is unknown). Keep a copy of the original, or save to a new path. Audible `.aax` is MPEG-4 and opens as MP4/M4A, with its audiobook atoms (narrator, short and parent titles, product IDs, release date) as named properties. Decryption is out of scope. ## Format Support Matrix @@ -72,6 +73,8 @@ See the [Migration Guide](docs/MIGRATION-FROM-TAGLIB.md) for detailed comparison | WavPack | APE tag | — | Native only | | Monkey's Audio | APE tag | — | Native only | | Musepack | APE tag | — | Native only | +| Audible .aa | Audible dictionary (chunk 2) | — | Native only | +| Audible .aax | iTunes atoms (ilst) | — | Native only | ## Installation diff --git a/docs/MIGRATION-FROM-TAGLIB.md b/docs/MIGRATION-FROM-TAGLIB.md index cd31a279..bb737214 100644 --- a/docs/MIGRATION-FROM-TAGLIB.md +++ b/docs/MIGRATION-FROM-TAGLIB.md @@ -554,6 +554,33 @@ if (result.IsSuccess) } ``` +### Audible Files (.aa, .aax) + +An `.aa` file has its own container with a key/value text dictionary. `.aax` is MPEG-4 and opens as `Mp4File`. + +```csharp +var result = AudibleFile.ReadFromFile("book.aa"); +if (result.IsSuccess) +{ + var aa = result.File!; + Console.WriteLine($"{aa.Tag.Title} by {aa.Tag.Author}, read by {aa.Tag.Narrator}"); + Console.WriteLine($"Duration: {aa.Properties.Duration}, codec: {aa.Tag.Codec}"); + + // Any dictionary key by name. DRM keys (codec, HeaderSeed, HeaderKey, EncryptedBlocks) cannot be changed. + Console.WriteLine(aa.Tag.GetValue("pub_date_start")); + aa.Tag.Narrator = "New Narrator"; + aa.SaveToFile(); // rewrites the dictionary; the encrypted audio is copied unchanged +} + +var aax = Mp4File.ReadFromFile("book.aax").File!; +Console.WriteLine($"{aax.Narrator} / {aax.ProductId} / {aax.ReleaseDate}"); +``` + +Differences from TagLib# for `.aa` (observed by running TagLib# 2.3 on the same files): + +- TagLib# reports the `provider` key as `Album` and `AlbumArtists`, and a duration of 0. TagLibSharp2 reports `Album` as null, `Artist` as the `author` key, the provider as `AudibleTag.Provider`, and the duration from the audio chunk size and codec. +- TagLib#'s save leaves an `.aa` file unchanged. TagLibSharp2 writes the dictionary. Edited files have been checked with ffprobe, ffmpeg, and ExifTool, not with Audible's own apps, which may check a digest the file stores. Keep a copy of the original, or save to a new path. + ### Musepack Files Musepack (.mpc) is a lossy audio format with excellent quality at low bitrates. It uses APE tags. @@ -643,7 +670,7 @@ if (result.IsSuccess) TagLibSharp2 includes several features not available in TagLib#: -- **Automatic format detection**: `MediaFile.Read()` auto-detects 16 formats: MP3, FLAC, Ogg Vorbis, Ogg Opus, Ogg FLAC, WAV, AIFF, MP4/M4A, ASF/WMA, DSF, DFF, WavPack, Monkey's Audio, Musepack, and Matroska/WebM +- **Automatic format detection**: `MediaFile.Read()` auto-detects MP3, FLAC, Ogg Vorbis, Ogg Opus, Ogg FLAC, WAV, AIFF, MP4/M4A (including Audible .aax), ASF/WMA, DSF, DFF, WavPack, Monkey's Audio, Musepack, Matroska/WebM, and Audible .aa - **DSD audio support**: Native DSF and DFF format support for high-resolution DSD audio - **Lossless format breadth**: WavPack and Monkey's Audio support with APE tag handling - **Async I/O**: Full async support throughout the API with cancellation token support diff --git a/src/TagLibSharp2/Audible/AudibleFile.cs b/src/TagLibSharp2/Audible/AudibleFile.cs new file mode 100644 index 00000000..c0c3fc43 --- /dev/null +++ b/src/TagLibSharp2/Audible/AudibleFile.cs @@ -0,0 +1,836 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using TagLibSharp2.Core; + +#pragma warning disable CA1513 // Use ObjectDisposedException.ThrowIf (not available in netstandard) + +namespace TagLibSharp2.Audible; + +/// +/// Represents the result of parsing an Audible .aa file. +/// +public readonly struct AudibleFileReadResult : IEquatable +{ + /// + /// Gets the parsed file, or null if parsing failed. + /// + public AudibleFile? File { get; } + + /// + /// Gets the error message if parsing failed, or null if successful. + /// + public string? Error { get; } + + /// + /// Gets a value indicating whether parsing was successful. + /// + public bool IsSuccess => File is not null && Error is null; + + AudibleFileReadResult (AudibleFile? file, string? error) + { + File = file; + Error = error; + } + + /// + /// Creates a successful parse result. + /// + /// The parsed file. + /// A successful result containing the file. + public static AudibleFileReadResult Success (AudibleFile file) => new (file, null); + + /// + /// Creates a failed parse result. + /// + /// The error message describing the failure. + /// A failed result containing the error. + public static AudibleFileReadResult Failure (string error) => new (null, error); + + /// + public bool Equals (AudibleFileReadResult other) => + Equals (File, other.File) && Error == other.Error; + + /// + public override bool Equals (object? obj) => + obj is AudibleFileReadResult other && Equals (other); + + /// + public override int GetHashCode () => HashCode.Combine (File, Error); + + /// + /// Determines whether two results are equal. + /// + public static bool operator == (AudibleFileReadResult left, AudibleFileReadResult right) => + left.Equals (right); + + /// + /// Determines whether two results are not equal. + /// + public static bool operator != (AudibleFileReadResult left, AudibleFileReadResult right) => + !left.Equals (right); +} + +/// +/// Represents an Audible .aa audiobook file: its text dictionary, cover image, and duration. +/// +/// +/// +/// There is no published specification. The layout below follows the prose description at +/// https://wiki.multimedia.cx/index.php?title=Audible_Audio (revision of 14 May 2025), checked byte by +/// byte against three real files (two ACELP.net, one MP3) and against what ffprobe reports for them. +/// All integers are big-endian. +/// +/// +/// offset 0 u32 file size, including this field +/// offset 4 u32 magic 0x57907536 +/// offset 8 u32 table-of-contents entry count (12 in every file seen) +/// offset 12 u32 unknown (0 in every file seen), kept as is +/// offset 16 count x { u32 type, u32 offset, u32 size } +/// +/// +/// Chunk types: 0 is the whole file (offset 0, size = file size). 2 is the text dictionary +/// (). 6 is the chapter and seek table, whose offsets are relative to the +/// audio. 10 is the encrypted audio. 11 is the cover: u32 image length, u32 file position of the image +/// (the next byte), then the image. The other chunks are opaque and are copied unchanged. +/// +/// +/// Duration is the size of chunk 10 in bits divided by the bit rate the codec key names +/// (acelp85 8500 bit/s, acelp16 16000 bit/s, mp332 32000 bit/s). This matches +/// ffprobe's duration on all three real files to the microsecond. +/// +/// +/// A save rewrites only the dictionary. Every table-of-contents offset at or after the dictionary moves +/// by the change in its size, the whole-file entry and the header file size grow or shrink by the same +/// amount, and the cover's image position moves with it. Every other byte, including the encrypted +/// audio and its DRM keys, is copied unchanged. Decryption is out of scope. +/// +/// +/// Edited files have been checked with ffprobe, ffmpeg, and ExifTool, which read the new values back. +/// They have not been tested with Audible's own apps. The file carries a 40-hex-digit value under the +/// key 68ec733412b9 and 40 opaque bytes in chunk 3 whose purpose is not published; if an app +/// checks either against the dictionary, it may refuse an edited file. Keep a copy of the original, or +/// save to a new path. +/// +/// +public sealed class AudibleFile : IMediaFile +{ + /// The magic value at offset 4. + public const uint Magic = 0x57907536; + + /// Table-of-contents chunk type of the whole file. + internal const uint WholeFileChunk = 0; + + /// Table-of-contents chunk type of the text dictionary. + internal const uint DictionaryChunk = 2; + + /// Table-of-contents chunk type of the encrypted audio. + internal const uint AudioChunk = 10; + + /// Table-of-contents chunk type of the cover image. + internal const uint CoverChunk = 11; + + const int HeaderSize = 16; + const int TocEntrySize = 12; + + // No real file has more than a dozen entries. The cap bounds the TOC read. + internal const int MaxTocEntries = 1024; + + // Real dictionaries are a few kilobytes and covers tens of kilobytes. The caps bound a stream read. + internal const int MaxDictionarySize = 16 * 1024 * 1024; + internal const int MaxCoverSize = 16 * 1024 * 1024; + + byte[]? _originalData; + bool _disposed; + IFileSystem? _sourceFileSystem; + Layout _layout; + + AudibleFile (Layout layout, AudibleTag tag, AudioProperties properties) + { + _layout = layout; + Tag = tag; + Properties = properties; + } + + /// + /// Gets the path to the source file, if available. + /// + public string? SourcePath { get; private set; } + + /// + /// Gets the text dictionary. + /// + public AudibleTag Tag { get; } + + /// + /// Gets the audio properties derived from the codec key and the audio chunk size. + /// + public AudioProperties Properties { get; } + + /// + /// Gets the file size the header declares. It is larger than the file when the file is truncated. + /// + public uint DeclaredFileSize => _layout.DeclaredSize; + + /// + Tag? IMediaFile.Tag => Tag; + + /// + IMediaProperties? IMediaFile.AudioProperties => Properties; + + /// + VideoProperties? IMediaFile.VideoProperties => null; + + /// + ImageProperties? IMediaFile.ImageProperties => null; + + /// + MediaTypes IMediaFile.MediaTypes => Properties.Duration > TimeSpan.Zero ? MediaTypes.Audio : MediaTypes.None; + + /// + public MediaFormat Format => MediaFormat.Audible; + + /// + /// Checks whether the data starts with an Audible .aa header. + /// + /// The first bytes of the file (at least 8). + /// True if the magic value is at offset 4. + public static bool IsValidFormat (ReadOnlySpan data) => + data.Length >= 8 && BinaryPrimitives.ReadUInt32BigEndian (data.Slice (4)) == Magic; + + /// + /// Parses an Audible .aa file from its bytes. + /// + /// The file data. + /// The parsed file, or a failure for malformed input. + /// + /// A file truncated after the dictionary still reads; its duration comes from the table of contents. + /// + public static AudibleFileReadResult Read (ReadOnlySpan data) + { + var layout = ParseLayout (data, data.Length, out var error); + if (layout is null) + return AudibleFileReadResult.Failure (error!); + + var dictionary = layout.Toc[layout.DictionaryIndex]; + var cover = CoverSpan (layout, data.Length); + var result = Build (layout, + data.Slice ((int)dictionary.Offset, (int)dictionary.Size), + cover.Length > 0 ? data.Slice ((int)cover.Offset, cover.Length) : default, + cover.Offset); + if (result.IsSuccess) + result.File!._originalData = data.ToArray (); + return result; + } + + /// + /// Reads the header, table of contents, dictionary, and cover. The audio stays on disk. + /// + internal static AudibleFileReadResult Read (Stream stream, string? sourcePath, IFileSystem? fileSystem) + { + if (!stream.CanSeek) { + var copied = Read (StreamBytes.ReadToEnd (stream)); + if (sourcePath is not null && copied.IsSuccess) + copied.File!._originalData = null; + return WithSource (copied, sourcePath, fileSystem); + } + + stream.Position = 0; + var header = StreamBytes.ReadAtMost (stream, HeaderSize); + var tocBytes = TocBytes (header); + if (tocBytes > header.Length) { + stream.Position = 0; + header = StreamBytes.ReadAtMost (stream, tocBytes); + } + + var layout = ParseLayout (header, stream.Length, out var error); + if (layout is null) + return AudibleFileReadResult.Failure (error!); + + var dictionaryEntry = layout.Toc[layout.DictionaryIndex]; + stream.Position = dictionaryEntry.Offset; + var dictionary = StreamBytes.ReadAtMost (stream, (int)dictionaryEntry.Size); + var cover = CoverSpan (layout, stream.Length); + var coverBytes = Array.Empty (); + if (cover.Length > 0) { + stream.Position = cover.Offset; + coverBytes = StreamBytes.ReadAtMost (stream, cover.Length); + } + + return WithSource (Build (layout, dictionary, coverBytes, cover.Offset), sourcePath, fileSystem); + } + + /// + /// Reads the header, table of contents, dictionary, and cover asynchronously. The audio stays on disk. + /// + internal static async Task ReadAsync ( + Stream stream, + string? sourcePath, + IFileSystem? fileSystem, + CancellationToken cancellationToken) + { + if (!stream.CanSeek) { + var copied = Read (await StreamBytes.ReadToEndAsync (stream, cancellationToken).ConfigureAwait (false)); + if (sourcePath is not null && copied.IsSuccess) + copied.File!._originalData = null; + return WithSource (copied, sourcePath, fileSystem); + } + + stream.Position = 0; + var header = await StreamBytes.ReadAtMostAsync (stream, HeaderSize, cancellationToken).ConfigureAwait (false); + var tocBytes = TocBytes (header); + if (tocBytes > header.Length) { + stream.Position = 0; + header = await StreamBytes.ReadAtMostAsync (stream, tocBytes, cancellationToken).ConfigureAwait (false); + } + + var layout = ParseLayout (header, stream.Length, out var error); + if (layout is null) + return AudibleFileReadResult.Failure (error!); + + var dictionaryEntry = layout.Toc[layout.DictionaryIndex]; + stream.Position = dictionaryEntry.Offset; + var dictionary = await StreamBytes.ReadAtMostAsync (stream, (int)dictionaryEntry.Size, cancellationToken).ConfigureAwait (false); + var cover = CoverSpan (layout, stream.Length); + var coverBytes = Array.Empty (); + if (cover.Length > 0) { + stream.Position = cover.Offset; + coverBytes = await StreamBytes.ReadAtMostAsync (stream, cover.Length, cancellationToken).ConfigureAwait (false); + } + + return WithSource (Build (layout, dictionary, coverBytes, cover.Offset), sourcePath, fileSystem); + } + + // Bytes of header plus TOC that a header claims, capped so a hostile count cannot size a read. + static int TocBytes (ReadOnlySpan header) + { + if (header.Length < HeaderSize) + return header.Length; + var count = BinaryPrimitives.ReadUInt32BigEndian (header.Slice (8)); + return count is 0 or > MaxTocEntries ? header.Length : HeaderSize + ((int)count * TocEntrySize); + } + + static AudibleFileReadResult WithSource (AudibleFileReadResult result, string? sourcePath, IFileSystem? fileSystem) + { + if (result.IsSuccess) { + result.File!.SourcePath = sourcePath; + result.File._sourceFileSystem = fileSystem; + } + return result; + } + + /// + /// Attempts to read an Audible .aa file from its bytes. + /// + /// The file data. + /// When successful, contains the parsed file. + /// True if parsing succeeded; otherwise, false. + public static bool TryRead (ReadOnlySpan data, out AudibleFile? file) + { + var result = Read (data); + file = result.File; + return result.IsSuccess; + } + + /// + /// Reads an Audible .aa file from disk. Only the header, dictionary, and cover are read. + /// + /// The path to the file. + /// Optional file system abstraction for testing. + /// A result containing the parsed file or an error. + public static AudibleFileReadResult ReadFromFile (string path, IFileSystem? fileSystem = null) + { + var fs = fileSystem ?? DefaultFileSystem.Instance; + if (!fs.FileExists (path)) + return AudibleFileReadResult.Failure ($"File not found: {path}"); + try { + using var stream = fs.OpenRead (path); + return Read (stream, path, fs); + } catch (IOException ex) { + return AudibleFileReadResult.Failure ($"Failed to read file: {ex.Message}"); + } catch (UnauthorizedAccessException ex) { + return AudibleFileReadResult.Failure ($"Access denied: {ex.Message}"); + } + } + + /// + /// Reads an Audible .aa file from disk asynchronously. Only the header, dictionary, and cover are read. + /// + /// The path to the file. + /// Optional file system abstraction for testing. + /// A token to cancel the operation. + /// A task containing a result with the parsed file or an error. + public static async Task ReadFromFileAsync ( + string path, + IFileSystem? fileSystem = null, + CancellationToken cancellationToken = default) + { + var fs = fileSystem ?? DefaultFileSystem.Instance; + if (!fs.FileExists (path)) + return AudibleFileReadResult.Failure ($"File not found: {path}"); + try { + using var stream = fs.OpenRead (path); + return await ReadAsync (stream, path, fs, cancellationToken).ConfigureAwait (false); + } catch (IOException ex) { + return AudibleFileReadResult.Failure ($"Failed to read file: {ex.Message}"); + } catch (UnauthorizedAccessException ex) { + return AudibleFileReadResult.Failure ($"Access denied: {ex.Message}"); + } catch (OperationCanceledException) { + return AudibleFileReadResult.Failure ("Operation was cancelled"); + } + } + + readonly record struct TocEntry (uint Type, uint Offset, uint Size) + { + public ulong End => (ulong)Offset + Size; + } + + sealed class Layout (uint declaredSize, TocEntry[] toc, int dictionaryIndex, int tocEnd) + { + public uint DeclaredSize { get; } = declaredSize; + public TocEntry[] Toc { get; } = toc; + public int DictionaryIndex { get; } = dictionaryIndex; + public int TocEnd { get; } = tocEnd; + + public bool SameAs (Layout other) + { + if (DeclaredSize != other.DeclaredSize || DictionaryIndex != other.DictionaryIndex || Toc.Length != other.Toc.Length) + return false; + for (var i = 0; i < Toc.Length; i++) { + if (Toc[i] != other.Toc[i]) + return false; + } + return true; + } + } + + // Parses the header and table of contents. data holds at least the header and TOC; fileLength is + // the real length, which bounds the dictionary. + static Layout? ParseLayout (ReadOnlySpan data, long fileLength, out string? error) + { + error = null; + if (data.Length < HeaderSize) { + error = $"Data too short for an Audible header: {data.Length} bytes, need {HeaderSize}"; + return null; + } + if (!IsValidFormat (data)) { + error = "Not an Audible .aa file: magic 0x57907536 not found at offset 4"; + return null; + } + + var declaredSize = BinaryPrimitives.ReadUInt32BigEndian (data); + var count = BinaryPrimitives.ReadUInt32BigEndian (data.Slice (8)); + if (count is 0 or > MaxTocEntries) { + error = $"Audible table of contents has {count} entries"; + return null; + } + + var tocEnd = HeaderSize + ((int)count * TocEntrySize); + if (data.Length < tocEnd) { + error = $"Audible table of contents is truncated: {count} entries need {tocEnd} bytes, have {data.Length}"; + return null; + } + + var toc = new TocEntry[count]; + var dictionaryIndex = -1; + for (var i = 0; i < toc.Length; i++) { + var at = HeaderSize + (i * TocEntrySize); + toc[i] = new TocEntry ( + BinaryPrimitives.ReadUInt32BigEndian (data.Slice (at)), + BinaryPrimitives.ReadUInt32BigEndian (data.Slice (at + 4)), + BinaryPrimitives.ReadUInt32BigEndian (data.Slice (at + 8))); + if (dictionaryIndex < 0 && toc[i].Type == DictionaryChunk) + dictionaryIndex = i; + } + + if (dictionaryIndex < 0) { + error = "Audible table of contents has no dictionary chunk (type 2)"; + return null; + } + + var dictionary = toc[dictionaryIndex]; + if (dictionary.Offset < tocEnd) { + error = $"Audible dictionary at {dictionary.Offset} overlaps the table of contents"; + return null; + } + if (dictionary.End > (ulong)fileLength) { + error = $"Audible dictionary ends at {dictionary.End}, past the end of the file ({fileLength} bytes)"; + return null; + } + if (dictionary.Size > MaxDictionarySize) { + error = $"Audible dictionary claims {dictionary.Size} bytes"; + return null; + } + + return new Layout (declaredSize, toc, dictionaryIndex, tocEnd); + } + + // The cover chunk's bytes that are in the file and small enough to read, or an empty span. + static (uint Offset, int Length) CoverSpan (Layout layout, long fileLength) + { + foreach (var entry in layout.Toc) { + if (entry.Type != CoverChunk) + continue; + if (entry.Size < 8 || entry.Size > MaxCoverSize || entry.End > (ulong)fileLength || entry.Offset < layout.TocEnd) + return (0, 0); + return (entry.Offset, (int)entry.Size); + } + return (0, 0); + } + + static AudibleFileReadResult Build (Layout layout, ReadOnlySpan dictionary, ReadOnlySpan cover, uint coverOffset) + { + var parsed = AudibleTag.Parse (dictionary); + if (!parsed.IsSuccess) + return AudibleFileReadResult.Failure (parsed.Error!); + + var tag = parsed.Tag!; + var picture = ParseCover (cover, coverOffset); + if (picture is not null) + tag.SetPictures ([picture]); + + return AudibleFileReadResult.Success (new AudibleFile (layout, tag, ComputeProperties (layout, tag.Codec))); + } + + // Cover chunk: u32 image length, u32 file position of the image, then the image. + static AudibleCoverPicture? ParseCover (ReadOnlySpan chunk, uint chunkOffset) + { + if (chunk.Length < 8) + return null; + + var length = BinaryPrimitives.ReadUInt32BigEndian (chunk); + var position = BinaryPrimitives.ReadUInt32BigEndian (chunk.Slice (4)); + if (position < (ulong)chunkOffset + 8) + return null; + var start = position - chunkOffset; + if (start > (uint)chunk.Length || length > (uint)chunk.Length - start || length == 0) + return null; + + return new AudibleCoverPicture (chunk.Slice ((int)start, (int)length).ToArray ()); + } + + static AudioProperties ComputeProperties (Layout layout, string? codec) + { + var (bitsPerSecond, sampleRate, channels, name) = codec?.ToUpperInvariant () switch { + "ACELP85" => (8500, 8000, 1, "ACELP.net"), + "ACELP16" => (16000, 16000, 1, "ACELP.net"), + "MP332" => (32000, 22050, 0, "MP3"), + _ => (0, 0, 0, (string?)codec) + }; + + var audioBytes = 0UL; + foreach (var entry in layout.Toc) { + if (entry.Type == AudioChunk) { + audioBytes = entry.Size; + break; + } + } + + var duration = bitsPerSecond > 0 + ? TimeSpan.FromTicks ((long)(audioBytes * 8UL * TimeSpan.TicksPerSecond / (ulong)bitsPerSecond)) + : TimeSpan.Zero; + return new AudioProperties (duration, bitsPerSecond / 1000, sampleRate, 0, channels, name); + } + + /// + /// Renders the file with the current dictionary. + /// + /// The original file bytes, including the audio. + /// The new file bytes, or when is not the file this object was read from or the new sizes do not fit in 32 bits. + /// The object has been disposed. + /// + /// Only the dictionary chunk changes. A dictionary that renders to the same bytes gives back the original bytes. + /// + public BinaryData Render (ReadOnlySpan originalData) + { + if (_disposed) + throw new ObjectDisposedException (nameof (AudibleFile)); + + var layout = ParseLayout (originalData, originalData.Length, out _); + if (layout is null || !layout.SameAs (_layout)) + return BinaryData.Empty; + + var dictionary = layout.Toc[layout.DictionaryIndex]; + var newDictionary = Tag.Render (); + var delta = (long)newDictionary.Length - dictionary.Size; + var dictionaryEnd = dictionary.End; + + var newDeclared = (long)layout.DeclaredSize + delta; + if (newDeclared is < 0 or > uint.MaxValue) + return BinaryData.Empty; + + var tailLength = originalData.Length - (int)dictionaryEnd; + var output = new byte[(long)dictionary.Offset + newDictionary.Length + tailLength]; + originalData.Slice (0, (int)dictionary.Offset).CopyTo (output); + newDictionary.Span.CopyTo (output.AsSpan ((int)dictionary.Offset)); + originalData.Slice ((int)dictionaryEnd).CopyTo (output.AsSpan ((int)dictionary.Offset + newDictionary.Length)); + + BinaryPrimitives.WriteUInt32BigEndian (output, (uint)newDeclared); + for (var i = 0; i < layout.Toc.Length; i++) { + var entry = layout.Toc[i]; + long offset = entry.Offset; + long size = entry.Size; + if (i == layout.DictionaryIndex) { + size = newDictionary.Length; + } else if ((ulong)entry.Offset >= dictionaryEnd) { + offset += delta; + if (entry.Type == CoverChunk && !MoveCoverPosition (output, entry, delta)) + return BinaryData.Empty; + } else if (entry.Offset <= dictionary.Offset && entry.End >= dictionaryEnd) { + size += delta; + } else if (entry.End > dictionary.Offset) { + // Starts before the dictionary and ends inside it: the shift would split it. + return BinaryData.Empty; + } + + // Neither goes below zero: a moved offset was at least the old dictionary end, and a grown or shrunk + // size belongs to an entry that contains the dictionary. Both are 32-bit fields in the file. + if (offset + size > uint.MaxValue) + return BinaryData.Empty; + + var at = HeaderSize + (i * TocEntrySize); + BinaryPrimitives.WriteUInt32BigEndian (output.AsSpan (at + 4), (uint)offset); + BinaryPrimitives.WriteUInt32BigEndian (output.AsSpan (at + 8), (uint)size); + } + + return new BinaryData (output); + } + + // The cover's image position is an absolute file offset into its own chunk, so it moves with the chunk. + // A chunk past the end of a truncated file is not in the output and has nothing to patch. + static bool MoveCoverPosition (byte[] output, TocEntry entry, long delta) + { + var newOffset = entry.Offset + delta; + if (entry.Size < 8 || newOffset + 8 > output.Length) + return true; + + var at = (int)newOffset + 4; + var position = BinaryPrimitives.ReadUInt32BigEndian (output.AsSpan (at)); + if (position < entry.Offset || position > entry.End) + return true; + + var moved = position + delta; + if (moved is < 0 or > uint.MaxValue) + return false; + BinaryPrimitives.WriteUInt32BigEndian (output.AsSpan (at), (uint)moved); + return true; + } + + /// + /// Saves the file to the specified path using atomic write. + /// + /// The target file path. + /// The original file bytes, including the audio. + /// Optional file system abstraction for testing. + /// A result indicating success or failure. + public FileWriteResult SaveToFile (string path, ReadOnlySpan originalData, IFileSystem? fileSystem = null) + { + if (_disposed) + throw new ObjectDisposedException (nameof (AudibleFile)); + + var rendered = Render (originalData); + if (rendered.IsEmpty) + return FileWriteResult.Failure ("Failed to render Audible file: the original data does not match the file that was read"); + + var fs = fileSystem ?? _sourceFileSystem; + var result = AtomicFileWriter.Write (path, rendered.Span, fs); + if (result.IsSuccess && Rendered (rendered) is { } layout && SourcePath is not null) + RefreshLayout (layout, ReadSourceHeader (fs)); + return result; + } + + // The next save re-reads the source and checks it against _layout. When this save rewrote the + // source, under any spelling of its path (".", "..", case, a link), the source's header and TOC are + // now the rendered ones, so the check is made against what is on disk, not against the path string. + static Layout? Rendered (BinaryData rendered) => ParseLayout (rendered.Span, rendered.Length, out _); + + void RefreshLayout (Layout rendered, (byte[] Header, long Length)? source) + { + if (source is not { } read) + return; + var onDisk = ParseLayout (read.Header, read.Length, out _); + if (onDisk is not null && onDisk.SameAs (rendered)) + _layout = onDisk; + } + + (byte[] Header, long Length)? ReadSourceHeader (IFileSystem? fileSystem) + { + try { + using var stream = (fileSystem ?? DefaultFileSystem.Instance).OpenRead (SourcePath!); + var header = StreamBytes.ReadAtMost (stream, HeaderSize); + var tocBytes = TocBytes (header); + if (tocBytes > header.Length) { + stream.Position = 0; + header = StreamBytes.ReadAtMost (stream, tocBytes); + } + return (header, stream.Length); + } catch (Exception ex) when (IsReadBackFailure (ex)) { + return null; + } + } + + // The read-back runs after the atomic rename has committed the save, so nothing it meets may turn that + // success into a failure: it does not observe the caller's token, and a failed read only skips the refresh. + static bool IsReadBackFailure (Exception ex) => + ex is IOException or UnauthorizedAccessException or NotSupportedException or ArgumentException + or OperationCanceledException or InvalidOperationException; // InvalidOperation covers ObjectDisposed + + async Task<(byte[] Header, long Length)?> ReadSourceHeaderAsync (IFileSystem? fileSystem) + { + try { + using var stream = (fileSystem ?? DefaultFileSystem.Instance).OpenRead (SourcePath!); + var header = await StreamBytes.ReadAtMostAsync (stream, HeaderSize, CancellationToken.None).ConfigureAwait (false); + var tocBytes = TocBytes (header); + if (tocBytes > header.Length) { + stream.Position = 0; + header = await StreamBytes.ReadAtMostAsync (stream, tocBytes, CancellationToken.None).ConfigureAwait (false); + } + return (header, stream.Length); + } catch (Exception ex) when (IsReadBackFailure (ex)) { + return null; + } + } + + /// + /// Saves the file to the specified path asynchronously using atomic write. + /// + /// The target file path. + /// The original file bytes, including the audio. + /// Optional file system abstraction for testing. + /// A token to cancel the operation. + /// A task containing a result indicating success or failure. + public async Task SaveToFileAsync ( + string path, + ReadOnlyMemory originalData, + IFileSystem? fileSystem = null, + CancellationToken cancellationToken = default) + { + if (_disposed) + throw new ObjectDisposedException (nameof (AudibleFile)); + + cancellationToken.ThrowIfCancellationRequested (); + var rendered = Render (originalData.Span); + if (rendered.IsEmpty) + return FileWriteResult.Failure ("Failed to render Audible file: the original data does not match the file that was read"); + + var fs = fileSystem ?? _sourceFileSystem; + var result = await AtomicFileWriter.WriteAsync (path, rendered.Memory, fs, cancellationToken).ConfigureAwait (false); + if (result.IsSuccess && Rendered (rendered) is { } layout && SourcePath is not null) + RefreshLayout (layout, await ReadSourceHeaderAsync (fs).ConfigureAwait (false)); + return result; + } + + /// + /// Saves the file to the specified path, copying the audio from the data or source file it was read from. + /// + /// The target file path. + /// Optional file system abstraction for testing. + /// A result indicating success or failure. + public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null) + { + if (_disposed) + throw new ObjectDisposedException (nameof (AudibleFile)); + + var fs = fileSystem ?? _sourceFileSystem; + if (_originalData is not null) + return SaveToFile (path, _originalData, fs); + if (string.IsNullOrEmpty (SourcePath)) + return FileWriteResult.Failure ("No source path available. File was not read from disk."); + + var read = FileHelper.SafeReadAllBytes (SourcePath!, fs); + if (!read.IsSuccess) + return FileWriteResult.Failure ($"Failed to re-read source file: {read.Error}"); + return SaveToFile (path, read.Data!.Value.Span, fs); + } + + /// + /// Saves the file back to its source path. + /// + /// Optional file system abstraction for testing. + /// A result indicating success or failure. + public FileWriteResult SaveToFile (IFileSystem? fileSystem = null) + { + if (_disposed) + throw new ObjectDisposedException (nameof (AudibleFile)); + if (string.IsNullOrEmpty (SourcePath)) + return FileWriteResult.Failure ("No source path available. File was not read from disk."); + return SaveToFile (SourcePath!, fileSystem); + } + + /// + /// Saves the file to the specified path asynchronously, copying the audio from the data or source file it was read from. + /// + /// The target file path. + /// Optional file system abstraction for testing. + /// A token to cancel the operation. + /// A task containing a result indicating success or failure. + public async Task SaveToFileAsync ( + string path, + IFileSystem? fileSystem = null, + CancellationToken cancellationToken = default) + { + if (_disposed) + throw new ObjectDisposedException (nameof (AudibleFile)); + + var fs = fileSystem ?? _sourceFileSystem; + if (_originalData is not null) + return await SaveToFileAsync (path, _originalData, fs, cancellationToken).ConfigureAwait (false); + if (string.IsNullOrEmpty (SourcePath)) + return FileWriteResult.Failure ("No source path available. File was not read from disk."); + + var read = await FileHelper.SafeReadAllBytesAsync (SourcePath!, fs, cancellationToken).ConfigureAwait (false); + if (!read.IsSuccess) + return FileWriteResult.Failure ($"Failed to re-read source file: {read.Error}"); + return await SaveToFileAsync (path, read.Data!.Value, fs, cancellationToken).ConfigureAwait (false); + } + + /// + /// Saves the file back to its source path asynchronously. + /// + /// Optional file system abstraction for testing. + /// A token to cancel the operation. + /// A task containing a result indicating success or failure. + public Task SaveToFileAsync ( + IFileSystem? fileSystem = null, + CancellationToken cancellationToken = default) + { + if (_disposed) + throw new ObjectDisposedException (nameof (AudibleFile)); + if (string.IsNullOrEmpty (SourcePath)) + return Task.FromResult (FileWriteResult.Failure ("No source path available. File was not read from disk.")); + return SaveToFileAsync (SourcePath!, fileSystem, cancellationToken); + } + + /// + /// Releases the retained original data. + /// + /// + /// After disposal, and the save methods throw . + /// + public void Dispose () + { + if (_disposed) + return; + + _originalData = null; + _sourceFileSystem = null; + _disposed = true; + } +} + +/// +/// The cover image stored in an Audible .aa cover chunk. +/// +sealed class AudibleCoverPicture (byte[] data) : Picture +{ + readonly BinaryData _data = new (data); + + public override string MimeType { get; } = DetectMimeType (data); + + public override PictureType PictureType => PictureType.FrontCover; + + public override string Description => string.Empty; + + public override BinaryData PictureData => _data; +} diff --git a/src/TagLibSharp2/Audible/AudibleTag.cs b/src/TagLibSharp2/Audible/AudibleTag.cs new file mode 100644 index 00000000..0d1c258c --- /dev/null +++ b/src/TagLibSharp2/Audible/AudibleTag.cs @@ -0,0 +1,483 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using System.Text; +using TagLibSharp2.Core; + +namespace TagLibSharp2.Audible; + +/// +/// The text metadata dictionary of an Audible .aa file (table-of-contents chunk type 2). +/// +/// +/// +/// Layout, all integers big-endian: +/// +/// +/// u32 count +/// count x { u8 0x00, u32 keyLength, u32 valueLength, key bytes, value bytes } +/// +/// +/// Keys are ASCII and values are UTF-8, with no terminator and no padding. Entries keep their +/// file order, their leading byte, and their exact value bytes, so a save that changes nothing +/// writes the same bytes back. +/// +/// +/// There is no published specification for .aa. This layout is the one described in prose at +/// https://wiki.multimedia.cx/index.php?title=Audible_Audio (revision of 14 May 2025), and it was +/// confirmed byte by byte on three real files, whose key/value pairs match what ffprobe reports +/// for the same files. +/// +/// +/// Some keys carry the DRM state the player needs to decrypt the audio (codec, +/// HeaderSeed, HeaderKey, EncryptedBlocks). refuses to +/// change them and keeps them, along with every other key it does not know. +/// +/// +public sealed class AudibleTag : Tag +{ + /// Dictionary key for the title. + public const string TitleKey = "title"; + + /// Dictionary key for the author. + public const string AuthorKey = "author"; + + /// Dictionary key for the narrator. + public const string NarratorKey = "narrator"; + + /// Dictionary key for the content provider. + public const string ProviderKey = "provider"; + + /// Dictionary key for the publication date (for example 20-JAN-2009). + public const string PublishDateKey = "pubdate"; + + /// Dictionary key for the short description. + public const string DescriptionKey = "description"; + + /// Dictionary key for the long description. + public const string LongDescriptionKey = "long_description"; + + /// Dictionary key for the keywords. + public const string KeywordsKey = "keywords"; + + /// Dictionary key for the copyright notice. + public const string CopyrightKey = "copyright"; + + /// Dictionary key for the short title. + public const string ShortTitleKey = "short_title"; + + /// Dictionary key for the parent (series or collection) title. + public const string ParentTitleKey = "parent_title"; + + /// Dictionary key for the parent short title. + public const string ParentShortTitleKey = "parent_short_title"; + + /// Dictionary key for the product identifier. + public const string ProductIdKey = "product_id"; + + /// Dictionary key for the title identifier. + public const string TitleIdKey = "title_id"; + + /// Dictionary key for the codec name (acelp85, acelp16, mp332). + public const string CodecKey = "codec"; + + /// Dictionary key for the price. + public const string PriceKey = "price"; + + /// Dictionary key for the publication start date. + public const string PublishDateStartKey = "pub_date_start"; + + /// Dictionary key for the short description variant. + public const string ShortDescriptionKey = "short_description"; + + // The audio cannot be decrypted without these. + static readonly HashSet ProtectedKeys = new (StringComparer.Ordinal) { + CodecKey, "HeaderSeed", "HeaderKey", "EncryptedBlocks" + }; + + // Clear() removes only these descriptive keys. Identifiers, licensing, and unknown keys stay. + static readonly string[] DescriptiveKeys = [ + TitleKey, AuthorKey, NarratorKey, ProviderKey, PriceKey, PublishDateKey, PublishDateStartKey, + DescriptionKey, ShortDescriptionKey, LongDescriptionKey, KeywordsKey, CopyrightKey, + ShortTitleKey, ParentTitleKey, ParentShortTitleKey + ]; + + // Each entry is a dictionary record in file order: the leading byte, the key, and the raw value bytes. + readonly List _entries = []; + IPicture[] _pictures = []; + + // Bytes after the last entry but inside the chunk. None of the real files has any; they are kept + // so that an unchanged save stays byte-identical. + byte[] _trailer = []; + + // The key's own bytes are kept so a non-ASCII key in a damaged file is written back unchanged. + sealed class Entry (byte lead, byte[] keyBytes, byte[] value) + { + public byte Lead { get; } = lead; + public byte[] KeyBytes { get; } = keyBytes; + public string Key { get; } = Encoding.ASCII.GetString (keyBytes); + public byte[] Value { get; set; } = value; + } + + /// + /// Creates an empty dictionary. + /// + public AudibleTag () + { + } + + /// + public override TagTypes TagType => TagTypes.Audible; + + /// + /// Stored under title. + public override string? Title { + get => GetValue (TitleKey); + set => SetValue (TitleKey, value); + } + + /// + /// Stored under author. + public override string? Artist { + get => GetValue (AuthorKey); + set => SetValue (AuthorKey, value); + } + + /// + /// Gets or sets the author. Same as . + /// + public string? Author { + get => GetValue (AuthorKey); + set => SetValue (AuthorKey, value); + } + + /// + /// Gets or sets the narrator (narrator). + /// + public string? Narrator { + get => GetValue (NarratorKey); + set => SetValue (NarratorKey, value); + } + + /// + /// Gets or sets the content provider (provider). + /// + public string? Provider { + get => GetValue (ProviderKey); + set => SetValue (ProviderKey, value); + } + + /// + /// Gets or sets the publication date exactly as stored (pubdate, for example 20-JAN-2009). + /// + public string? PublishDate { + get => GetValue (PublishDateKey); + set => SetValue (PublishDateKey, value); + } + + /// + /// Gets or sets the long description (long_description). + /// + public string? LongDescription { + get => GetValue (LongDescriptionKey); + set => SetValue (LongDescriptionKey, value); + } + + /// + /// Gets or sets the keywords (keywords). + /// + public string? Keywords { + get => GetValue (KeywordsKey); + set => SetValue (KeywordsKey, value); + } + + /// + /// Gets or sets the short title (short_title). + /// + public string? ShortTitle { + get => GetValue (ShortTitleKey); + set => SetValue (ShortTitleKey, value); + } + + /// + /// Gets or sets the parent title (parent_title). + /// + public string? ParentTitle { + get => GetValue (ParentTitleKey); + set => SetValue (ParentTitleKey, value); + } + + /// + /// Gets or sets the parent short title (parent_short_title). + /// + public string? ParentShortTitle { + get => GetValue (ParentShortTitleKey); + set => SetValue (ParentShortTitleKey, value); + } + + /// + /// Gets or sets the product identifier (product_id). + /// + public string? ProductId { + get => GetValue (ProductIdKey); + set => SetValue (ProductIdKey, value); + } + + /// + /// Gets or sets the title identifier (title_id). + /// + public string? TitleId { + get => GetValue (TitleIdKey); + set => SetValue (TitleIdKey, value); + } + + /// + /// Gets the codec name (codec). It describes the encrypted payload and cannot be changed. + /// + public string? Codec => GetValue (CodecKey); + + /// + /// The dictionary has no album key. This returns null and ignores a value. + public override string? Album { + get => null; + set { } + } + + /// + /// + /// The year at the end of pubdate. Setting a four-digit year keeps the day and month + /// of a DD-MON-YYYY date. Any other value is stored in pubdate as given. + /// + public override string? Year { + get { + var date = PublishDate; + if (date is null || date.Length < 4) + return null; + var year = date.Substring (date.Length - 4); + return IsFourDigits (year) ? year : null; + } + set { + var date = PublishDate; + if (value is not null && IsFourDigits (value) && date is { Length: 11 } && date[2] == '-' && date[6] == '-') + PublishDate = date.Remove (7) + value; + else + PublishDate = value; + } + } + + static bool IsFourDigits (string value) => + value.Length == 4 && char.IsDigit (value[0]) && char.IsDigit (value[1]) && char.IsDigit (value[2]) && char.IsDigit (value[3]); + + /// + /// The dictionary has no comment key. This returns null and ignores a value. See . + public override string? Comment { + get => null; + set { } + } + + /// + /// The dictionary has no genre key. This returns null and ignores a value. + public override string? Genre { + get => null; + set { } + } + + /// + /// The dictionary has no track key. This returns null and ignores a value. + public override uint? Track { + get => null; + set { } + } + + /// + /// Stored under description. + public override string? Description { + get => GetValue (DescriptionKey); + set => SetValue (DescriptionKey, value); + } + + /// + /// Stored under copyright, as written by Audible (it may contain HTML entities such as &#169;). + public override string? Copyright { + get => GetValue (CopyrightKey); + set => SetValue (CopyrightKey, value); + } + + /// + /// + /// The cover image from table-of-contents chunk type 11, when the file has one. It is read-only: + /// a value set here is ignored and the cover chunk is saved unchanged. + /// +#pragma warning disable CA1819 // Properties should not return arrays - TagLib# API compatibility + public override IPicture[] Pictures { + get => _pictures; + set { } + } +#pragma warning restore CA1819 + + /// + /// Gets the dictionary keys in file order. + /// + public IReadOnlyList Keys { + get { + var keys = new List (_entries.Count); + foreach (var entry in _entries) + keys.Add (entry.Key); + return keys; + } + } + + /// + /// Gets the value stored under a key, decoded as UTF-8. + /// + /// The key, compared case-sensitively. + /// The first value for the key, or null when the key is absent. + public string? GetValue (string key) + { + var entry = Find (key); + return entry is null ? null : Encoding.UTF8.GetString (entry.Value); + } + + /// + /// Sets, adds, or removes the value stored under a key. + /// + /// The key, ASCII, compared case-sensitively. + /// The value, or null or empty to remove the key. + /// The key is empty, not ASCII, or carries DRM state (codec, HeaderSeed, HeaderKey, EncryptedBlocks). + /// + /// An existing key keeps its position. A new key is appended. Later duplicates of the key are removed. + /// + public void SetValue (string key, string? value) + { + if (string.IsNullOrEmpty (key)) + throw new ArgumentException ("Key must not be empty.", nameof (key)); + foreach (var c in key) { + if (c > 0x7F) + throw new ArgumentException ("Key must be ASCII.", nameof (key)); + } + if (ProtectedKeys.Contains (key)) + throw new ArgumentException ($"'{key}' is needed to decrypt the audio and cannot be changed.", nameof (key)); + + var index = _entries.FindIndex (e => e.Key == key); + if (string.IsNullOrEmpty (value)) { + _entries.RemoveAll (e => e.Key == key); + return; + } + + var bytes = Encoding.UTF8.GetBytes (value); + if (index < 0) { + _entries.Add (new Entry (0, Encoding.ASCII.GetBytes (key), bytes)); + return; + } + + _entries[index].Value = bytes; + for (var i = _entries.Count - 1; i > index; i--) { + if (_entries[i].Key == key) + _entries.RemoveAt (i); + } + } + + Entry? Find (string key) + { + foreach (var entry in _entries) { + if (entry.Key == key) + return entry; + } + return null; + } + + /// + /// True when none of the descriptive keys that removes is present. + public override bool IsEmpty { + get { + foreach (var key in DescriptiveKeys) { + if (Find (key) is not null) + return false; + } + return true; + } + } + + /// + /// + /// Removes the descriptive keys (title, author, narrator, provider, price, dates, descriptions, + /// keywords, copyright, and the short and parent titles). Identifiers, licensing and DRM keys, + /// and unknown keys stay, so the audio can still be decrypted. The cover chunk is not changed. + /// + public override void Clear () + { + foreach (var key in DescriptiveKeys) + _entries.RemoveAll (e => e.Key == key); + } + + internal void SetPictures (IPicture[] pictures) => _pictures = pictures; + + /// + /// Parses a dictionary chunk. + /// + /// The chunk bytes, starting at the entry count. + /// The parsed dictionary, or a failure when a count or length runs past the chunk. + public static TagReadResult Parse (ReadOnlySpan data) + { + if (data.Length < 4) + return TagReadResult.Failure ("Audible dictionary is shorter than its entry count"); + + var count = BinaryPrimitives.ReadUInt32BigEndian (data); + // Every entry is at least 9 bytes, so a count the chunk cannot hold is rejected before the loop. + if (count > (uint)(data.Length - 4) / 9) + return TagReadResult.Failure ($"Audible dictionary claims {count} entries in {data.Length} bytes"); + + var tag = new AudibleTag (); + var offset = 4; + for (var i = 0u; i < count; i++) { + if (data.Length - offset < 9) + return TagReadResult.Failure ($"Audible dictionary entry {i} is truncated"); + + var lead = data[offset]; + var keyLength = BinaryPrimitives.ReadUInt32BigEndian (data.Slice (offset + 1)); + var valueLength = BinaryPrimitives.ReadUInt32BigEndian (data.Slice (offset + 5)); + offset += 9; + var remaining = (uint)(data.Length - offset); + if (keyLength > remaining || valueLength > remaining - keyLength) + return TagReadResult.Failure ($"Audible dictionary entry {i} runs past the chunk"); + + var key = data.Slice (offset, (int)keyLength).ToArray (); + offset += (int)keyLength; + var value = data.Slice (offset, (int)valueLength).ToArray (); + offset += (int)valueLength; + tag._entries.Add (new Entry (lead, key, value)); + } + + tag._trailer = data.Slice (offset).ToArray (); + return TagReadResult.Success (tag, offset); + } + + /// + /// Renders the dictionary chunk: the entry count, then every entry in order, then any bytes that followed the entries when it was read. + public override BinaryData Render () + { + var size = 4L + _trailer.Length; + foreach (var entry in _entries) + size += 9L + entry.KeyBytes.Length + entry.Value.Length; + if (size > int.MaxValue) + throw new InvalidOperationException ("Audible dictionary is too large to render."); + + var output = new byte[size]; + BinaryPrimitives.WriteUInt32BigEndian (output, (uint)_entries.Count); + var offset = 4; + foreach (var entry in _entries) { + output[offset] = entry.Lead; + BinaryPrimitives.WriteUInt32BigEndian (output.AsSpan (offset + 1), (uint)entry.KeyBytes.Length); + BinaryPrimitives.WriteUInt32BigEndian (output.AsSpan (offset + 5), (uint)entry.Value.Length); + offset += 9; + entry.KeyBytes.CopyTo (output, offset); + offset += entry.KeyBytes.Length; + entry.Value.CopyTo (output, offset); + offset += entry.Value.Length; + } + _trailer.CopyTo (output, offset); + + return new BinaryData (output); + } +} diff --git a/src/TagLibSharp2/Core/MediaFile.cs b/src/TagLibSharp2/Core/MediaFile.cs index b4696001..1007be40 100644 --- a/src/TagLibSharp2/Core/MediaFile.cs +++ b/src/TagLibSharp2/Core/MediaFile.cs @@ -5,6 +5,7 @@ using TagLibSharp2.Aiff; using TagLibSharp2.Ape; using TagLibSharp2.Asf; +using TagLibSharp2.Audible; using TagLibSharp2.Dff; using TagLibSharp2.Dsf; using TagLibSharp2.Matroska; @@ -38,6 +39,7 @@ namespace TagLibSharp2.Core; /// DFF/DSDIFF (DSD Interchange File Format - ID3v2 metadata) /// WMA/ASF (Windows Media Audio - ASF extended content) /// Matroska/WebM (Matroska tags) +/// Audible .aa (text dictionary). Audible .aax is MPEG-4 and opens as MP4. /// /// /// Reading and Modifying Tags @@ -398,6 +400,7 @@ static async Task ReadAsync ( MediaFormat.Mp3 => FromMp3 (await Mp3File.ReadAsync (stream, cancellationToken).ConfigureAwait (false)), MediaFormat.Flac => FromFlac (await FlacFile.ReadAsync (stream, cancellationToken).ConfigureAwait (false)), MediaFormat.Wav => FromWav (WavFile.Read (stream, sourcePath, fileSystem)), + MediaFormat.Audible => FromAudible (await AudibleFile.ReadAsync (stream, sourcePath, fileSystem, cancellationToken).ConfigureAwait (false)), _ => OpenDetected (format, stream, sourcePath, fileSystem, pathHint) }; return RememberMatroskaSource (result, sourcePath, fileSystem); @@ -420,6 +423,7 @@ static MediaFileResult OpenDetected (MediaFormat format, Stream stream, string? MediaFormat.Dsf => FromDsf (DsfFile.Read (stream, sourcePath, fileSystem)), MediaFormat.Dff => FromDff (DffFile.Read (stream, sourcePath, fileSystem)), MediaFormat.Asf => FromAsf (AsfFile.Read (stream, sourcePath, fileSystem)), + MediaFormat.Audible => FromAudible (AudibleFile.Read (stream, sourcePath, fileSystem)), _ => ReadFromData (StreamBytes.ReadToEnd (stream), pathHint) }; @@ -529,6 +533,13 @@ static MediaFileResult FromAsf (AsfFileReadResult result) return MediaFileResult.Success (result.File, result.File.Tag, MediaFormat.Asf); } + static MediaFileResult FromAudible (AudibleFileReadResult result) + { + if (!result.IsSuccess || result.File is null) + return MediaFileResult.Failure (result.Error ?? "Failed to parse Audible file"); + return MediaFileResult.Success (result.File, result.File.Tag, MediaFormat.Audible); + } + static MediaFileResult FromWav (WavFileReadResult result) { if (!result.IsSuccess || result.File is null) @@ -569,6 +580,7 @@ static MediaFileResult ReadCore (ReadOnlyMemory data, string? pathHint) MediaFormat.Asf => OpenAsf (data), MediaFormat.Musepack => OpenMusepack (data), MediaFormat.Matroska => OpenMatroska (data), + MediaFormat.Audible => FromAudible (AudibleFile.Read (data.Span)), _ => MediaFileResult.Failure ($"Unknown or unsupported file format{(pathHint is not null ? $": {pathHint}" : "")}") }; @@ -648,6 +660,10 @@ public static MediaFormat DetectFormat (ReadOnlySpan data, string? pathHin data[2] == MusepackSV8Magic[2] && data[3] == MusepackSV8Magic[3]) return MediaFormat.Musepack; + // Audible .aa: file size, then the magic 0x57907536 at offset 4 + if (AudibleFile.IsValidFormat (data)) + return MediaFormat.Audible; + // Musepack SV7: starts with "MP+" if (data[0] == MusepackSV7Magic[0] && data[1] == MusepackSV7Magic[1] && data[2] == MusepackSV7Magic[2]) @@ -679,7 +695,8 @@ public static MediaFormat DetectFormat (ReadOnlySpan data, string? pathHin ".MP3" => MediaFormat.Mp3, ".WAV" => MediaFormat.Wav, ".AIF" or ".AIFF" or ".AIFC" => MediaFormat.Aiff, - ".M4A" or ".M4B" or ".M4P" or ".M4V" or ".MP4" => MediaFormat.Mp4, + ".M4A" or ".M4B" or ".M4P" or ".M4V" or ".MP4" or ".AAX" => MediaFormat.Mp4, + ".AA" => MediaFormat.Audible, ".DSF" => MediaFormat.Dsf, ".DFF" => MediaFormat.Dff, ".WV" => MediaFormat.WavPack, @@ -1030,5 +1047,10 @@ public enum MediaFormat /// /// Matroska and WebM (.mkv, .mka, .mks, .mk3d, .webm). /// - Matroska + Matroska, + + /// + /// Audible audiobook (.aa). Audible .aax files are MPEG-4 and report . + /// + Audible } diff --git a/src/TagLibSharp2/Core/Tag.cs b/src/TagLibSharp2/Core/Tag.cs index 5eb98911..e2f72daf 100644 --- a/src/TagLibSharp2/Core/Tag.cs +++ b/src/TagLibSharp2/Core/Tag.cs @@ -67,6 +67,11 @@ public enum TagTypes /// Xmp = 1 << 9, + /// + /// Audible .aa text dictionary. + /// + Audible = 1 << 10, + /// /// All tag types. /// diff --git a/src/TagLibSharp2/Mp4/Mp4AtomMapping.cs b/src/TagLibSharp2/Mp4/Mp4AtomMapping.cs index a63bd400..64a35d24 100644 --- a/src/TagLibSharp2/Mp4/Mp4AtomMapping.cs +++ b/src/TagLibSharp2/Mp4/Mp4AtomMapping.cs @@ -53,6 +53,8 @@ internal static class Mp4AtomMapping DescriptionAlias, "aART", "trkn", "disk", "tmpo", "cpil", "pgap", "rtng", "covr", "soal", "soaa", "soar", "soco", "sonm", "©mvn", "©mvi", "©mvc", "©wrk", "shwm", "purl", "egid", "catg", "keyw", "pcst", "©pub", "©enc", "desc", "ldes", + Narrator, AudibleShortTitle, AudibleParentTitle, AudibleParentShortTitle, + AudibleParentProductId, AudibleProductId, AudibleReleaseDate, AudibleProductVersion, }; /// @@ -105,6 +107,17 @@ internal static class Mp4AtomMapping public const string Description = "desc"; public const string LongDescription = "ldes"; + // Audiobook atoms written by Audible in .aax files. The atom codes are the ones ExifTool names + // (exiftool -listx -QuickTime:ItemList:all); '@' is a literal 0x40, not the 0xA9 copyright sign. + public const string Narrator = "©nrt"; + public const string AudibleShortTitle = "@sti"; + public const string AudibleParentTitle = "@pti"; + public const string AudibleParentShortTitle = "@PST"; + public const string AudibleParentProductId = "@ppi"; + public const string AudibleProductId = "prID"; + public const string AudibleReleaseDate = "rldt"; + public const string AudibleProductVersion = "VERS"; + // Freeform metadata namespace public const string FreeformAtom = "----"; public const string FreeformMean = "mean"; diff --git a/src/TagLibSharp2/Mp4/Mp4AudioPropertiesParser.cs b/src/TagLibSharp2/Mp4/Mp4AudioPropertiesParser.cs index 5eef4af3..b40f28c6 100644 --- a/src/TagLibSharp2/Mp4/Mp4AudioPropertiesParser.cs +++ b/src/TagLibSharp2/Mp4/Mp4AudioPropertiesParser.cs @@ -299,7 +299,7 @@ private static AudioProperties ParseSampleDescription (ReadOnlySpan stsdDa var codec = System.Text.Encoding.ASCII.GetString (entryType); var codecSpecificData = entryData.Slice (28); - if (codec == "mp4a") { + if (codec is "mp4a" or "aavd") { // AAC - look for esds box return ParseMp4aEntry (codecSpecificData, duration, channels, sampleSize, sampleRateFromEntry); } else if (codec == "alac") { diff --git a/src/TagLibSharp2/Mp4/Mp4File.cs b/src/TagLibSharp2/Mp4/Mp4File.cs index 61b727e3..580c371e 100644 --- a/src/TagLibSharp2/Mp4/Mp4File.cs +++ b/src/TagLibSharp2/Mp4/Mp4File.cs @@ -574,6 +574,70 @@ public string? PodcastKeywords { set => EnsureTag ().PodcastKeywords = value; } + /// + /// Gets or sets the narrator ("©nrt", written by Audible in .aax files). + /// + public string? Narrator { + get => Tag?.Narrator; + set => EnsureTag ().Narrator = value; + } + + /// + /// Gets or sets the short title ("@sti", written by Audible in .aax files). + /// + public string? ShortTitle { + get => Tag?.ShortTitle; + set => EnsureTag ().ShortTitle = value; + } + + /// + /// Gets or sets the parent (series or collection) title ("@pti", written by Audible in .aax files). + /// + public string? ParentTitle { + get => Tag?.ParentTitle; + set => EnsureTag ().ParentTitle = value; + } + + /// + /// Gets or sets the parent short title ("@PST", written by Audible in .aax files). + /// + public string? ParentShortTitle { + get => Tag?.ParentShortTitle; + set => EnsureTag ().ParentShortTitle = value; + } + + /// + /// Gets or sets the parent product identifier ("@ppi", written by Audible in .aax files). + /// + public string? ParentProductId { + get => Tag?.ParentProductId; + set => EnsureTag ().ParentProductId = value; + } + + /// + /// Gets or sets the product identifier ("prID", written by Audible in .aax files). + /// + public string? ProductId { + get => Tag?.ProductId; + set => EnsureTag ().ProductId = value; + } + + /// + /// Gets or sets the release date, as stored (for example 02-Jul-2012) ("rldt", written by Audible in .aax files). + /// + public string? ReleaseDate { + get => Tag?.ReleaseDate; + set => EnsureTag ().ReleaseDate = value; + } + + /// + /// Gets or sets the product version ("VERS", written by Audible in .aax files). + /// + public string? ProductVersion { + get => Tag?.ProductVersion; + set => EnsureTag ().ProductVersion = value; + } + /// /// Gets or sets the content rating (Clean/Explicit/None). /// @@ -837,7 +901,8 @@ static string ExtractFileType (Mp4Box ftypBox) // + samplerate(4, 16.16 fixed) var codecType = entryData.Slice (4, 4).ToStringLatin1 (); codec = codecType switch { - "mp4a" => Mp4AudioCodec.Aac, + // Audible .aax stores AAC in an "aavd" entry: the mp4a layout, esds included, with encrypted samples. + "mp4a" or "aavd" => Mp4AudioCodec.Aac, "alac" => Mp4AudioCodec.Alac, "fLaC" => Mp4AudioCodec.Flac, "Opus" => Mp4AudioCodec.Opus, diff --git a/src/TagLibSharp2/Mp4/Mp4Tag.cs b/src/TagLibSharp2/Mp4/Mp4Tag.cs index 1a18ff5d..2197dbbc 100644 --- a/src/TagLibSharp2/Mp4/Mp4Tag.cs +++ b/src/TagLibSharp2/Mp4/Mp4Tag.cs @@ -650,6 +650,94 @@ public string? PodcastKeywords { set => SetText (Mp4AtomMapping.Keywords, value); } + /// + /// Gets or sets the narrator. + /// + /// + /// Uses the "©nrt" atom that Audible writes in .aax audiobooks. ExifTool reports it as Narrator. + /// + public string? Narrator { + get => GetText (Mp4AtomMapping.Narrator); + set => SetText (Mp4AtomMapping.Narrator, value); + } + + /// + /// Gets or sets the short title. + /// + /// + /// Uses the "@sti" atom that Audible writes in .aax audiobooks. ExifTool reports it as ShortTitle. + /// + public string? ShortTitle { + get => GetText (Mp4AtomMapping.AudibleShortTitle); + set => SetText (Mp4AtomMapping.AudibleShortTitle, value); + } + + /// + /// Gets or sets the parent (series or collection) title. + /// + /// + /// Uses the "@pti" atom that Audible writes in .aax audiobooks. ExifTool reports it as ParentTitle. + /// + public string? ParentTitle { + get => GetText (Mp4AtomMapping.AudibleParentTitle); + set => SetText (Mp4AtomMapping.AudibleParentTitle, value); + } + + /// + /// Gets or sets the parent short title. + /// + /// + /// Uses the "@PST" atom that Audible writes in .aax audiobooks. ExifTool reports it as ParentShortTitle. + /// + public string? ParentShortTitle { + get => GetText (Mp4AtomMapping.AudibleParentShortTitle); + set => SetText (Mp4AtomMapping.AudibleParentShortTitle, value); + } + + /// + /// Gets or sets the parent product identifier. + /// + /// + /// Uses the "@ppi" atom that Audible writes in .aax audiobooks. ExifTool reports it as ParentProductID. + /// + public string? ParentProductId { + get => GetText (Mp4AtomMapping.AudibleParentProductId); + set => SetText (Mp4AtomMapping.AudibleParentProductId, value); + } + + /// + /// Gets or sets the product identifier. + /// + /// + /// Uses the "prID" atom that Audible writes in .aax audiobooks. ExifTool reports it as ProductID. + /// + public string? ProductId { + get => GetText (Mp4AtomMapping.AudibleProductId); + set => SetText (Mp4AtomMapping.AudibleProductId, value); + } + + /// + /// Gets or sets the release date, as stored (for example 02-Jul-2012). + /// + /// + /// Uses the "rldt" atom that Audible writes in .aax audiobooks. ExifTool reports it as ReleaseDate. + /// + public string? ReleaseDate { + get => GetText (Mp4AtomMapping.AudibleReleaseDate); + set => SetText (Mp4AtomMapping.AudibleReleaseDate, value); + } + + /// + /// Gets or sets the product version. + /// + /// + /// Uses the "VERS" atom that Audible writes in .aax audiobooks. ExifTool reports it as ProductVersion. + /// + public string? ProductVersion { + get => GetText (Mp4AtomMapping.AudibleProductVersion); + set => SetText (Mp4AtomMapping.AudibleProductVersion, value); + } + /// #pragma warning disable CA1819 // Properties should not return arrays - TagLib# API compatibility public override IPicture[] Pictures { diff --git a/src/TagLibSharp2/README.md b/src/TagLibSharp2/README.md index 9007451c..f64614aa 100644 --- a/src/TagLibSharp2/README.md +++ b/src/TagLibSharp2/README.md @@ -30,8 +30,13 @@ A modern .NET library for reading and writing metadata in media files. | Monkey's Audio (APE) | ✅ | ✅ | ✅ | | Musepack | ✅ | ✅ | ✅ | | ASF/WMA | ✅ | ✅ | ✅ | +| Matroska/WebM | ✅ | ✅ | ✅ | +| Audible .aa | ✅ | ✅¹ | ✅ | +| Audible .aax (as MP4) | ✅ | ✅ | ✅ | | APE Tags (standalone) | ✅ | ✅ | — | +¹ The text dictionary is written; the encrypted audio is copied unchanged. Edited `.aa` files have been checked with ffprobe, ffmpeg, and ExifTool, not with Audible's own apps, which may check a digest stored in the file. Keep a copy of the original, or save to a new path. + ## Quick Start ```csharp diff --git a/src/TagLibSharp2/TagLibSharp2.csproj b/src/TagLibSharp2/TagLibSharp2.csproj index f7a53976..cfc86147 100644 --- a/src/TagLibSharp2/TagLibSharp2.csproj +++ b/src/TagLibSharp2/TagLibSharp2.csproj @@ -9,8 +9,8 @@ $(ReleaseVersion) - A modern .NET library for reading and writing metadata in media files. Supports 16 formats: MP3 (ID3v1/ID3v2), FLAC, Ogg Vorbis, Ogg Opus, Ogg FLAC, WAV, AIFF, MP4/M4A (AAC/ALAC), ASF/WMA, DSF (DSD), DFF (DSDIFF), WavPack, Monkey's Audio (.ape), Musepack, Matroska/WebM, and APE tags. Clean, span-based API designed for performance. MIT licensed alternative to TagLib#. - audio;metadata;id3;flac;vorbis;ogg;opus;mp3;mp4;m4a;aac;alac;wav;aiff;dsf;dsd;dff;dsdiff;ape;asf;wma;wavpack;musepack;mpc;monkeys-audio;tags;taglib;music;album-art;replaygain;musicbrainz + A modern .NET library for reading and writing metadata in media files. Supports 17 formats: MP3 (ID3v1/ID3v2), FLAC, Ogg Vorbis, Ogg Opus, Ogg FLAC, WAV, AIFF, MP4/M4A (AAC/ALAC, including Audible .aax), ASF/WMA, DSF (DSD), DFF (DSDIFF), WavPack, Monkey's Audio (.ape), Musepack, Matroska/WebM, Audible .aa, and APE tags. Clean, span-based API designed for performance. MIT licensed alternative to TagLib#. + audio;metadata;id3;flac;vorbis;ogg;opus;mp3;mp4;m4a;aac;alac;wav;aiff;dsf;dsd;dff;dsdiff;ape;asf;wma;wavpack;musepack;mpc;monkeys-audio;audible;aa;aax;audiobook;tags;taglib;music;album-art;replaygain;musicbrainz MIT https://github.com/decriptor/TagLibSharp2 README.md diff --git a/tests/TagLibSharp2.Tests/Audible/AudibleFileTests.cs b/tests/TagLibSharp2.Tests/Audible/AudibleFileTests.cs new file mode 100644 index 00000000..d00a5433 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Audible/AudibleFileTests.cs @@ -0,0 +1,449 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Audible; +using TagLibSharp2.Core; +using TagLibSharp2.Tests.Core; + +namespace TagLibSharp2.Tests.Audible; + +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Audible")] +public class AudibleFileTests +{ + [TestMethod] + public void Read_ValidFile_ReadsTheDictionary () + { + var result = AudibleFile.Read (AudibleTestBuilder.Create ()); + + Assert.IsTrue (result.IsSuccess, result.Error); + var tag = result.File!.Tag; + Assert.AreEqual ("A Test Book (Unabridged)", tag.Title); + Assert.AreEqual ("Ann Author", tag.Artist); + Assert.AreEqual ("Ann Author", tag.Author); + Assert.AreEqual ("Ned Narrator", tag.Narrator); + Assert.AreEqual ("Test Provider", tag.Provider); + Assert.AreEqual ("20-JAN-2009", tag.PublishDate); + Assert.AreEqual ("2009", tag.Year); + Assert.AreEqual ("Short description.", tag.Description); + Assert.AreEqual ("A longer description of the book.", tag.LongDescription); + Assert.AreEqual ("one, two", tag.Keywords); + Assert.AreEqual ("©2009 Ann Author; (P)2009 Test", tag.Copyright); + Assert.AreEqual ("A Test Book", tag.ShortTitle); + Assert.AreEqual ("A Test Book (Unabridged)", tag.ParentTitle); + Assert.AreEqual ("A Test Book", tag.ParentShortTitle); + Assert.AreEqual ("PF_TEST_000001_acelp85", tag.ProductId); + Assert.AreEqual ("PF_TEST_000001", tag.TitleId); + Assert.AreEqual ("acelp85", tag.Codec); + Assert.AreEqual ("1.98", tag.GetValue ("price")); + Assert.AreEqual ("6BBD842E462FE82ED754F4EBC32C096EF3120A54", tag.GetValue ("68ec733412b9")); + CollectionAssert.AreEqual (AudibleTestBuilder.DefaultEntries.Select (e => e.Key).ToList (), tag.Keys.ToList ()); + Assert.AreEqual (TagTypes.Audible, tag.TagType); + Assert.AreEqual (MediaFormat.Audible, result.File.Format); + } + + [TestMethod] + public void Read_KeysWithoutATagField_ReturnNull () + { + var tag = AudibleFile.Read (AudibleTestBuilder.Create ()).File!.Tag; + + Assert.IsNull (tag.Album); + Assert.IsNull (tag.Comment); + Assert.IsNull (tag.Genre); + Assert.IsNull (tag.Track); + Assert.IsNull (tag.GetValue ("missing")); + } + + [TestMethod] + [DataRow ("acelp85", 8500, 8, 8000, 1, "ACELP.net")] + [DataRow ("acelp16", 16000, 16, 16000, 1, "ACELP.net")] + [DataRow ("mp332", 32000, 32, 22050, 0, "MP3")] + [DataRow ("ACELP16", 16000, 16, 16000, 1, "ACELP.net")] + public void Read_Codec_DurationIsAudioBitsOverBitRate (string codec, int bitsPerSecond, int kbps, int sampleRate, int channels, string name) + { + // Eight seconds of audio is exactly bitsPerSecond bytes. + var audio = AudibleTestBuilder.Audio (bitsPerSecond); + + var file = AudibleFile.Read (AudibleTestBuilder.Create (audio: audio, codec: codec)).File!; + + Assert.AreEqual (TimeSpan.FromSeconds (8), file.Properties.Duration); + Assert.AreEqual (kbps, file.Properties.Bitrate); + Assert.AreEqual (sampleRate, file.Properties.SampleRate); + Assert.AreEqual (channels, file.Properties.Channels); + Assert.AreEqual (name, file.Properties.Codec); + Assert.AreEqual (MediaTypes.Audio, ((IMediaFile)file).MediaTypes); + } + + [TestMethod] + public void Read_DurationMatchesFfprobeOnTheRealAcelp85Sample () + { + // first.aa: chunk 10 is 3032215 bytes, codec acelp85; ffprobe reports duration=2853.849412. + var file = AudibleFile.Read (AudibleTestBuilder.Create (audio: new byte[3032215])).File!; + + Assert.AreEqual (2853.849412, file.Properties.Duration.TotalSeconds, 0.000001); + } + + [TestMethod] + public void Read_UnknownCodec_HasNoDuration () + { + var file = AudibleFile.Read (AudibleTestBuilder.Create (codec: "sony5")).File!; + + Assert.AreEqual (TimeSpan.Zero, file.Properties.Duration); + Assert.AreEqual (0, file.Properties.Bitrate); + Assert.AreEqual ("sony5", file.Properties.Codec); + Assert.AreEqual (MediaTypes.None, ((IMediaFile)file).MediaTypes); + } + + [TestMethod] + public void Read_Cover_IsTheFrontCoverPicture () + { + var jpeg = AudibleTestBuilder.Jpeg (); + + var tag = AudibleFile.Read (AudibleTestBuilder.Create (cover: jpeg)).File!.Tag; + + Assert.HasCount (1, tag.Pictures); + Assert.AreEqual ("image/jpeg", tag.Pictures[0].MimeType); + Assert.AreEqual (PictureType.FrontCover, tag.Pictures[0].PictureType); + Assert.AreEqual (string.Empty, tag.Pictures[0].Description); + CollectionAssert.AreEqual (jpeg, tag.Pictures[0].PictureData.ToArray ()); + } + + [TestMethod] + public void Read_NoCover_HasNoPicture () + { + var tag = AudibleFile.Read (AudibleTestBuilder.Create ()).File!.Tag; + + Assert.IsEmpty (tag.Pictures); + } + + [TestMethod] + [DataRow (0u)] + [DataRow (100_000u)] + public void Read_CoverPositionOutsideItsChunk_HasNoPicture (uint position) + { + var data = AudibleTestBuilder.Create (cover: AudibleTestBuilder.Jpeg ()); + var (_, offset, _) = AudibleTestBuilder.Toc (data, 11); + AudibleTestBuilder.SetU32 (data, (int)offset + 4, position); + + var result = AudibleFile.Read (data); + + Assert.IsTrue (result.IsSuccess, result.Error); + Assert.IsEmpty (result.File!.Tag.Pictures); + } + + [TestMethod] + public void Read_CoverLengthPastItsChunk_HasNoPicture () + { + var data = AudibleTestBuilder.Create (cover: AudibleTestBuilder.Jpeg ()); + var (_, offset, _) = AudibleTestBuilder.Toc (data, 11); + AudibleTestBuilder.SetU32 (data, (int)offset, 65); + + Assert.IsEmpty (AudibleFile.Read (data).File!.Tag.Pictures); + } + + [TestMethod] + public void Read_FileTruncatedAfterTheDictionary_StillReadsTagsAndDuration () + { + // The real samples are cut at 10 KiB, well inside the audio, while the TOC describes the whole file. + var full = AudibleTestBuilder.Create (audio: new byte[85_000], cover: AudibleTestBuilder.Jpeg ()); + var (_, dictionaryOffset, dictionarySize) = AudibleTestBuilder.Toc (full, 2); + var cut = full.AsSpan (0, (int)(dictionaryOffset + dictionarySize + 100)).ToArray (); + + var result = AudibleFile.Read (cut); + + Assert.IsTrue (result.IsSuccess, result.Error); + Assert.AreEqual ("A Test Book (Unabridged)", result.File!.Tag.Title); + Assert.AreEqual (TimeSpan.FromSeconds (80), result.File.Properties.Duration); + Assert.AreEqual ((uint)full.Length, result.File.DeclaredFileSize); + Assert.IsEmpty (result.File.Tag.Pictures); + } + + [TestMethod] + public void Read_EveryPrefixShorterThanTheDictionaryEnd_FailsWithoutThrowing () + { + var full = AudibleTestBuilder.Create (); + var (_, offset, size) = AudibleTestBuilder.Toc (full, 2); + var dictionaryEnd = (int)(offset + size); + + for (var length = 0; length < dictionaryEnd; length++) { + var result = AudibleFile.Read (full.AsSpan (0, length)); + Assert.IsFalse (result.IsSuccess, $"prefix of {length} bytes"); + Assert.IsNotNull (result.Error); + } + Assert.IsTrue (AudibleFile.Read (full.AsSpan (0, dictionaryEnd)).IsSuccess); + } + + [TestMethod] + public void Read_WrongMagic_Fails () + { + var data = AudibleTestBuilder.Create (); + data[4] ^= 0xFF; + + var result = AudibleFile.Read (data); + + Assert.IsFalse (result.IsSuccess); + StringAssert.Contains (result.Error, "magic"); + } + + [TestMethod] + [DataRow (0u)] + [DataRow (1025u)] + [DataRow (uint.MaxValue)] + public void Read_TocCountOutOfRange_Fails (uint count) + { + var data = AudibleTestBuilder.Create (); + AudibleTestBuilder.SetU32 (data, 8, count); + + Assert.IsFalse (AudibleFile.Read (data).IsSuccess); + } + + [TestMethod] + public void Read_NoDictionaryChunk_Fails () + { + var data = AudibleTestBuilder.Create (); + AudibleTestBuilder.SetU32 (data, 16 + (2 * 12), 99); + + var result = AudibleFile.Read (data); + + Assert.IsFalse (result.IsSuccess); + StringAssert.Contains (result.Error, "dictionary"); + } + + [TestMethod] + public void Read_DictionaryPastTheEnd_Fails () + { + var data = AudibleTestBuilder.Create (); + AudibleTestBuilder.SetU32 (data, 16 + (2 * 12) + 8, uint.MaxValue); + + Assert.IsFalse (AudibleFile.Read (data).IsSuccess); + } + + [TestMethod] + public void Read_DictionaryInsideTheToc_Fails () + { + var data = AudibleTestBuilder.Create (); + AudibleTestBuilder.SetU32 (data, 16 + (2 * 12) + 4, 20); + + Assert.IsFalse (AudibleFile.Read (data).IsSuccess); + } + + [TestMethod] + [DataRow (uint.MaxValue)] + [DataRow (1000u)] + public void Read_DictionaryCountTheChunkCannotHold_Fails (uint count) + { + var data = AudibleTestBuilder.Create (); + var (_, offset, _) = AudibleTestBuilder.Toc (data, 2); + AudibleTestBuilder.SetU32 (data, (int)offset, count); + + Assert.IsFalse (AudibleFile.Read (data).IsSuccess); + } + + [TestMethod] + [DataRow (1, uint.MaxValue)] + [DataRow (5, uint.MaxValue)] + [DataRow (5, 100_000u)] + public void Read_DictionaryEntryLengthPastTheChunk_Fails (int field, uint value) + { + var data = AudibleTestBuilder.Create (); + var (_, offset, _) = AudibleTestBuilder.Toc (data, 2); + AudibleTestBuilder.SetU32 (data, (int)offset + 4 + field, value); + + Assert.IsFalse (AudibleFile.Read (data).IsSuccess); + } + + [TestMethod] + public void Read_RandomBytesAfterTheMagic_NeverThrow () + { + var random = new Random (110); + for (var i = 0; i < 2000; i++) { + var data = AudibleTestBuilder.Create (); + for (var flips = 0; flips < 8; flips++) + data[8 + random.Next (data.Length - 8)] = (byte)random.Next (256); + + var result = AudibleFile.Read (data); + if (!result.IsSuccess) + Assert.IsNotNull (result.Error); + } + } + + [TestMethod] + public void IsValidFormat_ChecksTheMagicAtOffset4 () + { + Assert.IsTrue (AudibleFile.IsValidFormat (AudibleTestBuilder.Create ())); + Assert.IsFalse (AudibleFile.IsValidFormat (new byte[] { 0, 0, 0, 0, 0x57, 0x90, 0x75 })); + Assert.IsFalse (AudibleFile.IsValidFormat (new byte[8])); + } + + [TestMethod] + public void TryRead_ReportsSuccessAndFailure () + { + Assert.IsTrue (AudibleFile.TryRead (AudibleTestBuilder.Create (), out var file)); + Assert.IsNotNull (file); + Assert.IsFalse (AudibleFile.TryRead (new byte[3], out var none)); + Assert.IsNull (none); + } + + [TestMethod] + public void ReadResult_Equality () + { + var failure = AudibleFileReadResult.Failure ("x"); + Assert.AreEqual (failure, AudibleFileReadResult.Failure ("x")); + Assert.IsTrue (failure == AudibleFileReadResult.Failure ("x")); + Assert.IsTrue (failure != AudibleFileReadResult.Failure ("y")); + Assert.IsFalse (failure.Equals ((object)"x")); + Assert.AreEqual (failure.GetHashCode (), AudibleFileReadResult.Failure ("x").GetHashCode ()); + } + + [TestMethod] + public void ReadFromFile_ReadsAndRemembersThePath () + { + var fs = new MockFileSystem (); + fs.AddFile ("/book.aa", AudibleTestBuilder.Create ()); + + var result = AudibleFile.ReadFromFile ("/book.aa", fs); + + Assert.IsTrue (result.IsSuccess, result.Error); + Assert.AreEqual ("/book.aa", result.File!.SourcePath); + Assert.AreEqual ("Ned Narrator", result.File.Tag.Narrator); + } + + [TestMethod] + public async Task ReadFromFileAsync_ReadsAndRemembersThePath () + { + var fs = new MockFileSystem (); + fs.AddFile ("/book.aa", AudibleTestBuilder.Create (cover: AudibleTestBuilder.Jpeg ())); + + var result = await AudibleFile.ReadFromFileAsync ("/book.aa", fs); + + Assert.IsTrue (result.IsSuccess, result.Error); + Assert.AreEqual ("/book.aa", result.File!.SourcePath); + Assert.HasCount (1, result.File.Tag.Pictures); + } + + [TestMethod] + public async Task ReadFromFile_MissingOrDenied_Fails () + { + var fs = new MockFileSystem (); + fs.AddFile ("/denied.aa", AudibleTestBuilder.Create ()); + fs.MarkInaccessible ("/denied.aa"); + + Assert.IsFalse (AudibleFile.ReadFromFile ("/missing.aa", fs).IsSuccess); + Assert.IsFalse ((await AudibleFile.ReadFromFileAsync ("/missing.aa", fs)).IsSuccess); + StringAssert.Contains (AudibleFile.ReadFromFile ("/denied.aa", fs).Error, "Access denied"); + StringAssert.Contains ((await AudibleFile.ReadFromFileAsync ("/denied.aa", fs)).Error, "Access denied"); + } + + [TestMethod] + public async Task ReadFromFileAsync_Cancelled_Fails () + { + var fs = new MockFileSystem (); + fs.AddFile ("/book.aa", AudibleTestBuilder.Create ()); + using var cts = new CancellationTokenSource (); + await cts.CancelAsync (); + + var result = await AudibleFile.ReadFromFileAsync ("/book.aa", fs, cts.Token); + + Assert.IsFalse (result.IsSuccess); + StringAssert.Contains (result.Error, "cancelled"); + } + + [TestMethod] + public void MediaFile_DetectsByMagic_WithAnyName () + { + var data = AudibleTestBuilder.Create (); + + Assert.AreEqual (MediaFormat.Audible, MediaFile.DetectFormat (data)); + var result = MediaFile.ReadFromData (data, "book.bin"); + Assert.IsTrue (result.IsSuccess, result.Error); + Assert.AreEqual (MediaFormat.Audible, result.Format); + Assert.IsInstanceOfType (result.File); + Assert.AreEqual ("Ned Narrator", ((AudibleTag)result.Tag!).Narrator); + } + + [TestMethod] + public void MediaFile_ExtensionFallback_AaIsAudibleAndAaxIsMp4 () + { + Assert.AreEqual (MediaFormat.Audible, MediaFile.DetectFormat (new byte[] { 1, 2, 3 }, "book.aa")); + Assert.AreEqual (MediaFormat.Audible, MediaFile.DetectFormat (new byte[] { 1, 2, 3 }, "BOOK.AA")); + Assert.AreEqual (MediaFormat.Mp4, MediaFile.DetectFormat (new byte[] { 1, 2, 3 }, "book.aax")); + Assert.IsFalse (MediaFile.ReadFromData (new byte[] { 1, 2, 3 }, "book.aa").IsSuccess); + } + + [TestMethod] + public void MediaFile_Mp4WithAaxName_StaysMp4 () + { + var mp4 = TestBuilders.Mp4.CreateWithMetadata ("Book"); + + Assert.AreEqual (MediaFormat.Mp4, MediaFile.DetectFormat (mp4, "book.aa")); + Assert.AreEqual (MediaFormat.Mp4, MediaFile.ReadFromData (mp4, "book.aax").Format); + } + + [TestMethod] + public async Task MediaFile_PathAndStreamReads_MatchTheByteRead () + { + var data = AudibleTestBuilder.Create (cover: AudibleTestBuilder.Jpeg ()); + var fs = new MockFileSystem (); + fs.AddFile ("/book.aa", data); + + var path = MediaFile.Read ("/book.aa", fs); + var pathAsync = await MediaFile.ReadAsync ("/book.aa", fs); + var stream = MediaFile.Read (new MemoryStream (data)); + var streamAsync = await MediaFile.ReadAsync (new MemoryStream (data)); + using var unseekable = new NonSeekableStream (data); + var piped = MediaFile.Read (unseekable); + + foreach (var result in new[] { path, pathAsync, stream, streamAsync, piped }) { + Assert.IsTrue (result.IsSuccess, result.Error); + Assert.AreEqual (MediaFormat.Audible, result.Format); + var file = (AudibleFile)result.File!; + Assert.AreEqual ("A Test Book (Unabridged)", file.Tag.Title); + Assert.HasCount (1, file.Tag.Pictures); + Assert.AreEqual (TimeSpan.FromSeconds (8), file.Properties.Duration); + } + Assert.AreEqual ("/book.aa", ((AudibleFile)path.File!).SourcePath); + Assert.AreEqual ("/book.aa", ((AudibleFile)pathAsync.File!).SourcePath); + } + + [TestMethod] + public void Dispose_ThenRender_Throws () + { + var data = AudibleTestBuilder.Create (); + var file = AudibleFile.Read (data).File!; + file.Dispose (); + file.Dispose (); + + Assert.ThrowsExactly (() => file.Render (data)); + Assert.ThrowsExactly (() => file.SaveToFile ("/x.aa", new MockFileSystem ())); + Assert.ThrowsExactly (() => file.SaveToFile (new MockFileSystem ())); + Assert.ThrowsExactly (() => file.SaveToFile ("/x.aa", data, new MockFileSystem ())); + } + + [TestMethod] + public async Task Dispose_ThenSaveAsync_Throws () + { + var data = AudibleTestBuilder.Create (); + var file = AudibleFile.Read (data).File!; + file.Dispose (); + + await Assert.ThrowsExactlyAsync (() => file.SaveToFileAsync ("/x.aa", new MockFileSystem ())); + await Assert.ThrowsExactlyAsync (() => file.SaveToFileAsync (new MockFileSystem ())); + await Assert.ThrowsExactlyAsync (() => file.SaveToFileAsync ("/x.aa", data, new MockFileSystem ())); + } + + sealed class NonSeekableStream (byte[] data) : Stream + { + readonly MemoryStream _inner = new (data); + public override bool CanRead => true; + public override bool CanSeek => false; + public override bool CanWrite => false; + public override long Length => throw new NotSupportedException (); + public override long Position { get => throw new NotSupportedException (); set => throw new NotSupportedException (); } + public override void Flush () { } + public override int Read (byte[] buffer, int offset, int count) => _inner.Read (buffer, offset, count); + public override long Seek (long offset, SeekOrigin origin) => throw new NotSupportedException (); + public override void SetLength (long value) => throw new NotSupportedException (); + public override void Write (byte[] buffer, int offset, int count) => throw new NotSupportedException (); + } +} diff --git a/tests/TagLibSharp2.Tests/Audible/AudibleGuardTests.cs b/tests/TagLibSharp2.Tests/Audible/AudibleGuardTests.cs new file mode 100644 index 00000000..8af93961 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Audible/AudibleGuardTests.cs @@ -0,0 +1,252 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Audible; +using TagLibSharp2.Core; +using TagLibSharp2.Tests.Core; + +namespace TagLibSharp2.Tests.Audible; + +/// +/// Each bound in the reader and the save planner, with an input that only that bound stops. +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Audible")] +public class AudibleGuardTests +{ + const int TocAt = AudibleTestBuilder.HeaderSize; + + static int TocField (int index, int field) => TocAt + (index * 12) + (field * 4); + + // A file cut right after the dictionary, so TOC entries past it may point anywhere. + static byte[] Truncated () + { + var full = AudibleTestBuilder.Create (); + var (_, offset, size) = AudibleTestBuilder.Toc (full, 2); + return full.AsSpan (0, (int)(offset + size)).ToArray (); + } + + static AudibleFile Grown (byte[] data) + { + var file = AudibleFile.Read (data).File!; + file.Tag.Title = new string ('x', 200); + return file; + } + + [TestMethod] + [DataRow (0xFFFFFFF0u, 4u, DisplayName = "offset past 32 bits after the shift")] + [DataRow (0xFFFFFF00u, 0xF0u, DisplayName = "offset + size past 32 bits after the shift")] + public void Render_ChunkMovedPast32Bits_ReturnsEmpty (uint offset, uint size) + { + var data = Truncated (); + AudibleTestBuilder.SetU32 (data, TocField (7, 1), offset); + AudibleTestBuilder.SetU32 (data, TocField (7, 2), size); + var file = Grown (data); + + Assert.IsTrue (file.Render (data).IsEmpty); + Assert.IsFalse (file.SaveToFile ("/out.aa", data, new MockFileSystem ()).IsSuccess); + } + + [TestMethod] + public void Render_WholeFileEntryGrownPast32Bits_ReturnsEmpty () + { + var data = Truncated (); + AudibleTestBuilder.SetU32 (data, TocField (0, 2), 0xFFFFFFF8u); + + Assert.IsTrue (Grown (data).Render (data).IsEmpty); + } + + [TestMethod] + [DataRow (0xFFFFFFF8u, true)] + [DataRow (5u, false)] + public void Render_DeclaredSizeOutOf32Bits_ReturnsEmpty (uint declared, bool grow) + { + var data = Truncated (); + AudibleTestBuilder.SetU32 (data, 0, declared); + var file = AudibleFile.Read (data).File!; + if (grow) + file.Tag.Title = new string ('x', 200); + else + file.Tag.Clear (); + + Assert.IsTrue (file.Render (data).IsEmpty); + } + + [TestMethod] + public void Read_DictionaryOverTheCap_Fails () + { + var value = new string ('v', AudibleFile.MaxDictionarySize); + var data = AudibleTestBuilder.Create ([("title", value), ("codec", "acelp85")]); + + var result = AudibleFile.Read (data); + + Assert.IsFalse (result.IsSuccess); + StringAssert.Contains (result.Error, "claims"); + } + + [TestMethod] + public void Read_CoverChunkInsideTheToc_HasNoPicture () + { + // Four TOC entries end at 64. The cover chunk (type 11) starts at 52, inside entry 3, whose + // type, offset, and size fields read as a valid cover header: length 4, position 60, image = entry 3's size. + var dictionary = AudibleTestBuilder.Dictionary ([("title", "T"), ("codec", "acelp85")]); + var data = new byte[64 + dictionary.Length]; + AudibleTestBuilder.SetU32 (data, 0, (uint)data.Length); + AudibleTestBuilder.SetU32 (data, 4, AudibleTestBuilder.Magic); + AudibleTestBuilder.SetU32 (data, 8, 4); + SetEntry (data, 0, 0, 0, (uint)data.Length); + SetEntry (data, 1, 2, 64, (uint)dictionary.Length); + SetEntry (data, 2, 11, 52, 20); + SetEntry (data, 3, 4, 60, 0xFFD8FFE0); + dictionary.CopyTo (data, 64); + + var result = AudibleFile.Read (data); + + Assert.IsTrue (result.IsSuccess, result.Error); + Assert.IsEmpty (result.File!.Tag.Pictures); + } + + [TestMethod] + public void Read_CoverPositionInsideItsOwnHeader_HasNoPicture () + { + // Position = chunk + 4 points at the position field itself: inside the chunk but before the image. + var data = AudibleTestBuilder.Create (cover: AudibleTestBuilder.Jpeg ()); + var (_, offset, _) = AudibleTestBuilder.Toc (data, 11); + AudibleTestBuilder.SetU32 (data, (int)offset, 4); + AudibleTestBuilder.SetU32 (data, (int)offset + 4, offset + 4); + + var result = AudibleFile.Read (data); + + Assert.IsTrue (result.IsSuccess, result.Error); + Assert.IsEmpty (result.File!.Tag.Pictures); + } + + [TestMethod] + [DataRow (true, DisplayName = "source denied")] + [DataRow (false, DisplayName = "source deleted")] + public async Task SaveToAnotherPath_SourceUnreadable_StillSucceeds (bool denied) + { + // After a save the source's header is re-read to see whether the save rewrote it. A source that + // cannot be read then (denied or deleted) leaves the layout alone and does not fail the save. + var fs = new MockFileSystem (); + fs.AddFile ("/book.aa", AudibleTestBuilder.Create ()); + var file = AudibleFile.ReadFromFile ("/book.aa", fs).File!; + file.Tag.Title = "Copy with a longer title"; + var original = fs.ReadAllBytes ("/book.aa"); + if (denied) + fs.MarkInaccessible ("/book.aa"); + else + fs.Delete ("/book.aa"); + + Assert.IsTrue (file.SaveToFile ("/a.aa", original, fs).IsSuccess); + Assert.IsTrue ((await file.SaveToFileAsync ("/b.aa", original, fs)).IsSuccess); + + Assert.AreEqual ("Copy with a longer title", AudibleFile.Read (fs.ReadAllBytes ("/a.aa")).File!.Tag.Title); + CollectionAssert.AreEqual (fs.ReadAllBytes ("/a.aa"), fs.ReadAllBytes ("/b.aa")); + } + + [TestMethod] + public async Task SaveToAnotherPath_SourceReplacedMeanwhile_NextSaveStillRefuses () + { + // Only a source that now holds the layout this object wrote is adopted. A source another writer + // replaced is not, so the next save does not put this dictionary into someone else's file. + var fs = new MockFileSystem (); + fs.AddFile ("/book.aa", AudibleTestBuilder.Create ()); + var file = AudibleFile.ReadFromFile ("/book.aa", fs).File!; + var original = fs.ReadAllBytes ("/book.aa"); + fs.AddFile ("/book.aa", AudibleTestBuilder.Create (audio: AudibleTestBuilder.Audio (777))); + file.Tag.Title = "Mine"; + + var copy = file.SaveToFile ("/copy.aa", original, fs); + Assert.IsTrue (copy.IsSuccess, copy.Error); + var copy2 = await file.SaveToFileAsync ("/copy2.aa", original, fs); + Assert.IsTrue (copy2.IsSuccess, copy2.Error); + Assert.IsFalse (file.SaveToFile (fs).IsSuccess); + Assert.IsFalse ((await file.SaveToFileAsync (fs)).IsSuccess); + } + + [TestMethod] + public async Task SaveToFileAsync_CancelledAfterTheCommit_ReturnsTheWriteAndCanSaveAgain () + { + // The token is cancelled inside the atomic rename, after the new file is in place. The save has + // happened, so it must report success, and the layout must follow it so the next save works. + var inner = new MockFileSystem (); + inner.AddFile ("/book.aa", AudibleTestBuilder.Create (cover: AudibleTestBuilder.Jpeg ())); + using var cts = new CancellationTokenSource (); + var fs = new CancelOnMoveFileSystem (inner, cts); + var file = (await AudibleFile.ReadFromFileAsync ("/book.aa", fs)).File!; + + file.Tag.Title = "Committed with a longer title than before"; + var saved = await file.SaveToFileAsync (fs, cts.Token); + + Assert.IsTrue (cts.IsCancellationRequested, "the rename did not run"); + Assert.IsTrue (saved.IsSuccess, saved.Error); + Assert.AreEqual ("Committed with a longer title than before", AudibleFile.Read (inner.ReadAllBytes ("/book.aa")).File!.Tag.Title); + + file.Tag.Title = "Next"; + var next = await file.SaveToFileAsync (inner); + Assert.IsTrue (next.IsSuccess, next.Error); + Assert.AreEqual ("Next", AudibleFile.Read (inner.ReadAllBytes ("/book.aa")).File!.Tag.Title); + } + + [TestMethod] + public async Task SaveToFile_SourceHeaderReadFailsUnexpectedly_StillSucceeds () + { + // Any failure while re-reading the source after the commit leaves the layout alone; the save stands. + var inner = new MockFileSystem (); + inner.AddFile ("/book.aa", AudibleTestBuilder.Create ()); + var file = AudibleFile.ReadFromFile ("/book.aa", inner).File!; + var original = inner.ReadAllBytes ("/book.aa"); + var fs = new ThrowOnReadFileSystem (inner); + + foreach (var failure in new Exception[] { new NotSupportedException (), new ArgumentException ("bad path"), new ObjectDisposedException ("stream"), new InvalidOperationException (), new OperationCanceledException () }) { + fs.Failure = failure; + file.Tag.Title = "Saved despite " + failure.GetType ().Name; + var sync = file.SaveToFile ("/a.aa", original, fs); + var async = await file.SaveToFileAsync ("/b.aa", original, fs); + Assert.IsTrue (sync.IsSuccess, sync.Error); + Assert.IsTrue (async.IsSuccess, async.Error); + } + } + + sealed class CancelOnMoveFileSystem (MockFileSystem inner, CancellationTokenSource cts) : ForwardingFileSystem (inner) + { + public override void Move (string sourcePath, string destinationPath) + { + base.Move (sourcePath, destinationPath); + cts.Cancel (); + } + } + + sealed class ThrowOnReadFileSystem (MockFileSystem inner) : ForwardingFileSystem (inner) + { + public Exception? Failure { get; set; } + + public override Stream OpenRead (string path) => Failure is not null && path == "/book.aa" ? throw Failure : base.OpenRead (path); + } + + class ForwardingFileSystem (MockFileSystem inner) : IFileSystem + { + public bool FileExists (string path) => inner.FileExists (path); + public virtual Stream OpenRead (string path) => inner.OpenRead (path); + public Stream OpenReadWrite (string path) => inner.OpenReadWrite (path); + public Stream Create (string path) => inner.Create (path); + public byte[] ReadAllBytes (string path) => inner.ReadAllBytes (path); + public Task ReadAllBytesAsync (string path, CancellationToken cancellationToken = default) => inner.ReadAllBytesAsync (path, cancellationToken); + public void WriteAllBytes (string path, ReadOnlySpan data) => inner.WriteAllBytes (path, data); + public Task WriteAllBytesAsync (string path, ReadOnlyMemory data, CancellationToken cancellationToken = default) => inner.WriteAllBytesAsync (path, data, cancellationToken); + public void Delete (string path) => inner.Delete (path); + public virtual void Move (string sourcePath, string destinationPath) => inner.Move (sourcePath, destinationPath); + public string? GetDirectoryName (string path) => inner.GetDirectoryName (path); + public string GetFileName (string path) => inner.GetFileName (path); + public string CombinePath (string path1, string path2) => inner.CombinePath (path1, path2); + } + + static void SetEntry (byte[] data, int index, uint type, uint offset, uint size) + { + AudibleTestBuilder.SetU32 (data, TocField (index, 0), type); + AudibleTestBuilder.SetU32 (data, TocField (index, 1), offset); + AudibleTestBuilder.SetU32 (data, TocField (index, 2), size); + } +} diff --git a/tests/TagLibSharp2.Tests/Audible/AudibleIntegrationTests.cs b/tests/TagLibSharp2.Tests/Audible/AudibleIntegrationTests.cs new file mode 100644 index 00000000..0e90204f --- /dev/null +++ b/tests/TagLibSharp2.Tests/Audible/AudibleIntegrationTests.cs @@ -0,0 +1,138 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Audible; +using TagLibSharp2.Core; +using TagLibSharp2.Mp4; +using TagLibSharp2.Tests.Core; + +namespace TagLibSharp2.Tests.Audible; + +/// +/// Integration tests against real Audible files. +/// +/// +/// Skipped unless the environment names a file: +/// +/// TAGLIBSHARP2_TEST_AA: an Audible .aa file (for example taglib-sharp's samples/audible/first.aa) +/// TAGLIBSHARP2_TEST_AAX: an Audible .aax file +/// +/// Example: TAGLIBSHARP2_TEST_AA=/path/first.aa dotnet test --filter "TestCategory=Integration&TestCategory=Audible" +/// +[TestClass] +[TestCategory ("Integration")] +[TestCategory ("Manual")] +[TestCategory ("Audible")] +public class AudibleIntegrationTests : FileFormatTestBase +{ + const string AaEnvVar = "TAGLIBSHARP2_TEST_AA"; + const string AaxEnvVar = "TAGLIBSHARP2_TEST_AAX"; + + [TestMethod] + public void RealAa_ReadsTagsAndDuration () + { + var path = SkipIfNoTestFile (AaEnvVar, "Audible .aa"); + + var result = MediaFile.Read (path); + + Assert.IsTrue (result.IsSuccess, result.Error); + Assert.AreEqual (MediaFormat.Audible, result.Format); + var file = (AudibleFile)result.File!; + Assert.IsFalse (string.IsNullOrEmpty (file.Tag.Title)); + Assert.IsFalse (string.IsNullOrEmpty (file.Tag.Author)); + Assert.IsFalse (string.IsNullOrEmpty (file.Tag.Codec)); + Assert.IsNotNull (file.Tag.GetValue ("HeaderKey")); + Assert.IsTrue (file.Properties.Duration > TimeSpan.Zero, $"codec {file.Tag.Codec}"); + Console.WriteLine ($"{file.Tag.Title} / {file.Tag.Author} / {file.Tag.Narrator} / {file.Tag.Codec} / {file.Properties.Duration.TotalSeconds:F6}s"); + } + + [TestMethod] + public void RealAa_StreamAndByteReadsAgree () + { + var path = SkipIfNoTestFile (AaEnvVar, "Audible .aa"); + var bytes = File.ReadAllBytes (path); + + var fromBytes = AudibleFile.Read (bytes).File!; + var fromPath = AudibleFile.ReadFromFile (path).File!; + + CollectionAssert.AreEqual (fromBytes.Tag.Keys.ToList (), fromPath.Tag.Keys.ToList ()); + foreach (var key in fromBytes.Tag.Keys) + Assert.AreEqual (fromBytes.Tag.GetValue (key), fromPath.Tag.GetValue (key), key); + Assert.AreEqual (fromBytes.Properties, fromPath.Properties); + Assert.AreEqual (fromBytes.Tag.Pictures.Length, fromPath.Tag.Pictures.Length); + } + + [TestMethod] + public void RealAa_UnchangedRender_IsByteIdentical () + { + var path = SkipIfNoTestFile (AaEnvVar, "Audible .aa"); + var bytes = File.ReadAllBytes (path); + + var file = AudibleFile.Read (bytes).File!; + + CollectionAssert.AreEqual (bytes, file.Render (bytes).ToArray ()); + } + + [TestMethod] + public void RealAa_EditedSave_KeepsEveryOtherByte () + { + var path = SkipIfNoTestFile (AaEnvVar, "Audible .aa"); + var bytes = File.ReadAllBytes (path); + var file = AudibleFile.Read (bytes).File!; + var before = file.Tag.Keys.ToDictionary (k => k, k => file.Tag.GetValue (k)); + var dictionary = AudibleTestBuilder.Toc (bytes, 2); + + file.Tag.Title = "Edited title – ✓ with a different length"; + file.Tag.Narrator = "Edited narrator"; + var output = file.Render (bytes).ToArray (); + + var delta = output.Length - bytes.Length; + var reread = AudibleFile.Read (output).File!; + Assert.AreEqual ("Edited title – ✓ with a different length", reread.Tag.Title); + Assert.AreEqual ("Edited narrator", reread.Tag.Narrator); + foreach (var (key, value) in before.Where (kv => kv.Key is not "title" and not "narrator")) + Assert.AreEqual (value, reread.Tag.GetValue (key), key); + Assert.AreEqual (file.Properties, reread.Properties); + Assert.AreEqual ((long)file.DeclaredFileSize + delta, reread.DeclaredFileSize); + var end = (int)(dictionary.Offset + dictionary.Size); + var expected = ExpectedTail (bytes, end, delta); + CollectionAssert.AreEqual (expected, output.AsSpan (end + delta).ToArray (), "bytes after the dictionary"); + } + + // Every byte after the dictionary is copied, except the cover chunk's absolute image position + // (chunk 11, offset 4), which moves with the chunk. A truncated file may end before the cover. + static byte[] ExpectedTail (byte[] original, int dictionaryEnd, int delta) + { + var tail = original.AsSpan (dictionaryEnd).ToArray (); + var count = (int)AudibleTestBuilder.ReadU32 (original, 8); + for (var i = 0; i < count; i++) { + var (type, offset, size) = AudibleTestBuilder.Toc (original, i); + if (type != 11 || size < 8 || offset < dictionaryEnd || offset + 8L > original.Length) + continue; + var field = (int)offset + 4 - dictionaryEnd; + var position = AudibleTestBuilder.ReadU32 (tail, field); + if (position >= offset && position <= offset + (long)size) + AudibleTestBuilder.SetU32 (tail, field, (uint)(position + delta)); + } + return tail; + } + + [TestMethod] + public void RealAax_OpensAsMp4WhenItsMovieBoxIsComplete () + { + var path = SkipIfNoTestFile (AaxEnvVar, "Audible .aax"); + + var result = MediaFile.Read (path); + + // taglib-sharp's second.aax is cut at 10 KiB inside moov/trak/mdia/minf/stbl/stsz, before udta. + // ffprobe also rejects it ("error reading header"), so a failure is reported, not a crash. + if (!result.IsSuccess) { + Assert.IsNotNull (result.Error); + Assert.Inconclusive ($"{path} could not be read as MPEG-4: {result.Error}"); + } + Assert.AreEqual (MediaFormat.Mp4, result.Format); + var file = (Mp4File)result.File!; + Assert.AreEqual ("aax", file.FileType); + Console.WriteLine ($"{file.Title} / {file.Narrator} / {file.ProductId} / {file.Properties.Duration}"); + } +} diff --git a/tests/TagLibSharp2.Tests/Audible/AudibleRoundTripTests.cs b/tests/TagLibSharp2.Tests/Audible/AudibleRoundTripTests.cs new file mode 100644 index 00000000..bf8cc190 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Audible/AudibleRoundTripTests.cs @@ -0,0 +1,364 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using TagLibSharp2.Audible; +using TagLibSharp2.Core; +using TagLibSharp2.Tests.Core; + +namespace TagLibSharp2.Tests.Audible; + +/// +/// A save rewrites the dictionary only. Every other chunk keeps its bytes, every TOC offset past the +/// dictionary moves by the size change, and the header, whole-file entry, and cover position follow. +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Audible")] +public class AudibleRoundTripTests +{ + static readonly string[] KeptByClear = [ + "product_id", "title_id", "codec", "HeaderSeed", "EncryptedBlocks", "HeaderKey", + "license_list", "CPUType", "license_count", "68ec733412b9", "user_alias" + ]; + + [TestMethod] + public void Render_Unchanged_IsByteIdentical () + { + var data = AudibleTestBuilder.Create (cover: AudibleTestBuilder.Jpeg ()); + var file = AudibleFile.Read (data).File!; + + CollectionAssert.AreEqual (data, file.Render (data).ToArray ()); + } + + [TestMethod] + public void Render_SameValueSetAgain_IsByteIdentical () + { + var data = AudibleTestBuilder.Create (); + var file = AudibleFile.Read (data).File!; + file.Tag.Title = file.Tag.Title; + file.Tag.Narrator = file.Tag.Narrator; + + CollectionAssert.AreEqual (data, file.Render (data).ToArray ()); + } + + [TestMethod] + public void Render_NonAsciiKeyAndInvalidUtf8Value_AreWrittenBackUnchanged () + { + var dictionary = AudibleTestBuilder.Dictionary ([("title", "T"), ("codec", "acelp85")]); + // Append an entry with a 0xE9 key byte and a lone 0xFF value byte, then fix the count. + var odd = new byte[] { 1, 0, 0, 0, 2, 0, 0, 0, 1, (byte)'k', 0xE9, 0xFF }; + dictionary = AudibleTestBuilder.Concat (dictionary, odd); + BinaryPrimitives.WriteUInt32BigEndian (dictionary, 3); + var data = AudibleTestBuilder.CreateRaw (dictionary, AudibleTestBuilder.Audio (100), null); + var file = AudibleFile.Read (data).File!; + + CollectionAssert.AreEqual (data, file.Render (data).ToArray ()); + } + + [TestMethod] + public void Render_BytesAfterTheLastEntry_AreKept () + { + var dictionary = AudibleTestBuilder.Concat ( + AudibleTestBuilder.Dictionary ([("title", "T"), ("codec", "acelp85")]), [0xAB, 0xCD, 0xEF]); + var data = AudibleTestBuilder.CreateRaw (dictionary, AudibleTestBuilder.Audio (100), null); + var file = AudibleFile.Read (data).File!; + CollectionAssert.AreEqual (data, file.Render (data).ToArray ()); + + file.Tag.Title = "Longer title"; + var chunk = AudibleTestBuilder.Chunk (file.Render (data).ToArray (), 2); + + CollectionAssert.AreEqual (new byte[] { 0xAB, 0xCD, 0xEF }, chunk[^3..]); + } + + [TestMethod] + [DataRow ("x")] + [DataRow ("A much, much longer replacement title for this audiobook – with UTF-8 ✓")] + public void Render_TitleChange_MovesEveryLaterChunkAndKeepsTheirBytes (string title) + { + var jpeg = AudibleTestBuilder.Jpeg (); + var data = AudibleTestBuilder.Create (cover: jpeg); + var file = AudibleFile.Read (data).File!; + file.Tag.Title = title; + + var output = file.Render (data).ToArray (); + + var oldDictionary = AudibleTestBuilder.Toc (data, 2); + var newDictionary = AudibleTestBuilder.Toc (output, 2); + var delta = (long)newDictionary.Size - oldDictionary.Size; + Assert.AreNotEqual (0L, delta); + Assert.AreEqual (data.Length + delta, output.Length); + Assert.AreEqual ((uint)output.Length, BinaryPrimitives.ReadUInt32BigEndian (output)); + CollectionAssert.AreEqual (data.AsSpan (4, 12).ToArray (), output.AsSpan (4, 12).ToArray (), "magic, count, and unknown word"); + + var whole = AudibleTestBuilder.Toc (output, 0); + Assert.AreEqual ((0u, 0u, (uint)output.Length), whole); + + for (var i = 1; i < 12; i++) { + var before = AudibleTestBuilder.Toc (data, i); + var after = AudibleTestBuilder.Toc (output, i); + Assert.AreEqual (before.Type, after.Type); + if (i < 2) { + Assert.AreEqual (before, after, $"chunk {i} is before the dictionary"); + } else if (i > 2) { + Assert.AreEqual (before.Offset + delta, (long)after.Offset, $"chunk {i} offset"); + Assert.AreEqual (before.Size, after.Size, $"chunk {i} size"); + } + if (i != 2 && i != 11) + CollectionAssert.AreEqual (AudibleTestBuilder.Chunk (data, i), AudibleTestBuilder.Chunk (output, i), $"chunk {i} bytes"); + } + + var cover = AudibleTestBuilder.Toc (output, 11); + Assert.AreEqual (cover.Offset + 8, BinaryPrimitives.ReadUInt32BigEndian (output.AsSpan ((int)cover.Offset + 4)), "cover position"); + Assert.AreEqual ((uint)jpeg.Length, BinaryPrimitives.ReadUInt32BigEndian (output.AsSpan ((int)cover.Offset))); + + var reread = AudibleFile.Read (output).File!; + Assert.AreEqual (title, reread.Tag.Title); + CollectionAssert.AreEqual (jpeg, reread.Tag.Pictures[0].PictureData.ToArray ()); + Assert.AreEqual (file.Properties, reread.Properties); + CollectionAssert.AreEqual (file.Tag.Keys.ToList (), reread.Tag.Keys.ToList ()); + foreach (var key in reread.Tag.Keys.Where (k => k != "title")) + Assert.AreEqual (AudibleFile.Read (data).File!.Tag.GetValue (key), reread.Tag.GetValue (key), key); + } + + [TestMethod] + public void Render_TruncatedFile_ShiftsTheDeclaredSizeAndOffsetsByTheSameAmount () + { + var full = AudibleTestBuilder.Create (audio: new byte[85_000], cover: AudibleTestBuilder.Jpeg ()); + var (_, dictionaryOffset, dictionarySize) = AudibleTestBuilder.Toc (full, 2); + var cut = full.AsSpan (0, (int)(dictionaryOffset + dictionarySize + 300)).ToArray (); + var file = AudibleFile.Read (cut).File!; + file.Tag.Narrator = "Someone With A Much Longer Name Than Before"; + + var output = file.Render (cut).ToArray (); + + var delta = (long)AudibleTestBuilder.Toc (output, 2).Size - dictionarySize; + Assert.AreEqual (cut.Length + delta, output.Length); + Assert.AreEqual (full.Length + delta, BinaryPrimitives.ReadUInt32BigEndian (output)); + Assert.AreEqual (full.Length + delta, AudibleTestBuilder.Toc (output, 0).Size); + for (var i = 3; i < 12; i++) + Assert.AreEqual (AudibleTestBuilder.Toc (full, i).Offset + delta, (long)AudibleTestBuilder.Toc (output, i).Offset); + CollectionAssert.AreEqual ( + cut.AsSpan ((int)(dictionaryOffset + dictionarySize)).ToArray (), + output.AsSpan ((int)(dictionaryOffset + dictionarySize + delta)).ToArray ()); + + var reread = AudibleFile.Read (output).File!; + Assert.AreEqual ("Someone With A Much Longer Name Than Before", reread.Tag.Narrator); + Assert.AreEqual (file.Properties.Duration, reread.Properties.Duration); + } + + [TestMethod] + public void Render_DataFromAnotherFile_ReturnsEmpty () + { + var file = AudibleFile.Read (AudibleTestBuilder.Create ()).File!; + var other = AudibleTestBuilder.Create (audio: AudibleTestBuilder.Audio (999)); + + Assert.IsTrue (file.Render (other).IsEmpty); + Assert.IsTrue (file.Render (new byte[10]).IsEmpty); + } + + [TestMethod] + public void Render_ChunkThatEndsInsideTheDictionary_ReturnsEmpty () + { + var data = AudibleTestBuilder.Create (); + var (_, dictionaryOffset, _) = AudibleTestBuilder.Toc (data, 2); + // Chunk 1 now runs 10 bytes into the dictionary; moving the dictionary would split it. + var (_, oneOffset, _) = AudibleTestBuilder.Toc (data, 1); + AudibleTestBuilder.SetU32 (data, 16 + 12 + 8, dictionaryOffset - oneOffset + 10); + var file = AudibleFile.Read (data).File!; + file.Tag.Title = "Changed"; + + Assert.IsTrue (file.Render (data).IsEmpty); + Assert.IsFalse (file.SaveToFile ("/out.aa", data, new MockFileSystem ()).IsSuccess); + } + + [TestMethod] + public void Render_CoverWithAForeignPosition_LeavesThePositionAlone () + { + var data = AudibleTestBuilder.Create (cover: AudibleTestBuilder.Jpeg ()); + var (_, coverOffset, _) = AudibleTestBuilder.Toc (data, 11); + AudibleTestBuilder.SetU32 (data, (int)coverOffset + 4, 7); + var file = AudibleFile.Read (data).File!; + file.Tag.Title = "Changed title"; + + var output = file.Render (data).ToArray (); + + var (_, newOffset, _) = AudibleTestBuilder.Toc (output, 11); + Assert.AreEqual (7u, BinaryPrimitives.ReadUInt32BigEndian (output.AsSpan ((int)newOffset + 4))); + } + + [TestMethod] + public void Render_ClearedTag_KeepsDrmAndIdentifierKeys () + { + var data = AudibleTestBuilder.Create (); + var file = AudibleFile.Read (data).File!; + file.Tag.Clear (); + + var reread = AudibleFile.Read (file.Render (data).Span).File!; + + Assert.IsTrue (reread.Tag.IsEmpty); + CollectionAssert.AreEqual (KeptByClear, reread.Tag.Keys.ToList ()); + Assert.AreEqual (file.Properties.Duration, reread.Properties.Duration); + } + + [TestMethod] + public void SaveToFile_FromPath_RewritesAndCanSaveAgain () + { + var data = AudibleTestBuilder.Create (cover: AudibleTestBuilder.Jpeg ()); + var fs = new MockFileSystem (); + fs.AddFile ("/book.aa", data); + var file = AudibleFile.ReadFromFile ("/book.aa", fs).File!; + + file.Tag.Title = "First save with a longer title"; + Assert.IsTrue (file.SaveToFile (fs).IsSuccess); + file.Tag.Title = "Second"; + var second = file.SaveToFile (fs); + + Assert.IsTrue (second.IsSuccess, second.Error); + var reread = AudibleFile.ReadFromFile ("/book.aa", fs).File!; + Assert.AreEqual ("Second", reread.Tag.Title); + Assert.HasCount (1, reread.Tag.Pictures); + Assert.IsTrue (AudibleTestBuilder.IndexOf (fs.ReadAllBytes ("/book.aa"), AudibleTestBuilder.Audio (8500)) >= 0); + } + + [TestMethod] + public async Task SaveToFileAsync_FromPath_RewritesAndCanSaveAgain () + { + var data = AudibleTestBuilder.Create (cover: AudibleTestBuilder.Jpeg ()); + var fs = new MockFileSystem (); + fs.AddFile ("/book.aa", data); + var file = (await AudibleFile.ReadFromFileAsync ("/book.aa", fs)).File!; + + file.Tag.Narrator = "First async save"; + Assert.IsTrue ((await file.SaveToFileAsync (fs)).IsSuccess); + file.Tag.Narrator = "Second"; + var second = await file.SaveToFileAsync (fs); + + Assert.IsTrue (second.IsSuccess, second.Error); + Assert.AreEqual ("Second", AudibleFile.Read (fs.ReadAllBytes ("/book.aa")).File!.Tag.Narrator); + } + + [TestMethod] + public async Task SaveToFile_SourceUnderAnotherSpelling_CanSaveAgain () + { + // The source is rewritten through "dir/./book.aa", then saved again through SourcePath. + var dir = Path.Combine (Path.GetTempPath (), "tls-aa-" + Guid.NewGuid ().ToString ("N")); + Directory.CreateDirectory (dir); + try { + var path = Path.Combine (dir, "book.aa"); + File.WriteAllBytes (path, AudibleTestBuilder.Create (cover: AudibleTestBuilder.Jpeg ())); + var alias = dir + Path.DirectorySeparatorChar + "." + Path.DirectorySeparatorChar + "book.aa"; + + var file = AudibleFile.ReadFromFile (path).File!; + file.Tag.Title = "Saved through an alias with a longer title"; + Assert.IsTrue (file.SaveToFile (alias).IsSuccess); + file.Tag.Title = "Second"; + var second = file.SaveToFile (); + Assert.IsTrue (second.IsSuccess, second.Error); + + file.Tag.Title = "Async through the alias, longer again"; + Assert.IsTrue ((await file.SaveToFileAsync (alias)).IsSuccess); + file.Tag.Title = "Third"; + var third = await file.SaveToFileAsync (); + Assert.IsTrue (third.IsSuccess, third.Error); + + Assert.AreEqual ("Third", AudibleFile.ReadFromFile (path).File!.Tag.Title); + } finally { + Directory.Delete (dir, recursive: true); + } + } + + [TestMethod] + public async Task SaveToFile_SourceUnderAnotherCase_CanSaveAgain () + { + // MockFileSystem compares paths case-insensitively, like the default macOS and Windows file systems. + var fs = new MockFileSystem (); + fs.AddFile ("/Books/book.aa", AudibleTestBuilder.Create ()); + var file = AudibleFile.ReadFromFile ("/Books/book.aa", fs).File!; + + file.Tag.Title = "Saved under another case with a longer title"; + Assert.IsTrue (file.SaveToFile ("/BOOKS/BOOK.AA", fs).IsSuccess); + file.Tag.Narrator = "Second"; + var second = file.SaveToFile (fs); + Assert.IsTrue (second.IsSuccess, second.Error); + + file.Tag.Title = "Async under another case, longer"; + Assert.IsTrue ((await file.SaveToFileAsync ("/books/Book.aa", fs)).IsSuccess); + file.Tag.Narrator = "Third"; + var third = await file.SaveToFileAsync (fs); + Assert.IsTrue (third.IsSuccess, third.Error); + + Assert.AreEqual ("Third", AudibleFile.Read (fs.ReadAllBytes ("/Books/book.aa")).File!.Tag.Narrator); + } + + [TestMethod] + public async Task SaveToFile_ToAnotherPath_LeavesTheSourceAndCanSaveAgain () + { + var data = AudibleTestBuilder.Create (); + var fs = new MockFileSystem (); + fs.AddFile ("/book.aa", data); + var file = AudibleFile.ReadFromFile ("/book.aa", fs).File!; + file.Tag.Title = "Copy"; + + Assert.IsTrue (file.SaveToFile ("/copy.aa", fs).IsSuccess); + Assert.IsTrue ((await file.SaveToFileAsync ("/copy2.aa", fs)).IsSuccess); + + CollectionAssert.AreEqual (data, fs.ReadAllBytes ("/book.aa")); + Assert.AreEqual ("Copy", AudibleFile.Read (fs.ReadAllBytes ("/copy.aa")).File!.Tag.Title); + CollectionAssert.AreEqual (fs.ReadAllBytes ("/copy.aa"), fs.ReadAllBytes ("/copy2.aa")); + } + + [TestMethod] + public async Task SaveToFile_ReadFromBytes_UsesThoseBytes () + { + var data = AudibleTestBuilder.Create (); + var file = AudibleFile.Read (data).File!; + file.Tag.Title = "From bytes"; + var fs = new MockFileSystem (); + + Assert.IsTrue (file.SaveToFile ("/a.aa", fs).IsSuccess); + Assert.IsTrue ((await file.SaveToFileAsync ("/b.aa", fs)).IsSuccess); + Assert.IsTrue (file.SaveToFile ("/c.aa", data, fs).IsSuccess); + Assert.IsTrue ((await file.SaveToFileAsync ("/d.aa", data, fs)).IsSuccess); + + foreach (var path in new[] { "/a.aa", "/b.aa", "/c.aa", "/d.aa" }) + Assert.AreEqual ("From bytes", AudibleFile.Read (fs.ReadAllBytes (path)).File!.Tag.Title, path); + } + + [TestMethod] + public async Task SaveToFile_StreamWithoutAPath_Fails () + { + var opened = MediaFile.Read (new MemoryStream (AudibleTestBuilder.Create ())); + var file = (AudibleFile)opened.File!; + var fs = new MockFileSystem (); + + Assert.IsFalse (file.SaveToFile ("/x.aa", fs).IsSuccess); + Assert.IsFalse ((await file.SaveToFileAsync ("/x.aa", fs)).IsSuccess); + Assert.IsFalse (file.SaveToFile (fs).IsSuccess); + Assert.IsFalse ((await file.SaveToFileAsync (fs)).IsSuccess); + Assert.IsFalse (fs.FileExists ("/x.aa")); + } + + [TestMethod] + public async Task SaveToFile_WrongOriginalData_Fails () + { + var file = AudibleFile.Read (AudibleTestBuilder.Create ()).File!; + var fs = new MockFileSystem (); + + Assert.IsFalse (file.SaveToFile ("/x.aa", new byte[20], fs).IsSuccess); + Assert.IsFalse ((await file.SaveToFileAsync ("/x.aa", new byte[20], fs)).IsSuccess); + Assert.IsFalse (fs.FileExists ("/x.aa")); + } + + [TestMethod] + public async Task SaveToFile_SourceDeleted_Fails () + { + var fs = new MockFileSystem (); + fs.AddFile ("/book.aa", AudibleTestBuilder.Create ()); + var file = AudibleFile.ReadFromFile ("/book.aa", fs).File!; + fs.Delete ("/book.aa"); + + StringAssert.Contains (file.SaveToFile ("/out.aa", fs).Error, "re-read"); + StringAssert.Contains ((await file.SaveToFileAsync ("/out.aa", fs)).Error, "re-read"); + } +} diff --git a/tests/TagLibSharp2.Tests/Audible/AudibleTagTests.cs b/tests/TagLibSharp2.Tests/Audible/AudibleTagTests.cs new file mode 100644 index 00000000..cf1c74fa --- /dev/null +++ b/tests/TagLibSharp2.Tests/Audible/AudibleTagTests.cs @@ -0,0 +1,235 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Audible; +using TagLibSharp2.Core; + +namespace TagLibSharp2.Tests.Audible; + +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Audible")] +public class AudibleTagTests +{ + static readonly string[] ExpectedKeys = ["a", "title", "b"]; + + static AudibleTag Parsed () => AudibleFile.Read (AudibleTestBuilder.Create ()).File!.Tag; + + static AudibleTag RoundTrip (AudibleTag tag) + { + var parsed = AudibleTag.Parse (tag.Render ().Span); + Assert.IsTrue (parsed.IsSuccess, parsed.Error); + return parsed.Tag!; + } + + [TestMethod] + public void EveryNamedProperty_RoundTripsUnderItsKey () + { + var setters = new (string Key, Action Set, Func Get)[] { + (AudibleTag.TitleKey, (t, v) => t.Title = v, t => t.Title), + (AudibleTag.AuthorKey, (t, v) => t.Artist = v, t => t.Artist), + (AudibleTag.AuthorKey, (t, v) => t.Author = v, t => t.Author), + (AudibleTag.NarratorKey, (t, v) => t.Narrator = v, t => t.Narrator), + (AudibleTag.ProviderKey, (t, v) => t.Provider = v, t => t.Provider), + (AudibleTag.PublishDateKey, (t, v) => t.PublishDate = v, t => t.PublishDate), + (AudibleTag.DescriptionKey, (t, v) => t.Description = v, t => t.Description), + (AudibleTag.LongDescriptionKey, (t, v) => t.LongDescription = v, t => t.LongDescription), + (AudibleTag.KeywordsKey, (t, v) => t.Keywords = v, t => t.Keywords), + (AudibleTag.CopyrightKey, (t, v) => t.Copyright = v, t => t.Copyright), + (AudibleTag.ShortTitleKey, (t, v) => t.ShortTitle = v, t => t.ShortTitle), + (AudibleTag.ParentTitleKey, (t, v) => t.ParentTitle = v, t => t.ParentTitle), + (AudibleTag.ParentShortTitleKey, (t, v) => t.ParentShortTitle = v, t => t.ParentShortTitle), + (AudibleTag.ProductIdKey, (t, v) => t.ProductId = v, t => t.ProductId), + (AudibleTag.TitleIdKey, (t, v) => t.TitleId = v, t => t.TitleId), + }; + + foreach (var (key, set, get) in setters) { + var tag = new AudibleTag (); + set (tag, "Ünïcode ✓ " + key); + + var reread = RoundTrip (tag); + + Assert.AreEqual ("Ünïcode ✓ " + key, get (reread), key); + Assert.AreEqual ("Ünïcode ✓ " + key, reread.GetValue (key), key); + set (reread, null); + Assert.IsNull (get (reread), key); + Assert.IsNull (reread.GetValue (key), key); + } + } + + [TestMethod] + public void UnmappedFields_IgnoreAValueAndWriteNothing () + { + var tag = new AudibleTag { + Album = "Album", + Comment = "Comment", + Genre = "Genre", + Track = 3, + Pictures = [new AudibleTestPicture ()] + }; + + Assert.IsNull (tag.Album); + Assert.IsNull (tag.Comment); + Assert.IsNull (tag.Genre); + Assert.IsNull (tag.Track); + Assert.IsEmpty (tag.Pictures); + Assert.IsEmpty (tag.Keys); + Assert.AreEqual (4, tag.Render ().Length); + } + + [TestMethod] + [DataRow ("20-JAN-2009", "2009")] + [DataRow ("2011", "2011")] + [DataRow ("JAN-20", null)] + [DataRow ("abc", null)] + public void Year_IsTheLastFourDigitsOfPubdate (string pubdate, string? year) + { + var tag = new AudibleTag { PublishDate = pubdate }; + + Assert.AreEqual (year, tag.Year); + } + + [TestMethod] + public void Year_Set_KeepsTheDayAndMonth () + { + var tag = new AudibleTag { PublishDate = "20-JAN-2009" }; + + tag.Year = "2012"; + + Assert.AreEqual ("20-JAN-2012", tag.PublishDate); + } + + [TestMethod] + [DataRow ("2012-03-04")] + [DataRow ("2012")] + public void Year_SetWithoutADayMonthDate_StoresTheValue (string value) + { + var tag = new AudibleTag { PublishDate = "sometime" }; + + tag.Year = value; + + Assert.AreEqual (value, tag.PublishDate); + tag.Year = null; + Assert.IsNull (tag.PublishDate); + } + + [TestMethod] + public void SetValue_ExistingKey_KeepsItsPositionAndDropsLaterDuplicates () + { + var dictionary = AudibleTestBuilder.Dictionary ([("a", "1"), ("title", "first"), ("b", "2"), ("title", "second")]); + var tag = AudibleTag.Parse (dictionary).Tag!; + Assert.AreEqual ("first", tag.Title); + + tag.Title = "only"; + + CollectionAssert.AreEqual (ExpectedKeys, tag.Keys.ToList ()); + Assert.AreEqual ("only", RoundTrip (tag).Title); + } + + [TestMethod] + public void SetValue_NewKey_IsAppended () + { + var tag = Parsed (); + + tag.SetValue ("custom_key", "custom value"); + + Assert.AreEqual ("custom_key", tag.Keys[^1]); + Assert.AreEqual ("custom value", RoundTrip (tag).GetValue ("custom_key")); + } + + [TestMethod] + public void SetValue_EmptyRemovesEveryCopy () + { + var tag = AudibleTag.Parse (AudibleTestBuilder.Dictionary ([("k", "1"), ("k", "2")])).Tag!; + + tag.SetValue ("k", ""); + + Assert.IsEmpty (tag.Keys); + } + + [TestMethod] + [DataRow ("codec")] + [DataRow ("HeaderSeed")] + [DataRow ("HeaderKey")] + [DataRow ("EncryptedBlocks")] + public void SetValue_DrmKey_Throws (string key) + { + var tag = Parsed (); + + Assert.ThrowsExactly (() => tag.SetValue (key, "x")); + Assert.ThrowsExactly (() => tag.SetValue (key, null)); + Assert.IsNotNull (tag.GetValue (key)); + } + + [TestMethod] + [DataRow ("")] + [DataRow ("clé")] + public void SetValue_BadKey_Throws (string key) + { + Assert.ThrowsExactly (() => new AudibleTag ().SetValue (key, "x")); + } + + [TestMethod] + public void Clear_RemovesDescriptiveKeysOnly () + { + var tag = Parsed (); + Assert.IsFalse (tag.IsEmpty); + + tag.Clear (); + + Assert.IsTrue (tag.IsEmpty); + Assert.IsNull (tag.Title); + Assert.IsNull (tag.Narrator); + Assert.AreEqual ("acelp85", tag.Codec); + Assert.AreEqual ("2348022159 2271241904 4180629618 1869089845", tag.GetValue ("HeaderKey")); + Assert.AreEqual ("PF_TEST_000001", tag.TitleId); + } + + [TestMethod] + public void IsEmpty_TrueForANewTag_FalseWithAnyDescriptiveKey () + { + var tag = new AudibleTag (); + Assert.IsTrue (tag.IsEmpty); + + tag.SetValue ("unknown", "x"); + Assert.IsTrue (tag.IsEmpty); + + tag.Keywords = "k"; + Assert.IsFalse (tag.IsEmpty); + } + + [TestMethod] + public void Parse_ShorterThanTheCount_Fails () + { + Assert.IsFalse (AudibleTag.Parse ([0, 0, 0]).IsSuccess); + Assert.IsTrue (AudibleTag.Parse ([0, 0, 0, 0]).IsSuccess); + } + + [TestMethod] + public void Parse_EveryTruncation_FailsWithoutThrowing () + { + var dictionary = AudibleTestBuilder.Dictionary (AudibleTestBuilder.DefaultEntries); + + for (var length = 0; length < dictionary.Length; length++) + Assert.IsFalse (AudibleTag.Parse (dictionary.AsSpan (0, length)).IsSuccess, $"length {length}"); + Assert.AreEqual (dictionary.Length, AudibleTag.Parse (dictionary).BytesConsumed); + } + + [TestMethod] + public void Render_IsThePublishedLayout () + { + var tag = new AudibleTag { Title = "T" }; + + CollectionAssert.AreEqual ( + new byte[] { 0, 0, 0, 1, 0, 0, 0, 0, 5, 0, 0, 0, 1, (byte)'t', (byte)'i', (byte)'t', (byte)'l', (byte)'e', (byte)'T' }, + tag.Render ().ToArray ()); + } + + sealed class AudibleTestPicture : IPicture + { + public string MimeType => "image/png"; + public PictureType PictureType => PictureType.FrontCover; + public string Description => ""; + public BinaryData PictureData => new ([1, 2, 3]); + } +} diff --git a/tests/TagLibSharp2.Tests/Audible/AudibleTestBuilder.cs b/tests/TagLibSharp2.Tests/Audible/AudibleTestBuilder.cs new file mode 100644 index 00000000..a5c44a88 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Audible/AudibleTestBuilder.cs @@ -0,0 +1,219 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Buffers.Binary; +using System.Text; + +namespace TagLibSharp2.Tests.Audible; + +/// +/// Builds Audible .aa files with the layout of the real samples: a 16-byte header, a 12-entry +/// table of contents (types 0 to 11 in order), and chunks 1 to 11 back to back. +/// +internal static class AudibleTestBuilder +{ + public const uint Magic = 0x57907536; + public const int HeaderSize = 16; + public const int TocEntries = 12; + public const int TocEnd = HeaderSize + (TocEntries * 12); + + public static readonly (string Key, string Value)[] DefaultEntries = [ + ("product_id", "PF_TEST_000001_acelp85"), + ("title", "A Test Book (Unabridged)"), + ("author", "Ann Author"), + ("provider", "Test Provider"), + ("narrator", "Ned Narrator"), + ("price", "1.98"), + ("pubdate", "20-JAN-2009"), + ("description", "Short description."), + ("keywords", "one, two"), + ("long_description", "A longer description of the book."), + ("copyright", "©2009 Ann Author; (P)2009 Test"), + ("short_title", "A Test Book"), + ("title_id", "PF_TEST_000001"), + ("codec", "acelp85"), + ("HeaderSeed", "74039501"), + ("EncryptedBlocks", "6457"), + ("HeaderKey", "2348022159 2271241904 4180629618 1869089845"), + ("license_list", "55035360"), + ("CPUType", "1"), + ("license_count", "1"), + ("68ec733412b9", "6BBD842E462FE82ED754F4EBC32C096EF3120A54"), + ("parent_short_title", "A Test Book"), + ("parent_title", "A Test Book (Unabridged)"), + ("pub_date_start", "20-JAN-2009"), + ("short_description", "Short description."), + ("user_alias", "someone"), + ]; + + /// A tiny JPEG-looking image (SOI marker, filler, EOI marker). + public static byte[] Jpeg () + { + var image = new byte[64]; + image[0] = 0xFF; + image[1] = 0xD8; + image[2] = 0xFF; + image[3] = 0xE0; + for (var i = 4; i < image.Length - 2; i++) + image[i] = (byte)(i * 3); + image[^2] = 0xFF; + image[^1] = 0xD9; + return image; + } + + /// An audio chunk whose bytes are easy to find after a save. + public static byte[] Audio (int length) + { + var audio = new byte[length]; + for (var i = 0; i < audio.Length; i++) + audio[i] = (byte)(0x5A ^ (i * 7)); + return audio; + } + + public static byte[] Dictionary (IEnumerable<(string Key, string Value)> entries) + { + using var ms = new MemoryStream (); + var list = entries.ToList (); + WriteU32 (ms, (uint)list.Count); + foreach (var (key, value) in list) { + var k = Encoding.ASCII.GetBytes (key); + var v = Encoding.UTF8.GetBytes (value); + ms.WriteByte (0); + WriteU32 (ms, (uint)k.Length); + WriteU32 (ms, (uint)v.Length); + ms.Write (k, 0, k.Length); + ms.Write (v, 0, v.Length); + } + return ms.ToArray (); + } + + /// + /// Builds a whole file. null leaves chunk 11 empty. + /// + public static byte[] Create ( + IEnumerable<(string Key, string Value)>? entries = null, + byte[]? audio = null, + byte[]? cover = null, + string? codec = null) + { + var list = (entries ?? DefaultEntries).ToList (); + if (codec is not null) + list = list.Select (e => e.Key == "codec" ? (e.Key, codec) : e).ToList (); + return CreateRaw (Dictionary (list), audio ?? Audio (8500), cover); + } + + /// + /// Builds a whole file around raw dictionary bytes. + /// + public static byte[] CreateRaw (byte[] dictionary, byte[] audio, byte[]? cover) + { + var chunks = new byte[12][]; + chunks[1] = Concat (U32 (0x00010000), U32 (Magic), new byte[16]); + chunks[2] = dictionary; + chunks[3] = Filler (74, 3); + chunks[4] = new byte[4]; + chunks[5] = Concat (U32 (1), U32 (0x3288B995)); + chunks[6] = Concat (U32 (1), U32 (3), U32 (0xFFFFFFFF), U32 (0xFFFFFFFF), U32 ((uint)audio.Length), U32 (2), U16 (0xC010), U32 (2), U32 (0), U32 (0), U32 (1), U32 (0x415)); + chunks[7] = Filler (16, 7); + chunks[8] = new byte[4]; + chunks[9] = []; + chunks[10] = audio; + chunks[11] = []; // placeholder, filled once its offset is known + + var offsets = new uint[12]; + var position = (uint)TocEnd; + for (var t = 1; t <= 11; t++) { + offsets[t] = position; + if (t == 11 && cover is not null) + chunks[11] = Concat (U32 ((uint)cover.Length), U32 (position + 8), cover); + position += (uint)chunks[t].Length; + } + + var total = position; + using var ms = new MemoryStream (); + WriteU32 (ms, total); + WriteU32 (ms, Magic); + WriteU32 (ms, TocEntries); + WriteU32 (ms, 0); + WriteU32 (ms, 0); + WriteU32 (ms, 0); + WriteU32 (ms, total); + for (var t = 1; t <= 11; t++) { + WriteU32 (ms, (uint)t); + WriteU32 (ms, offsets[t]); + WriteU32 (ms, (uint)chunks[t].Length); + } + for (var t = 1; t <= 11; t++) + ms.Write (chunks[t], 0, chunks[t].Length); + return ms.ToArray (); + } + + public static (uint Type, uint Offset, uint Size) Toc (byte[] file, int index) + { + var at = HeaderSize + (index * 12); + return ( + BinaryPrimitives.ReadUInt32BigEndian (file.AsSpan (at)), + BinaryPrimitives.ReadUInt32BigEndian (file.AsSpan (at + 4)), + BinaryPrimitives.ReadUInt32BigEndian (file.AsSpan (at + 8))); + } + + public static byte[] Chunk (byte[] file, int index) + { + var (_, offset, size) = Toc (file, index); + return file.AsSpan ((int)offset, (int)size).ToArray (); + } + + public static uint ReadU32 (byte[] file, int offset) => + BinaryPrimitives.ReadUInt32BigEndian (file.AsSpan (offset)); + + public static void SetU32 (byte[] file, int offset, uint value) => + BinaryPrimitives.WriteUInt32BigEndian (file.AsSpan (offset), value); + + static byte[] Filler (int length, int seed) + { + var data = new byte[length]; + for (var i = 0; i < length; i++) + data[i] = (byte)(seed + (i * 11)); + return data; + } + + static byte[] U32 (uint value) + { + var data = new byte[4]; + BinaryPrimitives.WriteUInt32BigEndian (data, value); + return data; + } + + static byte[] U16 (ushort value) + { + var data = new byte[2]; + BinaryPrimitives.WriteUInt16BigEndian (data, value); + return data; + } + + static void WriteU32 (Stream stream, uint value) + { + var data = U32 (value); + stream.Write (data, 0, 4); + } + + public static byte[] Concat (params byte[][] parts) + { + var result = new byte[parts.Sum (p => p.Length)]; + var offset = 0; + foreach (var part in parts) { + part.CopyTo (result, offset); + offset += part.Length; + } + return result; + } + + public static int IndexOf (byte[] haystack, byte[] needle) + { + for (var i = 0; i + needle.Length <= haystack.Length; i++) { + if (haystack.AsSpan (i, needle.Length).SequenceEqual (needle)) + return i; + } + return -1; + } +} diff --git a/tests/TagLibSharp2.Tests/Core/ScanWithoutAudioTests.cs b/tests/TagLibSharp2.Tests/Core/ScanWithoutAudioTests.cs index 38dbfe44..3715bfe4 100644 --- a/tests/TagLibSharp2.Tests/Core/ScanWithoutAudioTests.cs +++ b/tests/TagLibSharp2.Tests/Core/ScanWithoutAudioTests.cs @@ -6,6 +6,7 @@ using TagLibSharp2.Aiff; using TagLibSharp2.Ape; using TagLibSharp2.Asf; +using TagLibSharp2.Audible; using TagLibSharp2.Core; using TagLibSharp2.Dff; using TagLibSharp2.Dsf; @@ -16,6 +17,7 @@ using TagLibSharp2.Ogg; using TagLibSharp2.Tests; using TagLibSharp2.Tests.Asf; +using TagLibSharp2.Tests.Audible; using TagLibSharp2.WavPack; using TagLibSharp2.Xiph; @@ -159,6 +161,17 @@ public async Task ReadAsync_Musepack_SkipsPackets () => [TestMethod] public async Task ReadAsync_Asf_SkipsDataObject () => await AssertScanAsync (AsfWithPackets (), "song.wma"); + [TestMethod] + public void Read_Audible_SkipsAudio () => AssertScan (AudibleWithAudio (), "book.aa"); + + [TestMethod] + public async Task ReadAsync_Audible_SkipsAudio () => await AssertScanAsync (AudibleWithAudio (), "book.aa"); + + static byte[] AudibleWithAudio () => AudibleTestBuilder.Create ( + AudibleTestBuilder.DefaultEntries.Select (e => e.Key == "title" ? (e.Key, "Window") : e), + audio: Payload (), + cover: AudibleTestBuilder.Jpeg ()); + static void AssertScan (byte[] file, string name, bool contiguous = true) { var loaded = MediaFile.ReadFromData (file, name); @@ -253,6 +266,7 @@ static void AssertStreamWithoutAPathDoesNotWrite (byte[] file, string name) DsfFile dsf => dsf.SaveToFile (path, fileSystem), DffFile dff => dff.SaveToFile (path, fileSystem), AsfFile asf => asf.SaveToFile (path, fileSystem), + AudibleFile audible => audible.SaveToFile (path, fileSystem), _ => FileWriteResult.Failure ("Unsupported file " + file.GetType ().Name) }; @@ -269,6 +283,7 @@ static void AssertStreamWithoutAPathDoesNotWrite (byte[] file, string name) DsfFile dsf => dsf.SaveToFileAsync (path, fileSystem), DffFile dff => dff.SaveToFileAsync (path, fileSystem), AsfFile asf => asf.SaveToFileAsync (path, fileSystem), + AudibleFile audible => audible.SaveToFileAsync (path, fileSystem), _ => Task.FromResult (FileWriteResult.Failure ("Unsupported file " + file.GetType ().Name)) }; diff --git a/tests/TagLibSharp2.Tests/MalformedInputTests.cs b/tests/TagLibSharp2.Tests/MalformedInputTests.cs index f2d93156..f8d34e51 100644 --- a/tests/TagLibSharp2.Tests/MalformedInputTests.cs +++ b/tests/TagLibSharp2.Tests/MalformedInputTests.cs @@ -3,6 +3,7 @@ using TagLibSharp2.Aiff; using TagLibSharp2.Ape; +using TagLibSharp2.Audible; using TagLibSharp2.Core; using TagLibSharp2.Dff; using TagLibSharp2.Dsf; @@ -898,4 +899,62 @@ public void ApeTag_RandomData_DoesNotCrash () Assert.IsFalse (result.IsSuccess, "Random data should fail without crashing"); } + + [TestMethod] + public void AudibleFile_EmptyInput_ReturnsFailure () + { + var result = AudibleFile.Read ([]); + Assert.IsFalse (result.IsSuccess, "Empty input should return failure, not crash"); + } + + [TestMethod] + public void AudibleFile_TruncatedHeader_ReturnsFailure () + { + byte[] data = [0x00, 0x00, 0x10, 0x00, 0x57, 0x90, 0x75, 0x36, 0x00, 0x00, 0x00]; + Assert.IsFalse (AudibleFile.Read (data).IsSuccess); + } + + [TestMethod] + public void AudibleFile_WrongMagic_ReturnsFailure () + { + var data = new byte[200]; + data[4] = 0x57; + Assert.IsFalse (AudibleFile.Read (data).IsSuccess); + } + + [TestMethod] + public void AudibleFile_OversizedTocCount_DoesNotAllocate () + { + // The count claims four billion entries; the reader must reject it before sizing anything. + byte[] data = [0x00, 0x00, 0x00, 0x20, 0x57, 0x90, 0x75, 0x36, 0xFF, 0xFF, 0xFF, 0xFF, 0, 0, 0, 0]; + Assert.IsFalse (AudibleFile.Read (data).IsSuccess); + Assert.IsFalse (MediaFile.Read (new MemoryStream (data)).IsSuccess); + } + + [TestMethod] + public void AudibleFile_AllZerosAndAllOnes_ReturnFailure () + { + Assert.IsFalse (AudibleFile.Read (new byte[1024]).IsSuccess); + Assert.IsFalse (AudibleFile.Read (Enumerable.Repeat ((byte)0xFF, 1024).ToArray ()).IsSuccess); + } + + [TestMethod] + public void AudibleFile_RandomDataWithMagic_DoesNotCrash () + { + var random = new Random (42); + for (var i = 0; i < 500; i++) { + var data = new byte[random.Next (16, 600)]; + random.NextBytes (data); + data[4] = 0x57; + data[5] = 0x90; + data[6] = 0x75; + data[7] = 0x36; + data[8] = 0; + data[9] = 0; + data[10] = 0; + data[11] = (byte)random.Next (1, 16); + _ = AudibleFile.Read (data); + _ = MediaFile.Read (new MemoryStream (data)); + } + } } diff --git a/tests/TagLibSharp2.Tests/Mp4/Mp4AudibleAtomTests.cs b/tests/TagLibSharp2.Tests/Mp4/Mp4AudibleAtomTests.cs new file mode 100644 index 00000000..0e6c0c51 --- /dev/null +++ b/tests/TagLibSharp2.Tests/Mp4/Mp4AudibleAtomTests.cs @@ -0,0 +1,169 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using System.Text; +using TagLibSharp2.Core; +using TagLibSharp2.Mp4; + +namespace TagLibSharp2.Tests.Mp4; + +/// +/// Audible .aax files are MPEG-4. Their audiobook atoms map to named properties. +/// +[TestClass] +[TestCategory ("Unit")] +[TestCategory ("Mp4")] +[TestCategory ("Audible")] +public class Mp4AudibleAtomTests +{ + static readonly (string Atom, Action Set, Func Get, Func FileGet, Action FileSet)[] Atoms = [ + ("©nrt", (t, v) => t.Narrator = v, t => t.Narrator, f => f.Narrator, (f, v) => f.Narrator = v), + ("@sti", (t, v) => t.ShortTitle = v, t => t.ShortTitle, f => f.ShortTitle, (f, v) => f.ShortTitle = v), + ("@pti", (t, v) => t.ParentTitle = v, t => t.ParentTitle, f => f.ParentTitle, (f, v) => f.ParentTitle = v), + ("@PST", (t, v) => t.ParentShortTitle = v, t => t.ParentShortTitle, f => f.ParentShortTitle, (f, v) => f.ParentShortTitle = v), + ("@ppi", (t, v) => t.ParentProductId = v, t => t.ParentProductId, f => f.ParentProductId, (f, v) => f.ParentProductId = v), + ("prID", (t, v) => t.ProductId = v, t => t.ProductId, f => f.ProductId, (f, v) => f.ProductId = v), + ("rldt", (t, v) => t.ReleaseDate = v, t => t.ReleaseDate, f => f.ReleaseDate, (f, v) => f.ReleaseDate = v), + ("VERS", (t, v) => t.ProductVersion = v, t => t.ProductVersion, f => f.ProductVersion, (f, v) => f.ProductVersion = v), + ]; + + [TestMethod] + public void AudibleAtoms_RoundTripUnderTheirExactCodes () + { + var data = TestBuilders.Mp4.CreateMinimalM4a (Mp4CodecType.Aac); + + foreach (var (atom, set, get, _, _) in Atoms) { + var file = Mp4File.Read (data).File!; + file.Tag ??= new Mp4Tag (); + set (file.Tag, "Value for " + atom); + + var rendered = file.Render (data).ToArray (); + + // '@' is 0x40 and '©' is 0xA9: the codes are Latin-1 bytes, not UTF-8. + var code = Encoding.Latin1.GetBytes (atom); + Assert.IsTrue (IndexOf (rendered, code) >= 0, $"{atom} not written"); + var reread = Mp4File.Read (rendered).File!; + Assert.AreEqual ("Value for " + atom, get (reread.Tag!), atom); + + set (reread.Tag!, null); + Assert.IsNull (get (Mp4File.Read (reread.Render (rendered).Span).File!.Tag ?? new Mp4Tag ()), atom); + } + } + + [TestMethod] + public void AudibleAtoms_FileForwardersMatchTheTag () + { + var data = TestBuilders.Mp4.CreateMinimalM4a (Mp4CodecType.Aac); + + foreach (var (atom, _, get, fileGet, fileSet) in Atoms) { + var file = Mp4File.Read (data).File!; + Assert.IsNull (fileGet (file), atom); + + fileSet (file, "Forwarded " + atom); + + Assert.AreEqual ("Forwarded " + atom, fileGet (file), atom); + Assert.AreEqual ("Forwarded " + atom, get (file.Tag!), atom); + } + } + + [TestMethod] + [DataRow ("CDEK")] + [DataRow ("CDET")] + [DataRow ("AACR")] + [DataRow ("GUID")] + public void UnnamedAudibleItem_SurvivesASave (string code) + { + // Audible writes these items too; nothing maps them, so a save must carry them through. + var data = TestBuilders.Mp4.CreateMinimalM4a (Mp4CodecType.Aac); + var file = Mp4File.Read (data).File!; + file.ProductVersion = "opaque value"; + var withItem = file.Render (data).ToArray (); + Encoding.ASCII.GetBytes (code).CopyTo (withItem, IndexOf (withItem, "VERS"u8.ToArray ())); + + var reread = Mp4File.Read (withItem).File!; + Assert.IsNull (reread.ProductVersion); + reread.Narrator = "Changed"; + var saved = reread.Render (withItem).ToArray (); + + Assert.IsTrue (IndexOf (saved, Encoding.ASCII.GetBytes (code)) >= 0, $"{code} dropped on save"); + Assert.IsTrue (IndexOf (saved, "opaque value"u8.ToArray ()) >= 0); + Assert.AreEqual ("Changed", Mp4File.Read (saved).File!.Narrator); + } + + [TestMethod] + public void AudibleAtom_SetOnAFileThatHasIt_LeavesOneItem () + { + var data = TestBuilders.Mp4.CreateMinimalM4a (Mp4CodecType.Aac); + var file = Mp4File.Read (data).File!; + file.Narrator = "First"; + var first = file.Render (data).ToArray (); + + var again = Mp4File.Read (first).File!; + again.Narrator = "Second"; + var saved = again.Render (first).ToArray (); + + var code = Encoding.Latin1.GetBytes ("\u00A9nrt"); + var at = IndexOf (saved, code); + Assert.IsTrue (at >= 0); + Assert.AreEqual (-1, IndexOf (saved.AsSpan (at + 4).ToArray (), code), "a second narrator item"); + Assert.AreEqual (-1, IndexOf (saved, "First"u8.ToArray ())); + Assert.AreEqual ("Second", Mp4File.Read (saved).File!.Narrator); + } + + [TestMethod] + public void AudibleAtoms_InAQuickTimeKeyedMeta_RoundTrip () + { + // An mdta meta names items through keys. An Audible atom has no key name, so it is written + // under a "udta"-namespace key holding its atom code, and read back through that key. + var data = TestBuilders.Mp4.CreateWithKeyedMeta ("mdta", TestBuilders.Mp4.KeysPayload ("title"), [TestBuilders.Mp4.CreateMdtaItem (1, "T")], inMovie: false, udtaExtra: null); + + foreach (var (atom, set, get, _, _) in Atoms) { + var file = Mp4File.Read (data).File!; + set (file.Tag!, "Keyed " + atom); + + var reread = Mp4File.Read (file.Render (data).Span).File!; + + Assert.AreEqual ("Keyed " + atom, get (reread.Tag!), atom); + Assert.AreEqual ("T", reread.Tag!.Title, atom); + } + } + + [TestMethod] + public void AaxBrand_OpensAsMp4WithTheBrandAsFileType () + { + var data = TestBuilders.Mp4.CreateMinimalM4a (Mp4CodecType.Aac); + Encoding.ASCII.GetBytes ("aax ").CopyTo (data, 8); + + var result = MediaFile.ReadFromData (data, "book.aax"); + + Assert.IsTrue (result.IsSuccess, result.Error); + Assert.AreEqual (MediaFormat.Mp4, result.Format); + Assert.AreEqual ("aax", ((Mp4File)result.File!).FileType); + } + + [TestMethod] + public void AavdSampleEntry_IsAac () + { + // .aax keeps AAC in an "aavd" sample entry with the mp4a layout and esds. + var data = TestBuilders.Mp4.CreateMinimalM4a (Mp4CodecType.Aac); + var at = IndexOf (data, "mp4a"u8.ToArray ()); + Encoding.ASCII.GetBytes ("aavd").CopyTo (data, at); + + var file = Mp4File.Read (data).File!; + + Assert.AreEqual (Mp4AudioCodec.Aac, file.AudioCodec); + Assert.AreEqual ("AAC", file.Properties.Codec); + var mp4a = TestBuilders.Mp4.CreateMinimalM4a (Mp4CodecType.Aac); + Assert.AreEqual (Mp4File.Read (mp4a).File!.Properties, file.Properties); + Assert.AreEqual (Mp4AudioPropertiesParser.Parse (mp4a), Mp4AudioPropertiesParser.Parse (data)); + } + + static int IndexOf (byte[] haystack, byte[] needle) + { + for (var i = 0; i + needle.Length <= haystack.Length; i++) { + if (haystack.AsSpan (i, needle.Length).SequenceEqual (needle)) + return i; + } + return -1; + } +} diff --git a/tests/TagLibSharp2.Tests/PublicApi/Snapshots/TagLibSharp2.PublicApi.verified.txt b/tests/TagLibSharp2.Tests/PublicApi/Snapshots/TagLibSharp2.PublicApi.verified.txt index 9dfe3d33..eb202518 100644 --- a/tests/TagLibSharp2.Tests/PublicApi/Snapshots/TagLibSharp2.PublicApi.verified.txt +++ b/tests/TagLibSharp2.Tests/PublicApi/Snapshots/TagLibSharp2.PublicApi.verified.txt @@ -658,6 +658,96 @@ namespace TagLibSharp2.Asf public TagLibSharp2.Core.BinaryData RenderContentDescription() { } } } +namespace TagLibSharp2.Audible +{ + public sealed class AudibleFile : System.IDisposable, TagLibSharp2.Core.IMediaFile + { + public const uint Magic = 1469084982u; + public uint DeclaredFileSize { get; } + public TagLibSharp2.Core.MediaFormat Format { get; } + public TagLibSharp2.Core.AudioProperties Properties { get; } + public string? SourcePath { get; } + public TagLibSharp2.Audible.AudibleTag Tag { get; } + public void Dispose() { } + public TagLibSharp2.Core.BinaryData Render(System.ReadOnlySpan originalData) { } + public TagLibSharp2.Core.FileWriteResult SaveToFile(TagLibSharp2.Core.IFileSystem? fileSystem = null) { } + public TagLibSharp2.Core.FileWriteResult SaveToFile(string path, TagLibSharp2.Core.IFileSystem? fileSystem = null) { } + public TagLibSharp2.Core.FileWriteResult SaveToFile(string path, System.ReadOnlySpan originalData, TagLibSharp2.Core.IFileSystem? fileSystem = null) { } + public System.Threading.Tasks.Task SaveToFileAsync(TagLibSharp2.Core.IFileSystem? fileSystem = null, System.Threading.CancellationToken cancellationToken = default) { } + public System.Threading.Tasks.Task SaveToFileAsync(string path, TagLibSharp2.Core.IFileSystem? fileSystem = null, System.Threading.CancellationToken cancellationToken = default) { } + public System.Threading.Tasks.Task SaveToFileAsync(string path, System.ReadOnlyMemory originalData, TagLibSharp2.Core.IFileSystem? fileSystem = null, System.Threading.CancellationToken cancellationToken = default) { } + public static bool IsValidFormat(System.ReadOnlySpan data) { } + public static TagLibSharp2.Audible.AudibleFileReadResult Read(System.ReadOnlySpan data) { } + public static TagLibSharp2.Audible.AudibleFileReadResult ReadFromFile(string path, TagLibSharp2.Core.IFileSystem? fileSystem = null) { } + public static System.Threading.Tasks.Task ReadFromFileAsync(string path, TagLibSharp2.Core.IFileSystem? fileSystem = null, System.Threading.CancellationToken cancellationToken = default) { } + public static bool TryRead(System.ReadOnlySpan data, out TagLibSharp2.Audible.AudibleFile? file) { } + } + public readonly struct AudibleFileReadResult : System.IEquatable + { + public string? Error { get; } + public TagLibSharp2.Audible.AudibleFile? File { get; } + public bool IsSuccess { get; } + public bool Equals(TagLibSharp2.Audible.AudibleFileReadResult other) { } + public override bool Equals(object? obj) { } + public override int GetHashCode() { } + public static TagLibSharp2.Audible.AudibleFileReadResult Failure(string error) { } + public static TagLibSharp2.Audible.AudibleFileReadResult Success(TagLibSharp2.Audible.AudibleFile file) { } + public static bool operator !=(TagLibSharp2.Audible.AudibleFileReadResult left, TagLibSharp2.Audible.AudibleFileReadResult right) { } + public static bool operator ==(TagLibSharp2.Audible.AudibleFileReadResult left, TagLibSharp2.Audible.AudibleFileReadResult right) { } + } + public sealed class AudibleTag : TagLibSharp2.Core.Tag + { + public const string AuthorKey = "author"; + public const string CodecKey = "codec"; + public const string CopyrightKey = "copyright"; + public const string DescriptionKey = "description"; + public const string KeywordsKey = "keywords"; + public const string LongDescriptionKey = "long_description"; + public const string NarratorKey = "narrator"; + public const string ParentShortTitleKey = "parent_short_title"; + public const string ParentTitleKey = "parent_title"; + public const string PriceKey = "price"; + public const string ProductIdKey = "product_id"; + public const string ProviderKey = "provider"; + public const string PublishDateKey = "pubdate"; + public const string PublishDateStartKey = "pub_date_start"; + public const string ShortDescriptionKey = "short_description"; + public const string ShortTitleKey = "short_title"; + public const string TitleIdKey = "title_id"; + public const string TitleKey = "title"; + public AudibleTag() { } + public override string? Album { get; set; } + public override string? Artist { get; set; } + public string? Author { get; set; } + public string? Codec { get; } + public override string? Comment { get; set; } + public override string? Copyright { get; set; } + public override string? Description { get; set; } + public override string? Genre { get; set; } + public override bool IsEmpty { get; } + public System.Collections.Generic.IReadOnlyList Keys { get; } + public string? Keywords { get; set; } + public string? LongDescription { get; set; } + public string? Narrator { get; set; } + public string? ParentShortTitle { get; set; } + public string? ParentTitle { get; set; } + public override TagLibSharp2.Core.IPicture[] Pictures { get; set; } + public string? ProductId { get; set; } + public string? Provider { get; set; } + public string? PublishDate { get; set; } + public string? ShortTitle { get; set; } + public override TagLibSharp2.Core.TagTypes TagType { get; } + public override string? Title { get; set; } + public string? TitleId { get; set; } + public override uint? Track { get; set; } + public override string? Year { get; set; } + public override void Clear() { } + public string? GetValue(string key) { } + public override TagLibSharp2.Core.BinaryData Render() { } + public void SetValue(string key, string? value) { } + public static TagLibSharp2.Core.TagReadResult Parse(System.ReadOnlySpan data) { } + } +} namespace TagLibSharp2.Core { public static class AtomicFileWriter @@ -1101,6 +1191,7 @@ namespace TagLibSharp2.Core Asf = 13, Musepack = 14, Matroska = 15, + Audible = 16, } [System.Flags] public enum MediaTypes @@ -1275,6 +1366,7 @@ namespace TagLibSharp2.Core Matroska = 128, FlacMetadata = 256, Xmp = 512, + Audible = 1024, AllTags = -1, } public sealed class ValidationIssue @@ -2402,22 +2494,30 @@ namespace TagLibSharp2.Mp4 public string? MusicBrainzReleaseCountry { get; set; } public string? MusicBrainzReleaseStatus { get; set; } public string? MusicBrainzReleaseType { get; set; } + public string? Narrator { get; set; } public string? OriginalReleaseDate { get; set; } + public string? ParentProductId { get; set; } + public string? ParentShortTitle { get; set; } + public string? ParentTitle { get; set; } public TagLibSharp2.Core.IPicture[] Pictures { get; } public string? PodcastCategory { get; set; } public string? PodcastEpisodeGuid { get; set; } public string? PodcastFeedUrl { get; set; } public string? PodcastKeywords { get; set; } + public string? ProductId { get; set; } + public string? ProductVersion { get; set; } public TagLibSharp2.Core.AudioProperties Properties { get; } public string? R128AlbumGain { get; set; } public double? R128AlbumGainDb { get; set; } public string? R128TrackGain { get; set; } public double? R128TrackGainDb { get; set; } + public string? ReleaseDate { get; set; } public string? Remixer { get; set; } public string? ReplayGainAlbumGain { get; set; } public string? ReplayGainAlbumPeak { get; set; } public string? ReplayGainTrackGain { get; set; } public string? ReplayGainTrackPeak { get; set; } + public string? ShortTitle { get; set; } public string? SourcePath { get; } public string? Subtitle { get; set; } public TagLibSharp2.Mp4.Mp4Tag? Tag { get; set; } @@ -2532,20 +2632,28 @@ namespace TagLibSharp2.Mp4 public override string? MusicBrainzReleaseType { get; set; } public override string? MusicBrainzTrackId { get; set; } public override string? MusicBrainzWorkId { get; set; } + public string? Narrator { get; set; } public override string? OriginalReleaseDate { get; set; } + public string? ParentProductId { get; set; } + public string? ParentShortTitle { get; set; } + public string? ParentTitle { get; set; } public override TagLibSharp2.Core.IPicture[] Pictures { get; set; } public string? PodcastCategory { get; set; } public string? PodcastEpisodeGuid { get; set; } public override string? PodcastFeedUrl { get; set; } public string? PodcastKeywords { get; set; } + public string? ProductId { get; set; } + public string? ProductVersion { get; set; } public override string? Publisher { get; set; } public override string? R128AlbumGain { get; set; } public override string? R128TrackGain { get; set; } + public string? ReleaseDate { get; set; } public override string? Remixer { get; set; } public override string? ReplayGainAlbumGain { get; set; } public override string? ReplayGainAlbumPeak { get; set; } public override string? ReplayGainTrackGain { get; set; } public override string? ReplayGainTrackPeak { get; set; } + public string? ShortTitle { get; set; } public override string? Subtitle { get; set; } public override TagLibSharp2.Core.TagTypes TagType { get; } public override string? Title { get; set; }