Cloudinary Blog

How to Implement Smooth Video Buffering for a Better Viewing Experience

Delivering an optimal smooth viewing experience

This article was originally posted on Scotch.io

In the early days of the web, the only thing that mattered was getting that content out to users no matter how long it took or what resources it consumed. As a matter of fact, users seemed to understand and were ready to wait till whenever there browser's loading spinner stops and the contents displayed.

Today, though, users’ patience has run out. They are no longer willing to wait because they know we – the engineers – can afford to give them a better experience.

While web content comes in different forms, today we will focus on video. Video optimization and delivery of a good viewing experience to users doesn’t come easy. Yes, flash is gone and HTML5 is here to stay; but don’t expect that you can just drop the video tag in your HTML and you’re done.

Let’s take a look at a common approach to delivering videos, popularly known as buffering.

What Video Buffering Is and Why Use It

Most videos on the web do something that looks like a pre-fetch. You may notice the progress bar showing another indicator that is greater than or equal to the current play time. This is what Youtube's streaming looks like:

The light gray portion of the progress bar indicates the buffered content.

YouTube dynamically adjusts the quality of that portion depending on the bandwidth and CPU capacity it detects. For example, if the bandwidth is poor, YouTube will pre-fetch the low-quality version of the above video. On the other hand, if the bandwidth is great, it would pre-fetch the high-quality version for rendering.

Put this together and users have a great experience whether or not their connectivity is superb or poor.

The key thing to keep in mind is not the fact that the video is pre-fetched, but rather that the pre-fetching is achieved with an intelligent strategy.

We also use this strategy at Scotch School to deliver video training courses:

Now that we have a basic understanding of what buffering is, let’s see how we can employ an intelligent strategy that entails buffering based on the bandwidth or CPU capacity conditions.

Meet Cloudinary's Adaptive Bitrate Streaming (HLS & MPEG)

Cloudinary offers a game-changing concept known as adaptive bitrate streaming (ABS), which is a video delivery technique that adjusts the quality of a video stream in real time according to detected bandwidth and CPU capacity. This approach enables videos to start quicker, with fewer buffering interruptions and at the best possible quality for the current device and network connection, to maximize user experience.

Videos provisioned using ABS are provided in versions known as representations, each with different quality and bitrates. Each video file must be accompanied by an index file that specifies predefined segments of the video. Additionally, there is a master playlist that points to the available representations with additional information about each one.

You can use this Cloudinary feature to deliver a better viewing experience for your users at no cost.

To deliver videos using adaptive streaming, Cloudinary generates multiple copies of your video prepared at different resolutions, qualities and data rates. The copies of the videos are then automatically generated and delivered from a single original video, transcoded to either or both of the following protocols:

  • HTTP Live Streaming (HLS)
  • Dynamic Adaptive Streaming over HTTP (MPEG-DASH)

Now that we’ve explained the concept, let’s write some code to put the pieces of these puzzles together.

Uploading Videos to Cloudinary

Cloudinary comes fully loaded with interesting features to make managing your media files an awesome experience. These features range from being a CDN for your media files (which means you can upload and store files to Cloudinary server) to manipulating your media files (as we discussed above).

Let’s take a look at how we can upload images from our Node servers to Cloudinary. Cloudinary offers a Node SDK that facilitates image uploads so you do not have to memorize the API URLs for doing this.

SDKs for PHP, Python, Ruby and .Net are also available with the same API methods.

Install the SDK by running:

Copy to clipboard
$ npm install cloudinary --save

Import cloudinary to your code base:

Copy to clipboard
var cloudinary = require('cloudinary');

Configure the SDK with your credentials (you can get one here):

Copy to clipboard
cloudinary.config({ 
  cloud_name: '[CLOUD_NAME]', 
  api_key: '[API_KEY]', 
  api_secret: '[API_SECRET]' 
});

... then use the following few lines to upload to Cloudinary:

Copy to clipboard
cloudinary.uploader.upload('dog.mp4', function(result) {
  // Upload handler
  console.log('result: ', result);
}, {
  public_id: 'my_dog',
  resource_type: 'video'
});

We can request the video from Cloudinary using the public URL we specified:

Copy to clipboard
cloudinary.video('my_dog');

The output of the above will be:

Copy to clipboard
<video poster='https://res.cloudinary.com/scotch.io/video/upload/my_dog.jpg'>
    <source src='https://res.cloudinary.com/scotch.io/video/upload/my_dog.webm' type='video/webm'>
    <source src='https://res.cloudinary.com/scotch.io/video/upload/my_dog.mp4' type='video/mp4'>
    <source src='https://res.cloudinary.com/scotch.io/video/upload/my_dog.ogv' type='video/ogg'>
</video>

This is mind blowing! Cloudinary generates the HTML for the various formats suitable for any given browser so we do not have to worry about that. Awesome, right?

Transformation with Streaming Profiles and Formats

Cloudinary uses transformations to manipulate media files. Such manipulations include:

Transformations are provided as configuration options and applied either once during upload (eager) or each time a user needs the media to be delivered (per request).

Cloudinary also provides a collection of predefined streaming profiles, where each profile defines a set of representations according to suggested best practices.

For example, the 4K profile creates eight different representations in 16:9 aspect ratio, from extremely high quality to audio only. Alternatively, the SD profile creates only three representations, all in 4:3 aspect ratio. Other commonly used profiles include the HD and Full HD profiles.

We are going to apply the streaming profile as an eager transformation to our upload logic:

Copy to clipboard
cloudinary.uploader.upload('dog.mp4', 
        function(result) {console.log(result); }, 
        { resource_type: "video", 
        eager: [
            { streaming_profile: "full_hd", format: "m3u8" }],                                   
        eager_async: true,
        eager_notification_url: "http://scotch.io/upload_completed",
        public_id: "my_dog"});
  • We initiate a usual upload process with the SDK specifying the URL of the image we want to send to our Cloudinary server
  • An eager transformation is initiated. This transformation is an array that takes a streaming profile configuration. The dog.mp4 video is encoded into HLS format using a Full HD streaming profile.
  • This process could take a while so we ensure that the eager transformation is asynchronous by setting eager_async to true

Embedding Videos

You can deliver/embed your eagerly transformed videos using the .m3u8 (HLS) or .mpd (MPEG-DASH) file format (extension) and include the streaming_profile. You can as well provide other non-adaptive streaming-related transformation options.

For example:

Copy to clipboard
cloudinary.video("my_dog.m3u8", {streaming_profile: "hd"});

Final Note

Personally, I have avoided the responsibility of implementing such a responsive video feature in a website because of being held responsible for customer frustrations. Cloudinary made this so simple, and using the solutions was free for the amount of resources I needed.

Using the adaptive streaming strategy is a proven technique that enables you to deliver an optimal, smooth viewing experience. This feature is just a small part of what Cloudinary offers for video and image management. To learn more, look the documentation or get started here.

Christian Nwamba Christian Nwamba is a code beast, with a passion for instructing computers and understanding it's language. In his next life, Chris hopes to remain a computer programmer.

Recent Blog Posts

Generate Waveform Images from Audio with Cloudinary

This is a reposting of an article written by David Walsh. Check out his blog HERE!
I've been working a lot with visualizations lately, which is a far cry from your normal webpage element interaction coding; you need advanced geometry knowledge, render and performance knowledge, and much more. It's been a great learning experience but it can be challenging and isn't always an interest of all web developers. That's why we use apps and services specializing in complex tasks like Cloudinary: we need it done quickly and by a tool written by an expert.

Read more
Make All Images on Your Website Responsive in 3 Easy Steps

Images are crucial to website performance, but most still don't implement responsive images. It’s not just about fitting an image on the screen, but also making the the image size relatively rational to the device. The srcset and sizes options, which are your best hit are hard to implement. Cloudinary provides an easier way, which we will discuss in this article.

Read more

The Future of Audio and Video on the Web

By Prosper Otemuyiwa
The Future of Audio and Video on the Web

Web sites and platforms are becoming increasingly media-rich. Today, approximately 62 percent of internet traffic is made up of images, with audio and video constituting a growing percentage of the bytes.

Read more

Embed Images in Email Campaigns at Scale

By Sourav Kundu
Embed Images in Email Campaigns at Scale

tl;dr

Cloudinary is a powerful image hosting solution for email marketing campaigns of any size. With features such as advanced image optimization and on-the-fly image transformation, backed by a global CDN, Cloudinary provides the base for a seamless user experience in your email campaigns leading to increased conversion and performance.

Read more
Build the Back-End For Your Own Instagram-style App with Cloudinary

Github Repo

Managing media files (processing, storage and manipulation) is one of the biggest challenges we encounter as practical developers. These challenges include:

A great service called Cloudinary can help us overcome many of these challenges. Together with Cloudinary, let's work on solutions to these challenges and hopefully have a simpler mental model towards media management.

Read more

Build A Miniflix in 10 Minutes

By Prosper Otemuyiwa
Build A Miniflix in 10 Minutes

Developers are constantly faced with challenges of building complex products every single day. And there are constraints on the time needed to build out the features of these products.

Engineering and Product managers want to beat deadlines for projects daily. CEOs want to roll out new products as fast as possible. Entrepreneurs need their MVPs like yesterday. With this in mind, what should developers do?

Read more