#!/usr/bin/env bash

## An ffplay wrapper that prints the duration of a media file and plays the file
## three seconds later.
##
## Usage: play [<ffplay-option>...] <file>
##
## Dependencies: FFmpeg, GNU coreutils, GNU grep, GNU sed
##
## I wrote this script after noticing that whenever I used ffplay (my preferred
## media player) to play a video, I usually paused it and switched back to the
## terminal to see the duration.

set -euo pipefail
shopt -s inherit_errexit

die() { echo "${0##*/}: $1" >&2; exit 1; }

[[ " $* " =~ ' --help ' ]] && sed -n 's/^## \?//p' "$0" && exit
(( $# )) || die 'missing argument'

file="${!#}"
[[ -f $file ]] || die "file not found: $file"

duration=$(ffprobe -loglevel error -pretty -show_entries format=duration "$file" |
  grep -o '[0-9]\+:[0-9]\+:[0-9]\+')

echo "Duration: $duration"
sleep 3
ffplay "$@"
