From d498d10e06be49dfaf99017c05744a266de6f9e6 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 11 Nov 2026 23:45:44 +0000 Subject: [PATCH 1/4] Build MediaInfoLib for WebAssembly and analyze streams in chunks - build-native-wasm.sh compiles MediaInfoLib + ZenLib with the Emscripten SDK of the .NET wasm-tools workload (same toolchain and -fwasm-exceptions/SIMD flags as the runtime) into native/browser-wasm/libmediainfo.a; zlib comes from the .NET runtime. SIZE_T_IS_LONG is needed on wasm32. - The logical P/Invoke library is now "libmediainfo": the WebAssembly SDK binds imports by the archive file name (desktop still goes through the resolver). - SharpMediaInfo.Native.Browser.targets adds the NativeFileReference; it is packed as buildTransitive so NuGet consumers link it automatically. - OpenStream no longer copies the whole stream in memory: it feeds 256 KB chunks and follows Open_Buffer_Continue_GoTo_Get seek requests. New OpenStreamAsync / MediaInfoBuilder.BuildAsync use Stream.ReadAsync. - Fix packing: natives were also packed as contentFiles with a build/../native path, which made NuGet restore fail for consumers. - SharpMediaInfo.Wasm.Smoke runs MediaInfo inside the .NET wasm runtime under Node; CI builds the browser-wasm native and runs it before packing. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SyVioAMhEw3uuqBekTJcn2 --- .github/workflows/ci.yml | 73 ++++++++- .gitignore | 1 + README.md | 32 +++- .../Fixtures/VirtualWavStream.cs | 144 +++++++++++++++++ .../MediaInfoNativeTests.cs | 76 ++++++++- SharpMediaInfo.Native/IMediaInfoNative.cs | 17 +- .../Interop/MediaInfoNativeMethods.cs | 23 ++- SharpMediaInfo.Native/MediaInfoNative.cs | 113 ++++++++++--- .../SharpMediaInfo.Native.csproj | 28 ++-- .../SharpMediaInfo.Native.Browser.targets | 30 ++++ .../build/SharpMediaInfo.Native.props | 3 + .../build/build-native-wasm.sh | 125 ++++++++++++++ .../Integration/MediaInfoBuilderTests.cs | 12 ++ SharpMediaInfo.Wasm.Smoke/Program.cs | 49 ++++++ .../SharpMediaInfo.Wasm.Smoke.csproj | 21 +++ SharpMediaInfo.Wasm.Smoke/VirtualWavStream.cs | 153 ++++++++++++++++++ SharpMediaInfo.Wasm.Smoke/wwwroot/main.mjs | 5 + SharpMediaInfo/MediaInfoBuilder.cs | 94 ++++++++--- 18 files changed, 933 insertions(+), 66 deletions(-) create mode 100644 SharpMediaInfo.Native.Tests/Fixtures/VirtualWavStream.cs create mode 100644 SharpMediaInfo.Native/build/SharpMediaInfo.Native.Browser.targets create mode 100755 SharpMediaInfo.Native/build/build-native-wasm.sh create mode 100644 SharpMediaInfo.Wasm.Smoke/Program.cs create mode 100644 SharpMediaInfo.Wasm.Smoke/SharpMediaInfo.Wasm.Smoke.csproj create mode 100644 SharpMediaInfo.Wasm.Smoke/VirtualWavStream.cs create mode 100644 SharpMediaInfo.Wasm.Smoke/wwwroot/main.mjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e5ccd39..295d264 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -29,8 +29,8 @@ env: AVALONIA_PROJECT: SharpMediaInfo.GUI.Avalonia/SharpMediaInfo.GUI.Avalonia.csproj WPF_PROJECT: SharpMediaInfo.GUI.WPF/SharpMediaInfo.GUI.WPF.csproj -# Stages: Resolve Version -> Native (per RID, from the MediaInfoLib submodule, cached) -# -> Test (Linux, Windows, macOS) -> Pack NuGet +# Stages: Resolve Version -> Native (per RID + browser-wasm, from the MediaInfoLib submodule, cached) +# -> Test (Linux, Windows, macOS, WebAssembly) -> Pack NuGet # -> Build (Windows, Linux, macOS desktop apps) # -> Pre-release (pull requests) / Tag & Release (master) # -> on a new release: Publish to GitHub Packages, Publish to nuget.org @@ -119,6 +119,11 @@ jobs: - rid: osx label: macOS universal os: macos-latest + # Static archive for .NET WebAssembly apps, compiled with the Emscripten SDK of the + # .NET wasm-tools workload (the same toolchain that links the runtime). + - rid: browser-wasm + label: WebAssembly + os: ubuntu-latest steps: # Submodules are fetched only on a cache miss (see below). - uses: actions/checkout@v7 @@ -139,7 +144,8 @@ jobs: uses: actions/cache/restore@v6 with: path: SharpMediaInfo.Native/native - key: native-${{ matrix.rid }}-${{ steps.key.outputs.submodules }}-${{ hashFiles('SharpMediaInfo.Native/build/build-native.*') }} + # browser-wasm also depends on the workload's Emscripten, i.e. on the .NET version. + key: native-${{ matrix.rid }}-${{ steps.key.outputs.submodules }}-${{ matrix.rid == 'browser-wasm' && format('{0}-{1}', env.DOTNET_VERSION, hashFiles('SharpMediaInfo.Native/build/build-native-wasm.sh')) || hashFiles('SharpMediaInfo.Native/build/build-native.*') }} - name: Fetch submodules if: steps.cache.outputs.cache-hit != 'true' @@ -154,11 +160,24 @@ jobs: if: steps.cache.outputs.cache-hit != 'true' && runner.os == 'macOS' run: brew install cmake + - name: Setup .NET (WebAssembly) + if: steps.cache.outputs.cache-hit != 'true' && matrix.rid == 'browser-wasm' + uses: actions/setup-dotnet@v6 + with: + dotnet-version: ${{ env.DOTNET_VERSION }} + dotnet-quality: 'ga' + + - name: Install wasm-tools workload + if: steps.cache.outputs.cache-hit != 'true' && matrix.rid == 'browser-wasm' + run: dotnet workload install wasm-tools + - name: Build native (${{ matrix.rid }}) if: steps.cache.outputs.cache-hit != 'true' shell: bash run: | - if [ "$RUNNER_OS" == "Windows" ]; then + if [ "${{ matrix.rid }}" == "browser-wasm" ]; then + bash SharpMediaInfo.Native/build/build-native-wasm.sh + elif [ "$RUNNER_OS" == "Windows" ]; then powershell -NoProfile -ExecutionPolicy Bypass -File SharpMediaInfo.Native/build/build-native.ps1 -Rid ${{ matrix.rid }} else bash SharpMediaInfo.Native/build/build-native.sh ${{ matrix.rid }} @@ -284,10 +303,54 @@ jobs: REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} REPORT_PREFIX: ${{ matrix.label }} + # Links the browser-wasm archive into a .NET WebAssembly app and runs it under Node: + # MediaInfoLib inside the WebAssembly runtime, chunked async stream analysis included. + test-wasm: + name: Test (WebAssembly) + runs-on: ubuntu-latest + needs: [native] + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Fetch MediaInfoLib submodule + shell: bash + run: git submodule update --init --depth 1 extern/MediaInfoLib + + - name: Setup .NET + uses: actions/setup-dotnet@v6 + with: + dotnet-version: ${{ env.DOTNET_VERSION }} + dotnet-quality: 'ga' + + - name: Install wasm-tools workload + run: dotnet workload install wasm-tools + + # browser-wasm for the app, linux-x64 because SharpMediaInfo.Native itself is built + # for the host RID. + - name: Download natives + uses: actions/download-artifact@v8 + with: + pattern: native-{browser-wasm,linux-x64} + path: SharpMediaInfo.Native/native + merge-multiple: true + + - name: Publish smoke test + run: dotnet publish SharpMediaInfo.Wasm.Smoke -c Release -o artifacts/wasm-smoke + + - name: Run smoke test (Node) + shell: bash + run: | + NODE="$(ls -d "$HOME"/.dotnet/packs/Microsoft.NET.Runtime.Emscripten.*.Node.linux-x64/*/tools/bin/node 2>/dev/null | sort -V | tail -n1)" + [ -x "$NODE" ] || NODE="$(command -v node)" + cd artifacts/wasm-smoke/wwwroot + "$NODE" main.mjs + pack: name: Pack NuGet runs-on: ubuntu-latest - needs: [version, native, test] + needs: [version, native, test, test-wasm] env: VERSION_SUFFIX: ${{ needs.version.outputs.version_suffix }} steps: diff --git a/.gitignore b/.gitignore index 6a027b1..c3e53aa 100644 --- a/.gitignore +++ b/.gitignore @@ -264,6 +264,7 @@ __pycache__/ /SharpMediaInfo.Native/native/**/*.dll /SharpMediaInfo.Native/native/**/*.so /SharpMediaInfo.Native/native/**/*.dylib +/SharpMediaInfo.Native/native/**/*.a /SharpMediaInfo.Native/native/**/VERSION.txt # CMake build trees created inside the submodule by build-native.sh /extern/MediaInfoLib/Project/CMake/build-*/ diff --git a/README.md b/README.md index 069d5a8..0220dbc 100644 --- a/README.md +++ b/README.md @@ -56,6 +56,7 @@ The Avalonia GUI with the [Avalonia Cascadia Theme](https://github.com/simonebor | `SharpMediaInfo.GUI.WPF` | WPF desktop app (Windows) | net10.0-windows | | `SharpMediaInfo.GUI.Avalonia` | Avalonia desktop app (cross-platform) | net10.0 / net10.0-windows | | `SharpMediaInfo.*.Tests` | TUnit test suites | net10.0 | +| `SharpMediaInfo.Wasm.Smoke` | WebAssembly smoke test (MediaInfoLib linked into the .NET wasm runtime, run with Node) | net10.0 (browser-wasm) | | `extern/MediaInfoLib`, `extern/ZenLib`, `extern/zlib` | Pinned native sources (submodules) | — | --- @@ -133,7 +134,24 @@ if (media.Video.Count > 0) Console.WriteLine(MediaInfo.LibraryVersion()); // "MediaInfoLib - v26.10" ``` -A stream can be analyzed the same way with `MediaInfoBuilder.FromStream(stream)`. +A seekable stream can be analyzed the same way with `MediaInfoBuilder.FromStream(stream)`. The +stream is read in 256 KB chunks, following MediaInfo's seek requests, so only the parts the parser +needs are read (typically a few MB, whatever the file size) and nothing is copied in memory. +`BuildAsync()` does the same with `Stream.ReadAsync`, for streams whose reads are truly +asynchronous (browser files, network): + +```csharp +await using var stream = await storageFile.OpenReadAsync(); +var media = await MediaInfoBuilder.FromStream(stream).WithReports().BuildAsync(cancellationToken); +``` + +### WebAssembly (browser-wasm) + +The packages also work in .NET WebAssembly apps (`Microsoft.NET.Sdk.WebAssembly`, Avalonia.Browser, +Blazor WebAssembly). MediaInfoLib ships as a static archive (`runtimes/browser-wasm/native/libmediainfo.a`) +that the package's `buildTransitive` targets hand to the WebAssembly SDK, which links it into +`dotnet.native.wasm`. That needs the native build tools: `dotnet workload install wasm-tools`. +In the browser there are no file paths, so use `FromStream(...).BuildAsync()`. --- @@ -158,6 +176,18 @@ Dependabot keeps the GitHub Actions current and Renovate the NuGet dependencies. | `win-x64`, `win-x86`, `win-arm64` | MSVC solution (`.sln`/`.slnx`) | | `linux-x64`, `linux-arm64` | CMake (ZenLib bundled, system zlib) | | `osx-x64`, `osx-arm64` | CMake (ZenLib bundled; `build-native.sh osx` builds both from one universal pass) | +| `browser-wasm` | CMake + Emscripten of the .NET `wasm-tools` workload (`build-native-wasm.sh`): static `libmediainfo.a` with ZenLib, zlib from the .NET runtime | + +`browser-wasm` is built with the same Emscripten (and the same `-fwasm-exceptions -msimd128` flags) the +.NET runtime is linked with, so no separate emsdk is needed. The `SharpMediaInfo.Wasm.Smoke` app links +it into a WebAssembly app and runs it under Node in CI: + +```bash +dotnet workload install wasm-tools +bash SharpMediaInfo.Native/build/build-native-wasm.sh # -> native/browser-wasm/libmediainfo.a +dotnet publish SharpMediaInfo.Wasm.Smoke -c Release -o artifacts/wasm-smoke +cd artifacts/wasm-smoke/wwwroot && node main.mjs # prints PASS/FAIL per check +``` Versions are pinned in `Directory.Build.props` (`MediaInfoVersion`, `LibZenVersion`); bumping them means updating the submodules to the matching tags. ZenLib has no release after v0.4.41, so it is diff --git a/SharpMediaInfo.Native.Tests/Fixtures/VirtualWavStream.cs b/SharpMediaInfo.Native.Tests/Fixtures/VirtualWavStream.cs new file mode 100644 index 0000000..1103c8d --- /dev/null +++ b/SharpMediaInfo.Native.Tests/Fixtures/VirtualWavStream.cs @@ -0,0 +1,144 @@ +using System.Text; + +namespace SharpMediaInfo.Native.Tests.Fixtures; + +/// +/// A seekable, read-only stream that presents a PCM WAV of arbitrary size without +/// allocating it: the 44-byte header is real, the sample data is generated on the fly +/// as zeros. An optional title is stored in a LIST/INFO chunk placed *after* the data, so +/// MediaInfo has to jump over the data to find it. It records how many bytes were read and +/// how many seeks happened, so tests can prove the analysis reads only what MediaInfo asks +/// for instead of the whole file. +/// +internal sealed class VirtualWavStream : Stream +{ + private readonly byte[] _header; + private readonly byte[] _trailer; + private readonly long _trailerStart; + private long _position; + + public VirtualWavStream(long dataSize, int sampleRate = 48000, short channels = 2, short bitsPerSample = 16, string? title = null) + { + if (dataSize <= 0 || dataSize % 2 != 0 || dataSize > uint.MaxValue - 1024) + throw new ArgumentOutOfRangeException(nameof(dataSize)); + + _trailer = title is null ? [] : CreateInfoChunk(title); + + int blockAlign = channels * bitsPerSample / 8; + using var ms = new MemoryStream(); + using (var w = new BinaryWriter(ms, Encoding.ASCII, leaveOpen: true)) + { + w.Write(Encoding.ASCII.GetBytes("RIFF")); + w.Write((uint)(36 + dataSize + _trailer.Length)); + w.Write(Encoding.ASCII.GetBytes("WAVE")); + w.Write(Encoding.ASCII.GetBytes("fmt ")); + w.Write(16); + w.Write((short)1); // PCM + w.Write(channels); + w.Write(sampleRate); + w.Write(sampleRate * blockAlign); + w.Write((short)blockAlign); + w.Write(bitsPerSample); + w.Write(Encoding.ASCII.GetBytes("data")); + w.Write((uint)dataSize); + } + _header = ms.ToArray(); + _trailerStart = _header.Length + dataSize; + Length = _trailerStart + _trailer.Length; + } + + // LIST/INFO chunk with a single INAM (title) entry. + private static byte[] CreateInfoChunk(string title) + { + var text = Encoding.ASCII.GetBytes(title + "\0"); + int padded = text.Length + (text.Length % 2); + using var ms = new MemoryStream(); + using (var w = new BinaryWriter(ms, Encoding.ASCII, leaveOpen: true)) + { + w.Write(Encoding.ASCII.GetBytes("LIST")); + w.Write(4 + 8 + padded); + w.Write(Encoding.ASCII.GetBytes("INFO")); + w.Write(Encoding.ASCII.GetBytes("INAM")); + w.Write(text.Length); + w.Write(text); + if (padded != text.Length) + w.Write((byte)0); + } + return ms.ToArray(); + } + + /// Total bytes handed out by Read/ReadAsync. + public long BytesRead { get; private set; } + + /// Number of Seek calls / Position assignments that moved the stream. + public int SeekCount { get; private set; } + + /// Number of ReadAsync calls (to tell the async path was used). + public int AsyncReadCount { get; private set; } + + public override bool CanRead => true; + public override bool CanSeek => true; + public override bool CanWrite => false; + public override long Length { get; } + + public override long Position + { + get => _position; + set => Seek(value, SeekOrigin.Begin); + } + + public override int Read(byte[] buffer, int offset, int count) => Read(buffer.AsSpan(offset, count)); + + public override int Read(Span destination) + { + int count = (int)Math.Min(destination.Length, Length - _position); + if (count <= 0) + return 0; + + destination[..count].Clear(); + CopyOverlap(_header, 0, destination[..count]); + CopyOverlap(_trailer, _trailerStart, destination[..count]); + + _position += count; + BytesRead += count; + return count; + } + + // Copies the part of `source` (located at `sourceStart` in the stream) that overlaps the + // window [_position, _position + destination.Length). + private void CopyOverlap(byte[] source, long sourceStart, Span destination) + { + long from = Math.Max(_position, sourceStart); + long to = Math.Min(_position + destination.Length, sourceStart + source.Length); + if (from < to) + source.AsSpan((int)(from - sourceStart), (int)(to - from)).CopyTo(destination[(int)(from - _position)..]); + } + + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + AsyncReadCount++; + await Task.Yield(); // behave like real asynchronous I/O + return Read(buffer.Span); + } + + public override long Seek(long offset, SeekOrigin origin) + { + long target = origin switch + { + SeekOrigin.Begin => offset, + SeekOrigin.Current => _position + offset, + SeekOrigin.End => Length + offset, + _ => throw new ArgumentOutOfRangeException(nameof(origin)), + }; + if (target < 0) + throw new IOException("Seek before the beginning of the stream."); + if (target != _position) + SeekCount++; + _position = target; + return _position; + } + + public override void Flush() { } + public override void SetLength(long value) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); +} diff --git a/SharpMediaInfo.Native.Tests/MediaInfoNativeTests.cs b/SharpMediaInfo.Native.Tests/MediaInfoNativeTests.cs index 7061485..42612f5 100644 --- a/SharpMediaInfo.Native.Tests/MediaInfoNativeTests.cs +++ b/SharpMediaInfo.Native.Tests/MediaInfoNativeTests.cs @@ -1,4 +1,4 @@ -using SharpMediaInfo.Native.Exception; +using SharpMediaInfo.Native.Exception; using SharpMediaInfo.Native.Tests.Fixtures; namespace SharpMediaInfo.Native.Tests; @@ -108,4 +108,78 @@ public async Task Dispose_IsIdempotent() native.Dispose(); native.Dispose(); // must not throw } + + // 2 GB of PCM: far more than any chunked reader should touch. The title sits in a chunk + // after the data, so finding it requires following MediaInfo's seek request. + private const long LargeDataSize = 2L * 1024 * 1024 * 1024; + private const long MaxBytesRead = 16L * 1024 * 1024; + private const string TrailingTitle = "Chunked reader"; + + [Test] + public async Task OpenStream_LargeStream_FollowsSeeksAndReadsOnlyWhatItNeeds() + { + using var stream = new VirtualWavStream(LargeDataSize, title: TrailingTitle); + using var native = IMediaInfoNative.Create(parseCoverData: false); + + native.OpenStream(stream); + + await Assert.That(native.GetStreamCount(StreamKind.Audio)).IsEqualTo(1); + await Assert.That(native.GetParameter(StreamKind.General, 0, "FileSize")).IsEqualTo(stream.Length.ToString()); + await Assert.That(native.GetParameter(StreamKind.General, 0, "Title")).IsEqualTo(TrailingTitle); + await Assert.That(stream.SeekCount).IsGreaterThanOrEqualTo(1); + await Assert.That(stream.BytesRead).IsLessThan(MaxBytesRead); + } + + [Test] + public async Task OpenStreamAsync_LargeStream_FollowsSeeksWithAsyncReads() + { + using var stream = new VirtualWavStream(LargeDataSize, title: TrailingTitle); + using var native = IMediaInfoNative.Create(parseCoverData: false); + + await native.OpenStreamAsync(stream); + + await Assert.That(native.GetStreamCount(StreamKind.Audio)).IsEqualTo(1); + await Assert.That(native.GetParameter(StreamKind.Audio, 0, "Format")).IsEqualTo("PCM"); + await Assert.That(native.GetParameter(StreamKind.General, 0, "Title")).IsEqualTo(TrailingTitle); + await Assert.That(stream.SeekCount).IsGreaterThanOrEqualTo(1); + await Assert.That(stream.AsyncReadCount).IsGreaterThanOrEqualTo(1); + await Assert.That(stream.BytesRead).IsLessThan(MaxBytesRead); + } + + [Test] + public async Task OpenStreamAsync_SmallWav_MatchesOpenFile() + { + var path = WavFixture.CreateTempWavFile(); + try + { + using var fromFile = IMediaInfoNative.Create(parseCoverData: false); + fromFile.OpenFile(path); + + using var stream = new MemoryStream(WavFixture.CreatePcmWav()); + using var fromStream = IMediaInfoNative.Create(parseCoverData: false); + await fromStream.OpenStreamAsync(stream); + + foreach (var parameter in new[] { "Format", "Duration", "SamplingRate", "Channels", "BitDepth" }) + { + await Assert.That(fromStream.GetParameter(StreamKind.Audio, 0, parameter)) + .IsEqualTo(fromFile.GetParameter(StreamKind.Audio, 0, parameter)); + } + } + finally + { + File.Delete(path); + } + } + + [Test] + public async Task OpenStreamAsync_Cancelled_Throws() + { + using var stream = new VirtualWavStream(LargeDataSize); + using var native = IMediaInfoNative.Create(parseCoverData: false); + using var cts = new CancellationTokenSource(); + cts.Cancel(); + + await Assert.That(async () => await native.OpenStreamAsync(stream, cts.Token)) + .Throws(); + } } diff --git a/SharpMediaInfo.Native/IMediaInfoNative.cs b/SharpMediaInfo.Native/IMediaInfoNative.cs index 4921b9e..3087988 100644 --- a/SharpMediaInfo.Native/IMediaInfoNative.cs +++ b/SharpMediaInfo.Native/IMediaInfoNative.cs @@ -60,12 +60,23 @@ string GetSpecificParameter( void OpenFile(string path); /// - /// Opens the specified stream for reading or writing operations. + /// Analyzes a readable, seekable stream. The stream is read in chunks, following the + /// seek requests of the library, so only the parts MediaInfo needs are read (typically + /// a few MB, whatever the size of the file) and nothing is buffered in memory. /// - /// The stream to open. The stream must be readable or writable, depending on the intended operation. Cannot be - /// null. + /// A readable, seekable, non-empty stream. Cannot be null. void OpenStream(Stream stream); + /// + /// Asynchronous variant of : reads go through + /// , so the caller's thread is free + /// while I/O is pending (needed in the browser, where there is a single thread and + /// file reads are asynchronous). + /// + /// A readable, seekable, non-empty stream. Cannot be null. + /// Cancels the analysis between two reads. + Task OpenStreamAsync(Stream stream, CancellationToken cancellationToken = default); + static IMediaInfoNative Create(bool parseCoverData) => new MediaInfoNative(parseCoverData); /// diff --git a/SharpMediaInfo.Native/Interop/MediaInfoNativeMethods.cs b/SharpMediaInfo.Native/Interop/MediaInfoNativeMethods.cs index ced931d..97c5fc7 100644 --- a/SharpMediaInfo.Native/Interop/MediaInfoNativeMethods.cs +++ b/SharpMediaInfo.Native/Interop/MediaInfoNativeMethods.cs @@ -1,4 +1,4 @@ -using SharpMediaInfo.Native.Enum; +using SharpMediaInfo.Native.Enum; using System; using System.Runtime.InteropServices; @@ -17,8 +17,12 @@ namespace SharpMediaInfo.Native.Interop /// internal static partial class MediaInfoNativeMethods { - // Logical library name used by the imports. Resolved at runtime via SetDllImportResolver. - private const string MEDIAINFO_LIB_FILENAME = "MediaInfo"; + // Logical library name used by the imports. On desktop it is resolved at runtime via + // SetDllImportResolver (mediainfo.dll / libmediainfo.so / libmediainfo.dylib). In the + // browser (browser-wasm) MediaInfoLib is linked statically into the runtime and the SDK + // binds imports by the archive's file name, so this must stay "libmediainfo" to match + // libmediainfo.a. + private const string MEDIAINFO_LIB_FILENAME = "libmediainfo"; // On Windows wchar_t is 2 bytes (UTF-16); elsewhere it is 4 bytes, so the wide API cannot // be marshalled as UTF-16 and we route through the narrow (UTF-8) MediaInfoA_* functions. @@ -128,6 +132,9 @@ private static string PtrToString(IntPtr value) => [LibraryImport(MEDIAINFO_LIB_FILENAME, EntryPoint = "MediaInfo_Open_Buffer_Continue")] private static partial nint OpenBufferContinue(IntPtr handle, IntPtr buffer, nuint bufferSize); + [LibraryImport(MEDIAINFO_LIB_FILENAME, EntryPoint = "MediaInfo_Open_Buffer_Continue_GoTo_Get")] + private static partial ulong OpenBufferContinueGoToGet(IntPtr handle); + [LibraryImport(MEDIAINFO_LIB_FILENAME, EntryPoint = "MediaInfo_Open_Buffer_Finalize")] private static partial nint OpenBufferFinalize(IntPtr handle); @@ -188,6 +195,16 @@ public static bool InitializeBuffer(IntPtr handle, long fileSize, long fileOffse public static nint ReadBuffer(IntPtr handle, IntPtr buffer, nuint bufferSize) => OpenBufferContinue(handle, buffer, bufferSize); + /// + /// After , the absolute offset the library wants the next buffer + /// to start from, or null to simply continue with the following bytes. + /// + public static long? GetBufferSeekRequest(IntPtr handle) + { + ulong offset = OpenBufferContinueGoToGet(handle); + return offset == ulong.MaxValue ? null : (long)offset; + } + /// Finalizes a buffered stream. Returns true on success. public static bool FinalizeBuffer(IntPtr handle) => OpenBufferFinalize(handle) != 0; diff --git a/SharpMediaInfo.Native/MediaInfoNative.cs b/SharpMediaInfo.Native/MediaInfoNative.cs index 4609cf0..ce7ce55 100644 --- a/SharpMediaInfo.Native/MediaInfoNative.cs +++ b/SharpMediaInfo.Native/MediaInfoNative.cs @@ -180,42 +180,107 @@ public void OpenFile(string path) } } + /// + /// Size of each chunk fed to the library. MediaInfo only needs a few of them per file + /// (headers, an index, maybe the tail), jumping around with seek requests. + /// + internal const int StreamChunkSize = 256 * 1024; + public void OpenStream(Stream stream) { + var reader = BeginStream(stream); + while (true) + { + int read = stream.Read(reader.Buffer, 0, reader.Buffer.Length); + if (!reader.Feed(read)) + break; + } + reader.Finish(); + } + + public async Task OpenStreamAsync(Stream stream, CancellationToken cancellationToken = default) + { + var reader = BeginStream(stream); + while (true) + { + cancellationToken.ThrowIfCancellationRequested(); + int read = await stream.ReadAsync(reader.Buffer.AsMemory(), cancellationToken).ConfigureAwait(false); + if (!reader.Feed(read)) + break; + } + reader.Finish(); + } + + private BufferFeeder BeginStream(Stream stream) + { + ArgumentNullException.ThrowIfNull(stream); if (!stream.CanRead || !stream.CanSeek || stream.Length <= 0) { throw new ArgumentException("The stream cannot be read or it's empty"); } - //get data from stream - using (var memoryStream = new MemoryStream()) + handle = new MediaInfoHandle(); + SetCoverDataParsing(parseCoverData); + + var reader = new BufferFeeder(handle.DangerousGetHandle(), stream); + reader.Start(); + return reader; + } + + /// + /// Drives MediaInfo's buffer API over a seekable stream without loading it in memory: + /// each chunk is passed to Open_Buffer_Continue, and whenever the library asks + /// for another position (Open_Buffer_Continue_GoTo_Get) the stream is moved there + /// and the parser re-initialised at that offset, exactly like MediaInfo's own file reader. + /// Only the reads differ between the sync and async paths; all native calls live here, + /// outside any await, so no buffer stays pinned across a suspension. + /// + private sealed class BufferFeeder(IntPtr handle, Stream stream) + { + // Bit 3 of the Open_Buffer_Continue status: the parser has everything it needs. + private const long StatusFinalized = 0x08; + + public byte[] Buffer { get; } = new byte[(int)Math.Min(StreamChunkSize, stream.Length)]; + + public void Start() + { + stream.Seek(0, SeekOrigin.Begin); + if (!MediaInfoNativeMethods.InitializeBuffer(handle, stream.Length, 0)) + { + throw new MediaInfoNativeOpenException("Unable to open the stream."); + } + } + + /// Feeds bytes; returns false when parsing is done. + public unsafe bool Feed(int count) { - stream.CopyTo(memoryStream); + if (count <= 0) + return false; // end of stream + + nint status; + fixed (byte* data = Buffer) + { + status = MediaInfoNativeMethods.ReadBuffer(handle, (IntPtr)data, (nuint)count); + } + if ((status & StatusFinalized) != 0) + return false; - var rawDataHandle = GCHandle.Alloc(memoryStream.GetBuffer(), GCHandleType.Pinned); - try + long? seekTo = MediaInfoNativeMethods.GetBufferSeekRequest(handle); + if (seekTo is long offset) { - IntPtr pointer = rawDataHandle.AddrOfPinnedObject(); - - //creates a new handle - handle = new MediaInfoHandle(); - - SetCoverDataParsing(parseCoverData); - - //opens the buffer - if (!MediaInfoNativeMethods.InitializeBuffer(handle.DangerousGetHandle(), stream.Length, 0)) - { - throw new MediaInfoNativeOpenException("Unable to open the stream."); - } - MediaInfoNativeMethods.ReadBuffer(handle.DangerousGetHandle(), pointer, (nuint)memoryStream.Length); - if (!MediaInfoNativeMethods.FinalizeBuffer(handle.DangerousGetHandle())) - { - throw new MediaInfoNativeFinalizeException("Unable to finalize the stream."); - } + if (offset < 0 || offset >= stream.Length) + return false; // nothing left to read there + stream.Seek(offset, SeekOrigin.Begin); + MediaInfoNativeMethods.InitializeBuffer(handle, stream.Length, offset); } - finally + return true; + } + + public void Finish() + { + if (!MediaInfoNativeMethods.FinalizeBuffer(handle)) { - rawDataHandle.Free(); + throw new MediaInfoNativeFinalizeException("Unable to finalize the stream."); } } } diff --git a/SharpMediaInfo.Native/SharpMediaInfo.Native.csproj b/SharpMediaInfo.Native/SharpMediaInfo.Native.csproj index 616ab6b..ad457e2 100644 --- a/SharpMediaInfo.Native/SharpMediaInfo.Native.csproj +++ b/SharpMediaInfo.Native/SharpMediaInfo.Native.csproj @@ -40,11 +40,14 @@ Text="MediaInfoLib submodule not found at $(MediaInfoLibDir). Run: git submodule update --init --recursive" /> + + - - + + + @@ -103,42 +109,49 @@ runtimes/win-x64/native/mediainfo.dll PreserveNewest true + runtimes/win-x64/native false runtimes/win-x86/native/mediainfo.dll PreserveNewest true + runtimes/win-x86/native false runtimes/win-arm64/native/mediainfo.dll PreserveNewest true + runtimes/win-arm64/native false runtimes/linux-x64/native/libmediainfo.so PreserveNewest true + runtimes/linux-x64/native false runtimes/linux-arm64/native/libmediainfo.so PreserveNewest true + runtimes/linux-arm64/native false runtimes/osx-x64/native/libmediainfo.dylib PreserveNewest true + runtimes/osx-x64/native false runtimes/osx-arm64/native/libmediainfo.dylib PreserveNewest true + runtimes/osx-arm64/native false @@ -148,13 +161,10 @@ - - - - - - - + + + diff --git a/SharpMediaInfo.Native/build/SharpMediaInfo.Native.Browser.targets b/SharpMediaInfo.Native/build/SharpMediaInfo.Native.Browser.targets new file mode 100644 index 0000000..0b02d2b --- /dev/null +++ b/SharpMediaInfo.Native/build/SharpMediaInfo.Native.Browser.targets @@ -0,0 +1,30 @@ + + + + $([MSBuild]::NormalizePath('$(MSBuildThisFileDirectory)', '..', 'runtimes', 'browser-wasm', 'native', 'libmediainfo.a')) + $([MSBuild]::NormalizePath('$(MSBuildThisFileDirectory)', '..', 'native', 'browser-wasm', 'libmediainfo.a')) + + + + + + + + + + diff --git a/SharpMediaInfo.Native/build/SharpMediaInfo.Native.props b/SharpMediaInfo.Native/build/SharpMediaInfo.Native.props index e93bfb0..928f070 100644 --- a/SharpMediaInfo.Native/build/SharpMediaInfo.Native.props +++ b/SharpMediaInfo.Native/build/SharpMediaInfo.Native.props @@ -18,11 +18,14 @@ $([System.String]::Copy($(EffectiveRid)).StartsWith('win')) $([System.String]::Copy($(EffectiveRid)).StartsWith('linux')) $([System.String]::Copy($(EffectiveRid)).StartsWith('osx')) + $([System.String]::Copy($(EffectiveRid)).Equals('browser-wasm')) mediainfo.dll libmediainfo.so libmediainfo.dylib + + libmediainfo.a $(MSBuildThisFileDirectory)..\native diff --git a/SharpMediaInfo.Native/build/build-native-wasm.sh b/SharpMediaInfo.Native/build/build-native-wasm.sh new file mode 100755 index 0000000..7db5733 --- /dev/null +++ b/SharpMediaInfo.Native/build/build-native-wasm.sh @@ -0,0 +1,125 @@ +#!/usr/bin/env bash +# Build MediaInfoLib (+ ZenLib) for browser-wasm as one static archive, +# native/browser-wasm/libmediainfo.a, ready to be linked into a .NET WebAssembly +# app with . +# +# The toolchain is the Emscripten SDK that ships with the .NET `wasm-tools` +# workload (`dotnet workload install wasm-tools`), so the archive is compiled by +# the exact Emscripten/LLVM version that links the .NET runtime: no separate +# emsdk install and no ABI mismatch. Flags follow the runtime defaults +# (WasmEnableExceptionHandling=true -> -fwasm-exceptions, WasmEnableSIMD=true). +# +# zlib is NOT bundled: the .NET browser runtime already links its own libz.a +# (standard zlib API), so MediaInfoLib is compiled against the zlib headers of +# the extern/zlib submodule and resolves the symbols from the runtime at link time. +# +# Usage: build-native-wasm.sh +# Env: EMSDK_PACK_DIR override the Emscripten SDK pack directory (…/Microsoft.NET.Runtime.Emscripten.*.Sdk./) +set -euo pipefail + +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" # .../SharpMediaInfo.Native/build +native_proj="$(cd "$here/.." && pwd)" # .../SharpMediaInfo.Native +repo_root="$(cd "$native_proj/.." && pwd)" +mediainfolib="$repo_root/extern/MediaInfoLib" +zlib_src="$repo_root/extern/zlib" +rid="browser-wasm" + +if [ ! -f "$mediainfolib/Project/CMake/CMakeLists.txt" ]; then + echo "MediaInfoLib submodule missing at $mediainfolib. Run: git submodule update --init --recursive" >&2 + exit 1 +fi + +# --- Locate the workload packs (dotnet install dir, then the user-local workload dir) ------- +case "$(uname -s)-$(uname -m)" in + Linux-x86_64) host=linux-x64 ;; + Linux-aarch64) host=linux-arm64 ;; + Darwin-x86_64) host=osx-x64 ;; + Darwin-arm64) host=osx-arm64 ;; + *) echo "Unsupported host: $(uname -s)-$(uname -m)" >&2; exit 1 ;; +esac + +pack_roots=() +[ -n "${DOTNET_ROOT:-}" ] && pack_roots+=("$DOTNET_ROOT/packs") +if command -v dotnet >/dev/null 2>&1; then + pack_roots+=("$(dirname "$(readlink -f "$(command -v dotnet)")")/packs") +fi +pack_roots+=("$HOME/.dotnet/packs") + +# newest version directory of a pack, searched across all pack roots +find_pack() { + local pattern="$1" root dir best="" + for root in "${pack_roots[@]}"; do + for dir in "$root"/$pattern/*/; do + [ -d "$dir" ] || continue + best="$(printf '%s\n%s\n' "$best" "${dir%/}" | sed '/^$/d' | sort -V | tail -n1)" + done + done + printf '%s' "$best" +} + +emsdk="${EMSDK_PACK_DIR:-$(find_pack "Microsoft.NET.Runtime.Emscripten.*.Sdk.$host")}" +node_pack="$(find_pack "Microsoft.NET.Runtime.Emscripten.*.Node.$host")" +cache_pack="$(find_pack "Microsoft.NET.Runtime.Emscripten.*.Cache.$host")" +runtime_pack="$(find_pack "Microsoft.NETCore.App.Runtime.Mono.browser-wasm")" + +if [ -z "$emsdk" ] || [ ! -x "$emsdk/tools/emscripten/emcc" ]; then + echo "Emscripten SDK pack not found. Install it with: dotnet workload install wasm-tools" >&2 + exit 1 +fi +echo "Emscripten SDK pack: $emsdk" + +tools="$emsdk/tools" +export DOTNET_EMSCRIPTEN_LLVM_ROOT="$tools/bin" +export DOTNET_EMSCRIPTEN_BINARYEN_ROOT="$tools" +export DOTNET_EMSCRIPTEN_NODE_JS="$node_pack/tools/bin/node" +export EMSDK_PATH="$tools" +export PATH="$tools/emscripten:$tools/bin:$node_pack/tools/bin:$PATH" +export PYTHONUTF8=1 +# Use the prebuilt (frozen) sysroot cache from the workload, like the .NET build does. +if [ -n "$cache_pack" ] && [ -d "$cache_pack/tools/emscripten/cache" ]; then + export EM_CACHE="$cache_pack/tools/emscripten/cache" + export EM_FROZEN_CACHE=1 +fi + +# Same code-generation flags as the .NET runtime (wasm EH + SIMD). +# SIZE_T_IS_LONG: on wasm32 size_t is `unsigned long` (32-bit), distinct from int32u/int64u, +# so ZenLib must declare its size_t overloads (it only auto-detects this on LP64/macOS). +wasm_flags="-fwasm-exceptions -msimd128 -O2 -DSIZE_T_IS_LONG" + +# zlib: headers from the submodule, library from the .NET runtime pack (only used so +# find_package(ZLIB) succeeds; a static archive does not link anything itself). +zlib_lib="$runtime_pack/runtimes/browser-wasm/native/libz.a" +[ -f "$zlib_lib" ] || zlib_lib="$zlib_src/zlib.h" # any existing file satisfies FindZLIB + +build_dir="$mediainfolib/Project/CMake/build-$rid" +mkdir -p "$build_dir" + +# CMP0077=NEW makes ZenLib's option(BUILD_SHARED_LIBS) honour the OFF MediaInfoLib sets. +# CURL is disabled: MediaInfoLib then only builds the runtime-loaded (dlopen) stub. +emcmake cmake -S "$mediainfolib/Project/CMake" -B "$build_dir" \ + -DBUILD_ZENLIB=1 -DBUILD_ZLIB=0 -DBUILD_SHARED_LIBS=OFF \ + -DZLIB_INCLUDE_DIR="$zlib_src" -DZLIB_LIBRARY="$zlib_lib" \ + -DCMAKE_DISABLE_FIND_PACKAGE_CURL=ON -DCMAKE_DISABLE_FIND_PACKAGE_TinyXML=ON \ + -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_C_FLAGS="$wasm_flags" -DCMAKE_CXX_FLAGS="$wasm_flags" \ + -DCMAKE_POLICY_VERSION_MINIMUM=3.5 \ + -DCMAKE_POLICY_DEFAULT_CMP0077=NEW + +jobs="$(nproc 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null || echo 4)" +cmake --build "$build_dir" --config Release -j"$jobs" + +mi_lib="$(find "$build_dir" -name 'libmediainfo.a' -not -path '*/CMakeFiles/*' | head -n1)" +zen_lib="$(find "$build_dir" -name 'libzen.a' -not -path '*/CMakeFiles/*' | head -n1)" +if [ -z "$mi_lib" ] || [ -z "$zen_lib" ]; then + echo "Build did not produce libmediainfo.a / libzen.a under $build_dir" >&2 + exit 1 +fi + +# Merge MediaInfoLib + ZenLib into one archive, so consumers reference a single file. +out_dir="$native_proj/native/$rid" +mkdir -p "$out_dir" +out="$out_dir/libmediainfo.a" +rm -f "$out" +printf 'CREATE %s\nADDLIB %s\nADDLIB %s\nSAVE\nEND\n' "$out" "$mi_lib" "$zen_lib" | "$tools/bin/llvm-ar" -M +"$tools/bin/llvm-ranlib" "$out" +echo "Native ready: $out" diff --git a/SharpMediaInfo.Tests/Integration/MediaInfoBuilderTests.cs b/SharpMediaInfo.Tests/Integration/MediaInfoBuilderTests.cs index eabb3a2..551fe9c 100644 --- a/SharpMediaInfo.Tests/Integration/MediaInfoBuilderTests.cs +++ b/SharpMediaInfo.Tests/Integration/MediaInfoBuilderTests.cs @@ -54,6 +54,18 @@ public async Task FromStream_Wav_Parses() await Assert.That(media.AudioCount).IsEqualTo(1); } + [Test] + public async Task FromStream_BuildAsync_Parses() + { + using var stream = new MemoryStream(WavFixture.CreatePcmWav()); + + var media = await MediaInfoBuilder.FromStream(stream).WithReports().BuildAsync(); + + await Assert.That(media.AudioCount).IsEqualTo(1); + await Assert.That(media.InfoStandard).IsNotNull(); + await Assert.That(media.InfoStandard!).Contains("Audio"); + } + [Test] public async Task WithReports_PopulatesStandardReport() { diff --git a/SharpMediaInfo.Wasm.Smoke/Program.cs b/SharpMediaInfo.Wasm.Smoke/Program.cs new file mode 100644 index 0000000..ae81300 --- /dev/null +++ b/SharpMediaInfo.Wasm.Smoke/Program.cs @@ -0,0 +1,49 @@ +using SharpMediaInfo; +using SharpMediaInfo.Wasm.Smoke; + +// Exercises the native MediaInfoLib linked into the .NET WebAssembly runtime. +// Prints one line per check and returns a non-zero exit code on failure. +var failures = 0; + +void Check(string name, bool ok, string detail) +{ + Console.WriteLine($"{(ok ? "PASS" : "FAIL")} {name}: {detail}"); + if (!ok) failures++; +} + +try +{ + var version = MediaInfo.LibraryVersion(); + Check("library version", version.Contains("MediaInfoLib"), version); + + using (var small = new MemoryStream(VirtualWavStream.CreateSmall())) + { + var media = await MediaInfoBuilder.FromStream(small).WithReports().BuildAsync(); + Check("small WAV (BuildAsync)", media.AudioCount == 1 && media.InfoStandard?.Contains("PCM") == true, + $"audio={media.AudioCount}, format={media.Audio?[0].Format}"); + } + + // 2 GB virtual WAV: more than the 32-bit wasm address space could ever hold in memory. + // The title lives in a chunk after the data, so MediaInfo must ask for a seek to find it. + using (var large = new VirtualWavStream(2L * 1024 * 1024 * 1024, title: "Chunked reader")) + { + var media = await MediaInfoBuilder.FromStream(large).BuildAsync(); + var title = media.General?[0].Title; + Check("2 GB virtual WAV (chunked, seeking)", + media.AudioCount == 1 && title == "Chunked reader" && large.SeekCount >= 1 && large.BytesRead < 16L * 1024 * 1024, + $"audio={media.AudioCount}, title={title}, read {large.BytesRead / 1024} KB of {large.Length / (1024 * 1024)} MB in {large.SeekCount} seek(s)"); + } + + using (var sync = new MemoryStream(VirtualWavStream.CreateSmall())) + { + var media = MediaInfoBuilder.FromStream(sync).Build(); + Check("small WAV (Build, sync)", media.AudioCount == 1, $"audio={media.AudioCount}"); + } +} +catch (Exception ex) +{ + Check("exception", false, ex.ToString()); +} + +Console.WriteLine(failures == 0 ? "SMOKE OK" : $"SMOKE FAILED ({failures})"); +return failures == 0 ? 0 : 1; diff --git a/SharpMediaInfo.Wasm.Smoke/SharpMediaInfo.Wasm.Smoke.csproj b/SharpMediaInfo.Wasm.Smoke/SharpMediaInfo.Wasm.Smoke.csproj new file mode 100644 index 0000000..ebca85a --- /dev/null +++ b/SharpMediaInfo.Wasm.Smoke/SharpMediaInfo.Wasm.Smoke.csproj @@ -0,0 +1,21 @@ + + + + $(DotNetTfm) + Exe + enable + enable + false + + + + + + + + + diff --git a/SharpMediaInfo.Wasm.Smoke/VirtualWavStream.cs b/SharpMediaInfo.Wasm.Smoke/VirtualWavStream.cs new file mode 100644 index 0000000..c36c365 --- /dev/null +++ b/SharpMediaInfo.Wasm.Smoke/VirtualWavStream.cs @@ -0,0 +1,153 @@ +using System.Text; + +namespace SharpMediaInfo.Wasm.Smoke; + +/// +/// A seekable, read-only stream that presents a PCM WAV of arbitrary size without +/// allocating it: the 44-byte header is real, the sample data is generated on the fly +/// as zeros. An optional title is stored in a LIST/INFO chunk placed *after* the data, so +/// MediaInfo has to jump over the data to find it. It records how many bytes were read and +/// how many seeks happened, so tests can prove the analysis reads only what MediaInfo asks +/// for instead of the whole file. +/// +internal sealed class VirtualWavStream : Stream +{ + private readonly byte[] _header; + private readonly byte[] _trailer; + private readonly long _trailerStart; + private long _position; + + public VirtualWavStream(long dataSize, int sampleRate = 48000, short channels = 2, short bitsPerSample = 16, string? title = null) + { + if (dataSize <= 0 || dataSize % 2 != 0 || dataSize > uint.MaxValue - 1024) + throw new ArgumentOutOfRangeException(nameof(dataSize)); + + _trailer = title is null ? [] : CreateInfoChunk(title); + + int blockAlign = channels * bitsPerSample / 8; + using var ms = new MemoryStream(); + using (var w = new BinaryWriter(ms, Encoding.ASCII, leaveOpen: true)) + { + w.Write(Encoding.ASCII.GetBytes("RIFF")); + w.Write((uint)(36 + dataSize + _trailer.Length)); + w.Write(Encoding.ASCII.GetBytes("WAVE")); + w.Write(Encoding.ASCII.GetBytes("fmt ")); + w.Write(16); + w.Write((short)1); // PCM + w.Write(channels); + w.Write(sampleRate); + w.Write(sampleRate * blockAlign); + w.Write((short)blockAlign); + w.Write(bitsPerSample); + w.Write(Encoding.ASCII.GetBytes("data")); + w.Write((uint)dataSize); + } + _header = ms.ToArray(); + _trailerStart = _header.Length + dataSize; + Length = _trailerStart + _trailer.Length; + } + + // LIST/INFO chunk with a single INAM (title) entry. + private static byte[] CreateInfoChunk(string title) + { + var text = Encoding.ASCII.GetBytes(title + "\0"); + int padded = text.Length + (text.Length % 2); + using var ms = new MemoryStream(); + using (var w = new BinaryWriter(ms, Encoding.ASCII, leaveOpen: true)) + { + w.Write(Encoding.ASCII.GetBytes("LIST")); + w.Write(4 + 8 + padded); + w.Write(Encoding.ASCII.GetBytes("INFO")); + w.Write(Encoding.ASCII.GetBytes("INAM")); + w.Write(text.Length); + w.Write(text); + if (padded != text.Length) + w.Write((byte)0); + } + return ms.ToArray(); + } + + /// A complete one-second 8 kHz mono WAV, materialized in memory. + public static byte[] CreateSmall() + { + using var source = new VirtualWavStream(16000, sampleRate: 8000, channels: 1); + var bytes = new byte[source.Length]; + source.ReadExactly(bytes); + return bytes; + } + + /// Total bytes handed out by Read/ReadAsync. + public long BytesRead { get; private set; } + + /// Number of Seek calls / Position assignments that moved the stream. + public int SeekCount { get; private set; } + + /// Number of ReadAsync calls (to tell the async path was used). + public int AsyncReadCount { get; private set; } + + public override bool CanRead => true; + public override bool CanSeek => true; + public override bool CanWrite => false; + public override long Length { get; } + + public override long Position + { + get => _position; + set => Seek(value, SeekOrigin.Begin); + } + + public override int Read(byte[] buffer, int offset, int count) => Read(buffer.AsSpan(offset, count)); + + public override int Read(Span destination) + { + int count = (int)Math.Min(destination.Length, Length - _position); + if (count <= 0) + return 0; + + destination[..count].Clear(); + CopyOverlap(_header, 0, destination[..count]); + CopyOverlap(_trailer, _trailerStart, destination[..count]); + + _position += count; + BytesRead += count; + return count; + } + + // Copies the part of `source` (located at `sourceStart` in the stream) that overlaps the + // window [_position, _position + destination.Length). + private void CopyOverlap(byte[] source, long sourceStart, Span destination) + { + long from = Math.Max(_position, sourceStart); + long to = Math.Min(_position + destination.Length, sourceStart + source.Length); + if (from < to) + source.AsSpan((int)(from - sourceStart), (int)(to - from)).CopyTo(destination[(int)(from - _position)..]); + } + + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + AsyncReadCount++; + await Task.Yield(); // behave like real asynchronous I/O + return Read(buffer.Span); + } + + public override long Seek(long offset, SeekOrigin origin) + { + long target = origin switch + { + SeekOrigin.Begin => offset, + SeekOrigin.Current => _position + offset, + SeekOrigin.End => Length + offset, + _ => throw new ArgumentOutOfRangeException(nameof(origin)), + }; + if (target < 0) + throw new IOException("Seek before the beginning of the stream."); + if (target != _position) + SeekCount++; + _position = target; + return _position; + } + + public override void Flush() { } + public override void SetLength(long value) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); +} diff --git a/SharpMediaInfo.Wasm.Smoke/wwwroot/main.mjs b/SharpMediaInfo.Wasm.Smoke/wwwroot/main.mjs new file mode 100644 index 0000000..ad609b4 --- /dev/null +++ b/SharpMediaInfo.Wasm.Smoke/wwwroot/main.mjs @@ -0,0 +1,5 @@ +// Node entry point: node bin//net10.0/browser-wasm/AppBundle/main.mjs +import { dotnet } from './_framework/dotnet.js'; + +const exitCode = await dotnet.run(); +process.exit(exitCode); diff --git a/SharpMediaInfo/MediaInfoBuilder.cs b/SharpMediaInfo/MediaInfoBuilder.cs index 6ef69a3..b1cf1b0 100644 --- a/SharpMediaInfo/MediaInfoBuilder.cs +++ b/SharpMediaInfo/MediaInfoBuilder.cs @@ -7,6 +7,8 @@ using System.Collections.Generic; using System.IO; using System.Numerics; +using System.Threading; +using System.Threading.Tasks; namespace SharpMediaInfo { @@ -138,11 +140,7 @@ public MediaInfo Build() #if DEBUG System.Diagnostics.Debug.WriteLine($"MediaInfoBuilder.Build() - parseCoverData: {_parseCoverData}, filePath: {_filePath}"); #endif - // When building from a copy there is no file or stream to open: the data has - // already been populated, so we must not touch the native library (creating a - // handle without opening anything would both throw on Close() and overwrite the - // copied stream counts with zeros). - if (_filePath != null || _stream != null) + if (HasSource) { // NOW create and open MediaInfoNative with correct parseCoverData value _mediaInfoNative = IMediaInfoNative.Create(_parseCoverData); @@ -155,33 +153,89 @@ public MediaInfo Build() { _mediaInfoNative.OpenStream(_stream); } + } - // Parse all stream information - GetStreamCount(); - ParseAllStreams(); + return Complete(); + } + finally + { + ReleaseNative(); + } + } - // Parse reports if requested - if (_parseCompleteReport) + /// + /// Builds an immutable MediaInfo instance, reading a stream source asynchronously. + /// Use it for streams whose reads are genuinely asynchronous (browser files, network): + /// the stream is read chunk by chunk with . + /// For a file path it behaves like . + /// + /// Cancels the analysis between two stream reads. + /// An immutable MediaInfo instance. + public async Task BuildAsync(CancellationToken cancellationToken = default) + { + ThrowIfBuilt(); + + try + { + if (HasSource) + { + _mediaInfoNative = IMediaInfoNative.Create(_parseCoverData); + + if (_filePath != null) { - GetCompleteReport(); + _mediaInfoNative.OpenFile(_filePath); } - if (_parseStandardReport) + else if (_stream != null) { - GetStandardReport(); + await _mediaInfoNative.OpenStreamAsync(_stream, cancellationToken).ConfigureAwait(false); } } - _isBuilt = true; - - // Create immutable MediaInfo instance - return MediaInfo.CreateFromBuilder(this); + return Complete(); } finally { - // Dispose native handle properly - _mediaInfoNative?.Close(); - _mediaInfoNative?.Dispose(); + ReleaseNative(); + } + } + + // When building from a copy there is no file or stream to open: the data has already + // been populated, so we must not touch the native library (creating a handle without + // opening anything would both throw on Close() and overwrite the copied stream counts + // with zeros). + private bool HasSource => _filePath != null || _stream != null; + + /// Reads everything from the opened native handle and creates the instance. + private MediaInfo Complete() + { + if (HasSource) + { + // Parse all stream information + GetStreamCount(); + ParseAllStreams(); + + // Parse reports if requested + if (_parseCompleteReport) + { + GetCompleteReport(); + } + if (_parseStandardReport) + { + GetStandardReport(); + } } + + _isBuilt = true; + + // Create immutable MediaInfo instance + return MediaInfo.CreateFromBuilder(this); + } + + private void ReleaseNative() + { + // Dispose native handle properly + _mediaInfoNative?.Close(); + _mediaInfoNative?.Dispose(); } #region Initialization Methods From 395e89943df66f280e5b4de60dbb77b6f816ad48 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 11:57:00 +0000 Subject: [PATCH 2/4] CI: release from release/* branches and check the package layout; 26.10.3 Same CI changes as on the release/* maintenance branches: pushes to release/* build, tag and publish (without becoming the Latest release), and the pack job fails if a package has contentFiles or '..' entries. 26.10.2 is taken by the release/26.10 packaging fix, so this goes out as 26.10.3. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SyVioAMhEw3uuqBekTJcn2 --- .github/workflows/ci.yml | 21 ++++++++++++++++++++- BuildVersion.props | 2 +- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 295d264..a86a7c5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,6 +4,7 @@ on: push: branches: - master + - release/* pull_request: branches: - master @@ -399,6 +400,20 @@ jobs: done ls -lh artifacts + # NuGet restore rejects packages with '..' in an entry path, and natives belong under + # runtimes//native only - never as contentFiles. + - name: Check package layout + run: | + BAD=0 + for PKG in artifacts/*.nupkg; do + ENTRIES=$(unzip -Z1 "$PKG") + if printf '%s\n' "$ENTRIES" | grep -E '(^|/)\.\.(/|$)|^contentFiles/|^content/'; then + echo "::error::$(basename "$PKG") has contentFiles or '..' entries" + BAD=1 + fi + done + exit $BAD + - name: Upload NuGet artifact uses: actions/upload-artifact@v7 with: @@ -751,7 +766,9 @@ jobs: name: Tag & Release runs-on: ubuntu-latest needs: [version, test, pack, build-windows, build-linux, build-macos] - if: github.ref == 'refs/heads/master' && github.event_name != 'pull_request' + if: >- + (github.ref == 'refs/heads/master' || startsWith(github.ref, 'refs/heads/release/')) && + github.event_name != 'pull_request' permissions: contents: write statuses: write @@ -805,6 +822,8 @@ jobs: tag_name: v${{ env.VERSION }} name: v${{ env.VERSION }} generate_release_notes: true + # Maintenance releases from release/* branches must not become "Latest". + make_latest: ${{ github.ref == 'refs/heads/master' }} files: release/* # A push that does not release on purpose (build, CI or docs changes) carries diff --git a/BuildVersion.props b/BuildVersion.props index 5b0502c..e83ec68 100644 --- a/BuildVersion.props +++ b/BuildVersion.props @@ -3,7 +3,7 @@ - 26.10.1 + 26.10.3 From 386568864cae6d3a73a99bddf972fd6bb5de4adc Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 12:25:08 +0000 Subject: [PATCH 3/4] CI: build the WebAssembly parts with the .NET 10 SDK The runner image now ships a newer SDK that takes precedence over the one setup-dotnet installs. With it the net10.0 smoke app would need wasm-tools-net10 and WasmBuildNative isn't applied, and the browser-wasm archive is compiled with that SDK's Emscripten. Pin the SDK with global.json in the two wasm jobs and invalidate the browser-wasm native cache entry. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SyVioAMhEw3uuqBekTJcn2 --- .github/workflows/ci.yml | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a86a7c5..4008079 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -146,7 +146,7 @@ jobs: with: path: SharpMediaInfo.Native/native # browser-wasm also depends on the workload's Emscripten, i.e. on the .NET version. - key: native-${{ matrix.rid }}-${{ steps.key.outputs.submodules }}-${{ matrix.rid == 'browser-wasm' && format('{0}-{1}', env.DOTNET_VERSION, hashFiles('SharpMediaInfo.Native/build/build-native-wasm.sh')) || hashFiles('SharpMediaInfo.Native/build/build-native.*') }} + key: native-${{ matrix.rid }}-${{ steps.key.outputs.submodules }}-${{ matrix.rid == 'browser-wasm' && format('{0}-sdk-pinned-{1}', env.DOTNET_VERSION, hashFiles('SharpMediaInfo.Native/build/build-native-wasm.sh')) || hashFiles('SharpMediaInfo.Native/build/build-native.*') }} - name: Fetch submodules if: steps.cache.outputs.cache-hit != 'true' @@ -162,12 +162,19 @@ jobs: run: brew install cmake - name: Setup .NET (WebAssembly) + id: setup-dotnet if: steps.cache.outputs.cache-hit != 'true' && matrix.rid == 'browser-wasm' uses: actions/setup-dotnet@v6 with: dotnet-version: ${{ env.DOTNET_VERSION }} dotnet-quality: 'ga' + # The runner image ships a newer SDK, which would otherwise win: its wasm-tools workload + # brings a different Emscripten than the .NET 10 runtime the archive is linked into. + - name: Pin the .NET SDK + if: steps.cache.outputs.cache-hit != 'true' && matrix.rid == 'browser-wasm' + run: dotnet new globaljson --sdk-version "${{ steps.setup-dotnet.outputs.dotnet-version }}" --force + - name: Install wasm-tools workload if: steps.cache.outputs.cache-hit != 'true' && matrix.rid == 'browser-wasm' run: dotnet workload install wasm-tools @@ -320,11 +327,17 @@ jobs: run: git submodule update --init --depth 1 extern/MediaInfoLib - name: Setup .NET + id: setup-dotnet uses: actions/setup-dotnet@v6 with: dotnet-version: ${{ env.DOTNET_VERSION }} dotnet-quality: 'ga' + # With a newer SDK on the runner a net10.0 browser app would need wasm-tools-net10, and + # WasmBuildNative would silently not link the archive. Build with the SDK 10 just set up. + - name: Pin the .NET SDK + run: dotnet new globaljson --sdk-version "${{ steps.setup-dotnet.outputs.dotnet-version }}" --force + - name: Install wasm-tools workload run: dotnet workload install wasm-tools From a7f7ba1f3ba766164a323bbfa7fb9c33fde88f7a Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 12:55:29 +0000 Subject: [PATCH 4/4] ci: find the workload's Node under DOTNET_ROOT in the WASM smoke test setup-dotnet installs to /usr/share/dotnet on hosted runners, so the $HOME/.dotnet glob matched nothing and ls exited 2, aborting the step under bash -e -o pipefail before the PATH fallback ran. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SyVioAMhEw3uuqBekTJcn2 --- .github/workflows/ci.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4008079..b2986df 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -356,7 +356,10 @@ jobs: - name: Run smoke test (Node) shell: bash run: | - NODE="$(ls -d "$HOME"/.dotnet/packs/Microsoft.NET.Runtime.Emscripten.*.Node.linux-x64/*/tools/bin/node 2>/dev/null | sort -V | tail -n1)" + # The workload's Node lives under the SDK root (/usr/share/dotnet on + # hosted runners). `ls` exits 2 when nothing matches, which aborts the + # step under bash -e -o pipefail, so guard it. + NODE="$( (ls -d "${DOTNET_ROOT:-$HOME/.dotnet}"/packs/Microsoft.NET.Runtime.Emscripten.*.Node.linux-x64/*/tools/bin/node 2>/dev/null || true) | sort -V | tail -n1)" [ -x "$NODE" ] || NODE="$(command -v node)" cd artifacts/wasm-smoke/wwwroot "$NODE" main.mjs