[FFmpeg-user] Is there a way to reconnect to a RTSP stream after it disappears from the network?
Mikhail Morfikov
mmorfikov at gmail.com
Mon Jan 6 12:38:29 EET 2025
On 2025-01-05 18:31, arthurpeabody wrote:
> When streamripper restarts after a dropout it creates a new file.
> When one archives a log file in Linux, the daemon that writes to it
> stops writing to it, for which reason one must stop a daemon when
> archiving its log file, then restart. This could be ffmpeg's
> problem: the file handle to which it was writing has disappeared and
> it isn't opening a new one.
I think I solved this. I mean, I'm not sure whether ffmpeg is able to do
what I wanted it to do, but I created the following systemd service which
is able to restart the ffmpeg proces when it timeouts:
------------------------------------
[Unit]
Description=FFMPEG streaming
Documentation=man:ffmpeg
DefaultDependencies=yes
After=media-Zami.mount
After=local-fs.target network-online.target nss-lookup.target
Before=multi-user.target
ConditionPathIsReadWrite=/media/Zami/ffmpeg-rec/
ConditionFileIsExecutable=/usr/bin/ffmpeg
[Service]
#StandardError=null
#StandardOutput=null
# Systemd specifiers are indicated by the % sign. Use "%%" in place of "%" to specify a single
# percent sign (in order to use the strftime ffmpeg option to get the timestamp in the filenames).
Environment="FILE_NAME=/media/Zami/ffmpeg-rec/%%Y-%%m-%%d-%%H-%%M-%%S.mkv"
ExecStart=/usr/bin/ffmpeg \
-hide_banner -loglevel error \
-timeout 1000000 -use_wallclock_as_timestamps 1 \
-rtsp_transport tcp -i rtsp://user:pass@192.168.1.242:554/stream1 \
-vcodec copy -acodec copy \
-f segment -segment_format mkv -segment_time 30 \
-reset_timestamps 1 -strftime 1 \
$FILE_NAME
#Restart=on-failure
Restart=always
RestartSec=5
TimeoutSec=1s
#RuntimeMaxSec=3600
# Hardening
ProtectSystem=full
PrivateTmp=true
SystemCallArchitectures=native
MemoryDenyWriteExecute=true
NoNewPrivileges=true
[Install]
WantedBy=multi-user.target
------------------------------------
So, in the ffmpeg exec line I added the `-timeout 1000000` parameter.
The option makes sure that when camera disappears ffmpeg will terminate
gracefully after one second (it will stop recording and close the file).
Then systemd detect this failure and initiates the service restart. Then
if the host is still down, ffmpeg will terminate because of "Error
opening input files: Connection timed out". In the 5s intervals, systemd
tries to restart the service, and if the camera is down, it tries over
and over till it shows up on the network. When the camera comes back to
life, ffmpeg starts recording with new a file. Nothing gets corrupted,
and everything seems to work just fine. Probably the systemd service file
needs some adjustments, but for now, it works more or less in the way I
wanted.
I still dont't know if ffmpeg is capable of doing this task alone. So if
someone knows the answer, please let me know.
More information about the ffmpeg-user
mailing list