#!/bin/bash
#
# make_variants_from_video: extract sample video frames from a video file
#
# Creates a foo-sq.jpg and thumbnail-sized files with sample frames
# named foo-f00000001-tn.jpg etc where 00000001 is the frame number.
# (currently creates 12 such sample frames from throughout the video)
#
# usage: make_variants_from_video *.avi
#        (but normally invoked by make_variants wrapper script)
#
# dependencies: mplayer, make_variant
#
# Gerald Oskoboiny, 26 Jan 2007
#
# source: http://impressive.net/software/photo/source/make_variants_from_video
#
# $Id: make_variants_from_video,v 1.1 2007/01/30 09:02:15 gerald Exp $
#

temp=.mvfv.$$

# define a pattern that matches errors from make_variant we don't care about
mvnonsense="^(No camera-specific|Argument .. isn.t num|Image contains no thumb)"

# helper function
copyframe() {
    make_variant 128 tn $temp/${framenum}.jpg 2>&1 | egrep -v "$mvnonsense"
    cp -a $temp/${framenum}-tn.jpg $base-f${framenum}-tn.jpg
}

for f in "$@"; do

    # check if variants have already been generated for this file
    base=`echo $f | sed 's/\.avi//'`
    if [ -f $base-f00000001-tn.jpg ]; then
	continue
    fi

    mkdir $temp || exit
    mplayer -nosound -vo jpeg:outdir=$temp $f > /dev/null 2>/dev/null
    numframes=$(/bin/ls $temp | wc -w); export numframes

    # copy the first frame
    framenum="00000001"; copyframe

    # also create a foo-sq.jpg based on the first frame
    make_variant 100 sq $temp/${framenum}.jpg 2>&1 | egrep -v "$mvnonsense"
    cp -a $temp/${framenum}-sq.jpg $base-sq.jpg

    # copy ten frames from throughout the video
    for n in $(seq 10); do
	framenum=$(printf "%08d" "`expr $numframes \* $n / 11`"); copyframe
    done

    # copy the last frame
    framenum=$(printf "%08d" "$numframes"); copyframe

    # clean up (safely)
    rm -f $temp/[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9].jpg
    rm -f $temp/*-sq.jpg $temp/*-tn.jpg
    rmdir $temp

done

