# Motion Guide - One Large Document.

This version of the Guide is made for inclusion in the Motion download package for off line reading.

If you read this document from the distribution package of Motion or from some not up to date mirror you should know that the URL for the always up to date version is http://www.lavrsen.dk/foswiki/bin/view/Motion/MotionGuide. If you are already on the Foswiki based Motion site clicking the link just mentioned will lead you to the index page for the Motion Guide documents.

This topic consists of the following subtopics: MotionOverview, KnownProblems, InstallOverview, PrepareInstall, ConfigureScript, MakeInstall, UpgradingFromOlderVersion, RunningMotionConfigFiles, CommandLineOptions, ConfigFileOptions, SignalsKill, ErrorLogging, CaptureDeviceOptions, MotionDetectionSettings, ImageFileOutput, TuningMotion, MpegFilmsFFmpeg, SnapshotsWebCam, TextFeatures, AdvancedFilenames, ConversionSpecifiers, WebcamServer, RemoteControlHttp, ExternalCommands, TrackingControl, UsingDatabases, LoopbackDevice.

- Motion Guide - Installation
  - Motion Overview
    - What is Motion?
    - How do I get Motion and what does it cost?
    - Maintenance and Support
    - Which version to download and use?
    - What features does Motion have?
    - FreeBSD
    - MacOSX
    - Documentation
    - Supported Hardware
  - Known Problems
  - How do I install Motion?
  - Preparation For Install
  - Configure Script
  - Make
    - Make Install
    - Un-install
    - Additional Make Options
  - Upgrading From Older Version
  - Running Motion
    - Important Definitions
    - The Config Files
  - Command Line Options
  - Config File Options
    - Options in Alphabetical Order.
    - Obsolete Options
  - Signals (sent with e.g. kill command)
  - Error Logging
- Motion Guide - Basic Features
  - Capture Device Options - The Basic Setup
  - video4linux (V4L) devices
    - auto_brightness
    - brightness
    - contrast
    - framerate
    - frequency
    - height
    - hue
    - input
    - minimum_frame_time
    - norm
    - rotate
    - saturation
    - tunerdevice
    - v4l2_palette
    - videodevice
    - width
  - Network Cameras
    - netcam_http
    - netcam_proxy
    - netcam_tolerant_check
    - netcam_url
    - netcam_userpass
  - Round Robin feature
    - roundrobin_frames
    - roundrobin_skip
    - switchfilter
  - Motion Detection Settings
    - area_detect
    - despeckle
    - gap
    - lightswitch
    - mask_file
    - max_mpeg_time
    - minimum_motion_frames
    - noise_level
    - noise_tune
    - output_all
    - post_capture
    - pre_capture
    - smart_mask_speed
    - threshold
    - threshold_tune
  - Image File Output
    - output_motion
    - output_normal
    - ppm
    - quality
  - Tuning Motion
  - Generating MPEG films with ffmpeg
    - ffmpeg_bps
    - ffmpeg_cap_motion
    - ffmpeg_cap_new
    - ffmpeg_deinterlace
    - ffmpeg_timelapse
    - ffmpeg_timelapse_mode
    - ffmpeg_variable_bitrate
    - ffmpeg_video_codec
  - Snapshots - The Traditional Periodic Web Camera
    - snapshot_interval
  - Text Features
    - locate
    - text_changes
    - text_double
    - text_event
    - text_left
    - text_right
  - Advanced Filenames
    - ffmpeg_filename (now called movie_filename)
    - jpeg_filename
    - movie_filename
    - snapshot_filename
    - target_dir
    - timelapse_filename
  - Conversion Specifiers for Advanced Filename and Text Features
  - Webcam Server
    - webcam_limit
    - webcam_localhost
    - webcam_maxrate
    - webcam_motion
    - webcam_port
    - webcam_quality
  - Remote Control with http
    - control_authentication
    - control_html_output
    - control_localhost
    - control_port
  - External Commands
    - on_area_detected
    - on_camera_lost
    - on_event_end
    - on_event_start
    - on_motion_detected
    - on_movie_end
    - on_movie_start
    - on_picture_save
    - quiet
    - What happened to mail and sms?
      - Sending email at start of event
      - Sending SMS at start of event
- Motion Guide - Special Features
  - Tracking Control
    - Tracking Feature with Logitech Quickcam Sphere/Orbit
    - track_auto
    - track_iomojo_id
    - track_maxx
    - track_maxy
    - track_motorx
    - track_motory
    - track_move_wait
    - track_port
    - track_speed
    - track_step_angle_x
    - track_step_angle_y
    - track_stepsize
    - track_type
  - Using Databases
    - sql_log_image
    - sql_log_mpeg
    - sql_log_snapshot
    - sql_log_timelapse
    - sql_query
  - MySQL
    - mysql_db
    - mysql_host
    - mysql_password
    - mysql_user
  - PostgreSQL
    - pgsql_db
    - pgsql_host
    - pgsql_password
    - pgsql_port
    - pgsql_user
  - Video4Linux Loopback Device
    - motion_video_pipe
    - video_pipe

# Motion Guide - Installation

## Motion Overview

### What is Motion?

Motion is a program that monitors the video signal from one or more cameras and is able to detect if a significant part of the picture has changed. Or in other words, it can detect motion.

The program is written in C and is made for the Linux operating system.

Motion is a command line based tool. It has absolutely no graphical user interface. Everything is setup either via the command line or via a set of configuration files (simple ASCII files that can be edited by any ASCII editor).

The output from motion can be:

- jpg files
- ppm format files
- mpeg video sequences

### How do I get Motion and what does it cost?

Motion is an open source type of project. It does not cost anything. Motion is published under the GNU GENERAL PUBLIC LICENSE (GPL) version 2 or later. It may be a bit difficult to understand all the details of the license text (especially if your first language is not English). It means that you can get the program, install it and use it freely. You do not have to pay anything and you do not have to register anywhere or ask the author or publisher for permission. The GPL gives you both rights and some very reasonable duties when it comes to copying, distribution and modification of the program. So in very general terms you do not have to worry about licensing as a normal hobby user. If you want to use Motion in a commercial product, if you want to distribute either modified or original versions of Motion - for free or for a fee, you should read the license carefully. For more information about free software and the GPL, I encourage you to study the very interesting documents about the subject available the of the Free Software Foundation pages about the Philosophy of the GNU Project.

### Maintenance and Support

Both Motion and the Motion Guide are written by people that do all this as a hobby and without asking for any payments or donations. We have a life other than developing Motion and its documentation. This means that bugfixes and updates to this guide are done as our time and families allow it. You are however encouraged to participate and contribute in a very active mailing list. It is a list with a very "positive attitude" and with many contributors that propose features, post patches, discuss problems and patiently answer newbie questions with a very positive spirit. Expect 1-10 emails per day.

To get motion direct your browser to the Motion Homepage.

On the Download Files page you will find a links to the latest stable version both as sources and binaries for some of the most popular Linux distributions. You will also find links to development versions. Snapshot releases are special test releases that are normally very stable. Every day a Motion Daily Source Snap is created from the Motion Subversion

Motion was originally written by Jeroen Vreeken who still actively participates in the development of Motion and later Folkert van Heusden continued as a lead programmer with Kenneth Lavrsen responsible for Motion Guide, website and releases on Sourceforge.

From version 3.1.12 Motion is now project managed entirely by Kenneth Lavrsen, and the project now shift towards being developed by many contributers.

For support we encourage you to join the mailing list instead of writing to Jeroen, Folkert or Kenneth directly. We are all very active on the mailing list and by using the mailing list much more users will have benefit of the answers. Newbies and stupid questions are welcome on the list. Contributions in the form of patches are also very welcome on the mailing list.

### Which version to download and use?

Versions 3.2.X are the current version. There is at the moment no development branch. The versions 3.1.X ended at 3.1.20 and there will be no more 3.1.X releases. If you use use a version older than 3.2.X you are encouraged to update.

Since 3.1.13 quite many options have been renamed to make setting up Motion easier. From 3.1.17-18 some unfinished features have been removed. The Berkeley mpeg feature is now removed because the ffmpeg feature is now mature and much better working. At version 3.1.18 a new network camera feature was introduced replacing the old cURL based netcam code and introducing support of mjpeg streaming cameras. However this new code was quite difficult to get stable. During the development of 3.2.2 the network camera code was totally rewritten again learning from our experience and now finally it seems to be stable.

Motion is included in Debian, while Ubuntu and RPM users can find binary packages on the Motion Sourceforge file download page.

### What features does Motion have?

See more description at the Motion Homepage.

- Taking snapshots of movement
- Watch multiple video devices at the same time
- Watch multiple inputs on one capture card at the same time
- Live streaming webcam (using multipart/x-mixed-replace)
- Real time creation of mpeg movies using libraries from ffmpeg
- Take automated snapshots on regular intervals
- Take automated snapshots at irregular intervals using cron
- Executing external program when detecting movement
- Execute external program at the beginning of an event of several motion detections.
- Execute external program at the end of an event of several motion detections.
- Execute external program when a picture is saved.
- Execute external program when a movie mpeg is created (opened)
- Execite external program when a movie mpeg ends (closed)
- Motion tracking
- Feed events to an MySQL or PostgreSQL database.
- Feed video back to a video4linux loopback for real time viewing
- Web interface using Motion Related Projects such as motion.cgi, Kenneths Webcam Package, Kevins Webpage, X-Motion and many more.
- User configurable and user defined on screen display.
- Control via simple web interface.
- Automatic noise and threshold control
- Ability to control the pan/tilt of a Logitech Sphere (or Orbit) camera
- Highly configurable display of text on images.
- High configurable definition of path and file names of the stored images and films.

You can find more information and links at the Motion Homepage.

### FreeBSD

Motion is originally developed for Linux and it is still mainly developed and supported for this platform. From version 3.1.15 an experimental port has been made by Angel Carpintero. Not all features of Motion are supported at this time and it still needs a lot of test time on different hardware. Angel is very interested in feedback. Join the Motion Mailing List and give your feedback there. Patches for bugfixes and for enabling the missing features are very welcome. The rest of this guide is still mainly targeted for Linux users. Follow this topic to Install FreeBSD.

### MacOSX

From Motion version 3.2.4 it is now also possible to build and install Motion under MacOSX. Feature set it the same as for FreeBSD. See the MacOSX topic for specific help how to install Motion and its dependencies on MacOSX. Again this port has been contributed by Angel Carpintero.

### Documentation

You have the following sources of information:

- This Motion Guide.
- The Frequently Asked Questions
- The author of the program has written a description of the technology behind motion.
- The man page. After installation simply write man motion
- The default motion.conf file (motion-dist.conf) that comes with the package.

### Supported Hardware

Input devices: Here we are thinking about the cameras.

Motion supports video input from two kinds of sources.

Standard video4linux devices (e.g. /dev/video0). Motion has no drivers for cameras. Installing the camera itself is outside the scope of this document. But here are some nice links.

