Socket
Book a DemoInstallSign in
Socket

@stormstreaming/stormlibrary

Package Overview
Dependencies
Maintainers
1
Versions
117
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@stormstreaming/stormlibrary

A JavaScript library containing core web video player functionality for embedding live-video streams on a website. Part of StormStreaming Suite.

latest
Source
npmnpm
Version
5.0.0-rc.6
Version published
Weekly downloads
124
-18.95%
Maintainers
1
Weekly downloads
 
Created
Source

Storm JavaScript Library

Storm Library is a core web video player for embedding live-video streams on a website. It is a part of Storm Streaming Suite and requires a Storm Streaming Server instance or Cloud subscription to work. This library contains only core network and media functionality and comes with no GUI (user interface), except for a video element. For a full-fledged video player with progress bars, buttons, etc., please check Storm Player, which is a GUI wrapper for this project. It can be used as sample code or as a ready-to-use component for your website.

This library comes in IIFE, ESM, AMD, UMD, and CJS versions (if you're not familiar with these, use IIFE, and it will work fine). TypeScript definitions are also included.

If you wish to test the library, check its API, or view code snippets, please visit our demo page: https://www.stormstreaming.com/demo/index.html

To get started, check our examples and documentation at https://www.stormstreaming.com/docs/v2/javascript-getting-started

Installation

  • Using NPM:

npm install @stormstreaming/stormlibrary

  • Using Yarn:

yarn add @stormstreaming/stormlibrary

  • Manually - if you're unfamiliar with NPM/Yarn or simply want to test it out, just download the /dist/iife/index.js file and embed it on your website.

Sample setup

  • IIFE (Immediately-Invoked Function Expression).
<!doctype html>
<html lang="en">
<head>
    <title>Storm JavaScript Library - IIFE Sample page</title>
    <meta charset="UTF-8"/>
    <script src="dist/iife/index.js"></script>
</head>
<body>
<div id="videoHolder"></div>
<script>
    /**
     * Standard configuration object
     */
    const streamConfig = {
        stream: {
            serverList: [                                // list of streaming servers, 2nd, 3rd etc. will be used as backup
                {
                    host: "localhost",                   // host or IP address of a Storm Streaming server instance
                    application: "live",                 // application name (can be configured in Storm server settings)
                    port: 80,                            // server port, usually 80 (non-ssl) or 443 (ssl)
                    ssl: false                           // whether SSL connection should be used or not
                }
            ],
            streamKey: "test"                             // (optional) initial streamKey to which library subscribes by default
        },
        settings: {
            autoStart: true,                              // if set to true, video will start playing automatically, but will be muted too
            video: {
                containerID: "videoHolder",               // ID of the HTML container for the video element
                aspectRatio: "16:9",                      // <video> element will scale to provided aspect-ratio. This parameter is optional and will overwrite "height" parameter as "width" will only be used for calculations
                width: "100%",                            // <video> element width, can be either "px" or "%" (*string*), as (*number*) will always be "px" value. For % it'll auto-scale to parent container
            },
            debug: {
                console: {                                // console output
                    enabled: true                         // if console output is activated
                }
            }
        }
    };

    /**
     * Creating an instance of the Storm library
     */
    const storm = stormLibrary(streamConfig);

    /**
     * Prior to initialization some event-listeners can be added
     */
    storm.initialize();

</script>
</body>
</html>
  • UMD (Universal Module Definition).
<!doctype html>
<html lang="en">
  <head>
    <title>Storm JavaScript Player - UMD Sample page</title>
    <meta charset="UTF-8" />
    <script src="../dist/umd/index.js"></script>
  </head>
  <body>
    <div id="videoHolder"></div>
    <script>
      /**
       * Basic configuration object
       */
      const streamConfig = {
          stream: {
              serverList: [                                // list of streaming servers, 2nd, 3rd etc. will be used as backup
                  {
                      host: "localhost",                   // host or IP address of a Storm Streaming server instance
                      application: "live",                 // application name (can be configured in Storm server settings)
                      port: 8080,                          // server port, usually 80 (non-ssl) or 443 (ssl)
                      ssl: false                           // whether SSL connection should be used or not
                  }
              ],
              streamKey: "test"                            // (optional) initial streamKey to which library subscribes by default
          },
          settings: {
              autoStart: true,                             // if set to true, video will start playing automatically
              video: {
                  containerID: "videoHolder",              // ID of the HTML container
                  aspectRatio: "16:9",                     // <video> element will scale to provided aspect-ratio. This parameter is optional and will overwrite "height" parameter as "width" will only be used for calculations
                  width: "100%",                           // <video> element width, can be either "px" or "%" (*string*), as (*number*) will always be "px" value. For % it'll auto-scale to parent container
              },
              debug: {
                  console: {                               // console output
                      enabled: true                        // if console output is activated
                  }
              }
          }
      };

      /**
       * Creating an instance of the Storm library
       */
      const storm = stormLibrary.create(streamConfig);

      /**
       * Prior to initialization some event-listeners can be added
       */
      storm.initialize();
      
    </script>
  </body>
</html>
  • ESM (ECMAScript Module).
import { StormLibrary } from "../dist/esm/index.js";

/**
 * Basic configuration object
 */
const streamConfig = {
    stream: {
        serverList: [                                // list of streaming servers, 2nd, 3rd etc. will be used as backup
            {
                host: "localhost",                   // host or IP address of a Storm Streaming server instance
                application: "live",                 // application name (can be configured in Storm server settings)
                port: 8080,                          // server port, usually 80 (non-ssl) or 443 (ssl)
                ssl: false                           // whether SSL connection should be used or not
            }
        ],
        streamKey: "test"                             // (optional) initial streamKey to which library subscribes by default
    },
    settings: {
        autoStart: true,                              // if set to true, video will start playing automatically
        video: {
            containerID: "videoHolder",               // ID of the HTML container
            aspectRatio: "16:9",                      // <video> element will scale to provided aspect-ratio. This parameter is optional and will overwrite "height" parameter as "width" will only be used for calculations
            width: "100%",                            // <video> element width, can be either "px" or "%" (*string*), as (*number*) will always be "px" value. For % it'll auto-scale to parent container
        },
        debug: {
            console: {                                // console output
                enabled: true                         // if console output is activated
            }
        }
    }
};


/**
 * Creating an instance of the Storm library
 */
const storm = new StormLibrary(streamConfig);

/**
 * Prior to initialization some event-listeners can be added
 */
storm.initialize();
  • AMD (Asynchronous Module Definition).
<!doctype html>
<html lang="en">
  <head>
    <title>Storm JavaScript Player - AMD Sample page</title>
    <meta charset="UTF-8" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.min.js"></script>
  </head>
  <body>
    <div id="videoHolder"></div>
    <script>

      /**
       * Full configuration object
       */
      const streamConfig = {
          stream: {                                         // main stream block [required]    
              serverList: [                                         // list of streaming servers, 2nd, 3rd etc. will be used as backup
                  {
                      host: "localhost",                            // host or IP address of a Storm Streaming Server/Cloud instance [required]  
                      application: "live",                          // application name within Storm Streaming Server/Cloud instance [required]  
                      port: 8080,                                   // server port, by default 80 for non-SSL and 443 for ssl connections [optional]
                      ssl: false                                    // whether SSL connection should be used or not
                  }
              ],
              streamKey: "test"                                     // default streamKey library should subscribe to [optional]
          },
          settings: {                                       // main settings block [required]
              autoStart: true,                                      // if set to true, video will start playing automatically, false by default [optional]
              autoConnect: true,                                    // decides if library should establish connection with a server right after initialization, true by default [optional]
              restartOnError:true,                                  // if library encounters any error, if set to true, it'll try to restart [optional]
              reconnectTime: 1,                                     // reconnect time in seconds, 1 by default [optional]
              enabledProtocols: ["storm", "hls"],                   // list of enabled protocols, ["storm", "hls"] by default [optional]
              video: {                                      // video settings block [required]
                  scalingMode:"fill",                               // default scaling for video, fill by default, other options include: "letterbox", "crop", "original" [optional]
                  containerID: "videoHolder",                       // ID of the HTML container for the library (optional) [required]
                  aspectRatio: "16:9",                              // <video> element will scale to provided aspect-ratio. This parameter is optional and will overwrite "height" parameter as "width" will only be used for calculations [optional]
                  width: "100%",                                    // <video> element width, can be either "px" or "%" (*string*), as (*number*) will always be "px" value. For % it'll auto-scale to parent container [optional]
              },
              audio: {                                      // audio settings block [optional]
                  startVolume:100,                                  // The initial volume for the player. Default value 100 [optional]
                  muted: false,                                     // Whenever player should be muted upon startup, false by default [optional]
              },
              buffer: {                                     // buffer settings block [optional]
                  minValue:0.2,                                     // Minimum stream length (in seconds) below which buffering will start. Default value 0.2 second
                  startValue:0.5,                                   // Required stream length (in seconds) for it to start playing. Default value 0.5 second
                  maxValue:2.0,                                     // Maximum stream length (in seconds) above which the video will begin to accelerate to ensure minimal delays compared to the source material. Default value 2.0 seconds.
                  targetValue:0.7,                                  // Buffer length that stormLibrary will try to maintain. Default value 0.7 second
              },
              quality: {                                    // quality settings block [optional]
                  controlMode: "RESOLUTION_AWARE",                  // Selected quality control mode. Other options include "PASSIVE", "HIGHEST_QUALITY", "LOWEST_QUALITY". By default "RESOLUTION_AWARE" [optional]
                  initialUpgradeTimeout: 30,                        // This parameter defines the time interval (in seconds) between successive attempts to change the quality. 30 seconds by default [optional]
                  maxUpgradeTimeout:3600,                           // This parameter defines the maximum time interval (in seconds) allowed between quality change attempts. 3600 by default [optional]
              }
              debug: {                                      // debug settings block
                  console: {                                
                      enabled: false,                                    // Defines tracing options for the player that will be output to the browser’s console. False by default  [optional]
                      logTypes:["ERROR", "INFO", "TRACE", "WARNING", "SUCCESS"], // Decides which log types will be output using this channel. Log types are: ERROR, INFO, TRACE, WARNING, and SUCCESS. [optional]
                      monoColor:false                                   // Single color for all console outputs per specific library instance. False by default [optional]
                  },
                  container {
                      enabled: false,
                      containerID: "log-element",
                      logTypes:["ERROR", "INFO", "TRACE", "WARNING", "SUCCESS"], // Decides which log types will be output using this channel. Log types are: ERROR, INFO, TRACE, WARNING, and SUCCESS. [optional]
                      monoColor:false                                   // Single color for all console outputs per specific library instance. False by default [optional]
                  }
              }
          }
      };

      /**
       * Path to the AMD module
       */
      requirejs(['../dist/amd/index'], function (storm) {

          /**
           * Library instance
           */
           const player = new storm.create(streamConfig);
          
          /**
           * Prior to initialization some event-listeners can be added
           */
          player.initialize();

      });
    </script>
  </body>
</html>

Attaching and detaching events

/**
 * An event can be registered using the addEventListener method (preferably before the initialize() method is called)
 */
storm.addEventListener("playbackStateChange", onLibraryStateChange);

/**
 * Inline functions work well too...
 */
storm.addEventListener("playbackStateChange", function(event){
    console.log("playbackStateChange: "+event.state);
});

/**
 * An event can also be removed...
 */
storm.removeEventListener("playbackStateChange", onLibraryStateChange);

/**
 * All event listeners of a specific type can be removed like this
 */
storm.removeEventListener("playbackStateChange");

Subscribing and unsubscribing to a streamKey (manual method)

/**
 * Subscribing to a streamKey called "test" and initiating playback
 */
storm.subscribe("test", true);

/**
 * Unsubscribing from a streamKey. If you simply want to change the streamKey, just use subscribe again
 */
storm.unsubscribe();

Attaching and detaching library (manual method)

/**
 * Attaching the library to a container by container ID
 */
storm.attachToContainer("containerName");

/**
 * Attaching the library to a container by reference
 */
const myContainer = document.getElementById("containerName")
storm.attachToContainer(myContainer);

/**
 * attachToContainer method returns true/false depending if operation was successfull or not
 */

let isAttachSuccessful = storm.attachToContainer(myContainer);
if(!isAttachSuccessful){
    console.log("Something went wrong - maybe container does not exist?")
}

/**
 * Detaching the library from a container (it will also pause the stream)
 */
storm.detachFromContainer();

Resizing library (manual method)

/**
 * Setting the library width and height to 100% of its parent
 */
storm.setSize("100%", "100%");

/**
 * Setting width and height to 1280x720
 */
storm.setSize("1280px", "720px");

/**
 * Setting just the width to 100%
 */
storm.setWidth("100%");

/**
 * Setting the height to 720px
 */
storm.setHeight("720px");

Library Event List

Event nameAdditional dataDescriptionCan be fired more than once
serverConnectionInitiateserverURL:stringFired when a library instance initiates a connection with a Storm Streaming Server/Cloud instance.yes (once per connection)
serverConnectserverURL:stringTriggered when a library instance successfully establishes a connection with a Storm Streaming Server/Cloud instance.yes (once per connection)
serverDisconnectserverURL:stringCalled when a library instance is disconnected from the Storm Streaming Server/Cloud (after a connection was previously established), which may occur due to viewer networking issues or Storm Streaming Server/Cloud problems.yes (once per connection)
serverConnectionRestartisSilent:booleanFired whenever a library instance needs to restart a connection with a Storm Streaming Server/Cloud instance.yes (once per connection)
serverConnectionErrorserverURL:stringTriggered when a library instance fails to establish a connection with a Storm Streaming Server/Cloud instance, possibly due to networking issues. If there are additional servers on the configuration list and the "restartOnError" parameter is set to true, the library will attempt to connect to a different server instead.yes (once per connection)
allConnectionsFailed-Associated with serverConnectionError. If a library instance is unable to connect to any of the servers provided in the configuration list, this event indicates that no further action can be taken.no
playerReady-Triggered when a library instance is initialized via the initialize() method.no
compatibilityError-Triggered if a browser or device does not support any of the provided sources. Please note that the library will attempt all possible measures (switching between various modes) to ensure maximum compatibility with a given device. However, there may be instances where it is simply impossible to initiate a video.yes
interactionRequired-Certain browsers and devices do not permit a video element to initiate on its own and necessitate direct user interaction, such as a mouse click or a touch gesture. This event signifies that such an engagement is required.no
SSLError-Triggered if an SSL layer is required for specific sources and the browser does not provide it.no
videoElementCreatevideoElement: HTMLVideoElementTriggered whenever a video element within a library instance is either created or recreated.no
authorizationError-Fired when a library instance fails to authorize with a server application on a Storm Streaming Server/Cloud instance (e.g., incorrect token).yes
authorizationComplete-Called when a library instance successfully authorizes with a server application on a Storm Streaming Server/Cloud instance.yes
invalidLicense-Fired whenever a Storm Streaming Server/Cloud license expires.no
streamConfigChangenewConfig: StormStreamConfigNotifies that basic stream configuration has been updated.yes
subscriptionStartstreamKey:stringFired when a subscription request is initiated.yes
subscriptionCompletestreamKey:string, sourceList:Array(ISourceItem)Fired when a subscription request is completed.yes
subscriptionFailedstreamKey:stringNotifies that a subscription request has failed.yes
containerChangecontainer: HTMLElement | null;Fired whenever a library is detached or attached to a new container.yes
resizeUpdatewidth:number, height:numberTriggered when the video size is changed or updated.yes

Playback Event List

Event nameAdditional dataDescriptionCan be fired more than once
playbackRequeststreamKey:stringIndicates that a request for a stream playback has been created.yes (once per video)
playbackInitiate-Fired whenever a playback of a stream is successfully requested from a Storm Streaming Server/Cloud instance.yes (once per video)
playbackStart-Notifies that video playback has started (video is now playing).yes
playbackPause-Notifies that video playback has been paused (due to end-user or system interaction).yes
playbackProgressplaybackStarTime:number, playbackDuration:number, streamStartTime:number, streamDuration:number, dvrCacheSize:numberInforms on video progress, stream/playback start-time, stream/playback duration and nDVR cache size.yes
playbackStateChangestate: PlaybackStateInforms on video playback state change.yes
streamStateChangestate: StreamStateNotifies that stream state has changed (stream state always refers to the original stream on a server).yes
streamStop-Called when the stream is closed on the server side (usually it means that the broadcaster has stopped streaming, or stream was unpublished).yes
streamNotFound-Called whenever a stream with a specific name was not found on the server (this includes hibernated streams or sub-streams).yes (once per video)
streamMetadataUpdatemetadata:StreamMetadataInforms of metadata arrival for current video. MetaData contains information about stream codecs, width, height, bitrate, etc.yes
bufferingStart-Indicates that video content is being readied for playback. The video buffer must fill in order for the video to start.yes
bufferingComplete-Indicates that the buffer is full and playback is about to start.yes
volumeChangevolume:number, muted:boolean, invokedBy: user | browserNotifies that video volume was changed (either its value was changed, or video was muted/un-muted).yes
playbackError-Indicates that there was a problem with the playback (it usually means that the browser was not able to play a source material due to malformed bitcode).yes (once per video)
fullScreenEnter-Fired whenever a library instance enters browser fullscreen mode (either native or overlay type).yes
fullScreenExit-Fired whenever a library instance exits fullscreen mode (either native or overlay type).yes
qualityListUpdatequalityList:ArrayFired whenever a list of available qualities (substreams) is updated.yes
sourceDowngradebandwidthCap:numberFired when the video source is downgraded due to bandwidth limitations.yes

StormLibrary API

MethodReturnsReturn typeDescription
initialize()-voidInitializes the library object. From this point, a connection to the server is established and authentication occurs. It is recommended to add all event listeners before calling this method to ensure they can be properly captured.
isInitialized()true if this library instance was already initializedbooleanReturns true if this library instance has already been initialized.
isConnected()true if this library instance is connected to a serverbooleanReturns true if this library instance is connected to a server.
isAuthorized()true if this library instance is authorized with a serverbooleanReturns true if this library instance is authorized with a server.
getLibraryID()Library ID (first instance starts with 0, next one gets 1, etc.)numberReturns the ID of this library instance. Each subsequent instance has a higher number.
getBranch()Name of a development branchstringReturns the development branch of this library (e.g., main, experimental).
getVersion()Library version in xx.xx.xx formatstringReturns the version of this library instance. The version is returned in the SemVer format (Major.Minor.Patch).
getServerInfo()An object containing server infoServerInfoReturns an object containing server info like its common name, version, and protocol version.
play()-voidInitiates playback of a video stream. If a video was previously paused, you can use this method to resume playback. For this method to work, the library must be subscribed to a stream (check the streamKey field in the config and/or the subscribe method).
pause()-voidPauses current playback. To restart playback, please use the play() method.
stop()-voidStops the current playback and ceases all operations. It also disconnects the library from a server. To restore connection, use the subscribe() method.
togglePlay()-voidWorks as a pause/play switch depending on the current object state.
isPlaying()true if playback is activebooleanReturns true if this library instance is currently playing a stream. To obtain more detailed information about the stream's state, you can use the getPlaybackState() method.
getPlaybackState()Current Playback StatePlaybackStateReturns the current playback state of this library instance.
getStreamState()Current Stream StateStreamStateReturns the current stream state to which the library is subscribed.
seek(time:number)-voidSeeks stream to a given time (stream source timestamp).
mute()-voidMutes the library's video object. It's not the same as setVolume(0), as both methods can be applied together.
unmute()-voidUnmutes the library's video object.
toggleMute()-voidSwitches between mute and unmute methods depending on the current state.
isMute()true if the library is mutedbooleanChecks whether the library is muted.
setVolume(newVolume:number)-voidSets new volume for the library (0-100). Once the method is performed, the volumeChange event will be triggered. If the video was muted prior to the volume change, it will be automatically unmuted.
getVolume()Current volume level 0-100numberReturns library volume (0-100).
setSize(width:number | string, height:number | string)-voidSets a new width and height for the video element. The values can be given as a number (in which case they are treated as the number of pixels), or as a string ending with "px" (this will also be the number of pixels) or "%", where the number is treated as a percentage of the parent container's value.
setWidth(width:number | string)-voidSets a new width for the library. The value can be given as a number (in which case it is treated as the number of pixels), or as a string ending with "px" (this will also be the number of pixels) or "%", where the number is treated as a percentage of the parent container's value.
getWidth()Video object widthnumberReturns current library width in pixels.
setHeight(height:number | string)-voidSets a new height for the library. The value can be given as a number (in which case it is treated as the number of pixels), or as a string ending with "px" (this will also be the number of pixels) or "%", where the number is treated as a percentage of the parent container's value.
getHeight()Video object heightnumberReturns current library height in pixels.
updateToSize()-voidForces the library to recalculate its size based on parent internal dimensions.
setScalingMode(newMode:ScalingType)-voidChanges the library scaling mode. For reference, please check scaling mode in the library config.
getScalingMode()Current scaling modeScalingTypeReturns the current library scaling mode. For reference, please check scaling mode in the library config.
setStreamConfig(config:StormStreamConfig)-voidSets stream config for the library (or overwrites an existing one).
getStreamConfig()Storm Streaming Configuration objectStormStreamingConfigReturns the current config for the library.
makeScreenshot()A promise containing either a blob or nullPromise<Blob | null>Returns a promise that resolves with a screenshot of the video element as a blob, or null if taking the screenshot was not possible.
destroy()-voidDestroys this instance of StormLibrary and disconnects from a server.
addEventListener(eventName:*string*, callback:function, removable:boolean = true)-voidRegisters an event with a library instance. Whenever a registered event occurs, the library will call the provided function.
removeEventListener(eventName:*string*, callback:function)-voidRemoves event listener from the library. If callback is not provided, all events of that type will be removed.
removeAllEventListeners()-voidRemoves all removable event listeners from the library.
getSourceItemList()Array containing available sourcesISourceItem[]Returns an array of all available source items.
removeAllSources()-voidRemoves all SourceItems from a library instance. This method, however, will not stop current playback.
getQualityItemList()Array containing available stream quality optionsArrayReturns an array of all available stream quality items.
subscribe(streamKey:string, andPlay:boolean)-voidRequests a subscription to a given streamKey. When a library is subscribed to a certain streamKey, it will receive notifications regarding its status.
unsubscribe()-voidCancels subscription to a currently selected stream and stops playback.
getSubscriptionKey()Current subscription streamKeystringReturns current (last used) subscription streamKey.
playSourceItem(sourceItem:ISourceItem)-voidStarts a playback of a provided Stream Source Item.
playQualityItem(id:number)true if Source Item related to that quality was foundbooleanChanges the selected video quality to the one corresponding to the specified ID. A list of qualities can be obtained through the getQualityItemList() method.
getCurrentSourceItem()ISourceItem object or nullISourceItem | nullReturns the current source item. If no source was selected yet, null might be returned instead.
addSourceItem(sourceItem:SourceItem, addAndPlay:boolean)-voidAdds a new stream object to the library. It can also start playing it automatically.
attachToContainer(containerID:string | HTMLElement)true if attaching was successfulbooleanAttaches the library to a new parent container using either a container ID (string) or a reference to an HTMLElement. If the instance is already attached, it will be moved to a new parent.
detachFromContainer()true if detaching was successfulbooleanDetaches the library from the current parent element, if possible.
getContainer()Parent HTMLElement or nullHTMLElement | nullReturns the current parent element of the library, or null if none exists.
enterFullScreen()-voidEnters the FullScreen mode.
exitFullScreen()-voidExits the FullScreen mode.
isFullScreenMode()true if the library is in FullScreen modebooleanReturns true if the library instance is in FullScreen mode.
getAbsoluteStreamTime()UnixtimenumberReturns the current playback time.
getVideoElement()Reference to the main Video ElementHTMLVideoElementReturns the Video Element used by this instance of the library.
getQualityControlMode()Current Quality Control ModeQualityControlModeReturns the currently used quality control mode.
setQualityControlMode(mode:QualityControlMode, forceRestart:boolean = true)-voidSets the quality control mode for this player instance. You can force a reload of the mechanism, which may result in an immediate quality change.
getPlaybackRate()Playback SpeednumberReturns current playback ratio (usually between 0.9 and 1.1).
getBandwidthAnalyser()Object containing bandwidth stability statisticsBandwidthAnalyserReturns the Bandwidth Analyser component for the library. This component contains statistical data regarding the stability of the internet connection.
getBandwidthMeter()Object containing bandwidth performance statisticsBandwidthMeterReturns the Bandwidth Meter component for the library. This component contains statistical data related to the performance of the internet connection.
getBufferAnalyser()Object containing buffer state and stabilityBufferAnalyserReturns the Buffer Analyser component for the library. This component contains statistical data regarding the buffer state and its stability.
createBufferGraph(container:string | HTMLElement, interval:number)Graph for video buffer sizeBufferGraphCreates a buffer size graph in the specified location (container ID or reference). The graph is a separate object that must be started using its start() method and stopped using its stop() method. The dimensions of the graph depend on the dimensions of the specified container.
createBandwidthGraph(container:string | HTMLElement, interval:number)Graph for bandwidth speedBandwidthGraphCreates a bandwidth performance graph in the specified location (container ID or reference). The graph is a separate object that must be started using its start() method and stopped using its stop() method. The dimensions of the graph depend on the dimensions of the specified container.
createBufferStabilityGraph(container:string | HTMLElement, interval:number)Graph for buffer stabilityBufferStabilityGraphCreates a buffer stability graph in the specified location (container ID or reference). The graph is a separate object that must be started using its start() method and stopped using its stop() method. The dimensions of the graph depend on the dimensions of the specified container.

Objects & Enums

PlaybackState Enum

ValueDescription
INITIALIZEDComponent has been initialized.
PLAYING Stream is playing.
BUFFERINGStream is buffering.
PAUSEDStream was paused by user or a browser.
STOPPEDStream has been stopped.
UNKNOWNUnknown state.

StreamState Enum

ValueDescription
NOT_INITIALIZED Stream has not been initialized.
INITIALIZED Stream has been initialized.
NOT_FOUNDStream has not been found.
AWAITINGStream exists, but there is no data yet.
NOT_PUBLISHEDStream exists, but hasn't been published.
PUBLISHEDStream exists and it's published (can stream).
UNPUBLISHEDStream exists, but has been unublished.
STOPPEDStream existed, but has been stopped (server-side).
CLOSEDStream existed, but has been removed (server-side).
UNKNOWNStream status is unknown (there is no connection a the server).
ERRORError while retrieving stream status.

ScalingType Enum

ValueDescription
FILLScales content to fill the entire container, may distort aspect ratio.
LETTER_BOXScales content to fit within container while preserving aspect ratio, may add black bars.
CROPScales content to fill container while preserving aspect ratio, may crop edges.
ORIGINALDisplays content at its original size without scaling.

QualityControlMode Enum

ValueDescription
PASSIVELibrary will use previously saved information from RESOLUTIN_AWARE mode, but it'll not react to any resize.
RESOLUTION_AWAREQuality will depend on library screen size and source resolution (closest match).
HIGHEST_QUALITY Library will always pick the highest available quality.
LOWEST_QUALITYLibrary will always pick the lowest available quality.
UNKNOWNQuality mode has not been provided or Quality Control has not been initialized yet.

QualityItem Object

FieldReturn ValueDescription
idnumberReturns the quality item ID, which can later be used to activate this particular quality.
labelstringReturns the quality label, which consists of the vertical resolution and "p", e.g., "1080p".
monogramstringReturns the monogram for this quality based on its resolution, e.g., "LQ", "SD", "HD", "FH", "2K", "4K".
isAutobooleanReturns true if this quality item is of the auto type.

StreamMetadata

FieldReturn ValueDescription
videoWidthnumberWidth of the video frame in pixels.
videoHeightnumberHeight of the video frame in pixels.
videoTimeScalenumberTime unit for video timestamps, typically expressed in Hz.
constantFrameRatebooleanIndicates whether the video stream has a constant frame rate (true) or variable frame rate (false).
videoDataRatenumberBit rate of the video stream expressed in bits per second (bps).
frameRatenumberNumber of frames per second in the video stream.
encoderstringName of the software or hardware encoder used to encode the video stream.
videoCodecstringCodec used for video compression (e.g., H.264, H.265, VP9).
audioCodecstringCodec used for audio compression (e.g., AAC, MP3, Opus).
audioChannelsnumberNumber of audio channels in the stream (e.g., 2 for stereo, 6 for 5.1 surround).
audioSampleRatenumberAudio sampling rate expressed in Hz (e.g., 44100, 48000).
audioSampleSizenumberBit depth of audio samples (e.g., 16, 24, 32).
audioDataRatenumberBit rate of the audio stream expressed in bits per second (bps).

ServerInfo

FieldReturn ValueDescription
namestringCommon name of the server.
groupstringGroup name of the server.
protocolVersionnumberProtocol version used by the server.
serverInitTimenumberServer initialization time as Unix timestamp.
versionnumberVersion of the server protocol.

FAQ & Troubleshooting

1. What is the difference between StormLibrary and StormPlayer?

StormLibrary is the base project that provides server stream connection handling and management. However, it doesn't have a user interface (except for the video object itself). StormPlayer provides the interface and is built on top of StormLibrary.

2. What is the difference between playbackState and streamState events?

The playbackState parameter refers to the video playback state in the library object. If the stream is playing, we get the PLAYING state; if the video is currently buffering, we have the BUFFERING state, etc. The streamState parameter refers to the stream state on the server that the library object is connected to, e.g., NOT_FOUND tells us that such a stream doesn't exist, and AWAITING means we're waiting for it to start.

3. Why does the library sometimes start muted and sometimes with sound from the beginning?

There are two factors to consider separately here. First, the library remembers user settings regarding volume and whether the stream is muted or not. If the user muted the stream, it will be muted immediately upon page refresh. The same applies to the volume value. However, there's also the issue of browser mechanics, where audio playback is not allowed unless the user has interacted with the page (e.g., clicking/touching). When we receive a volumeChange event, we also get information about whether the value change was initiated by the user or the browser, for example:

/**
 * Example event listener for volume change event
 */
storm.addEventListener("volumeChange", function(event){
    if(event.muted == true && event.invokedBy == "browser"){
        // library was muted by a browser
    }

    if(event.muted == true && event.invokedBy == "user"){
        // library was muted by a user
    }
});

4. Why does the video stop when I change the library container?

When we use the detachFromContainer() method, the library stops being part of the document's DOM tree and is automatically stopped by the browser. If we want to move the library object to another container, we can simply use the attachToContainer method. The library object will then be moved to the new location without stopping playback.

5. What is the difference between RESOLUTION_AWARE and PASSIVE quality control modes?

When starting the library with active resolution aware mode, it selects stream parameters based on the video window size. If the library dimensions change, it will try to select the appropriate resolution again. In PASSIVE mode, data regarding window size is ignored, and the last saved settings are used. For example, we can give the library object RESOLUTION_AWARE mode on the transmission page where we have a large player, and PASSIVE when we want to quickly preview on a thumbnail. This way, a stream started on a thumbnail will select its quality as if it were in the target size and can be moved to the player location without restarting playback.

6. What is the allConnectionsFailed event for?

It's possible to define multiple Storm server addresses. If one of them doesn't work, the library will try to connect to the next one on the list. When all defined servers (even if there's only one) are marked as non-functioning, this event will be triggered.

7. If my project is not based on TypeScript, how should I handle ENUMs?

Each enum is essentially a string with a name analogous to its type, so:

/*
 * TypeScript version
 */
setQualityControlMode(QualityControlMode.RESOLUTION_AWARE);

Is the same as:

/*
 * JavaScript version
 */
setQualityControlMode("RESOLUTION_AWARE");

8. Will the library object automatically adjust to the parent container's dimensions?

Yes, as long as the width and/or height parameters are defined as percentage values, e.g., "100%". It's also important that the parent has its size defined, which may depend on parameters like display, float, etc.

/**
 * Example with aspectRatio
 */
video: {
    containerID: "videoHolder",
    aspectRatio: "16:9",
    width: "100%",                          
}

/**
 * Example without aspectRatio
 * Remember that the parent must have defined width and height dimensions 
 * and appropriate display type.
 */
video: {
    containerID: "videoHolder",
    width: "100%",
    height: "100%",                             
}

9. How does the aspectRatio parameter from config relate to width and height parameters?

The aspectRatio parameter forces the library object to adopt dimensions in appropriate proportions. The width parameter serves as the basis for calculation, and the library object's size (height) is calculated based on it. Therefore, the height parameter can be omitted when using aspectRatio.

10. I don't see the library object on my page.

Make sure the player container exists, and also check if, when using dimensions dependent on the parent (percentage values), the parent has defined dimensions. It may be that the container doesn't have height, for example, and the library sets its size to 0px. It's worth enabling debug mode in the configuration to see exactly what's happening in the library object.

Browser compatibility

  • Edge 12+
  • Chrome 31+
  • Firefox 42+
  • Safari 13+
  • Opera 15+

For legacy browsers, HLS mode is used instead.

Resources

License

Keywords

stormstreaming

FAQs

Package last updated on 24 Sep 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts