Quick Start

Last updated: November 3th, 2019

What is PHP FFmpeg Video Streaming?

This package provides integration with PHP-FFMpeg and package media content for online streaming such as DASH and HLS. You can also use DRM for HLS packaging. There are several options to open a file from clouds and save files to them as well.

In the following page, you can download a complete example that contains server-side and client-side

Go To Download

Github Repository: https://github.com/aminyazdanpanah/PHP-FFmpeg-video-streaming

Bug Tracker and Issues: https://github.com/aminyazdanpanah/PHP-FFmpeg-video-streaming/issues

Installation

Step One: Requirement

    • FFMpeg

    • This Library requires a working FFmpeg. You will need both FFMpeg and FFProbe binaries to use it.

      Getting FFMpeg

      Useful Tip For Windows Users:

      For binary detection, you need to add FFmpeg and FFprobe to your system path

Step Two: Installing Package

This version of the package is only compatible with PHP 7.2 or higher.

Install the package via composer:

composer require aminyazdanpanah/php-ffmpeg-video-streaming

Alternatively, add the dependency directly to your composer.json file:

"require": {
    "aminyazdanpanah/php-ffmpeg-video-streaming": "^1.1"
}

Getting Composer

For downloading composer see here

Usage

First of all, you need to include the package in Your Code:

require 'vendor/autoload.php'; // path to the autoload file

NOTE:

If you are using such a framework(e.g. Laravel) that includes the autoload already, then you can skip this step.

Configuration

FFMpeg will autodetect ffmpeg and ffprobe binaries. If you want to give binary paths explicitly, you can pass an array as configuration. A Psr\Logger\LoggerInterface can also be passed to log binary executions.

use Monolog\Handler\StreamHandler;
use Monolog\Logger;

use Streaming\FFMpeg;

$config = [
    'ffmpeg.binaries'  => '/usr/bin/ffmpeg',
    'ffprobe.binaries' => '/usr/bin/ffprobe',
    'timeout'          => 3600, // The timeout for the underlying process
    'ffmpeg.threads'   => 12,   // The number of threads that FFmpeg should use
];

$log = new Logger('FFmpeg_Streaming');
$log->pushHandler(new StreamHandler('/var/log/ffmpeg-streaming.log')); // path to log file
    
$ffmpeg = FFMpeg::create($config, $log);

Opening a Resource

There are several ways to open a file:

1. From a FFmpeg supported resource

You can pass a local path of video(or a supported resource) to the open method:

$video = $ffmpeg->open('/var/www/media/videos/test.mp4');

For opening a file from a supported FFmpeg resource such as "http", "pipe", "rtmp" and etc. please see FFmpeg Protocols Documentation

For example:

$video = $ffmpeg->open('https://www.aminyazdanpanah.com/PATH/TO/VIDEO.MP4');
2. From a Cloud

You can open a file from a cloud by passing an array of cloud configuration to the openFromCloud method.

In this page, you will find some examples of opening a file from Amazon S3, Google Cloud Storage, Microsoft Azure Storage, and a custom cloud.

$video = $ffmpeg->openFromCloud($from_google_cloud);

DASH

Dynamic Adaptive Streaming over HTTP (DASH), also known as MPEG-DASH, is an adaptive bitrate streaming technique that enables high quality streaming of media content over the Internet delivered from conventional HTTP web servers. Similar to Apple's HTTP Live Streaming (HLS) solution, MPEG-DASH works by breaking the content into a sequence of small HTTP-based file segments, each segment containing a short interval of playback time of content that is potentially many hours in duration, such as a movie or the live broadcast of a sports event. The content is made available at a variety of different bit rates, i.e., alternative segments encoded at different bit rates covering aligned short intervals of playback time. While the content is being played back by an MPEG-DASH client, the client uses a bit rate adaptation (ABR) algorithm to automatically select the segment with the highest bit rate possible that can be downloaded in time for playback without causing stalls or re-buffering events in the playback. The current MPEG-DASH reference client dash.js offers both buffer-based (BOLA) and hybrid (DYNAMIC) bit rate adaptation algorithms. Thus, an MPEG-DASH client can seamlessly adapt to changing network conditions and provide high quality playback with fewer stalls or re-buffering events.

