Motion

# Configuration

## Basic Setup

Motion is able to process images from many different types of cameras. The following is brief overview of the process to set up the Motion software.

- Determine the type of camera
  - v4l2 devices which are most webcams
  - Composite capture cards
  - Network or IP cameras
  - The PI camera
  - Static movie files.
- Specify the camera in the configuration files.
- Start Motion from a terminal via the command line
- Review the messages to ensure camera was found and press cntrl-c to exit
- Specify a target_dir in the configuration file.
- Enable the web stream in the configuration file

- Specify a stream_port
- Optionally turn off stream_localhost if you want to view the stream from a different computer

- Enable the web control in the configuration file

- Specify a webcontrol_port
- Optionally turn off webcontrol_localhost if you want to view the webcontrol from a different computer
- Specify which parameters to show on the webcontrol via webcontrol_parms
- Optionally specify a stream_preview_method

The above should allow users to get Motion running and being able to view images via the stream. The next steps refine and finish a basic setup.

- Refine how the image is captured with the image processing parameters
- Specify the motion detection parameters
- Execute scripts, Save pictures or movies.

The most difficult step in the above process will be the motion detection settings and specifying them to minimize the false positives. To assist this process, Motion provides the stream_preview_method option 3 which allows users to see side by side images of where the motion is occurring next to the regular image.

- Specify stream_preview_method 3
- Specify webcontrol_parms 2
- Start Motion and in a web browser navigate to the webcontrol port
- Try adjusting the threshold, noise_level, despeckle_filter and smart_mask_speed
- Make sure to write configuration to file in order to save any changes.

Motion also includes a setup_mode which provides more values reported on the motion images and in the log to assist the setup.

The following are some additional topics which may be of interest during the initial setup.

- Run automatically at start (Run as service)
- Remove deprecated parameters warnings (Remove deprecated)
- List/include all possible configuration parameters (All parameters)

Video4linux devices must be installed per the requirements of the camera. It is out of the scope of this document to tell you how to do this and it depends on which type of camera. Once the camera is installed it will have the device name(s) of /dev/video0, /dev/video1, /dev/video2...

FreeBSD has a different naming scheme for pci devices that use the bktr subsystem. The bktr subsystem will report devices using a naming scheme of /dev/bktr0, /dev/bktr1, etc. These device may also need to use the other special device for the tuner. The tuner will need to be specified with the tunerdevice option as /dev/tuner0.

USB cameras take a lot of bandwidth. A USB camera connected to a USB2 port or hub consumes virtually all the bandwidth that the port can handle. Even with a small framesize and low framerate you should not expect to have more than one camera per USB controller. If you need more than one USB camera it is possible to add extra USB PCI cards to your computer. It is also possible that your computer has more than one controller for different USB slots. For example, if the computer has six USB ports, the three on the left may be on controller A versus the three on the right may be on controller B. In this situation, connecting two cameras to ports only on the left would not work due to excessive bandwidth. However connecting one camera to port on the right and the other to the port on the left may work since they are on different controllers.

Motion permits the use of video cards that have discreet input channels. Since USB cameras do not have input channels, the option input must be set to the value -1 for USB cameras.

Network cameras are set up via the netcam_url parameter. The latest versions of Motion support rtsp format which many cameras now stream. Some users have requested a list of the network cameras that will work with Motion. Since Motion can now process RTSP streams, almost all cameras are supported. Simply review the specifications of the camera and validate that RTSP or RTMP is listed. The cameras that will not work are those specifically sold to be integrated into proprietary software monitoring systems. When determining cameras, consider carefully before selecting a wireless camera. Cameras require a solid consistent signal and use a lot of bandwidth. Inconsistencies in the wireless signal can result in a poor user experience so the use of a hardwired camera is recommended.

The URL connection string to enter is specific to the camera and is usually provided by the manufacturer. The connection string is the same as what would be used by other video playing software such as VLC. If the camera does not stream via RTSP and instead uses a MJPEG, then Motion can also view that format. See the option netcam_url for additional options.

Raspberry Pi cameras can be set up two different ways. If Motion is installed by using the apt packages (e.g. apt-get install motion), then the camera must be set up using the bcm2835-v4l2 module which creates a v4l2 device for the camera. Users will need to install this module using the command `sudo modprobe bcm2835-v4l2`. This will set up the camera as a normal v4l2 device and it can be accessed via a standard /dev/videoX device. If Motion is built from source or installed via the deb packages on the project release page, then an additional option is to set up the camera using the mmalcam_name parameter or using the bcm2835-v4l2 module. When Motion is installed via apt, the mmalcam option is not available.

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 -1 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 camera config files with the same video device name but different input numbers Motion automatically goes into round robin mode.

Many TV tuner cards have the input channels: TV Tuner = 0, Standard composite video = 1, S-VHS = 3. Others 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 and perhaps also a S-Video input. For all these cards the inputs are numbered. The numbering varies from card to card so the easiest is to experiment with a program such as VLC that can show the video stream.

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).

Static files can also be processed by Motion in one of two ways. The first method is by using the netcam_url option and using a prefix of file:\\. With this method, Motion will process the file at the speed specified by framerate. This allows the user to either speed up or slow down the video processing to suit the particular need.

The second option for processing a static file requires a bit of additional setup and uses a v4l2loopback device. To set this up, first install the loopback software as described in the Output - Pipe Options section of this guide to create a /dev/videoX device and then use software such as ffmpeg to stream the static file into the v4l2 device. e.g. `ffmpeg -re -i mymovie.mp4 -f v4l2 /dev/video0` Then in a separate terminal, start Motion with it set to use the `/dev/video0` device as input. This method can can also be used to reformat the content to a different format. The following outputs the original movie into a gray pixel format. `ffmpeg -re -i mymovie.mp4 -f v4l2 -pix_fmt gray /dev/video0` This can be helpful as a interim process where ffmpeg supports a particular input but that format is not yet supported by Motion.

Run as Service

The following instructions are only applicable to Debian and Ubuntu based systems. For other distributions, users should consult their distribution documentation and provide pull requests to the Motion developers so that this section can be updated with their distribution.

Motion can be set up to run as a service which means that it will start automatically whenever the computer is started. When setting up Motion to run as a service, it should be done only after all the other configuration has been completed. It is much easier to edit and revise the parameters when Motion is just running in a terminal rather than as a service. Motion now uses the systemctl and when running as a service, the option daemon must be set as `off`

The following commands control the Motion service.

- Start the Motion service`sudo systemctl start motion`
- Stop the Motion service`sudo systemctl stop motion`

When running as a service, Motion runs as the user `motion` and this user is automatically added to the user group of `video`. By only be included in this user group, when Motion is run, it will only have limited permissions. It is NOT recommended that this user get added to the `sudo` group. Instead, only add this user to groups that are specifically required.

## Command Line Options

SYNOPSIS `motion [ -hbnsm ] [ -c config file path ] [ -d level ] [ -k level ] [ -p pid_file ] [ -l log_file ]`

- -c : Full path and filename of config file.
- -h : Show help screen
- -b : Run in daemon mode
- -n : Run in non-daemon mode
- -s : Run in setup mode. Also forces non-daemon mode.
- -d : Run with message log level 1 - 9
- -k : Run with message log type 1 - 9
- -l : Full path and file name for log file
- -p : Full path and file name for the process id file
- -m : Start in pause mode

## The Configuration 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 /etc/motion)

If you have write access to /usr/local/etc/motion then the editor recommends having only one motion.conf file in the default /usr/local/etc/motion 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/motion 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 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 at the same time. The motion.conf file establishes global parameters that apply to all cameras and separate camera.conf files that specify the parameters that apply to each specific camera. The camera.conf files are specified at the bottom of the motion.conf file. If you only have one camera you only need the motion.conf file but if you have more than one camera, then you will need to have one camera config file per camera plus the motion.conf file.

If you have for example two cameras you need motion.conf and two camera config files. So a total of three config files.

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

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

The first camera is defined in the first camera file called from motion.conf. The 2nd camera is defined in the 2nd camera 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 camera config file.

To make it clear, the camera files format and syntax is the same as motion.conf. An example of what you might want in a camera file as follows: assume you have two cameras, attached to one system. Create files camera0.conf and camera1.conf. At the end of motion.conf, uncomment out the lines that refer to them. The full contents of the camera files can be as simple as

camera0.conf:
`video_device /dev/video0`

camera1.conf:
`video_device /dev/video1`

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 "camera" is defined in motion.conf, the camera 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 camera config file.
4. Motion reads the command line option again overruling any previously defined options.

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

Nearly all config options can be unique for a specific camera and placed in a camera config file. There are a few options that must be in motion.conf and cannot be in a camera config file: webcontrol_* , daemon, and camera.

If motion is built without specific features such as ffmpeg, mysql etc it will ignore the options that belong to those features.

Deprecated Parameters

Over the years, Motion has added many new configuration parameters and changed the name of a few of them so that there is some consistency to the parameter names. Since version 3.4.1, when a configuration parameter has a new name or additional functionality, Motion will try to interpret the value specified for the old parameter and translate it to the new parameter. These translations will be reported in the log as Motion is started. To eliminate these warnings, ensure that a webcontrol_port is specified and that the webcontrol_interface is specified as 0 (or not listed). Then start motion, open a browser and navigate to the webcontrol port. When on that page, select `write configuration`. This will re-write the configuration files with all the current parameters to Motion. Note that depending upon where the configuration files are located, Motion may need to be started using `sudo`.

Parameters in distributed configuration files

As of this writing, Motion includes over 150 parameters. With this volume of parameters, navigating the configuration file with every possible has become onerous. Starting with version 4.2, the distributed configuration files only include a limited subset of the configuration parameters. Users can add to the files as needed the parameters that are applicable to their set up. Users that wish to have every parameter listed and included in the configuration file can follow the process described immediately above in the Remove deprecated section. i.e. Use the webcontrol interface to write out the configuration file.

Extended descriptions / documentation are not included in the configuration file. This guide should be consulted for documentation of the configuration parameters.

## 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 movie file of the last event and exit |
SIGUSR1 | Motion will create an movie file of the current event. |

## Configuration Options-Listed Alphabetically

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, SQLite, FFMPEG, etc).

