#!/bin/bash

# Check if URL is provided
if [ -z "$1" ]; then
    echo "Usage: $0 <m3u8_url>"
    exit 1
fi

URLx="$1"
URL="${URLx%%\\?*}"

echo URL

OUTPUT_FILE="output_low.mp3"

echo "Analyzing stream with ffprobe..."

# Find the first audio stream index that is stereo (2 channels) and AAC codec
STREAM_INDEX=$(ffprobe -v error -show_entries stream=index,codec_name,channels -of csv=p=0 "$URL" | \
awk -F, '$2=="aac" && $3==2 {print $1; exit}')

# Check if a matching stream was found
if [ -z "$STREAM_INDEX" ]; then
    echo "Error: No stereo AAC audio stream found."
    exit 1
fi

echo "Found matching stereo AAC stream at index: $STREAM_INDEX"
echo "Downloading AAC audio..."

rm -f output.aac

# Extract the specific stream and convert to lowest quality MP3 (CBR 32k or VBR 9)
ffmpeg -v error -y -i "$URL" -map 0:a:"$STREAM_INDEX" -c copy output.aac

echo "Converting to for -ar 44100 -b:a 128k  MP3..."

#ffmpeg -i output.aac   "$OUTPUT_FILE"

ffmpeg -i output.aac  -b:a 128k  "$OUTPUT_FILE"




echo "Done! Saved to $OUTPUT_FILE"