|
| 1 | +//----------------------------------------------------------------------------- |
| 2 | +// Filename: Program.cs |
| 3 | +// |
| 4 | +// Description: An example WebRTC server application that attempts to send a |
| 5 | +// test pattern to a browser peer and that uses a prototype .NET version of the |
| 6 | +// VP8 encoder. A web socket is used for signalling. |
| 7 | +// |
| 8 | +// The point of this demo is that it does not require any native libraries or |
| 9 | +// audio/video devices. This makes it a good palce to start for checking |
| 10 | +// whether a particular platform can be used to establish WebRTC connections |
| 11 | +// and get a media strem flowing. |
| 12 | +// |
| 13 | +// TODO: Not available until the VP8.NET project ports the encoder. |
| 14 | +// |
| 15 | +// Author(s): |
| 16 | +// Aaron Clauson ([email protected]) |
| 17 | +// |
| 18 | +// History: |
| 19 | +// 12 Mar 2025 Aaron Clauson Created, Dublin, Ireland. |
| 20 | +// |
| 21 | +// License: |
| 22 | +// BSD 3-Clause "New" or "Revised" License, see included LICENSE.md file. |
| 23 | +//----------------------------------------------------------------------------- |
| 24 | + |
| 25 | +using System; |
| 26 | +using System.Collections.Generic; |
| 27 | +using System.Linq; |
| 28 | +using System.Net; |
| 29 | +using System.Threading; |
| 30 | +using System.Threading.Tasks; |
| 31 | +using Microsoft.Extensions.Logging; |
| 32 | +using Microsoft.Extensions.Logging.Abstractions; |
| 33 | +using Serilog; |
| 34 | +using Serilog.Extensions.Logging; |
| 35 | +using SIPSorcery.Media; |
| 36 | +using SIPSorcery.Net; |
| 37 | +using Vpx.Net; |
| 38 | +using WebSocketSharp.Server; |
| 39 | + |
| 40 | +namespace demo |
| 41 | +{ |
| 42 | + class Program |
| 43 | + { |
| 44 | + private const int WEBSOCKET_PORT = 8081; |
| 45 | + private const string STUN_URL = "stun:stun.cloudflare.com"; |
| 46 | + |
| 47 | + private static Microsoft.Extensions.Logging.ILogger logger = NullLogger.Instance; |
| 48 | + |
| 49 | + static void Main() |
| 50 | + { |
| 51 | + Console.WriteLine("WebRTC Get Started"); |
| 52 | + |
| 53 | + logger = AddConsoleLogger(); |
| 54 | + |
| 55 | + // Start web socket. |
| 56 | + Console.WriteLine("Starting web socket server..."); |
| 57 | + var webSocketServer = new WebSocketServer(IPAddress.Any, WEBSOCKET_PORT); |
| 58 | + webSocketServer.AddWebSocketService<WebRTCWebSocketPeer>("/", (peer) => peer.CreatePeerConnection = CreatePeerConnection); |
| 59 | + webSocketServer.Start(); |
| 60 | + |
| 61 | + Console.WriteLine($"Waiting for web socket connections on {webSocketServer.Address}:{webSocketServer.Port}..."); |
| 62 | + Console.WriteLine("Press ctrl-c to exit."); |
| 63 | + |
| 64 | + // Ctrl-c will gracefully exit the call at any point. |
| 65 | + ManualResetEvent exitMre = new ManualResetEvent(false); |
| 66 | + Console.CancelKeyPress += delegate (object sender, ConsoleCancelEventArgs e) |
| 67 | + { |
| 68 | + e.Cancel = true; |
| 69 | + exitMre.Set(); |
| 70 | + }; |
| 71 | + |
| 72 | + // Wait for a signal saying the call failed, was cancelled with ctrl-c or completed. |
| 73 | + exitMre.WaitOne(); |
| 74 | + } |
| 75 | + |
| 76 | + private static Task<RTCPeerConnection> CreatePeerConnection() |
| 77 | + { |
| 78 | + RTCConfiguration config = new RTCConfiguration |
| 79 | + { |
| 80 | + iceServers = new List<RTCIceServer> { new RTCIceServer { urls = STUN_URL } }, |
| 81 | + //X_BindAddress = IPAddress.Any |
| 82 | + }; |
| 83 | + var pc = new RTCPeerConnection(config); |
| 84 | + |
| 85 | + var testPatternSource = new VideoTestPatternSource(); |
| 86 | + var videoEncoderEndPoint = new Vp8NetVideoEncoderEndPoint(); |
| 87 | + var audioSource = new AudioExtrasSource(new AudioEncoder(), new AudioSourceOptions { AudioSource = AudioSourcesEnum.Music }); |
| 88 | + |
| 89 | + MediaStreamTrack videoTrack = new MediaStreamTrack(videoEncoderEndPoint.GetVideoSourceFormats(), MediaStreamStatusEnum.SendRecv); |
| 90 | + pc.addTrack(videoTrack); |
| 91 | + MediaStreamTrack audioTrack = new MediaStreamTrack(audioSource.GetAudioSourceFormats(), MediaStreamStatusEnum.SendRecv); |
| 92 | + pc.addTrack(audioTrack); |
| 93 | + |
| 94 | + testPatternSource.OnVideoSourceRawSample += videoEncoderEndPoint.ExternalVideoSourceRawSample; |
| 95 | + videoEncoderEndPoint.OnVideoSourceEncodedSample += pc.SendVideo; |
| 96 | + audioSource.OnAudioSourceEncodedSample += pc.SendAudio; |
| 97 | + |
| 98 | + pc.OnVideoFormatsNegotiated += (formats) => videoEncoderEndPoint.SetVideoSourceFormat(formats.First()); |
| 99 | + pc.OnAudioFormatsNegotiated += (formats) => audioSource.SetAudioSourceFormat(formats.First()); |
| 100 | + pc.onsignalingstatechange += () => |
| 101 | + { |
| 102 | + logger.LogDebug($"Signalling state change to {pc.signalingState}."); |
| 103 | + |
| 104 | + if (pc.signalingState == RTCSignalingState.have_local_offer) |
| 105 | + { |
| 106 | + logger.LogDebug($"Local SDP offer:\n{pc.localDescription.sdp}"); |
| 107 | + } |
| 108 | + else if (pc.signalingState == RTCSignalingState.stable) |
| 109 | + { |
| 110 | + logger.LogDebug($"Remote SDP offer:\n{pc.remoteDescription.sdp}"); |
| 111 | + } |
| 112 | + }; |
| 113 | + |
| 114 | + pc.onconnectionstatechange += async (state) => |
| 115 | + { |
| 116 | + logger.LogDebug($"Peer connection state change to {state}."); |
| 117 | + |
| 118 | + if (state == RTCPeerConnectionState.connected) |
| 119 | + { |
| 120 | + await audioSource.StartAudio(); |
| 121 | + await testPatternSource.StartVideo(); |
| 122 | + } |
| 123 | + else if (state == RTCPeerConnectionState.failed) |
| 124 | + { |
| 125 | + pc.Close("ice disconnection"); |
| 126 | + } |
| 127 | + else if (state == RTCPeerConnectionState.closed) |
| 128 | + { |
| 129 | + await testPatternSource.CloseVideo(); |
| 130 | + await audioSource.CloseAudio(); |
| 131 | + } |
| 132 | + }; |
| 133 | + |
| 134 | + // Diagnostics. |
| 135 | + pc.OnReceiveReport += (re, media, rr) => logger.LogDebug($"RTCP Receive for {media} from {re}\n{rr.GetDebugSummary()}"); |
| 136 | + pc.OnSendReport += (media, sr) => logger.LogDebug($"RTCP Send for {media}\n{sr.GetDebugSummary()}"); |
| 137 | + pc.GetRtpChannel().OnStunMessageReceived += (msg, ep, isRelay) => logger.LogDebug($"STUN {msg.Header.MessageType} received from {ep}."); |
| 138 | + pc.oniceconnectionstatechange += (state) => logger.LogDebug($"ICE connection state change to {state}."); |
| 139 | + |
| 140 | + // To test closing. |
| 141 | + //_ = Task.Run(async () => |
| 142 | + //{ |
| 143 | + // await Task.Delay(5000); |
| 144 | + |
| 145 | + // audioSource.OnAudioSourceEncodedSample -= pc.SendAudio; |
| 146 | + // videoEncoderEndPoint.OnVideoSourceEncodedSample -= pc.SendVideo; |
| 147 | + |
| 148 | + // logger.LogDebug("Closing peer connection."); |
| 149 | + // pc.Close("normal"); |
| 150 | + //}); |
| 151 | + |
| 152 | + return Task.FromResult(pc); |
| 153 | + } |
| 154 | + |
| 155 | + /// <summary> |
| 156 | + /// Adds a console logger. Can be omitted if internal SIPSorcery debug and warning messages are not required. |
| 157 | + /// </summary> |
| 158 | + private static Microsoft.Extensions.Logging.ILogger AddConsoleLogger() |
| 159 | + { |
| 160 | + var seriLogger = new LoggerConfiguration() |
| 161 | + .Enrich.FromLogContext() |
| 162 | + .MinimumLevel.Is(Serilog.Events.LogEventLevel.Debug) |
| 163 | + .WriteTo.Console() |
| 164 | + .CreateLogger(); |
| 165 | + var factory = new SerilogLoggerFactory(seriLogger); |
| 166 | + SIPSorcery.LogFactory.Set(factory); |
| 167 | + return factory.CreateLogger<Program>(); |
| 168 | + } |
| 169 | + } |
| 170 | +} |
0 commit comments