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?


Sign up for Cloudinary free today!


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

Top Five Web-Video Formats of 2021

By William Imoh
The Five Most Popular Web-Video Formats and Streaming Protocols

Over the past 15 years, the video industry has undergone a significant change in video formats on the web. In particular, in the early 2010s, the 3GP format, which the 3rd Generation Partnership Project (3GPP) created for 3G-enabled mobile devices, went nearly extinct. The advancement of mobile devices and cellular networks has brought about the need for pioneers to build better formats for a faster user experience.

Read more
Cloudinary Introduces Integration With SAP Commerce Cloud

We’re excited to announce Cloudinary’s integration with SAP Commerce Cloud, through which the latter’s customers can significantly boost the visual media experience on their website or app.

SAP Commerce Cloud powers some of the largest e-commerce sites (B2C, B2B, and B2B2C businesses), complete with building blocks like storefront design and order management. Reinforced with Cloudinary’s laser-sharp focus on optimizing, managing, and delivering images and videos, the new extension will enable SAP Commerce Cloud customers to create unique and engaging visual experiences effortlessly.

Read more
Personalizing Video Email for Marketing Campaigns With Cloudinary

As critical as it is to engage with shoppers in order to succeed in e-commerce, old-style, boring emails are far from being effective. In fact, they tend to be annoying because no one likes to read formulaic, generic messages that are sent en masse. For better results, rethink your email marketing campaigns and try out creative strategies.

Read more
Muted Videos and Subtitles

The bane of our existence is the lack of efficient ways for tackling the plethora of recurring tasks in our lives. One of those tasks is surfing the internet. We consume a lot of web content daily, of which a large percentage are images and videos. We’re constantly quickly scrolling through 30-second videos or checking out pictures of cute items we’d like to buy in our free time.

Read more

Building a Roommate-Matching App With Cloudinary and Jamstack

By Marcelo Ricardo de Oliveira
Building a Roommate-Matching App With Cloudinary and Jamstack

Roommate matching can be a pain—especially during the COVID pandemic when people don't want to meet in person. Matching apps like Flatmates, Roomster, and roommates.com are helpful, and if you're in the roommate-matching space, you know that great video is essential for those seeking roommates. Fortunately, Cloudinary can help.

Read more