aboutsummaryrefslogtreecommitdiffstats
path: root/client-website/js/symple.player.webrtc.js
blob: eb57fa7db69e584f9aa07d9f1b1ca2f91d0f4e7a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
// -----------------------------------------------------------------------------
// WebRTC Engine
//
window.RTCPeerConnection = window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
window.RTCSessionDescription = window.mozRTCSessionDescription || window.RTCSessionDescription;
window.RTCIceCandidate = window.mozRTCIceCandidate || window.RTCIceCandidate;
navigator.getUserMedia = navigator.mozGetUserMedia || navigator.webkitGetUserMedia;
window.URL = window.webkitURL || window.URL;

var myLocalStream = undefined;
var isVideoMuted = false;
var isAudioMuted = false;

   
Symple.Media.registerEngine({
    id: 'WebRTC',
    name: 'WebRTC Player',
    formats: 'VP8, Opus', 
    preference: 100,
    support: (function() {
        return typeof RTCPeerConnection != "undefined";
    })()
});


Symple.Player.Engine.WebRTC = Symple.Player.Engine.extend({
    init: function(player) {
        Symple.log("SympleWebRTC: Init");
        this._super(player);
        
        this.rtcConfig = player.options.rtcConfig || {
          iceServers: [
            { url: "stun:stun.l.google.com:19302" }
          ]
        }
        this.rtcOptions = player.options.rtcOptions || {
            optional: [
                {DtlsSrtpKeyAgreement: true} // FF <=> Chrome interop
            ]
        }
        this.mediaConstraints = player.options.mediaConstraints || {}
        //this.mediaConstraints = player.options.mediaConstraints || {
        //  'mandatory': {
        //    'OfferToReceiveAudio':true, 
        //    'OfferToReceiveVideo':true
        //  }
        //};
    },
    
    setup: function() {
        Symple.log("SympleWebRTC: Setup");
        
        this._createPeerConnection(); 
        
        // Note: Absolutely position video element so it scales to  
        // the parent element size. Need to test in other browsers.        
        
        if (typeof(this.video) == 'undefined') {
            Symple.log("SympleWebRTC: Setup: Peer video");
            this.video = $('<video autoplay></video>')
            this.player.screen.prepend(this.video);    
        }
        
        //this.video = $('<video width="100%" height="100%" style="position:absolute;left:0;top:0;"></video>'); // Chrome
        //this.selfVideo = typeof(this.selfVideo) == 'undefined' ? $('<video></video>') : this.selfVideo;
        //this.video = typeof(this.video) == 'undefined' ? $('<video></video>') : this.video; // style="position:absolute;left:0;top:0;"  width="100%" height="100%"  style="max-width:100%;height:auto;"
    },
      
    destroy: function() {   
        Symple.log("SympleWebRTC: Destroy");
        this.sendLocalSDP = null;
        this.sendLocalCandidate = null;
        
        if (this.video) {
            this.video[0].src = '';
            this.video[0] = null;
            this.video = null;
            // Anything else required for video cleanup?
        }
                
        if (this.pc) {
            this.pc.close();
            this.pc = null;
            // Anything else required for peer connection cleanup?
        }        
    },

    play: function(params) {        
        Symple.log("SympleWebRTC: Play", params);
        
        // The 'playing' state will be set when candidates
        // gathering is complete.
        // TODO: Get state events from the video element 
        // to shift from local loading to playing state.       
        
        if (params && params.localMedia) {
          
            // Get the local stream, show it in the local video element and send it
            var self = this;  
            navigator.getUserMedia({ audio: !params.disableAudio, video: !params.disableVideo }, 
            
                // successCallback
                function (localStream) {              
                    
                    //self._createPeerConnection(); 
                    myLocalStream = localStream;
                        
                    // Play the local stream
                    self.video[0].src = URL.createObjectURL(localStream);
                    self.pc.addStream(localStream);

                    //if (params.caller)
                        self.pc.createOffer(
                            function(desc) { self._onLocalSDP(desc); }, function(err) { self.setError("createOffer() Failed: " + err);});
                    //else
                    //    self.pc.createAnswer(
                    //        function(desc) { self._onLocalSDP(desc); },
                    //        function() { // error
                    //            self.setError("Cannot create local SDP answer");
                    //        },
                    //        null //this.mediaConstraints;
                    //    )

                    //function gotDescription(desc) {
                    //    pc.setLocalDescription(desc);
                    //    signalingChannel.send(JSON.stringify({ "sdp": desc }));
                    //}
                },

                // errorCallback
                function(err) {
                    self.setError("getUserMedia() Failed: " + err);
                });
        }
    },

    stop: function() {
        
        if (this.video) {
            this.video[0].src = '';
            // Do not nullify
        }
                
        // TODO: Close peer connection?
        if (this.pc) {
            this.pc.close();
            this.pc = null;
        }

        if (myLocalStream) {
            myLocalStream.stop();
            myLocalStream = undefined;
        }
            
        this.setState('stopped');
    },
    
    mute: function(flag) {
        // Mute unless explicit false given
        flag = flag === false ? false : true;
        Symple.log("SympleWebRTC: Mute:", flag);
        
        if (this.video) {
            this.video.prop('muted', flag); //mute
        } 
    },

    muteLocal: function() {
        Symple.log('mute');
        if (this.video) {
            this.video[0].muted = true;
        } 
    },

    toggleVideo: function() {
        videoTracks = myLocalStream.getVideoTracks();
        if (videoTracks.length === 0) {
            Symple.log('No local video available.');
            return;
        }

        if (isVideoMuted) {
            for (i = 0; i < videoTracks.length; i++) {
                videoTracks[i].enabled = true;
            }
            Symple.log('Video unmuted.');
        } else {
            for (i = 0; i < videoTracks.length; i++) {
                videoTracks[i].enabled = false;
            }
            Symple.log('Video muted.');
        }

        isVideoMuted = !isVideoMuted;
    },

    toggleAudio: function() {
        audioTracks = myLocalStream.getAudioTracks();

        if (audioTracks.length === 0) {
            Symple.log('No local audio available.');
            return;
        }

        if (isAudioMuted) {
            for (i = 0; i < audioTracks.length; i++) {
                audioTracks[i].enabled = true;
            }
            Symple.log('Audio unmuted.');
        } else {
            for (i = 0; i < audioTracks.length; i++){
                audioTracks[i].enabled = false;
            }
            Symple.log('Audio muted.');
        }

        isAudioMuted = !isAudioMuted;
    },

    fullscreenVideo: function() {
        if (this.video[0].requestFullscreen) {
            this.video[0].requestFullscreen();
        } else if (this.video[0].mozRequestFullScreen) {
            this.video[0].mozRequestFullScreen();
        } else if (this.video[0].webkitRequestFullscreen) {
            this.video[0].webkitRequestFullscreen();
        }
    },


    // Initiates the player with local media capture
    //startLocalMedia: function(params) {        
        //Symple.log("SympleWebRTC: Play", params);
        
        // The 'playing' state will be set when candidates
        // gathering is complete.
        // TODO: Get state events from the video element 
        // to shift from local loading to playing state.        
    //},
    
    //
    // Called when local SDP is ready to be sent to the peer.
    sendLocalSDP: new Function,
    
    //
    // Called when a local candidate is ready to be sent to the peer.    
    sendLocalCandidate: new Function,    
    
    //
    // Called when remote SDP is received from the peer.
    onRemoteSDP: function(desc) {   
        Symple.log('SympleWebRTC: Recieve remote SDP:', desc)        
        if (!desc || !desc.type || !desc.sdp)
            throw "Invalid SDP data"
                    
        //if (desc.type != "offer")
        //    throw "Only SDP offers are supported"
        
        var self = this;             
        this.pc.setRemoteDescription(new RTCSessionDescription(desc), 
            function() {
                Symple.log('SympleWebRTC: SDP success');
                //alert('success')
            }, 
            function(message) {
                console.error('SympleWebRTC: SDP error:', message);
                self.setError("Cannot parse remote SDP offer");
            }
        );   
            
        if (desc.type == "offer") {
            this.pc.createAnswer(
                function(answer) { // success
                    self._onLocalSDP(answer);                    
                    //alert('answer')
                },
                function() { // error
                    self.setError("Cannot create local SDP answer");
                },
                null //this.mediaConstraints
            );
        }
    },    
    
    //
    // Called when remote candidate is received from the peer.
    onRemoteCandidate: function(candidate) { 
        //Symple.log("SympleWebRTC: Recieve remote candiate ", candidate);
        if (!this.pc)
            throw 'The peer connection is not initialized' // call onRemoteSDP first
            
        this.pc.addIceCandidate(new RTCIceCandidate({
            //sdpMid: candidate.sdpMid, 
            sdpMLineIndex: candidate.sdpMLineIndex, 
            candidate: candidate.candidate
        }));      
    },   
    
    
    //
    // Private methods
    //

    //
    // Called when local SDP is received from the peer.
    _onLocalSDP: function(desc) {       
        try {
            this.pc.setLocalDescription(desc);
            this.sendLocalSDP(desc);
        } 
        catch (e) {
            Symple.log("Failed to send local SDP:", e);            
        }
    }, 
    
    _createPeerConnection: function() {          
        if (this.pc)
            throw 'The peer connection is already initialized'
              
        Symple.log("SympleWebRTC: Creating peer connection: ", this.rtcConfig);
                
        var self = this;
        this.pc = new RTCPeerConnection(this.rtcConfig, this.rtcOptions);
        this.pc.onicecandidate = function(event) {
            if (event.candidate) {
                //Symple.log("SympleWebRTC: Local candidate gathered:", event.candidate);                
                self.sendLocalCandidate(event.candidate); 
            } 
            else {
                Symple.log("SympleWebRTC: Local candidate gathering complete");
            }
        };
        this.pc.onaddstream = function(event) {         
            Symple.log("SympleWebRTC: Remote stream added:", URL.createObjectURL(event.stream));
                
            // Set the state to playing once candidates have completed gathering.
            // This is the best we can do until ICE onstatechange is implemented.
            self.setState('playing');
                
            self.video[0].src = URL.createObjectURL(event.stream);
            self.video[0].play(); 
        };
        this.pc.onremovestream = function(event) { 
            Symple.log("SympleWebRTC: Remote stream removed:", event);
            self.video[0].stop(); 
        };
        
        // Note: The following state events are completely unreliable.
        // Hopefully when the spec is complete this will change, but
        // until then we need to "guess" the state.
        //this.pc.onconnecting = function(event) { Symple.log("SympleWebRTC: onconnecting:", event); };
        //this.pc.onopen = function(event) { Symple.log("SympleWebRTC: onopen:", event); };
        //this.pc.onicechange = function(event) { Symple.log("SympleWebRTC: onicechange :", event); };
        //this.pc.onstatechange = function(event) { Symple.log("SympleWebRTC: onstatechange :", event); };
        
        Symple.log("SympleWebRTC: Setupd RTCPeerConnnection with config: " + JSON.stringify(this.rtcConfig));
    }
});


//
// Helpers

Symple.Media.iceCandidateType = function(candidateSDP) {
  if (candidateSDP.indexOf("typ relay") != -1)
    return "turn";
  if (candidateSDP.indexOf("typ srflx") != -1)
    return "stun";
  if (candidateSDP.indexOf("typ host") != -1)
    return "host";
  return "unknown";
}