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
110 changes: 104 additions & 6 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ on:
push:
branches:
- master
- release/*
pull_request:
branches:
- master
Expand All @@ -29,8 +30,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
Expand Down Expand Up @@ -119,6 +120,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
Expand All @@ -139,7 +145,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}-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'
Expand All @@ -154,11 +161,31 @@ jobs:
if: steps.cache.outputs.cache-hit != 'true' && runner.os == 'macOS'
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

- 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 }}
Expand Down Expand Up @@ -284,10 +311,63 @@ 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
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

# 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: |
# 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

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:
Expand Down Expand Up @@ -336,6 +416,20 @@ jobs:
done
ls -lh artifacts

# NuGet restore rejects packages with '..' in an entry path, and natives belong under
# runtimes/<rid>/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:
Expand Down Expand Up @@ -688,7 +782,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
Expand Down Expand Up @@ -742,6 +838,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
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -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-*/
Expand Down
2 changes: 1 addition & 1 deletion BuildVersion.props
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<!-- The release version: bump this, and merging to master tags and publishes vX.Y.Z.
CI passes a pre-release VersionSuffix for pull request builds (pr.12.34 -> 26.10.1-pr.12.34).
Keep it aligned with MediaInfoVersion: the libraries ship the MediaInfo version. -->
<VersionPrefix>26.10.1</VersionPrefix>
<VersionPrefix>26.10.3</VersionPrefix>
</PropertyGroup>

<PropertyGroup>
Expand Down
32 changes: 31 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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) | — |

---
Expand Down Expand Up @@ -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()`.

---

Expand All @@ -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
Expand Down
144 changes: 144 additions & 0 deletions SharpMediaInfo.Native.Tests/Fixtures/VirtualWavStream.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
using System.Text;

namespace SharpMediaInfo.Native.Tests.Fixtures;

/// <summary>
/// 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.
/// </summary>
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();
}

/// <summary>Total bytes handed out by Read/ReadAsync.</summary>
public long BytesRead { get; private set; }

/// <summary>Number of Seek calls / Position assignments that moved the stream.</summary>
public int SeekCount { get; private set; }

/// <summary>Number of ReadAsync calls (to tell the async path was used).</summary>
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<byte> 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<byte> 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<int> ReadAsync(Memory<byte> 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();
}
Loading
Loading