From a5a43903ec7014c5449b0760275d0c7a9bbd89e0 Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Thu, 3 Dec 2026 17:55:35 -0700 Subject: [PATCH 1/7] docs: Move the roadmap to GitHub issues and remove ROADMAP files ROADMAP.md and docs/ROADMAP.md were stale: most of what they listed as planned has shipped, and the root file named a private local path. Their open items move to GitHub issues and the TagLibSharp2 project board; the README's Future list becomes a Roadmap link and a short Not planned section (disc audio formats, XMP in audio files, Audible decryption). The migration guide's "not yet supported" list drops MPEG-4 video, which opens as MP4, adds APEv2 in MP3 and image Exif/IPTC, and links the board. --- README.md | 12 +- ROADMAP.md | 394 ---------------------------------- docs/MIGRATION-FROM-TAGLIB.md | 6 +- docs/ROADMAP.md | 262 ---------------------- 4 files changed, 12 insertions(+), 662 deletions(-) delete mode 100644 ROADMAP.md delete mode 100644 docs/ROADMAP.md diff --git a/README.md b/README.md index 2fa15f19..4af2b92b 100644 --- a/README.md +++ b/README.md @@ -322,9 +322,15 @@ This is a clean-room rewrite of media tagging functionality, designed from speci - [x] Duration from every ADTS frame header, profile, sample rate, channels - [x] ID3v2, APEv2, and ID3v1 tags; saves keep the frame bytes -### Future -- [ ] Speex format (Ogg container support exists) -- [ ] TrueAudio format +### Roadmap + +Planned work is tracked in [GitHub issues](https://github.com/decriptor/TagLibSharp2/issues), grouped by milestone, and on the [TagLibSharp2 project board](https://github.com/users/decriptor/projects/7). + +### Not planned + +- DVD-Audio and Blu-ray audio: these are disc formats, not audio files. +- XMP metadata in audio files. Still images update the XMP copies of the fields they edit. +- Decrypting Audible audio. ## Documentation diff --git a/ROADMAP.md b/ROADMAP.md deleted file mode 100644 index ad7b933b..00000000 --- a/ROADMAP.md +++ /dev/null @@ -1,394 +0,0 @@ -# TagLibSharp2 Implementation Roadmap - -## Current Status Overview - -Based on the specification in `/Users/sshaw/code/roon-8/Docs/TagLibSharp2/` and the current codebase. - -### Legend -- βœ… Implemented -- πŸ”Ά Partial (needs more work) -- ❌ Not started - ---- - -## Phase 1: Core Infrastructure - -| Component | Status | Notes | -|-----------|--------|-------| -| BinaryData (ByteVector equivalent) | βœ… | Immutable binary data with Span support | -| BinaryDataBuilder | βœ… | For building binary data | -| Tag base class | βœ… | Full property set including MusicBrainz, ReplayGain | -| IFileSystem abstraction | βœ… | With async support | -| Picture/IPicture | βœ… | PictureType enum complete | -| AudioProperties/IMediaProperties | βœ… | Base interfaces defined | -| TagValidation | βœ… | Validation result types | -| AtomicFileWriter | βœ… | Safe file writing | -| Endian readers | πŸ”Ά | In BinaryData, may need standalone EndianReader class | -| Syncsafe integer utilities | βœ… | BinaryData.ToSyncSafeUInt32, BinaryDataBuilder.AddSyncSafeUInt32 | -| Extended float (80-bit) for AIFF | βœ… | ExtendedFloat class with full ToDouble/FromDouble/ToBytes support | -| ITagLibStream interface | ❌ | Stream abstraction from spec (alternative to IFileSystem) | -| Format detection factory | βœ… | MediaFile.Read with magic byte detection | - ---- - -## Phase 2: Tag Formats - -### ID3v1 Tag -| Feature | Status | -|---------|--------| -| Read | βœ… | -| Write | βœ… | -| Genre lookup | βœ… | -| ID3v1.1 track number | βœ… | - -### ID3v2 Tag -| Feature | Status | -|---------|--------| -| Header parsing | βœ… | -| v2.2 support (3-char frames) | βœ… | Read and mapped to ID3v2.3 IDs. A save writes the tag as ID3v2.3 | -| v2.3 support | βœ… | -| v2.4 support | βœ… | -| Extended header parsing | βœ… | -| Text frames (TIT2, TPE1, etc.) | βœ… | -| Picture frame (APIC) | βœ… | -| Comment frame (COMM) | βœ… | -| UserText frame (TXXX) | βœ… | -| URL frames (WXXX, WCOM, etc.) | βœ… | -| Lyrics frame (USLT) | βœ… | -| Sync lyrics frame (SYLT) | βœ… | -| Unique file ID (UFID) | βœ… | -| Involved people (TIPL/TMCL) | βœ… | -| Popularimeter (POPM) | βœ… | -| Private frame (PRIV) | βœ… | -| General object (GEOB) | βœ… | -| Chapter frame (CHAP) | βœ… | -| Table of contents (CTOC) | βœ… | -| Global unsync (tag-level) | βœ… | -| Frame-level unsync (v2.4) | βœ… | -| Compression (zlib) | βœ… | -| Grouping identity | βœ… | -| Data length indicator | βœ… | -| Apple proprietary frames (WFED, MVNM, MVIN) | βœ… | -| Duplicate tag detection | βœ… | -| Footer support | βœ… | -| Encryption support | βœ… | Detected, content preserved | - -### Vorbis Comments (Xiph) -| Feature | Status | -|---------|--------| -| Read | βœ… | -| Write | βœ… | -| Multi-value fields | βœ… | -| METADATA_BLOCK_PICTURE (base64) | βœ… | Full base64 encode/decode | - -### APE Tag βœ… Complete -| Feature | Status | -|---------|--------| -| Read | βœ… | -| Write | βœ… | -| Binary items | βœ… | -| Cover art | βœ… | - -*Unlocks WavPack, Musepack, and Monkey's Audio formats.* - -### MP4/iTunes Atoms βœ… Complete -| Feature | Status | -|---------|--------| -| Read | βœ… | -| Write | βœ… | -| Standard atoms (Β©nam, Β©ART, etc.) | βœ… | -| trkn/disk parsing | βœ… | -| covr (cover art) | βœ… | -| Freeform atoms (----) | βœ… | -| Extended size atoms | βœ… | -| Duplicate atom merging | βœ… | - -### ASF/WMA Tags βœ… Complete -| Feature | Status | -|---------|--------| -| Read | βœ… | -| Write | βœ… | -| Content Description Object | βœ… | -| Extended Content Description | βœ… | -| WM/Picture | βœ… | - -### RIFF INFO Tags -| Feature | Status | -|---------|--------| -| Read | βœ… | -| Write | βœ… | -| Standard fields (INAM, IART, etc.) | βœ… | - ---- - -## Phase 3: File Format Handlers (P0 - MVP) - -### MP3/MPEG βœ… Complete (Read+Write) -| Feature | Status | -|---------|--------| -| Basic read | βœ… | -| ID3v2 at start | βœ… | -| ID3v1 at end | βœ… | -| MPEG frame header parsing | βœ… | -| Xing/VBRI VBR header | βœ… | -| LAME tag info | πŸ”Ά | -| Duration calculation (VBR) | βœ… | -| Duration calculation (CBR) | βœ… | -| APE tag support | ❌ | -| Write/save | βœ… | - -### FLAC -| Feature | Status | -|---------|--------| -| Magic + metadata blocks | βœ… | -| STREAMINFO | βœ… | -| VORBIS_COMMENT | βœ… | -| PICTURE block | βœ… | -| CUESHEET | βœ… | -| SEEKTABLE | βœ… (preserved during write) | -| APPLICATION | βœ… (preserved during write) | -| MD5 audio signature | βœ… | -| Write/save | βœ… | -| Padding management | βœ… | -| Metadata block reordering | ❌ | - -### OGG Vorbis -| Feature | Status | -|---------|--------| -| Page parsing | βœ… | -| CRC validation | βœ… (optional, off by default) | -| Identification header | βœ… | -| Comment header | βœ… | -| Read | βœ… | -| Write | βœ… | -| Duration from granule | βœ… | - -### WAV βœ… Complete -| Feature | Status | -|---------|--------| -| RIFF container | βœ… | -| fmt chunk (audio properties) | βœ… | -| WAVEFORMATEXTENSIBLE | βœ… | -| data chunk | βœ… | -| LIST INFO tags | βœ… | -| ID3v2 chunk | βœ… | -| bext chunk (BWF) | βœ… | -| Pictures (via ID3v2) | βœ… | -| Write | βœ… | - -### AIFF βœ… Complete -| Feature | Status | -|---------|--------| -| FORM container | βœ… | -| COMM chunk | βœ… | -| Extended float parsing | βœ… | -| ID3 chunk | βœ… | -| AIFC format detection | βœ… | -| AIFC compression info | βœ… | -| Pictures (via ID3v2) | βœ… | -| Write | βœ… | - -### AAC/ALAC (M4A/MP4) βœ… Complete -| Feature | Status | -|---------|--------| -| Atom navigation | βœ… | -| moov/udta/meta/ilst path | βœ… | -| Audio properties from stsd | βœ… | -| AAC properties via esds | βœ… | -| ALAC properties via magic cookie | βœ… | -| Duration from mvhd/mdhd | βœ… | -| Tag read | βœ… | -| Tag write | βœ… | -| MediaFile factory integration | βœ… | - -### DSF (DSD) βœ… Complete -| Feature | Status | -|---------|--------| -| DSD chunk | βœ… | -| fmt chunk | βœ… | -| ID3v2 at metadata offset | βœ… | -| Audio properties | βœ… | -| Duration (use double for overflow safety) | βœ… | -| Write | βœ… | - -### Opus βœ… Complete -| Feature | Status | -|---------|--------| -| OpusHead parsing | βœ… | -| OpusTags parsing | βœ… | -| Pre-skip handling | βœ… | -| Duration (48kHz output) | βœ… | -| Write/save | βœ… | - ---- - -## Phase 4: File Format Handlers (P1 - Extended) - -| Format | Status | Notes | -|--------|--------|-------| -| DFF (DSDIFF) | βœ… | ID3v2 tags (unofficial extension) | -| WMA/ASF | βœ… | Full ASF container | -| WavPack | βœ… | APE tags | -| Musepack | βœ… | APE tags, SV7/SV8 | -| OGG FLAC | βœ… | FLAC in OGG container | -| Speex | ❌ | Vorbis Comments | -| TrueAudio | ❌ | ID3v2/ID3v1 | - ---- - -## Phase 5: File Format Handlers (P2 - Niche) - -| Format | Status | Notes | -|--------|--------|-------| -| Monkey's Audio (.ape) | βœ… | APE tags | -| MOD | ❌ | Title only, embedded | -| S3M | ❌ | Title only | -| IT | ❌ | Title + message | -| XM | ❌ | Title only | - ---- - -## Implementation Priority Order - -### MVP (Core Formats) - -1. **WAV** - Studio/archival format, very common - - RIFF parsing - - fmt chunk for audio properties - - LIST INFO for basic tags - - ID3v2 chunk for full tags - -2. **AIFF** - Mac studio format - - FORM container - - COMM chunk with 80-bit float - - ID3 chunk - -3. **MP4/M4A** βœ… - Apple ecosystem (AAC/ALAC) - - Atom navigation - - iTunes metadata atoms - - Cover art - - MediaFile factory integration - -4. **DSF** - DSD primary format - - DSD/fmt chunk parsing - - ID3v2 at offset - -5. **Opus** βœ… - Modern streaming format - - OpusHead/OpusTags - - 48kHz output rate - -6. **APE Tag Format** - Needed for Musepack/WavPack/Monkey's Audio - - Required before those format handlers - -7. **VBR Header Support** - Accurate MP3 duration - - Xing/Info header - - VBRI header - -### Nice to Have (P1) - -8. **WMA/ASF** - Legacy Windows format -9. **DFF** - DSD secondary format -10. **WavPack** - Lossless with lossy hybrid -11. **Musepack** - Audiophile lossy - -### Low Priority (P2) - -12. **OGG FLAC** -13. **Speex** -14. **TrueAudio** -15. **Monkey's Audio** -16. **MOD/S3M/IT/XM** - Tracker formats - ---- - -## v0.6.0 Status - -All major format goals have been achieved: -- βœ… DSF format support -- βœ… DFF format support -- βœ… APE Tag format -- βœ… WavPack format -- βœ… ASF/WMA format -- βœ… Musepack format -- βœ… Monkey's Audio format -- βœ… Ogg FLAC format - -### Edge Cases Complete -- βœ… Duplicate ID3v2 tag detection -- βœ… Apple proprietary frames (WFED, MVNM, MVIN) -- βœ… MP4 duplicate atom merging - -### Remaining Work -| Item | Effort | Notes | -|------|--------|-------| -| IDisposable pattern | βœ… | IMediaFile extends IDisposable, all file types implement | -| Test coverage >90% | βœ… | ~90% line coverage | -| Large file tests | πŸ”Ά | Deferred (no >4GB test files in repo) | -| Performance benchmarks | πŸ”Ά | Not formally documented | - -### Deferred -- Speex format -- TrueAudio format -- Tracker formats (MOD/S3M/IT/XM) -- TagLib# compatibility shim - ---- - -## Critical Issues to Address - -From spec document "Critical Implementation Notes": - -1. **Integer Overflow in DSD Duration** - βœ… Fixed (use double arithmetic) -2. **Encoding Class Name Collision** - βœ… Not applicable (clean-room design) -3. **LocalFileStream.Insert Off-by-One** - βœ… Not applicable (no LocalFileStream) -4. **GetTextFrame Return Type** - βœ… Proper nullable annotations (`string?`) -5. **XiphComment Empty String Handling** - βœ… Distinguishes null vs empty -6. **OGG Page Parsing Infinite Loop** - βœ… Fixed in v0.3.0 (safety limits) -7. **Missing IDisposable Pattern** - βœ… IMediaFile extends IDisposable -8. **Unsafe BitConverter Usage** - βœ… BinaryData uses explicit endian methods -9. **ID3v1 Genre Property** - βœ… Static Id3v1Genre class with GetName/GetIndex - ---- - -## Testing Requirements - -- [x] Round-trip tests for all formats (read β†’ modify β†’ write β†’ read) -- [x] Cross-tagger compatibility (foobar2000, Mp3tag, iTunes, Picard) -- [ ] Large file support (>4GB) - Deferred -- [x] Corrupted file handling (153 test cases) -- [ ] Performance benchmarks (<10ms tag reading) - Not formally documented -- [x] Memory efficiency tests (streaming read, no full-file buffering) -- [x] Path saves copy audio in 64 KB pieces and match a full-file render (#20). `Render` and a span save still build one buffer - ---- - -## API Compatibility - -Consider adding compatibility shim for TagLib# consumers: -- `TagLib.File.Create()` factory method -- `TagLib.Tag` unified tag interface -- Property mappings for common use cases - ---- - -## Estimated Effort by Phase - -| Phase | Status | Notes | -|-------|--------|-------| -| WAV | βœ… | Complete with RIFF + INFO + ID3v2 + BWF + WAVEFORMATEXTENSIBLE | -| AIFF | βœ… | Complete with FORM + COMM + ID3 + AIFC | -| VBR Headers | βœ… | Complete with Xing/VBRI parsing | -| MP4/M4A | βœ… | Complete with ISO 14496-12 parsing + iTunes atoms + AAC/ALAC | -| Opus | βœ… | Complete with OpusHead + OpusTags + R128 gain | -| DSF | βœ… | Complete with DSD chunk + ID3v2 at offset | -| DFF | βœ… | Complete with ID3v2 tag support | -| APE Tags | βœ… | Complete with binary items + cover art | -| WavPack | βœ… | Complete with APE tags | -| ASF/WMA | βœ… | Complete with GUID-based parsing | -| Musepack | βœ… | Complete with SV7/SV8 + APE tags | -| Monkey's Audio | βœ… | Complete with APE tags | -| Ogg FLAC | βœ… | Complete with FLAC in Ogg container | - ---- - -*Last Updated: 2026-01-05 (ROADMAP verification complete)* diff --git a/docs/MIGRATION-FROM-TAGLIB.md b/docs/MIGRATION-FROM-TAGLIB.md index 4e8c0c0c..19277c1c 100644 --- a/docs/MIGRATION-FROM-TAGLIB.md +++ b/docs/MIGRATION-FROM-TAGLIB.md @@ -493,10 +493,10 @@ async Task GetTitleAsync(string path, CancellationToken ct = default) ## What's Not Yet Supported -TagLibSharp2 is under active development. These TagLib# features are planned but not yet implemented: +These TagLib# features are not implemented yet. Planned work is tracked in [GitHub issues](https://github.com/decriptor/TagLibSharp2/issues) and on the [project board](https://github.com/users/decriptor/projects/7). -- **Formats**: Speex, TrueAudio, Tracker formats (MOD/S3M/IT/XM) -- **Features**: Matroska/WebM non-picture attachments are not written (tag values, chapters, and picture attachments are; WebM has no attachments), MPEG-4 video files, AVI DivX (`IDVX`) and MovieID (`LIST MID `) tags (they are kept unchanged on save) +- **Formats**: Speex, TrueAudio, tracker formats (MOD/S3M/IT/XM), APEv2 tags in MP3 files +- **Features**: Matroska/WebM non-picture attachments are not written (tag values, chapters, and picture attachments are; WebM has no attachments). AVI DivX (`IDVX`) and MovieID (`LIST MID `) tags are not read; they are kept unchanged on save. Exif, IPTC and most XMP values in images are not read ## Format-Specific Examples diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md deleted file mode 100644 index 5f6bd534..00000000 --- a/docs/ROADMAP.md +++ /dev/null @@ -1,262 +0,0 @@ -# TagLibSharp2 Roadmap - -> Generated: January 2026 -> Last Updated: November 2026 -> Status: Production ready - audio and video formats read and write tags; still images open with dimensions, polish phase - -## Executive Summary - -TagLibSharp2 reads and writes tags for the audio and video formats below. JPEG, PNG, GIF, BMP, PCX, Netpbm, TIFF, DNG, and SVG open with width and height. PNG text keywords, the GIF comment, and the JPEG COM marker can be edited. A JPEG title is stored in XMP `dc:title` and read from IFD0 `XPTitle` (0x9C9B) when the XMP has none. A field edit also removes that field's Exif copies, a JPEG title's `XPTitle` included, when the Exif structure is plain, and updates the matching XMP property. An edit with a copy to remove from any other Exif structure is refused and nothing is written. GPS, IPTC, and other Exif values are not read into the tag. SVG metadata is not read or written yet. Remaining audio gaps are niche formats: Speex (obsolete), TrueAudio (niche), and tracker formats (demoscene). Matroska/WebM saves tag values, chapters, and picture attachments. A path save copies the audio in 64 KB pieces instead of loading the file. `Render` and a save from a span still build one buffer. - ---- - -## Implementation Status Matrix - -### Format Support - -| Format | Required | Implemented | Read | Write | Priority | Notes | -|--------|----------|-------------|------|-------|----------|-------| -| MP3 | P0 | βœ… | βœ… | βœ… | - | Production ready | -| FLAC | P0 | βœ… | βœ… | βœ… | - | Production ready | -| MP4/M4A | P0 | βœ… | βœ… | βœ… | - | Production ready. A video track gives coded width, height, codec, and rotation; its sample entry is not read as audio | -| WAV | P0 | βœ… | βœ… | βœ… | - | Production ready | -| AIFF | P0 | βœ… | βœ… | βœ… | - | Production ready | -| DSF | P0 | βœ… | βœ… | βœ… | - | Recently added | -| Ogg Vorbis | P0 | βœ… | βœ… | βœ… | - | Production ready | -| Opus | P0 | βœ… | βœ… | βœ… | - | Production ready | -| WMA/ASF | P1 | βœ… | βœ… | βœ… | - | Production ready | -| DFF | P1 | βœ… | βœ… | βœ… | - | Recently added | -| WavPack | P1 | βœ… | βœ… | βœ… | - | Recently added | -| Musepack | P1 | βœ… | βœ… | βœ… | - | SV7 and SV8 support | -| Matroska/WebM | P2 | βœ… | βœ… | βœ… | - | Tag values, chapters, picture attachments, and track enabled flags are saved. Album is `TITLE` at target 50, or the `ALBUM` tag ffmpeg writes. Setting it updates a target-50 `TITLE` and any `ALBUM` beside it, keeping the shown title at target 30 when the track has none; any other file gets `ALBUM` at target 50, so no reader shows the album as the title. Other attachments are preserved, not rewritten | -| MPEG PS / video ES | P2 | βœ… | βœ… | βœ… | - | ID3v2 and ID3v1 around the stream; duration from PTS or GOP time codes | -| AVI (incl. OpenDML) | P2 | βœ… | βœ… | βœ… | - | RIFF INFO and ID32 tags; movi and every index kept valid. A path save copies movi in 64 KB pieces | -| JPEG, PNG, GIF, BMP, PCX, Netpbm, TIFF, DNG, SVG | P2 | βœ… | Dimensions | PNG text, GIF comment, JPEG COM and title (XMP `dc:title`, read from `XPTitle` too), plain Exif removal, matching XMP | - | A path save copies pixels in 64 KB pieces. Render still copies every other byte. A JPEG title is written to XMP `dc:title` (a new XMP segment when there is none) and every `XPTitle` is removed; clearing removes both. IPTC `ObjectName` is not changed. A field edit removes Exif copies only when the structure is plain, and refuses otherwise. GPS and IPTC are not read. TIFF, DNG, BMP, PCX, Netpbm, and SVG have no text tag | -| Ogg FLAC | P1 | βœ… | βœ… | βœ… | - | Recently added | -| AAC (ADTS/ADIF) | P1 | βœ… | βœ… | βœ… | - | ID3v2, APEv2, ID3v1 tags | -| Speex | P1 | ❌ | ❌ | ❌ | LOW | Uses Vorbis Comment | -| TrueAudio | P2 | ❌ | ❌ | ❌ | LOW | Uses ID3v2 | -| Monkey's Audio | P2 | βœ… | βœ… | βœ… | - | Recently added | -| MOD | P2 | ❌ | ❌ | ❌ | LOW | Tracker format | -| S3M | P2 | ❌ | ❌ | ❌ | LOW | Tracker format | -| IT | P2 | ❌ | ❌ | ❌ | LOW | Tracker format | -| XM | P2 | ❌ | ❌ | ❌ | LOW | Tracker format | - -### Tag Format Support - -| Tag Format | Required | Implemented | Notes | -|------------|----------|-------------|-------| -| ID3v1 | βœ… | βœ… | Complete | -| ID3v2.2 | βœ… | Read; saved as ID3v2.3 | 3-character IDs mapped to their ID3v2.3 names. A save writes an ID3v2.3 tag with every frame that was read; a frame with no ID3v2.3 name is skipped | -| ID3v2.3 | βœ… | βœ… | Big-endian frame sizes, `TYER`. Text lists split on NUL only; the TPE1 "/" rule is not applied | -| ID3v2.4 | βœ… | βœ… | Default for a new tag. Syncsafe sizes, UTF-8, `TDRC`. Text lists split on NUL only (frames Β§4.2) | -| Vorbis Comment | βœ… | βœ… | Full field mapping | -| MP4/iTunes | βœ… | βœ… | Apple atom support | -| APE Tag | βœ… | βœ… | v2 with binary items | -| ASF Attributes | βœ… | βœ… | Complete with WM/* mappings | -| RIFF INFO | βœ… | βœ… | For WAV files | - ---- - -## Phase 1: Critical Gaps (HIGH Priority) - -### 1.1 WMA/ASF Format Support βœ… COMPLETE -**Status: Implemented January 2026** - -Full read support implemented with: -- ASF container parsing (GUID-based object structure) -- Content Description (Title, Author, Copyright, Description, Rating) -- Extended Content Description (WM/* attributes) -- File Properties (duration, bitrate, file size) -- Stream Properties (sample rate, channels, codec detection) -- Security hardening with bounds checking and overflow protection - -**Files created:** -``` -src/TagLibSharp2/Asf/ -β”œβ”€β”€ AsfFile.cs # Container parser -β”œβ”€β”€ AsfTag.cs # Tag implementation -β”œβ”€β”€ AsfGuid.cs # 128-bit GUID struct -β”œβ”€β”€ AsfGuids.cs # Well-known GUID constants -β”œβ”€β”€ AsfDescriptor.cs # Typed attribute values -β”œβ”€β”€ AsfContentDescription.cs # 5 fixed fields -β”œβ”€β”€ AsfExtendedContentDescription.cs # Key-value attributes -β”œβ”€β”€ AsfFileProperties.cs # Duration, bitrate -└── AsfStreamProperties.cs # Audio codec info -``` - ---- - -### 1.2 Edge Case Handling βœ… COMPLETE -**Status: All edge cases implemented as of v0.5.0** - -| Edge Case | Status | Implementation | -|-----------|--------|----------------| -| iTunes ID3v2.3 with syncsafe sizes | βœ… | Syncsafe fallback when big-endian fails | -| UTF-16 without BOM fallback | βœ… | Falls back to little-endian (Windows default) | -| Duplicate ID3v2 tags | βœ… | `HasDuplicateTag` detection, auto-removed on save | -| Apple proprietary v2.3 frames | βœ… | TSOA, TSOT, TSOP, WFED, MVNM, MVIN implemented | -| MP4 duplicate atoms | βœ… | Multiple data atoms merged with "; " separator | -| ID3v2 text list separator | βœ… | NUL only, in v2.2, v2.3, and v2.4. A slash stays inside the value. `"(17)"` is still an ID3v1 genre | - ---- - -### 1.3 Cross-Tagger Compatibility Tests -**Status: Mostly Complete** - -Cross-tagger compatibility tests exist in `CrossTaggerCompatibilityTests.cs` and `Mp4CompatibilityTests.cs`: -- [x] MusicBrainz Picard field names (TXXX descriptions) -- [x] ReplayGain format (foobar2000, Mp3tag compatible) -- [x] iTunes compilation flag ("1" value) -- [x] Classical music fields (WORK, MOVEMENT) -- [x] AcoustID fields -- [x] R128 gain normalization -- [x] Standard frame IDs and Vorbis Comment uppercase names - -Integration tests with real files (requires env vars): -- [ ] foobar2000 (TEST_MP4_FOOBAR2000) -- [ ] Mp3tag -- [ ] iTunes -- [ ] VLC -- [ ] MediaMonkey -- [ ] Kid3 - ---- - -## Phase 2: Format Expansion (MEDIUM Priority) - -### 2.1 Musepack Support -**Effort: Small | Business Value: Medium** - -Musepack uses APE tags (already implemented). Primarily need: -- Magic byte detection for SV7/SV8 streams -- Audio properties parsing from stream headers -- Registration in MediaFile factory - -**Files to create:** -``` -src/TagLibSharp2/Musepack/ -β”œβ”€β”€ MusepackFile.cs -└── MusepackProperties.cs -``` - -### 2.2 Speex Support -**Effort: Small | Business Value: Low** - -Speex is an Ogg-encapsulated format using Vorbis Comments (already implemented). - -**Requirements:** -- Speex header parsing for audio properties -- Registration in Ogg container detection - -### 2.3 TrueAudio Support -**Effort: Small | Business Value: Low** - -TrueAudio uses ID3v1/ID3v2 tags (already implemented). - -**Requirements:** -- TTA header parsing for audio properties -- Magic byte detection - ---- - -## Phase 3: Tracker Formats (LOW Priority) - -Tracker formats (MOD, S3M, IT, XM) have limited tagging capabilities and are lower priority. - -### Implementation Notes: -- MOD: Metadata at offset 1080, 31 sample names (20 chars each) -- S3M: Similar to MOD but with SCRM signature -- IT: IMPM signature, extended instrument names -- XM: Extended Module format with pattern data - -**Recommendation:** Implement as read-only with minimal tag support initially. - ---- - -## Phase 4: Quality & Polish - -### 4.1 Performance Optimization -- [ ] Benchmark suite for regression testing -- [ ] Memory profiling for large file handling -- [ ] Parallel read safety verification - -### 4.2 Documentation -- [ ] XML documentation coverage audit -- [ ] Migration guide from TagLib# -- [ ] API reference generation - -### 4.3 Missing Metadata Fields - -Verify these extended fields are properly mapped: - -| Field | ID3v2 | Vorbis | MP4 | Status | -|-------|-------|--------|-----|--------| -| UserTags | TTAG | TAGS | Β©tag | Verify | -| Version | TVER | VERSION | Β©ver | Verify | -| RecordingDate | - | PERFORMANCEDATE | - | Add | -| Section | TXXX:SECTION | SECTION | - | Verify | - ---- - -## Backlog: Not Planned - -These items from the requirements are explicitly not planned: - -| Item | Reason | -|------|--------| -| XMP metadata | Out of scope for audio files | -| DVD/BD audio | Not standard audio files | - ---- - -## Work Breakdown - -### Sprint 1: ASF/WMA Foundation βœ… COMPLETE -1. βœ… Create ASF container parser with GUID detection -2. βœ… Implement ASF attribute reading -3. βœ… Add audio properties extraction -4. βœ… Create AsfTag implementing Tag interface -5. βœ… Add comprehensive test suite (12 security tests) -6. βœ… Register in MediaFile factory - -### Sprint 2: Edge Cases & Compatibility βœ… COMPLETE -1. βœ… Fix UTF-16 BOM fallback in TextFrame and LyricsFrame -2. βœ… Add iTunes syncsafe fallback for v2.3 tags -3. βœ… Handle duplicate tags gracefully (detection + auto-removal) -4. βœ… Add cross-tagger compatibility tests -5. βœ… Add remaining Apple proprietary frames (TSOA, TSOT, TSOP, WFED, MVNM, MVIN) - -### Sprint 3: Format Expansion (1-2 weeks effort) -1. βœ… Add Musepack support (SV7 and SV8) -2. Add Speex support -3. Add TrueAudio support -4. Verify all extended metadata fields - -### Sprint 4: Tracker Formats (1 week effort) -1. MOD format (read-only) -2. S3M format (read-only) -3. IT format (read-only) -4. XM format (read-only) - ---- - -## Success Metrics - -| Metric | Current (v0.5.0) | Target | -|--------|------------------|--------| -| Format coverage | 17/23 (74%) | 23/23 (100%) | -| Test coverage | 90.1% βœ… | >90% | -| Round-trip tests | All 17 formats βœ… | All formats | -| Cross-tagger compat | Unit tests βœ… | 7 major taggers | -| Edge case handling | Complete βœ… | All documented cases | - ---- - -## Appendix: Specification References - -- **ASF:** [Microsoft ASF Specification](https://docs.microsoft.com/en-us/windows/win32/wmformat/overview-of-the-asf-format) -- **Musepack:** [Musepack SV8 Specification](https://wiki.hydrogenaud.io/index.php?title=Musepack) -- **Speex:** [Speex Manual](https://speex.org/docs/manual/speex-manual/) -- **TrueAudio:** [TTA Specification](http://tausoft.org/wiki/True_Audio_Codec_Format) -- **Tracker Formats:** [ModPlug Tracker Documentation](https://wiki.openmpt.org/Manual:_Module_formats) From 1aea78376ba861fc5274b3768b5b2cbf697addb9 Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Thu, 3 Dec 2026 17:55:35 -0700 Subject: [PATCH 2/7] docs: Correct the 0.7.0 changelog The Unreleased section said things the code no longer does. A Changed entry kept splitting a slash-separated ID3v2 value ("AC/DC" as Performers [AC, DC] "as before"), against the Breaking Changes entry: lists split on NUL only. The custom-field, tagless-view and AVI entries described WAV INFO as Latin-1; since #209 and #216 it is read and written as UTF-8 when valid and Windows-1252 otherwise. The AVI entry said a list with no CSET is refused when a guessed field must be rewritten, which #216 replaced with a field-by-field write. The still-image entry said no XMP or Exif value is read, though the JPEG title is. Three changes since 0.6.0 had no entry: RiffChunk.TotalSize and AiffChunk.TotalSize changed from int to long (now under Breaking Changes), Matroska and WebM support itself (#53), and stream reads with no retained audio payload (#54, #20). The two Changed headings are merged, and the hard-wrapped entries are unwrapped like the rest. --- CHANGELOG.md | 90 +++++++++++++++------------------------------------- 1 file changed, 25 insertions(+), 65 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 21e3fbe0..7f5eaa56 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,10 +13,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **Changed**: `MediaFile.ReadAsync (path, default)` and `MediaFile.ReadAsync (stream, default)` no longer compile: `default` now matches both the old overload and the new one that takes `MediaReadOptions` (CS0121). Pass `null`, or name the parameter (#157) - **Changed**: `AiffFile.Tag` is now a get-only `Tag?` view over the ID3 chunk and the native AIFF text chunks (it was a settable `Id3v2Tag?`). Assign or read the ID3 tag through the new `AiffFile.Id3v2Tag` property; code that assigned `AiffFile.Tag` or used ID3-only members on it no longer compiles. `AiffFile.Tag.Render()` throws `NotSupportedException`, as the other combined views do; render the `AiffFile` instead - **Changed**: `Id3v2Tag.IsEmpty` is false when the tag holds any frame, including lyrics, ratings, pictures, comments, user text, URLs and private frames. It used to check only the basic fields, so WAV and AIFF saves dropped an ID3 chunk that held only, for example, a composer, a publisher or a BPM -- **Changed**: `Tag` is no longer null on a tagless `Mp3File`, `AacFile`, `DsfFile`, `DffFile`, `MpegPsFile`, `AiffFile`, `FlacFile`, `WavPackFile`, `MonkeysAudioFile` or `MusepackFile`, nor `IMediaFile.Tag` on a tagless `WavFile` or on an `Mp4File` with no `ilst`. It is an empty view whose `TagType` is `None`: test `Tag.IsEmpty` (no standard field and no picture), or the format's stored-tag properties, to find an untagged file. Reading the view does not change the file; the first value written creates the format's tag on save (ID3v2 for MP3, AAC, DSF, DFF and MPEG-PS, the ID3 chunk for AIFF and WAV, a Vorbis comment for FLAC, APEv2 for WavPack, Monkey's Audio and Musepack, an `ilst` for MP4; `Mp4File.Tag` itself stays null until then). On WAV that is an `id3 ` chunk rather than RIFF INFO, which holds one Latin-1 value per field; reading the view leaves `WavFile.InfoTag` null. A write that leaves the tag the view created empty (null, `Clear`, writing back an empty value, or a value set and later cleared) removes it again, so the save writes the file as a save with no edit does; a save also writes nothing for a created tag emptied through the stored-tag property (`Id3v2Tag`, `ApeTag`, `VorbisComment`, `Mp4File.Tag`), and a reference to a tag the view dropped no longer reaches the file. The view's `SupportsCustomFields` answers for the tag its first write creates. `Tag` is null after `Dispose`. On a tagless DSF, DFF, WavPack, Monkey's Audio or Musepack file it is a `CombinedTag`, not an `Id3v2Tag` or `ApeTag`, and so is `IMediaFile.Tag` on an MP4 with no `ilst`. Still images that have no text store (TIFF, DNG, BMP, PCX, Netpbm, SVG) still return null. `MediaFileResult.Tag` is the opened file's `Tag`, read each time it is read, so it is that view too (it was null for a tagless WAV, DSF or DFF file). +- **Changed**: `Tag` is no longer null on a tagless `Mp3File`, `AacFile`, `DsfFile`, `DffFile`, `MpegPsFile`, `AiffFile`, `FlacFile`, `WavPackFile`, `MonkeysAudioFile` or `MusepackFile`, nor `IMediaFile.Tag` on a tagless `WavFile` or on an `Mp4File` with no `ilst`. It is an empty view whose `TagType` is `None`: test `Tag.IsEmpty` (no standard field and no picture), or the format's stored-tag properties, to find an untagged file. Reading the view does not change the file; the first value written creates the format's tag on save (ID3v2 for MP3, AAC, DSF, DFF and MPEG-PS, the ID3 chunk for AIFF and WAV, a Vorbis comment for FLAC, APEv2 for WavPack, Monkey's Audio and Musepack, an `ilst` for MP4; `Mp4File.Tag` itself stays null until then). On WAV that is an `id3 ` chunk rather than RIFF INFO, which holds one value per field and declares no text encoding; reading the view leaves `WavFile.InfoTag` null. A write that leaves the tag the view created empty (null, `Clear`, writing back an empty value, or a value set and later cleared) removes it again, so the save writes the file as a save with no edit does; a save also writes nothing for a created tag emptied through the stored-tag property (`Id3v2Tag`, `ApeTag`, `VorbisComment`, `Mp4File.Tag`), and a reference to a tag the view dropped no longer reaches the file. The view's `SupportsCustomFields` answers for the tag its first write creates. `Tag` is null after `Dispose`. On a tagless DSF, DFF, WavPack, Monkey's Audio or Musepack file it is a `CombinedTag`, not an `Id3v2Tag` or `ApeTag`, and so is `IMediaFile.Tag` on an MP4 with no `ilst`. Still images that have no text store (TIFF, DNG, BMP, PCX, Netpbm, SVG) still return null. `MediaFileResult.Tag` is the opened file's `Tag`, read each time it is read, so it is that view too (it was null for a tagless WAV, DSF or DFF file). - **Changed**: ID3v2 text lists split on NUL only, in v2.2, v2.3 and v2.4. `Performers`, `AlbumArtists`, `Composers`, `Genres` and `GetTextFrameValues` no longer split on `/`, so a v2.3 `AC/DC` reads as one value, as ffprobe, exiftool and MediaInfo read it. Writes join on NUL in every version. This applies to ID3v2 in MP3, WAV, AIFF, DSF, DFF, raw AAC, MPEG-PS and AVI; `n/m` numbers and `(17)` genres are unchanged -- **Changed**: `ApePicture.GetKeyForPictureType` and `GetKey` return `Cover Art ()` for a role without its own key, instead of `Cover Art (Front)`; `LeadArtist` is `Cover Art (LeadArtist)`, no longer `Cover Art (Artist)`. `GetPictureTypeForKey` reads those names in any case and with a space between words (`Cover Art (Lead Artist)`), and returns `Other` for a null key and for a key that is not a role's name, such as `Cover Art (3)` or `Cover Art (Other, BackCover)` +- **Changed**: `ApePicture.GetKeyForPictureType` and `GetKey` return `Cover Art ()` for a role without its own key, instead of `Cover Art (Front)`; `LeadArtist` is `Cover Art (LeadArtist)`, no longer `Cover Art (Artist)`. `GetPictureTypeForKey` reads those names in any case and with a space between words (`Cover Art (Lead Artist)`), where 0.6.0 read `Cover Art (LeadArtist)` and the other names without a key of their own as `Other`. - **Changed**: an `Mp4File` with a video track reports it: `IMediaFile.VideoProperties` is no longer always null, `MediaTypes` includes `Video` (and is `Video` alone for a file with no audio), and `Properties` describes the audio track only. A track that another track names as chapters (`tref`/`chap`), such as Apple's chapter images in an `.m4a`, is neither the video nor the audio, so such an `.m4a` still reports `Audio` alone +- **Changed**: `RiffChunk.TotalSize` and `AiffChunk.TotalSize` are `long`; they were `int`. A chunk size near `int.MaxValue` no longer overflows. Code that assigns either to an `int` needs a cast, and code compiled against 0.6.0 must be rebuilt - **Changed**: `Mp4Picture.PictureType` returns the role this library stored in the `covr` data atom's locale (see Added) instead of always `FrontCover`. A picture whose locale is 0, or any real country or language, is still `FrontCover` ### Added @@ -29,24 +30,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - MP4 `covr` pictures keep a role other than front cover by a private convention: the data atom's locale holds the role, one higher than the ID3 picture type, in its top byte, a country byte no real locale uses. AVFoundation, QuickLook, ffprobe, ExifTool and MediaInfo still show the image as a cover; a reader that matched the locale to the user's country would skip it. APE cover items keep every picture role - Tagless MP3, AAC, DSF, DFF, MPEG-PS, AIFF, WAV, FLAC, WavPack, Monkey's Audio, Musepack and MP4 files accept `file.Tag.Title = …` and the other tag setters without a tag being created first - `MediaReadOptions.SkipPictures` reads a file without its embedded pictures (#157). `MediaFile.Read`, `ReadAsync` and `ReadFromData` take the options; the existing overloads read every picture as before. A skip read returns what a full read returns once its pictures are cleared, `Tag.Pictures` is empty and `PicturesLoaded` is false; a file that a full read rejects is rejected with the same error. Three things differ from clearing a full read with `Tag.Pictures = []`: an APE text or locator item under a "Cover Art" key is kept, because only a binary one is a picture; `Tag.TagType` and `Tag.IsEmpty` describe what remains, so a tag that held only pictures reads as absent; and `AiffFile.AllChunks` holds the ID3 chunk without its picture frames. The pictures left out are FLAC PICTURE blocks, `METADATA_BLOCK_PICTURE` comments in FLAC, Ogg Vorbis, Opus and Ogg FLAC (a value that does not decode as a picture stays a text field, as in a full read), Ogg FLAC PICTURE blocks, ID3v2 APIC and PIC frames in MP3, WAV, AIFF, DSF, DFF, raw AAC, MPEG-PS and AVI, MP4 `covr` items and QuickTime artwork keys, ASF `WM/Picture` descriptors and Metadata and Metadata Library records, APE binary "Cover Art" items in Monkey's Audio, WavPack, Musepack and raw AAC, Matroska image attachments, and the Audible cover. Each walk takes its decisions from the full reader's own rules for that structure, and what it cannot walk it hands to that reader unchanged, so both reads parse the same items. A file path or seekable stream seeks past each picture payload; an ID3 tag unsynchronised as a whole (v2.2, v2.3) and a `METADATA_BLOCK_PICTURE` value are read through once to decode them, and are not kept. Where a walk cannot decide without the picture bytes (a comment value it dropped turns out not to be a picture, Ogg pages that the packet scan would stop on, or Ogg pages that leave a packet open at the end), that part is read as a full read reads it and its pictures are dropped. `ReadFromData` and a stream that cannot seek are walked the same way in memory, so they return what a stream read of the same bytes returns, and keep no copy of a picture. Saving a file read this way fails with "Cannot save because pictures were not loaded. Read the file again without SkipPictures." and writes nothing. `Render` stays available and writes what a full read with its pictures cleared writes, except that it also leaves out Ogg FLAC PICTURE blocks and ASF Metadata Library `WM/Picture` records, which a full read keeps as raw blocks; the Audible cover chunk, which `Render` never changes, stays. A WAV, AIFF, DSF or DFF file read with `SkipPictures` by `ReadFromData` or from a stream keeps no copy of its sound, as a stream read keeps none, so its `Render` throws `InvalidOperationException` when it has sound to write; read it from a path to render it. A still image is the picture, so it keeps its bytes and saves. `ReadAsync` for MP3, FLAC, MPEG-PS, Audible and AVI calls the synchronous skip reader -- `Tag.GetCustomField`, `Tag.SetCustomField`, `Tag.RemoveCustomField`, and `Tag.SupportsCustomFields` read, - write, and remove a named field with one or more values on any tag (#112). The field lives in the format's - own storage: a Vorbis comment field, an APE text item, an ID3v2 `TXXX` frame, an MP4 `----:com.apple.iTunes` - freeform atom, an ASF attribute, a file-level Matroska `SimpleTag`, or a RIFF INFO chunk (Latin-1 in WAV; - any text in AVI, saved under the file's CSET rules). ID3v1 reports no support. `CombinedTag` (MP3, raw AAC, - AVI with an ID3v2 chunk, MPEG program streams), `FlacTag`, and the AIFF view (`AiffFile.Tag`) forward the - members. A combined view writes the values into every tag that can store them and removes the name from a - tag that cannot (RIFF INFO holds one value), so no tag keeps an older value. On ASF the first value goes to - the Content Description or Extended Content Description and the others to the Metadata Library Object, as - Windows writes them. `GetCustomField`, `Performers`, `AlbumArtists`, `Composers`, and `Genres` read every - value; `SetCustomField` and those four properties write them back the same way; a remove, a mapped setter - given a new value, and `Clear` drop the Metadata Library values too. ASF follows the write-back rule of - ID3v2, APE, and Vorbis Comments (`Tag.IsWriteBack`): writing back the exact value a mapped property read - changes nothing, `null` always clears, a stored value the getter cannot read included (the DWORD year - mutagen writes, say), and `CopyTo` always replaces. A single-value ASF getter returns the first non-empty - value of its attribute (a string, a number, or a BOOL), from the Content Description or Extended Content - Description and then the Metadata and Metadata Library Objects, as the ID3v2, APE, and Vorbis Comment - getters do, and `IsCompilation = false` clears a true stored in any of them. +- `Tag.GetCustomField`, `Tag.SetCustomField`, `Tag.RemoveCustomField`, and `Tag.SupportsCustomFields` read, write, and remove a named field with one or more values on any tag (#112). The field lives in the format's own storage: a Vorbis comment field, an APE text item, an ID3v2 `TXXX` frame, an MP4 `----:com.apple.iTunes` freeform atom, an ASF attribute, a file-level Matroska `SimpleTag`, or a RIFF INFO chunk (in WAV, read and written as UTF-8 when valid and as Windows-1252 otherwise; in AVI, saved under the file's CSET rules). ID3v1 reports no support. `CombinedTag` (MP3, raw AAC, AVI with an ID3v2 chunk, MPEG program streams), `FlacTag`, and the AIFF view (`AiffFile.Tag`) forward the members. A combined view writes the values into every tag that can store them and removes the name from a tag that cannot (RIFF INFO holds one value), so no tag keeps an older value. On ASF the first value goes to the Content Description or Extended Content Description and the others to the Metadata Library Object, as Windows writes them. `GetCustomField`, `Performers`, `AlbumArtists`, `Composers`, and `Genres` read every value; `SetCustomField` and those four properties write them back the same way; a remove, a mapped setter given a new value, and `Clear` drop the Metadata Library values too. ASF follows the write-back rule of ID3v2, APE, and Vorbis Comments (`Tag.IsWriteBack`): writing back the exact value a mapped property read changes nothing, `null` always clears, a stored value the getter cannot read included (the DWORD year mutagen writes, say), and `CopyTo` always replaces. A single-value ASF getter returns the first non-empty value of its attribute (a string, a number, or a BOOL), from the Content Description or Extended Content Description and then the Metadata and Metadata Library Objects, as the ID3v2, APE, and Vorbis Comment getters do, and `IsCompilation = false` clears a true stored in any of them. +- Matroska and WebM (`.mkv`, `.mka`, `.mks`, `.mk3d`, `.webm`): `MatroskaFile` and `MediaFormat.Matroska` (#53). Reads and writes the `Tags` values, including `SORT_WITH` sort names, and reads the duration and the audio and video properties of the main tracks. The entries below describe tracks, pictures, chapters and the tag mapping +- `MediaFile.Read (Stream)` and `MediaFile.ReadAsync (Stream)` read a file from a stream (#54). A seekable stream is read by the ranges the format needs; a stream that cannot seek is copied once. Path and stream reads no longer keep the audio payload in memory, so scanning a library holds only the metadata of each file (#20) - `MatroskaFile.Tracks` lists the first 4096 known-size `TrackEntry` elements as `MatroskaTrack` objects, and `MatroskaFile.IsTrackListTruncated` tells when a file had more. Each track has `TrackNumber`, `TrackUid`, `TrackType`, `CodecId`, `IsDefault`, and `IsEnabled` (RFC 9559 Β§5.1.4.1). - `MatroskaTrack.IsEnabled` is written back on save. A stored `FlagEnabled` is rewritten in place. A missing one is added to the `TrackEntry`, taking the room from the `Void` right after `Tracks` when it has enough so no element moves; otherwise everything after `Tracks` moves once, with every SeekHead, Cues and Cluster `Position` value and CRC-32 updated, each widened when it no longer fits. Adding a FlagEnabled (minver 2) also makes the EBML header's `DocTypeVersion` at least 2: a stored lower value is raised, and an empty or missing one is written (RFC 9559 section 7); no Segment Position moves. A track the caller did not set keeps its bytes. - `AiffFile.Id3v2Tag`, and `AiffFile.Title`, `Artist`, `Comment` and `Copyright` @@ -57,32 +43,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Matroska: setting `Pictures` writes image attachments (RFC 9559 sections 5.1.6 and 21.1). A new front cover is named `cover.` plus the extension of its media type (`cover.jpg`, `cover.png`; another image type such as GIF becomes `cover.gif`, although RFC 9559 recommends only JPEG and PNG for covers). It goes first unless the file keeps its normal cover (`cover.*`); that one keeps its place and the new one goes after the kept attachments. A kept `small_cover` or `cover_land` is not the normal cover. Other picture types get names such as `back.jpg` or `artist.png`, which read back as their type. The description goes in `FileDescription`. An attachment that matches a picture, compared with the media type as stored, keeps its `FileName`, `FileUID` and bytes. A new `FileUID` is random, nonzero and different from every `FileUID` in the file. Fonts and other non-image attachments are kept. Removing a picture removes only its attachment and any tag that targeted only that attachment. - Matroska: a new or moved `Attachments` element goes after the last Cluster or in a Void, and gets an entry in the first SeekHead. The SeekHead can widen its size field to grow into the Void after it. - Matroska/WebM chapters (#114): `MatroskaFile.Chapters` reads and writes editions (`MatroskaEdition`) and nested chapter atoms (`MatroskaChapter`) with UID, string UID, start and end time, display strings with languages and countries (`MatroskaChapterDisplay`), and the enabled and hidden flags (RFC 9559 section 5.1.7). New UIDs are random and nonzero. Chapter titles never become `Tag.Title`. WebM saves write only the chapter elements WebM supports, edited or not. A save fails when a chapter it adds or changes ends before it starts, starts outside its parent, or lacks an end in an ordered edition (RFC 9559 section 20.2); the error names the chapter by position and UID. A chapter that was not changed is not checked and, in a Matroska file, is written back byte for byte; one moved to another edition or parent, or in an edition whose own values changed, is checked with everything nested in it. An added edition without chapters is not an edit. Atom nesting (32 levels) and parsed children (65,536) are bounded; the rest is kept as one copy of its bytes, so memory stays linear. `Clear()`, `RemoveEdition`, and a removal through `Editions` remove a `Chapters` element even when it held no chapter atoms. An edited `Chapters` element goes in front of the first Cluster (RFC 9559 section 6.6), moving what follows, so a reader that goes front to back finds it; with an ordered edition it goes after the first Info and before the first Tracks, as section 6.6 asks, when the file has them in that order. -- **MP4 chapters** (#113): `Mp4File.Chapters` reads and replaces the chapter list, with the new `Mp4Chapter` - type (start time, title, derived end time). Reading takes the QuickTime chapter track (the text track named - by a `tref`/`chap` reference), then the Nero `chpl` box. Saving writes both: `chpl` (first 255 chapters) and - the chapter track (an existing one keeps its track ID; otherwise a new disabled text track is added and - referenced from every sound and video track). New chapter samples go in their own `mdat` after `moov`, and - every other track's chunk offsets move with them. That `mdat` replaces the one an earlier chapter save wrote, - so repeated edits do not grow the file. A save that leaves the list alone keeps the chapter bytes. - Chapter samples in movie fragments are read; changing chapters whose track has, or may have, samples in movie - fragments fails with an error instead of leaving a second list. A replaced track keeps its language, handler, - and flags. New tracks use `nmhd` and `tx3g` in MP4 (Apple TN2174) and `gmhd` and the QTFF `text` - description in QuickTime files (major brand `qt `, or no `ftyp`). A chapter sample that is not valid - UTF-8/UTF-16 text yields to `chpl`. Clearing also removes Apple chapter image and URL tracks. - A set replaces every chapter title track with the one list: other title tracks (for example one per - language) are removed, and a track whose chapter reference named one then names the rebuilt track. A - chapter URL track (samples with an `href` modifier, 3GPP TS 26.245 Β§5.17.1.5) and chapter image tracks stay. - Chapters and the tag are separate: `ClearAllMetadata()` and `Tag = null` keep the chapters, and - `Chapters = []` keeps the tag. +- **MP4 chapters** (#113): `Mp4File.Chapters` reads and replaces the chapter list, with the new `Mp4Chapter` type (start time, title, derived end time). Reading takes the QuickTime chapter track (the text track named by a `tref`/`chap` reference), then the Nero `chpl` box. Saving writes both: `chpl` (first 255 chapters) and the chapter track (an existing one keeps its track ID; otherwise a new disabled text track is added and referenced from every sound and video track). New chapter samples go in their own `mdat` after `moov`, and every other track's chunk offsets move with them. That `mdat` replaces the one an earlier chapter save wrote, so repeated edits do not grow the file. A save that leaves the list alone keeps the chapter bytes. Chapter samples in movie fragments are read; changing chapters whose track has, or may have, samples in movie fragments fails with an error instead of leaving a second list. A replaced track keeps its language, handler, and flags. New tracks use `nmhd` and `tx3g` in MP4 (Apple TN2174) and `gmhd` and the QTFF `text` description in QuickTime files (major brand `qt `, or no `ftyp`). A chapter sample that is not valid UTF-8/UTF-16 text yields to `chpl`. Clearing also removes Apple chapter image and URL tracks. A set replaces every chapter title track with the one list: other title tracks (for example one per language) are removed, and a track whose chapter reference named one then names the rebuilt track. A chapter URL track (samples with an `href` modifier, 3GPP TS 26.245 Β§5.17.1.5) and chapter image tracks stay. Chapters and the tag are separate: `ClearAllMetadata()` and `Tag = null` keep the chapters, and `Chapters = []` keeps the tag. - `AviFile` reads and writes AVI files (RIFF `AVI ` form, including OpenDML `odml`/`indx` and `AVIX` forms). `MediaFile.Read` detects them as `MediaFormat.Avi`; WAV stays the `WAVE` form. - Properties: duration (OpenDML `dmlh` total frames when present, timed by the video stream's rate and scale), video width, height, frame rate and BITMAPINFOHEADER FourCC, and the first audio stream's WAVEFORMATEX sample rate, channels, bits and bitrate. - Tags: every `LIST INFO` in the first RIFF form (`InfoTag`) and an ID3v2 tag in an `ID32` chunk (`Id3v2Tag`). The unified `Tag` puts INFO first. - Saving keeps the `movi` sample bytes. New tags reuse the tag and `JUNK` space between `hdrl` and `movi`, so nothing moves; when they do not fit, the data moves and the RIFF size, absolute `idx1` offsets, `indx` super index entries, and each standard index's base offset (or, when the base stays put, each entry whose data moved) are shifted. A save is refused, without writing, when an index cannot be verified first. A changed tag chunk cut off by the end of the file is turned into `JUNK`, so a removed value does not return. An unchanged save writes the original bytes. - A file whose RIFF size is still the streaming placeholder 0xFFFFFFFF reports no duration: its frame counts were never filled in. - - AVI INFO text honours a `CSET` chunk (code page 65001, 1252, 0 or 28591); without one, valid UTF-8 (ffmpeg's and TagLib#'s encoding) is read as UTF-8 and other text as Windows-1252. On save, an unchanged value keeps its exact bytes and the file keeps its `CSET` (or its absence); changed values are written in the file's code page when they fit it (ASCII only when there is no `CSET`), otherwise the list becomes UTF-8 with a `CSET` of code page 65001 before it. When the list becomes UTF-8, untouched text in a declared code page decoded exactly (1252, 28591, 0) is rewritten as the same text in UTF-8, and untouched text whose code page is a guess because of a byte its declared code page leaves undefined (0x81, 0x8D, 0x8F, 0x90, 0x9D in 1252; 0x80-0x9F under code page 0) as the UTF-8 of the text read (#220). With no `CSET`, or a `CSET` of a code page not decoded here (for example Shift-JIS or cp1251), untouched text that is not UTF-8 keeps its bytes, the changes are written by the read rule, and such a `CSET` is dropped. A CSET rewritten to 65001 keeps the file's country, language and dialect codes. The five undefined 1252 code points are never written as 1252 bytes; a value holding one goes to UTF-8. WAV INFO is unchanged (Latin-1). + - AVI INFO text honours a `CSET` chunk (code page 65001, 1252, 0 or 28591); without one, valid UTF-8 (ffmpeg's and TagLib#'s encoding) is read as UTF-8 and other text as Windows-1252. On save, an unchanged value keeps its exact bytes and the file keeps its `CSET` (or its absence); changed values are written in the file's code page when they fit it (ASCII only when there is no `CSET`), otherwise the list becomes UTF-8 with a `CSET` of code page 65001 before it. When the list becomes UTF-8, untouched text in a declared code page decoded exactly (1252, 28591, 0) is rewritten as the same text in UTF-8, and untouched text whose code page is a guess because of a byte its declared code page leaves undefined (0x81, 0x8D, 0x8F, 0x90, 0x9D in 1252; 0x80-0x9F under code page 0) as the UTF-8 of the text read (#220). With no `CSET`, or a `CSET` of a code page not decoded here (for example Shift-JIS or cp1251), untouched text that is not UTF-8 keeps its bytes, the changes are written by the read rule, and such a `CSET` is dropped. A CSET rewritten to 65001 keeps the file's country, language and dialect codes. The five undefined 1252 code points are never written as 1252 bytes; a value holding one goes to UTF-8. WAV INFO, which declares no character set, is read and written by the rule in Fixed (#209, #216). - A path save copies `movi` in 64 KB pieces and patches `idx1` and OpenDML indexes from the source, so it no longer loads the file. `Render` and `SaveToFile(path, span)` still build one buffer. `MediaFile.Read` and `AviFile.ReadFromFile` read only the header and tag chunks. - Matroska `AlbumArtistSort` and `ComposerSort`: `SORT_WITH` nested in the album-level `ARTIST` (`TargetTypeValue` 50) and in `COMPOSER`, with flat `ALBUM_ARTIST_SORT` / `COMPOSER_SORT` as the fallback. Clearing removes both forms at every level the getter reads. When the track inherits the album's `ARTIST`, writing either `ArtistSort` or `AlbumArtistSort` first copies that `ARTIST` to the track level, so the other sort is kept (#116). -- Still images: `MediaFile.Read` and `StillImageFile.Read`/`ReadFromFile`/`ReadFromFileAsync` open JPEG, PNG, GIF, BMP, PCX, Netpbm (PBM, PGM, PPM, PNM), TIFF, DNG, and SVG and report width and height. A TIFF or DNG reports the size exiftool's ImageSize gives (measured case by case): the width and height of the first IFD whose NewSubfileType is 0, the full-resolution image, in the order exiftool reads them (IFD0, its SubIFDs depth first with their next IFDs, then IFD0's next IFD), or else IFD0's; unlike exiftool, a width and a height come from one IFD, and a size of 0, a negative one or one past 2^31 - 1 is none. DNG is TIFF with the DNG version tag in IFD0. A table of any size whose entries fit in the data is read, as exiftool reads one of 65,535 entries, and SubIFD offsets are decoded as exiftool decodes them, with the same rules as the Exif pointers below (in BigTIFF also LONG8, SLONG8 and IFD8, but not UNDEFINED); the walk reads at most 4,096 IFDs, 64 SubIFD levels deep, and stops once it has read more entries than tables that do not overlap could hold. A classic IFD is read when 0, 2 or 4 bytes of its next-IFD field are present and is not read when 1 or 3 are (exiftool 13.55 drops that directory). When that directory is IFD0 the file is not opened, and the error is "IFD0's next-IFD field has 1 of its 4 bytes, so IFD0 is not read and the image has no size" (or 3 of its 4 bytes). A wholly missing next field is still read, with no next IFD. A JPEG whose frame height is 0 takes it from the DNL segment after the first scan (ITU-T T.81 Β§B.2.5). PNG text keywords (Title, Author, Description, Copyright, Creation Time, Comment) are written before the pixel data, the GIF comment after the header, and the JPEG COM marker before the scan; exiftool's PNG `Artist` keyword is read as the artist when there is no `Author`. `Render` copies every other byte, including the pixels and anything after the PNG IEND, the GIF trailer, or the JPEG EOI; a no-op save is byte-identical. A path save (`SaveToFile(path)` and `SaveToFileAsync`) copies those pixels in 64 KB pieces and writes the same bytes as `Render`. When a field changes, its copies elsewhere in the file change too: the XMP property (`dc:title`, `dc:creator`, `dc:description`, `dc:rights`, `exif:UserComment`) is replaced in place, keeping its start and end tags, or removed for null, in PNG `XML:com.adobe.xmp` and ImageMagick's `Raw profile type xmp`, JPEG APP1 XMP, and the GIF XMP extension; the Exif copies (IFD0 `ImageDescription`, `Artist`, `Copyright`, the Windows XP title, author and comment tags, and `UserComment`) are removed from PNG `eXIf`, ImageMagick's raw EXIF, and JPEG APP1 Exif, from every table exiftool reads with its Exif tags (measured with exiftool 13.55): IFD0 and the IFDs chained after it (IFD1, IFD2, ...), and every Exif IFD (0x8769), SubIFD (0x014A) and interoperability IFD (0xA005) any of them points at, however deep (exiftool shows a copy from any of them; ImageIO and TagLib# read a subset), each table walked once. A pointer is followed as exiftool decodes it: a BYTE, SHORT, LONG, SBYTE, SSHORT, SLONG or IFD value, or UNDEFINED with count 1; an Exif IFD pointer only with count 1, a GPS or interoperability pointer by its first value, SubIFDs by every value; a negative value, or values that do not all lie in the data, name nothing; two pointer arrays at one offset are each read by their own type. IFD0's Exif IFD and GPS pointers are also followed as TagLib# reads them, their 4-byte field taken as a LONG whatever their type and count (measured), so the copy TagLib# shows from such a table is removed too, and its GPS table is protected. A GPS table is read with its GPS tags only: nothing in it is edited and no pointer in it is followed. A table is walked when its entries fit in the data. A pointer whose table's entries do not fit is skipped, as readers skip it. A field edit runs only when that structure is plain, and nothing is written otherwise. It is not plain when a strip, tile or thumbnail offset or length (TIFF 6.0 tags 0x0111/0x0117, 0x0144/0x0145 and 0x0201/0x0202) is typed other than SHORT or LONG; when one of those arrays is named more than once (two tables, both sides of one pair, or the same tag twice in one table); when a complete pair names more values than half the bytes; when a classic next-IFD field has only one, two or three of its four bytes (a wholly absent next field stays editable; exiftool itself still reads a table that has two); when removing an entry would change whether exiftool reads that table's first entry, including a change no tag shows; or when a removed value shares a protected byte, or compacting a table would rewrite any protected range other than that table. Two protected ranges may share a byte. Clear does not use this gate. An edit with nothing to remove still saves. A save is also refused when the tables hold more entries than the data could without overlapping and the block's bytes could hold an entry with one of the field's tags, of any type; edits with nothing to remove save. The `Artist` and ImageMagick `exif:*` text keywords are dropped. A packet no XMP reader reads because it is not well-formed, and does not name a changed field, an ImageMagick raw profile that is not hex, and PNG text that is not zlib data or whose iTXt header is cut short, which no reader decodes, are kept as they are; compressed text past the shared inflation budget is refused, since it cannot be checked. A JPEG stores the comment and the title, and a GIF the comment; only their copies change. An XMP packet followed by NULs or padding (as ImageIO writes it) is edited and the tail kept, and GIF XMP written as data sub-blocks (ImageIO) is edited as well as the raw form with its magic trailer. A save that cannot update a copy (XMP that is not well-formed or has a DTD and names a changed field's property, a value XML cannot hold, an Exif block that is not classic TIFF and whose bytes could hold an entry with one of the field's tags, in either byte order, a JPEG XMP packet that would outgrow its segment, extended XMP, or a GIF XMP block in neither the raw form with its magic trailer nor data sub-blocks, that holds a UserComment) is refused with its own reason, as is a container that cannot be spliced, or a multi-picture JPEG whose MPF index cannot be corrected or (for Clear) followed; the file is left unchanged. A length-changing edit moves bytes after the edited segment, as exiftool does; a maker-note pointer to data after the image (for example Sony's preview tag 0x2001) is not rewritten (#163). When a maker note is not fully located, a removed value outside the Exif tables keeps its bytes. Inflated PNG text is capped at 1 MiB for the whole file, on read and on save. `Clear` removes all tag metadata and keeps only what a decoder or colour management needs, or the file's structure: PNG critical chunks and tRNS, gAMA, cHRM, sRGB, iCCP, cICP, mDCV, cLLI, sBIT, bKGD, hIST, pHYs, sPLT, the APNG chunks, oFFs, pCAL, sCAL and sTER; JPEG APP0 JFIF/JFXX, APP2 ICC_PROFILE, MPF and the ISO 21496-1 gain map, APP14 Adobe, the XMP an HDR decoder needs to find and apply a gain map (Ultra HDR `hdrgm` and `Container`/`Item` directory, Apple `apdi` and `HDRGainMap` version and headroom, and the motion-photo `Camera:MotionPhoto`, `MotionPhotoVersion` and `MotionPhotoPresentationTimestampUs` so a motion photo stays one; Clear writes a new packet from those properties alone, each checked against the value the format defines (a version, a Boolean, a Real or three, an integer, a timestamp that may be -1, an item semantic of `Primary`, `GainMap` or `MotionPhoto`, a MIME type of `image/jpeg`, `image/heic`, `image/avif`, `video/mp4` or `video/quicktime`, a length or padding), so no other property, attribute, nested structure or text survives; an item value outside those lists is dropped and the item keeps its place and length, a directory item may be written as `rdf:li` > `rdf:Description`, and a directory with an entry that holds no item is dropped whole; the first occurrence of a property wins, and the gain map's `Item:Length` follows its new length while later items such as a motion-photo video keep theirs. An Apple gain map of version 65536 (iPhone 12-14) has no headroom in its XMP: ImageIO and libultrahdr take it from the primary image's Apple maker note, tags 33 and 48. For such a file Clear writes a new Exif in the primary holding only those two maker-note values, copied as stored, and nothing else of the Exif: no IFD0, GPS or other Exif tag and no other maker-note tag. The values kept are the ones ImageIO applies, measured with every level duplicated and broken (where libultrahdr reads a file differently, Clear follows ImageIO): the first Exif segment, whose TIFF magic must be 42; at each level (IFD0's Exif IFD pointers, each Exif IFD's MakerNote entries, the maker note's 0x0021 and 0x0030 entries) an occurrence ImageIO cannot use is skipped and a later usable one overrides an earlier one, two Exif IFDs merging value by value; a maker-note value is usable when it is SRATIONAL with every value inside the maker note, at any offset; the headroom is kept only when both winning entries have count 1 (otherwise ImageIO renders no HDR image), and a winning MakerNote that is not Apple's keeps nothing. ImageIO then renders exactly what it rendered before, HDR or SDR; without the values it renders the photo SDR and libultrahdr refuses it. The new Exif is a minimal carrier for the two decode parameters, not a conformant Exif: it deliberately omits the tags Exif marks mandatory (ExifVersion, ComponentsConfiguration, ColorSpace, the pixel dimensions, YCbCrPositioning, the resolution tags), consistent with Clear removing all other Exif, so `exiftool -validate` warns about them; ImageIO, libultrahdr, ffmpeg, exiftool and TagLib# all read it), and the APP11 JPEG XT decoding boxes (`ftyp`, `TONE`, `RTRF`, `LTRF`, `LCHK`, `SPEC`, `RESI`); GIF graphic control and plain text extensions, looping and ICC application extensions. Everything else goes, including PNG text, `eXIf`, `tIME` and `caBX`, JPEG Exif (but for the Apple headroom above), the rest of XMP and extended XMP, IPTC, maker segments and every other APP11 box (JUMBF/C2PA, `xml `, `uuid`, `json`, `Exif`, unknown), and GIF XMP and ImageMagick's IPTC. In a multi-picture JPEG (MPF), Clear cleans every image the MPF index lists with the same rules; the index's offsets and sizes are rewritten after Clear and after an edit. An MP index outside its APP2 segment, or listing an image before the first image's end (its EOI), outside the file or overlapping another, is not followed: Clear is refused, and so is an edit that would move the later images. Apple's PNG `iDOT` is dropped when a chunk between it and the first IDAT changes. A field the format does not store reads back as null. EXIF, IPTC, and XMP values are not read yet, and SVG metadata is not read or written yet. +- Still images: `MediaFile.Read` and `StillImageFile.Read`/`ReadFromFile`/`ReadFromFileAsync` open JPEG, PNG, GIF, BMP, PCX, Netpbm (PBM, PGM, PPM, PNM), TIFF, DNG, and SVG and report width and height. A TIFF or DNG reports the size exiftool's ImageSize gives (measured case by case): the width and height of the first IFD whose NewSubfileType is 0, the full-resolution image, in the order exiftool reads them (IFD0, its SubIFDs depth first with their next IFDs, then IFD0's next IFD), or else IFD0's; unlike exiftool, a width and a height come from one IFD, and a size of 0, a negative one or one past 2^31 - 1 is none. DNG is TIFF with the DNG version tag in IFD0. A table of any size whose entries fit in the data is read, as exiftool reads one of 65,535 entries, and SubIFD offsets are decoded as exiftool decodes them, with the same rules as the Exif pointers below (in BigTIFF also LONG8, SLONG8 and IFD8, but not UNDEFINED); the walk reads at most 4,096 IFDs, 64 SubIFD levels deep, and stops once it has read more entries than tables that do not overlap could hold. A classic IFD is read when 0, 2 or 4 bytes of its next-IFD field are present and is not read when 1 or 3 are (exiftool 13.55 drops that directory). When that directory is IFD0 the file is not opened, and the error is "IFD0's next-IFD field has 1 of its 4 bytes, so IFD0 is not read and the image has no size" (or 3 of its 4 bytes). A wholly missing next field is still read, with no next IFD. A JPEG whose frame height is 0 takes it from the DNL segment after the first scan (ITU-T T.81 Β§B.2.5). PNG text keywords (Title, Author, Description, Copyright, Creation Time, Comment) are written before the pixel data, the GIF comment after the header, and the JPEG COM marker before the scan; exiftool's PNG `Artist` keyword is read as the artist when there is no `Author`. `Render` copies every other byte, including the pixels and anything after the PNG IEND, the GIF trailer, or the JPEG EOI; a no-op save is byte-identical. A path save (`SaveToFile(path)` and `SaveToFileAsync`) copies those pixels in 64 KB pieces and writes the same bytes as `Render`. When a field changes, its copies elsewhere in the file change too: the XMP property (`dc:title`, `dc:creator`, `dc:description`, `dc:rights`, `exif:UserComment`) is replaced in place, keeping its start and end tags, or removed for null, in PNG `XML:com.adobe.xmp` and ImageMagick's `Raw profile type xmp`, JPEG APP1 XMP, and the GIF XMP extension; the Exif copies (IFD0 `ImageDescription`, `Artist`, `Copyright`, the Windows XP title, author and comment tags, and `UserComment`) are removed from PNG `eXIf`, ImageMagick's raw EXIF, and JPEG APP1 Exif, from every table exiftool reads with its Exif tags (measured with exiftool 13.55): IFD0 and the IFDs chained after it (IFD1, IFD2, ...), and every Exif IFD (0x8769), SubIFD (0x014A) and interoperability IFD (0xA005) any of them points at, however deep (exiftool shows a copy from any of them; ImageIO and TagLib# read a subset), each table walked once. A pointer is followed as exiftool decodes it: a BYTE, SHORT, LONG, SBYTE, SSHORT, SLONG or IFD value, or UNDEFINED with count 1; an Exif IFD pointer only with count 1, a GPS or interoperability pointer by its first value, SubIFDs by every value; a negative value, or values that do not all lie in the data, name nothing; two pointer arrays at one offset are each read by their own type. IFD0's Exif IFD and GPS pointers are also followed as TagLib# reads them, their 4-byte field taken as a LONG whatever their type and count (measured), so the copy TagLib# shows from such a table is removed too, and its GPS table is protected. A GPS table is read with its GPS tags only: nothing in it is edited and no pointer in it is followed. A table is walked when its entries fit in the data. A pointer whose table's entries do not fit is skipped, as readers skip it. A field edit runs only when that structure is plain, and nothing is written otherwise. It is not plain when a strip, tile or thumbnail offset or length (TIFF 6.0 tags 0x0111/0x0117, 0x0144/0x0145 and 0x0201/0x0202) is typed other than SHORT or LONG; when one of those arrays is named more than once (two tables, both sides of one pair, or the same tag twice in one table); when a complete pair names more values than half the bytes; when a classic next-IFD field has only one, two or three of its four bytes (a wholly absent next field stays editable; exiftool itself still reads a table that has two); when removing an entry would change whether exiftool reads that table's first entry, including a change no tag shows; or when a removed value shares a protected byte, or compacting a table would rewrite any protected range other than that table. Two protected ranges may share a byte. Clear does not use this gate. An edit with nothing to remove still saves. A save is also refused when the tables hold more entries than the data could without overlapping and the block's bytes could hold an entry with one of the field's tags, of any type; edits with nothing to remove save. The `Artist` and ImageMagick `exif:*` text keywords are dropped. A packet no XMP reader reads because it is not well-formed, and does not name a changed field, an ImageMagick raw profile that is not hex, and PNG text that is not zlib data or whose iTXt header is cut short, which no reader decodes, are kept as they are; compressed text past the shared inflation budget is refused, since it cannot be checked. A JPEG stores the comment and the title, and a GIF the comment; only their copies change. An XMP packet followed by NULs or padding (as ImageIO writes it) is edited and the tail kept, and GIF XMP written as data sub-blocks (ImageIO) is edited as well as the raw form with its magic trailer. A save that cannot update a copy (XMP that is not well-formed or has a DTD and names a changed field's property, a value XML cannot hold, an Exif block that is not classic TIFF and whose bytes could hold an entry with one of the field's tags, in either byte order, a JPEG XMP packet that would outgrow its segment, extended XMP, or a GIF XMP block in neither the raw form with its magic trailer nor data sub-blocks, that holds a UserComment) is refused with its own reason, as is a container that cannot be spliced, or a multi-picture JPEG whose MPF index cannot be corrected or (for Clear) followed; the file is left unchanged. A length-changing edit moves bytes after the edited segment, as exiftool does; a maker-note pointer to data after the image (for example Sony's preview tag 0x2001) is not rewritten (#163). When a maker note is not fully located, a removed value outside the Exif tables keeps its bytes. Inflated PNG text is capped at 1 MiB for the whole file, on read and on save. `Clear` removes all tag metadata and keeps only what a decoder or colour management needs, or the file's structure: PNG critical chunks and tRNS, gAMA, cHRM, sRGB, iCCP, cICP, mDCV, cLLI, sBIT, bKGD, hIST, pHYs, sPLT, the APNG chunks, oFFs, pCAL, sCAL and sTER; JPEG APP0 JFIF/JFXX, APP2 ICC_PROFILE, MPF and the ISO 21496-1 gain map, APP14 Adobe, the XMP an HDR decoder needs to find and apply a gain map (Ultra HDR `hdrgm` and `Container`/`Item` directory, Apple `apdi` and `HDRGainMap` version and headroom, and the motion-photo `Camera:MotionPhoto`, `MotionPhotoVersion` and `MotionPhotoPresentationTimestampUs` so a motion photo stays one; Clear writes a new packet from those properties alone, each checked against the value the format defines (a version, a Boolean, a Real or three, an integer, a timestamp that may be -1, an item semantic of `Primary`, `GainMap` or `MotionPhoto`, a MIME type of `image/jpeg`, `image/heic`, `image/avif`, `video/mp4` or `video/quicktime`, a length or padding), so no other property, attribute, nested structure or text survives; an item value outside those lists is dropped and the item keeps its place and length, a directory item may be written as `rdf:li` > `rdf:Description`, and a directory with an entry that holds no item is dropped whole; the first occurrence of a property wins, and the gain map's `Item:Length` follows its new length while later items such as a motion-photo video keep theirs. An Apple gain map of version 65536 (iPhone 12-14) has no headroom in its XMP: ImageIO and libultrahdr take it from the primary image's Apple maker note, tags 33 and 48. For such a file Clear writes a new Exif in the primary holding only those two maker-note values, copied as stored, and nothing else of the Exif: no IFD0, GPS or other Exif tag and no other maker-note tag. The values kept are the ones ImageIO applies, measured with every level duplicated and broken (where libultrahdr reads a file differently, Clear follows ImageIO): the first Exif segment, whose TIFF magic must be 42; at each level (IFD0's Exif IFD pointers, each Exif IFD's MakerNote entries, the maker note's 0x0021 and 0x0030 entries) an occurrence ImageIO cannot use is skipped and a later usable one overrides an earlier one, two Exif IFDs merging value by value; a maker-note value is usable when it is SRATIONAL with every value inside the maker note, at any offset; the headroom is kept only when both winning entries have count 1 (otherwise ImageIO renders no HDR image), and a winning MakerNote that is not Apple's keeps nothing. ImageIO then renders exactly what it rendered before, HDR or SDR; without the values it renders the photo SDR and libultrahdr refuses it. The new Exif is a minimal carrier for the two decode parameters, not a conformant Exif: it deliberately omits the tags Exif marks mandatory (ExifVersion, ComponentsConfiguration, ColorSpace, the pixel dimensions, YCbCrPositioning, the resolution tags), consistent with Clear removing all other Exif, so `exiftool -validate` warns about them; ImageIO, libultrahdr, ffmpeg, exiftool and TagLib# all read it), and the APP11 JPEG XT decoding boxes (`ftyp`, `TONE`, `RTRF`, `LTRF`, `LCHK`, `SPEC`, `RESI`); GIF graphic control and plain text extensions, looping and ICC application extensions. Everything else goes, including PNG text, `eXIf`, `tIME` and `caBX`, JPEG Exif (but for the Apple headroom above), the rest of XMP and extended XMP, IPTC, maker segments and every other APP11 box (JUMBF/C2PA, `xml `, `uuid`, `json`, `Exif`, unknown), and GIF XMP and ImageMagick's IPTC. In a multi-picture JPEG (MPF), Clear cleans every image the MPF index lists with the same rules; the index's offsets and sizes are rewritten after Clear and after an edit. An MP index outside its APP2 segment, or listing an image before the first image's end (its EOI), outside the file or overlapping another, is not followed: Clear is refused, and so is an edit that would move the later images. Apple's PNG `iDOT` is dropped when a chunk between it and the first IDAT changes. A field the format does not store reads back as null. Apart from the JPEG title, EXIF, IPTC, and XMP values are not read yet, and SVG metadata is not read or written yet. #### Raw AAC (ADTS/ADIF) Support - `AacFile` reads and writes raw AAC files (`.aac`): ADTS (ISO/IEC 13818-7 Β§6.2, MPEG-2 and MPEG-4) and ADIF (Β§6.1) @@ -115,9 +85,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Matroska flat sorts (`ARTIST_SORT`, `ALBUM_ARTIST_SORT`, `COMPOSER_SORT`) belong to the value in their own Tag, as ffmpeg writes them. A Tag without that value passes its sort down to the value below it, and a broader Tag that repeats the same value is the same value (the tagging spec allows repeating it per track). Only a broader Tag with a different value keeps its own sort apart. A set leaves one copy, in the value's Tag; a clear removes every copy of that value's sort; a cleared value takes the sorts of its own Tag and of the value-less broader Tags above it, unless an equal value below still reads them, and a broader Tag that repeats it keeps its own; and a value placed between another value and its sort moves that sort down to the value it sorts. The track title, album title and album-level album artist pair their sorts over the run that starts at their level, so a value-less `ALBUM_ARTIST_SORT` at 60 or 70 is read, cleared and replaced too. A value written equal to the broader one it shadows repeats that SimpleTag with its `SORT_WITH`. Tags that target a chapter, attachment, track or edition are never read or changed by these rules. - Matroska custom fields named `TITLE_SORT`, `ARTIST_SORT`, `ALBUM_SORT`, `ALBUM_ARTIST_SORT` or `COMPOSER_SORT` are read, written and removed through the matching sort property, so they pair with their value and see a nested `SORT_WITH`; a sort takes one value. - Matroska setters treat writing back the value read as a no-op, so the file's bytes stay as they were; a null still clears, including a value a broader level holds behind an empty one. They follow `Tag.IsWriteBack`, checked before anything changes and against the list the getter reads: `""` or an empty list is a write-back only when no value holds text, and `CopyTo` makes the target hold exactly the source's value, so a copy equal to the target's first ISRC, catalog number, artist or genre replaces the rest of the list. `Publisher = null` also removes `LABEL`, and `ReplayGainTrackGain`/`ReplayGainTrackPeak` remove the older `REPLAYGAIN_GAIN`/`REPLAYGAIN_PEAK` copy on a set or clear, as their getters read those names. +- An APE artist, album artist, composer, or genre is the first name. It is not a comma-joined string. A Basic copy from APE into MP4, ASF, RIFF INFO, or ID3v1 keeps that first name. A copy with the Extended options into ASF keeps every name, the first in the Content Description and the rest in the Metadata Library. A copy into ID3v2 keeps the full list. +- A single-value ID3v2 or Vorbis Comment property, and an APE artist, album artist, composer, or genre, returns the first non-empty value, and an empty string only when every value is empty. Other APE text items still read every non-empty value joined with ", " (`A\0B` reads "A, B"). So do the public `Id3v2Tag.GetTextFrame`, `Id3v2Tag.GetUserText`, and `VorbisComment.GetValue`, and the ID3v2 comment and lyrics, which read the first non-empty frame without a description, then the first other one. ID3v2.4 Β§4.2 stores several strings as a NUL-separated list and Vorbis field names may repeat, so `"\0V2"` and `ARTIST=` + `ARTIST=V2` read `V2`. A value is kept as written: only an empty value is skipped, so `" \0B"` reads `" "`, as other readers show it. `Id3v2Tag.GetTextFrameValues` and the ID3v2 list properties no longer trim or drop blank NUL-separated values, so for NUL-separated values the single value and the first list entry agree. A slash is not a separator (see Breaking Changes), so `AC/DC` reads Artist `AC/DC` and Performers [`AC/DC`]. This replaces the earlier reading of a leading NUL as an empty first value, and it differs from mutagen and TagLib#, which return the empty first ID3v2 value; for a comment it matches what ffprobe and TagLib# show. Writing back the value read changes nothing, so a multi-value frame, item, or repeated field keeps every value. `= ""` clears: it removes the ID3v2 frame (for a comment or lyrics, every frame without a description) or the APE item, and leaves one empty Vorbis field. The comparison is ordinal, so a case-only edit still writes, and `null` clears like `= ""`. For an ID3v2 comment or lyrics, both remove only the frames without a description; a described comment or lyrics frame (such as `ID3v1 Comment`) is then still read, as before. This covers every ID3v2 string property (every text and TXXX frame, the year, the podcast feed URL, the MusicBrainz recording ID, the comment and the lyrics, and the movement number and total), every APE text property, and every Vorbis text field. +- `CopyTo` reads every source value before it writes any. It replaces the target's list with the source value, even when that equals the target's first value. A list (performers, album artists, composers, genres, and the sort and role lists) that the target already holds is left as it is, and with `Extended` the artist and genre travel in those lists, so a `Basic` copy alone is what writes a single name over a list. When the source and target read from a common tag (a tag copied into itself, or a file's combined `Tag` copied into one of its own tags or into another view over them, as two reads of `Mp3File.Tag` are), the copy only adds values the target does not show. An empty source value still clears the field, as `= ""` does, so through a view it also clears what the view showed from another tag (an ID3v1 title, an AIFF `NAME` chunk). So `mp3.Id3v2Tag.CopyTo (mp3.Tag)` no longer rewrites the ID3v1 tag with values the combined view already shows from ID3v2. A fallback field of its own beside a value equal to the copied one stays: Vorbis `ORIGINALYEAR`, APE `Date`, and the ID3v2.3 `TDOR` beside `TORY`. Pictures are outside these rules: a non-empty source picture list always replaces the target's, as before. +- A list copied into a tag that holds one name (MP4, ASF, RIFF INFO, ID3v1, or the base `Tag` list setters) stores its first non-empty entry, not an empty first entry. A copy of `ARTIST=` + `ARTIST=V2` into an MP4, WAV, or WMA file stores `V2`, as a `Basic` copy already did, instead of clearing the artist and genre. +- Vorbis and APE movements follow MusicBrainz Picard's tag mapping: the name is `MOVEMENTNAME` and the number is `MOVEMENT` (`MOVEMENTNUMBER` is still read first and kept in step). A new name is written to `MOVEMENTNAME` and a new number to `MOVEMENT`, where the name went to `MOVEMENT` and the number to `MOVEMENTNUMBER` before. A `MOVEMENT` that is not a number is still read as the name when there is no `MOVEMENTNAME`, and is kept in step with a new name; a numeric name then goes to `MOVEMENTNAME` only. Clearing one half never changes how the other half reads, and a copy from a Picard FLAC no longer writes the number "2" over an ID3v2 `MVNM`. +- Clearing an APE year also removes `Date`, and setting a new year also writes it to an existing `Date`. A locator reads as the same string a title locator reads. An empty text item reads as an empty string, and a binary item reads as null, for a name and for a title. +- Clearing a Vorbis original release date also removes `ORIGINALYEAR`, and setting a new date rewrites an existing `ORIGINALYEAR` to its four-digit year. Writing back the APE year, Vorbis original release date, or movement already read changes nothing, so a Picard or Mp3tag tag keeps every field. An empty `Year` or `ORIGINALDATE` no longer hides a filled `Date` or `ORIGINALYEAR`; the same holds for an empty ID3v2 `MVNM`, and for a `TDOR` or `TORY` that holds no date. +- An ID3v2 movement write now also stores the name in Apple's `MVNM` frame, and a movement number or total also updates `MVIN`, keeping the other half. Clearing removes those frames too. +- Setting a new ID3v2 original release date, or clearing it, removes both `TDOR` and `TORY`, then writes the frame for the tag's version, so the other version's frame cannot come back. Writing back the date already read changes nothing. ### Fixed +Some of these entries fix features that are new in 0.7.0 (Matroska/WebM, MPEG-PS, AVI, raw AAC, Audible, still images, MP4 chapters and keyed metadata, custom fields, `SkipPictures`), so the bug they describe was only in builds from `main`, never in a release. + - A crafted ID3v2 tag of many small compressed frames that each declare a large decompressed size no longer makes a read or a save allocate without bound (#275). One read of a file now inflates at most 64 MiB in all, shared by every compressed frame of every ID3v2 tag it parses: top-level frames, those CHAP and CTOC embed, and every ID3 chunk of an AIFF and the tag chunks after a WAV or AIFF, which are recognised as tags without inflating anything; a save re-encodes embedded frames within 16 MiB. The per-frame limits stay 16 MiB and 1,100:1; there was no limit across the tag or the file, so 50 frames of 16 MiB allocated about 800 MB to read, 40 ID3 chunks in an AIFF about 1.9 GB, and a save of an 819 KB tag rendered 839 MB; that save now allocates about 165 MB. A frame past the budget is not decoded and is written back as stored, byte for byte. A save whose ID3v2 tag, or one of its frames, would be larger than an ID3v2 size can hold (0x0FFFFFFF) now fails with a result that says so and writes nothing, in MP3, raw AAC, MPEG-PS, WAV, AIFF, DSF, DFF and AVI, where it threw `ArgumentOutOfRangeException` from the size writer; the check renders the tag, with the padding the carrier writes it with, only when a bound on its size, taken from the frames without rendering them, could pass the limit. A save that renders the tag as it was read, to see whether the caller changed it (MPEG-PS, AVI, and WAV or AIFF with a tag chunk after the form), takes a tag as read that is too large to render as changed, so an edit that makes the tag smaller saves. `Id3v2Tag.Render` and a carrier's `Render` throw an `InvalidOperationException` with that message - An ID3v2.3 frame that is both compressed and grouped reads (#272). ID3v2.3 Β§3.3.1 puts the extra bytes in the flags' order, the decompressed size before the group byte, and the group byte was read first, so the size was read from the wrong bytes and a frame that compresses well was rejected. ID3v2.4, which puts the group byte first, is unchanged. This reaches the frames CHAP and CTOC embed too - An ID3v2 URL frame (W*** and the URL of WXXX) whose URL has characters outside ISO-8859-1 writes each of them percent-encoded as UTF-8, as an IRI maps to a URI (RFC 3987 Β§3.1), where each was written as `?` (#266). A URL that ISO-8859-1 holds is written as given, and a character from U+0080 to U+00FF stays one ISO-8859-1 byte; a read gives back the text written, in its encoded form. The frame's `Url` keeps what was set until the file is read again @@ -162,7 +143,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - An ID3v2.4 tag whose footer flag is set with no footer after it no longer takes the 10 bytes after its body (#202). The reader counted the footer from the flag alone, so those bytes were not the audio's, and a save dropped them: an MP3, AAC or MPEG-PS file lost the first 10 bytes of its audio. ID3v2.4 Β§3.4 makes the footer a copy of the header whose identifier is "3DI"; a footer now counts only when that "3DI" is there, on every reader that finds where a tag ends: the tag read, the copy a `SkipPictures` read makes, AAC's audio start and detection, and MPEG-PS's tag length. A tag with a real footer reads as before. - A path save after a save over the source now writes what a fresh read of the file on disk, given the same edit, writes (#179). Each save reads the file the save before it left on disk. MP3, FLAC, AAC and untagged DSF files applied the offsets of the first read to it and reported success: an MP3 lost audio and its duration changed, a FLAC file kept old metadata in front of its audio, an AAC file got a wrong stream extent and, from the third save on, no duration, and an untagged DSF file that was given a tag kept that tag as sound. PNG, JPEG and GIF files planned the edit against the bytes they read and copied from the file on disk: the second save wrote an unreadable JPEG, a GIF without its comment and a PNG whose chunks no longer reach IEND. MPEG-PS refused the second save in place. MP3, FLAC, AAC, MPEG-PS, PNG, JPEG and GIF files now take the layout of the file a save wrote over their source, by path or by span and under any spelling of the path; the source is read back after the save to tell. A span save from the bytes of that file works, and one from the bytes they read now fails with a message that names the file they last saved over their source (Audible's message, which said it was the file read, now says so too). A DSF file keeps its sound where the read found it, so it describes every file it saves; a path save from a source that ends before that sound fails with the message `Render` gives. A path save of an MP3, FLAC or AAC file whose source is no longer of a length the object describes now fails and writes nothing. A known limit, filed as #195: an MP3 or AAC file with two tags of one kind stacked (two ID3v2 tags in front, or two ID3v1 tags at the end). A read takes the outer tag and leaves the inner one in the audio, as before; a save that drops the outer tag uncovers the inner one, which a fresh read of the saved file takes as its tag and this object does not, so a later save of the object keeps the inner tag in front of the tag it writes. No audio is lost. - `Mp3File.Id3v1Tag = null` followed by a save now removes the ID3v1 tag; its 128 bytes used to stay at the end of the file as audio, and a read of the saved file still found the tag. Giving a file without an ID3v1 tag one no longer drops the last 128 bytes of its audio. The audio ends at the ID3v1 tag of the file, not at the one the object holds. -- A save of a Monkey's Audio, WavPack or Musepack file no longer drops the APEv2 tag's 32-byte header and clears the footer's "has header" flag (#217). The tag read from the file is written back the way it was read: with a header when it had one, footer-only when it had none, so a save with no edit keeps the tag's layout and the file's size. Any other tag, a new one or one parsed elsewhere and assigned, gets the format's layout, as before: footer-only in these formats, a header in raw AAC. `ApeTag.Render ()` writes a parsed tag with the header it was read with, and a new one without; `RenderWithOptions` is unchanged. Items are still written in order of size, as before. +- A save of a Monkey's Audio, WavPack or Musepack file no longer drops the APEv2 tag's 32-byte header and clears the footer's "has header" flag (#217). The tag read from the file is written back the way it was read: with a header when it had one, footer-only when it had none, so a save with no edit keeps the tag's layout and the file's size. Any other tag, a new one or one parsed elsewhere and assigned, gets the format's layout, as before: footer-only in these formats, a header in raw AAC. `ApeTag.Render ()` writes a parsed tag with the header it was read with, and a new one without; `RenderWithOptions` is unchanged. Items are written in the order they were read (#238). - An APEv2 footer that claims a header (bit 31) with no `APETAGEX` in front of its items reads the same from a path or stream as from bytes (#240). The stream tag read of Monkey's Audio, WavPack and Musepack and the MPEG-PS trailer search took the claim at its word: a small Musepack file read no tag from a path, a small Monkey's Audio file read a bitrate of 0, and an MPEG-PS file did not find an ID3v2 tag appended before such an APE tag. Every reader now counts a header only when those bytes are there, as the bytes read already did. - A path save of a Monkey's Audio, WavPack or Musepack file whose APEv2 tag is followed by Lyrics3 v2 and ID3v1 no longer keeps the old tag in front of the new one (#241). When the first read from the end held LYRICSBEGIN but only part of the APE footer in front of it, the save did not read further, kept the old tag as audio and grew the file by its size. It now reads the footer, and writes what `Render` writes. - A path or stream read of a Monkey's Audio, WavPack or Musepack file with no APEv2 tag at its end no longer returns a tag that sits at the end of the header bytes it reads (#242). Those reads parse the header bytes joined to the tag read from the end; with no tag there, a footer and items at the end of the header bytes became the file's tag, and a save wrote it at the end of the file. A tag now counts only when it starts in the part read from the end, so these reads find a tag only where a read from bytes does. @@ -209,31 +190,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Matroska: an edited or added top-level element stays listed in the SeekHead (RFC 9559 section 6.1). When the SeekHead has no room for its Seek, or its Seek cannot hold the new offset, the element goes right after the first SeekHead. The SeekHead is written again with every Seek at the width it needs, and everything after it moves once. Without a SeekHead the element goes before the first Cluster. Before this, an artist edit or a no-op save on `test1.mkv` or `test6.mkv` dropped the Tags Seek, and ffprobe and mediainfo lost the tags. - Matroska: when a save moves elements, the Segment Positions (RFC 9559 section 16) in each SeekPosition in every SeekHead, the Cues `CueClusterPosition`, `CueCodecState` and the historic `CueRefCluster` and `CueRefCodecState`, and Cluster `Position` follow them, with their CRC-32 values. A value that no longer fits its field is written wider, and its SeekHead or Cues element grows, moving what follows once more; however the widths cascade, the work stays linear in the size of the SeekHead and Cues elements. The deprecated `ReferenceVirtual` (Appendix A.4, inside a BlockGroup) is left as it is. Before this, a cover or Tags element over about 64 KB on a file whose CueClusterPosition had two bytes was refused or lost its Seek, a CueCodecState kept its old value, and growing an element could void another element's Seek. A zero CueCodecState still names the TrackEntry. An empty Cues position reads as 0 (RFC 8794 section 7.2) and is kept, or written wider when the offset 0 it names moves. A Cluster `Position` that cannot widen in place is voided, since it is optional. Cues values are read only on their RFC 9559 section 5.1.5 paths (Cues, CuePoint, CueTrackPositions, CueReference); any other nesting is copied as it is, so a file that nests CuePoints thousands deep cannot exhaust the stack. The widths are rewritten at most seven times; a crafted file whose widths keep growing is refused there (a move falls back to its first placement). - Matroska: a save keeps one copy of the Segment body at a time; a move no longer holds a second one. -- **MP4**: A version 1 `mvhd` or `mdhd` whose 64-bit duration is past `TimeSpan.MaxValue` no longer throws - out of `Mp4File.Read` or `Mp4AudioPropertiesParser.Parse`; the duration saturates. -- ID3v2 UTF-16 text with a byte order mark on each string (ID3v2.3 Β§3.3, mutagen's default) reads without a - U+FEFF at the start of every value after the first, in text frames, `TXXX`, and `TIPL`/`TMCL`/`IPLS`. One - decoder reads all of them on every target framework. A text or `TXXX` frame read from a file renders with the - BOMs and the trailing terminators it was read with, so an empty last value survives an unchanged save. A - `TXXX` that `SetCustomField` writes in an ID3v2.3 tag has a BOM before each value; a frame built in code keeps - one BOM, as before. -- Writing back the gain `R128TrackGainDb` or `R128AlbumGainDb` read keeps the stored text, so `-0512` is not - rewritten as `-512`. `null` still clears it, text the getter cannot parse included. -- An ASF title, artist, copyright, comment, or rating write replaces the same-named Extended Content Description - descriptor that ffmpeg writes beside the Content Description field, so other tools no longer show the old value. - An empty Content Description field reads that descriptor. - -### Changed - -- An APE artist, album artist, composer, or genre is the first name. It is not a comma-joined string. A Basic copy from APE into MP4, ASF, RIFF INFO, or ID3v1 keeps that first name. A copy with the Extended options into ASF keeps every name, the first in the Content Description and the rest in the Metadata Library. A copy into ID3v2 keeps the full list. -- A single-value ID3v2 or Vorbis Comment property, and an APE artist, album artist, composer, or genre, returns the first non-empty value, and an empty string only when every value is empty. Other APE text items still read every non-empty value joined with ", " (`A\0B` reads "A, B"). So do the public `Id3v2Tag.GetTextFrame`, `Id3v2Tag.GetUserText`, and `VorbisComment.GetValue`, and the ID3v2 comment and lyrics, which read the first non-empty frame without a description, then the first other one. ID3v2.4 Β§4.2 stores several strings as a NUL-separated list and Vorbis field names may repeat, so `"\0V2"` and `ARTIST=` + `ARTIST=V2` read `V2`. A value is kept as written: only an empty value is skipped, so `" \0B"` reads `" "`, as other readers show it. `Id3v2Tag.GetTextFrameValues` and the ID3v2 list properties no longer trim or drop blank NUL-separated values, so for NUL-separated values the single value and the first list entry agree. A value with `/` and no NUL is still split on `/` and trimmed, in any ID3v2 version, so `AC/DC` reads Artist `AC/DC` and Performers [`AC`, `DC`], as before. This replaces the earlier reading of a leading NUL as an empty first value, and it differs from mutagen and TagLib#, which return the empty first ID3v2 value; for a comment it matches what ffprobe and TagLib# show. Writing back the value read changes nothing, so a multi-value frame, item, or repeated field keeps every value. `= ""` clears: it removes the ID3v2 frame (for a comment or lyrics, every frame without a description) or the APE item, and leaves one empty Vorbis field. The comparison is ordinal, so a case-only edit still writes, and `null` clears like `= ""`. For an ID3v2 comment or lyrics, both remove only the frames without a description; a described comment or lyrics frame (such as `ID3v1 Comment`) is then still read, as before. This covers every ID3v2 string property (every text and TXXX frame, the year, the podcast feed URL, the MusicBrainz recording ID, the comment and the lyrics, and the movement number and total), every APE text property, and every Vorbis text field. -- `CopyTo` reads every source value before it writes any. It replaces the target's list with the source value, even when that equals the target's first value. A list (performers, album artists, composers, genres, and the sort and role lists) that the target already holds is left as it is, and with `Extended` the artist and genre travel in those lists, so a `Basic` copy alone is what writes a single name over a list. When the source and target read from a common tag (a tag copied into itself, or a file's combined `Tag` copied into one of its own tags or into another view over them, as two reads of `Mp3File.Tag` are), the copy only adds values the target does not show. An empty source value still clears the field, as `= ""` does, so through a view it also clears what the view showed from another tag (an ID3v1 title, an AIFF `NAME` chunk). So `mp3.Id3v2Tag.CopyTo (mp3.Tag)` no longer rewrites the ID3v1 tag with values the combined view already shows from ID3v2. A fallback field of its own beside a value equal to the copied one stays: Vorbis `ORIGINALYEAR`, APE `Date`, and the ID3v2.3 `TDOR` beside `TORY`. Pictures are outside these rules: a non-empty source picture list always replaces the target's, as before. -- A list copied into a tag that holds one name (MP4, ASF, RIFF INFO, ID3v1, or the base `Tag` list setters) stores its first non-empty entry, not an empty first entry. A copy of `ARTIST=` + `ARTIST=V2` into an MP4, WAV, or WMA file stores `V2`, as a `Basic` copy already did, instead of clearing the artist and genre. -- Vorbis and APE movements follow MusicBrainz Picard's tag mapping: the name is `MOVEMENTNAME` and the number is `MOVEMENT` (`MOVEMENTNUMBER` is still read first and kept in step). A new name is written to `MOVEMENTNAME` and a new number to `MOVEMENT`, where the name went to `MOVEMENT` and the number to `MOVEMENTNUMBER` before. A `MOVEMENT` that is not a number is still read as the name when there is no `MOVEMENTNAME`, and is kept in step with a new name; a numeric name then goes to `MOVEMENTNAME` only. Clearing one half never changes how the other half reads, and a copy from a Picard FLAC no longer writes the number "2" over an ID3v2 `MVNM`. -- Clearing an APE year also removes `Date`, and setting a new year also writes it to an existing `Date`. A locator reads as the same string a title locator reads. An empty text item reads as an empty string, and a binary item reads as null, for a name and for a title. -- Clearing a Vorbis original release date also removes `ORIGINALYEAR`, and setting a new date rewrites an existing `ORIGINALYEAR` to its four-digit year. Writing back the APE year, Vorbis original release date, or movement already read changes nothing, so a Picard or Mp3tag tag keeps every field. An empty `Year` or `ORIGINALDATE` no longer hides a filled `Date` or `ORIGINALYEAR`; the same holds for an empty ID3v2 `MVNM`, and for a `TDOR` or `TORY` that holds no date. -- An ID3v2 movement write now also stores the name in Apple's `MVNM` frame, and a movement number or total also updates `MVIN`, keeping the other half. Clearing removes those frames too. -- Setting a new ID3v2 original release date, or clearing it, removes both `TDOR` and `TORY`, then writes the frame for the tag's version, so the other version's frame cannot come back. Writing back the date already read changes nothing. +- **MP4**: A version 1 `mvhd` or `mdhd` whose 64-bit duration is past `TimeSpan.MaxValue` no longer throws out of `Mp4File.Read` or `Mp4AudioPropertiesParser.Parse`; the duration reads as unknown (#181). +- ID3v2 UTF-16 text with a byte order mark on each string (ID3v2.3 Β§3.3, mutagen's default) reads without a U+FEFF at the start of every value after the first, in text frames, `TXXX`, and `TIPL`/`TMCL`/`IPLS`. One decoder reads all of them on every target framework. A text or `TXXX` frame read from a file renders with the BOMs and the trailing terminators it was read with, so an empty last value survives an unchanged save. A `TXXX` that `SetCustomField` writes in an ID3v2.3 tag has a BOM before each value; a frame built in code keeps one BOM, as before. +- Writing back the gain `R128TrackGainDb` or `R128AlbumGainDb` read keeps the stored text, so `-0512` is not rewritten as `-512`. `null` still clears it, text the getter cannot parse included. +- An ASF title, artist, copyright, comment, or rating write replaces the same-named Extended Content Description descriptor that ffmpeg writes beside the Content Description field, so other tools no longer show the old value. An empty Content Description field reads that descriptor. ## [0.6.0] - 2026-01-05 From d15c1f687ff0a9505f7e758897efa8bf4ecf9e19 Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Thu, 3 Dec 2026 17:55:45 -0700 Subject: [PATCH 3/7] docs: Update README and guides for 0.7.0 Every C# example in the README, the package README, QuickStart, the Cookbook, the migration guide and CORE-TYPES now compiles against the current API; about sixty did not. They called members that do not exist (MediaFile.Open, Mp3File.Pictures and TotalTracks, WavFile.AudioProperties, Mp4File.SetCoverArt, Id3v2Tag.GetChapters, AddFrame and GetPOPM, ValidationResult.Issues, Duration on WavPack, Monkey's Audio, Musepack, Ogg FLAC and ASF files), passed arguments in the wrong order (PictureFrame, FlacPicture) or a token where IFileSystem goes, or edited a detached new VorbisComment or Id3v2Tag that was never saved. Saves now use the path overloads, which copy the audio in 64 KB pieces, and simple edits go through the tag view that exists on tagless files. Claims corrected against the code: MP3 does not read APEv2; new BinaryData(byte[]) copies the array; Tag.Track is not renamed; AVI saves stream movi and no longer refuse a no-CSET list with Windows-1252 text; the build needs the .NET 10 SDK and builds Debug by default; the repository folder is TagLibSharp2. The README gains a support matrix for Matroska, MPEG-PS, AVI and Audible, the package README lists MPEG-PS and AVI, ARCHITECTURE describes the IFileSystem and path-save layer instead of a planned one, the new-format checklist names IMediaFile, the tag view and SkipPictures, and the docs index lists every guide. Links from docs/ to files outside it (examples, tools/README.md, CLAUDE.md, CONTRIBUTING.md, LICENSE) are absolute GitHub URLs, so they resolve on GitHub and on the documentation site, and CORE-TYPES is linked as "Core types" now that the site has a generated API reference. CONTRIBUTING's benchmarking section, which described a planned project under tests/, points at benchmarks/TagLibSharp2.Benchmarks and its real run commands. The docs follow the 0.7.0 fixes: an unknown or unrepresentable duration, bit rate or sample rate reads as 0 (CORE-TYPES); a save that cannot write the file whole fails rather than drop bytes (MIGRATION); a Matroska TITLE in a Tag with no target type is the title, not the album (#221), a chapter without a UID reads Uid 0 (#244), and a save past the 65,536 Tags or chapter entries a read models fails (#247); an ASF Broadcast Flag makes the duration 0 and AsfFileProperties.IsBroadcast reports it; ApeTag.Render keeps a read tag's header (#217). Review fixes: the album-art, bulk-update and builder samples compile and run as written (one cover file per picture, only files actually saved counted, builders disposed); the TagLib# comparisons follow the TagLib# 2.3.0 public API (it opens DSF, WavPack, Monkey's Audio and Musepack, and has no Speex, TrueAudio, tracker or DSDIFF support), and the mapping tables state the type changes (Year and ReplayGain are strings, the numbers nullable); the Matroska chapter limit is 65,536 elements inside Chapters, about 9,300 titled chapters; the DSDIFF channel information is the CHNL count; IndexOutOfRangeException and builder pooling are documented; the implementation guide's sibling lists match the code; QuickStart and the Cookbook state the namespaces they assume and are linked from both readmes; docs links are relative again. The FileOperations example prints the path save and cancellationToken, and the examples readme describes it. After the 0.7.0 fixes that followed: the WebP rule in CORE-TYPES (#234), `AsfFile.FileProperties` for the Broadcast Flag in the migration guide (#250), the WAV custom-field footnote for a file with both tags (#235), the AVI CSET rules, under which no value this library reads makes a save fail (#220), and Cookbook notes that a chapter keeps its sub-frames (#265) and that a UTF-8 frame is written as ISO-8859-1 or UTF-16 in an ID3v2.3 tag (#255). --- CONTRIBUTING.md | 23 ++- README.md | 59 +++++--- docs/ARCHITECTURE.md | 58 +++----- docs/BUILDING.md | 25 ++-- docs/CORE-TYPES.md | 71 +++++---- docs/Cookbook.md | 225 +++++++++++++++-------------- docs/IMPLEMENTATION-GUIDE.md | 7 +- docs/MIGRATION-FROM-TAGLIB.md | 176 ++++++++++------------ docs/NEW-FORMAT-CHECKLIST.md | 27 ++-- docs/QuickStart.md | 84 ++++++----- docs/README.md | 7 +- examples/FileOperations/Program.cs | 10 +- examples/README.md | 25 +++- src/TagLibSharp2/README.md | 10 +- 14 files changed, 438 insertions(+), 369 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2e973ffb..50c8209e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -5,7 +5,7 @@ Thank you for your interest in contributing to TagLibSharp2! This document provi ## Getting Started 1. Fork the repository -2. Clone your fork: `git clone https://github.com/YOUR_USERNAME/tagsharp.git` +2. Clone your fork: `git clone https://github.com/YOUR_USERNAME/TagLibSharp2.git` 3. Create a branch: `git checkout -b feature/your-feature-name` 4. Make your changes 5. Run tests: `dotnet test` @@ -16,7 +16,7 @@ Thank you for your interest in contributing to TagLibSharp2! This document provi ### Prerequisites -- .NET 8.0 SDK or later +- .NET 10 SDK or later (it builds every target framework) - Your preferred IDE (VS Code, Visual Studio, Rider) ### Build & Test @@ -109,7 +109,7 @@ We use MSTest. Tests should be: [TestMethod] public void AddUInt32BE_WritesCorrectBytes () { - var builder = new BinaryDataBuilder (); + using var builder = new BinaryDataBuilder (); builder.AddUInt32BE (0x12345678); @@ -158,24 +158,19 @@ Benchmark when modifying: ### Performance Guidelines 1. **Avoid allocations in hot paths** - Use `Span` and `stackalloc` -2. **Use `[AggressiveInlining]`** - For small, frequently-called methods (all `Add*` methods use this) +2. **Use `[AggressiveInlining]`** - For small, frequently-called methods (the fixed-width integer `Add*` methods use this) 3. **Pre-size builders** - When final size is known 4. **Prefer `.Span` over `.Slice()`** - Span is zero-copy; Slice allocates -### Benchmarking (Future) +### Benchmarking -For significant performance changes, benchmarks will be added to `tests/TagLibSharp2.Benchmarks/`: +`benchmarks/TagLibSharp2.Benchmarks` uses BenchmarkDotNet. `MediaFileReadBenchmark` measures one `MediaFile.Read` of an MP3, a WAV and a FLAC file with a 1 MiB payload; the number to watch is Allocated, which should stay far under the payload. Run it with: -```csharp -[MemoryDiagnoser] -public class BinaryDataBenchmarks -{ - [Benchmark] - public void ParseHeader_1KB () { ... } -} +```bash +dotnet run -c Release --project benchmarks/TagLibSharp2.Benchmarks -f net10.0 -- --filter '*' ``` -Run with: `dotnet run -c Release --project tests/TagLibSharp2.Benchmarks` +`-- --list flat` lists the benchmarks. `-- --scan [rounds]` reads the three sample files repeatedly and prints the time; `-- --scan --retain` keeps every result and prints `READY` so a memory profiler can attach. For a significant performance change, add a benchmark beside the existing one. ## Architecture diff --git a/README.md b/README.md index 4af2b92b..fae745e5 100644 --- a/README.md +++ b/README.md @@ -25,10 +25,10 @@ See the [Migration Guide](docs/MIGRATION-FROM-TAGLIB.md) for detailed comparison - **Multi-Target**: Supports .NET Standard 2.0/2.1, .NET 8.0, and .NET 10.0 - **Format Support**: - Audio: MP3 (ID3v1, ID3v1.1, ID3v2.2 read and saved as ID3v2.3, ID3v2.3, ID3v2.4), FLAC, Ogg Vorbis, Ogg Opus, Ogg FLAC, WAV (RIFF INFO/ID3v2), AIFF (ID3v2), MP4/M4A (AAC/ALAC, including a video track's coded width and height, codec, and rotation), raw AAC (ADTS/ADIF, ID3v2/APEv2/ID3v1), ASF/WMA, DSF (DSD), DFF (DSDIFF), WavPack, Monkey's Audio (.ape), Musepack. A tagless MP3, raw AAC, DSF, DFF, WAV, AIFF, FLAC, WavPack, Monkey's Audio, Musepack, or MP4 file still has a tag view (`IMediaFile.Tag`): reading it does not write a tag, the first assignment creates the format's tag (ID3v2 in MP3, AAC, DSF, DFF, WAV and AIFF; a Vorbis comment in FLAC; APEv2; an MP4 `ilst`), and an assignment that leaves that tag empty removes it again, so a save then writes no empty tag - - Matroska/WebM (`.mkv`, `.mka`, `.mks`, `.mk3d`, `.webm`): tags (including `SORT_WITH` sort names for title, artist, album, album artist, and composer), chapters (editions and nested chapter atoms), duration, audio and video properties, tracks, and pictures. The album is read from `TITLE` at target type 50, else from the `ALBUM` tag ffmpeg writes. Setting the album never changes the title this library reads, and never makes ffprobe or MediaInfo show the album as the title. A file with a `TITLE` at target 50 has it updated, with any `ALBUM` beside it; when the track has no title of its own, the title it showed is first kept as `TITLE` at target 30. Any other file gets an `ALBUM` tag at target 50, which ffprobe, MediaInfo and ExifTool report as the album, and no `TITLE`. On a file ffmpeg wrote, album artists that would otherwise replace the track's artist are written as `ALBUM_ARTIST`. Tag values, chapters, pictures, and each track's enabled flag can be saved. A disabled track is not picked as the main audio or video track. Pictures are image attachments: a new front cover is written as `cover.jpg` or `cover.png` (another image type keeps its own extension, such as `cover.gif`), and fonts and other attachments are kept. WebM has no attachments, so a save that would add a picture to a WebM file fails. + - Matroska/WebM (`.mkv`, `.mka`, `.mks`, `.mk3d`, `.webm`): tags (including `SORT_WITH` sort names for title, artist, album, album artist, and composer), chapters (editions and nested chapter atoms), duration, audio and video properties, tracks, and pictures. The album is read from a `TITLE` whose target type is set to 50, else from the `ALBUM` tag ffmpeg writes; a `TITLE` in a Tag with no target type is the title, as ffprobe, exiftool and MediaInfo show it, not the album. Setting the album never changes the title this library reads, and never makes ffprobe or MediaInfo show the album as the title. A file with a `TITLE` at target 50 has it updated, with any `ALBUM` beside it; when the track has no title of its own, the title it showed is first kept as `TITLE` at target 30. Any other file gets an `ALBUM` tag at target 50, which ffprobe, MediaInfo and ExifTool report as the album, and no `TITLE`. On a file ffmpeg wrote, album artists that would otherwise replace the track's artist are written as `ALBUM_ARTIST`. Tag values, chapters, pictures, and each track's enabled flag can be saved. A disabled track is not picked as the main audio or video track. Pictures are image attachments: a new front cover is written as `cover.jpg` or `cover.png` (another image type keeps its own extension, such as `cover.gif`), and fonts and other attachments are kept. WebM has no attachments, so a save that would add a picture to a WebM file fails. A read models at most 65,536 Tags and SimpleTags, and 65,536 elements inside `Chapters` (about 9,300 chapters with a title, since each chapter's UID, times and display are elements too), and keeps the rest as their bytes; a save that would write one past those limits fails and leaves the file as it was. - MPEG program streams (`.mpg`, `.mpeg`, `.mpe`, `.vob`) and MPEG video elementary streams (`.mpv`, `.m1v`, `.m2v`): duration, MPEG-1/MPEG-2 video properties, and the first audio stream (MPEG audio, AC-3, LPCM). ID3v2 in front of the stream, an ID3v2.4 tag appended after it (the layout TagLib# writes), and ID3v1 are read and written in place; the stream bytes are not changed. A tagless stream still has a tag view: reading it does not write a tag, the first assignment creates an ID3v2 tag, and an assignment that leaves that tag empty removes it again. - 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. - - AVI (`.avi`, including OpenDML): RIFF INFO and `ID32` (ID3v2) tags, duration, video size, frame rate and FourCC, and the first audio stream. Tags are saved without changing the `movi` sample data; every `idx1` and OpenDML index stays valid. INFO text follows the RIFF `CSET` chunk (ISO 8859-1 when there is none): 65001, 1252, 0 and 28591 are decoded, and with no `CSET` valid UTF-8 (what ffmpeg and TagLib# write) is read as UTF-8 and other text as Windows-1252. On save, a value you did not change keeps its exact bytes and the file keeps its `CSET`; changed values are written in the file's code page when they fit it (with no `CSET`, ASCII only), otherwise the list becomes UTF-8 with a `CSET` of code page 65001 before it, which ffprobe, TagLib# and exiftool read (mediainfo ignores `CSET`). When the list becomes UTF-8, untouched text in a declared code page that is decoded exactly (1252, 28591, 0) is rewritten as the same text in UTF-8; the save is refused, with an error naming the field and the reason, when an untouched value's code page is only a guess (no `CSET`), is not decoded here (Shift-JIS, cp1251, ...), or the value holds a byte its declared code page leaves undefined (0x81, 0x8D, 0x8F, 0x90, 0x9D in 1252; 0x80-0x9F under code page 0). The new `CSET` keeps the old one's country, language and dialect codes. The five undefined 1252 code points are written as UTF-8, never as 1252 bytes. A save loads the whole file into memory (about one file's worth when nothing moves, two when the data has to move), so AVI files of 2 GiB or more cannot be saved yet; reading has no such limit. + - AVI (`.avi`, including OpenDML): RIFF INFO and `ID32` (ID3v2) tags, duration, video size, frame rate and FourCC, and the first audio stream. Tags are saved without changing the `movi` sample data; every `idx1` and OpenDML index stays valid. INFO text follows the RIFF `CSET` chunk: code pages 65001, 1252, 0 and 28591 are decoded, and with no `CSET` valid UTF-8 (what ffmpeg and TagLib# write) is read as UTF-8 and other text as Windows-1252. On save, a value you did not change keeps its exact bytes and the file keeps its `CSET`; changed values are written in the file's code page when they fit it (with no `CSET`, ASCII only), otherwise the list becomes UTF-8 with a `CSET` of code page 65001 before it, which ffprobe, TagLib# and exiftool read (mediainfo ignores `CSET`). When the list becomes UTF-8, untouched text in a declared code page that is decoded exactly (1252, 28591, 0) is rewritten as the same text in UTF-8, and untouched text holding a byte its declared code page leaves undefined (0x81, 0x8D, 0x8F, 0x90, 0x9D in 1252; 0x80-0x9F under code page 0) as the UTF-8 of the text read. With no `CSET` and Windows-1252 text in the list, or a `CSET` of a code page not decoded here (Shift-JIS, cp1251, ...), the list is written field by field instead, as WAV INFO is: untouched values keep their bytes, changed values are written as Windows-1252 when that reads back as the value and otherwise as UTF-8, and such a `CSET` is dropped. No value this library reads makes a save fail (#220). The new `CSET` keeps the old one's country, language and dialect codes. The five undefined 1252 code points are written as UTF-8, never as 1252 bytes. A path save copies the `movi` data in 64 KB pieces. When the new tags do not fit the space before `movi`, the data moves, and a file that would grow past 2 GiB is refused. `Render` and a save from a span build the file in one buffer. - Still images: JPEG, PNG, GIF, BMP, PCX, Netpbm (`.pbm`, `.pgm`, `.ppm`, `.pnm`), TIFF, DNG, and SVG open through `MediaFile.Read` or `StillImageFile.ReadFromFile` with width and height. PNG text, the GIF comment, and the JPEG COM marker and title can be edited. A JPEG title is stored in XMP `dc:title`, in a new XMP segment when the file has none, and is read from there, or from IFD0 `XPTitle` (0x9C9B) when the XMP has none. A set or a clear also removes every `XPTitle`, through the same plain-structure Exif edit as any other copy, so ExifTool, Exiv2, macOS ImageIO and TagLib# show the new title (measured), and Windows reads `dc:title` when no `XPTitle` is there (System.Title photo metadata policy). A set writes one `x-default` title and drops the other languages. A title whose XMP would not fit in one 64 KB segment is refused. IPTC `ObjectName` and Exif `ImageDescription` are not changed: after a clear, ImageIO shows an IPTC `ObjectName` as the title, and Windows falls back to `UserComment` or `ImageDescription`. A PNG edit also updates the XMP and Exif copies of the field. GPS, IPTC, and other Exif values are not read. TIFF, DNG, BMP, PCX, Netpbm, and SVG have dimensions and no text tag. ## Format Support Matrix @@ -47,7 +47,7 @@ See the [Migration Guide](docs/MIGRATION-FROM-TAGLIB.md) for detailed comparison | **Custom fields** | βœ… | βœ… | βœ… | βœ… | βœ…Β² | βœ…ΒΉΒ² | βœ…ΒΉ | βœ…ΒΉΒ³ | βœ…βΉ | βœ…ΒΉ | βœ…ΒΉ | βœ…βΈ | βœ…βΈ | βœ…βΈ | βœ…ΒΉ | | **Performer roles** | βœ… | βœ… | βœ… | βœ… | βœ…Β² | βœ…ΒΉ | βœ…ΒΉ | β€” | βœ…βΉ | βœ…ΒΉ | βœ…ΒΉ | βœ…βΈ | βœ…βΈ | βœ…βΈ | βœ…ΒΉ | | **BWF broadcast metadata** | β€” | β€” | β€” | β€” | β€” | βœ… | β€” | β€” | β€” | β€” | β€” | β€” | β€” | β€” | β€” | -| **Surround sound info** | β€” | β€” | β€” | β€” | β€” | βœ…Β³ | β€” | βœ…βΆ | β€” | βœ…β· | βœ…β· | β€” | β€” | β€” | β€” | +| **Surround sound info** | β€” | β€” | β€” | β€” | β€” | βœ…Β³ | β€” | βœ…βΆ | β€” | βœ…β· | βœ…ΒΉβ· | β€” | β€” | β€” | β€” | | **DSD sample rates** | β€” | β€” | β€” | β€” | β€” | β€” | β€” | β€” | β€” | βœ… | βœ… | β€” | β€” | β€” | β€” | ΒΉ Via embedded ID3v2 tag @@ -56,19 +56,38 @@ See the [Migration Guide](docs/MIGRATION-FROM-TAGLIB.md) for detailed comparison ⁴ Via R128 gain tags (RFC 7845) ⁡ Via iTunes ----:com.apple.iTunes:replaygain_* atoms ⁢ Via channel layout in stsd/esds -⁷ Via channel type in fmt chunk (Mono, Stereo, 5.1 surround) +⁷ Via the channel type in the DSF fmt chunk (`DsfChannelType`). The enum misnames values 5 and 6 and has no name for 7 (5.1); see #260 ⁸ Via APE tag ⁹ Via ASF Extended Content Description ¹⁰ From the ADTS frame headers or the ADIF header. HE-AAC reports the AAC core sample rate. ΒΉΒΉ Nero `chpl` box and QuickTime chapter track, read and write (`Mp4File.Chapters`) -ΒΉΒ² Via ID3v2 `TXXX`, or a four-character RIFF INFO chunk when the file has no ID3v2 tag +ΒΉΒ² Via ID3v2 `TXXX`, and a RIFF INFO chunk for a four-character name. A file with both tags gets such a field in both (INFO holds one value); a file with only INFO stores only four-character names ΒΉΒ³ Via ----:com.apple.iTunes freeform atoms +| Feature | Matroska/WebM | MPEG-PS | AVI | Audible .aa | +|---------|:-------------:|:-------:|:---:|:-----------:| +| **Read metadata** | βœ… | βœ… | βœ… | βœ… | +| **Write metadata** | βœ… | βœ…ΒΉ | βœ… | βœ… | +| **Audio properties** | βœ… | βœ… | βœ… | βœ… | +| **Video properties** | βœ… | βœ… | βœ… | β€” | +| **Async I/O** | βœ… | βœ… | βœ… | βœ… | +| **Album art** | βœ… | βœ…ΒΉ | βœ…ΒΉβ΄ | Read | +| **ReplayGain** | βœ… | βœ…ΒΉ | βœ…ΒΉβ΄ | β€” | +| **MusicBrainz IDs** | βœ… | βœ…ΒΉ | βœ…ΒΉβ΄ | β€” | +| **Lyrics** | βœ… | βœ…ΒΉ | βœ…ΒΉβ΄ | β€” | +| **Chapters** | βœ… | β€” | β€” | β€” | +| **Custom fields** | βœ… | βœ…ΒΉ | βœ…ΒΉβ΅ | —¹⁢ | + +¹⁴ Via the ID3v2 tag in an `ID32` chunk; RIFF INFO has no field for it +¹⁡ Via a four-character RIFF INFO chunk, and `TXXX` when the file has an `ID32` chunk +¹⁢ `AudibleTag.GetValue` and `SetValue` read and write any dictionary key +¹⁷ The channel count from the DSDIFF `CHNL` chunk; its channel IDs (the speaker layout) are not read + ### Tag Format by Container | Container | Native Tag | Alternative Tags | Priority | |-----------|------------|------------------|----------| -| MP3 | ID3v2 | ID3v1, APE | ID3v2 preferred | +| MP3 | ID3v2 | ID3v1 | ID3v2 preferred. An APEv2 tag is not read | | FLAC | Vorbis Comment | β€” | Native only | | Ogg Vorbis | Vorbis Comment | β€” | Native only | | Ogg Opus | Vorbis Comment | β€” | Native only | @@ -98,7 +117,7 @@ Or build from source: ```bash git clone https://github.com/decriptor/TagLibSharp2.git -cd tagsharp +cd TagLibSharp2 dotnet build ``` @@ -106,6 +125,7 @@ dotnet build ```csharp using TagLibSharp2.Core; +using TagLibSharp2.Id3.Id3v2; using TagLibSharp2.Mpeg; using TagLibSharp2.Xiph; using TagLibSharp2.Ogg; @@ -128,9 +148,9 @@ if (mp3Result.IsSuccess) var mp3 = mp3Result.File!; Console.WriteLine($"{mp3.Title} by {mp3.Artist}"); - // Modify and save + // Modify and save back to song.mp3. A path save copies the audio in 64 KB pieces. mp3.Title = "New Title"; - mp3.SaveToFile("song.mp3", File.ReadAllBytes("song.mp3")); + mp3.SaveToFile(); } // MP4/M4A files with iTunes metadata @@ -139,7 +159,7 @@ if (mp4Result.IsSuccess) { var mp4 = mp4Result.File!; Console.WriteLine($"{mp4.Title} - {mp4.Duration}"); - Console.WriteLine($"Codec: {mp4.AudioCodec}, {mp4.Properties?.SampleRate}Hz"); + Console.WriteLine($"Codec: {mp4.AudioCodec}, {mp4.Properties.SampleRate}Hz"); } // FLAC and Ogg Vorbis work the same way @@ -149,15 +169,15 @@ var ogg = OggVorbisFile.ReadFromFile("song.ogg").File; // Ogg Opus (RFC 7845) with R128 gain var opusResult = OggOpusFile.ReadFromFile("song.opus"); var opus = opusResult.File; -Console.WriteLine($"Opus: {opus?.Properties?.Duration}, R128 gain: {opus?.Properties?.OutputGain}dB"); +Console.WriteLine($"Opus: {opus?.Properties.Duration}, output gain: {opus?.OutputGainDb} dB"); // WAV files support both RIFF INFO and ID3v2 tags -WavFile.TryRead(new BinaryData(File.ReadAllBytes("song.wav")), out var wav); -Console.WriteLine($"WAV: {wav.Title} - {wav.AudioProperties?.Duration}"); +var wav = WavFile.ReadFromFile("song.wav").File!; +Console.WriteLine($"WAV: {wav.Title} - {wav.Properties.Duration}"); // AIFF files (read and write, includes audio properties) -AiffFile.TryRead(new BinaryData(File.ReadAllBytes("song.aiff")), out var aiff); -Console.WriteLine($"AIFF: {aiff.AudioProperties?.SampleRate}Hz"); +var aiff = AiffFile.ReadFromFile("song.aiff").File!; +Console.WriteLine($"AIFF: {aiff.Properties?.SampleRate}Hz"); aiff.Id3v2Tag = new Id3v2Tag { Title = "Updated Title" }; aiff.SaveToFile("song.aiff"); @@ -166,6 +186,9 @@ var tagged = MediaFile.Read("song.flac").Tag!; tagged.SetCustomField("MY_APP_DATA", "first", "second"); IReadOnlyList custom = tagged.GetCustomField("MY_APP_DATA"); +// Skip embedded pictures when scanning a library (a file read this way cannot be saved) +var scan = MediaFile.Read("song.flac", new MediaReadOptions { SkipPictures = true }); + // Async support for high-throughput scenarios var asyncResult = await Mp4File.ReadFromFileAsync("song.m4a"); ``` @@ -176,7 +199,7 @@ See the [examples](examples/) directory for more comprehensive usage patterns. ```bash git clone https://github.com/decriptor/TagLibSharp2.git -cd tagsharp +cd TagLibSharp2 dotnet build dotnet test ``` @@ -334,9 +357,11 @@ Planned work is tracked in [GitHub issues](https://github.com/decriptor/TagLibSh ## Documentation +- [Quick Start Guide](docs/QuickStart.md) - Read and write tags in a few lines +- [Cookbook](docs/Cookbook.md) - Recipes for common tasks, by format - [Migration Guide](docs/MIGRATION-FROM-TAGLIB.md) - Migrating from TagLib# - [Architecture Overview](docs/ARCHITECTURE.md) - Design principles and allocation behavior -- [Core Types Reference](docs/CORE-TYPES.md) - Complete API documentation +- [Core Types](docs/CORE-TYPES.md) - `BinaryData`, pictures, properties and `IMediaFile` - [Building Guide](docs/BUILDING.md) - Build instructions and requirements - [Examples](examples/) - Working code samples diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 3ec42750..63b4f475 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -12,7 +12,7 @@ TagLibSharp2 is a clean-room MIT-licensed library for reading and writing metada ## Project Structure ``` -tagsharp/ +TagLibSharp2/ β”œβ”€β”€ src/ β”‚ └── TagLibSharp2/ β”‚ β”œβ”€β”€ Core/ # Foundation types @@ -37,6 +37,8 @@ tagsharp/ β”‚ β”‚ β”œβ”€β”€ OggVorbisFile.cs # Ogg Vorbis files β”‚ β”‚ β”œβ”€β”€ OggPage.cs # Ogg page parsing β”‚ β”‚ └── OggCrc.cs # CRC computation +β”‚ β”œβ”€β”€ Aac/, Ape/, Asf/, Audible/, Dff/, Dsf/, Image/, +β”‚ β”‚ Matroska/, Mp4/, Mpeg/, Musepack/, WavPack/ # Other formats, one folder each β”‚ β”œβ”€β”€ Aiff/ # AIFF container support β”‚ β”‚ β”œβ”€β”€ AiffFile.cs # AIFF/AIFC container parser β”‚ β”‚ β”œβ”€β”€ AiffChunk.cs # AIFF chunk (FourCC + data, big-endian) @@ -93,7 +95,7 @@ The Core layer provides binary data handling primitives used by all format imple - **Growth Strategy**: Doubles capacity (min 256 bytes), grows to exact size if larger, clamps to max array length - **Overflow Protection**: `CheckedAdd()` prevents integer overflow - **Format-Specific**: `AddSyncSafeUInt32`, `AddUInt24BE/LE` for tag formats -- **Aggressive Inlining**: All `Add*` methods are marked `[AggressiveInlining]` +- **Aggressive Inlining**: The fixed-width integer `Add*` methods are marked `[AggressiveInlining]` ``` β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” @@ -116,8 +118,9 @@ The Core layer provides binary data handling primitives used by all format imple The Builder pattern separates construction from use: ```csharp -// Construction (mutable) -var header = new BinaryDataBuilder() +// Construction (mutable; dispose the builder, which may hold a pooled buffer) +using var builder = new BinaryDataBuilder(); +var header = builder .Add(0x49, 0x44, 0x33) // "ID3" .Add(0x04, 0x00) // Version 2.4.0 .Add(0x00) // Flags @@ -135,7 +138,7 @@ Understanding when allocations occur is critical for performance: | Operation | Allocates? | Notes | |-----------|-----------|-------| -| `new BinaryData(byte[])` | No | Wraps existing array | +| `new BinaryData(byte[])` | **Yes** | Copies the array | | `new BinaryData(ReadOnlySpan)` | **Yes** | Copies to new array | | `data.Span` | No | Zero-copy view | | `data.Slice(...)` | **Yes** | Creates new BinaryData with copied data | @@ -146,7 +149,7 @@ Understanding when allocations occur is critical for performance: ### Zero-Allocation Parsing Pattern ```csharp -// Read from file - one allocation +// Read from file - the constructor copies the array var data = new BinaryData(fileBytes); // Parse using Span (zero allocations) @@ -156,8 +159,7 @@ var version = span[3]; var size = data.ToSyncSafeUInt32(6); // Only allocate when storing results -if (needsSubset) - var subset = data.Slice(offset, length); // Allocates only here +BinaryData subset = needsSubset ? data.Slice(offset, length) : data; // Slice allocates only here ``` ## Target Frameworks @@ -190,10 +192,10 @@ The abstract `Tag` base class provides common metadata properties: β”‚ + Title: string? β”‚ β”‚ + Artist: string? β”‚ β”‚ + Album: string? β”‚ -β”‚ + Year: uint? β”‚ +β”‚ + Year: string? β”‚ β”‚ + Track: uint? β”‚ β”‚ + Genre: string? β”‚ -β”‚ + Pictures: IReadOnlyList β”‚ +β”‚ + Pictures: IPicture[] β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β–² β”‚ @@ -202,6 +204,8 @@ The abstract `Tag` base class provides common metadata properties: Id3v1Tag Id3v2Tag VorbisComment RiffInfoTag ``` +Other tags derive from it too: `ApeTag`, `Mp4Tag`, `AsfTag`, `MatroskaTag` and `AudibleTag`. `CombinedTag`, `FlacTag` and the tag `AiffFile.Tag` returns are views that read from and write to the tags a file holds. On a tagless audio file the view is empty, and its first write creates the format's tag. + ### ID3 Implementation ``` @@ -216,7 +220,7 @@ Id3v1Tag (128 bytes, end of file) Id3v2Tag (variable size, start of file) β”œβ”€β”€ Id3v2Header -β”‚ β”œβ”€β”€ Version (2.3 or 2.4) +β”‚ β”œβ”€β”€ Version (2.2 read and saved as 2.3, 2.3, or 2.4) β”‚ β”œβ”€β”€ Flags β”‚ └── Size (syncsafe) └── Frames[] @@ -312,46 +316,30 @@ AiffFile Note: AIFF uses big-endian byte order throughout (vs RIFF little-endian) ``` -## Future Architecture - -### File I/O Layer (Planned) +## File I/O Layer -File write operations and streaming support: +Every `ReadFromFile`, `ReadFromFileAsync` and `SaveToFile` overload takes an optional `IFileSystem`. `DefaultFileSystem` uses the real file system; tests pass their own implementation. -``` -β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” -β”‚ IFileAbstraction β”‚ -β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ -β”‚ + Name: string β”‚ -β”‚ + ReadStream: Stream β”‚ -β”‚ + WriteStream: Stream β”‚ -β”‚ + CloseStream(stream): void β”‚ -β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ - β–² - β”‚ -β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” -β”‚ β”‚ -LocalFile MemoryFile -``` +A save from a path (`SaveToFile()`, `SaveToFile(path)` and their async forms) copies the audio or image data from the source file in 64 KB pieces, writes a temporary file beside the destination, and moves it into place. A failed or cancelled save leaves the destination unchanged. `Render` and the overloads that take the original bytes build the whole file in one buffer. ## Performance Guidelines 1. **Use `.Span` for zero-allocation parsing** - Work with `ReadOnlySpan` directly; only create `BinaryData` when storing results 2. **Pre-size builders when length is known** - `new BinaryDataBuilder(expectedSize)` avoids growth allocations -3. **Inline hot paths** - `BinaryDataBuilder` applies `[AggressiveInlining]` to all `Add*` methods +3. **Inline hot paths** - `BinaryDataBuilder` applies `[AggressiveInlining]` to the fixed-width integer `Add*` methods 4. **Avoid LINQ in loops** - Use explicit iteration for performance-critical code 5. **Prefer stackalloc for small buffers** - Up to ~256 bytes on stack 6. **Target netstandard2.1+ when possible** - Avoids string encoding allocations ## Error Handling +- **Result types** - Reading a file returns a `...ReadResult` (or `MediaFileResult`) and saving returns a `FileWriteResult`. A malformed file or a failed save is reported through `IsSuccess` and `Error`, not thrown - **ArgumentException family** - Invalid parameters (null, out of range) -- **InvalidOperationException** - Invalid state (capacity exceeded) -- **FormatException** - Malformed file data (future) -- No silent failures - errors are thrown, not swallowed +- **InvalidOperationException** - Invalid state (capacity exceeded, a render that has no source to copy from) +- No silent failures - an error is returned or thrown, not swallowed ## Thread Safety - `BinaryData` - Thread-safe (immutable, no mutable state) - `BinaryDataBuilder` - Not thread-safe (single-threaded construction expected) -- Future file types - Read operations thread-safe, writes require synchronization +- File types (`Mp3File`, `FlacFile`, ...) - Mutable and not synchronized; do not share one instance between threads while it is being edited or saved diff --git a/docs/BUILDING.md b/docs/BUILDING.md index cc59f02b..3f89d6f0 100644 --- a/docs/BUILDING.md +++ b/docs/BUILDING.md @@ -2,8 +2,8 @@ ## Prerequisites -- **.NET SDK 8.0** or later (includes support for all target frameworks) -- Optional: .NET 10 SDK for net10.0 target +- **.NET SDK 10.0** or later (builds every target framework, including net10.0) +- The .NET 8 runtime, to run the tests on net8.0 Verify your installation: @@ -15,7 +15,7 @@ dotnet --list-sdks ```bash git clone https://github.com/decriptor/TagLibSharp2.git -cd tagsharp +cd TagLibSharp2 dotnet build dotnet test ``` @@ -24,8 +24,8 @@ dotnet test | Command | Description | |---------|-------------| -| `dotnet build` | Build all projects (Release by default) | -| `dotnet build -c Debug` | Build in Debug configuration | +| `dotnet build` | Build all projects (Debug by default) | +| `dotnet build -c Release` | Build in Release configuration | | `dotnet test` | Run all tests on all target frameworks | | `dotnet pack` | Create NuGet package | | `dotnet clean` | Clean build outputs | @@ -160,18 +160,21 @@ dotnet format ## Project Structure ``` -tagsharp/ +TagLibSharp2/ β”œβ”€β”€ Directory.Build.props # Shared build settings β”œβ”€β”€ Directory.Packages.props # Central package management β”œβ”€β”€ TagLibSharp2.slnx # Solution file β”œβ”€β”€ src/ β”‚ └── TagLibSharp2/ β”‚ β”œβ”€β”€ TagLibSharp2.csproj # Library project -β”‚ └── Core/ # Source files -└── tests/ - └── TagLibSharp2.Tests/ - β”œβ”€β”€ TagLibSharp2.Tests.csproj - └── Core/ # Test files +β”‚ β”œβ”€β”€ Core/ # Shared types +β”‚ └── Mp4/, Xiph/, ... # One folder per format +β”œβ”€β”€ tests/ +β”‚ └── TagLibSharp2.Tests/ +β”‚ β”œβ”€β”€ TagLibSharp2.Tests.csproj +β”‚ └── Core/, Mp4/, ... # Tests mirror the source folders +β”œβ”€β”€ examples/ # Sample projects +└── tools/ # Comparison, fuzzing and mutation tools ``` ## Build Configuration diff --git a/docs/CORE-TYPES.md b/docs/CORE-TYPES.md index 6deeff26..ff7f2207 100644 --- a/docs/CORE-TYPES.md +++ b/docs/CORE-TYPES.md @@ -9,7 +9,7 @@ Immutable wrapper for binary data with parsing utilities. ### Creation ```csharp -// From byte array (wraps, no copy) +// From byte array (copies the array) var data = new BinaryData(new byte[] { 0x49, 0x44, 0x33 }); // From span (copies data) @@ -98,7 +98,6 @@ All methods support an optional `offset` parameter (default 0). | `ToInt64BE(offset)` | `long` | Big-endian 64-bit signed | | `ToInt64LE(offset)` | `long` | Little-endian 64-bit signed | | `ToUInt24BE(offset)` | `uint` | Big-endian 24-bit unsigned | -| `ToUInt24LE(offset)` | `uint` | Little-endian 24-bit unsigned | | `ToSyncSafeUInt32(offset)` | `uint` | ID3v2 syncsafe integer | ```csharp @@ -153,8 +152,8 @@ var combined = data1 + data2; // Operator overload ```csharp // To hex string -string hex = data.ToHexString(); // "0102030405" -string hex = data.ToHexStringUpper(); // "0102030405" +string hex = data.ToHexString(); // "0102030405"; bytes AB CD give "abcd" +string hex = data.ToHexStringUpper(); // "0102030405"; bytes AB CD give "ABCD" // From hex string var data = BinaryData.FromHexString("0102030405"); @@ -196,7 +195,8 @@ ushort crc16 = data.ComputeCrc16Ccitt(); | Exception | Condition | |-----------|-----------| | `ArgumentOutOfRangeException` | Negative length in constructor | -| `ArgumentOutOfRangeException` | Index/offset out of bounds | +| `IndexOutOfRangeException` | Indexer (`data[i]`) out of bounds | +| `ArgumentOutOfRangeException` | Offset or length out of bounds in `Slice` and the `To*` readers | | `ArgumentOutOfRangeException` | Syncsafe value > 0x0FFFFFFF | | `ArgumentOutOfRangeException` | 24-bit value > 0xFFFFFF | | `FormatException` | Invalid hex string | @@ -207,14 +207,16 @@ ushort crc16 = data.ComputeCrc16Ccitt(); Mutable builder for constructing `BinaryData` instances. +`BinaryDataBuilder` is `IDisposable`. A buffer of 1 KB or more is rented from `ArrayPool.Shared`, both at construction and when the builder grows, and `Dispose` (or `Reset`) returns it to the pool. Dispose a builder when you are done with it, with `using`. A disposed builder can still be used; it allocates a new buffer. + ### Creation ```csharp // Default capacity (256 bytes) -var builder = new BinaryDataBuilder(); +using var builder = new BinaryDataBuilder(); -// Custom initial capacity (recommended when size is known) -var builder = new BinaryDataBuilder(1024); +// Custom initial capacity (recommended when size is known). 1 KB or more is rented from ArrayPool. +using var pooled = new BinaryDataBuilder(1024); ``` ### Properties @@ -232,7 +234,8 @@ var builder = new BinaryDataBuilder(1024); All `Add*` methods return `this` for fluent chaining. ```csharp -var builder = new BinaryDataBuilder() +using var builder = new BinaryDataBuilder(); +builder .Add(0x49) // Single byte .Add(0x44, 0x33) // Multiple bytes (params) .Add(existingData.Span) // From span @@ -334,7 +337,7 @@ byte[] array = builder.ToArray(); | Operation | Allocates? | Notes | |-----------|-----------|-------| -| `new BinaryData(byte[])` | No | Wraps existing array | +| `new BinaryData(byte[])` | **Yes** | Copies the array | | `new BinaryData(ReadOnlySpan)` | **Yes** | Copies to new array | | `data.Span` | No | Zero-copy view | | `data.Slice(...)` | **Yes** | Creates new BinaryData with copied data | @@ -345,7 +348,7 @@ byte[] array = builder.ToArray(); ### Zero-Allocation Parsing Pattern ```csharp -// Read from file - one allocation +// Wrap the file bytes - the constructor copies the array once var data = new BinaryData(fileBytes); // Parse using Span (zero allocations) @@ -369,7 +372,8 @@ var tagData = data.Slice(10, (int)size); ```csharp public BinaryData CreateId3v2Header(uint tagSize) { - return new BinaryDataBuilder() + using var builder = new BinaryDataBuilder(); + return builder .Add(0x49, 0x44, 0x33) // "ID3" magic .Add(0x04, 0x00) // Version 2.4.0 .Add(0x00) // Flags @@ -384,7 +388,8 @@ public BinaryData CreateId3v2Header(uint tagSize) public BinaryData CreateVorbisComment(string vendor, string[] comments) { var vendorBytes = Encoding.UTF8.GetByteCount(vendor); - var builder = new BinaryDataBuilder() + using var builder = new BinaryDataBuilder(); + builder .AddUInt32LE((uint)vendorBytes) // Vendor string length .AddStringUtf8(vendor) .AddUInt32LE((uint)comments.Length); // Number of comments @@ -410,7 +415,8 @@ public BinaryData CreateStreamInfoBlock( uint minFrameSize, uint maxFrameSize) { - return new BinaryDataBuilder() + using var builder = new BinaryDataBuilder(); + return builder .AddUInt16BE(minBlockSize) .AddUInt16BE(maxBlockSize) .AddUInt24BE(minFrameSize) @@ -500,7 +506,7 @@ string mime = Picture.DetectMimeType(imageData); // "image/jpeg" string mime = Picture.DetectMimeType(data, "cover.unknown"); ``` -Supported formats: JPEG, PNG, GIF, BMP, WebP, TIFF. +Magic bytes identify JPEG, PNG, GIF, BMP and WebP (RIFF data whose form type at offset 8 is `WEBP`; WAV, AVI and other RIFF forms are not WebP). When they match none, the file extension is used: `.jpg`, `.jpeg`, `.png`, `.gif`, `.bmp`, `.webp`, `.tif` or `.tiff`. Anything else is `application/octet-stream`. --- @@ -542,9 +548,9 @@ Interface for audio/video stream properties. Implemented by `AudioProperties` st | Property | Type | Description | |----------|------|-------------| -| `Duration` | `TimeSpan` | Duration of the media | -| `Bitrate` | `int` | Bitrate in kbps (0 if unknown) | -| `SampleRate` | `int` | Sample rate in Hz (0 if unknown) | +| `Duration` | `TimeSpan` | Duration of the media (`TimeSpan.Zero` if unknown, including a duration a `TimeSpan` cannot hold) | +| `Bitrate` | `int` | Bitrate in kbps (0 if unknown or too large for an `int`) | +| `SampleRate` | `int` | Sample rate in Hz (0 if unknown or past `int.MaxValue`) | | `BitsPerSample` | `int` | Bit depth (0 for lossy formats) | | `Channels` | `int` | Number of audio channels | | `Codec` | `string?` | Codec name (e.g., "FLAC", "MP3") | @@ -553,8 +559,8 @@ Interface for audio/video stream properties. Implemented by `AudioProperties` st ```csharp // Access through IMediaFile interface -IMediaFile file = MediaFile.Open("song.flac"); -IMediaProperties? props = file.AudioProperties; +using var file = MediaFile.Read("song.flac").GetFileAs(); +IMediaProperties? props = file?.AudioProperties; if (props is not null) { @@ -587,9 +593,9 @@ public readonly record struct AudioProperties( | Property | Type | Description | |----------|------|-------------| -| `Duration` | `TimeSpan` | Audio duration | -| `Bitrate` | `int` | Bitrate in kbps | -| `SampleRate` | `int` | Sample rate in Hz | +| `Duration` | `TimeSpan` | Audio duration (`TimeSpan.Zero` if unknown) | +| `Bitrate` | `int` | Bitrate in kbps (0 if unknown or too large for an `int`) | +| `SampleRate` | `int` | Sample rate in Hz (0 if unknown or past `int.MaxValue`) | | `BitsPerSample` | `int` | Bit depth | | `Channels` | `int` | Channel count | | `Codec` | `string?` | Codec name | @@ -665,6 +671,7 @@ public readonly record struct VideoProperties( | `Bitrate` | `int` | Bitrate in kbps | | `FrameRate` | `double` | Frames per second | | `Codec` | `string?` | Codec name (e.g., "H.264", "VP9") | +| `Rotation` | `int` | Clockwise rotation in degrees (0-359) a player should apply; init-only, not in the constructor. Read from the MP4/QuickTime track matrix and Matroska `ProjectionPoseRoll`; 0 for other formats | | `IsValid` | `bool` | True if Width > 0 and Height > 0 | ### Static Members @@ -787,20 +794,23 @@ Interface for media file containers with tags and properties. | Property | Type | Description | |----------|------|-------------| -| `Tag` | `Tag?` | Primary metadata tag | +| `Tag` | `Tag?` | Primary metadata tag. On a tagless audio or video file this is an empty view, not null; the first value written creates the format's tag. Null after `Dispose`, and for still images with no text store | | `AudioProperties` | `IMediaProperties?` | Audio stream properties | | `VideoProperties` | `VideoProperties?` | Video stream properties | | `ImageProperties` | `ImageProperties?` | Image properties | | `MediaTypes` | `MediaTypes` | Types of media in the file | | `SourcePath` | `string?` | File path if read from disk | | `Format` | `MediaFormat` | Detected file format | +| `PicturesLoaded` | `bool` | False when the file was read with `MediaReadOptions.SkipPictures` (a still image returns true) | ### Usage ```csharp -using IMediaFile file = MediaFile.Open("song.flac"); +using var file = MediaFile.Read("song.flac").GetFileAs(); +if (file is null) + return; -// Access tag metadata +// Access tag metadata (an empty view when the file has no tag) if (file.Tag is not null) { Console.WriteLine($"Title: {file.Tag.Title}"); @@ -825,14 +835,21 @@ Console.WriteLine($"Format: {file.Format}"); |--------|:-----:|:-----:|:-----:| | FLAC | βœ“ | | | | MP3 | βœ“ | | | +| Raw AAC (ADTS/ADIF) | βœ“ | | | | Ogg Vorbis | βœ“ | | | | Ogg Opus | βœ“ | | | +| Ogg FLAC | βœ“ | | | | WAV | βœ“ | | | | AIFF | βœ“ | | | -| MP4/M4A | βœ“ | | | +| MP4/M4A (including Audible .aax) | βœ“ | βœ“ | | | ASF/WMA | βœ“ | | | | DSF (DSD) | βœ“ | | | | DFF (DSDIFF) | βœ“ | | | | Monkey's Audio | βœ“ | | | | WavPack | βœ“ | | | | Musepack | βœ“ | | | +| Audible .aa | βœ“ | | | +| Matroska/WebM | βœ“ | βœ“ | | +| MPEG program stream / video elementary stream | βœ“ | βœ“ | | +| AVI | βœ“ | βœ“ | | +| JPEG, PNG, GIF, BMP, PCX, Netpbm, TIFF, DNG, SVG | | | βœ“ | diff --git a/docs/Cookbook.md b/docs/Cookbook.md index 9666dd04..c7b6e0dd 100644 --- a/docs/Cookbook.md +++ b/docs/Cookbook.md @@ -2,6 +2,8 @@ Practical recipes for common audio tagging tasks. +The recipes are fragments. They assume `using TagLibSharp2.Core;` (`MediaFile`, `Tag`, `PictureType`, `BinaryData`, `BatchProcessor`) and the namespace of the format they use: `TagLibSharp2.Mpeg` (`Mp3File`), `TagLibSharp2.Id3.Id3v2` and `TagLibSharp2.Id3.Id3v2.Frames` (ID3v2 tags and frames), `TagLibSharp2.Xiph` (FLAC and Vorbis comments), `TagLibSharp2.Ogg` (Ogg Vorbis, Opus, Ogg FLAC), `TagLibSharp2.Mp4`, `TagLibSharp2.Dsf`, `TagLibSharp2.Ape` or `TagLibSharp2.Matroska`. Some continue from the recipe before them (`result`, `mp3`, `file`). + ## Table of Contents 1. [Reading Tags](#reading-tags) @@ -75,7 +77,7 @@ if (result.IsSuccess) Console.WriteLine($"ReplayGain: {vorbis?.ReplayGainTrackGain}"); // Access stream info - var streamInfo = flac.StreamInfo; + var streamInfo = flac.Properties; Console.WriteLine($"Sample Rate: {streamInfo.SampleRate} Hz"); Console.WriteLine($"Channels: {streamInfo.Channels}"); Console.WriteLine($"Bits: {streamInfo.BitsPerSample}"); @@ -103,8 +105,8 @@ var customField = id3v2.GetUserText("MY_APP_DATA"); // Vorbis Comment - Any field var vorbis = flac.VorbisComment!; -var acoustId = vorbis.GetValue("ACOUSTID_ID"); -var customField = vorbis.GetValue("MY_APP_DATA"); +var vorbisAcoustId = vorbis.GetValue("ACOUSTID_ID"); +var vorbisCustomField = vorbis.GetValue("MY_APP_DATA"); ``` --- @@ -124,41 +126,41 @@ if (result.IsSuccess) mp3.Album = "New Album"; mp3.Year = "2024"; mp3.Track = 1; - mp3.TotalTracks = 12; + mp3.Tag!.TotalTracks = 12; mp3.Genre = "Rock"; - var originalData = File.ReadAllBytes("song.mp3"); - mp3.SaveToFile("song.mp3", originalData); + mp3.SaveToFile(); // writes back to song.mp3, copying the audio in 64 KB pieces } ``` ### Write Extended Metadata ```csharp -var mp3 = result.File!; +// Writes go to every tag the file has; a tagless MP3 gets an ID3v2 tag +var tag = result.File!.Tag!; // Disc information -mp3.DiscNumber = 1; -mp3.TotalDiscs = 2; +tag.DiscNumber = 1; +tag.TotalDiscs = 2; // Credits -mp3.Composer = "Composer Name"; -mp3.Conductor = "Conductor Name"; -mp3.AlbumArtist = "Various Artists"; +tag.Composer = "Composer Name"; +tag.Conductor = "Conductor Name"; +tag.AlbumArtist = "Various Artists"; // Production -mp3.Copyright = "2024 Record Label"; -mp3.Publisher = "Record Label"; -mp3.Isrc = "USRC12345678"; -mp3.BeatsPerMinute = 120; +tag.Copyright = "2024 Record Label"; +tag.Publisher = "Record Label"; +tag.Isrc = "USRC12345678"; +tag.BeatsPerMinute = 120; // Classification -mp3.Grouping = "Holiday"; -mp3.Subtitle = "Radio Edit"; -mp3.InitialKey = "Am"; +tag.Grouping = "Holiday"; +tag.Subtitle = "Radio Edit"; +tag.InitialKey = "Am"; // Compilation flag -mp3.IsCompilation = true; +tag.IsCompilation = true; ``` ### Write MusicBrainz IDs @@ -205,7 +207,7 @@ tag.R128AlbumGain = "256"; // +1 dB Any tag, whatever the format. The field is stored where the format keeps named fields: a Vorbis comment, an APE item, an ID3v2 `TXXX` frame, an MP4 `----:com.apple.iTunes:` atom, an ASF attribute, a Matroska -`SimpleTag`, or a RIFF INFO chunk (four-character names only). `SetCustomField` returns false and changes +`SimpleTag`, or a RIFF INFO chunk (four-character names, one value). `SetCustomField` returns false and changes nothing when the format cannot store the name or the values; ID3v1 stores none. ```csharp @@ -237,9 +239,10 @@ vorbis.SetValue("CATALOG_ID", "ABC-12345"); ```csharp var result = Mp3File.ReadFromFile("song.mp3"); -if (result.IsSuccess && result.File!.Pictures.Length > 0) +if (result.IsSuccess && result.File!.Tag!.Pictures.Length > 0) { - foreach (var picture in result.File.Pictures) + var index = 0; + foreach (var picture in result.File.Tag.Pictures) { Console.WriteLine($"Type: {picture.PictureType}"); Console.WriteLine($"MIME: {picture.MimeType}"); @@ -251,7 +254,8 @@ if (result.IsSuccess && result.File!.Pictures.Length > 0) "image/png" => ".png", _ => ".bin" }; - File.WriteAllBytes($"cover{extension}", picture.PictureData.ToArray()); + // One file per picture, so a front and a back cover do not overwrite each other + File.WriteAllBytes($"cover-{index++}-{picture.PictureType}{extension}", picture.PictureData.ToArray()); } } ``` @@ -262,6 +266,7 @@ if (result.IsSuccess && result.File!.Pictures.Length > 0) using TagLibSharp2.Id3.Id3v2.Frames; var mp3 = result.File!; +var id3v2 = mp3.Id3v2Tag ??= new Id3v2Tag(); var imageBytes = File.ReadAllBytes("cover.jpg"); var picture = new PictureFrame( @@ -270,7 +275,7 @@ var picture = new PictureFrame( "Album Cover", imageBytes); -mp3.Id3v2Tag?.AddPicture(picture); +id3v2.AddPicture(picture); // Add back cover var backCover = new PictureFrame( @@ -278,7 +283,7 @@ var backCover = new PictureFrame( PictureType.BackCover, "Back Cover", File.ReadAllBytes("back.jpg")); -mp3.Id3v2Tag?.AddPicture(backCover); +id3v2.AddPicture(backCover); ``` ### Add Album Art to FLAC @@ -291,16 +296,16 @@ var imageBytes = File.ReadAllBytes("cover.jpg"); // Get image dimensions (simplified - use actual image library) var picture = new FlacPicture( - PictureType.FrontCover, "image/jpeg", + PictureType.FrontCover, "Album Cover", + new BinaryData(imageBytes), width: 500, height: 500, colorDepth: 24, - colorCount: 0, - new BinaryData(imageBytes)); + colorCount: 0); -flac.VorbisComment?.AddPicture(picture); +flac.AddPicture(picture); // a FLAC PICTURE metadata block ``` ### Remove Album Art @@ -338,16 +343,16 @@ if (result.IsSuccess) // Audio properties Console.WriteLine($"Duration: {mp4.Duration}"); - Console.WriteLine($"Codec: {mp4.AudioCodec}"); // Aac, Alac, or Unknown - Console.WriteLine($"Sample Rate: {mp4.Properties?.SampleRate} Hz"); - Console.WriteLine($"Bitrate: {mp4.Properties?.Bitrate} kbps"); - Console.WriteLine($"Channels: {mp4.Properties?.Channels}"); + Console.WriteLine($"Codec: {mp4.AudioCodec}"); // Aac, Alac, Mp3, Opus, Flac, Ac3, Eac3, or Unknown + Console.WriteLine($"Sample Rate: {mp4.Properties.SampleRate} Hz"); + Console.WriteLine($"Bitrate: {mp4.Properties.Bitrate} kbps"); + Console.WriteLine($"Channels: {mp4.Properties.Channels}"); // Album art - if (mp4.CoverArt is { } cover) + if (mp4.Pictures is [var cover, ..]) { - Console.WriteLine($"Cover: {cover.MimeType}, {cover.Data.Length} bytes"); - File.WriteAllBytes("cover.jpg", cover.Data.ToArray()); + Console.WriteLine($"Cover: {cover.MimeType}, {cover.PictureData.Length} bytes"); + File.WriteAllBytes("cover.jpg", cover.PictureData.ToArray()); } } ``` @@ -366,7 +371,7 @@ if (result.IsSuccess) mp4.Title = "My Song"; mp4.Artist = "My Artist"; mp4.Album = "My Album"; - mp4.Year = 2024; + mp4.Year = "2024"; mp4.Track = 1; mp4.TotalTracks = 12; mp4.DiscNumber = 1; @@ -376,16 +381,17 @@ if (result.IsSuccess) // Extended metadata mp4.Composer = "Composer Name"; mp4.AlbumArtist = "Album Artist"; - mp4.Grouping = "Holiday"; - mp4.Description = "Song description"; - mp4.Copyright = "2024 Record Label"; + var tag = mp4.Tag!; // the ilst tag, created by the setters above when the file had none + tag.Grouping = "Holiday"; + tag.Description = "Song description"; + tag.Copyright = "2024 Record Label"; // Compilation flag - mp4.IsCompilation = true; + tag.IsCompilation = true; // MusicBrainz IDs - mp4.MusicBrainzTrackId = "f4e7c9d8-1234-5678-9abc-def012345678"; - mp4.MusicBrainzReleaseId = "a1b2c3d4-5678-90ab-cdef-1234567890ab"; + tag.MusicBrainzTrackId = "f4e7c9d8-1234-5678-9abc-def012345678"; + tag.MusicBrainzReleaseId = "a1b2c3d4-5678-90ab-cdef-1234567890ab"; // Save (uses SourcePath) mp4.SaveToFile(); @@ -398,6 +404,7 @@ if (result.IsSuccess) ### Add Album Art to MP4 ```csharp +using TagLibSharp2.Core; using TagLibSharp2.Mp4; var result = Mp4File.ReadFromFile("song.m4a"); @@ -405,9 +412,9 @@ if (result.IsSuccess) { var mp4 = result.File!; - // Add cover art (auto-detects JPEG vs PNG) + // Add cover art (the covr data type is taken from the image bytes: JPEG, PNG, GIF or BMP) var imageBytes = File.ReadAllBytes("cover.jpg"); - mp4.SetCoverArt(new BinaryData(imageBytes)); + mp4.AddPicture(new Mp4Picture("image/jpeg", PictureType.FrontCover, "", new BinaryData(imageBytes))); mp4.SaveToFile(); } @@ -448,19 +455,15 @@ if (result.IsSuccess) // Audio properties var props = opus.Properties; - Console.WriteLine($"Duration: {props?.Duration}"); - Console.WriteLine($"Sample Rate: {props?.SampleRate} Hz"); - Console.WriteLine($"Channels: {props?.Channels}"); - - // R128 gain (per RFC 7845) - Console.WriteLine($"Output Gain: {props?.OutputGain} dB"); - Console.WriteLine($"R128 Track Gain: {props?.R128TrackGain}"); - Console.WriteLine($"R128 Album Gain: {props?.R128AlbumGain}"); - - // Multi-stream info - Console.WriteLine($"Mapping Family: {props?.MappingFamily}"); - Console.WriteLine($"Stream Count: {props?.StreamCount}"); - Console.WriteLine($"Coupled Count: {props?.CoupledCount}"); + Console.WriteLine($"Duration: {props.Duration}"); + Console.WriteLine($"Sample Rate: {props.SampleRate} Hz"); // always 48000 (Opus output rate) + Console.WriteLine($"Channels: {props.Channels}"); + Console.WriteLine($"Input Sample Rate: {opus.InputSampleRate} Hz"); + + // Gain (per RFC 7845): header output gain, then the R128 tags + Console.WriteLine($"Output Gain: {opus.OutputGainDb} dB"); // OutputGain is the raw Q7.8 value + Console.WriteLine($"R128 Track Gain: {opus.VorbisComment?.R128TrackGain}"); + Console.WriteLine($"R128 Album Gain: {opus.VorbisComment?.R128AlbumGain}"); } ``` @@ -473,7 +476,7 @@ var result = OggOpusFile.ReadFromFile("song.opus"); if (result.IsSuccess) { var opus = result.File!; - var vorbis = opus.VorbisComment ?? new VorbisComment(); + var vorbis = opus.VorbisComment!; // read from the OpusTags header every Opus stream has vorbis.Title = "My Song"; vorbis.Artist = "My Artist"; @@ -482,8 +485,7 @@ if (result.IsSuccess) vorbis.SetValue("R128_TRACK_GAIN", "-512"); // -2 dB in Q7.8 vorbis.SetValue("R128_ALBUM_GAIN", "256"); // +1 dB in Q7.8 - var data = File.ReadAllBytes("song.opus"); - opus.SaveToFile("song.opus", data); + opus.SaveToFile(); } ``` @@ -511,7 +513,7 @@ if (result.IsSuccess) Console.WriteLine($"Sample Rate: {props?.SampleRate} Hz"); Console.WriteLine($"DSD Format: {GetDsdFormat(props?.SampleRate)}"); Console.WriteLine($"Channels: {props?.Channels}"); - Console.WriteLine($"Channel Type: {props?.ChannelType}"); // Mono, Stereo, Surround + Console.WriteLine($"Channel Type: {props?.ChannelType}"); // values 5 and 6 are misnamed (#260); trust Channels for the count Console.WriteLine($"Duration: {props?.Duration}"); Console.WriteLine($"Bits Per Sample: {props?.BitsPerSample}"); } @@ -557,8 +559,8 @@ if (result.IsSuccess) { var dsf = result.File!; - // Modify ID3v2 tag (creates one if not present) - var tag = dsf.Id3v2Tag ?? new Id3v2Tag(); + // Modify the tag (the first write creates an ID3v2 tag if the file has none) + var tag = dsf.Tag!; tag.Title = "My DSD Song"; tag.Artist = "My Artist"; tag.Album = "My Album"; @@ -585,7 +587,7 @@ if (result.IsSuccess) Console.WriteLine($"Duration: {dsf.Properties?.Duration}"); // Async write - dsf.Id3v2Tag!.Title = "Updated Title"; + dsf.Tag!.Title = "Updated Title"; await dsf.SaveToFileAsync(); } ``` @@ -672,6 +674,9 @@ ape.SetValue("ENCODER", "My Encoder v1.0"); // Render to binary (with optional header) var tagData = ape.RenderWithOptions(includeHeader: true); + +// Render() writes a tag read from a file with the header it was read with, and a new tag footer-only. +// Saving a Monkey's Audio, WavPack or Musepack file keeps the layout of the tag it read. ``` ### APE Tag with Binary Data (Cover Art) @@ -710,7 +715,7 @@ ape.TotalDiscs = 2; // MusicBrainz identifiers ape.MusicBrainzTrackId = "12345678-1234-1234-1234-123456789012"; -ape.MusicBrainzReleaseId = "abcdefgh-abcd-abcd-abcd-abcdefghijkl"; +ape.MusicBrainzReleaseId = "a1b2c3d4-5678-90ab-cdef-1234567890ab"; ape.MusicBrainzArtistId = "11111111-2222-3333-4444-555555555555"; // Item count @@ -730,14 +735,12 @@ var results = await BatchProcessor.ProcessAsync( files, async (path, ct) => { - var result = await Mp3File.ReadFromFileAsync(path, ct: ct); - if (!result.IsSuccess) return null; + // SkipPictures reads the tags without loading embedded cover art + var options = new MediaReadOptions { SkipPictures = true }; + var result = await MediaFile.ReadAsync(path, options, cancellationToken: ct); + if (!result.IsSuccess) throw new InvalidDataException(result.Error); // reported as a failure - return new { - Path = path, - Title = result.File!.Title, - Artist = result.File.Artist - }; + return (Title: result.Tag?.Title, Artist: result.Tag?.Artist); }, maxDegreeOfParallelism: 4, progress: new Progress(p => @@ -760,19 +763,19 @@ var results = await BatchProcessor.ProcessAsync( files, async (path, ct) => { - var result = await Mp3File.ReadFromFileAsync(path, ct: ct); + var result = await Mp3File.ReadFromFileAsync(path, cancellationToken: ct); if (!result.IsSuccess) return false; var mp3 = result.File!; mp3.Album = "Corrected Album Name"; mp3.AlbumArtist = "Various Artists"; - var data = await File.ReadAllBytesAsync(path, ct); - await mp3.SaveToFileAsync(path, data, ct); - return true; + var save = await mp3.SaveToFileAsync(path, cancellationToken: ct); + return save.IsSuccess; }); -Console.WriteLine($"Updated {results.SuccessCount()} files"); +// SuccessCount() counts every file whose delegate did not throw, including the ones that returned false +Console.WriteLine($"Updated {results.Count(r => r.IsSuccess && r.Value)} files"); ``` ### Find Files Missing Metadata @@ -784,23 +787,23 @@ var missingData = await BatchProcessor.ProcessAsync( files, async (path, ct) => { - var result = await Mp3File.ReadFromFileAsync(path, ct: ct); - if (!result.IsSuccess) return null; + var result = await Mp3File.ReadFromFileAsync(path, cancellationToken: ct); + var issues = new List(); + if (!result.IsSuccess) { issues.Add(result.Error!); return issues; } var mp3 = result.File!; - var issues = new List(); if (string.IsNullOrEmpty(mp3.Title)) issues.Add("Missing title"); if (string.IsNullOrEmpty(mp3.Artist)) issues.Add("Missing artist"); - if (mp3.Pictures.Length == 0) issues.Add("Missing album art"); + if (mp3.Tag!.Pictures.Length == 0) issues.Add("Missing album art"); - return issues.Count > 0 ? new { Path = path, Issues = issues } : null; + return issues; }); -foreach (var item in missingData.WhereSucceeded().Where(r => r.Value is not null)) +foreach (var item in missingData.WhereSucceeded().Where(r => r.Value!.Count > 0)) { - Console.WriteLine($"{item.Value!.Path}:"); - foreach (var issue in item.Value.Issues) + Console.WriteLine($"{item.Path}:"); + foreach (var issue in item.Value!) Console.WriteLine($" - {issue}"); } ``` @@ -818,7 +821,7 @@ var flacResult = FlacFile.ReadFromFile("song.flac"); if (mp3Result.IsSuccess && flacResult.IsSuccess) { var sourceTag = mp3Result.File!.Id3v2Tag; - var targetTag = flacResult.File!.VorbisComment ?? new VorbisComment(); + var targetTag = flacResult.File!.Tag!; // the FLAC view: Vorbis comment and PICTURE blocks if (sourceTag is not null) { @@ -832,8 +835,7 @@ if (mp3Result.IsSuccess && flacResult.IsSuccess) TagCopyOptions.Pictures); } - var data = File.ReadAllBytes("song.flac"); - flacResult.File.SaveToFile("song.flac", data); + flacResult.File.SaveToFile(); } ``` @@ -884,7 +886,7 @@ if (!validation.IsValid) } // Safe to save -mp3.SaveToFile(path, originalData); +mp3.SaveToFile(); ``` ### Work with Chapters (Podcasts/Audiobooks) @@ -894,8 +896,8 @@ using TagLibSharp2.Id3.Id3v2.Frames; var tag = mp3.Id3v2Tag!; -// Read chapters -var chapters = tag.GetChapters(); +// Read chapters (CHAP frames) +var chapters = tag.ChapterFrames; foreach (var chapter in chapters) { Console.WriteLine($"Chapter: {chapter.ElementId}"); @@ -909,11 +911,13 @@ foreach (var chapter in chapters) var newChapter = new ChapterFrame( elementId: "chp01", startTimeMs: 0, - endTimeMs: 300000); // 5 minutes + endTimeMs: 300000) // 5 minutes +{ + Title = "Introduction" // stored as a TIT2 sub-frame +}; +tag.AddChapter(newChapter); -// Add title to chapter -newChapter.AddSubFrame(new TextFrame("TIT2", "Introduction")); -tag.AddFrame(newChapter); +// A save keeps every sub-frame a chapter was read with (subtitle, link, image, unknown frames), not only its title ``` MP4, M4A and M4B files (audiobooks) keep chapters in a QuickTime chapter track and a Nero `chpl` box. @@ -959,7 +963,9 @@ foreach (var edition in mkv.Chapters.Editions) foreach (var chapter in edition.Chapters) Console.WriteLine($"{chapter.Start} {chapter.Title} ({chapter.Displays.Count} displays)"); -// Add, edit, and remove. New chapters and editions get random nonzero UIDs. +// Add and edit (RemoveChapter on an edition or chapter, and RemoveEdition, remove). +// New chapters and editions get random nonzero UIDs. A chapter read without a ChapterUID reads Uid 0, +// and setting Uid to 0 means "no UID yet": a save that writes the chapter gives it one. var intro = mkv.Chapters.AddChapter(TimeSpan.Zero, TimeSpan.FromMinutes(2), "Introduction"); intro.AddChapter(TimeSpan.FromSeconds(30), TimeSpan.FromSeconds(60), "Opening titles"); mkv.Chapters.DefaultEdition!.Chapters[0].Title = "Cold open"; @@ -967,7 +973,8 @@ mkv.Chapters.DefaultEdition!.Chapters[0].Title = "Cold open"; // Chapter titles never become mkv.Tag.Title. A save that does not change the // chapters keeps the original Chapters bytes. A WebM save writes only the chapter elements WebM // supports, so hidden and disabled flags are dropped there. A chapter that ends before it starts, -// or a lowest-level chapter without an end in an ordered edition, fails the save (RFC 9559 section 20.2). +// or a lowest-level chapter without an end in an ordered edition, fails the save (RFC 9559 section 20.2), +// as does one past the 65,536 elements a read models inside Chapters (about 9,300 titled chapters). mkv.SaveToFile(); ``` @@ -991,7 +998,7 @@ if (syncLyrics is not null) // Add synchronized lyrics var newLyrics = new SyncLyricsFrame { - Encoding = TextEncodingType.Utf8, + Encoding = TextEncodingType.Utf8, // ID3v2.4; in an ID3v2.3 tag it is written as ISO-8859-1 or UTF-16 Language = "eng", ContentType = SyncLyricsType.Lyrics, Description = "Lyrics" @@ -999,7 +1006,7 @@ var newLyrics = new SyncLyricsFrame newLyrics.AddSyncItem("First line", 0); newLyrics.AddSyncItem("Second line", 3000); -tag.AddFrame(newLyrics); +tag.AddSyncLyrics(newLyrics); ``` ### Access Popularimeter (Ratings/Play Counts) @@ -1010,18 +1017,19 @@ using TagLibSharp2.Id3.Id3v2.Frames; var tag = mp3.Id3v2Tag!; // Read ratings -var popm = tag.GetPOPM("my-email@example.com"); +var popm = tag.GetPopularimeter("my-email@example.com"); if (popm is not null) { Console.WriteLine($"Rating: {popm.Rating}/255"); Console.WriteLine($"Play Count: {popm.PlayCount}"); } -// Simple rating access (uses any email) +// Simple rating access (the first POPM frame, whatever its email) Console.WriteLine($"Rating: {tag.Rating}"); -// Add/update rating +// Add/update rating (creates a POPM frame with a default email when there is none) tag.Rating = 200; // ~4 stars +tag.SetPopularimeter("my-email@example.com", rating: 255, playCount: 12); ``` ### Safe Async Pattern @@ -1031,7 +1039,7 @@ async Task ProcessFileAsync(string path, CancellationToken ct) { try { - var result = await Mp3File.ReadFromFileAsync(path, ct: ct); + var result = await Mp3File.ReadFromFileAsync(path, cancellationToken: ct); if (!result.IsSuccess) { Console.WriteLine($"Failed to read: {result.Error}"); @@ -1041,8 +1049,9 @@ async Task ProcessFileAsync(string path, CancellationToken ct) var mp3 = result.File!; mp3.Title = "Updated"; - var data = await File.ReadAllBytesAsync(path, ct); - await mp3.SaveToFileAsync(path, data, ct); + var save = await mp3.SaveToFileAsync(path, cancellationToken: ct); + if (!save.IsSuccess) + Console.WriteLine($"Failed to save: {save.Error}"); } catch (OperationCanceledException) { @@ -1075,7 +1084,7 @@ public class TagService } } -// Test code uses mock +// Test code passes a fake IFileSystem (MockFileSystem and CreateTestMp3 are your own test helpers) [TestMethod] public async Task GetTitle_ValidFile_ReturnsTitle() { diff --git a/docs/IMPLEMENTATION-GUIDE.md b/docs/IMPLEMENTATION-GUIDE.md index f3664b52..6c31b268 100644 --- a/docs/IMPLEMENTATION-GUIDE.md +++ b/docs/IMPLEMENTATION-GUIDE.md @@ -62,11 +62,12 @@ Every table must cover: - **Entry points.** Span, stream and path. Sync and async. `ReadFromFile`/`ReadFromFileAsync`. The windowed stream reader, which is a separate code path from the span reader. `MediaFile` detection, the extension - fallback in `DetectFormat`, and `SupportedExtensions` where a format has one. A detection change must not + fallback in `DetectFormat`, and the `OpenDetected` and `ReadFromData` dispatch. A detection change must not take another format's files. Run the whole suite and the grid over the corpus to check this. - **Sibling formats.** Every format that stores the same structure or field. ID3v2 lives in MP3, WAV, AIFF, - DSF, DFF and MPEG-PS. APEv2 lives in MP3, Monkey's Audio, WavPack and Musepack. Vorbis comments live in - FLAC, Ogg Vorbis, Opus and Ogg FLAC. EBML and ISO boxes nest the same way everywhere. + DSF, DFF, MPEG-PS, raw AAC and AVI. APEv2 lives in raw AAC, Monkey's Audio, WavPack and Musepack (MP3 does + not read it, and MPEG-PS keeps one unread). Vorbis comments live in FLAC, Ogg Vorbis, Opus and Ogg + FLAC. EBML and ISO boxes nest the same way everywhere. - **Every write path, each with its expected outcome** (rule 7 below): - A setter or `""` changes only that mapped field. Null clears that field. - `Clear()` and assigning null (`file.Id3v2Tag = null`, `file.Tag = null`) remove all tag metadata, diff --git a/docs/MIGRATION-FROM-TAGLIB.md b/docs/MIGRATION-FROM-TAGLIB.md index 19277c1c..01c8fdbc 100644 --- a/docs/MIGRATION-FROM-TAGLIB.md +++ b/docs/MIGRATION-FROM-TAGLIB.md @@ -29,6 +29,7 @@ file.Save(); ### TagLibSharp2 (After) ```csharp using TagLibSharp2.Core; +using TagLibSharp2.Mpeg; // Auto-detect format var result = MediaFile.Read("song.mp3"); @@ -44,7 +45,7 @@ if (mp3Result.IsSuccess) { var mp3 = mp3Result.File!; mp3.Title = "New Title"; - mp3.SaveToFile("song.mp3", File.ReadAllBytes("song.mp3")); + mp3.SaveToFile(); // back to song.mp3 } ``` @@ -89,10 +90,10 @@ string[] artists = file.Tag.Performers; // Array property var result = Mp3File.ReadFromFile("song.mp3"); var mp3 = result.File!; string? title = mp3.Title; // From ID3v2 or ID3v1 -string[] artists = mp3.Performers; // Array property +string[] artists = mp3.Tag!.Performers; // Array property ``` -### 3. File Operations: In-Place vs Explicit +### 3. File Operations: Saving **TagLib#** modifies files in-place: ```csharp @@ -101,61 +102,43 @@ file.Tag.Title = "New Title"; file.Save(); // Modifies original file ``` -**TagLibSharp2** requires explicit data handling: +**TagLibSharp2** saves explicitly and returns a result: ```csharp var result = Mp3File.ReadFromFile("song.mp3"); var mp3 = result.File!; mp3.Title = "New Title"; -// Read original bytes, render new data, save atomically -var originalData = File.ReadAllBytes("song.mp3"); -mp3.SaveToFile("song.mp3", originalData); +// Write back to the file it was read from +var saved = mp3.SaveToFile(); +if (!saved.IsSuccess) + Console.WriteLine(saved.Error); ``` -#### Why SaveToFile Requires Original Bytes - -This design is intentional and provides several benefits: - -1. **Memory efficiency**: Audio files can be gigabytes. TagLibSharp2 only parses metadata, not audio data. The audio content stays on disk until you're ready to write. - -2. **Explicit data flow**: You control when and how the original file is read. This enables: - - Reading from one location, writing to another - - Processing files from streams or memory buffers - - Avoiding double-reads when you already have the bytes - -3. **Atomic saves**: The original bytes are combined with updated metadata and written atomically (temp file + rename), ensuring you never lose data on failure. - -4. **Format preservation**: Unknown chunks (FLAC APPLICATION blocks, WAV metadata) are preserved from the original bytes. +A save from a path copies the audio from the source file in 64 KB pieces, so a large file is never held in memory. It writes a temporary file and renames it over the destination, so a failed save leaves the original file as it was. A save that cannot write the file whole (for example a FLAC metadata block whose length runs into the audio, an Ogg file with a broken header page, or an ASF header whose objects do not fill it) fails with the reason and writes nothing, rather than drop bytes. Unknown chunks and blocks (FLAC APPLICATION blocks, WAV chunks, MP4 boxes) are copied unchanged. **Common patterns:** ```csharp -// Pattern 1: Modify in-place (like TagLib#) -var result = Mp3File.ReadFromFile("song.mp3"); -var mp3 = result.File!; +// Pattern 1: Modify in place (like TagLib#) +var mp3 = Mp3File.ReadFromFile("song.mp3").File!; mp3.Title = "New Title"; -mp3.SaveToFile("song.mp3", File.ReadAllBytes("song.mp3")); +mp3.SaveToFile(); -// Pattern 2: Read once, modify, save (more efficient) -var bytes = File.ReadAllBytes("song.mp3"); -var result = Mp3File.Read(bytes); -var mp3 = result.File!; -mp3.Title = "New Title"; -mp3.SaveToFile("song.mp3", bytes); +// Pattern 2: Copy with modifications (the source file is left unchanged) +var copy = Mp3File.ReadFromFile("source.mp3").File!; +copy.Title = "Modified Copy"; +copy.SaveToFile("destination.mp3"); -// Pattern 3: Copy with modifications -var bytes = File.ReadAllBytes("source.mp3"); -var result = Mp3File.Read(bytes); -var mp3 = result.File!; -mp3.Title = "Modified Copy"; -mp3.SaveToFile("destination.mp3", bytes); +// Pattern 3: Bytes already in memory. Pass the bytes of the file as it is on disk. +var bytes = File.ReadAllBytes("song.mp3"); +var inMemory = Mp3File.Read(bytes).File!; +inMemory.Title = "New Title"; +inMemory.SaveToFile("song.mp3", bytes); // Pattern 4: Async with cancellation -var bytes = await File.ReadAllBytesAsync("song.mp3", cancellationToken); -var result = await Mp3File.ReadFromFileAsync("song.mp3", ct: cancellationToken); -var mp3 = result.File!; -mp3.Title = "New Title"; -await mp3.SaveToFileAsync("song.mp3", bytes, cancellationToken); +var asyncMp3 = (await Mp3File.ReadFromFileAsync("song.mp3", cancellationToken: cancellationToken)).File!; +asyncMp3.Title = "New Title"; +await asyncMp3.SaveToFileAsync(cancellationToken: cancellationToken); ``` ### 4. Async Support @@ -167,11 +150,11 @@ var file = TagLib.File.Create("song.mp3"); // Blocking **TagLibSharp2** supports async operations: ```csharp -var result = await Mp3File.ReadFromFileAsync("song.mp3", cancellationToken); +var result = await Mp3File.ReadFromFileAsync("song.mp3", cancellationToken: cancellationToken); if (result.IsSuccess) { var mp3 = result.File!; - await mp3.SaveToFileAsync("song.mp3", originalData, cancellationToken); + await mp3.SaveToFileAsync(cancellationToken: cancellationToken); } ``` @@ -191,16 +174,16 @@ if (result.IsSuccess) | `Tag.FirstComposer` | `Composers[0]` | Use array indexer | | `Tag.Genres` | `Genres` | Same (array) | | `Tag.FirstGenre` | `Genres[0]` | Use array indexer | -| `Tag.Year` | `Year` | Same | -| `Tag.Track` | `TrackNumber` | Renamed | -| `Tag.TrackCount` | `TotalTracks` | Renamed | -| `Tag.Disc` | `DiscNumber` | Renamed | -| `Tag.DiscCount` | `TotalDiscs` | Renamed | +| `Tag.Year` | `Year` | `string?` here (`"2024"`); `uint` in TagLib# | +| `Tag.Track` | `Track` | `uint?` here; `uint` in TagLib# | +| `Tag.TrackCount` | `TotalTracks` | Renamed; `uint?` | +| `Tag.Disc` | `DiscNumber` | Renamed; `uint?` | +| `Tag.DiscCount` | `TotalDiscs` | Renamed; `uint?` | | `Tag.Comment` | `Comment` | Same | | `Tag.Lyrics` | `Lyrics` | Same | | `Tag.Conductor` | `Conductor` | Same | | `Tag.Copyright` | `Copyright` | Same | -| `Tag.BeatsPerMinute` | `BeatsPerMinute` | Same | +| `Tag.BeatsPerMinute` | `BeatsPerMinute` | `uint?` here; `uint` in TagLib# | | `Tag.Pictures` | `Pictures` | Returns `IPicture[]` | ### MusicBrainz Properties @@ -211,16 +194,16 @@ if (result.IsSuccess) | `Tag.MusicBrainzReleaseId` | `MusicBrainzReleaseId` | | `Tag.MusicBrainzArtistId` | `MusicBrainzArtistId` | | `Tag.MusicBrainzReleaseGroupId` | `MusicBrainzReleaseGroupId` | -| `Tag.MusicBrainzReleaseArtistId` | `MusicBrainzAlbumArtistId` | +| `Tag.MusicBrainzReleaseArtistId` | `MusicBrainzReleaseArtistId` (an alias of `MusicBrainzAlbumArtistId`) | ### ReplayGain Properties -| TagLib# | TagLibSharp2 | -|---------|--------------| -| `Tag.ReplayGainTrackGain` | `ReplayGainTrackGain` | -| `Tag.ReplayGainTrackPeak` | `ReplayGainTrackPeak` | -| `Tag.ReplayGainAlbumGain` | `ReplayGainAlbumGain` | -| `Tag.ReplayGainAlbumPeak` | `ReplayGainAlbumPeak` | +| TagLib# | TagLibSharp2 | Notes | +|---------|--------------|-------| +| `Tag.ReplayGainTrackGain` | `ReplayGainTrackGain` | `string?` as stored (`"-6.50 dB"`); `double` in TagLib# | +| `Tag.ReplayGainTrackPeak` | `ReplayGainTrackPeak` | `string?` as stored (`"0.988547"`); `double` in TagLib# | +| `Tag.ReplayGainAlbumGain` | `ReplayGainAlbumGain` | `string?`; `double` in TagLib# | +| `Tag.ReplayGainAlbumPeak` | `ReplayGainAlbumPeak` | `string?`; `double` in TagLib# | ## Type Changes @@ -236,7 +219,7 @@ PictureType type = picture.Type; **TagLibSharp2**: ```csharp -IPicture picture = mp3.Pictures[0]; +IPicture picture = mp3.Tag!.Pictures[0]; BinaryData data = picture.PictureData; byte[] bytes = data.ToArray(); // Or use Span string mime = picture.MimeType; @@ -253,8 +236,8 @@ bool hasId3v2 = (types & TagTypes.Id3v2) != 0; **TagLibSharp2**: ```csharp -TagTypes type = mp3.TagType; // Single tag type per object -bool isId3v2 = type == TagTypes.Id3v2; +TagTypes types = mp3.Tag!.TagType; // Every tag the combined view holds +bool hasId3v2Flag = (types & TagTypes.Id3v2) != 0; // Or check available tags bool hasId3v2 = mp3.Id3v2Tag is not null; @@ -387,7 +370,7 @@ byte[] bytes = data.Data; **TagLibSharp2** uses `BinaryData` with `Span` support: ```csharp -BinaryData data = mp3.Pictures[0].PictureData; +BinaryData data = mp3.Tag!.Pictures[0].PictureData; // Multiple access patterns byte[] bytes = data.ToArray(); // Allocates new array @@ -412,28 +395,30 @@ file.Save(); **TagLibSharp2** (ID3v2): ```csharp var picture = new PictureFrame( - PictureType.FrontCover, "image/jpeg", + PictureType.FrontCover, "Album Art", new BinaryData(imageBytes)); -mp3.Id3v2Tag!.AddPicture(picture); -mp3.SaveToFile("song.mp3", originalData); +var id3v2 = mp3.Id3v2Tag ??= new Id3v2Tag(); +id3v2.AddPicture(picture); +mp3.SaveToFile(); ``` **TagLibSharp2** (FLAC/Vorbis): ```csharp var picture = new FlacPicture( - PictureType.FrontCover, "image/jpeg", + PictureType.FrontCover, "Album Art", + new BinaryData(imageBytes), width: 500, height: 500, colorDepth: 24, - colorCount: 0, - new BinaryData(imageBytes)); + colorCount: 0); -flac.VorbisComment.AddPicture(picture); +flac.AddPicture(picture); // a FLAC PICTURE metadata block +flac.SaveToFile(); ``` ## Common Migration Patterns @@ -477,7 +462,7 @@ void SetTitle(string path, string title) var mp3 = result.File!; mp3.Title = title; - mp3.SaveToFile(path, File.ReadAllBytes(path)); + mp3.SaveToFile(); } ``` @@ -486,17 +471,20 @@ void SetTitle(string path, string title) // TagLibSharp2 only - no TagLib# equivalent async Task GetTitleAsync(string path, CancellationToken ct = default) { - var result = await Mp3File.ReadFromFileAsync(path, ct: ct); + var result = await Mp3File.ReadFromFileAsync(path, cancellationToken: ct); return result.IsSuccess ? result.File!.Title : null; } ``` ## What's Not Yet Supported -These TagLib# features are not implemented yet. Planned work is tracked in [GitHub issues](https://github.com/decriptor/TagLibSharp2/issues) and on the [project board](https://github.com/users/decriptor/projects/7). +These TagLib# 2.3.0 features are not implemented yet: + +- **AVI tags**: DivX (`IDVX`) and MovieID (`LIST MID `) tags are not read; they are kept unchanged on save +- **Image metadata**: Exif, IPTC and most XMP values are not read +- **Camera raw images**: TagLib# has file types for CR2, NEF, ARW, PEF and RW2, and opens KDC, ORF, SRF, CRW, MRW, RAF and X3F without metadata. There is no camera raw format here; a raw file with a TIFF header may open as TIFF, with its size only -- **Formats**: Speex, TrueAudio, tracker formats (MOD/S3M/IT/XM), APEv2 tags in MP3 files -- **Features**: Matroska/WebM non-picture attachments are not written (tag values, chapters, and picture attachments are; WebM has no attachments). AVI DivX (`IDVX`) and MovieID (`LIST MID `) tags are not read; they are kept unchanged on save. Exif, IPTC and most XMP values in images are not read +Also not implemented yet: APEv2 tags in MP3 files; writing Matroska/WebM attachments other than pictures (tag values, chapters, and picture attachments are written; WebM has no attachments); and Speex, TrueAudio and the tracker formats (MOD/S3M/IT/XM), which TagLib# 2.3.0 does not open either. Planned work is tracked in [GitHub issues](https://github.com/decriptor/TagLibSharp2/issues) and on the [project board](https://github.com/users/decriptor/projects/7). ## Format-Specific Examples @@ -546,7 +534,7 @@ if (result.IsSuccess) var wv = result.File!; // Audio properties - Console.WriteLine($"Duration: {wv.Duration}"); + Console.WriteLine($"Duration: {wv.Properties.Duration}"); Console.WriteLine($"Sample Rate: {wv.SampleRate}"); Console.WriteLine($"Bits Per Sample: {wv.BitsPerSample}"); @@ -557,8 +545,7 @@ if (result.IsSuccess) // APE tags support ReplayGain natively wv.ApeTag!.ReplayGainTrackGain = "-6.50 dB"; - var rendered = wv.Render(originalData); - wv.SaveToFile("audio.wv"); + wv.SaveToFile(); } ``` @@ -573,7 +560,7 @@ if (result.IsSuccess) var ape = result.File!; // Audio properties - Console.WriteLine($"Duration: {ape.Duration}"); + Console.WriteLine($"Duration: {ape.Properties.Duration}"); Console.WriteLine($"Compression Level: {ape.CompressionLevel}"); Console.WriteLine($"Version: {ape.Version}"); @@ -581,8 +568,7 @@ if (result.IsSuccess) ape.EnsureApeTag().Title = "Track Title"; ape.EnsureApeTag().Artist = "Artist"; - var rendered = ape.Render(originalData); - ape.SaveToFile("audio.ape"); + ape.SaveToFile(); } ``` @@ -624,16 +610,15 @@ if (result.IsSuccess) var mpc = result.File!; // Audio properties - Console.WriteLine($"Duration: {mpc.Duration}"); - Console.WriteLine($"Stream Version: {mpc.StreamVersion}"); // SV7 or SV8 - Console.WriteLine($"Average Bitrate: {mpc.AverageBitrate} kbps"); + Console.WriteLine($"Duration: {mpc.Properties.Duration}"); + Console.WriteLine($"Stream Version: {mpc.StreamVersion}"); // 7 or 8 + Console.WriteLine($"Bitrate: {mpc.Properties.Bitrate} kbps"); // Metadata via APE tag mpc.EnsureApeTag().Title = "Track Title"; mpc.EnsureApeTag().MusicBrainzTrackId = "guid-here"; - var rendered = mpc.Render(originalData); - mpc.SaveToFile("audio.mpc"); + mpc.SaveToFile(); } ``` @@ -655,7 +640,6 @@ if (result.IsSuccess) Console.WriteLine($"Format: {aac.Properties.StreamFormat}"); // Adts or Adif // Writes go to every tag the file has. An untagged file gets ID3v2. - aac.EnsureId3v2Tag(); aac.Tag!.Title = "Track Title"; aac.SaveToFile(); // the AAC frames are copied unchanged @@ -673,7 +657,7 @@ if (result.IsSuccess) var oggFlac = result.File!; // FLAC audio properties - Console.WriteLine($"Duration: {oggFlac.Duration}"); + Console.WriteLine($"Duration: {oggFlac.Properties.Duration}"); Console.WriteLine($"Sample Rate: {oggFlac.SampleRate}"); Console.WriteLine($"Bits Per Sample: {oggFlac.BitsPerSample}"); @@ -681,8 +665,7 @@ if (result.IsSuccess) oggFlac.EnsureVorbisComment().Title = "Track Title"; oggFlac.VorbisComment!.ReplayGainTrackGain = "-6.50 dB"; - var rendered = oggFlac.Render(originalData); - oggFlac.SaveToFile("audio.oga"); + oggFlac.SaveToFile(); } ``` @@ -697,10 +680,10 @@ if (result.IsSuccess) var wma = result.File!; // Audio properties - Console.WriteLine($"Duration: {wma.Duration}"); - Console.WriteLine($"Sample Rate: {wma.SampleRate}"); - Console.WriteLine($"Bitrate: {wma.Bitrate} kbps"); - Console.WriteLine($"Channels: {wma.Channels}"); + Console.WriteLine($"Duration: {wma.Properties.Duration}"); + Console.WriteLine($"Sample Rate: {wma.Properties.SampleRate}"); + Console.WriteLine($"Bitrate: {wma.Properties.Bitrate} kbps"); + Console.WriteLine($"Channels: {wma.Properties.Channels}"); // Content Description (Title, Artist, Copyright) Console.WriteLine($"Title: {wma.Title}"); @@ -723,18 +706,19 @@ if (result.IsSuccess) } ``` +A file whose File Properties Object has the Broadcast Flag set (a capture still being written) has no valid play duration, so `Duration` is 0. `wma.FileProperties?.IsBroadcast` reports the flag; `FileProperties` also gives the file ID, size, creation date, packet counts and bit rate. + ## New Features Not in TagLib# TagLibSharp2 includes several features not available in TagLib#: -- **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, MPEG program streams / video elementary streams, raw AAC (ADTS/ADIF), Audible .aa, and AVI -- **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 +- **Format detection from content**: `MediaFile.Read()` identifies the format from the file's bytes, where TagLib#'s `File.Create` goes by the extension or MIME type. It 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, MPEG program streams / video elementary streams, raw AAC (ADTS/ADIF), Audible .aa, AVI, and JPEG, PNG, GIF, BMP, PCX, Netpbm, TIFF, DNG and SVG images +- **DSDIFF**: DFF files, which TagLib# 2.3.0 does not open (it opens DSF, WavPack, Monkey's Audio and Musepack, as this library does) - **Async I/O**: Full async support throughout the API with cancellation token support - **Result-based error handling**: No exceptions for invalid files, predictable control flow ## Getting Help - [GitHub Issues](https://github.com/decriptor/TagLibSharp2/issues) -- [API Documentation](CORE-TYPES.md) +- [Core types](CORE-TYPES.md) - [Examples](../examples/) diff --git a/docs/NEW-FORMAT-CHECKLIST.md b/docs/NEW-FORMAT-CHECKLIST.md index 6e286397..b4531cf2 100644 --- a/docs/NEW-FORMAT-CHECKLIST.md +++ b/docs/NEW-FORMAT-CHECKLIST.md @@ -30,7 +30,7 @@ Create files following existing patterns: ``` src/TagLibSharp2/{Format}/ -β”œβ”€β”€ {Format}File.cs # Main file class (extends MediaFile) +β”œβ”€β”€ {Format}File.cs # Main file class (implements IMediaFile) β”œβ”€β”€ {Format}FileReadResult.cs # Result type (if complex) β”œβ”€β”€ {Format}Tag.cs # Tag implementation (if format-specific) β”œβ”€β”€ {Format}AudioProperties.cs # Audio properties (if format-specific) @@ -48,16 +48,16 @@ tests/TagLibSharp2.Tests/{Format}/ ### File Class (`{Format}File.cs`) -- [ ] Inherit from `MediaFile` base class -- [ ] Implement `IDisposable` pattern (call `base.Dispose()`) -- [ ] Static `Parse(ReadOnlySpan data)` method returning result type +- [ ] Implement `IMediaFile` (which extends `IDisposable`); `MediaFile` is the static factory, not a base class +- [ ] Static `Read(ReadOnlySpan data)` method returning the result type, and a `Read(Stream, ...)` that takes `MediaReadOptions` - [ ] Static `ReadFromFile(string path, IFileSystem? fileSystem = null)` method -- [ ] Static `ReadFromFileAsync(string path, IFileSystem? fileSystem = null, CancellationToken ct = default)` method +- [ ] Static `ReadFromFileAsync(string path, IFileSystem? fileSystem = null, CancellationToken cancellationToken = default)` method - [ ] `Render()` method returning `BinaryData` (for write support) -- [ ] `SaveToFile(string path, IFileSystem? fileSystem = null)` method -- [ ] `SaveToFileAsync(string path, IFileSystem? fileSystem = null, CancellationToken ct = default)` method -- [ ] Override `Tag` property (create lazily if needed) -- [ ] Override `AudioProperties` property +- [ ] `SaveToFile(string path, IFileSystem? fileSystem = null)` method that copies the payload from `SourcePath` in 64 KB pieces (`PathSave` and `StreamCopy`), not through one buffer +- [ ] `SaveToFileAsync(string path, IFileSystem? fileSystem = null, CancellationToken cancellationToken = default)` method +- [ ] `IMediaFile.Tag`: a view that is never null on a tagless file (`CombinedTag.SingleOrView` with a `TagCreation`), so the first write creates the tag and an emptied tag is not written; null after `Dispose` +- [ ] `IMediaFile.AudioProperties`, `VideoProperties`, `ImageProperties`, `MediaTypes` and `PicturesLoaded` +- [ ] `MediaReadOptions.SkipPictures`: leave picture payloads out, and refuse a save of a file read that way (`PictureSkip.Refuse`) - [ ] Convenience properties delegating to Tag (Title, Artist, Album, etc.) ### Result Types @@ -107,11 +107,10 @@ If format needs custom tag: Update `src/TagLibSharp2/Core/MediaFile.cs`: -- [ ] Add magic bytes constant: `private static readonly byte[] {Format}Magic = ...` -- [ ] Add detection in `DetectFormat()` method -- [ ] Add case in `OpenFromData()` switch -- [ ] Add `Open{Format}()` helper method (optional) -- [ ] Update `SupportedExtensions` if applicable +- [ ] Add magic bytes constant: `static readonly byte[] {Format}Magic = ...` +- [ ] Add detection in `DetectFormat()`, and an extension fallback if the format has a known extension +- [ ] Add a case to the `OpenDetected` switch (path and stream reads) and to the `ReadFromData` path +- [ ] Add an `Open{Format}()` helper method (optional) ## Code Style Requirements diff --git a/docs/QuickStart.md b/docs/QuickStart.md index 77ca6fb1..25179619 100644 --- a/docs/QuickStart.md +++ b/docs/QuickStart.md @@ -2,6 +2,8 @@ Get started with TagLibSharp2 in under 5 minutes. +The examples assume the namespaces of the types they use: `TagLibSharp2.Core` (`MediaFile`, `Tag`, `PictureType`, `BinaryData`) and the format's own namespace, such as `TagLibSharp2.Mpeg` for `Mp3File`, `TagLibSharp2.Xiph` for `FlacFile` and `VorbisComment`, `TagLibSharp2.Mp4` for `Mp4File`, and `TagLibSharp2.Id3.Id3v2` for `Id3v2Tag`. Most blocks list them. + ## Installation ```bash @@ -22,7 +24,7 @@ if (result.IsSuccess) Console.WriteLine($"Artist: {result.Tag?.Artist}"); Console.WriteLine($"Album: {result.Tag?.Album}"); Console.WriteLine($"Year: {result.Tag?.Year}"); - Console.WriteLine($"Format: {result.Format}"); // Mp3, Flac, OggVorbis, OggOpus, or Mp4 + Console.WriteLine($"Format: {result.Format}"); // A MediaFormat value: Mp3, Flac, OggVorbis, Opus, Mp4, ... } else { @@ -33,9 +35,12 @@ else ### Format-Specific Access ```csharp +using TagLibSharp2.Dsf; +using TagLibSharp2.Mp4; using TagLibSharp2.Mpeg; -using TagLibSharp2.Xiph; using TagLibSharp2.Ogg; +using TagLibSharp2.WavPack; +using TagLibSharp2.Xiph; // MP3 files var mp3 = Mp3File.ReadFromFile("song.mp3"); @@ -72,35 +77,32 @@ if (opus.IsSuccess) { var file = opus.File!; Console.WriteLine($"Title: {file.VorbisComment?.Title}"); - Console.WriteLine($"R128 Gain: {file.Properties?.OutputGain}dB"); + Console.WriteLine($"Output gain: {file.OutputGainDb} dB"); } // MP4/M4A files -using TagLibSharp2.Mp4; var mp4 = Mp4File.ReadFromFile("song.m4a"); if (mp4.IsSuccess) { var file = mp4.File!; Console.WriteLine($"Title: {file.Title}"); Console.WriteLine($"Duration: {file.Duration}"); - Console.WriteLine($"Codec: {file.AudioCodec}"); // Aac, Alac, or Unknown + Console.WriteLine($"Codec: {file.AudioCodec}"); // An Mp4AudioCodec value: Aac, Alac, Mp3, ... } // DSF files (DSD high-resolution audio) -using TagLibSharp2.Dsf; var dsf = DsfFile.ReadFromFile("song.dsf"); if (dsf.IsSuccess) { var file = dsf.File!; Console.WriteLine($"Title: {file.Id3v2Tag?.Title}"); Console.WriteLine($"Sample Rate: {file.Properties?.SampleRate}"); // DSD64=2822400, DSD128=5644800 - Console.WriteLine($"Channel Type: {file.Properties?.ChannelType}"); // Mono, Stereo, or Surround + Console.WriteLine($"Channel Type: {file.Properties?.ChannelType}"); // Mono, Stereo, ... (values 5 and 6 are misnamed, #260) } -// APE tagged files (MP3 with APEv2) -using TagLibSharp2.Ape; -var result = Mp3File.ReadFromFile("song.mp3"); -if (result.IsSuccess && result.File!.ApeTag is { } ape) +// APE tagged files (WavPack, Monkey's Audio, Musepack, raw AAC) +var wv = WavPackFile.ReadFromFile("song.wv"); +if (wv.IsSuccess && wv.File!.ApeTag is { } ape) { Console.WriteLine($"Title: {ape.Title}"); Console.WriteLine($"ReplayGain: {ape.ReplayGainTrackGain}"); @@ -112,6 +114,8 @@ if (result.IsSuccess && result.File!.ApeTag is { } ape) ### MP3 Files ```csharp +using TagLibSharp2.Mpeg; + var result = Mp3File.ReadFromFile("song.mp3"); if (result.IsSuccess) { @@ -123,28 +127,28 @@ if (result.IsSuccess) mp3.Album = "My Album"; mp3.Year = "2024"; mp3.Track = 1; - mp3.TotalTracks = 12; + mp3.Tag!.TotalTracks = 12; // The tag view exists even when the file has no tag yet - // Save changes - var originalData = File.ReadAllBytes("song.mp3"); - mp3.SaveToFile("song.mp3", originalData); + // Save back to song.mp3 (the audio is copied in 64 KB pieces) + mp3.SaveToFile(); } ``` ### FLAC Files ```csharp +using TagLibSharp2.Xiph; + var result = FlacFile.ReadFromFile("song.flac"); if (result.IsSuccess) { var flac = result.File!; - var vorbis = flac.VorbisComment ?? new VorbisComment(); + var tag = flac.Tag!; // Creates a Vorbis comment on the first write when the file has none - vorbis.Title = "My Song"; - vorbis.Artist = "My Artist"; + tag.Title = "My Song"; + tag.Artist = "My Artist"; - var originalData = File.ReadAllBytes("song.flac"); - flac.SaveToFile("song.flac", originalData); + flac.SaveToFile(); } ``` @@ -162,7 +166,7 @@ if (result.IsSuccess) mp4.Title = "My Song"; mp4.Artist = "My Artist"; mp4.Album = "My Album"; - mp4.Year = 2024; + mp4.Year = "2024"; mp4.Track = 1; mp4.TotalTracks = 12; @@ -176,14 +180,15 @@ if (result.IsSuccess) All file operations support async for better performance: ```csharp +using TagLibSharp2.Mpeg; + var result = await Mp3File.ReadFromFileAsync("song.mp3"); if (result.IsSuccess) { var mp3 = result.File!; mp3.Title = "Updated Title"; - var originalData = await File.ReadAllBytesAsync("song.mp3"); - await mp3.SaveToFileAsync("song.mp3", originalData); + await mp3.SaveToFileAsync(); } ``` @@ -193,6 +198,7 @@ Process multiple files in parallel: ```csharp using TagLibSharp2.Core; +using TagLibSharp2.Mpeg; var files = Directory.GetFiles("music/", "*.mp3"); @@ -200,7 +206,7 @@ var results = await BatchProcessor.ProcessAsync( files, async (path, ct) => { - var result = await Mp3File.ReadFromFileAsync(path, ct: ct); + var result = await Mp3File.ReadFromFileAsync(path, cancellationToken: ct); return result.IsSuccess ? result.File!.Title : null; }, maxDegreeOfParallelism: 4, @@ -219,10 +225,12 @@ Console.WriteLine($"Processed {successful.Count} files, {failed.Count} failed"); ### Reading Album Art ```csharp +using TagLibSharp2.Mpeg; + var result = Mp3File.ReadFromFile("song.mp3"); -if (result.IsSuccess && result.File!.Pictures.Length > 0) +if (result.IsSuccess && result.File!.Tag!.Pictures.Length > 0) { - var picture = result.File.Pictures[0]; + var picture = result.File.Tag.Pictures[0]; Console.WriteLine($"Type: {picture.PictureType}"); Console.WriteLine($"MIME: {picture.MimeType}"); @@ -234,7 +242,10 @@ if (result.IsSuccess && result.File!.Pictures.Length > 0) ### Adding Album Art ```csharp +using TagLibSharp2.Core; +using TagLibSharp2.Id3.Id3v2; using TagLibSharp2.Id3.Id3v2.Frames; +using TagLibSharp2.Mpeg; var result = Mp3File.ReadFromFile("song.mp3"); if (result.IsSuccess) @@ -248,8 +259,9 @@ if (result.IsSuccess) "Album Cover", imageBytes); - mp3.Id3v2Tag?.AddPicture(picture); - mp3.SaveToFile("song.mp3", File.ReadAllBytes("song.mp3")); + var id3v2 = mp3.Id3v2Tag ??= new Id3v2Tag(); + id3v2.AddPicture(picture); + mp3.SaveToFile(); } ``` @@ -259,6 +271,7 @@ Check tags for common issues: ```csharp using TagLibSharp2.Core; +using TagLibSharp2.Mpeg; var result = Mp3File.ReadFromFile("song.mp3"); if (result.IsSuccess) @@ -268,7 +281,7 @@ if (result.IsSuccess) if (validation is not null) { - foreach (var issue in validation.Issues) + foreach (var issue in validation.AllIssues) { Console.WriteLine($"[{issue.Severity}] {issue.Field}: {issue.Message}"); } @@ -280,6 +293,8 @@ if (result.IsSuccess) ```csharp using TagLibSharp2.Core; +using TagLibSharp2.Mpeg; +using TagLibSharp2.Xiph; // Copy from MP3 to FLAC var mp3Result = Mp3File.ReadFromFile("song.mp3"); @@ -288,9 +303,9 @@ var flacResult = FlacFile.ReadFromFile("song.flac"); if (mp3Result.IsSuccess && flacResult.IsSuccess) { var sourceTag = mp3Result.File!.Id3v2Tag; - var targetTag = flacResult.File!.VorbisComment; + var targetTag = flacResult.File!.Tag!; - if (sourceTag is not null && targetTag is not null) + if (sourceTag is not null) { // Copy all metadata sourceTag.CopyTo(targetTag); @@ -298,7 +313,7 @@ if (mp3Result.IsSuccess && flacResult.IsSuccess) // Or copy selectively sourceTag.CopyTo(targetTag, TagCopyOptions.Basic | TagCopyOptions.Pictures); - flacResult.File.SaveToFile("song.flac", File.ReadAllBytes("song.flac")); + flacResult.File.SaveToFile(); } } ``` @@ -308,6 +323,8 @@ if (mp3Result.IsSuccess && flacResult.IsSuccess) TagLibSharp2 uses result types instead of exceptions: ```csharp +using TagLibSharp2.Mpeg; + var result = Mp3File.ReadFromFile("nonexistent.mp3"); if (!result.IsSuccess) @@ -323,6 +340,7 @@ var mp3 = result.File!; ## Next Steps -- [API Reference](CORE-TYPES.md) - Detailed type documentation +- [Cookbook](Cookbook.md) - Recipes for common tasks, by format +- [Core types](CORE-TYPES.md) - `BinaryData`, pictures, properties and `IMediaFile` - [Migration Guide](MIGRATION-FROM-TAGLIB.md) - For TagLib# users - [Examples](../examples/) - More code samples diff --git a/docs/README.md b/docs/README.md index cb36402d..f34724a6 100644 --- a/docs/README.md +++ b/docs/README.md @@ -6,9 +6,14 @@ Developer and contributor resources for the TagLibSharp2 library. | Document | Description | |----------|-------------| +| [QuickStart.md](QuickStart.md) | Read and write tags in a few lines | +| [Cookbook.md](Cookbook.md) | Recipes for common tasks, by format | +| [MIGRATION-FROM-TAGLIB.md](MIGRATION-FROM-TAGLIB.md) | Moving from TagLib# | | [ARCHITECTURE.md](ARCHITECTURE.md) | Core architecture, design patterns, and project structure | | [BUILDING.md](BUILDING.md) | Build commands, target frameworks, and troubleshooting | -| [CORE-TYPES.md](CORE-TYPES.md) | API reference for `BinaryData` and `BinaryDataBuilder` | +| [CORE-TYPES.md](CORE-TYPES.md) | API reference for `BinaryData`, `BinaryDataBuilder`, pictures, properties and `IMediaFile` | +| [IMPLEMENTATION-GUIDE.md](IMPLEMENTATION-GUIDE.md) | How to take a change from issue to pull request | +| [NEW-FORMAT-CHECKLIST.md](NEW-FORMAT-CHECKLIST.md) | Everything a new format needs | ## Quick Links diff --git a/examples/FileOperations/Program.cs b/examples/FileOperations/Program.cs index 92b8ef1e..48c0ae1a 100644 --- a/examples/FileOperations/Program.cs +++ b/examples/FileOperations/Program.cs @@ -188,10 +188,12 @@ static async Task DemoSafeFileOps () // Pattern 2: Atomic saves Console.WriteLine ("\n 2. Atomic file saves:"); - Console.WriteLine (@" // Read original, modify, save atomically - var originalData = await File.ReadAllBytesAsync(path); + Console.WriteLine (@" // Modify, then save back to the file it was read from. + // The audio is copied in 64 KB pieces into a temp file that replaces the original. mp3.Title = ""New Title""; - await mp3.SaveToFileAsync(path, originalData);"); + var saved = await mp3.SaveToFileAsync(); + if (!saved.IsSuccess) + Console.WriteLine(saved.Error);"); // Pattern 3: Use IFileSystem for testing Console.WriteLine ("\n 3. Testable file operations:"); @@ -206,7 +208,7 @@ static async Task DemoSafeFileOps () // Pattern 4: Cancellation support Console.WriteLine ("\n 4. Cancellation support:"); Console.WriteLine (@" using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30)); - var result = await Mp3File.ReadFromFileAsync(path, ct: cts.Token);"); + var result = await Mp3File.ReadFromFileAsync(path, cancellationToken: cts.Token);"); await Task.CompletedTask.ConfigureAwait (false); } diff --git a/examples/README.md b/examples/README.md index 114f845d..602e1412 100644 --- a/examples/README.md +++ b/examples/README.md @@ -42,9 +42,28 @@ cd examples/TagOperations dotnet run ``` -## File Operations +## FileOperations -For working with actual audio files, see the main README Quick Start section: +Demonstrates working with whole files. It builds small MP3, FLAC and Ogg files in memory, so it needs no sample files: + +- Format detection with `MediaFile.ReadFromData` +- Batch processing with `BatchProcessor` and progress reporting +- Tag validation +- Copying tags between formats with `CopyTo` and `TagCopyOptions` +- Safe file operation patterns: result checks, path saves, `IFileSystem` for tests, and cancellation + +FileOperations is the example the solution builds. + +### Running + +```bash +cd examples/FileOperations +dotnet run +``` + +## Reading and Saving Files + +For reading and saving files on disk, see the main README Quick Start section: ```csharp // Read MP3 with unified ID3v1/ID3v2 access @@ -53,7 +72,7 @@ if (mp3.IsSuccess) { Console.WriteLine($"Title: {mp3.File!.Title}"); mp3.File.Title = "New Title"; - mp3.File.SaveToFile("song.mp3", File.ReadAllBytes("song.mp3")); + mp3.File.SaveToFile(); } // Read FLAC diff --git a/src/TagLibSharp2/README.md b/src/TagLibSharp2/README.md index bcf05439..39c67854 100644 --- a/src/TagLibSharp2/README.md +++ b/src/TagLibSharp2/README.md @@ -32,6 +32,8 @@ A modern .NET library for reading and writing metadata in media files. | Musepack | βœ… | βœ… | βœ… | | ASF/WMA | βœ… | βœ… | βœ… | | Matroska/WebM | βœ… | βœ… | βœ… | +| MPEG program stream / video elementary stream | βœ… | βœ… | βœ… | +| AVI (including OpenDML) | βœ… | βœ… | βœ… | | Audible .aa | βœ… | βœ…ΒΉ | βœ… | | Audible .aax (as MP4) | βœ… | βœ… | βœ… | | APE Tags (standalone) | βœ… | βœ… | β€” | @@ -53,10 +55,10 @@ if (result.IsSuccess) Console.WriteLine($"{mp3.Title} by {mp3.Artist}"); Console.WriteLine($"Duration: {mp3.Duration}"); - // Modify tags + // Modify tags and save back to song.mp3 mp3.Title = "New Title"; mp3.Artist = "New Artist"; - mp3.SaveToFile("song.mp3", File.ReadAllBytes("song.mp3")); + mp3.SaveToFile(); } // Read FLAC tags @@ -100,8 +102,10 @@ else ## Documentation - [GitHub Repository](https://github.com/decriptor/TagLibSharp2) +- [Quick Start Guide](https://github.com/decriptor/TagLibSharp2/blob/main/docs/QuickStart.md) +- [Cookbook](https://github.com/decriptor/TagLibSharp2/blob/main/docs/Cookbook.md) - [Migration Guide](https://github.com/decriptor/TagLibSharp2/blob/main/docs/MIGRATION-FROM-TAGLIB.md) -- [API Documentation](https://github.com/decriptor/TagLibSharp2/blob/main/docs/CORE-TYPES.md) +- [Core Types](https://github.com/decriptor/TagLibSharp2/blob/main/docs/CORE-TYPES.md) - [Examples](https://github.com/decriptor/TagLibSharp2/tree/main/examples) ## License From dbb09ff1167a6c5144ec789e3d98bd90925ecf69 Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Thu, 3 Dec 2026 17:55:45 -0700 Subject: [PATCH 4/7] build: Set the default version to 0.7.0 --- Directory.Build.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Directory.Build.props b/Directory.Build.props index bed32168..e07a4bcb 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -8,7 +8,7 @@ Copyright (c) 2025-2026 Stephen Shaw and contributors - 0.6.0 + 0.7.0 dev From 9b72675d76155434bccc945d097cb565eeb7749a Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Fri, 4 Dec 2026 09:29:01 -0700 Subject: [PATCH 5/7] build: Update the package description and tags for 0.7.0 The nuget.org description now lists AVI and says the JPEG title can be edited, matching the README's format list, and the tags gain avi, matroska, mkv and webm. --- src/TagLibSharp2/TagLibSharp2.csproj | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/TagLibSharp2/TagLibSharp2.csproj b/src/TagLibSharp2/TagLibSharp2.csproj index 5cfd0fd9..df025781 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 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, MPEG program streams (.mpg/.vob/.m2v), raw AAC, Audible .aa, and APE tags. Still images (JPEG, PNG, GIF, BMP, PCX, Netpbm, TIFF, DNG, SVG) open with width and height. PNG text, GIF comments, and JPEG COM markers can be edited. 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;mpeg;mpg;vob;audible;aa;aax;audiobook;tags;taglib;music;album-art;replaygain;musicbrainz;image;jpeg;png;gif;tiff;svg + A modern .NET library for reading and writing metadata in media files. Supports 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, MPEG program streams (.mpg/.vob/.m2v), AVI (including OpenDML), raw AAC, Audible .aa, and APE tags. Still images (JPEG, PNG, GIF, BMP, PCX, Netpbm, TIFF, DNG, SVG) open with width and height. PNG text, GIF comments, and the JPEG comment and title can be edited. 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;mpeg;mpg;vob;avi;matroska;mkv;webm;audible;aa;aax;audiobook;tags;taglib;music;album-art;replaygain;musicbrainz;image;jpeg;png;gif;tiff;svg MIT https://github.com/decriptor/TagLibSharp2 README.md From 79cce19477d59974b81c9b03d22315b4e9f2d76a Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Thu, 3 Dec 2026 20:13:01 -0700 Subject: [PATCH 6/7] docs: Move the MP4 design notes under docs/design The two MP4 documents were planning notes for v0.4.0, kept beside the user guides and published with them. The box, data-type and source catalogue stays as docs/design/mp4-box-reference.md, under a header saying it was written for v0.4.0 and that the code and CHANGELOG are authoritative; "Roadmap" leaves its name. MP4_ACCEPTANCE_CRITERIA.md, the user stories and definition of done for that shipped release, is removed: its out-of-scope list (video tracks, movement and work fields) no longer matches the code. The note's code blocks are fenced as text and called pseudo-code, since they name no real API. Its sources are the specifications and documents the project works from and the output of tools run as black boxes; the list of other implementations is removed, the clean-room note names them as sources not to read, and the Opus-in-ISOBMFF document is cited by its title rather than as RFC 8486, which is "Ambisonics in an Ogg Opus Container". The docs index links the note. --- docs/MP4_ACCEPTANCE_CRITERIA.md | 855 ------------------ docs/README.md | 1 + .../mp4-box-reference.md} | 78 +- 3 files changed, 36 insertions(+), 898 deletions(-) delete mode 100644 docs/MP4_ACCEPTANCE_CRITERIA.md rename docs/{MP4_COMPREHENSIVE_SPECIFICATION_ROADMAP.md => design/mp4-box-reference.md} (95%) diff --git a/docs/MP4_ACCEPTANCE_CRITERIA.md b/docs/MP4_ACCEPTANCE_CRITERIA.md deleted file mode 100644 index e7926d1f..00000000 --- a/docs/MP4_ACCEPTANCE_CRITERIA.md +++ /dev/null @@ -1,855 +0,0 @@ -# MP4/M4A Acceptance Criteria - -**Version:** 1.0 -**Date:** 2025-12-31 -**Target Release:** TagLibSharp2 v0.4.0 -**Feature:** MP4/M4A Audio File Format Support - ---- - -## Table of Contents - -1. [Executive Summary](#executive-summary) -2. [User Stories](#user-stories) -3. [Acceptance Criteria](#acceptance-criteria) -4. [Definition of Done](#definition-of-done) -5. [Out of Scope](#out-of-scope) -6. [Success Metrics](#success-metrics) -7. [Test Coverage Requirements](#test-coverage-requirements) - ---- - -## Executive Summary - -MP4/M4A format support is the most requested feature for TagLibSharp2 and is critical for Apple ecosystem users. This feature enables developers to read and write metadata for AAC and ALAC audio files using the iTunes-style metadata format. - -**Primary Use Cases:** -- Music library organization and management -- Podcast episode metadata editing -- Audiobook chapter management -- Album artwork management -- Cross-platform audio metadata editing - -**Target Formats:** -- M4A (AAC-LC compressed audio) -- M4A (ALAC lossless audio) -- M4B (audiobook with chapters) - ---- - -## User Stories - -### US-1: Read MP4 Metadata - -**As a** developer building a music library application -**I want to** read MP4/M4A metadata using TagLibSharp2 -**So that I can** display song information, album artwork, and organize music files - -**Acceptance Criteria:** -- Read all P0 metadata atoms (title, artist, album, etc.) -- Extract cover art in JPEG and PNG formats -- Read track and disc numbers with total counts -- Read boolean flags (compilation, gapless playback) -- Read tempo/BPM values -- Handle files with missing or partial metadata gracefully - ---- - -### US-2: Write MP4 Metadata - -**As a** developer building a metadata editor -**I want to** write MP4/M4A metadata using TagLibSharp2 -**So that I can** organize music libraries and correct incorrect metadata - -**Acceptance Criteria:** -- Write all P0 metadata atoms -- Embed cover art (JPEG and PNG) -- Set track and disc numbers -- Set compilation and gapless playback flags -- Preserve unknown atoms during write -- Maintain file playability after write -- Support atomic file writes (no corruption on failure) - ---- - -### US-3: Read Cover Art from M4A Files - -**As a** developer building a music player UI -**I want to** extract album artwork from M4A files -**So that I can** display cover art in the player interface - -**Acceptance Criteria:** -- Extract JPEG cover art (type indicator 13) -- Extract PNG cover art (type indicator 14) -- Support multiple embedded images -- Provide image format detection -- Return image binary data for display -- Handle files with no artwork gracefully - ---- - -### US-4: Detect AAC vs ALAC Codec - -**As a** developer building a codec analyzer -**I want to** detect the audio codec in M4A files -**So that I can** show users whether files are lossy or lossless - -**Acceptance Criteria:** -- Identify AAC-LC codec from esds box -- Identify ALAC codec from alac magic cookie -- Distinguish AAC variants (LC, Main, SSR, LTP) -- Return codec name as string -- Detect other audio codecs (AC-3, Opus, MP3) -- Handle multi-codec files (return primary audio track codec) - ---- - -### US-5: Extract Accurate Audio Duration - -**As a** developer building a playlist manager -**I want to** get accurate playback duration for M4A files -**So that I can** show total playlist time and individual track lengths - -**Acceptance Criteria:** -- Extract duration from mvhd (movie header) -- Extract duration from mdhd (media header) -- Calculate duration in seconds with millisecond precision -- Handle edit lists for gapless playback -- Match ffprobe duration within 1 second -- Support files with unusual timescales - ---- - -### US-6: Extract Audio Properties - -**As a** developer building an audio file analyzer -**I want to** read sample rate, bit depth, channels, and bitrate -**So that I can** show detailed technical information about audio files - -**Acceptance Criteria:** -- Extract sample rate for AAC (from esds Audio Specific Config) -- Extract sample rate for ALAC (from magic cookie) -- Extract channel count (mono, stereo, 5.1, 7.1) -- Extract bit depth for ALAC (16, 20, 24, 32-bit) -- Calculate or extract bitrate (CBR and VBR) -- Handle unusual sample rates (8kHz to 96kHz) - ---- - -### US-7: Round-Trip Metadata Preservation - -**As a** developer building a metadata editor -**I want to** read, modify, and write M4A files without data loss -**So that I can** safely edit metadata without corrupting files or losing information - -**Acceptance Criteria:** -- Preserve all unmodified metadata atoms -- Preserve audio data exactly (byte-for-byte) -- Maintain file structure integrity -- Keep unknown atoms unchanged -- Preserve edit lists and other technical atoms -- No data loss on consecutive read-write cycles - ---- - -### US-8: Handle Large Files - -**As a** developer building an audiobook editor -**I want to** work with large M4B files (>4GB) -**So that I can** edit long-form audiobook metadata - -**Acceptance Criteria:** -- Support files larger than 4GB -- Use 64-bit chunk offsets (co64) when present -- Use 64-bit durations (version 1 boxes) -- Handle largesize fields (size == 1) -- Stream file reading without loading entire file into memory - ---- - -## Acceptance Criteria - -### Feature: Read MP4 Metadata - -#### Scenario: Read title from M4A file -```gherkin -Given an M4A file with title "Test Song" -When I read the file with TagLibSharp2 -Then the Tag.Title property should be "Test Song" -``` - -#### Scenario: Read artist from M4A file -```gherkin -Given an M4A file with artist "Test Artist" -When I read the file with TagLibSharp2 -Then the Tag.Artist property should be "Test Artist" -``` - -#### Scenario: Read album from M4A file -```gherkin -Given an M4A file with album "Test Album" -When I read the file with TagLibSharp2 -Then the Tag.Album property should be "Test Album" -``` - -#### Scenario: Read album artist from M4A file -```gherkin -Given an M4A file with album artist "Various Artists" -When I read the file with TagLibSharp2 -Then the Tag.AlbumArtist property should be "Various Artists" -``` - -#### Scenario: Read track number with total -```gherkin -Given an M4A file with track 3 of 12 -When I read the file with TagLibSharp2 -Then the Tag.Track property should be 3 -And the Tag.TrackCount property should be 12 -``` - -#### Scenario: Read disc number with total -```gherkin -Given an M4A file with disc 2 of 3 -When I read the file with TagLibSharp2 -Then the Tag.Disc property should be 2 -And the Tag.DiscCount property should be 3 -``` - -#### Scenario: Read genre from M4A file -```gherkin -Given an M4A file with genre "Jazz" -When I read the file with TagLibSharp2 -Then the Tag.Genre property should be "Jazz" -``` - -#### Scenario: Read year from M4A file -```gherkin -Given an M4A file with year "2025" -When I read the file with TagLibSharp2 -Then the Tag.Year property should be 2025 -``` - -#### Scenario: Read comment from M4A file -```gherkin -Given an M4A file with comment "Test comment" -When I read the file with TagLibSharp2 -Then the Tag.Comment property should be "Test comment" -``` - -#### Scenario: Read tempo/BPM from M4A file -```gherkin -Given an M4A file with BPM 120 -When I read the file with TagLibSharp2 -Then the Tag.BeatsPerMinute property should be 120 -``` - -#### Scenario: Read compilation flag -```gherkin -Given an M4A file marked as compilation -When I read the file with TagLibSharp2 -Then the Tag.IsCompilation property should be true -``` - -#### Scenario: Read missing metadata gracefully -```gherkin -Given an M4A file with no metadata -When I read the file with TagLibSharp2 -Then the Tag.Title property should be null -And no exception should be thrown -``` - ---- - -### Feature: Write MP4 Metadata - -#### Scenario: Write title to M4A file -```gherkin -Given an M4A file -When I set Tag.Title to "New Title" -And I save the file -Then reading the file again should show Tag.Title as "New Title" -``` - -#### Scenario: Write artist to M4A file -```gherkin -Given an M4A file -When I set Tag.Artist to "New Artist" -And I save the file -Then reading the file again should show Tag.Artist as "New Artist" -``` - -#### Scenario: Write track number -```gherkin -Given an M4A file -When I set Tag.Track to 5 -And I set Tag.TrackCount to 10 -And I save the file -Then reading the file again should show track 5 of 10 -``` - -#### Scenario: Update existing metadata -```gherkin -Given an M4A file with title "Old Title" -When I set Tag.Title to "New Title" -And I save the file -Then reading the file again should show Tag.Title as "New Title" -And the file should remain playable -``` - -#### Scenario: Remove metadata -```gherkin -Given an M4A file with title "Test" -When I set Tag.Title to null -And I save the file -Then reading the file again should show Tag.Title as null -``` - -#### Scenario: Preserve unmodified metadata -```gherkin -Given an M4A file with title "Song" and artist "Artist" -When I set Tag.Album to "Album" -And I save the file -Then reading the file again should show all three fields correctly -``` - ---- - -### Feature: Cover Art Support - -#### Scenario: Read JPEG cover art -```gherkin -Given an M4A file with JPEG album artwork -When I read the file with TagLibSharp2 -Then the Tag.Pictures array should contain 1 picture -And the picture format should be JPEG -And the picture data should match the embedded image -``` - -#### Scenario: Read PNG cover art -```gherkin -Given an M4A file with PNG album artwork -When I read the file with TagLibSharp2 -Then the Tag.Pictures array should contain 1 picture -And the picture format should be PNG -And the picture data should match the embedded image -``` - -#### Scenario: Write JPEG cover art -```gherkin -Given an M4A file -When I add a JPEG image to Tag.Pictures -And I save the file -Then reading the file again should contain the JPEG image -And the file should be playable in iTunes -``` - -#### Scenario: Write PNG cover art -```gherkin -Given an M4A file -When I add a PNG image to Tag.Pictures -And I save the file -Then reading the file again should contain the PNG image -And the file should be playable in iTunes -``` - -#### Scenario: Replace cover art -```gherkin -Given an M4A file with existing cover art -When I replace Tag.Pictures with a new image -And I save the file -Then reading the file again should contain only the new image -``` - -#### Scenario: Remove cover art -```gherkin -Given an M4A file with cover art -When I clear Tag.Pictures -And I save the file -Then reading the file again should have no pictures -``` - ---- - -### Feature: Codec Detection - -#### Scenario: Detect AAC-LC codec -```gherkin -Given an M4A file with AAC-LC audio -When I read the file with TagLibSharp2 -Then the AudioProperties.Codec should be "AAC-LC" -``` - -#### Scenario: Detect ALAC codec -```gherkin -Given an M4A file with ALAC audio -When I read the file with TagLibSharp2 -Then the AudioProperties.Codec should be "ALAC" -``` - -#### Scenario: Detect sample entry type -```gherkin -Given an M4A file -When I read the file with TagLibSharp2 -Then the sample entry type should be "mp4a" or "alac" -``` - ---- - -### Feature: Audio Properties - -#### Scenario: Extract duration with millisecond precision -```gherkin -Given an M4A file with 3 minutes 45.678 seconds duration -When I read the file with TagLibSharp2 -Then the AudioProperties.Duration should be within 0.1 seconds of actual -``` - -#### Scenario: Extract sample rate for AAC -```gherkin -Given an AAC M4A file with 44100 Hz sample rate -When I read the file with TagLibSharp2 -Then the AudioProperties.SampleRate should be 44100 -``` - -#### Scenario: Extract sample rate for ALAC -```gherkin -Given an ALAC M4A file with 48000 Hz sample rate -When I read the file with TagLibSharp2 -Then the AudioProperties.SampleRate should be 48000 -``` - -#### Scenario: Extract channel count -```gherkin -Given an M4A file with stereo audio -When I read the file with TagLibSharp2 -Then the AudioProperties.Channels should be 2 -``` - -#### Scenario: Extract bit depth for ALAC -```gherkin -Given an ALAC M4A file with 24-bit audio -When I read the file with TagLibSharp2 -Then the AudioProperties.BitsPerSample should be 24 -``` - -#### Scenario: Extract bitrate for AAC -```gherkin -Given an AAC M4A file with 256 kbps bitrate -When I read the file with TagLibSharp2 -Then the AudioProperties.Bitrate should be within 10 kbps of 256 -``` - -#### Scenario: Calculate bitrate for VBR files -```gherkin -Given an AAC M4A file with variable bitrate -When I read the file with TagLibSharp2 -Then the AudioProperties.Bitrate should reflect the average bitrate -``` - ---- - -### Feature: Round-Trip Integrity - -#### Scenario: Preserve all metadata on round-trip -```gherkin -Given an M4A file with complete metadata -When I read the file -And I modify Tag.Title -And I save the file -And I read the file again -Then all other metadata fields should be unchanged -``` - -#### Scenario: Preserve audio data exactly -```gherkin -Given an M4A file -When I modify metadata and save -Then the audio data should be byte-identical to the original -``` - -#### Scenario: Preserve unknown atoms -```gherkin -Given an M4A file with custom vendor atoms -When I modify metadata and save -Then the custom atoms should be preserved -``` - -#### Scenario: Consecutive writes -```gherkin -Given an M4A file -When I perform 5 consecutive read-modify-write cycles -Then the file should remain valid and playable -And no metadata should be lost -``` - ---- - -### Feature: Chapters - -An MP4 file stores chapters in two places, and `Mp4File.Chapters` reads and replaces both: - -- **QuickTime chapter track**: a disabled text track that a sound or video track names in its `tref`/`chap` - reference (ISO 14496-12 Β§8.3.3; QuickTime File Format). Each sample is one title: a 16-bit length, then UTF-8 - (or UTF-16 with a byte order mark), then optional modifier boxes such as `encd` (3GPP TS 26.245 Β§5.17). - Times come from `stts` in the `mdhd` timescale, positions from `stsc`/`stsz`/`stco`/`co64`, and an edit - list's empty edit delays the track. -- **Nero `chpl`** in `moov/udta`: version 1, 4 reserved bytes, an 8-bit count (at most 255 entries), and per entry - a 64-bit start in 100 ns units, an 8-bit length, and a UTF-8 title. There is no published specification; the - layout is the one ffmpeg writes and ffprobe and MediaInfo read back. - -#### Scenario: Read chapters -```gherkin -Given an M4B file with a chapter track, a chpl box, or both -When I read the file -Then Chapters lists each start time and title in order -And each EndTime is the next start, or the track or file end for the last chapter -And the chapter track wins when the two forms disagree (as ffprobe reads it) -And chpl start times are used when both forms hold the same titles (100 ns precision) -``` - -#### Scenario: Replace chapters -```gherkin -Given an MP4 file with or without chapters -When I set Chapters and save -Then chpl holds the first 255 chapters, titles cut to 255 UTF-8 bytes on a character boundary -And the chapter track holds every chapter: an existing track keeps its track_ID, language, handler, and flags; - otherwise a new one is added and every sound and video track gets a chap reference to it -And a new MP4 chapter track uses nmhd and a tx3g sample entry (Apple TN2174); a QuickTime one uses gmhd and the - QTFF text sample description -And the new samples sit in their own mdat right after moov -And that mdat replaces the one an earlier chapter save wrote, so repeated edits do not grow the file -And old chapter samples that share an mdat with other media stay there unreferenced -And every other track's chunk offsets move with the same update a tag edit makes -And ffprobe, MediaInfo, and TagLibSharp2 read the same list back -``` - -#### Scenario: Remove chapters -```gherkin -Given an MP4 file with chapters -When I set Chapters to an empty list and save -Then chpl, every track a chap reference names (titles, and Apple chapter URL and image tracks), and those - references are removed, so Apple players list no chapters either -``` - -#### Scenario: Fragmented movie -```gherkin -Given a fragmented MP4 (moov/mvex) whose chapter track keeps samples in movie fragments -When I read the file -Then Chapters lists the fragment samples (tfhd/tfdt/trun, ISO 14496-12 Β§8.8) -When I change Chapters and save -Then the save fails with an error and the file is not written, - because a track rebuilt in moov would leave the fragment samples as a second chapter list -When the fragmented movie has no chapter track -Then a save writes chpl only -``` - -#### Scenario: Leave chapters alone -```gherkin -Given an MP4 file with chapters -When I save without setting Chapters, or set the list the file already holds -Then the chpl bytes and the chapter samples are unchanged -``` - ---- - -### Feature: Large File Support - -#### Scenario: Handle 5GB M4B file -```gherkin -Given an M4B audiobook file larger than 4GB -When I read the file with TagLibSharp2 -Then metadata should be read successfully -And memory usage should be reasonable (<100MB) -``` - -#### Scenario: Use 64-bit chunk offsets -```gherkin -Given an M4A file with co64 (64-bit chunk offset) atom -When I read the file with TagLibSharp2 -Then the file should be parsed correctly -``` - ---- - -### Feature: Error Handling - -#### Scenario: Handle corrupted ftyp -```gherkin -Given an M4A file with corrupted file type box -When I attempt to read the file -Then a descriptive error should be returned -And no exception should crash the application -``` - -#### Scenario: Handle truncated file -```gherkin -Given an M4A file that was truncated during download -When I attempt to read the file -Then available metadata should be extracted -And an error should indicate the file is incomplete -``` - -#### Scenario: Handle DRM-protected file -```gherkin -Given an M4A file with FairPlay DRM -When I attempt to read the file -Then an error should indicate the file is protected -And no attempt to decrypt should be made -``` - ---- - -## Definition of Done - -### P0 Metadata Atoms (Must Support) - -- [ ] `Β©nam` - Title -- [ ] `Β©ART` - Artist -- [ ] `Β©alb` - Album -- [ ] `aART` - Album Artist -- [ ] `trkn` - Track Number (with total) -- [ ] `disk` - Disc Number (with total) -- [ ] `covr` - Cover Art (JPEG and PNG) -- [ ] `Β©gen` - Genre -- [ ] `Β©day` - Year/Date -- [ ] `Β©cmt` - Comment -- [ ] `Β©lyr` - Lyrics -- [ ] `Β©wrt` - Composer -- [ ] `Β©grp` - Grouping -- [ ] `cpil` - Compilation flag -- [ ] `pgap` - Gapless playback flag -- [ ] `tmpo` - BPM/Tempo - -### Audio Properties (Must Extract) - -- [ ] AAC codec detection and identification -- [ ] ALAC codec detection and identification -- [ ] Duration accurate to within 1 second of ffprobe -- [ ] Sample rate extraction (AAC and ALAC) -- [ ] Channel count extraction -- [ ] Bit depth extraction (ALAC) -- [ ] Bitrate extraction or calculation - -### File Operations (Must Work) - -- [ ] Read metadata from M4A files -- [ ] Write metadata to M4A files -- [ ] Round-trip preserves all metadata -- [ ] Atomic file writes (no corruption on failure) -- [ ] Files remain playable after write - -### Compatibility (Must Pass) - -- [ ] Files written are playable in iTunes/Music.app -- [ ] Files written are playable in VLC -- [ ] Files written are readable by foobar2000 -- [ ] Files written are readable by Mp3tag -- [ ] Files written are readable by MusicBrainz Picard - -### Code Quality (Must Meet) - -- [ ] 100+ unit tests covering core functionality -- [ ] Integration tests with real M4A/M4B files -- [ ] Round-trip tests (read β†’ write β†’ read) -- [ ] XML documentation on all public APIs -- [ ] Clean room implementation (no GPL/LGPL code) - -### Integration (Must Complete) - -- [ ] Integration with `MediaFile.Read()` factory -- [ ] Integration with `MediaFormat` enum -- [ ] Support for `.m4a`, `.m4b`, `.mp4` (audio) extensions -- [ ] Result type pattern (no exceptions for expected errors) - ---- - -## Out of Scope - -The following features are explicitly **NOT** included in v0.4.0: - -### Video Track Support -- Video codec detection (avc1, hvc1, etc.) -- Video media header (vmhd) parsing -- Video frame analysis -- Video thumbnail extraction - -**Rationale:** TagLibSharp2 is an audio metadata library. Video support adds significant complexity for limited benefit. - -### DRM Decryption -- FairPlay DRM decryption -- CENC/Widevine decryption -- Protected content playback - -**Rationale:** DRM decryption is legally complex and out of scope for a metadata library. Files will be detected as protected and reading will fail gracefully. - -### Movie Fragments (DASH/HLS) -- Movie fragment (moof) boxes -- Track fragment (traf) boxes -- Segment index (sidx) boxes -- Fragmented file support - -**Rationale:** Streaming formats use different structures. Initial release focuses on traditional M4A files. - -### Chapter Support (Delivered after v0.4.0) -Chapter support was deferred from v0.4.0 and is now delivered: see -[Feature: Chapters](#feature-chapters). Still out of scope: chapter images (an Apple video track that a -`chap` reference names) and chapter URLs are kept as they are on a replace but are not edited; no chapter -track is added to a fragmented movie (`mvex` needs a `trex` per track) or to a file with no track; and the -chapters of a fragmented movie that has a chapter track cannot be changed (the save fails when that track has samples in movie fragments). - -### Advanced Metadata -- TV show metadata (tvsh, tven, tvnn) -- Podcast-specific atoms (purl, egid) -- iTunes Store IDs (cnID, atID, plID) -- Movement/work metadata (classical music) - -**Rationale:** These are P1/P2 features that can be added after core tagging works. - -### File Optimization -- Relocating moov atom to beginning of file -- Padding management -- File size optimization - -**Rationale:** Optimization features can be added later. Initial focus is correctness. - -### Multi-Track Files -- Multiple audio track support -- Language-specific track selection -- Track enable/disable flags - -**Rationale:** Most M4A files have single audio track. Multi-track support can be added in v0.5.0. - ---- - -## Success Metrics - -### Zero Data Loss -- **Target:** 100% metadata preservation on round-trip -- **Measurement:** Automated round-trip tests with 100+ real-world files -- **Pass Criteria:** All fields match after read β†’ write β†’ read cycle - -### Performance -- **Target:** Read time <10ms for typical M4A file -- **Measurement:** Benchmark suite with files of varying sizes -- **Pass Criteria:** 95th percentile read time under 10ms on reference hardware - -### Compatibility -- **Target:** Files playable in all major players -- **Measurement:** Manual testing with iTunes, VLC, foobar2000 -- **Pass Criteria:** Zero playback errors across all tested players - -### Code Coverage -- **Target:** 90%+ code coverage for MP4 module -- **Measurement:** Code coverage analysis with dotnet test -- **Pass Criteria:** All public APIs covered, all critical paths tested - -### Duration Accuracy -- **Target:** Duration matches ffprobe within 1 second -- **Measurement:** Compare AudioProperties.Duration with ffprobe output -- **Pass Criteria:** 100% of test files within tolerance - ---- - -## Test Coverage Requirements - -### Unit Tests (Minimum 100 tests) - -#### Box Parsing Tests (20 tests) -- ftyp box parsing (valid brands) -- mvhd box parsing (version 0 and 1) -- mdhd box parsing (version 0 and 1) -- tkhd box parsing -- hdlr box parsing (audio handler detection) -- stsd box parsing (sample descriptions) -- esds box parsing (AAC config) -- alac magic cookie parsing -- ilst box parsing (metadata item list) -- data atom parsing (UTF-8, integer, JPEG, PNG) - -#### Metadata Tests (30 tests) -- Read/write each P0 text field (10 tests) -- Read/write track/disc numbers (4 tests) -- Read/write boolean flags (4 tests) -- Read/write BPM (2 tests) -- Read/write cover art JPEG (3 tests) -- Read/write cover art PNG (3 tests) -- Multiple cover art images (2 tests) -- Empty/null metadata handling (2 tests) - -#### Audio Properties Tests (20 tests) -- Duration extraction (mvhd) -- Duration extraction (mdhd) -- Sample rate extraction (AAC from esds) -- Sample rate extraction (ALAC from magic cookie) -- Channel count extraction -- Bit depth extraction (ALAC) -- Bitrate extraction (AAC from esds) -- Bitrate calculation (from sample table) -- Codec detection (AAC-LC, ALAC) -- Edge cases (unusual sample rates, high bit depths) - -#### Round-Trip Tests (15 tests) -- Read β†’ write β†’ read (metadata preserved) -- Modify one field (others unchanged) -- Add new metadata (existing preserved) -- Remove metadata (file valid) -- Multiple consecutive writes -- Large file (>100MB) round-trip - -#### Error Handling Tests (15 tests) -- Corrupted ftyp box -- Missing required boxes (moov, mdhd) -- Invalid box sizes -- Truncated file -- DRM-protected file detection -- Malformed metadata atoms -- Invalid data type indicators -- Zero-byte file -- Non-MP4 file - -### Integration Tests (20 tests) - -#### Real-World Files -- AAC M4A from iTunes Store -- ALAC M4A from Apple Music -- M4B audiobook with chapters -- M4A with large cover art (>2MB) -- M4A with no metadata -- M4A with complete metadata -- Large file (>1GB) -- Multi-track file - -#### Cross-Tool Compatibility -- Read file created by iTunes -- Read file created by foobar2000 -- Write file readable by iTunes -- Write file readable by VLC -- Write file readable by Mp3tag - ---- - -## Acceptance Sign-Off - -### Stakeholder Approval - -- [ ] Product Manager - Feature complete -- [ ] Lead Developer - Code review passed -- [ ] QA - All tests passing -- [ ] Technical Writer - Documentation complete - -### Release Readiness - -- [ ] All P0 acceptance criteria met -- [ ] Definition of Done checklist complete -- [ ] Success metrics targets achieved -- [ ] Test coverage requirements met -- [ ] No P0 or P1 bugs outstanding -- [ ] Performance benchmarks passed -- [ ] Compatibility testing complete -- [ ] Documentation published - ---- - -**Document Status:** Draft -**Last Updated:** 2025-12-31 -**Next Review:** Upon implementation start diff --git a/docs/README.md b/docs/README.md index f34724a6..714ba595 100644 --- a/docs/README.md +++ b/docs/README.md @@ -14,6 +14,7 @@ Developer and contributor resources for the TagLibSharp2 library. | [CORE-TYPES.md](CORE-TYPES.md) | API reference for `BinaryData`, `BinaryDataBuilder`, pictures, properties and `IMediaFile` | | [IMPLEMENTATION-GUIDE.md](IMPLEMENTATION-GUIDE.md) | How to take a change from issue to pull request | | [NEW-FORMAT-CHECKLIST.md](NEW-FORMAT-CHECKLIST.md) | Everything a new format needs | +| [design/mp4-box-reference.md](design/mp4-box-reference.md) | MP4 box and metadata reference, a design note written for v0.4.0 | ## Quick Links diff --git a/docs/MP4_COMPREHENSIVE_SPECIFICATION_ROADMAP.md b/docs/design/mp4-box-reference.md similarity index 95% rename from docs/MP4_COMPREHENSIVE_SPECIFICATION_ROADMAP.md rename to docs/design/mp4-box-reference.md index 61ffad8b..52bf10dc 100644 --- a/docs/MP4_COMPREHENSIVE_SPECIFICATION_ROADMAP.md +++ b/docs/design/mp4-box-reference.md @@ -1,4 +1,6 @@ -# MP4/M4A Comprehensive Specification Roadmap +# MP4/M4A Box and Metadata Reference + +> Design reference written for v0.4.0 (2025-12-31). Parts of it are out of date: the code and CHANGELOG.md are authoritative, and its planning sections describe that release, not current work. Its code blocks are pseudo-code that names no real API. **Version:** 1.0 **Date:** 2025-12-31 @@ -14,14 +16,14 @@ 4. [Audio Property Extraction Path](#3-audio-property-extraction-path) 5. [Metadata Atom Complete Reference](#4-metadata-atom-complete-reference) 6. [Edge Cases and Compatibility Matrix](#5-edge-cases-and-compatibility-matrix) -7. [Implementation Roadmap by Priority](#6-implementation-roadmap-by-priority) +7. [Implementation Priorities for v0.4.0](#6-implementation-priorities-for-v040) 8. [Authoritative Sources](#authoritative-sources) --- ## Executive Summary -This document provides a **complete** specification roadmap for implementing MP4/M4A support in TagLibSharp2, covering the full ISO Base Media File Format (ISO 14496-12), MP4 File Format (ISO 14496-14), Apple QuickTime extensions, and iTunes-specific metadata. +This document is a specification reference for implementing MP4/M4A support in TagLibSharp2, covering the full ISO Base Media File Format (ISO 14496-12), MP4 File Format (ISO 14496-14), Apple QuickTime extensions, and iTunes-specific metadata. **Key Standards:** - **ISO/IEC 14496-12** - ISO Base Media File Format (ISOBMFF) @@ -132,7 +134,7 @@ All box types defined in ISO 14496-12 and registered extensions. Each box is cat | `alac` | Apple Lossless Audio Codec | Audio/ALAC | **P0** | Apple Extension | | `ac-3` | Dolby Digital (AC-3) | Audio | P1 | ETSI TS 102 366 | | `ec-3` | Dolby Digital Plus (E-AC-3) | Audio | P1 | ETSI TS 102 366 | -| `Opus` | Opus Audio | Audio | P2 | RFC 8486 | +| `Opus` | Opus Audio | Audio | P2 | Opus in ISOBMFF (opus-codec.org) | | `mp3.` | MP3 Audio | Audio | P2 | ISO 14496-3 Amd.3 | | `sawb` | AMR-WB Audio | Audio | P3 | 3GPP TS 26.244 | | `samr` | AMR-NB Audio | Audio | P3 | 3GPP TS 26.244 | @@ -145,7 +147,7 @@ All box types defined in ISO 14496-12 and registered extensions. Each box is cat | `alac` | ALAC Magic Cookie | Leaf | ALAC only | **P0** | Apple ALAC spec | | `dac3` | Dolby Digital (AC-3) Info | Leaf | AC-3 only | P1 | ETSI TS 102 366 | | `dec3` | E-AC-3 Specific Box | Leaf | E-AC-3 only | P1 | ETSI TS 102 366 | -| `dOps` | Opus Specific Box | Leaf | Opus only | P2 | RFC 8486 | +| `dOps` | Opus Specific Box | Leaf | Opus only | P2 | Opus in ISOBMFF (opus-codec.org) | | `wave` | Wave Atom (legacy) | Container | Legacy | P2 | QuickTime legacy | | `chan` | Channel Layout | Leaf | Optional | P1 | Apple Extension | | `btrt` | Bit Rate Box | Leaf | Optional | P2 | ISO 14496-12 Β§8.5.2.2 | @@ -249,7 +251,7 @@ All box types defined in ISO 14496-12 and registered extensions. Each box is cat **Range:** -32,768.0 to +32,767.99998 (resolution: 1.5Γ—10^-5) **Conversion:** -```csharp +```text // Float to 16.16 fixed point int32 ToFixed16_16(double value) => (int)Math.Round(value * 65536.0); @@ -302,7 +304,7 @@ double FromFixed16_16(int32 fixedValue) => fixedValue / 65536.0; **Units:** Seconds since epoch **Conversion to Unix Timestamp:** -```csharp +```text // ISO BMFF time to Unix timestamp const long MacToUnixEpochOffset = 2082844800L; // Seconds between 1904 and 1970 long unixTime = isoTime - MacToUnixEpochOffset; @@ -468,7 +470,7 @@ duration: uint32/64 // Duration in timescale units (version-dependent) ``` **Calculation:** -```csharp +```text double durationSeconds = (double)duration / timescale; ``` @@ -488,7 +490,7 @@ duration: uint32/64 // Duration in media timescale units ``` **Calculation:** -```csharp +```text double trackDurationSeconds = (double)duration / timescale; ``` @@ -510,7 +512,7 @@ For each entry: ``` **Calculation:** -```csharp +```text uint totalDuration = 0; foreach (var entry in entries) { totalDuration += entry.sample_count * entry.sample_delta; @@ -558,7 +560,7 @@ Bits 33-36: channelConfiguration (4 bits) ``` **Sampling Frequency Index Lookup Table:** -```csharp +```text private static readonly int[] SamplingFrequencies = { 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350, 0, 0, 0 // explicit in stream @@ -588,7 +590,7 @@ Offset Size Field ``` **Extract:** -```csharp +```text byte[] magicCookie = ReadAlacMagicCookie(36); int sampleRate = (magicCookie[23] << 24) | (magicCookie[24] << 16) | (magicCookie[25] << 8) | magicCookie[26]; @@ -613,7 +615,7 @@ Offset Size Field ``` **Extract:** -```csharp +```text uint32 sampleRateFixed = ReadUInt32BigEndian(offset + 24); double sampleRate = (sampleRateFixed >> 16) + ((sampleRateFixed & 0xFFFF) / 65536.0); ``` @@ -661,7 +663,7 @@ channelConfiguration (4 bits): #### From ALAC Magic Cookie **Extract:** -```csharp +```text byte channels = magicCookie[12]; // Offset 12, range 1-8 ``` @@ -696,7 +698,7 @@ samplesize: uint16 // Offset 18 in AudioSampleEntry #### From ALAC Magic Cookie **Extract:** -```csharp +```text byte sampleSize = magicCookie[8]; // Offset 8: 16, 20, 24, or 32 bits ``` @@ -719,7 +721,7 @@ avgBitrate: uint32 // Average bitrate in bps (0 = unknown) #### Method 2: From ALAC Magic Cookie **Extract:** -```csharp +```text uint avgBitrate = ReadUInt32BigEndian(magicCookie, offset: 19); // 0 = unknown ``` @@ -730,7 +732,7 @@ uint avgBitrate = ReadUInt32BigEndian(magicCookie, offset: 19); // 0 = unknown **Path:** `stbl` β†’ `stsz` (Sample Size Box) + `mdhd` (duration) **Algorithm:** -```csharp +```text // Read all sample sizes uint totalBytes = 0; if (stsz.sample_size != 0) { @@ -1115,8 +1117,8 @@ covr - `----:org.musicbrainz:Track Id` = MusicBrainz recording UUID **Registration:** -```csharp -// Mutagen-style registration +```text +// Registration of a freeform key RegisterFreeformKey("musicbrainz_artistid", "MusicBrainz Artist Id", "org.musicbrainz"); ``` @@ -1140,7 +1142,7 @@ chpl (Chapter List) - FullBox ``` **Timestamp Conversion:** -```csharp +```text double seconds = timestamp / 10_000_000.0; // 100ns to seconds ``` @@ -1173,7 +1175,7 @@ double seconds = timestamp / 10_000_000.0; // 100ns to seconds - **Version 1:** Uses `uint64` for the same fields (for dates after 2040 or very long files) **Handling:** -```csharp +```text if (version == 0) { creation_time = ReadUInt32(); modification_time = ReadUInt32(); @@ -1241,7 +1243,7 @@ if (version == 0) { #### Implementation -```csharp +```text bool IsProtected(Mp4File file) { // Check for pssh boxes if (file.HasBox("pssh")) return true; @@ -1324,7 +1326,7 @@ Some MP4 files contain multiple audio tracks: --- -## 6. Implementation Roadmap by Priority +## 6. Implementation Priorities for v0.4.0 ### P0 (Must Have for v0.4.0) - **Core Audio Tagging** @@ -1491,39 +1493,32 @@ Some MP4 files contain multiple audio tracks: ## Authoritative Sources -This roadmap is compiled from the following authoritative sources: +The project works from the specifications and documents below, and from the output of other tools run as black boxes (ffprobe, exiftool, MediaInfo and the like) on files they write or read. It does not use any other implementation's source code. ### Official Specifications 1. [ISO/IEC 14496-12:2015](https://www.iso.org/standard/68960.html) - ISO Base Media File Format (ISOBMFF) 2. [ISO/IEC 14496-14:2020](https://www.iso.org/standard/79110.html) - MP4 File Format 3. [MP4 Registration Authority](https://mp4ra.org/) - Official registry of box types, codecs, brands 4. [Apple QuickTime File Format Specification](https://developer.apple.com/library/archive/documentation/QuickTime/QTFF/QTFFPreface/qtffPreface.html) - Official Apple documentation -5. [RFC 8486](https://www.opus-codec.org/docs/opus_in_isobmff.html) - Opus in ISOBMFF - -### Implementation References -6. [Mutagen](https://mutagen.readthedocs.io/en/latest/api/mp4.html) - Python MP4 library (well-documented) -7. [AtomicParsley](https://atomicparsley.sourceforge.net/) - Command-line MP4 metadata tool -8. [mp4v2 iTunes Metadata Wiki](https://github.com/sergiomb2/libmp4v2/wiki/iTunesMetadata) - Reverse-engineered iTunes tags -9. [Bento4](https://www.bento4.com/) - Professional MP4 library and tools -10. [FFmpeg isom.c](https://github.com/FFmpeg/FFmpeg/blob/master/libavformat/isom.c) - Production MP4 parser +5. [Encapsulation of Opus in ISO Base Media File Format](https://www.opus-codec.org/docs/opus_in_isobmff.html) - Opus in ISOBMFF, version 0.6.8, hosted on opus-codec.org (not an RFC) ### Technical Articles -11. [Auphonic Blog: MPEG-4 iTunes-style Metadata](https://auphonic.com/blog/2012/02/18/podcast-comparison-part-4-mpeg-4-itunes-style-metadata-aac-audio-m4a-mp4/) -12. [Understanding AAC - MultimediaWiki](https://wiki.multimedia.cx/index.php/Understanding_AAC) -13. [ALAC Magic Cookie Description](https://github.com/macosforge/alac/blob/master/ALACMagicCookieDescription.txt) -14. [Language tagging in GPAC](https://github.com/gpac/gpac/wiki/Language-tagging-in-GPAC) +6. [Auphonic Blog: MPEG-4 iTunes-style Metadata](https://auphonic.com/blog/2012/02/18/podcast-comparison-part-4-mpeg-4-itunes-style-metadata-aac-audio-m4a-mp4/) +7. [Understanding AAC - MultimediaWiki](https://wiki.multimedia.cx/index.php/Understanding_AAC) +8. [ALAC Magic Cookie Description](https://github.com/macosforge/alac/blob/master/ALACMagicCookieDescription.txt) +9. [Language tagging in GPAC](https://github.com/gpac/gpac/wiki/Language-tagging-in-GPAC) ### Format Documentation -15. [Library of Congress - ISO Base Media File Format](https://www.loc.gov/preservation/digital/formats/fdd/fdd000079.shtml) -16. [Library of Congress - MPEG-4 File Format](https://www.loc.gov/preservation/digital/formats/fdd/fdd000155.shtml) -17. [QuickTime File Format 2001 PDF](https://developer.apple.com/standards/qtff-2001.pdf) +10. [Library of Congress - ISO Base Media File Format](https://www.loc.gov/preservation/digital/formats/fdd/fdd000079.shtml) +11. [Library of Congress - MPEG-4 File Format](https://www.loc.gov/preservation/digital/formats/fdd/fdd000155.shtml) +12. [QuickTime File Format 2001 PDF](https://developer.apple.com/standards/qtff-2001.pdf) --- ## Notes for Implementation ### Clean Room Development -- **Do NOT reference TagLib# source code** for MP4 implementation +- **Do NOT read the source code** of TagLib#, ffmpeg, mutagen, MP4v2, AtomicParsley, Bento4 or any other implementation; run other tools only as black boxes and compare their output - **Do reference** format specifications, official docs, and test files - **OK to design** similar APIs (APIs aren't copyrightable) - **OK to use** existing MP4 files as test inputs @@ -1547,6 +1542,3 @@ This roadmap is compiled from the following authoritative sources: - **DRM detected:** Return "protected file" error - **Truncated data:** Gracefully degrade (return what's available) ---- - -**End of Roadmap** From 0608bf411a82480b0c179bc94b30e12ebb5810c9 Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Fri, 4 Dec 2026 07:18:09 -0700 Subject: [PATCH 7/7] docs: Date the 0.7.0 changelog The Unreleased section becomes 0.7.0, dated 2026-12-04, under a new empty Unreleased section. The link list at the end gains 0.7.0 and an Unreleased comparison from v0.7.0. --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7f5eaa56..3e121eca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [0.7.0] - 2026-12-04 + ### Breaking Changes - **Changed**: `IMediaFile` has a new `PicturesLoaded` property. A type outside the library that implements `IMediaFile` must add it. Audio and video files return true unless they were read with `SkipPictures`. `StillImageFile` returns true even then, because the image is the picture (#157) @@ -793,6 +795,8 @@ Some of these entries fix features that are new in 0.7.0 (Matroska/WebM, MPEG-PS ### Changed - `BinaryData(byte[])` constructor now copies the array to ensure true immutability +[Unreleased]: https://github.com/decriptor/TagLibSharp2/compare/v0.7.0...HEAD +[0.7.0]: https://github.com/decriptor/TagLibSharp2/releases/tag/v0.7.0 [0.6.0]: https://github.com/decriptor/TagLibSharp2/releases/tag/v0.6.0 [0.5.0]: https://github.com/decriptor/TagLibSharp2/releases/tag/v0.5.0 [0.4.0]: https://github.com/decriptor/TagLibSharp2/releases/tag/v0.4.0