Search code examples
linuxcronraspberry-pirtsp

crontab to start and change libcamera-vid RTSP stream on a Raspberry Pi


I'm using my Raspberry Pi as a security cam, and I want the ability to automatically start the libcamera-vid stream on reboot, plus change some settings throughout the day.

I pieced together the below script just googling around...

#!/bin/bash
pkill -f libcamera-vid ;
H=$(date +%k%M)
(( 700 <= H && H < 2000 )) && libcamera-vid -t 0 --inline -n --bitrate 3000000 --width 1920 --height 1080 --rotation 180 --framerate 24 --autofocus-mode manual --gain 2 --sharpness 4.0  --contrast 1.2 --brightness 0.1 --codec libav --libav-format flv --libav-audio --audio-device alsa_input.usb-C-Media_Electronics_Inc._USB_PnP_Sound_Device-00.mono-fallback --audio-bitrate 192000 --av-sync 2000000 -o - | cvlc stream:///dev/stdin --sout '#rtp{sdp=rtsp://:8554/securcam}' || libcamera-vid -t 0 --inline -n --bitrate 3000000 --width 1920 --height 1080 --rotation 180 --framerate 24 --autofocus-mode manual --gain 26 --sharpness 2.0  --contrast 1.2 --brightness 0.1 --codec libav --libav-format flv --libav-audio --audio-device alsa_input.usb-C-Media_Electronics_Inc._USB_PnP_Sound_Device-00.mono-fallback --audio-bitrate 192000 --av-sync 2000000 -o - | cvlc stream:///dev/stdin --sout '#rtp{sdp=rtsp://:8554/securcam}'
#this is how I added my jobs in the cron
@reboot /home/user/scripts/rebootcam.sh
05 07 * * *  /home/user/scripts/rebootcam.sh                                    
20 05 * * * /home/user/scripts/rebootcam.sh

The script runs fine via a terminal, but it will not run via a cron job. It appears the cron will execute the last part of the script (vlc rtsp stream) and either error out or ignore the libcamera-vid commands.

I'm assuming the pipe to run the output stream is breaking the script when run by the cron.

I'm hoping some guru can explain if this can be run via the cron or not.

Thanks for any help.


Solution

  • I recently figured out the source of the issue stopping the cron job from executing. Since I'm invoking an audio option (--libav-audio) in the script, the script will call on a connection to PulseAudio, and PulseAudio was refusing a connection with the error listed below...

    [002f2e18] vlcpulse audio output error: PulseAudio server connection failure: Connection refused

    I found a solution on another StackExchange post, which advised to include the following string in front of a cron job...

    XDG_RUNTIME_DIR=/run/user/$(id -u)
    

    Here's an example of how the cron job should look with the XDG string. Note, you do not have to change the XDG string, you can simply add it to your cron job exactly as posted above.

    05 06 * * * XDG_RUNTIME_DIR=/run/user/$(id -u) /home/user/scripts/rebootcam.sh  >> /home/user/my.log 2>&1
    

    The cron job now executes successfully without issue.