Code Monkey home page Code Monkey logo

php-ffmpeg-video-streaming's Introduction

๐Ÿ“ผ PHP FFmpeg - Video Streaming

Total Downloads

This package utilizes FFmpeg to bundle media content for online streaming, including DASH and HLS. Additionally, it provides the capability to implement DRM for HLS packaging. The program offers a range of options to open files from cloud storage and save files to cloud storage as well.

Documentation

Full Documentation is available describing all features and components.

Basic Usage

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()
    ->addRepresentations([$r_360p, $r_480p, $r_720p])
    ->save();

Get from Basic and Pro packages for Video Streaming

Our platform empowers businesses to expand their reach globally by delivering exceptional video streaming experiences. Enjoy unmatched reliability, scalability, and high-definition quality across a diverse range of devices, ensuring your content captivates audiences worldwide.

Plans

Features / Plans Basic Pro
Authentication โœ… โœ…
Access-control list (ACL) โœ… โœ…
Video On-Demand (HLS and DASH) โœ… โœ…
HLS Encryption(Single key and key rotation) โœ… โœ…
Video Quality Settings: Manually Choose from 144p to 4k or auto mode โœ… โœ…
Real-Time Progress Monitoring: progress bar to display the live upload and transcoding progress โœ… โœ…
Dark and light theme โœ… โœ…
Live Streaming: From Browser Webcam, IP Cameras, Live Streaming Software โ›”๏ธ โœ…
Bespoke player design: Crafted to perfectly align with your brand identity and user preferences. โ›”๏ธ โœ…
Add Subtitles and Audios: add different subtitle and audio files to stream โ›”๏ธ โœ…
Monetization: Subscriptons/pay-per-view/ads โ›”๏ธ โœ…
Advanced Analytics: Views/Watched hours/Visited countries and more โ›”๏ธ โœ…
Robust DRM Systems: Widevine, FairPlay Streaming and PlayReady โ›”๏ธ โœ…
Social Media Integration: Like, Comment, Share and embed videos โ›”๏ธ โœ…
Cloud-based CDN: Accelerates content delivery worldwide through integration with major cloud storage providers such as Amazon S3, Google Cloud Storage, and Microsoft Azure. โ›”๏ธ โœ…
Tailored features: We can integrate any specific functionality you require into your platform. โ›”๏ธ โœ…
Support 3 Months Customizable
Online Demo See Online Demo Book Free Demo
Get GET CONTACT US
We tailor OTT platforms to exact client specifications, offering flexible and affordable pricing.

Contributors

Your contribution is crucial to our success, regardless of its size. We appreciate your support and encourage you to read our CONTRIBUTING guide for detailed instructions on how to get involved. Together, we can make a significant impact.

Made with contrib.rocks.

License

The MIT License (MIT). See License File for more information.

php-ffmpeg-video-streaming's People

Contributors

aminyazdanpanah avatar b-vadym avatar digilist avatar edicleoberners avatar finagin avatar mashsajid avatar renovate-bot avatar shalmor avatar skyeewers avatar taochangle avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

php-ffmpeg-video-streaming's Issues

HLS h264_amf

Hi,
trying to implement AMD encoding future with video codec h264_amf working good on PHP-FFMpeg/PHP-FFMpeg but i cant implement this on your code i tried to extend Streaming\Format\X264 to support 'h264_amf' but no effect sltill using only CPU to encode and also can we change Audiocodec to on hls streaming.

Autogenerate representation for .mp4 file

Hello Guys,
I am using your library to create HLS files. It works great. I want to create .mp4 to multiple bitrates using this same library. Is it possible? Can I do something like

$video->hls()
->encryption($save_to, $url)
->x264()
->setFormat($format)
->addRepresentations($rep)
->autoGenerateRepresentations([r_720p,r_240p])
->save(null , $destinationURL);

For mp4 source file and output as mp4 file itself in 720 and 240. I know I can use ffm-peg but from my understanding, I have to generate the individual file for each representation.

Regards,

Ideas about fmp4 (fragmented mp4s)

Thank you so much for your very useful library.

I was wondering if you have any ideas about how to accomplish the following.

Currently I have:

class HlsVideo extends \Streaming\HLS {

    protected \Streaming\Filters\Filter $filter;

    public function getFilter(): \Streaming\Filters\Filter {
        return new HlsFilter($this);
    }

}

and

use Streaming\File;
use Streaming\HLS;
use Streaming\Representation;

class HlsFilter extends \Streaming\Filters\HLSFilter {

    const INIT_DOT_MP4 = "init.mp4";

    public function setFmp4Options(array &$filter, $dirname, $ts_sub_dir, array $path_parts, \Streaming\Representation $rep) {
        $filter[] = "-hls_segment_type";
        $filter[] = "fmp4";
        $filter[] = "-hls_fmp4_init_filename";
        $filter[] = $dirname . "/" . $ts_sub_dir . self::INIT_DOT_MP4;
        $filter[] = "-hls_segment_filename";
        $segmentsFilenamePattern = $dirname . "/" . $ts_sub_dir . $path_parts["filename"] . "_" . $rep->getHeight() . "p_%04d.m4s";
        $filter[] = $segmentsFilenamePattern;
    }
//... Then the rest of the class is nearly identical to \Streaming\Filters\HLSFilter but I couldn't just extend your class because you used private methods. So I copied and pasted most of your functions into my class, and then my function HLSFilter calls `$this->setFmp4Options($filter, $dirname, $ts_sub_dir, $path_parts, $rep);`

Then in a third class I call encryptVideo:

public function encryptVideo(string $inputFilename, string $outputFilename, string $keyInfoFilePath) {
    $log = new Logger('FFmpeg_Streaming');
    $log->pushHandler(new StreamHandler('storage/logs/ffmpeg-streaming.log'));
    $ffmpeg = FFMpeg::create($this->getConfig(), $log);
    $video = $ffmpeg->open($inputFilename);
    $format = new \Streaming\Format\X264();
    $representations = [$this->getOriginalRepresentation($video)];
    $hlsVideo = new HLS\HlsVideo($video);
    $hlsVideo
            ->setFormat($format)
            ->setHlsKeyInfoFile($keyInfoFilePath)
            ->addRepresentations($representations)
            ->setHlsAllowCache(false)
            ->save($outputFilename);
}

public function getOriginalRepresentation(Media $video): Representation {
    $firstVideoStream = $video->getStreams()->videos()->first();
    $width = $firstVideoStream->get('width');
    $height = $firstVideoStream->get('height');
    $kiloBitrate = $firstVideoStream->get('bit_rate') / self::KILO_MULTIPLIER;
    return (new Representation)->setResize($width, $height)
                    //->setAudioKiloBitrate($audioKiloBitrate)//Where can I retrieve the original audioKiloBitrate?
                    ->setKiloBitrate($kiloBitrate);
}

This nearly works!

It properly creates the m4s files, the m3u8 files, and the init.mp4 file.

And then I use hls.js on my webpage to try to show the video.

Initially, it won't load.

But then I can get the video to load properly if I refresh the page after making this edit to list_1080p.m3u8:

Change from:

#EXT-X-MAP:URI="/myproject/public/storage/000000002/init.mp4"

To:

#EXT-X-MAP:URI="init.mp4"

What can I change so that ffmpeg knows the absolute path of where to save the init.mp4 but also knows to write in the m3u8 only the filename init.mp4 without any path?

And I'm curious if you have any suggestions about a better way to do what I've done so far; maybe there is a way to avoid copying and pasting your code.

And if you have ideas about my question above in the comment in getOriginalRepresentation, I'd love to hear, too.

Thanks so much. :-)

