Skip to content

Instantly share code, notes, and snippets.

@Dagnan
Created November 8, 2023 14:23
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Dagnan/f6c7cbc8e17b6aee5657e8ee0f596728 to your computer and use it in GitHub Desktop.
Save Dagnan/f6c7cbc8e17b6aee5657e8ee0f596728 to your computer and use it in GitHub Desktop.
require 'open3'
RTSP_USER = 'user'
RTSP_PASSWORD = 'password'
RTSP_HOST = '192.168.1.100'
RTSP_PATH = '/live2'
RTSP_PROXY_URI = 'rtmp://127.0.0.1/live/test'
SCREENSHOT_FILE_NAME = 'screenshot.png'
SCREENSHOT_FPS = 1
SEND_COLOR_CMD = "ffmpeg -f lavfi -i color=green:1920x1080:d=1:r=15,format=yuv420p -vcodec libx264 -f flv \"#{RTSP_PROXY_URI}\""
SEND_SCREENSHOT_CMD = "ffmpeg -loop 1 -i #{SCREENSHOT_FILE_NAME} -vcodec libx264 -t 6 -r 15 -f flv \"#{RTSP_PROXY_URI}\""
SEND_CAMERA_FEED_CMD = "ffmpeg -y -f rtsp -rtsp_transport tcp -i rtsp://#{RTSP_USER}:#{RTSP_PASSWORD}@#{RTSP_HOST}#{RTSP_PATH} -filter_complex 'split=2[pic][vid];[pic]fps=#{SCREENSHOT_FPS}[png]' -map '[vid]' -an -preset ultrafast -vcodec libx264 -f flv \"#{RTSP_PROXY_URI}\" -map '[png]' -update 1 #{SCREENSHOT_FILE_NAME}"
ERROR_EXPECTED = "404 Stream Not Found"
def screenshot_or_still_img()
# If we previously captured a screenshot from the camera that's what we send
if File.exists?(SCREENSHOT_FILE_NAME)
SEND_SCREENSHOT_CMD
else
# Otherwise we send a solid color image
SEND_COLOR_CMD
end
end
def send_screenshot_or_still_img()
cmds = screenshot_or_still_img()
puts cmds
_color_stdout_str, color_stderr_str, color_status = Open3.capture3(*cmds)
if !color_status.success?
puts "Error while sending secondary command: #{color_stderr_str}"
exit 1
end
end
loop do
puts SEND_CAMERA_FEED_CMD
_stdout_str, stderr_str, status = Open3.capture3(*SEND_CAMERA_FEED_CMD)
if !status.success?
# We send only a replacement of the camera feed when we get a 404 back
if stderr_str.include?(ERROR_EXPECTED)
send_screenshot_or_still_img()
else
puts "Unhandled error: #{stderr_str}"
exit 1
end
end
sleep 1
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment