An Introduction to Video Surveillance with 'Motion'

Posted by simms on Mon 6 Feb 2006 at 07:54

Videochatting and amateur pornography are all well and good, but have you ever wondered what else you can do with that webcam?
Well, thanks to the efforts of many dedicated open-source coders, any half-decent PC can be turned into a motion-detecting, snapshot-making, video-recording D.I.Y. security solution.

motion, a program designed to detect movement by analyzing streams of images, is one great way of doing this.
And while installing and configuring this piece of software used to be a royal pain in the butt, with the advent of Sarge, we now have an easy-to-install motion package right in the main repositories.

Before we go on, you should know that while motion was originally designed to interact with devices managed via Video4Linux (V4L), it is also able to interact with network cameras accessible via HTTP over TCP/IP.
In this introduction I will cover using a V4L video device (webcam, TV card, etc.) directly attached to your PC, but once you get the hang of it, using network cameras instead won't require much effort.

Initial requirements

This article assumes you have:
  • a working Debian `Sarge' installation
  • at least one working video device connected to your system and recognized as /dev/videoX, where 'X' is an index starting from zero (check the boot-time hardware detection messages to see)
NB: Setting up your video device is outside the scope of this article. In my case I have a cheapo Kensington USB webcam that is supported by the kernel using the se401 module, so it shows up automatically as /dev/video0 on my system.
There are many webcams out there, and Linux' hardware support varies wildly among the different models, so if you're going to buy a new webcam for your Linux box, I'd recommend that you try to make sure it's already supported -- if your camera isn't recognized by the kernel at boot time, it's likely that you'll have to find and compile a driver for it, so you can save yourself a lot of trouble by picking one that is already well-known in the Linux world.

Those who can get their hands on an old analog camera and a compatible TV capture card can use the capture card as the video device, except that it needs to be configured (set to the right channel and so on) before motion is started; there are many utilities for this, for example v4lctl.
As far as initial camera setup is concerned, the xawtv package can also be of great help if you have X installed, as it allows you to test video device output right on your monitor.

A first foray

We will begin by setting up the motion package and testing its interaction with our source video device.

For starters, get 'root' and invoke:
apt-get install motion
According to apt-get, the program itself will take up a few megs of disk space once installed.
This isn't much, but if you plan to capture and keep motion-generated video files, my advice would be to prepare a separate disk partition just for this purpose. Its size is up to you -- I'd recommend a couple GB to start -- but the number of cameras, their resolution, and your capture settings must be taken into consideration. In any case, starting with a separate partition is a good way to play around with the program without endangering the rest of your system -- should you happen to 'misunderestimate' your needs, motion will stop working once the target partition is filled up, but nothing else will get screwed up.
For the purposes of this article, we will assume that an empty disk partition has been created and mounted as /vidcap.

motion can run as a daemon or as a regular console program, according to settings read from configuration files and from the command-line.
Command-line settings override what is in the configuration file. Personally I prefer to avoid using the command-line options, so that I can tune and back up my configuration with ease.
Once you graduate to a multi-camera setup, you will need to split up your configuration into 'thread files' specific to each camera, but we don't need to worry about that now.

For the Debian package, a single configuration file is installed by default as /etc/motion/motion.conf, so that is where we will go to configure our setup.
As 'root', open /etc/motion/motion.conf with your favourite text editor.

Look for the line that says videodevice /dev/video0, and change this line so that it points to your working video device.
Immediately below, you should see width and height lines -- these need to be changed so that they match your camera's resolution in pixels. Generally you should go with the highest supported resolution unless you have good reasons (crappy CPU, low memory) not to do so; you want motion to have as many pixels to work with as possible.

If you're using a TV capture card as your video source, you'll also need a line that says input X somewhere in your config file, where 'X' is a number corresponding to the input to use from the card (normally 1). You will also need to specify a TV standard (the norm setting) matching the card's output -- normally 0 for PAL, 1 for NTSC, 2 for SECAM, and 3 for PAL NC.

motion comes with its own built-in web server, allowing it to stream 'live' video device output to [proper] web browsers, in MJPEG format. This is probably not what you're looking to do with it, but at this point it's a perfectly crumulent way of checking whether motion can grok output from our video device; another advantage of this facility is that it allows us to test our setup without a working X installation.
This is what we will do now.

Insert the following lines into /etc/motion/motion.conf:
output_all off
output_normal off
output_motion off

This disables all file output facilities.

Now look for the line that says webcam_port 0, and change the zero to a suitable port number to use for motion's mini-webserver. I go with the example 8000, which is accessible to hosts inside my LAN.

If the machine running motion can't run a graphical web browser itself, one more change is required:
look for the line that says webcam_localhost on, and change it to webcam_localhost off. This will allow HTTP clients other than the local host to access the webcam.

That's it! We're ready to roll.
Save and close /etc/motion/motion.conf.
Back at the command line, cross your fingers and punch in:
motion

If everything went well, you should see something like
Processing thread 0 - config file motion.conf
Thread0 device: /dev/video0 input: 8
This tells us motion is running.
Leave it be, and open up a graphical web browser (perhaps on another machine). Point it to http://hostname:port as appropriate -- in my case this is http://motionserver:8000. If your browser supports MJPEG as it should, you should now see 'live' output from your webcam!
NB: modern browsers should really have no problem with this. If using Firefox, you might have to refresh the page after loading it initially to get proper output. Internet Explorer users: please, give it up and get a real browser. I haven't seen a single IE setup that can deal with MJPEG, so it's t.s. for you, yet again.

Capturing motion events

OK, assuming the above instructions worked for you, we can now move on to detecting and capturing motion events, which is what motion is really for. We have two ways of storing detected events: as still image files, or as video files.
If motion is still running from before, hit Ctrl-C in its console to terminate our test run. Now return to /etc/motion/motion.conf (or wherever you chose to place the config file).
Look for the target_dir specification, and change it so that it points to the directory where you want the event data to be stored -- as per my instructions above, this would be /vidcap.
Producing motion event images
This is quite simple. In the config file, change the output_normal option from off to on.
Save the file, return to the prompt and launch motion again. While motion is running, any movement detected via your video source will result in a series of sequentially-numbered JPG files being dropped into your target directory (as defined with target_dir above).
Producing motion event videos
Let's take it one step further. Instead of capturing image sequences for each event, motion can harness the awesome power of ffmpeg to build fully-animated event video files with minimal overhead. The video files are built frame-by-frame 'on the fly', so they are finished and ready to watch almost immediately after the given 'event' is over.

Because it is considered 'non-free', ffmpeg is not available from the standard Debian repositories. To install it, you will need to add the following line to your /etc/apt/sources.list file:
deb ftp://ftp.nerim.net/debian-marillat/ sarge main

Now run
apt-get update
apt-get install ffmpeg

Once ffmpeg is installed, return to the motion config file and look for ffmpeg_cap_new off.
Changing this option to on will enable event video generation using ffmpeg.
There's one more setting you may want to add here:
ffmpeg_video_codec msmpeg4
This will force ffmpeg to use an internal video codec that is [generally] compatible with Windows Media Player without any additional codec installation, which can be pretty useful.
If omitted, this setting defaults to mpeg4, which is normally viewable anywhere true MPEG-4 is supported.

Note that there is no need to install any additional codecs (such as the popular packages from mplayerhq.hu) to get the above working. This is nice because it minimizes external dependencies, use of patent-encumbered technologies, and use of disk space.

Anyway, if you followed my instructions up to this point, save and close the config file, and launch motion again.
It's now time for a brief celebratory dance in front of your camera. When you are finished, you may browse to your storage directory, and find out just how ridiculous you look.
target_dir should begin to fill up with sequentially-numbered video event files .. and that's my cue to exit.

Onwards

The above introduction should be enough to get you started.
I'm sure you can imagine many different uses for motion.
The program supports execution of external commands at event time, so it is relatively simple to use these to hook it up to a database, or some sort of notification system (e-mail, SMS, etc.). With the right script 'glue', motion could easily be used as the core of a web-based surveillance system. Another feature I didn't really cover here is timelapse capture, which can be a lot of fun to play with (for instance, you can set up a camera to record the life of a houseplant over a few months' time).

Before we conclude, here are some caveats I should probably share with you:
  • for more permanent installations, it's wiser to run motion as a special unprivileged user;
  • also for security's sake, you probably shouldn't expose motion's mini-webserver to the internet -- this means running a proper firewall, or blocking external access with webcam_localhost on;
  • every kind of camera and situation will require some tuning -- in the long run you'll have to adjust the settings so that 'false alarms' are minimal and image quality is acceptable;
  • as far as surveillance gear is concerned, webcams are utterly sub-par, so don't expect miracles -- a production-grade system will require decent network cameras no matter what.

For the version in Debian stable (3.1.19), a detailed guide to configuring the program can be found at http://www.lavrsen.dk/twiki/bin/view/Motion/MotionGuide3x1x20.
For the purposes of this posting, you can ignore the instructions relating to compilation / installation, but the configuration tips are valid, so don't be afraid to dive in. Browsing around the same site, you will also find a selection of active mailing lists, and detailed information regarding compilation / installation / patching of newer versions, from source (NB: this is not for the faint of heart -- the program is in active development, and the bleeding-edge versions tend to be flaky).

So, that's it. You should now have a basic motion detection setup on your Debian box.

Just remember: you're not actually being paranoid if 'they' are really out to get you ;)

 

 


Posted by Steve (82.41.xx.xx) on Mon 6 Feb 2006 at 08:02
[ View Steve's Scratchpad | View Weblogs ]

A great introduction!

Just two small comments:

ffmpeg

If you're using Sid/Unstable then ffmpeg is available in Debian's repositories. (I didn't check Sarge, but I didn't need to add anything foreign to my sources.list file to install it and it seemed to work correctly)

Running automatically

As well as shipping with a sample configuration file the package contains a sample init.d file too. So you can make the monitor startup at boot time automatically:

cp /usr/share/doc/motion/examples/motion.init-Debian  /etc/init.d/motion
chmod 755 /etc/init.d/motion
update-rd.d motion defaults

Once you've done that you can add the "deamon" setting into /etc/motion/motion.conf:

daemon on

Now your monitoring can be started/stopped with:

/etc/init.d/motion stop
/etc/init.d/motion start

If it is useful I could post a brief guide to getting a Phillips webcam working with module-assistant tomorrow or so?

Steve

[ Parent | Reply to this comment ]

Posted by simms (216.13.xx.xx) on Mon 6 Feb 2006 at 12:47
Thanks for the tip, I didn't know it was so simple to do.
I generally control the motion process in a much more brute-force way, starting and stopping it as needed using custom scripts and cron jobs.

Here's a few more basic tips for those who followed the article:

Tracking event triggers

If your motion setup seems to be triggering too many false alarms -- i.e. generating too many snapshots / videos because of negligible movement in the camera's field of view -- you may want to try the 'locate' feature, which will force the program to draw a rectangle in each frame around the pixels it considers to have 'moved'. Just add locate on to your config file. Then adjust the threshold value as needed.
If the false alarms are being triggered in an area that can be ignored (e.g. a mirror reflecting movement on a street), consider using a mask file.
The text_changes parameter can also be helpful: when it is set to on, motion will add the number of detected 'changed' pixels to the upper right corner of each frame.

Making timelapse videos

As I mentioned in the main piece, motion is also able to generate timelapse videos. This kind of output is very much like what you would get from archaic VCR-based security systems, in that it represents the camera's perspective regardless of any detected movement.
The nice thing about this is that it can be done while motion detection features are enabled (at the cost of a few extra CPU cycles), so that you can compare the timelapse output to that generated from 'events', which lets you see whether your detection settings are sensitive enough.

Here are the config file settings relevant to timelapse facilities:
# Turn on timelapse feature and capture one frame every X seconds:
ffmpeg_timelapse X

# Choose a `rollover' time for timelapse videos.
# Valid choices for period are
# "hourly", "daily", "weekly-sunday", "weekly-monday", "monthly", and "manual".

