HTML5 Streaming SDK API

The Red5 Pro HTML5 SDK allows you to integrate live streaming video into your desktop and mobile browser.

Quickstart

To begin working with the Red5 Pro HTML5 SDK in your project:

Installation

In a browser: download the latest release

<!-- *Recommended WebRTC Shim -->
<script src="http://webrtc.github.io/adapter/adapter-latest.js"></script>
<!-- Red5 Pro SDK -->
<script src="lib/red5pro/red5pro-sdk.min.js"></script>
<!-- video container -->
<div id="video-container">
<video id="red5pro-subscriber" width="600" height="300" controls autoplay>
</video>
</div>
<!-- Create subscriber -->
<script>
(function(red5pro) {

var rtcSubscriber = new red5pro.RTCSubscriber();
var viewer = new red5pro.PlaybackView();
viewer.attachSubscriber(rtcSubscriber);

rtcSubscriber.init({
protocol: 'ws',
host: 'localhost',
port: 8081,
app: 'live',
streamName: 'mystream',
iceServers: [{urls: 'stun:stun2.l.google.com:19302'}]
})
.then(function() {
return rtcSubscriber.play();
})
.then(function() {
console.log('Playing!');
})
.catch(function(err) {
console.log('Something happened. ' + err);
});

}(red5prosdk));
</script>

import { RTCSubscriber, PlaybackView } from 'red5pro-sdk'

const subscriber = new RTCSubscriber()
const view = new PlaybackView()
view.attachSubscriber(subscriber)

subscriber.init({
protocol: 'ws',
host: 'localhost',
port: 8081,
app: 'live',
streamName: 'publisher1',
iceServers: [{urls: 'stun:stun2.l.google.com:19302'}]
})
.then(() => {
subscriber.play()
})
.then(() => {
console.log('Playing!')
})
.catch(err => {
console.log('Something happened. ' + err)
})

Included as post build of red5pro-sdk-example.js on a webpage:

<!doctype html>
<html>
<head>
<!-- * Recommended WebRTC Shim -->
<script src="http://webrtc.github.io/adapter/adapter-latest.js"></script>
</head>
<body>
<div id="video-container">
<video id="red5pro-subscriber" width="600" height="300" controls autoplay>
</video>
</div>
<!-- Red5 Pro SDK -->
<script src="lib/red5pro-sdk-example.js"></script>
</body>
</html>

Requirements

The Red5 Pro HTML SDK is intended to communicate with a Red5 Pro Server, which allows for broadcasting and consuming live streams utilizing WebRTC and various protocols, including RTMP and HLS.

As such, you will need a distribution of the Red5 Pro Server running locally or accessible from the web, such as Amazon Web Services.

Usage

This section describes using the Red5 Pro HTML SDK browser install to create sessions for a Publisher and a Subscriber.

Publisher

The following publisher types / protocols are supported:

Additionally, the Red5 Pro HTML SDK allows for automatic detection and failover to determine the correct publisher option to use based on desired order and browser support. To learn more, visit the Publisher Auto Failover and Order section.

Publisher WebRTC

Utilizes WebSockets and WebRTC support in modern browsers.

It is recommended to include adapter.js when targeting the WebRTC subscriber.

Configuration Properties for Publisher

Property Description Notes
protocol The protocol for the WebSocket communication; ws or wss. Required. If deployed remotely, browsers require communication over secure WebSockets.
host The IP or address that the WebSocket server resides on. Required
port The port on the host that the WebSocket server resides on; 8081 or 8083. Required
app The webapp name that the WebSocket is listening on. Required
streamName The name of the stream to subscribe to. Required
iceServers The list of ICE servers to use in requesting a Peer Connection. Required
streamMode The mode to broadcast; live, record or append. Optional. Default: live
bandwidth A configuration object to setup bandwidth setting in publisher. Optional. Default: {audio: 56, video: 512}.
connectionParams An object of connection parameters to send to the server upon connection request. Optional. Default: undefined

Example for Publisher

...
<body>
<div id="video-container">
<video id="red5pro-publisher"></video>
</div>
</body>
...
<!-- WebRTC Shim -->
<script src="http://webrtc.github.io/adapter/adapter-latest.js"></script>
<!-- Exposes `red5prosdk` on the window global. -->
<script src="lib/red5pro/red5pro-sdk.min.js"></script>
...
<script>
var iceServers = [{urls: 'stun:stun2.l.google.com:19302'}];

// Create a new instance of the WebRTC publisher.
var publisher = new red5prosdk.RTCPublisher();

