#!/usr/bin/env bash
# Usage: bash mp4-interleave.sh check /path/to/video.mp4
#        bash mp4-interleave.sh fix [-r] /path/to/video.mp4
#        bash mp4-interleave.sh fixd [-r] /path/to/directory
#        bash mp4-interleave.sh checkd /path/to/directory
export LC_ALL=C

# Convert ffprobe decimal seconds to integer microseconds (no floating point).
to_us() {
    local sign whole frac
    [[ $1 =~ ^(-?)([0-9]+)(\.([0-9]+))?$ ]] || return 1
    sign=${BASH_REMATCH[1]}
    whole=${BASH_REMATCH[2]}
    frac=${BASH_REMATCH[4]}000000
    REPLY=$((10#$whole * 1000000 + 10#${frac:0:6}))
    [[ $sign == - ]] && REPLY=$((-REPLY))
    return 0
}

mib() {
    local n=$(( $1 * 1000 / 1048576 ))
    printf '%d.%03d' "$((n / 1000))" "$((n % 1000))"
}

# Seconds with millisecond precision; input is nonnegative microseconds.
seconds() {
    printf '%d.%03d' "$(($1 / 1000000))" "$((($1 / 1000) % 1000))"
}

check() {
    local file=$1 batch=${2:-0} vi= ai= duration= format= duration_us pct sec prev=-1 packets meta
    local stream ts pos field kind idx codec cover i j t d near gap n sum max min over
    local time_order pos_order lb lb_text total_lb=0 ordered_samples=0
    local samples=0 matched_samples=0 total=0 total_sum=0 total_max=0 total_over=0
    local limit=16777216 # 16 MiB: screening heuristic, not a standard
    local tolerance=250000 # maximum DTS pairing gap: 250 ms
    local depth_limit=1000000 # 1 s observed DTS inversion: screening heuristic
    local -a vt vp at ap fields

    # One metadata probe rather than three separate file opens.
    meta=$(ffprobe -v error \
        -show_entries stream=index,codec_type:stream_disposition=attached_pic:format=duration,format_name \
        -of compact=p=1:nk=0 -i "$file") || return 1
    while IFS='|' read -r -a fields; do
        kind=${fields[0]}; idx=; codec=; cover=0
        for field in "${fields[@]}"; do
            case $field in
                index=*) idx=${field#*=} ;;
                codec_type=*) codec=${field#*=} ;;
                disposition:attached_pic=*) cover=${field#*=} ;;
                duration=*) [[ $kind == format ]] && duration=${field#*=} ;;
                format_name=*) [[ $kind == format ]] && format=${field#*=} ;;
            esac
        done
        if [[ $kind == stream && $idx =~ ^[0-9]+$ ]]; then
            [[ -z $vi && $codec == video && $cover == 0 ]] && vi=$idx
            [[ -z $ai && $codec == audio ]] && ai=$idx
        fi
    done <<< "$meta"
    if ((batch)); then
        case ",$format," in
            *,mp4,*|*,mov,*) ;;
            *) printf 'SKIP: not an MP4/MOV-family container (%s).\n' "$format"; return 12 ;;
        esac
        if [[ -z $vi || -z $ai ]]; then
            printf 'SKIP: no video/audio pair.\n'
            return 12
        fi
    fi
    if [[ -z $vi || -z $ai ]] || ! to_us "$duration" || (( REPLY <= 0 )); then
        printf 'Cannot detect: need video, audio and a known duration.\n' >&2
        ((batch)) && return 11
        return 1
    fi
    duration_us=$REPLY

    printf 'Video stream: %s | Audio stream: %s\n' "$vi" "$ai"
    printf '%-8s %8s %8s %12s %12s %12s %10s %12s\n' \
        'Sample' 'Seek(s)' 'Pairs' 'Min(MiB)' 'Avg(MiB)' 'Max(MiB)' '>=16MiB' 'OrderLB(s)'
    for pct in 10 30 50 70 90; do
        sec=$((duration_us * pct / 100 / 1000000))
        (( sec == prev )) && continue
        prev=$sec; samples=$((samples + 1))
        # Seek to a nearby seek point, then read ~3 s, not the entire file.
        packets=$(ffprobe -v error -read_intervals "${sec}%+3" \
            -show_packets -show_entries packet=stream_index,dts_time,pos \
            -of compact=p=0:nk=0 -i "$file") || return 1
        vt=(); vp=(); at=(); ap=(); time_order=1; pos_order=1
        while IFS='|' read -r -a fields; do
            stream=; ts=; pos=
            for field in "${fields[@]}"; do
                case $field in
                    stream_index=*) stream=${field#*=} ;;
                    dts_time=*) ts=${field#*=} ;;
                    pos=*) pos=${field#*=} ;;
                esac
            done
            [[ $stream == "$vi" || $stream == "$ai" ]] || continue
            [[ $pos =~ ^[0-9]+$ ]] && to_us "$ts" || continue
            pos=$((10#$pos)); t=$REPLY
            if [[ $stream == "$vi" ]]; then
                i=${#vt[@]}
                if ((i > 0)); then
                    ((t < vt[i-1])) && time_order=0
                    ((pos < vp[i-1])) && pos_order=0
                fi
                vt+=("$t"); vp+=("$pos")
            else
                i=${#at[@]}
                if ((i > 0)); then
                    ((t < at[i-1])) && time_order=0
                    ((pos < ap[i-1])) && pos_order=0
                fi
                at+=("$t"); ap+=("$pos")
            fi
        done <<< "$packets"

        # Nearest DTS matching: linear for the usual ordered tracks.
        # Fall back to exhaustive matching only for non-monotonic DTS.
        n=0; sum=0; max=0; min=-1; over=0; j=0
        for ((i=0; i<${#vt[@]}; i++)); do
            (( ${#at[@]} > 0 )) || break
            t=${vt[i]}; near=-1; gap=$((tolerance + 1))
            if ((time_order)); then
                # Use the first audio packet at or after this video DTS,
                # then compare with its predecessor. Handles duplicate DTS.
                while ((j+1 < ${#at[@]} && at[j] < t)); do
                    j=$((j+1))
                done
                near=$j; gap=$((t-at[j])); ((gap<0)) && gap=$((-gap))
                if ((j>0)); then
                    d=$((t-at[j-1])); ((d<0)) && d=$((-d))
                    if ((d<=gap)); then near=$((j-1)); gap=$d; fi
                fi
                ((gap <= tolerance)) || continue
            else
                for ((j=0; j<${#at[@]}; j++)); do
                    d=$((t-at[j])); ((d<0)) && d=$((-d))
                    if ((d<gap)); then
                        gap=$d; near=$j
                        ((d==0)) && break
                    fi
                done
                ((near>=0)) || continue
            fi
            d=$((vp[i]-ap[near])); ((d<0)) && d=$((-d))
            n=$((n+1)); sum=$((sum+d))
            ((d>max)) && max=$d
            ((min<0 || d<min)) && min=$d
            ((d>=limit)) && over=$((over+1))
        done

        # Merge the two sampled tracks in physical offset order.
        # A later-written packet with an earlier DTS reveals time inversion.
        # The largest observed inversion is a sample-only lower bound;
        # NOT the exact full-file or chunk-level interleaving depth.
        lb=0; lb_text=N/A
        if ((time_order && pos_order && ${#vt[@]} && ${#at[@]})); then
            i=0; j=0
            while ((i<${#vt[@]} && j<${#at[@]})); do
                if ((vp[i]<ap[j])); then
                    d=$((vt[i]-at[j])); i=$((i+1))
                elif ((ap[j]<vp[i])); then
                    d=$((at[j]-vt[i])); j=$((j+1))
                else
                    i=$((i+1)); j=$((j+1)); continue
                fi
                ((d>lb)) && lb=$d
            done
            lb_text=$(seconds "$lb")
            ordered_samples=$((ordered_samples+1))
            ((lb>total_lb)) && total_lb=$lb
        fi

        if ((n==0)); then
            printf '%-8s %8d %8s %12s %12s %12s %10s %12s\n' \
                "$pct%" "$sec" 'N/A' '-' '-' '-' '-' "$lb_text"
            continue
        fi
        matched_samples=$((matched_samples+1))
        printf '%-8s %8d %8d %12s %12s %12s %9d%% %12s\n' \
            "$pct%" "$sec" "$n" "$(mib "$min")" "$(mib "$((sum/n))")" \
            "$(mib "$max")" "$((over*100/n))" "$lb_text"
        total=$((total+n)); total_sum=$((total_sum+sum)); total_over=$((total_over+over))
        ((max>total_max)) && total_max=$max
    done
    printf '\nUsable samples: %d/%d | Physical-order samples: %d/%d\n' \
        "$matched_samples" "$samples" "$ordered_samples" "$samples"
    if ((ordered_samples)); then
        printf 'Observed cross-track DTS inversion: >= %s s (sample lower bound only)\n' \
            "$(seconds "$total_lb")"
    fi
    if ((total==0)); then
        printf 'INCONCLUSIVE: no matching DTS packets (within 250 ms).\n' >&2
        ((batch)) && return 11
        return 1
    fi
    printf 'Matched: %d | Avg: %s MiB | Max: %s MiB\n' \
        "$total" "$(mib "$((total_sum/total))")" "$(mib "$total_max")"
    if ((total_over>0 || total_lb>depth_limit)); then
        printf 'WARNING: %d/%d pairs >= 16 MiB; sampled order inversion > 1 s: ' "$total_over" "$total"
        if ((total_lb>depth_limit)); then printf 'yes\n'; else printf 'not observed\n'; fi
        ((batch)) && return 10
    elif ((matched_samples<samples || ordered_samples<samples)); then
        printf 'INCONCLUSIVE: incomplete sampling; no alert in usable data.\n'
        ((batch)) && return 11
    else
        printf 'OK: no sampled alert (not a full-file or standards compliance guarantee).\n'
    fi
    return 0
}

supported_file() {
    case $1 in
        *.[mM][pP]4|*.[mM][oO][vV]|*.[mM]4[vV]|*.3[gG][pP]|*.3[gG]2) return 0 ;;
        *) return 1 ;;
    esac
}

fix() {
    local file=$1 replace=${2:-0} output
    local -a muxer=()
    if [ "$replace" -eq 1 ] && [ -L "$file" ]; then
        printf 'Refusing to replace a symbolic link: %s\n' "$file" >&2
        return 1
    fi
    if ! supported_file "$file"; then
        printf 'Fix supports MP4/MOV/M4V/3GP/3G2 files only.\n' >&2; return 1
    fi
    # .m4v can otherwise select the raw MPEG-4 video muxer.
    case $file in
        *.[mM]4[vV]) muxer=(-f mp4) ;;
        *.[mM][pP]4) muxer=(-f mp4) ;;
        *.[mM][oO][vV]) muxer=(-f mov) ;;
        *.3[gG][pP]) muxer=(-f 3gp) ;;
        *.3[gG]2) muxer=(-f 3g2) ;;
    esac
    output="${file%.*}-interleaving.${file##*.}"
    if [ -e "$output" ] || [ -L "$output" ]; then
        printf 'Output already exists: %s\n' "$output" >&2
        return 1
    fi
    ffmpeg -hide_banner -nostdin -n -i "$file" -map 0 -c copy \
        -movflags +faststart "${muxer[@]}" "$output" || {
        printf 'Remux failed; an incomplete output may remain: %s\n' "$output" >&2
        return 1
    }
    if [ ! -f "$output" ] || [ ! -s "$output" ] || [ -L "$output" ]; then
        printf 'Remux failed: output is not a valid nonempty regular file.\n' >&2
        return 1
    fi
    if ((replace)); then
        # Both paths are in the same directory; replace by rename only after success.
        if [ ! -f "$file" ] || [ -L "$file" ]; then
            printf 'Replacement aborted: original is not a regular file.\n' >&2
            return 1
        fi
        mv -f -- "$output" "$file" || {
            printf 'Replacement failed; check the original and output: %s / %s\n' "$file" "$output" >&2
            return 1
        }
        printf '\nReplaced: %s\n' "$file"
    else
        printf '\nOutput: %s\n' "$output"
    fi
}

# Directory mode: recurse with Bash globs, no find or external file scanners.
# check batch statuses: 0 clean, 10 alert, 11 inconclusive, 12 skip, 1 error.
batch_walk() {
    local dir=$1 entry rc
    if [[ ! -r $dir || ! -x $dir ]]; then
        printf 'Cannot read directory: %s\n' "$dir" >&2
        failed=$((failed+1))
        return 0
    fi
    for entry in "$dir"/*; do
        [[ -L $entry ]] && continue
        if [[ -d $entry ]]; then
            batch_walk "$entry"
        elif [[ -f $entry ]] && supported_file "$entry"; then
            # Generated output is never an input to a subsequent batch run.
            if [[ ${entry%.*} == *-interleaving ]]; then
                skipped=$((skipped+1))
                continue
            fi
            scanned=$((scanned+1))
            printf '\n=== %s ===\n' "$entry"
            check "$entry" 1
            rc=$?
            case $rc in
                0) clean=$((clean+1)) ;;
                10)
                    alerts=$((alerts+1))
                    if [[ $action == fix ]]; then
                        if fix "$entry" "$replace"; then
                            fixed=$((fixed+1))
                        else
                            failed=$((failed+1))
                        fi
                    else
                        alert_paths+=("$entry")
                    fi
                    ;;
                11) inconclusive=$((inconclusive+1)) ;;
                12) skipped=$((skipped+1)) ;;
                *) failed=$((failed+1)) ;;
            esac
        fi
    done
    return 0
}

batch() (
    local dir=$1 replace=${2:-0} action=$3 path
    local scanned=0 clean=0 alerts=0 fixed=0 skipped=0 inconclusive=0 failed=0
    local -a alert_paths=()
    shopt -s nullglob dotglob
    batch_walk "$dir"
    printf '\n=== Batch summary ===\n'
    if [[ $action == fix ]]; then
        printf 'Scanned: %d | OK: %d | Alerts: %d | Fixed: %d | Skipped: %d | Inconclusive: %d | Failed: %d\n' \
            "$scanned" "$clean" "$alerts" "$fixed" "$skipped" "$inconclusive" "$failed"
    else
        printf 'Scanned: %d | OK: %d | Alerts: %d | Skipped: %d | Inconclusive: %d | Failed: %d\n' \
            "$scanned" "$clean" "$alerts" "$skipped" "$inconclusive" "$failed"
        printf '\n=== Files needing interleaving repair (%d) ===\n' "$alerts"
        if ((alerts)); then
            for path in "${alert_paths[@]}"; do
                printf '%s\n' "$path"
            done
        else
            printf '(none)\n'
        fi
        if ((failed || inconclusive)); then
            printf '\nNOTE: failed or inconclusive files are not included in the repair list.\n' >&2
        fi
    fi
    ((failed == 0 && inconclusive == 0))
)

usage() {
    printf 'Usage: %s check /path/to/video.mp4\n       %s fix [-r] /path/to/video.mp4\n       %s fixd [-r] /path/to/directory\n       %s checkd /path/to/directory\n' "$0" "$0" "$0" "$0" >&2
    exit 2
}

(( $# >= 1 )) || usage
mode=$1; shift
replace=0
case $mode in
    fix|--fix|fixd|--fixd)
        if (( $# == 2 )); then
            if [[ $1 == -r ]]; then
                replace=1; shift
            elif [[ $2 == -r ]]; then
                replace=1; set -- "$1"
            fi
        fi
        ;;
    check|--check|checkd|--checkd) ;;
    *) usage ;;
esac
(( $# == 1 )) || usage
file=$1
[[ $file == /* ]] || file=./$file
case $mode in
    fixd|--fixd)
        [[ -d $file ]] || { printf 'Directory not found: %s\n' "$file" >&2; exit 1; }
        batch "$file" "$replace" fix ;;
    checkd|--checkd)
        [[ -d $file ]] || { printf 'Directory not found: %s\n' "$file" >&2; exit 1; }
        # Absolute paths make the summary easy to reuse from other directories.
        [[ $file == /* ]] || file=$PWD/${file#./}
        batch "$file" 0 check ;;
    check|--check|fix|--fix)
        [[ -f $file ]] || { printf 'File not found: %s\n' "$file" >&2; exit 1; }
        case $mode in
            check|--check) check "$file" ;;
            fix|--fix) fix "$file" "$replace" ;;
        esac ;;
    *) printf 'Unknown mode: %s\n' "$mode" >&2; exit 2 ;;
esac