"Failed: error: Your FFProbe version is too old and does not support `-help` option, please upgrade." NULL

ffmpeg

ffmpeg version 4.1.3-0york116.04 Copyright (c) 2000-2019 the FFmpeg developers
built with gcc 5.4.0 (Ubuntu 5.4.0-6ubuntu1
16.04.11) 20160609
configuration: --prefix=/usr --extra-version='0york1~16.04' --toolchain=hardened --libdir=/usr/lib/x86_64-linux-gnu --incdir=/usr/include/x86_64-linux-gnu --arch=amd64 --enable-gpl --disable-stripping --enable-avresample --disable-filter=resample --enable-avisynth --enable-gnutls --enable-ladspa --enable-libaom --enable-libass --enable-libbluray --enable-libbs2b --enable-libcaca --enable-libcdio --enable-libcodec2 --enable-libflite --enable-libfontconfig --enable-libfreetype --enable-libfribidi --enable-libgme --enable-libgsm --enable-libjack --enable-libmp3lame --enable-libmysofa --enable-libopenjpeg --enable-libopenmpt --enable-libopus --enable-libpulse --enable-librsvg --enable-librubberband --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libspeex --enable-libssh --enable-libtheora --enable-libtwolame --enable-libvidstab --enable-libvorbis --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx265 --enable-libxml2 --enable-libxvid --enable-libzmq --enable-libzvbi --enable-lv2 --enable-omx --enable-openal --enable-opengl --enable-sdl2 --enable-nonfree --enable-libfdk-aac --enable-libdc1394 --enable-libdrm --enable-libiec61883 --enable-chromaprint --enable-frei0r --enable-libx264 --enable-shared
libavutil 56. 22.100 / 56. 22.100
libavcodec 58. 35.100 / 58. 35.100
libavformat 58. 20.100 / 58. 20.100
libavdevice 58. 5.100 / 58. 5.100
libavfilter 7. 40.101 / 7. 40.101
libavresample 4. 0. 0 / 4. 0. 0
libswscale 5. 3.100 / 5. 3.100
libswresample 3. 3.100 / 3. 3.100
libpostproc 55. 3.100 / 55. 3.100
Hyper fast Audio and Video encoder

FFprobe:

fprobe version 4.1.3-0york116.04 Copyright (c) 2007-2019 the FFmpeg developers
built with gcc 5.4.0 (Ubuntu 5.4.0-6ubuntu1
16.04.11) 20160609
configuration: --prefix=/usr --extra-version='0york1~16.04' --toolchain=hardened --libdir=/usr/lib/x86_64-linux-gnu --incdir=/usr/include/x86_64-linux-gnu --arch=amd64 --enable-gpl --disable-stripping --enable-avresample --disable-filter=resample --enable-avisynth --enable-gnutls --enable-ladspa --enable-libaom --enable-libass --enable-libbluray --enable-libbs2b --enable-libcaca --enable-libcdio --enable-libcodec2 --enable-libflite --enable-libfontconfig --enable-libfreetype --enable-libfribidi --enable-libgme --enable-libgsm --enable-libjack --enable-libmp3lame --enable-libmysofa --enable-libopenjpeg --enable-libopenmpt --enable-libopus --enable-libpulse --enable-librsvg --enable-librubberband --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libspeex --enable-libssh --enable-libtheora --enable-libtwolame --enable-libvidstab --enable-libvorbis --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx265 --enable-libxml2 --enable-libxvid --enable-libzmq --enable-libzvbi --enable-lv2 --enable-omx --enable-openal --enable-opengl --enable-sdl2 --enable-nonfree --enable-libfdk-aac --enable-libdc1394 --enable-libdrm --enable-libiec61883 --enable-chromaprint --enable-frei0r --enable-libx264 --enable-shared
libavutil 56. 22.100 / 56. 22.100
libavcodec 58. 35.100 / 58. 35.100
libavformat 58. 20.100 / 58. 20.100
libavdevice 58. 5.100 / 58. 5.100
libavfilter 7. 40.101 / 7. 40.101
libavresample 4. 0. 0 / 4. 0. 0
libswscale 5. 3.100 / 5. 3.100
libswresample 3. 3.100 / 3. 3.100
libpostproc 55. 3.100 / 55. 3.100
Simple multimedia streams analyzer
usage: ffprobe [OPTIONS] [INPUT_FILE]

Error:
"Failed: error: Your FFProbe version is too old and does not support -help option, please upgrade." NULL

autoGenerateRepresentations() Bug (with vertical videos?)

Describe the bug

I am using the following code:

$video->dash() ->setFormat($format) ->generateHlsPlaylist() ->autoGenerateRepresentations([360, 480, 720, 1080]) ->save(null, $to_s3);

In the .m3u8 file there should be 4 streams of my video. yet if I use a 4K video using these settings the code will create also create the 2160p video stream.

You can test it with the following Video: https://fuego-files.s3.eu-central-1.amazonaws.com/public/16612219545e3d64db55f19/1587737965e3d64d711a36/video/video.mp4

To Reproduce
Use the code from above and the video from above.

Expected behavior
There should be no 2160p stream

Desktop/Server (please complete the following information):
ffmpeg version 4.2.2-1ubuntu1~18.04

setMediaInfoBinary Usage Example

Hi,
How can i bypass MediaInfo path with setMediaInfoBinary? When i call function from Streaming\MediaInfo, it is showing error for other variables?
Can you give usage example setMediaInfoBinary?

Thanks,
Salih

wana help to reduce file size

Is your feature request related to a problem? Please describe.
no
Describe the solution you'd like
hi , at first thank you for share your code
i have problem with size of files that converted to DRM (.ts files ), i mean , for example , file that used to stream have 10MB size , after generating .ts files , key ,... generated file have 22 MB
file size , is it natural ? (it is 2x grather than none stream file )
if it is not natural , how can i use other option to reduce this files size ?
Additional context
this is code that i used to generate file

$save_to = 'C:\xampp\htdocs\hls\key';
//A URL (or a path) to access the key on your website
$url = 'http://localhost/hls/key';
//$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);
$format = new Streaming\Format\X264();
$format->on('progress', function ($video, $format, $percentage){
echo sprintf("\r Transcoding... (%s%%)[%s%s]", $percentage, str_repeat('#', $percentage), str_repeat('-', (100 - $percentage)));
});
//var_dump($video->hls()->getHlsListSize());
$video->hls()
->encryption($save_to, $url)
->setFormat($format)
->x264()
->autoGenerateRepresentations([])
->save(base_path.'/files/test2.m3u8');