// Create a view instance based on video element id.
var view = new red5prosdk.PublisherView('red5pro-publisher');

// Access user media.
navigator.getUserMedia({
audio: true,
video: true
}, function(media) {

// Upon access of user media,
// 1. Attach the stream to the publisher.
// 2. Show the stream as preview in view instance.
publisher.attachStream(media);
view.preview(media);

}, function(error) {
console.error(error);
});

view.attachPublisher(publisher);

// Initialize
publisher.init({
protocol: 'ws',
host: '10.0.0.1',
port: 8081,
app: 'live',
streamName: 'mystream',
streamMode: 'live',
iceServers: iceServers
})
.then(function() {
// Invoke the publish action
return publisher.publish();
})
.catch(function(error) {
// A fault occurred while trying to initialize and publish the stream.
console.error(error);
});
</script>

Publisher Flash/RTMP

Embeds a SWF file, utilizing swfobject, to incorporate publishing over RTMP.

The Red5 Pro HTML SDK supports the following SWF integration:

  • A bare-bones RTMP publisher - included in the src directory as red5pro-publisher.swf - and distributed with the live webapp of the Red5 Pro Server install.
  • Note: You will need to provide a URL to the swfobject library which will be dynamically injected at runtime if not - by default - found relative to the page at lib/swfobject.
  • Your own custom Flash client, by specifying the swf property in the init configuration!

Configuration Properties for Publisher Flash/RTMP

Property Description Notes
protocol The protocol of the RTMP streaming endpoint; rtmp or rtmps Required
host The IP or address that the stream resides on. Required
port The port that the stream is accessible on. (e.g., 1935) Required
app The application to locate the stream. Required
streamName The stream name to subscribe to. Required
streamMode The mode to broadcast; live, record or append. Optional. Default: live
connectionParams An object of connection parameters to send to the server upon connection request. Optional. Default: undefined
swf The swf file location to use as the Flash client publisher. Optional. Default: lib/red5pro/red5pro-publisher.swf
width The width of the video element within the SWF movie. Optional. Default: 320
height The height of the video element within the SWF movie. Optional. Default: 240
embedWidth The width of the object element for the SWF movie embed. Optional. Default: 320
embedHeight The height of the object element for the SWF movie embed. Optional. Default: 240
minFlashVersion Minimum semversion of the target Flash Player. Optional. Default: 10.0.0
swfobjectURL Location of the swfobject dependency library that will be dynamically injected. Optional. Default: lib/swfobject/swfobject.js
productInstallURL Location of the playerProductInstall SWF used by swfobject. Optional. Default: lib/swfobject/playerProductInstall.swf

Example for Publisher Flash/RTMP

...
<body>
<div id="video-container">
<video id="red5pro-publisher"></video>
</div>
</body>
...
<!-- WebRTC Shim -->
<script src="http://webrtc.github.io/adapter/adapter-latest.js"></script>
<!-- Exposes `red5prosdk` on the window global. -->
<script src="lib/red5pro/red5pro-sdk.min.js"></script>
...
<script>
  var iceServers = [{urls: 'stun:stun2.l.google.com:19302'}];

  // Create a new instance of the WebRTC publisher.
  var publisher = new red5prosdk.RTMPPublisher();

  // Create a view instance based on video element id.
  var view = new red5prosdk.PublisherView('red5pro-publisher');
  view.attachPublisher(publisher);

  // Initialize
  publisher.init({
    protocol: 'rtmp',
    host: '10.0.0.1',
    port: 1935,
    app: 'live',
    streamName: 'mystream',
    swf: 'lib/red5pro/red5pro-publisher.swf'
  })
  .then(function() {
    // Invoke publish action.
    publisher.publish()
  })
  .catch(function(error) {
    // A fault occurred while trying to initialize and publish the stream.
    console.error(error);
  });
</script>

Publisher Auto Failover and Order

While you can specifically target a publisher - as described in the previous Player Flavors section - you may want to let the library select the optimal publisher based on browser compatibility per support flavors.

As you may have noticed form the previous section, the source configuration for each publisher has differing property requirements. This is due simply to the technologies and broadcast strategies that each use:

  • The WebRTC player utilizes WebSockets, WebRTC and getUserMedia to publish a video and to be displayed in an HTML5 video element.
  • The Flash/RTMP player utilizes a SWF file to broadcast and view streaming video from the Flash Player plugin.

As such, the init configuration provided to the library to allow for auto-failover player selection should be provided with attributes defining the target source(s) - i.e., rtc and/or rtmp:

