pack-vid/pack-vid

355 lines
10 KiB
Plaintext
Raw Normal View History

2023-01-15 01:20:35 +00:00
#!/usr/bin/env php
<?php
2023-01-15 03:16:50 +00:00
// Squishes given video input into sub-4000kb .mp4
2023-04-10 02:23:42 +00:00
// Crops or pads to 16:9 (letterbox default; --crop to crop)
// Includes stereo audio (to strip, pass --no-audio)
2023-01-15 03:16:50 +00:00
// HDR to SDR tonemapping
2023-01-15 01:20:35 +00:00
// Picks bitrate to match
// Picks resolution based on bitrate target
// 2-pass encoding with libx264 veryslow
2023-05-01 16:37:02 +00:00
// fps limiter: warning requires newer ffmpeg than debian-buster
2023-01-15 01:20:35 +00:00
$args = $_SERVER['argv'];
$self = array_shift( $args );
2023-03-26 18:36:46 +00:00
$maxBytes = 4000 * 1000; // fit in 4MB
2023-04-05 01:52:34 +00:00
$maxBytes = $maxBytes * 15 / 16; // leave some headroom
2023-03-26 18:36:46 +00:00
2023-01-15 18:25:47 +00:00
$options = [
2023-04-10 02:23:42 +00:00
'crop' => false,
2023-04-25 04:24:51 +00:00
'letterbox' => false,
2023-04-10 02:23:42 +00:00
'no-audio' => false,
2023-04-23 01:28:27 +00:00
'exposure' => '0', // stops
2023-04-21 04:51:24 +00:00
'peak' => '1000', // '10000' is max
2023-04-23 22:14:27 +00:00
'preset' => 'medium',
2023-04-22 00:57:03 +00:00
'fps' => '60000/1001',
2023-03-26 18:36:46 +00:00
'size' => $maxBytes,
2023-04-21 04:51:24 +00:00
'quality' => 1.0,
2023-05-16 19:14:49 +00:00
'hdr' => false,
2023-05-28 00:04:17 +00:00
'dither' => false,
2023-01-15 18:25:47 +00:00
];
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;
}
2023-01-15 18:25:47 +00:00
}
2023-01-15 01:20:35 +00:00
if ( count ( $args ) < 2 ) {
2023-01-15 18:25:47 +00:00
die(
"Usage: $self [options...] <srcfile.mp4> <destfile.mp4>\n" .
"Options:\n" .
2023-04-25 04:24:51 +00:00
" --crop crop to 16:9\n" .
" --letterbox pad to 16:9\n" .
2023-04-10 02:23:42 +00:00
" --no-audio strip audio\n" .
" --exposure=n adjust exposure\n" .
" --peak=n set HDR peak nits\n" .
2023-04-23 18:46:50 +00:00
" --preset=key set h.264 encoding preset\n" .
2023-03-26 18:36:46 +00:00
" --fps=n frame rate limit\n" .
" --size=n target file size in bytes (default 3.5M)\n" .
2023-05-16 19:14:49 +00:00
" --quality=n fraction of base bitrate to break on (deafult 0.75)\n" .
2023-05-28 00:04:17 +00:00
" --hdr force HDR input processing on\n" .
" --dither enable dithering in 8-bit downconversion\n"
2023-01-15 18:25:47 +00:00
);
2023-01-15 01:20:35 +00:00
}
[ $src, $dest ] = $args;
2023-01-15 18:25:47 +00:00
convert( $src, $dest, $options );
2023-01-15 01:20:35 +00:00
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 ) {
2023-05-16 19:14:49 +00:00
$n = round( $n );
2023-01-15 01:20:35 +00:00
if ( $n & 1 ) {
$n++;
}
return $n;
}
2023-03-26 18:36:46 +00:00
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 extractTracks( $streams, $type ) {
return array_values(
array_filter( $streams, function ( $stream ) use ( $type ) {
return $stream->codec_type === $type;
} )
);
}
2023-01-15 18:25:47 +00:00
function convert( $src, $dest, $options ) {
2023-03-26 18:36:46 +00:00
$maxBits = 8 * sizify( $options['size'] );
2023-01-15 01:20:35 +00:00
$probe = ffprobe( $src );
$videoTracks = extractTracks( $probe->streams, 'video' );
$audioTracks = extractTracks( $probe->streams, 'audio' );
2023-02-22 21:15:06 +00:00
if ( count( $videoTracks ) == 0 ) {
var_dump( $probe );
die("oh no\n");
}
2023-01-15 01:20:35 +00:00
$track = $videoTracks[0];
$duration = floatval( $track->duration );
$width = $track->width;
$height = $track->height;
2023-05-16 19:14:49 +00:00
$hdr = $track->color_primaries === 'bt2020' || $options['hdr'];
2023-01-15 01:20:35 +00:00
$keyframeInt = ceil( $duration * 60 );
$bitrate = floor( $maxBits / $duration );
2023-01-15 18:25:47 +00:00
if ( $options[ 'no-audio' ] || count( $audioTracks ) == 0 ) {
2023-04-10 02:23:42 +00:00
$audio = [ '-an' ];
} else {
2023-01-15 18:25:47 +00:00
$audioBitrate = 96 * 1000;
2023-04-10 02:23:42 +00:00
$audio = [
'-ac', 2,
'-b:a', $audioBitrate,
];
2023-01-15 18:25:47 +00:00
$bitrate -= $audioBitrate;
}
2023-04-10 02:23:42 +00:00
$bitrate = max( $bitrate, 16000 );
2023-01-15 01:20:35 +00:00
$mbits = 1000 * 1000;
2023-04-10 02:23:42 +00:00
$base = intval( $mbits * floatval( $options['quality'] ) );
if ( $bitrate < 0.125 * $base || $height < 144 ) {
$frameWidth = 256;
$frameHeight = 144;
$bitrate = min( $bitrate, $base * 0.25 );
} elseif ( $bitrate < 0.25 * $base || $height < 180 ) {
$frameWidth = 320;
$frameHeight = 180;
$bitrate = min( $bitrate, $base * 0.5 );
} elseif ( $bitrate < 0.5 * $base || $height < 288 ) {
$frameWidth = 512;
$frameHeight = 288;
$bitrate = min( $bitrate, $base * 0.5 );
} elseif ( $bitrate < 1 * $base || $height < 480 ) {
2023-01-25 00:48:44 +00:00
$frameWidth = 640;
$frameHeight = 360;
$bitrate = min( $bitrate, $base );
} elseif ( $bitrate < 2 * $base || $height < 540) {
2023-01-15 18:25:47 +00:00
$frameWidth = 854;
$frameHeight = 480;
$bitrate = min( $bitrate, $base * 2 );
} elseif ( $bitrate < 2.5 * $base || $height < 720) {
$frameWidth = 960;
$frameHeight = 540;
$bitrate = min( $bitrate, $base * 2.5 );
} elseif ( $bitrate < 4 * $base || $height < 1080) {
2023-01-15 18:25:47 +00:00
$frameWidth = 1280;
$frameHeight = 720;
$bitrate = min( $bitrate, $base * 4 );
2023-01-15 01:20:35 +00:00
} else {
2023-01-15 18:25:47 +00:00
$frameWidth = 1920;
$frameHeight = 1080;
2023-04-22 00:57:03 +00:00
$bitrate = min( $bitrate, $base * 8 );
2023-01-15 18:25:47 +00:00
}
2023-02-12 22:04:46 +00:00
$aspect = $width / $height;
2023-05-16 19:14:49 +00:00
$pixels = $width * $height;
// canonical base rate is 1 megabit at 480p
$bitrate = min( $bitrate, 4 * $base );
2023-05-17 16:53:50 +00:00
/*
2023-05-16 19:14:49 +00:00
$minWidth = 640;
$minHeight = 360;
$baseWidth = 854;
$baseHeight = 480;
$pixelsPerBit = ( $baseWidth * $baseHeight ) / $base;
$maxWidth = 1920;
$maxHeight = 1080;
$maxrate = $base * ( $maxWidth * $maxHeight ) / ( $baseWidth * $baseHeight );
$pixels = $bitrate * $pixelsPerBit;
$frameHeight = evenize( sqrt( $pixels / $aspect ) );
$frameWidth = evenize( $frameHeight * $aspect );
if ( $aspect > 16 / 9 ) {
if ( $frameWidth < $minWidth ) {
$frameWidth = $minWidth;
$frameHeight = evenize( $frameWidth / $aspect );
} elseif ( $frameWidth > $maxWidth ) {
$frameWidth = $maxWidth;
$frameHeight = evenize( $frameWidth / $aspect );
$bitrate = min( $bitrate, $maxrate );
}
} else {
if ( $frameHeight < $minHeight ) {
$frameHeight = $minHeight;
$frameWidth = evenize( $frameHeight * $aspect );
} elseif ( $frameWidth > $maxWidth ) {
$frameHeight = $maxHeight;
$frameWidth = evenize( $frameHeight * $aspect );
$bitrate = min( $bitrate, $maxrate );
}
}
2023-05-17 16:53:50 +00:00
*/
2023-05-16 19:14:49 +00:00
2023-02-12 22:04:46 +00:00
$wide = $aspect > ( $frameWidth / $frameHeight );
2023-04-10 02:23:42 +00:00
$crop = boolval( $options['crop'] );
2023-04-25 04:24:51 +00:00
$letterbox = boolval( $options['letterbox'] );
2023-04-10 02:23:42 +00:00
if ( $crop ) {
2023-02-12 22:04:46 +00:00
if ( $wide ) {
$scaleHeight = $frameHeight;
$scaleWidth = evenize( $frameHeight * $aspect );
2023-04-10 02:23:42 +00:00
} else {
$scaleWidth = $frameWidth;
$scaleHeight = evenize( $frameWidth / $aspect );
2023-02-12 22:04:46 +00:00
}
2023-01-15 18:25:47 +00:00
} else {
2023-02-12 22:04:46 +00:00
if ( $wide ) {
$scaleWidth = $frameWidth;
$scaleHeight = evenize( $frameWidth / $aspect );
2023-04-10 02:23:42 +00:00
} else {
$scaleHeight = $frameHeight;
$scaleWidth = evenize( $frameHeight * $aspect );
2023-02-12 22:04:46 +00:00
}
2023-01-15 01:20:35 +00:00
}
$exposure = floatval( $options['exposure'] );
2023-04-09 21:52:06 +00:00
$peakNits = floatval( $options['peak'] );
2023-01-31 06:54:34 +00:00
$sdrNits = 80;
$peak = $peakNits / $sdrNits;
2023-01-15 01:20:35 +00:00
$filters = [ "scale=w=$scaleWidth:h=$scaleHeight" ];
if ( $hdr ) {
2023-04-22 00:57:03 +00:00
$filters[] = "zscale=t=linear";
if ( $exposure ) {
$filters[] = "exposure=$exposure";
}
$filters[] = "tonemap=hable:peak=$peak:desat=0.0";
2023-05-28 00:04:17 +00:00
if ( $options['dither'] ) {
$dither = ":dither=ordered";
} else {
$dither = "";
}
$filters[] = "zscale=t=bt709:p=bt709:m=bt709:r=full$dither";
$filters[] = "vibrance=0.2";
2023-01-15 01:20:35 +00:00
}
$filters[] = "format=yuv420p";
2023-04-10 02:23:42 +00:00
if ( $crop ) {
$filters[] = "crop=w=$frameWidth:h=$frameHeight";
2023-04-25 04:24:51 +00:00
} elseif ( $letterbox ) {
2023-02-12 22:04:46 +00:00
$offsetX = round( ( $frameWidth - $scaleWidth) / 2 );
$offsetY = round( ( $frameHeight - $scaleHeight) / 2 );
$filters[] = "pad=w=$frameWidth:h=$frameHeight:x=$offsetX:y=$offsetY";
2023-01-15 18:25:47 +00:00
}
2023-01-15 01:20:35 +00:00
$vf = implode( ',', $filters );
$fps = $options['fps'];
2023-04-23 18:46:50 +00:00
$preset = $options['preset'];
2023-03-26 20:55:26 +00:00
2023-04-09 21:52:06 +00:00
$tempPrefix = 'pack-vid-passlog' . rand(0,1 << 31);
$passlog = tempnam( '.', $tempPrefix );
run( 'ffmpeg',
array_merge( [
'-i', $src,
'-f', 'mp4',
2023-05-01 16:37:02 +00:00
'-fpsmax', $fps,
//'-r', $fps,
'-vf', $vf,
'-c:v', 'libx264',
'-b:v', $bitrate,
2023-03-26 20:55:26 +00:00
'-preset', $preset,
'-pass', '1',
2023-01-31 06:54:34 +00:00
'-passlogfile', $passlog,
'-g', $keyframeInt,
], $audio, [
'-y', '/dev/null'
] )
);
2023-01-15 18:25:47 +00:00
run( 'ffmpeg',
array_merge( [
'-i', $src,
'-vf', $vf,
2023-05-01 16:37:02 +00:00
'-fpsmax', $fps,
//'-r', $fps,
2023-01-15 18:25:47 +00:00
'-c:v', 'libx264',
'-b:v', $bitrate,
2023-03-26 20:55:26 +00:00
'-preset', $preset,
2023-01-15 18:25:47 +00:00
'-pass', '2',
2023-01-31 06:54:34 +00:00
'-passlogfile', $passlog,
2023-01-15 18:25:47 +00:00
'-g', $keyframeInt,
], $audio, [
2023-01-15 18:44:06 +00:00
'-movflags', '+faststart',
2023-01-15 18:25:47 +00:00
'-y', $dest
] )
);
2023-04-09 21:52:06 +00:00
$len = strlen( $tempPrefix );
if ( $len > 0 ) {
$dir = dir( './' );
for ( $entry = $dir->read(); $entry !== false; $entry = $dir->read() ) {
if ( substr( $entry, 0, $len ) === $tempPrefix ) {
print "...deleting temp file: $entry\n";
unlink( $entry );
}
}
$dir->close();
}
2023-01-15 01:20:35 +00:00
}