thank you again for you help

create master playlists and add multi generated hls m3u8 to master playlists

i want generate this format 360p , 480p ,720p in different time,
then put all in one playlist,
have you any advice or code sample?
(I do not want generate mutl Representations at same time)

my goal is :
#EXTM3U
#EXT-X-VERSION:3
#EXT-X-STREAM-INF:BANDWIDTH=20480,RESOLUTION=854x480
file_example_480p.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=20480,RESOLUTION=640x360
file_example_360p.m3u8

Uncaught Error: Class 'Representation' -> addRepresentation Function

Hi,
I'm getting error when i try different representation add. My PHP Version is 7.3.8. I tried with different php versions but still same. Can you please check?

Here is my code,
`
require_once 'assets/vendor/autoload.php';

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

$format = new Streaming\Format\X264();
$format->on('progress', function ($video, $format, $percentage) {
echo "$percentage% is transcoded\n";
});

$rep_1 = (new Representation())->setKiloBitrate(1000)->setResize(1080 , 720);
$rep_2 = (new Representation())->setKiloBitrate(500)->setResize(640 , 360);
$rep_3 = (new Representation())->setKiloBitrate(200)->setResize(480 , 270);

$ffmpeg = Streaming\FFMpeg::create($config)
->open('short.mp4') // the path to the video
->HLS()
->addRepresentation($rep_1) // Add a representation
->addRepresentation($rep_2) // Add a representation
->addRepresentation($rep_3) // Add a representation
->setHlsTime(20)
->setFormat($format)
->setHlsAllowCache(false)
->save();
`

Error Message,
Fatal error: Uncaught Error: Class 'Representation' not found in

Encoded Files are not playable

Describe the bug
Hi, I'm having trouble with multi quality encoding. System is producing playlist and every file but files are not playable. If we encode each quality separately, then it plays fine. But then I need to recreate main Manifest file.

To Reproduce
$360 = (new Representation)->setKiloBitrate(276)->setResize(640, 360);
$r_480p = (new Representation)->setKiloBitrate(750)->setResize(854, 480);
$video->HLS()
->setFormat($format)
->setHlsTime(8)
->setHlsAllowCache(false)
->fragmentedMP4()
->addRepresentations([$r_360, $r_480])
->save();
Or
$video->HLS()
->setFormat($format)
->setHlsTime(8)
->setHlsAllowCache(false)
->fragmentedMP4()
->autoGenerateRepresentations([360, 480])
->save();

PS: This only happens if we choose ->fragmentedMP4()

Expected behavior
It should have exported playable files which are possible only if we run it in loop and then encode each quality separately.

Everything seems to be broken after this update

Describe the bug
Everything seems to be broken after this update. Nothing working as earlier

To Reproduce
Steps to reproduce the behavior:

  1. Go to '/../...'
  2. On Line '...'
  3. The code '....'
  4. See error

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop/Server (please complete the following information):

  • OS: [e.g. Linux]
  • Version [e.g. Ubuntu 18]
  • FFmpeg vesion [e.g. 4.1]

Additional context
Add any other context about the problem here.

master playlist is consisting duplicate line of max representation

Describe the bug
A clear and concise description of what the bug is.

Below is the sample laster playlist that I have generated
#EXTM3U
#EXT-X-VERSION:3
#EXT-X-STREAM-INF:BANDWIDTH=344064,RESOLUTION=426x240,NAME="240"
input_240p.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=431104,RESOLUTION=640x360,NAME="360"
input_360p.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=574464,RESOLUTION=1280x720,NAME="720"
input_720p.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=862208,RESOLUTION=1280x720,NAME="720"
input_720p.m3u8

this is resulting in more data download from cloud server

To Reproduce
Steps to reproduce the behavior:

I am adding below to video object
$video = $this->FFMpeg->open('input.mp4');
$video->HLS()
->autoGenerateRepresentations([240, 360, 720])
->encryption($save_to, $url, $key_info_path)
->setAdditionalParams(['-hls_flags', 'periodic_rekey'])
->setFormat($format)
->setHlsTime(5)
->X264()
->setHlsAllowCache(false)
->setTsSubDirectory('ts_files')
->save(null, $to_aws_cloud);

Expected behavior
A clear and concise description of what you expected to happen.

#EXTM3U
#EXT-X-VERSION:3
#EXT-X-STREAM-INF:BANDWIDTH=344064,RESOLUTION=426x240,NAME="240"
input_240p.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=431104,RESOLUTION=640x360,NAME="360"
input_360p.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=574464,RESOLUTION=1280x720,NAME="720"
input_720p.m3u8

also want way to define default representation in case of auto

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop/Server (please complete the following information):

  • OS: [e.g. Linux]
  • Version [e.g. Ubuntu 18]
  • FFmpeg vesion [e.g. 4.1]
    FFmpeg vesion 4

Additional context
Add any other context about the problem here.

Hosting Block with Example Video

Hi Amin,
I was working with your example via documantation. Your hosting blocked me. In default example you have one video from your hosting, i was using for my test case. Probably because of to many get request, it blocked. Now i can not access to documantation or your website :)

Example video from documantion,
https://www.aminyazdanpanah.com/my_sweetie.mp4

Maybe you should change location of example video. And if you can refresh firewall, i would appreciate it.

Thanks,
Salih

hls single file

trying to make this work:

ffmpeg -threads 0 -i test.mp4 -r 24 -g 48 -keyint_min 48 -sc_threshold 0 -c:v libx264^
 -s:v:0 1920x1080 -b:v:0 5200k -maxrate:v:0 5720k -bufsize:v:0 5200k^
 -s:v:1 1280x720 -b:v:1 3100k -maxrate:v:1 3410k -bufsize:v:1 3100k^
 -b:a 128k -ar 44100 -ac 2^
 -map 0:v -map 0:v -map 0:a^
 -f hls -var_stream_map "v:0,agroup:audio v:1,agroup:audio a:0,agroup:audio"^
 -hls_flags single_file -hls_segment_type fmp4 -hls_list_size 0 -hls_time 6  -master_pl_name master.m3u8 -y test%v.m3u8

so i edited the HLSFilter.php file:

    private function initArgs(Representation $rep): array
    {
        return [
            "-s:v", $rep->getResize(),
            "-crf", "20",
            "-r", "24",
            "-sc_threshold", "0",
            "-g", "48",
            "-keyint_min", "48",
            "-f", "hls",
            "-b:v", $rep->getKiloBitrate() . "k",
            "-maxrate", intval($rep->getKiloBitrate() * 1.2) . "k",
            "-hls_flags", "single_file",
            "-hls_segment_type", $this->hls->getHlsSegmentType(),
            "-hls_list_size", $this->hls->getHlsListSize(),
            "-hls_time", $this->hls->getHlsTime(),
            "-master_pl_name", $this->getInitFilename(),
            "-y", $this->getInitFilename()
        ];
    }

not sure if this is good or not? any other way to do that better? not sure also how to map the audios