- Driver for USB Philips cameras (and more) This driver is a fork of the old pcw(x) driver which got kicked out of the kernel. (see: http://www.smcc.demon.nl/webcam/). See also the new PWC Documentation Site which is hosted in this wiki.
- BTTV Driver (capture cards). Part of many distributions now.
- OV511 based USB cameras are supported as standard by newer Kernels.
- kernel driver for USB cameras based on Sunplus spca50
- rivatv.sourceforge.net Driver for tv/composite/svideo input with most Nvidia based video cards. Network cameras (which are actually cameras with a built in web server that can be connected directory to your network).
- Axis Communications

## Known Problems

See also the Frequently Asked Questions and Bug Reports for known open bugs.

Kernel 2.6 and pwc. Note that for kernel 2.6 there is a new release of the Philips WebCam (pwc) drivers 10.0.X. It is recommended to install this. At the time of this being written the 2.6.12+ kernels have a version of pwc built-in but it is a cripled version which can only support very small picture size. You can however download the latest source code of the pwc driver (at this time 10.0.11) and build it without having to rebuild your kernel. But you will need to have either the kernel sources or a special kernel-header package installed to compile it. See Installation of PWC page which is also hosted in this wiki.

If you use use a Logitech Quickcam Orbit or Sphere using the driver pwc/pwcx and kernel 2.6.X you should replace the file in the Motion sources called pwc-ioctl.h with the one that comes with the your pwc version. Motion is shipped with 3 versions of pwc-ioctl.h-VERSION. Rename the one that fits your major pwc version number best to pwc-ioctl.h (after renaming the current to something else). There has been some small adjustments in the API that requires that you have the right header file.

Camera picture dimensions must be multiple of 16 Dimentions of camera image must have both height and width that are a multiple of 16. Thís is normally not a problem. All standard sizes like 640, 480, 352, 320, 288, 240, ...etc are multiples of 16. But if you intend to monitor a network camera which is saving jpeg images you may have to pay attention to the dimensions of the picture.

ffmpeg_filename has changed name to movie_filename The 3.2.5 release contains a motion_guide and man page in which it was forgotten to change ffmpeg_filename to movie_filename. Please note that the option that defines the filenames for mpeg movies is now called movie_filename. This change is made because we may soon implement alternatives to ffmpeg and then ffmpeg_filename will be a bad name. This is fixed in release 3.2.5.1.

error: `time_current_frame' undeclared (first use in this function) A bug in 3.2.5 and 3.2.5.1 where a bugfix related to snapshot feature has created a new bug when you compile Motion without ffmpeg libs installed. This is fixed in 3.2.6.

## How do I install Motion?

Motion is mainly distributed as source files that you must compile yourself. There is also an RPM made on Fedora Core 3. And Debian packages are available for selected versions.

The short overview of the steps to install Motion from sources.

- Preparation: Motion uses a number of shared libraries that must be installed on your computer before you can build Motion. The needed shared libraries depends on the features you wish to use. Features network camera, ffmpeg, MySQL and PostgreSQL needs specific shared libraries installed. See preparation section for more information.

- Download the motion source files (distributed as tar'ed and compressed files). Place the file in a place of your own choice.

- Untar and uncompress the file to the place you want the program installed. Editor recommends placing the motion source file directory in /usr/local. If you do not have write access to the /usr/local directory (you are under the mercy of an ignorant system administrator with a severe case of paranoia) - you can install the program in a directory in your home directory. You will then need to read the next section about how to configure before you compile the program. Below is shown the exact commands using version 3.2.X installed in /usr/local as an example (replace /path/to with the actual placement of the tar.gz file).

    cd /usr/local
    tar -xvzf /path/to/motion-3.2.X.tar.gz

- You will now have created a directory called motion-3.2.X. You can rename it to motion (mv motion-3.1.X motion). I recommend creating a symbolic link to the current version. This way you can more easily experiment with different version simply by changing the link.

    ln -s motion-3.2.X motion

- Now change to the new directory

    cd motion

- Run configure. You can start with the defaults. If you need to modify the installation parameters you can read the next section.

    ./configure

- Build the code

    make

- Install the code, manual page, etc

    make install

- In /etc/motion/etc you will find a file called motion-dist.conf. If it is the first time you install Motion - rename this file to motion.conf and edit as a minimum the settings: videodevice, input, norm, frequency, width, height and target_dir. That should get you going.

- Run the program. To enable more features you must modify the config file.

    motion

## Preparation For Install

Note: If you're using SuSE 9.2, you might want to ADDITIONALLY have a look at Compiling on SuSE 9.2. As mentioned on that page as well, you will still need to read the instructions here as well.

Before you start you may need to install a number of shared libraries that Motion uses. If they are missing the feature will simply normally not be included. Most of these libraries can be found on the CDs of your distribution. A few will have to be downloaded from the Internet. Note that when you install software using pre-compiled binaries (Redhat type RPMs, Debian debs etc) you normally only get what is needed to run the programs themselves. In order to compile other programs from source that uses these pre-compiled libraries you also need to installed the development packages. These are normally called the same name as the package suffixed by -devel or -dev. These development packages contains the header files (xxx.h) that Motion needs to build with the shared libraries. If you build a library from sources you already have these header files. It is recommended to simply install the pre-compiled binary packages and their development brothers.

This is a list of shared libraries used by Motion and the RPM packages that provides them.

Motion will always need these libraries to be built and work

Library | RPM Packages | Debian Packages
--- | --- | ---
libm, libresolv, libdl, libpthread, libc, ld-linux, libcrypt, and libnsl | glibc and glibc-devel | libc6 , libc6-dev ,libglib1.2
libjpeg | libjpeg and libjpeg-devel | libjpeg62 and libjpeg62-dev ( optional libjpeg-mmx-dev )
libz | zlib and zlib-devel | zlib1g and zlib1g-dev

For generating mpeg films with ffmpeg you need this library:
(See also the section Generating MPEG films with ffmpeg for how to install ffmpeg and libavformat/libavcodec)
Motion must be installed with revision 0.4.8 or 0.4.9pre1 of ffmpeg. Motion will also work with later CVS snapshots of ffmpeg but the API of the ffmpeg libraries changes all the time and without warning. If you have problems compiling Motion or with running an RPM of Motion you may try with an older CVS snapshot of ffmpeg. The Motion developers will like to know when ffmpeg changes and breaks Motion so we can fix it. Please file a bug report then with the exact date of the ffmpeg CVS version you have trouble with.

Library | RPM Packages | Debian Packages
--- | --- | ---
libavcodec, libavformat | ffmpeg and ffmpeg-devel or install from source | libavcodec-dev libavcodec0d libavformat-dev libavformat0d (*)

Debian has not provided deb packages for ffmpeg due patent issues. However this is about to change so checkout for availability of newer versions of debian ffmpeg debs. You can build yourself from source or from Christian Marillat website or apt repository.

    deb http://www.debian-multimedia.org stable main # ( etch )
    deb http://www.debian-multimedia.org testing main # ( lenny )
    deb http://www.debian-multimedia.org unstable main # ( sid )

Add the suitable line to your /etc/apt/sources.list and run this:

    apt-get update ; apt-get -y install libavcodec-dev libavcodec0d libavformat-dev libavformat0d

For logging in MySQL you need this library:

Library | RPM Packages | Debian Packages
--- | --- | ---
libmysqlclient | mysql and mysql-devel | libmysqlclient15-off and libmysqlclient15-dev

For logging in PostgreSQL you need this library:

Library | RPM Packages | Debian Packages
--- | --- | ---
libpq | postgresql-libs and postgresql-devel | libpq-dev and libpq4

## Configure Script

Configure is script that you run to setup the build environment for the C-compiler. It generates the "Makefile" which the program "make" uses to compile and install the software.

To run configure your current directory must be the motion directory. You type

`./configure`

You can add the parameter `./configure --help` to get help on the different switches.

This is walk through of the options.

Option | Description Defaults for the options are specified in brackets [ ] | Editors comment
--- | --- | ---
-h, --help | display this help and exit |
--help=short | display options specific to this package | This command shows the options special to motion. Recommended
--help=recursive | display the short help of all the included packages |
-V, --version | display version information and exit | Gives no useful information
-q, --quiet, --silent | do not print `checking...' messages | Not very useful. Output to screen is only a few lines anyway.
--cache-file=FILE | cache test results in FILE. [disabled] | No function
-C, --config-cach | alias for `--cache-file=config.cache' | No function
-n, --no-create | do not create output files | Used for testing if other switches produce error - without writing anything to the disk
--srcdir=DIR | find the sources in DIR. [configure dir or `..'] | DIR is a directory path. Editor recommends having the current directory being the motion installation directory and not using this switch. Then it defaults to the same directory as where the configure script is which is the current directory.
Installation directories: |  |
--prefix=PREFIX | install architecture-independent files in PREFIX [/usr/local] | The default /usr/local means that the executable binary "motion" is installed in /usr/local/bin, the manual page in /usr/local/man/man1, the document files in /usr/local/docs/motion-version, configuration file in /usr/local/etc, and some examples config files in /usr/local/examples/motion-versionEditor recommends keeping this default setting. If you are experimenting with many parallel versions it may be interesting to set the PREFIX to e.g. /usr/local/motion and then add /usr/local/motion/bin to your search path (or simply cd /usr/local/motion/bin before execution). This way you can change version just by changing the symbolic link in /usr/local/motion as suggested earlier in this guide. If you are installing the software on a machine where you have no access to the /usr/local but have write access to a home directory, then you should change this to point to a directory within your home tree. Example: --prefix=$HOME
--exec-prefix=EPREFIX | install architecture-dependent files in EPREFIX [PREFIX] | If you set this it only defines an alternative installation directory for the executable binary. Note: The executable binary will be placed in a directory "bin" below the directory specified by this option Editor recommends leaving this as default (i.e. not setting it).
--bindir=DIR | user executables [EPREFIX/bin] | With this option you can control exactly in which directory the executable binary is installed. The previous option automatically adds the bin directory. Here you are in fill control.
--sbindir=DIR | System admin executables [EPREFIX/sbin] | Not used by motion. Ignore it.
--libexecdir=DIR | program executables [EPREFIX/libexec] | Not used by motion. Ignore it.
--datadir=DIR | read-only architecture-independent data [PREFIX/share] | Not used by motion. Ignore it.
--sysconfdir=DIR | read-only single-machine data [PREFIX/etc] | This is where motion both installs the default configuration file and also where it later searches for it. Motion searches for the configuration file "motion.conf" in the following order: 1. Current directory from where motion was invoked 2. $HOME/.motion 3. The sysconfig directory set by this switch. If not defined the default is /usr/local/etc/ Editor recommends leaving this at default. Be careful if you run "make install" again. This will overwrite the motion.conf file that you have edited and experimented with for hours. Make sure to keep a copy in a safe place. Alternatively, copy the working file to the motion base install directory. Then make install will simply copy the same file back again.
--sharedstatedir=DIR | modifiable architecture-independent data [PREFIX/com] | Not used by motion. Ignore it.
--localstatedir=DIR | modifiable single-machine data [PREFIX/var] | Not used by motion. Ignore it.
--libdir=DIR | object code libraries [EPREFIX/lib] | Not used by motion. Ignore it.
--includedir=DIR | C header files [PREFIX/include] | Not used by motion. Ignore it.
--oldincludedir=DIR | C header files for non-gcc [/usr/include] | Not used by motion. Ignore it.
--infodir=DIR | info documentation [PREFIX/info] | Not used by motion. Ignore it.
--mandir=DIR | man documentation [PREFIX/man] | Editor recommends the default.
Optional Packages: |  |
--with-linuxthreads | Use linuxthreads in BSD instead of native phtreads | Only relevant for BSD. In Linux we always use this per default.
--with-pwcbsd | Use pwcbsd based webcams ( only BSD ) | This option allow to build motion to support V4L/V4L2 in BSD. HowtoMotionPwcFreeBSD
--without-bktr | Exclude to use bktr subsystem , that usually useful for devices as network cameras | ONLY used in *BSD
--without-v4l | Exclude using v4l (video4linux) subsystem. Makes Motion so it only supports network cameras. | Can be used if you do not need V4L support and maybe lack some of the libraries for it.
--with-jpeg-mmx=DIR | Specify the prefix for the install path for jpeg-mmx for optimized jpeg handling (optional). If this is not specified motion will try to find the library /usr/lib/libjpeg-mmx.a /usr/local/lib/libjpeg-mmx.a. | Considered experimental
--with-ffmpeg=DIR | Specify the path for the directory prefix in which the library and headers are installed. If not specified configure will search in /usr/ and /usr/local/ | DIR is the directory PREFIX in which the ffmpeg shared libraries and their headers are installed. If you install ffmpeg from sources and use the default directories or if ffmpeg is installed as a binary package (RPM or deb) you do not need to specify the directory prefix. Configure will find the libraries automatically. If you installed ffmpeg from sources and specified a different --prefix when building ffmpeg you must use the same value for the DIR ( --with-ffmpeg=DIR). For more information on FFmpeg see the FFmpeg project home page. FFmpeg is a package that enables streamed video mpeg signal from your web camera to a browser. Editor recommends installing ffmpeg from source and in the directory /usr/local/ffmpeg and build ffmpeg with ./configure --enable-shared. This places libraries in /usr/local/lib and headers in /usr/local/include.
--without-ffmpeg | Do not compile with ffmpeg | Use this if you do not want to compile with ffmpeg. If ffmpeg is not installed you do not need to specify that Motion must build without ffmpeg.
--with-mysql-lib=DIR | Lib directory of MySQL | Normally, configure will scan all possible default installation paths for MySQL libs. When its fail, use this command to tell configure where MySQL libs installation root directory is.
--with-mysql-include=DIR | Include directory with headers for MySQL | Normally, configure will scan all possible default installation paths for MySQL include. When its fail, use this command to tell configure where MySQL include installation directory is. This is the directory with the MySQL header files.
--without-mysql | Do not compile with MySQL support | Use this if you do not want to include MySQL support in the package. This can also be useful if you get compilation errors related to MySQL and you actually do not need the feature anyway.
--without-pgsql | Do not compile with PostgreSQL support | Use this if you do not want to include PostgreSQL support in the package. This can also be useful if you get compilation errors related to PostgreSQL and you actually do not need the feature anyway.
--with-pgsql-include=DIR | Normally, configure will scan all possible default installation paths for pgsql include. When it fails, use this command to tell configure where pgsql include installation root directory is. |
--with-pgsql-lib=DIR | Normally, configure will scan all possible default installation paths for pgsql libs. When it fails, use this command to tell configure where pgsql libs installation root directory is. |
--without-optimizecpu | Exclude autodetecting platform and cpu type. This will disable the compilation of gcc optimizing code by platform and cpu. | Use this if the optimization causes problems. Typically if you build on some non X386 compatible CPU.
Developers options |  |
--with-developer-flags | Add additional warning flags for the compiler. | This option is for developers only. It produces a flood of warnings that helps the developer to write more robust code. These warnings are normally harmless but can sometimes be a latent defect. For more information about these flags, see CompileWithDeveloperFlags

## Make

When you run make, all the C-source files are automatically compiled and linked. Just look out for error messages.

Make uses a file called "Makefile" which is generated by the "configure" script you just ran. If you have special needs you can manually edit this file. Next time you run configure a new Makefile will be generated and your changes are lost.

Attention!

If you have run `make` before, you should run a `make clean` before running `make` again. This cleans out all the object files that were generated the previous time you ran `make`. If you do not run `make clean` first before you rebuild Motion you may not get the additional feature included. For example: If you built Motion without ffmpeg support and then add it later - and rebuild Motion without running `make clean` first - the ffmpeg feature does not get compiled into the Motion binary.

First time you build motion run `./configure`, `make`, `make install`. If you need to build it again (to run with different configure options) run `./configure`, `make clean`, `make`, `make install`.

### Make Install

`make install` simply copies all the nice files that were generated during the compilation/linking that make did.

Makes the directories (if they do not already exist)(path shown are the defaults): /usr/local/bin, usr/local/man/man1, /usr/local/etc, /usr/local/share/doc/motion-3.2.X, and /usr/local/share/doc/examples/motion-3.2.X.

Copies the following files from the base motion directory (assuming the default PREFIX /usr/local was used when running configure - otherwise adjust to the actuals you chose)

- Executable binary "motion" to /usr/local/bin
- Manual page "motion.1" to /usr/local/man/man1
- Document files "CHANGELOG, COPYING, CREDITS, INSTALL, and README to /usr/local/share/doc/motion-3.2.X
- Example configuration files "*.conf" to /usr/local/share/doc/examples/motion-3.2.X
- Configuration file "motion-dist.conf" to /usr/local/etc

Note that the any existing files are overwritten. The default config file motion-dist.conf is named like this so that you do not get your working motion.conf file overwritten when you upgrade Motion.

### Un-install

From the motion base installation directory you simply run `make uninstall`

And delete the base installation directory in /usr/local and any link pointing to it. If you have forgotten where you installed it or someone else did it for you, simply search for the files and directories starting with motion. If the filenames and the directories match the names described in the "Make Install" section of this document, you can safely delete them.

### Additional Make Options

The make command can be run with several options. `make`, `make install` and `make uninstall` has already been described above.

make clean
  deletes all the binary files (object files) and the motion binary generated by make. It also deletes temporary files and any jpg files that motion has saved in the motion source directory. It is very important to always run `make clean` before you run `make` if you change the configuration (like adding features such as ffmpeg) and rebuild motion.

make distclean
  deletes the files: config.status, config.log, config.cache, Makefile, and motion.spec.

make updateguide
  fetches a fresh new copy of this guide and place it in your motion source directory. Note that the pictures are not downloaded.

make dist
  performs make clean, make distclean and make updateguide in one single operation.

## Upgrading From Older Version

If you are upgrading from motion 3.0.X or from an older version of 3.1.X you should note that many options have been removed from version 3.1.13 and forward and many new have arrived. You still have most of the old features. The options have been changed for two reasons. New more flexible features and to simplify getting started with Motion. With 3.2.1 the changes are significant. You should also note these major differences.

- The use of thread files has completely changed. Read the section "The Config Files" carefully.
- The mask file format has changed. Read the section about "Mask File"
- Pre_capture feature introduced in 3.1.12
- Advanced filename feature enables very flexible filename definitions (3.1.13)
- onffmpegclose options enables running external scripts when mpeg file is closed (3.1.13)
- despeckle feature improves motion detection and noise immunity (3.1.13)
- Minimum_motion_frames feature prevents short noise events from being saved (3.1.14)
- If you use the database features you need to note that from version 3.1.15 and forward the fields have been redefined. Removed are second, minute, hour, day, month and year. Instead these six have been replaced by a real timestamp field called time_stamp. The relatively new field 'type' has been renamed to 'file_type' to avoid reserved SQL words. A new field 'text_left' has been added which stores the text given by the config option text_left. And last a field called 'camera' has been added which stores the thread number.
- From 3.1.15 the ffmpeg feature now also supports mpeg4 and msmpeg4. The build process of Motion now use ffmpeg libraries as shared libraries. The --with-libavcodec has been replaced by a --with-ffmpeg which only needed to specify if you are installing ffmpeg from sources in a non-standard location. If you have installed ffmpeg from sources already you will need to rebuild by running (from within the ffmpeg source file root) ./configure --enable-shared followed by make and make install. If you had installed ffmpeg from a binary RPM or deb you probably don't have to do anything.
- Rotate feature was introduced in 3.1.15
- Berkeley mpeg feature has been removed in 3.1.18 (use ffmpeg - it is much better)
- Incomplete prediction feature was removed in 3.1.18. (lack of interest in finishing it)
- Smart Mask feature introduced in 3.1.18
- output_normal can now also have the value "first" which means only save first jpg from each event (3.1.18)
- ffmpeg-0.4.9 is now supported. Motion detection mpegs can no longer be saved as mpeg1 (ffmpeg does not support non-standard framerates in 0.4.9) (3.1.18)
- Motion now supports most (not all) mjpeg streaming cameras (3.1.18).
- output_normal can now have values "first" or "best". It is used when you need to present a link to an mpeg movie shown as a single jpeg image. "First" saves the first picture frame in the new event. "Best" saves the picture frame with most motion content (most changed pixels) when the event is over. "on" still saves all motion detection picture frames plus pre and post captured images. With "best" you can set jpeg_filename = "preview" and it gets the same filename as the mpeg file but with extension .jpg. Option "locate" can also take the value "preview" which makes it only draw a rectangel on the jpeg but not on the mpeg movie. (3.2.1)
- The xmlrpc remote control interface is replaced by a much nicer http remote control interface. (3.2.1)
- All the options that calls external programs have been made much more generic. New onxxxx options have been added. Execute, sms and mail have been replaced by the generic on_event_start. (3.2.1)
- New setup mode makes setting all the detection options much easier.
- netcam now also supports proxies (3.2.2) and ftp (3.2.4)
- text on the pictures can be set to double size (3.2.2)
- Tracking with Logitech Sphere/Orbit improved (3.2.4)
- SQL database feature is now fully configurable so you can control which fields you have in the database.
- Many new conversion specifiers have been added which can be used both in filenames, commands, text, and SQL database features (3.2.2-3.2.4)
- Stepper motor tracking feature extended to also include a Y axis (3.2.5)
- ffmpeg_filename has been renamed to movie_filename to prepare for alternative implementation to mpeg files made with ffmpeg (3.2.5)
- New feature: ffmpeg_deinterlace which can de-interlace using the ffmpeg libs (3.2.5)
- New feature: minimum_frame_time which enables Motion to run at frame rates below 2. minimum_gap feature was removed since this was useless and the new minimum_frame_time feature replaces it with much better function. (3.2.7)
- New feature: process_id_file which writes a PID file when started and removes it when stopped (3.2.7)
- V4L2 support with many new supported palettes : V4L2_PIX_FMT_SBGGR8, V4L2_PIX_FMT_SN9C10X, V4L2_PIX_FMT_JPEG, V4L2_PIX_FMT_UYVY (3.2.8)
- ffmpeg_video_codec allow swf (3.2.8)
- V4L2 fix support for : V4L2_PIX_FMT_MJPEG (3.2.9)
- ffmpeg_video_codec allow flv and ffv1(3.2.9)
- v4l2_palette: allow to choose preferable palette to be use by motion to capture from those supported by your videodevice.
- netcam_http: setup keep_alive , 1.1 or 1.0 http method to be used by netcam.
- on_camera_lost: Command to be executed when a camera can't be opened or if it is lost.
- AreaDetect, on_area_detected: Command to be executed by area_detect trigger.
- ConfigOptionNetcamTolerantCheck , netcam_tolerant_check less strict jpeg checks for network cameras with a poor/buggy firmware ( 3.2.11 ).

The table below shows the new options in the left column, and obsolete options in the right column. If the there are options on both sides in a row it means that the options in the left column replaced the options in the right column.

New Options | Obsolete Options
--- | ---
text_left (3.1.13) text_right (3.1.13) text_changes (3.1.13) | drawtext_user (3.1.13) drawtext_shots (3.1.13) drawtext_changes (3.1.13)
jpeg_filename (3.1.13) ffmpeg_filename (3.1.13) snapshot_filename (3.1.13) timelapse_filename (3.1.13) predict_filename (3.1.13) (predict_filename removed in 3.1.18) | oldlayout (3.1.13) snapshots_overwrite (3.1.13)
snapshot_interval (3.1.13) | snapshots (3.1.13)
| realmotion (3.1.13)
despeckle (3.1.13) |
pre_capture (3.1.12) |
ffmpeg_timelapse (v. 3.1.14) | ffmpeg_timelaps (renamed v 3.1.14)
ffmpeg_timelapse_mode (3.1.14) |
sql_log_image (3.1.14) sql_log_snapshot (3.1.14) sql_log_mpeg (3.1.14) sql_log_timelapse (3.1.14) sql_log_prediction (3.1.14) |
minimum_motion_frames (3.1.14) |
rotate (3.1.15) |
ffmpeg_variable_bitrate (3.1.15) ffmpeg_video_codec (3.1.15) |
| berkeley_single_directory (3.1.18) mpeg_encode (3.1.18) mpeg_encode_bin (3.1.18) adjust_rate off (3.1.18) jpg_cleanup (3.1.18)
| predict_filename (3.1.18) predict_enable (3.1.18) predict_threshold (3.1.18) predict_description (3.1.18) sql_log_prediction (3.1.18)
brightness (3.1.18) contrast (3.1.18) saturation (3.1.18) hue (3.1.18) |
smart_mask_speed (3.1.18) |
output_normal valid values are now "on", "off", "first" (3.1.18) and "best" (3.2.1) |
setup_mode (3.2.1) | always_changes (3.2.1)
locate valid values are now "on", "off", "preview" (3.2.1) |
jpeg_filename Besides normal path names the value "preview" has speciel meaning together with output_normal = "best" (3.2.1) |
control_html_output (3.2.1) |
on_event_start (3.2.1) | execute (3.2.1) sms (3.2.1) mail (3.2.1)
on_event_end (3.2.1) |
on_motion_detected (3.2.1) |
on_picture_save (3.2.1) | onsave (3.2.1)
on_movie_start (3.2.1) on_movie_end (3.2.1) | onmpeg (3.2.1) onffmpegclose (introduced 3.1.13)(renamed to on_movie_end 3.2.1)
netcam_proxy (3.2.2) |
text_double (3.2.2) |
webcam_motion Feature has been heavily improved so it is actually usefull now (3.2.2). |
netcam_url Now also supports fetching single frame jpeg pictures via ftp using ftp:// syntax (3.2.4) |
track_step_angle_x (3.2.4) track_step_angle_y (3.2.4) Add better configuration of auto tracking with a Logitech Sphere/Orbit camera. |
track_move_wait (3.2.4) track_auto (3.2.4) Adds better configuration of auto tracking feature |
sql_query (3.2.4) Adds full flexibility of defining fields when using the SQL database features. |
track_maxy (3.2.5) track_motory (3.2.5) |
movie_filename (3.2.5) | ffmpeg_filename (3.2.5)
ffmpeg_deinterlace (3.2.5) |
minimum_frame_time (3.2.7) | minimum_gap (3.2.7)
process_id_file (3.2.7) |
ffmpeg_video_codec allow swf (3.2.8) |
ffmpeg_video_codec allow flv and ffv1 (3.2.9) |
v4l2_palette (3.2.10) netcam_http (3.2.10) on_camera_lost (3.2.10) area_detect, on_area_detected(3.2.10) ffmpeg_video_codec mov(3.2.10) output_normal center(3.2.10) |
| night_compensate (3.2.10) low_cpu (3.2.10)
netcam_tolerant_check (3.2.11) |

## Running Motion

### Important Definitions

Motion is invoked from the command line. It has no GUI. Everything is controlled from config files. From version 3.2 the command line is only used to define location of config file and a few special runtime modes (setup and non-daemon).

A few important definitions.

- A snapshot is a picture taken at regular intervals independently of any movement in the picture.
- A "motion" image/mpeg shows the pixels that have actually changed during the last frames. These pictures are not very useful for normal presentation to the public but they are quite useful for testing and tuning and making mask files as you can see exactly where motion sees something moving. Motion is shown in greytones. If labelling is enabled the largest area is marked as blue. Smart mask is shown in read.
- A "normal" image is the real image taken by the camera with text overlayed.

### The Config Files

If Motion was invoked with command line option `-c pathname` Motion will expect the config file to be as specified. When you specify the config file on the command line with -c you can call it anything.

If you do not specify -c or the filename you give Motion does not exist, Motion will search for the configuration file called 'motion.conf' in the following order:

1. Current directory from where motion was invoked
2. Then in a directory called '.motion' in the current users home directory (shell environment variable $HOME). E.g. /home/goofy/.motion/motion.conf
3. The directory defined by the --sysconfdir=DIR when running .configure during installation of Motion
   (If this option was not defined the default is /usr/local/etc/)

If you have write access to /usr/local/etc then the editor recommends having only one motion.conf file in the default /usr/local/etc/ directory.

Motion has a configuration file in the distribution package called motion-dist.conf. When you run 'make install' this file gets copied to the /usr/local/etc directory.

The configuration file needs to be renamed from motion-dist.conf to motion.conf. The original file is called motion-dist.conf so that your perfectly working motion.conf file does not accidentally get overwritten when you re-install or upgrade to a newer version of Motion.

If you have more than one camera you should not try and invoke Motion more times. Motion is made to work with more than one camera in a very elegant way and the way to do it is to create a number of thread config files. Motion will then create an extra tread of itself for each camera. If you only have one camera you only need the motion.conf file. The minute you have two or more cameras you must have one thread config file per camera besides the motion.conf file.

So if you have for example two cameras you need motion.conf and two thread config files. Total of 3 config files.

An option that is common to all cameras can be placed in motion.conf. (You can also put all parameters in the thread files but that makes a lot of editing when you change a common thing).

An option that is unique to a camera must be defined in each thread file.

It is often seen that people copy the entire motion.conf into the thread config files and change a few options. This works but it not recommended because it is more difficult to maintain and overview. Keep all the common options in motion.conf and the few unique only in the thread config files

The first camera is defined in the first thread file called from motion.conf. The 2nd camera is defined in the 2nd thread file called from motion.conf etc.

Any option defined in motion.conf will be used for all cameras except for the cameras in which the same option is defined in a thread config file.

Motion reads its configuration parameters in the following sequence. If the same parameter exists more than one place the last one read wins.

1. Motion reads the configuration file motion.conf from the beginning of the file going down line by line.
2. If the option "thread" is defined in motion.conf, the thread configuration file(s) is/(are) read.
3. Motion continues reading the rest of the motion.conf file. Any options from here will overrule the same option previously defines in a thread config file.
4. Motion reads the command line option again overruling any previously defined options.

So always call the thread config files in the end of the motion.conf file. If you define options in motion.conf AFTER the thread file calls, the same options in the thread files will never be used. So always put the thread file call at the end of motion.conf.

Nearly all config options can be unique for a specific camera and placed in a thread config file. There are a few options that must be in motion.conf and cannot be in a thread config file: control_authentication, control_html_output, control_localhost, control_port, daemon, and thread.

If motion is built without specific features such as ffmpeg, mysql etc it will ignore the options that belongs to these features. You do not have to remove them or comment them out.

If you run the http control command http://host:port/0/config/writeyes, motion will overwrite motion.conf and all the thread.conf files by autogenerated config files neatly formatted and only with the features included that Motion was built with. If you later re-build Motion with more features or upgrade to a new version, you can use your old config files, run the motion.conf.write command, and you will have new config files with the new options included all set to their default values. This makes upgrading very easy to do.

## Command Line Options

In Motion 3.2.1 and forward most command line options have been removed and replaced them by an option to specify location to motion.conf and a few options related to setting up motion. There are now only few command line options left and they are basically all new.

SYNOPSIS

    motion [ -hns ] [ -c config file path ] [ -d level ]  [ -p process_id_file ]

Option | Description | Editors comment
--- | --- | ---
-n | Run in non-daemon mode. | Instead of running Motion in the background Motion runs in the terminal window writing messages when things happen. If you have problems getting Motion to start or work, run Motion in this mode to get more messages that can help you solve the problem.
-s | Run in setup mode. | Also forces non-daemon mode
-c config file path | Full path and filename of config file. | E.g. /home/kurt/motion.conf. Default is /usr/local/etc unless specified differently when building Motion. Many RPMs and debian packages will most likely use /etc or /etc/motion as default
-h | Show help screen. |
-d level | Debugging mode | This mode is used for developers to enable debug messages. Normal users will not need to use this mode unless a developer request to get additional information in the attempt to resolve a bug. Mainly the netcam code has debugging features. The level defines how much debugging info you get. A high number displays all debugging.
-p process_id_file | Full path of process ID file | Full path and filename of process id file (PID file). This is optional. If none is given as command line option or in motion.conf (process_id_file) Motion will not create a PID file.

## Config File Options

These are the options that can be used in the config file.

All number values are integer numbers (no decimals allowed). Boolean options can be on or off.

Some configuration options are only used if Motion is built on a system that has the matching software libraries installed (MySQL, PostgreSQL and FFMPEG).

MySQL

- mysql_db, mysql_host, mysql_user, mysql_password

PostgreSQL

- pgsql_db, pgsql_host, pgsql_user, pgsql_password, pgsql_port

FFMPEG (libavcodec)

- ffmpeg_cap_new, ffmpeg_cap_motion, ffmpeg_filename, ffmpeg_timelapse, ffmpeg_timelapse_mode, ffmpeg_bps, ffmpeg_variable_bitrate, ffmpeg_video_codec

### Options in Alphabetical Order.

The table below lists all the Motion options in alphabetical order. Click on the option name to see a longer description of each.

Option | Range/Values Default | Description
--- | --- | ---
area_detect | Values: 1 - 999999999 Default: Not defined | Detect motion center in predefined areas. A script (on_area_detected) is started immediately when motion center is detected in one of the given areas, but only once during an event even if there is motion in a different configured area.
auto_brightness | Values: on, off Default: off | Let motion regulate the brightness of a video device. Only recommended for cameras without auto brightness
brightness | Values: 0 - 255 Default: 0 (disabled) | The brightness level for the video device.
contrast | Values: 0 - 255 Default: 0 (disabled) | The contrast level for the video device.
control_authentication | Values: Max 4096 characters Default: Not defined | To protect HTTP Control by username and password, use this option for HTTP 1.1 Basic authentication. The string is specified as username:password. Do not specify this option for no authentication. This option must be placed in motion.conf and not in a thread config file.
control_html_output | Values: on, off Default: on | Enable HTML in the answer sent back to a browser connecting to the control_port. This option must be placed in motion.conf and not in a thread config file.
control_localhost | Values: on, off Default: on | Limits the http (html) control to the localhost. This option must be placed in motion.conf and not in a thread config file.
control_port | Values: 0 - 65535 Default: 0 (disabled) | Sets the port number for the http (html using browser) based remote control. This option must be placed in motion.conf and not in a thread config file.
daemon | Values: on, off Default: off | Start in daemon (background) mode and release terminal. This option must be placed in motion.conf and not in a thread config file.
despeckle | Values: EedDl Default: Not defined | Despeckle motion image using combinations of (E/e)rode or (D/d)ilate. And ending with optional (l)abeling.
ffmpeg_bps | Values: 0 - 9999999 Default: 400000 | Bitrate of mpegs produced by ffmpeg. Bitrate is bits per second. Default: 400000 (400kbps). Higher value mans better quality and larger files. Option requires that ffmpeg libraries are installed.
ffmpeg_cap_motion | Values: on, off Default: off | Use ffmpeg libraries to encode motion type mpeg movies where you only see the pixels that changes.
ffmpeg_cap_new | Values: on, off Default: off | Use ffmpeg libraries to encode mpeg movies in realtime.
ffmpeg_deinterlace | Values: on, off Default: off | Use ffmpeg to deinterlace video. Necessary if you use an analog camera and see horizontal combing on moving objects in video or pictures.
ffmpeg_filename (now called movie_filename) | Values: Max 4095 characters Default: %v-%Y%m%d%H%M%S | File path for motion triggered ffmpeg movies (mpeg) relative to target_dir. This option was renamed to movie_filename in 3.2.5 to enable better integration of alternative movie libraries to the current ffmpeg solution.
ffmpeg_timelapse | Values: 0 - 2147483647 Default: 0 (disabled) | Create a timelapse movie saving a picture frame at the interval in seconds set by this parameter. Set it to 0 if not used.
ffmpeg_timelapse_mode | Values: hourly, daily, weekly-sunday, weekly-monday, monthly, manual Default: daily | The file rollover mode of the timelapse video.
ffmpeg_variable_bitrate | Values: 0, 2 - 31 Default: 0 (disabled) | Enables and defines variable bitrate for the ffmpeg encoder. ffmpeg_bps is ignored if variable bitrate is enabled. Valid values: 0 (default) = fixed bitrate defined by ffmpeg_bps, or the range 2 - 31 where 2 means best quality and 31 is worst.
ffmpeg_video_codec | Values: mpeg1 (ffmpeg-0.4.8 only), mpeg4, msmpeg4, swf, flv, ffv1, mov Default: mpeg4 | Codec to be used by ffmpeg for the video compression. Timelapse mpegs are always made in mpeg1 format independent from this option.
framerate | Values: 2 - 100 Default: 100 (no limit) | Maximum number of frames to be captured from the camera per second.
frequency | Values: 0 - 999999 Default: 0 (Not set) | The frequency to set the tuner to (kHz). Valid range: per tuner spec, default: 0 (Don't set it)
gap | Values: 0 - 2147483647 Default: 60 | Gap is the seconds of no motion detection that triggers the end of an event. An event is defined as a series of motion images taken within a short timeframe.
height | Values: Device Dependent Default: 288 | The height of each frame in pixels.
hue | Values: 0 - 255 Default: 0 (disabled) | The hue level for the video device.
input | Values: 0 - 7, 8 = disabled Default: 8 (disabled) | Input channel to use expressed as an integer number starting from 0. Should normally be set to 1 for video/TV cards, and 8 for USB cameras.
jpeg_filename | Values: Max 4095 characters Default: %v-%Y%m%d%H%M%S-%q | File path for motion triggered images (jpeg or ppm) relative to target_dir. Value 'preview' makes a jpeg filename with the same name body as the associated saved mpeg movie file.
lightswitch | Values: 0 - 100 Default: 0 (disabled) | Ignore sudden massive light intensity changes given as a percentage of the picture area that changed intensity.
locate | Values: on, off, preview Default: off | Locate and draw a box around the moving object. Value 'preview' makes Motion only draw a box on a saved preview jpeg image and not on the saved mpeg movie.
mask_file | Values: Max 4095 characters Default: Not defined | PGM file to use as a sensitivity mask. This picture MUST have the same width and height as the frames being captured and be in binary format.
max_mpeg_time | Values: 0 (infinite) - 2147483647 Default: 3600 | The maximum length of an mpeg movie in seconds. Set this to zero for unlimited length.
minimum_frame_time | Values: 0 - 2147483647 Default: 0 | Minimum time in seconds between the capturing picture frames from the camera. Default: 0 = disabled - the capture rate is given by the camera framerate.
minimum_motion_frames | Values: 1 - 1000s Default: 1 | Picture frames must contain motion at least the specified number of frames in a row before they are detected as true motion. At the default of 1, all motion is detected. Valid range is 1 to thousands, but it is recommended to keep it within 1-5.
motion_video_pipe | Values: Max 4095 characters Default: Not defined | The video4linux video loopback input device for motion images. If a particular pipe is to be used then use the device filename of this pipe, if a dash '-' is given motion will use /proc/video/vloopback/vloopbacks to locate a free pipe. Default: not set
movie_filename | Values: Max 4095 characters Default: %v-%Y%m%d%H%M%S | File path for motion triggered ffmpeg movies (mpeg) relative to target_dir. This was previously called ffmpeg_filename.
mysql_db | Values: Max 4095 characters Default: Not defined | Name of the MySQL database.
mysql_host | Values: Max 4095 characters Default: localhost | IP address or domain name for the MySQL server. Use "localhost" if motion and MySQL runs on the same server.
mysql_password | Values: Max 4095 characters Default: Not defined | The MySQL password.
mysql_user | Values: Max 4095 characters Default: Not defined | The MySQL user name.
netcam_http | Values: 1.0, keep_alive, 1.1 Default: 1.0 | The setting for keep-alive of network socket, should improve performance on compatible net cameras. ( new in 3.2.10 )
netcam_proxy | Values: Max 4095 characters Default: Not defined | URL to use for a netcam proxy server, if required. The syntax is http://myproxy:portnumber
netcam_tolerant_check | Values: on, off Default: off | Set less strict jpeg checks for network cameras with a poor/buggy firmware.
netcam_url | Values: Max 4095 characters Default: Not defined | Specify an url to a downloadable jpeg file or raw mjpeg stream to use as input device. Such as an AXIS 2100 network camera.
netcam_userpass | Values: Max 4095 characters Default: Not defined | For network cameras protected by username and password, use this option for HTTP 1.1 Basic authentication. The string is specified as username:password. Do not specify this option for no authentication.
noise_level | Values: 1 - 255 Default: 32 | The noise level is used as a threshold for distinguishing between noise and motion.
noise_tune | Values: on, off Default: on | Activates the automatic tuning of noise level.
norm | Values: 0 (PAL), 1 (NTSC), 2 (SECAM), 3 (PAL NC no colour) Default: 0 (PAL) | Select the norm of the video device. Values: 0 (PAL), 1 (NTSC), 2 (SECAM), 3 (PAL NC no colour). Default: 0 (PAL)
on_area_detected | Values: Max 4095 characters Default: Not defined | Command to be executed when motion in a predefined area is detected. Check option area_detect.
on_camera_lost | Values: Max 4095 characters Default: Not defined | Command to be executed when a camera can't be opened or if it is lost. You can use Conversion Specifiers and spaces as part of the command. Use %f for passing filename (with full path) to the command. (new in 3.2.10)
on_event_end | Values: Max 4095 characters Default: Not defined | Command to be executed when an event ends after a period of no motion. The period of no motion is defined by option gap. You can use Conversion Specifiers and spaces as part of the command.
on_event_start | Values: Max 4095 characters Default: Not defined | Command to be executed when an event starts. An event starts at first motion detected after a period of no motion defined by gap. You can use ConversionSpecifiers and spaces as part of the command.
on_motion_detected | Values: Max 4095 characters Default: Not defined | Command to be executed when a motion frame is detected. You can use Conversion Specifiers and spaces as part of the command.
on_movie_end | Values: Max 4095 characters Default: Not defined | Command to be executed when an ffmpeg movie is closed at the end of an event. You can use Conversion Specifiers and spaces as part of the command. Use %f for passing filename (with full path) to the command.
on_movie_start | Values: Max 4095 characters Default: Not defined | Command to be executed when an mpeg movie is created. You can use Conversion Specifiers and spaces as part of the command. Use %f for passing filename (with full path) to the command.
on_picture_save | Values: Max 4095 characters Default: Not defined | Command to be executed when an image is saved. You can use Conversion Specifiers and spaces as part of the command. Use %f for passing filename (with full path) to the command.
output_all | Values: on, off Default: off | Picture are saved continuously as if motion was detected all the time.
output_motion | Values: on, off Default: off | Output pictures with only the moving object. This feature generates the special motion type movies where you only see the pixels that changes as a graytone image. If labelling is enabled you see the largest area in blue. Smartmask is shown in red.
output_normal | Values: on, off, first, best, center (since 3.2.10) Default: on | Normal image is an image that is stored when motion is detected. It is the same image that was taken by the camera. I.e. not a motion image like defined by output_motion. Default is that normal images are stored.
pgsql_db | Values: Max 4095 characters Default: Not defined | Name of the PostgreSQL database.
pgsql_host | Values: Max 4095 characters Default: localhost | IP address or domain name for the PostgreSQL server. Use "localhost" if motion and PostgreSQL runs on the same server.
pgsql_password | Values: Max 4095 characters Default: Not defined | The PostgreSQL password.
pgsql_port | Values: 0 - 65535 Default: 5432 | The PostgreSQL server port number.
pgsql_user | Values: Max 4095 characters Default: Not defined | The PostgreSQL user name.
post_capture | Values: 0 - 2147483647 Default: 0 (disabled) | Specifies the number of frames to be captured after motion has been detected.
ppm | Values: on, off Default: off | Output ppm images instead of jpeg. This uses less CPU time, but causes a LOT of hard disk I/O, and it is generally slower than jpeg.
pre_capture | Values: 0 - 100s Default: 0 (disabled) | Specifies the number of previous frames to be outputted at motion detection. Recommended range: 0 to 5, default=0. Do not use large values! Large values will cause Motion to skip video frames and cause unsmooth mpegs. To smooth mpegs use larger values of post_capture instead.
process_id_file | Values: Max 4095 characters Default: Not defined | File to store the process ID, also called pid file. Recommended value when used: /var/run/motion.pid
quality | Values: 1 - 100 Default: 75 | The quality for the jpeg images in percent.
quiet | Values: on, off Default: off | Be quiet, don't output beeps when detecting motion.
rotate | Values: 0, 90, 180, 270 Default: 0 (not rotated) | Rotate image the given number of degrees. The rotation affects all saved images as well as mpeg movies.
roundrobin_frames | Values: 1 - 2147483647 Default: 1 | Specifies the number of frames to capture before switching inputs, this way also slow switching (e.g. every second) is possible.
roundrobin_skip | Values: 1 - 2147483647 Default: 1 | Specifies the number of frames to skip after a switch. (1 if you are feeling lucky, 2 if you want to be safe).
saturation | Values: 0 - 255 Default: 0 (disabled) | The colour saturation level for the video device.
setup_mode | Values: on, off Default: off | Run Motion in setup mode.
smart_mask_speed | Values: 0 - 10 Default: 0 (disabled) | Slugginess of the smart mask. Default is 0 = DISABLED. 1 is slow, 10 is fast.
snapshot_filename | Values: Max 4095 characters Default: %v-%Y%m%d%H%M%S-snapshot | File path for snapshots (jpeg or ppm) relative to target_dir.
snapshot_interval | Values: 0 - 2147483647 Default: 0 (disabled) | Make automated snapshots every 'snapshot_interval' seconds.
sql_log_image | Values: on, off Default: on | Log to the database when creating motion triggered image file.
sql_log_mpeg | Values: on, off Default: off | Log to the database when creating motion triggered mpeg file.
sql_log_snapshot | Values: on, off Default: on | Log to the database when creating a snapshot image file.
sql_log_timelapse | Values: on, off Default: off | Log to the database when creating timelapse mpeg file
sql_query | Values: Max 4095 characters Default: insert into security(camera, filename, frame, file_type, time_stamp, text_event) values('%t', '%f', '%q', '%n', '%Y-%m-%d %T', '%C') | SQL query string that is sent to the database. The values for each field are given by using convertion specifiers
switchfilter | Values: on, off Default: off | Turns the switch filter on or off. The filter can distinguish between most switching noise and real motion. With this you can even set roundrobin_skip to 1 without generating much false detection.
target_dir | Values: Max 4095 characters Default: Not defined = current working directory | Target directory for picture and movie files.
text_changes | Values: on, off Default: off | Turns the text showing changed pixels on/off.
text_double | Values: on, off Default: off | Draw characters at twice normal size on images.
text_event | Values: Max 4095 characters Default: %Y%m%d%H%M%S | This option defines the value of the speciel event conversion specifier %C. You can use any conversion specifier in this option except %C. Date and time values are from the timestamp of the first image in the current event.
text_left | Values: Max 4095 characters Default: Not defined | User defined text overlayed on each in the lower left corner. Use A-Z, a-z, 0-9, " / ( ) @ ~ # < > , . : - + _ \n and vertical bar and conversion specifiers (codes starting by a %).
text_right | Values: Max 4095 characters Default: %Y-%m-%d\n%T | User defined text overlayed on each in the lower right corner. Use A-Z, a-z, 0-9, " / ( ) @ ~ # < > , . : - + _ \n and vertical bar and conversion specifiers (codes starting by a %). Default: %Y-%m-%d\n%T = date in ISO format and time in 24 hour clock
thread | Values: Max 4095 characters Default: Not defined | Specifies full path and filename for a thread config file. Each camera needs a thread config file containing the options that are unique to the camera. If you only have one camera you do not need thread config files. If you have two or more cameras you need one thread config file for each camera in addition to motion.conf. This option must be placed in motion.conf and not in a thread config file.
threshold | Values: 1 - 2147483647 Default: 1500 | Threshold for declaring motion. The threshold is the number of changed pixels counted after noise filtering, masking, despeckle, and labelling.
threshold_tune | Values: on, off Default: off | Activates the automatic tuning of threshold level. ( It's broken )
timelapse_filename | Values: Max 4095 characters Default: %v-%Y%m%d-timelapse | File path for timelapse mpegs relative to target_dir (ffmpeg only).
track_auto | Values: on, off Default: off | Enable auto tracking
track_iomojo_id | Values: 0 - 65535 Default: 0 | Use this option if you have an iomojo smilecam connected to the serial port instead of a general stepper motor controller.
track_maxx | Values: 0 - 65535 Default: 0 | The maximum position for servo x.
track_maxy | Values: 0 - 65535 Default: 0 | The maximum position for servo y.
track_motorx | Values: 0 - 65535 Default: 0 | The motor number that is used for controlling the x-axis.
track_motory | Values: 0 - 65535 Default: 0 | The motor number that is used for controlling the y-axis.
track_move_wait | Values: 0 - 65535 Default: 10 | Delay during which tracking is disabled after auto tracking has moved the camera. Delay is defined as number of picture frames.
track_port | Values: Max 4095 characters Default: Not defined | This is the device name of the serial port to which the stepper motor interface is connected.
track_speed | Values: 0 - 255 Default: 255 | Speed to set the motor to.
track_step_angle_x | Values: 0-90 Default: 10 | Angle in degrees the camera moves per step on the X-axis with auto tracking. Currently only used with pwc type cameras.
track_step_angle_y | Values: 0-40 Default: 10 | Angle in degrees the camera moves per step on the Y-axis with auto tracking. Currently only used with pwc type cameras.
track_stepsize | Values: 0 - 255 Default: 40 | Number of steps to make.
track_type | Values: 0 (none), 1 (stepper), 2 (iomojo), 3 (pwc), 4 (generic), 5 (uvcvideo) Default: 0 (None) | Type of tracker.
tunerdevice | Values: Max 4095 characters Default: /dev/tuner0 | The tuner device used for controlling the tuner in a tuner card. This option is only used when Motion is compiled for FreeBSD.
v4l2_palette | Values: 0 - 8 Default: 8 | Allow to choose preferable palette to be use by motion to capture from those supported by your videodevice. ( new in 3.2.10 )
video_pipe | Values: Max 4095 characters Default: Not defined | The video4linux video loopback input device for normal images. If a particular pipe is to be used then use the device filename of this pipe. If a dash '-' is given motion will use /proc/video/vloopback/vloopbacks to locate a free pipe.
videodevice | Values: Max 4095 characters Default: /dev/video0 (FreeBSD: /dev/bktr0) | The video device to be used for capturing. Default for Linux is /dev/video0. for FreeBSD the default is /dev/bktr0.
webcam_limit | Values: 0 - 2147483647 Default: 0 (unlimited) | Limit the number of frames to number frames. After 'webcam_limit' number of frames the connection will be closed by motion. The value 0 means unlimited.
webcam_localhost | Values: on, off Default: on | Limits the access to the webcam to the localhost.
webcam_maxrate | Values: 1 - 100 Default: 1 | Limit the framerate of the webcam in frames per second. Default is 1. Set the value to 100 for practically unlimited.
webcam_motion | Values: on, off Default: off | If set to 'on' Motion sends slows down the webcam stream to 1 picture per second when no motion is detected. When motion is detected the stream runs as defined by webcam_maxrate. When 'off' the webcam stream always runs as defined by webcam_maxrate.
webcam_port | Values: 0 - 65535 Default: 0 (disabled) | TCP port on which motion will listen for incoming connects with its webcam server.
webcam_quality | Values: 1 - 100 Default: 50 | Quality setting in percent for the mjpeg picture frames transferred over the webcam connection. Keep it low to restrict needed bandwidth.
width | Values: Device Dependent Default: 352 | The width in pixels of each frame. Valid range is camera dependent.

### Obsolete Options

Option | Range/Values Default | Description
--- | --- | ---
low_cpu | Values: 0 - 100 Default: 0 (disabled) | When this option is not zero motion will be in a low cpu mode while not detecting motion. In low cpu mode Motion reduces the framerate to the value given for this option. Value zero means disabled. ( DEPRECATED )
minimum_gap | Values: 0 - 2147483647 Default: 0 (no minimum) | The minimum time between two shots in seconds. ( DEPRECATED )
night_compensate | Values: on, off Default: off | When this option is set the noise threshold will be lowered if the picture is dark. This will improve the sensitivity in dark places. However it might also increase the number of false alarms since most cameras also increase light sensitivity with their AGC (Automatic Gain Control) and this will increase noise. ( DEPRECATED )

## Signals (sent with e.g. kill command)

A signal can be sent from the command line by typing e.g. `kill -s SIGHUP pid`, where the last parameter is the process ID which you get by typing `ps -ef ¦ grep motion`. The PID is the first on the list which is the parent process for the threads. Motion responds to the following signals:

Signal | Description | Editors comment
--- | --- | ---
SIGHUP | The config file will be reread. | This is a very useful signal when you experiment with settings in the config file.
SIGTERM | If needed motion will create an mpeg file of the last event and exit |
SIGUSR1 | Motion will create an mpeg file of the current event. |

## Error Logging

Motion reports errors to the console when it runs in non-daemon mode. And it outputs even more information when run in setup mode.

Error logging has been implemented so that errors during daemon (background) mode are logged in the syslog.

The syslog is in most Linux systems the file `/var/log/messages` (e.g. RedHat/Fedora) or `/var/log/syslog` and `/var/log/user.log` (e.g. Debian).

# Motion Guide - Basic Features

## Capture Device Options - The Basic Setup

Before you can start using motion you need to know some basics about your camera. Either you have a camera connected directly to your computer. In this case it is a video4linux type of camera. Or you connect to a network camera using a normal web URL.

## video4linux (V4L) devices

You need to install your camera with the right driver. It is out of scope of this document to tell you how to do this and it depends on which type of camera.

Once installed the camera(s) will have the device names /dev/video0, /dev/video1, /dev/video2...

FreeBSD has a different naming of devices. When you build Motion for FreeBSD the default device name is /dev/bktr0. Under FreeBSD a TV card has a special device for controlling the tuner (e.g. /dev/tuner0). The option tunerdevice is only valid when Motion is built and running under FreeBSD. For Linux do not include this option in the config file (remove or comment out).

USB cameras take a lot of bandwidth. A USB camera connected to a USB 1.1 port or hub consumes all the bandwidth. Even with a small framesize and low framerate you should not expect to have more than one camera per USB 1.1 controller. If you need more than 1 USB camera add extra USB PCI cards to your computer. There exists cards that have 4 inputs each with their own controller and with full bandwidth. Many 4-input cards only have 1 controller. USB cameras do not have the feature of selecting input channels. To disable the input selection the option input must be set to the value 8 for USB cameras.

Composite video cards are normally made with a chip called BT878 (older cards have a BT848). They all use the Linux driver called 'bttv'.

There are cards with more then one video input but still only one BT878 chip. They have a video multiplexer which input is selected with the config option input. Input channel numbers start at 0 (which is why the value 8 and not 0 disables input selection). There are video capture cards available with 4 or 8 inputs but only one chip. They present themselves as one single video device and you select input using the 'input' option. If you define e.g. 4 thread config files with the same videodevice name but different input numbers Motion automatically goes into round robin mode. See the round robin section for more information. Many TV tuner cards have the input channels: TV Tuner = 0, Standard composite video = 1, S-VHS = 3. Other have TV=0, composite video 1= 1, composite video = 2, S-VHS = 3. For video capture cards input 1 is normally the composite video input.

Some capture cards are specially made for surveillance with for example 4 inputs. Others have a TV tuner, a composite input (phono socket) and perhaps also a S-VHS input. For all these cards the inputs are numbered. The numbering varies from card to card so the easiest is to experiment for 5 minutes with a program that can show the videostream. Use a program such as Camstream or xawtv to experiment with the values.

If you use the TV tuner input you also need to set the frequency of the TV channel using the option frequency. Otherwise set 'frequency' to 0.

Finally you need to set the TV norm. Values: 0 (PAL), 1 (NTSC), 2 (SECAM), 3 (PAL NC no colour). Default is 0 (PAL). If your camera is a PAL black and white you may get a better result with norm=3 (PAL no colour).

If the netcam_url option is defined all the video4linux options are ignored so make sure the netcam_url option is commented out if you do not need it.

These are the parameters used for video4linux devices

### auto_brightness

- Type: Boolean
- Range / Valid values: on, off
- Default: off
- Option Topic

Let motion regulate the brightness of a video device. Only recommended for cameras without auto brightness

Motion will try to adjust the brightness of the video device if the images captured are too dark or too light. This option will be most useful for video devices like web cams, which sometimes don't have such an option in hardware.

The auto_brightness feature will adjust the brightness of the device up or down until the value defined by the option brightness is reached (1 = dark, 255 = bright). If brightness is zero auto_brightness will try to adjust to the average brightness level 128.

You need to know if the camera supports auto brightness. Most cameras have auto everything. If your video device already does this for you this option might cause oscillations. If you do not know assume that it has and do not use the Motion auto brightness feature. At least not to start with.

### brightness

- Type: Integer
- Range / Valid values: 0 - 255
- Default: 0 (disabled)
- Option Topic

The brightness level for the video device.

Value 0 means that Motion does not set the brightness value but leaves it unchanged.

If this setting is used in conjunction with the auto_brightness feature then this setting is the average brightness level in the range 1 (dark) to 255 (bright) that the auto_brightness feature will try to achieve by adjusting the device brightness up and down.

### contrast

- Type: Boolean
- Range / Valid values: 0 - 255
- Default: 0 (disabled)
- Option Topic

The contrast level for the video device.

Disabled (Value 0) means that Motion does not set the contrast value.

### framerate

- Type: Integer
- Range / Valid values: 2 - 100
- Default: 100 (no limit)
- Option Topic

Maximum number of frames to be captured from the camera per second.

The faster you fetch pictures from the camera the more CPU load you get and the more pictures get included when Motion is detected.

Motion will stop storing pictures if the framerate is set to less than 2.

Set this parameter to the maximum number of images per second that you want to store either as images or as mpeg films.

To set intervals longer than one second use the 'minimum_gap' option instead.

### frequency

- Type: Boolean
- Range / Valid values: 0 - 999999
- Default: 0 (Not set)
- Option Topic

The frequency to set the tuner to (kHz). Valid range: per tuner spec, default: 0 (Don't set it)

This option is only relevant if you have a TV tuner card where you can select the tuner frequency. Your tuner card must support this feature.

### height

- Type: Integer
- Range / Valid values: Device Dependent
- Default: 288
- Option Topic

The height of each frame in pixels.

The height of the image in pixels. Motion does not scale so should be set to the actual size of the v4l device. In case of a net camera motion sets the height to the height of the first image read.

Motion actually set the size of the image coming from the video4linux device.

Your camera or capture/TV card will not support any picture size. You must know which frame size (width and height) the camera supports. If you do not know start with width 320 and height 240 which most cameras and capture cards supports.

For some device drivers like pwc (driver for Philips USB cameras) setting the size to a non-standard value makes the driver create an image of the nearest smaller size and create a gray band around the image to fit the size given by motion. Note that it is the driver and not motion that generates the gray band. Motion will try to detect motion in the entire image including the gray band.

Motion requires that dimensions of camera image must have both height and width that are a multiple of 16. Thís is normally not a problem. All standard sizes like 640, 480, 352, 320, 288, 240, ...etc are multiples of 16.

### hue

- Type: Integer
- Range / Valid values: 0 - 255
- Default: 0 (disabled)
- Option Topic

The hue level for the video device.

Normally only relevant for NTSC cameras.

### input

- Type: Integer
- Range / Valid values: 0 - 7, 8 = disabled
- Default: 8 (disabled)
- Option Topic

Input channel to use expressed as an integer number starting from 0. Should normally be set to 1 for video/TV cards, and 8 for USB cameras.

This parameter is really used only with video capture cards that has more than one input.

However if you set the input number to e.g. 1 for a USB camera (ov511 or pwc driver) motion writes an error message back. If you set it to 8 it does not give you any warning.

If you have a video capture card you can define the channel to tune to using this option. If you are using a USB device, network camera or a capture card without tuner you should set the value to the default 8.

Many TV tuner cards have the input channels: TV Tuner = 0, Standard composite video = 1, S-VHS = 3. Other have TV=0, composite video 1= 1, composite video = 2, S-VHS = 3. It is recommended to set the parameter to 8 for USB cameras as your first try. For video capture cards input 1 is normally the composite video input.

### minimum_frame_time

- Type: Integer
- Range / Valid values: 0 - 2147483647
- Default: 0
- Option Topic

Minimum time in seconds between the capturing picture frames from the camera. Default: 0 = disabled - the capture rate is given by the camera framerate.

This option is used when you want to capture images at a rate lower than 2 per second.

When this is enabled the framerate option is used only to set the pace the Motion service the webcam port etc. Running Motion at framerate 2 is normally fine.

This feature is introduced in Motion 3.2.7

### norm

- Type: Discrete Strings
- Range / Valid values: 0 (PAL), 1 (NTSC), 2 (SECAM), 3 (PAL NC no colour)
- Default: 0 (PAL)
- Option Topic

Select the norm of the video device. Values: 0 (PAL), 1 (NTSC), 2 (SECAM), 3 (PAL NC no colour). Default: 0 (PAL)

This value is only used for capture cards using the BTTV driver.

### rotate

- Type: Discrete Strings
- Range / Valid values: 0, 90, 180, 270
- Default: 0 (not rotated)
- Option Topic

Rotate image the given number of degrees. The rotation affects all saved images as well as mpeg movies.

The rotation feature is used when the camera is hanging upside down (180 degrees) or if you choose a picture format in portrait instead of the normal landscape (90 or 270 degrees).

Note that the CPU load increases when using this feature with a value other than 0. Also note that Motion automatically swaps width and height if you rotate 90 or 270 degrees, so you don't have to touch these options.

### saturation

- Type: Integer
- Range / Valid values: 0 - 255
- Default: 0 (disabled)
- Option Topic

The colour saturation level for the video device.

### tunerdevice

- Type: String
- Range / Valid values: Max 4095 characters
- Default: /dev/tuner0
- Option Topic

The tuner device used for controlling the tuner in a tuner card. This option is only used when Motion is compiled for FreeBSD.

Make sure to remove or comment out this option when running Motion under Linux.

### v4l2_palette

- Type: Integer
- Range / Valid values: 0 - 8
- Default: 8
- Option Topic

Allow to choose preferable palette to be use by motion to capture from those supported by your videodevice. ( new in 3.2.10 )

i.ex if your videodevice supports V4L2 _PIX_FMT_SBGGR8 and V4L2 _PIX_FMT_MJPEG by default motion will use V4L2 _PIX_FMT_MJPEG so set v4l2_palette 1 to force motion use V4L2 _PIX_FMT_SBGGR8 instead.

Values :

    V4L2_PIX_FMT_SN9C10X : 0 'S910'
    V4L2_PIX_FMT_SBGGR8 : 1 'BA81'
    V4L2_PIX_FMT_MJPEG : 2 'MJPEG'
    V4L2_PIX_FMT_JPEG : 3 'JPEG'
    V4L2_PIX_FMT_RGB24 : 4 'RGB3'
    V4L2_PIX_FMT_UYVY : 5 'UYVY'
    V4L2_PIX_FMT_YUYV : 6 'YUYV'
    V4L2_PIX_FMT_YUV422P : 7 '422P'
    V4L2_PIX_FMT_YUV420 : 8 'YU12'

### videodevice

- Type: String
- Range / Valid values: Max 4095 characters
- Default: /dev/video0 (FreeBSD: /dev/bktr0)
- Option Topic

The video device to be used for capturing. Default for Linux is /dev/video0. for FreeBSD the default is /dev/bktr0.

This is the video4linux device name. Ignore this for net cameras.

### width

- Type: Integer
- Range / Valid values: Device Dependent
- Default: 352
- Option Topic

The width in pixels of each frame. Valid range is camera dependent.

Motion does not scale so should be set to the actual size of the v4l device.

In case of a net camera motion sets the height to the height of the first image read.

Motion actually set the size of the image coming from the video4linux device.

Your camera or capture/TV card will not support any picture size. You must know which frame size (width and height) the camera supports. If you do not know start with width 320 and height 240 which most cameras and capture cards supports.

For some device drivers like pwc (driver for Philips USB cameras) setting the size to a non-standard value makes the driver create an image of the nearest smaller size and create a gray band around the image to fit the size given by motion. Note that it is the driver and not motion that generates the gray band. Motion will try to detect motion in the entire image including the gray band.

Motion requires that dimensions of camera image must have both height and width that are a multiple of 16. Thís is normally not a problem. All standard sizes like 640, 480, 352, 320, 288, 240, ...etc are multiples of 16.

## Network Cameras

Motion can connect to a network camera through a normal TCP socket. All you need to give it is the URL. The URL given must return either one single jpeg picture or an mjpeg stream. For the time being Motion cannot connect to a video stream such a mpeg, mpeg4, divx. The URL must return one single jpeg image or an mjpeg stream! You can connect through a proxy server.

Also watch out that you do not use a URL that create an HTML page with an embedded jpg. What must be returned is the jpg picture itself or the raw mjpeg stream.

When the netcam_url is defined all the video4linux options above are ignored!!

If the connection to a network camera is lost - Motion will reuse the last good image for approx 30 seconds. AFter 30 seconds the image is replaced by a grey image with a text telling that the signal is lost and when the connection was lost. This text and its date format is not configurable and there are no plans to make it configurable in order to keep the number config options under control.

Note that Motion requires that dimensions of camera image must have both height and width that are a multiple of 16. Thís is normally not a problem. All standard sizes like 640, 480, 352, 320, 288, 240, ...etc are multiples of 16. But if you intend to monitor a network camera which is saving jpeg images you may have to pay attention to the dimensions of the picture.

The network camera feature has been completely re-written in Motion 3.2.2. We believe the netcam feature is much more stable now that it was in previous versions. Motion tries to reconnect to the camera if the connection is lost. There is no official standard for mjpeg and we know that there are probably still some cameras that are not yet supported. If you run into a problem please file a Bug Report with as much information about the format as possible. A binary raw dump of the first 2-3 frames with headers and boundary strings is very useful. You can see how to make it on the special topic NetcamMjpegStreamDumps. When you have the file you can upload it to the same topic.

### netcam_http

- Type: Discrete Strings
- Range / Valid values: 1.0, keep_alive, 1.1
- Default: 1.0
- Option Topic

The setting for keep-alive of network socket, should improve performance on compatible net cameras. ( new in 3.2.10 )

- 1.0: the historical implementation using HTTP/1.0, closing the socket after each http request.
- keep_alive: Use HTTP/1.0 requests with keep alive header to reuse the same connection.
- 1.1: Use HTTP/1.1 requests that support keep alive as default.

### netcam_proxy

- Type: String
- Range / Valid values: Max 4095 characters
- Default: Not defined
- Option Topic

URL to use for a netcam proxy server, if required. The syntax is http://myproxy:portnumber

Use this if you need to connect to a network camera through a proxy server.

Example of syntax: "http://myproxy.mydomain.com:1024

If the proxy port number is 80 you can ommit the port number. Then the syntax is use "http://myproxy.mydomain.com" .

Leave this option undefined if you do not use a proxy server.

### netcam_tolerant_check

- Type: Boolean
- Range / Valid values: on, off
- Default: off
- Option Topic

Set less strict jpeg checks for network cameras with a poor/buggy firmware.

### netcam_url

- Type: String
- Range / Valid values: Max 4095 characters
- Default: Not defined
- Option Topic

Specify an url to a downloadable jpeg file or raw mjpeg stream to use as input device. Such as an AXIS 2100 network camera.

Example of URL: http://www.gate.com/pe1rxq/jeroen.jpg.

Motion can connect to a network camera through a normal TCP socket. All you need to give it is the URL. The URL given must return either one single jpeg picture or an mjpeg stream. For the time being Motion cannot connect to a video stream such a mpeg, mpeg4, divx. The URL must return one single jpeg image or an mjpeg stream!

Also watch out that you do not use a URL that create an HTML page with an embedded jpg. What must be returned is the jpg picture itself or the raw mjpeg stream.

When the netcam_url is defined all the video4linux options are ignored!!

Motion can also fetch jpeg pictures via ftp. You then use the ftp:// syntax instead.

### netcam_userpass

- Type: String
- Range / Valid values: Max 4095 characters
- Default: Not defined
- Option Topic

For network cameras protected by username and password, use this option for HTTP 1.1 Basic authentication. The string is specified as username:password. Do not specify this option for no authentication.

To use no authentication simply remove this option from the config file comment it out with "#" or ";" in front.

## Round Robin feature

This feature is automatically activated where multiple threads are sharing the same video device (for example /dev/video0). Each thread can then set different input channels to change camera with the input option or by tuning the tuner with frequency option.

Round Robin is not relevant for Network cameras or standard USB web cameras. The Round Robin feature is used with video capture cards which have multiple inputs per video chip.

Note that round robin is not the ideal way to run multiple cameras. When the capture card changes input it takes a little while before the decoder chip has syncronized to the new camera. You can improve this if you have expensive cameras with a syncronize input. Only one camera can be decoded at a time so if you have 4 cameras connected 3 of the camera threads will need to wait for their turn. The fact that cameras have to take turns and the fact that you have to skip a few frames after each turn dramatically lowers the possible framerate. You can get a high framerate by viewing each camera for a long time. But then you may miss the action on one of the inactive cameras. If you can affort it avoid Round Robin and buy the more expensive type of capture cards that has one decoder chip per input. If you only need 2 or 3 cameras you can also simply put 2 or 3 cheap TV cards in the computer. Linux has no problem working with multiple TV cards.

- If multiple threads use the same video device, they each can capture roundrobin_frames number of frames before having to share the device with the other threads.
- When another thread wants to watch another input or frequency or size the first roundrobin_skip number of frames are skipped to allow the device to settle.
- The last option switch_filter is supposed to prevent the change of camera from being detected as Motion. Its function is not perfect and sometimes prevents detection of real motion. You should start with having the option disabled and then try with the option enabled to see if you can skip less frames without loosing the detection of the type of motion you normally want to detect.

These are the special Round Robin options

### roundrobin_frames

- Type: Integer
- Range / Valid values: 1 - 2147483647
- Default: 1
- Option Topic

Specifies the number of frames to capture before switching inputs, this way also slow switching (e.g. every second) is possible.

The Round Robin feature is automatically activated where multiple threads are sharing the same video device. Each thread can then set different input channels or frequencies to change camera.

If multiple threads use the same video device, they each can capture roundrobin_frames number of frames before having to share the device with the other threads.

### roundrobin_skip

- Type: Integer
- Range / Valid values: 1 - 2147483647
- Default: 1
- Option Topic

Specifies the number of frames to skip after a switch. (1 if you are feeling lucky, 2 if you want to be safe).

The Round Robin feature is automatically activated where multiple threads are sharing the same video device. Each thread can then set different input channels or frequencies to change camera.

When another thread wants to watch another input or frequency or size the first roundrobin_skip number of frames are skipped to allow the device to settle.

### switchfilter

- Type: Boolean
- Range / Valid values: on, off
- Default: off
- Option Topic

Turns the switch filter on or off. The filter can distinguish between most switching noise and real motion. With this you can even set roundrobin_skip to 1 without generating much false detection.

This is a round robin related feature used when you have a capture card with multiple inputs (controlled by the 'input' option) on the same videodevice.

This feature was seriously broken until Motion 3.2.4

## Motion Detection Settings

These are the options that controls the detection of motion. Further details follows after.

### area_detect

- Type: String
- Range / Valid values: 1 - 999999999
- Default: Not defined
- Option Topic

Detect motion center in predefined areas. A script (on_area_detected) is started immediately when motion center is detected in one of the given areas, but only once during an event even if there is motion in a different configured area.

Areas are numbered like that:

          1    2    3
          4    5    6
          7    8    9

One or more areas can be specified with this option.

Example: You want to monitor if the center of motion occurrs in the lower third of the image - that is area 7, 8 and 9. Simply set 'area_detect' to '789' and 'on_area_detect' will be executed as soon as the center of motion was detected in area 7, 8 or 9. If you want to monitor area 2, 3, 5 and 6, set '2356'.

### despeckle

- Type: String
- Range / Valid values: EedDl
- Default: Not defined
- Option Topic

Despeckle motion image using combinations of (E/e)rode or (D/d)ilate. And ending with optional (l)abeling.

A way of tuning (by removing or enhancing) noise in the motion image. Options for the despeckle feature are any of 'e', 'E', 'd' or 'D'. This can be combined by a trailing 'l' (letter l) which enables the labeling feature. Default: Not Defined (Don't despeckle and label).

Wind blowing grass and trees around or poor light conditions can cause a lot of dots (or noise) to appear in the motion image (See the section on Tuning Motion). This feature removes (or enhances!) this noise and so improves the reliability of motion.

The 'e' option removes diamonds, 'E' removes squares and alternating eE will remove circles. Each e/E you add will shrink the noise by a pixel all the way around. So 'despeckle Ee' will remove circles of radius 2. However, this will also shrink the detection by 2 and will affect the threshold. So to remove noise and then restore the detected motion to its original size try 'despeckle EedD'.

After the despeckle feature is done you can let the labeling feature search for areas of connected pixels and "label" each area. The program will now trigger motion based on the number of changed pixels in the largest area. In other words, the largest labeled area has to be above the threshold to trigger a motion detected.

The value EedDl is a good starting point. The possible combinations are endless and it requires many experiments to find the best combination. Just remember that the labeling feature only works as intended if it runs after the despeckle feature. Ie. the letter 'l' must be the last letter and only one 'l'.

If you have very few problems with false detections leave this option either blank or at EedD which will remove most of the single pixel noise. A very detailed technical explanation of the despeckle part can be found at the webpage of the author of this feature Ian McConnell's Webcam: Motion Web Page

### gap

- Type: Integer
- Range / Valid values: 0 - 2147483647
- Default: 60
- Option Topic

Gap is the seconds of no motion detection that triggers the end of an event. An event is defined as a series of motion images taken within a short timeframe.

Recommended value is 60 seconds (Default). The value 0 is allowed (but not recommended) and disables events causing all Motion to be written to one single mpeg file and no pre_capture. You can force an event to end and a new to begin using the http control 'http://host:port/thread_number/action/makemovie'. Disabling events has bad side effects on noise_tune and smartmask. Both features can only work properly outside an event. When gap is set to 0, both features don't work properly anymore.

An event is defined as a series of motion images taken within a short timeframe. E.g. a person walking through the room is an event that may have caused 10 single jpg images to be stored. This option defines how long a pause between detected motions that is needed to be defined as a new event.

The gap timer starts after the last motion is detected and post_capture images have been saved and appended to open movie mpeg files.

Any motion detected before the gap timer times out resets the gap timer so it starts counting over again.

Detailed Description

The option 'gap' is important. It defines how long a period of no motion detected it takes before we say an event is over. An event is defined as a series of motion images taken within a short timeframe. E.g. a person walking through the room is an event that may have caused 10 single jpg images to be stored. Motion detected includes post_captured frames set by the 'post_capture' option. The 'gap' option defines how long a pause between detected motions that is needed to be defined as a new event. A good starting value is 60 seconds.

The way 'gap' works in more technical terms is:

- Gap is a timer that timeout 'gap' seconds after the last video frame with motion is detected.
- If 'post_capture' is activated then the gap timer starts counting after the last image of the post_capture buffer has been saved.
- The gap timer is reset and starts all over each time new motion is detected, so you will not miss any action by having a short 'gap' value. It will just create more events (e.g. more mpegs files)

The gap value impacts many functions in Motion.

- When the gap timer runs out the event number is increased by one next time motion is detected. When you use the %v conversion specifier in filenames or text features this means that the number in filename or text increased by one.
- The pre_capture feature only works at the beginning of an event. So if you have a very large 'gap' value pre_capture is not working very often.
- When you make mpegs using the ffmpeg features a new mpeg file is started at the beginning of an event when the first motion is detected. When 'gap' seconds has passed without motion (and post_captured frames saved) the mpeg files is completed and closed.
- Do not use large gap values to generate one large mpeg4 file. If Motion stops working this mpeg4 file never gets properly completed and closed and you will not be able to view it.
- Some of the tracking features sets the camera back to the center position when an event is over.

Note that 'gap' and 'minimum_gap' have nothing to do with each other.

### lightswitch

- Type: Integer
- Range / Valid values: 0 - 100
- Default: 0 (disabled)
- Option Topic

Ignore sudden massive light intensity changes given as a percentage of the picture area that changed intensity.

Experiment to see what works best for your application.

Note: From version 3.1.17 (snap release 2 and on) this option has changed from a boolean (on or off) to a number in percent between 0 and 100. Zero means the option is disabled.

The value defines the picture areas in percent that will trigger the lightswitch condition. When lightswitch is detected motion detection is disabled for 5 picture frames. This is to avoid false detection when light conditions change and when a camera changes sensitivity at low light.

### mask_file

- Type: String
- Range / Valid values: Max 4095 characters
- Default: Not defined
- Option Topic

PGM file to use as a sensitivity mask. This picture MUST have the same width and height as the frames being captured and be in binary format.

Full path of the PGM (portable gray map) mask file (binary format).

If you have one or more areas of the camera image in which you do NOT want motion detected (e.g. a tree that moves in the wind or a corner of the picture where you can see cars/pedestrians passing by) you need a mask file. This file is a picture that you create in your favorite photo editing program. The areas that you want detected must be white. The error that you want ignored must be black. The pgm image must be the same size (number of pixels high and wide) as the pictures that are taken by the camera (video4linux device).

You can adjust sensitivity by using gray tones.

If you do not have a mask file disable this option by not having it in the config file or comment it out ("#"or ";" as first character in line). If you are using the `rotate` option, note that the mask is applied after the rotation.

Detailed Description

The mask file must be a pgm format image file (portable gray map). Note that you must choose the BINARY format.

The feature is simple. Create an image of exact the same size as the ones you get from your video device (camera). Make a purely white picture and paint the areas that you want to mask out black. You can also make gray areas where you want to lower the sensitivity to motion. Normally you will stick to pure black and white.

One easy method for generating the mask file is as follows.

You can just take a motion captured picture, edit it with black and white for the mask and save it as a pgm file. If you cannot save in this format save as a grayscale jpg and then you can convert it to pgm format with

`djpeg -grayscale -pnm [inputfile] > mask.pgm`

(assuming you have djpeg installed - part of the jpeg lib package).

Note that the mask file option masks off the detection of motion. The entire picture is still shown on the picture. This means that you cannot use the feature to mask off an area that you do not want people to see.

Below are an example of a webcam picture and a mask file to prevent the detection cars in the street.

Normal picture. Notice the street is visible through the hedge.

Mask file (converted to png format so it can be shown by your web browser)

### max_mpeg_time

- Type: Integer
- Range / Valid values: 0 (infinite) - 2147483647
- Default: 3600
- Option Topic

The maximum length of an mpeg movie in seconds. Set this to zero for unlimited length.

### minimum_motion_frames

- Type: Boolean
- Range / Valid values: 1 - 1000s
- Default: 1
- Option Topic

Picture frames must contain motion at least the specified number of frames in a row before they are detected as true motion. At the default of 1, all motion is detected. Valid range is 1 to thousands, but it is recommended to keep it within 1-5.

Note that the picture frames are buffered by Motion and once motion is detected also the first frames containing motion are saved so you will not miss anything.

The feature is used when you get many false detections when the camera changes light sensitivity or light changes.

Experiment for best setting. Even though Motion accepts large values you should set this to a relatively low number (below 10). For each step larger than 1 Motion reserves space in RAM for the picture frame buffer. If you have a large value Motion will miss many frames from the camera while it is processing the all the pictures in the buffer.

### noise_level

- Type: Integer
- Range / Valid values: 1 - 255
- Default: 32
- Option Topic

The noise level is used as a threshold for distinguishing between noise and motion.

This is different from the threshold parameter. This is changes at pixel level. The purpose is to eliminate the changes generated by electric noise in the camera. Especially in complete darkness you can see the noise as small grey dots that come randomly in the picture. This noise can create false motion detection. What this parameter means is that the intensity of a pixel must change more than +/- the noise threshold parameter to be counted.

### noise_tune

- Type: Boolean
- Range / Valid values: on, off
- Default: on
- Option Topic

Activates the automatic tuning of noise level.

This feature makes Motion continuously adjust the noise threshold for distinguishing between noise and motion. The 'noise_level' setting is ignored when activating this feature. This is a new feature and new algorithm. It may give different results depending on camera and light conditions. Report your experience with it on the Motion mailing list. If it does not work well, deactivate the 'noise_tune' option and use the manual setting of 'noise_level' instead.

### output_all

- Type: Boolean
- Range / Valid values: on, off
- Default: off
- Option Topic

Picture are saved continuously as if motion was detected all the time.

This feature is not meant to be the normal mode of operation. Especially not if you have the output_normal or output_motion features enabled since it will keep on saving pictures on the disk and you will soon run out of disk space. So be careful with this command.

If your frame rate is 10 pictures per second motion will save 10 new picture pr second until the disk is full.

It does all the normal actions that are done when motion is detected. It saves pictures on the harddisk, execute external scripts, etc as fast as the frame rate of the camera. So it is probably a good idea to run with a low framerate when using this feature and to not use activate all the features that saves files on the disk.

The idea of this feature is that you can turn the feature on and off for a short period of time to test or to generate continuous mpeg films when needed.

### post_capture

- Type: Integer
- Range / Valid values: 0 - 2147483647
- Default: 0 (disabled)
- Option Topic

Specifies the number of frames to be captured after motion has been detected.

The purpose of this is mainly to create smooth video clips each time motion is detected. Use it to you personal taste (and disk space)..

This option is the preferred way to create continuous movies. Post_capture does not consume extra RAM and it does not create pauses in the movie even with large values.

If you only store mpegs movies and do not have output_normal on, then the recommended post_capture value is what is equivalent to 1-5 seconds of movie.

### pre_capture

- Type: Integer
- Range / Valid values: 0 - 100s
- Default: 0 (disabled)
- Option Topic

Specifies the number of previous frames to be outputted at motion detection. Recommended range: 0 to 5, default=0. Do not use large values! Large values will cause Motion to skip video frames and cause unsmooth mpegs. To smooth mpegs use larger values of post_capture instead.

Motion buffers the number of picture frames defined by 'pre_capture'. When motion is detected the pictures in the buffer are included in the video clip generated by ffmpeg. The effect is that it seems the program knew in advance that the event was going to take place and started the recording before it actually happened. This is a nice feature that give more complete video clips of an event.

If pre_capture is set to 0 the feature is disabled. Keep this value below 5.

The recommended value would be approx 0.5 second of video so the value should be defined so it fits the framerate and the desired pre-capture time. E.g. 0.5 second at 20 frames pr second would mean a value of 5. You should never use a value larger than 10.

You can in theory have up to 100s of pre-captured frames but naturally this makes motion leave a larger footprint in the memory of the computer. More important Motion is processing all the buffered images including saving jpegs, encoding mpegs, writing to databases and executing external programs after the first image is detected as Motion.

Motion will not grab another image until this is done. This means that even moderate values for pre_capture combined with high framerates will mean that you will miss quite many frames of Motion. It is therefore recommended to use relative small values for pre_capture. Depending on your chosen framerate and depending on the features enabled values from 1-5 are sensible.

If you wish to create smooth mpegs during events using large pre_capture values will do the opposite! It will create a long pause where a lot of action is missed.

To get a smooth mpeg use a large value for post_capture which does not cost any performance hit or RAM space.

### smart_mask_speed

- Type: Integer
- Range / Valid values: 0 - 10
- Default: 0 (disabled)
- Option Topic

Slugginess of the smart mask. Default is 0 = DISABLED. 1 is slow, 10 is fast.

Smartmask is a dynamic, self-learning mask. Smartmask will disable sensitivity in areas with frequent motion (like trees in the wind). Sensitivity is turned on again after some time of no more motion in this area. The built mask is a bit larger at the borders than the actual motion was. This way smartmask works more reliable when sudden moves occur under windy conditions.

smart_mask_speed - tunes the slugginess of the mask. It accepts values from 0 (turned off) to 10 (fast). Fast means here that the mask is built quick, but it is also not staying very long with no more motion. Slow means that it takes a while until the mask is built but it also stays longer. A good start value for smart_mask_speed is 5. This setting is independent from the framerate. The attack and decay time is constant over all available framerates.

When smartmask is enabled and motion is also configured to either write motion-images or motion-mpegs, the current smartmask is copied as an overlay into the black/white motion-pictures/mpegs in red colour. Same thing happens to the webcam stream when Motion runs in setup_mode. That way you can easily adjust smart_mask_speed.

Detailed Description

The mask_file option provides a static mask to turn off sensitivity in certain areas. This is very usefull to mask a street with cars passing by all day long etc...

But imagine a scenario with large bushes and big trees where all the leaves are moving in the wind also triggering motion from time to time even with despeckle turned on. Of course you can also define a static mask here, but what if the bushes are growing during spring and summer? Well, you have to adapt the mask from time to time. What if the camera position moves slightly? What if someone grows new plants in your garden? You always have to setup a new static mask.

The answer to this problem is the smart mask feature introduced in Motion 3.1.18. A dynamic, self-learing mask.

Smart mask will disable sensitivity in areas with frequent motion (like trees in the wind). Sensitivity is turned on again after some time of no more motion in this area. The built mask is a bit larger at the borders than the actual motion. This way smartmask works more reliably when sudden moves occur under windy conditions.

### threshold

- Type: Integer
- Range / Valid values: 1 - 2147483647
- Default: 1500
- Option Topic

Threshold for declaring motion. The threshold is the number of changed pixels counted after noise filtering, masking, despeckle, and labelling.

The 'threshold' option is the most important detection setting. When motion runs it compares the current image frame with the previous and counts the number of changed pixels after having processed the image with noise filtering, masking, despeckle and labeling. If more pixels than defined by 'threshold' have changed we assume that we have detected motion. Set the threshold as low as possible so that you get the motion you want detected but large enough so that you do not get detections from noise and plants moving. Note that the larger your frames are, the more pixels you have. So for large picture frame sizes you need a higher threshold.

Use the -s (setup mode) command line option and/or the text_changes config file option to experiment to find the right threshold value. If you do not get small movements detected (see the mouse on the kitchen floor) lower the value. If motion detects too many birds or moving trees, increase the number. Practical values would be from a few hundred to 2000 indoors and 1000-10000 outdoors.

### threshold_tune

- Type: Boolean
- Range / Valid values: on, off
- Default: off
- Option Topic

Activates the automatic tuning of threshold level. ( It's broken )

This feature makes Motion continuously adjust the threshold for declaring motion.

The threshold setting is ignored when activating this feature. It may give different results depending on your camera, light conditions, indoor/outdoor, the motion to be detected etc. If it does not work well, deactivate the 'threshold_tune' option and use the manual setting of threshold instead.

## Image File Output

The following options controls how Motion generates images when detection motion.

### output_motion

- Type: Boolean
- Range / Valid values: on, off
- Default: off
- Option Topic

Output pictures with only the moving object. This feature generates the special motion type movies where you only see the pixels that changes as a graytone image. If labelling is enabled you see the largest area in blue. Smartmask is shown in red.

Motion images shows the motion content of the pictures. This is good for tuning and testing but probably not very interesting for the general public.

Default is not to store motion images. Motion pictures are stored the same place and with the same filename as normal motion triggered pictures except they have an "m" appended at the end of the filename before the .jpg or .ppm. E.g. the name can be 01-20020424232936-00m.jpg.

### output_normal

- Type: Discrete Strings
- Range / Valid values: on, off, first, best, center (since 3.2.10)
- Default: on
- Option Topic

Normal image is an image that is stored when motion is detected. It is the same image that was taken by the camera. I.e. not a motion image like defined by output_motion. Default is that normal images are stored.

If you set the value to 'first' Motion saves only the first motion detected picture per event.

If you set it to "best" Motion saves the picture with most changed pixels during the event. This is useful if you store mpegs on a webserver and want to present a jpeg to show the content of the mpeg on a webpage. "best" requires a little more CPU power and resources compared to "first".

Picture with motion nearest center of picture is saved when set to 'center' (since 3.2.10).

Set to 'off' to not write pictures (jpeg or ppm).

### ppm

- Type: Boolean
- Range / Valid values: on, off
- Default: off
- Option Topic

Output ppm images instead of jpeg. This uses less CPU time, but causes a LOT of hard disk I/O, and it is generally slower than jpeg.

The recommendation is to always use jpg except if you have a specific need to store high quality pictures without any quality loss. For web cameras you should always choose jpg. Note that the built in webcam server requires that this parameter is set to off.

### quality

- Type: Integer
- Range / Valid values: 1 - 100
- Default: 75
- Option Topic

The quality for the jpeg images in percent.

100 means hardly compressed. A small number means a much smaller file size but also a less nice quality image to look at. 50 is a good compromise for most.

## Tuning Motion

Motion 3.2 introduces a new feature Setup Mode. This is a great new feature with really make tuning all the settings of Motion much more easy and transparent. In setup mode two things happen:

1. With 'motion -s' Motion runs in console mode instead of daemon. It outputs a lot of useful information for each frame from the camera. Each message is prefixed by [number] where number is the camera number (thread number).
2. When you look at the mjpeg webcam stream you see a black image with numbers. What you see is the number of changed pixels, number of labeled areas and noise setting. When something moves you see the pixels detected as Motion in black and white. The largest labelled area (assuming despeckle is enabled and with the 'l' at the end) is blue. It is only the blue areas which is counted as Motion. If smartmask is enabled you see this as red areas.

Here is a suggestion how to initially setup Motion.

- Disable despeckle (comment it out in motion.conf).
- Disable smartmask
- Enable both http control and webcam by setting port numbers. Example 8080 for control and 8081 for webcam.
- Start Motion in setup mode
- View the webcam stream. Either with Cambozola or with Firefox. http://localhost:8081/ Firefox often needs to reload the page before it works. Bug in Firefox. Internet Explorer cannot show the stream unless you make a webpage on your Apache with Cambozola applet.
- Open new browser window and connect to the http interface. http://localhost:8080/ . You can now control and change almost anything while Motion is running. You cannot resize the image. That was too hard to code. To disable a feature enter a space.
- Start by experimenting with noise level. Do this both during daylight and during darkness. You will be surprised to see how much noise a camera makes during night. Try using the automatic noise feature. It should work for most.
- Now try the despeckle feature. Enable it using the recommended default EedDl. If this is not enough experiment. Remember that the l must be the last letter. It is fun to play with.
- Set the threshold to what you want to trigger Motion.

In normal mode you can use the same setting with two browser windows and experiment with settings of the camera if needed.

From the web interface you can ask Motion to write all your changes back to the config files (motion.conf and thread config files). It will even tidy them up for you so they look nice.

There are two sets of options to adjust.

- The options that controls the camera device: See CaptureDeviceOptions
- The options that controls the actual motion detection: MotionDetectionSettings

Normal picture frame

Motion type picture frame with despeckle. Note that the largest area is blue and only this is counted as Motion.

The Motion image shows how Motion maintains a "reference frame" which is not just the last picture frame but a matematical calculation of the past images. This enlarges real Motion and ensures that it is not easy to sneak in slowly.

## Generating MPEG films with ffmpeg

The ffmpeg option can generate mpeg films very fast and "on the fly". This means that the mpeg film is growing each time motion is detected.

Some people on the Motion mailing list have had trouble building the ffmpeg package because they did not have the NASM assembler package installed. So pay attention to this if you run into problems.

ffmpeg exists as binary packages for most distributions including RPMs and debian packages.

Ffmpeg is an interesting project. The releases have not been very consistent over time. The official releases are out of date now. So we are forced to take our chance and checkout a version from their CVS server and hope that we are lucky in getting a version that works. See ffmpeg project page. We encourage the maintaners of such an important project to introduce better release schedules in the near future for the benefit of opensource software.

In order to help people finding a version of ffmpeg that works we have started testing the Motion package with a selection of binaries and a CVS snapshot. The CVS source snapshot of ffmpeg which is certified with Motion is available on the Related projects file area on the Motion Sourceforge project

Motion works with the following versions of ffmpeg:

- ffmpeg-0.4.8. With this release Motion supports mpeg1, mpeg4 and msmpeg4. Lately newer distributions have problems building this 2003 release of ffmpeg so many of you no longer have this option.
- ffmpeg-0.4.9pre1. Is supported starting from Motion version 3.1.18. With this release Motion supports mpeg4 and msmpeg4 but not mpeg1. The reason is that the ffmpeg team has decided no longer to support non-standard framerates in their mpeg1 encoder library. Also ffmpeg-0.4.9pre1 gives people problems on newer distributions.
- ffmpeg from CVS. This may work. We cannot continuously monitor and try every time a new source file is checked into ffmpeg. You will have to try.
- ffmpeg RPMs. Currently each Motion release is tested with the current Livna ffmpeg rpm package for Fedora. See the Download Files page for direct links to the version which has been certified with the latest Motion release.
- ffmpeg debian binaries. Latest versions from the debian repository for Debian Sarge works fine with Motion.
- Certified ffmpeg CVS snapshot for latest Motion release is available from the Motion Sourceforge Related Projects file area

The timelapse feature always runs mpeg1 with both ffmpeg 0.4.8 and 0.4.9 and newer. Motion simply creates the timelapse film with a standard mpeg1 framerate. Note : maximum size for timelapse files is 2GB.

In principle Motion can be made to support many other formats. It requires additional coding in Motion. You are welcome to submit patches. All ffmpeg related code is in the source file ffmpeg.c. It is not trivial to do because the ffmpeg libraries not documented at all. All you have is a couple of code examples.

To build ffpmeg from source follow these steps:

Download the ffmpeg and untar it to /usr/local/ffmpeg. Then it should be a simple matter of entering the ffmpeg directory and run the commands

    cd /usr/local/ffmpeg
    ./configure --enable-shared
    make
    make install

This creates the `libavcodec.so` and `libavformat.so` libraries under `/usr/local/lib` and header files under `/usr/local/include/ffmpeg`.

You probably need to do one more step.

Make sure you have 'root' privileges for the next steps.

Open the file `/etc/ld.so.conf` in your favorite text editor.

Add this line of text if it is not already there - otherwise go to the next step (ldconfig).

`/usr/local/lib` Run the command `ldconfig`.

Motion should now be able to find the shared libraries for ffmpeg (`libavcodec.so` and `libavformat.so`) in `/usr/local/lib`.

You can also find a pre-compiled binary package (e.g. rpm or deb) and install this. Normally an rpm will place the `libavcodec.so` under `/usr/lib`. There are various RPMs available from different repositories. Some need additional RPMs that are actually not needed by Motion but need to be installed to satisfy dependencies. The editor has tried different RPMs of ffmpeg-0.4.8 and they all seem to work.

Motion then need to be built by running `./configure`, `make` and `make install`. (Note that with earlier versions of motion you had to specify the location of libavcodec. Now configure searches for the shared library in `/usr/lib` and `/usr/local/lib` by default.)

Note that if you install ffmpeg from source and already have ffmpeg installed from an RPM, the Motion configure may very well find the binary library from the rpm instead of the sources. Make sure to uninstall any old ffmpeg RPMs before you install ffmpeg from sources.

These are the config file options related to ffmpeg.

### ffmpeg_bps

- Type: Integer
- Range / Valid values: 0 - 9999999
- Default: 400000
- Option Topic

Bitrate of mpegs produced by ffmpeg. Bitrate is bits per second. Default: 400000 (400kbps). Higher value mans better quality and larger files. Option requires that ffmpeg libraries are installed.

To use this feature you need to install the FFmpeg Streaming Multimedia System.

Experiment to get the desired quality. The better quality the bigger files. This option is ignored if ffmpeg_variable_bitrate is not 0 (disabled).

### ffmpeg_cap_motion

- Type: Boolean
- Range / Valid values: on, off
- Default: off
- Option Topic

Use ffmpeg libraries to encode motion type mpeg movies where you only see the pixels that changes.

Works like ffmpeg_cap_new but outputs motion pixel type pictures instead.

This feature generates the special motion type movie where you only see the pixels that changes as a graytone image. If labelling is enabled you see the largest area in blue. Smartmask is shown in red. The filename given is the same as the normal mpegs except they have an 'm' appended after the filename before the .mpg. E.g. 20040424181525m.mpg

To use this feature you need to install the FFmpeg Streaming Multimedia System

### ffmpeg_cap_new

- Type: Boolean
- Range / Valid values: on, off
- Default: off
- Option Topic

Use ffmpeg libraries to encode mpeg movies in realtime.

Generates a new film at the beginning of each new event and appends to the film for each motion detected within the same event. The current event ends when the time defined by the 'gap' option has passed with no motion detected. At the next detection of motion a new mpeg film is started.

To use this feature you need to install the FFmpeg Streaming Multimedia System

Must not be included in config file without having ffmpeg installed.

### ffmpeg_deinterlace

- Type: Boolean
- Range / Valid values: on, off
- Default: off
- Option Topic

Use ffmpeg to deinterlace video. Necessary if you use an analog camera and see horizontal combing on moving objects in video or pictures.

To use this feature you need to install the FFmpeg Streaming Multimedia System

Must not be included in config file without having ffmpeg installed.

### ffmpeg_timelapse

- Type: Boolean
- Range / Valid values: 0 - 2147483647
- Default: 0 (disabled)
- Option Topic

Create a timelapse movie saving a picture frame at the interval in seconds set by this parameter. Set it to 0 if not used.

This feature uses ffmpegs libavcodec to encode a timelaps movie saving a picture frame at the interval in seconds set by this parameter. Setting this option to 0 disables it.

The feature gives your viewer the chance to watch the day pass by. It makes a nice effect to film flowers etc closeup during the day. Options like frame_rate, snapshot, gap etc have no impact on the ffmpeg timelapse function.

Note that the timelapse format is always mpeg1 independent of ffmpeg_video_codec. This is because mpeg1 allows the timelapse to stop and the file to be reopened and more film appended.

To use this feature you need to install the FFmpeg Streaming Multimedia System.

(renamed from ffmpeg_timelaps to ffmpeg_timelapse in 3.1.14)

### ffmpeg_timelapse_mode

- Type: Discrete Strings
- Range / Valid values: hourly, daily, weekly-sunday, weekly-monday, monthly, manual
- Default: daily
- Option Topic

The file rollover mode of the timelapse video.

Note that it is important that you use the conversion specifiers in ffmpeg_filename that ensure that the new timelapse file indeed is a new file. If the filename does not change Motion will simply append the timelapse pictures to the existing file.

The value 'Manual' means that Motion does not automatically rollover to a new filename. You can do it manually using the http control interface by setting the option 'ffmpeg_timelapse' to 0 and then back to your chosen value. Value 'hourly' rolls over on the full hour. Value 'daily' which is the default rolls over at midnight. There are two weekly options because depending on where you come from a week may either start on Sunday or Monday. And 'monthly' naturally rolls over on the 1st of the month.

### ffmpeg_variable_bitrate

- Type: Integer
- Range / Valid values: 0, 2 - 31
- Default: 0 (disabled)
- Option Topic

Enables and defines variable bitrate for the ffmpeg encoder. ffmpeg_bps is ignored if variable bitrate is enabled. Valid values: 0 (default) = fixed bitrate defined by ffmpeg_bps, or the range 2 - 31 where 2 means best quality and 31 is worst.

Experiment for the value that gives you the desired compromise between size and quality.

### ffmpeg_video_codec

- Type: Discrete Strings
- Range / Valid values: mpeg1 (ffmpeg-0.4.8 only), mpeg4, msmpeg4, swf, flv, ffv1, mov
- Default: mpeg4
- Option Topic

Codec to be used by ffmpeg for the video compression. Timelapse mpegs are always made in mpeg1 format independent from this option.

- mpeg1 - gives you mpeg1 files with extension .mpg. It is only supported by the old ffmpeg version 0.4.8. The ffmpeg team decided no longer to support non-standard framerates for mpeg1 from ffmpeg version 0.4.9pre1.
- mpeg4 - gives you mpeg4 files with extension .avi
- msmpeg4 - also gives you mpeg4 files. It is s recommended for use with Windows Media Player because it requires with no installation of codec on the Windows client.
- swf - gives you a flash film with extension .swf
- flv - gives you a flash video with extension .flv
- ffv1 - FF video codec 1 for Lossless Encoding (experimental)
- mov - QuickTime (since 3.2.10).

This option does not affect the timelapse feature. Timelapse is always recorded in mpeg1 format because we need to be able to append to an existing file. mpeg4 does not easily allow this.

See also the section Advanced Filenames where the two additional options ffmpeg_filename and timelapse_filename are defined.

If you want to use this feature you can read about the FFmpeg Streaming Multimedia System

## Snapshots - The Traditional Periodic Web Camera

Motion can also act like a traditional web camera.

### snapshot_interval

- Type: Integer
- Range / Valid values: 0 - 2147483647
- Default: 0 (disabled)
- Option Topic

Make automated snapshots every 'snapshot_interval' seconds.

The snapshots are stored in the target directory + the directory/filename specified by the snapshot_filename option.

This is the traditional web camera feature where a picture is taken at a regular interval independently of motion in the picture.

See the also snapshot_filename option in the section Advanced Filenames.

## Text Features

Text features are highly flexible. You can taylor the text displayed on the images and films to your taste and you can add your own user defined text.

This is how the overlayed text is located.

| CHANGES
TEXT_LEFT | TEXT_RIGHT YYYY-MM-DD HH:MM:SS

You are allowed to put the text in quotation marks. This allows you to use leading spaces. By combining spaces and new lines '\n' you can place your text anywhere on the picture. Experiment to find your preferred look. When setting the text using http remote control the text must be URL encoded. The browser does this for you. If you need to set it with a command line tool, use a browser first and let it make the encoded URL for you. Then you can copy paste it to your script file or cron line or whatever you want to use.

Below are the options that controls the display of text. The 'locate' option is not a text feature but described here because it is related to information overlayed on the output images.

The `text_event` feature is special in that it defines the conversion specifier %C which can be used both for text display and for filenames.

### locate

- Type: Boolean
- Range / Valid values: on, off, preview
- Default: off
- Option Topic

Locate and draw a box around the moving object. Value 'preview' makes Motion only draw a box on a saved preview jpeg image and not on the saved mpeg movie.

The value 'preview' only works when 'output_normal' is set to either 'first' or 'best'.

### text_changes

- Type: Boolean
- Range / Valid values: on, off
- Default: off
- Option Topic

Turns the text showing changed pixels on/off.

By setting this option to 'on' the number of pixels that changed compared to the reference frame is displayed in the upper right corner of the pictures. This is good for calibration and test. Maybe not so interesting for a greater public. Set it to your personal taste.

### text_double

- Type: Boolean
- Range / Valid values: on, off
- Default: off

Draw characters at twice normal size on images.

This option makes the text defined by text_left, text_right and text_changes twice the normal size. This may be useful when using large picture formats such as 640 x 480.

### text_event

- Type: String
- Range / Valid values: Max 4095 characters
- Default: %Y%m%d%H%M%S
- Option Topic

This option defines the value of the speciel event conversion specifier %C. You can use any conversion specifier in this option except %C. Date and time values are from the timestamp of the first image in the current event.

The idea is that %C can be used filenames and text_left/right for creating a unique identifier for each event.

Option text_event defines the value %C which then can be used in filenames and text_right/text_left. The text_event/%C uses the time stamp for the first image detected in a new event. %C is an empty string when no event is in progress (gap period expired). Pre_captured and minimum_motion_frames images are time stamped before the event happens so %C in text_left/right does not have any effect on those images.

### text_left

- Type: String
- Range / Valid values: Max 4095 characters
- Default: Not defined
- Option Topic

User defined text overlayed on each in the lower left corner. Use A-Z, a-z, 0-9, " / ( ) @ ~ # < > , . : - + _ \n and vertical bar and conversion specifiers (codes starting by a %).

text_left is displayed in the lower left corner of the pictures. If the option is not defined no text is displayed at this position.

You can place the text in quotation marks to allow leading spaces. With a combination is spaces and newlines you can position the text anywhere on the picture.

Detailed Description

A conversion specifier is a code that starts by % (except newline which is \n). The conversion specifiers used has the same function as for the C function strftime (3). The most commonly used are:

- %Y = year
- %m = month as two digits
- %d = date
- %H = hour
- %M = minute
- %S = second
- %T = HH:MM:SS

These are unique to motion

- %v = event
- %q = frame number
- %t = thread (camera) number
- %D = changed pixels
- %N = noise level
- %i = width of motion area
- %J = height of motion area
- %K = X coordinate of motion center
- %L = Y coordinate of motion center
- %C = value defined by text_event

With a combination of text, spaces, new lines \n and conversion specifiers you have some very flexible text features.

For a full list of conversion specifiers see the section Conversion Specifiers for Advanced Filename and Text Feature.

### text_right

- Type: String
- Range / Valid values: Max 4095 characters
- Default: %Y-%m-%d\n%T
- Option Topic

User defined text overlayed on each in the lower right corner. Use A-Z, a-z, 0-9, " / ( ) @ ~ # < > , . : - + _ \n and vertical bar and conversion specifiers (codes starting by a %). Default: %Y-%m-%d\n%T = date in ISO format and time in 24 hour clock

text_right is displayed in the lower right corner of the pictures. If the option is not defined no text is displayed at this position.

You can place the text in quotation marks to allow leading spaces. With a combination is spaces and newlines you can position the text anywhere on the picture.

A major difference from text_left is that if this option is undefined the default is %Y-%m-%d\n%T which displays the date in ISO format YYYY-MM-DD and below the time in 24 hour clock HH:MM:SS.

Detailed Description

A conversion specifier is a code that starts by % (except newline which is \n). The conversion specifiers used has the same function as for the C function strftime (3). The most commonly used are:

- %Y = year
- %m = month as two digits
- %d = date
- %H = hour
- %M = minute
- %S = second
- %T = HH:MM:SS

These are unique to motion

- %v = event
- %q = frame number
- %t = thread (camera) number
- %D = changed pixels
- %N = noise level
- %i = width of motion area
- %J = height of motion area
- %K = X coordinate of motion center
- %L = Y coordinate of motion center
- %C = value defined by text_event

With a combination of text, spaces, new lines \n and conversion specifiers you have some very flexible text features.

For a full list of conversion specifiers see the section Conversion Specifiers for Advanced Filename and Text Feature.

## Advanced Filenames

Motion has a very advanced and flexible automated filenaming feature.

By using conversion specifiers (codes that consist of a '%' followed by a letter) you can build up the filenames including sub directories for pictures and movies using any combination of letters, numbers and conversion specifiers which are codes that represents time, date, event number and frame numbers.

The option `target_dir` is the target directory for all snapshots, motion images and normal images. The default is the current working directory (current working directory of the terminal from which motion was started). You will normally always want to specify this parameter.

Note that the options `snapshot_filename`, `jpeg_filename`, `ffmpeg_filename`, and `timelapse_filename` all allow specifying directories by using '/' in the filename. These will all be relative to `target_dir`. This means in principle that you can specify `target_dir` as '/' and be 100% flexible. It also means that Motion can write files all over your harddisk if you make a mistake. It is recommended to specify the `target_dir` as deep or detailed as possible for this reason. And note that `targer_dir` does not allow conversion specifiers.

The conversion specifier %C which is defined by the option text_event is interesting in connection with filenames because it can be used to create files and directories for each event in a very flexible way.

The convertion specifier %t (thread/camera number) is also very useful. Here is an example of filename definitions in motion.conf:

    target_dir /usr/local/webcam
    snapshot_filename cam%t/%v-%Y%m%d%H%M%S-snapshot
    jpeg_filename cam%t/%v-%Y%m%d%H%M%S-%q
    ffmpeg_filename cam%t/%v-%Y%m%d%H%M%S
    timelapse_filename cam%t/%Y%m%d%H-timelapse

The smart thing is that this defines the filename of all your camera threads in motion.conf so you do not need to specify target dir and filenames in the thread config files. In the above example an mpegfile for camera thread 3 will be saved as a filename similar to `/usr/local/webcam/cam3/28-20051128130840.avi`

NOTE: Unless you use the `minimum_gap` option to limit the number of shots to less then one per second - you must use the frame modifier %q as part of the `jpeg_filename`. Otherwise the pictures saved within the same second will overwrite each other. The %q in `jpeg_filename` ensures that each jpeg (or ppm) picture saved gets a unique filename.

Security Warning! Note that the flexibility of this feature also means you have to pay attention to the following.

- Anyone with access to the remote control port (http) can alter the values of these options and save files anywhere on your server with the same privileges as the user running Motion. Anyone can access your control port if you have not either limited access to localhost or limited access using firewalls in the server. You should always have a router between a machine running Motion with remote control enabled and the Internet and make sure the Motion control port is not accessible from the outside.
- Anyone with local access to the computer and edit rights to the motion.conf file can alter the values of these options and save files anywhere on your server with the same privileges as the user running Motion. Make sure the motion.conf file is maximum readonly to anyone else but the user running Motion.
- It is a good idea to run Motion as a harmless user. Not as root.

These are the advanced filename options in motion.conf

### ffmpeg_filename (now called movie_filename)

This option was renamed to movie_filename in 3.2.5 to enable better integration of alternative movie libraries to the current ffmpeg solution.

- Type: String
- Range / Valid values: Max 4095 characters
- Default: %v-%Y%m%d%H%M%S
- Option Topic

File path for motion triggered ffmpeg movies (mpeg) relative to target_dir. This option was renamed to movie_filename in 3.2.5 to enable better integration of alternative movie libraries to the current ffmpeg solution.

Default value is equivalent to legacy 'oldlayout' option For Motion 3.0 compatible mode (directories based on date and time) choose: %Y/%m/%d/%H%M%S

File extension .mpg or .avi is automatically added so do not include this.

This option uses conversion specifiers which are codes that start by % and then a letter. The conversion specifiers used has the same function as for the C function strftime (3). The most commonly used are:

- %Y = year
- %m = month as two digits
- %d = date
- %H = hour
- %M = minute
- %S = second
- %T = HH:MM:SS

These are unique to motion

- %v = event
- %q = frame number
- %t = thread (camera) number
- %D = changed pixels
- %N = noise level
- %i = width of motion area
- %J = height of motion area
- %K = X coordinate of motion center
- %L = Y coordinate of motion center
- %C = value defined by text_event

If you are happy with the directory structures the way they were in earlier versions of motion use %v-%Y%m%d%H%M%S for 'oldlayout on' and %Y/%m/%d/%H%M%S for 'oldlayout off'.

### jpeg_filename

- Type: String
- Range / Valid values: Max 4095 characters
- Default: %v-%Y%m%d%H%M%S-%q
- Option Topic

File path for motion triggered images (jpeg or ppm) relative to target_dir. Value 'preview' makes a jpeg filename with the same name body as the associated saved mpeg movie file.

Default value is equivalent to legacy 'oldlayout' option. For Motion 3.0 compatible mode (directories based on date and time) choose: %Y/%m/%d/%H/%M/%S-%q

This option uses conversion specifiers which are codes that start by % and then a letter. The conversion specifiers used has the same function as for the C function strftime (3). The most commonly used are:

- %Y = year
- %m = month as two digits
- %d = date
- %H = hour
- %M = minute
- %S = second
- %T = HH:MM:SS

These are unique to motion

- %v = event
- %q = frame number
- %t = thread (camera) number
- %D = changed pixels
- %N = noise level
- %i = width of motion area
- %J = height of motion area
- %K = X coordinate of motion center
- %L = Y coordinate of motion center
- %C = value defined by text_event

If you are happy with the directory structures the way they were in earlier versions of motion use %v-%Y%m%d%H%M%S-%q for 'oldlayout on' and %Y/%m/%d/%H/%M/%S-%q for 'oldlayout off'.

The value 'preview' only works when 'output_normal' is set to 'best'. It makes Motion name the best preview jpeg file (image with most changed pixels during the event) with the same body name as the mpeg movie created during the same event. The purpose is to create a good single image that represents the saved mpeg moview so you can decide if you want to see it and spend time downloading it from a web page.

### movie_filename

- Type: String
- Range / Valid values: Max 4095 characters
- Default: %v-%Y%m%d%H%M%S
- Option Topic

File path for motion triggered ffmpeg movies (mpeg) relative to target_dir. This was previously called ffmpeg_filename.

This option was renamed from ffmpeg_filename to movie_filename in Motion 3.2.5.

Default value is equivalent to legacy 'oldlayout' option For Motion 3.0 compatible mode (directories based on date and time) choose: %Y/%m/%d/%H%M%S

File extension .mpg or .avi is automatically added so do not include this.

This option uses conversion specifiers which are codes that start by % and then a letter. The conversion specifiers used has the same function as for the C function strftime (3). The most commonly used are:

- %Y = year
- %m = month as two digits
- %d = date
- %H = hour
- %M = minute
- %S = second
- %T = HH:MM:SS

These are unique to motion

- %v = event
- %q = frame number
- %t = thread (camera) number
- %D = changed pixels
- %N = noise level
- %i = width of motion area
- %J = height of motion area
- %K = X coordinate of motion center
- %L = Y coordinate of motion center
- %C = value defined by text_event

If you are happy with the directory structures the way they were in earlier versions of motion use %v-%Y%m%d%H%M%S for 'oldlayout on' and %Y/%m/%d/%H%M%S for 'oldlayout off'.

### snapshot_filename

- Type: String
- Range / Valid values: Max 4095 characters
- Default: %v-%Y%m%d%H%M%S-snapshot
- Option Topic

File path for snapshots (jpeg or ppm) relative to target_dir.

Default value is equivalent to legacy 'oldlayout' option. For Motion 3.0 compatible mode (directories based on date and time) choose: %Y/%m/%d/%H/%M/%S-snapshot

File extension .jpg or .ppm is automatically added so do not include this A symbolic link called lastsnap.jpg (or lastsnap.ppm) created in the target_dir will always point to the latest snapshot, unless snapshot_filename is exactly 'lastsnap'

This option uses conversion specifiers which are codes that start by % and then a letter. The conversion specifiers used has the same function as for the C function strftime (3). The most commonly used are:

- %Y = year
- %m = month as two digits
- %d = date
- %H = hour
- %M = minute
- %S = second
- %T = HH:MM:SS

These are unique to motion

- %v = event
- %q = frame number
- %t = thread (camera) number
- %D = changed pixels
- %N = noise level
- %i = width of motion area
- %J = height of motion area
- %K = X coordinate of motion center
- %L = Y coordinate of motion center
- %C = value defined by text_event

If you are happy with the directory structures the way they were in earlier versions of motion use %v-%Y%m%d%H%M%S-snapshot for 'oldlayout on' and %Y/%m/%d/%H/%M/%S-snapshot for 'oldlayout off'.

For the equivalent of the now obsolete option 'snap_overwrite' use the value 'lastsnap'.

### target_dir

- Type: String
- Range / Valid values: Max 4095 characters
- Default: Not defined = current working directory
- Option Topic

Target directory for picture and movie files.

This is the target directory for all snapshots, images files and movie files. The default is the current working directory (current working directory of the terminal from which motion was started). You will normally always want to specify this parameter as an absolute path.

Note that the options snapshot_filename, jpeg_filename, ffmpeg_filename, and timelapse_filename all allows specifying directories. These will all be relative to 'target_dir'. This means in principle that you can specify target_dir as '/' and be 100% flexible. It also means that Motion can write files all over your harddisk if you make a mistake. It is recommended to specify the target_dir as deep or detailed as possible for this reason.

### timelapse_filename

- Type: String
- Range / Valid values: Max 4095 characters
- Default: %v-%Y%m%d-timelapse
- Option Topic

File path for timelapse mpegs relative to target_dir (ffmpeg only).

Default value is equivalent to legacy 'oldlayout' option.

For Motion 3.0 compatible mode (directories based on date and time) choose: %Y/%m/%d-timelapse

File extension .mpg is automatically added so do not include this.

This option uses conversion specifiers which are codes that start by % and then a letter. The conversion specifiers used has the same function as for the C function strftime (3). The most commonly used are:

- %Y = year
- %m = month as two digits
- %d = date
- %H = hour
- %M = minute
- %S = second
- %T = HH:MM:SS

These are unique to motion

- %v = event
- %q = frame number
- %t = thread (camera) number
- %D = changed pixels
- %N = noise level
- %i = width of motion area
- %J = height of motion area
- %K = X coordinate of motion center
- %L = Y coordinate of motion center
- %C = value defined by text_event

If you are happy with the directory structures the way they were in earlier versions of motion use %v-%Y%m%d-timelapse for 'oldlayout on' and %Y/%m/%d-timelapse for 'oldlayout off'.

## Conversion Specifiers for Advanced Filename and Text Features

The table below shows all the supported Conversion Specifiers you can use in the options `text_event`, `text_left`, `text_right`, `sql_query`, `snapshot_filename`, `jpeg_filename`, `ffmpeg_filename`, `timelapse_filename`, `on_event_start`, `on_event_end`, `on_picture_save`, `on_movie_start`, `on_movie_end`, and `on_motion_detected`.

In `text_left` and `text_right` you can additionally use '\n' for new line.

Conversion Specifier | Description
--- | ---
%a | The abbreviated weekday name according to the current locale.
%A | The full weekday name according to the current locale.
%b | The abbreviated month name according to the current locale.
%B | The full month name according to the current locale.
%c | The preferred date and time representation for the current locale.
%C | Text defined by the text_event feature
%d | The day of the month as a decimal number (range 01 to 31).
%D | Number of pixels detected as Motion. If labelling is enabled the number is the number of pixels in the largest labelled motion area.
%E | Modifier: use alternative format, see below.
%f | File name - used in the on_picture_save, on_movie_start, on_movie_end, and sql_query features.
%F | Equivalent to %Y-%m-%d (the ISO 8601 date format).
%H | The hour as a decimal number using a 24-hour clock (range 00 to 23).
%i | Width of the rectangle containing the motion pixels (the rectangle that is shown on the image when locate is on).
%I | The hour as a decimal number using a 12-hour clock (range 01 to 12).
%j | The day of the year as a decimal number (range 001 to 366).
%J | Height of the rectangle containing the motion pixels (the rectangle that is shown on the image when locate is on).
%k | The hour (24-hour clock) as a decimal number (range 0 to 23); single digits are preceded by a blank. (See also %H.)
%K | X coordinate in pixels of the center point of motion. Origin is upper left corner.
%l | The hour (12-hour clock) as a decimal number (range 1 to 12); single digits are preceded by a blank. (See also %I.)
%L | Y coordinate in pixels of the center point of motion. Origin is upper left corner and number is positive moving downwards (I may change this soon).
%m | The month as a decimal number (range 01 to 12).
%M | The minute as a decimal number (range 00 to 59).
%n | Filetype as used in the on_picture_save, on_movie_start, on_movie_end, and sql_query features.
%N | Noise level.
%o | Threshold. The number of detected pixels required to trigger motion. When threshold_tune is 'on' this can be used to show the current tuned value of threshold.
%p | Either 'AM' or 'PM' according to the given time value, or the corresponding strings for the current locale. Noon is treated as `pm' and midnight as `am'.
%P | Like %p but in lowercase: `am' or `pm' or a corresponding string for the current locale.
%q | Picture frame number within current second. For jpeg filenames this should always be included in the filename if you save more then 1 picture per second to ensure unique filenames. It is not needed in filenames for mpegs.
%Q | Number of detected labels found by the despeckle feature
%r | The time in a.m. or p.m. notation.
%R | The time in 24-hour notation (%H:%M).
%s | The number of seconds since the Epoch, i.e., since 1970-01-01 00:00:00 UTC.
%S | The second as a decimal number (range 00 to 61).
%t | Thread number (camera number)
%T | The time in 24-hour notation (%H:%M:%S).
%u | The day of the week as a decimal, range 1 to 7, Monday being 1. See also %w.
%U | The week number of the current year as a decimal number, range 00 to 53, starting with the first Sunday as the first day of week 01. See also %V and %W.
%v | Event number. An event is a series of motion detections happening with less than 'gap' seconds between them.
%V | The ISO 8601:1988 week number of the current year as a decimal number, range 01 to 53, where week 1 is the first week that has at least 4 days in the current year, and with Monday as the first day of the week. See also %U and %W.
%w | The day of the week as a decimal, range 0 to 6, Sunday being 0. See also %u.
%W | The week number of the current year as a decimal number, range 00 to 53, starting with the first Monday as the first day of week 01.
%x | The preferred date representation for the current locale without the time.
%X | The preferred time representation for the current locale without the date.
%y | The year as a decimal number without a century (range 00 to 99).
%Y | The year as a decimal number including the century.
%z | The time-zone as hour offset from GMT.
%Z | The time zone or name or abbreviation.

## Webcam Server

Motion has simple webcam server built in. The video stream is in mjpeg format.

Each thread can have its own webcam server. If you enable the webcam server (option webcam_port to a number different from 0) and you have more than one camera, you must make sure to include webcam_port in each thread config file and set webcam_port to different and unique port numbers or zero (disable). Otherwise each webcam server will use the setting from the motion.conf file and try to bind to the same port. If the webcam_port numbers are not different from each other Motion will disable the webcam feature.

Note: The webcam server feature requires that the option `ppm` is set to off.

The `webcam_maxrate` and `webcam_quality` options are important to limit the load on your server and link. Don't set them too high unless you only use it on the localhost or on an internal LAN. The option `webcam_quality` is equivalent to the quality level for jpeg pictures.

The `webcam_limit` option prevents people from loading your Network connection by streaming for hours and hours. The options defines the number of picture frames sent as mjpeg Motion will allow without re-connecting (e.g. clicking refresh in the browser).

The option `webcam_localhost` is a security feature. When enabled you can only access the webserver on the same machine as Motion is running on. If you want to present a live webcam on your web site this feature must be disabled.

The webserver generates a stream in "multipart jpeg" format (mjpeg). You cannot watch the stream with most browsers. Only certain versions of Netscape works. Mozilla and Firefox brosers can view the mjpeg stream but you often have to refresh the page once to get the streaming going. Internet Explorer cannot show the mjpeg stream. For public viewing this is not very useful. There exists a java applet called Cambozola which enabled any Java capable browser to show the stream. To enable the feature to a broad audience you should use this applet or similar.

To use the webcam feature with Cambozola is actually very simple.

1. Create a html page in which you will want the streamed picture.

2. In the html page include this code

    <applet code=com.charliemouse.cambozola.Viewer
        archive=cambozola.jar width="320" height="240" style="border-width:1; border-color:gray; border-style:solid;">
        <param name=url value="http://www.myurl.com:8081">
    </applet>

Where the width and height is the image size of the video stream.

Replace www.myurl.com:8081 by the real url and port number of your choice.

3. In the same directory you place the cambozola.jar file. No need to build the java applet from source. Simply use the applet in the package.

4. Enable the feature in motion.conf.

You can also view the live webcam stream using MPlayer like this:

    mplayer -demuxer lavf http://www.myurl.com:8081/stream.mjpg

Note that the `stream.mjpg` part is important, without it you will get a `LAVF_check: no clue about this gibberish!` error from libavformat.

These are the special webcam parameters.

### webcam_limit

- Type: Integer
- Range / Valid values: 0 - 2147483647
- Default: 0 (unlimited)
- Option Topic

Limit the number of frames to number frames. After 'webcam_limit' number of frames the connection will be closed by motion. The value 0 means unlimited.

Number can be defined by multiplying actual webcam rate by desired number of seconds. Actual webcam rate is the smallest of the numbers framerate and webcam_maxrate.

### webcam_localhost

- Type: Boolean
- Range / Valid values: on, off
- Default: on
- Option Topic

Limits the access to the webcam to the localhost.

By setting this to on, the webcam can only be accessed on the same machine on which Motion is running.

### webcam_maxrate

- Type: Integer
- Range / Valid values: 1 - 100
- Default: 1
- Option Topic

Limit the framerate of the webcam in frames per second. Default is 1. Set the value to 100 for practically unlimited.

Don't set 'webcam_maxrate' too high unless you only use it on the localhost or on an internal LAN.

### webcam_motion

- Type: Boolean
- Range / Valid values: on, off
- Default: off
- Option Topic

If set to 'on' Motion sends slows down the webcam stream to 1 picture per second when no motion is detected. When motion is detected the stream runs as defined by webcam_maxrate. When 'off' the webcam stream always runs as defined by webcam_maxrate.

Use this option to save bandwidth when there is not anything important to see from the camera anyway.

Note that this feature was greatly improved from Motion version 3.2.2. Before 3.2.2 the option stopped the webcam stream except when Motion was detected. This made the feature not very useful because it made it difficult to connect to the webcam stream and most mjpeg viewers would timeout and give an error message. From 3.2.2 the feature has been greatly improved and actually quite recommendable.

### webcam_port

- Type: Integer
- Range / Valid values: 0 - 65535
- Default: 0 (disabled)
- Option Topic

TCP port on which motion will listen for incoming connects with its webcam server.

Note that each camera thread must have its own unique port number and it must also be different from the control_port number.

A good value to select is 8081 for camera 1, 8082 for camera 2, 8083 for camera 3 etc etc.

### webcam_quality

- Type: Integer
- Range / Valid values: 1 - 100
- Default: 50
- Option Topic

Quality setting in percent for the mjpeg picture frames transferred over the webcam connection. Keep it low to restrict needed bandwidth.

The mjpeg stream consists of a header followed by jpeg frames separated by content-length and boundary string. The quality level defines the size of the individual jpeg pictures in the mjpeg stream. If you set it too high you need quite a high bandwidth to view the stream.

## Remote Control with http

Motion can be remote controlled via a simple http interface. http is the language a normal web browser talks when it requests a web page. The web server answers back with some simple http headers followed by a webpage coded in HTML.

Most Motion config options can be changed while Motion is running except options related to the size of the captured images and mask files which are loaded only when Motion starts. So only your fantasy sets the limit to what you can change combining cron and the remote control interface for Motion.

So the most obvious tool to use to remote control Motion is any web browser. All commands are sent using the http GET method which simply means that the information is sent via the URL and maybe a query string. You can use any browser (Firefox, Mozilla, Internet Explorer, Konquerer, Opera etc). You can also use the text based browser lynx to control Motion from a console. It navigates fine through the very simple and minimalistic http control interface of Motion.

The details about how to control Motion via the URL is described in detail in the Motion http API topic.

But it is probably simpler to connect to the control port with a browser, navigate to the function you want, and copy the URL from the browser URL entry line. If your control_port is 8080 and you browse from the same machine on which Motion runs simply look up http://localhost:8080/ and navigate around. Connecting from a remote machine is done by using a domain name (example http://mydomain.com:8080/) or the IP address of the machine (example http://192.168.1.4:8080/). The option control_localhost must be off to allow connection from a remote machine.

If you want to use a script or cron to automatically change Motion settings while Motion runs you use a program that can fetch a webpage. We simply just throw away the html page that Motion returns. Programs commonly available on Linux machines are wget and lwp-request. Here is an example of how to start and stop motion detection via cron. These two lines are added to /etc/crontab.

    0 9 * * * root /usr/bin/lwp-request http://localhost:8080/0/detection/start > /dev/null
    0 18 * * * root /usr/bin/lwp-request http://localhost:8080/0/detection/pause > /dev/null

If you want to use the http remote control from your own software (for example your own PHP front end) you can set the new motion.conf option html_output off. Then Motion answers back with very basic text only and no html around it. A bit like the xmlrpc interface did.

To remote control Motion from a web pages you can for example use PHP. In PHP it takes this simple code line to send a remote commend to Motion. Here we pause motion detection for camera 2

`readfile('http://localhost:8080/2/detection/pause');`

What happened to XMLRPC?

XMLRPC is replaced by a simpler http remote control interface. It is still being worked on but it is absolutely useable now and much nicer to work with than xmlrpc. Another advantage is that you do not need to install xmlrpc libraries. It is all written in standard C.

Security Warning! Note that this feature also means you have to pay attention to the following.

- Anyone with access to the remote control port (http) can alter the values of any options and save files anywhere on your server with the same privileges as the user running Motion. They can execute any command on your computer with the same privileges as the user running Motion. Anyone can access your control port if you have not either limited access to localhost or limited access using firewalls in the server. You should always have a router between a machine running Motion with remote control enabled and the Internet and make sure the Motion control port is not accessible from the outside.
- If you limit control port to localhost you still need to take care of any user logging into the server with any kind of terminal session.
- It is a good idea to run Motion as a harmless user. Not as root!!

These are the config file options that control Motion.

These must be placed in motion.conf and not in a thread config file.

### control_authentication

- Type: String
- Range / Valid values: Max 4096 characters
- Default: Not defined
- Option Topic

To protect HTTP Control by username and password, use this option for HTTP 1.1 Basic authentication. The string is specified as username:password. Do not specify this option for no authentication. This option must be placed in motion.conf and not in a thread config file.

By setting this to on, the control using http (browser) can only be accessed using login and password ( following the Basic Authentication defined in HTTP RFC).

### control_html_output

- Type: Boolean
- Range / Valid values: on, off
- Default: on
- Option Topic

Enable HTML in the answer sent back to a browser connecting to the control_port. This option must be placed in motion.conf and not in a thread config file.

The recommended value for most is "on" which means that you can navigate and control Motion with a normal browser. By setting this option to "off" the replies are in plain text which may be easier to parse for 3rd party programs that control Motion.

### control_localhost

- Type: Boolean
- Range / Valid values: on, off
- Default: on
- Option Topic

Limits the http (html) control to the localhost. This option must be placed in motion.conf and not in a thread config file.

By setting this to on, the control using http (browser) can only be accessed on the same machine on which Motion is running.

### control_port

- Type: Integer
- Range / Valid values: 0 - 65535
- Default: 0 (disabled)
- Option Topic

Sets the port number for the http (html using browser) based remote control. This option must be placed in motion.conf and not in a thread config file.

This sets the TCP/IP port number to be used for control of motion using http (browser). Port numbers below 1024 normally requires that you have root privileges. Port 8080 is a fine choice of port to use for the purpose.

-- KennethLavrsen - 12 Apr 2005

## External Commands

Motion can execute external commands based on the motion detection and related events. They are all described in this section. The option `quiet` is also included in this section.

A redesign of the external commands was due. They were not very easy to understand, not all were flexible enough and some were missing. So a new external command feature set was made for 3.2.1 and on.

This is how the new script commands look like:

Function | Old Option | New Option | Argument Appended
--- | --- | --- | ---
Start of event (first motion) | execute | on_event_start | None
End of event (no motion for gap seconds) | New! | on_event_end | None
Picture saved (jpg or ppm) | onsave | on_picture_save | Filename of picture
Movie starts (mpeg file opened) | onmpeg | on_movie_start | Filename of movie
Movie ends (mpeg file closed) | onffmpegclose | on_movie_end | Filename of movie
Motion detected (each single frame with Motion detected) | New! | on_motion_detected | None

Mail and sms has been removed because they were not configurable. If you want to send event-based mails or sms, just use one of those commands above and send the mail from that script. See What happened to mail and sms?

Security Warning! Note that this feature also means you have to pay attention to the following.

- Anyone with access to the remote control port (http) can execute any command on your computer with the same privileges as the user running Motion. Anyone can access your control port if you have not either limited access to localhost or limited access using firewalls in the server. You should always have a router between a machine running Motion with remote control enabled and the Internet and make sure the Motion control port is not accessible from the outside.
- If you limit control port to localhost you still need to take care of any user logging into the server with any kind of GUI or terminal session. All it takes is a browser or single command line execution to change settings in Motion.
- It is a good idea to run Motion as a harmless user. Not as root!!

These are the options

### on_area_detected

- Type: String
- Range / Valid values: Max 4095 characters
- Default: Not defined
- Option Topic

Command to be executed when motion in a predefined area is detected. Check option area_detect.

### on_camera_lost

- Type: String
- Range / Valid values: Max 4095 characters
- Default: Not defined
- Option Topic

Command to be executed when a camera can't be opened or if it is lost. You can use Conversion Specifiers and spaces as part of the command. Use %f for passing filename (with full path) to the command. (new in 3.2.10)

NOTE: There is situations when motion don't detect a lost camera!
It depends on the driver, some drivers dosn't detect a lost camera at all
Some hangs the motion thread. Some even hangs the PC!

### on_event_end

- Type: String
- Range / Valid values: Max 4095 characters
- Default: Not defined
- Option Topic

Command to be executed when an event ends after a period of no motion. The period of no motion is defined by option gap. You can use Conversion Specifiers and spaces as part of the command.

Full path name of the program/script.

This can be any type of program or script. Remember to set the execution bit in the ACL and if it is a script type program such as perl or bash also remember the shebang line (e.g. #!/user/bin/perl) as the first line of the script.

The command is run when an event is over. I.e. the number of seconds defined by the time 'gap' has passed since the last detection of motion and motion closes the mpeg file.

### on_event_start

- Type: String
- Range / Valid values: Max 4095 characters
- Default: Not defined
- Option Topic

Command to be executed when an event starts. An event starts at first motion detected after a period of no motion defined by gap. You can use ConversionSpecifiers and spaces as part of the command.

Full path name of the program/script.

This can be any type of program or script. Remember to set the execution bit in the ACL and if it is a script type program such as perl or bash also remember the shebang line (e.g. #!/user/bin/perl) as the first line of the script.

The command is run when an event starts. I.e. the first motion is detected since the last event.

This option replaces the former options 'mail', 'sms' and 'execute'.

### on_motion_detected

- Type: String
- Range / Valid values: Max 4095 characters
- Default: Not defined
- Option Topic

Command to be executed when a motion frame is detected. You can use Conversion Specifiers and spaces as part of the command.

Do not write "none" if you do not want to execute commands. Simply do not include the option in the file or comment it out by placing a "#" or ";" as the first character on the line before the execute command.

### on_movie_end

- Type: String
- Range / Valid values: Max 4095 characters
- Default: Not defined
- Option Topic

Command to be executed when an ffmpeg movie is closed at the end of an event. You can use Conversion Specifiers and spaces as part of the command. Use %f for passing filename (with full path) to the command.

Full path name of the program/script.

This can be any type of program or script. Remember to set the execution bit in the ACL and if it is a script type program such as perl or bash also remember the shebang line (e.g. #!/user/bin/perl) as the first line of the script.

The command is run when an event is over. I.e. the number of seconds defined by the time 'gap' has passed since the last detection of motion and motion closes the mpeg file.

This option was previously called onffmpegclose.

Note that from Motion 3.2.4 the path name of the picture file is no longer appended to the command. Instead you can use the conversion specifier %f to insert the picture filename (full path) anywhere in the command.

Most common conversion specifiers

- %Y = year, %m = month, %d = date
- %H = hour, %M = minute, %S = second
- %v = event
- %q = frame number
- %t = thread (camera) number
- %D = changed pixels
- %N = noise level
- %i and %J = width and height of motion area
- %K and %L = X and Y coordinates of motion center
- %C = value defined by text_event
- %f = filename with full path
- %n = number indicating filetype

### on_movie_start

- Type: String
- Range / Valid values: Max 4095 characters
- Default: Not defined
- Option Topic

Command to be executed when an mpeg movie is created. You can use Conversion Specifiers and spaces as part of the command. Use %f for passing filename (with full path) to the command.

Full path name of the program/script.

This can be any type of program or script. Remember to set the execution bit in the ACL and if it is a script type program such as perl or bash also remember the shebang line (e.g. #!/user/bin/perl) as the first line of the script. When you use ffmpeg the film is generated on the fly and on_movie_start then runs when the new mpeg file is created. Often you will want to use the on_movie_end option which runs when the mpeg file is closed and the event is over.

This option was previously called onmpeg.

Note that from Motion 3.2.4 the path name of the picture file is no longer appended to the command. Instead you can use the conversion specifier %f to insert the picture filename (full path) anywhere in the command.

Most common conversion specifiers

- %Y = year, %m = month, %d = date
- %H = hour, %M = minute, %S = second
- %v = event
- %q = frame number
- %t = thread (camera) number
- %D = changed pixels
- %N = noise level
- %i and %J = width and height of motion area
- %K and %L = X and Y coordinates of motion center
- %C = value defined by text_event
- %f = filename with full path
- %n = number indicating filetype

### on_picture_save

- Type: String
- Range / Valid values: Max 4095 characters
- Default: Not defined
- Option Topic

Command to be executed when an image is saved. You can use Conversion Specifiers and spaces as part of the command. Use %f for passing filename (with full path) to the command.

Full path name of the program/script.

This can be any type of program or script. Remember to set the execution bit in the file access control list (chmod) and if it is a script type program such as perl or bash also remember the shebang line (e.g. #!/usr/bin/perl) as the first line of the script.

Note that from Motion 3.2.4 the path name of the picture file is no longer appended to the command. Instead you can use the conversion specifier %f to insert the picture filename (full path) anywhere in the command.

Most common conversion specifiers

- %Y = year, %m = month, %d = date
- %H = hour, %M = minute, %S = second
- %v = event
- %q = frame number
- %t = thread (camera) number
- %D = changed pixels
- %N = noise level
- %i and %J = width and height of motion area
- %K and %L = X and Y coordinates of motion center
- %C = value defined by text_event
- %f = filename with full path
- %n = number indicating filetype

### quiet

- Type: Boolean
- Range / Valid values: on, off
- Default: off
- Option Topic

Be quiet, don't output beeps when detecting motion.

Only works in non-daemon mode.

### What happened to mail and sms?

The 6 new on_xxxxx options replace the former execute, mail and sms options.

They are quite generic and flexible. These small bash scripts gives to the same functionality as mail and sms BUT you have all the flexibility you want to extend the messages, change the 'from' email address etc.

#### Sending email at start of event

Script written by JoergWeber

    #!/bin/sh

    # Motion sample script to send an e-mail at start of an event.
    # Replaces the former 'mail' option.
    # Just define this script as 'on_event_start'-script in motion.conf like that:
    # on_event_start send_mail "%Y-%m-%d %T"

    #change to suit your needs:
    #location of 'mail' binary
    MAIL="/usr/bin/mail"
    #Destination e-mail address
    TO="root@localhost"
    #Subject of the e-mail
    SUBJECT="Motion detected"

    #Don't change anything below this line
    echo -e "This is an automated message generated by motion.\n\nMotion detected: $1\n\n" | $MAIL -s "$SUBJECT" $TO

#### Sending SMS at start of event

Script written by JoergWeber

If you uncomment the line `#/usr/local/bin/send_mail $1` you can combine both sending email and sms.

    #!/bin/sh

    # Motion sample script to send an sms at start of an event.
    # Replaces the former 'sms' option.
    # Just define this script as 'on_event_start'-script in motion.conf like that:
    # on_event_start send_sms "%Y-%m-%d %T"
    #
    # If you want to send an e-mail message here as well, just uncomment the last
    # line of this script.

    #change to suit your needs:
    #location of 'sms-client' binary
    SMS_CLIENT="/usr/bin/sms_client"
    #Destination sms number
    TO="12345"

    #Don't change anything below this line
    $SMS_CLIENT $TO "Motion detected $1"

    #/usr/local/bin/send_mail $1

# Motion Guide - Special Features

## Tracking Control

This is still at the experimental stage. Read more about it motion tracking page.

### Tracking Feature with Logitech Quickcam Sphere/Orbit

Motion supports controlling the pan and tilt feature of a Logitech Quickcam Sphere/Orbit.

Motion can move the camera to a fixed position given in degrees pan (left-right) and tilt (down-up). Movement can be set with absolute coordinates or relative to current position. There is also an auto tracking feature for the Logitech Quickcam Sphere/Orbit but it is not very mature. It is fun to play with but not very useful yet. See this topic of how KennethLavrsen controls his Sphere: LogitechSphereControl.

For a detailed description of http remote control see the section Remote Control with http.

List of tracking options

### track_auto

- Type: Boolean
- Range / Valid values: on, off
- Default: off
- Option Topic

Enable auto tracking

Requires a tracking camera type supported by Motion.

### track_iomojo_id

- Type: Integer
- Range / Valid values: 0 - 65535
- Default: 0
- Option Topic

Use this option if you have an iomojo smilecam connected to the serial port instead of a general stepper motor controller.

Only used for iomojo camera.

### track_maxx

- Type: Integer
- Range / Valid values: 0 - 65535
- Default: 0
- Option Topic

The maximum position for servo x.

Only used for stepper motor tracking.

### track_maxy

- Type: Integer
- Range / Valid values: 0 - 65535
- Default: 0
- Option Topic

The maximum position for servo y.

Only used for stepper motor tracking.

### track_motorx

- Type: Integer
- Range / Valid values: 0 - 65535
- Default: 0
- Option Topic

The motor number that is used for controlling the x-axis.

Only used for stepper motor tracking.

### track_motory

- Type: Integer
- Range / Valid values: 0 - 65535
- Default: 0
- Option Topic

The motor number that is used for controlling the y-axis.

Only used for stepper motor tracking.

### track_move_wait

- Type: Integer
- Range / Valid values: 0 - 65535
- Default: 10
- Option Topic

Delay during which tracking is disabled after auto tracking has moved the camera. Delay is defined as number of picture frames.

The actual delay is depending on the chosen framerate. If you want the camera to move maximum once every 2 seconds and the framerate is 10 then you need to set the track_move_wait value to 2 * 10 = 20.

### track_port

- Type: String
- Range / Valid values: Max 4095 characters
- Default: Not defined
- Option Topic

This is the device name of the serial port to which the stepper motor interface is connected.

Only used for stepper motor tracking.

### track_speed

- Type: Integer
- Range / Valid values: 0 - 255
- Default: 255
- Option Topic

Speed to set the motor to.

Only used for stepper motor tracking.

### track_step_angle_x

- Type: Integer
- Range / Valid values: 0-90
- Default: 10
- Option Topic

Angle in degrees the camera moves per step on the X-axis with auto tracking. Currently only used with pwc type cameras.

Requires a tracking camera type pwc.

### track_step_angle_y

- Type: Integer
- Range / Valid values: 0-40
- Default: 10
- Option Topic

Angle in degrees the camera moves per step on the Y-axis with auto tracking. Currently only used with pwc type cameras.

Requires a tracking camera type pwc.

### track_stepsize

- Type: Integer
- Range / Valid values: 0 - 255
- Default: 40
- Option Topic

Number of steps to make.

Only used for stepper motor tracking.

### track_type

- Type: Discrete Strings
- Range / Valid values: 0 (none), 1 (stepper), 2 (iomojo), 3 (pwc), 4 (generic), 5 (uvcvideo)
- Default: 0 (None)
- Option Topic

Type of tracker.

Motion has special tracking options which use either a serial stepper motor controller, an iomojo smile cam or a Philips WebCam driver compatible pan/tilt camera such as the Logitech Quickcam Sphere or Orbit.

To disable tracking, set this to 0 and the other track options are ignored.

Value 1 is for the special Motion Tracking project using a stepper motor and a home made controller.

Value 2 is for the iomojo smilecam

Value 3 is for pwc type USB tracking cameras such as the Logitech Quickcam Sphere/Orbit which is driven by the pwc (Philips WebCam) driver. To use this camera your version of pwc must be at least 8.12.

Value 4 is the generic track type. Currently it has no other function than enabling some of the internal Motion features related to tracking. Eventually more functionality will be implemented for this type.

Value 5 is for uvcvideo type USB tracking cameras such as the Logitech Quickcam Sphere/Orbit MP (new Model) which is driven by the uvcvideo driver. This option was added in Motion 3.2.8.

## Using Databases

Motion can be compiled with both MySQL and PostgreSQL database support. When enabled Motion adds a record to a table in the database as specified by the sql_query. The query contains the fields that are used and the value are given by using conversion specifiers for dynamic data like filename, time, number of detected pixels etc. Motion does not place any binary images in the database and it cannot remove old records.

Motion only adds records to the database when files are created. The database contains records of saved files which means to get a record in the database the feature that enables for example motion detection, timelapse, snapshots etc must be enabled. The sql_log options defines which types of files are logged in the database.

The following sql_log options are common to both MySQL and PostgreSQL.

### sql_log_image

- Type: Boolean
- Range / Valid values: on, off
- Default: on
- Option Topic

Log to the database when creating motion triggered image file.

Configuration option common to MySQL and PostgreSQL. Motion must be built with MySQL or PostgreSQL support to use this feature.

### sql_log_mpeg

- Type: Boolean
- Range / Valid values: on, off
- Default: off
- Option Topic

Log to the database when creating motion triggered mpeg file.

Configuration option common to MySQL and PostgreSQL. Motion must be built with MySQL or PostgreSQL support to use this feature.

### sql_log_snapshot

- Type: Boolean
- Range / Valid values: on, off
- Default: on
- Option Topic

Log to the database when creating a snapshot image file.

Configuration option common to MySQL and PostgreSQL. Motion must be built with MySQL or PostgreSQL support to use this feature.

### sql_log_timelapse

- Type: Boolean
- Range / Valid values: on, off
- Default: off
- Option Topic

Log to the database when creating timelapse mpeg file

Configuration option common to MySQL and PostgreSQL. Motion must be built with MySQL or PostgreSQL support to use this feature.

### sql_query

- Type: String
- Range / Valid values: Max 4095 characters
- Default: insert into security(camera, filename, frame, file_type, time_stamp, text_event) values('%t', '%f', '%q', '%n', '%Y-%m-%d %T', '%C')
- Option Topic

SQL query string that is sent to the database. The values for each field are given by using convertion specifiers

Most common conversion specifiers

- %Y = year, %m = month, %d = date
- %H = hour, %M = minute, %S = second
- %v = event
- %q = frame number
- %t = thread (camera) number
- %D = changed pixels
- %N = noise level
- %i and %J = width and height of motion area
- %K and %L = X and Y coordinates of motion center
- %C = value defined by text_event
- %f = filename with full path
- %n = number indicating filetype

See the "MySQL" section for detailed information about the database itself.

## MySQL

You can use the MySQL database to register each file that is stored by motion.

You need to generate a new database with a name of your own choice. You must enter this name in the config file (mysql_db option). The default value for the option sql_query requires that you create a new database in MySQL with a new table called "security" with the following fields:

insert into security(camera, filename, frame, file_type, time_stamp, text_event) values('%t', '%f', '%q', '%n', '%Y-%m-%d %T', '%C')

- camera (int) - camera (thread) number
- filename (char60) - filename (full path)
- frame (int) - the number of the picture frame
- file_type (int) - file type as a number - see table below.
- time_stamp (timestamp) - timestamp for the picture in native database format
- text_event (timestamp) - The text from the text_event option which by default is compatible with timestamps in SQL.

Note from version 3.2.4 the introduction of sql_query completely redefines the way you setup the SQL feature. It is now 100% flexible and can easily be made compatible with your existing Motion database from earlier versions of Motion.

These are the file type descriptions and the file type numbers stored in the database.

Normal image | 1
Snapshot image | 2
Motion image (showing only pixels defined as motion) | 4
Normal mpeg image | 8
Motion mpeg (showing only pixels defined as motion) | 16
Timelapse mpeg | 32

You can create the table using the following SQL statement.

`CREATE TABLE security (camera int, filename char(80) not null, frame int, file_type int, time_stamp timestamp(14), text_event timestamp(14));`

If you choose to use text_event for a non-timestamp value you can instead define something like.

`CREATE TABLE security (camera int, filename char(80) not null, frame int, file_type int, time_stamp timestamp(14), text_event char(40));`

Remember to update grant table to give access to the mysql username you choose for motion.

It would be too much to go into detail about how to setup and use MySQL. After all this is a guide about Motion. However here are some hints and links.

Setting Up a MySQL Based Website - A beginners guide from Linux Planet.

Webmonkey PHP/!MySQL tutorial - Entertaining and easy to read.

The phpMyAdmin homepage. The best and simplest tool to use MySQL (editors opinion). Requires Apache/PHP.

The options for MySQL

### mysql_db

- Type: String
- Range / Valid values: Max 4095 characters
- Default: Not defined
- Option Topic

Name of the MySQL database.

MySQL CONFIG FILE OPTION. Motion must be built with MySQL libraries to use this feature.

If you compiled motion with MySQL support you will need to set the mysql options if you want motion to log events to the database.

### mysql_host

- Type: String
- Range / Valid values: Max 4095 characters
- Default: localhost
- Option Topic

IP address or domain name for the MySQL server. Use "localhost" if motion and MySQL runs on the same server.

MySQL CONFIG FILE OPTION. Motion must be built with MySQL libraries to use this feature.

### mysql_password

- Type: String
- Range / Valid values: Max 4095 characters
- Default: Not defined
- Option Topic

The MySQL password.

MySQL CONFIG FILE OPTION. Motion must be built with MySQL libraries to use this feature.

### mysql_user

- Type: String
- Range / Valid values: Max 4095 characters
- Default: Not defined
- Option Topic

The MySQL user name.

MySQL CONFIG FILE OPTION. Motion must be built with MySQL libraries to use this feature.

## PostgreSQL

Same/similar as for MySQL above.

The options for PostgreSQL

### pgsql_db

- Type: String
- Range / Valid values: Max 4095 characters
- Default: Not defined
- Option Topic

Name of the PostgreSQL database.

PostgreSQL CONFIG FILE OPTION. Motion must be built with PostgreSQL libraries to use this feature.

If you compiled motion with PostgreSQL support you will need to set all the pgsql_ options if you want motion to log events to the database.

### pgsql_host

- Type: String
- Range / Valid values: Max 4095 characters
- Default: localhost
- Option Topic

IP address or domain name for the PostgreSQL server. Use "localhost" if motion and PostgreSQL runs on the same server.

PostgreSQL CONFIG FILE OPTION. Motion must be built with pgsql_db libraries to use this feature.

### pgsql_password

- Type: String
- Range / Valid values: Max 4095 characters
- Default: Not defined
- Option Topic

The PostgreSQL password.

PostgreSQL CONFIG FILE OPTION. Motion must be built with PostgreSQL libraries to use this feature.

### pgsql_port

- Type: Integer
- Range / Valid values: 0 - 65535
- Default: 5432
- Option Topic

The PostgreSQL server port number.

PostgreSQL CONFIG FILE OPTION. Motion must be built with PostgreSQL libraries to use this feature.

### pgsql_user

- Type: String
- Range / Valid values: Max 4095 characters
- Default: Not defined
- Option Topic

The PostgreSQL user name.

PostgreSQL CONFIG FILE OPTION. Motion must be built with PostgreSQL libraries to use this feature.

## Video4Linux Loopback Device

You can use this driver for looking at motion in realtime. The video4linux driver is written by the same author that first created Motion. You can find the source and a brief description at the video4linux loopback device web page.

The video4linux device is a Kernel module which installs itself as a video pipe. It has an input and an output. The module simply takes anything that comes on its input and send it out at the output. The purpose of this is to create a standard video4linux type video device that other programs can then use. You may now ask: "What do I need that for?".

Only one program can access a video device at a time. When motion is using a camera - no other program can access the same camera. But motion is made to be able to feed a video signal to the video loopback device. This way an additional program such as Camstream, Xawtv, a video stream server etc can watch the signal from a camera that motion uses already. What you see is not the live camera stream but the exact same picture that motion uses for detecting motion and the same pictures that are saved/streamed. You can also choose to see the "motion" type images where you see the pixels that are changing - live. Originally the video4linux pipe was used as an interface between Motion and a Webcam server. Since version 2.9 Motion has had its own webserver so this usage is no longer very relevant.

When you install the video loopback device it will create an input - for example /dev/video5 and an output - for example /dev/video6. You can then tell motion to "pipe" the video signal to the /dev/video5 and look at the pictures live using e.g. Camstream on /dev/video6. Camstream is "fooled" to think it is looking at a real camera.

Installing

Installing the video loopback device is not difficult. At least not when you have this document available.

First you must prepare your system for more video devices. You will need two extra devices for each video pipe that you want.

For example if you have 4 cameras they will probably run at /dev/video0, /dev/video1, /dev/video2, and /dev/video3. So you will need additional 8 video devices. This is easy to do.

    mknod /dev/video4 c 81 4
    mknod /dev/video5 c 81 5
    mknod /dev/video6 c 81 6
    mknod /dev/video7 c 81 7
    mknod /dev/video8 c 81 8
    mknod /dev/video9 c 81 9
    mknod /dev/video10 c 81 10
    mknod /dev/video11 c 81 11

Note that the video device number is the same as the last parameter given on each line.

You may need to set the ownership and permissions (chown and chmod) to be the same as the video devices that were already there.

Now you need to install the video loopback device.

Download the latest video4linux loopback device . Place the file in a place of your own choice.

Untar and uncompress the file to the place you want the program installed. Editor recommends /usr/local/vloopback.

`cd /usr/local`

`tar -xvzf /path/to/vloopback-1.1-rc1.tar.gz`

You now have a directory called vloopback-1.1-rc1. You can rename it to vloopback (mv vloopback-1.1-rc1 vloopback). I recommend creating a symbolic link to the current version. This way you can more easily experiment with different versions simply by changing the link.

`ln -s vloopback-1.1-rc1 vloopback`

Now change to the new directory

`cd vloopback`

Build the code

`make`

There is a good chance that the make will not work and give you a long list of errors. To run make the following must be available on you machine.

- The kernel source files must be installed.
- The source files must be available at /usr/src/linux.
  E.g. the new Red Hat 7.3 does not have a link to the sources called linux. Instead there is a link called linux-2.4. This is easy to fix. Just create a link to the real source tree. Do not rename! Add a link using this command (replacing the kernel version number with the one you have on your machine)
  `ln -s /usr/src/linux-2.4.18-4 /usr/src/linux`
- Alternatively you can change the vloopback makefile so that the "LINUXSRC=/usr/src/linux" line is changed to the actual path. I recommend the link solution since this may solve other similar problems that you can get when installing other software.

When compiling on a newer Linux distribution you may get a warning about a header file malloc.h. To remove this warning simply change the header reference as suggested by the warning.

In vloopback.c you replace the line

`#include <linux/malloc.h>`

with the line

`#include <linux/slab.h>`

Install the code you built as a Kernel module. There are two options: pipes should be set to the number of video loopbacks that you want. Probably one for each camera. The dev_offset defines which video device number will be the first. If dev_offset is not defined the vloopback module will install itself from the first available video device. If you want the cameras to be assigned to the lower video device numbers you must either load vloopback after loading the video device modules OR use the dev_offset option when loading vloopback. Vloopback then installs itself in the sequence input 0, output 0, input 1, output 1, input 2, output 2 etc. Here is shown the command for our example of 4 cameras and 4 loopback devices and the first loopback device offset to /dev/video4.

`/sbin/insmod /usr/local/vloopback/vloopback.o pipes=4 dev_offset=4`

When you run the command you may get a warning about tainting the Kernel. Just ignore this. You can choose to copy the vloopback.o file into a directory in the /lib/modules tree where the insmod/modprobe programs are already looking for modules. Then the command gets simpler (/sbin/insmod vloopback pipes=.....).

If you want the loopback device to load during boot, you can place the call in one of the bootup scripts such as /etc/rc.d/rc.local. Vloopback should be loaded before you start motion.

To activate the vloopback device in motion set the 'video_pipe' option in the motion.conf file. You can also view the special motion pictures where you see the changed pixels by setting the option 'motion_video_pipe' in motion.conf. When setting the video_pipe and/or motion_video_pipe options either specify the input device as e.g. /dev/video4. You can also set the parameter to '-' which means that motion will find the first vacant video loopback device input. If you have more than one camera you may want to control which loopback device each thread uses. Then you need to define the specific device name in motion.conf for the first camera and in each thread config file for the other cameras. If you set the video_pipe parameter to '-' in the motion.conf file and not setting it in the thread config files, motion automatically assign video devices in the same sequence as the threads are loaded. You can combine both video_pipe and motion_video_pipe but then naturally you will need twice as many pipes.

De-activating should be done with this command

`/sbin/modprobe -r vloopback`

Description of the motion.conf options related to video loopback device.

### motion_video_pipe

- Type: String
- Range / Valid values: Max 4095 characters
- Default: Not defined
- Option Topic

The video4linux video loopback input device for motion images. If a particular pipe is to be used then use the device filename of this pipe, if a dash '-' is given motion will use /proc/video/vloopback/vloopbacks to locate a free pipe. Default: not set

Using this you can view the results in real time. E.g. by using the program camstream. The difference between this option and the video-pipe option is that this option shows the motion version of the images instead of the normal images.

Disable this option by not having it in the config file (or comment it out with "#" or ";").

### video_pipe

- Type: String
- Range / Valid values: Max 4095 characters
- Default: Not defined
- Option Topic

The video4linux video loopback input device for normal images. If a particular pipe is to be used then use the device filename of this pipe. If a dash '-' is given motion will use /proc/video/vloopback/vloopbacks to locate a free pipe.

Using this you can view the results in real time. E.g. by using the program camstream.

Disable this option by not having it in the config file (or comment it out with "#" or ";").

-- KennethLavrsen - 13 Apr 2005