3838using SIPSorcery . OpenAIWebRTC . Models ;
3939using SIPSorceryMedia . Abstractions ;
4040using System ;
41+ using System . Collections . Generic ;
4142using System . Threading . Tasks ;
4243
4344namespace demo ;
4445
4546class Program
4647{
48+ private static string ? _stunUrl = string . Empty ;
49+ private static string ? _turnUrl = string . Empty ;
50+
4751 static async Task Main ( string [ ] args )
4852 {
4953 Log . Logger = new LoggerConfiguration ( )
@@ -58,6 +62,9 @@ static async Task Main(string[] args)
5862 Log . Information ( "WebRTC OpenAI Browser Bridge Demo Program" ) ;
5963
6064 var openAiKey = Environment . GetEnvironmentVariable ( "OPENAI_API_KEY" ) ?? string . Empty ;
65+ _stunUrl = Environment . GetEnvironmentVariable ( "STUN_URL" ) ;
66+ _turnUrl = Environment . GetEnvironmentVariable ( "TURN_URL" ) ;
67+ bool . TryParse ( Environment . GetEnvironmentVariable ( "WAIT_FOR_ICE_GATHERING_TO_SEND_OFFER" ) , out var waitForIceGatheringToSendOffer ) ;
6168
6269 if ( string . IsNullOrWhiteSpace ( openAiKey ) )
6370 {
@@ -107,6 +114,11 @@ static async Task Main(string[] args)
107114 config ,
108115 RTCSdpType . offer ) ;
109116
117+ webSocketPeer . OfferOptions = new RTCOfferOptions
118+ {
119+ X_WaitForIceGatheringToComplete = waitForIceGatheringToSendOffer
120+ } ;
121+
110122 var browserPeerTask = webSocketPeer . Run ( ) ;
111123
112124 SetOpenAIPeerEventHandlers ( openAiWebRTCEndPoint ) ;
@@ -183,6 +195,18 @@ private static void ConnectPeers(RTCPeerConnection browserPc, IWebRTCEndPoint op
183195 /// </summary>
184196 private static Task < RTCPeerConnection > CreateBrowserPeerConnection ( RTCConfiguration pcConfig )
185197 {
198+ pcConfig . iceServers = new List < RTCIceServer > ( ) ;
199+
200+ if ( ! string . IsNullOrWhiteSpace ( _stunUrl ) )
201+ {
202+ pcConfig . iceServers . Add ( _stunUrl . ParseStunServer ( ) ) ;
203+ }
204+
205+ if ( ! string . IsNullOrWhiteSpace ( _turnUrl ) )
206+ {
207+ pcConfig . iceServers . Add ( _turnUrl . ParseStunServer ( ) ) ;
208+ }
209+
186210 var peerConnection = new RTCPeerConnection ( pcConfig ) ;
187211
188212 MediaStreamTrack audioTrack = new MediaStreamTrack ( AudioCommonlyUsedFormats . OpusWebRTC , MediaStreamStatusEnum . SendRecv ) ;
@@ -191,3 +215,19 @@ private static Task<RTCPeerConnection> CreateBrowserPeerConnection(RTCConfigurat
191215 return Task . FromResult ( peerConnection ) ;
192216 }
193217}
218+
219+ public static class StunServerExtensions
220+ {
221+ public static RTCIceServer ParseStunServer ( this string stunServer )
222+ {
223+ var fields = stunServer . Split ( ';' ) ;
224+
225+ return new RTCIceServer
226+ {
227+ urls = fields [ 0 ] ,
228+ username = fields . Length > 1 ? fields [ 1 ] : null ,
229+ credential = fields . Length > 2 ? fields [ 2 ] : null ,
230+ credentialType = RTCIceCredentialType . password
231+ } ;
232+ }
233+ }
0 commit comments