My cheap IP camera gives an RTSP stream and not much else. Three ffmpeg jobs cover what I need from it: a still image every minute, continuous recording, and short clips cut out of the recordings. They share the same input options, so they are on one page.
The input part
Every command below starts like this:
ffmpeg -hide_banner -loglevel error \
-rtsp_transport tcp \
-i "rtsp://user:pass@192.168.1.50:554/stream1" ...
-rtsp_transport tcp is the important flag. Over Wi-Fi, RTSP over UDP loses packets, and lost packets give
grey or broken frames. The stream path (/stream1 here) is different for each camera brand, so check the
manual or the camera’s own app. Many cameras also have a low-resolution sub-stream. I record the main stream
and use the sub-stream for live view.
The URL contains the camera password, so every script and unit file with it is readable only by its user.
A still image every minute
The camera has no usable snapshot URL. I want one JPEG per minute, for a timelapse and to see that the camera is still alive:
ffmpeg -hide_banner -loglevel error -rtsp_transport tcp \
-i "$URL" -frames:v 1 -q:v 2 -y /srv/cam/latest.jpg
-frames:v 1 stops after one frame, -q:v 2 is high JPEG quality (31 is the lowest), and -y overwrites the
file.
H.264 sends a full picture, a keyframe, only every few seconds. The frames in between contain only changes. If
ffmpeg starts in the middle, the first frame can be smeared or grey. ffmpeg usually waits for a keyframe, but
with my camera it sometimes did not. -ss 1 after the input fixed it: ffmpeg decodes and drops the first
second.
When the camera is offline, ffmpeg can wait for a long time. The timeout command from coreutils stops it.
A web page that shows latest.jpg may also read the file while ffmpeg is still writing it, so the script
writes a temp file and renames it. mv on the same filesystem is atomic.
#!/bin/sh
URL="rtsp://user:pass@192.168.1.50:554/stream1"
DIR=/srv/cam
timeout 20 ffmpeg -hide_banner -loglevel error -rtsp_transport tcp \
-i "$URL" -ss 1 -frames:v 1 -q:v 2 -y "$DIR/.tmp.jpg" \
&& mv "$DIR/.tmp.jpg" "$DIR/latest.jpg" \
&& cp "$DIR/latest.jpg" "$DIR/archive/$(date +%Y%m%d-%H%M).jpg"
It runs from cron every minute, and the archive needs a cleanup job, or it fills the disk:
* * * * * /usr/local/bin/cam-snapshot.sh
15 4 * * * find /srv/cam/archive -mtime +7 -delete
Recording into 5-minute files
I wanted my own recordings, without a cloud service and without a full NVR program. One ffmpeg command does it:
ffmpeg -hide_banner -loglevel warning -rtsp_transport tcp \
-i "rtsp://user:pass@192.168.1.50:554/stream1" \
-c copy -map 0 \
-f segment -segment_time 300 -segment_format mp4 \
-reset_timestamps 1 -strftime 1 \
"/srv/cam/front/%Y-%m-%d_%H-%M-%S.mp4"
-c copy means no re-encoding. ffmpeg only repacks the H.264 stream into files, so the CPU load is very low
and it runs fine on a Raspberry Pi. -map 0 keeps the audio too, if the camera sends any.
-f segment -segment_time 300 starts a new file about every 5 minutes. With -c copy, ffmpeg can only cut at
a keyframe, so the files are not exactly 300 seconds long. -reset_timestamps 1 makes each file start at time
0, which players handle better, and -strftime 1 puts the date and time into the file name.
ffmpeg exits when the camera reboots or the network drops, so systemd runs it and restarts it:
# /etc/systemd/system/cam-front.service
[Unit]
Description=Record front camera
After=network-online.target
Wants=network-online.target
[Service]
User=recorder
ExecStart=/usr/bin/ffmpeg -hide_banner -loglevel warning -stimeout 10000000 -rtsp_transport tcp -i "rtsp://user:pass@192.168.1.50:554/stream1" -c copy -map 0 -f segment -segment_time 300 -segment_format mp4 -reset_timestamps 1 -strftime 1 /srv/cam/front/%%Y-%%m-%%d_%%H-%%M-%%S.mp4
Restart=always
RestartSec=10
[Install]
WantedBy=multi-user.target
% is a special character in unit files, so it must be written as %%. My first version had single %,
and the unit failed with an unclear error.
-stimeout 10000000 is the RTSP socket timeout in microseconds, so 10 seconds, and it goes before -i. It
covers the case where the connection stays open but no data arrives. Without it, ffmpeg waits forever. With
it, ffmpeg exits and systemd starts it again.
Disk space: the bitrate in Mbit/s times 10.8 gives GB per day. A 4 Mbit/s stream is about 43 GB per day. I keep 7 days:
# /etc/cron.daily/cam-cleanup
#!/bin/sh
find /srv/cam -type f -name '*.mp4' -mtime +7 -delete
MP4 plays everywhere, also in a browser. But a file cut off by a crash or a power cut may not play at all.
MKV (-segment_format matroska and .mkv file names) stays readable after a crash, but browsers do not play
it. An MKV file can become MP4 later without re-encoding: ffmpeg -i in.mkv -c copy out.mp4. On a Pi without a
UPS, that trade is worth thinking about.
Cutting a clip without re-encoding
The usual case is 30 seconds out of a long recording. Re-encoding is slow on a small machine and lowers the quality. Stream copy is fast and lossless:
ffmpeg -ss 00:12:30 -i input.mp4 -t 30 -c copy -avoid_negative_ts make_zero clip.mp4
-ss before -i seeks in the input, which is fast. -t 30 takes 30 seconds; -to 00:13:00 gives an end
time instead. -avoid_negative_ts make_zero fixes the timestamps, so players start at zero.
The cut is not exact. With -c copy, the clip can only start at a keyframe. IP cameras often send a keyframe
only every few seconds, so the clip can start several seconds early, and some players show a frozen picture
until the next keyframe. This lists the keyframes near the start time:
ffprobe -v error -select_streams v:0 -skip_frame nokey \
-show_entries frame=pts_time -of csv=p=0 \
-read_intervals 12:20%12:40 input.mp4
Then use one of those times for -ss. For a frame-exact cut, or a different size or format, re-encode:
ffmpeg -ss 00:12:30 -i input.mp4 -t 30 \
-c:v libx264 -crf 20 -preset veryfast -c:a aac -b:a 128k clip.mp4
-crf 20 gives good quality; higher numbers give smaller files. Clips with the same codec and settings can
be joined without re-encoding, with the concat demuxer:
printf "file '%s'\n" part1.mp4 part2.mp4 > list.txt
ffmpeg -f concat -safe 0 -i list.txt -c copy joined.mp4