#!/bin/bash
# Detailed keyframe analysis for INTRO.mp4

INTRO_PATH="/home/mbetterclient/mbetterc/assets/INTRO.mp4"

echo "=========================================="
echo "KEYFRAME ANALYSIS FOR INTRO.mp4"
echo "=========================================="
echo ""

echo "1. Total keyframe count..."
echo "-------------------------------------------"
KEYFRAME_COUNT=$(ffprobe -v error -select_streams v:0 -show_entries frame=key_frame -of csv=p=0 "$INTRO_PATH" 2>&1 | grep -c "^1$" || echo "0")
echo "Total keyframes: $KEYFRAME_COUNT"
echo ""

echo "2. Keyframe intervals (first 20)..."
echo "-------------------------------------------"
ffprobe -v error -select_streams v:0 -show_entries frame=pkt_pts_time,key_frame -of csv=p=0 "$INTRO_PATH" 2>&1 | grep ",1$" | head -20
echo ""

echo "3. Keyframe intervals (last 20)..."
echo "-------------------------------------------"
ffprobe -v error -select_streams v:0 -show_entries frame=pkt_pts_time,key_frame -of csv=p=0 "$INTRO_PATH" 2>&1 | grep ",1$" | tail -20
echo ""

echo "4. Checking for gaps > 10 seconds between keyframes..."
echo "-------------------------------------------"
ffprobe -v error -select_streams v:0 -show_entries frame=pkt_pts_time,key_frame -of csv=p=0 "$INTRO_PATH" 2>&1 | grep ",1$" | awk -F',' '
BEGIN { prev = 0 }
{
    if (prev > 0) {
        gap = $1 - prev;
        if (gap > 10) {
            printf "GAP: %.2f seconds between %.2f and %.2f\n", gap, prev, $1;
        }
    }
    prev = $1;
}'
echo ""

echo "5. Checking keyframes around 200-300 seconds..."
echo "-------------------------------------------"
ffprobe -v error -select_streams v:0 -show_entries frame=pkt_pts_time,key_frame -of csv=p=0 "$INTRO_PATH" 2>&1 | grep ",1$" | awk -F',' '$1 >= 200 && $1 <= 300 {print}'
echo ""

echo "6. GOP (Group of Pictures) analysis..."
echo "-------------------------------------------"
ffprobe -v error -select_streams v:0 -show_entries frame=pkt_pts_time,key_frame -of csv=p=0 "$INTRO_PATH" 2>&1 | awk -F',' '
BEGIN { count = 0; max_gop = 0; gop_start = 0 }
{
    if ($2 == 1) {
        if (count > 0) {
            gop_size = $1 - gop_start;
            if (gop_size > max_gop) max_gop = gop_size;
            if (gop_size > 10) printf "Large GOP: %.2f seconds starting at %.2f\n", gop_size, gop_start;
        }
        gop_start = $1;
        count++;
    }
}
END { printf "Max GOP size: %.2f seconds\n", max_gop }'
echo ""

echo "7. Recommended fix: Re-encode with fixed keyframe interval..."
echo "-------------------------------------------"
echo "Run this command to fix the video:"
echo ""
echo "ffmpeg -i $INTRO_PATH -c:v libx264 -preset medium -g 90 -keyint_min 90 -sc_threshold 0 -c:a copy ${INTRO_PATH}.fixed.mp4"
echo ""
echo "This will ensure a keyframe every 3 seconds (90 frames at 30fps)"
echo ""

echo "=========================================="
echo "ANALYSIS COMPLETE"
echo "=========================================="