Auto-archiving ZoneMinder recordings to video files

While ZoneMinder (www, github) is a great free and open-source surveillance camera software suite, it still lacks in some aspects. One of these is in its storage/transcoding of input video into series of JPEG images. This limits the amount of compression achieved by the system, such that a system with a high number of cameras must have a significant amount of storage to store history video past a few days.

For a single-camera setup recording at a low framerate, the recording time can be expanded far beyond the capabilities of JPEG. In the following script, all images for a day are moved to a folder and placed in sequential order, and ffmpeg is used to convert the series of images into a video. In this case mpeg4 (divx/xvid) is used because it’s less CPU intensive, however libx264 could be used to ¬†obtain higher compression.

With the camera recording at 4 frames per second at 1600×1200 resolution, ~345,000 images at around ~50GB are compressed to a 7GB video file. Additionally, the hard drive is monitored, and the oldest video is removed when disk usage exceeds 90%.

#!/bin/bash
ARDT=`date +%Y%m%d --date="7 days ago"`
MONITORNUM=1
cd /media/media/zmc
pf="/media/media/zoneminder/events/$MONITORNUM/${ARDT:2:2}/${ARDT:4:2}/${ARDT:6:2}"
C=0
for hr in `ls $pf`
do
    for mn in `ls $pf/$hr`
    do
        for sc in `ls $pf/$hr/$mn`
        do
            for i in `ls $pf/$hr/$mn/$sc`
            do
                  mv $pf/$hr/$mn/$sc/$i `printf "%09d" $C`.jpg
                  C=$((C+1))
            done
        done
    done
done
rm -rf $pf
/usr/bin/ffmpeg -i %09d.jpg -vcodec mpeg4 -qscale 10 -g 50 ../front-"${ARDT}".avi > /dev/null
echo "Made $C images totalling `du -h .|awk '{print $1}'` into a `ls -lh ../front-"${ARDT}".avi |awk '{print $5}'` video file at `date`"
for i in {0..9}; do rm -f *$i.jpg; done

diskfr=`df -h|awk '/media/media/{print $5}'|sed 's/%//'`
if [ $diskfr -gt 90 ]; then
    trfile=`ls -lh /media/media/*.avi|awk 'NR==1{print $9}'`
    echo "Space on /media/media exceeds 90%. Removing $trfile"
    rm $trfile
fi

Note that the process of moving so many images takes a few minutes, and this (along with the encoding time) would significantly increase with higher recording framerates. Ultimately, ZoneMinder will be a top-notch solution if h.264 encapsulation and storage is adopted as a storage intermediate, rather than JPEG, and there is in fact a bounty for such a feature.