...
<body>
<div id="video-container">
<video id="red5pro-publisher"></video>
</div>
</body>
...
<!-- WebRTC Shim -->
<script src="http://webrtc.github.io/adapter/adapter-latest.js"></script>
<!-- Exposes `red5prosdk` on the window global. -->
<script src="lib/red5pro/red5pro-sdk.min.js"></script>
...
<script>
  var iceServers = [{urls: 'stun:stun2.l.google.com:19302'}];

  // Create a new instance of the failover publisher.
  var publisher = new red5prosdk.Red5ProPublisher();

  // Create a view instance based on video element id.
  var view = new red5prosdk.PublisherView('red5pro-publisher');
  view.attachPublisher(publisher);

  // Set publish order and initialize
  publisher
    .setPublishOrder(['rtc', 'rtmp'])
    .init({
      "rtmp": {
        // See above documentation for RTMP source option requirements.
      },
      "rtc": {
        // See above documentation for WebRTC source option requirements.
      }
    })
    .then(function(selectedPublisher) {
      // Publisher implementation determined based on order and browser support.

      // If determined publisher implementation is WebRTC,
      //  set up preview and establish stream.
      if (selectedPublisher.getType().toLowerCase() === publisher.publishTypes.RTC) {
        navigator.getUserMedia(
          {
            audio: true,
            video: true
          },
          function (media) {
            selectedPublisher.attachStream(media)
            publisherView.preview(media);
          },
          function (error) {
            console.error(error);
          }
        );
      }
      return selectedPublisher.publish();
    })
    .then(function() {
      // Publishing has initiated successfully.
    })
    .catch(function(error) {
    });
</script>

Publisher Lifecycle Events

Please refer to the Publisher Events documentation regarding the events API.


Subscriber

The following player types / protocols are supported:

Additionally, the Red5 Pro HTML SDK allows for automatic detection and failover to determine the correct playback option to use based on desired order and browser support. To learn more, visit the Subscriber Auto Failover and Order section.

Subscriber WebRTC

Utilizes WebSockets and WebRTC support in modern browsers.

It is recommended to include adapter.js when targeting the WebRTC subscriber.

Configuration Properties for Subscriber

Property Description Notes
protocol The protocol for the WebSocket communication. Required
host The IP or address that the WebSocket server resides on. Required
port The port on the host that the WebSocket server resides on. Required
app The webapp name that the WebSocket is listening on. Required
streamName The name of the stream to subscribe to. Required
subscriptionId A unique string representing the requesting client. Optional. Default generated by library.
iceServers The list of ICE servers to use in requesting a Peer Connection. Required
bandwidth A configuration object to setup playback. Optional
autoplay Flag to autoplay the stream when received upon negotiation. Optional. Default: true
videoEncoding Specifies target video encoder. Optional. Default: Server decides
audio Encoding Specifies target audio encoder. Optional. Default: Server decides
connectionParams An object of connection parameters to send to the server upon connection request. Optional. Default: undefined

Video Encoding Configuration

By not providing the videoEncoding attribute in the WebRTC Subscriber configuration, the server will choose the default encoder to use. If you do not wish for the server to default, you can provide the following values for the property:

  • VP8
  • H264
  • NONE
Audio Encoding Configuration

By not providing the audioEncoding attribute in the WebRTC Subscriber configuration, the server will choose the default encoder to use. If you do not wish for the server to default, you can provide the following values for the property:

  • Opus
  • PCMU
  • PCMA
  • Speex
  • NONE

Example for Subscriber

...
<body>
<div id="video-container">
<video id="red5pro-video"></video>
</div>
</body>
...
<!-- WebRTC Shim -->
<script src="http://webrtc.github.io/adapter/adapter-latest.js"></script>
<!-- Exposes `red5prosdk` on the window global. -->
<script src="lib/red5pro/red5pro-sdk.min.js"></script>
...
<script>
var iceServers = [{urls: 'stun:stun2.l.google.com:19302'}];

// Create a view instance based on video element id.
var viewer = new red5prosdk.PlaybackView('red5pro-video');

// Create a new instance of the WebRTC subcriber.
var subscriber = new red5prosdk.RTCSubscriber();
// Attach the subscriber to the view.
viewer.attachSubscriber(subscriber);