MPEG-DASH is the first adaptive bit-rate HTTP-based streaming solution that is an international standard. MPEG-DASH should not be confused with a transport protocol — the transport protocol that MPEG-DASH uses is TCP. MPEG-DASH uses existing HTTP web server infrastructure that is used for delivery of essentially all World Wide Web content. It allows devices like Internet-connected televisions, TV set-top boxes, desktop computers, smartphones, tablets, etc. to consume multimedia content (video, TV, radio, etc.) delivered via the Internet, coping with variable Internet receiving conditions. Standardizing an adaptive streaming solution is meant to provide confidence to the market that the solution can be adopted for universal deployment, compared to similar but more proprietary solutions like Smooth Streaming by Microsoft, or HDS by Adobe. Unlike HLS, HDS, or Smooth Streaming, DASH is codec-agnostic, which means it can use content encoded with any coding format, such as H.265, H.264, VP9, etc. Learn more

Create DASH Files Based on Original Video

This method allows you to create a multi-representations MPD file automatically based on the video size and bit rate:

$video->DASH()
    ->HEVC() // Format of the video. Alternatives: X264() and VP9()
    ->autoGenerateRepresentations() // Auto generate representations
    ->setAdaption('id=0,streams=v id=1,streams=a') // Set the adaption.
    ->save(); // It can be passed a path to the method or it can be null
Generate representations manually:

You can create HLS files by specifying the "KiloBitrate" and the "Resize"

use Streaming\Representation;

$r_144p  = (new Representation)->setKiloBitrate(95)->setResize(256, 144);
$r_240p  = (new Representation)->setKiloBitrate(150)->setResize(426, 240);
$r_360p  = (new Representation)->setKiloBitrate(276)->setResize(640, 360);
$r_480p  = (new Representation)->setKiloBitrate(750)->setResize(854, 480);
$r_720p  = (new Representation)->setKiloBitrate(2048)->setResize(1280, 720);
$r_1080p = (new Representation)->setKiloBitrate(4096)->setResize(1920, 1080);
$r_2k    = (new Representation)->setKiloBitrate(6144)->setResize(2560, 1440);
$r_4k    = (new Representation)->setKiloBitrate(17408)->setResize(3840, 2160);

$video->DASH()
    ->HEVC()
    ->addRepresentations([$r_144p, $r_240p, $r_360p, $r_480p, $r_720p, $r_1080p, $r_2k, $r_4k])
    ->setSegDuration(30) // Default value is 10 
    ->setAdaption('id=0,streams=v id=1,streams=a')
    ->save('/var/www/media/videos/dash-stream.mpd');

NOTE:

For more information about FFMpeg and its dash options please visit its website.

HLS

HTTP Live Streaming (also known as HLS) is an HTTP-based adaptive bitrate streaming communications protocol implemented by Apple Inc. as part of its QuickTime, Safari, OS X, and iOS software. Client implementations are also available in Microsoft Edge, Firefox and some versions of Google Chrome. Support is widespread in streaming media servers.

HLS resembles MPEG-DASH in that it works by breaking the overall stream into a sequence of small HTTP-based file downloads, each download loading one short chunk of an overall potentially unbounded transport stream. A list of available streams, encoded at different bit rates, is sent to the client using an extended M3U playlist.

Based on standard HTTP transactions, HTTP Live Streaming can traverse any firewall or proxy server that lets through standard HTTP traffic, unlike UDP-based protocols such as RTP. This also allows content to be offered from conventional HTTP servers and delivered over widely available HTTP-based content delivery networks. The standard also includes a standard encryption mechanism and secure-key distribution using HTTPS, which together provide a simple DRM system. Later versions of the protocol also provide for trick-mode fast-forward and rewind and for integration of subtitles.

Apple has documented HTTP Live Streaming as an Internet Draft (Individual Submission), the first stage in the process of publishing it as a Request for Comments (RFC). As of December 2015, the authors of that document have requested the RFC Independent Stream Editor (ISE) to publish the document as an informational (non-standard) RFC outside of the IETF consensus process. In August 2017, RFC8216 was published to describe version 7 of the protocol. Learn more

Create HLS Files Based on Original Video

This method allows you to create a multi-representations M3U8 files automatically based on the video size and bit rate:

$video->HLS()
    ->X264()
    ->autoGenerateRepresentations([720, 360]) // You can limit the numbers of representatons
    ->save();
Generate representations manually:

You can create HLS files by specifying the "KiloBitrate" and the "Resize"

use Streaming\Representation;

$r_360p  = (new Representation)->setKiloBitrate(276)->setResize(640, 360);
$r_480p  = (new Representation)->setKiloBitrate(750)->setResize(854, 480);
$r_720p  = (new Representation)->setKiloBitrate(2048)->setResize(1280, 720);

