Categories
FreeBSD/Unix

Motion recording webcam script

To do a motion recording camera with FreeBSD 8.1 you need to install multimedia/pwcbsd and multimedia/mencoder from ports. With these and a short perl script you can do a camera that records motion and splits them in to separate files when there is inactivity for 600s.

#!/usr/local/bin/perl
#
# Author: Jan Melen-jan(at)melen.org
#
use POSIX qw(strftime);
use IO::Select;

if (($#ARGV + 1) != 1) {
    print "    Usage: camera.pl <Dir for storing mpeg4 files>\n";
    exit;
}

$dir = "$ARGV[0]/";
$sel = new IO::Select();

sub open_pwcview {
    open(PWCVIEW, "/usr/local/bin/pwcview -hkr -s sif -f 5 |")
        or die "Can't start pwcview: $!";
    binmode(PWCVIEW);
    $sel->add(\*PWCVIEW);
}

sub close_pwcview {
    $sel->remove(\*PWCVIEW);
    close(PWCVIEW);
}

sub open_mencoder {
    $now_string = strftime("%Y%m%d-%H%M%S", localtime);
    $filename = $dir. $now_string. ".avi";
    open(MENCODER, "| /usr/local/bin/mencoder -demuxer rawvideo -rawvideo ".
        "fps=5:w=320:h=240:i420 - -ovc lavc -lavcopts vcodec=mpeg4 ".
        "-o ". $filename)
        or die "Can't start mencoder: $!";
    binmode(MENCODER);
}

sub close_mencoder {
    close(MENCODER);
}

open(PID, ">". $dir. "camera.pid") or die "Can't open pidfile: $!";
print PID $$. "\n";
close(PID);

open_pwcview();
while (1) {
    @ready = $sel->can_read(600);
    if ($#ready >= 0) {
        if ($mcopen != 1) {
            open_mencoder();
            $mcopen = 1;
        }
        $bytes = ;
        if (length($bytes) == 0) {
            close_pwcview();
            close_mencoder();
            $mcopen=0;
            open_pwcview();
        } else {
            print MENCODER $bytes;
        }
    } else {
        close_mencoder();
        $mcopen=0;
    }
}