Skip to content

Adaptive HLS Streaming Using the HTML5 Video Tag

When the <video> HTML tag was first introduced in 2007, Web Hypertext Application Technology Working Group (WHATWG)(https://whatwg.org/) took interactivity with the Web to a whole new level. No longer do you have to tackle unique plug-ins or insert weird markups before posting videos online. Who still remembers the Flash days?

This is part of a series of articles about Live Streaming Video.

Despite those groundbreaking developments, trusting the <video> tag alone to handle your video tasks remains a subject of intense debate because that tag comes with disadvantages, for example:

  • Longer loading time: Milliseconds could make all the difference with respect to page performance. The plain <video> tag might cause slowdowns that lead to site inaccessibility by older computers.

  • Challenges with SEO optimization: Unless you add extensive informative and useful content that relates to <video>, a page that looks perfect to the human eye can appear downright skeletal to Google’s Web crawler.

  • Potential browser incompatibility: Advancements in browsers over time have led to the potential risk of some viewers accessinga site with a background that shows a glaring error message instead of your video. Even though you can take steps to reduce that risk, such as posting videos in various formats with multiple sources, depending on the user’s browser; or displaying a static image as a last resort, the fact remains that users are denied the intended display.

  • Higher production overhead: Working with the <video> tag only requires that you write large chunks of fallback code so that your video can reach the widest audience. Doing so could easily lead to verbose code that is hard to maintain in the long run.

Over the past decade, several solutions that address the loopholes in the <video> tag have emerged, one of which being the Cloudinary Video Player, a JavaScript-based HTML5 player that you can easily embed into Web pages.

In essence, Cloudinary is the media-management platform for Web and mobile developers. Its Video Player features numerous capabilities, such as the following:

  • Broad device support, which works on a wide range of deviceson both mobile apps and Web browsers.

  • Integrated support of all model player controls, such as:

    • Play/Pause
    • Mute/Unmute
    • Analytics ready
    • Scroll to play
    • Volume control
    • Maximize/Exit
    • Loop and other related features, all customizable.
  • Video transformations, which you can apply to all the videos delivered in that player.

  • Multiple players on the same page. You can configure each player with different or identical options but assign the same sources to the players.

  • Support of popular video formats, such as .mp4, .ogv, .webm, .mov. Feel free to specify multiple formats for your videos; the player automatically selects the best one for the browser in which a video is playing.

  • Full support for adaptive bitrate streaming, that is, HTTP Live Streaming (HLS) and Dynamic Adaptive Streaming Over HTTP (MPEG-DASH), including automatic generation of all required streaming representations and supporting files.

  • A playlist, on which you list all your videos or only those that contain a tag that you specify. Optionally, you can display a Next thumbnail toward the end of each of the videos on the list as a clue of the upcoming video.

  • Analytics, which track the number of viewers and views with the related timestamps. . Also tracked are such events as start, pause, the percentages of the viewing sessions as they relate to the full length of the videos. Subsequently, the Cloudinary Video Player can pass the data to your Google Analytics account or other analytics trackers that you specify.

  • Display of recommended videos at the end of each of the videos.

For details on the capabilities of the Cloudinary Video Player, see the documentation.

Now let’s take a look at how to take advantage of the Cloudinary Video Player’s features on your videos and make your site stand out.

First, install the Cloudinary Video Player, as follows:

As a start, edit the HTML file and list the files that you need for running the player through the unpkg content delivery network (CDN):

 <!-- HTML -->
<link href="https://unpkg.com/cloudinary-video-player/dist/cld-video-player.min.css" rel="stylesheet">
<script src="https://unpkg.com/cloudinary-core/cloudinary-core-shrinkwrap.min.js" type="text/javascript"></script>
<script src="https://unpkg.com/cloudinary-video-player/dist/cld-video-player.min.js"
  type="text/javascript"></script>
Code language: HTML, XML (xml)
  1. You can also install via npm. On the command line, install the Cloudinary Video Player:

    install via terminal
    $ npm install lodash cloudinary-core cloudinary-video-player
    
  2. Add the CSS and JavaScript links to the HTML pages on which you plan to run the Cloudinary Video Player:

    <link href="node_modules/cloudinary-video-player/dist/cld-video-player.min.css" rel="stylesheet">
    <script src="node_modules/lodash/lodash.js" type="text/javascript"></script>
    <script src="node_modules/cloudinary-core/cloudinary-core.js" type="text/javascript"></script>
    <script src="node_modules/cloudinary-video-player/dist/cld-video-player.min.js" type="text/javascript"></script>
    Code language: HTML, XML (xml)

    OR

    import cloudinary from 'cloudinary-core';
    import 'cloudinary-video-player';
    
        // CSS
    import '../../node_modules/cloudinary-video-player/dist/cld-video-player.min.css';
    Code language: JavaScript (javascript)

    Now that the installation is complete. Next, we’ll learn the steps for optimizing videos with Cloudinary for an engaging visual experience.

Posting a video on your page takes only a few simple steps:

  1. In the HTML file, create a video tag with a cld-video-player class and an id value of your choice. In addition, you can add other standard HTML5 video hls player attributes, as in this example

    <video
      id="my-demo-player"
      controls
      autoplay
      class="cld-video-player">
    </video>
    Code language: HTML, XML (xml)
  2. Instantiate a new Cloudinary instance with your cloud name. To acquire a cloud name, one, sign up with Cloudinary for free. Furthermore, set other configuration parameters, as you desire. See this example:

    var cloud = cloudinary.Cloudinary.new({ cloud_name: "my-cloudname", secure: true});
    Code language: PHP (php)
  3. Call Cloudinary’s built in videoPlayer method to initialize your video player. Be sure to specify the id value you defined earlier:

    var demoplayer = cld.videoPlayer('demo-player')
    Code language: JavaScript (javascript)
  4. Optional. To add multiple players with identical configurations to your page, call the videoPlayers method and specify the public IDs for each of the <video> tags, hence saving yourself the chore of defining the tags’ id attributes:

    var players = cld.videoPlayers('.cld-video-player',
    {<Insert your configurations here.>}
    )
    Code language: JavaScript (javascript)

With the videoPlayer method, you can list your preferences, such as which video to play and which transformations to apply. You can also configure other settings either as properties of your <video> tag or as constructor variables of videoPlayer. Since those settings and transformations relate to the Video Player itself, they also apply to all the video sources that are played there.

Now create a playlist on your page with the videoPlayer.playlist method and define the videos’ public IDs. Plus, you can do the following::

  • Configure transformations for each of the videos by means of the public IDs.
  • Generate another playlist for all the videos in your Cloudinary account with a tag that you specify.
  • Control your playlist with the playlist method, for example, navigate to a specific video on the playlist with an index and auto-advance to the next one when a video ends.

The following code creates a playlist with three video IDs:book, ocean, and dog. book plays with a transformation that overrides the default player settings. The next video in the list automatically begins 10 seconds after the previous one has finished playing. When the last video ends, a replay starts from the beginning.

vplayer.playlist([
  'book',
  { publicId: 'oceans',
    transformation: { width: 500, crop: 'pad' } },
  'dog'
], autoAdvance: 10, repeat: true)
Code language: JavaScript (javascript)

With a combination of Cloudinary’s built-in methods and capabilities, you can create a playlist for a specific tag. Calling the playlistByTag method generates such a tag and its options.

The example below does the following:

Create a playlist from all videos with a tag called demo. For every video source demo receives, playlistByTag applies a transformation of a 10-degree angle rotation. lay each video in succession and then reloop to the beginning of the playlist, displaying he pcoming video thumbnail five seconds before the end of each video. Displays a message in the console log at the end of the process.

player.playlistByTag("demo"
{ sourceParams: { angle: 10 }, autoAdvance: 0, repeat: true, presentUpcoming: 5 })
.then(function(player)
{
            console.log("Playlist loaded")
 })
Code language: JavaScript (javascript)

To retrieve the sources for a tag that you specify without actually creating a playlist, call thesourcesByTag method, which shares the same syntax and supports the same options as playlistByTag. Simple and straightforward.

The example below retrieves the source data from all the videos with the tag demo,subsequently passing the sources to the playlist method.

player.sourcesByTag("demo")
  .then(function(sources) {
    player.playlist(sources)
  })
Code language: JavaScript (javascript)

The HTML5 <video> tag by itself along with certain built-in video players do not work with HLS or MPEG-DASH adaptive bitrate-streaming formats. With the Cloudinary Video Player, you can automatically transcode from standard video formats to HLS, MPEG-DASH, or any other similar video format. You can also stream any video in your Cloudinary account to your audience according to the bandwidth and CPU capacity that the Video Player detects in real time.

Be sure to transcode your video to HLS or MPEG-DASH before posting the video.. Transcoding involves a multistep process. For details, see the related Cloudinary documentation.

Also, when uploading a video to your Cloudinary account, specify an eager transformation with the streaming profile your desire and an adaptive streaming format. Doing so ensures that Cloudinary generates all the required files and video representations, ready for delivery on request.

Furthermore, you can specify which video source-file to play with the sourceTypes method or the data-cld-source-types attribute to apply hls or dash in the transformation and add the streaming profile of your preference. Here are two examples:

With the sourceTypes method:

player.source('oceans', { sourceTypes: ['hls'], transformation: {
 streaming_profile: 'hd' } })
Code language: JavaScript (javascript)

With the data-cld-source-types method:

data-cld-source='{"publicId": "oceans", "transformation": {"streaming_profile": "hd"}}'
data-cld-source-types='["hls"]'
Code language: JavaScript (javascript)

With the Cloudinary Video Player, you can collect data on how and when your customers are watching your videos by capturing important events and passing them to your Google Analytics account or other analytics trackers. To use this feature with Google Analytics, do either of the following:

Set the analytics parameter to true, which monitors all available events except timeplayed. Specify the events to monitor and the event subsettings, if any.

Take a look at these examples:

etting the analytics parameter to true:

var vplayer = cld.videoPlayer({ ... , analytics: true })
Code language: JavaScript (javascript)

Specifying the events to monitor:

var vplayer = cld.videoPlayer({ ... , analytics: {
  events: ['play', 'pause', 'ended', { type: 'percentsplayed', percents: [10, 40, 70, 90]   }, 'error']
} })
Code language: JavaScript (javascript)

Afterwards, add the Google Analytics tracking code snippet with the Google tracking ID near the top of the <head> tag on your HTML page:

<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-XXXXX-Y', 'auto');
ga('send', 'pageview');
</script>
Code language: HTML, XML (xml)
Note:

Replace the 'UA-XXXXX-Y' string with the tracking ID of the Google Analytics property you wish to track. To obtain a tracking ID, sign up for Google Analytics.

Bear in mind that, because the Cloudinary Video Player is scaffolded over the VideoJS player core API, you can customize your player with the vplayer.videojs property, which furnishes other robust capabilities, including that of heading off potential issues. For details, see the VideoJS player documentation.

The Cloudinary Video Player offers numerous ways for enhancing videos for posting on the Web. In particular, its hands-on and comprehensive approach for tackling the challenges of optimum video delivery is concrete proof that it’s the right tool to choose.

Related content: Read our guide to vod live stream.


Back to top

Featured Post