#!/usr/bin/env bash set -x INPUT=$1 # input file OUTPUT=$2 # target file SIZE=$3 # [0-9]+[GgMmKk] TEMP=$(mktemp) DURATION=$(mediainfo --Inform="Video;%Duration%" $INPUT) durS=$(($DURATION/1000)) if [[ "$SIZE" =~ [0-9]+[Gg] ]]; then gb=${SIZE/[Gg]/} kb=$(($gb * 8 * 1024 * 1024)) fi if [[ "$SIZE" =~ [0-9]+[Mm] ]]; then mb=${SIZE/[Mm]/} kb=$(($mb * 8 * 1024)) # doing 1M = 1000K just to build in some overhead fi if [[ "$SIZE" =~ [0-9]+[Kk] ]]; then k=${SIZE/[Kk]/} kb=$((k * 8)) fi if [ ! $kb ]; then echo "unable to calculate bitrate" exit fi audiosize=$((160*durS)) target=$(($kb-$audiosize)) bitrate=$(($target/$durS)) ffmpeg -i $1 \ -y \ -f mp4 \ -g 15 \ -movflags +faststart \ -preset ultrafast \ -threads 9 \ -c:v libx264 \ -b:v ${bitrate}k \ -pass 1 \ -an \ -passlogfile $TEMP \ /dev/null ffmpeg -i $1 \ -y \ -b:a 160k \ -c:a aac \ -ac 2 \ -f mp4 \ -g 15 \ -movflags +faststart \ -preset ultrafast \ -threads 9 \ -c:v libx264 \ -b:v ${bitrate}k \ -pass 2 \ -passlogfile $TEMP \ $2