#!/bin/bash
# FFmpeg Stream Multiplexer
# Features: Smart Stream Mapping, Terminology Integration, Path-Safety
# Based on original concept by Tony Brijeski, coded by Google Gemini 3

# 1. MAIN UI DIALOG
# We use a single form for a better "Modern" feel
MUX_DATA=$(yad --form \
    --title="FFmpeg Mulitiplexer" \
    --image="/usr/local/share/icons/custom/ffmpeg-app.png" \
    --window-icon="/usr/local/share/icons/custom/ffmpeg.png" \
    --width=720 --center \
    --text="<b>Combine separate Video and Audio streams into chosen container.</b>\nStreams will be 'Stream Copied' (no quality loss).\nSave your file with the correct format extension (.mp4, .mkv etc.)\n*Existing Audio will be removed from Video Files!" \
    --field="Select Source Video:FL" "" \
    --field="Select Source Audio:FL" "" \
    --field="Output Destination:SFL" "" \
    --button="Multiplex":10 \
    --button="Cancel":1)

[[ $? -ne 10 ]] && exit 0

# Parse Fields
VIDEO_IN=$(echo "$MUX_DATA" | cut -d'|' -f1)
AUDIO_IN=$(echo "$MUX_DATA" | cut -d'|' -f2)
OUTPUT_OUT=$(echo "$MUX_DATA" | cut -d'|' -f3)

# 2. SANITY CHECKS
if [[ -z "$VIDEO_IN" || -z "$AUDIO_IN" || -z "$OUTPUT_OUT" ]]; then
    yad --error --text="All fields (Video, Audio, and Output) are required." --width=350 --center
    exit 1
fi

# Ensure output has an extension
if [[ ! "$OUTPUT_OUT" == *.* ]]; then
    yad --error --text="Please provide a file extension (e.g., .mp4, .mkv, .mpg) in the output path." --width=350 --center
    exit 1
fi

# 3. EXECUTION
# -map 0:v (Take video from first file)
# -map 1:a (Take audio from second file)
# -shortest (Ensures the file ends when the shortest stream ends)
terminology -T="Multiplexing Selected Video and Audio Files" -e bash -c "echo 'Multiplexing Streams...'; \
ffmpeg -y -i '$VIDEO_IN' -i '$AUDIO_IN' \
-map 0:v -map 1:a \
-c:v copy -c:a copy -shortest \
'$OUTPUT_OUT'; \
if [ \$? -eq 0 ]; then \
    echo -e '\nSUCCESS: File created at $OUTPUT_OUT'; \
    sleep 2; \
else \
    echo -e '\nERROR: Multiplexing failed!'; \
    read -p 'Press Enter to see why...'; \
fi"

# 4. FINAL NOTIFICATION
notify-send "Stream Muxing Complete!" --icon="/usr/local/share/icons/custom/ffmpeg.png"