Different Export Path .ts files in the .m3u8 Path

Hi,
Can you seperate export path and ts files in the .m3u8 path? When i put path to ->save(); , it is pushing same path to m3u8 file. Actually i need without folder path in m3u8 file, i'm keeping all files in the folder. It is causing mess in converter folder when i export without path.

Example,
-> I'm exporting to export/movieName
-> Framework is pushing files names like export/movieName/file.ts

I need,
-> Export path will be again export/movieName
-> File names will be without export folder path

Just idea, i hope I've explained clear :)

I can't anti download from tool download

I can't anti download from tool download.
my code here:
//A path you want to save a random key to your local machine
$save_to = base_path() . '/lib/' . $randomString . '/key';
//A URL (or a path) to access the key on your website
$url = url('/') . '/lib/enc.key';
// or $url = '/"PATH TO THE KEY DIRECTORY"/key';
$format = new Streaming\Format\X264();
$format->on('progress', function ($video, $format, $percentage) {
echo sprintf("\rTranscoding...(%s%%) [%s%s]", $percentage, str_repeat('#', $percentage), str_repeat('-', (99 - $percentage)));
});
$video->hls()
->x264()
->setFormat($format)
->encryption($save_to, $url, 1)
->autoGenerateRepresentations([720, 360]) // You can limit the numbers of representatons
->save(base_path() . '/lib/' . $randomString . '/' . $randomString . '.m3u8');

please help, thanks!

Cannot transcode Video only files (DASH)

Hey I tried transcode an MP4 file with no audio to HLS and DASH.
Transcoding to HLS worked fine but it does not work to DASH.

I tried the following Adaptions:
->setAdaption('id=0,streams=v')
->setAdaption('id=0,streams=v id=1,streams=a')

Both failed.

I also tried to Transcode to HLS first, upload it and then try to do the HLS to DASH transcoding but that threw an error of ("Invalid Kilobit rate")

To Reproduce
Try to Transcode an MP4 file that has no sound to DASH

Desktop/Server (please complete the following information):

  • OS: [e.g. Linux] Ubuntu 18.04
  • FFmpeg vesion [e.g. 4.1] ffmpeg version 3.4.6-0ubuntu0.18.04.1

After finishing HLS Encoding Gives Error (We could not find the binary)

Describe the bug
I'm using Laravel Job Below is the code and Error logs. Please advice

Laravel Code

$config = [
'ffmpeg.binaries' => '/usr/bin/ffmpeg',
'ffprobe.binaries' => '/usr/bin/ffprobe',
'timeout' => 3600,
'ffmpeg.threads' => 12,
];

                    $rep_144 = (new Representation)->setKiloBitrate(95)->setResize(256 , 144);
                    $rep_240 = (new Representation)->setKiloBitrate(150)->setResize(426 , 240);
                    $rep_360 = (new Representation)->setKiloBitrate(276)->setResize(640 , 360);
                    $rep_480 = (new Representation)->setKiloBitrate(750)->setResize(854 , 480);
                    $rep_720 = (new Representation)->setKiloBitrate(2048)->setResize(1280 , 720);

                    $ffmpeg = \Streaming\FFMpeg::create($config)
                        ->open($this->inputFile)
                        ->HLS()
                        ->X264()
                        ->addRepresentation($rep_144)
                        ->addRepresentation($rep_240)
                        ->addRepresentation($rep_360)
                        ->addRepresentation($rep_480)
                        ->addRepresentation($rep_720)
                        ->setHlsTime(5) // Set Hls Time. Default value is 10 
                        ->setHlsAllowCache(false) // Default value is true 
                        ->save($path);

Error Logs
[2019-11-05 11:29:49] local.ERROR: Streaming\Exception\RuntimeException: We could not find the binary().
Please check the path to the binary in vendor/aminyazdanpanah/php-ffmpeg-video-streaming/src/Process/Process.php:50
Stack trace:
#0 vendor/aminyazdanpanah/php-ffmpeg-video-streaming/src/Process/Process.php(32): Streaming\Process\Process->getBinary(NULL)
#1 vendor/aminyazdanpanah/php-ffmpeg-video-streaming/src/MediaInfo/MediaInfo.php(29): Streaming\Process\Process->__construct('mediainfo')
#2 vendor/aminyazdanpanah/php-ffmpeg-video-streaming/src/StreamingAnalytics.php(62): Streaming\MediaInfo\MediaInfo::initialize('/var/www/html/s...', 'mediainfo')
#3 vendor/aminyazdanpanah/php-ffmpeg-video-streaming/src/StreamingAnalytics.php(46): Streaming\StreamingAnalytics->getOriginalMetadata()
#4 vendor/aminyazdanpanah/php-ffmpeg-video-streaming/src/Export.php(69): Streaming\StreamingAnalytics->analyse()
#5 app/Jobs/StreamviewCompressVideo.php(147): Streaming\Export->save()
#6 [internal function]: App\Jobs\StreamviewCompressVideo->handle()
#7 bootstrap/cache/compiled.php(1257): call_user_func_array(Array, Array)
#8 bootstrap/cache/compiled.php(9874): Illuminate\Container\Container->call(Array)
#9 [internal function]: Illuminate\Bus\Dispatcher->Illuminate\Bus{closure}(Object(App\Jobs\StreamviewCompressVideo))
#10 bootstrap/cache/compiled.php(9970): call_user_func(Object(Closure), Object(App\Jobs\StreamviewCompressVideo))
#11 [internal function]: Illuminate\Pipeline\Pipeline->Illuminate\Pipeline{closure}(Object(App\Jobs\StreamviewCompressVideo))
#12 bootstrap/cache/compiled.php(9948): call_user_func(Object(Closure), Object(App\Jobs\StreamviewCompressVideo))
#13 bootstrap/cache/compiled.php(9875): Illuminate\Pipeline\Pipeline->then(Object(Closure))
#14 vendor/laravel/framework/src/Illuminate/Queue/CallQueuedHandler.php(41): Illuminate\Bus\Dispatcher->dispatchNow(Object(App\Jobs\StreamviewCompressVideo))
#15 vendor/laravel/framework/src/Illuminate/Queue/Jobs/Job.php(130): Illuminate\Queue\CallQueuedHandler->call(Object(Illuminate\Queue\Jobs\RedisJob), Array)
#16 vendor/laravel/framework/src/Illuminate/Queue/Jobs/RedisJob.php(50): Illuminate\Queue\Jobs\Job->resolveAndFire(Array)
#17 vendor/laravel/framework/src/Illuminate/Queue/Worker.php(213): Illuminate\Queue\Jobs\RedisJob->fire()
#18 vendor/laravel/framework/src/Illuminate/Queue/Worker.php(156): Illuminate\Queue\Worker->process('redis', Object(Illuminate\Queue\Jobs\RedisJob), '0', '0')
#19 vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(125): Illuminate\Queue\Worker->pop('', 'default', '0', '3', '0')
#20 vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(78): Illuminate\Queue\Console\WorkCommand->runWorker('', 'default', '0', '128', false)
#21 [internal function]: Illuminate\Queue\Console\WorkCommand->fire()
#22 bootstrap/cache/compiled.php(1257): call_user_func_array(Array, Array)
#23 vendor/laravel/framework/src/Illuminate/Console/Command.php(169): Illuminate\Container\Container->call(Array)
#24 vendor/symfony/console/Command/Command.php(256): Illuminate\Console\Command->execute(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#25 vendor/laravel/framework/src/Illuminate/Console/Command.php(155): Symfony\Component\Console\Command\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#26 vendor/symfony/console/Application.php(794): Illuminate\Console\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#27 vendor/symfony/console/Application.php(186): Symfony\Component\Console\Application->doRunCommand(Object(Illuminate\Queue\Console\WorkCommand), Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#28 vendor/symfony/console/Application.php(117): Symfony\Component\Console\Application->doRun(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#29 vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(107): Symfony\Component\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#30 artisan(35): Illuminate\Foundation\Console\Kernel->handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#31 {main}

