The Duplex Sample 2.0 is a Windows application that sends and receives video and audio through a WebRTC 2.0 channel, between SDK applications and browser guests. This article shows how to run the C# version and how its WebRTCHelper class uses the MConnect API. It is installed in Samples WebRTC\C#\WebRTC 2.0 (MFormats: Sample Duplex 2.0, MPlatform: Duplex Sample 2.0); the code below is from the MFormats version.
Run the sample
- Start the sample. The channel URL is filled in as
https://videosdk.medialooks.com:8080/Room/<computer name>. Use a name that is hard to guess. - Choose a source: <Live Source> (then choose the video and audio devices and click Init Device), <File>, or an external
mp://sender. - Choose the video codec (
vp8,vp9,cpu_h264,gpu_h264) and the bitrate (default5M). - Click Start streaming. If the channel does not exist yet, this instance creates it and becomes the Host (the window title shows
Duplex mode: server). - Start a second instance, on this or another computer, with the same channel URL. It joins as a Guest (
Duplex mode: client). - Or let a browser in: the Host shows a Web Guest Link (
https://<server>/wg2/<id>, with camera and microphone) and a Web Preview Link (https://<server>/<id>, watch only).
A Host with several guests shows the guest selected in the remote peer list, or all of them with Mix All Remote peers. Output to device sends the received video to a renderer. The codec can be changed while streaming; the bitrate is applied when you start. A channel URL with ?receive=1 only receives and opens no local source.
Create or join the channel
The helper first asks the signaling server for the list of channels, with Enum_Create on a separate URL. If the channel URL is listed, it joins; otherwise it creates the channel:
server.Enum_Create(URL + "_enum", $"username={userName} password={password}", " ", null, out server_manager);
if (isChanneAlreadyExists())
{
current_channel = ConnectToChannel(channel_url); // Guest
mode = PeerMode.client;
}
else
{
current_channel = CreateChannel(channel_url); // Host
current_channel.OnEventSafe += new IMEventsEvent_OnEventSafeEventHandler(Current_channel_OnEventSafe);
mode = PeerMode.server;
}
The list is read with VTSG_EnumGetCount and VTSG_EnumGetByIndex:
server_manager.VTSG_EnumGetCount(null, out var count, null);
for (int i = 0; i < count; i++)
{
server_manager.VTSG_EnumGetByIndex("", i, out var channel, out var channel_props);
if (channel.Equals(channel_url))
return true;
}
The Guest connects with a name; the Host can set a constant ID, so that its web links do not change (Constant stream ID), and mark the channel as protected:
// Guest
server.Channel_Connect(_url, "name=my_receiver", "", callback, out var channel);
// Host
var segments = new Uri(_url).AbsolutePath.Trim('/').Split('/');
server.Channel_Create(_url, (constant_id ? $"id={segments[1]}" : "") + (secure.IsProtected() ? " secured='true'" : ""), "", callback, out var channel);
The helper keeps the channel as MCChannelClass ((MCChannelClass)channel), which in C# gives access to PropsSet and PropsGet. After that the sample switches mix-minus on, so that a guest does not hear itself, see WebRTC Mix-Minus:
current_channel.PropsSet("mix_minus.enabled", "true");
current_channel.PropsSet("mix_minus.src_channels", "all");
current_channel.PropsSet("mix_minus.delay_msec", "300");
current_channel.PropsSet("mix_minus.audio.level_msec", "300");
current_channel.PropsSet("mix_minus.level_db", "-10");
The first line switches mix-minus on. For the other properties see the optional settings of mix-minus.
Protect the channel
The key button opens the Protection Form. With Anonymous Access switched on (the default), the channel is open. Switch it off and add users with a password and an optional expiry date. The Host then creates the channel with secured='true', the web guest page asks for a login and a password, and the Host checks them in the remote_offer event.
The event arrives with the attribute succeeded already set to true: the guest is accepted unless the handler sets it to false. Reject the guest first and accept it only after a valid login:
void Current_channel_OnEventSafe(string bsChannelID, string bsEventName, string bsEventParam, object pEventObject)
{
if (bsEventName != "remote_offer")
return;
var attributes = pEventObject as MFORMATSLib.IMAttributes; // MPLATFORMLib in MPlatform
if (attributes == null || !secure.IsProtected()) // Anonymous Access: every guest is accepted
return;
// Reject first, accept only a valid login
attributes.AttributesStringSet("succeeded", "false");
attributes.AttributesStringSet("reason", "not_authorized");
// These calls throw if the guest sent no credentials
attributes.AttributesStringGet("guest_login", out string guest_login);
attributes.AttributesStringGet("guest_password", out string guest_password);
if (secure.IsValid(guest_login, guest_password))
{
attributes.AttributesStringSet("succeeded", "true");
attributes.AttributesRemove("reason");
}
}
The order matters. If a guest sends no login or no password, AttributesStringGet throws and the lines after it do not run. The SDK also waits at most one second for the handler and then uses the value that succeeded has at that moment. So reject before you read or check anything, keep the check quick and do not block the thread that receives the events.
Important: replace the handler in your copy of the sample if it sets the attribute succeded (with one e after the two c) or reads the login before it rejects the guest. The SDK reads only succeeded, so with the misspelled name every web guest is accepted. Correcting the spelling alone is not enough: a guest that sends no credentials is still accepted.
The check applies to web guests. An application that connects with Channel_Connect is not checked by it. The Delphi version of the sample has no guest protection: it creates the channel without secured and does not handle remote_offer.
Send and receive
A worker thread takes frames from the source, sends them into the channel and shows them in the local preview:
m_objLive.SourceFrameConvertedGet(ref m_avProps, 100 * 10000, out pFrame, ""); // or m_objReader for a file
current_channel.ChannelSend(-1, pFrame, "");
m_objPreview.ReceiverFramePut(pFrame, -1, "");
Marshal.ReleaseComObject(pFrame);
Another thread receives. A Guest receives from the Host and passes an empty peer ID. A Host passes the ID of the guest it wants to show:
object frame = null;
if (mode == PeerMode.server)
current_channel.ChannelReceive(0, -1, show_remote_peer, out frame, ""); // the selected guest
else
current_channel.ChannelReceive(0, -1, "", out frame, ""); // the Host
With Mix All Remote peers the Host receives a frame from every guest and places up to four of them in a 2x2 grid on a 1920x1080 frame (MFFactory.MFFrameCreateFromMem, MFConvert, MFOverlay). The mixed picture is also published as the mp:// sender Multiview, which can be chosen as the source to send it back to the guests.
Connected peers and state
The IDs of the connected guests are properties of the channel:
current_channel.ChannelInfoGet(out var info);
for (int i = 0; i < info.nChannelsConnected; i++)
current_channel.PropsGet($"connected[{i}]::remote::id", out string peerId);
The Events log shows the structure returned by ChannelInfoGet. With MConnect only the signaling state (eSGNState) and the number of connected peers (nChannelsConnected) are filled. In your own application read traffic, frame rate and latency from the stat:: properties of the channel:
current_channel.PropsGet("stat::send_total_kbps", out string kbps);
The signaling server also lists the peers it knows. The method GetRoomMembers of the helper reads them with VTSG_EnumGetByIndex and leaves out the entries with mode enum, which are connections that only read the list, and its own ID.
An application does not have to restore a lost connection to the signaling server: MConnect reconnects by itself, every 5 seconds by default (property sgn.reconnect_interval_msec).
Close
current_channel.ChannelDisconnect(channel_url, "");
current_channel.ChannelClose("");
Release every frame that SourceFrameGet or ChannelReceive returns, otherwise the memory use grows. In your own application do not change controls directly from the sending and receiving threads.
The MPlatform version
The WebRTC calls are the same. The helper works with MFrame instead of MFFrame, the sources are MFile and MLive objects (SourceFrameGet(-1, out frame, 0)), and the previews are MPreview objects (ReceiverPutFrame("", frame)). An MFormats application can be connected to a channel of an MPlatform application and the other way round.
Reference and help
- MConnectClass, IMCChannel, IMCChannelSGN
- MConnect properties
- If something does not work, see WebRTC 2.0 FAQ and troubleshooting.
Still have questions?
Tell us what didn’t work or what you’d like clarified.