#!/bin/bash

# compare software vs hardware decoding of h264 rtsp video stream
# brainboxes 2025


# Default values (overridable via command-line arguments)
DEFAULT_RTSP_URL="rtsp://192.168.1.123"
DEFAULT_DURATION=30

# Parse command-line arguments
RTSP_URL="${1:-$DEFAULT_RTSP_URL}"
DURATION="${2:-$DEFAULT_DURATION}"

# Validate duration is a number
if ! [[ "$DURATION" =~ ^[0-9]+$ ]]; then
    echo "Error: Duration must be a positive integer. Using default $DEFAULT_DURATION seconds."
    DURATION=$DEFAULT_DURATION
fi

# Log files
SOFTWARE_LOG="software_decode.log"
HARDWARE_LOG="hardware_v4l2m2m_decode.log"

# Function to probe stream settings
probe_stream() {
    echo -e "\nProbing stream settings..."
    local stream_info=$(ffmpeg -i "$RTSP_URL" 2>&1 | grep "Stream #0:0")
    
    if [ -z "$stream_info" ]; then
        echo "Error: No video stream found at $RTSP_URL"
        exit 1
    fi

    echo "Stream Settings:"
    echo "URL: $RTSP_URL"
    echo " $stream_info"
    echo "------------------------------"
}

# Run stream probe
probe_stream

# Print test configuration
echo "Testing configuration:"
echo "DURATION: $DURATION seconds"
echo "------------------------------"

# Test software decoding (h264)
echo "Testing software decoding (h264)..."
ffmpeg -i "$RTSP_URL" -c:v h264 -t "$DURATION" -f null - -benchmark 2> "$SOFTWARE_LOG"

# Test hardware decoding (h264_v4l2m2m)
echo "Testing hardware decoding (h264_v4l2m2m)..."
ffmpeg -i "$RTSP_URL" -c:v h264_v4l2m2m -pix_fmt yuv420p -t "$DURATION" -f null - -benchmark 2> "$HARDWARE_LOG"

# Extract and compare results
echo "Software Decoding Results (h264):"
grep "bench:" "$SOFTWARE_LOG"

echo "Hardware Decoding Results (h264_v4l2m2m):"
grep "bench:" "$HARDWARE_LOG"

# Display errors (if any)
echo "Software Decoding Errors:"
grep -i "error" "$SOFTWARE_LOG"

echo "Hardware Decoding Errors:"
grep -i "error" "$HARDWARE_LOG"