Version 4.1 | Version 4.2 | Version 4.3 | Current Version
area_detect | area_detect | area_detect | area_detect
auto_brightness | auto_brightness | auto_brightness | auto_brightness
camera | camera | camera | camera
camera_dir | camera_dir | camera_dir | camera_dir
camera_id | camera_id | camera_id | camera_id
camera_name | camera_name | camera_name | camera_name
daemon | daemon | daemon | daemon
database_busy_timeout | database_busy_timeout | database_busy_timeout | database_busy_timeout
database_dbname | database_dbname | database_dbname | database_dbname
database_host | database_host | database_host | database_host
database_password | database_password | database_password | database_password
database_port | database_port | database_port | database_port
database_type | database_type | database_type | database_type
database_user | database_user | database_user | database_user
despeckle_filter | despeckle_filter | despeckle_filter | despeckle_filter
emulate_motion | emulate_motion | emulate_motion | emulate_motion
event_gap | event_gap | event_gap | event_gap
flip_axis | flip_axis | flip_axis | flip_axis
framerate | framerate | framerate | framerate
height | height | height | height
| lightswitch_frames | lightswitch_frames | lightswitch_frames
lightswitch | lightswitch_percent | lightswitch_percent | lightswitch_percent
locate_motion_mode | locate_motion_mode | locate_motion_mode | locate_motion_mode
locate_motion_style | locate_motion_style | locate_motion_style | locate_motion_style
logfile | log_file | log_file | log_file
log_level | log_level | log_level | log_level
log_type | log_type | log_type | log_type
mask_file | mask_file | mask_file | mask_file
mask_privacy | mask_privacy | mask_privacy | mask_privacy
minimum_frame_time | minimum_frame_time | minimum_frame_time | minimum_frame_time
minimum_motion_frames | minimum_motion_frames | minimum_motion_frames | minimum_motion_frames
mmalcam_name | mmalcam_name | mmalcam_name | mmalcam_name
mmalcam_control_params | mmalcam_control_params | mmalcam_control_params | mmalcam_params
ffmpeg_bps | movie_bps | movie_bps | movie_bps
ffmpeg_video_codec | movie_codec | movie_codec | movie_codec
ffmpeg_duplicate_frames | ffmpeg_duplicate_frames | movie_duplicate_frames | movie_duplicate_frames
extpipe | movie_extpipe | movie_extpipe | movie_extpipe
use_extpipe | movie_extpipe_use | movie_extpipe_use | movie_extpipe_use
movie_filename | movie_filename | movie_filename | movie_filename
max_movie_time | movie_max_time | movie_max_time | movie_max_time
ffmpeg_output_movies | movie_output | movie_output | movie_output
ffmpeg_output_debug_movies | movie_output_motion | movie_output_motion | movie_output_motion
| movie_passthrough | movie_passthrough | movie_passthrough
ffmpeg_variable_bitrate | movie_quality | movie_quality | movie_quality
| native_language | native_language | native_language
|  |  | netcam_high_params
netcam_highres | netcam_highres | netcam_highres | netcam_high_url
|  | netcam_decoder | netcam_params
netcam_keepalive | netcam_keepalive | netcam_keepalive | netcam_params
netcam_proxy | netcam_proxy | netcam_proxy | netcam_params
netcam_tolerant_check | netcam_tolerant_check | netcam_tolerant_check | netcam_params
rtsp_uses_tcp | netcam_use_tcp | netcam_use_tcp | netcam_params
netcam_url | netcam_url | netcam_url | netcam_url
netcam_userpass | netcam_userpass | netcam_userpass | netcam_userpass
noise_level | noise_level | noise_level | noise_level
noise_tune | noise_tune | noise_tune | noise_tune
on_area_detected | on_area_detected | on_area_detected | on_area_detected
on_camera_found | on_camera_found | on_camera_found | on_camera_found
on_camera_lost | on_camera_lost | on_camera_lost | on_camera_lost
on_event_end | on_event_end | on_event_end | on_event_end
on_event_start | on_event_start | on_event_start | on_event_start
on_motion_detected | on_motion_detected | on_motion_detected | on_motion_detected
on_movie_end | on_movie_end | on_movie_end | on_movie_end
on_movie_start | on_movie_start | on_movie_start | on_movie_start
on_picture_save | on_picture_save | on_picture_save | on_picture_save
|  |  | pause
exif_text | picture_exif | picture_exif | picture_exif
output_pictures | picture_output | picture_output | picture_output
output_debug_pictures | picture_output_motion | picture_output_motion | picture_output_motion
picture_filename | picture_filename | picture_filename | picture_filename
picture_type | picture_type | picture_type | picture_type
quality | picture_quality | picture_quality | picture_quality
process_id_file | pid_file | pid_file | pid_file
post_capture | post_capture | post_capture | post_capture
pre_capture | pre_capture | pre_capture | pre_capture
quiet | quiet | quiet | quiet
rotate | rotate | rotate | rotate
roundrobin_frames | roundrobin_frames | roundrobin_frames | roundrobin_frames
roundrobin_skip | roundrobin_skip | roundrobin_skip | roundrobin_skip
switchfilter | roundrobin_switchfilter | roundrobin_switchfilter | roundrobin_switchfilter
setup_mode | setup_mode | setup_mode | setup_mode
smart_mask_speed | smart_mask_speed | smart_mask_speed | smart_mask_speed
snapshot_filename | snapshot_filename | snapshot_filename | snapshot_filename
snapshot_interval | snapshot_interval | snapshot_interval | snapshot_interval
sql_log_movie | sql_log_movie | sql_log_movie | sql_log_movie
sql_log_picture | sql_log_picture | sql_log_picture | sql_log_picture
sql_log_snapshot | sql_log_snapshot | sql_log_snapshot | sql_log_snapshot
sql_log_timelapse | sql_log_timelapse | sql_log_timelapse | sql_log_timelapse
sql_query | sql_query | sql_query | sql_query
sql_query_start | sql_query_start | sql_query_start | sql_query_start
| sql_query_stop | sql_query_stop | sql_query_stop
stream_auth_method | stream_auth_method | stream_auth_method | stream_auth_method
stream_authentication | stream_authentication | stream_authentication | stream_authentication
| stream_cors_header | stream_cors_header | stream_header_params
| stream_grey | stream_grey | stream_grey
stream_localhost | stream_localhost | stream_localhost | stream_localhost
stream_maxrate | stream_maxrate | stream_maxrate | stream_maxrate
stream_motion | stream_motion | stream_motion | stream_motion
stream_port | stream_port | stream_port | stream_port
| stream_preview_method | stream_preview_method | stream_preview_method
stream_preview_newline | stream_preview_newline | stream_preview_newline | stream_preview_newline
stream_preview_scale | stream_preview_scale | stream_preview_scale | stream_preview_scale
stream_quality | stream_quality | stream_quality | stream_quality
| stream_tls | stream_tls | stream_tls
target_dir | target_dir | target_dir | target_dir
text_changes | text_changes | text_changes | text_changes
text_event | text_event | text_event | text_event
text_left | text_left | text_left | text_left
text_right | text_right | text_right | text_right
text_double | text_scale | text_scale | text_scale
threshold | threshold | threshold | threshold
| threshold_maximum | threshold_maximum | threshold_maximum
threshold_tune | threshold_tune | threshold_tune | threshold_tune
timelapse_codec | timelapse_codec | timelapse_codec | timelapse_codec
timelapse_filename | timelapse_filename | timelapse_filename | timelapse_filename
timelapse_fps | timelapse_fps | timelapse_fps | timelapse_fps
timelapse_interval | timelapse_interval | timelapse_interval | timelapse_interval
timelapse_mode | timelapse_mode | timelapse_mode | timelapse_mode
track_auto | track_auto | track_auto | track_auto
| track_generic_move | track_generic_move | track_generic_move
track_iomojo_id | track_iomojo_id | track_iomojo_id | track_iomojo_id
track_maxx | track_maxx | track_maxx | track_maxx
track_maxy | track_maxy | track_maxy | track_maxy
track_motorx | track_motorx | track_motorx | track_motorx
track_motory | track_motory | track_motory | track_motory
track_move_wait | track_move_wait | track_move_wait | track_move_wait
track_port | track_port | track_port | track_port
track_speed | track_speed | track_speed | track_speed
track_step_angle_x | track_step_angle_x | track_step_angle_x | track_step_angle_x
track_step_angle_y | track_step_angle_y | track_step_angle_y | track_step_angle_y
track_stepsize | track_stepsize | track_stepsize | track_stepsize
track_type | track_type | track_type | track_type
tunerdevice | tunerdevice | tunerdevice | tuner_device
frequency | frequency | frequency | video_params
input | input | input | video_params
norm | norm | norm | video_params
v4l2_palette | v4l2_palette | v4l2_palette | video_params
brightness | vid_control_params | vid_control_params | video_params
contrast | vid_control_params | vid_control_params | video_params
hue | vid_control_params | vid_control_params | video_params
power_line_frequency | vid_control_params | vid_control_params | video_params
saturation | vid_control_params | vid_control_params | video_params
| vid_control_params | vid_control_params | video_params
videodevice | videodevice | videodevice | video_device
video_pipe | video_pipe | video_pipe | video_pipe
motion_video_pipe | video_pipe_motion | video_pipe_motion | video_pipe_motion
|  |  | watchdog_tmo
|  |  | watchdog_kill
| webcontrol_auth_method | webcontrol_auth_method | webcontrol_auth_method
webcontrol_authentication | webcontrol_authentication | webcontrol_authentication | webcontrol_authentication
| webcontrol_cert | webcontrol_cert | webcontrol_cert
| webcontrol_cors_header | webcontrol_cors_header | webcontrol_header_params
webcontrol_html_output | webcontrol_interface | webcontrol_interface | webcontrol_interface
ipv6_enabled | webcontrol_ipv6 | webcontrol_ipv6 | webcontrol_ipv6
| webcontrol_key | webcontrol_key | webcontrol_key
webcontrol_localhost | webcontrol_localhost | webcontrol_localhost | webcontrol_localhost
|  |  | webcontrol_lock_attempts
|  |  | webcontrol_lock_max_ips
|  |  | webcontrol_lock_minutes
webcontrol_parms | webcontrol_parms | webcontrol_parms | webcontrol_parms
webcontrol_port | webcontrol_port | webcontrol_port | webcontrol_port
| webcontrol_tls | webcontrol_tls | webcontrol_tls
width | width | width | width
stream_limit | -Deprecated | -Deprecated | -Deprecated
substream_port | -Deprecated | -Deprecated | -Deprecated

## Configuration Options-Listed by Topic

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, SQLite, FFMPEG, etc).

System Processing-General Info

daemon | setup_mode | pid_file | log_file
log_level | log_type | quiet | native_language
camera_name | camera_id | camera | camera_dir
| target_dir | watchdog_tmo | watchdog_kill

Video4Linux Devices-General Info

video_device | video_params | auto_brightness | tuner_device
roundrobin_frames | roundrobin_skip | roundrobin_switchfilter

Network Cameras-General Info

netcam_url | netcam_params | netcam_high_url | netcam_high_params
netcam_userpass

Raspberry Pi Camera-General Info

mmalcam_name | mmalcam_params

Image Processing-General Info

width | height | framerate | minimum_frame_time
rotate | flip_axis | locate_motion_mode | locate_motion_style
text_left | text_right | text_changes | text_scale
text_event

Motion Detection-General Info

emulate_motion | pause | threshold | threshold_maximum
threshold_tune | noise_level | noise_tune | despeckle_filter
area_detect | mask_file | mask_privacy | smart_mask_speed
lightswitch_percent | lightswitch_frames | minimum_motion_frames | event_gap
pre_capture | post_capture

Script Execution-General Info

on_event_start | on_event_end | on_picture_save | on_motion_detected
on_area_detected | on_movie_start | on_movie_end | on_camera_lost
on_camera_found

Pictures-General Info

picture_output | picture_output_motion | picture_type | picture_quality
picture_exif | picture_filename | snapshot_interval | snapshot_filename

Movies-General Info

movie_output | movie_output_motion | movie_max_time | movie_bps
movie_quality | movie_codec | movie_duplicate_frames | movie_passthrough
movie_filename | movie_extpipe_use | movie_extpipe | timelapse_filename
timelapse_interval | timelapse_mode | timelapse_codec | timelapse_fps

Pipes-General Info

video_pipe | video_pipe_motion

Webcontrol-General Info

webcontrol_port | webcontrol_ipv6 | webcontrol_localhost | webcontrol_parms
webcontrol_interface | webcontrol_auth_method | webcontrol_authentication | webcontrol_tls
webcontrol_cert | webcontrol_key | webcontrol_header_params | webcontrol_lock_attempts
webcontrol_lock_minutes | webcontrol_lock_max_ips

Live Stream-General Info

stream_port | stream_localhost | stream_auth_method | stream_authentication
stream_tls | stream_header_params | stream_preview_scale | stream_preview_newline
stream_preview_method | stream_quality | stream_grey | stream_maxrate
stream_motion

Database-General Info

database_type | database_dbname | database_host | database_port
database_user | database_password | database_busy_timeout | sql_log_picture
sql_log_snapshot | sql_log_movie | sql_log_timelapse | sql_query
sql_query_start | sql_query_stop

Tracking-General Info

track_type | track_auto | track_port | track_motorx
track_motorx_reverse | track_motory | track_motory_reverse | track_maxx
track_minx | track_maxy | track_miny | track_homex
track_homey | track_iomojo_id | track_step_angle_x | track_step_angle_y
track_move_wait | track_speed | track_stepsize | track_generic_move

## Configuration Options-Detail Descriptions

The following section provides detailed descriptions of each of the configuration options.

### Conversion Specifiers

%Y | year | %m | month | %d | day
%H | hour | %M | minute | %S | second
%T | HH:MM:SS | %v | event | %q | frame number
%t | camera id number | %D | changed pixels | %N | noise level
%w | width of the image | %h | height of the image | %i | width of motion area
%J | height of motion area | %K | X coordinates of motion center | %L | Y coordinates of motion center
%C | value defined by text_event | %f | filename with full path | %n | number indicating filetype
%o | threshold | %Q | Number of labels from despeckle | %{dbeventid} | See sql_query_start
%$ | camera name | %{fps} | current frames per second | %{host} | name of computer running Motion
%{ver} | The version of Motion

The use of quotation marks around string is permitted. In addition to the above, the conversion specifiers include the same options as for the C function strftime (3).

### System Processing

### daemon

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

When Motion is started, immediately go to daemon mode and release the terminal. Set the option to off when running Motion as a service.

### setup_mode

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

When this option is turned on, Motion starts in setup mode so that the parameters can be set more easily. In setup mode two things happen: 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 id number. When you look at the 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 labeled 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. (There are other ways to accomplish this.)

- Disable despeckle (comment it out in motion.conf).
- Disable smartmask
- Enable both the webcontrol and streams make sure to specify the webcontrol_parms. The below assumes that the webcontrol is specified as port 8080 and the stream as 8081
- Start Motion in setup mode
- Open a browser and connect to the webcontrol interface. http://localhost:8080/ . You can now control and change almost anything while Motion is running. 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.
- Set the threshold to what you want to trigger Motion.