Desktop/Server (please complete the following information):

  • OS: Linux
  • Version Ubuntu 16
  • FFmpeg vesion 4.1.3

Allow Initial Parameters

Is your feature request related to a problem? Please describe.
php-ffmpeg allows you to set initial parameters now and the latest prerelease is using this version of php-ffmpeg but doesn't allow setting of the initial parameters.

Describe the solution you'd like
Ability to call setInitialParameters just as in php-ffmpeg

Describe alternatives you've considered
No other method of setting initial parameters such as -presets veryfast at the moment.

Additional context
Please see PHP-FFMpeg/PHP-FFMpeg#703

Warning: A non-numeric value encountered

This is my code

<?php

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

use Streaming\FFMpeg;

require 'includes/VideoLib/vendor/autoload.php';

$config = [
    'ffmpeg.binaries'  => 'C:\ffmpeg\bin\ffmpeg.exe',
    'ffprobe.binaries' => 'C:\ffmpeg\bin\ffprobe.exe',
    '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('video-log/ffmpeg-streaming.log')); // path to log file
    
$ffmpeg = FFMpeg::create($config, $log);
$video = $ffmpeg->open(ROOT_PATH . 'data\video\5986e0c173718d572df1dc57833cb8c8.mp4');

die;

I get errors like this.

image

This error appears when I add the following line of code:

$video = $ffmpeg->open(ROOT_PATH . 'data\video\5986e0c173718d572df1dc57833cb8c8.mp4');

Was I doing something wrong? How to fix this?

Take more time to convert to HLS

Thank you for the Great library :) This is not a Bug.

I tried to convert 389.4 MB, 30 Minutes mp4 file to hls on production server. It is take more than 1 hour to convert.

Is that issue with server or code? I use 4vCPU, 16GB RAM Cloud server. Is there any recommended specification for the server?

$config = [
            'timeout' => 0,
        ];
        $log = new Logger('FFmpeg_Streaming');
        $log->pushHandler(new StreamHandler('/logs/ffmpeg-streaming.log'));
        $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)));
        });

        $ffmpeg = FFMpeg::create($config, $log);
        $path = 'path/video.mp4';
        $save_path =  'path/'.$video_id.'.m3u8';

        $video = $ffmpeg->open($path);

        $reps = new AutoReps($video, $format, [360, 480, 720, 1080]);

        $video->hls()
            ->setFormat($format)
            ->setHlsTime(5) 
            ->setHlsAllowCache(false)
            ->addRepresentations($reps->getCalculatedReps())
            ->save($save_path);

How to use autoGenerateRepresentations

How to use autoGenerateRepresentations to create regular mp4 videos, not hls

like that:
$video = $ffmpeg->open ('video.mp4');
$video->autoGenerateRepresentations ([144,240])->save ();
?

CAN WE USE THIS ONE IN PRODUCTION

Hi Aminyazdanpanah,

Can we use this software in production environment and how it will get to know what is resolution of input file it got this automatically or we have to do that manually.

we want a open source software which detect the input stream and transcode the video into dash format automatically and after transcoding it will check media is transcoded or not successfully

[Question] Convert MP4 to HLS without transcoding

Hello,
I am trying to split mp4 to HLS without generate other representations just keep original encoding.
If use without autoGenerateRepresentations i get error Call to a member function getHeight() on bool

Does it work with audio-only files ?

Hi
Is there a way to convert audio-only file using HLS ?
I tried to do: $ffmpeg->open(input.mp3)->hls()->save(output.m3u8) but got an "Audio only accepts AudioFilterInterface filters" error

From ffmpeg binary, the command line is : "ffmpeg -i input.mp3 -options -f hls output.m3u8"

Thanks
Cyril

Update php-ffmpeg to 0.16

Is your feature request related to a problem? Please describe.
php-ffmpeg/php-ffmpeg released 0.16 version. When installing a new version in project, composer has a version conflict with php-ffmpeg-video-streaming

Describe the solution you'd like
Is it possible update to version 0.16?

width not divisible by 2

Describe the bug
#0:0 (h264 (native) -> h264 (libx264)) Press [q] to stop, [?] for help [libx264 @ 0x557aed4d1d20] width not divisible by 2 (577x324) Error initializing output stream 0:0 -- Error while opening encoder for output stream #0:0 - maybe incorrect parameters such as bit_rate, rate, width or height Conversion failed!

To Reproduce
Steps to reproduce the behavior:

  1. I used ->HLS() and ->autoGenerateRepresentations([]) on a video that had a width or height that wasn't an even number (in my case, 577x324).

Expected behavior
Properly encode video.

Desktop/Server (please complete the following information):

  • ffmpeg version 3.4.6-0ubuntu0.18.04.1

Additional context
I fixed the problem with the following code, which feels a little bit weird. Maybe you will come up with a better solution. Also note that I fixed a typo in the phpdoc:

/**
 * @param $k_bitrate
 * @param $width
 * @param $height
 * @return Representation
 * @throws InvalidArgumentException
 */
private function addRep($k_bitrate, $width, $height): Representation {
    $evenWidth = $this->roundUpToNextEvenNumber($width);
    $evenHeight = $this->roundUpToNextEvenNumber($height);
    return (new Representation)->setKiloBitrate($k_bitrate)->setResize($evenWidth, $evenHeight);
}

protected function roundUpToNextEvenNumber(float $input): int {//https://stackoverflow.com/a/34363542/
    $output = ceil($input); // Round up decimals to an integer
    if ($output % 2 == 1) {
        $output++; // If odd, add one
    }
    return $output;
}

https://www.google.com/search?q=ffmpeg+%22width+not+divisible+by+2%22 shows lots of people with this problem, but I didn't like any of the solutions I saw.

FFMpeg::create(array('timeout'=>0)) in mac generating wrong representations

Describe the bug

my ffmpeg with config
FFMpeg::create(array('timeout'=>0)) in mac