$video->HLS()
    ->X264()
    ->setHlsBaseUrl('https://bucket.s3-us-west-1.amazonaws.com/videos') // Add a base URL
    ->addRepresentations([$r_360p, $r_480p, $r_720p])
    ->setHlsTime(5) // Set Hls Time. Default value is 10 
    ->setHlsAllowCache(false) // Default value is true 
    ->save();

NOTE:

You cannot use HEVC and VP9 formats for HLS packaging.

NOTE:

See HLS options for more information.

Encrypted HLS

The encryption process requires some kind of secret (key) together with an encryption algorithm. HLS uses AES in cipher block chaining (CBC) mode. This means each block is encrypted using the ciphertext of the preceding block. Learn more

You must specify a path to save a random key to your local machine and also a URL(or a path) to access the key on your website(the key you will save must be accessible from your website). You must pass both these parameters to the encryption method:

Single Key

The following code generates a key for all TS files.

//A path you want to save a random key to your server
$save_to = '/home/public_html/PATH_TO_KEY_DIRECTORY/random_key.key';

//A URL (or a path) to access the key on your website
$url = 'https://www.aminyazdanpanah.com/PATH_TO_KEY_DIRECTORY/random_key.key';
// or $url = '/PATH_TO_KEY_DIRECTORY/random_key.key';

$video->HLS()
    ->X264()
    ->setTsSubDirectory('ts_files')// put all ts files in a subdirectory
    ->encryption($save_to, $url)
    ->autoGenerateRepresentations([1080, 480, 240])
    ->save('/var/www/media/videos/hls-stream.m3u8');


Key Rotation

This technique allows you to encrypt each TS file with a new encryption key. This can improve security and allows for more flexibility. You can also modify the code to use a different key for each set of segments(i.e. if 10 TS files have been generated then rotate the key) or you can generate a new encryption key at every periodic time(i.e. every 10 seconds).

First, you need to create a listener class that is extended by "Evenement\EventEmitter" and is implemented by "Alchemy\BinaryDriver\Listeners\ListenerInterface". This allows you to get all lines of FFmpeg logs regardless of the type of them.

class LineListener extends Evenement\EventEmitter implements Alchemy\BinaryDriver\Listeners\ListenerInterface
{
    private $event;

    public function __construct($event = 'line')
    {
        $this->event = $event;
    }

    public function handle($type, $data)
    {
        foreach (explode(PHP_EOL, $data) as $line) {
            $this->emit($this->event, [$line]);
        }
    }

    public function forwardedEvents()
    {
        return [$this->event];
    }
}

You can also use the "Alchemy\BinaryDriver\Listeners\DebugListener" object instead and skip this step.

After that, you should pass an instance of the object to the "listen" method in the "FFMpegDriver" object and get the line of FFmpeg logs. When a new TS file has been created, you should generate a new encryption key and update the key info file.

$save_to = "/home/public_html/PATH_TO_KEY_DIRECTORY/key_rotation";
$url = "https://www.aminyazdanpanah.com/PATH_TO_KEY_DIRECTORY/key_rotation";
$key_info_path = Streaming\File::tmp();
$ts_files = [];

$update_key_info_file = function ($number) use ($save_to, $url, $key_info_path) {
    $u_key_path = $save_to . "_" . $number;
    $u_url = $url . "_" . $number;
    Streaming\HLSKeyInfo::generate($u_key_path, $u_url, $key_info_path);
};

$ffmpeg = Streaming\FFMpeg::create();
$ffmpeg->getFFMpegDriver()->listen(new LineListener);
$ffmpeg->getFFMpegDriver()->on('line', function ($line) use (&$ts_files, $update_key_info_file) {
    // Check if a new TS file is generated or not
    if(false !== strpos($line, ".ts' for writing") && !in_array($line, $ts_files)){
        // A new TS file has been created! Generate a new encryption key and update the key info file
        array_push($ts_files, $line);
        call_user_func($update_key_info_file, count($ts_files));
    }
});

$video = $ffmpeg->open("path/to/video");

$video->HLS()
    ->encryption($save_to, $url, $key_info_path)
    ->setAdditionalParams(['-hls_flags', 'periodic_rekey'])
    ->X264()
    ->autoGenerateRepresentations([240])
    ->save('/var/www/media/encryption_key_rotation/hls-stream.m3u8');

NOTE:

It is very important to protect your key(s) on your website using a token or a session/cookie(It is highly recommended).

NOTE:

However HLS supports AES encryption, which you can encrypt your streams, it is not a full DRM solution. If you want to use a full DRM solution, I recommend trying FairPlay Streaming solution which then securely exchange keys, and protect playback on devices.

Transcoding

A format can also extend FFMpeg\Format\ProgressableInterface to get realtime information about the transcoding.

$format = new Streaming\Format\HEVC();
$start_time = 0;

$percentage_to_time_left = function ($percentage) use (&$start_time) {
    if($start_time === 0){
        $start_time = time();
        return "Calculating...";
    }

    $diff_time = time() - $start_time;
    $seconds_left = 100 * $diff_time / $percentage - $diff_time;

    return gmdate("H:i:s", $seconds_left);
};
$format->on('progress', function ($video, $format, $percentage) use($percentage_to_time_left) {
    // You can update a field in your database or can log it to a file
    // You can also create a socket connection and show a progress bar to users
    echo sprintf("\rTranscoding...(%s%%) %s [%s%s]", $percentage, $percentage_to_time_left($percentage), str_repeat('#', $percentage), str_repeat('-', (99 - $percentage)));
});

$video->DASH()
    ->setFormat($format)
    ->autoGenerateRepresentations()
    ->setAdaption('id=0,streams=v id=1,streams=a')
    ->save();

HLS Transcoding:

$format = new Streaming\Format\X264();
$current_percentage = 0;

$format->on('progress', function ($video, $format, $percentage) use (&$current_percentage) {
    $percentage = intval($percentage);
    if ($current_percentage !== $percentage) {
        echo sprintf("\r Transcoding... (%s%%)[%s%s]", $percentage, str_repeat('#', $percentage), str_repeat('-', (100 - $percentage)));
        $current_percentage = $percentage;
    }
});

$video->HLS()
    ->setFormat($format)
    ->setTsSubDirectory('ts_files')
    ->setHlsBaseUrl('https://bucket.s3-us-west-1.amazonaws.com/videos')
    ->autoGenerateRepresentations([240, 144], [200, 100]) // You can also set the kilo bite rate of each video
    ->save('/var/www/media/videos/dash/test.m3u8');
Output From a Terminal:

NOTE:

See Formats for more information.

Saving Files

There are three options to save your packaged video files:

1. To a Local Path

You can pass a local path to the save method. If there was no directory in the path, then the package auto makes the directory.

$dash = $video->DASH()
            ->HEVC()
            ->autoGenerateRepresentations()
            ->setAdaption('id=0,streams=v id=1,streams=a');
            
$dash->save('/var/www/media/videos/dash/test.mpd');

It can also be null. The default path to save files is the input path.

$hls = $video->HLS()
            ->X264()
            ->autoGenerateRepresentations();
            
$hls->save();

NOTE:

If you open a file from a cloud and do not pass a path to save the file to your local machine, you will have to pass a local path to the "save" method.

2. To a Cloud:

You can save your files to a cloud by passing an array of cloud configuration to the save method.

In this page, you will find some examples of saving files to Amazon S3, Google Cloud Storage, Microsoft Azure Storage, and a custom cloud.

$dash->save(null, [$to_aws_cloud, $to_google_cloud, $to_microsoft_azure, $to_custom_cloud]);

A path can also be passed to save a copy of files to your local machine.

$hls->save('/var/www/media/videos/hls/test.m3u8', [$to_google_cloud, $to_custom_cloud]);

NOTE:

This option(Save To Clouds) is only for VOD (it does not support live streaming).

NOTE:

You can open a file from your local machine(or a cloud) and save files to a local path or a cloud(or multiple clouds).

Metadata Extraction

After saving files(wherever you saved them), you can extract the metadata from the video and streams:

extract($hls->save());

echo $filename; // path to metadata.json
print_r($metadata); // print metadata -> it's an array

Live

You can pass a url to live method to upload all the segments files to the HTTP server using the HTTP PUT method, and update the manifest files every refresh times.

// DASH live
$dash->live('http://YOUR-WEBSITE.COM/live-stream/out.mpd');

// HLS live
$hls
    ->setMasterPlaylist('/var/www/stream/live-master-manifest.m3u8')
    ->live('http://YOUR-WEBSITE.COM/live-stream/out.m3u8');

NOTE:

