summaryrefslogtreecommitdiff
path: root/ffmgrep.sh
blob: 243c0c77b246912b79f320d1c157eccb6e0897fb (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
#!/bin/bash

# LOOKS THROUGH SUBTITLES OF GIVEN FILES TO FIND THE TIMESTAMP(S) OF INPUT STRING

if (($# < 2)); then
    echo >&2 "$0: script requires at least two arguments: Text to grep and at least one file with subtitles, in that order"
    exit 1
else
    expr="$1"
    shift
fi

FILES=()
TMPDIR="ffmgrep.XXXXX"
STREAM=0
CACHEFLAG=0
COLOR1="\o033[32m"
COLOR2="\o033[36m"
ENDCOLOR="\o033[0m"

while (($#)); do
    if [[ ! -f $1 ]]; then
        echo >&2 "$0: $1 is not a valid file"
        exit 1
    else
        FILES+=("$1")
    fi
    shift
done

# we do a little caching

OLD_TMPDIR=$( ls -ltc /tmp/ | grep -E "^d.*ffmgrep\..{5}" | head -n1 | sed -r "s|.*(ffmgrep)|\/tmp\/\1|g" )

if [[ ! -d "$OLD_TMPDIR" ]]; then
    TMPDIR=$(mktemp --directory -t "$TMPDIR")
else
    for file in "${FILES[@]}"; do
        basefile="$(basename "$file")"
        if [[ ! -f "${OLD_TMPDIR}/${basefile%.*}.vtt" ]]; then
            rm -r $OLD_TMPDIR
            TMPDIR=$(mktemp --directory -t "$TMPDIR")
            break
        fi
    done
    [[ -d "$OLD_TMPDIR" ]] && TMPDIR="$OLD_TMPDIR" && CACHEFLAG=1
fi

for file in "${FILES[@]}"; do
    [[ $CACHEFLAG -eq 1 ]] && break
    basefile="$(basename "$file")"
    [[ -z $(ffmpeg -i "$file" -c copy -map 0:s:0 -frames:s 1 -f null - -v 0 -hide_banner; echo $?) ]] && echo "NO SUBTITLES FOUND IN FILE $file. SKIPPING..." && continue
    ffmpeg -i "$file" -map "0:s:${STREAM}" -hide_banner -loglevel error -f webvtt "${TMPDIR}/${basefile%.*}.vtt"
done

# grep -B 1 --no-group-separator -E -i "$expr" ${TMPDIR}/*vtt | awk 'NR%2{printf "%s ",$0;next;}1' | sed -r "s|${TMPDIR//\//\\\/}\/(.*?)\.vtt-([[:digit:]]+:[[:digit:]]+\.[[:digit:]]+ --> [[:digit:]]+:[[:digit:]]+\.[[:digit:]]+) .*?\.vtt:(.*$)|${COLOR1}\1${ENDCOLOR}: ${COLOR2}(\2)${ENDCOLOR} \3|g"

grep --with-filename -r "" ${TMPDIR} | sed -r "s|.*\.vtt:$||g" | awk -v RS= '{$1=$1}1' | grep --no-group-separator -E -i "$expr" | sed -r "s|${TMPDIR//\//\\\/}\/[^\/]*\.vtt[-:]||2g; s|${TMPDIR//\//\\\/}\/(.*?)\.vtt[-:](([[:digit:]]+[:\.])+[[:digit:]]+ --> ([[:digit:]]+[:\.])+[[:digit:]]+) (.*$)|${COLOR1}\1${ENDCOLOR}: ${COLOR2}(\2)${ENDCOLOR} \5 |g"