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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/TagLibSharp2/Aiff/AiffFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -422,6 +422,7 @@ public BinaryData Render ()
public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null)
{
var data = Render ();
fileSystem ??= _sourceFileSystem;
return AtomicFileWriter.Write (path, data.Span, fileSystem);
}

Expand All @@ -438,6 +439,7 @@ public Task<FileWriteResult> SaveToFileAsync (
CancellationToken cancellationToken = default)
{
var data = Render ();
fileSystem ??= _sourceFileSystem;
return AtomicFileWriter.WriteAsync (path, data.Memory, fileSystem, cancellationToken);
}

Expand Down
26 changes: 18 additions & 8 deletions src/TagLibSharp2/Core/MediaFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,11 @@ public static MediaFileResult Read (Stream stream, string? pathHint = null)
#else
ArgumentNullException.ThrowIfNull (stream);
#endif
return Read (stream, pathHint, sourcePath: null, fileSystem: null);
try {
return Read (stream, pathHint, sourcePath: null, fileSystem: null);
} catch (IOException ex) {
return MediaFileResult.Failure (ex.Message);
}
}

/// <summary>
Expand Down Expand Up @@ -240,7 +244,17 @@ public static Task<MediaFileResult> ReadAsync (
#else
ArgumentNullException.ThrowIfNull (stream);
#endif
return ReadAsync (stream, pathHint, sourcePath: null, fileSystem: null, cancellationToken);
return ReadStreamAsync (stream, pathHint, cancellationToken);
}

static async Task<MediaFileResult> ReadStreamAsync (Stream stream, string? pathHint, CancellationToken cancellationToken)
{
try {
return await ReadAsync (stream, pathHint, sourcePath: null, fileSystem: null, cancellationToken)
.ConfigureAwait (false);
} catch (IOException ex) {
return MediaFileResult.Failure (ex.Message);
}
}

static MediaFileResult Read (Stream stream, string? pathHint, string? sourcePath, IFileSystem? fileSystem)
Expand Down Expand Up @@ -336,9 +350,9 @@ static MediaFileResult FromWav (WavFileReadResult result)
/// <param name="pathHint">Optional file path hint for extension-based detection.</param>
/// <returns>A result containing the parsed file or an error.</returns>
public static MediaFileResult ReadFromData (ReadOnlyMemory<byte> data, string? pathHint = null) =>
ReadCore (data, pathHint, sourceFileSystem: null, rememberPath: false);
ReadCore (data, pathHint);

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

Expand All @@ -361,10 +375,6 @@ static MediaFileResult ReadCore (ReadOnlyMemory<byte> data, string? pathHint, IF
_ => 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;
}