// Initialize
subscriber.init({
    protocol: 'ws',
    host: '10.0.0.1',
    port: 8081,
    app: 'live',
    subscriptionId: 'subscriber-' + Math.floor(Math.random() * 0x10000).toString(16),
    streamName: 'mystream',
    iceServers: iceServers,
    bandwidth: {
      audio: 56,
      video: 512
    }
  })
  .then(function(player) {
    // `player` is the WebRTC Player instance.
    // Invoke the play action.
    player.play();
  })
  .catch(function(error) {
    // A fault occurred while trying to initialize and playback the stream.
    console.error(error)
  });
</script>

Subscriber Flash/RTMP

Embeds a SWF file, utilizing swfobject, to incorporate playback over RTMP.

The Red5 Pro HTML SDK supports the following SWF integration:

  • A customized videojs swf - included in src directory as red5pro-videojs.swf - and utilizing the RTMP playback support from videojs.
  • Note: You will need to also include the videojs script on the page as it is not bundled in the Red5 Pro HTML SDK.
  • A bare-bones RTMP playback viewer - included in the src directory as red5pro-subscriber.swf - and distributed with the live webapp of the Red5 Pro Server install.
  • Note: You will need to provide a URL to the swfobject library which will be dynamically injected at runtime if not - by default - found relative to the page at lib/swfobject.
  • Your own custom Flash client, by specifying the swf property in the init configuration!

Configuration Properties for Publisher Subscriber Flash/RTMP

Property Description Notes
protocol The protocol of the RTMP streaming endpoint. (e.g., rtmp, rtmps) Required
host The IP or address that the stream resides on. Required
port The port that the stream is accessible on. Required
app The application to locate the stream. Required
streamName The stream name to subscribe to. Required
mimeType The mimeType to assign the source added to the video element Optional. Default: rtmp/flv
connectionParams An object of connection parameters to send to the server upon connection request. Optional. Default: undefined
swf The swf file location to use as the Flash client playback. Optional. Default: lib/red5pro/red5pro-video-js.swf
width The width of the video element within the SWF movie. Optional. Default: 320
height The height of the video element within the SWF movie. Optional. Default: 240
embedWidth The width of the object element for the SWF movie embed. Optional. Default: 320
embedHeight The height of the object element for the SWF movie embed. Optional. Default: 240
useVideoJS Flag to utilize the videojs library. Optional. Default: false
minFlashVersion Minimum semversion of the target Flash Player. Optional. Default: 10.0.0
swfobjectURL Location of the swfobject dependency library that will be dynamically injected. Optional. Default: lib/swfobject/swfobject.js
productInstallURL Location of the playerProductInstall SWF used by swfobject. Optional. Default: lib/swfobject/playerProductInstall.swf

Example for Subscriber Flash/RTMP

...
<body>
<div id="video-container">
<video id="red5pro-video" width="600" height="300"
class="video-js vjs-default-skin"
controls autoplay data-setup="{}">
</video>
</div>
</body>
...
<!-- Optional VideoJS support. -->
<link href="lib/videojs/video-js.min.css" rel="stylesheet">
<script src="lib/videojs/video.min.js"></script>
<script src="lib/videojs/videojs-media-sources.min.js"></script>

<!-- Exposes `red5prosdk` on the window global. -->
<script src="lib/red5pro/red5pro-sdk.min.js"></script>
...
<script>
// Create a view instance based on video element id.
var viewer = new red5prosdk.PlaybackView('red5pro-video');

// Create a new instance of the Flash/RTMP subcriber.
var subscriber = new red5prosdk.RTMPSubscriber();
// Attach the subscriber to the view.
viewer.attachSubscriber(subscriber);

// Initialize
subscriber.init({
    protocol: 'rtmp',
    host: '10.0.0.1',
    port: 1935,
    app: 'live',
    streamName: 'mystream',
    mimeType: 'rtmp/flv',
    swf: 'lib/red5pro-video-js.swf'
  })
  .then(function(player) {
    // `player` is the WebRTC Player instance.
    // Invoke the play action.
    player.play();
  })
  .catch(function(error) {
    // A fault occurred while trying to initialize and playback the stream.
    console.error(error)
  });
</script>

The above example defaults to integrating with the videojs library and the custom player build created for the Red5 Pro HTML SDK.

This is the default behavior when the useVideoJS property of the init configuration is set or left as the default value of true.

By setting useVideoJS: false on the init configuration, you can allow the library to load the default red5pro-subscriber.swf, or specify your own custom SWF!

HLS

Utilizes the HLS support for videojs.

Configuration Properties for Publisher HLS