$video = $this->FFMpeg->open('stream/input/input.mp4');

            $video->hls()
                ->x264()
                ->encryption($save_to, $url)
                ->setFormat($format)
                ->setSegSubDirectory(self::$ts_folders)
                ->autoGenerateRepresentations(json_decode($streamRequest->resolutions, true))
                ->setHlsAllowCache(false)
                ->save(null , [$to]);

json_decode($streamRequest->resolutions, true) = [720, 360, 240]

resulting
in input.m3u8
input_240p.m3u8
input_360p.m3u8
input_540.m3u8 which is wrong

If i don't use array('timeout'=>0) in ffmpeg object process times out after 5 mins

To Reproduce
Steps to reproduce the behavior:

  1. Go to '/../...'
  2. On Line '...'
  3. The code '....'
  4. See error

Expected behavior
Please let me know how can give timeout to hls process and 540 files are generated instead of 720

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop/Server (please complete the following information):

  • OS: MAC
  • Version [10.15.3]
  • FFmpeg vesion [e.g. 4.1]

Additional context
Add any other context about the problem here.

Main playlists and other functions are broken after Update

It looks like that in new v1.2.1 Update, functions are not working anymore
No Multiple Qualities.
fragmentMP4() not working.
Playlist of any quality includes few segments only.
Cache control not working.
HLStime not working.

#EXTM3U
#EXT-X-VERSION:3
#EXT-X-TARGETDURATION:6
#EXT-X-MEDIA-SEQUENCE:22
#EXTINF:1.209622,
db_480p22.ts
#EXTINF:0.959356,
db_480p23.ts
#EXTINF:2.168978,
db_480p24.ts
#EXTINF:5.505867,
db_480p25.ts
#EXTINF:2.586089,
db_480p26.ts

Code:

$video->HLS() ->setFormat($format) ->fragmentedMP4() ->addRepresentations([$r_360p, $r_480p]) ->setHlsTime(10) ->setHlsAllowCache(false) ->save(BASEPATH.'output/db.m3u8');

Error while trying to convert mp4 file to hls larger than 1gb

Describe the bug
At first I thought it must be memory issue so I increase my instance memory to 3gb but still it's keep crashing. I am converting .mp4 file which has size of 1.3gb to hls format with r_480p.

Error Log

[47.247.29.52:49950-Q:A42210924CD33A09-9#wordpress] [STDERR] PHP Fatal error: Uncaught Symfony\Component\Process\Exception\ProcessTimedOutException: The process "'/usr/bin/ffmpeg' '-y' '-i' '/var/www/html/ffmpeg/1782829481.mp4' '-c:v' 'libx264' '-c:a' 'aac' '-bf' '1' '-keyint_min' '25' '-g' '250' '-sc_threshold' '40' '-hls_list_size' '0' '-hls_time' '10' '-hls_allow_cache' '1' '-hls_segment_type' 'mpegts' '-hls_fmp4_init_filename' '1782829481_480p_init.mp4' '-hls_segment_filename' '/tmp/php_ffmpeg_video_streaming/5ebb0032cee24/1782829481_480p_%04d.ts' '-s:v' '854x480' '-b:v' '750k' '-strict' '-2' '/tmp/php_ffmpeg_video_streaming/5ebb0032cee24/1782829481_480p.m3u8' '-c:v' 'libx264' '-c:a' 'aac' '-bf' '1' '-keyint_min' '25' '-g' '250' '-sc_threshold' '40' '-hls_list_size' '0' '-hls_time' '10' '-hls_allow_cache' '1' '-hls_segment_type' 'mpegts' '-hls_fmp4_init_filename' '1782829481_1080p_init.mp4' '-hls_segment_filename' '/tmp/php_ffmpeg_video_streaming/5ebb0032cee24/1782829481_1080p_%04d.ts' '-s:v' '1920x1080' '-b:v' '4096k' '-strict' '-2' '/tmp/php_ffmpeg_video_streaming/5ebb0032cee24/1 in /var/www/html/ffmpeg/vendor/alchemy/binary-driver/src/Alchemy/BinaryDriver/ProcessRunner.php on line 95
--

Delete hls segments automatically from time to time and PID fetching

I am working in a live stream solution and it is already working, there are two things that would be great: Cleaning automatically the hls segments so it doesnt clutter the server (Right now i am using a custom command) and i'd like to get the PID for each thread so i can control who stalls and who keeps on running so i can kill and relaunch the process.

Another thing that would be really useful is the ability to follow the execution status of the process but this i think i will contribute.

Will also add the nvenc settings for you.

Large File not encoded

My previous issue regarding to mkv extensions is solved. Thank you.
But now i have another issue. unfortunately encode stop. following error
will display.
An uncaught Exception was encountered

Type: FFMpeg\Exception\RuntimeException

Message: Encoding failed

Filename:
/home/mamimovies/public_html/mami_movies/vendor/php-ffmpeg/php-ffmpeg/src/FFMpeg/Media/AbstractVideo.php

Line Number: 106

Backtrace:

File:
/home/mamimovies/public_html/mami_movies/vendor/aminyazdanpanah/php-ffmpeg-video-streaming/src/Media.php
Line: 82
Function: call_user_func_array

File:
/home/mamimovies/public_html/mami_movies/vendor/aminyazdanpanah/php-ffmpeg-video-streaming/src/Export.php
Line: 59
Function: __call

File:
/home/mamimovies/public_html/mami_movies/application/controllers/Convert.php
Line: 50
Function: save

File: /home/mamimovies/public_html/mami_movies/index.php
Line: 292
Function: require_once

I have large file for i.g more then 1GB
My current code is following.

$filename= 'kasoor.mp4';
$v11=FCPATH.'assets/images/VCMobile/kasoor/'.$filename;
$foldername = pathinfo($filename, PATHINFO_FILENAME);
$newfile = FCPATH .'assets/images/VCMobile/'.$foldername.'/Leikhamton.m3u8';
$config = [
       'ffmpeg.binaries'  => '/usr/bin/ffmpeg',
       'ffprobe.binaries' => '/usr/bin/ffprobe',
       'timeout'          => 0, // The timeout for the underlying process
       'ffmpeg.threads'   => 12,   // The number of threads that FFMpeg should use
  ];
  $ffmpeg = Streaming\FFMpeg::create($config);
  $video = $ffmpeg->open($v11);
  $rep_2 = (new Representation())->setKiloBitrate(1024)->setResize(640 , 360);
  $video->HLS()
           ->X264()
           ->setHlsTime(10)
           ->addRepresentation($rep_2)
           ->setHlsAllowCache(false)
           ->save();
 echo "success";
 exit; 

I did't find any solution pls help me.
Thank You.

Change Files Permission to Public in Digital Ocean Cloud

Describe the bug
First of all thanks for the library. I'm facing one issue I'm uploading HLS in Digital Ocean Cloud but unfortunately files permission is private. How can I change it ? Please see below my code.

Code


$aws_cloud_upload_options = [
                    'dest' => $s3VideoPath,
                    'ACL'          => 'public-read'
                ];
                
                $to_aws_cloud = [
                    'cloud' => $aws_cloud,
                    'options' => $aws_cloud_upload_options
                ];

$ffmpegHLS = \Streaming\FFMpeg::create($config)
                    ->openFromCloud($from_aws_cloud)
                    ->HLS()
                    ->X264()
                    ->addRepresentation($rep_360)
                    ->addRepresentation($rep_480)
                    ->setHlsTime(5)
                    ->setHlsAllowCache(false);
                    $metadata = $ffmpegHLS->save(null, $to_aws_cloud);

composer.lock

-----> PHP app detected

! ERROR: No 'composer.lock' found!

!

! A 'composer.lock' file was not found in your project, but there

! is a 'composer.json' file with dependencies inside 'require'.

!

! The lock file is required in order to guarantee reliable and

! reproducible installation of dependencies across platforms and

! deploys. You must follow the Composer best practice of having

! your lock file under version control in order to deploy. The

! lock file must not be in your '.gitignore'.

!

! Please perform the following steps locally on your computer to

! resolve this issue before attempting another deploy:

! 1) remove 'composer.lock' from file '.gitignore', if present

