Skip to content

Add a Unity audio/video source example, with a netstandard2.1 build of SIPSorcery.VP9 - #1965

Merged
sipsorcery merged 4 commits into
masterfrom
examples/unity-audio-video-source
Dec 4, 2026
Merged

sipsorcery merged 4 commits into
masterfrom
examples/unity-audio-video-source

Conversation

@sipsorcery

@sipsorcery sipsorcery commented Dec 4, 2026 •

Copy link
Copy Markdown
Member

Adds examples/WebRTCExamples/UnityAudioVideoSource: a Unity game (the robot from Unity Hub's Get Started With Unity template) streams its camera view and audio to a browser over a SIPSorcery peer connection. Everything is managed code: video is VP9 from SIPSorcery.VP9, which now also builds for netstandard2.1 so that Unity's Mono can load it.

The full Unity project was too big for the repo: 253 MB, two thirds of it the template's tutorial videos. So this is an overlay: only the example's own files. You apply it to a project created from the template, and no Unity template content is committed.

What's in it

  • Assets/Scripts/WebRTCVideoSource.cs streams the game:
    • Video: a mirror camera renders to a 640x360 RenderTexture, read back at 25 fps and VP9-encoded with VP9Codec (speed 9, up to 4 threads). RTP timestamps come from each frame's capture time.
    • Audio: the AudioListener's mix is Opus-encoded.
    • Signaling: an in-process HttpListener serves the browser page and the offer/answer on http://localhost:8081.
    • It logs a warning once if the scene has no MainCamera, and if the editor is in Debug code optimisation (the encoder is about 4x slower there).
  • Assets/Editor/SIPSorcerySceneSetup.cs places the PlayerRobot and the background music in GetStarted_Scene and saves it. The template ships the scene without the robot, and the robot carries the camera and the AudioListener; without it the Game view says "No cameras rendering".
    • It runs once by itself, and again on demand from SIPSorcery > Add Robot And Music To Scene.
  • setup.ps1 -ProjectPath <project> builds SIPSorcery and SIPSorcery.VP9 for netstandard2.1 into Assets/Plugins/SIPSorcery and copies the scripts in.
    • It removes DLLs an older copy of the example left behind: the FFmpeg plugins, and DLLs directly in Assets/Plugins, since Unity refuses duplicate assemblies.
  • Assets/Editor/AutoPlaySmokeTest.cs enters play mode from -executeMethod, for testing without the editor window.
  • README.md covers the setup steps, measured encode times, and notes:
    • Opus only.
    • Unity's own Microsoft.Extensions 8.0 assemblies.
    • runInBackground.
    • The iet-framework 6.x namespace change when upgrading a project.

The netstandard2.1 build already uses the 8.0 Microsoft.Extensions packages (src/Directory.Packages.props), which matches what Unity 6000.5+ ships. So the script needs no version pin, and the plugins need no .meta tweaks.

SIPSorcery.VP9 for netstandard2.1

SIPSorcery.VP9 now targets netstandard2.1;net8.0;net9.0;net10.0. The netstandard2.1 build has no SIMD and no [InlineArray]:

  • The port tools write its inline arrays as nested structs (port.py arrays-netstandard) and each SIMD kernel's name as a call to its C kernel (simd.py fallback), into netstandard/.
  • fixerr.py has a netstandard2.1 pass that takes element addresses through crt.addr(ref ...).
  • netstandard/polyfills.cs stands in for the missing APIs.
  • Its output is byte-identical to the .NET builds.

Two fixes Mono needed:

  • Worker hooks: Mono's &method is a trampoline until the method is compiled and its code afterwards. worker_threads now also matches hooks by GetFunctionPointer; without it, 2+ threads deadlocked.
  • Discarded struct reads: Roslyn keeps a pointer-field read whose value is discarded ((void)p->f, 0 * p->f, an unused local) as a load of the whole struct, then pop. CoreCLR turns that into a null check, but Mono copies the struct onto the stack. For VP9_COMP that's 937 KB, which overflowed Unity's 1 MB thread stack on the first inter frame.
    • patches.py discarded_reads() removes these reads when the port is regenerated.
    • StackFrameTests scans the IL for any that come back.
    • The encoder's stack use on Mono fell from about 1 MB to under 200 KB.

Also

Adds three settings files to the older examples/WebRTCExamples/UnityVideoSource project: MemorySettings.asset, MultiplayerManager.asset and VersionControlSettings.asset in ProjectSettings. A current Unity 6 editor writes them when it opens the project. They hold only Unity's default values, and committing them stops them showing up as untracked.

Testing

  • Created a fresh project from template com.unity.template.get-started 2.1.1 with Unity 6000.6.12f1 and ran setup.ps1 on it.
  • Played it headless with -executeMethod AutoPlaySmokeTest.Run. The browser at http://localhost:8081 received the robot's view at 640x360 and 25 fps, plus Opus audio. The encoder took about 13 ms a frame at 1 Mbit/s.
    • With -debugCodeOptimization it ran at about 17 fps (55 ms a frame), and the warning was logged.
  • Ran the plugin cleanup on a copy of an older project's Assets/Plugins.
  • SIPSorcery.VP9.UnitTest (22, including StackFrameTests) and SIPSorcery.VP9.TestVectors (264) pass on net10.
  • A full regeneration of the port reproduces the committed C# exactly.
  • On Unity's x64 Mono, the netstandard2.1 build gives the same encoded stream as the .NET 10 SIMD build.

Pull request CI doesn't build SIPSorcery.VP9; the tag-triggered NuGet workflow packs it, and the package will now include a netstandard2.1 library. Only the Unity editor was tested, not player builds.

🤖 Generated with Claude Code

sipsorcery and others added 2 commits December 3, 2026 23:54
…ed template

The Unity project that streams the Get Started robot game to a browser was too big to keep
in the repo (253 MB, two thirds of it the template's tutorial videos). This adds only what
the example itself needs, to be applied to a project created from Unity Hub's "Get Started
With Unity" template:

- WebRTCVideoSource.cs streams the game camera (VP8 via SIPSorceryMedia.FFmpeg) and the
  AudioListener's mix (Opus) over a SIPSorcery peer connection, with signaling and the
  browser page served on http://localhost:8081.
- SIPSorcerySceneSetup.cs places the PlayerRobot (which carries the camera and the
  AudioListener) and the background music in the template's scene, which ships without
  them, so the Game view and the stream aren't empty.
- setup.ps1 builds the SIPSorcery libraries for netstandard2.1 into
  Assets/Plugins/SIPSorcery and copies the scripts into the project.

Tested on a fresh project from template 2.1.1 with Unity 6000.6.12f1: 960x540 VP8 at
about 25 fps and Opus audio in the browser.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Opening the UnityVideoSource project in a current Unity 6 editor writes three
ProjectSettings files that the repo didn't have: MemorySettings.asset,
MultiplayerManager.asset and VersionControlSettings.asset. They hold only
Unity's default values. Committing them, as Unity expects for ProjectSettings,
stops them showing up as untracked every time the project is opened.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Comment on lines +157 to +160
catch (Exception excp)
{
Debug.LogError($"WebRTCVideoSource failed to initialise: {excp}");
}
Comment on lines +291 to +294
catch (Exception excp)
{
logger.LogError($"Encode loop failed: {excp}");
}
Comment on lines +355 to +358
catch (Exception excp)
{
logger.LogError($"Audio send loop failed: {excp}");
}
return dir;
}
}
catch { /* malformed PATH entry */ }
{
HttpListenerContext ctx;
try { ctx = await _http.GetContextAsync().ConfigureAwait(false); }
catch { break; }
Comment on lines +464 to +468
catch (Exception excp)
{
logger.LogError($"HTTP handler error: {excp.Message}");
try { ctx.Response.StatusCode = 500; ctx.Response.Close(); } catch { }
}
catch (Exception excp)
{
logger.LogError($"HTTP handler error: {excp.Message}");
try { ctx.Response.StatusCode = 500; ctx.Response.Close(); } catch { }
{
Destroy(_audioTap);
}
try { _http?.Stop(); } catch { }
}
}
}
catch (OperationCanceledException) { }
}
}
}
catch (OperationCanceledException) { }
sipsorcery and others added 2 commits December 4, 2026 08:28
SIPSorcery.VP9 now also targets netstandard2.1, the profile Unity loads.
That build has no SIMD (no Vector128) and no [InlineArray]: the tools
write its inline arrays as nested structs (port.py arrays-netstandard)
and each SIMD kernel's name as a call to its C kernel (simd.py
fallback). fixerr.py gets a netstandard2.1 pass that takes element
addresses through crt.addr(ref ...), and netstandard/polyfills.cs
stands in for the missing APIs. The output is byte-identical to the
.NET builds.

