#!/bin/bash
# Video playback optimization script for Raspberry Pi
# Improves video smoothness and reduces stuttering

echo "Optimizing system for smooth video playback..."

# 1. Increase GPU memory split for better video performance
if [ -f /boot/config.txt ]; then
    echo "Checking GPU memory configuration..."
    if grep -q "gpu_mem=" /boot/config.txt; then
        # GPU memory already configured, check if it's sufficient
        CURRENT_GPU_MEM=$(grep "gpu_mem=" /boot/config.txt | head -1 | cut -d'=' -f2)
        if [ "$CURRENT_GPU_MEM" -lt 256 ]; then
            sudo sed -i 's/gpu_mem=.*/gpu_mem=256/' /boot/config.txt
            echo "✓ GPU memory increased to 256MB for video"
        fi
    else
        # Add GPU memory setting
        echo "gpu_mem=256" | sudo tee -a /boot/config.txt > /dev/null
        echo "✓ GPU memory set to 256MB for video"
    fi
fi

# 2. Install video codec support
echo "Installing video codec libraries..."
sudo apt-get install -y \
    libva-drm2 \
    libva2 \
    libavcodec-extra \
    libavutil-dev \
    2>/dev/null || true

# 3. Optimize swappiness for better memory management
echo "Optimizing memory management..."
if [ -f /proc/sys/vm/swappiness ]; then
    CURRENT_SWAP=$(cat /proc/sys/vm/swappiness)
    if [ "$CURRENT_SWAP" -gt 30 ]; then
        echo 30 | sudo tee /proc/sys/vm/swappiness > /dev/null
        echo "vm.swappiness=30" | sudo tee -a /etc/sysctl.conf > /dev/null
        echo "✓ Swappiness optimized"
    fi
fi

# 4. Disable CPU frequency scaling for consistent performance
echo "Ensuring CPU performance mode..."
for cpu in /sys/devices/system/cpu/cpu[0-9]*; do
    if [ -f "$cpu/cpufreq/scaling_governor" ]; then
        echo performance | sudo tee "$cpu/cpufreq/scaling_governor" > /dev/null 2>&1 || true
    fi
done
echo "✓ CPU set to performance mode"

# 5. Optimize file system cache
echo "Optimizing filesystem cache..."
echo 50 | sudo tee /proc/sys/vm/vfs_cache_pressure > /dev/null
echo "vm.vfs_cache_pressure=50" | sudo tee -a /etc/sysctl.conf > /dev/null
echo "✓ Filesystem cache optimized"

echo ""
echo "✅ Video playback optimization complete!"
echo "Note: Some changes require a reboot to take effect."
