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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ 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/ID3v2), FLAC, Ogg Vorbis, Ogg Opus, Ogg FLAC, WAV (RIFF INFO/ID3v2), AIFF (ID3v2), MP4/M4A (AAC/ALAC), ASF/WMA, DSF (DSD), DFF (DSDIFF), WavPack, Monkey's Audio (.ape), Musepack
- Matroska/WebM (`.mkv`, `.mka`, `.mks`, `.mk3d`, `.webm`): reading only — tags, duration, audio and video properties, and pictures. Saving the file is not supported yet.
- Matroska/WebM (`.mkv`, `.mka`, `.mks`, `.mk3d`, `.webm`): tags, duration, audio and video properties, and pictures. Tag values can be saved. Picture attachments are read but not rewritten.

## Format Support Matrix

Expand Down
4 changes: 2 additions & 2 deletions docs/MIGRATION-FROM-TAGLIB.md
Original file line number Diff line number Diff line change
Expand Up @@ -464,7 +464,7 @@ async Task<string?> GetTitleAsync(string path, CancellationToken ct = default)
TagLibSharp2 is under active development. These TagLib# features are planned but not yet implemented:

- **Formats**: Speex, TrueAudio, Tracker formats (MOD/S3M/IT/XM)
- **Features**: Matroska/WebM file save (reading tags is supported), MPEG-4 video files
- **Features**: Matroska/WebM picture attachments and chapters are not written (tag values are), MPEG-4 video files

## Format-Specific Examples

Expand Down Expand Up @@ -643,7 +643,7 @@ if (result.IsSuccess)

TagLibSharp2 includes several features not available in TagLib#:

- **Automatic format detection**: `MediaFile.Read()` auto-detects 16 formats: MP3, FLAC, Ogg Vorbis, Ogg Opus, Ogg FLAC, WAV, AIFF, MP4/M4A, ASF/WMA, DSF, DFF, WavPack, Monkey's Audio, Musepack, and Matroska/WebM (reading)
- **Automatic format detection**: `MediaFile.Read()` auto-detects 16 formats: MP3, FLAC, Ogg Vorbis, Ogg Opus, Ogg FLAC, WAV, AIFF, MP4/M4A, ASF/WMA, DSF, DFF, WavPack, Monkey's Audio, Musepack, and Matroska/WebM
- **DSD audio support**: Native DSF and DFF format support for high-resolution DSD audio
- **Lossless format breadth**: WavPack and Monkey's Audio support with APE tag handling
- **Async I/O**: Full async support throughout the API with cancellation token support
Expand Down
6 changes: 3 additions & 3 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: January 2026 (v0.5.0 release)
> Status: Production ready - 15 formats read and write, Matroska/WebM reading, polish phase
> Status: Production ready - 16 formats read and write tags, polish phase

## Executive Summary

TagLibSharp2 currently supports **15 formats** with read and write, plus Matroska/WebM reading. The library has mature read/write capabilities for all major formats. Remaining gaps are niche formats: Speex (obsolete), TrueAudio (niche), and tracker formats (demoscene). Matroska/WebM file save is still open.
TagLibSharp2 currently supports **16 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). Matroska/WebM saves tag values; it does not rewrite attachments or chapters.

---

Expand All @@ -28,7 +28,7 @@ TagLibSharp2 currently supports **15 formats** with read and write, plus Matrosk
| DFF | P1 | ✅ | ✅ | ✅ | - | Recently added |
| WavPack | P1 | ✅ | ✅ | ✅ | - | Recently added |
| Musepack | P1 | ✅ | ✅ | ✅ | - | SV7 and SV8 support |
| Matroska/WebM | P2 | partial | ✅ | — | - | Tags, pictures, duration, and track properties. File save is still open |
| Matroska/WebM | P2 | ✅ | ✅ | ✅ | - | Tag values are saved. Attachments and chapters are preserved, not rewritten |
| Ogg FLAC | P1 | ✅ | ✅ | ✅ | - | Recently added |
| Speex | P1 | ❌ | ❌ | ❌ | LOW | Uses Vorbis Comment |
| TrueAudio | P2 | ❌ | ❌ | ❌ | LOW | Uses ID3v2 |
Expand Down
19 changes: 14 additions & 5 deletions src/TagLibSharp2/Core/MediaFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ namespace TagLibSharp2.Core;
/// <item>DSF (DSD Stream File - ID3v2 metadata)</item>
/// <item>DFF/DSDIFF (DSD Interchange File Format - ID3v2 metadata)</item>
/// <item>WMA/ASF (Windows Media Audio - ASF extended content)</item>
/// <item>Matroska/WebM (Matroska tags; reading)</item>
/// <item>Matroska/WebM (Matroska tags)</item>
/// </list>
///
/// <para><b>Reading and Modifying Tags</b></para>
Expand Down Expand Up @@ -152,7 +152,7 @@ public static MediaFileResult Read (string path, IFileSystem? fileSystem = null)
if (!readResult.IsSuccess)
return MediaFileResult.Failure (readResult.Error!);

return ReadFromData (readResult.Data!.Value, path);
return ReadCore (readResult.Data!.Value, path, fileSystem, rememberPath: true);
}

/// <summary>
Expand All @@ -179,7 +179,7 @@ public static async Task<MediaFileResult> ReadAsync (
if (!readResult.IsSuccess)
return MediaFileResult.Failure (readResult.Error!);

return ReadFromData (readResult.Data!.Value, path);
return ReadCore (readResult.Data!.Value, path, fileSystem, rememberPath: true);
}

