Skip to content

Commit

Permalink
JSDK-1510 Adding examples page, using fetch() and using async/await.
Browse files Browse the repository at this point in the history
  • Loading branch information
manjeshbhargav committed Sep 19, 2017
1 parent cf19a0a commit 94792f0
Show file tree
Hide file tree
Showing 7 changed files with 119 additions and 56 deletions.
10 changes: 3 additions & 7 deletions README.md
Expand Up @@ -45,13 +45,9 @@ video in both the tabs!

## Examples

The project contains some common use-case examples for the Twilio Video JS SDK. After running the application
by following the instructions above, click on these links to run the examples.

* [Bandwidth Constraints](http://localhost:3000/bandwidthconstraints)
* [Local Video Filter](http://localhost:3000/localvideofilter)
* [Local Video Snapshot](http://localhost:3000/localvideosnapshot)
* [Media Device Selection](http://localhost:3000/mediadevices)
The project contains some use-case examples for the Twilio Video JS SDK. After running the application
by following the instructions above, go to [http://localhost:3000/examples](http://localhost:3000/examples)
to try them out.

## License

Expand Down
1 change: 0 additions & 1 deletion examples/bandwidthconstraints/public/index.html
@@ -1,5 +1,4 @@
<!DOCTYPE html>
<html>
<html lang="en">
<head>
<meta charset="UTF-8">
Expand Down
77 changes: 40 additions & 37 deletions examples/bandwidthconstraints/src/index.js
Expand Up @@ -77,7 +77,7 @@ function detachTrack(audioElement, videoElement, track) {
/**
* Connect to or disconnect from a Room.
*/
function connectToOrDisconnectFromRoom(e) {
async function connectToOrDisconnectFromRoom(e) {
e.preventDefault();
if (room) {
e.target.value = 'Connect to Room';
Expand All @@ -91,17 +91,15 @@ function connectToOrDisconnectFromRoom(e) {
var maxVideoBitrate = videoBitrateSelector.value
? Number(videoBitrateSelector.value)
: null;
var creds = await getRoomCredentials();

getRoomCredentials().then(function(creds) {
return connectWithBandwidthConstraints(
creds.token,
roomName,
maxAudioBitrate,
maxVideoBitrate);
}).then(function(_room) {
room = _room;
e.target.value = 'Disconnect from Room';
});
room = await connectWithBandwidthConstraints(
creds.token,
roomName,
maxAudioBitrate,
maxVideoBitrate);

e.target.value = 'Disconnect from Room';
}

function setupBitrateGraph(kind, containerId, canvasId) {
Expand All @@ -112,27 +110,24 @@ function setupBitrateGraph(kind, containerId, canvasId) {
return function startBitrateGraph(room, intervalMs) {
var bytesReceived = 0;
var timestamp = Date.now();
var interval = setInterval(function() {
var interval = setInterval(async function() {
if (!room) {
clearInterval(interval);
return;
}
room.getStats().then(function(stats) {
var remoteTrackStats = kind === 'audio'
? stats[0].remoteAudioTrackStats[0]
: stats[0].remoteVideoTrackStats[0]

var _bytesReceived = remoteTrackStats.bytesReceived;
var _timestamp = remoteTrackStats.timestamp;

var bitrate = Math.round((_bytesReceived - bytesReceived) * 8 / (_timestamp - timestamp));
bitrateSeries.addPoint(_timestamp, bitrate);
bitrateGraph.setDataSeries([bitrateSeries]);
bitrateGraph.updateEndDate();

bytesReceived = _bytesReceived;
timestamp = _timestamp;
});
var stats = await room.getStats();
var remoteTrackStats = kind === 'audio'
? stats[0].remoteAudioTrackStats[0]
: stats[0].remoteVideoTrackStats[0]
var _bytesReceived = remoteTrackStats.bytesReceived;
var _timestamp = remoteTrackStats.timestamp;
var bitrate = Math.round((_bytesReceived - bytesReceived) * 8 / (_timestamp - timestamp));

bitrateSeries.addPoint(_timestamp, bitrate);
bitrateGraph.setDataSeries([bitrateSeries]);
bitrateGraph.updateEndDate();
bytesReceived = _bytesReceived;
timestamp = _timestamp;
}, intervalMs);

bitrateGraph.graphDiv_.style.display = '';
Expand All @@ -159,11 +154,12 @@ function updateBandwidthParametersInRoom() {
updateBandwidthConstraints(room, maxAudioBitrate, maxVideoBitrate);
}

// Load the code snippet.
getSnippet('./helpers.js').then(function(snippet) {
(async function() {
// Load the code snippet.
var snippet = await getSnippet('./helpers.js');
var pre = document.querySelector('pre.language-javascript');
pre.innerHTML = Prism.highlight(snippet, Prism.languages.javascript);
}).then(function() {

// Set listeners to the bandwidth selectors.
audioBitrateSelector.onchange = updateBandwidthParametersInRoom;
videoBitrateSelector.onchange = updateBandwidthParametersInRoom;
Expand All @@ -176,13 +172,14 @@ getSnippet('./helpers.js').then(function(snippet) {
startVideoBitrateGraph = setupBitrateGraph('video', 'videobitrategraph', 'videobitratecanvas');

// Get the credentials to connect to the Room.
return getRoomCredentials();
}).then(function(creds) {
var creds = await getRoomCredentials();

// Connect to a random Room with no media. This Participant will
// display the media of the second Participant that will enter
// the Room with bandwidth constraints.
return Video.connect(creds.token, { tracks: [] });
}).then(function(_room) {
var _room = await Video.connect(creds.token, { tracks: [] });

// Disconnect from the Room on page unload.
window.onbeforeunload = function() {
if (room) {
room.disconnect();
Expand All @@ -193,19 +190,25 @@ getSnippet('./helpers.js').then(function(snippet) {

roomName = _room.name;

// Attach the newly added Track to the DOM and start the bitrate graph.
_room.on('trackAdded', attachTrack.bind(
null,
audioPreview,
videoPreview,
startAudioBitrateGraph.bind(null, _room),
startVideoBitrateGraph.bind(null, _room)));

// Detach the removed Track from the DOM and stop the bitrate graph.
_room.on('trackRemoved', detachTrack.bind(
null,
audioPreview,
videoPreview));

// Detach Participant's Tracks and stop the bitrate graphs upon disconnect.
_room.on('participantDisconnected', function(participant) {
participant.tracks.forEach(detachTrack.bind(null, audioPreview, videoPreview));
participant.tracks.forEach(detachTrack.bind(
null,
audioPreview,
videoPreview));
});
});
}());
5 changes: 5 additions & 0 deletions examples/index.css
@@ -0,0 +1,5 @@
a.card {
margin-bottom: 15px;
outline: none;
text-decoration: none;
}
67 changes: 65 additions & 2 deletions examples/index.html
@@ -1,10 +1,73 @@
<!DOCTYPE html>
<html lang="en">
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Twilio Video SDK Examples</title>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Examples</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<link rel="stylesheet" href="index.css">
</head>
<body>

<div class="jumbotron">
<div class="container-fluid">
<h2 class="display-3">Examples</h2>
<p class="lead">These example apps demonstrate special use-cases of the Twilio Video JS SDK.</p>
</div>
</div>
<div class="container-fluid">
<div class="row">
<div class="col-sm-12">
<div class="card-deck">
<a class="card" href="/bandwidthconstraints" style="text-decoration: none">
<h4 class="card-header">
Bandwidth Constraints
</h4>
<div class="card-block">
<p class="card-text">
This app demonstrates the Bandwidth Constraints API, which can be used to control the send-side
bandwidth of the media that is published to the Room.
</p>
</div>
</a>
<a class="card" href="/localvideofilter" style="text-decoration: none">
<h4 class="card-header">
Local Video Filter
</h4>
<div class="card-block">
<p class="card-text">
This app demonstrates a way to apply filters to the LocalVideoTrack. The filtered LocalVideoTrack
can then be used to connect to a Room.
</p>
</div>
</a>
</div>
</div>
<div class="col-sm-12">
<div class="card-deck">
<a class="card" href="/localvideosnapshot" style="text-decoration: none">
<h4 class="card-header">
Local Video Snapshot
</h4>
<div class="card-block">
<p class="card-text">
This app demonstrates a way to capture a snapshot of the LocalVideoTrack using the HTMLCanvasElement.
</p>
</div>
</a>
<a class="card" href="/mediadevices" style="text-decoration: none">
<h4 class="card-header">
Media Device Selection
</h4>
<div class="card-block">
<p class="card-text">
This app demonstrates a way to select the media devices to be used for capturing local media.
</p>
</div>
</a>
</div>
</div>
</div>
</div>
</body>
</html>
11 changes: 2 additions & 9 deletions examples/util/getroomcredentials.js
Expand Up @@ -5,15 +5,8 @@
* @returns {Promise<{identity: string, token: string}>}
*/
function getRoomCredentials() {
return new Promise(function(resolve) {
var xhr = new XMLHttpRequest();
xhr.open('GET', '/token', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
resolve(JSON.parse(xhr.responseText));
}
};
xhr.send(null);
return fetch('/token').then(function(response) {
return response.json();
});
}

Expand Down
4 changes: 4 additions & 0 deletions server/index.js
Expand Up @@ -35,6 +35,10 @@ var app = express();
var quickstartPath = path.join(__dirname, '../quickstart/public');
app.use('/quickstart', express.static(quickstartPath));

// Set up the path for the examples page.
var examplesPath = path.join(__dirname, '../examples');
app.use('/examples', express.static(examplesPath));

/**
* Default to the Quick Start application.
*/
Expand Down

0 comments on commit 94792f0

Please sign in to comment.