#!/usr/bin/env bash if ! command -v inotifywait >/dev/null 2>&1; then echo "Please install inotify_utils" exit 1 fi if ! command -v v4l2-ctl >/dev/null 2>&1; then echo "Please install v4l-utils" exit 1 fi declare -A STREAMS sigint() { for pid in "${STREAMS[@]}"; do wait "$pid" done } trap sigint INT failed() { file=$1 echo "Streaming $file failed" tail -n 5 "/tmp/${file}_log" unset "STREAMS[$file]" } streaming() { echo "Streaming $1" echo "Logfile: /tmp/$1_log" (set -o xtrace; ffmpeg \ -f v4l2 \ -framerate 30 \ -i "/dev/$1" \ -pix_fmt uyvy422 \ -f libndi_newtek \ -y "$1" \ > "/tmp/$1_log" \ 2>&1 ) || failed "$1" unset "STREAMS[$file]" } check() { file=$1 echo "Found $file" if v4l2-ctl -n -d "/dev/$file" | grep -q 'Input'; then (streaming "$file") & STREAMS[$file]=$! echo "$file PID ${STREAMS[$file]}" fi } check_initial_devices() { for file in /dev/video*; do file="${file##*/}" check "$file" done } listen_for_new_devices() { inotifywait -m /dev --format "%f" -e create | while read -r file; do if [[ "$file" =~ video[0-9]+$ ]]; then if ! ps -p "${STREAMS[$file]}"> /dev/null; then unset "STREAMS[$file]" fi if [[ ! -v "STREAMS[$file]" ]]; then check "$file" fi fi done } check_initial_devices listen_for_new_devices