Red5 Pro HTML5 SDK

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>

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.

Start using the Red5 Pro Server today!

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 Auto Failover section.

WebRTC Publisher

Utilizes WebSockets and WebRTC support in modern browsers.

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

WebRTC Publisher Configuration Properties

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

...
<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>

Flash/RTMP Publisher

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!

Flash/RTMP Publisher Configuration Properties

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
framerate The FPS of data capture of the Camera. More Info) Optional. Default: 15
bandwidth The maximum amount of bandwidth in bytes. More Info Optional. Default: 50*1000
quality The picture quality determined by compression applied to each video frame. Values: 1 - 100. More Info Optional. Default: 80
profile The H264 Profile. More Info Optional. Default: baseline
level The H264 Level. More Info Optional. Default: 3.1

Example

...
<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);
    });

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 Auto Failover section.

WebRTC Subscriber

Utilizes WebSockets and WebRTC support in modern browsers.

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

WebRTC Subscriber Configuration Properties

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

...
<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>

Flash/RTMP Subscriber

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!

Flash/RTMP Subscriber Configuration Properties

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

...
<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)
  });

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 Subscriber

Utilizes the HLS support for videojs.

HLS Configuration Properties

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

...
<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>
...
  // 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)
  });

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

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

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

The following describes the events dispatched from the Shared Object of the Red5 Pro HTML SDK.

Shared Object 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.