Skip to content

The unified API

Melih Ercan edited this page Sep 16, 2026 · 2 revisions

The unified API

This is the WebRTCme package and the WebRTCme.dll assembly — the layer that turns five different native SDKs into one C# surface, and the only one most consumers ever touch.

It is two things in one assembly, which is worth knowing before reading the source:

  • Api/ — the common surface. Interfaces, models and enums that mirror the W3C WebRTC 1.0 API. Nothing platform-specific, no implementation.
  • Platforms/{Blazor,Android,iOS,MacCatalyst,Windows}/ — five implementations of it, each calling one binding. Exactly one is compiled into any given build.

The surface mirrors the browser's

The design rule is one sentence: if you have used WebRTC in JavaScript, you already know this API. The same objects, the same methods, the same events, in C# casing.

JavaScript C#
new RTCPeerConnection(config) window.RTCPeerConnection(config)
pc.createOffer() await pc.CreateOffer()
pc.setLocalDescription(offer) await pc.SetLocalDescription(offer)
pc.onicecandidate = … pc.OnIceCandidate += …
pc.createDataChannel("x") pc.CreateDataChannel("x")
navigator.mediaDevices.getUserMedia(c) await window.Navigator().MediaDevices.GetUserMedia(c)

So the MDN WebRTC documentation and the W3C specification are usable references for this API, which is the point — rather than inventing a .NET-shaped abstraction and documenting it from scratch.

Roughly: 31 interfaces, 46 models, 30 enums.

Getting in

There is one entry point, and it needs no dependency injection:

IWebRtc  webRtc = CrossWebRtc.Current;       // the platform's plug-in
IWindow  window = webRtc.Window(jsRuntime);  // jsRuntime is Blazor-only; ignored elsewhere

IWindow is the factory for everything else, standing in for the browser's window:

public interface IWindow : IDisposable
{
    INavigator Navigator();
    IMediaStream MediaStream();
    IRTCPeerConnection RTCPeerConnection(RTCConfiguration configuration = null);
    IMediaRecorder MediaRecorder(IMediaStream stream, MediaRecorderOptions options = null);
}

INavigator.MediaDevices gets you to capture:

var devices = window.Navigator().MediaDevices;
var stream  = await devices.GetUserMedia(new MediaStreamConstraints
{
    Audio = new MediaStreamContraintsUnion { Value = true },
    Video = new MediaStreamContraintsUnion { Value = true }
});

That is more ceremony than JavaScript's { audio: true, video: true }, and the next section explains why it has to be.

The IJSRuntime argument. Blazor is JSInterop over the browser's own WebRTC, so it needs the runtime handle that a component gets injected and a plain class cannot reach. The other four bindings take the argument and ignore it, so passing it unconditionally is correct on every platform — and means one piece of code runs everywhere. See Hello world.

What is on IRTCPeerConnection

The W3C surface, near enough in full:

// state
RTCPeerConnectionState ConnectionState { get; }
RTCIceConnectionState  IceConnectionState { get; }
RTCIceGatheringState   IceGatheringState { get; }
RTCSignalingState      SignalingState { get; }
RTCSessionDescriptionInit LocalDescription  { get; }
RTCSessionDescriptionInit RemoteDescription { get; }

// events
event EventHandler<IRTCPeerConnectionIceEvent> OnIceCandidate;
event EventHandler<IRTCDataChannelEvent>       OnDataChannel;
event EventHandler<IRTCTrackEvent>             OnTrack;
event EventHandler OnConnectionStateChanged;
event EventHandler OnNegotiationNeeded;
// … and OnIceCandidateError, OnIceConnectionStateChange,
//     OnIceGatheringStateChange, OnSignalingStateChange

// negotiation
Task<RTCSessionDescriptionInit> CreateOffer(RTCOfferOptions options = null);
Task<RTCSessionDescriptionInit> CreateAnswer(RTCAnswerOptions options = null);
Task SetLocalDescription(RTCSessionDescriptionInit description);
Task SetRemoteDescription(RTCSessionDescriptionInit description);
Task AddIceCandidate(RTCIceCandidateInit candidate);

// media and data
IRTCRtpSender      AddTrack(IMediaStreamTrack track, IMediaStream stream);
IRTCRtpTransceiver AddTransceiver(MediaStreamTrackKind kind, RTCRtpTransceiverInit init = null);
IRTCDataChannel    CreateDataChannel(string label, RTCDataChannelInit options = null);
Task<IRTCStatsReport> GetStats();

Events are plain .NET EventHandlers rather than the browser's on… properties, so several subscribers work. Unsubscribe when you are done: on Blazor each subscription registers a JavaScript listener, and a wrapper rebuilt per call that keeps adding listeners is a leak this codebase has shipped before.

IMediaDevices

Task<MediaDeviceInfo[]> EnumerateDevices();
Task<IMediaStream> GetUserMedia(MediaStreamConstraints constraints);
Task<IMediaStream> GetDisplayMedia(MediaStreamConstraints constraints);
MediaTrackSupportedConstraints GetSupportedConstraints();
event EventHandler<IMediaStreamTrackEvent> OnDeviceChange;

