Debian 下使用 PHP 进行视频处理
一 方案总览
二 环境准备
三 方法一 使用 PHP-FFmpeg 库
<?php
require 'vendor/autoload.php';
use FFMpeg\FFMpeg;
use FFMpeg\Format\Video\X264;
use FFMpeg\Coordinate\TimeCode;
$ffmpeg = FFMpeg::create([
'ffmpeg.binaries' => '/usr/bin/ffmpeg',
'ffprobe.binaries' => '/usr/bin/ffprobe',
'timeout' => 3600,
]);
$video = $ffmpeg->open('/data/in.mp4');
// 转码为 H.264/AAC
$format = new X264();
$format->setAudioCodec('aac');
$video->save($format, '/data/out.mp4');
// 截取第10秒缩略图
$frame = $video->frame(TimeCode::fromSeconds(10));
$frame->save('/data/thumb.jpg');
四 方法二 使用 exec 调用 FFmpeg 命令行
<?php
$in = '/data/in.mp4';
$wm = '/data/logo.png';
$out = '/data/out_wm.mp4';
$pos = 'overlay=W-w-10:H-h-10'; // 右下角,距边10px
$cmd = sprintf(
'ffmpeg -y -i %s -i %s -filter_complex "[1]format=rgba,colorchannelmixer=aa=0.5[wm];[0][wm]%s" -c:a copy %s 2>&1',
escapeshellarg($in), escapeshellarg($wm), $pos, escapeshellarg($out)
);
exec($cmd, $lines, $ret);
if ($ret === 0) {
echo "Watermark OK: $out\n";
} else {
echo "FFmpeg failed:\n" . implode("\n", $lines) . "\n";
}
<?php
$in = '/data/in.mp4';
$dir = '/data/hls/';
$m3u8 = $dir . 'playlist.m3u8';
if (!is_dir($dir)) mkdir($dir, 0755, true);
$cmd = sprintf(
'ffmpeg -y -i %s -c:v libx264 -c:a aac -hls_time 10 -hls_list_size 0 '
. '-hls_segment_filename %s -f hls %s 2>&1',
escapeshellarg($in),
escapeshellarg($dir . 'seg_%03d.ts'),
escapeshellarg($m3u8)
);
exec($cmd, $lines, $ret);
echo $ret === 0 ? "HLS OK: $m3u8\n" : "FFmpeg failed:\n" . implode("\n", $lines) . "\n";
五 常见问题与优化
-hwaccel vaapi -i in.mp4 -c:v h264_vaapi out.mp4(需服务器与 FFmpeg 编译支持)。