<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Bharath Kotha on Medium]]></title>
        <description><![CDATA[Stories by Bharath Kotha on Medium]]></description>
        <link>https://medium.com/@bharathkotha?source=rss-1b65511afb1d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Io3hYSU8QwyDbYdp</url>
            <title>Stories by Bharath Kotha on Medium</title>
            <link>https://medium.com/@bharathkotha?source=rss-1b65511afb1d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 04:32:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bharathkotha/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Perfect Negotiation (WebRTC Series — Part4)]]></title>
            <link>https://bharathkotha.medium.com/perfect-negotiation-webrtc-series-part4-7ea5b009a9e2?source=rss-1b65511afb1d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ea5b009a9e2</guid>
            <category><![CDATA[webrtc]]></category>
            <category><![CDATA[real-time-communication]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[conference]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Bharath Kotha]]></dc:creator>
            <pubDate>Sat, 28 Oct 2023 02:24:19 GMT</pubDate>
            <atom:updated>2023-10-28T02:26:00.154Z</atom:updated>
            <content:encoded><![CDATA[<h3>Perfect Negotiation (WebRTC Series — Part4)</h3><p><em>In this article, we’ll look at perfect negotiation pattern that prevents the WebRTC peers being end up in a dead lock. This change will also let us use a symmetric code between two clients. By doing so we can let the peers start negotiation in any order.</em></p><p>In part 1, 2, and 3 of the series we looked at the basics of webrtc and how to implement a basic web conference app in web and Android. One of the restrictions we had with previous implementation is that the receiver will always have to start before the initiator . In real world scenario, this requires the participants to co-ordinate the initiation of webrtc session. This article discusses a pattern that will resolve this limitation. After implementing the patterns in this article, the participants just need to use the meeting ID and join the call in any order.</p><p>The source code used in this article is available at <a href="https://github.com/bharath-kotha/WebRTC-Articles/tree/master/webrtc-android-2">https://github.com/bharath-kotha/WebRTC-Articles/tree/master/webrtc-android-2</a></p><p>Let’s jump right in and look at the problems with the previous implementation and we can address those problems.</p><h3>Problem and Solution</h3><h4>1. MQTT as signalling channel</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*pnOz36JLwyZwB3rNsA5XDQ.png" /><figcaption>Issue with using MQTT as signalling server</figcaption></figure><p>The first issue comes not from the WebRTC itself but from our choice of signalling protocol, MQTT. MQTT works in a pub-sub model. Whenever a publisher publishes a message on a topic, all the subscribers of that topic will receive the message. If there’re no subscribers to the topic then the message will be ignore. Also, it doesn’t have a mechanism to check the present number of subscribers to a topic.</p><p>Now consider the scenario depicted in the sequence diagram. Let’s say as soon as a webrtc client is connected to the signalling channel, it creates an SDP offer and transmits it. It wouldn’t know whether a subscriber is already connected to the signalling channel to listen to it’s messages. And sure enough if the second client is not connected then the SDP offer is lost. And when the second client is connected and transmits its own SDP offer, the first client doesn’t know what to do with the offer.</p><p>We’ll solve this problem by sending peer messages and acknowledgements. We add a new message type called peer and we’ll exchange peer messages before actual SDP process can being. Each peer will have it’s own ID, a randomly generated integer, and send this ID to the other client. Once the other client receives the ID, it sends its own ID along with a hasRemoteId parameter set to true indicating that it received the remote ID. The ID used here also helps in solving the glare problem discussed next</p><p>The code to send the peer info will look like this</p><pre>private var  selfId: Int = Random.nextInt(0, 10000)<br>private var remoteId: Int? = null<br><br>private fun sendPeerInfo() {<br>    val payload = JSONObject()<br>    payload.put(&quot;type&quot;, &quot;peer&quot;)<br>    payload.put(&quot;selfId&quot;, this.selfId)<br>    payload.put(&quot;hasRemoteId&quot;, remoteId != null)<br>    sendMqttMessage(payload)<br>}</pre><p>And once the peer info is received, handlePeerInfo method is called which stores the remote ID and decides whether to send peer info again or can start with the SDP protocol. The code for this is as below</p><pre>private fun handlePeerInfo(message: JSONObject) {<br>  val hasRemoteId = message.get(&quot;hasRemoteId&quot;) as Boolean<br>  this.remoteId = message.get(&quot;selfId&quot;) as Int<br><br>  // If remote peer doesn&#39;t have our info then send it<br>  // Otherwise start the negotiation<br>  if(!hasRemoteId){<br>      sendPeerInfo()<br>  }<br>  else {<br>      createAndSendLocalDescription()<br>  }<br>}</pre><p>The following sequence diagram depicts how the peer info exchange happens after we make these changes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*8SWdjsZgrB6XDH16lofDEQ.png" /></figure><h4>2. Offer Glare (Race condition)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*0Ojqbbkj1OyKFsUerbQ0eg.png" /><figcaption>Offer Glare</figcaption></figure><p>The next problem we look at is a race condition when both peers tries to send the offers at the same time. This can happen when the session is first initialized or changed subsequently (media is added or removed). Consider the case in the diagram above. Both peers have created their own offers and set the local description. After that they receive the offers from the remote peers. The peers don’t know how to respond to this offer since they have their own offers already set. To solve this problem, we’ll employ a couple of techniques, one to detect glare and the other to respond to it.</p><p>To identify the glare, we set a variable called makingOffer to true just before we start creating the offer and set it to false after the offer is transmitted to the other peer. This technique is more reliable than depending on signallingState to identify glare as creating offer is asynchronous and take some time and we might not detect collision if we receive the offer while self offer is being created.</p><p>The second technique is to deal with offer glare. We solve the problem by assigning the polite role to one of the peers and the impolite role to the other. The polite peer rollbacks the offer in case of glare and the impolite one continues with it’s offer. We shouldn’t rollback the offers from both the peers as that could cause offer glare again the next time offers are sent and this could end up in the connection never being established. Do note though that in case if there’s no offer collision then the impolite peer will accept the offer from the polite peer.</p><p>So how do we agree upon which peer is polite and impolite? This is where the ID we’ve sent during peer info exchange comes into picture. We generated ID as a random number between 1 and 10,000 and sent to the other peer. Whichever peer has the lower ID will be the polite peer and the one with the higher ID will be the impolite peer. Since we won’t continue negotiation till both peers know the ID of the other peer, we’ll always know which one is polite and impolite peer.</p><p>Let’s look at the code to generate and send the offer</p><pre>private fun createAndSendLocalDescription() {<br>  val sdpObserver = object : SdpObserver {<br>      var sdpType : SessionDescription.Type = SessionDescription.Type.OFFER<br><br>      override fun onCreateSuccess(sdp: SessionDescription?) {<br>          Log.i(TAG, &quot;onCreateSuccess: ${sdp?.description}&quot;)<br>          peerConnection?.setLocalDescription(dummySdpObserver, sdp)<br>          val payload = JSONObject()<br>          payload.put(&quot;type&quot;, &quot;sdp&quot;)<br>          payload.put(&quot;sdp&quot;, sdp?.description)<br>          payload.put(&quot;sdpType&quot;, sdpType.ordinal)<br>          sendMqttMessage(payload)<br>          makingOffer = false<br>      }<br>  }<br>// If remote signallingState is stable then we didn&#39;t receive offer yet<br>  if(peerConnection?.localDescription == null &amp;&amp; peerConnection?.signalingState() == PeerConnection.SignalingState.STABLE) {<br>      makingOffer = true<br>      peerConnection?.createOffer(sdpObserver, createSDPConstraints())<br>  }<br>// If we received the remote offer then generate answer<br>  else if (peerConnection?.remoteDescription != null &amp;&amp; peerConnection?.signalingState() == PeerConnection.SignalingState.HAVE_REMOTE_OFFER) {<br>      sdpObserver.sdpType = SessionDescription.Type.ANSWER<br>      peerConnection?.createAnswer(sdpObserver, createSDPConstraints())<br>  }<br>}</pre><p>The method above takes care of generating offer or answer depending on the state of the peerConnection and transmitting it to the other peer. If we haven’t received the offer yet and don’t have local offer then we’ll create offer and send. If we have received the remote offer then we generate an answer to the offer and send it to remote peer.</p><p>Now let’s look at how do handle when the session description is received</p><pre>private fun handleSdpMessage(message: JSONObject) {<br>  // Determine whether this peer is polite or impolite based on IDs<br>  val polite = selfId &lt; remoteId!!<br>  val sdpTypeInt = message.get(&quot;sdpType&quot;) as Int<br>  val sdpType = SessionDescription.Type.values()[sdpTypeInt]<br><br>  // Detect collision<br>  val collision = sdpType == SessionDescription.Type.OFFER &amp;&amp; (makingOffer || peerConnection!!.signalingState() != PeerConnection.SignalingState.STABLE)<br><br>  // If we&#39;re impolite peer and there&#39;s offer collision then ignore offer<br>  // Otherwise, proceed by adding remote description and generating answer<br>  ignoreOffer = !polite &amp;&amp; collision<br>  if(ignoreOffer) {<br>      return<br>  }<br>  val sessionDescription = SessionDescription(sdpType, message.get(&quot;sdp&quot;) as String)<br>  // Setting remote offer while there is an existing local offer will rollback the local offer and use the remote offer<br>  peerConnection?.setRemoteDescription(dummySdpObserver, sessionDescription)<br>  if (sdpType == SessionDescription.Type.OFFER) {<br>      createAndSendLocalDescription()<br>  }<br>}</pre><h3>Conclusion</h3><p>By using the techniques in this article, we’ll be able to have a symmetric code between the peers and also handle the session negotiations in a way that peers don’t get stuck. Do checkout <a href="https://webrtc.github.io/samples/src/content/peerconnection/perfect-negotiation/">this</a> live action demo that depicts the perfect negotiation when the glare happens.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ea5b009a9e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Web Conferencing App(The WebRTC Series — Part 3)]]></title>
            <link>https://bharathkotha.medium.com/web-conferencing-app-the-webrtc-series-part-3-983f1a0b81a6?source=rss-1b65511afb1d------2</link>
            <guid isPermaLink="false">https://medium.com/p/983f1a0b81a6</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[real-time-communication]]></category>
            <category><![CDATA[conference]]></category>
            <category><![CDATA[streaming]]></category>
            <category><![CDATA[webrtc]]></category>
            <dc:creator><![CDATA[Bharath Kotha]]></dc:creator>
            <pubDate>Sat, 26 Aug 2023 07:24:15 GMT</pubDate>
            <atom:updated>2023-08-26T07:24:15.798Z</atom:updated>
            <content:encoded><![CDATA[<h3>Web Conferencing App(The WebRTC Series — Part 3)</h3><p><em>In this article, we’ll write a simple, fully-functional WebRTC Conferencing Android App. We’ll be working on creating peer connection, adding media tracks, signaling, SDP exchange, and ICE negotiation to setup the conferencing app.</em></p><p>In <a href="https://bharathkotha.medium.com/webrtc-architecture-the-webrtc-series-part-1-c1f21802ce32">part 1 of the series</a>, we have discussed the WebRTC architecture and its components. <a href="https://bharathkotha.medium.com/webrtc-conferencing-app-the-webrtc-series-part-2-74a9c18fecbf">In part 2 of the series</a>, we built a functional WebRTC Conferencing app that runs in a browser. In this article, we’ll be building an app similar to the one in part 2 but for Android. Read part 1 if you’re not already familiar with WebRTC architecture and part 2 if you want to know how to work with WebRTC in web. I will be repeating some concepts from part 2 so this article will be self-sufficient. If you already read part 2 then you can glance through the explanations.</p><p>The source code for the article can be found at <a href="https://github.com/bharath-kotha/WebRTC-Articles/tree/master/webrtc-android-1">https://github.com/bharath-kotha/WebRTC-Articles/tree/master/webrtc-android-1</a>. Here’s a screenshot of what we’ll be building by the end of the article</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*pLOq5iHyES3qcuBzTyU0lA.png" /><figcaption>WebRTC Conferencing App</figcaption></figure><h3>Let’s get coding</h3><p>We’ll be following the below steps to create the conferencing application.</p><ol><li>Creating a layout for the application</li><li>Creating PeerConnection object</li><li>Adding video and audio tracks</li><li>Signaling</li><li>SDP exchange</li><li>ICE negotiation</li></ol><h3>1. Creating the Layout</h3><p>We’ll be having the following components in the UI</p><ol><li>remoteView — A video element to display the video of the remote peer</li><li>localView — A video element to display the video captured from our camera. We’ll add remoteView and localView as sinks for the video tracks later in the article.</li><li>meetingId — A text inupt for shared ID using which two people can join the call. This will be used to generate the MQTT topic used in signalling</li><li>role — A dropdown to help with signaling to establish WebRTC connection. Role can be either initiator or receiver.</li></ol><p>I’m not including the actual XML used to generate the layout here as it would take a lot of space and as it is not the main topic of the discussion. The source code used for this article can be found <a href="https://github.com/bharath-kotha/WebRTC-Articles/blob/master/webrtc-android-1/app/src/main/res/layout/activity_main.xml">here</a>.</p><h3>2. Create RTCPeerConnection Object</h3><p>Now that the layout is ready, we’ll actually start working with WebRTC APIs. We need to create PeerConnection objects that provides the core API to stream the media between two peers. There will be two PeerConnection objects, one in each peer, that will establish a connection between them and stream media tracks from one to the other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*amT2YVyr9mMfkUU1P-w70w.png" /><figcaption>Peers connected using PeerConnection API</figcaption></figure><p>Creating of PeerConnection objects in Android is not as straight forward as it is in Web. We first need to initialize and create PeerConnectionFactory and create a new PeerConnection object from it. The PeerConnectionFactory object is later used to create video and audio tracks. First start by adding the WebRTC dependency in build.gradle</p><pre>implementation &#39;io.getstream:stream-webrtc-android:1.0.2&#39;</pre><p>And then create the PeerConnectionFactory as follows</p><pre>// Initialize PeerConnectionFactory<br>val pcfOptions = PeerConnectionFactory.InitializationOptions.builder(context)<br>    .setEnableInternalTracer(true)<br>    .createInitializationOptions()<br>PeerConnectionFactory.initialize(options)<br><br>// Create PeerConnectionFactory<br>val eglBase = EglBase.create()<br>val peerConnFactory = PeerConnectionFactory.builder()<br>    .setAudioDeviceModule(createJavaAudioDevice(context))<br>    .setVideoDecoderFactory(DefaultVideoDecoderFactory(eglBase?.eglBaseContext))<br>    .setVideoEncoderFactory(DefaultVideoEncoderFactory(eglBase?.eglBaseContext, true, true))<br>    .setOptions(PeerConnectionFactory.Options().apply {<br>        disableNetworkMonitor = true<br>    })<br>    .createPeerConnectionFactory()</pre><p>Here, eglBase is used to share resources required for rendering and processing video data. Now that we have create PeerConnectionFactory, we can create a new PeerConnection object from it.</p><pre>val iceBuilder = PeerConnection.IceServer.builder(&quot;stun:stun.l.google.com:19302&quot;)<br>iceBuilder.setTlsCertPolicy(PeerConnection.TlsCertPolicy.TLS_CERT_POLICY_INSECURE_NO_CHECK)<br>val iceServers = arrayListOf(iceBuilder.createIceServer())<br><br>val rtcConfig = PeerConnection.RTCConfiguration(iceServers)<br>rtcConfig.tcpCandidatePolicy = PeerConnection.TcpCandidatePolicy.DISABLED<br>rtcConfig.bundlePolicy = PeerConnection.BundlePolicy.MAXBUNDLE<br>rtcConfig.rtcpMuxPolicy = PeerConnection.RtcpMuxPolicy.REQUIRE<br>rtcConfig.continualGatheringPolicy = PeerConnection.ContinualGatheringPolicy.GATHER_CONTINUALLY<br>rtcConfig.keyType = PeerConnection.KeyType.ECDSA<br>rtcConfig.sdpSemantics = PeerConnection.SdpSemantics.UNIFIED_PLAN<br><br>peerConnection = peerConnFactory?.createPeerConnection(rtcConfig, object : PeerConnection.Observer{}</pre><p>Here we’re first creating a list of ICE servers, passing it into RTCConfiguration object which in turn is passed into createPeerConnection method of PeerConnectionFactory. The ICE servers are used to establish a P2P connection between peers running in two different computer which is explained later in this article. We’re passing some more configurations in RTCConfiguration object in the above code which we’ll discuss in a future article. Also, we need to implement the methods in the PeerConnection.Observer interface which we’ll be doing later in the article. Now that we have PeerConnection object, let’s add media that needs to be shared with other peer.</p><h3>3. Adding Media Tracks to RTCPeerConnection</h3><p><strong>Adding Video</strong></p><p>Creating and adding video stream involves a few steps</p><ol><li>Create video source</li><li>Create video capturer and initialize it</li><li>Create video from video source and render local video</li><li>Add the track to the PC object</li></ol><p>Each of the video source, capturer, and track have different responsibilities. Video capturer object encapsulates the Camera2 Android APIs used for capturing the video. Video source interface feeds the captured video as frames into WebRTC framework. Video track contains APIs to render video of local and remote peers.</p><p>Following is the code to do the 4 steps.</p><pre>// 1. Create video source<br>val localVideoSource = peerConnFactory?.createVideoSource(false)<br><br>// 2. Create video capturer and initialize<br>val enumerator = Camera2Enumerator(context)<br>val deviceNames = enumerator.deviceNames<br><br>// Try to get front facing camera. If it&#39;s not available, get any camera<br>for (deviceName in deviceNames) {<br>    if (enumerator.isFrontFacing(deviceName)) {<br>        videoCapturer = enumerator.createCapturer(deviceName, null)   <br>    }<br>}<br><br>if(videoCapturer == null) {<br>    for (deviceName in deviceNames) {<br>        if (!enumerator.isFrontFacing(deviceName)) {<br>            videoCapturer = enumerator.createCapturer(deviceName, null)<br>        }<br>    }<br>}<br><br>val surfaceTextureHelper = SurfaceTextureHelper.create(Thread.currentThread().name, eglBase.eglBaseContext)<br>videoCapturer?.initialize(surfaceTextureHelper, context, localVideoSource?.capturerObserver)<br>videoCapturer?.startCapture(480, 640, 30)<br><br>// 3. Create video track and render local video<br>localVideoTrack = peerConnFactory?.createVideoTrack(&quot;Video&quot;, localVideoSource)<br>localVideoTrack.addSink(localView)  // localView comes from layout<br><br>// 4. Add track to PC object created before<br>peerConnection?.addTrack(localVideoTrack)</pre><p><strong>Adding Audio</strong></p><p>Sharing audio data is simpler than video. We just need to create an audio source and audio track. WebRTC will internally handle the capturing and playing of audio. Here’s the code to do so</p><pre>// 1. Create audio source<br>val audioSource = peerConnFactory?.createAudioSource(MediaConstraints())<br><br>// 2. Create audio track from audio source<br>val audioTrack = peerConnFactory?.createAudioTrack(&quot;Audio&quot;, audioSource)<br>audioTrack?.setEnabled(true)<br><br>// 3. Add the track to peerConnection<br>peerConnection?.addTrack(audioTrack)</pre><p><strong>Listening for remote tracks</strong></p><p>After completing the above two steps, we have successfully added the local video and audio tracks. But we also have to listen for the tracks added by the remote peer. This we do by implementing the onTrack method of PeerConnection.Observer that we passed to createPeerConnection method. Note that we’re handling only video data by adding sink to it. Audio data is automatically handled by WebRTC.</p><pre>override fun onTrack(transceiver: RtpTransceiver?) {<br>    super.onTrack(transceiver)<br>    if (transceiver?.receiver?.track() is VideoTrack) {<br>        remoteVideoTrack = transceiver.receiver.track() as VideoTrack<br>        remoteView?.let {  // remoteView comes from the layout<br>            remoteVideoTrack?.addSink(it)<br>        }<br>    }<br>}</pre><h3>4. Signaling</h3><p>In the next two steps in setting up the conference app, we need to exchange setup information between two peers. This process of exchanging connection-related information is called signaling in the WebRTC world. We need to do the signaling process out of the band since the connection between the peers is not established yet. Let’s discuss the signaling architecture briefly before jumping into SDP and ICE.</p><p>We’ll be using the MQTT protocol for signaling in this article. But we can as well use any other protocol/mechanism instead of MQTT. All that is required for signaling is to be able to deliver messages to the other peer quickly and reliably. I chose MQTT because it’s a simple lightweight pub-sub protocol and there’s a freely hosted HiveMQ server which I can use without much hassle. Refer to this <a href="https://docs.hivemq.com/hivemq/4.16/user-guide/introduction.html">documentation</a> for more details about MQTT</p><p>MQTT uses the pub-sub model to exchange messages between clients. The topics used by the clients are created on the fly when they’ve been published or subscribed to. First, start by including the MQTT library in the HTML file as follows</p><pre>implementation &#39;com.hivemq:hivemq-mqtt-client:1.2.1&#39;</pre><p>After including the library, we establish a connection to the MQTT broker and subscribe on the topic as follows</p><pre>val client = MqttClient.builder()<br>    .identifier(clientId)  // clientID is a random UUID<br>    .serverHost(&quot;mqtt-dashboard.com&quot;)<br>    .serverPort(1883)<br>    .useMqttVersion5()<br>    .buildAsync()<br><br>val connFeature = client.connectWith().cleanStart(true).send()<br>connFeature.whenComplete { _, throwable -&gt;<br>    if (throwable != null) {<br>        Log.e(TAG, &quot;Connection Error: ${throwable.cause}&quot;, )<br>    }<br>    <br>    else {<br>        // If we wanted to send any messages before connection, they will be queued in pendingMessages and will be sent after connected<br>        pendingMessage.forEach { message -&gt;<br>            publishInternal(message)<br>        }<br>        pendingMessage.clear()<br>    }<br>}<br><br>// Subscribe to topic<br>val topic = &quot;webrtc/conference/$meetingId&quot;  //meetingID is entered by user<br>client.subscribeWith()<br>    .topicFilter(topic)<br>    .send()</pre><p>In the above code, we included the meeting ID in the topic name to correctly connect two participants that wanted to connect with each other. Let’s look at the code segment to publish a message on an MQTT topic.</p><pre>private fun sendMqttMessage(payload: JSONObject) {<br>    payload.put(&quot;role&quot;, role)<br>    mqtt.publish(payload.toString())<br>}<br><br>private fun publish(message: String) {<br>    client.publishWith()<br>        .topic(topic)<br>        .payload(message.toByteArray())<br>        .send()<br>        .whenComplete { publishResult, throwable -&gt;<br>            if (throwable != null) Log.e(TAG, &quot;publish error: $throwable&quot;)<br>        }<br>}</pre><p>We’re using the same topic to publish from both participants of the conference. Since both peers publish and subscribe to the same topic, it’s critical to distinguish the messages from the other peer. To do so, we attach the self role to every MQTT message. And on receiving the, we check if the role in the message matches the self role and ignore the message if it matches as shown below.</p><pre>val mqttMessageListener : (String, String) -&gt; Unit =  { _, payload -&gt;<br>    val message = JSONObject(payload)<br>    val role = message.get(&quot;role&quot;) as String<br>    val type = message.get(&quot;type&quot;) as String<br>    if (role != this.role)  {<br>        if (type == &quot;sdp&quot;) handleSdpMessage(message)<br>        else if (type == &quot;ice&quot;) handleICEMessage(message)<br>    }<br>}<br><br>client.publishes(MqttGlobalPublishFilter.ALL) { message -&gt;<br>    val payload = Charsets.UTF_8.decode(message.payload.get()).toString()<br>    Log.i(TAG, &quot;Received Message: $payload&quot;)<br>    mqttMessageListener(topic, payload)<br>}<br><br></pre><h3>5. SDP Exchange</h3><p>Now that we’ve setup our signalling channel, let’s proceed with the actually signalling. SDP Exchange is the first step in the signalling process. The SDP exchange process involves generating an offer from <em>the initiator peer </em>and receiving it on the <em>receiving peer</em> and generating an answer in response and sending it back to the <em>initiator peer</em>. Because of this offer-answer protocol, we need to distinguish between an initiator and a receiver which we do so using the role dropdown element. Please refer to <a href="https://bharathkotha.medium.com/webrtc-architecture-the-webrtc-series-part-1-c1f21802ce32">article 1 </a>for more details about SDP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*BJzfu_GlGBmq-WUp9nk-vQ.png" /><figcaption>SDP Exchange</figcaption></figure><p>The initiator peer starts the signalling process by creating SDP offering and transmitting it to the other peer through signalling channel. One thing to note here is that each peer sets its own SDP as the local description and the SDP received from the other peer as the remote description. This is required to negotiate the media protocols depending on peers’ capabilities.</p><pre>if(role == &quot;Initiator&quot;) {<br>    peerConnection?.createOffer(object : SdpObserver {<br>        override fun onCreateSuccess(sdp: SessionDescription?) {<br>            peerConnection?.setLocalDescription(dummySdpObserver, sdp)<br>            val payload = JSONObject()<br>            payload.put(&quot;type&quot;, &quot;sdp&quot;)<br>            payload.put(&quot;sdp&quot;, sdp?.description)<br>            sendMqttMessage(payload)<br>        }<br><br>        override fun onSetSuccess() {<br>            Log.i(TAG, &quot;onSetSuccess: &quot;)<br>        }<br><br>        override fun onCreateFailure(error: String?) {<br>            Log.e(TAG, &quot;onCreateFailure: $error&quot;, )<br>        }<br><br>        override fun onSetFailure(error: String?) {<br>            Log.e(TAG, &quot;onSetFailure: $error&quot;, )<br>        }<br><br>    }, createSDPConstraints())<br>}</pre><p>SDP message contains information about which media tracks are added and what protocols are supported to transmit the media. For example, SRTP is used to transmit audio and video whereas SCTP is used to transport other data. SDP also contains various parameters that further configures these protocols.</p><p>On receiving the SDP message, the <em>receiver</em> peer will set the SDP as the remote description and generates an SDP answer. The generated SDP answer is set as <em>receiver</em> peer’s local description and transmitted back to the <em>initiator</em>peer and the <em>initiator</em> peer sets the answer as the remote description. The following code handles the SDP message received through signaling.</p><pre>if(role == &quot;Initiator&quot;) {<br>    val sessionDescription = SessionDescription(SessionDescription.Type.ANSWER, message.get(&quot;sdp&quot;) as String)<br>    peerConnection?.setRemoteDescription(dummySdpObserver, sessionDescription)<br>} <br><br>else if (role == &quot;Receiver&quot;) {<br>    val sessionDescription = SessionDescription(SessionDescription.Type.OFFER, message.get(&quot;sdp&quot;) as String)<br>    peerConnection?.setRemoteDescription(dummySdpObserver, sessionDescription)<br>    peerConnection?.createAnswer(object : SdpObserver {<br>        override fun onCreateSuccess(sdp: SessionDescription?) {<br>            peerConnection?.setLocalDescription(dummySdpObserver, sdp)<br>            val payload = JSONObject()<br>            payload.put(&quot;type&quot;, &quot;sdp&quot;)<br>            payload.put(&quot;sdp&quot;, sdp?.description)<br><br>            sendMqttMessage(payload)<br>        }<br><br>        override fun onSetSuccess() {<br>            TODO(&quot;Not yet implemented&quot;)<br>        }<br><br>        override fun onCreateFailure(error: String?) {<br>            TODO(&quot;Not yet implemented&quot;)<br>        }<br><br>        override fun onSetFailure(error: String?) {<br>            TODO(&quot;Not yet implemented&quot;)<br>        }<br><br>    }, createSDPConstraints())<br>}</pre><p>One important thing here is that, because we’re usingMQTT as signaling transport, the <em>receiver</em> should start first and subscribe to the MQTT topic and wait for<em> </em>the<em> initiator</em>’s message. If the<em> initiator</em> starts first, the SDP message will get lost as the <em>receiver</em> is still not connected, leading to failed SDP negotiation.</p><h3>6. ICE Negotiation and Connection Establishment</h3><p>After adding the local description the connection object starts gathering the ICE candidates. ICE candidates contains information about how the nodes can reach the connection object in network. Each ICE candidate is a possible way to connect but doesn’t guarantee a connection. The candidates are gathered on both the peers and should be exchanged with the other peer. After the exchange, all candidate pairs, one from each peer, are checked to find a pair where both peers can reach each other. More about this is explained in <a href="https://bharathkotha.medium.com/webrtc-architecture-the-webrtc-series-part-1-c1f21802ce32">article 1</a>.</p><p>PeerConnection.Observer object used while creating PeerConnection object has onIceCandidate method that’s called everytime WebRTC gathers an ICE candidate. Let’s implement this method to send the gathered ICE candidate to the remote peer</p><pre>override fun onIceCandidate(ice: IceCandidate?) {<br>    val payload = JSONObject()<br>    payload.put(&quot;type&quot;, &quot;ice&quot;)<br>    payload.put(&quot;ice&quot;, ice)<br>    payload.put(&quot;sdpMid&quot;, ice?.sdpMid)<br>    payload.put(&quot;sdpMLineIndex&quot;, ice?.sdpMLineIndex)<br>    payload.put(&quot;description&quot;, ice?.sdp)<br><br>    sendMqttMessage(payload)<br>}</pre><p>And after the remote peer receives the ICE candidate, it is added to peer connection as follows</p><pre>private fun handleICEMessage(message: JSONObject) {<br>    val sdpMid = message.get(&quot;sdpMid&quot;) as String<br>    val sdpMLineIndex = message.get(&quot;sdpMLineIndex&quot;) as Int<br>    val iceDescription = message.get(&quot;description&quot;) as String<br>    val ice = IceCandidate(sdpMid, sdpMLineIndex, iceDescription)<br><br>    peerConnection?.addIceCandidate(ice)<br>}</pre><h3>Putting it all together</h3><p>That’s all the code that’s required for a functioning Android webRTC conferencing app. Take the code written so far and install it in two android devices and fire up the apps. Give the required permissions by going into settings (We haven’t handled dynamic permissions so the permissions needs to be given from settings).Enter same meeting ID in both the devices. Select one devices as receiver and the other as initiator. Start the receiver first followed by the initiator. Voila, you have your own conferencing app.</p><h3>Next steps</h3><p>This and the previous articles just explain the basics of how to work with WebRTC. There’s a lot more to itIn the next articles, let’s dig a little deeper into the core workings of WebRTC and how to customise a few configuration parameters.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=983f1a0b81a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WebRTC Conferencing App(The WebRTC Series — Part 2)]]></title>
            <link>https://bharathkotha.medium.com/webrtc-conferencing-app-the-webrtc-series-part-2-74a9c18fecbf?source=rss-1b65511afb1d------2</link>
            <guid isPermaLink="false">https://medium.com/p/74a9c18fecbf</guid>
            <category><![CDATA[streaming]]></category>
            <category><![CDATA[real-time-communication]]></category>
            <category><![CDATA[conference]]></category>
            <category><![CDATA[webrtc]]></category>
            <dc:creator><![CDATA[Bharath Kotha]]></dc:creator>
            <pubDate>Sat, 01 Jul 2023 09:58:51 GMT</pubDate>
            <atom:updated>2023-07-01T10:03:12.650Z</atom:updated>
            <content:encoded><![CDATA[<h3>Web Conferencing App(The WebRTC Series — Part 2)</h3><blockquote>In this article, we’ll write a simple, fully-functional WebRTC Conferencing App that runs in a web browser. We’ll be working on creating peer connection, adding media tracks, signaling, SDP exchange, and ICE negotiation to setup the conferencing app.</blockquote><p>In <a href="https://bharathkotha.medium.com/webrtc-architecture-the-webrtc-series-part-1-c1f21802ce32">part 1 of the series</a>, we have discussed the WebRTC architecture and its components. We have also looked at a basic application workflow. We’ll take the concepts from the article and implement a functioning conferencing app. Go ahead and read the <a href="https://bharathkotha.medium.com/webrtc-architecture-the-webrtc-series-part-1-c1f21802ce32">article</a> on WebRTC architecture if you’re not already familiar with the concepts.</p><p>You can try the app that we’ll implement in this article from <a href="https://bharath-kotha.github.io/webrtc/articles/1/">here</a>. Open the link in two different browsers. Once opened, enter the same meeting ID in both browsers. Select the role as <em>WebRTC SDP Receiver</em> in the first browser and click on “Join Conference”. In the second browser, select the role as <em>WebRTC SDP Initiator</em> and click on “Join Conference”. Both browsers should now be able to communicate with each other.</p><p>Here’s a screenshot of the final app if you haven’t checked out the sample app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WzwDSXFjy0yhCjFEvvJjnA.png" /><figcaption>WebRTC Conferencing App</figcaption></figure><p>The source code for all the code snippets used in this article is available here — <a href="https://github.com/bharath-kotha/WebRTC-Articles/tree/master/WebRTC-web-1">https://github.com/bharath-kotha/WebRTC-Articles/tree/master/WebRTC-web-1</a>. Without further ado</p><h3>Let’s get coding</h3><p>We’ll be following the below steps to create the conferencing application. The rest of this section discusses each of these steps in more depth.</p><ol><li>Creating a layout for the application</li><li>Creating RTCPeerConnection object</li><li>Adding video and audio tracks</li><li>Signaling</li><li>SDP exchange</li><li>ICE negotiation</li></ol><h4>1. Creating the Layout</h4><p>Let’s think about what we need in the interface. At the least, we need a window to see the other person. Along with that, it would be good if we can see ourselves as well during video calls. Also, we need a shared meeting ID between two participants. Along with these we’ll also be adding another dropdown for the SDP role. This information helps in SDP negotiation process described later.</p><p>So, we’ll be having the following components in the UI</p><ol><li>Remote Video — A video element to display the video of the other person</li><li>Local Video — A video element to display the video captured from our camera</li><li>Meeting ID — A text inupt for shared ID using which two people can join the call.</li><li>Role — A dropdown to help with signaling to establish WebRTC connection (discussed in depth later)</li></ol><p>Here’s the code to add these elements to the UI</p><pre>&lt;input type=&quot;text&quot; id=&quot;meetingId&quot;&gt;<br>&lt;select id=&quot;role&quot;&gt;<br>    &lt;option value=&quot;initiator&quot;&gt;WebRTC SDP Initiator&lt;/option&gt;<br>    &lt;option value=&quot;receiver&quot;&gt;WebRTC SDP Receiver&lt;/option&gt;<br>&lt;/select&gt;<br>&lt;button id=&quot;joinButton&quot;&gt;Join Conference&lt;/button&gt;<br>&lt;div class=&quot;video-container&quot;&gt;<br>    &lt;div class=&quot;local-video&quot;&gt;<br>        &lt;h2&gt;Local Video&lt;/h2&gt;<br>        &lt;video id=&quot;localVideo&quot; autoplay muted&gt;&lt;/video&gt;<br>    &lt;/div&gt;<br>    &lt;div class=&quot;remote-video&quot;&gt;<br>        &lt;h2&gt;Remote Video&lt;/h2&gt;<br>        &lt;video id=&quot;remoteVideo&quot; autoplay&gt;&lt;/video&gt;<br>    &lt;/div&gt;<br>&lt;/div&gt;</pre><p>Next, we should apply the CSS rules to organize the UI and make it look better. We‘ll leave out the styling details here as it is not relevant to our discussion. The CSS code is available <a href="https://github.com/bharath-kotha/WebRTC-Articles/blob/master/WebRTC-web-1/style.css">here </a>to make the UI look similar to the one shared in the screenshot.</p><h4>2. Create RTCPeerConnection Object</h4><p>Now that the layout is ready, we’ll actually start working with WebRTC APIs. RTCPeerConnection is the first among them that provides the core API to stream the media between two peers. There will be two RTCPeerConnection objects, one in each peer, that will establish a connection between them and stream media tracks from one to the other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*amT2YVyr9mMfkUU1P-w70w.png" /><figcaption>RTCPeerConnection</figcaption></figure><p>Creating a peer connection object is quite easy and can be done using the following code</p><pre>const configuration = { iceServers: [{ urls: &#39;stun:stun.l.google.com:19302&#39; }] };<br>let rtcConnection = new RTCPeerConnection(configuration);</pre><p>Here we’re passing a list of STUN servers as a configuration when initializing RTCPeerConnection. STUN servers are helpful in establishing the connection between the peer connection objects as discussed later in the article. It’s possible to pass more configuration options while initializing the RTCPeerConnection object. We’ll discuss these options in a future article.</p><h4>3. Adding Media Tracks to RTCPeerConnection</h4><p>Next, we proceed by adding the audio and video to the connection so that the other peer can receive it. MediaDevices interface provides a simple API to ask user permissions for camera/microphone and once they are granted, return a MediaStream object. A MediaStream object consists of one or more MediaStreamTrack objects that are synchronized and related to the same source. For example, there will be one audio and one video MediaStreamTrack in the MediaStream for each peer for the conferencing app. Once the MediaStream is obtained, we’ll have to add the individual tracks to the RTCPeerConnection object. As a final step, let’s also add the Stream to the localVideo HTML element so that the local video can be rendered.</p><pre>// Request access to user&#39;s camera and microphone<br>localStream = await navigator.mediaDevices.getUserMedia(<br>  { audio: true, video: true }<br>);<br><br>// Add local media stream tracks to the connection<br>localStream.getTracks().forEach((track) =&gt; {<br>    rtcConnection.addTrack(track, localStream);<br>});<br><br>// Display local video stream in the local video element<br>const localVideo = document.getElementById(&#39;localVideo&#39;);<br>localVideo.srcObject = localStream;</pre><p>We have added the local tracks to connection object but we also need to receive the track information from the remote peer as well if we want to display the other participant video. RTCPeerConnection objects provides this information through track event. Let’s catch these remote tracks by attaching an event listener for track event and add the tracks to remoteVideo HTML element.</p><pre>// Set remote video stream as the source for the remote video element<br>rtcConnection.addEventListener(&#39;track&#39;, (event) =&gt; {<br>    const remoteVideo = document.getElementById(&#39;remoteVideo&#39;);<br>    if (event.track.kind === &#39;video&#39;) {<br>        remoteVideo.srcObject = event.streams[0];<br>    }<br>});</pre><h4>4. Signaling</h4><p>In the next two steps in setting up the conference app, we need to exchange setup information between two peers. This process of exchanging connection-related information is called signaling in the WebRTC world. We need to do the signaling process out of the band since the connection between the peers is not established yet. Let’s discuss the signaling architecture briefly before jumping into SDP and ICE.</p><p>We’ll be using the MQTT protocol for signaling in this article. But we can as well use any other protocol/mechanism instead of MQTT. All that is required for signaling is to be able to deliver messages to the other peer quickly and reliably. I chose MQTT because it’s a simple lightweight pub-sub protocol and there’s a freely hosted HiveMQ server which I can use without much hassle. Refer to this <a href="https://docs.hivemq.com/hivemq/4.16/user-guide/introduction.html">documentation</a> for more details about MQTT</p><p>MQTT uses the pub-sub model to exchange messages between clients. The topics used by the clients are created on the fly when they’ve been published or subscribed to. First, start by including the MQTT library in the HTML file as follows</p><pre>&lt;script src=&quot;https://unpkg.com/mqtt/dist/mqtt.min.js&quot;&gt;&lt;/script&gt;</pre><p>After including the library, we establish a connection to the MQTT broker and subscribe on the topic as follows</p><pre><br>const mqttBroker = &#39;wss://mqtt-dashboard.com:8884/mqtt&#39;;<br>const mqttTopicPrefix = &#39;webrtc/conference/&#39;; // Replace with your MQTT topic<br>let mqttClient;<br><br>const meetingId = document.getElementById(&#39;meetingId&#39;).value;<br><br>// Connect to the MQTT broker<br>mqttClient = mqtt.connect(mqttBroker);<br>mqttTopic = mqttTopicPrefix + meetingId<br><br>// Handle MQTT connection<br>mqttClient.on(&#39;connect&#39;, () =&gt; {<br>    console.log(&#39;Connected to MQTT broker&#39;);<br><br>    // Subscribe to the MQTT topic<br>    mqttClient.subscribe(mqttTopic);<br>});</pre><p>Here we include the meeting ID in the topic name to correctly connect two participants using the meeting ID. Let’s look at the code segment to publish a message on an MQTT topic.</p><pre>// Function to send MQTT message<br>function sendMqttMessage(payload) {<br>    const meetingId = document.getElementById(&#39;meetingId&#39;).value;<br>    const role = document.getElementById(&#39;role&#39;).value;<br><br>    const mqttTopic = mqttTopicPrefix + meetingId<br>    payload.role = role;<br>    <br>    mqttClient.publish(mqttTopic, JSON.stringify(payload));<br>}</pre><p>If you notice, we’re actually using the same topic to publish from both participants of the conference. Since both peers publish and subscribe to the same topic, it’s critical to distinguish the messages from the other peer. To do so, we attach the self role to every MQTT message. And on receiving the, we check if the role in the message matches the self role and ignore the message if it matches.</p><pre>// message event is triggered on every new message on the subscrived topic<br>mqttClient.on(&#39;message&#39;, handleMqttMessage);<br><br>function handleMqttMessage(topic, message) {<br>    const payload = JSON.parse(message);<br>    const role = document.getElementById(&#39;role&#39;).value<br><br>    // Ignore self messages<br>    if(payload.role === role) return;<br><br>    if (payload.type === &#39;sdp&#39;) {<br>        handleSdpMessage(payload.sdp);<br>    } else if (payload.type === &#39;ice&#39;) {<br>        handleIceCandidate(payload.candidate);<br>    }<br>}</pre><h4>5. SDP Exchange</h4><p>SDP Exchange is the first step in the connection establishment process. The SDP exchange process involves generating an offer from <em>the initiator peer </em>and receiving it on the <em>receiving peer</em> and generating an answer in response and sending it back to the <em>initiator peer</em>. Because of this offer-answer protocol, we need to distinguish between an initiator and a receiver which we do so using the role dropdown element. Please refer to <a href="https://bharathkotha.medium.com/webrtc-architecture-the-webrtc-series-part-1-c1f21802ce32">article 1 </a>for more details about SDP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*Lsd25Vy2eleu8zcabfMKFg.png" /><figcaption>SDP Exchange</figcaption></figure><p>negotiationneeded event is an indicator from RTCPeerConnection that we can proceed with the SDP exchange. We’ll attach an event listener for this event and send the SDP offer if the role is <em>initiator</em>. One thing to note here is that each peer sets its own SDP as the local description and the SDP received from the other peer as the remote description. This is required to negotiate the media protocols depending on peers’ capabilities.</p><pre>// Send SDP offer to the receiver<br>rtcConnection.addEventListener(&#39;negotiationneeded&#39;, async () =&gt; {<br>    const role = document.getElementById(&#39;role&#39;).value;<br>    if (role === &#39;receiver&#39;) return;<br>    try {<br>        // Create offer and set local description<br>        const offer = await rtcConnection.createOffer();<br>        await rtcConnection.setLocalDescription(offer);<br><br>        console.log(&#39;SDP offer created and set as local description&#39;);<br><br>        // Send offer to the receiver<br>        sendMqttMessage({<br>            meetingId: document.getElementById(&#39;meetingId&#39;).value,<br>            type: &#39;sdp&#39;,<br>            sdp: rtcConnection.localDescription.sdp<br>        });<br>    } catch (error) {<br>        console.error(&#39;Error creating SDP offer:&#39;, error);<br>    }<br>});</pre><p>SDP message contains information about which media tracks are added and what protocols are supported to transmit the media. For example, SRTP is used to transmit audio and video whereas SCTP is used to transport other data. SDP also contains various parameters that further configures these protocols.</p><p>On receiving the SDP message, the <em>receiver</em> peer will set the SDP as the remote description and generates an SDP answer. The generated SDP answer is set as <em>receiver</em> peer’s local description and transmitted back to the <em>initiator</em> peer and the <em>initiator</em> peer sets the answer as the remote description. The following code handles the SDP message through signaling in both <em>initiator</em> and <em>receiver</em>.</p><pre>role = document.getElementById(&#39;role&#39;).value<br>if (role === &#39;initiator&#39;) {<br>    await rtcConnection.setRemoteDescription({ type: &#39;answer&#39;, sdp });<br>    console.log(&#39;SDP answer set as remote description&#39;);<br>} else if (role === &#39;receiver&#39;) {<br>    await rtcConnection.setRemoteDescription({ type: &#39;offer&#39;, sdp });<br>    console.log(&#39;SDP offer set as remote description&#39;);<br><br>    // Create answer and set local description<br>    const answer = await rtcConnection.createAnswer();<br>    await rtcConnection.setLocalDescription(answer);<br><br>    console.log(&#39;SDP answer created and set as local description&#39;);<br><br>    // Send answer to the initiator<br>    sendMqttMessage({<br>        meetingId: document.getElementById(&#39;meetingId&#39;).value,<br>        type: &#39;sdp&#39;,<br>        role: document.getElementById(&#39;role&#39;).value,<br>        sdp: rtcConnection.localDescription.sdp<br>    });<br>}</pre><p>One thing to note here is that, because of the use of MQTT as signaling transport, the <em>receiver</em> should do the start first and subscribe to the MQTT topic and wait for<em> </em>the<em> initiator</em>’s message. If the<em> initiator</em> starts first, the SDP message will be lost as the <em>receiver</em> is still not connected, leading to failed SDP negotiation. There’s an algorithm for exchanging SDP that doesn’t have this drawback that we’ll discuss in a future article.</p><h4>6. ICE Negotiation and Connection Establishment</h4><p>After adding the local description the connection object starts gathering the ICE candidates. ICE candidates contains information about how the nodes can reach the connection object in network. Each ICE candidate is a possible way to connect but doesn’t guarantee a connection. The candidates are gathered on both the peers and should be exchanged with the other peer. After the exchange, all candidate pairs, one from each peer, are checked to find a pair where both peers can reach each other. More about this is explained in <a href="https://bharathkotha.medium.com/webrtc-architecture-the-webrtc-series-part-1-c1f21802ce32">article 1</a>.</p><p>RTCPeerConnection provides an icecandidate event to indicate whenever it gathers an ICE candidate. Let’s add an event listener and send the message to the other peer</p><pre>// Handle ICE candidates<br>rtcConnection.addEventListener(&#39;icecandidate&#39;, (event) =&gt; {<br>    if (event.candidate) {<br>        // Send ICE candidate to the other participant<br>        sendMqttMessage({<br>            meetingId: document.getElementById(&#39;meetingId&#39;).value,<br>            type: &#39;ice&#39;,<br>            candidate: event.candidate<br>        });<br>    }<br>});</pre><p>The ICE candidate received from the other peer should be added to the peer connection as follows</p><pre>rtcConnection.addIceCandidate(candidate);</pre><p>That’s it. We’re done with all the steps required for setting up a functioning conferencing application.</p><h3>Putting it all together</h3><p>Now that we have done with all the steps, let’s fire up the browser and see what we have achieved. Open the app in two browsers and follow the steps in the introduction of this article to start conferencing. We now have our own conferencing application that is secure and end-to-end encrypted. Go ahead and share it with your colleagues and loved ones.</p><h3>What’s next?</h3><p>In this article, we have intentionally missed out on a few concepts such as configuring RTCPeerConnection, symmetric SDP exchange, etc. We’ll take up these concepts along with implementing the conferencing app in android in the future articles. Finally, this <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API">documentation</a> from MDN is a good resource for learning more about WebRTC.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74a9c18fecbf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WebRTC Architecture (The WebRTC Series — Part 1)]]></title>
            <link>https://bharathkotha.medium.com/webrtc-architecture-the-webrtc-series-part-1-c1f21802ce32?source=rss-1b65511afb1d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1f21802ce32</guid>
            <category><![CDATA[real-time-communication]]></category>
            <category><![CDATA[webrtc]]></category>
            <category><![CDATA[streaming]]></category>
            <dc:creator><![CDATA[Bharath Kotha]]></dc:creator>
            <pubDate>Sat, 17 Jun 2023 10:21:55 GMT</pubDate>
            <atom:updated>2023-06-17T10:21:55.260Z</atom:updated>
            <content:encoded><![CDATA[<h3>WebRTC Architecture (The WebRTC Series — Part 1)</h3><blockquote>The part 1 of the series introduces some of the core concepts of WebRTC such as signalling, SDP, ICE protocol, STUN and TURN protocols, Data Channel and discusses a basic application workflow.</blockquote><p>WebRTC framework has gained a lot of moment in the real-time communication space in recent times owing to Covid. It’s supported by over 2 Billion browsers world-wide. This technology is used in some famous real-time communication applications including Google Meet, Discord, and Amazon Chime.</p><p>Recently, I had a chance to work on the WebRTC on a project and got to learn a lot of new cool stuff about real-time video streaming. There were some challenges along the way while working on the project as the documentation for webRTC was not that great for native applications. So, I thought I would share some insights I got while working on WebRTC through a series of articles. Let’s dive right in.</p><h3><strong>What is WebRTC?</strong></h3><p>WebRTC is an open-source framework that enables real-time communication and conferencing applications on web browsers and native devices without the need of intermediate servers. Wow! That’s a handful of words. Let’s understand each characteristic of WebRTC a bit better.</p><p><strong>Open-source framework: </strong>WebRTC is an open standard developed by google back in 2011 and still being improved. It’s a set of previously existing protocols put together to enable realtime communications.</p><p><strong>Real-time communication and conferencing: </strong>WebRTC framework can be used to achieve latencies in the &lt;500ms range making it an ideal solution for real-time communications. One thing to note here is that real-time communication is different than live-streaming. Real-time communication involves interaction between people that requires ultra low latencies whereas live-streaming requires latencies in the order of 1— 30seconds</p><p><strong>Device support: </strong>WebRTC is supported by many modern browsers such as Chrome, Firefox, Safari, Edge, Opera, etc. (It has Web in it’s name, duh!). Though it was initially developed for Web, the supported was added for C++ native APIs as well. The APIs are ported for Android and iOS platforms as well making it one of the most ubiquitous real-time communications framework.</p><p><strong>Serverless media communication: </strong>WebRTC is built-upon the peer-to-peer architecture eliminating the need for a central server to exchange the video, audio data. The lack of need for a server reduces costs significantly for an application developer. There’re a few of gotchas here.</p><ul><li>We still need a server so that peers can find each other(using a process called signalling) before media can be transported.</li><li>To establish a connection between peers that are behind NAT, a STUN server might be required.</li><li>In case if the peers can’t communicate with each other directly, we might need a server to relay the media data.</li></ul><p>We’ll understand these cases better later in the article.</p><p><strong>Batteries included:</strong> WebRTC framework comes with all the necessary modules required for real-time communications out of the box. It doesn’t require installing other codecs, plugins, or third-party software. WebRTC supports some famous codecs including VP8, VP9, H.264, H.265, etc.</p><p><strong>Security:</strong> WebRTC was built with security in mind. All the media communicated using the framework is end-to-end encrypted by default.</p><p>Now that there’s a slightly better understanding of what WebRTC can do, let’s jump into the architectural components of WebRTC.</p><h3>Architecture</h3><p>Working with WebRTC involves understanding some basic architectural building blocks (I don’t claim it’s easy). Some of them include</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*S4HJv9imfDxsFX0gmhd_Iw.png" /><figcaption>WebRTC Application Architecture</figcaption></figure><p><strong>PeerConnection: </strong>The main APIs of WebRTC are exposed through the PeerConnection class. This class encapsulates major parts of media streaming setup including negotiating media requirements, establishing connection with the other peer, encoding, decoding, transporting data, bandwidth estimation etc.</p><p><strong>Signalling:</strong> Signalling is a fancy name for a protocol where the peers (peer connections) exchange information on how and what to communicate. Signalling is done out-of-band which means that WebRTC doesn’t specify how the signalling info is exchanged. The signalling can be done using a server or we can even write the signalling data on a post card and send it to the other peer for all WebRTC cares(though it wouldn’t be real-time anymore if we do that). The lack of specification for signalling exchange gives a lot of flexibility for developers. I have personally developed a WebRTC application that runs completely offline without internet on a local Wi-Fi network. Signalling mainly includes exchanging of SDP and ICE candidates, described below.</p><p><strong>Session Description Protocol (SDP): </strong>SDP is used to negotiate the media information being exchanged. SDP data contains details such as what media (video/audio) is being transmitted, which protocols are used to transmit media (different protocols such as SRTP, SCTP, DTLS, etc. can be used for video, audio, and data channel), which ports are being used, which codecs are supported, codec parameters, etc. As mentioned before, SDP exchange happens as part of signalling. The initiating peer creates SDP offer that contains the above information and sends to the other peer and the other peer looks at SDP offer and generates it’s own answer and sends back to initiating peer thus completing the negotiation.</p><p><strong>Interactive Connectivity Establishment (ICE): </strong>ICE protocol is used to establish connection between two peers. ICE is required because <a href="https://en.wikipedia.org/wiki/Network_address_translation">NAT</a> in IPv4 networks makes it difficult for peers to connect with each other directly if they are behind NAT. ICE provides mechanism using which peers can be connected with each other even if they are behind NAT. As part of ICE negotiation, first a set of ICE candidates are gathered at each peer and exchanged with the other peer. An ICE candidate represents information about a possible way the peer can be connected. After that, connectivity checks are performed for each set of local and remote ICE candidates and a pair of ICE candidates are agreed upon to exchange media at the end. The media exchange path would have been established when the ICE negotiation is completed.</p><p>The connection thus established can be in one of the three categories based on the network each peer belongs to. They are</p><ol><li>Using the <em>host</em> ICE candidates if the peers can connect with each other without traversing NAT</li><li>Using STUN protocol (explained below) if the peers can reach each other by traversing NAT</li><li>Using a relay server using TURN protocol (explained below) if the peers can’t connect with each using NAT traversal</li></ol><p><strong>Session Traversal Utilities for NAT (STUN): </strong>Without STUN, two peers behind NAT can’t reach each other’s IP address. To make the direct connection possible, they first need to connect to a publicly reachable STUN server. This creates a hole in the NAT server (a hole is technically a mapping from network local host and port to a publicly accessible host and port). The information about this hold is then exchanged with the other peer using signalling as an STUN ICE candidate after which the connection can be established. After the connection is established, the media is directly exchanged with the other peer utilizing the hold in the NAT.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*uRHTxKfB2n3DAXHNf3RTqA.png" /><figcaption>ICE Connection Establishment through STUN</figcaption></figure><p><strong>Traversal Using Relays around NAT (TURN): </strong>The STUN connection establishment doesn’t work for all kinds of NAT. The connection establishment is not be possible using STUN if a peer is behind a <a href="https://en.wikipedia.org/wiki/Network_address_translation#Methods_of_translation">symmetric NAT</a> which is a more secure version of NAT. In this case application will have to depend on relay servers called TURN servers to exchange media. The peer will first establish a connection with the TURN server and share this connection information with the other peer through signalling as an TURN ICE candidate. Then the other peer can establish the connection with the relay server and transmit media. In this case, the media is not transmitted to peer but instead sent through a relay that could incur additional. Many companies that provide WebRTC services charge the customers for these relay servers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*CtRyhx9n9n3cQpBAb0RinQ.png" /><figcaption>ICE Connection Establishment through TURN</figcaption></figure><p><strong>Data Channels: </strong>WebRTC provides a way for applications to exchange non-media data through data channel interface of a peer connection. The data exchanged is by default encrypted. It’s possible to configure how data should be delivered when using data channels. Some of the configuration options possible are whether to deliver data in-order, guaranteed delivery etc.</p><p>Now that some of the broad concepts in WebRTC are discussed, let’s look at a typical workflow of a conferencing application between two client.</p><h3>WebRTC Workflow for Conferencing</h3><p>The following steps would be required to establish a connection between two peers and exchange media data.</p><ol><li>Create Peer Connection objects on both clients</li><li>Add the video and audio tracks to the Peer Connection using the API provided on Peer Connection</li><li>Add any data channel if required on the Peer Connection</li><li>Designate a client as signalling initiator (let’s call it Client1) and create an offer using Peer Connection on that client</li><li>Send this offer to the other client (Client2) using the signalling server</li><li>Receive the SDP offer on Client2 and generate SDP answer using Peer Connection and send it back to Client1</li><li>Receive the SDP answer on Client1 and accept.</li><li>Register a callback of ICE candidates on Peer Connection on both clients and as soon as ICE candidates are received, exchange them with the other client</li><li>Wait for the callback from the Peer Connection regarding the media track added from the other client</li><li>Wait for the ICE negotiation completion event from Peer Connection and attach necessary Views to handle the video/audio/data from the other peer.</li></ol><p>This is an high-level overview of the steps involved in establishing a real-time communication channel. Coding of the application involves dealing with a lot more fine-grained details which will be discussed in later articles.</p><h3>What Next?</h3><p>This is an overall introduction of WebRTC architecture and concepts. The next article in the series will be about how to put together these concepts and build a sample WebRTC project. Hope to see you there!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1f21802ce32" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why is my database write IO is so high]]></title>
            <link>https://bharathkotha.medium.com/how-select-statement-can-cause-disk-write-io-80932fcc9def?source=rss-1b65511afb1d------2</link>
            <guid isPermaLink="false">https://medium.com/p/80932fcc9def</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Bharath Kotha]]></dc:creator>
            <pubDate>Sun, 07 Aug 2022 17:20:59 GMT</pubDate>
            <atom:updated>2022-08-15T04:55:27.155Z</atom:updated>
            <content:encoded><![CDATA[<p>SELECT query might be one of the things causing the high disk write IO under the hood. Yes, reading data from the database can cause writes to disk. However strange it may seem, it happens because the database has to return the data in the format/order that we ask it to. This post sets up a small SELECT query that would cause disk writes and explains which part of the query is causing it.</p><p>To set things up, we’ll be creating two tables — books and authors. Postgres is used to do the setup in this post. The scripts might need to be modified little bit to match the other databases. To create the tables, run the following SQL statements.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/67447cd79336e0840f4594df1057318a/href">https://medium.com/media/67447cd79336e0840f4594df1057318a/href</a></iframe><p>Once the tables are created, the below script generates the data to be loaded into the tables.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32c43f1c9e39ad68466a7444003b06f3/href">https://medium.com/media/32c43f1c9e39ad68466a7444003b06f3/href</a></iframe><p>The scripts generates SQL statements required to populate the data and writes them to data.sql file. The number of authors and number of books can be controlled by the variables at the top of the script. Once the file is generated, the data can be imported to the database using the following shell command</p><pre>psql -q -U username -d database_name -h localhost --password &lt; /path/to/data.sql</pre><p>The loading and generating of the data might take sometime depending on the size of the data. Also, the tables might need to be truncated if the data was already loaded before and wants to load again.</p><p>Now let’s run the ANALYZE on a couple of simple queries and see what happens. Run the following query in the database terminal</p><pre>EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM book INNER JOIN author ON book.author_id = author.id ORDER BY book.id LIMIT 100;</pre><p>This is the sort of queries that gets run when when admin pages are opened on Django dashboard (and select_related is populated on admin). The above query results in the following query plan</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3714615907024debe9bdc1d468ff6f9/href">https://medium.com/media/f3714615907024debe9bdc1d468ff6f9/href</a></iframe><p>This is how the above query plan is read</p><p>Lines 7–8: Scan through books table following primary key<br>Lines 9–11: Find the author of the book in the authors table by fetching it based on the author id (autho_id of the book is available from lines 7–8)<br>Lines 5–6: Do above two steps for all the rows in books table<br>Lines 3–4: Limit the results to 100</p><p>In more general words, the query plan says that find the first 100 rows of books table sorted by ID and follow the foreign key to find the authors of those books. More importantly, the query is not writing anything back to DB and using the memory to compute the entire query result. And the query itself is finished in around 25 ms.</p><p>Let’s see what happens if the query changes slightly to sort it based on book title alongside id. This could be a query that will be executed when the tables in the Django admin dashboard are clicked to sort by a different column. Execute the following ANALYZE query</p><pre>EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM book INNER JOIN author ON book.author_id = author.id ORDER BY title ASC, book.id ASC LIMIT 100;</pre><p>And the query plan output looks like following</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2afe328f3c540d3683e105a8652e8c07/href">https://medium.com/media/2afe328f3c540d3683e105a8652e8c07/href</a></iframe><p>Wow!! That’s a huge query plan. Let’s dig a little deep into what’s happening here</p><p>Lines 6–7: Plan and launch 2 worker threads<br>Lines 20–24: Using the workers, hash the authors table by sequentially scanning it to prepare it for join.<br>Lines 15–19: Using the workers, sequentially scan the books table and join it with the authors table using the hash<br>Lines 9–14: Sort the data using a Top-N heap sort algorithm<br>Lines 5–8: Join the data from the worker threads<br>Lines 3–4: Limit the output to 100 rows</p><p>A seemingly innocuous query caused the database to sequentially scan the tables, hash and join them. Since the working memory is not sufficient to perform these actions, the database had to write temporary data to the disk. Sequentially scan tables itself is a very expensive operations for large tables. Moreover, having to write the roughly same amount of data back to disk will be more costly slowing the query considerably. A total of 195896 temporary blocks were written while executing the query and the query took almost 26 seconds usually not acceptable in a OLTP systems.</p><p>This is an issue we actually faced in our production system. We have seen the database disk write IO start shooting up and the available storage space reduce rapidly. It was very unintuitive for us to identify that a SELECT query was causing the issue. It had a cascading effect on the system performance for quite a while. We were able to debug the issue and resolve it thanks to the monitoring in place. Adding alerts around disk usage, write IOPS will also help identifying such issues on time and keep production systems stable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80932fcc9def" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Don’t mutate objects inside Celery task]]></title>
            <link>https://bharathkotha.medium.com/dont-mutate-objects-inside-celery-task-cef1ba334e22?source=rss-1b65511afb1d------2</link>
            <guid isPermaLink="false">https://medium.com/p/cef1ba334e22</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[celery]]></category>
            <dc:creator><![CDATA[Bharath Kotha]]></dc:creator>
            <pubDate>Sat, 12 Jun 2021 17:59:21 GMT</pubDate>
            <atom:updated>2021-06-12T17:59:21.089Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, when I was trying to write a celery task I had an issue with mutating a dictionary (changing the dictionary values) when the retries are enabled for the task. When I searched through the internet, I couldn’t find any resources which were related to the problem. So I wanted to describe what exactly was the problem and how to avoid it.</p><p>Tl;dr Don’t modify the mutable datatype objects inside the celery tasks when the tasks could be retried. If you have to, first make a copy of the mutable object and make changes to the copy.</p><p>I was writing a code to store some logs data to a database for analytics . The incoming data needed to be slightly modified such as changing timestamp, calculating updated time, etc. before logging it to the DB. I wanted to do this job asynchronously and with retries so that the logging won’t fail. Since the application that I was working on had Python Celery setup and configured, I chose to create a task to complete this job. Following is an emulation of part of what the code does</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nkQdQlRP9St6dCAgtKrm4g.png" /></figure><p>In the file, we’re trying to save the travel details to a database. The celery task save_travel_details converts the epoch time to ISO format and calls save_to_db to save the data. In the save_to_db method, we’re just printing the data to terminal, but in production this would usually be a network call to a database which could fail due to lot of reasons such network failures, transaction rollbacks, DB overloads, etc. Now if we run the file typing python tasks.py, we can see the following output (install pytest, celery, pytest-celery if you’re getting import errors)</p><pre>{&#39;from&#39;: &#39;Hyderabad&#39;, &#39;to&#39;: &#39;Bangalore&#39;, &#39;flight_number&#39;: &#39;PQ126BN&#39;, &#39;time&#39;: &#39;2021-06-12 15:00:00&#39;}</pre><p>Till here everything seems fine. But we haven’t tested what happens when the save_to_db call fails. To emulate the scenario, I used pytest to setup the environment and run the tests. (Alternatively, I could use a debugger to go through the code flow) Following is the code for the tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wKMXcSJ-5241iY_Q7m1ZHw.png" /><figcaption>test_tasks.py</figcaption></figure><p>For the purpose of the discussion, I won’t go and explain about pytest, mocks, or patching. But essentially in the line 26 above, we’re making save_to_db to throw an exception. And another detail here is that retry method calls signature method internally to wrap arguments, task, and task options into a single Signature object. Later task scheduling calls (such as apply_async etc.) or made on the Signature object. Details about the signature method can be found here — <a href="https://docs.celeryproject.org/en/stable/reference/celery.html#celery.signature">https://docs.celeryproject.org/en/stable/reference/celery.html#celery.signature</a>. We’re mocking the signature call to see if it being called and what arguments it is being called with.</p><p>Now when we run the first test using pytest -s -W ignore::DeprecationWarning -k test_save_travel_details_success we see the following output</p><p>Everything seems to be working fine. We would expect the second test to pass as well. When we run the second test, following is the (shortened) output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jAVaUY7ALtC39oBFy2eUbg.png" /></figure><p>Well, that was not expected. When we look closely at the output of the test, we can see that the call to signature method was made but it was not with the parameters that we have expected. To see what arguments were passed to signature method, comment out the signature_mock.assert_called_with line and uncomment print(signature_mock.mock_calls) method and re-run the test. Here’s the output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1DdMa2FmdiNePenl7t4X0Q.png" /></figure><p>Here we can see that the signature method was passed other parameters along with our data such task_id, options, etc.. That is to be expected. But when we look at our data, the timestamp has been changed from the epoch timestamp to ISO string which was passed to subsequent retry calls. So when we’re trying to convert this string to ISO string a second time, it would lead to an error TypeError: an integer is required (got type str)</p><p>This behavior is caused by the way celery schedules tasks. When a celery task is scheduled, the parameters are serialized and saved in the broker. When a worker is available to pickup the task, it will take the parameters from the broker and starts executing. If the task succeeds, the result is written back to the configured backend. But if the task fails due to any exception, we’ll have to call the retry method to retry the task later. We can limit the number of times a task is retries and present number of retry is sent as a context to the retry method. But either way, the parameters will be removed from the broker once the work acknowledges that it has received the task. The retry method checks if the number of configured retries is not exceeded and instead of the parameters it picked up from broker it will schedule another task with the mutated parameters and pushes it to the broker. So, if any mutable parameter is passed to the task and it is changed in the task, the next retry will get the updated parameters instead of the original parameter. This could cause unwanted side effects and might become difficult to debug because of the asynchronous nature of execution.</p><p>To solve the problem, let’s make a small change in the save_travel_details method. Now it should look like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Ic4hIH0kYIiT12bS7ePRQ.png" /></figure><p>Here, instead of directly modifying the passed in array, we’re first making a copy of it and using that to make modifications on timestamp. We can alternatively pass only immutable parameters to the task (best practice but wouldn’t always be possible). Now let’s run the second test again and see the output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sfTo-pjoWalj9QGBpVhdgg.png" /></figure><p>Sure enough, the timestamp was sent as an epoch instead of ISO string to the signature method which shouldn’t cause any issues in the subsequent retry calls.</p><p>To conclude, don’t modify the mutable datatype objects inside celery tasks.</p><p>Luckily, we had the logging and monitoring enabled and configured in our staging servers because of which I was able to at least guess the problem and read about it. I hope this story will help those people who didn’t know something like this could happen. My suggestion, always use logging and monitoring to catch these kind of issues. Though it might take a little extra cost(in terms of money or time) it would save a lot of time and headache later.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cef1ba334e22" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to make a habit stick]]></title>
            <link>https://bharathkotha.medium.com/how-to-make-a-habit-stick-47969c37d5de?source=rss-1b65511afb1d------2</link>
            <guid isPermaLink="false">https://medium.com/p/47969c37d5de</guid>
            <category><![CDATA[habits]]></category>
            <category><![CDATA[habit-building]]></category>
            <category><![CDATA[self-improvement]]></category>
            <dc:creator><![CDATA[Bharath Kotha]]></dc:creator>
            <pubDate>Wed, 14 Oct 2020 03:26:16 GMT</pubDate>
            <atom:updated>2020-10-14T03:26:16.569Z</atom:updated>
            <content:encoded><![CDATA[<p>During this pandemic I wanted to form a few new habits, I guess like everyone else, but I could never continue them for more than a couple of weeks. There was a lot of excitement when starting a new habit but it slowly dies down as the time progresses and I completely forget about it in a month or so. And I’ll remember it a couple of months later and the cycle repeats. Later, I got to thinking and introspecting and tried a new ritual of forming habits. I’m here to share the ritual in the hope that it could be helpful to someone who is in need.</p><p>Before jumping in, let’s take a minute to talk about something called non-negotiables. The non-negotiables are the rules that you set for yourself or the values that you upheld yourself to or anything that matters to you that you can’t compromise on. For example, meditating for 30 minutes a day can be a non-negotiable for some people while watching Netflix for an hour every day might be for some other. Working for 80 hours a week is non-negotiable for Elon Musk. Non-negotiables can define who you’re 10 years down the future. Using non-negotiables was key for me to start forming habits. Without further ado let’s jump right into the steps to forming a habit.</p><ol><li>Decide the habits that you want to make. Choose somewhere between 3–5 habits. I know the urge to make all the habits at once in this fast paced world but having too many goals can overwhelm anyone through the process. Also, recall/review is one of the steps in the process and it would be easier for the human brain to remember 3 things than 10 things. For my last quarter, I chose working out, learning something for an hour at least, and meta-cognition as my goals.</li><li>Set a time window to form a habit. According to a few researches, it takes somewhere around 60–90 days before a habit becomes automatic. Having three goals every quarter (3 months) worked for me really well. At the beginning of every quarter, I set 3 goals for the quarter and review and monitor them throughout the quarter. Having a short period doesn’t really work in making a habit in the long run.</li><li>Review the goals every day. This is where the non-negotiable part comes in. Spend a few minutes every day, non-negotiably, to review what you have done about your goals that day. Keep an alarm at a fixed time and whenever the alarm rings, just review what you have done about your goals. Don’t have mental blocks. Keep your alarm during a time when you won’t be preoccupied with other work, like just after dinner. Reviewing this way will help you track your goals and trick your mind into stick to the habit (by making it feel guilty if needed). In my case, I started writing every day on what I did about my goals/habits in a journal. When I put it into the journal, it’s like someone appreciating me when I have done something about my goals and criticizing me when I didn’t.</li></ol><p>Well, that’s it. Repeat it until you master it and form new goals. Last quarter, I was able to make 2 habits out of my 3 goals this way. For me, that itself is a good achievement. The one goal that I couldn’t convert to habit from my last quarter, I added it as a new goal for the current quarter and hoping it would stick this time. Let me know how forming a habit this way goes for you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47969c37d5de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Distributed data backup and storage]]></title>
            <link>https://bharathkotha.medium.com/distributed-data-backup-and-storage-374f05c1f615?source=rss-1b65511afb1d------2</link>
            <guid isPermaLink="false">https://medium.com/p/374f05c1f615</guid>
            <category><![CDATA[backup]]></category>
            <category><![CDATA[distributed]]></category>
            <category><![CDATA[ideas]]></category>
            <category><![CDATA[privacy]]></category>
            <category><![CDATA[backup-redefined]]></category>
            <dc:creator><![CDATA[Bharath Kotha]]></dc:creator>
            <pubDate>Tue, 18 Aug 2020 17:00:34 GMT</pubDate>
            <atom:updated>2020-08-18T17:00:34.915Z</atom:updated>
            <content:encoded><![CDATA[<p>A few days back I was reading an article on a software tool that can be used to sync files between multiple devices of a user. While reading, I got thinking why should it be the devices of the same user, and why not use a distributed backup system where a single file is not saved in any single device but distributed over a cluster of devices. And surely, when I googled, as is the norm, there are only a few attempts at such distributed file backup systems. None of them seemed to be robust or got a good amount of traction. So I wanted to take a dig at what such a system could possibly accomplish and what would be the complications in building such a system.</p><p>Let me first tell what my concept of a distributed file system is. Everyone must be familiar with file backup solutions like Google Drive, Dropbox, etc. which saves data in cloud or utilities like rsync which can be used to backup data to another disk. All of these tools essentially saves the data to a single hard drive/SSD (which might have their own backups in turn) or group of hard drives/SSDs owned by a single user or organization. But imagine a solution where a single file is split across many hard drives (let’s call the computer to which the hard drive is connected as a node) in the backup system cluster and no single hard drive has the full data of the file contents. This can provide a lot of advantages including privacy, redundancy, speed, etc. for the backups. This is what I’m calling as a distributed file backup system.</p><p>A distributed file backup system could have many advantages</p><ul><li><strong>Privacy</strong>: Since the complete file is not saved anywhere (other than the primary user’s own hard drive), no one will be able to peek into the file contents.</li><li><strong>Redundancy: </strong>Losing one server from the cluster will not lead to a total data lose</li><li><strong>Speed:</strong> If the systems where the data is close to the data owner, then the backup and retrieval will be very fast. Since the data is divided into chunks, multiple simultaneous connections with different nodes in the cluster can also increase the speed.</li><li><strong>Cost:</strong> According to a survey, most of the users don’t use more than 50% of their drive storage. The distributed file backup can use this space and reduce costs in building storage infrastructure.</li></ul><p>The good doesn’t come without its costs. There will be a bunch of challenges to solve before this could take complete form though. Some of the main challenges could be</p><ul><li><strong>Availability of nodes:</strong> Since the user’s computers act as nodes in the cluster, likely, not all nodes are always online and some systems might fail without any notice. This will lead to some interesting problems like when should the algorithms assume that the node hosting a particular chunk of the file is lost and therefore should backup to some other node, how many systems should the chunk be backed up to have good availability of data.</li><li><strong>Availability of data:</strong> Since some of the nodes storing the chunks of a file might be down, the data restoring might not be possible immediately when required.</li><li><strong>Where to store chunks:</strong> One of the biggest challenges would be to find appropriate nodes in the cluster to store the data and find those nodes when retrieving the data. There are many factors to consider here including closeness of the nodes, internet bandwidth of the nodes, fairness of the nodes (A user who is backing up 100 GB of his data should not contribute 1GB of his hard drive space to the cluster)</li><li><strong>Ensuring fairness:</strong> We first have to design what fairness means and then how to ensure/enforce this fairness across all the nodes participating in the cluster. The fairness could be about the storage contribution, uptime, bandwidth, etc.</li><li><strong>Storage space:</strong> To make the data redundant and available, storing the same chunk in multiple nodes might be necessarily increasing the required storage space for backups. This problem can be alleviated somewhat with compression algorithms.</li></ul><p>There could be many use-case scenarios for such a file system</p><ul><li><strong>File backup system:</strong> This was the main theme of the article.</li><li><strong>Organizational file backup:</strong> An organization could provide some servers as the nodes in the cluster and when used with the employees’ computers as nodes as well, some of the challenges above can be solved quite easily. If the provided servers are always up and running, the cluster can be tuned to provide high availability, consistency, and reliability. The cost for the servers will be reduced since backup storage for the servers will be replaced by the employee’s computers.</li><li><strong>Storing user data:</strong> The privacy of user data is a major concern these days. There are dozens of instances of user data leakage every year from some of the large organizations. But if the system is tuned slightly differently so that the primary data itself is not stored in a single disk but distributed across nodes, the likelihood of data getting leaked will reduce. Some of these large organizations can come together to set up some public nodes and all the user data will be distributed among different nodes of different organizations and not a single server will have all the user data.</li></ul><p>There are a lot of possibilities for such a system but designing and implementing such a system will probably be not an easy task. I just wanted to share my idea with the world and see what you think. Leave a comment if you think the idea is cool. It would be exciting to see if the open-source community thinks this is an interesting idea and picks it up as a project someday.</p><p><strong>References:</strong></p><ul><li><a href="https://github.com/Hermes/hermes">https://github.com/Hermes/hermes</a></li><li><a href="https://www.handybackup.net/distributed-backup-system.shtml">https://www.handybackup.net/distributed-backup-system.shtml</a></li><li><a href="https://www.andrew.cmu.edu/course/18-842-nwalia/">https://www.andrew.cmu.edu/course/18-842-nwalia/</a></li><li><a href="https://github.com/domhauton/membraned">https://github.com/domhauton/membraned</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=374f05c1f615" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why I like computers]]></title>
            <link>https://bharathkotha.medium.com/why-i-like-computers-40f07438a4cd?source=rss-1b65511afb1d------2</link>
            <guid isPermaLink="false">https://medium.com/p/40f07438a4cd</guid>
            <dc:creator><![CDATA[Bharath Kotha]]></dc:creator>
            <pubDate>Sun, 26 Jul 2020 18:21:03 GMT</pubDate>
            <atom:updated>2020-07-26T18:21:03.210Z</atom:updated>
            <content:encoded><![CDATA[<p>A few days back I was just browsing something on the internet and suddenly it hit me the complexities that go into the simple activity of browsing which a lot of people will just take for granted these days. I couldn’t help but wonder how it all came to be. I thought I could just take a minute and appreciate the things that are involved.</p><p>When someone opens a browser and type something into the address bar, a lot of programs and hardware developed by numerous people over the decades works in tandem to make it possible. There are all sorts of things involved from keyboard hardware (which in by itself is a small computer), keyboard drivers, data buses, OS, processor hardware, computer memory, monitors, monitor drivers etc.</p><p>As probably many would already know, processor technology is probably the one that has advanced so much in last century. Fun fact: did you know that once computer was used to refer to women who used to do hand computations during the World War era. Even before that people has created mechanical devices which can perform basic mathematical operations in the 18th century itself.</p><p>In the early days of the modern computer, people built computers processors using vacuum tube technology. With the advent of transistors, the entire pace of the development of the computers changed. As Moore’s law suggests, the computer processing power is increase dramatically in the last 7 decades. With advances in manufacturing technology, people crammed more and more transistors into smaller and smaller places increasing the processing power and reducing the power consumed by the processors. There are also developments in cache technology, and various other components which goes into making the computer processors. Today, the latest technology just takes 5nm to print a transistor. Compare that to the room full of vacuum tubes in early 1950s. In the last two decades, people have realized that cramming more transistors into small spaces and increasing the clock speeds is not going to help much for longer (When the size of transistor decreases considerably, they will start exhibiting different properties. When the clock speed increases, a lot of heat gets generated which needs to be dissipated quickly, melting the processors otherwise) and started building multi-core processors. Today’s it’s common to see 6 core and 8 core processors and there are even 32 core CPU. There are also advances in instruction set architectures, floating point arithmetic etc.</p><p>When the computers were in their initial days, people used to manually connect different cables to program the computer. Then there were punched cards and punched tapes to input the data into the computer. Then came keyboards having just 8 keys to enter the octal numbers. In 1950s the first full keyed keyboard came about. Even after that there were a lot of innovations to reduce the cost and make the keyboards mainstream.</p><p>Displays technology has also changed from the initial days of computers. People again used punch cards and punch tapes to interpret the output of the computers. The first computer monitors used cathode ray tubes (CRT) technology to display characters. These displays were only capable of showing only one color on the screen and used to be very bulky. There were a lot of innovations including LCD monitors and LED monitors which reduced the size of the monitors and increased the resolution of displays and the color reproduction. Nowadays its common to see QHD monitors with 144 Hz refresh rates and a hundred other tech specs.</p><p>And there are thousands of developers who wrote millions and billions lines of code. In the initial days people used to directly rewire the computers to perform different mathematical operations (like FPGA). Then there were days when people directly used to write the programs in machine languages (1s and 0s). Can you believe that programmers used to punch holes and feed it into the computer to program it? People invented assembly languages to write code in a slightly human readable way (well, some people can read it quite easily I guess). People began writing first compilers in 1950s using which people can write code in much more readable format (an average human still can’t read it probably 😅). There are incredible advancements in compiler technology and the programming languages and the field is still changing continuously to the growing needs of programmers. But a lot of programming paradigms that we’re seeing today (functional programming, objective programming, meta programming, etc.) existed in the 1960s and 70s itself. Performance, security, and ease of programming are shaping the new programming languages that are being written these days. Operating systems have also advanced from being programs which can run a single other program to programs which can let multiple people login simultaneously, and let multiple programs run simultaneous, on different hardware while providing security and performance.</p><p>And then there comes the internet. Internet is ubiquitous. Though computers were initially invented to do standalone computers, it’s very rare to see computers which does just that these days. Though the first versions of the internet research began in 1960s, it took 3 decades for it become mainstream. The usage of internet surged in 1990s with the invention of world wide web. The whole internet stack itself is so fascinating, making it possible for billions of computers to exchange petabytes and exabytes of data everyday. Imagine living a day without internet (It will probably be peaceful for some people but don’t tell me that there won’t be that urge to check your mobile. Oh year, your mobile is also a computer)</p><p>And there are harddrives (again punch cards -&gt; magnetic tapes -&gt; floppy drives -&gt; magnetic disks -&gt; SSDs), RAM technology (relays and mechanical counters -&gt; CRTs -&gt; magnetic core meory -&gt; semiconductor memory), and bus technology, databases, cloud computing, battery technologies, manufacturing technologies, and many more which made the computers as they are today. It feels great to live in this era which is sitting on decades of such innovations. A lot more innovation is happening at unprecedented scale now more than ever. It might not be a far distant dream to talk to the computers and computers talking back to you. And soooo many innovations coming together in such a nice way to make such a job as browsing the internet an effortless task is what makes me really fascinated about the computers field.</p><p>Hope this article helps someone appreciate the work of countless brilliant minds who made these technologies possible.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40f07438a4cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>