当前位置:网站首页>Install ffmpeg in LNMP environment and use it in yii2
Install ffmpeg in LNMP environment and use it in yii2
2022-06-25 03:35:00 【Chafferer WANG】
1. Installation on server ffmpeg command
# 1. Enter command line mode , My system is Ubuntu kernel , Use apt-get install
apt-get install ffmpeg
# It seems to be slow to implement , I'm not sure if it's my network problem , Wait for installation to complete
# 2. Check... After installation ffmpeg and ffprobe Command location ,php You need to specify the location of these two commands in the code
which ffmpeg
which ffprobe
# The command position is generally in bin Next , I was in /usr/local/bin below , namely /usr/local/bin/ffmpeg and /usr/local/bin/ffprobe
2. Yii2 Install in composer package
composer require php-ffmpeg/php-ffmpeg
3. stay Yii2 The use of
1. Get the frame picture at the specified second position of the video
// 1. Create an object and specify the location of the command on the server
// Writing a : Go through step first 2 Get command location manually , Then fill in
$ffmpeg = \FFMpeg\FFMpeg::create([
'ffmpeg.binaries' => '/usr/local/bin/ffmpeg',
'ffprobe.binaries' => '/usr/local/bin/ffprobe',
]);
// Write two : Directly through the code exec Execute the command to get
$ffmpeg = \FFMpeg\FFMpeg::create([
'ffmpeg.binaries' => exec('which ffmpeg'),
'ffprobe.binaries' => exec('which ffprobe'),
]);
// 2. Specify the location of the video file on the server
$base_path = realpath(Yii::$app->getBasePath().'/../');// Here I get the root directory pointed to by the domain name , It can be modified according to your actual situation
$video = $ffmpeg->open($base_path.'/1655958237.mp4');
// 3. Specify the number of seconds for the video frame to be acquired , For example, get the first second
$frame = $video->frame(\FFMpeg\Coordinate\TimeCode::fromSeconds(1));
//4. Save video frame pictures , be known as 1.jpg
$frame->save($base_path.'/1.jpg');
Complete code
try {
$ffmpeg = \FFMpeg\FFMpeg::create([
'ffmpeg.binaries' => exec('which ffmpeg'),
'ffprobe.binaries' => exec('which ffprobe'),
]);
$base_path = realpath(Yii::$app->getBasePath().'/../');
$video = $ffmpeg->open($base_path.'/1655958237.mp4');
$frame = $video->frame(\FFMpeg\Coordinate\TimeCode::fromSeconds(1));
$frame->save($base_path.'/1.jpg');
echo ' To be successful ';
} catch(\Exception $e) {
echo ' Acquisition failure '.$e->getMessage();
}
ffmpeg Other functions of
Be careful ️: I haven't actually applied the following functions ,
Direct reference to the content of this website https://github.com/PHP-FFMpeg/PHP-FFMpeg
transcoding
You can use the FFMpeg\Media\Video:save
Methods transcode the video . You will pass on a FFMpeg\Format\FormatInterface
.
Please note that , Audio and video bit rates are set in format . You can set the kilobit rate to 0 To disable this -b:v Options .
$format = new FFMpeg\Format\Video\X264();
$format->on('progress', function ($video, $format, $percentage) {
echo "$percentage % transcoded";
});
$format
->setKiloBitrate(1000)
->setAudioChannels(2)
->setAudioKiloBitrate(256);
$video->save($format, 'video.avi');
Extracting images FFMpeg\Media\Video::frame
You can use this method to extract frames at any time code .
This code returns FFMpeg\Media\Frame
Corresponds to the second 42 Example . You can put any FFMpeg\Coordinate\TimeCode
Pass as a parameter , Please refer to the dedicated documentation below for more information .
$frame = $video->frame(FFMpeg\Coordinate\TimeCode::fromSeconds(42));
$frame->save('image.jpg');
If you want to extract multiple images from the video , The following filters can be used :
$video
->filters()
->extractMultipleFrames(FFMpeg\Filters\Video\ExtractMultipleFramesFilter::FRAMERATE_EVERY_10SEC, '/path/to/destination/folder/')
->synchronize();
$video
->save(new FFMpeg\Format\Video\X264(), '/path/to/new/file');
By default , This saves the frame as jpg Images .
You can use setFrameFileType Save the frame in another format to overwrite it :
$frameFileType = 'jpg'; // either 'jpg', 'jpeg' or 'png'
$filter = new ExtractMultipleFramesFilter($frameRate, $destinationFolder);
$filter->setFrameFileType($frameFileType);
$video->addFilter($filter);
Clip
Cut the video at the desired point . Use input search method . It is faster than using filter clips .
$clip = $video->clip(FFMpeg\Coordinate\TimeCode::fromSeconds(30), FFMpeg\Coordinate\TimeCode::fromSeconds(15));
$clip->save(new FFMpeg\Format\Video\X264(), 'video.avi');
The clip filter has two parameters :
$start, An example of FFMpeg\Coordinate\TimeCode, Specifies the start point of the clip
$duration, Optional , An example of FFMpeg\Coordinate\TimeCode, Specify the duration of the clip
On the clip , You can apply the same filters as the video . For example, resize filter .
$clip = $video->clip(FFMpeg\Coordinate\TimeCode::fromSeconds(30), FFMpeg\Coordinate\TimeCode::fromSeconds(15));
$clip->filters()->resize(new FFMpeg\Coordinate\Dimension(320, 240), FFMpeg\Filters\Video\ResizeFilter::RESIZEMODE_INSET, true);
$clip->save(new FFMpeg\Format\Video\X264(), 'video.avi');
Generate waveform
FFMpeg\Media\Audio::waveform You can use this method to generate the waveform of the audio file .
This code returns a FFMpeg\Media\Waveform example . You can choose to pass the dimension as the first two parameters and the hexadecimal string color array for ffmpeg For waveforms , For more information , Please refer to the dedicated documentation below .
The output file must use PNG Extension .
$waveform = $audio->waveform(640, 120, array('#00FF00'));
$waveform->save('waveform.png');
If you want to get the waveform from the video , Please convert it to audio file first .
// Open your video file
$video = $ffmpeg->open( 'video.mp4' );
// Set an audio format
$audio_format = new FFMpeg\Format\Audio\Mp3();
// Extract the audio into a new file as mp3
$video->save($audio_format, 'audio.mp3');
// Set the audio file
$audio = $ffmpeg->open( 'audio.mp3' );
// Create the waveform
$waveform = $audio->waveform();
$waveform->save( 'waveform.png' );
filter
FFMpeg\Media\Video You can use the FFMpeg\Media\Video::addFilter Method to apply a filter . Video accepts audio and video filters .
You can build your own filters , Some filters are tied to PHP-FFMpeg in - They can be passed through the FFMpeg\Media\Video::filters Method access .
Filters are linkable
$video
->filters()
->resize($dimension, $mode, $useStandards)
->framerate($framerate, $gop)
->synchronize();
rotate
Rotate the video to a given angle .
v i d e o − > f i l t e r s ( ) − > r o t a t e ( video->filters()->rotate( video−>filters()−>rotate(angle);
$angle The parameter must be one of the following constants :
FFMpeg\Filters\Video\RotateFilter::ROTATE_90: 90° Clockwise
FFMpeg\Filters\Video\RotateFilter::ROTATE_180: 180°
FFMpeg\Filters\Video\RotateFilter::ROTATE_270: 90° Anti-clockwise
Resize
Resize the video to the given size .
$video->filters()->resize($dimension, $mode, $useStandards);
The resizing filter takes three parameters :
$dimension, An example of FFMpeg\Coordinate\Dimension
$mode, constant FFMpeg\Filters\Video\ResizeFilter::RESIZEMODE_* One of the constants
$useStandards, A Boolean value , Enforce the closest aspect ratio criterion .
If you want non-standard video , You can use the fill filter to resize the video to the desired size , And wrap it into a black strip .
$video->filters()->pad($dimension);
pad The filter takes a parameter :
$dimension, An example of FFMpeg\Coordinate\Dimension
Don't forget to save it later .
$video->save(new FFMpeg\Format\Video\X264(), $new_file);
watermark
Use the given image to watermark the video .
$video
->filters()
->watermark($watermarkPath, array(
'position' => 'relative',
'bottom' => 50,
'right' => 50,
));
The watermark filter has two parameters :
$watermarkPath, The path to your watermark file . $coordinates, An array , Define how you want to locate the watermark . You can use the relative positioning or absolute positioning demonstrated above :
$video
->filters()
->watermark($watermarkPath, array(
'position' => 'absolute',
'x' => 1180,
'y' => 620,
));
Frame rate
Change the frame rate of the video .
$video->filters()->framerate($framerate, $gop);
The frame rate filter has two parameters :
$framerate, An example of FFMpeg\Coordinate\FrameRate
$gop, One GOP value ( Integers )
Sync
Synchronize audio and video .
Some containers may use delays that cause output to be out of sync . This filter solves this problem .
$video->filters()->synchronize();
Clip
Cut the video at the desired point .
$video->filters()->clip(FFMpeg\Coordinate\TimeCode::fromSeconds(30), FFMpeg\Coordinate\TimeCode::fromSeconds(15));
The clip filter has two parameters :
$start, An example of FFMpeg\Coordinate\TimeCode, Specifies the start point of the clip
$duration, Optional , An example of FFMpeg\Coordinate\TimeCode, Specify the duration of the clip
Crops
According to width and height (a Point) Clip video
$video->filters()->crop(new FFMpeg\Coordinate\Point("t*100", 0, true), new FFMpeg\Coordinate\Dimension(200, 600));
It requires two parameters :
$point, An example of FFMpeg\Coordinate\Point, Specify the point to crop
$dimension, An example of FFMpeg\Coordinate\Dimension, Specify the dimension of the output video
The voice
FFMpeg\Media\Audio You can also transcode , namely : Change codec , Isolate audio or video . You can extract frames .
transcoding
You can use this method to transcode audio FFMpeg\Media\Audio:save. You will pass on a FFMpeg\Format\FormatInterface.
Please note that , The audio kilobit rate is set in the audio format .
$ffmpeg = FFMpeg\FFMpeg::create();
$audio = $ffmpeg->open('track.mp3');
$format = new FFMpeg\Format\Audio\Flac();
$format->on('progress', function ($audio, $format, $percentage) {
echo "$percentage % transcoded";
});
$format
->setAudioChannels(2)
->setAudioKiloBitrate(256);
$audio->save($format, 'track.flac');
It can monitor the transcoding progress in real time , For more information , Please refer to the format document below .
filter
FFMpeg\Media\Audio You can use the FFMpeg\Media\Audio::addFilter Method to apply a filter . It only accepts audio filters .
You can build your own filters , Some filters are tied to PHP-FFMpeg in - They can be passed through the FFMpeg\Media\Audio::filters Method access .
Tailoring
Cut the audio at the desired point .
$audio->filters()->clip(FFMpeg\Coordinate\TimeCode::fromSeconds(30), FFMpeg\Coordinate\TimeCode::fromSeconds(15));
Metadata
Add metadata to audio file . Just pass the keys for all the metadata you want to add = Value to array . If no parameters are passed to the filter , All metadata will be deleted from the input file . The currently supported data is title 、 The artist 、 Album 、 The artist 、 composer 、 song 、 year 、 describe 、 Artwork
$audio->filters()->addMetadata(["title" => "Some Title", "track" => 1]);
//remove all metadata and video streams from audio file
$audio->filters()->addMetadata();
Add artwork to audio file
$audio->filters()->addMetadata([“artwork” => “/path/to/image/file.jpg”]);
Be careful : at present ffmpeg( edition 3.2.2) Support only .mp3 Draft output of documents
Resampling
Resample audio files .
$audio->filters()->resample($rate);
The resample filter has two parameters :
$rate, A valid audio sample rate value ( Integers )
frame
A frame is an image on the video time code ; Please refer to the above documentation on frame extraction .
FFMpeg\Media\Frame::save You can use this method to save frames .
$frame->save('target.jpg');
This method has a second optional Boolean parameter . Set it to true To get an accurate image ; Execution takes more time .
Moving graph
gif Is an animated image extracted from a video sequence .
FFMpeg\Media\Gif::save You can use this method to save gif file .
$video = $ffmpeg->open( '/path/to/video' );
$video
->gif(FFMpeg\Coordinate\TimeCode::fromSeconds(2), new FFMpeg\Coordinate\Dimension(640, 480), 3)
->save($new_file);
This method has a third optional Boolean parameter , The duration of the animation . If you don't set it , You will get a fixed gif Images .
cascade
This feature allows you to generate an audio or video file based on multiple sources .
There are two ways to connect videos , It depends on the codec of the source . If your sources are all encoded with the same codec , You will want to use FFMpeg\Media\Concatenate::saveFromSameCodecs Better performance . If your source is already encoded with a different codec , You will need to use FFMpeg\Media\Concatenate::saveFromDifferentCodecs.
The first function will use the initial codec as the codec for the generated file . Use the second function , You will be able to select the required codec for the generated file .
You also need to pay attention to , When using saveFromDifferentCodecs When the method is used , Your files must have video and audio streams .
In both cases , You must provide a set of files .
To connect a video encoded with the same codec , Do the following :
// In order to instantiate the video object, you HAVE TO pass a path to a valid video file.
// We recommend that you put there the path of any of the video you want to use in this concatenation.
$video = $ffmpeg->open( '/path/to/video' );
$video
->concat(array('/path/to/video1', '/path/to/video2'))
->saveFromSameCodecs('/path/to/new_file', TRUE);
Saving Boolean parameters of a function allows you to use duplicate parameters , This greatly accelerates the generation of encoded files .
To connect videos encoded with different codecs , Do the following :
// In order to instantiate the video object, you HAVE TO pass a path to a valid video file.
// We recommend that you put there the path of any of the video you want to use in this concatenation.
$video = $ffmpeg->open( '/path/to/video' );
$format = new FFMpeg\Format\Video\X264();
$format->setAudioCodec("libmp3lame");
$video
->concat(array('/path/to/video1', '/path/to/video2'))
->saveFromDifferentCodecs($format, '/path/to/new_file');
of FFMPEG More details on concatenation in , See here 、 Here and here .
Advanced media
AdvancedMedia There may be multiple inputs and multiple outputs .
This class has been developed primarily for use with -filter_complex.
therefore , its filters() Method can only be accepted in -filter_complex Filter used internally by the command .AdvancedMedia Some built-in filters have been included .
Basic use
for example :
$advancedMedia = $ffmpeg->openAdvanced(array('video_1.mp4', 'video_2.mp4'));
$advancedMedia->filters()
->custom('[0:v][1:v]', 'hstack', '[v]');
$advancedMedia
->map(array('0:a', '[v]'), new X264('aac', 'libx264'), 'output.mp4')
->save();
This code uses 2 Input video , Stack them horizontally on 1 Of the output videos , And add the audio of the first video to this new video .( For only 1 Inputs and only 1 A simple filter graph of outputs is not possible ).
Complex examples
AdvancedMedia A more difficult example of possibility . Consider that all input videos already have the same resolution and duration .(“xstack” The filter is already in 4.1 Version of ffmpeg Add ).
$inputs = array(
'video_1.mp4',
'video_2.mp4',
'video_3.mp4',
'video_4.mp4',
);
$advancedMedia = $ffmpeg->openAdvanced($inputs);
$advancedMedia->filters()
->custom('[0:v]', 'negate', '[v0negate]')
->custom('[1:v]', 'edgedetect', '[v1edgedetect]')
->custom('[2:v]', 'hflip', '[v2hflip]')
->custom('[3:v]', 'vflip', '[v3vflip]')
->xStack('[v0negate][v1edgedetect][v2hflip][v3vflip]', XStackFilter::LAYOUT_2X2, 4, '[resultv]');
$advancedMedia
->map(array('0:a'), new Mp3(), 'video_1.mp3')
->map(array('1:a'), new Flac(), 'video_2.flac')
->map(array('2:a'), new Wav(), 'video_3.wav')
->map(array('3:a'), new Aac(), 'video_4.aac')
->map(array('[resultv]'), new X264('aac', 'libx264'), 'output.mp4')
->save();
This code uses 4 Input video , Then reverse the first video , Store the results in [v0negate] Streaming , Detect edges in the second video , Store the results in [v1edgedetect] Streaming , Flip the third video horizontally , Store the results in [v2hflip] Streaming , Flip the fourth video vertically , Store results in [v3vflip] Streaming , And then 4 The generated flows are merged into one 2x2 Collage video . Then save the audio in the original video as 4 Different formats , And save the generated collage video to a separate file .
As you can see , You can be in a ffmpeg Command to get multiple input sources , Perform complex processing on them and generate multiple output files at the same time .
Give me a map !
You do not have to use -filter_complex. You can only use -map Options . for example , Just extract the audio from the video :
$advancedMedia = $ffmpeg->openAdvanced(array('video.mp4'));
$advancedMedia
->map(array('0:a'), new Mp3(), 'output.mp3')
->save();
customized
if necessary , You can additionally customize AdvancedMedia Result ffmpeg command :
$advancedMedia = $ffmpeg->openAdvanced($inputs);
$advancedMedia
->setInitialParameters(array('the', 'params', 'that', 'will', 'be', 'added', 'before', '-i', 'part', 'of', 'the', 'command'))
->setAdditionalParameters(array('the', 'params', 'that', 'will', 'be', 'added', 'at', 'the', 'end', 'of', 'the', 'command'));
Format
A format implementation FFMpeg\Format\FormatInterface. To save to a video file , Please use FFMpeg\Format\VideoInterface and FFMpeg\Format\AudioInterface For audio files .
The format can also be extended FFMpeg\Format\ProgressableInterface To get real-time information about transcoding .
The predefined format already provides progress information as an event .
$format = new FFMpeg\Format\Video\X264();
$format->on('progress', function ($video, $format, $percentage) {
echo "$percentage % transcoded";
});
$video->save($format, 'video.avi');
The callback provided for an event can be any callable .
Add additional parameters
You can add other parameters to the encoding request according to the video format .
setAdditionalParameters The parameter of the method is an array .
$format = new FFMpeg\Format\Video\X264();
$format->setAdditionalParameters(array('foo', 'bar'));
$video->save($format, 'video.avi');
Add initial parameters
You can also add initial parameters to the encoding request according to the video format . This is covering FFMpeg The default input codec in is especially convenient .
setInitialParameters The parameter of the method is an array .
$format = new FFMpeg\Format\Video\X264();
$format->setInitialParameters(array('-acodec', 'libopus'));
$video->save($format, 'video.avi');
Create your own format
The easiest way to create a format is to extend the summary FFMpeg\Format\Video\DefaultVideo and FFMpeg\Format\Audio\DefaultAudio. And implement the following methods .
class CustomWMVFormat extends FFMpeg\Format\Video\DefaultVideo
{
public function __construct($audioCodec = 'wmav2', $videoCodec = 'wmv2')
{
$this
->setAudioCodec($audioCodec)
->setVideoCodec($videoCodec);
}
public function supportBFrames()
{
return false;
}
public function getAvailableAudioCodecs()
{
return array('wmav2');
}
public function getAvailableVideoCodecs()
{
return array('wmv2');
}
}
coordinate
FFMpeg Many units are used to represent time and space coordinates .
FFMpeg\Coordinate\AspectRatio Represents aspect ratio .
FFMpeg\Coordinate\Dimension Represents a dimension .
FFMpeg\Coordinate\FrameRate Represents the frame rate .
FFMpeg\Coordinate\Point Represents a point .( since v0.10.0 It supports dynamic integration )
FFMpeg\Coordinate\TimeCode Represents a time code .
FFP probe
FFMpeg\FFProbe Be inside FFMpeg\FFMpeg Used to detect media . You can also use it to extract media metadata .
$ffprobe = FFMpeg\FFProbe::create();
$ffprobe
->streams('/path/to/video/mp4') // extracts streams informations
->videos() // filters video streams
->first() // returns the first video stream
->get('codec_name'); // returns the codec_name property
$ffprobe = FFMpeg\FFProbe::create();
$ffprobe
->format('/path/to/video/mp4') // extracts file informations
->get('duration'); // returns the duration property
Verify media files
( from 0.10.0 Start ) You can use PHP-FFMpeg Of FFProbe The wrapper verifies the media file .
$ffprobe = FFMpeg\FFProbe::create();
$ffprobe->isValid('/path/to/file/to/check'); // returns bool
边栏推荐
- XML modeling
- 在线股票开户安全吗?
- MATLAB主窗口与编辑器窗口分开为两个界面的解决办法
- 用向量表示两个坐标系的变换
- Is it safe to open an account in the way of winning 100% of the new bonds
- C#实现水晶报表绑定数据并实现打印
- AOSP ~ WIFI架构总览
- Is it reliable for CITIC Securities to open a mobile account? Is it safe?
- MySQL learning notes -- addition, deletion, modification and query on a single table
- TCC mode explanation and code implementation of Seata's four modes
猜你喜欢
Getting started with unityshader Essentials - PBS physics based rendering
CUDA编程入门极简教程
XML modeling
How transformers Roberta adds tokens
Refresh mechanism of vie
保险也能拼购?个人可以凑够人数组团购买医疗保险的4大风险
Expressing the transformation of two coordinate systems with vectors
后台页制作01《ivx低代码签到系统制作》
大咖说*计算讲谈社|如何提出关键问题?
MySql安装教程
随机推荐
好用的字典-defaultdict
202112-2 序列查询新解
Error log format and precautions
Skywalking implements cross thread trace delivery
Doak CMS article management system recommendation
C语言数组与结构体指针
How can novices of cross-border e-commerce prevent store association? What tool is good?
Leecode learning notes - the shortest path for a robot to reach its destination
Administrator如何禁止另一个人踢掉自己?
MySQL modifies and deletes tables in batches according to the table prefix
Is it safe to open an account online? Online and other answers
Two way combination of business and technology to build a bank data security management system
Can the polardb database be connected to the data source through MySQL
36岁前亚马逊变性黑客,窃取超1亿人数据被判20年监禁!
自动化测试
做自媒体不知道怎样变现?7大变现方法分享
mysql学习笔记--单张表上的增删改查
14 bs对象.节点名称.name attrs string 获取节点名称 属性 内容
[proteus simulation] Arduino uno+ nixie tube display 4X4 keyboard matrix keys
VSCode中如何实现点击DOM自动定位到相应代码行