gatoAlfa

Thursday, October 2, 2008

security camera

My sister has a Panasonic camera, BL-C131A and it has a neat feature to periodically or based on IR or movement triggers upload images to an FTP server. The camera will upload the files with a filename with a prefix you choose and then the date and time, for example a filename will be: mv20080919065310878.jpg
Having the files in an FTP server is nice, but not very convenient to check them. I wrote this script to be used in a cron job to join many images together and create an .mp4 movie. It uses the ffmpeg program.

Here is the source code for the script, generate_movie:

#!/bin/bash
# cp or mv files older thant 24h in the $1 location
# to the $2 location, generate a movie with the files
# and move the movie back to $1, then delete the files in $2
# $3 is the prefix for the name of the files

if [ $# -lt 3 ]; then
echo "USAGE $0 sourceDir tempDir prefix"
exit;
fi

export SOURCE=$1
export DEST=$2
export PREFIX=$3
export MOV_NAME=$PREFIX-`date +'%Y-%m-%d'`.mp4
export PID=$$
export CP_OR_MV=mv
export COMP_FILE=temp-$PID

#create a file to be used as a time reference
touch $DEST/$COMP_FILE
# allow some time for any current file xfer to finish
sleep 90

#find any files older than the COMP_FILE
#then copy or move them
if [ $CP_OR_MV = "mv" ]
then
find $SOURCE -type f ! -newer $DEST/$COMP_FILE -name "$PREFIX*.jpg" -exec mv {} $DEST \;
else
find $SOURCE -type f ! -newer $DEST/$COMP_FILE -name "$PREFIX*.jpg" -exec cp -p {} $DEST \;
fi
rm $2/$COMP_FILE

#rename the files in seq. order (ffmpeg limitation)
n=1
for file in `ls $DEST/$PREFIX*.jpg`; do
mv $file $DEST/$PREFIX-$PID-`printf "%06d" $n`.jpg
n=$(($n+1))
done

#encode the files into a movie
ffmpeg -r 5 -sameq -i $DEST/$PREFIX-$PID-%06d.jpg -y $SOURCE/$MOV_NAME >& /dev/null

#email the movie
#if [ -s $SOURCE/$MOV_NAME ]
#then
#mutt -s "Report $PREFIX" -a $SOURCE/$MOV_NAME bla@ble.com </dev/null
#fi

#delete images if the movie was created
if [ -s $SOURCE/$MOV_NAME ]
then
rm $DEST/$PREFIX-$PID-*.jpg
else
echo "error:" $SOURCE/$MOV_NAME "not created. Leaving" $DEST/$PREFIX-$PID- "files untouched."
fi