Expand Down
3 changes: 3 additions & 0 deletions src/TagLibSharp2/Dff/DffFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -586,6 +586,7 @@ public FileWriteResult SaveToFile (string path, ReadOnlySpan<byte> originalData,

try {
var rendered = Render ();
fileSystem ??= _sourceFileSystem;
return AtomicFileWriter.Write (path, rendered.Span, fileSystem);
} catch (Exception ex) {
return FileWriteResult.Failure ($"Failed to save file: {ex.Message}");
Expand Down Expand Up @@ -623,6 +624,7 @@ public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null)

try {
var rendered = Render ();
fileSystem ??= _sourceFileSystem;
return AtomicFileWriter.Write (path, rendered.Span, fileSystem);
} catch (Exception ex) {
return FileWriteResult.Failure ($"Failed to save file: {ex.Message}");
Expand Down Expand Up @@ -687,6 +689,7 @@ private async Task<FileWriteResult> SaveToFileAsyncCore (
{
try {
var rendered = Render ();
fileSystem ??= _sourceFileSystem;
return await AtomicFileWriter.WriteAsync (path, rendered.Memory, fileSystem, cancellationToken)
.ConfigureAwait (false);
} catch (Exception ex) {
Expand Down
2 changes: 2 additions & 0 deletions src/TagLibSharp2/Dsf/DsfFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -494,6 +494,7 @@ public FileWriteResult SaveToFile (string path, ReadOnlySpan<byte> originalData,
if (rendered.IsEmpty)
return FileWriteResult.Failure ("Failed to render DSF file");

fileSystem ??= _sourceFileSystem;
return AtomicFileWriter.Write (path, rendered.Span, fileSystem);
}

Expand All @@ -520,6 +521,7 @@ public Task<FileWriteResult> SaveToFileAsync (
if (rendered.IsEmpty)
return Task.FromResult (FileWriteResult.Failure ("Failed to render DSF file"));

fileSystem ??= _sourceFileSystem;
return AtomicFileWriter.WriteAsync (path, rendered.Memory, fileSystem, cancellationToken);
}

Expand Down
2 changes: 2 additions & 0 deletions src/TagLibSharp2/Matroska/MatroskaFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,7 @@ public FileWriteResult SaveToFile (string path, ReadOnlySpan<byte> originalData,
if (!MatroskaRewrite.TryRewrite (originalData, Tag, out var rewritten, out var error))
return FileWriteResult.Failure (error);

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

Expand Down Expand Up @@ -252,6 +253,7 @@ public Task<FileWriteResult> SaveToFileAsync (
if (!MatroskaRewrite.TryRewrite (originalData.Span, Tag, out var rewritten, out var error))
return Task.FromResult (FileWriteResult.Failure (error));

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

Expand Down
9 changes: 8 additions & 1 deletion src/TagLibSharp2/Matroska/MatroskaRewrite.cs
Original file line number Diff line number Diff line change
Expand Up @@ -348,6 +348,7 @@ static bool TryPatchSeek (byte[] body, EbmlElement seek, Plan plan, ref bool cha
if (positionElement.DataLength is > 0 and <= 8
&& TryWriteUnsigned (body, positionElement.DataOffset, (int)positionElement.DataLength, desired)) {
changed = true;
UpdateElementCrc (body, seek.Position, seek.End);
if (isTags)
referenced = true;
return true;
Expand Down Expand Up @@ -490,8 +491,14 @@ static bool TryPatchCueValues (byte[] body, int offset, int end, Plan plan, ref
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))
var nested = false;
if (!TryPatchCueValues (body, element.DataOffset, element.End, plan, ref nested))
return false;
if (nested) {
changed = true;
if (element.Id != MatroskaIds.Cues)
UpdateElementCrc (body, element.Position, element.End);
}
}

offset = element.End;
Expand Down
99 changes: 81 additions & 18 deletions src/TagLibSharp2/Matroska/MatroskaTag.cs
Original file line number Diff line number Diff line change
Expand Up @@ -594,31 +594,94 @@ 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)
var matches = new List<SimpleTag> ();
foreach (var block in _blocks) {
if (!block.IsFileLevel || block.Level != level)
continue;
foreach (var tag in existing.Tags) {
if (tag.Name != name)
continue;
previous = tag;
break;
foreach (var tag in block.Tags) {
if (tag.Name == name)
matches.Add (tag);
}
}

RemoveAt (level, name);
if (values is null || values.Length == 0)
var preferDefault = false;
foreach (var tag in matches) {
if (tag.IsDefault)
preferDefault = true;
}

var primary = new List<SimpleTag> ();
foreach (var tag in matches) {
if (!preferDefault || tag.IsDefault)
primary.Add (tag);
}

var incoming = new List<string> ();
if (values is not null) {
foreach (var value in values) {
if (!string.IsNullOrEmpty (value))
incoming.Add (value);
}
}

if (incoming.Count == 0) {
RemoveTags (primary);
return;
}

if (primary.Count == 0) {
var block = FileBlock (level);
foreach (var value in incoming)
block.Tags.Add (new SimpleTag (name, value));
return;
}

var home = BlockContaining (primary[0]);
ReplaceTag (primary[0], CopyTag (primary[0], incoming[0]));
if (primary.Count > 1)
RemoveTags (primary.GetRange (1, primary.Count - 1));
for (var i = 1; i < incoming.Count; i++) {
var source = i < primary.Count ? primary[i] : primary[0];
home.Tags.Add (CopyTag (source, incoming[i]));
}
}

var block = FileBlock (level);
foreach (var value in values) {
if (string.IsNullOrEmpty (value))
static SimpleTag CopyTag (SimpleTag previous, string text)
{
var tag = new SimpleTag (previous.Name, text, previous.IsDefault) {
Language = previous.Language,
LanguageBcp47 = previous.LanguageBcp47,
Binary = previous.Binary
};
tag.Children.AddRange (previous.Children);
return tag;
}

void ReplaceTag (SimpleTag previous, SimpleTag replacement)
{
foreach (var block in _blocks) {
var index = block.Tags.IndexOf (previous);
if (index < 0)
continue;
block.Tags.Add (new SimpleTag (name, value) {
Language = previous?.Language,
LanguageBcp47 = previous?.LanguageBcp47,
Binary = previous?.Binary
});
block.Tags[index] = replacement;
return;
}
}

TagBlock BlockContaining (SimpleTag tag)
{
foreach (var block in _blocks) {
if (block.Tags.Contains (tag))
return block;
}

return FileBlock (ItemLevel);
}

void RemoveTags (List<SimpleTag> tags)
{
foreach (var block in _blocks) {
block.Tags.RemoveAll (tag => tags.Contains (tag));
}
}

Expand Down
2 changes: 2 additions & 0 deletions src/TagLibSharp2/Mp4/Mp4File.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2135,6 +2135,7 @@ public FileWriteResult SaveToFile (string path, ReadOnlySpan<byte> originalData,
if (rendered.IsEmpty)
return FileWriteResult.Failure ("Failed to render MP4 file");

fileSystem ??= _sourceFileSystem;
return AtomicFileWriter.Write (path, rendered.Span, fileSystem);
}

Expand All @@ -2156,6 +2157,7 @@ public Task<FileWriteResult> SaveToFileAsync (
if (rendered.IsEmpty)
return Task.FromResult (FileWriteResult.Failure ("Failed to render MP4 file"));

fileSystem ??= _sourceFileSystem;
return AtomicFileWriter.WriteAsync (path, rendered.Memory, fileSystem, cancellationToken);
}

Expand Down
2 changes: 2 additions & 0 deletions src/TagLibSharp2/Mpeg/Mp3File.cs
Original file line number Diff line number Diff line change
Expand Up @@ -655,6 +655,7 @@ public FileWriteResult SaveToFile (string path, ReadOnlySpan<byte> originalData,
if (rendered.IsEmpty)
return FileWriteResult.Failure ("Failed to render MP3 file");

fileSystem ??= _sourceFileSystem;
return AtomicFileWriter.Write (path, rendered.Span, fileSystem);
}

Expand All @@ -676,6 +677,7 @@ public Task<FileWriteResult> SaveToFileAsync (
if (rendered.IsEmpty)
return Task.FromResult (FileWriteResult.Failure ("Failed to render MP3 file"));

fileSystem ??= _sourceFileSystem;
return AtomicFileWriter.WriteAsync (path, rendered.Memory, fileSystem, cancellationToken);
}

Expand Down
2 changes: 2 additions & 0 deletions src/TagLibSharp2/Ogg/OggOpusFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -585,6 +585,7 @@ public FileWriteResult SaveToFile (string path, ReadOnlySpan<byte> originalData,
if (rendered.IsEmpty)
return FileWriteResult.Failure ("Failed to render Ogg Opus file");

fileSystem ??= _sourceFileSystem;
return AtomicFileWriter.Write (path, rendered.Span, fileSystem);
}

Expand All @@ -606,6 +607,7 @@ public Task<FileWriteResult> SaveToFileAsync (
if (rendered.IsEmpty)
return Task.FromResult (FileWriteResult.Failure ("Failed to render Ogg Opus file"));

fileSystem ??= _sourceFileSystem;
return AtomicFileWriter.WriteAsync (path, rendered.Memory, fileSystem, cancellationToken);
}

Expand Down
2 changes: 2 additions & 0 deletions src/TagLibSharp2/Ogg/OggVorbisFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -495,6 +495,7 @@ public FileWriteResult SaveToFile (string path, ReadOnlySpan<byte> originalData,
if (rendered.IsEmpty)
return FileWriteResult.Failure ("Failed to render Ogg Vorbis file");

fileSystem ??= _sourceFileSystem;
return AtomicFileWriter.Write (path, rendered.Span, fileSystem);
}

Expand All @@ -516,6 +517,7 @@ public Task<FileWriteResult> SaveToFileAsync (
if (rendered.IsEmpty)
return Task.FromResult (FileWriteResult.Failure ("Failed to render Ogg Vorbis file"));

fileSystem ??= _sourceFileSystem;
return AtomicFileWriter.WriteAsync (path, rendered.Memory, fileSystem, cancellationToken);
}

Expand Down
4 changes: 3 additions & 1 deletion src/TagLibSharp2/Riff/RiffFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,9 @@ internal static bool TryRead (Stream stream, out RiffFile file, out List<Skipped
file.FileSize = (uint)header[4] | ((uint)header[5] << 8) | ((uint)header[6] << 16) | ((uint)header[7] << 24);
file.FormType = FourCharacters (header, 8);

var limit = Math.Min (stream.Length, (long)file.FileSize + 8);
// 0xFFFFFFFF is a placeholder from streamed writers, same as TryParse.
var formEnd = file.FileSize == 0xFFFFFFFF ? stream.Length : (long)file.FileSize + 8;
var limit = Math.Min (stream.Length, formEnd);
while (stream.Position + RiffChunk.HeaderSize <= limit) {
var chunkHeader = StreamBytes.ReadAtMost (stream, RiffChunk.HeaderSize);
if (chunkHeader.Length < RiffChunk.HeaderSize)
Expand Down
Loading
Loading