summaryrefslogtreecommitdiffstats
path: root/roles/prerec/templates/reencode.sh
blob: c9c87e19c629062cf4a38b74b8ee22207557f5f3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#!/usr/bin/env bash

set -euo pipefail

# Defaults
q=32
cpu=4
time_limit=""
print_only=false
limit_resolution=1080
limit_fps=29.99

with_suffix() {
    suffix="$1"
    echo "$input" | sed "s/--original\.\([a-z0-9]*\$\)/--$suffix\.\\1/"
}

while getopts :q:c:t:s OPT; do
    case $OPT in
        q|+q)
            q="$OPTARG"
            ;;
        c|+c)
            cpu="$OPTARG"
            ;;
        t|+t)
            time_limit="-to $OPTARG"
            ;;
        s)
            print_only=true
            ;;
        *)
            echo "usage: `basename $0` [+-q ARG] [+-c ARG} [--] ARGS..."
            exit 2
    esac
done
shift `expr $OPTIND - 1`
OPTIND=1

input="$1"
input_limited="$(with_suffix "original-limited")"
output="$2"

command="$(cat<<EOF
# Preliminary pass to limit resolution and fps
ffmpeg -y -i "$input" $time_limit \
       -vf "scale='-1':'min($limit_resolution,ih)',
            select='eq(n,0)+if(gt(t-prev_selected_t,1/$limit_fps),1,0)'" \
        -c:v rawvideo -c:a pcm_s16le -f nut - | ffmpeg -y -f nut -i - -vf "fps=$limit_fps" "$input_limited"

# Reencode
ffmpeg -y -i "$input_limited" $time_limit \
       -vf "scale='-1':'min($limit_resolution,ih)',
            select='eq(n,0)+if(gt(t-prev_selected_t,1/$limit_fps),1,0)'" \
       -c:v libvpx-vp9 -b:v 0 -crf $q -an \
       -row-mt 1 -tile-columns 2 -tile-rows 2 -cpu-used $cpu -g 240 \
       -pass 1 -f webm -threads $cpu /dev/null &&
    ffmpeg -y -i "$input_limited" $time_limit \
           -vf "scale='-1':'min($limit_resolution,ih)',
                select='eq(n,0)+if(gt(t-prev_selected_t,1/$limit_fps),1,0)'" \
               -c:v libvpx-vp9 -b:v 0 -crf $q -c:a libopus \
               -row-mt 1 -tile-columns 2 -tile-rows 2 -cpu-used $cpu \
               -pass 2 -threads $cpu -- "$output"
EOF
)"

if [ $print_only == true ]; then
    echo "$command"
else
    eval "$command"
fi