In normal mode you can use the same setting with two browser tabs 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 camera config files).

### pid_file

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

Specify the full path and file name in order to store the pid for processing.

### log_file

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

Use this option to specify the full path and filename to use for logging of the messages generated from Motion. If this option is not defined, the stderr and syslog is used. Note that Motion can generate a LOT of messages and as a result, this option should be considered if the log_level is at any of the higher levels.

### log_level

- Type: Integer
- Range / Valid values: 1 - 9
- Default: 6

This option specifies the level of verbosity of the messages sent from Motion. At a level of 8(DBG), there are a LOT of messages. At a level of 1(EMR) virtually no messages will be output.

The various levels are [1..9] (EMR, ALR, CRT, ERR, WRN, NTC, INF, DBG, ALL).

When reporting any issues or errors associated with the Motion application, use the INF level.

### log_type

- Type: Discreet Strings
- Range / Valid values: See Below
- Default: ALL

The different components of Motion use different log types. This option allows the user to only show the messages from particular components. The choices for this option are: COR, STR, ENC, NET, DBL, EVT, TRK, VID, ALL

### quiet

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

Be quiet, don't output beeps when detecting motion. Only works in non-daemon mode.

### native_language

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

Enable native language for Motion webcontrol and log messages.

Motion will use the locale variable LANGUAGE for determining the webcontrol and log messages. If messages or the webcontrol still display in English, then the messages / words have not yet been translated.

Please consider helping the developers by submitting pull requests to add new translations and correcting any inaccurate translations.

When this option is specified as 'off', the webcontrol and log messages will be provided in English.

### camera_name

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

This option specifies a camera name to be used in the format specifiers as well as on the web interface.

### camera_id

- Type: Integer
- Range / Valid values: 1 - 32000
- Default: The sequence that the camera file is read

This option is useful for situations where there are multiple cameras being used by Motion. This option allows for the assignment of a numeric id number that can be used in database queries, format specifiers as well as for the web interface and streams.

If this option is not specified, the thread number as determined by Motion is used. The number assigned to each camera must be unique.

When using multiple cameras, the default for the main thread is 0 (zero) but this can be overridden as needed by specifying a camera_id in the motion.conf file even though there are not any cameras running on this thread.

### camera

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

The full path and file name for the camera file. Motion allows for this line to be listed in the motion.conf file multiple times. These specifications should be the LAST lines in the motion.conf file. See the Configuration Files section within this guide for a complete discussion of what to put into the camera0.conf, camera1.conf, cameraX.conf files that would be specified in this option.

### camera_dir

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

This option specifies a directory to contain the individual camera configuration files. Any files ending in '.conf' in this directory will be read as a camera config file.
Users can disable a camera (config file) by renaming it so it does not end with '.conf'.

### target_dir

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

The full path for the target directory for picture and movie files to be saved. The default is the current directory. This is the target directory for all snapshots, picture files and movie files. You will normally always want to specify this parameter as an absolute path.

Note that the file name options are all saved relative to this target_dir This means in principle that you can specify target_dir as '/' and be 100% flexible. But this is NOT recommended. It is recommended that this directory be specified as deep as possible.

### watchdog_tmo

- Type: int
- Range / Valid values: Integer
- Default: 30

The number of seconds a camera can be non-responsive before Motion attempts to stop the camera gracefully.

### watchdog_kill

- Type: int
- Range / Valid values: Integer
- Default: 30

The number of seconds after the timeout has expired until Motion forcefully kills the camera that is unresponsive.

### Video4Linux Device

Please refer to the Basic Setup section of this guide for an additional discussion of Video4Linux devices and how to test and specify them correctly for Motion.

### video_device

- Type: String
- Range / Valid values: Max 4095 characters
- Default: /dev/video0

The video device to be used for capturing. Default is /dev/video0. See the Basic Setup section of this guide for an additional discussion of this option.

This option is the usual method to specify the video4linux device name. If the camera does not work when specifying it with this option, it is also possible to specify the device in the netcam_url with the v4l2 prefix option. The netcam_url option uses an alternative method to open and operate the device which may work with this option fails. If the netcam_url is used for either this alternative method or for a normal network camera, the video_device option is ignored.

Since the exact device number is set by the kernel upon boot, when there is more than one video device it is possible that the particular cameras that were assigned to /dev/video0 and /dev/video1 may switch. In order to set up Motion so that a particular camera is always assigned the same way, users can set up a symbolic link using udev rules. To do this a unique attribute must be identified for each camera. The camera attributes can be viewed by using the command `udevadm info -a -p $(udevadm info -q path -n /dev/video0)` while the camera is attached. Usually a serial number can be used. ("Usually" because some cameras have been observed to have the same serial number for different cameras)

Once a unique attribute has been identified for each camera, edit or create the file `/etc/udev/rules.d/99-local.rules`.

Assuming that the unique attribute for the camera was name and was `ATTR{name}=="Philips SPC 900NC webcam"` you would add the following line to the 99-local.rules file: `KERNEL=="video[0-9]*", ATTR{name}=="Philips\ SPC\ 900NC*", SYMLINK+="video-webcam0"`

Once the change has been made and saved, reboot the computer and there should now be a "sticky" device called /dev/video-webcam0

### video_params

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

For most devices the configuration options are automatically assigned but devices also usually allow the user to change certain settings to suit their needs. The options that the camera manufacturer permits the user to change are called "controls". The video_params option allows users to specify values for these controls when Motion runs.

The video_params option also allows users to specify some Motion specific parameters that are used to open the camera. In previous versions of Motion, these options were the frequency, input, norm and v4l2_palette options. These options have now been embedded into the video_params option to provide consistency.

The following is the list of previous Motion options that have now been replaced by the video_params option.

- brightness
- contrast
- hue
- power_line_frequency
- saturation
- frequency
- input
- norm
- v4l2_palette

While it always recommended that users remove older configuration options and only use the new options, if users have within the configuration file any of the deprecated options list above, Motion will continue to read those values and upgrade them into the new video_params option. The resulting pictures from the device may however may not be comparable due to different interpretations of the values.

It is therefore highly recommended that users remove the old configuration values and calibrate their devices only using this new configuration option.

To use this parameter, users will need to first identify the name or ID description of the particular control. Next, simply specify the control/id followed by an equal sign and then the desired value. The specification of multiple controls can be specified by separating them with a comma.

Since the name of some controls can include a comma or spaces, names can also be specified by enclosing them in double quotes. To help users know which controls are available for their device, the Motion log will report the available controls, associated IDs and minimum/maximum values permitted when the log_level is specified as INF or higher.

e.g. Change the log_level to INF, start up Motion with the device attached and specified, let it report items to the log and then shut Motion down. Within the Motion log, it will list which controls the device has that can be adjusted.

The following is a sample output from the log and examples of how to specify the parameters

- [1:ml1:c1] [INF] [VID] v4l2_ctrls_list: ---------Controls---------
- [1:ml1:c1] [INF] [VID] v4l2_ctrls_list: V4L2 ID Name and Range
- [1:ml1:c1] [INF] [VID] v4l2_ctrls_list: ID09963776 Brightness, 0 to 127
- [1:ml1:c1] [INF] [VID] v4l2_ctrls_list: ID09963777 Contrast, 0 to 63
- [1:ml1:c1] [INF] [VID] v4l2_ctrls_list: ID09963778 Saturation, -100 to 100
- [1:ml1:c1] [INF] [VID] v4l2_ctrls_list: ID09963788 White Balance, Automatic, 0 to 4
- [1:ml1:c1] [INF] [VID] v4l2_ctrls_list: menu item: Value 0 Indoor (Incandescant Lighting)
- [1:ml1:c1] [INF] [VID] v4l2_ctrls_list: menu item: Value 1 Outdoor (Sunlight) Mode
- [1:ml1:c1] [INF] [VID] v4l2_ctrls_list: menu item: Value 2 Indoor (Fluorescent Lighting) M
- [1:ml1:c1] [INF] [VID] v4l2_ctrls_list: menu item: Value 3 Manual Mode
- [1:ml1:c1] [INF] [VID] v4l2_ctrls_list: menu item: Value 4 Auto Mode
- [1:ml1:c1] [INF] [VID] v4l2_ctrls_list: ID09963790 Red Balance, 0 to 255
- [1:ml1:c1] [INF] [VID] v4l2_ctrls_list: ID09963791 Blue Balance, 0 to 255
- [1:ml1:c1] [INF] [VID] v4l2_ctrls_list: ID09963792 Gamma, 0 to 31
- [1:ml1:c1] [INF] [VID] v4l2_ctrls_list: ID09963793 Exposure, 0 to 255
- [1:ml1:c1] [INF] [VID] v4l2_ctrls_list: ID09963794 Gain, Automatic, 0 to 1
- [1:ml1:c1] [INF] [VID] v4l2_ctrls_list: ID09963795 Gain, 0 to 63
- [1:ml1:c1] [INF] [VID] v4l2_ctrls_list: ID09963804 Backlight Compensation, 0 to 1
- [1:ml1:c1] [INF] [VID] v4l2_ctrls_list: ID09963807 Color Effects, 0 to 1
- [1:ml1:c1] [INF] [VID] v4l2_ctrls_list: menu item: Value 0 None
- [1:ml1:c1] [INF] [VID] v4l2_ctrls_list: menu item: Value 1 Black & White
- [1:ml1:c1] [INF] [VID] v4l2_ctrls_list: ID09963809 Band-Stop Filter, 0 to 1
- [1:ml1:c1] [INF] [VID] v4l2_ctrls_list: ID10025216 Auto contour, 0 to 1
- [1:ml1:c1] [INF] [VID] v4l2_ctrls_list: ID10025217 Contour, 0 to 63
- [1:ml1:c1] [INF] [VID] v4l2_ctrls_list: ID10025218 Dynamic Noise Reduction, 0 to 3
- [1:ml1:c1] [INF] [VID] v4l2_ctrls_list: ID10025219 Auto White Balance Speed, 1 to 32
- [1:ml1:c1] [INF] [VID] v4l2_ctrls_list: ID10025220 Auto White Balance Delay, 0 to 63
- [1:ml1:c1] [INF] [VID] v4l2_ctrls_list: ID10025221 Save User Settings, 0 to 0
- [1:ml1:c1] [INF] [VID] v4l2_ctrls_list: ID10025222 Restore User Settings, 0 to 0
- [1:ml1:c1] [INF] [VID] v4l2_ctrls_list: ID10025223 Restore Factory Settings, 0 to 0
- [1:ml1:c1] [INF] [VID] v4l2_ctrls_list: --------------------------

Example 1: Set the gain to manual, then the gain to 50 and the brightness to 30

`video_params "Gain, Automatic"=1,ID09963795=50, brightness=30`

a equally valid alternative method for specifying this example would be

`video_params ID09963794=1,ID09963795=50, ID09963776=30`

or another way of specifying it could be

`video_params ID09963794=1,"Gain"=50, "brightness"=30`

Example 2: Set the saturation to 50 and the contrast to 100

`video_params saturation=50,contrast=100`

As can be seen in these examples, the specification can use either the control ID or the name of the control. If the control name has embedded blanks or commas, then it must be enclosed in quotes. Special care should be taken when using the name. As shown above, there is a comma that separates the name of the control versus the valid range of values. That comma is NOT part of the control name and only delimits the end of the name for the Motion log.

#### palette

- Type: Integer
- Range / Valid values: 0 - 20
- Default: 17

The palette option is specified in the video_params option and allows the user to specify the preferred palette for Motion to use. If the video device does not support this preferred format, Motion will loop through the available palettes to try to find one that is supported by both Motion and the device.

Motion will report the supported palettes of the device when Motion starts when the log_level is specified as NTC or higher.

The default of 17 is highly preferred over all other formats since this the native format that Motion uses internally.

The following are each of the palette options. For the Motion configuration, specify the numeric value as the Motion option.

V4l2 Option | FOURCC | v4l2_palette option
V4L2_PIX_FMT_SN9C10X | S910 | 0
V4L2_PIX_FMT_SBGGR16 | BYR2 | 1
V4L2_PIX_FMT_SBGGR8 | BA81 | 2
V4L2_PIX_FMT_SPCA561 | S561 | 3
V4L2_PIX_FMT_SGBRG8 | GBRG | 4
V4L2_PIX_FMT_SGRBG8 | GRBG | 5
V4L2_PIX_FMT_PAC207 | P207 | 6
V4L2_PIX_FMT_PJPG | PJPG | 7
V4L2_PIX_FMT_MJPEG | MJPG | 8
V4L2_PIX_FMT_JPEG | JPEG | 9
V4L2_PIX_FMT_RGB24 | RGB3 | 10
V4L2_PIX_FMT_SPCA501 | S501 | 11
V4L2_PIX_FMT_SPCA505 | S505 | 12
V4L2_PIX_FMT_SPCA508 | S508 | 13
V4L2_PIX_FMT_UYVY | UYVY | 14
V4L2_PIX_FMT_YUYV | YUYV | 15
V4L2_PIX_FMT_YUV422P | 422P | 16
V4L2_PIX_FMT_YUV420 | YU12 | 17
V4L2_PIX_FMT_Y10 | Y10 | 18
V4L2_PIX_FMT_Y12 | Y12 | 19
V4L2_PIX_FMT_GREY | GREY | 20

