summaryrefslogtreecommitdiff
path: root/dot/local/bin/twmp4
blob: 755c67b38d4a368a19068648e34008fbfc682aa3 (plain)
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
72
73
74
75
76
77
78
79
80
81
82
83
#!/bin/bash

usage()
{
    cat <<EOF
Usage: $0 [options] <input>

  Options:
    --help|--usage|-h
    --start <time>
    --end <time>
EOF
}

[ $# -gt 0 ] || set -- --help
ARGS=$(getopt -o 'h' --long 'usage,help,start:,end:' -n 'twmp4' -- "$@") || exit
eval set -- "$ARGS"
unset ARGS

INPUT_OPTIONS=
while [ $# -gt 0 ]
do
    case "$1" in
        -h|--help|--usage) usage; exit ;;
        --start) INPUT_OPTIONS="$INPUT_OPTIONS -ss $2"; OUTPUT_SUFFIX="${OUTPUT_SUFFIX:+$OUTPUT_SUFFIX.}$2"; shift;;
        --end) INPUT_OPTIONS="$INPUT_OPTIONS -to $2"; OUTPUT_SUFFIX="${OUTPUT_SUFFIX:+$OUTPUT_SUFFIX.}$2"; shift;;
        --) shift; break ;;
        -*) usage; exit 1 ;;
        *) break;;
    esac
    shift
done

INPUT=$1
set -ex

[ -f "$INPUT" ]

OUTPUT_SUFFIX=${OUTPUT_SUFFIX:+$OUTPUT_SUFFIX.}twitter.mp4

case "$INPUT" in
    *.mp4) OUTPUT=${INPUT%.mp4}.$OUTPUT_SUFFIX ;;
    *.*) OUTPUT=${INPUT%.*}.$OUTPUT_SUFFIX ;;
    *) OUTPUT=${INPUT}.$OUTPUT_SUFFIX ;;
esac

# source: https://gist.github.com/nikhan/26ddd9c4e99bbf209dd7

if [ ! -e "$OUTPUT" ]
then
    ffmpeg -hide_banner \
           $INPUT_OPTIONS \
           -i "$INPUT" \
           $OUTPUT_OPTIONS \
           -vcodec libx264 \
           -vf 'scale=640:trunc(ow/a/2)*2' \
           -acodec aac \
           -vb 1024k \
           -minrate 1024k -maxrate 1024k \
           -bufsize 1024k -ar 44100 \
           -strict experimental \
           -r 30 \
           "$OUTPUT"
fi

video_length()
{
    ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "$1"
}

chunk_seconds=135 # twitter max is 140, but ffmpeg can run over specified time
video_length=$(video_length "$OUTPUT")

if [ "${video_length%.*}" -gt "$chunk_seconds" ]
then
    # source: https://unix.stackexchange.com/questions/1670/how-can-i-use-ffmpeg-to-split-mpeg-video-into-10-minute-chunks/212518#212518
    CHUNKS=${OUTPUT%.mp4}.%03d.mp4
    ffmpeg -hide_banner \
           -i "$OUTPUT" \
           -c copy \
           -map 0 \
           -segment_time "$chunk_seconds" -f segment -reset_timestamps 1 "$CHUNKS"
fi