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?

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 Page

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

    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 hls Players?

Recent Blog Posts

Our $2B Valuation

By
Blackstone Growth Invests in Cloudinary

When we started our journey in 2012, we were looking to improve our lives as developers by making it easier for us to handle the arduous tasks of handling images and videos in our code. That initial line of developer code has evolved into a full suite of media experience solutions driven by a mission that gradually revealed itself over the course of the past 10 years: help companies unleash the full potential of their media to create the most engaging visual experiences.

Read more
Direct-to-Consumer E-Commerce Requires Compelling Visual Experiences

When brands like you adopt a direct–to-consumer (DTC) e-commerce approach with no involvement of retailers or marketplaces, you gain direct and timely insight into evolving shopping behaviors. Accordingly, you can accommodate shoppers’ preferences by continually adjusting your product offering and interspersing the shopping journey with moments of excitement and intrigue. Opportunities abound for you to cultivate engaging customer relationships.

Read more
Automatically Translating Videos for an International Audience

No matter your business focus—public service, B2B integration, recruitment—multimedia, in particular video, is remarkably effective in communicating with the audience. Before, making video accessible to diverse viewers involved tasks galore, such as eliciting the service of production studios to manually dub, transcribe, and add subtitles. Those operations were costly and slow, especially for globally destined content.

Read more
Cloudinary Helps Minted Manage Its Image-Generation Pipeline at Scale

Shoppers return time and again to Minted’s global online community of independent artists and designers because they know they can count on unique, statement-making products of the highest quality there. Concurrently, the visual imagery on Minted.com must do justice to the designs into which the creators have poured their hearts and souls. For Minted’s VP of Engineering David Lien, “Because we are a premium brand, we need to ensure that every single one of our product images matches the selected configuration exactly. For example, if you pick an 18x24 art print on blue canvas, we will show that exact combination on the hero images in the PDF.”

Read more
Highlights on ImageCon 2021 and a Preview of ImageCon 2022

New year, same trend! Visual media will continue to play a monumental role in driving online conversions. To keep up with visual-experience trends and best practices, Cloudinary holds an annual conference called ImageCon, a one-of-a-kind event that helps attendees create the most engaging visual experiences possible.

Read more