Property Description Notes
protocol The protocol uri that the stream source resides on. Required
host The IP or address uri that the stream source resides on. Required
port The port uri that the stream source resides on. Required
app The webapp name that the stream source resides in. Required
streamName The stream name to subscribe to. Required
mimeType The mime-type of the stream source. Optional. Default: application/x-mpegURL
swf The fallback SWF file to use if HTML5 video element is not supported. Optional. Default: lib/red5pro/red5pro-video-js.swf

Example for HLS

...
<body>
<div id="video-container">
<video id="red5pro-video" width="600" height="300"
class="video-js vjs-default-skin"
controls autoplay data-setup="{}">
</video>
</div>
</body>
...
<!-- Required VideoJS support for HLS playback. -->
<link href="lib/videojs/video-js.min.css" rel="stylesheet">
<script src="lib/videojs/video.min.js"></script>
<script src="lib/videojs/videojs-media-sources.min.js"></script>
<script src="lib/videojs/videojs.hls.min.js"></script>

<!-- Exposes `red5prosdk` on the window global. -->
<script src="lib/red5pro/red5pro-sdk.min.js"></script>
...
<script>
// Create a view instance based on video element id.
var viewer = new red5prosdk.PlaybackView('red5pro-video');

// Create a new instance of the HLS subcriber.
var subscriber = new red5prosdk.HLSSubscriber();
// Attach the subscriber to the view.
viewer.attachSubscriber(subscriber);

// Initialize
subscriber.init({
  protocol: 'http',
  host: '10.0.0.1',
  port: 5080,
  app: 'live',
  streamName: 'mystream',
  mimeType: 'application/x-mpegURL',
  swf: 'lib/red5pro/red5pro-video-js.swf'
  })
  .then(function(player) {
    // `player` is the WebRTC Player instance.
    // Invoke the play action.
    player.play();
  })
  .catch(function(error) {
    // A fault occurred while trying to initialize and playback the stream.
    console.error(error)
  });
</script>

In the above example, the SWF fallback - used when the videojs library determines that HLS support is not sufficient - is the custom videojs client developed for the Red5 Pro HTML SDK.

You can provide your own custom SWF, just as you can for the Flash/RTMP playback, by setting the swf init configuration property.

Subscriber Auto Failover and Order

While you can specifically target a player - as described in the previous Player Flavors section - you may want to let the library select the optimal player based on browser compatibility per support flavors.

As you may have noticed form the previous section, the source configuration for each player has differing property requirements. This is due simply to the technologies and playback strategies that each use:

  • The WebRTC player utilizes WebSockets and WebRTC to subscribe to a video to be displayed in an HTML5 video element.
  • The Flash/RTMP player utilizes a SWF file to playback streaming video in the Flash Player plugin.
  • The HLS player utilizes the HTTP Live Streaming protocol to subscribe to a stream and VideoJS to provide playback with optional fallback of SWF.

As such, the init configuration provided to the library to allow for auto-failover player selection should be provided with attributes defining the target source(s) - i.e., rtc, rtmp and/or hls:

...
<body>
<div id="video-container">
<video id="red5pro-video" width="600" height="300"
class="video-js vjs-default-skin"
controls autoplay data-setup="{}">
</video>
</div>
</body>
...
<!-- WebRTC Shim -->
<script src="http://webrtc.github.io/adapter/adapter-latest.js"></script>

<!-- VideoJS support for HLS playback. -->
<link href="lib/videojs/video-js.min.css" rel="stylesheet">
<script src="lib/videojs/video.min.js"></script>
<script src="lib/videojs/videojs-media-sources.min.js"></script>
<script src="lib/videojs/videojs.hls.min.js"></script>

<!-- Exposes `red5prosdk` on the window global. -->
<script src="lib/red5pro/red5pro-sdk.min.js"></script>
...
<script>
// Create a view instance based on video element id.
var viewer = new red5prosdk.PlaybackView('red5pro-video');

// Create a new instance of the HLS subcriber.
var subscriber = new red5prosdk.Red5ProSubscriber();
// Attach the subscriber to the view.
viewer.attachSubscriber(subscriber);

subscriber
  .setPlaybackOrder(['rtc', 'rtmp', 'hls'])
  .init({
    "rtmp": {
    // See above documentation for RTMP source option requirements.
    },
    "rtc": {
    // See above documentation for WebRTC source option requirements.
    },
    "hls": {
    // See above documentation for HLS source option requirements
    }
  })
  .then(function(player) {
    // `player` has been determined from browser support.
    // Invoke play action
    player.play()
  })
  .then(function() {
    // Playback has initiated successfully.
  })
  .catch(function(error) {
    // A fault occurred in finding failover player and playing stream.
    console.error(error)
  });
