Migrating Your WebRTC Utility from Twilio to AWS: A Developer’s Information


On December fifth, 2023 Twilio introduced the Finish of Life (EOL) of their Programmable Video product. This abrupt providing discontinuation has compelled many purchasers to discover different choices for working good digital camera or video streaming options. On this weblog, we’ll spotlight some issues that prospects can make the most of as steerage to form their migration technique.

Scalability, depth and breadth of capabilities, and safety implementation are essential parameters that can affect the design of your video streaming options and the purposes constructed round it. Designing for long run reliability requires considering how your utility will deal with excessive site visitors volumes and video high quality. These are frequent challenges whereas delivering for vary of units via out there Software program Improvement Kits (SDKs). Due to this fact, when your present know-how requires code adjustments to lift-and-shift to new WebRTC know-how, it ought to embody a purpose-fit code migration technique that addresses the beforehand talked about challenges and supplies complete testing routine to ceaselessly cross-check your migration progress.

Amazon Kinesis Video Streams, a managed cloud service that makes it simple so that you can securely stream video from linked units to AWS for analytics, machine studying (ML), playback, and different processing. It presents a super path so that you can simply help and combine close to real-time video streams from linked cameras and comparable units to be used instances, reminiscent of surveillance, reside streaming, and video evaluation. Furthermore, Amazon Kinesis Video Streams integration with different AWS companies lets you extensively course of and retailer giant volumes of information, making it simple so that you can migrate your present answer with minimal disruption. On this weblog, our instance code will concentrate on serving to you migrate your present Twilio-based streaming answer to AWS with the assistance of Amazon Kinesis Video Streams. However, earlier than we go additional into the particular implementation with Amazon Kinesis Video Streams, it’s essential that you just study all of the out there choices and make an knowledgeable alternative aligned together with your use case and enterprise wants. Due to this fact, please learn Select the best AWS video service to your use case to familiarize your self with all possible choices.

Twilio to Amazon Kinesis Video Streams Implementation

The code examples under present a situation the place chances are you’ll be changing Twilio with Amazon Kinesis Video Streams with WebRTC performance. It demonstrates fundamental WebRTC performance with Twilio and changing it with Amazon Kinesis Video Streams. This code doesn’t dive into many complexities of a real-world utility, reminiscent of full signaling logic, ICE candidate dealing with, and UI interplay. To get extra conversant in the WebRTC protocols and Amazon Kinesis Video Stream signaling, please assessment a number of the reference supplies talked about under.

Conditions

    • An AWS account
    • Kinesis Video Streams service permissions through IAM position or IAM coverage
    • An EC2 occasion or serverless capacity to run NodeJS with Categorical would even be crucial to duplicate the code examples.

Organising a WebRTC Connection With Twilio

The supply code under demonstrates Twilio API use for room creation, token technology and passing the safety token to the shopper to permit connection to the room. Your use and courses might fluctuate relying in your implementation. For the aim of preserving this instance easy, our most important JavaScript class file is the place these features are outlined.

// use dotenv configuration
require("dotenv").config();

// use uuid for guids
const { v4: uuidv4 } = require("uuid");

/*
*  This part is twilio token dealing with, room creation and authn
*  That is later changed with a kvs signaling object to be used
*/

const AccessToken = require("twilio").jwt.AccessToken;
const VideoGrant = AccessToken.VideoGrant;

// ExpressJS is used to serve the applying and deal with HTTP posts, will get, and many others
const specific = require("specific");
const app = specific();
const port = 5000;

// use the Categorical JSON middleware
app.use(specific.json());


// create the twilioClient
const twilioClient = require("twilio")(
  course of.env.TWILIO_API_KEY,
  course of.env.TWILIO_API_SECRET,
  { accountSid: course of.env.TWILIO_ACCOUNT_SID }
);

const findOrCreateRoom = async (roomName) => {
    strive {
      // see if the room exists already. If it does not, this can throw
      // error 20404.
      await twilioClient.video.v1.rooms(roomName).fetch();
    } catch (error) {
      // the room was not discovered, so create it
      if (error.code == 20404) {
        await twilioClient.video.v1.rooms.create({
          uniqueName: roomName,
          kind: "go",
        });
      } else {
        // let different errors bubble up
        throw error;
      }
    }
  };

  const getAccessToken = (roomName) => {
    // create an entry token
    const token = new AccessToken(
      course of.env.TWILIO_ACCOUNT_SID,
      course of.env.TWILIO_API_KEY,
      course of.env.TWILIO_API_SECRET,
      // generate a random distinctive id for this participant
      { id: uuidv4() }
    );
    // create a video grant for this particular room
    const videoGrant = new VideoGrant({
      room: roomName,
    });
  
    // add the video grant
    token.addGrant(videoGrant);
    // serialize the token and return it
    return token.toJwt();
  };

The above operate definitions facilitate acquisition of a brand new Twilio room or becoming a member of one if it already exists. Twilio makes use of JSON Net Tokens (JWT) to grant entry to new or present rooms. The JWT is generated from Twilio credentials then granted to the room. These server-generated tokens are then handed to purchasers to hook up with a room.

