Thursday, March 26, 2015

Peer to Peer Video Streaming with WebRTC

Chatting has become essential for internet users. Among them most of the users use Video Chat software. But with the introduction of WebRTC, now people do not need to install separate software for chatting (video, audio, and text). Only requirement is a web browser.

Let's move on to implementation. Implementation is very simple and it is only a javascript file.

First create following html page.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<!DOCTYPE html>
<html>
    <head>
    <meta charset="utf-8" />
    <title>WebRTC video Session</title>
</head>
<body>
    <div id="videoModal"></div>
</body>
<script type="text/javascript" src="videoSession.js"></script>
</html>

Next we will write videoSession.js file

  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 
 function VideoSession(ip){

//WebRTC connection related variables
    var socket = new WebSocket('ws://'+ip+'/');  // change the IP address to your websocket server
    VideoSession.stunServer = "stun.l.google.com:19302";
    var sourcevid;
    var remotevid;
    var localStream = null;
    var remoteStream;
    var peerConn = null;
    var started = false;
    var isRTCPeerConnection = true;
    var mediaConstraints = {'mandatory': {
       'OfferToReceiveAudio':true, 
       'OfferToReceiveVideo':true }};
       
    //create html tags in given html and set vaules
    this.initialize = function(videoModal){
  
        $("#"+videoModal).html(
            '<div class="modal-dialog-video-session">'
             +  '<div class="modal-content">'
             +    '<div class="modal-header">'
             +    '<button type="button" class="close" data-dismiss="modal" aria-label="Close">'
             +     '<span aria-hidden="true">&times;</span>'
             +    '</button>'
             +    '<h4 class="modal-title" id="myModalLabel">My sessions</h4>'   
             +     '</div>'
    
             +     '<!-- upload popup content start-->'
             +   '<div class="modal-body">'
     
             +    '<!-- row for upload popup content start-->'
             +    '<div class="row">'
             +     '<div class="col-md-8" >'
             +      '<video id="remotevid" width="100%" frameborder="0" controls autoplay></video>'
             +      '<br>'
             +     '</div>'
             +     '<div class="col-md-4">'
             +      '<video id="sourcevid" width="100%" frameborder="0" autoplay></video>'  
             +     '</div>'
             +    '</div><!-- row for upload popup content end--> '
  
             +    '<br>'
             +     '</div><!-- upload popup content end-->'
     
             +  '</div>'
             +   '</div>'
  );
  
        sourcevid = $("#sourcevid"); 
        remotevid = $("#remotevid");
    }
 
    //dispaly Modal
    this.showUI = function(videoModal){
        $("#"+videoModal).modal("toggle");
    }
 
    //start video session
    this.startVideo = function() {
        // Replace the source of the video element with the stream from the camera
        try {
            //request local media device access
            navigator.webkitGetUserMedia({audio: true, video: true}, successCallback, errorCallback);
        } catch (e) {
            navigator.webkitGetUserMedia("video,audio", successCallback, errorCallback);
        }
        function successCallback(stream) {
            //set source video src to local stream
            sourcevid.attr("src",window.webkitURL.createObjectURL(stream));
            sourcevid.css("webkitTransform","rotateY(180deg)");
            localStream = stream;
     
            //start connect
            if (!started && localStream) {
                console.log("Creating PeerConnection.");
                createPeerConnection();
                Utility.logg('Adding local stream...');
                peerConn.addStream(localStream);
                started = true;
                Utility.logg("isRTCPeerConnection: " + isRTCPeerConnection);
   
                //create offer
                peerConn.createOffer(setLocalAndSendMessage, null, mediaConstraints);
    
                //end connect
 
            } else {
                alert("Local stream not running yet.");
            }
        }
        function errorCallback(error) {
            Utility.logg('An error occurred: [CODE ' + error.code + ']');
        }
    }
  

    //Create peer connection
    function createPeerConnection() {
  
        Utility.logg("Creating peer connection");
        var servers = [];
        servers.push({'url':'stun:' + VideoSession.stunServer});
        var pc_config = {'iceServers':servers};   
        peerConn = new webkitRTCPeerConnection(pc_config);
 
        //bind events
        peerConn.onicecandidate = onIceCandidate;
        peerConn.onaddstream = onRemoteStreamAdded;
        peerConn.onremovestream = onRemoteStreamRemoved;
  
        // accept connection request
        socket.addEventListener("message", onMessage, false);
    
    }
 
 
    //--------------------------------Events---------------------------------
 
    // when remote adds a stream, hand it on to the local video element
    function onRemoteStreamAdded(event) {
        Utility.logg("Added remote stream");
        remotevid.attr("src",window.webkitURL.createObjectURL(event.stream));
  
        //show the start time
        var today = new Date();
        var startTime = today.toLocaleTimeString();
        $("#videoSessionStartTime").html("Start Time : "+startTime);
    }
  
    // when remote removes a stream, remove it from the local video element
    function onRemoteStreamRemoved(event) {
        Utility.logg("Remove remote stream");
        remotevid.attr("src","");
    }
 
    //when candidate is ready send messages to server
    function onIceCandidate(event) {
        if (event.candidate) {
            sendMessage({type: 'candidate',
            label: event.candidate.sdpMLineIndex,
            id: event.candidate.sdpMid,
            candidate: event.candidate.candidate});
        } else {
            Utility.logg("End of candidates.");
        }
    }
 
    //when message is received, trigger this event
    function onMessage(evt) {
        Utility.logg("RECEIVED: " + evt.data);
        if (isRTCPeerConnection)
            processSignalingMessage(evt.data);
    }
 
    function onHangUp() {
        Utility.logg("Hang up.");
        if (started) {
            closeSession();
        }
    }
 
    //--------------------------------Events---------------------------------
 

    //process all the received mesages
    function processSignalingMessage(message) {
        var msg = JSON.parse(message);
        if (msg.type === 'offer') {
            if(started){
                peerConn.close();
                peerConn = null;
                started = false;
            }
            if (!started && localStream) {

                createPeerConnection();
                Utility.logg('Adding local stream...');
                peerConn.addStream(localStream);
                started = true;
                Utility.logg("isRTCPeerConnection: " + isRTCPeerConnection);
                //set remote description
                peerConn.setRemoteDescription(new RTCSessionDescription(msg));
                //create answer
                console.log("Sending answer to peer.");
                peerConn.createAnswer(setLocalAndSendMessage, null, mediaConstraints);
            }
 
            } else if (msg.type === 'answer' && started) {
                peerConn.setRemoteDescription(new RTCSessionDescription(msg));
            } else if (msg.type === 'candidate' && started) {
                var candidate = new RTCIceCandidate({sdpMLineIndex:msg.label, candidate:msg.candidate});
                peerConn.addIceCandidate(candidate);
            } else if (msg.type === 'chat'){
                addChatMsg(msg.nick, msg.cid, msg.data);
            } else if (msg.type === 'bye' && started) {
                Utility.logg("Remote Hang up.");
                closeSession();
            }
        }
 
        // send the message to websocket server
        function sendMessage(message) {
            var mymsg = JSON.stringify(message);
            Utility.logg("SEND: " + mymsg);
            socket.send(mymsg);
        }
    
        //set session discrption and send it to server
        function setLocalAndSendMessage(sessionDescription) {
            peerConn.setLocalDescription(sessionDescription);
            sendMessage(sessionDescription);
        }
   
        //close the session
        function closeSession() {
            peerConn.close();
            peerConn = null;
            started = false;
            sendMessage({type: 'bye'});
            remotevid.attr("src",""); 
        }
  
        window.onbeforeunload = function() {
            if (started) {
                closeSession();
            }
        }
    }

Now we have completed implementation of videoSession.js file. Let's see how to invoke this JS. Now add following code just after the 10th line of your html page.

1
2
3
4
5
6
<script type="text/javascript">
    var vs = new VideoSession("10.10.1.37:1337"); //ip and port for your nodejs server
    vs.initialize("videoModal");
    vs.showUI("videoModal");
    vs.startVideo();
</script>

You'will need JQuery to run videoSession script. So add following line just before 10th line of html page.
<script type="text/javascript" src="assets/js/jquery-1.10.2.min.js"></script>

That's it. Run your web page and enjoy WebRTC.

Salesforce Metadata Deployment

Salesforce Metadata Deployment What are metadata? Let's understand this through a simple example. Imagine you are a Salesforce Admin an...