It is possible that after looping through all of the palette options for the camera, Motion will not find a palette that is acceptable for processing. In this situation, it may be possible to be the camera to work using the netcam_url option with the v4l2 prefix.

#### input

- Type: Integer
- Range / Valid values: -1, 0 - ?
- Default: -1

The input option is specified in the video_params option and allows the user to specify the input channel to use for the device.

For USB cameras, the input option should specify -1.

For other devices such as capture cards, the input option is device dependent but usually starts with zero. Using an external application such as VLC can allow for easier specification of the input associated with the camera.

#### norm

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

The norm option is specified in the video_params option and allows the user to specify the television norm to use for the device.

#### frequency

- Type: Integer
- Range / Valid values: 0 - 999999
- Default: 0 (Not set)

The frequency option is specified in the video_params option and allows the user to specify the frequency to use for the device.

The default is 0 meaning it is not set. This option is only relevant if the device is a TV tuner card where the frequency can be set.

### auto_brightness

- Type: Integer
- Range / Valid values: 0 - 3
- Default: 0

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 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 is close to a target value.

By default, the target value is the midpoint between the minimum and maximum value permitted for the control being adjusted. (See methods available below)

Users can specify a different target value by specifying a value for the control in the video_params option.

Motion allows for three possible methods for adjusting the brightness.

- 1: Use the brightness control to regulate the brightness (equivalent to specifying on/yes)
- 2: Use the exposure control to regulate the brightness
- 3: Use the exposure absolute control to regulate the brightness

### tuner_device

- Type: String
- Range / Valid 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 with the bktr option. See the Basic Setup section of this guide for a additional discussion of this option.

### roundrobin_frames

- Type: Integer
- Range / Valid 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. The Round Robin feature is automatically activated where multiple cameras are sharing the same video device. Each camera can then set different input or frequency options to change camera. If multiple cameras use the same video device, they each can capture roundrobin_frames number of frames before having to share the device with the other cameras.

Round Robin is not relevant for Network cameras or standard USB web cameras. It is used with video capture cards which have multiple inputs per video chip. This is not the ideal way to run multiple cameras. When the capture card changes input it takes some time before the decoder chip has synchronized to the new camera. You can improve this if you have expensive cameras with a synchronized input. Only one camera can be decoded at a time so if you have 4 cameras connected 3 of the cameras 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 afford 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. (or better yet, it multiple cheap network cameras) If multiple cameras use the same video device, they each can capture roundrobin_frames number of frames before having to share the device with the other cameras. When another camera 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 roundrobin_switchfilter 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.

### roundrobin_skip

- Type: Integer
- Range / Valid 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). The Round Robin feature is automatically activated where multiple cameras are sharing the same video device. Each camera can then set different input channels or frequencies to change camera. When another camera wants to watch another input or frequency or size the first roundrobin_ skip number of frames are skipped to allow the device to settle.

### roundrobin_switchfilter

- Type: Boolean
- Range / Valid 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. 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 video_device.

### Network Cameras

Motion can connect to certain network cameras. Please refer to the Basic Setup section of this guide for an additional discussion of network camera and how to test and specify them correctly for Motion.

Motion cannot connect to a video stream such a mpeg, mpeg4, divx to connect to streams such as these the user may review the static files portion of the Basic Setup section of this guide which illustrates some possible work arounds using ffmpeg and v4l2loopback devices.

The URL must return one single jpeg image, a mjpeg stream a RTSP stream, RTMP stream, file or ftp. When getting a still image, make sure to validate that the camera is serving up a actual raw JPG file and not a HTML page with an embedded JPG which Motion will not be able to process. When the netcam_url is defined the video4linux options above are mostly 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.

### netcam_url

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

URL for a network camera.

The list below illustrates some of the more common protocols for network cameras but Motion does not restrict the protocols to this list. Other protocols that are available via the ffmpeg libraries can also be specified.

http://

This prefix uses the traditional http format and opens a netcam that provides a motion jpg image.

When using the rtsp format, Motion will ignore the netcam_keepalive and netcam_tolerant_check options.

rtsp://

This prefix is the standard for all modern network cameras. It is recommended that users search the web or the camera manual for the exact connection string to use for their camera.

Once a potential connection string is found, it should be validated as being functional using a external application such as ffplay or vlc.

The connection string that works for these applications is what needs to be specified for this option.

When using the rtsp format, Motion will ignore the netcam_keepalive and netcam_tolerant_check options.

rtmp://

This prefix may be available on modern network cameras. It is recommended that users search the web or the camera manual for the exact connection string to use for their camera.

Once a potential connection string is found, it should be validated as being functional using a external application such as ffplay or vlc.

The connection string that works for these applications is what needs to be specified for this option.

When using the rtmp format, Motion will ignore the netcam_keepalive and netcam_tolerant_check options.

file://

This option allows for the processing of a existing movie file. Motion will open the file and process the file at the framerate specified in the Motion configuration file. Note that since the file may have been created using a different framerate than specified in the Motion config file, the file may be processed at either a faster or slower rate than real time.

A sample format for the netcam_url would be `netcam_url file:///home/user/cam1/cam1_20180817084027.mkv`

This option is useful for "reprocessing" a movie created by Motion to fine tune the detection options.

At the end of the movie file, Motion will restart the movie file at the beginning so that you can continue to refine the detection parameters.

v4l2://

This option allows for an alternative method of using a v4l2 device that is not natively supported by Motion.

A sample format for the netcam_url would be `v4l2:///dev/video0` Internally, this is equivalent to running the following from the command line `ffplay -f v4l2 /dev/video0`

mjpeg://

This is an alternative prefix for http for use when Motion is compiled without ffmpeg.

mjpg://

This option may process very old netcams with non standard mjpeg formats.

jpeg://

This option is for processing a static JPG file that is updated by processes external to Motion. It must be a local file and specified such as jpeg:///path/current.jpg

ftp://

This prefix opens the ftp site and grabs a static image. The camera will be expected to periodically replace that static image as it processes images.

### netcam_params

- Type: String
- Range / Valid values: Max 4095 characters
- Default: varies by camera type

This option allows for specification of parameters to the network camera. The format for specifying parameters and values is the same as what is given in the examples for video_params. The parameters are delimited by commas and provided in the format of parameter_name = parameter_value.

For cameras that use the url prefix of mjpeg, ftp, mjpg, and jpeg the options permitted are limited to keepalive, proxy and tolerant_check. These parameters correspond to the options provided in previous versions of Motion.

For cameras that use other url prefixes, the parameters permitted are those available from the ffmpeg library plus a some that are specific to Motion as specified below. The options of keepalive, proxy, tolerant_check are not applicable to these cameras.

The following summarizes some of the options. Full descriptions of all the ffmpeg options will be contained in the documentation for ffmpeg.

#### keepalive

- Type: String
- Range / Valid values: Max 4095 characters
- Default: off

The keepalive option is specified in the netcam_params option.

The setting for keep-alive of network socket, should improve performance on compatible net cameras.

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

#### proxy

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

The proxy option is specified in the netcam_params option.

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 omit the port number. Then the syntax is use "http://myproxy.mydomain.com" . Leave this option undefined if you do not use a proxy server.

#### tolerant_check

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

The tolerant_check option is specified in the netcam_params option.

Use less strict jpeg checks for network cameras

#### decoder

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

The decoder option is specified in the netcam_params option.

This option is specific to the Motion software and allows for specifying a user requested decoder for the camera. Motion will try to open the camera using the decoder specified by this parameter. If it not successful, it will fall back to the default decoder. This option may improve performance in certain situations for certain platforms and cameras.

Users can find the names of the decoders in ffmpeg on their system by going to a command prompt and typing `ffmpeg -decoders` and looking for the name of the decoder with a 'D' next to it and correlating this with the type of image provided from the camera. Note that although the decoder may be listed, it still may not work within Motion.

In addition to the decoders specified by ffmpeg, additional different decoder options may also be found by reviewing the Motion log. These decoders will be shown as "available" in the log when log_level is specified at the INF level or higher.

Not all decoders will work even if they are indicated as available or work using ffmpeg externally to Motion. If the camera does not open using the requested decoder, try a different decoder or leave this parameter empty to use the default.

#### capture_rate

- Type: int
- Range / Valid values: Integer
- Default: framerate

The capture_rate option is specified in the netcam_params option.

This option allows for the user to request a specific frame per second (FPS) capture rate for the network camera. This is needed at times so that the rate Motion is capturing images is in sync with what the camera is sending.

When this value is used, it makes a slight distinction from the usual interpretation of framerate. The capture_rate will specify how fast images are captured and decoded and the framerate will specify the rate at which they are processed for motion.

For example, if the capture_rate were set to be 10 and the framerate was set to be 20, what would happen is that each captured image would end up going through the Motion detection / processing routines twice because that loop is processing at twice the speed of the capture loop. Conversely, if the capture_rate was set to 20 and the framerate is specified as 10, then Motion will be detecting and processing every other image captured.

The reason that the capture_rate is not systematically set to the framerate within Motion has to with the camera. Each camera will provide a stream of images usually in some compression format such as H264 or H265 and provide those images at a particular FPS. If the capture and decoding FPS of Motion is set to a rate lower than the camera, decoding and disconnection errors will occur.

To avoid the decoding and disconnection errors, it is recommended that the FPS of the camera be adjusted where possible. Generally, it is preferable to have the FPS of the camera be slightly lower than the capture_rate of Motion. This allows for the decoder to perform better and reduce decoding errors. For example if the capture_rate is set at 5 and the camera is sending images at 30 FPS, the resulting images, processing latency, etc is going to be extremely "poor". But if the camera FPS is set at 4 instead, the results will "better".

Reviews of the Motion log at the INF level can assist in determining whether a higher capture_rate is required. In particular, look for the following:

- Log messages indicating what the netcam capture rate is versus the log entry for the camera FPS.
- The network camera is disconnecting and reconnecting frequently.
- A significant number of ffmpeg_avcodec_log messages

#### rtsp_transport

- Range / Valid values: tcp, udp, see ffmpeg documentation
- Default: tcp

The rtsp_transport option is specified in the netcam_params option. This option is from the ffmpeg libraries.

The rtsp_transport value of tcp is highly preferred because without this option the rtsp/rtmp images are frequently corrupted and result in many false positive values and images that appear to be smeared.

For some cameras, a tcp transport is not provided from the camera. Some Motion users have reported using `netsed` can workaround this limitation of the camera using the following method:

`Instead of: netcam_url rtsp://192.168.0.51:554/onvif1
Use: netcam_url rtsp://127.0.0.1:554/onvif1
Then in a different process, start netsed to substitude AVP; with AVP/TCP;
netsed tcp 554 192.168.0.51 554 's/AVP;/AVP%2FTCP;'
`

#### input_format

- Range / Valid values: mjpeg, h264, see ffmpeg documentation
- Default: tcp

The input_format option is specified in the netcam_params option. This option is from the ffmpeg libraries. This option is used for specifying the palette format of the camera when using the v4l2 via netcam option.

### netcam_high_url

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

The network camera high resolution URL used in conjunction with the netcam_url parameter. Users may specify the normal resolution in the netcam_url and that will be used for the motion detection and then specify the high resolution url for this parameter.
Motion detection on the normal resolution will trigger the saving of images from the high resolution stream. Note that the ONLY overlay that will be present on the resulting high resolution pictures and movies is the privacy mask. The other overlays such as date/time, motion boxes, camera name, etc will not be included. Users wishing to see those overlays on the resulting images and movies will need to specify the high resolution url as the netcam_url and not use this option.

If the netcam_url is not specified, this option is ignored.

When this option is used with the movie_passthrough even less processing occurs. Since the movie_passthrough bypasses decoding the stream, images will be saved as provided from the camera and the privacy mask will not be applied.

### netcam_high_params

- Type: String
- Range / Valid values: Max 4095 characters
- Default: varies by camera type

This option is the same as netcam_params option except this option applies the parameters to the high resolution camera.

### netcam_userpass

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

The username and password for the network camera. The string is specified as username:password. If the camera does not have any authentication to the stream, leave this option empty.

