Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ See the [Migration Guide](docs/MIGRATION-FROM-TAGLIB.md) for detailed comparison
- 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.
- 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.
- 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 can be edited; a PNG edit also updates the XMP and Exif copies of the field. Other image metadata is not read or written yet.

## Format Support Matrix

Expand Down
12 changes: 12 additions & 0 deletions docs/IMPLEMENTATION-GUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,16 @@ how it was broken before.
- **Fields the format requires** are kept: the Vorbis comment vendor string, which the header must
carry (Xiph Vorbis comment, "vendor_length / vendor_string"), and Matroska's mandatory `MuxingApp`
and `WritingApp` (RFC 9559).
- **Segments a decoder or colour management needs, or that carry the file's structure**, are kept: in
still images, JPEG APP0 JFIF/JFXX, APP2 ICC_PROFILE, APP2 MPF (the multi-picture index; its offsets and
sizes are rewritten, and Clear cleans every image it lists), APP2 ISO 21496-1 (gain map), APP14 Adobe
(colour transform), the gain-map XMP properties an HDR decoder needs (Ultra HDR `hdrgm` and the
`Container`/`Item` directory with only the item values the formats enumerate, Apple `apdi` and `HDRGainMap` version and headroom, motion-photo `Camera` flags, each with the value shape its format defines, written into a new packet; nothing of the original packet is copied.) and, for a version-65536 Apple gain map, a new Exif holding only Apple maker-note tags 33 and 48 (the headroom ImageIO and libultrahdr compute from them; decode parameters, no personal data; when an Exif repeats a pointer, a MakerNote or a tag, the values kept are the ones ImageIO applies (`AppleHeadroom.Keep`); nothing else of the Exif is kept, so it is a minimal carrier that omits Exif's mandatory format tags and `exiftool -validate` warns, while every tested reader reads it), and the APP11 JPEG
XT decoding boxes named in public sources (`ftyp`, `TONE`, `RTRF`, `LTRF`, `LCHK`, `SPEC`, `RESI`); PNG critical chunks and the decode/colour chunks (tRNS, gAMA, cHRM, sRGB, iCCP, cICP, mDCV, cLLI,
sBIT, bKGD, hIST, pHYs, sPLT, the APNG chunks, oFFs, pCAL, sCAL, sTER); GIF graphic control and plain text
extensions, NETSCAPE2.0/ANIMEXTS1.0 looping and ICCRGBG1012. Everything else goes, including C2PA
manifests (PNG caBX, JPEG APP11 JUMBF), which any edit invalidates, every other APP11 box (`xml `,
`uuid`, `json`, `Exif` and unknown ones carry metadata), and unknown APPn, chunks and extensions.
- **Chapters** are file structure, not tag metadata. A tag `Clear()` keeps them in Matroska and in MP4
(checked on main: ffprobe lists the same chapters after a Clear and a save). Use the chapter API to
remove them.
Expand Down Expand Up @@ -240,6 +250,8 @@ A fix is new code, so steps (b) to (e) apply to it in full.
| `Bounds.AllocatedBytes (action)` | Bytes allocated on this thread while `action` runs. Synchronous code only. |
| `Bounds.AssertAllocatesAtMost (limit, action)` | Fails with the count when a parse allocates past a bound. |
| `Bounds.AssertLinearAllocation (build, run, n)` | Measures n, 2n and 4n, and fails when the second increment is more than 3× the first (linear work is 2×). This catches quadratic copies even behind a fixed cost. |
| `Bounds.LeastAllocated (action)` | The least bytes `action` allocates after one warm-up, so a single noisy run does not set the bound. |
| `Bytes.Count (data, needle)` | How many times a byte sequence occurs in `data`, including overlaps. |
| `CountingStream` | Counts bytes read, reads and seeks, to pin that a stream path reads only what it needs. |
| `Hostile.EveryTruncation (valid, read)` | Runs every prefix through `read`, then reports how many threw and the first lengths. |
| `Hostile.ByteFlips (valid, read)` | Changes each byte to 0x00 and 0xFF and XORs it with 0x01 and 0x80, reporting the offset and value of each throw. `values:` sets the replacement values. |
Expand Down
5 changes: 3 additions & 2 deletions docs/ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@

> Generated: January 2026
> Last Updated: November 2026
> Status: Production ready - 18 formats read and write tags, polish phase
> Status: Production ready - audio and video formats read and write tags; still images open with dimensions, polish phase

## Executive Summary

TagLibSharp2 currently supports **18 formats** with read and write. The library has mature read/write capabilities for all major formats. Remaining gaps are niche formats: Speex (obsolete), TrueAudio (niche), and tracker formats (demoscene). 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.
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 field edit also removes that field's Exif copies when the Exif structure is plain, and updates the matching XMP property; any other Exif structure is refused and nothing is written. Exif values are not read into the tag. IPTC is not read or written, and 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.

---

Expand All @@ -31,6 +31,7 @@ TagLibSharp2 currently supports **18 formats** with read and write. The library
| Matroska/WebM | P2 | ✅ | ✅ | ✅ | - | Tag values, chapters, picture attachments, and track enabled flags are saved. 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, plain Exif removal, matching XMP | - | A path save copies pixels in 64 KB pieces. Render still copies every other byte. A field edit removes Exif copies only when the structure is plain, and refuses otherwise. IPTC is not read or written. SVG metadata is not read or written yet |
| Ogg FLAC | P1 | ✅ | ✅ | ✅ | - | Recently added |
| AAC (ADTS/ADIF) | P1 | ✅ | ✅ | ✅ | - | ID3v2, APEv2, ID3v1 tags |
| Speex | P1 | ❌ | ❌ | ❌ | LOW | Uses Vorbis Comment |
Expand Down
4 changes: 4 additions & 0 deletions src/TagLibSharp2/Core/AtomicFileWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,10 @@ internal static FileWriteResult WriteStream (string path, IFileSystem? fileSyste
destinationExisted = fileSystem.FileExists (path);
fileSystem.Move (tempPath, path);
return FileWriteResult.Success (ReportedBytes (bytesWritten));
} catch (OperationCanceledException) {
if (tempPath is not null)
CleanupTempFile (tempPath, fileSystem);
return FileWriteResult.Failure ("Operation was cancelled");
} catch (EndOfStreamException ex) {
return FailWrite (
tempPath,
Expand Down
11 changes: 8 additions & 3 deletions src/TagLibSharp2/Core/BinaryData.cs
Original file line number Diff line number Diff line change
Expand Up @@ -979,11 +979,16 @@ static ushort[] BuildCrc16CcittTable ()
/// Computes CRC-32 using the standard polynomial (0xEDB88320).
/// This is compatible with zlib/PNG CRC.
/// </summary>
public uint ComputeCrc32 ()
public uint ComputeCrc32 () => ComputeCrc32 (Data);

/// <summary>
/// Computes CRC-32 over <paramref name="data"/> without copying it.
/// </summary>
internal static uint ComputeCrc32 (ReadOnlySpan<byte> data)
{
var crc = 0xFFFFFFFF;
for (var i = 0; i < Data.Length; i++)
crc = Crc32Table[(crc ^ Data[i]) & 0xFF] ^ (crc >> 8);
for (var i = 0; i < data.Length; i++)
crc = Crc32Table[(crc ^ data[i]) & 0xFF] ^ (crc >> 8);
return ~crc;
}

Expand Down
80 changes: 77 additions & 3 deletions src/TagLibSharp2/Core/MediaFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@
// Licensed under the MIT License. See LICENSE file in the project root for full license information.

using System.Buffers.Binary;
using System.Runtime.InteropServices;
using TagLibSharp2.Aac;
using TagLibSharp2.Aiff;
using TagLibSharp2.Ape;
using TagLibSharp2.Asf;
using TagLibSharp2.Audible;
using TagLibSharp2.Dff;
using TagLibSharp2.Dsf;
using TagLibSharp2.Image;
using TagLibSharp2.Matroska;
using TagLibSharp2.Mp4;
using TagLibSharp2.Mpeg;
Expand Down Expand Up @@ -416,6 +418,9 @@ static async Task<MediaFileResult> ReadAsync (
MediaFormat.MpegPs => FromMpegPs (await MpegPsFile.ReadAsync (stream, sourcePath, fileSystem, cancellationToken).ConfigureAwait (false)),
MediaFormat.Audible => FromAudible (await AudibleFile.ReadAsync (stream, sourcePath, fileSystem, cancellationToken).ConfigureAwait (false)),
MediaFormat.Avi => FromAvi (await AviFile.ReadAsync (stream, sourcePath, fileSystem, cancellationToken).ConfigureAwait (false)),
MediaFormat.Jpeg or MediaFormat.Png or MediaFormat.Gif or MediaFormat.Bmp or MediaFormat.Pcx
or MediaFormat.Netpbm or MediaFormat.Tiff or MediaFormat.Dng or MediaFormat.Svg
=> OpenImage (await StreamBytes.ReadToEndAsync (stream, cancellationToken).ConfigureAwait (false), format),
_ => OpenDetected (format, stream, sourcePath, fileSystem, pathHint)
};
return RememberMatroskaSource (result, sourcePath, fileSystem);
Expand Down Expand Up @@ -445,11 +450,15 @@ static MediaFileResult OpenDetected (MediaFormat format, Stream stream, string?
_ => ReadFromData (StreamBytes.ReadToEnd (stream), pathHint)
};

// ReadFromData's path is only an extension hint. A path read can save Matroska back to that file.
// ReadFromData's path is only an extension hint. A path read can save Matroska and still images back to that file.
static MediaFileResult RememberMatroskaSource (MediaFileResult result, string? sourcePath, IFileSystem? fileSystem)
{
if (sourcePath is not null && result.IsSuccess && result.File is MatroskaFile matroska)
if (sourcePath is null || !result.IsSuccess)
return result;
if (result.File is MatroskaFile matroska)
matroska.SetSourcePath (sourcePath, fileSystem);
else if (result.File is StillImageFile image)
image.SetSource (sourcePath, fileSystem);
return result;
}

Expand Down Expand Up @@ -627,6 +636,8 @@ static MediaFileResult ReadCore (ReadOnlyMemory<byte> data, string? pathHint)
MediaFormat.Aac => FromAac (AacFile.Read (data)),
MediaFormat.Audible => FromAudible (AudibleFile.Read (data.Span)),
MediaFormat.Avi => FromAvi (AviFile.Read (data.Span)),
MediaFormat.Jpeg or MediaFormat.Png or MediaFormat.Gif or MediaFormat.Bmp or MediaFormat.Pcx
or MediaFormat.Netpbm or MediaFormat.Tiff or MediaFormat.Dng or MediaFormat.Svg => OpenImage (data, format),
_ => MediaFileResult.Failure ($"Unknown or unsupported file format{(pathHint is not null ? $": {pathHint}" : "")}")
};

Expand Down Expand Up @@ -751,6 +762,11 @@ static MediaFormat DetectFormat (ReadOnlySpan<byte> data, string? pathHint, Stre
if (MpegFrame.IsStartOfAudio (data))
return MediaFormat.Mp3;

// After the audio signatures. A markup check that decoded every unknown buffer
// would copy an MP3, an ID3 tag, or an ASF header on the way to "not an image".
if (data.Length >= 4 && ImageHeader.TryDetect (data, out var image))
return image == MediaFormat.Tiff && StillImageFile.HasDngName (pathHint) ? MediaFormat.Dng : image;

// Fall back to extension
if (!string.IsNullOrEmpty (pathHint)) {
var ext = Path.GetExtension (pathHint).ToUpperInvariant ();
Expand All @@ -774,6 +790,15 @@ static MediaFormat DetectFormat (ReadOnlySpan<byte> data, string? pathHint, Stre
".MPG" or ".MPEG" or ".MPE" or ".VOB" or ".MPV" or ".M1V" or ".M2V" => MediaFormat.MpegPs,
".AAC" => MediaFormat.Aac,
".AVI" => MediaFormat.Avi,
".JPG" or ".JPEG" or ".JPE" => MediaFormat.Jpeg,
".PNG" => MediaFormat.Png,
".GIF" => MediaFormat.Gif,
".BMP" or ".DIB" => MediaFormat.Bmp,
".PCX" => MediaFormat.Pcx,
".PBM" or ".PGM" or ".PPM" or ".PNM" => MediaFormat.Netpbm,
".TIF" or ".TIFF" => MediaFormat.Tiff,
".DNG" => MediaFormat.Dng,
".SVG" => MediaFormat.Svg,
_ => MediaFormat.Unknown
};
}
Expand Down Expand Up @@ -950,6 +975,28 @@ static MediaFileResult OpenMonkeysAudio (ReadOnlyMemory<byte> data)
return MediaFileResult.Success (result.File!, result.File!.ApeTag, MediaFormat.MonkeysAudio);
}

static MediaFileResult OpenImage (ReadOnlyMemory<byte> data, MediaFormat format)
{
var opened = StillImageFile.Open (OwnedBytes (data), format);
return opened.IsSuccess
? MediaFileResult.Success (opened.File!, opened.File!.Tag, format)
: MediaFileResult.Failure (opened.Error!);
}

// Reuse the array behind a memory that already owns the whole buffer. A slice is copied.
static byte[] OwnedBytes (ReadOnlyMemory<byte> data)
{
if (MemoryMarshal.TryGetArray (data, out ArraySegment<byte> segment)
&& segment.Array is byte[] array
&& segment.Offset == 0
&& segment.Count == array.Length
&& data.Length == array.Length)
return array;

return data.ToArray ();
}


static MediaFileResult OpenAsf (ReadOnlyMemory<byte> data)
{
var result = AsfFile.Read (data.Span);
Expand Down Expand Up @@ -1141,5 +1188,32 @@ public enum MediaFormat
/// <summary>
/// AVI (RIFF <c>AVI </c> form, including OpenDML).
/// </summary>
Avi
Avi,

/// <summary>JPEG still image.</summary>
Jpeg,

/// <summary>PNG still image.</summary>
Png,

/// <summary>GIF still image.</summary>
Gif,

/// <summary>BMP still image.</summary>
Bmp,

/// <summary>PCX still image.</summary>
Pcx,

/// <summary>Netpbm raster (PBM, PGM, PPM, or PNM).</summary>
Netpbm,

/// <summary>TIFF still image.</summary>
Tiff,

/// <summary>DNG, a TIFF file with the DNG version tag or a .dng name.</summary>
Dng,

/// <summary>SVG image.</summary>
Svg
}
5 changes: 5 additions & 0 deletions src/TagLibSharp2/Core/Tag.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,11 @@ public enum TagTypes
/// </summary>
Audible = 1 << 10,

/// <summary>
/// Text stored in a still image: PNG keywords, a GIF comment, or a JPEG COM marker.
/// </summary>
Image = 1 << 11,

/// <summary>
/// All tag types.
/// </summary>
Expand Down
51 changes: 51 additions & 0 deletions src/TagLibSharp2/Image/Endian.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// Copyright (c) 2025-2026 Stephen Shaw and contributors
// Licensed under the MIT License. See LICENSE file in the project root for full license information.

using System.Buffers.Binary;

namespace TagLibSharp2.Image;

/// <summary>
/// Reads and writes unsigned integers in either byte order over spans: the one byte-order helper of the image
/// code (TIFF and Exif "II"/"MM", the MPF index, PNG chunk fields, BMP headers).
/// </summary>
static class Endian
{
public static int U16 (ReadOnlySpan<byte> data, int at, bool le) =>
le ? BinaryPrimitives.ReadUInt16LittleEndian (data.Slice (at)) : BinaryPrimitives.ReadUInt16BigEndian (data.Slice (at));

public static long U32 (ReadOnlySpan<byte> data, int at, bool le) =>
le ? BinaryPrimitives.ReadUInt32LittleEndian (data.Slice (at)) : BinaryPrimitives.ReadUInt32BigEndian (data.Slice (at));

public static int I32 (ReadOnlySpan<byte> data, int at, bool le) =>
le ? BinaryPrimitives.ReadInt32LittleEndian (data.Slice (at)) : BinaryPrimitives.ReadInt32BigEndian (data.Slice (at));

/// <summary>False outside the data, or for a value above <see cref="long.MaxValue"/>.</summary>
public static bool TryU64 (ReadOnlySpan<byte> data, int at, bool le, out long value)
{
value = 0;
if (at < 0 || at > data.Length - 8)
return false;
var raw = le ? BinaryPrimitives.ReadUInt64LittleEndian (data.Slice (at)) : BinaryPrimitives.ReadUInt64BigEndian (data.Slice (at));
if (raw > long.MaxValue)
return false;
value = (long)raw;
return true;
}

public static void WriteU16 (Span<byte> data, int at, int value, bool le)
{
if (le)
BinaryPrimitives.WriteUInt16LittleEndian (data.Slice (at), (ushort)value);
else
BinaryPrimitives.WriteUInt16BigEndian (data.Slice (at), (ushort)value);
}

public static void WriteU32 (Span<byte> data, int at, long value, bool le)
{
if (le)
BinaryPrimitives.WriteUInt32LittleEndian (data.Slice (at), (uint)value);
else
BinaryPrimitives.WriteUInt32BigEndian (data.Slice (at), (uint)value);
}
}
Loading
Loading