|
| 1 | +//----------------------------------------------------------------------------- |
| 2 | +// Filename: Program.cs |
| 3 | +// |
| 4 | +// Description: An example WebRTC server application that attempts to send and |
| 5 | +// receive audio and video. This example attempts to use the ffmpeg libraries for |
| 6 | +// the video encoding. A web socket is used for signalling. |
| 7 | +// |
| 8 | +// Author(s): |
| 9 | +// Aaron Clauson (aaron@sipsorcery.com) |
| 10 | +// |
| 11 | +// History: |
| 12 | +// 06 Apr 2025 Aaron Clauson Created, Dublin, Ireland. |
| 13 | +// |
| 14 | +// License: |
| 15 | +// BSD 3-Clause "New" or "Revised" License, see included LICENSE.md file. |
| 16 | +//----------------------------------------------------------------------------- |
| 17 | + |
| 18 | +using System; |
| 19 | +using System.Diagnostics.Eventing.Reader; |
| 20 | +using System.Linq; |
| 21 | +using System.Net; |
| 22 | +using System.Threading.Tasks; |
| 23 | +using Microsoft.AspNetCore.Builder; |
| 24 | +using Microsoft.AspNetCore.Hosting; |
| 25 | +using Microsoft.Extensions.Logging; |
| 26 | +using Microsoft.Extensions.Logging.Abstractions; |
| 27 | +using Serilog; |
| 28 | +using Serilog.Extensions.Logging; |
| 29 | +using SIPSorcery.Media; |
| 30 | +using SIPSorcery.Net; |
| 31 | +using SIPSorceryMedia.FFmpeg; |
| 32 | +using WebSocketSharp.Server; |
| 33 | + |
| 34 | +namespace demo; |
| 35 | + |
| 36 | +class Program |
| 37 | +{ |
| 38 | + private const int ASPNET_PORT = 8080; |
| 39 | + private const int WEBSOCKET_PORT = 8081; |
| 40 | + //private const string STUN_URL = "stun:stun.cloudflare.com"; |
| 41 | + private const string LINUX_FFMPEG_LIB_PATH = "/usr/local/lib/"; |
| 42 | + |
| 43 | + private static Microsoft.Extensions.Logging.ILogger logger = NullLogger.Instance; |
| 44 | + |
| 45 | + static void Main() |
| 46 | + { |
| 47 | + Console.WriteLine("WebRTC FFmpeg Get Started"); |
| 48 | + |
| 49 | + if (Environment.OSVersion.Platform == PlatformID.Unix) |
| 50 | + { |
| 51 | + SIPSorceryMedia.FFmpeg.FFmpegInit.Initialise(SIPSorceryMedia.FFmpeg.FfmpegLogLevelEnum.AV_LOG_VERBOSE, LINUX_FFMPEG_LIB_PATH, logger); |
| 52 | + } |
| 53 | + else |
| 54 | + { |
| 55 | + SIPSorceryMedia.FFmpeg.FFmpegInit.Initialise(SIPSorceryMedia.FFmpeg.FfmpegLogLevelEnum.AV_LOG_VERBOSE, null, logger); |
| 56 | + } |
| 57 | + |
| 58 | + logger = AddConsoleLogger(); |
| 59 | + |
| 60 | + // Start web socket. |
| 61 | + Console.WriteLine("Starting web socket server..."); |
| 62 | + var webSocketServer = new WebSocketServer(IPAddress.Any, WEBSOCKET_PORT); |
| 63 | + webSocketServer.AddWebSocketService<WebRTCWebSocketPeer>("/", (peer) => peer.CreatePeerConnection = CreatePeerConnection); |
| 64 | + webSocketServer.Start(); |
| 65 | + |
| 66 | + Console.WriteLine($"Waiting for web socket connections on {webSocketServer.Address}:{webSocketServer.Port}..."); |
| 67 | + Console.WriteLine("Press ctrl-c to exit."); |
| 68 | + |
| 69 | + var builder = WebApplication.CreateBuilder(); |
| 70 | + |
| 71 | + builder.WebHost.ConfigureKestrel(options => |
| 72 | + { |
| 73 | + options.Listen(IPAddress.Any, ASPNET_PORT); |
| 74 | + }); |
| 75 | + |
| 76 | + var app = builder.Build(); |
| 77 | + |
| 78 | + // Map the root URL (/) to return "Hello World" |
| 79 | + ///app.MapGet("/", () => "Hello World"); |
| 80 | + |
| 81 | + app.UseDefaultFiles(); |
| 82 | + app.UseStaticFiles(); |
| 83 | + |
| 84 | + app.Run(); |
| 85 | + } |
| 86 | + |
| 87 | + private static Task<RTCPeerConnection> CreatePeerConnection() |
| 88 | + { |
| 89 | + RTCConfiguration config = new RTCConfiguration |
| 90 | + { |
| 91 | + //iceServers = new List<RTCIceServer> { new RTCIceServer { urls = STUN_URL } }, |
| 92 | + X_BindAddress = IPAddress.Any // Docker images typically don't support IPv6 so force bind to IPv4. |
| 93 | + }; |
| 94 | + var pc = new RTCPeerConnection(config); |
| 95 | + |
| 96 | + var testPatternSource = new VideoTestPatternSource(new FFmpegVideoEncoder()); |
| 97 | + var audioSource = new AudioExtrasSource(new AudioEncoder(), new AudioSourceOptions { AudioSource = AudioSourcesEnum.Music }); |
| 98 | + |
| 99 | + MediaStreamTrack videoTrack = new MediaStreamTrack(testPatternSource.GetVideoSourceFormats(), MediaStreamStatusEnum.SendRecv); |
| 100 | + pc.addTrack(videoTrack); |
| 101 | + MediaStreamTrack audioTrack = new MediaStreamTrack(audioSource.GetAudioSourceFormats(), MediaStreamStatusEnum.SendRecv); |
| 102 | + pc.addTrack(audioTrack); |
| 103 | + |
| 104 | + testPatternSource.OnVideoSourceEncodedSample += pc.SendVideo; |
| 105 | + audioSource.OnAudioSourceEncodedSample += pc.SendAudio; |
| 106 | + |
| 107 | + pc.OnVideoFormatsNegotiated += (formats) => testPatternSource.SetVideoSourceFormat(formats.First()); |
| 108 | + pc.OnAudioFormatsNegotiated += (formats) => audioSource.SetAudioSourceFormat(formats.First()); |
| 109 | + pc.onsignalingstatechange += () => |
| 110 | + { |
| 111 | + logger.LogDebug($"Signalling state change to {pc.signalingState}."); |
| 112 | + |
| 113 | + if (pc.signalingState == RTCSignalingState.have_local_offer) |
| 114 | + { |
| 115 | + logger.LogDebug($"Local SDP offer:\n{pc.localDescription.sdp}"); |
| 116 | + } |
| 117 | + else if (pc.signalingState == RTCSignalingState.stable) |
| 118 | + { |
| 119 | + logger.LogDebug($"Remote SDP offer:\n{pc.remoteDescription.sdp}"); |
| 120 | + } |
| 121 | + }; |
| 122 | + |
| 123 | + pc.onconnectionstatechange += async (state) => |
| 124 | + { |
| 125 | + logger.LogDebug($"Peer connection state change to {state}."); |
| 126 | + |
| 127 | + if (state == RTCPeerConnectionState.connected) |
| 128 | + { |
| 129 | + await audioSource.StartAudio(); |
| 130 | + await testPatternSource.StartVideo(); |
| 131 | + } |
| 132 | + else if (state == RTCPeerConnectionState.failed) |
| 133 | + { |
| 134 | + pc.Close("ice disconnection"); |
| 135 | + } |
| 136 | + else if (state == RTCPeerConnectionState.closed) |
| 137 | + { |
| 138 | + await testPatternSource.CloseVideo(); |
| 139 | + await audioSource.CloseAudio(); |
| 140 | + } |
| 141 | + }; |
| 142 | + |
| 143 | + // Diagnostics. |
| 144 | + pc.OnReceiveReport += (re, media, rr) => logger.LogDebug($"RTCP Receive for {media} from {re}\n{rr.GetDebugSummary()}"); |
| 145 | + pc.OnSendReport += (media, sr) => logger.LogDebug($"RTCP Send for {media}\n{sr.GetDebugSummary()}"); |
| 146 | + pc.GetRtpChannel().OnStunMessageReceived += (msg, ep, isRelay) => logger.LogDebug($"STUN {msg.Header.MessageType} received from {ep}."); |
| 147 | + pc.oniceconnectionstatechange += (state) => logger.LogDebug($"ICE connection state change to {state}."); |
| 148 | + |
| 149 | + // To test closing. |
| 150 | + //_ = Task.Run(async () => |
| 151 | + //{ |
| 152 | + // await Task.Delay(5000); |
| 153 | + |
| 154 | + // audioSource.OnAudioSourceEncodedSample -= pc.SendAudio; |
| 155 | + // videoEncoderEndPoint.OnVideoSourceEncodedSample -= pc.SendVideo; |
| 156 | + |
| 157 | + // logger.LogDebug("Closing peer connection."); |
| 158 | + // pc.Close("normal"); |
| 159 | + //}); |
| 160 | + |
| 161 | + return Task.FromResult(pc); |
| 162 | + } |
| 163 | + |
| 164 | + /// <summary> |
| 165 | + /// Adds a console logger. Can be omitted if internal SIPSorcery debug and warning messages are not required. |
| 166 | + /// </summary> |
| 167 | + private static Microsoft.Extensions.Logging.ILogger AddConsoleLogger() |
| 168 | + { |
| 169 | + var seriLogger = new LoggerConfiguration() |
| 170 | + .Enrich.FromLogContext() |
| 171 | + .MinimumLevel.Is(Serilog.Events.LogEventLevel.Debug) |
| 172 | + .WriteTo.Console() |
| 173 | + .CreateLogger(); |
| 174 | + var factory = new SerilogLoggerFactory(seriLogger); |
| 175 | + SIPSorcery.LogFactory.Set(factory); |
| 176 | + return factory.CreateLogger<Program>(); |
| 177 | + } |
| 178 | +} |
0 commit comments