### Raspberry Pi Camera

Motion can use the Raspberry Pi camera when connected and Motion is compiled and installed with the MMAL support. Before setting up Motion with the camera, it is recommended that the user first validate that the camera is functional with the raspistill/raspivid applications.

Please refer to the Basic Setup section of this guide for an additional discussion of network camera and how to test and specify them correctly for Motion.

### mmalcam_name

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

Name of camera to use if you are using a camera accessed through OpenMax/MMAL. The standard Raspberry Pi camera device name is "vc.ril.camera" without the quotes.

Motion will ignore this option when the MMAL support is not included. In these situations, users will need to use the modprobe method of setting up the camera as a v4l2 device. See the Basic Setup section of this guide for further details.

### mmalcam_params

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

This option allows the user to specify control parameters to the Pi camera. The documentation of all of the options available to the Raspberry Camera module is beyond the scope of this guide. In general, the command line options that are available via the raspistill / raspivid applications are the options that can be specified in this Motion configuration option. Some of the more frequently used options are:

- Horizontal Flip: -hf
- Vertical Flip: -vf
- Rotation: -rot

Motion will ignore this option when the MMAL support is not included. In these situations, users will need to use the modprobe method of setting up the camera as a v4l2 device. See the Basic Setup section of this guide for further details.

### Image Processing

### width

- Type: Integer
- Range / Valid values: Device Dependent
- Default: 640

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

For all devices, the width must be a multiple of 8.

Motion does not scale v4l2 devices and http netcams so the value should be set to the actual size of the image provided by the device. In case of a rtsp/rtmp network camera, Motion will rescale the camera image to the requested dimensions. This rescaling comes at a very high CPU cost so it is recommended that the network camera send the image in the same dimensions as included in the configuration file.

While Motion will not rescale the image provided, it will attempt to set the size of the image coming from the video4linux device to match the values provided for height/width.

It is important to realize that certain height/width combinations are only valid at certain frame rates. The particular combinations which are valid are dependent upon the device.

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.

### height

- Type: Integer
- Range / Valid values: Device Dependent
- Default: 480

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

For all devices, the height must be a multiple of 8.

Motion does not scale v4l2 devices and http netcams so the value should be set to the actual size of the image provided by the device. In case of a rtsp/rtmp network camera, Motion will rescale the camera image to the requested dimensions. This rescaling comes at a very high CPU cost so it is recommended that the network camera send the image in the same dimensions as included in the configuration file.

While Motion will not rescale the image provided, it will attempt to set the size of the image coming from the video4linux device to match the values provided for height/width.

It is important to realize that certain height/width combinations are only valid at certain frame rates. The particular combinations which are valid are dependent upon the device.

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.

### framerate

- Type: Integer
- Range / Valid values: 2 - 100
- Default: 15

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 movies. To set intervals longer than one second use the 'minimum_frame_time' option instead.

### minimum_frame_time

- Type: Integer
- Range / Valid 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. 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.

### rotate

- Type: Discrete Integers
- Range / Valid 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 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.

### flip_axis

- Type: Discrete Strings
- Range / Valid values: none, v, h
- Default: none (no change)

Flip the image according to specified axis. The flip affects all saved images as well as movies. The flip feature is used when the camera is pointed towards a mirror or provides itself a mirrored image (as found in some cars). Note that the CPU load increases when using this feature with a value other than none.

### locate_motion_mode

- Type: Discrete Strings
- Range / Valid 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 movie.

### locate_motion_style

- Type: Discrete Strings
- Range / Valid values: box, redbox, cross, redcross
- Default: box

Set the look and style of the locate box if enabled.

### text_left

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

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

If the option is not defined no text is displayed at this position.

You can use Conversion Specifiers to define this field and also include a new line specifier as \n and spaces if this option is enclosed in quotes.

By combining spaces and new lines '\n' you can place your text anywhere on the picture. 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.

This is how the overlaid text is located.

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

### text_right

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

User defined text overlaid on each in the lower right corner. Use A-Z, a-z, 0-9, " / ( ) @ ~ # < > \ , . : - + _ \n and conversion specifiers

If the option is not defined no text is displayed at this position.

You can use Conversion Specifiers to define this field and also include a new line specifier as \n and spaces if this option is enclosed in quotes.

By combining spaces and new lines '\n' you can place your text anywhere on the picture. 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.

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.

This is how the overlaid text is located.

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

### text_changes

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

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 testing. This is how the overlaid text is located.

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

### text_scale

- Type: Integer
- Range / Valid values: 1 - 10
- Default: 1

The scale at which to draw text over the image. The recommended range is 1 - 10. This option makes the text defined by text_left, text_right and text_changes drawn at n-times the normal size. This may be useful when using large picture formats such as 1280 x 720.

### text_event

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

This option is special in that it defines the conversion specifier %C which can be used both for text display and for filenames. This option defines the value of the special 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. You can use Conversion Specifiers to define this field (except for this option itself)

### Motion Detection

### emulate_motion

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

Always save images even if there was no motion

### pause

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

When Motion is started, pause the motion detection.

### threshold

- Type: Integer
- Range / Valid 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. 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. (Unless of course you are one of the many many users who use Motion to bird watch!) Practical values would be from a few hundred to thousands.

### threshold_maximum

- Type: Integer
- Range / Valid values: 0, 1 to unlimited
- Default: 0 (off)

This parameter specifies the maximum number of pixels that will trigger motion. When the number of changed pixels is above the maximum, it will not trigger an event. The result is that Motion will only trigger events when the number of pixels changes is above the threshold and less than the threshold_maximum. A value of zero disables threshold_maximum.

### threshold_tune

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

Activate the automatic tuning of threshold level. 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.

### noise_level

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

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

Activates the automatic tuning of noise level. This feature makes Motion continuously adjust the noise threshold for distinguishing between noise and motion.

When activating this feature, the noise_level setting is used as a value added to the dynamic noise level rather than the absolute value.

### despeckle_filter

- Type: String
- Range / Valid values: Combinations of E,e,D,d and l
- Default: Not defined

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.

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

### area_detect

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

Detect motion in predefined areas (1 - 9) and when Motion is detected in the area, execute the script. All of motion detection still continue. This option is only to execute the on_area_detect script.

Areas are numbered like

- 1 2 3
- 4 5 6
- 7 8 9

### mask_file

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

The full path and filename for the masking pgm file. If needed, the mask will be resized to match the width and height of the frames being captured. 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 area that you want ignored must be black. The pgm image should be the same size (number of pixels high and wide) as the pictures that are taken by the camera so you can define the correct area to mask. 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. If you are using the rotate or flip_axis options, 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 8-bit format.

To use this feature create an image of exact the same size as the ones you get from your camera. Then make it purely white for the areas you want detected and black for the areas you want ignored. 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 method for generating the mask file is as follows.

Take a motion captured picture, edit it with black and white for the mask and export it as a pgm file. with a program such as gimp. 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. Instead use the mask_privacy option.

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)

### mask_privacy

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

The full path and filename for the privacy masking pgm file. This file works like the mask_file as described above. The difference with this parameter is that while the mask_file excludes the section from detecting motion, this file excludes the section of the image completely.

mask_privacy is applied before detection so no motion will ever be detected in the excluded area. This parameter could however still be used with the mask_file. e.g. This file could exclude the neighbors yard and the mask_file would exclude the blowing tree from motion detection. The resulting pictures/movies would show solid black in place of the neighbors yard but the tree would still be in the pictures/movies.

### smart_mask_speed

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

Speed for 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.

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.

The mask_file option provides a static mask to turn off sensitivity in certain areas. This is very useful 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 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.

### lightswitch_percent

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

Ignore sudden massive light intensity changes when the percentage of the picture area that changed intensity is greater than this value. The value defines the picture area in percent above which the lightswitch condition will trigger. When lightswitch is detected motion detection is disabled for a configured number of frames. This is to avoid false detection when light conditions change and when a camera changes sensitivity at low light.

### lightswitch_frames

- Type: Integer
- Range / Valid values: 1 - 1000
- Default: 5

The number of frames to ignore when the lightswitch condition is triggered (see above).

### minimum_motion_frames

- Type: Integer
- Range / Valid 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. 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. 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.

### event_gap

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

The number of seconds of no motion detected that triggers the end of an event. An event is defined as a series of motion images taken within a short timeframe. An event ends right after no more motion is detected and post_capture is over.

The value -1 is allowed and disables events causing all Motion to be written to one single movie file and no pre_capture. If set to 0, motion is running in gapless mode. Disabling events has bad side effects on noise_tune and smartmask. Both features can only work properly outside an event. When event_gap is set to -1, both features don't work properly anymore.

For example, a person walking through a room starts an event. During the event many single images will be detected as movement. Once the movement has stopped being detected, the post_capture starts. Then once that is finished, the timer starts as specified in event_gap.

If any motion is detected before the timer finishes, the existing event continues and the timer is reset. If no motion is detected during the time, the event ends.

The event_gap value impacts many functions in Motion.

- When the 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 'event_gap' value pre_capture is not working very often.
- When you make movies a new file is started at the beginning of an event when the first motion is detected. When 'event_gap' seconds has passed without motion (and post_captured frames saved) the movie files are completed and closed.
- Do not use large event_gap values to generate one large movie file. If Motion stops working this movie file never gets properly completed and closed 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.

### pre_capture

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

Specifies the number of pre-captured (buffered) pictures from before motion was detected that will be output at motion detection. The recommended range is 0 to 5. It is not recommended to use large values. Large values will cause Motion to skip video frames and cause unsmooth movies.

This is because Motion is processing all the buffered images including saving jpegs, encoding the movie, writing to databases and executing external programs immediately 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 probably miss many frames of Motion.

To create smooth movies 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 movie. 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. 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. 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.

It is therefore recommended to use relatively small values for pre_capture. Depending on your chosen framerate and depending on the features enabled values from 1-5 are sensible.

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