Migrating to Amazon Kinesis Video Streams

The JavaScript supply code under demonstrates utilizing the AWS SDK to create an Amazon Kinesis Video Streams signaling channel to be used. Once more, our most important JavaScript class file is the place these features are outlined; nevertheless, chances are you’ll need to create new courses or file nomenclature to create new instantiations of Kinesis Video Stream purchasers. Producer and shopper purposes require legitimate credentials to entry Amazon Kinesis video streams. Although not demonstrated under, this may be achieved with short-term safety credentials in IAM to your producer and shopper utility entry.

//  That is the KVS signaling alternative
   
// Import AWS SDK and crucial parts
const AWS = require('aws-sdk');
const { KinesisVideo, KinesisVideoSignalingChannels } = require('aws-sdk');

// Configure AWS credentials
AWS.config.replace({
  accessKeyId: course of.env.AWS_ACCESS_KEY,
  secretAccessKey: course of.env.AWS_SECRET_KEY,
  area: course of.env.AWS_REGION
});
// Initialize AWS Kinesis Video and Signaling Purchasers
const kinesisVideoClient = new KinesisVideo({ apiVersion: '2019-12-04' });
const signalingClient = new KinesisVideoSignalingChannels({ apiVersion: '2019-12-04' });

async operate createChannel(chnName) {
      strive {
        information = await kinesisVideoClient.createSignalingChannel({ 
           ChannelName: chnName
           })
           .promise();
        console.log('Created signaling channel:', information.ChannelARN);
        //sigchan = information.ChannelARN;
        // Additional code for signaling in WebRTC goes right here
    } catch (error) {
        console.error('Error creating signaling channel:', error);
    }
    return information.ChannelARN;
}

// Perform to connect native media (simplified)
async operate attachLocalMedia(channelARN) {
    strive {
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: true });
      // That is the place you'd sometimes join the stream to a WebRTC peer connection
      console.log('Stream able to be linked to Kinesis Video Stream');
    } catch (error) {
          console.error('Media machine entry error:', error);
    }
}

The aws-sdk supplies the required libraries to your Amazon Kinesis Video Streams migration. It’s helpful and constant past this use case for the aforementioned credential administration for shopper utility entry. The JavaScript above creates a signaling channel. The signaling element manages the WebRTC signaling endpoints that enable purposes to securely join with one another for peer-to-peer reside media streaming.

Server Aspect POST dealing with

The app.put up Categorical routing examples under show a situation the place utility HTTP POST calls may be modified to make the most of the newly created Amazon Kinesis Video Streams signaling channels to your video wants. You will need to notice that further features for ICE signaling will likely be required for peer connectivity.

app.put up("/twexample", async (req, res) => {
  // return 400 if the request has an empty physique or no roomName
  if (!req.physique || !req.physique.roomName) {
    return res.standing(400).ship("Should embody roomName argument.");
  }
  const roomName = req.physique.roomName;
  // discover or create a room with the given roomName
  findOrCreateRoom(roomName);
  // generate an Entry Token for a participant on this room
  const token = getAccessToken(roomName);
  res.ship({
    token: token,
  });
});

/* POST to /twexample URL for a twilio room
   embody JSON within the physique to specify a room title
   {"roomName":"our kvs signaling channel"}
*/

app.put up("/kvsexample", async (req, res) => {
  // Much less complicated than above twilio instance - if no roomName specified within the physique, use random
  if (!req.physique.roomName || req.physique.roomName.size === 0) {
    roomName = uuidv4();  
    console.log(`eval physique not met - utilizing rand ${roomName}`);
  } else {
    roomName = req.physique.roomName
  }

  sigchan = await createChannel(roomName);
 
  console.log(`arn=`, sigchan);
  res.ship({
    ChannelARN: sigchan,
  })
});

Key Modifications within the Migration

      • Use of Async/Await: The instance above makes use of async/await for higher dealing with of asynchronous operations. This may enhance utility efficiency lowering the necessity for complicated operate callback chains.
      • Signaling for WebRTC: The Amazon Kinesis Video Streams instance acknowledges the necessity for extra WebRTC signaling code, which is a posh course of involving creating presents, answering, and dealing with ICE candidates.

Conclusion

Transitioning to Amazon Kinesis Video Streams supplies a strong platform for real-time video processing and analytics, appropriate for eventualities like reside streaming and surveillance. With its user-friendly options, AWS service integration and WebRTC capabilities, you solely pay for what you employ. An alternative choice talked about above on this weblog could possibly be migrating to Amazon Chime SDK, which presents a super answer for real-time communication wants, facilitating video/audio conferencing and collaborative platforms with its user-friendly options and AWS service integration. For additional steerage or inquiries concerning this migration, please attain out to AWS Assist or your AWS Account Staff or submit an IoT Migration Request right here.

Barry McCall

Barry McCall

Barry McCall is a Sr. Technical Account Supervisor with AWS

Recent Articles

Related Stories

Leave A Reply

Please enter your comment!
Please enter your name here

Stay on op - Ge the daily news in your inbox