</script>

Important things to note:

  • Only rtc, rtmp and hls are supported values for order and are also accessible as enums on Red5ProVidepPlayer.playbackTypes

Subscriber Lifecycle Events


Publisher Events

This section describes the events dispatched from the Publisher of the Red5 Pro HTML SDK.

Listening to Publisher Events

The Publisher(s) included in the SDK are event emitters that have a basic API to subscribing and unsubscribing to events either by name or by wildcard.

To subscribe to all events from a publisher:

function handlePublisherEvent (event) {
// The name of the event:
var type = event.type;
// The dispatching publisher instance:
var publisher = event.publisher;
// Optional data releated to the event (not available on all events):
var data = event.data;
}

var publisher = new red5prosdk.RTCPublisher();
publisher.on('*', handlePublisherEvent);

The * type assignment is considered a "Wildcard" subscription - all events being issued by the publisher instance will invoke the assign event handler.

To unsubscribe to all events from a publisher after assinging an event handler:

publisher.off('*', handlePublisherEvent);

The following sections of this document describe the event types that can also be listened to directly, instead of using the * wildcard.

Publisher Common Events

The following events are common across all Publisher implementations from the Red5 Pro HTML SDK. They can be accessed from the global red5prosdk object from the PublisherEventTypes attribute.

Access Name Meaning
CONNECT_SUCCESS 'Connect.Success' When the publisher has established a required remote connection, such as to a WebSocket or RTMP-based server.
CONNECT_FAILURE 'Connect.Failure' When the publisher has failed to establish a required remote connection for streaming.
PUBLISH_START 'Publish.Start' When the publisher has started a broadcast stream.
PUBLISH_FAIL 'Publish.Fail' When the publisher has failed to start a broadcast stream.
PUBLISH_INVALID_NAME 'Publish.InvalidName' When the publisher is rejected from starting a broadcast stream because the streamName provided is already in use.
UNPUBLISH_SUCCESS 'Unpublish.Success' When the publisher has successfully closed an active broadcast stream.

WebRTC Publisher Events

The following events are specific to the RTCPublisher implementation and accessible on the global red5prosdk object from the RTCPublisherEventTypes attribute. These events are dispatched during the lifecycle of thre trickle ICE functionality required to start a broadcast:

Access Name Meaning
MEDIA_STREAM_AVAILABLE 'WebRTC.MediaStream.Available' When the negotation process has returned a MediaStream object to use.
PEER_CONNECTION_AVAILABLE 'WebRTC.PeerConnection.Available' When the negotation process has produced a valid PeerConnection.
OFFER_START 'WebRTC.Offer.Start' When the publisher requests to send an offer using a SessionDescription on the PeerConnection.
OFFER_END 'WebRTC.Offer.End' When the publisher has received an answer from the SDP offer on the PeerConnection.
ICE_TRICKLE_COMPLETE 'WebRTC.IceTrickle.Complete' When the negotaiton process (a.k.a. trickle) has completed and the publisher will attempt at opening a broadcast stream.

RTMP Publisher Events

The following events are specific to the RTMPPublisher implementation and accessible on the global red5prosk object from the RTMPPublisherTypes attribute:

Access Name Meaning
EMBED_SUCCESS 'FlashPlayer.Embed.Success' When the publisher-based SWF is successfully embedded in the page.
EMBED_FAILURE 'FlashPlayer.Embed.Failure' When the publisher-based SWF fails to be embedded properly in the page.

Subscriber Events

This section describes the events dispatched from the Subscriber of the Red5 Pro HTML SDK.

Listening to Subscriber Events

The Subscriber(s) included in the SDK are event emitters that have a basic API to subscribing and unsubscribing to events either by name or by wildcard.

To subscribe to all events from a subscriber:

function handleSubscriberEvent (event) {
// The name of the event:
var type = event.type;
// The dispatching publisher instance:
var subscriber = event.subscriber;
// Optional data releated to the event (not available on all events):
var data = event.data;
}

var subscriber = new red5prosdk.RTCSubscriber();
subscriber.on('*', handleSubscriberEvent);

The * type assignment is considered a "Wildcard" subscription - all events being issued by the subscriber instance will invoke the assign event handler.

To unsubscribe to all events from a subscriber after assinging an event handler:

subscriber.off('*', handleSubscriberEvent);

The following sections of this document describe the event types that can also be listened to directly, instead of using the * wildcard.