### post_capture

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

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 movies and do not have output_normal on, then the recommended post_capture value is what is equivalent to 1-5 seconds (Don't forget to multiply the seconds desired by the framerate for this parameter)

### Script Execution

Motion can execute external commands based on the motion detection and related events. They are described in the sections below.

Security Warning!

These features mean 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!!

### on_event_start

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

The full path and file name of the program/script to be executed at the start of an event. An event starts at first motion detected after a period of no motion defined by gap.

You can use Conversion Specifiers and spaces as part of the command. 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.

### on_event_end

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

The full path and file name of the program/script to be executed when a event ends. An event ends after the event_gap has expired.

You can use Conversion Specifiers and spaces as part of the command. 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.

### on_picture_save

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

The full path and file name of the program/script to be executed when a picture is saved.

You can use Conversion Specifiers and spaces as part of the command. 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.

Use %f for passing filename (with full path) to the command.

### on_motion_detected

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

The full path and file name of the program/script to be executed when motion is detected.

You can use Conversion Specifiers and spaces as part of the command. 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.

### on_area_detected

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

The full path and file name of the program/script to be executed when motion is detected in the predefined area indicated in the area_detect option.

You can use Conversion Specifiers and spaces as part of the command. 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.

### on_movie_start

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

The full path and file name of the program/script to be executed when a new movie is being created.

You can use Conversion Specifiers and spaces as part of the command. 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.

Use %f for passing filename (with full path) to the command.

### on_movie_end

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

The full path and file name of the program/script to be executed after a new movie was created.

You can use Conversion Specifiers and spaces as part of the command. 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.

Use %f for passing filename (with full path) to the command.

### on_camera_lost

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

The full path and file name of the command to be executed when a camera can't be opened or if it is lost.
Note that there are situations when motion doesn't detect a lost camera. It is dependent upon the camera and driver and it is advised that this option be tested for each configuration. It has also been observed that there are also situations in which the disconnection of the camera even hangs the PC in which case this script will not be executed.

You can use Conversion Specifiers and spaces as part of the command. 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.

### on_camera_found

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

The full path and file name of the command to be executed when a lost camera is found
If motion fails to detect a lost camera, it will also fail to know it found one.

You can use Conversion Specifiers and spaces as part of the command. 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.

### Output - Picture Options

Motion can output different types of pictures. The normal picture is indicated below.

The motion type picture or also referred to as a debug picture is shown below. 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 mathematical calculation of the past images. This enlarges real Motion and ensures that it is not easy to sneak in slowly.

### picture_output

- Type: Discrete Strings
- Range / Valid values: on, off, first, best
- Default: off

This option controls the output of the normal image.

'on' is the usual selection.

'first' is Motion saves only the first motion detected picture per event.

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

'off' to don't write pictures

When the netcam_highres option is selected along with the movie_passthrough the output pictures will be provided in normal resolution not high resolution.

### picture_output_motion

- Type: Boolean
- Range / Valid 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.

If a Smartmask is specified, it is shown in red.

This option is good for tuning and testing but probably not very interesting for the general public.

Default is not to store these 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.

### picture_type

- Type: Discrete Strings
- Range / Valid values: jpeg, webp, ppm, grey
- Default: jpeg

This option specifies the type of picture file to output. The recommendation is to always use jpeg except if you have a specific need to store high quality pictures without any quality loss.

### picture_quality

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

The quality for the jpeg or webp images in percent. 100 means hardly compressed. A small number means a much smaller file size but also a poorer quality image to look at.

### picture_exif

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

Use this option to specify the text to include in a JPEG EXIF comment The EXIF timestamp is included independent of this text.

You can use Conversion Specifiers in this option.

### picture_filename

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

This option indicates the file name and optionally the path for the pictures relative to target_dir.

The file extension .jpg, webp or .ppm is automatically added.

You can use Conversion Specifiers in this option.

### snapshot_interval

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

This parameter specifies the number of seconds between each snapshot

### snapshot_filename

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

This option indicates the file name and optionally the path for the snapshots relative to target_dir.

The file extension .jpg, webp or .ppm is automatically added.

A symbolic link called lastsnap.jpg is created in the target_dir and will always point to the latest snapshot, unless snapshot_filename is exactly 'lastsnap'

You can use Conversion Specifiers in this option.

### Output - Movie Options

### movie_output

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

Use ffmpeg libraries to encode movies of the motion. This option generates a new movie at the beginning of each new event and appends to the movie for each motion detected within the same event. The current event ends when the time defined by the 'event_gap' option has passed with no motion detected. At the next detection of motion a new movie is started.

### movie_output_motion

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

Use ffmpeg libraries to encode motion type movies where you only see the pixels that changes. Works like movie_output 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 labeling is enabled you see the largest area in blue. Smartmask is shown in red. The filename given is the same as the normal movies except they have an 'm' appended after the filename.

### movie_max_time

- Type: Integer
- Range / Valid values: 0 (infinite) - 2147483647
- Default: 120

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

### movie_bps

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

Bitrate of movies produced by ffmpeg. Bitrate is bits per second. A higher value means better quality and larger files if the camera is on a fixed bitrate setting. Experiment to get the desired quality. The better quality the bigger files. This option is ignored if movie_quality is not 0 (disabled).

### movie_quality

- Type: Integer
- Range / Valid values: 0 - 100
- Default: 60

Enables and defines a variable bitrate for the ffmpeg encoder. The option of movie_bps is ignored if variable bitrate is enabled. A value of 0 disables this option while values 1 - 100 varies the quality of the movie. The value of 1 means worst quality and 100 is the best quality.

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

### movie_codec

- Type: Discrete Strings
- Range / Valid values: mpeg4, msmpeg4, swf, flv, ffv1, mov, mp4, mkv, hevc
- Default: mkv

Container/Codec to be used for the video.

- mpeg4 or msmpeg4 - gives you files with extension .avi
- 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
- mov - QuickTime
- mp4 - MPEG-4 Part 14 H264 encoding
- mkv - Matroska container with H264 encoding
- hevc -MP4 container with H.265 / HEVC (High Efficiency Video Coding)

Note that certain containers can handle different codecs than the defaults indicated above. For example, the mkv container can handle virtually any codec. Motion can optionally take an additional specification with this parameter. By specifying the container (mkv) and then appending a colon and the ffmpeg codec name Motion will attempt to use the specified codec for the container. This permits options such as encoding the h265 codec into a mkv container instead of mp4 by specifying the option as `mkv:libx265`

### movie_duplicate_frames

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

When specified, if the CPU can not keep up with the requested frame rate for the movies, frames will be duplicated in order to keep up with the frame rate.

Users should never use this option since the resulting movies will have the same frame sent multiple times and therefore the movie will appear to "stall" and look terrible.

### movie_passthrough

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

When using a RTSP, RTMP, HTTP and some V4l2 cameras, create movie files of the motion with the packets obtained directly from the camera.

For v4l2 cameras to use the movie_passthrough, they must be specified using the netcam_url parameter and the `v4l2` prefix. Only webcams that provide mjpeg or H264 will work with the movie_passthrough.

When using only the single netcam_url this option will reduce the processing required when encoding the images to the resulting movie file. Decoding of the image will still occur on the image in order to process the motion detection.

When using both the netcam_url and the netcam_highres what will occur is that normal resolution stream will be captured and decoded, when motion is detected, the high resolution images will be captured and processed into the movie file without going through the decode/encode processing.

This option should reduce CPU usage but does increase memory requirements.

No image processing is performed so text overlays, privacy masks etc will not be on the resulting video. The resulting movie may also include a few extra frames at the start that would not exist if the movie was created without the passthrough option.

Since this option bypasses the decoding of the high resolution images to reduce CPU, when images are saved via the picture_output option, the pictures provided will be from the normal resolution stream.

### movie_filename

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

File path for motion triggered movies relative to target_dir. Note that the file extension is automatically added to the name based upon the codec selected.

You can use Conversion Specifiers in this option.

### movie_extpipe_use

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

This option specifies whether to send the output to a pipe for external encoding into a movie.

Piping raw video to stdout has some advantages comparing to using built-in ffmpeg encoder.
First, you can use any encoder that supports RAW frames from stdin so you are not limited to the formats that are currently implemented in motion. See examples in movie_extpipe
Second, external encoders utilize separate cpu core(s) on multi-core systems so movie encoding is offloaded from main motion thread to separate core(s) giving noticeable performance boost

Note that this option does not require the install or configure of the videoloopback software.

### movie_extpipe

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

This option specifies the program name and options for the program that will receive and process the images during a movie event.

Note that this option does not require the install or configure of the videoloopback software.

Sample:

`movie_extpipe mencoder -demuxer rawvideo -rawvideo w=%w:h=%h:i420 -ovc x264 -x264encopts bframes=4:frameref=1:subq=1:scenecut=-1:nob_adapt:threads=1:keyint=1000:8x8dct:vbv_bufsize=4000:crf=24:partitions=i8x8,i4x4:vbv_maxrate=800:no-chroma-me -vf denoise3d=16:12:48:4,pp=lb -of avi -o %f.avi - -fps %fps`

`movie_extpipe x264 - --input-res %wx%h --fps %fps --bitrate 2000 --preset ultrafast --quiet -o %f.mp4`

`movie_extpipe mencoder -demuxer rawvideo -rawvideo w=%w:h=%h:fps=%fps -ovc x264 -x264encopts preset=ultrafast -of lavf -o %f.mp4 - -fps %fps`

`movie_extpipe ffmpeg -y -f rawvideo -pix_fmt yuv420p -video_size %wx%h -framerate %fps -i pipe:0 -vcodec libx264 -preset ultrafast -f mp4 %f.mp4`

### timelapse_interval

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

Create a timelapse video saving a picture frame at the interval in seconds set by this parameter.

### timelapse_mode

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

The file rollover mode of the timelapse video. Note that it is important that you use the Conversion Specifiers in timelapse_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 timelapse_interval to 0 and then back to your chosen value.

The 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.

### timelapse_fps

- Type: Integer
- Range / Valid values: 0 - 100's
- Default: 30

The frame per second rate to use in the playback of the timelapse video.

### timelapse_codec

- Type: Discrete Strings
- Range / Valid values: mpg, mpeg4
- Default: mpg

Container/Codec to be used by timelapse video.

- mpg - Creates mpg file with mpeg-2 encoding. If Motion is shutdown and restarted, new pics will be appended to any previously created file with name indicated for timelapse.
- mpeg4 - Creates avi file with the default encoding. If Motion is shutdown and restarted, new pics will create a new file with the name indicated for timelapse.

Note that different containers are NOT planned for this option since the nature of recording a timelapse is not what typical movies containers and codecs are designed to do. Users desiring a different container/codec can use ffmpeg directly to either re-encode a finished timelapse video or output the timelapse as jpg picture files and use ffmpeg to encode those jpgs into a movie.

### timelapse_filename

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

File path for the timelapse videos relative to target_dir. Note that the file extension is automatically added to the name based upon the codec selected.

You can use Conversion Specifiers in this option.

### Output - Pipe Options

Motion provides two pipe variations. The first option is a v4l2loopback device with normal images. Using this pipe option, the video that is captured from the v4l2 device is piped into a new v4l2 device using the v4l2loopback software. This piping is desired when the user wishes to use the video device at the same time as Motion is using the same device. By default, only one application can have a device open at one time. Unlike a physical device, the videoloopback devices take both input and output. The module simply takes anything that comes on its input and send it out at the output.

When you install the video loopback device it will create a new device for example /dev/video1 while the actual webcam device would be /dev/video0. You can then tell motion to open the physical device (/dev/video0) and "pipe" the video signal to the /dev/video1. You will then be able to open the /dev/video1 device with external videoplayers such as VLC and and look at the pictures live. VLC is "fooled" to think it is looking at a real camera.

Installing

The video loopback device can be added installed via apt in many distributions. The package tested with Motion is v4l2loopback-dkms. Once the package is installed, you just need to run `sudo modprobe v4l2loopback`. This will add a new video device that you can use for the loopback. It is believed that there are additional options associated with the v4l2loopback that allows for adding more than one device. See the documentation of the v4l2loopback project for additional details.

To activate the vloopback device in Motion set the 'video_pipe' option in the motion.conf file to the device name associated with the one created by v4l2loopback.
You can also view the special motion pictures where you see the changed pixels by setting the option 'video_pipe_motion' in motion.conf. When setting the video_pipe and/or video_pipe_motion options specify the input device as e.g. /dev/video1.

De-activating should be done with this command

`sudo modprobe -r v4l2loopback`

The second option for pipe is the same as the above except motion images are sent to the loopback device.

### video_pipe

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

The video4linux video loopback device for normal images. The device would be specified in the format like /dev/video1

### video_pipe_motion

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

The video4linux video loopback device for motion images. The device would be specified in the format like /dev/video1

### Web Control

Motion has a limited web interface to control some parameters while running. By default, the changing of any parameters via the web interface is disabled via the webcontrol_parms configuration option. This is for security purposes. If the webcontrol_parms is enabled, some Motion configuration options can be changed while Motion is running. Other configuration options must be saved and Motion restarted to become effective.

If your webcontrol_port is 8080, then open the following from the same machine on which Motion is running http://localhost:8080/

To access the web control from remote machine, first set the webcontrol_localhost to `off` then connect using the IP of the remote machine instead of `localhost` (example http://192.168.1.4:8080/).

If you want to use a script or cron to automatically change Motion settings while Motion runs, use a program that can fetch or send a webpage. Common programs are `wget` , `lwp-request` and `curl`.

Example to pause motion detection

`lwp-request http://localhost:8080/0/detection/pause`

Example to start motion detection

`lwp-request http://localhost:8080/0/detection/start`

Example script to update the text_left with cpu load (verbose for clarity)

`#!/bin/bash
LOAD=`top -b -n2 | grep "Cpu(s)" | awk '{print $2+$4}' | tail -n1`
TEXTLEFT=""
TEXTLEFT=$TEXTLEFT"System at %{host}"
TEXTLEFT=$TEXTLEFT"\nCPU $LOAD "
TEXTLEFT=$TEXTLEFT"\nfps: %{fps}"
TEXTLEFT=$TEXTLEFT"\nDate: %Y-%m-%d"
TEXTLEFT=$TEXTLEFT"\n%T-%q"
# Replace special chars with needed urlcodes
TEXTLEFT="${TEXTLEFT//%/%25}" #Replace % with %25
TEXTLEFT="${TEXTLEFT// /%20}" #Replace spaces with %20
TEXTLEFT="${TEXTLEFT//\{/%7B}" #Replace { with %7B
TEXTLEFT="${TEXTLEFT//\}/%7D}" #Replace } with %7D
curl http://localhost:8080/1/config/set?text_left=$TEXTLEFT
return 0
` Note that the replacement of characters with the urlcode values is required whenever updating via a script or outside the html/css webcontrol_interface

To control from your own software (for example your own PHP front end) the motion.conf option webcontrol_interface can be set to `1`(text) which will cause Motion to remove the html tags in the responses and there is no navigation of any pages via a web browser.

The following definitions will be used when summarizing the commands that are available for control of Motion.

- `{IP}` The IP address of the computer running Motion
- `{port}` The port specified for the webcontrol
- `{camid}` The camera_id of the camera.
- `{parm}` The Motion configuration parameter requested.
- `{value1}` The first value of the Motion configuration parameter requested.
- `{value2}` The second value of the Motion configuration parameter requested.

The following are the commands available.

- `{IP}:{port}/{camid}/config/list` Lists all the configuration values for the camera.
- `{IP}:{port}/{camid}/config/set?{parm}={value1}`Set the value for the requested parameter
- `{IP}:{port}/{camid}/config/get?query={parm}` Return the value currently set for the parameter.
- `{IP}:{port}/{camid}/config/write` Write the current parameters to the file.
- `{IP}:{port}/{camid}/detection/status` Return the current status of the camera.
- `{IP}:{port}/{camid}/detection/connection` Return the connection status of the camera.
- `{IP}:{port}/{camid}/detection/start` Start or resume motion detection.
- `{IP}:{port}/{camid}/detection/pause` Pause the motion detection.
- `{IP}:{port}/{camid}/action/eventstart` Trigger a new event.
- `{IP}:{port}/{camid}/action/eventend` Trigger the end of a event.
- `{IP}:{port}/{camid}/action/snapshot` Create a snapshot
- `{IP}:{port}/{camid}/action/restart` Shutdown and restart Motion
- `{IP}:{port}/{camid}/action/quit` Close all connections to the camera
- `{IP}:{port}/{camid}/action/end` Entirely shutdown the Motion application
- `{IP}:{port}/{camid}/track/center` Send command to center PTZ camera
- `{IP}:{port}/{camid}/track/set?x={value1}&y={value2}` Send command to PTZ camera to move to location specified by x and y
- `{IP}:{port}/{camid}/track/set?pan={value1}&tilt={value2}` Send command to PTZ camera to pan to value1 and tilt to value2

As a general rule, when the {camid} references the camera_id in the main motion.conf file, the webcontrol actions referenced above are going to be applied to every camera that is connected to Motion. This camera_id is usually specified as 0 (zero). So issuing a command of `{IP}:{port}/0/detection/pause` is going to pause all the cameras.

A point of clarification with respect to the differences between `pause`, `quit`, and `end`. When the action of `pause` is executed, Motion will stop the motion detection processing and of course all events but will continue to process and decode images from the camera. This allows for a faster transition when the user executes a `start` The `quit` action conversely not only stops the motion detection but also disconnects from the camera and decoding of images. To start motion detection after a `quit`, the user must execute a `restart` which will reinitialize the connection to the camera. And since the camera was completely disconnect, it can take more than a few seconds for Motion to fully start and have the camera available for processing or viewing. Finally, there is an option for `end`. This option completely terminates the Motion application. It closes all connections to all the cameras and terminates the application. This may be required when running Motion in daemon mode. Note that there is no way to restart the Motion application from the webcontrol interface after processing a `end` request.

If the item above is available via the HTML/CSS interface, it is also possible to see the exact URL sent to Motion in the log. Change the log level to 8 (debug), then open up the Motion webcontrol interface and perform the action in question. In the log Motion will report the exact URL sent to Motion that performed the action.

ALERT! Security Warning! 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 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. Also make sure to adjust the webcontrol_parms to the lowest level possible.
- 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.
- Run Motion as a harmless user. DO NOT RUN AS ROOT!!

### webcontrol_port

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

Sets the port number for the http based control of the Motion parameters. This option must be placed in the motion.conf file and not in a camera config file. Port numbers below 1024 normally require that you have root privileges. The port 8080 is the typical selection of the port for this purpose.

### webcontrol_ipv6

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

Listen for connections from IPv6 and IPV4.

### webcontrol_localhost

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

This option restricts the control of the Motion parameters to the localhost. This option must be placed in motion.conf and not in a camera 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.

### webcontrol_parms

- Type: Integer
- Range / Valid values: 0 - 3
- Default: 0

Sets the type of parameters that will be listed on the webcontrol page and available for modification.

- 0: None - No configuration parameters will be available.
- 1: Limited- A limited list of parameters will be available.
- 2: Advanced - The advanced list of parameters will be available. These typically require Motion to be restarted to become effective.
- 3: Restricted - User IDs, passwords and "on_" commands.

The default for this parameter is 0 (none) to enhance the security of the web interface. The setting of the webcontrol_parms is NEVER included on the web interface and this parameter must be specified via the configuration file. EXTREME Care should be exercised when using level restricted level because if the webcontrol is compromised, it may compromise the computer.

Users are strongly advised to only set this option to something other than zero when initially setting up the cameras. Once Motion has been configured, it is advised to complete the set up by setting this value back to zero!

### webcontrol_interface

- Type: Integer
- Range / Valid values: 0 - 2
- Default: 0

The type of webcontrol interface to provide.

- The value of 0 provides a traditional web page interface using html/css.
- The value of 1 provides a text only interface suitable for programmatic access.
- The value of 2 provides the legacy web control interface

This option must be placed in motion.conf and not in a camera config file. The recommended value for most is "0" which provides a page you can navigate and control Motion with a normal browser.

### webcontrol_auth_method

- Type: Integer
- Range / Valid values:0, 1, 2
- Default: 0

Authentication method to use for the webcontrol port

- 0 = disabled
- 1 = Basic authentication
- 2 = Digest authentication

### webcontrol_authentication

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

This parameter establishes the username and password to use for the stream. The syntax is username:password

### webcontrol_tls

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

This option specifies whether to enable SSL/TLS for the webcontrol port. For some distributions the library that Motion uses may not have been compiled with SSL/TLS support. In this situation Motion can not support SSL/TLS connections. Whether SSL/TLS can be supported will be reported in the log. In addition to selecting this option, a webcontrol_cert and webcontrol_key file must also be specified.

### webcontrol_cert

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

Full path to the certification file for SSL/TLS support. Only used when webcontrol_tls is enabled.

### webcontrol_key

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

Full path to the key file for SSL/TLS support. Only used when webcontrol_tls is enabled.

### webcontrol_header_params

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

User specified header(s) for the webcontrol. The header/value pair is separated by an equal sign and multiple header/value pairs are separated by commas. If the header or value includes an equal sign or comma, then the header or value must be enclosed in double quotes. e.g.

`webcontrol_header_params Access-Control-Allow-Origin=*, Cache-Control="no-cache"`

When Motion parses this parameter, it only shows the values in the Motion log when webcontrol_localhost is set to on. When the webcontrol_localhost is set to off, Motion will redact the values in the log.

### webcontrol_lock_attempts

- Type: String
- Range / Valid values: Integers
- Default: 5

This parameter applies to the webcontrol port and all stream ports.

The maximum number of failed authentication attempts to the web control or streams before the client IP is locked out for the duration specified by webcontrol_lock_minutes.

### webcontrol_lock_minutes

- Type: String
- Range / Valid values: Integers
- Default: 5

This parameter applies to the webcontrol port and all stream ports.

The number of minutes that a IP is locked out when the number of failed authentication attempts has been reached. Note that when the user attempts to connect the during the lock out period, the timer is reset to zero. So if the user set the time at 5 minutes and attempted to log in after 4 minutes, they would have to wait a total of 9 minutes before Motion would start to prompt for a password again. The attempt to open the web site at minute 4 resets the clock even though Motion does not even respond with a prompt.

### webcontrol_lock_max_ips

- Type: String
- Range / Valid values: Integers
- Default: 25

This parameter applies to the webcontrol port and all stream ports.

Motion can only keep track of a limited amount of IPs that are attempting to log in but failing. This parameter specifies the maximum number of IPs that can be blocked at the same time. Motion will clear the log of IPs that have been locked out but the webcontrol_lock_minutes has expired so this parameter represents the maximum concurrent IPs locked out. Note that when this maximum is reached, Motion will deny all connections until one of the time of one of the lockouts expires.

While it is permitted to have a high value for this, it should be noted that it could impact the loading time for the webcontrol and streams. Motion loops through the entire array looking for the connecting IP to determine whether to block it on each and every connection.

### Live Stream

Motion has simple webcam server built in which allows for streaming the images from the camera(s).

The streams are generated in "multipart jpeg" format (mjpeg) which most browsers can display. If the browser does not directly open the stream, it may be possible to manually create a simple HTML page that references the stream.

Some regular stream players such as mplayer, ffplay and avplay may open the streams as well by specifying the network stream as `http://localhost:mystreamportnumber/`

While normally the stream players will open after a bit, it may be useful to also provide the format such as `ffplay -f mjpeg http://localhost:mystreamportnumber/`

It has been observed by the author that VLC will not open the stream. This is not a Motion limitation but instead is related to the general VLC support for MJPG http streams.

While the above examples indicate the Motion streams can be accessed as `http://localhost:mystreamportnumber/` Motion does provide other options for accessing the streams and images. In addition to sub-streams, motion image streams and static images, Motion can also be configured to use just a single port for accessing streams to all cameras. This is accomplished by specifying a stream port within the motion.conf file and also using separate camera files. The following examples should clarify the methods by which streams can be accessed:

- `{IP}` The IP address of the computer running Motion
- `{port0}` The port specified for the stream within the motion.conf file.
- `{portX}` The port specified for the stream within a camera.conf file.
- `{camid}` The camera_id of the camera.

- `{IP}:{port0}/cameras.json` JSON object with IDs and names of all cameras
- `{IP}:{port0}/status.json` JSON object with information about all cameras
- `{IP}:{port0}/{camid}/` Primary stream for the camera
- `{IP}:{port0}/{camid}/stream` Primary stream for the camera
- `{IP}:{port0}/{camid}/substream` Sub-stream for the camera
- `{IP}:{port0}/{camid}/motion` Motion image stream for the camera
- `{IP}:{port0}/{camid}/source` Source image from the camera
- `{IP}:{port0}/{camid}/current` Static JPG for the camera
- `{IP}:{port0}/{camid}/status.json` JSON object with information about the camera
- `{IP}:{portX}/` Primary stream for the camera running on port {portX}
- `{IP}:{portX}/stream` Primary stream for the camera running on port {portX}
- `{IP}:{portX}/substream` Sub-stream for the camera running on port {portX}
- `{IP}:{portX}/motion` Motion image stream for the camera running on port {portX}
- `{IP}:{portX}/source` Source image from the camera running on port {portX}
- `{IP}:{portX}/current` Static JPG for the camera running on port {portX}
- `{IP}:{portX}/status.json` JSON object with information about the camera running on port {portX}

### stream_port

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

The TCP port that Motion will send the main stream. The stream port must be different than the webcontrol_port. If the port is specified within the motion.conf file (as opposed to being specified in the camerax.conf files), then Motion will provide all streams on that single port by specifying a different url. See the stream section above for further details and examples of how ports can be specified. If setting a unique port for each camera good value may be to select is 8081 for camera 1, 8082 for camera 2, 8083 for camera 3 etc.

### stream_localhost

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

Limits the access to the stream to the localhost. By setting this to on, the stream can only be accessed on the same machine on which Motion is running.

### stream_auth_method

- Type: Integer
- Range / Valid values: 0, 1, 2
- Default: 0

This parameter establishes desired authentication method for the stream port. The parameters have the following meaning.

- 0 = disabled
- 1 = Basic authentication
- 2 = MD5 digest (the safer authentication)

Note that if you are enabling the webcontrol feature of Motion, you really really really ... should enable security authentications. No. Seriously. You really should. See the security warnings in this document regarding how it completely opens up your system.

### stream_authentication

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

This parameter establishes the username and password to use for the stream. The syntax is username:password

### stream_tls

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

This option specifies whether to enable SSL/TLS for the stream port. For some distributions the library that Motion uses may not have been compiled with SSL/TLS support. In this situation Motion can not support SSL/TLS connections. Whether SSL/TLS can be supported will be reported in the log. In addition to selecting this option, a webcontrol_cert and webcontrol_key file must also be specified.

### stream_header_params

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

User specified header(s) for the stream. The header/value pair is separated by an equal sign and multiple header/value pairs are separated by commas. If the header or value includes an equal sign or comma, then the header or value must be enclosed in double quotes. e.g.

`stream_header_params Access-Control-Allow-Origin=*, Cache-Control="no-cache"`

When Motion parses this parameter, it only shows the values in the Motion log when stream_localhost is set to on. When the stream_localhost is set to off, Motion will redact the values in the log.

### stream_preview_scale

- Type: Integer
- Range / Valid values: 1 to 100s
- Default: 25

If the webcontrol page has HTML enabled, Motion displays all of the streams on the home webcontrol page in HTML format so that all the images can be viewed by standard browsers.

This parameter indicates the percentage to scale the stream image when it is placed on the page. Note that this is scaled on the browser side, Motion will keep sending full frame.

Numbers greater than 100 are permitted.

### stream_preview_newline

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

If the webcontrol page has HTML enabled, Motion displays all images of the streams on the home webcontrol page in HTML format so that all the images can be viewed by standard browsers.

This parameter determines whether the image is placed on a new line in the webcontrol web page.

Preview images are placed on to the webcontrol home page in camera id number order. This parameter allows the user some flexibility in organizing the images on the page.

Setting this parameter to off will set the image to the right of any image from a lower numbered thread number. Setting it to 'on' will place the image on the start of the next line(below).

Users that require a more polished and customized preview page are encouraged to create their own local HTML page that reference the URL streams.

### stream_preview_method

- Type: Integer
- Range / Valid values: 0 - 4
- Default: 0

This option determines the method used for displaying images on the webcontrol page.

- 0 = Full stream images are sent and scaled by the client to the webcontrol page
- 1 = Substream images are sent by Motion. This saves bandwidth
- 2 = Static images are sent by Motion and the page must be manually refreshed
- 3 = Full stream images and motion images side by side to assist setup of detection
- 4 = The source image provided by camera without privacy or other Motion overlays

### stream_quality

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

Quality setting in percent for the jpeg picture frames transferred over the live stream connection. When it is set to a low number, it will lower the bandwidth required to stream the images.

### stream_grey

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

Send the live stream in grey (black and white) rather than color. Useful for limiting bandwidth.

### stream_maxrate

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

Limit the framerate of the stream in frames per second. Set the value to 100 for practically unlimited. Don't set this parameter too high unless you only use it on the localhost or on an internal LAN.

### stream_motion

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

Limit the framerate to 1 frame per second when there is no motion being detected and increase it to the stream_maxrate when there is motion.

### Database

Motion can record many details of its images, movies, and events in a database. Support for one or more of the Database Management Systems (DBMS) MySQL, MariaDB, PostgreSQL, and SQLite3 may be incorporated when Motion is built from source. Many Linux distributions provide packages to selectively incorporate most or all of Motion's DBMS support. Configuration option database_type specifies which DBMS, if any, is used in a given Motion run.

When a Motion installation includes DBMS support, SQL statements to insert or update database records may be specified using Motion's database configuration options sql_query, sql_query_start, and sql_query_stop. These SQL statements may record dynamic image, movie, and event data in database tables using Conversion Specifiers for data elements like filename, time, number of changed pixels detected etc. Motion does not record images or movies themselves in a database.

Motion can insert or update database records when it creates image or movie files, when it recognizes the beginning of a motion event, and when it closes movie files at the end of a motion event. sql_query and sql_query_stop are executed only for the image and movie file types enabled by their respective sql_log_* configuration options. The sql_log_* options do not impact sql_query_start, which, if specified, is always executed at event start.

Configuration option sql_query_start allows motion-detected events to be assigned unique event IDs and recorded in the database independently from Motion's recording of images and movies. When this SQL statement and the related database table schema are so configured, the database assigns an event ID that is globally unique within its table and returns the ID to the motion thread that recorded the event. The conversion specifier %{dbeventid} may then be included in subsequently executed sql_query and sql_query_stop statements to insert that event ID into database records created for associated files or to control updates of event-related records. For example, sql_query_stop may specify a SQL UPDATE statement that inserts event end time into a recently-started event's record. (Note that Motion's "event" data item, conversion specifier %v, is unique only within a given camera and Motion run).

Motion does not provide for deletion of the database records it creates nor for the images and movies they catalog. Other user-provided scripts or software may analyze, search, display, and purge database records and related images and movies.

Example SQL statements defining a database table to record Motion file details:

MySQL; MariaDB : `CREATE TABLE security (camera INTEGER NOT NULL, filename VARCHAR(255) NOT NULL, file_type INTEGER NOT NULL, time_stamp DATETIME NOT NULL, frame INTEGER, motion_event INTEGER, movie_end DATETIME);`

Postgresql : `CREATE TABLE security (camera INTEGER NOT NULL, filename VARCHAR NOT NULL, file_type INTEGER NOT NULL, time_stamp TIMESTAMP NOT NULL, frame INTEGER, motion_event INTEGER, movie_end TIMESTAMP);`

Sample SQL defining a table for Motion-recognized events, each with a unique `%{dbeventid}` ID:

MySQL; MariaDB : `CREATE TABLE event (event_id INTEGER PRIMARY KEY AUTO_INCREMENT, camera INTEGER NOT NULL, event_start DATETIME NOT NULL, event_stop DATETIME, motion_event INTEGER NOT NULL, event_text VARCHAR(255));`

SQLite3 : `CREATE TABLE event (event_id INTEGER PRIMARY KEY AUTOINCREMENT, camera INTEGER NOT NULL, event_start REAL NOT NULL, event_stop REAL, motion_event INTEGER NOT NULL, event_text TEXT);` (SQLite3 has no native timestamp data type; REAL supports timestamps down to microsecond precision.)

PostgreSQL : `CREATE TABLE event (event_id SERIAL PRIMARY KEY, camera INTEGER NOT NULL, event_start TIMESTAMP NOT NULL, event_stop TIMESTAMP, motion_event INTEGER NOT NULL, motion_pixels INTEGER, motion_x INTEGER, motion_y INTEGER, event_text VARCHAR);`
sql_query_start `INSERT INTO event values (DEFAULT, %t, '%Y-%m-%d %T', NULL, %v, %D, %K, %L, %C) RETURNING event_id`
sql_query_stop `UPDATE event SET event_stop='%Y-%m-%d %T' WHERE %n=8 AND event_id=%{dbeventid} AND event_stop IS NULL` (assumes movie_output and sql_log_movie are enabled)

### database_type

- Type: String
- Range / Valid values: `mysql`, `mariadb`, `postgresql`, `sqlite3`
- Default: Not defined

This option specifies the database type.

### database_dbname

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

Name of a database (SQLite3: full path to the database file) containing preexisting table(s) created with schema(s) consistent with any SQL statements specified by sql_query* configuration options.

### database_host

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

The host on which the database is located. Hostname, domain name, or IP address. Optionally for PostgreSQL, full path of the local directory containing its Unix domain pipe; e.g., `/var/run/postgresql`. Ignored for SQLite3.

### database_port

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

The port number that is used for the database. Ignored for SQLite3. Typical values are: mysql=3306 and postgresql=5432

### database_user

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

The user account name for database. Ignored for SQLite3.

### database_password

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

The user password for database. Ignored for SQLite3.

### database_busy_timeout

- Type: Integer
- Range / Valid values: 0 or more, millisec.
- Default: 0, immediate timeout

SQLite3 only. If a required SQLite3 table is locked when a Motion thread issues a SQL statement, the maximum time it may block the camera's Motion thread before that SQL statement is abandoned.

### sql_log_picture

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

Log to the database when Motion triggers an image file to be saved.

### sql_log_snapshot

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

Log to the database when creating a snapshot image file.

### sql_log_movie

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

Log to the database when creating a motion triggered movie file.

### sql_log_timelapse

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

Log to the database when creating a timelapse movie file

### sql_query

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

SQL statement (typically INSERT) to a database table when a sql_log_* image file is recorded or movie file recording begins.

You can use Conversion Specifiers within the query.

Sample Queries (depend upon the table provided):

`INSERT INTO security(camera, filename, frame, file_type, time_stamp, text_event) VALUES(%t, '%f', %q, %n, '%Y-%m-%d %T', '%C')`
`INSERT IGNORE INTO security(camera, file_name, year, month, day, hour, minute) VALUES (8, '%f', %Y, %m,%d, %H, %M)`
`INSERT INTO security(camera, event_id, filename, frame, file_type, time_stamp) VALUES(%t, %{dbeventid}, '%f', %q, %n, '%Y-%m-%d %T')`

### sql_query_start

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

SQL statement (typically INSERT) executed when a motion event is recognized. This can be used, for example, to record event start times and generate unique event IDs.

You can use Conversion Specifiers in this statement.

Upon successful INSERTion of a record into a database table whose schema generates a positive integer ID for each new record, the returned `mysql_insert_id()`, `sqlite3_last_insert_rowid()`, or PostgreSQL `INSERT ... RETURNING` value is saved until the next `sql_query_start` is executed for the same camera. `%{dbeventid}` can then be used as a value in `sql_query` or `sql_query_stop` statements. To obtain `%{dbeventid}` for PostgreSQL, an INSERT statement must include a `RETURNING` clause that yields a single positive integer value. Absent a valid ID value returned by the database, `%{dbeventid}` yields zero.

Sample Queries (presuming the schema of table `event` defines a column that generates unique IDs):

MySQL; MariaDB; SQLite3: `INSERT INTO event(camera, event_start) VALUES(%t, '%Y-%m-%d %T')`

PostgreSQL: `INSERT INTO event(camera, event_start) VALUES(%t, '%Y-%m-%d %T') RETURNING event_id`

### sql_query_stop

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

SQL statement (typically INSERT or UPDATE) executed when Motion stops recording a motion-triggered or timelapse movie. For example, this can update an events table with an event end timestamp, provided that movie_output and sql_log_movie are enabled.

You can use Conversion Specifiers in this statement. File type (conversion specifier `%n`) allows distinction between motion movie end and timelapse movie end.

Sample Queries:

`UPDATE security SET movie_end='%Y-%m-%d %T' WHERE filename='%f'`
`UPDATE event SET event_stop='%Y-%m-%d %T' WHERE %n=8 AND event_id=%{dbeventid} AND event_stop IS NULL`

### Tracking

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. Review and revise the Motion code regarding tracking if these features are required. The Motion developers do not have any tracking cameras so it is unlikely that tracking features will be developed in any way. (We have no way to test anything!)

### track_type

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

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. This option executes the track_generic_move script. Users can write their own script to move the camera based upon the Conversion Specifiers passed to the script and/or based upon the environment variables set by Motion.

Value 5 is for uvcvideo type USB tracking cameras such as the Logitech Quickcam Sphere/Orbit MP which is driven by the uvcvideo driver.

### track_auto

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

Enable auto tracking of the motion. Requires a tracking camera or custom script as specified in the track_type above.

### track_port

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

This is the device name of the serial port to which the stepper motor interface is connected. Only used for stepper motor tracking.

### track_motorx

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

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

### track_motorx_reverse

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

Description

### track_motory

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

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

### track_motory_reverse

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

### track_maxx

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

The maximum position for servo x. Only used for stepper motor tracking.

### track_minx

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

### track_maxy

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

The maximum position for servo y. Only used for stepper motor tracking.

### track_miny

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

### track_homex

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

### track_homey

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

### track_iomojo_id

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

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_step_angle_x

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

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 - 2147483647
- Default: 0

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_move_wait

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

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_speed

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

Speed to set the motor to. Only used for stepper motor tracking.

### track_stepsize

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

Number of steps to make. Only used for stepper motor tracking.

### track_generic_move

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

The full path and file name of the command to execute to move a PTZ camera in generic tracking mode

Users have the option of using the Conversion Specifiers and including the parameters as part of command line options to the script and/or to obtain the values from system environment variables as indicated below.

The following are the parameters provided as environment variables:

- When called to recenter the camera: TRACK_ACTION=center TRACK_XOFF TRACK_YOFF
- When called to track a motion: TRACK_ACTION=move TRACK_CENT_X TRACK_CENT_Y TRACK_CENT_WIDTH TRACK_CENT_HEIGHT TRACK_CENT_MINX TRACK_CENT_MAXX TRACK_CENT_MINY TRACK_CENT_MAXY TRACK_IMGS_WIDTH TRACK_IMGS_HEIGHT TRACK_IMGS_MOTIONSIZE

The following is a sample script that moves a PTZ netcam based upon the system environment variables. The 3/8 and 5/8 are illustrative only and set based upon testing with a VIVOTEK PZ81X1 camera. The values and methods applicable to any other camera would need to be established by the user.

`#!/bin/bash
LOCKFILE=/tmp/track_generic_move_netcam.lock
if [ -e "$LOCKFILE" ]; then # Trick to avoid flooding
exit 0 # the netcam of multiple
fi # moving commands.
function movecam() {
touch $LOCKFILE
curl "http://youripaddress/cgi-bin/camctrl/camctrl.cgi?move=$1"
LOCKED=true
}
case "$TRACK_ACTION" in
"center")
movecam home
;;
"move")
if [ "$TRACK_CENT_X" -lt "$((TRACK_IMGS_WIDTH*3/8))" ]; then
movecam left
fi
if [ "$TRACK_CENT_X" -gt "$((TRACK_IMGS_WIDTH*5/8))" ]; then
movecam right
fi
if [ "$TRACK_CENT_Y" -lt "$((TRACK_IMGS_HEIGHT*3/8))" ]; then
movecam up
fi
if [ "$TRACK_CENT_Y" -gt "$((TRACK_IMGS_HEIGHT*5/8))" ]; then
movecam down
fi
;;
esac
if [ "$LOCKED" = "true" ]; then
sleep 2
rm -f "$LOCKFILE"
fi
`