GetDisplayMedia is the one method whose behaviour genuinely differs by platform — see What works where.

OnDeviceChange is declared here but, on the native platforms, the IMediaDevices instance is held privately by the implementation and a consumer has no route to it. The middleware's ILocalMediaStream.OnDeviceChange is that route.

Constraints, and the JSON underneath

In JavaScript a constraint is a union — a bare value, or an object with ideal / exact / min / max. C# has no union types, so each one is modelled as a class with a Value and an Object, and you set whichever you mean: MediaStreamContraintsUnion, ConstrainBoolean, ConstrainDouble, ConstrainULong, ConstrainDOMString.

That is the one place this API is visibly clumsier than the browser's, and it is the price of mirroring the specification exactly rather than inventing a friendlier shape that then cannot express half of it.

var constraints = new MediaStreamConstraints
{
    Audio = new MediaStreamContraintsUnion { Value = true },
    Video = new MediaStreamContraintsUnion
    {
        Object = new MediaTrackConstraints
        {
            Width      = new ConstrainULong  { Object = new ConstrainULongRange  { Ideal = 1280 } },
            Height     = new ConstrainULong  { Object = new ConstrainULongRange  { Ideal = 720 } },
            FrameRate  = new ConstrainDouble { Object = new ConstrainDoubleRange { Ideal = 30 } },
            FacingMode = new ConstrainDOMString
            {
                Ideal = new ConstrainDOMStringUnion { Value = "user" }
            }
        }
    }
};

ILocalMediaStream.GetCameraMediaStreamAsync in the middleware wraps the common cases, so most apps never write this by hand.

Each constraint type has a JsonConverter applied by attribute, along with converters for all 29 enums, so the models serialise to exactly the shape the browser expects. That matters beyond Blazor — the same models are what the SDP layer and the mediasoup client round-trip.

How one assembly holds five implementations

A bait-and-switch multi-target. WebRTCme.csproj sets EnableDefaultCompileItems=false and picks the source per target framework:

<ItemGroup Condition="'$(TargetFramework)' == 'net10.0-android'">
  <Compile Include="**\Android\**\*.cs" />
  <Compile Include="*.cs" />
  <ProjectReference Include="…WebRTCme.Bindings.Maui.Android.csproj" PrivateAssets="all" />
</ItemGroup>

Api/** is compiled into every slice; exactly one Platforms/ folder joins it. So every slice exports identical public types with a different implementation behind them, and WebRtc.Create() — the thing CrossWebRtc.Current calls — resolves to whichever one was compiled.

flowchart LR
  proj["WebRTCme.csproj<br/>one project<br/>five target frameworks"]

  subgraph Slices["lib/ folders in the package"]
    direction TB
    s1["net10.0<br/>Api + Platforms/Blazor"]
    s2["net10.0-android<br/>Api + Platforms/Android"]
    s3["net10.0-ios<br/>Api + Platforms/iOS"]
    s4["net10.0-maccatalyst<br/>Api + Platforms/MacCatalyst"]
    s5["net10.0-windows…<br/>Api + Platforms/Windows"]
  end

  proj --> Slices
  Slices --> pick["NuGet picks one,<br/>by your app's TFM"]
Loading

The trap this creates, and it is worth understanding. NuGet falls back. A net10.0-android project restoring a package with no Android slice resolves lib/net10.0/ instead and compiles perfectly, because the API is identical across slices — but nothing implements it on that platform. Nothing says so until the app runs on a phone and finds nothing behind the interface. That is why Hello world exists, and why Tests/Test-Package.ps1 reads project.assets.json back and requires every target framework to have resolved its own slice rather than settling for a successful compile. See Testing.

What is folded into the package

flowchart LR
  subgraph pkg["WebRTCme.nupkg"]
    direction TB
    a["WebRTCme.dll<br/>Api + one Platforms folder"]
    b["WebRTCme.Bindings.*.dll<br/>one per slice"]
    c["native payload<br/>.aar · .resources.zip · runtimes/win-x64"]
    d["_content/WebRTCme/JsInterop.js"]
  end
  api2["Api/ — was WebRTCme.Api"] --> a
  bnd["five binding projects"] --> b
Loading

Three things vanished as separate packages in this release and are now inside this one: WebRTCme.Api, WebRTCme.Bindings and WebRTCme.Bindings.Blazor. WebRTCme.Api went furthest — it is no longer even a separate assembly. Its types kept the WebRTCme namespace, so no source edit is needed. See Releases.

The mechanics, and the reasons each one is the way it is, are in doc/Packaging.md. Read it before changing anything there: dotnet pack drops payloads it does not recognise silently, which is how this repository has historically shipped broken packages.

Where next

Middleware The layer above: a video tile, managers, view models
Connection Signalling done for you, peer-to-peer or through an SFU
Bindings The layer below: what each platform implementation calls
What works where Which parts of this surface are real on which platform

Clone this wiki locally

⌂ 换网址