From 4c73131575df1fc056d28862c517407504a5d01b Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Mon, 16 Nov 2026 19:13:14 -0700 Subject: [PATCH 1/4] feat: Save Matroska and WebM tags --- README.md | 2 +- docs/MIGRATION-FROM-TAGLIB.md | 4 +- docs/ROADMAP.md | 6 +- src/TagLibSharp2/Core/MediaFile.cs | 19 +- src/TagLibSharp2/Matroska/MatroskaFile.cs | 213 +++- src/TagLibSharp2/Matroska/MatroskaIds.cs | 9 + src/TagLibSharp2/Matroska/MatroskaRewrite.cs | 939 ++++++++++++++++++ src/TagLibSharp2/Matroska/MatroskaTag.cs | 43 +- src/TagLibSharp2/TagLibSharp2.csproj | 2 +- .../Matroska/MatroskaFileTests.cs | 2 +- .../Matroska/MatroskaSaveTests.cs | 703 +++++++++++++ .../TagLibSharp2.PublicApi.verified.txt | 9 + 12 files changed, 1923 insertions(+), 28 deletions(-) create mode 100644 src/TagLibSharp2/Matroska/MatroskaRewrite.cs create mode 100644 tests/TagLibSharp2.Tests/Matroska/MatroskaSaveTests.cs diff --git a/README.md b/README.md index d3da56b..b3bffc3 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/docs/MIGRATION-FROM-TAGLIB.md b/docs/MIGRATION-FROM-TAGLIB.md index b4dee60..cd31a27 100644 --- a/docs/MIGRATION-FROM-TAGLIB.md +++ b/docs/MIGRATION-FROM-TAGLIB.md @@ -464,7 +464,7 @@ async Task 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 @@ -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 diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 6255f20..e36cfaa 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -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. --- @@ -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 | diff --git a/src/TagLibSharp2/Core/MediaFile.cs b/src/TagLibSharp2/Core/MediaFile.cs index c61dd15..7c6b85f 100644 --- a/src/TagLibSharp2/Core/MediaFile.cs +++ b/src/TagLibSharp2/Core/MediaFile.cs @@ -36,7 +36,7 @@ namespace TagLibSharp2.Core; /// DSF (DSD Stream File - ID3v2 metadata) /// DFF/DSDIFF (DSD Interchange File Format - ID3v2 metadata) /// WMA/ASF (Windows Media Audio - ASF extended content) -/// Matroska/WebM (Matroska tags; reading) +/// Matroska/WebM (Matroska tags) /// /// /// Reading and Modifying Tags @@ -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); } /// @@ -179,7 +179,7 @@ public static async Task ReadAsync ( if (!readResult.IsSuccess) return MediaFileResult.Failure (readResult.Error!); - return ReadFromData (readResult.Data!.Value, path); + return ReadCore (readResult.Data!.Value, path, fileSystem, rememberPath: true); } /// @@ -188,11 +188,14 @@ public static async Task ReadAsync ( /// The file data. /// Optional file path hint for extension-based detection. /// A result containing the parsed file or an error. - public static MediaFileResult ReadFromData (ReadOnlyMemory data, string? pathHint = null) + public static MediaFileResult ReadFromData (ReadOnlyMemory data, string? pathHint = null) => + ReadCore (data, pathHint, sourceFileSystem: null, rememberPath: false); + + static MediaFileResult ReadCore (ReadOnlyMemory 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), @@ -210,6 +213,12 @@ public static MediaFileResult ReadFromData (ReadOnlyMemory 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; } /// diff --git a/src/TagLibSharp2/Matroska/MatroskaFile.cs b/src/TagLibSharp2/Matroska/MatroskaFile.cs index 589cccf..c07c761 100644 --- a/src/TagLibSharp2/Matroska/MatroskaFile.cs +++ b/src/TagLibSharp2/Matroska/MatroskaFile.cs @@ -52,11 +52,12 @@ namespace TagLibSharp2.Matroska; /// /// A Matroska or WebM file. Reading maps Tags onto . -/// Rewriting the container is not implemented: a short or shifted element corrupts the file. +/// Saving splices into the first Segment. /// public sealed class MatroskaFile : IMediaFile { const ulong DefaultTimestampScale = 1_000_000; + IFileSystem? _sourceFileSystem; MatroskaFile (MatroskaTag tag, TimeSpan? duration, TrackLayout layout) { @@ -159,7 +160,7 @@ public static MatroskaFileReadResult Read (ReadOnlySpan 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 @@ -202,12 +203,125 @@ public static bool TryRead (ReadOnlySpan data, out MatroskaFile? file) return result.IsSuccess; } + /// Writes the rendered Tags element into a copy of . + /// The rewritten file, or empty when the container cannot be bounded. + public BinaryData Render (ReadOnlySpan originalData) => + MatroskaRewrite.TryRewrite (originalData, Tag, out var rewritten, out _) + ? new BinaryData (rewritten) + : BinaryData.Empty; + + /// Saves tags into using as the container. + public FileWriteResult SaveToFile (string path, ReadOnlySpan 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); + } + + /// Saves tags into , re-reading the container from . + 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); + } + + /// Saves tags back to . + 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); + } + + /// Saves tags into using as the container. + public Task SaveToFileAsync ( + string path, + ReadOnlyMemory 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); + } + + /// Saves tags into , re-reading the container from . + public async Task 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); + } + + /// Saves tags back to . + public Task 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); + } + + /// Reads a Matroska or WebM file from disk. + 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; + } + + /// Reads a Matroska or WebM file from disk. + public static async Task 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; + } + /// 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 data, EbmlElement header) { @@ -501,8 +615,13 @@ static void ReadTags (ReadOnlySpan data, ReadOnlySpan 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; @@ -544,14 +663,18 @@ static void ReadTargets (ReadOnlySpan 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; } @@ -575,6 +698,9 @@ static SimpleTag ReadSimpleTag (ReadOnlySpan body) { var name = string.Empty; string? text = null; + string? language = null; + string? languageBcp47 = null; + byte[]? binary = null; var isDefault = true; var children = new List (); var offset = 0; @@ -586,6 +712,12 @@ static SimpleTag ReadSimpleTag (ReadOnlySpan 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) @@ -593,12 +725,65 @@ static SimpleTag ReadSimpleTag (ReadOnlySpan body) 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; } + /// + /// An unknown-size Segment ends at the next EBML header or Segment. + /// A known-size Segment ends at the size it declares. RFC 8794. + /// + internal static int PayloadEnd (ReadOnlySpan data, EbmlElement segment) => + segment.UnknownSize ? EndAtNextTopLevel (data, segment.DataOffset) : segment.End; + + static int EndAtNextTopLevel (ReadOnlySpan 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 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 Range (ReadOnlySpan data, EbmlElement element, int parentEnd) { if (!element.UnknownSize) diff --git a/src/TagLibSharp2/Matroska/MatroskaIds.cs b/src/TagLibSharp2/Matroska/MatroskaIds.cs index 483b57f..cb6ee43 100644 --- a/src/TagLibSharp2/Matroska/MatroskaIds.cs +++ b/src/TagLibSharp2/Matroska/MatroskaIds.cs @@ -42,6 +42,12 @@ static class MatroskaIds public const ulong FileData = 0x465C; public const ulong Cluster = 0x1F43B675; public const ulong Cues = 0x1C53BB6B; + public const ulong Seek = 0x4DBB; + public const ulong SeekId = 0x53AB; + public const ulong SeekPosition = 0x53AC; + public const ulong CuePoint = 0xBB; + public const ulong CueTrackPositions = 0xB7; + public const ulong CueClusterPosition = 0xF1; public const ulong Attachments = 0x1941A469; public const ulong Chapters = 0x1043A770; public const ulong Tags = 0x1254C367; @@ -54,8 +60,11 @@ static class MatroskaIds public const ulong TagAttachmentUid = 0x63C6; public const ulong SimpleTag = 0x67C8; public const ulong TagName = 0x45A3; + public const ulong TagLanguage = 0x447A; + public const ulong TagLanguageBcp47 = 0x447B; public const ulong TagDefault = 0x4484; public const ulong TagDefaultBogus = 0x44B4; + public const ulong TagBinary = 0x4485; public const ulong TagString = 0x4487; public static bool IsSegmentChild (ulong id) => diff --git a/src/TagLibSharp2/Matroska/MatroskaRewrite.cs b/src/TagLibSharp2/Matroska/MatroskaRewrite.cs new file mode 100644 index 0000000..e82db8e --- /dev/null +++ b/src/TagLibSharp2/Matroska/MatroskaRewrite.cs @@ -0,0 +1,939 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Core; + +namespace TagLibSharp2.Matroska; + +/// +/// Splices a rendered Tags element into the first Segment. +/// An unknown-size element is copied only when its end is a parsed sibling or the parent end. +/// Bytes that do not parse are not scanned once a real element has been seen. +/// +static class MatroskaRewrite +{ + public static bool TryRewrite (ReadOnlySpan data, MatroskaTag tag, out byte[] rewritten, out string error) + { + rewritten = []; + if (!TryParse (data, out var layout, out error) || layout is null) + return false; + + var tags = tag.Render ().ToArray (); + var plan = PlanEdit (layout.Pieces, tags); + if (!TryBuild (data, layout, plan, out var body, out var seekHeads, out var cues, out var tagsOffset, out error)) + return false; + if (tags.Length > 0 && tagsOffset != plan.TagsOffset) { + error = "Matroska tags could not be placed"; + return false; + } + + if (!TryPatch (body, seekHeads, cues, plan, out error)) + return false; + + var originalLength = layout.SegmentEnd - layout.DataOffset; + if (originalLength != body.Length || !data.Slice (layout.DataOffset, originalLength).SequenceEqual (body)) + UpdateLeadingCrc (body); + + rewritten = Assemble (data, layout, body, out error); + return rewritten.Length > 0 && error.Length == 0; + } + + sealed class Layout + { + public Layout (int segmentPosition, int idWidth, int sizeWidth, bool unknownSize, int dataOffset, int segmentEnd, List pieces) + { + SegmentPosition = segmentPosition; + IdWidth = idWidth; + SizeWidth = sizeWidth; + UnknownSize = unknownSize; + DataOffset = dataOffset; + SegmentEnd = segmentEnd; + Pieces = pieces; + } + + public int SegmentPosition { get; } + + public int IdWidth { get; } + + public int SizeWidth { get; } + + public bool UnknownSize { get; } + + public int DataOffset { get; } + + public int SegmentEnd { get; } + + public List Pieces { get; } + } + + readonly struct Piece + { + public Piece (ulong id, int offset, int length, bool unknownSize) + { + Id = id; + Offset = offset; + Length = length; + UnknownSize = unknownSize; + } + + public ulong Id { get; } + + public int Offset { get; } + + public int Length { get; } + + public bool UnknownSize { get; } + } + + sealed class Plan + { + public byte[] Tags { get; set; } = []; + + public int ReplaceStart { get; set; } = -1; + + public int ReplaceEnd { get; set; } = -1; + + public byte[]? Replacement { get; set; } + + public bool VoidTags { get; set; } + + public bool Append { get; set; } + + public int InsertBefore { get; set; } = -1; + + public int TagsOffset { get; set; } = -1; + + public int ShiftFrom { get; set; } = int.MaxValue; + + public int Delta { get; set; } + + public bool MustRetarget { get; set; } + + public bool ShouldAdd { get; set; } + } + + static Plan PlanEdit (List pieces, byte[] tags) + { + var plan = new Plan { Tags = tags }; + var tagIndexes = new List (); + for (var i = 0; i < pieces.Count; i++) { + if (pieces[i].Id == MatroskaIds.Tags) + tagIndexes.Add (i); + } + + if (tags.Length == 0) { + plan.VoidTags = tagIndexes.Count > 0; + plan.MustRetarget = tagIndexes.Count > 0; + return plan; + } + + plan.ShouldAdd = tagIndexes.Count == 0; + if (TryFindFit (pieces, tags, out var start, out var end, out var fitted)) { + plan.ReplaceStart = start; + plan.ReplaceEnd = end; + plan.Replacement = fitted; + plan.TagsOffset = OffsetOf (pieces, start); + plan.VoidTags = true; + plan.MustRetarget = TagMoved (pieces, tagIndexes, plan.TagsOffset); + return plan; + } + + plan.VoidTags = true; + var last = pieces.Count - 1; + if (last >= 0 && pieces[last].Id == MatroskaIds.Tags) { + plan.ReplaceStart = last; + plan.ReplaceEnd = last; + plan.Replacement = tags; + plan.TagsOffset = OffsetOf (pieces, last); + plan.MustRetarget = TagMoved (pieces, tagIndexes, plan.TagsOffset); + return plan; + } + + if (last >= 0 && pieces[last].UnknownSize) { + plan.InsertBefore = last; + plan.TagsOffset = OffsetOf (pieces, last); + plan.ShiftFrom = plan.TagsOffset; + plan.Delta = tags.Length; + plan.MustRetarget = true; + return plan; + } + + plan.Append = true; + plan.TagsOffset = OffsetOf (pieces, pieces.Count); + plan.MustRetarget = tagIndexes.Count > 0; + return plan; + } + + static bool TagMoved (List pieces, List tagIndexes, int tagsOffset) + { + foreach (var index in tagIndexes) { + if (OffsetOf (pieces, index) != tagsOffset) + return true; + } + + return false; + } + + static bool TryBuild ( + ReadOnlySpan data, + Layout layout, + Plan plan, + out byte[] body, + out List<(int Start, int End)> seekHeads, + out List<(int Start, int End)> cues, + out int tagsOffset, + out string error) + { + body = []; + seekHeads = new List<(int, int)> (); + cues = new List<(int, int)> (); + tagsOffset = -1; + error = ""; + var pieces = layout.Pieces; + if (plan.Replacement is not null && plan.ReplaceEnd != pieces.Count - 1) { + var region = 0; + for (var index = plan.ReplaceStart; index <= plan.ReplaceEnd; index++) + region += pieces[index].Length; + if (plan.Replacement.Length != region) { + error = "Matroska tags could not be placed"; + return false; + } + } + + using var builder = new BinaryDataBuilder (Math.Max (16, data.Length)); + var i = 0; + while (i < pieces.Count) { + if (i == plan.ReplaceStart && plan.Replacement is not null) { + tagsOffset = builder.Length; + builder.Add (plan.Replacement); + i = plan.ReplaceEnd + 1; + continue; + } + + var piece = pieces[i]; + if (plan.VoidTags && piece.Id == MatroskaIds.Tags) { + if (!TryMakeVoid (piece.Length, out var hole)) { + error = "Matroska tags could not be placed"; + return false; + } + + builder.Add (hole); + i++; + continue; + } + + if (i == plan.InsertBefore) { + tagsOffset = builder.Length; + builder.Add (plan.Tags); + } + + var at = builder.Length; + builder.Add (data.Slice (piece.Offset, piece.Length)); + if (piece.Id == MatroskaIds.SeekHead) + seekHeads.Add ((at, at + piece.Length)); + else if (piece.Id == MatroskaIds.Cues) + cues.Add ((at, at + piece.Length)); + i++; + } + + if (plan.Append) { + tagsOffset = builder.Length; + builder.Add (plan.Tags); + } + + body = builder.ToArray (); + return true; + } + + static bool TryPatch ( + byte[] body, + List<(int Start, int End)> seekHeads, + List<(int Start, int End)> cues, + Plan plan, + out string error) + { + error = ""; + var strict = plan.MustRetarget || plan.Delta != 0; + if (strict || plan.ShouldAdd) { + foreach (var seekHead in seekHeads) { + if (!TryPatchSeekHead (body, seekHead.Start, seekHead.End, plan, strict, out error)) + return false; + } + } + + if (plan.Delta == 0) + return true; + + foreach (var cue in cues) { + if (!TryPatchCues (body, cue.Start, cue.End, plan, out error)) + return false; + } + + return true; + } + + static bool TryPatchSeekHead (byte[] body, int start, int end, Plan plan, bool strict, out string error) + { + error = ""; + if (!EbmlReader.TryRead (body, start, Math.Min (end, body.Length), out var seekHead) + || seekHead.UnknownSize + || seekHead.Position != start) { + error = "Matroska SeekHead cannot be bounded"; + return !strict; + } + + var children = new List (); + var offset = seekHead.DataOffset; + while (offset < seekHead.End) { + if (!EbmlReader.TryRead (body, offset, seekHead.End, out var child) || child.UnknownSize) { + error = "Matroska SeekHead cannot be bounded"; + return !strict; + } + + children.Add (child); + offset = child.End; + } + + if (offset != seekHead.End) { + error = "Matroska SeekHead cannot be bounded"; + return !strict; + } + + var changed = false; + var referenced = false; + foreach (var child in children) { + if (child.Id != MatroskaIds.Seek) + continue; + if (!TryPatchSeek (body, child, plan, ref changed, ref referenced)) { + error = "Matroska SeekHead cannot be updated"; + return false; + } + } + + if (plan.TagsOffset >= 0 && !referenced && TryAddSeek (body, seekHead, (ulong)plan.TagsOffset)) { + changed = true; + referenced = true; + } + + if (changed) + UpdateElementCrc (body, seekHead.Position, seekHead.End); + return true; + } + + static bool TryPatchSeek (byte[] body, EbmlElement seek, Plan plan, ref bool changed, ref bool referenced) + { + var strict = plan.MustRetarget || plan.Delta != 0; + if (!TryReadSeek (body, seek, out var id, out var position, out var positionElement)) + return strict ? TryDropSeek (body, seek, ref changed) : true; + + var isTags = id == MatroskaIds.Tags; + ulong desired; + if (isTags) { + if (plan.TagsOffset < 0) + return TryDropSeek (body, seek, ref changed); + desired = (ulong)plan.TagsOffset; + } else if (plan.Delta != 0 && position >= (ulong)plan.ShiftFrom) { + desired = position + (ulong)plan.Delta; + if (desired < position) + return false; + } else + return true; + + if (desired == position) { + if (isTags) + referenced = true; + return true; + } + + if (positionElement.DataLength is > 0 and <= 8 + && TryWriteUnsigned (body, positionElement.DataOffset, (int)positionElement.DataLength, desired)) { + changed = true; + if (isTags) + referenced = true; + return true; + } + + var rebuilt = MakeSeek (isTags ? MatroskaIds.Tags : id, desired); + var total = seek.End - seek.Position; + if (TryFit (rebuilt, total, out var fitted)) { + fitted.CopyTo (body.AsSpan (seek.Position)); + changed = true; + if (isTags) + referenced = true; + return true; + } + + return TryDropSeek (body, seek, ref changed); + } + + static bool TryReadSeek (byte[] body, EbmlElement seek, out ulong id, out ulong position, out EbmlElement positionElement) + { + id = 0; + position = 0; + positionElement = default; + var sawId = false; + var sawPosition = false; + var offset = seek.DataOffset; + while (offset < seek.End) { + if (!EbmlReader.TryRead (body, offset, seek.End, out var child) || child.UnknownSize) + return false; + var payload = body.AsSpan (child.DataOffset, child.UnknownSize ? 0 : (int)child.DataLength); + if (child.Id == MatroskaIds.SeekId && payload.Length > 0) { + id = ReadId (payload); + sawId = true; + } else if (child.Id == MatroskaIds.SeekPosition) { + position = child.DataLength <= 0 ? 0 : EbmlReader.ReadUInt (payload); + positionElement = child; + sawPosition = true; + } + + offset = child.End; + } + + return sawId && sawPosition && offset == seek.End; + } + + static bool TryDropSeek (byte[] body, EbmlElement seek, ref bool changed) + { + var total = seek.End - seek.Position; + if (!TryMakeVoid (total, out var hole)) + return false; + hole.CopyTo (body.AsSpan (seek.Position)); + changed = true; + return true; + } + + static bool TryAddSeek (byte[] body, EbmlElement seekHead, ulong tagsOffset) + { + var seek = MakeSeek (MatroskaIds.Tags, tagsOffset); + var offset = seekHead.DataOffset; + while (offset < seekHead.End) { + if (!EbmlReader.TryRead (body, offset, seekHead.End, out var child) || child.UnknownSize) + break; + if (child.Id == MatroskaIds.Void) { + var total = child.End - child.Position; + if (TryFit (seek, total, out var fitted)) { + fitted.CopyTo (body.AsSpan (child.Position)); + return true; + } + } + + offset = child.End; + } + + return TryAbsorbVoid (body, seekHead, seek); + } + + static bool TryAbsorbVoid (byte[] body, EbmlElement seekHead, byte[] seek) + { + var at = seekHead.End; + if ((uint)at >= (uint)body.Length || !EbmlReader.TryRead (body, at, body.Length, out var voidEl)) + return false; + if (voidEl.Id != MatroskaIds.Void || voidEl.UnknownSize || voidEl.Position != at) + return false; + + var voidTotal = voidEl.End - voidEl.Position; + var remain = voidTotal - seek.Length; + if (remain < 0 || remain == 1) + return false; + if (remain > 0 && !TryMakeVoid (remain, out _)) + return false; + + if (!EbmlReader.TryReadVint (body, seekHead.Position, seekHead.DataOffset, true, 4, out _, out var idWidth, out _)) + return false; + var sizeWidth = seekHead.HeaderLength - idWidth; + var newDataLength = (ulong)seekHead.DataLength + (ulong)seek.Length; + if (sizeWidth < 1 || newDataLength > MaxSize (sizeWidth)) + return false; + + EncodeSize (newDataLength, sizeWidth).CopyTo (body.AsSpan (seekHead.Position + idWidth)); + seek.CopyTo (body.AsSpan (at)); + if (remain > 0 && TryMakeVoid (remain, out var hole)) + hole.CopyTo (body.AsSpan (at + seek.Length)); + UpdateElementCrc (body, seekHead.Position, seekHead.End + seek.Length); + return true; + } + + static bool TryPatchCues (byte[] body, int start, int end, Plan plan, out string error) + { + error = ""; + if (!EbmlReader.TryRead (body, start, Math.Min (end, body.Length), out var cues) || cues.UnknownSize || cues.Position != start) { + error = "Matroska Cues cannot be bounded"; + return false; + } + + var changed = false; + if (!TryPatchCueValues (body, cues.DataOffset, cues.End, plan, ref changed)) { + error = "Matroska Cues cannot be updated"; + return false; + } + + if (changed) + UpdateElementCrc (body, cues.Position, cues.End); + return true; + } + + static bool TryPatchCueValues (byte[] body, int offset, int end, Plan plan, ref bool changed) + { + while (offset < end) { + if (!EbmlReader.TryRead (body, offset, end, out var element) || element.UnknownSize) + return false; + if (element.Id == MatroskaIds.CueClusterPosition) { + if (element.DataLength is < 1 or > 8) + return false; + var value = EbmlReader.ReadUInt (body.AsSpan (element.DataOffset, (int)element.DataLength)); + if (value >= (ulong)plan.ShiftFrom) { + var updated = value + (ulong)plan.Delta; + if (updated < value || !TryWriteUnsigned (body, element.DataOffset, (int)element.DataLength, updated)) + return false; + if (updated != value) + changed = true; + } + } else if (element.Id is MatroskaIds.CuePoint or MatroskaIds.CueTrackPositions or MatroskaIds.Cues) { + if (!TryPatchCueValues (body, element.DataOffset, element.End, plan, ref changed)) + return false; + } + + offset = element.End; + } + + return true; + } + + static bool TryParse (ReadOnlySpan data, out Layout? layout, out string error) + { + layout = null; + error = ""; + if (!MatroskaFile.IsValidFormat (data)) { + error = "Not a Matroska file: missing EBML header"; + return false; + } + + if (!EbmlReader.TryRead (data, 0, data.Length, out var header) || header.Id != MatroskaIds.Ebml || header.UnknownSize) { + error = "Not a Matroska file: EBML header is truncated"; + return false; + } + + var docType = ReadDocType (data, header); + if (docType is null) { + error = "Not a Matroska file: DocType is missing"; + return false; + } + + if (!docType.Equals ("matroska", StringComparison.OrdinalIgnoreCase) + && !docType.Equals ("webm", StringComparison.OrdinalIgnoreCase)) { + error = "Not a Matroska file: DocType is " + docType; + return false; + } + + var offset = header.End; + var found = false; + EbmlElement segment = default; + while (offset < data.Length) { + if (!EbmlReader.TryRead (data, offset, data.Length, out var element)) + break; + if (element.Id == MatroskaIds.Segment) { + segment = element; + found = true; + break; + } + + if (element.UnknownSize) { + error = "Matroska element size is unknown before Segment"; + return false; + } + + offset = element.End; + } + + if (!found) { + error = "Matroska file has no Segment"; + return false; + } + + var end = MatroskaFile.PayloadEnd (data, segment); + if (!TryPieces (data, segment.DataOffset, end, out var pieces, out error)) + return false; + if (!EbmlReader.TryReadVint (data, segment.Position, segment.DataOffset, true, 4, out _, out var idWidth, out _)) { + error = "Matroska segment cannot be bounded"; + return false; + } + + var sizeWidth = segment.HeaderLength - idWidth; + if (sizeWidth < 1 || idWidth < 1) { + error = "Matroska segment cannot be bounded"; + return false; + } + + layout = new Layout (segment.Position, idWidth, sizeWidth, segment.UnknownSize, segment.DataOffset, end, pieces); + return true; + } + + static bool TryPieces (ReadOnlySpan data, int start, int end, out List pieces, out string error) + { + pieces = new List (); + error = ""; + var offset = start; + var sawElement = false; + while (offset < end) { + if (!EbmlReader.TryRead (data, offset, end, out var element)) { + if (sawElement) { + error = "Matroska segment cannot be bounded"; + return false; + } + + var gap = offset; + while (offset < end && !EbmlReader.TryRead (data, offset, end, out _)) + offset++; + if (offset > gap) + pieces.Add (new Piece (0, gap, offset - gap, false)); + continue; + } + + int pieceEnd; + if (element.UnknownSize) { + if (!TryBound (data, element.DataOffset, end, out pieceEnd)) { + error = "Matroska element size is unknown and cannot be bounded"; + return false; + } + } else + pieceEnd = element.End; + + if (pieceEnd < element.Position || pieceEnd > end) { + error = "Matroska segment cannot be bounded"; + return false; + } + + pieces.Add (new Piece (element.Id, element.Position, pieceEnd - element.Position, element.UnknownSize)); + sawElement = true; + offset = pieceEnd; + } + + if (OffsetOf (pieces, pieces.Count) != end - start) { + error = "Matroska segment cannot be bounded"; + return false; + } + + return true; + } + + /// + /// The unknown element ends at the next top-level sibling, or at + /// when every byte up to that point parses. A failed read is not skipped. + /// + static bool TryBound (ReadOnlySpan data, int offset, int parentEnd, out int end) + { + end = offset; + while (offset < parentEnd) { + if (!EbmlReader.TryRead (data, offset, parentEnd, out var element)) + return false; + if (MatroskaIds.IsSegmentChild (element.Id)) { + end = element.Position; + return true; + } + + if (element.UnknownSize) + return false; + offset = element.End; + } + + end = parentEnd; + return true; + } + + static string? ReadDocType (ReadOnlySpan data, EbmlElement header) + { + var offset = header.DataOffset; + var end = header.End; + while (offset < end) { + if (!EbmlReader.TryRead (data, offset, end, out var element) || element.UnknownSize) + break; + if (element.Id == MatroskaIds.DocType) + return EbmlReader.ReadString (data.Slice (element.DataOffset, (int)element.DataLength)); + offset = element.End; + } + + return null; + } + + static byte[] Assemble (ReadOnlySpan data, Layout layout, byte[] body, out string error) + { + error = ""; + var size = layout.UnknownSize + ? data.Slice (layout.SegmentPosition + layout.IdWidth, layout.SizeWidth).ToArray () + : EncodeFittedSize ((ulong)body.Length, layout.SizeWidth); + if (size.Length == 0) { + error = "Matroska segment size cannot be written"; + return []; + } + + using var output = new BinaryDataBuilder (data.Length + body.Length + 8); + output.Add (data.Slice (0, layout.SegmentPosition)); + output.Add (data.Slice (layout.SegmentPosition, layout.IdWidth)); + output.Add (size); + output.Add (body); + if (layout.SegmentEnd < data.Length) + output.Add (data.Slice (layout.SegmentEnd)); + return output.ToArray (); + } + + static bool TryFindFit (List pieces, ReadOnlySpan tags, out int start, out int end, out byte[] fitted) + { + for (var i = 0; i < pieces.Count; i++) { + if (pieces[i].Id != MatroskaIds.Tags) + continue; + if (TryConsume (pieces, i, tags, out end, out fitted)) { + start = i; + return true; + } + } + + for (var i = 0; i < pieces.Count; i++) { + if (pieces[i].Id != MatroskaIds.Void || pieces[i].UnknownSize) + continue; + if (TryConsume (pieces, i, tags, out end, out fitted)) { + start = i; + return true; + } + } + + start = -1; + end = -1; + fitted = []; + return false; + } + + static bool TryConsume (List pieces, int start, ReadOnlySpan tags, out int end, out byte[] fitted) + { + var available = 0; + end = start; + fitted = []; + for (var i = start; i < pieces.Count; i++) { + if (i != start && (pieces[i].Id != MatroskaIds.Void || pieces[i].UnknownSize || pieces[start].UnknownSize)) + break; + available += pieces[i].Length; + end = i; + if (available >= tags.Length && TryFit (tags, available, out fitted)) + return true; + } + + return false; + } + + static bool TryFit (ReadOnlySpan element, int region, out byte[] fitted) + { + fitted = []; + if (element.Length > region || region < 0) + return false; + var slack = region - element.Length; + if (slack == 0) { + fitted = element.ToArray (); + return true; + } + + if (slack == 1) + return TryWiden (element, out fitted) && fitted.Length == region; + if (!TryMakeVoid (slack, out var hole)) + return false; + fitted = new byte[region]; + element.CopyTo (fitted); + hole.CopyTo (fitted.AsSpan (element.Length)); + return true; + } + + static bool TryWiden (ReadOnlySpan element, out byte[] widened) + { + widened = []; + if (!EbmlReader.TryRead (element, 0, element.Length, out var parsed) || parsed.UnknownSize) + return false; + if (!EbmlReader.TryReadVint (element, 0, element.Length, true, 4, out _, out var idWidth, out _)) + return false; + var sizeWidth = parsed.HeaderLength - idWidth; + if (sizeWidth < 1 || sizeWidth >= 8) + return false; + var payloadLength = (int)parsed.DataLength; + var size = EncodeSize ((ulong)payloadLength, sizeWidth + 1); + widened = new byte[idWidth + size.Length + payloadLength]; + element.Slice (0, idWidth).CopyTo (widened); + size.CopyTo (widened.AsSpan (idWidth)); + element.Slice (parsed.DataOffset, payloadLength).CopyTo (widened.AsSpan (idWidth + size.Length)); + return widened.Length == element.Length + 1; + } + + static bool TryMakeVoid (int total, out byte[] bytes) + { + bytes = []; + if (total < 2) + return false; + for (var width = 1; width <= 8; width++) { + var payload = total - 1 - width; + if (payload < 0 || (ulong)payload > MaxSize (width)) + continue; + var size = EncodeSize ((ulong)payload, width); + bytes = new byte[total]; + bytes[0] = 0xEC; + size.CopyTo (bytes.AsSpan (1)); + return true; + } + + return false; + } + + static byte[] MakeSeek (ulong elementId, ulong position) + { + var seekId = EbmlWriter.Master (MatroskaIds.SeekId, IdBytes (elementId)); + var seekPosition = EbmlWriter.Master (MatroskaIds.SeekPosition, UnsignedBytes (position)); + using var body = new BinaryDataBuilder (seekId.Length + seekPosition.Length); + body.Add (seekId); + body.Add (seekPosition); + return EbmlWriter.Master (MatroskaIds.Seek, body.Span).ToArray (); + } + + static byte[] UnsignedBytes (ulong value) + { + var width = 1; + var probe = value; + while (probe > 0xFF && width < 8) { + width++; + probe >>= 8; + } + + var bytes = new byte[width]; + for (var i = width - 1; i >= 0; i--) { + bytes[i] = (byte)value; + value >>= 8; + } + + return bytes; + } + + static byte[] IdBytes (ulong id) + { + var width = id > 0xFFFFFF ? 4 : id > 0xFFFF ? 3 : id > 0xFF ? 2 : 1; + var bytes = new byte[width]; + for (var i = width - 1; i >= 0; i--) { + bytes[i] = (byte)id; + id >>= 8; + } + + return bytes; + } + + static ulong ReadId (ReadOnlySpan payload) + { + ulong id = 0; + for (var i = 0; i < payload.Length; i++) + id = (id << 8) | payload[i]; + return id; + } + + static bool TryWriteUnsigned (byte[] buffer, int offset, int width, ulong value) + { + if (width is < 1 or > 8) + return false; + if (width < 8) { + var max = (1UL << (8 * width)) - 1; + if (value > max) + return false; + } + + for (var i = width - 1; i >= 0; i--) { + buffer[offset + i] = (byte)value; + value >>= 8; + } + + return true; + } + + static byte[] EncodeFittedSize (ulong value, int width) + { + if (value <= MaxSize (width)) + return EncodeSize (value, width); + var needed = 0; + for (var candidate = width + 1; candidate <= 8; candidate++) { + if (value <= MaxSize (candidate)) { + needed = candidate; + break; + } + } + + return needed == 0 ? [] : EncodeSize (value, needed); + } + + static byte[] EncodeSize (ulong value, int width) + { + var raw = (1UL << (7 * width)) | value; + var bytes = new byte[width]; + for (var i = width - 1; i >= 0; i--) { + bytes[i] = (byte)raw; + raw >>= 8; + } + + return bytes; + } + + static ulong MaxSize (int width) => (1UL << (7 * width)) - 2; + + static int OffsetOf (List pieces, int index) + { + var offset = 0; + for (var i = 0; i < index; i++) + offset += pieces[i].Length; + return offset; + } + + static void UpdateElementCrc (byte[] body, int elementStart, int elementEnd) + { + if (!EbmlReader.TryRead (body, elementStart, elementEnd, out var parent) || parent.UnknownSize) + return; + if (!EbmlReader.TryRead (body, parent.DataOffset, parent.End, out var first)) + return; + if (first.Id != MatroskaIds.Crc32 || first.UnknownSize || first.DataLength != 4) + return; + WriteCrc (body, first.DataOffset, first.End, parent.End); + } + + static void UpdateLeadingCrc (byte[] body) + { + var offset = 0; + while (offset < body.Length && !EbmlReader.TryRead (body, offset, body.Length, out _)) + offset++; + if (!EbmlReader.TryRead (body, offset, body.Length, out var element)) + return; + if (element.Id != MatroskaIds.Crc32 || element.UnknownSize || element.DataLength != 4) + return; + WriteCrc (body, element.DataOffset, element.End, body.Length); + } + + static void WriteCrc (byte[] body, int payloadOffset, int coveredStart, int coveredEnd) + { + var crc = Crc32 (body.AsSpan (coveredStart, coveredEnd - coveredStart)); + body[payloadOffset] = (byte)crc; + body[payloadOffset + 1] = (byte)(crc >> 8); + body[payloadOffset + 2] = (byte)(crc >> 16); + body[payloadOffset + 3] = (byte)(crc >> 24); + } + + static uint Crc32 (ReadOnlySpan data) + { + var crc = 0xFFFFFFFFu; + for (var i = 0; i < data.Length; i++) + crc = CrcTable[(crc ^ data[i]) & 0xFF] ^ (crc >> 8); + return ~crc; + } + + static readonly uint[] CrcTable = BuildCrcTable (); + + static uint[] BuildCrcTable () + { + var table = new uint[256]; + for (uint i = 0; i < table.Length; i++) { + var crc = i; + for (var bit = 0; bit < 8; bit++) + crc = (crc & 1) == 1 ? 0xEDB88320u ^ (crc >> 1) : crc >> 1; + table[i] = crc; + } + + return table; + } +} diff --git a/src/TagLibSharp2/Matroska/MatroskaTag.cs b/src/TagLibSharp2/Matroska/MatroskaTag.cs index 6235453..d0f1474 100644 --- a/src/TagLibSharp2/Matroska/MatroskaTag.cs +++ b/src/TagLibSharp2/Matroska/MatroskaTag.cs @@ -594,6 +594,18 @@ void SetAt (ulong level, string name, string? value) void SetAtValues (ulong level, string name, string[]? values) { + SimpleTag? previous = null; + foreach (var existing in _blocks) { + if (!existing.IsFileLevel || existing.Level != level) + continue; + foreach (var tag in existing.Tags) { + if (tag.Name != name) + continue; + previous = tag; + break; + } + } + RemoveAt (level, name); if (values is null || values.Length == 0) return; @@ -602,7 +614,11 @@ void SetAtValues (ulong level, string name, string[]? values) foreach (var value in values) { if (string.IsNullOrEmpty (value)) continue; - block.Tags.Add (new SimpleTag (name, value)); + block.Tags.Add (new SimpleTag (name, value) { + Language = previous?.Language, + LanguageBcp47 = previous?.LanguageBcp47, + Binary = previous?.Binary + }); } } @@ -669,6 +685,14 @@ internal sealed class TagBlock public List Tags { get; } = new (); + readonly List _targetChildren = []; + + byte[]? _original; + + internal void KeepOriginal (byte[] element) => _original = element; + + internal void KeepTarget (byte[] element) => _targetChildren.Add (element); + public bool HasName (string name) { foreach (var tag in Tags) { @@ -704,8 +728,13 @@ public void Collect (string name, bool preferDefault, List values) public BinaryData Render () { + if (_original is not null) + return new BinaryData (_original); + using var body = new BinaryDataBuilder (); body.Add (EbmlWriter.Unsigned (MatroskaIds.TargetTypeValue, Level)); + foreach (var child in _targetChildren) + body.Add (child); var targets = EbmlWriter.Master (MatroskaIds.Targets, body.ToBinaryData ().Span); using var tag = new BinaryDataBuilder (); tag.Add (targets); @@ -731,16 +760,28 @@ public SimpleTag (string name, string? text, bool isDefault = true) public bool IsDefault { get; } + public string? Language { get; set; } + + public string? LanguageBcp47 { get; set; } + + public byte[]? Binary { get; set; } + public List Children { get; } = new (); public BinaryData Render () { using var body = new BinaryDataBuilder (); body.Add (EbmlWriter.String (MatroskaIds.TagName, Name)); + if (Language is not null) + body.Add (EbmlWriter.String (MatroskaIds.TagLanguage, Language)); + if (LanguageBcp47 is not null) + body.Add (EbmlWriter.String (MatroskaIds.TagLanguageBcp47, LanguageBcp47)); if (!IsDefault) body.Add (EbmlWriter.Unsigned (MatroskaIds.TagDefault, 0)); if (Text is not null) body.Add (EbmlWriter.String (MatroskaIds.TagString, Text)); + if (Binary is not null) + body.Add (EbmlWriter.Master (MatroskaIds.TagBinary, Binary)); foreach (var child in Children) body.Add (child.Render ()); return EbmlWriter.Master (MatroskaIds.SimpleTag, body.ToBinaryData ().Span); diff --git a/src/TagLibSharp2/TagLibSharp2.csproj b/src/TagLibSharp2/TagLibSharp2.csproj index 3b5b3a8..f7a5397 100644 --- a/src/TagLibSharp2/TagLibSharp2.csproj +++ b/src/TagLibSharp2/TagLibSharp2.csproj @@ -9,7 +9,7 @@ $(ReleaseVersion) - A modern .NET library for reading and writing metadata in media files. Supports 16 formats: MP3 (ID3v1/ID3v2), FLAC, Ogg Vorbis, Ogg Opus, Ogg FLAC, WAV, AIFF, MP4/M4A (AAC/ALAC), ASF/WMA, DSF (DSD), DFF (DSDIFF), WavPack, Monkey's Audio (.ape), Musepack, Matroska/WebM (reading), and APE tags. Clean, span-based API designed for performance. MIT licensed alternative to TagLib#. + A modern .NET library for reading and writing metadata in media files. Supports 16 formats: MP3 (ID3v1/ID3v2), FLAC, Ogg Vorbis, Ogg Opus, Ogg FLAC, WAV, AIFF, MP4/M4A (AAC/ALAC), ASF/WMA, DSF (DSD), DFF (DSDIFF), WavPack, Monkey's Audio (.ape), Musepack, Matroska/WebM, and APE tags. Clean, span-based API designed for performance. MIT licensed alternative to TagLib#. audio;metadata;id3;flac;vorbis;ogg;opus;mp3;mp4;m4a;aac;alac;wav;aiff;dsf;dsd;dff;dsdiff;ape;asf;wma;wavpack;musepack;mpc;monkeys-audio;tags;taglib;music;album-art;replaygain;musicbrainz MIT https://github.com/decriptor/TagLibSharp2 diff --git a/tests/TagLibSharp2.Tests/Matroska/MatroskaFileTests.cs b/tests/TagLibSharp2.Tests/Matroska/MatroskaFileTests.cs index 8c0908d..4a60622 100644 --- a/tests/TagLibSharp2.Tests/Matroska/MatroskaFileTests.cs +++ b/tests/TagLibSharp2.Tests/Matroska/MatroskaFileTests.cs @@ -11,7 +11,7 @@ namespace TagLibSharp2.Tests.Matroska; [TestClass] [TestCategory ("Unit")] [TestCategory ("Matroska")] -public class MatroskaFileTests +public partial class MatroskaFileTests { [TestMethod] public void Read_AlbumAndTrackTargets_KeepsEachLevel () diff --git a/tests/TagLibSharp2.Tests/Matroska/MatroskaSaveTests.cs b/tests/TagLibSharp2.Tests/Matroska/MatroskaSaveTests.cs new file mode 100644 index 0000000..c64e2ca --- /dev/null +++ b/tests/TagLibSharp2.Tests/Matroska/MatroskaSaveTests.cs @@ -0,0 +1,703 @@ +// Copyright (c) 2025-2026 Stephen Shaw and contributors +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TagLibSharp2.Core; +using TagLibSharp2.Matroska; +using TagLibSharp2.Tests.Core; + +namespace TagLibSharp2.Tests.Matroska; + +public partial class MatroskaFileTests +{ + [TestMethod] + public void Read_SecondUnknownSegment_StaysOutOfTheFirst () + { + var first = Unknown (0x18538067, Concat ( + Tags (Tag (50, Simple ("TITLE", "Movie"))), + Master (0x1F43B675, new byte[] { 0x11 }))); + var second = Unknown (0x18538067, Concat ( + Tags (Tag (30, Simple ("TITLE", "Later"))), + Master (0x1F43B675, new byte[] { 0x22 }))); + var parsed = MatroskaFile.Read (Matroska (Concat (first, second))); + + Assert.IsTrue (parsed.IsSuccess, parsed.Error); + Assert.AreEqual ("Movie", parsed.File!.Tag.Title); + } + + [TestMethod] + public void Save_UnknownSizeSegment_StopsBeforeTheNextSegment () + { + var marker = new byte[] { 0x11, 0x11, 0x11, 0x11 }; + var first = Unknown (0x18538067, Concat ( + Tags (Tag (50, Simple ("TITLE", "First"))), + Master (0x1F43B675, marker))); + var second = Master (0x18538067, Concat ( + Tags (Tag (50, Simple ("TITLE", "Second"))), + Master (0x1F43B675, new byte[] { 0x22, 0x22, 0x22, 0x22 }))); + var original = Matroska (Concat (first, second)); + var parsed = MatroskaFile.Read (original).File!; + parsed.Tag.Artist = "Added"; + + var fs = new MockFileSystem (); + fs.AddFile ("/two.mkv", original); + var saved = parsed.SaveToFile ("/two.mkv", original, fs); + + Assert.IsTrue (saved.IsSuccess, saved.Error); + var bytes = fs.ReadAllBytes ("/two.mkv"); + Assert.IsTrue (bytes.AsSpan (bytes.Length - second.Length).SequenceEqual (second)); + var head = bytes.AsSpan (0, bytes.Length - second.Length).ToArray (); + var again = MatroskaFile.Read (head); + Assert.IsTrue (again.IsSuccess, again.Error); + Assert.AreEqual ("First", again.File!.Tag.Title); + Assert.AreEqual ("Added", again.File.Tag.Artist); + Assert.AreEqual (1, CountOf (head, marker)); + } + + [TestMethod] + public void Save_ChapterTitle_StaysOffTheFile () + { + var original = FileWith ( + Tags ( + Tag (50, Simple ("TITLE", "Movie")), + ChapterTag (30, Chapter (7), Simple ("TITLE", "Chapter"))), + Master (0x1F43B675, new byte[] { 0x33 })); + var parsed = MatroskaFile.Read (original); + Assert.AreEqual ("Movie", parsed.File!.Tag.Title); + + parsed.File.Tag.Artist = "Someone"; + var fs = new MockFileSystem (); + fs.AddFile ("/chap.mkv", original); + var saved = parsed.File.SaveToFile ("/chap.mkv", original, fs); + + Assert.IsTrue (saved.IsSuccess, saved.Error); + var bytes = fs.ReadAllBytes ("/chap.mkv"); + var again = MatroskaFile.Read (bytes).File!; + Assert.AreEqual ("Movie", again.Tag.Title); + Assert.AreEqual ("Someone", again.Tag.Artist); + Assert.IsNull (again.Tag.Album); + Assert.IsTrue (bytes.AsSpan ().IndexOf (Element (0x63C4, new byte[] { 7 })) >= 0); + } + + [TestMethod] + public void Save_FileLevelLanguage_IsWrittenBack () + { + var title = Master (0x67C8, Concat ( + Element (0x45A3, "TITLE"u8), + Element (0x447A, "eng"u8), + Element (0x4487, "Movie"u8))); + var original = FileWith ( + Tags (Master (0x7373, Concat (Master (0x63C0, Element (0x68CA, new byte[] { 50 })), title))), + Master (0x1F43B675, new byte[] { 0x44 })); + var parsed = MatroskaFile.Read (original).File!; + parsed.Tag.Artist = "Someone"; + + var fs = new MockFileSystem (); + fs.AddFile ("/lang.mkv", original); + var saved = parsed.SaveToFile ("/lang.mkv", original, fs); + + Assert.IsTrue (saved.IsSuccess, saved.Error); + var bytes = fs.ReadAllBytes ("/lang.mkv"); + Assert.AreEqual ("Movie", MatroskaFile.Read (bytes).File!.Tag.Title); + Assert.IsTrue (bytes.AsSpan ().IndexOf (Element (0x447A, "eng"u8)) >= 0); + } + + [TestMethod] + public void Save_RewritesCommonFields_AndLeavesTheClusterBytes () + { + var marker = new byte[] { 0xDE, 0xAD, 0xBE, 0xEF, 0x11, 0x22 }; + var scale = Element (0x2AD7B1, new byte[] { 0x0F, 0x42, 0x40 }); + var info = Master (0x1549A966, Concat (scale, Element (0x4489, Float32 (1500f)))); + var audio = Master (0x1654AE6B, Master (0xAE, Concat ( + Element (0x83, new byte[] { 2 }), + Element (0x86, "A_VORBIS"u8), + Master (0xE1, Element (0xB5, Float32 (44100f)))))); + var pictures = Master (0x1941A469, Master (0x61A7, Concat ( + Element (0x4660, "image/png"u8), + Element (0x466E, "cover.png"u8), + Element (0x465C, new byte[] { 9, 8, 7, 6, 5 })))); + var cluster = Master (0x1F43B675, marker); + var original = FileWith ( + info, + audio, + Tags ( + Tag (50, Simple ("TITLE", "Old Album"), Simple ("ARTIST", "Old Album Artist"), Simple ("TOTAL_PARTS", "8")), + Tag (30, + Simple ("TITLE", "Old Title"), + Simple ("ARTIST", "Old Artist"), + Simple ("DATE_RELEASED", "1991"), + Simple ("COMMENT", "Old"), + Simple ("GENRE", "Old Genre"), + Simple ("PART_NUMBER", "1"), + Simple ("COMPOSER", "Old Composer"), + Simple ("COPYRIGHT", "Old Copy"), + Simple ("DESCRIPTION", "Old Desc"), + Simple ("LYRICS", "Old Lyrics"), + Simple ("CONDUCTOR", "Old Conductor"), + Simple ("PUBLISHER", "Old Label"))), + pictures, + cluster); + var clusterAt = IndexOf (original, marker); + Assert.IsTrue (clusterAt > 0); + + var parsed = MatroskaFile.Read (original); + Assert.IsTrue (parsed.IsSuccess, parsed.Error); + var tag = parsed.File!.Tag; + tag.Title = "New Title"; + tag.Artist = "New Artist"; + tag.Performers = new[] { "New Artist", "Guest" }; + tag.Album = "New Album"; + tag.AlbumArtists = new[] { "New Album Artist" }; + tag.Year = "2024"; + tag.Comment = "New Comment"; + tag.Genre = "Jazz"; + tag.Track = 4; + tag.TotalTracks = 12; + tag.Composers = new[] { "Ada" }; + tag.Copyright = "New Copy"; + tag.Description = "New Desc"; + tag.Lyrics = "New Lyrics"; + tag.Conductor = "New Conductor"; + tag.Publisher = "New Label"; + + var fs = new MockFileSystem (); + fs.AddFile ("/song.mkv", original); + parsed.File.SetSourcePath ("/song.mkv", fs); + var saved = parsed.File.SaveToFile (fs); + + Assert.IsTrue (saved.IsSuccess, saved.Error); + var bytes = fs.ReadAllBytes ("/song.mkv"); + Assert.AreEqual (clusterAt, IndexOf (bytes, marker)); + Assert.AreEqual (1, CountOf (bytes, marker)); + var again = MatroskaFile.Read (bytes); + Assert.IsTrue (again.IsSuccess, again.Error); + var round = again.File!.Tag; + Assert.AreEqual ("New Title", round.Title); + Assert.AreEqual ("New Artist", round.Artist); + Assert.AreEqual (2, round.Performers.Length); + Assert.AreEqual ("Guest", round.Performers[1]); + Assert.AreEqual ("New Album", round.Album); + Assert.AreEqual ("New Album Artist", round.AlbumArtists[0]); + Assert.AreEqual ("2024", round.Year); + Assert.AreEqual ("New Comment", round.Comment); + Assert.AreEqual ("Jazz", round.Genre); + Assert.AreEqual (4u, round.Track); + Assert.AreEqual (12u, round.TotalTracks); + Assert.AreEqual ("Ada", round.Composers[0]); + Assert.AreEqual ("New Copy", round.Copyright); + Assert.AreEqual ("New Desc", round.Description); + Assert.AreEqual ("New Lyrics", round.Lyrics); + Assert.AreEqual ("New Conductor", round.Conductor); + Assert.AreEqual ("New Label", round.Publisher); + Assert.AreEqual (TimeSpan.FromSeconds (1.5), again.File.Duration); + IMediaFile media = again.File; + Assert.AreEqual (44100, media.AudioProperties!.SampleRate); + Assert.AreEqual (1, round.Pictures.Length); + Assert.IsTrue (round.Pictures[0].PictureData.Span.SequenceEqual (new byte[] { 9, 8, 7, 6, 5 })); + } + + [TestMethod] + public void Save_InsertsTagsWhenTheFileHasNone () + { + var marker = new byte[] { 0xC0, 0xFF, 0xEE }; + var info = Master (0x1549A966, Element (0x7BA9, "Segment Title"u8)); + var original = FileWith (info, Master (0x1F43B675, marker)); + var parsed = MatroskaFile.Read (original).File!; + + // With no existing tag block the item level is 50, so TITLE there is the title. + parsed.Tag.Title = "Added"; + parsed.Tag.Artist = "Someone"; + + var fs = new MockFileSystem (); + fs.AddFile ("/new.mkv", original); + var saved = parsed.SaveToFile ("/new.mkv", original, fs); + + Assert.IsTrue (saved.IsSuccess, saved.Error); + var bytes = fs.ReadAllBytes ("/new.mkv"); + Assert.AreEqual (1, CountOf (bytes, marker)); + var tag = MatroskaFile.Read (bytes).File!.Tag; + Assert.AreEqual ("Added", tag.Title); + Assert.AreEqual ("Someone", tag.Artist); + Assert.IsTrue (bytes.AsSpan ().IndexOf ("Segment Title"u8) >= 0); + } + + [TestMethod] + public void Save_ClearingAValue_RemovesItAndKeepsTheOthers () + { + var original = FileWith (Tags (Tag (30, + Simple ("TITLE", "Keep"), + Simple ("ARTIST", "Drop"), + Simple ("GENRE", "Drop Genre"), + Simple ("COMMENT", "Drop Comment")))); + var parsed = MatroskaFile.Read (original).File!; + parsed.Tag.Artist = null; + parsed.Tag.Genre = null; + parsed.Tag.Comment = ""; + + var fs = new MockFileSystem (); + fs.AddFile ("/cleared.mkv", original); + var saved = parsed.SaveToFile ("/cleared.mkv", original, fs); + + Assert.IsTrue (saved.IsSuccess, saved.Error); + var tag = MatroskaFile.Read (fs.ReadAllBytes ("/cleared.mkv")).File!.Tag; + Assert.AreEqual ("Keep", tag.Title); + Assert.IsNull (tag.Artist); + Assert.AreEqual (0, tag.Performers.Length); + Assert.IsNull (tag.Genre); + Assert.IsNull (tag.Comment); + } + + [TestMethod] + public void Save_ClearingTheOnlyTitle_LeavesNoTitle () + { + var original = FileWith (Tags (Tag (30, Simple ("TITLE", "Gone")))); + var parsed = MatroskaFile.Read (original).File!; + parsed.Tag.Title = null; + + var fs = new MockFileSystem (); + fs.AddFile ("/only.mkv", original); + var saved = parsed.SaveToFile ("/only.mkv", original, fs); + + Assert.IsTrue (saved.IsSuccess, saved.Error); + Assert.IsNull (MatroskaFile.Read (fs.ReadAllBytes ("/only.mkv")).File!.Tag.Title); + } + + [TestMethod] + public void Save_WebM_RoundTripsTheDocTypeAndTitle () + { + var original = Matroska (Master (0x18538067, Tags (Tag (30, Simple ("TITLE", "Clip")))), "webm"); + var parsed = MatroskaFile.Read (original).File!; + parsed.Tag.Title = "Web Clip"; + parsed.Tag.Artist = "Camera"; + + var fs = new MockFileSystem (); + fs.AddFile ("/clip.webm", original); + var saved = parsed.SaveToFile ("/clip.webm", original, fs); + + Assert.IsTrue (saved.IsSuccess, saved.Error); + var bytes = fs.ReadAllBytes ("/clip.webm"); + Assert.IsTrue (bytes.AsSpan ().IndexOf ("webm"u8) >= 0); + Assert.IsTrue (bytes.AsSpan ().IndexOf ("matroska"u8) < 0); + var tag = MatroskaFile.Read (bytes).File!.Tag; + Assert.AreEqual ("Web Clip", tag.Title); + Assert.AreEqual ("Camera", tag.Artist); + } + + [TestMethod] + public void Save_TwoTagsElements_DoNotKeepTheReplacedValues () + { + var original = FileWith ( + Tags (Tag (30, Simple ("TITLE", "First"))), + Tags (Tag (30, Simple ("ARTIST", "Second")))); + var parsed = MatroskaFile.Read (original).File!; + Assert.AreEqual ("Second", parsed.Tag.Artist); + parsed.Tag.Title = "Third"; + + var fs = new MockFileSystem (); + fs.AddFile ("/two.mkv", original); + Assert.IsTrue (parsed.SaveToFile ("/two.mkv", original, fs).IsSuccess); + + var tag = MatroskaFile.Read (fs.ReadAllBytes ("/two.mkv")).File!.Tag; + Assert.AreEqual ("Third", tag.Title); + Assert.AreEqual ("Second", tag.Artist); + } + + [TestMethod] + public void Save_NoSourcePath_DoesNotWrite () + { + var original = FileWith (Tags (Tag (30, Simple ("TITLE", "Stay")))); + var parsed = MatroskaFile.Read (original).File!; + parsed.Tag.Title = "Changed"; + var fs = new MockFileSystem (); + fs.AddFile ("/stay.mkv", original); + + var saved = parsed.SaveToFile (fs); + + Assert.IsFalse (saved.IsSuccess); + Assert.IsTrue (original.AsSpan ().SequenceEqual (fs.ReadAllBytes ("/stay.mkv"))); + } + + [TestMethod] + public async Task SaveAsync_RoundTripsBackToTheSourcePath () + { + var original = FileWith (Tags (Tag (30, Simple ("TITLE", "Before"), Simple ("ARTIST", "A")))); + var fs = new MockFileSystem (); + fs.AddFile ("/async.mkv", original); + var opened = await MatroskaFile.ReadFromFileAsync ("/async.mkv", fs); + Assert.IsTrue (opened.IsSuccess, opened.Error); + Assert.AreEqual ("/async.mkv", opened.File!.SourcePath); + opened.File.Tag.Title = "After"; + + var saved = await opened.File.SaveToFileAsync (fs); + + Assert.IsTrue (saved.IsSuccess, saved.Error); + Assert.AreEqual ("After", MatroskaFile.Read (fs.ReadAllBytes ("/async.mkv")).File!.Tag.Title); + Assert.AreEqual ("A", MatroskaFile.Read (fs.ReadAllBytes ("/async.mkv")).File!.Tag.Artist); + } + + [TestMethod] + public void Save_ToAnotherPath_LeavesTheSourceUntouched () + { + var original = FileWith (Tags (Tag (30, Simple ("TITLE", "Source")))); + var fs = new MockFileSystem (); + fs.AddFile ("/src.mkv", original); + var parsed = MatroskaFile.ReadFromFile ("/src.mkv", fs).File!; + parsed.Tag.Title = "Copy"; + + var saved = parsed.SaveToFile ("/dst.mkv", fs); + + Assert.IsTrue (saved.IsSuccess, saved.Error); + Assert.IsTrue (original.AsSpan ().SequenceEqual (fs.ReadAllBytes ("/src.mkv"))); + Assert.AreEqual ("Copy", MatroskaFile.Read (fs.ReadAllBytes ("/dst.mkv")).File!.Tag.Title); + Assert.AreEqual ("Source", MatroskaFile.Read (fs.ReadAllBytes ("/src.mkv")).File!.Tag.Title); + } + + [TestMethod] + public void Save_UnknownSizeThatCannotBeBounded_DoesNotWrite () + { + var tags = Tags (Tag (30, Simple ("TITLE", "Old"))); + var unbounded = Concat (new byte[] { 0x1F, 0x43, 0xB6, 0x75, 0xFF }, new byte[] { 0x00, 0x11, 0x22 }); + var original = FileWith (tags, unbounded); + Assert.AreEqual ("Old", MatroskaFile.Read (original).File!.Tag.Title); + var parsed = MatroskaFile.Read (original).File!; + parsed.Tag.Title = "New"; + var fs = new MockFileSystem (); + fs.AddFile ("/bad.mkv", original); + + var saved = parsed.SaveToFile ("/bad.mkv", original, fs); + + Assert.IsFalse (saved.IsSuccess); + StringAssert.Contains (saved.Error, "bounded"); + Assert.IsTrue (original.AsSpan ().SequenceEqual (fs.ReadAllBytes ("/bad.mkv"))); + } + + [TestMethod] + public void Save_MediaFileRead_SetsSourcePath () + { + var original = FileWith (Tags (Tag (30, Simple ("TITLE", "Media")))); + var fs = new MockFileSystem (); + fs.AddFile ("/media.mkv", original); + + var opened = MediaFile.Read ("/media.mkv", fs); + + Assert.IsTrue (opened.IsSuccess, opened.Error); + var file = opened.GetFileAs (); + Assert.IsNotNull (file); + Assert.AreEqual ("/media.mkv", file!.SourcePath); + file.Tag.Album = "From MediaFile"; + var saved = file.SaveToFile (fs); + Assert.IsTrue (saved.IsSuccess, saved.Error); + Assert.AreEqual ("From MediaFile", MatroskaFile.Read (fs.ReadAllBytes ("/media.mkv")).File!.Tag.Album); + Assert.AreEqual ("Media", MatroskaFile.Read (fs.ReadAllBytes ("/media.mkv")).File!.Tag.Title); + } + + [TestMethod] + public void Save_SeekHead_KeepsATagsPointerThatStillFits () + { + var marker = new byte[] { 0xAB, 0xCD }; + var cluster = Master (0x1F43B675, marker); + var tags = Tags (Tag (30, Simple ("TITLE", "Old"))); + var info = Master (0x1549A966, Element (0x7BA9, "Info"u8)); + var probe = Concat (SeekEntry (MatroskaIds.Tags, 0), info, tags, cluster); + var tagsAt = probe.Length - tags.Length - cluster.Length; + Assert.IsTrue (tagsAt < 0x80); + var seek = Master (0x114D9B74, Concat ( + SeekEntry (MatroskaIds.Info, (ulong)SeekEntry (MatroskaIds.Tags, 0).Length), + SeekEntry (MatroskaIds.Tags, (ulong)tagsAt))); + // Recompute once the real SeekHead length is known. Both seeks use a one-byte position. + var body = Concat (seek, info, tags, cluster); + tagsAt = seek.Length + info.Length; + var infoAt = seek.Length; + Assert.IsTrue (tagsAt < 0x80); + seek = Master (0x114D9B74, Concat ( + SeekEntry (MatroskaIds.Info, (ulong)infoAt), + SeekEntry (MatroskaIds.Tags, (ulong)tagsAt))); + Assert.AreEqual (body.Length - info.Length - tags.Length - cluster.Length, seek.Length); + var original = FileWith (seek, info, tags, cluster); + var parsed = MatroskaFile.Read (original).File!; + parsed.Tag.Title = "New"; + + var fs = new MockFileSystem (); + fs.AddFile ("/seek.mkv", original); + var saved = parsed.SaveToFile ("/seek.mkv", original, fs); + + Assert.IsTrue (saved.IsSuccess, saved.Error); + var bytes = fs.ReadAllBytes ("/seek.mkv"); + Assert.AreEqual (1, CountOf (bytes, marker)); + Assert.AreEqual ("New", MatroskaFile.Read (bytes).File!.Tag.Title); + var seeks = ReadSeeks (bytes); + var tagsSeek = seeks.Find (entry => entry.Id == MatroskaIds.Tags); + Assert.AreNotEqual (0UL, tagsSeek.Id); + Assert.IsTrue (IsElementAt (bytes, tagsSeek.Position, MatroskaIds.Tags)); + var infoSeek = seeks.Find (entry => entry.Id == MatroskaIds.Info); + Assert.IsTrue (IsElementAt (bytes, infoSeek.Position, MatroskaIds.Info)); + } + + [TestMethod] + public void Save_SeekHead_DropsATagsPointerThatWouldPointAtTheWrongOffset () + { + // The new Tags element is appended past offset 255. A one-byte SeekPosition cannot + // hold that offset, and the Seek element has no spare byte, so the entry is removed. + var marker = new byte[] { 0x11, 0x22, 0x33, 0x44 }; + var cluster = Master (0x1F43B675, Concat (marker, new byte[240])); + var tags = Tags (Tag (30, Simple ("TITLE", "Old"))); + var info = Master (0x1549A966, Element (0x7BA9, "I"u8)); + var seekProbe = Master (0x114D9B74, SeekEntry (MatroskaIds.Tags, 1)); + var tagsAt = seekProbe.Length + info.Length; + Assert.IsTrue (tagsAt < 0x80); + var seek = Master (0x114D9B74, SeekEntry (MatroskaIds.Tags, (ulong)tagsAt)); + var original = FileWith (seek, info, tags, cluster); + Assert.IsTrue (seek.Length + info.Length + tags.Length + cluster.Length > 255); + var parsed = MatroskaFile.Read (original).File!; + parsed.Tag.Title = new string ('N', 80); + + var fs = new MockFileSystem (); + fs.AddFile ("/drop.mkv", original); + var saved = parsed.SaveToFile ("/drop.mkv", original, fs); + + Assert.IsTrue (saved.IsSuccess, saved.Error); + var bytes = fs.ReadAllBytes ("/drop.mkv"); + Assert.AreEqual (new string ('N', 80), MatroskaFile.Read (bytes).File!.Tag.Title); + Assert.AreEqual (1, CountOf (bytes, marker)); + foreach (var entry in ReadSeeks (bytes)) { + if (entry.Id != MatroskaIds.Tags) + continue; + Assert.IsTrue (IsElementAt (bytes, entry.Position, MatroskaIds.Tags)); + } + + Assert.IsFalse (ReadSeeks (bytes).Exists (entry => entry.Id == MatroskaIds.Tags && entry.Position == (ulong)tagsAt)); + } + + [TestMethod] + public void Save_ShiftedCluster_UpdatesCueClusterPositionAndKeepsThePayload () + { + var marker = new byte[] { 0xCA, 0xFE, 0xBA, 0xBE }; + var clusterPayload = Element (0xEC, marker); + var info = Master (0x1549A966, Element (0x7BA9, "Live"u8)); + var cues = CueElement (0); + ulong clusterPos = 0; + for (var i = 0; i < 4; i++) { + clusterPos = (ulong)(info.Length + cues.Length); + cues = CueElement (clusterPos); + } + + Assert.AreEqual (clusterPos, (ulong)(info.Length + cues.Length)); + Assert.IsTrue (clusterPos < 0x80); + var cluster = Concat (new byte[] { 0x1F, 0x43, 0xB6, 0x75, 0xFF }, clusterPayload); + var original = FileWith (info, cues, cluster); + var parsed = MatroskaFile.Read (original).File!; + parsed.Tag.Title = "Shifted"; + + var fs = new MockFileSystem (); + fs.AddFile ("/live.mkv", original); + var saved = parsed.SaveToFile ("/live.mkv", original, fs); + + Assert.IsTrue (saved.IsSuccess, saved.Error); + var bytes = fs.ReadAllBytes ("/live.mkv"); + Assert.AreEqual ("Shifted", MatroskaFile.Read (bytes).File!.Tag.Title); + Assert.AreEqual (1, CountOf (bytes, marker)); + Assert.IsTrue (TryReadCueClusterPosition (bytes, out var position, out var crcOk)); + Assert.IsTrue (crcOk); + Assert.IsTrue (IsElementAt (bytes, position, MatroskaIds.Cluster)); + Assert.AreNotEqual ((ulong)clusterPos, position); + } + + static byte[] Unknown (ulong id, byte[] payload) + { + var idBytes = Id (id); + var result = new byte[idBytes.Length + 1 + payload.Length]; + idBytes.CopyTo (result, 0); + result[idBytes.Length] = 0xFF; + payload.CopyTo (result, idBytes.Length + 1); + return result; + } + + static byte[] SeekEntry (ulong id, ulong position) => + Master (0x4DBB, Concat (Element (0x53AB, Id (id)), Element (0x53AC, UIntBytes (position)))); + + static byte[] UIntBytes (ulong value) + { + if (value <= 0xFF) + return new[] { (byte)value }; + if (value <= 0xFFFF) + return new[] { (byte)(value >> 8), (byte)value }; + return new[] { (byte)(value >> 16), (byte)(value >> 8), (byte)value }; + } + + static byte[] CueElement (ulong clusterPos) + { + var inner = Master (0xBB, Concat ( + Element (0xB3, new byte[] { 0 }), + Master (0xB7, Concat ( + Element (0xF7, new byte[] { 1 }), + Element (0xF1, UIntBytes (clusterPos)))))); + return WithCrc (MatroskaIds.Cues, inner); + } + + static byte[] WithCrc (ulong id, byte[] payload) + { + var crc = new BinaryData (payload).ComputeCrc32 (); + var crcBytes = new byte[4]; + System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian (crcBytes, crc); + return Master (id, Concat (Element (0xBF, crcBytes), payload)); + } + + readonly struct SeekRef + { + public SeekRef (ulong id, ulong position) + { + Id = id; + Position = position; + } + + public ulong Id { get; } + + public ulong Position { get; } + } + + static List ReadSeeks (byte[] file) + { + var found = new List (); + if (!TrySegmentBody (file, out var body, out var bodyAt)) + return found; + var offset = 0; + while (offset < body.Length && EbmlReader.TryRead (body, offset, body.Length, out var element) && !element.UnknownSize) { + if (element.Id == MatroskaIds.SeekHead) + ReadSeekHead (body.AsSpan (element.DataOffset, (int)element.DataLength), found); + offset = element.End; + } + + return found; + } + + static void ReadSeekHead (ReadOnlySpan body, List found) + { + var offset = 0; + while (offset < body.Length && EbmlReader.TryRead (body, offset, body.Length, out var element) && !element.UnknownSize) { + if (element.Id == 0x4DBB) + found.Add (ReadSeek (body.Slice (element.DataOffset, (int)element.DataLength))); + offset = element.End; + } + } + + static SeekRef ReadSeek (ReadOnlySpan body) + { + ulong id = 0; + ulong position = 0; + var offset = 0; + while (offset < body.Length && EbmlReader.TryRead (body, offset, body.Length, out var element) && !element.UnknownSize) { + var payload = body.Slice (element.DataOffset, (int)element.DataLength); + if (element.Id == 0x53AB) + id = ReadId (payload); + else if (element.Id == 0x53AC) + position = EbmlReader.ReadUInt (payload); + offset = element.End; + } + + return new SeekRef (id, position); + } + + static ulong ReadId (ReadOnlySpan payload) + { + ulong id = 0; + for (var i = 0; i < payload.Length; i++) + id = (id << 8) | payload[i]; + return id; + } + + static bool IsElementAt (byte[] file, ulong segmentPosition, ulong id) + { + if (!TrySegmentBody (file, out _, out var bodyAt)) + return false; + var at = bodyAt + (int)segmentPosition; + var idBytes = Id (id); + return at >= 0 && at + idBytes.Length <= file.Length && file.AsSpan (at, idBytes.Length).SequenceEqual (idBytes); + } + + static bool TryReadCueClusterPosition (byte[] file, out ulong position, out bool crcOk) + { + position = 0; + crcOk = false; + if (!TrySegmentBody (file, out var body, out _)) + return false; + var offset = 0; + while (offset < body.Length && EbmlReader.TryRead (body, offset, body.Length, out var element) && !element.UnknownSize) { + if (element.Id == MatroskaIds.Cues) { + var cues = body.AsSpan (element.DataOffset, (int)element.DataLength); + crcOk = CrcMatches (cues); + return TryFindCuePosition (cues, ref position); + } + + offset = element.End; + } + + return false; + } + + static bool CrcMatches (ReadOnlySpan master) + { + if (!EbmlReader.TryRead (master, 0, master.Length, out var crc) || crc.Id != MatroskaIds.Crc32 || crc.DataLength != 4) + return false; + var stored = System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian (master.Slice (crc.DataOffset, 4)); + var computed = new BinaryData (master.Slice (crc.End).ToArray ()).ComputeCrc32 (); + return stored == computed; + } + + static bool TryFindCuePosition (ReadOnlySpan body, ref ulong position) + { + var offset = 0; + while (offset < body.Length && EbmlReader.TryRead (body, offset, body.Length, out var element) && !element.UnknownSize) { + if (element.Id == MatroskaIds.CueClusterPosition && element.DataLength > 0) { + position = EbmlReader.ReadUInt (body.Slice (element.DataOffset, (int)element.DataLength)); + return true; + } + + if (element.Id is 0xBB or 0xB7 && TryFindCuePosition (body.Slice (element.DataOffset, (int)element.DataLength), ref position)) + return true; + offset = element.End; + } + + return false; + } + + static bool TrySegmentBody (byte[] file, out byte[] body, out int bodyAt) + { + body = Array.Empty (); + bodyAt = 0; + var offset = 0; + while (offset < file.Length && EbmlReader.TryRead (file, offset, file.Length, out var element)) { + if (element.Id == MatroskaIds.Segment && !element.UnknownSize) { + bodyAt = element.DataOffset; + body = file.AsSpan (element.DataOffset, (int)element.DataLength).ToArray (); + return true; + } + + if (element.UnknownSize) + return false; + offset = element.End; + } + + return false; + } + + static int IndexOf (byte[] data, byte[] pattern) + { + var found = data.AsSpan ().IndexOf (pattern); + return found; + } + + static int CountOf (byte[] data, byte[] pattern) + { + var count = 0; + var span = data.AsSpan (); + var at = 0; + while (at <= span.Length - pattern.Length) { + var found = span.Slice (at).IndexOf (pattern); + if (found < 0) + break; + count++; + at += found + 1; + } + + return count; + } +} diff --git a/tests/TagLibSharp2.Tests/PublicApi/Snapshots/TagLibSharp2.PublicApi.verified.txt b/tests/TagLibSharp2.Tests/PublicApi/Snapshots/TagLibSharp2.PublicApi.verified.txt index d518678..747f7ba 100644 --- a/tests/TagLibSharp2.Tests/PublicApi/Snapshots/TagLibSharp2.PublicApi.verified.txt +++ b/tests/TagLibSharp2.Tests/PublicApi/Snapshots/TagLibSharp2.PublicApi.verified.txt @@ -2229,8 +2229,17 @@ namespace TagLibSharp2.Matroska public string? SourcePath { get; } public TagLibSharp2.Matroska.MatroskaTag Tag { get; } public void Dispose() { } + public TagLibSharp2.Core.BinaryData Render(System.ReadOnlySpan originalData) { } + public TagLibSharp2.Core.FileWriteResult SaveToFile(TagLibSharp2.Core.IFileSystem? fileSystem = null) { } + public TagLibSharp2.Core.FileWriteResult SaveToFile(string path, TagLibSharp2.Core.IFileSystem? fileSystem = null) { } + public TagLibSharp2.Core.FileWriteResult SaveToFile(string path, System.ReadOnlySpan originalData, TagLibSharp2.Core.IFileSystem? fileSystem = null) { } + public System.Threading.Tasks.Task SaveToFileAsync(TagLibSharp2.Core.IFileSystem? fileSystem = null, System.Threading.CancellationToken cancellationToken = default) { } + public System.Threading.Tasks.Task SaveToFileAsync(string path, TagLibSharp2.Core.IFileSystem? fileSystem = null, System.Threading.CancellationToken cancellationToken = default) { } + public System.Threading.Tasks.Task SaveToFileAsync(string path, System.ReadOnlyMemory originalData, TagLibSharp2.Core.IFileSystem? fileSystem = null, System.Threading.CancellationToken cancellationToken = default) { } public static bool IsValidFormat(System.ReadOnlySpan data) { } public static TagLibSharp2.Matroska.MatroskaFileReadResult Read(System.ReadOnlySpan data) { } + public static TagLibSharp2.Matroska.MatroskaFileReadResult ReadFromFile(string path, TagLibSharp2.Core.IFileSystem? fileSystem = null) { } + public static System.Threading.Tasks.Task ReadFromFileAsync(string path, TagLibSharp2.Core.IFileSystem? fileSystem = null, System.Threading.CancellationToken cancellationToken = default) { } public static bool TryRead(System.ReadOnlySpan data, out TagLibSharp2.Matroska.MatroskaFile? file) { } } public readonly struct MatroskaFileReadResult : System.IEquatable From 196ce762c44f7ba4484cf6cae9cd52d045ffd660 Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Mon, 16 Nov 2026 20:55:05 -0700 Subject: [PATCH 2/4] test: Cover the Matroska save branches the patch check missed --- .../Matroska/MatroskaSaveTests.cs | 153 ++++++++++++++++++ 1 file changed, 153 insertions(+) diff --git a/tests/TagLibSharp2.Tests/Matroska/MatroskaSaveTests.cs b/tests/TagLibSharp2.Tests/Matroska/MatroskaSaveTests.cs index c64e2ca..8db8ebf 100644 --- a/tests/TagLibSharp2.Tests/Matroska/MatroskaSaveTests.cs +++ b/tests/TagLibSharp2.Tests/Matroska/MatroskaSaveTests.cs @@ -501,6 +501,159 @@ public void Save_ShiftedCluster_UpdatesCueClusterPositionAndKeepsThePayload () Assert.AreNotEqual ((ulong)clusterPos, position); } + [TestMethod] + public void Render_UnreadableContainer_ReturnsEmpty () + { + var file = MatroskaFile.Read (FileWith (Master (0x1F43B675, new byte[] { 1 }))).File!; + Assert.AreEqual (0, file.Render (new byte[] { 1, 2, 3 }).Length); + } + + [TestMethod] + public void Save_WithoutASourcePath_DoesNotWrite () + { + var file = MatroskaFile.Read (FileWith (Master (0x1F43B675, new byte[] { 1 }))).File!; + var saved = file.SaveToFile (); + Assert.IsFalse (saved.IsSuccess); + Assert.AreEqual ("No source path available. File was not read from disk.", saved.Error); + saved = file.SaveToFile ("/song.mkv"); + Assert.AreEqual ("No source path available. File was not read from disk.", saved.Error); + } + + [TestMethod] + public async Task SaveAsync_WithoutASourcePath_DoesNotWrite () + { + var file = MatroskaFile.Read (FileWith (Master (0x1F43B675, new byte[] { 1 }))).File!; + var saved = await file.SaveToFileAsync (); + Assert.AreEqual ("No source path available. File was not read from disk.", saved.Error); + saved = await file.SaveToFileAsync ("/song.mkv"); + Assert.AreEqual ("No source path available. File was not read from disk.", saved.Error); + } + + [TestMethod] + public void Save_MissingSourceFile_DoesNotWrite () + { + var file = MatroskaFile.Read (FileWith (Master (0x1F43B675, new byte[] { 1 }))).File!; + file.SetSourcePath ("/missing.mkv", new MockFileSystem ()); + var saved = file.SaveToFile (); + Assert.IsFalse (saved.IsSuccess); + Assert.IsTrue (saved.Error!.Contains ("Failed to re-read source file", StringComparison.Ordinal)); + } + + [TestMethod] + public async Task SaveAsync_MissingSourceFile_DoesNotWrite () + { + var file = MatroskaFile.Read (FileWith (Master (0x1F43B675, new byte[] { 1 }))).File!; + file.SetSourcePath ("/missing.mkv", new MockFileSystem ()); + var saved = await file.SaveToFileAsync (); + Assert.IsFalse (saved.IsSuccess); + Assert.IsTrue (saved.Error!.Contains ("Failed to re-read source file", StringComparison.Ordinal)); + } + + [TestMethod] + public void Save_FileLevelLanguageAndBinary_AreWrittenBack () + { + var targets = Master (0x63C0, Concat ( + Element (0x68CA, new byte[] { 50 }), + Element (0x63CA, "MOVIE"u8))); + var title = Master (0x67C8, Concat ( + Element (0x45A3, "TITLE"u8), + Element (0x447B, "en-US"u8), + Element (0x4485, new byte[] { 1, 2, 3 }), + Element (0x4487, "Movie"u8))); + var original = FileWith (Tags (Master (0x7373, Concat (targets, title))), Master (0x1F43B675, new byte[] { 9 })); + var parsed = MatroskaFile.Read (original).File!; + Assert.AreEqual ("Movie", parsed.Tag.Title); + parsed.Tag.Artist = "Someone"; + + var fs = new MockFileSystem (); + fs.AddFile ("/lang.mkv", original); + var saved = parsed.SaveToFile ("/lang.mkv", original, fs); + Assert.IsTrue (saved.IsSuccess, saved.Error); + var bytes = fs.ReadAllBytes ("/lang.mkv"); + Assert.AreEqual ("Movie", MatroskaFile.Read (bytes).File!.Tag.Title); + Assert.IsTrue (bytes.AsSpan ().IndexOf (Element (0x447B, "en-US"u8)) >= 0); + Assert.IsTrue (bytes.AsSpan ().IndexOf (Element (0x4485, new byte[] { 1, 2, 3 })) >= 0); + Assert.IsTrue (bytes.AsSpan ().IndexOf (Element (0x63CA, "MOVIE"u8)) >= 0); + } + + [TestMethod] + public void Read_UnknownClusterEndingAtAnInfoElement_KeepsTheTitle () + { + var cluster = Unknown (0x1F43B675, Element (0xEC, new byte[] { 1, 2, 3, 4 })); + var info = Master (0x1549A966, Element (0x7BA9, "After"u8)); + var parsed = MatroskaFile.Read (Matroska (Unknown (0x18538067, Concat (cluster, info)))); + Assert.IsTrue (parsed.IsSuccess, parsed.Error); + Assert.AreEqual ("After", parsed.File!.Tag.Title); + } + + [TestMethod] + public void Read_UnknownClusterThatDoesNotParse_StillOpens () + { + var cluster = Unknown (0x1F43B675, new byte[] { 0xFF }); + var parsed = MatroskaFile.Read (Matroska (Unknown (0x18538067, cluster))); + Assert.IsTrue (parsed.IsSuccess, parsed.Error); + Assert.IsNull (parsed.File!.Tag.Title); + } + + [TestMethod] + public void Read_UnknownClusterOfOnlyAVoid_RunsToTheEnd () + { + var cluster = Unknown (0x1F43B675, Element (0xEC, new byte[] { 9 })); + var parsed = MatroskaFile.Read (Matroska (Unknown (0x18538067, cluster))); + Assert.IsTrue (parsed.IsSuccess, parsed.Error); + } + + [TestMethod] + public void Save_RejectsAContainerThatCannotBeRewritten () + { + var tag = MatroskaFile.Read (FileWith (Master (0x1F43B675, new byte[] { 1 }))).File!; + var fs = new MockFileSystem (); + AssertFailure (tag, fs, "/a.mkv", new byte[] { 0x1A, 0x45, 0xDF, 0xA3 }, "truncated"); + AssertFailure (tag, fs, "/b.mkv", Matroska (Array.Empty (), "avi"), "DocType is avi"); + AssertFailure (tag, fs, "/c.mkv", Master (0x1A45DFA3, Element (0x4286, new byte[] { 1 })), "DocType is missing"); + AssertFailure (tag, fs, "/d.mkv", Concat (Master (0x1A45DFA3, Element (0x4282, "matroska"u8)), new byte[] { 0xEC, 0xFF }), "unknown before Segment"); + AssertFailure (tag, fs, "/e.mkv", Master (0x1A45DFA3, Element (0x4282, "matroska"u8)), "no Segment"); + } + + [TestMethod] + public void Save_LeadingPaddingInsideTheSegment_IsKept () + { + var cluster = Master (0x1F43B675, new byte[] { 0xAB, 0xCD }); + var original = Matroska (Master (0x18538067, Concat (new byte[] { 0x00, 0x00 }, cluster))); + var parsed = MatroskaFile.Read (original).File!; + parsed.Tag.Title = "Padded"; + var fs = new MockFileSystem (); + fs.AddFile ("/pad.mkv", original); + var saved = parsed.SaveToFile ("/pad.mkv", original, fs); + Assert.IsTrue (saved.IsSuccess, saved.Error); + var bytes = fs.ReadAllBytes ("/pad.mkv"); + Assert.AreEqual ("Padded", MatroskaFile.Read (bytes).File!.Tag.Title); + Assert.AreEqual (1, CountOf (bytes, new byte[] { 0xAB, 0xCD })); + } + + [TestMethod] + public void Save_GarbageAfterARealElement_DoesNotWrite () + { + var info = Master (0x1549A966, Element (0x7BA9, "T"u8)); + var original = Matroska (Master (0x18538067, Concat (info, new byte[] { 0x01 }))); + var parsed = MatroskaFile.Read (FileWith (Master (0x1F43B675, new byte[] { 1 }))).File!; + var fs = new MockFileSystem (); + fs.AddFile ("/bad.mkv", new byte[] { 1 }); + var saved = parsed.SaveToFile ("/bad.mkv", original, fs); + Assert.IsFalse (saved.IsSuccess); + Assert.IsTrue (saved.Error!.Contains ("cannot be bounded", StringComparison.Ordinal)); + Assert.AreEqual (1, fs.ReadAllBytes ("/bad.mkv").Length); + } + + static void AssertFailure (MatroskaFile file, MockFileSystem fs, string path, byte[] original, string error) + { + fs.AddFile (path, new byte[] { 1 }); + var saved = file.SaveToFile (path, original, fs); + Assert.IsFalse (saved.IsSuccess, path); + Assert.IsTrue (saved.Error!.Contains (error, StringComparison.Ordinal), saved.Error); + Assert.AreEqual (1, fs.ReadAllBytes (path).Length); + } + static byte[] Unknown (ulong id, byte[] payload) { var idBytes = Id (id); From a257ac863b026b96c6583c2425bd2e764d43d314 Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Mon, 16 Nov 2026 21:19:37 -0700 Subject: [PATCH 3/4] test: Pin Matroska SeekHead CRC, UTF-8 titles, and attachment names --- .../Matroska/MatroskaSaveTests.cs | 118 ++++++++++++++++++ 1 file changed, 118 insertions(+) diff --git a/tests/TagLibSharp2.Tests/Matroska/MatroskaSaveTests.cs b/tests/TagLibSharp2.Tests/Matroska/MatroskaSaveTests.cs index 8db8ebf..f4c6327 100644 --- a/tests/TagLibSharp2.Tests/Matroska/MatroskaSaveTests.cs +++ b/tests/TagLibSharp2.Tests/Matroska/MatroskaSaveTests.cs @@ -501,6 +501,105 @@ public void Save_ShiftedCluster_UpdatesCueClusterPositionAndKeepsThePayload () Assert.AreNotEqual ((ulong)clusterPos, position); } + [TestMethod] + public void Save_SeekHeadCrc32_ReadsAndKeepsAValidCrc () + { + var marker = new byte[] { 0xC0, 0x1A, 0x42 }; + var info = Master (0x1549A966, Element (0x7BA9, "Info"u8)); + var tags = Tags (Tag (30, Simple ("TITLE", "Old"))); + var cluster = Master (0x1F43B675, marker); + var seek = SeekHeadWithCrc (0, 0); + var infoAt = seek.Length; + var tagsAt = seek.Length + info.Length; + seek = SeekHeadWithCrc ((ulong)infoAt, (ulong)tagsAt); + Assert.AreEqual (infoAt, seek.Length); + var original = FileWith (seek, info, tags, cluster); + var parsed = MatroskaFile.Read (original); + Assert.IsTrue (parsed.IsSuccess, parsed.Error); + Assert.AreEqual ("Old", parsed.File!.Tag.Title); + Assert.IsTrue (SeekHeadCrcOk (original)); + + parsed.File.Tag.Title = "New"; + var fs = new MockFileSystem (); + fs.AddFile ("/crc.mkv", original); + var saved = parsed.File.SaveToFile ("/crc.mkv", original, fs); + + Assert.IsTrue (saved.IsSuccess, saved.Error); + var bytes = fs.ReadAllBytes ("/crc.mkv"); + Assert.AreEqual ("New", MatroskaFile.Read (bytes).File!.Tag.Title); + Assert.AreEqual (1, CountOf (bytes, marker)); + Assert.IsTrue (SeekHeadCrcOk (bytes)); + } + + [TestMethod] + public void Save_UnicodeTitle_RoundTripsUtf8 () + { + var title = "So schön anders"; + var marker = new byte[] { 0x11, 0x22 }; + var original = FileWith (Tags (Tag (30, Simple ("TITLE", title))), Master (0x1F43B675, marker)); + var parsed = MatroskaFile.Read (original); + Assert.AreEqual (title, parsed.File!.Tag.Title); + parsed.File.Tag.Comment = "Anmerkung"; + + var fs = new MockFileSystem (); + fs.AddFile ("/utf.mkv", original); + var saved = parsed.File.SaveToFile ("/utf.mkv", original, fs); + Assert.IsTrue (saved.IsSuccess, saved.Error); + var bytes = fs.ReadAllBytes ("/utf.mkv"); + var again = MatroskaFile.Read (bytes).File!; + Assert.AreEqual (title, again.Tag.Title); + Assert.AreEqual ("Anmerkung", again.Tag.Comment); + Assert.IsTrue (bytes.AsSpan ().IndexOf (System.Text.Encoding.UTF8.GetBytes (title)) >= 0); + } + + [TestMethod] + public void Save_Level70Title_StaysOnThatTarget () + { + var original = FileWith (Tags (Tag (70, Simple ("TITLE", "Collection"))), Master (0x1F43B675, new byte[] { 3 })); + var parsed = MatroskaFile.Read (original).File!; + Assert.AreEqual ("Collection", parsed.Tag.Title); + Assert.IsNull (parsed.Tag.Album); + parsed.Tag.Title = "Renamed"; + + var fs = new MockFileSystem (); + fs.AddFile ("/level.mkv", original); + var saved = parsed.SaveToFile ("/level.mkv", original, fs); + Assert.IsTrue (saved.IsSuccess, saved.Error); + var bytes = fs.ReadAllBytes ("/level.mkv"); + var again = MatroskaFile.Read (bytes).File!; + Assert.AreEqual ("Renamed", again.Tag.Title); + Assert.IsNull (again.Tag.Album); + Assert.IsTrue (bytes.AsSpan ().IndexOf (Element (0x68CA, new byte[] { 70 })) >= 0); + Assert.IsFalse (bytes.AsSpan ().IndexOf (Element (0x68CA, new byte[] { 30 })) >= 0); + } + + [TestMethod] + public void Save_ExistingAttachmentName_IsLeftAlone () + { + var picture = new byte[] { 9, 8, 7, 6 }; + var attachment = Master (0x1941A469, Master (0x61A7, Concat ( + Element (0x4660, "image/png"u8), + Element (0x466E, "cover.png"u8), + Element (0x465C, picture)))); + var original = FileWith (Tags (Tag (30, Simple ("TITLE", "Film"))), attachment, Master (0x1F43B675, new byte[] { 4 })); + var parsed = MatroskaFile.Read (original).File!; + Assert.AreEqual (1, parsed.Tag.Pictures.Length); + parsed.Tag.Artist = "Someone"; + + var fs = new MockFileSystem (); + fs.AddFile ("/art.mkv", original); + var saved = parsed.SaveToFile ("/art.mkv", original, fs); + Assert.IsTrue (saved.IsSuccess, saved.Error); + var bytes = fs.ReadAllBytes ("/art.mkv"); + var again = MatroskaFile.Read (bytes).File!; + Assert.AreEqual ("Film", again.Tag.Title); + Assert.AreEqual ("Someone", again.Tag.Artist); + Assert.AreEqual (1, again.Tag.Pictures.Length); + CollectionAssert.AreEqual (picture, again.Tag.Pictures[0].PictureData.ToArray ()); + Assert.IsTrue (bytes.AsSpan ().IndexOf ("cover.png"u8) >= 0); + Assert.IsTrue (bytes.AsSpan ().IndexOf ("FrontCover.jpg"u8) < 0); + } + [TestMethod] public void Render_UnreadableContainer_ReturnsEmpty () { @@ -686,6 +785,25 @@ static byte[] CueElement (ulong clusterPos) return WithCrc (MatroskaIds.Cues, inner); } + static byte[] SeekHeadWithCrc (ulong infoAt, ulong tagsAt) => + WithCrc (MatroskaIds.SeekHead, Concat ( + SeekEntry (MatroskaIds.Info, infoAt), + SeekEntry (MatroskaIds.Tags, tagsAt))); + + static bool SeekHeadCrcOk (byte[] file) + { + if (!TrySegmentBody (file, out var body, out _)) + return false; + var offset = 0; + while (offset < body.Length && EbmlReader.TryRead (body, offset, body.Length, out var element) && !element.UnknownSize) { + if (element.Id == MatroskaIds.SeekHead) + return CrcMatches (body.AsSpan (element.DataOffset, (int)element.DataLength)); + offset = element.End; + } + + return false; + } + static byte[] WithCrc (ulong id, byte[] payload) { var crc = new BinaryData (payload).ComputeCrc32 (); From 0f5b75095ad4ae934c9d95a7148882697edc9db0 Mon Sep 17 00:00:00 2001 From: Stephen Shaw Date: Tue, 17 Nov 2026 00:12:01 -0700 Subject: [PATCH 4/4] test: Cover clearing tags and SeekHead or Cues that cannot move --- .../Matroska/MatroskaSaveTests.cs | 85 +++++++++++++++++++ 1 file changed, 85 insertions(+) diff --git a/tests/TagLibSharp2.Tests/Matroska/MatroskaSaveTests.cs b/tests/TagLibSharp2.Tests/Matroska/MatroskaSaveTests.cs index f4c6327..e99e113 100644 --- a/tests/TagLibSharp2.Tests/Matroska/MatroskaSaveTests.cs +++ b/tests/TagLibSharp2.Tests/Matroska/MatroskaSaveTests.cs @@ -600,6 +600,91 @@ public void Save_ExistingAttachmentName_IsLeftAlone () Assert.IsTrue (bytes.AsSpan ().IndexOf ("FrontCover.jpg"u8) < 0); } + [TestMethod] + public void Save_ClearingEveryTag_VoidsTheTagsElement () + { + var marker = new byte[] { 0xC1, 0xC2, 0xC3 }; + var original = FileWith (Tags (Tag (30, Simple ("TITLE", "Gone"))), Master (0x1F43B675, marker)); + var parsed = MatroskaFile.Read (original).File!; + parsed.Tag.Clear (); + + var fs = new MockFileSystem (); + fs.AddFile ("/clear.mkv", original); + var saved = parsed.SaveToFile ("/clear.mkv", original, fs); + + Assert.IsTrue (saved.IsSuccess, saved.Error); + var bytes = fs.ReadAllBytes ("/clear.mkv"); + Assert.IsNull (MatroskaFile.Read (bytes).File!.Tag.Title); + Assert.AreEqual (1, CountOf (bytes, marker)); + } + + [TestMethod] + public void Save_VoidAfterSeekHead_GainsATagsPointer () + { + var marker = new byte[] { 0xD1, 0xD2 }; + var info = Master (0x1549A966, Element (0x7BA9, "Info"u8)); + var hole = Element (0xEC, new byte[24]); + var cluster = Master (0x1F43B675, marker); + var seek = Master (0x114D9B74, SeekEntry (MatroskaIds.Info, 0)); + var infoAt = seek.Length + hole.Length; + Assert.IsTrue (infoAt < 0x80); + seek = Master (0x114D9B74, SeekEntry (MatroskaIds.Info, (ulong)infoAt)); + Assert.AreEqual (infoAt, seek.Length + hole.Length); + var original = FileWith (seek, hole, info, cluster); + var parsed = MatroskaFile.Read (original).File!; + parsed.Tag.Title = "Added"; + + var fs = new MockFileSystem (); + fs.AddFile ("/addseek.mkv", original); + var saved = parsed.SaveToFile ("/addseek.mkv", original, fs); + + Assert.IsTrue (saved.IsSuccess, saved.Error); + var bytes = fs.ReadAllBytes ("/addseek.mkv"); + Assert.AreEqual ("Added", MatroskaFile.Read (bytes).File!.Tag.Title); + Assert.AreEqual (1, CountOf (bytes, marker)); + var tagsSeek = ReadSeeks (bytes).Find (entry => entry.Id == MatroskaIds.Tags); + Assert.AreNotEqual (0UL, tagsSeek.Id); + Assert.IsTrue (IsElementAt (bytes, tagsSeek.Position, MatroskaIds.Tags)); + } + + [TestMethod] + public void Save_UnknownChildInSeekHead_DoesNotWriteWhenTheClusterMoves () + { + var info = Master (0x1549A966, Element (0x7BA9, "Info"u8)); + var seek = Master (0x114D9B74, Concat (SeekEntry (MatroskaIds.Info, 20), new byte[] { 0xEC, 0xFF })); + var cluster = Unknown (0x1F43B675, Element (0xEC, new byte[] { 1, 2, 3, 4 })); + var original = FileWith (seek, info, cluster); + var parsed = MatroskaFile.Read (original).File!; + parsed.Tag.Title = "Nope"; + + var fs = new MockFileSystem (); + fs.AddFile ("/badseek.mkv", original); + var saved = parsed.SaveToFile ("/badseek.mkv", original, fs); + + Assert.IsFalse (saved.IsSuccess); + Assert.IsTrue (saved.Error!.Contains ("SeekHead cannot be bounded", StringComparison.Ordinal), saved.Error); + Assert.AreEqual (original.Length, fs.ReadAllBytes ("/badseek.mkv").Length); + } + + [TestMethod] + public void Save_UnknownChildInCues_DoesNotWriteWhenTheClusterMoves () + { + var info = Master (0x1549A966, Element (0x7BA9, "Info"u8)); + var cues = Master (0x1C53BB6B, Concat (Element (0xBB, new byte[] { 0 }), new byte[] { 0xEC, 0xFF })); + var cluster = Unknown (0x1F43B675, Element (0xEC, new byte[] { 9, 8, 7 })); + var original = FileWith (info, cues, cluster); + var parsed = MatroskaFile.Read (original).File!; + parsed.Tag.Title = "Nope"; + + var fs = new MockFileSystem (); + fs.AddFile ("/badcues.mkv", original); + var saved = parsed.SaveToFile ("/badcues.mkv", original, fs); + + Assert.IsFalse (saved.IsSuccess); + Assert.IsTrue (saved.Error!.Contains ("Cues cannot", StringComparison.Ordinal), saved.Error); + Assert.AreEqual (original.Length, fs.ReadAllBytes ("/badcues.mkv").Length); + } + [TestMethod] public void Render_UnreadableContainer_ReturnsEmpty () {