#!/bin/sh

# Script to extract the first audio streams from video files without quality loss.

for input_file in "$@"
do
  # Check if the file exists
  if test ! -f "$input_file"; then
    echo "File not found: $input_file"
    continue
  fi

  # Get the codec name of the first audio stream
  codec_name=`ffprobe -v error -select_streams a:0 -show_entries stream=codec_name \
    -of default=noprint_wrappers=1:nokey=1 "$input_file"`

  # Map codec_name to file extension
  case "$codec_name" in
    mp3)
      extension="mp3"
      ;;
    aac)
      extension="aac"
      ;;
    ac3)
      extension="ac3"
      ;;
    flac)
      extension="flac"
      ;;
    vorbis)
      extension="ogg"
      ;;
    opus)
      extension="opus"
      ;;
    pcm_s16le)
      extension="wav"
      ;;
    *)
      echo "Unsupported codec ($codec_name) in file: $input_file"
      continue
      ;;
  esac

  # Construct the output file name
  output_file="${input_file}.${extension}"

  # Extract the audio stream without re-encoding
  ffmpeg -i "$input_file" -vn -acodec copy "$output_file"

done