pack-vid/pack-vid

249 lines
6.5 KiB
PHP
Executable File

#!/usr/bin/env php
<?php
// Squishes given video input into sub-4000kb .mp4
// Crops or pads to 16:9 (crop default; --letterbox to pad)
// Strips audio (to override, pass --audio for 96 kbps AAC)
// HDR to SDR tonemapping
// Picks bitrate to match
// Picks resolution based on bitrate target
// 2-pass encoding with libx264 veryslow
$args = $_SERVER['argv'];
$self = array_shift( $args );
$maxBytes = 4000 * 1000; // fit in 4MB
$maxBytes = $maxBytes * 7 / 8; // leave some headroom
$options = [
'letterbox' => false,
'audio' => false,
'exposure' => '0',
'peak' => '10000',
'fps' => '60',
'size' => $maxBytes,
];
while ( count( $args ) > 0 && substr( $args[0], 0, 2 ) == '--' ) {
$option = substr( array_shift( $args ), 2 );
$parts = explode( '=', $option, 2 );
if ( count( $parts ) == 2 ) {
[ $key, $val ] = $parts;
$options[$key] = $val;
} else {
$options[$option] = true;
}
}
if ( count ( $args ) < 2 ) {
die(
"Usage: $self [options...] <srcfile.mp4> <destfile.mp4>\n" .
"Options:\n" .
" --letterbox pad instead of cropping\n" .
" --audio include audio\n" .
" --exposure=n adjust exposure\n" .
" --peak=n set HDR peak nits\n" .
" --fps=n frame rate limit\n" .
" --size=n target file size in bytes (default 3.5M)\n"
);
}
[ $src, $dest ] = $args;
convert( $src, $dest, $options );
exit(0);
//
function run( $cmd, $args ) {
$commandLine = implode( ' ',
array_merge(
[ escapeshellcmd( $cmd ) ],
array_map( 'escapeshellarg', $args )
)
);
echo "$commandLine\n";
$output = shell_exec( $commandLine );
if ( $output === false ) {
throw new Error( "Failed to run $cmd" );
}
return $output;
}
function ffprobe( $path ) {
$output = run( 'ffprobe', [
'-hide_banner',
'-show_format',
'-show_streams',
'-print_format',
'json',
'--',
$path
] );
$data = json_decode( $output );
if ( $data === null ) {
throw new Error( "Failed to read JSON from ffprobe: $output" );
}
return $data;
}
function evenize( $n ) {
$n = ceil( $n );
if ( $n & 1 ) {
$n++;
}
return $n;
}
function sizify( $str ) {
$matches = [];
if ( preg_match( '/^(\d+(?:\.\d+)?)([kmgt]?)$/i', $str, $matches ) ) {
[ , $digits, $suffix ] = $matches;
$n = floatval( $digits );
switch ( strtolower( $suffix ) ) {
case 't': $n *= 1000; // fall through
case 'g': $n *= 1000; // fall through
case 'm': $n *= 1000; // fall through
case 'k': $n *= 1000; // fall through
default: return $n;
}
return $n;
}
die( "Unexpected size format '$str'\n" );
}
function convert( $src, $dest, $options ) {
$maxBits = 8 * sizify( $options['size'] );
$probe = ffprobe( $src );
$videoTracks = array_values(
array_filter( $probe->streams, function ( $stream ) {
return $stream->codec_type === 'video';
} )
);
if ( count( $videoTracks ) == 0 ) {
var_dump( $probe );
die("oh no\n");
}
$track = $videoTracks[0];
$duration = floatval( $track->duration );
$width = $track->width;
$height = $track->height;
$hdr = $track->color_primaries === 'bt2020';
$keyframeInt = ceil( $duration * 60 );
$bitrate = floor( $maxBits / $duration );
if ( $options[ 'audio' ] ) {
$audioBitrate = 96 * 1000;
$audio = [ '-b:a', $audioBitrate ];
$bitrate -= $audioBitrate;
} else {
$audio = [ '-an' ];
}
$mbits = 1000 * 1000;
if ( $bitrate < $mbits || $height < 480 ) {
$frameWidth = 640;
$frameHeight = 360;
} elseif ( $bitrate < 2 * $mbits || $height < 720) {
$frameWidth = 854;
$frameHeight = 480;
} elseif ( $bitrate < 4 * $mbits || $height < 1080) {
$frameWidth = 1280;
$frameHeight = 720;
} else {
$frameWidth = 1920;
$frameHeight = 1080;
}
$aspect = $width / $height;
$wide = $aspect > ( $frameWidth / $frameHeight );
$pad = boolval( $options['letterbox'] );
if ( $pad ) {
if ( $wide ) {
$scaleWidth = $frameWidth;
$scaleHeight = evenize( $frameWidth / $aspect );
} else {
$scaleHeight = $frameHeight;
$scaleWidth = evenize( $frameHeight * $aspect );
}
} else {
if ( $wide ) {
$scaleHeight = $frameHeight;
$scaleWidth = evenize( $frameHeight * $aspect );
} else {
$scaleWidth = $frameWidth;
$scaleHeight = evenize( $frameWidth / $aspect );
}
}
$exposure = floatval( $options['exposure'] );
$peakNits = floatval( $options['peakNits'] );
$sdrNits = 80;
$peak = $peakNits / $sdrNits;
$filters = [ "scale=w=$scaleWidth:h=$scaleHeight" ];
if ( $hdr ) {
$filters[] = "zscale=t=linear:p=bt709";
if ( $exposure ) {
$filters[] = "exposure=$exposure";
}
$filters[] = "tonemap=hable:peak=$peak";
$filters[] = "zscale=t=bt709:m=bt709:r=full";
}
$filters[] = "format=yuv420p";
if ( $options['letterbox'] ) {
$offsetX = round( ( $frameWidth - $scaleWidth) / 2 );
$offsetY = round( ( $frameHeight - $scaleHeight) / 2 );
$filters[] = "pad=w=$frameWidth:h=$frameHeight:x=$offsetX:y=$offsetY";
} else {
$filters[] = "crop=w=$frameWidth:h=$frameHeight";
}
$vf = implode( ',', $filters );
$fps = $options['fps'];
// $preset = 'veryslow'; // annoying at higher resolutions
$preset = 'slow';
$passlog = tempnam( '.', 'pack-vid-passlog' );
run( 'ffmpeg',
array_merge( [
'-i', $src,
'-f', 'mp4',
'-fpsmax', $fps,
'-vf', $vf,
'-c:v', 'libx264',
'-b:v', $bitrate,
'-preset', $preset,
'-pass', '1',
'-passlogfile', $passlog,
'-g', $keyframeInt,
], $audio, [
'-y', '/dev/null'
] )
);
run( 'ffmpeg',
array_merge( [
'-i', $src,
'-vf', $vf,
'-fpsmax', $fps,
'-c:v', 'libx264',
'-b:v', $bitrate,
'-preset', $preset,
'-pass', '2',
'-passlogfile', $passlog,
'-g', $keyframeInt,
], $audio, [
'-movflags', '+faststart',
'-y', $dest
] )
);
}