/// <summary>
Expand All @@ -188,11 +188,14 @@ public static async Task<MediaFileResult> ReadAsync (
/// <param name="data">The file data.</param>
/// <param name="pathHint">Optional file path hint for extension-based detection.</param>
/// <returns>A result containing the parsed file or an error.</returns>
public static MediaFileResult ReadFromData (ReadOnlyMemory<byte> data, string? pathHint = null)
public static MediaFileResult ReadFromData (ReadOnlyMemory<byte> data, string? pathHint = null) =>
ReadCore (data, pathHint, sourceFileSystem: null, rememberPath: false);

static MediaFileResult ReadCore (ReadOnlyMemory<byte> data, string? pathHint, IFileSystem? sourceFileSystem, bool rememberPath)
{
var format = DetectFormat (data.Span, pathHint);

return format switch {
var result = format switch {
MediaFormat.Flac => OpenFlac (data),
MediaFormat.OggVorbis => OpenOggVorbis (data),
MediaFormat.Opus => OpenOpus (data),
Expand All @@ -210,6 +213,12 @@ public static MediaFileResult ReadFromData (ReadOnlyMemory<byte> data, string? p
MediaFormat.Matroska => OpenMatroska (data),
_ => MediaFileResult.Failure ($"Unknown or unsupported file format{(pathHint is not null ? $": {pathHint}" : "")}")
};

// ReadFromData's path is only an extension hint. A path read can save Matroska back to that file.
if (rememberPath && result.IsSuccess && pathHint is not null && result.File is MatroskaFile matroska)
matroska.SetSourcePath (pathHint, sourceFileSystem);

return result;
}

/// <summary>
Expand Down
213 changes: 199 additions & 14 deletions src/TagLibSharp2/Matroska/MatroskaFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,11 +52,12 @@ namespace TagLibSharp2.Matroska;

/// <summary>
/// A Matroska or WebM file. Reading maps <c>Tags</c> onto <see cref="Tag"/>.
/// Rewriting the container is not implemented: a short or shifted element corrupts the file.
/// Saving splices <see cref="MatroskaTag.Render"/> into the first <c>Segment</c>.
/// </summary>
public sealed class MatroskaFile : IMediaFile
{
const ulong DefaultTimestampScale = 1_000_000;
IFileSystem? _sourceFileSystem;

MatroskaFile (MatroskaTag tag, TimeSpan? duration, TrackLayout layout)
{
Expand Down Expand Up @@ -159,7 +160,7 @@ public static MatroskaFileReadResult Read (ReadOnlySpan<byte> data)
var scale = DefaultTimestampScale;
double? durationTicks = null;
var layout = new TrackLayout ();
var segmentEnd = segment.UnknownSize ? data.Length : segment.End;
var segmentEnd = PayloadEnd (data, segment);
offset = segment.DataOffset;
while (offset < segmentEnd) {
// Padding and a short illegal ID are skipped. A live segment can put
Expand Down Expand Up @@ -202,12 +203,125 @@ public static bool TryRead (ReadOnlySpan<byte> data, out MatroskaFile? file)
return result.IsSuccess;
}

/// <summary>Writes the rendered <c>Tags</c> element into a copy of <paramref name="originalData"/>.</summary>
/// <returns>The rewritten file, or empty when the container cannot be bounded.</returns>
public BinaryData Render (ReadOnlySpan<byte> originalData) =>
MatroskaRewrite.TryRewrite (originalData, Tag, out var rewritten, out _)
? new BinaryData (rewritten)
: BinaryData.Empty;

/// <summary>Saves tags into <paramref name="path"/> using <paramref name="originalData"/> as the container.</summary>
public FileWriteResult SaveToFile (string path, ReadOnlySpan<byte> originalData, IFileSystem? fileSystem = null)
{
if (!MatroskaRewrite.TryRewrite (originalData, Tag, out var rewritten, out var error))
return FileWriteResult.Failure (error);

return AtomicFileWriter.Write (path, rewritten, fileSystem);
}

/// <summary>Saves tags into <paramref name="path"/>, re-reading the container from <see cref="SourcePath"/>.</summary>
public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null)
{
if (string.IsNullOrEmpty (SourcePath))
return FileWriteResult.Failure ("No source path available. File was not read from disk.");

var fs = fileSystem ?? _sourceFileSystem;
var readResult = FileHelper.SafeReadAllBytes (SourcePath!, fs);
if (!readResult.IsSuccess)
return FileWriteResult.Failure ("Failed to re-read source file: " + readResult.Error);

return SaveToFile (path, readResult.Data!.Value.Span, fileSystem);
}

/// <summary>Saves tags back to <see cref="SourcePath"/>.</summary>
public FileWriteResult SaveToFile (IFileSystem? fileSystem = null)
{
if (string.IsNullOrEmpty (SourcePath))
return FileWriteResult.Failure ("No source path available. File was not read from disk.");

return SaveToFile (SourcePath!, fileSystem);
}

/// <summary>Saves tags into <paramref name="path"/> using <paramref name="originalData"/> as the container.</summary>
public Task<FileWriteResult> SaveToFileAsync (
string path,
ReadOnlyMemory<byte> originalData,
IFileSystem? fileSystem = null,
CancellationToken cancellationToken = default)
{
if (!MatroskaRewrite.TryRewrite (originalData.Span, Tag, out var rewritten, out var error))
return Task.FromResult (FileWriteResult.Failure (error));

return AtomicFileWriter.WriteAsync (path, rewritten, fileSystem, cancellationToken);
}

/// <summary>Saves tags into <paramref name="path"/>, re-reading the container from <see cref="SourcePath"/>.</summary>
public async Task<FileWriteResult> SaveToFileAsync (
string path,
IFileSystem? fileSystem = null,
CancellationToken cancellationToken = default)
{
if (string.IsNullOrEmpty (SourcePath))
return FileWriteResult.Failure ("No source path available. File was not read from disk.");

var fs = fileSystem ?? _sourceFileSystem;
var readResult = await FileHelper.SafeReadAllBytesAsync (SourcePath!, fs, cancellationToken).ConfigureAwait (false);
if (!readResult.IsSuccess)
return FileWriteResult.Failure ("Failed to re-read source file: " + readResult.Error);

return await SaveToFileAsync (path, readResult.Data!.Value, fileSystem, cancellationToken).ConfigureAwait (false);
}

/// <summary>Saves tags back to <see cref="SourcePath"/>.</summary>
public Task<FileWriteResult> SaveToFileAsync (
IFileSystem? fileSystem = null,
CancellationToken cancellationToken = default)
{
if (string.IsNullOrEmpty (SourcePath))
return Task.FromResult (FileWriteResult.Failure ("No source path available. File was not read from disk."));

return SaveToFileAsync (SourcePath!, fileSystem, cancellationToken);
}

/// <summary>Reads a Matroska or WebM file from disk.</summary>
public static MatroskaFileReadResult ReadFromFile (string path, IFileSystem? fileSystem = null)
{
var readResult = FileHelper.SafeReadAllBytes (path, fileSystem);
if (!readResult.IsSuccess)
return MatroskaFileReadResult.Failure (readResult.Error!);

var result = Read (readResult.Data!.Value.Span);
if (result.IsSuccess)
result.File!.SetSourcePath (path, fileSystem);
return result;
}

/// <summary>Reads a Matroska or WebM file from disk.</summary>
public static async Task<MatroskaFileReadResult> ReadFromFileAsync (
string path,
IFileSystem? fileSystem = null,
CancellationToken cancellationToken = default)
{
var readResult = await FileHelper.SafeReadAllBytesAsync (path, fileSystem, cancellationToken).ConfigureAwait (false);
if (!readResult.IsSuccess)
return MatroskaFileReadResult.Failure (readResult.Error!);

var result = Read (readResult.Data!.Value.Span);
if (result.IsSuccess)
result.File!.SetSourcePath (path, fileSystem);
return result;
}

/// <inheritdoc/>
public void Dispose ()
{
}

internal void SetSourcePath (string? path) => SourcePath = path;
internal void SetSourcePath (string? path, IFileSystem? fileSystem = null)
{
SourcePath = path;
_sourceFileSystem = fileSystem;
}

static string? ReadDocType (ReadOnlySpan<byte> data, EbmlElement header)
{
Expand Down Expand Up @@ -501,8 +615,13 @@ static void ReadTags (ReadOnlySpan<byte> data, ReadOnlySpan<byte> body, Matroska
while (offset < body.Length) {
if (!EbmlReader.TryRead (body, offset, body.Length, out var element))
break;
if (element.Id == MatroskaIds.Tag && !element.UnknownSize)
tag.AddBlock (ReadTag (body.Slice (element.DataOffset, (int)element.DataLength)));
if (element.Id == MatroskaIds.Tag && !element.UnknownSize) {
var raw = body.Slice (element.Position, element.End - element.Position).ToArray ();
var block = ReadTag (body.Slice (element.DataOffset, (int)element.DataLength));
if (!block.IsFileLevel)
block.KeepOriginal (raw);
tag.AddBlock (block);
}
if (element.UnknownSize)
break;
offset = element.End;
Expand Down Expand Up @@ -544,14 +663,18 @@ static void ReadTargets (ReadOnlySpan<byte> body, TagBlock block)
var payload = body.Slice (element.DataOffset, (int)element.DataLength);
if (element.Id == MatroskaIds.TargetTypeValue && payload.Length > 0)
block.Level = EbmlReader.ReadUInt (payload);
else if (element.Id == MatroskaIds.TagChapterUid)
NoteTargetUid (payload, ref chapterAll, ref chapterSpecific);
else if (element.Id == MatroskaIds.TagAttachmentUid)
NoteTargetUid (payload, ref attachmentAll, ref attachmentSpecific);
else if (element.Id == MatroskaIds.TagTrackUid)
NoteTargetUid (payload, ref trackAll, ref trackSpecific);
else if (element.Id == MatroskaIds.TagEditionUid)
NoteTargetUid (payload, ref editionAll, ref editionSpecific);
else {
block.KeepTarget (body.Slice (element.Position, element.End - element.Position).ToArray ());
if (element.Id == MatroskaIds.TagChapterUid)
NoteTargetUid (payload, ref chapterAll, ref chapterSpecific);
else if (element.Id == MatroskaIds.TagAttachmentUid)
NoteTargetUid (payload, ref attachmentAll, ref attachmentSpecific);
else if (element.Id == MatroskaIds.TagTrackUid)
NoteTargetUid (payload, ref trackAll, ref trackSpecific);
else if (element.Id == MatroskaIds.TagEditionUid)
NoteTargetUid (payload, ref editionAll, ref editionSpecific);
}

offset = element.End;
}

Expand All @@ -575,6 +698,9 @@ static SimpleTag ReadSimpleTag (ReadOnlySpan<byte> body)
{
var name = string.Empty;
string? text = null;
string? language = null;
string? languageBcp47 = null;
byte[]? binary = null;
var isDefault = true;
var children = new List<SimpleTag> ();
var offset = 0;
Expand All @@ -586,19 +712,78 @@ static SimpleTag ReadSimpleTag (ReadOnlySpan<byte> body)
name = EbmlReader.ReadString (payload);
else if (element.Id == MatroskaIds.TagString)
text = EbmlReader.ReadString (payload);
else if (element.Id == MatroskaIds.TagLanguage)
language = EbmlReader.ReadString (payload);
else if (element.Id == MatroskaIds.TagLanguageBcp47)
languageBcp47 = EbmlReader.ReadString (payload);
else if (element.Id == MatroskaIds.TagBinary)
binary = payload.ToArray ();
else if (element.Id == MatroskaIds.TagDefault || element.Id == MatroskaIds.TagDefaultBogus)
isDefault = payload.Length == 0 || EbmlReader.ReadUInt (payload) != 0;
else if (element.Id == MatroskaIds.SimpleTag)
children.Add (ReadSimpleTag (payload));
offset = element.End;
}

var tag = new SimpleTag (name, text, isDefault);
var tag = new SimpleTag (name, text, isDefault) {
Language = language,
LanguageBcp47 = languageBcp47,
Binary = binary
};
foreach (var child in children)
tag.Children.Add (child);
return tag;
}

/// <summary>
/// An unknown-size Segment ends at the next EBML header or Segment.
/// A known-size Segment ends at the size it declares. RFC 8794.
/// </summary>
internal static int PayloadEnd (ReadOnlySpan<byte> data, EbmlElement segment) =>
segment.UnknownSize ? EndAtNextTopLevel (data, segment.DataOffset) : segment.End;

static int EndAtNextTopLevel (ReadOnlySpan<byte> data, int offset)
{
while (offset < data.Length) {
if (!EbmlReader.TryRead (data, offset, data.Length, out var element))
return data.Length;
if (element.Id == MatroskaIds.Ebml || element.Id == MatroskaIds.Segment)
return element.Position;
if (element.UnknownSize) {
if (!TrySkipUnknown (data, element.DataOffset, out var next))
return data.Length;
offset = next;
continue;
}

offset = element.End;
}

return data.Length;
}

static bool TrySkipUnknown (ReadOnlySpan<byte> data, int offset, out int next)
{
next = offset;
while (offset < data.Length) {
if (!EbmlReader.TryRead (data, offset, data.Length, out var element))
return false;
if (MatroskaIds.IsSegmentChild (element.Id)
|| element.Id == MatroskaIds.Ebml
|| element.Id == MatroskaIds.Segment) {
next = element.Position;
return true;
}

if (element.UnknownSize)
return false;
offset = element.End;
}

next = data.Length;
return true;
}

static ReadOnlySpan<byte> Range (ReadOnlySpan<byte> data, EbmlElement element, int parentEnd)
{
if (!element.UnknownSize)
Expand Down
Loading
Loading