Two fixes Mono needed:

- Mono's &method is a trampoline until the method is compiled and its
  code afterwards, so worker_threads matches hooks by
  GetFunctionPointer as well. Without it, 2+ threads deadlocked.
- Roslyn keeps a pointer-field read whose value is discarded
  ((void)p->f, 0 * p->f, an unused local) as a load of the whole
  struct then pop. CoreCLR makes that a null check; Mono copies the
  struct onto the stack, 937 KB for VP9_COMP, which overflowed Unity's
  1 MB thread stack on the first inter frame. patches.py
  discarded_reads() removes these reads, and StackFrameTests checks the
  IL for any that come back. The encoder's stack use on Mono fell from
  about 1 MB to under 200 KB.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
UnityAudioVideoSource now VP9-encodes with VP9Codec from SIPSorcery.VP9's
netstandard2.1 build, so the example is all managed code and FFmpeg
needn't be installed. setup.ps1 publishes SIPSorcery.VP9 in place of
SIPSorceryMedia.FFmpeg and removes the FFmpeg plugins an earlier run
left.

- The stream is 640x360 at speed 9 on up to 4 threads: about 15 ms a
  frame on Unity's Mono in Release code optimisation, so 25 fps.
- Each frame's RTP timestamp comes from its capture time, so a slow
  encode doesn't slow the video down.
- The editor's default Debug code optimisation makes the encoder about
  4x slower (about 17 fps); the script logs a warning then, and the
  README has the measured times and how to change the size.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@sipsorcery sipsorcery changed the title Add a Unity audio/video source example as an overlay on the Get Started template Add a Unity audio/video source example, with a netstandard2.1 build of SIPSorcery.VP9 Dec 4, 2026
@sipsorcery
sipsorcery merged commit 7ef05b1 into master Dec 4, 2026
6 checks passed
@sipsorcery
sipsorcery deleted the examples/unity-audio-video-source branch December 4, 2026 08:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant