@@ -105,7 +105,27 @@ function enableControls() {
105
105
async function startStreaming ( ) {
106
106
disableControls ( ) ;
107
107
108
+ const candidates = [ ] ;
109
+ let patchEndpoint = undefined ;
108
110
pc = new RTCPeerConnection ( ) ;
111
+
112
+ pc . onicegatheringstatechange = ( ) =>
113
+ console . log ( 'Gathering state change:' , pc . iceGatheringState ) ;
114
+ pc . onconnectionstatechange = ( ) =>
115
+ console . log ( 'Connection state change:' , pc . connectionState ) ;
116
+ pc . onicecandidate = ( event ) => {
117
+ if ( event . candidate == null ) {
118
+ return ;
119
+ }
120
+
121
+ const candidate = JSON . stringify ( event . candidate ) ;
122
+ if ( patchEndpoint === undefined ) {
123
+ candidates . push ( candidate ) ;
124
+ } else {
125
+ sendCandidate ( patchEndpoint , candidate ) ;
126
+ }
127
+ } ;
128
+
109
129
pc . addTrack ( localStream . getAudioTracks ( ) [ 0 ] , localStream ) ;
110
130
const { sender : videoSender } = pc . addTransceiver (
111
131
localStream . getVideoTracks ( ) [ 0 ] ,
@@ -145,6 +165,13 @@ async function startStreaming() {
145
165
} ) ;
146
166
147
167
if ( response . status == 201 ) {
168
+ patchEndpoint = response . headers . get ( 'location' ) ;
169
+ console . log ( 'Successfully initialized WHIP connection' ) ;
170
+
171
+ for ( const candidate of candidates ) {
172
+ sendCandidate ( patchEndpoint , candidate ) ;
173
+ }
174
+
148
175
const sdp = await response . text ( ) ;
149
176
await pc . setRemoteDescription ( { type : 'answer' , sdp : sdp } ) ;
150
177
button . innerText = 'Stop Streaming' ;
@@ -163,6 +190,26 @@ async function startStreaming() {
163
190
}
164
191
}
165
192
193
+ async function sendCandidate ( patchEndpoint , candidate ) {
194
+ const response = await fetch ( patchEndpoint , {
195
+ method : 'PATCH' ,
196
+ cache : 'no-cache' ,
197
+ headers : {
198
+ 'Content-Type' : 'application/trickle-ice-sdpfrag' ,
199
+ } ,
200
+ body : candidate ,
201
+ } ) ;
202
+
203
+ if ( response . status === 204 ) {
204
+ console . log ( `Successfully sent ICE candidate:` , candidate ) ;
205
+ } else {
206
+ console . error (
207
+ `Failed to send ICE, status: ${ response . status } , candidate:` ,
208
+ candidate
209
+ ) ;
210
+ }
211
+ }
212
+
166
213
function stopStreaming ( ) {
167
214
pc . close ( ) ;
168
215
pc = undefined ;
0 commit comments