#!/bin/sh

# record_webcam.sh
# 2022-03-18
# by Gernot Walzl

# This script records the video and audio stream from a webcam.
#
# To list controls of the webcam:
# v4l2-ctl -d "$VIDEO_DEV" --list-ctrls
#
# To list supported video output formats of the webcam:
# v4l2-ctl -d "$VIDEO_DEV" --list-formats-ext

VIDEO_DEV=${VIDEO_DEV:-'/dev/video0'}  # v4l2-ctl --list-devices
AUDIO_DEV=${AUDIO_DEV:-'hw:1,0'}       # arecord --list-devices
OUTPUT_DIR=${OUTPUT_DIR:-"$HOME/webcam"}

print_usage () {
  echo "Usage:"
  echo "  $0 {start,stop,status,toggle}"
}

get_pid () {
  ps -fC ffmpeg | grep "$VIDEO_DEV" | awk '{ print $2 }'
}

start_recording () {
  if [ -n "$(get_pid)" ]; then
    echo "Already recording"
    return 1
  fi

  mkdir -p "$OUTPUT_DIR"

  # disable auto focus
  #v4l2-ctl -d "$VIDEO_DEV" --set-ctrl focus_auto=0
  v4l2-ctl -d "$VIDEO_DEV" --set-ctrl focus_automatic_continuous=0
  v4l2-ctl -d "$VIDEO_DEV" --set-ctrl focus_absolute=0

  # set output format of the webcam
  v4l2-ctl -d "$VIDEO_DEV" --set-fmt-video width=1920,height=1080,pixelformat=H264

  # copy the h264 encoded video stream
  # alternatively, encode the video stream using:
  # -codec:v h264_v4l2m2m
  ffmpeg -f video4linux2 -input_format h264 -i "$VIDEO_DEV" \
         -f alsa -i "$AUDIO_DEV" \
         -codec:v copy \
         "${OUTPUT_DIR}/$(date +%Y-%m-%d_%H%M%S).mp4" &
}

stop_recording () {
  local PID
  PID=$(get_pid)
  if [ -z "$PID" ]; then
    echo "Already stopped"
    return 1
  fi
  kill "$PID"
}

print_status () {
  if [ -z "$(get_pid)" ]; then
    echo "Stopped"
  else
    echo "Recording"
  fi
}

case "$1" in
 'start')
  start_recording
  ;;
 'stop')
  stop_recording
  ;;
 'status')
  print_status
  ;;
 'toggle')
  if [ -z "$(get_pid)" ]; then
    start_recording
  else
    stop_recording
  fi
  ;;
 *)
  print_usage
esac