In the HLS method, you must upload the master manifest to the server manually. (Upload the /var/www/stream/live-master-manifest.m3u8 file to the http://YOUR-WEBSITE.COM)

Conversion

You can convert your stream to a file or to another stream protocols. You should pass a manifest of a stream to the open method:

1. HLS To DASH
$stream = $ffmpeg->open('https://www.aminyazdanpanah.com/PATH/TO/HLS-MANIFEST.M3U8');

$stream->DASH()
    ->X264()
    ->addRepresentations([$r_360p, $r_480p]) 
    ->save('/var/www/media/dash-stream.mpd');
2. DASH To HLS
$stream = $ffmpeg->open('https://www.aminyazdanpanah.com/PATH/TO/DASH-MANIFEST.MPD');

$stream->HLS()
           ->X264()
           ->autoGenerateRepresentations([720, 360])
           ->save('/var/www/media/hls-stream.m3u8');
3. Stream(DASH or HLS) To File:
$format = new Streaming\Format\X264();
$format->on('progress', function ($video, $format, $percentage){
    echo sprintf("\rTranscoding...(%s%%) [%s%s]", $percentage, str_repeat('#', $percentage), str_repeat('-', (100 - $percentage)));
});

$stream->stream2file()
           ->setFormat($format)
           ->save('/var/www/media/new-video.mp4');

Other Advanced Features

You can easily use other advanced features in the PHP-FFMpeg library. In fact, when you open a file with the open method(or "fromURL"), it holds the Media object that belongs to the PHP-FFMpeg.

For exploring other advanced features, please read the Full PHP-FFMpeg Documentation.

$ffmpeg = Streaming\FFMpeg::create()
$video = $$ffmpeg->fromURL("https://www.aminyazdanpanah.com/my_sweetie.mp4", "/var/wwww/media/my/new/video.mp4");

Extracting image

You can extract a frame at any timecode using the FFMpeg\Media\Video::frame method.

$frame = $video->frame(FFMpeg\Coordinate\TimeCode::fromSeconds(42));
$frame->save('/var/www/media/videos/poster.jpg');

NOTE:

You can use the image as a video's poster.

Gif

A gif is an animated image extracted from a sequence of the video. You can save gif files using the FFMpeg\Media\Gif::save method.

$video
    ->gif(FFMpeg\Coordinate\TimeCode::fromSeconds(2), new FFMpeg\Coordinate\Dimension(640, 480), 3)
    ->save('/var/www/media/videos/animated_image.gif');

This method has a third optional boolean parameter, which is the duration of the animation. If you don't set it, you will get a fixed gif image.

NOTE:

You can use the gif as a video's thumbnail.

Asynchronous Task Execution

Packaging process will may take a while and it is recommended to run it in the background(or in a cloud e.g. Google Cloud). There are some libraries that you can use.

Symphony(The Console Component): You can use this library to create command-line commands. Your console commands can be used for any recurring task, such as cronjobs, imports, or other batch jobs. Learn more.

Laravel(Queues): If you are using Laravel for development, Laravel Queues is a wonderful tool for this use case. It allows you to create a job and dispatch it. Learn more

Google Cloud Tasks: Google Cloud Tasks is a fully managed service that allows you to manage the execution, dispatch, and delivery of a large number of distributed tasks. You can asynchronously perform work outside of a user request. Learn more

NOTE:

It is not necessary to use these libraries. It is just a suggestion. You can also create a script to create packaged video files and run a job in the cron job.

Several Open Source Players

You can use these players to play your packaged videos.




NOTE:

You should pass a manifest of stream(e.g. https://www.aminyazdanpanah.com/PATH_TO_STREAM_DIRECTORY/dash-stream.mpd or /PATH_TO_STREAM_DIRECTORY/hls-stream.m3u8 ) to these players.

NOTE:

As you may know, IOS does not have native support for DASH. Although there are some libraries such as Viblast and MPEGDASH-iOS-Player to support this technique, I have never tested them. So if you know any IOS player that supports DASH Stream and also works fine, please send me an e-mail to add it to the above list.

Demos

DASH(dash.js)

HLS(hls.js)

Contributing and Reporting Bugs

I'd love your help in improving, correcting, adding to the specification. Please file an issue or submit a pull request.

If you have any question, please just file an issue.

If you discover a security vulnerability within this package, please contact me.

Warning:

If you have any questions about this package or FFmpeg, please DO NOT send an email to me (or submit the contact form on my website). Emails regarding these issues will be ignored. Instead, you should file an issue in the repository on Github.

If you like this project, please ⭐️ Star it on the Github.