#!/bin/bash

# durtc
# returns duration in timecode format HH:MM:SS:FF, assuming fps is 25

# usage examples
# simple
#     durtc *.mp4
# using gnu parallel and sorting by 2nd column
#     find . -type f -iname "*.mp4" | parallel --gnu durtc | sort -k2

# checks
command -v bc >/dev/null 2>&1 || { >&2 echo "I need bc installed." ; exit 1; }
command -v mediainfo >/dev/null 2>&1 || { >&2 echo "I need mediainfo installed." ; exit 1; }

while [ $# -gt 0 ]; do

    file=$(readlink -f "$1")
    #baseext=$(basename "${1}")  
    
    # variable
    fps=25 # assuming some fps (must be integer)
    
    # is it file
    test -f "$file" || { >&2 echo "Not a file: $file" ; shift; continue; } # "continue" should skip to next file in this while loop.
    
    # check if fps is the same as assumed fps, otherwise the results are wrong (due to calculating duration from %FrameCount%)
    fpsreal=$(mediainfo --Inform="Video;%FrameRate%" "$file")
    
    # bash can't compare floating point stuff, so bc must be used here
    # note that $fps must still be integer (or change the "# Count frames, seconds, minutes and hours" math).
    if (( $(echo "$fps==$fpsreal" | bc -l) == 0 )); then # negating the logic here somehow
        { >&2 echo "Wrong fps: $fpsreal $file" ; shift; continue; } # "continue" should skip to next file in this while loop.
    fi
    
    # get info
    frames=$(mediainfo --Inform="Video;%FrameCount%" "$file")
    
    # Count frames, seconds, minutes and hours
    f=$(( frames%fps ))
    s=$(( frames/fps%60 ))
    m=$(( frames/fps/60%60 ))
    h=$(( frames/fps/60/60%24 ))
    
    # pad with zeroes
    printf -v f "%02d" $f
    printf -v s "%02d" $s
    printf -v m "%02d" $m
    printf -v h "%02d" $h
    
    tmpname="${file##/*/}"
    name=${tmpname%.*}
    
    if [[ ! "$frames" == "" ]] ; then
    echo $h:$m:$s:$f "$name" 
     else
     echo  ..unknown.. "$name"
    fi

shift
done