! 2) if no 'composer.lock' exists, run 'composer update'

! 3) stage the lock file changes using 'git add composer.lock'

! 4) if you edited '.gitignore', also run 'git add .gitignore'

! 5) commit the change using 'git commit'

!

! Please remember to always keep your 'composer.lock' updated in

! lockstep with 'composer.json' to avoid common problems related

! to dependencies during collaboration and deployment.

!

! Please refer to the Composer documentation for further details:

! https://getcomposer.org/doc/

! https://getcomposer.org/doc/01-basic-usage.md

! Push rejected, failed to compile PHP app.

! Push failed

Hi can you please add composer.lock
Unfortunately i'm not familiar with composer.

The above error i got while deploying this repo to heroku.

Could not find tag for codec none in stream #0, codec not currently supported in container - incorrect codec parameters ?

Describe the bug
Trying to transcode an MP4 Video ( https://fuego-files.s3.eu-central-1.amazonaws.com/public/7c27c350565cf536a3de8f1e92c0448/23f6318b13cce446972ce1bf37df514/video/video.mp4 ) when I came across this error.

Edit: I have found that a similar/same error occurs when using this video ( https://fuego-files.s3.eu-central-1.amazonaws.com/public/2372b4ff89f01c95942243eb09572bd/d797b844073e642f966ed99a8ed64eb/video/video.mp4 ) which seems to be a HEVC video. Maybe that will help while debugging too.

I am using the code @aminyazdanpanah provided in Error #46 (thanks by the way!). Code works perfectly fine on most videos but I have been seeing some issues while batch processing videos and this is one I found that I cant find a fix for.

The ffmpeg command is:

ffmpeg '-y' '-i' 'video.mp4' '-bf' '1' '-keyint_min' '120' '-g' '120' '-sc_threshold' '0' '-b_strategy' '0' '-use_timeline' '1' '-use_template' '1' '-init_seg_name' 'video_init_$RepresentationID$.$ext$' '-media_seg_name' 'video_chunk_$RepresentationID$_$Number%05d$.$ext$' '-seg_duration' '2' '-hls_playlist' '1' '-f' 'dash' '-map' '0' '-b:v:0' '5075k' '-s:v:0' '640x360' '-map' '0' '-b:v:1' '6344k' '-s:v:1' '854x480' '-map' '0' '-b:v:2' '8458k' '-s:v:2' '1280x720' '-map' '0' '-b:v:3' '12688k' '-s:v:3' '1920x1080' '-c:v' 'libx264' '-strict' '-2' '/tmp/php_ffmpeg_video_streaming/video2.mpd'

Exact output that throws the error:

[mp4 @ 0x55f62b9bf580] Could not find tag for codec none in stream #0, codec not currently supported in container Could not write header for output file #0 (incorrect codec parameters ?): Invalid argument Error initializing output stream 0:12 --

To Reproduce

A) Use code from #46 and use the file i provided.
B) Download the provided video and use the ffmpeg command provided