ffmpeg_timelapse_mode period

Note that although timelapse videos are generated with ffmpeg, the ffmpeg_video_codec setting is irrelevant to this feature. Timelapse videos are generated 'on the fly' as the frames come in from the video device, so the only supported format is 'classic' MPEG1.

[ Parent | Reply to this comment ]

Posted by Anonymous (193.114.xx.xx) on Mon 15 May 2006 at 10:52

With a small addition you can have motion come up on boot if you wish:


cctv:/etc/init.d# update-rc.d motion defaults
 Adding system startup for /etc/init.d/motion ...
   /etc/rc0.d/K20motion -> ../init.d/motion
   /etc/rc1.d/K20motion -> ../init.d/motion
   /etc/rc6.d/K20motion -> ../init.d/motion
   /etc/rc2.d/S20motion -> ../init.d/motion
   /etc/rc3.d/S20motion -> ../init.d/motion
   /etc/rc4.d/S20motion -> ../init.d/motion
   /etc/rc5.d/S20motion -> ../init.d/motion

You can always undo this with:

cctv:/etc/init.d# update-rc.d -f  motion remove

[ Parent | Reply to this comment ]

Posted by Anonymous (71.160.xx.xx) on Thu 3 Nov 2011 at 11:03
It should be the following code for setting motion to run for the default runlevels:

update-rc.d motion defaults

—Dustin Williams
dustin-williams.com

[ Parent | Reply to this comment ]

Posted by deadcat (68.127.xx.xx) on Mon 6 Feb 2006 at 08:48
[ View Weblogs ]
i use motion for video surveillance as well, but a friend of mine told me about this software too: http://www.zoneminder.com/
seems very fancy but havent tried it out yet since motion does what i needed! (=

[ Parent | Reply to this comment ]

Posted by Anonymous (213.164.xx.xx) on Mon 6 Feb 2006 at 09:22
ZM is good.

[ Parent | Reply to this comment ]

Posted by simms (216.46.xx.xx) on Mon 6 Feb 2006 at 12:08
Actually I've tried ZoneMinder as well before sticking with Motion.
ZoneMinder's not bad, but it's tightly integrated with its own web interface, which has its flaws and isn't very customizable. In my experience ZM also takes a lot more work to configure initially, especially now that a proper Debian motion package is available.

[ Parent | Reply to this comment ]

Posted by deadcat (68.127.xx.xx) on Mon 6 Feb 2006 at 20:43
[ View Weblogs ]
i agree with the user interface, thats why i never really want to try ZM hehe

[ Parent | Reply to this comment ]

Posted by PJ_at_Belzabar_Software (61.11.xx.xx) on Mon 6 Feb 2006 at 09:28
[ View Weblogs ]
Lovely. I have been considering doing something like this for quite a while, just waiting for the prices and storage to reach the right point.

For surveillance I'd imagine expensive network cameras would be the way to go since those cheapo usb cams presumably can't work over a distance of more than a few feet, right?

PJ

[ Parent | Reply to this comment ]

Posted by simms (65.92.xx.xx) on Mon 6 Feb 2006 at 10:00
Yes, netcams are the only way to do it IMHO.
It can mean a lot of cabling work unless you go wireless (and secure, eh?).
But 'motion' can handle different video device types at the same time, so you can mix & match as per the situation.
One thing people do is re-use the existing coaxial CCTV setup in a building and pass it to motion via a multi-chip TV capture card.

[ Parent | Reply to this comment ]

Posted by simms (65.92.xx.xx) on Mon 6 Feb 2006 at 09:51
ffmpeg_video_code msmpeg4
should read
ffmpeg_video_codec msmpeg4

[ Parent | Reply to this comment ]

Posted by Steve (82.41.xx.xx) on Mon 6 Feb 2006 at 11:27
[ View Steve's Scratchpad | View Weblogs ]

Thanks, I've updated the text now.

Steve

[ Parent | Reply to this comment ]

Posted by Anonymous (24.233.xx.xx) on Wed 4 Oct 2006 at 05:13
is not apple to apple comparison
zoneminder is far more featured than motion, thus you cannot have it both ways. (a lot of functions and command line)
For instance, in a full fledge surveillance application you want to smartly trigger motion detection. A ray of sun, a moving tree, a temporary shadow may trigger false alarms. Thus you better use a powerful graphic interface to select zones and apply specific characteristics to them (ignore, combine) etc, etc. And this is only the beginning.
Calixto

[ Parent | Reply to this comment ]

Posted by Anonymous (24.186.xx.xx) on Tue 27 Nov 2007 at 03:54
Motion supports all of that and more. Smartmasks automatically desensitize areas where motion is frequent. Like leaves blowing on trees. All extremely configurable.
I use motion with over 70 cameras on a 3TB NAS. All running Debian. Works like a champ!

[ Parent | Reply to this comment ]

Posted by Anonymous (69.107.xx.xx) on Fri 26 Apr 2013 at 13:56
I have a newbie question. How specifically can I get motion to write to a mounted nas portion? I run in daemon mode and motion does not seem to have permission to write to mounted nas

[ Parent | Reply to this comment ]

Posted by Anonymous (152.3.xx.xx) on Tue 6 Nov 2007 at 18:34
this was fantastic howto. I which there were more ppl out there capable of writing down-to-the-earth and useful guides.

I got this working w/ gentoo and motion 3.2.8. thanks.

[ Parent | Reply to this comment ]

Posted by Anonymous (85.80.xx.xx) on Mon 14 Apr 2008 at 08:36
Good write, how much cpu do i need for a server 2 run exp 5 cam whit good res ?

[ Parent | Reply to this comment ]

Sign In

Username:

Password:

[Register|Advanced]

 

Flattr

 

Current Poll

What do you use for configuration management?








( 534 votes ~ 7 comments )