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.

Wednesday, January 21, 2015

WPF MVVM DataGridView column header click event command binding

I was doing WPF project with MVVM design pattern. There I used a DataGridView to show my data as a table. But I needed to sort the data in the grid, with my own algorithm instead of using the default sorting. Therefore I needed to bind a command to the header. I did not know any anwer to do that. While searching on the internet I found this answer.

I just had to add these line inside the style of DataGrid Header.

1
2
3
4
5
6
7
<style targettype="{x:Type DataGridColumnHeader}">
    <setter Property="Command"
                            Value="{Binding MyCommand}"/>
    <setter Property="CommandParameter"
                            Value="{Binding Path=Content, RelativeSource={RelativeSource Self}}"/>
              ...
</style>

Tuesday, September 9, 2014

FPDF MultiCell problem Solved : PHP

FPDF is a really good tool to create PDF files using PHP. But I faced a huge problem with MultiCell method when I need to print a long paragraph. When there is no sufficient space, it automatically create a new page but there is no top margine.

While searching for a solution, I fount this article. Hope this will help you.

View Article Here.

Wednesday, July 30, 2014

Insertion Sort Java Implementation

When we talk about algorithms, Sorting and Searching is quite significant. There are few sorting and searching algorithms. Today I'm going to present you the java implementation of Insertion sort.

int[] insertion_sort(int[] x){
    int key = 0;
    for(int j=1 ; x.length > j ; j++){
        key = x[j];
        while(i > 0 && x[j] > key){
            x[i+1] = x[i];
            i = i - 1;
        }
        x[i+1] = key;
    }
    return x;
}
In the next post I hope to implement quick sort.   
References : Introduction to Algorithms 3rd ed. T. Cormen...

Tuesday, July 29, 2014

Languages : How a computer understands different languages

We know that you can write computer programs using different computer languages such as Java, C. But the problem is how the computer understands all the instructions given in those languages. It is very simple to understand when we think a computer as a living object.

Each and every one of you have a mother language. You can understand instructions which are in your mother language without any problem. Computers also have a mother language. It is machine language (known as binary language, alphabet with 1s and 0s). Computer can understand instructions which are in machine language.


As you grow you will learn different languages(for an instance : French). After you have learnt french you will understand french instructions also. You will receive the french instructions and you will translate it into English or into your mother language. Then you know what to do. You will act according to the instruction. In computers, same thing happens. You give instructions to the computer in JAVA. JAVA compiler will translate your source code in to machine language. Then computer understands the instructions.

That's why you need a compiler and that's how a computer understands different languages. It is more like you learn a different language.

Monday, July 28, 2014

Generate Dynamic PDFs : Implementation in PHP

In this post we are going to discuss how we can generate Portable Document Files using PHP. Creating PDFs dynamically is very importent especially when we have dynamic data. Actually this is very easy since we can find pre-developed library.

You should download fpdf.php file first.
Then you can create PDF.php file as follows.

require('fpdf.php');
class PDF extends FPDF {
     
 function Header() {
  //write your own code segment
 }
  
 function Footer() {
  //write your own code segment
 }

Now you're ready to generate PDF files. Refer this code.

require('pdf.php');
$pdf=new PDF("P","mm","A4");
$pdf->SetMargins(25.4,25.4,25.4);
$pdf->AddPage();
$pdf->Cell(30, 5, 'This is the Fist page');
$pdf->AddPage();
$pdf->SetY(25.4);
$pdf->SetFont('Arial', 'BIU', 12);
$pdf->Cell(0, 5, 'Sample Text', 0, 1);
ob_start();
$pdf->Output();//pdf will be downloaded
ob_end_flush();

Sunday, July 27, 2014

Hanoi Tower Implementation in C

Here I am supposed to implement only the function which will print the instructions to move plates.

void hanoi(int n,char source,char temp,char dest){
        if(n>0){
                hanoi(n-1,source,dest,temp);
                printf("move plate from %c to %c",source,dest);
                hanoi(n-1,temp,source,dest);
        }
}
If you have read my previous post, I think you can understand this function. Feel free to use this code. Enjoy hanoi tower. Try this function with n=32. You will understand how slow your computer is. Good Luck!

Salesforce Metadata Deployment

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