Desktop/Server (please complete the following information):
ffmpeg version 4.2.2-1ubuntu118.04.sav0 Copyright (c) 2000-2019 the FFmpeg developers
built with gcc 7 (Ubuntu 7.5.0-3ubuntu1
18.04

Ideas about watermark

I made a watermark overlay, here:

abstract class Streaming extends Stream
{
    /** @var array */
    private $watermark = [];
    // ....
    /**
     * @var $watermarkPath string
     * @var $coordinates array
     * @return string
     */
    public function watermark($watermarkPath, array $coordinates = array()): Stream
    {
        $this->watermark = [
            'watermarkPath' => $watermarkPath,
            'coordinates' => $coordinates,
        ];
        return $this;
    }

    /**
     * @return array $watermark
     */
    public function getWatermark(): array
    {
        return $this->watermark;
    }
}
class HLSFilter extends FormatFilter
{
    //...
    /**
     * @param Representation $rep
     * @param bool $not_last
     */
    private function getArgs(Representation $rep, bool $not_last): void
    {
        $this->filter = array_merge(
            $this->filter,
            $this->getFormatOptions($this->hls->getFormat()),
            Utiles::arrayToFFmpegOpt($this->initArgs($rep)),
            Utiles::arrayToFFmpegOpt($this->hls->getAdditionalParams()),
            $this->watermarkCommand(), //-vf string
            ["-strict", $this->hls->getStrict()],
            $this->playlistPath($rep, $not_last)
        );
    }

    /**
     * @return array
     */
    protected function watermarkCommand()
    {
        $watermark = $this->hls->getWatermark();
        return $watermark ? Utiles::watermarkPosition($watermark) : [];
    }
}
class Utiles
{
    /**
     * @param array $watermark
     * @return array
     */
    public static function watermarkPosition($watermark)
    {
        $coordinates = $watermark['coordinates'];
        $watermarkPath = $watermark['watermarkPath'];
        $position = isset($coordinates['position']) ? $coordinates['position'] : 'absolute';

        switch ($position) {
            case 'relative':
                if (isset($coordinates['top'])) {
                    $y = $coordinates['top'];
                } elseif (isset($coordinates['bottom'])) {
                    $y = 'main_h - ' . $coordinates['bottom'] . ' - overlay_h';
                } else {
                    $y = 0;
                }

                if (isset($coordinates['left'])) {
                    $x = $coordinates['left'];
                } elseif (isset($coordinates['right'])) {
                    $x = 'main_w - ' . $coordinates['right'] . ' - overlay_w';
                } else {
                    $x = 0;
                }

                break;
            default:
                $x = isset($coordinates['x']) ? $coordinates['x'] : 0;
                $y = isset($coordinates['y']) ? $coordinates['y'] : 0;
                break;
        }

        return array(
            '-vf',
            'movie=' . $watermarkPath . ' [watermark]; [in][watermark] overlay=' . $x . ':' . $y . ' [out]',
        );
    }
}

using:

$ffmpeg_video->hls()
    ->watermark('wt.png', array(
        'position' => 'relative',
        'bottom' => 0,
        'right' => 0,
    ))
    ->x264()->addRepresentations([$representations])->save();

Do you have any ideas on how to improve / change this watermarking option?
and is my decision as a whole correct?
thank!

PHP Fatal error: Uncaught Alchemy\BinaryDriver\Exception\ExecutionFailureException: ffmpeg failed to execute command

Describe the bug
I get this error when I'm trying to convert mp4 video to encrypted hls video. This happens only with one video and not all of them.

PHP Fatal error: Uncaught Alchemy\BinaryDriver\Exception\ExecutionFailureException: ffmpeg failed to execute command '/usr/local/bin/ffmpeg' '-y' '-i' '/videos_source/video_filename.mp4' '-c:v' 'libx264' '-s:v' '426x240' '-crf' '20' '-sc_threshold' '0' '-g' '48' '-keyint_min' '48' '-hls_list_size' '0' '-hls_time' '10' '-hls_allow_cache' '1' '-b:v' '367k' '-maxrate' '440k' '-hls_segment_type' 'mpegts' '-hls_fmp4_init_filename' 'playlist_init.mp4' '-hls_segment_filename' '/videos_dist/video_filename.mp4/playlist_240p_%04d.ts' '-hls_key_info_file' '/tmp/php_ffmpeg_video_streaming/streamc7Prme' '-strict' '-2' '/videos_dist/video_filename.mp4/playlist_240p.m3u8' '-c:v' 'libx264' '-s:v' '853x480' '-crf' '20' '-sc_threshold' '0' '-g' '48' '-keyint_min' '48' '-hls_list_size' '0' '-hls_time' '10' '-hls_allow_cache' '1' '-b:v' '551k' '-maxrate' '661k' '-hls_segment_type' 'mpegts' '-hls_fmp4_init_filename' 'playl in vendor/aminyazdanpanah/php-ffmpeg-video-streaming/src/Stream.php on line 126

To Reproduce
Conversion Code:
$ffmpeg_config = [ 'timeout' => 0, // The timeout for the underlying process ]; $ffmpeg = FFMpeg::create($ffmpeg_config); $video = $ffmpeg->open($video_source_path); $video->HLS()->X264()->encryption($enc_key_save_to, $enc_key_url)->autoGenerateRepresentations([1080, 480, 240])->save($video_save_path.'/playlist.m3u8');

Desktop/Server (please complete the following information):

  • OS: Server
  • Version: CentOS 7.7 with cPanel.
  • FFmpeg vesion: ffmpeg version N-52056-ge5d25d1147-static

Additional context
And when I run the command directly from terminal it works fine.
/usr/local/bin/ffmpeg -y -i /videos_source/video_filename.mp4 -c:v libx264 -s:v 426x240 -crf 20 -sc_threshold 0 -g 48 -keyint_min 48 -hls_list_size 0 -hls_time 10 -hls_allow_cache 1 -b:v 367k -maxrate 440k -hls_segment_type mpegts -hls_fmp4_init_filename playlist_init.mp4 -hls_segment_filename /videos_dist/video_filename.mp4/playlist_240p_%04d.ts -hls_key_info_file /tmp/php_ffmpeg_video_streaming/streamc7Prme -strict -2 /videos_dist/video_filename.mp4/playlist_240p.m3u8 -c:v libx264 -s:v 853x480 -crf 20 -sc_threshold 0 -g 48 -keyint_min 48 -hls_list_size 0 -hls_time 10 -hls_allow_cache 1 -b:v 551k -maxrate 661k -hls_segment_type mpegts -hls_fmp4_init_filename playl

Unable to probe from mp4 link

I tried this code but I got an error saying unable to probe


       $upload=$episode->upload;
        $stream=new FTPStreamHelper($upload->file_path);
        $config = [
            'ffmpeg.binaries'  => 'F:/ffmpeg/bin/ffmpeg.exe',
            'ffprobe.binaries' => 'F:/ffmpeg/bin/ffprobe.exe',
        ];

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

        $video = $ffmpeg->open("http://techslides.com/demos/sample-videos/small.mp4");

        $video->dash()
            ->x264() // Format of the video. Alternatives: hevc() and vp9()
            ->autoGenerateRepresentations() // Auto generate representations
            ->save(public_path('video-stream.mpd')); // It can be passed a path to the method or it can be null

image

but when I try to do it manually in CMD, I think it seems fine

image

mkv file not encode.

Hello Sir,
i had use your repository for encoding videos, major file types are supported but mkv files are not supported.
it will show error like below.

An uncaught Exception was encountered
Type: Streaming\Exception\Exception

Message: Invalid stream

Filename: C:\wamp64\www\codeigniter\encode_test\vendor\aminyazdanpanah\php-ffmpeg-video-streaming\src\AutoRepresentations.php

Line Number: 59

Backtrace:

File: C:\wamp64\www\codeigniter\encode_test\vendor\aminyazdanpanah\php-ffmpeg-video-streaming\src\AutoRepresentations.php
Line: 70
Function: getKiloBitRate

File: C:\wamp64\www\codeigniter\encode_test\vendor\aminyazdanpanah\php-ffmpeg-video-streaming\src\Traits\Representation.php
Line: 57
Function: get

File: C:\wamp64\www\codeigniter\encode_test\application\controllers\Welcome.php
Line: 49
Function: autoGenerateRepresentations

File: C:\wamp64\www\codeigniter\encode_test\index.php
Line: 316
Function: require_once

my code is below

$config = [
		   	'ffmpeg.binaries'  => MYPATH.'ffmpeg.exe', // the path to the FFMpeg binary
            'ffprobe.binaries' => MYPATH.'ffprobe.exe', // the path to the FFProbe binary
		    'timeout'          => 3600000, // The timeout for the underlying process
		    'ffmpeg.threads'   => 12,   // The number of threads that FFMpeg should use
		    ];
		    
		$ffmpeg = Streaming\FFMpeg::create($config);
		
		$format = new Streaming\Format\X264();

		$format->on('progress', function ($video, $format, $percentage) {
		    echo "</br>$percentage% is transcoded\n";
		});

		$ffmpeg
		    ->open(MYPATH.'output\\sample.mkv')
		    ->HLS()
		    ->setFormat($format)
		    ->autoGenerateRepresentations([1080, 480, 360])
		    ->save(MYPATH.'output\\samplenew\\sample.m3u8');

i don't know how to fix pls help.
Thankx in Advance.

can we run this in cron alert

can we run this one on cron alert and it will automatically do all the things. can it automatically detect input video resolution and transcode the video according to predefined streams can we use widewine or any drm tool with this one please help me in this matter.

Tvheadend or similar input

Hi!

Thanks for the wonderful library,

i am working in a streaming project and getting input via tvheadend, then i have to stream it again using rtp protocol:

ffmpeg -i "http://@localhost:9981/stream/channelid/556832578" -vcodec libx264 -vb 500k -vprofile baseline -acodec mp2 -ac 2 -f rtp_mpegts rtp://192.168.99.205:1001

I don't think the video wrapper will be a problem, but the "rtp_mpegts" part worries me a little bit.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.