Subscriber Common Events

The following events are common across all Subscriber implementations from the Red5 Pro HTML SDK. They can be accessed from the global red5prosdk object from the SubscriberEventTypes attribute.

Access Name Meaning
CONNECT_SUCCESS 'Connect.Success' When the subscriber has established a required remote connection, such as to a WebSocket or RTMP-based server.
CONNECT_FAILURE 'Connect.Failure' When the subscriber has failed to establish a required remote connection for consuming a stream.
SUBSCRIBE_START 'Subscribe.Start' When the subscriber has started a subscribing to a stream.
SUBSCRIBE_FAIL 'Subscribe.Fail' When the subscriber has failed to start subscribing to a stream.
SUBSCRIBE_INVALID_NAME 'Subscribe.InvalidName' When the subscriber is cannot start subscribing to stream because a stream associated with the streamName is not available.
SUBSCRIBE_STOP 'Subscribe.Stop' When the subscriber has successfully closed an active subscription to a stream.
SUBSCRIBE_METADATA 'Subscribe.Metadata' When metadata is received on the client from the server.

WebRTC Subscriber Events

The following events are specific to the RTCSubscriber implementation and accessible on the global red5prosdk object from the RTCSubscriberEventTypes attribute. These events are dispatched during the lifecycle of thre trickle ICE functionality required to start subscribing to a stream:

Access Name Meaning
PEER_CONNECTION_AVAILABLE 'WebRTC.PeerConnection.Available' When the negotation process has produced a valid PeerConnection.
OFFER_START 'WebRTC.Offer.Start' When the subscriber requests to start an offer on the PeerConnection.
OFFER_END 'WebRTC.Offer.End' When the subscriber has received a SessionDescription from a requested offer over the PeerConnection.
ANSWER_START 'WebRTC.Answer.Start' When the subscriber requests to send an answer on the PeerConnection.
ANSWER_END 'WebRTC.Answer.End' When the subscriber has received an answer (in form of a MediaStream) over the PeerConnection.
CANDIDATE_START 'WebRTC.Candidate.Start' When the subscriber requests to send a candidate on the PeerConnection.
CANDIDATE_END 'WebRTC.Candidate.End' When the subscriber has received a candidate over the PeerConnection.
ICE_TRICKLE_COMPLETE 'WebRTC.IceTrickle.Complete' When the negotaiton process (a.k.a. trickle) has completed and the subscriber will attempt at consuming a stream.

RTMP Subscriber Events

The following events are specific to the RTMPSubscriber implementation and accessible on the global red5prosk object from the RTMPSubscriberEventTypes attribute:

Access Name Meaning
EMBED_SUCCESS 'FlashPlayer.Embed.Success' When the subscriber-based SWF is successfully embedded in the page.
EMBED_FAILURE 'FlashPlayer.Embed.Failure' When the subscriber-based SWF fails to be embedded properly in the page.

HLS Subscriber Events

There are currently no HLS-specific events. Please refer to the common events.

Shared Object

Use of Shared objects requires an active stream - either publishing or subscribing. The content of the stream isn't important to the shared object itself, even a muted audio-only stream will be enough. Also, which stream you are connected to isn't important to which shared object you access, meaning that clients across multiple streams can use the same object, or there could be multiple overlapping objects in the same stream.

Shared Object Usage

Creating a Shared Object with Publisher stream

(function (nav, red5pro) {
  var so;
  var gUM = {video: true, audio: true};
  var publisher = new red5pro.Red5ProPublisher();
  publisher.init(configuration)
    // Resolve to proper publisher implementation as you normally would.
    .then( function(publisherImpl) {
      return new Promise( function(resolve, reject) {
        var implType = publisherImpl.getType().toUpperCase();
        if (implType === publisher.publishTypes.RTC.toUpperCase()) {
          nav.getUserMedia(gUM, function (media) {
            publisherImpl.attachStream(media);
            resolve(publisherImpl);
          }, function (error) {
            reject(error);
          });
        }
        else {
          resolve(publisherImpl);
        }
      });
    })
    // Request to publish.
    .then( function(publisherImpl) {
      return publisherImpl.publish()
    })
    // Instantiate Shared Object with publisher instance.
    .then( function(publisherImpl) {
      so = new red5pro.Red5ProSharedObject('sharedObjectTest', publisherImpl);
      so.on('*', handleSharedObjectEvents);
    })
    .catch( function(error) {
      // handle possible error in instantiation od publisher implementation.
    });
})(navigator.mediaDevice || navigator, window.red5prosdk);

