Cloudinary Blog

Adaptive HLS Streaming Using the HTML5 Video Tag

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?


Delivering Compelling Video Experiences at Scale


Understanding the Shortcomings of the <video> Tag

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.

Introducing the Capabilities of the Cloudinary Video Player

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.

Leveraging the Cloudinary Video Player

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.

Installing the Player

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):

Copy to clipboard
 <!-- 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>
  1. You can also install via npm. On the command line, install the Cloudinary Video Player:

    Copy to clipboard
    # 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:

    Copy to clipboard
    <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>

    OR

    Copy to clipboard
    import cloudinary from 'cloudinary-core';
    import 'cloudinary-video-player';
    
    // CSS
    import '../../node_modules/cloudinary-video-player/dist/cld-video-player.min.css';

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

Posting Videos on aage

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-player attributes, as in this example

    Copy to clipboard
    <video
    id="my-demo-player"
    controls
    autoplay
    class="cld-video-player">
    </video>
  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:

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

    Copy to clipboard
    var demoplayer = cld.videoPlayer('demo-player')
  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:

    Copy to clipboard
    var players = cld.videoPlayers('.cld-video-player',
    {<Insert your configurations here.>}
    )

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.

Creating Playlists

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.

Copy to clipboard
vplayer.playlist([
  'book',
  { publicId: 'oceans',
    transformation: { width: 500, crop: 'pad' } },
  'dog'
], autoAdvance: 10, repeat: true)

The playlistByTag Method

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.

Copy to clipboard
player.playlistByTag("demo"
{ sourceParams: { angle: 10 }, autoAdvance: 0, repeat: true, presentUpcoming: 5 })
.then(function(player)
{
            console.log("Playlist loaded")
 })

The sourcesByTag Method

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.

Copy to clipboard
player.sourcesByTag("demo")
  .then(function(sources) {
    player.playlist(sources)
  })

Formatting Videos With HLS or MPEG-DASH

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:

Copy to clipboard
player.source('oceans', { sourceTypes: ['hls'], transformation: {
 streaming_profile: 'hd' } })

With the data-cld-source-types method:

Copy to clipboard
data-cld-source='{"publicId": "oceans", "transformation": {"streaming_profile": "hd"}}'
data-cld-source-types='["hls"]'

Collecting Analytics

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:

Copy to clipboard
var vplayer = cld.videoPlayer({ ... , analytics: true })

Specifying the events to monitor:

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

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

Copy to clipboard
<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>

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.

Moving On

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.


Want to learn more about HTML5 Video Players?

Recent Blog Posts

Maya Shavin: How I Built My Website

Besides working as a senior front-end developer at Cloudinary, I'm also a content creator, a blogger, and an open-source developer. Follow me at @mayashavin and on mayashavin.com.

In the beginning, my website, mayashavin.com, was mainly for showcasing the status of my development projects and keeping me organized with my speaking schedule. Initially, I built it with Vue.js, later on switching to Nuxt.js (aka Nuxt) for a higher SEO score, and deployed it with Netlify. After some time, I added a blog section with Netlify CMS as the content management system (CMS). Everything was fine until I added more content and features, which led to a significant decline in the site’s performance. Also, the site design needed a modern look. So, I gave the site a makeover.

Read more
Automation Frees Up PetRescue’s Staff to Help Pets Find Their Forever Homes

As we spend more time at home, many of us are adopting pets for the joy, companionship and a surprising range of health benefits. In Australia, where our nonprofit customer PetRescue is located, there’s a shortage of pets to adopt. Last August, the Guardian reported that dog shelters in Australia emptied and adoption fees for puppies were running as high as $AUS1800.

Read more
Cloudinary and Contentful Make Modern Content Management Easier

I am pleased to share that Cloudinary and Contentful have joined forces to further streamline the creation, processing, and delivery of online content through Cloudinary’s digital asset management (DAM) solution and advanced transformation and delivery capabilities for images and video. What’s more, the partnership delivers a headless approach to DAM. By leveraging APIs for media management tasks, marketers and developers alike benefit from an integrated stack of optimized assets for optimization and automation. As a result, page loads are fast and beautiful, and at scale—with less overhead and effort.

Read more
Introducing Cloudinary's Nuxt Module

Since its initial release in October 2016 by the Chopin brothers as a server-side framework that runs on top of Vue.js, Nuxt (aka Nuxt.js) has gained prominence in both intuitiveness and performance. The framework offers numerous built-in features based on a modular architecture, bringing ease and simplicity to web development. Not surprisingly, Nuxt.js has seen remarkable growth in adoption by the developer community along with accolades galore. At this writing, Nuxt has earned over 30K stars on GitHub and 96 active modules with over a million downloads per month. And the upward trend is ongoing.

Read more
How Quality and Quantity can go Hand in Hand

When it comes to quality versus quantity, you’ll often hear people say, “It’s the quality that counts, not the quantity”. While that’s true in many situations, there are also cases where you want both quality and quantity. You may have thousands of images on your website and you want them all to look great. This is especially important if your website allows users to upload their own content, for example, to sell their own products or services. You don't want their poor quality images to reflect badly on your brand.

Read more