Creating a Shared Object with Subscriber Stream

(function (red5pro) {
  var so;
  var subscriber = new red5pro.Red5ProSubscriber();
  subscriber.init(configuration)
    .then( function(subscriberImpl) {
      return subscriberImpl.play();
    })
    .then( function(subscriberImpl) {
      so = new red5pro.Red5ProSharedObject('sharedObjectTest', subscriberImpl);
      so.on('*', handleSharedObjectEvents);
    })
    .catch( function(error) {
      // handle possible error in instantiation od subscriber implementation.
    });
})(window.red5prosdk);

Closing a Shared Object

Closing a remote Shared Object instance is as easy as invoking close.

so.off('*', handleSharedObjectEvents);
so.close();

The event delegate is also removed using the off method, since SharedObject is an instance of EventEmitter.

Shared Object Property Updates

Remote Shared Objects use JSON for transmission, meaning that its structure is primarily up to your discretion. The base object will always be a dictionary with string keys, while values can be strings, numbers, booleans, arrays, or other dictionaries - with the same restriction on sub-objects.

This example simply uses a number to keep a count of how many people are connected to the object. As seen in the PROPERTY_UPDATE handler, value can be accessed from the object by name, and set using setProperty:

so.on(red5pro.SharedObjectEventTypes.PROPERTY_UPDATE, function (event) {
  if (event.data.hasOwnProperty('count')) {
    appendMessage('User count is: ' + event.data.count + '.');
    if (!hasRegistered) {
      hasRegistered = true;
      so.setProperty('count', parseInt(event.data.count) + 1);
    }
  }
  else if (!hasRegistered) {
    hasRegistered = true;
    so.setProperty('count', 1);
  }
});

Shared Object Method Updates

The Shared Object interface also allows sending messages to other people watching the object. By sending a Object through the send method, that object will be passed to all the listening clients that implement the specified call.

function sendMessageOnSharedObject (message) {
  so.send('messageTransmit', {
    user: configuration.stream1,
    message: message
  });
}

Like with the parameters of the object, as long as the Object sent parses into JSON, the structure of the object is up to you, and it will reach the other clients in whole as it was sent.

In this example, we are marking the message object as type messageTransmit with data related ot the user sending the message and a message String.

In the event handler for messages, this example then invokes that method name of messageTransmit on the callback client:

// Invoked from METHOD_UPDATE event on Shared Object instance.
function messageTransmit (message) { // eslint-disable-line no-unused-vars
  soField.value = ['User "' + message.user + '": ' + message.message, soField.value].join('\n');
}
...
so.on(red5pro.SharedObjectEventTypes.METHOD_UPDATE, function (event) {
  soCallback[event.data.methodName].call(null, event.data.message);
});

Shared Object Events

This section describes the events dispatched from the Shared Object of the Red5 Pro HTML SDK.

Creation

A connected Publisher or Subscriber instance is required to create a new SharedObject instance. You will not have to worry about the failover type of these connections (either WebRTC or Flash) as the SDK accounts for how to handle the messaging through a common API.

Listening to SharedObject Events

The SharedObject included in the SDK is an event emitter that has a basic API to subscribing and unsubscribing to events either by name or by wildcard.

To subscribe to all events from a shared object:

function handleSharedObjectEvent (event) {
// The name of the event:
var type = event.type;
// The name associated with the shared object instance:
var name = event.name;
// Optional data releated to the event (not available on all events):
var data = event.data;
}

var so = new red5prosdk.Red5ProSharedObject();
so.on('*', handleSharedObjectEvent);

The * type assignment is considered a "Wildcard" subscription - all events being issued by the shared object instance will invoke the assign event handler.

To unsubscribe to all events from a shared object after assinging an event handler:

so.off('*', handleSharedObjectEvent);

The following sections of this document describe the event types that can also be listened to directly, instead of using the * wildcard.

Shared Object Common Events

The following events are common across all SharedObject implementations from the Red5 Pro HTML SDK. They can be accessed from the global red5prosdk object from the SharedObjectEventTypes attribute.

Access Name Meaning
CONNECT_SUCCESS 'Connect.Success' When the shared object has established a required remote connection.
CONNECT_FAILURE 'Connect.Failure' When the shared object has failed to establish a required remote connection.
PROPERTY_UPDATE 'SharedObject.PropertyUpdate' When an update to a property held on the shared object has been updated.
METHOD_UPDATE 'SharedObject.MethodUpdate' When a client has invoked a message to be received on connected clients.