Files
nginx-hls/scripts/validate-media.sh
T
2026-09-27 15:55:38 +08:00

101 lines
2.7 KiB
Bash
Executable File

#!/usr/bin/env bash
set -euo pipefail
media_root=${1:-data}
if ! command -v ffprobe >/dev/null 2>&1; then
echo "ffprobe is required to validate media." >&2
exit 2
fi
if [[ ! -d $media_root ]]; then
printf 'Media directory does not exist: %s\n' "$media_root" >&2
exit 2
fi
valid_count=0
invalid_count=0
validate_file() {
local file=$1
local format_name streams codec type attached_pic
local video_count=0
local audio_count=0
local invalid_reason=
if ! format_name=$(ffprobe -v error -show_entries format=format_name \
-of default=noprint_wrappers=1:nokey=1 "$file"); then
printf 'INVALID: %q: unreadable or corrupt MP4\n' "$file" >&2
return 1
fi
if [[ ,$format_name, != *,mp4,* ]]; then
printf 'INVALID: %q: expected an MP4 container, got %s\n' "$file" "$format_name" >&2
return 1
fi
if ! streams=$(ffprobe -v error \
-show_entries stream=codec_name,codec_type:stream_disposition=attached_pic \
-of csv=p=0 "$file"); then
printf 'INVALID: %q: unable to inspect streams\n' "$file" >&2
return 1
fi
while IFS=, read -r codec type attached_pic; do
case "$type" in
video)
if [[ $attached_pic == 1 ]]; then
continue
fi
if [[ $codec != h264 ]]; then
invalid_reason="unsupported video codec $codec"
fi
((video_count += 1))
;;
audio)
if [[ $codec != aac ]]; then
invalid_reason="unsupported audio codec $codec"
fi
((audio_count += 1))
;;
*)
invalid_reason="unsupported $type track ($codec)"
;;
esac
done <<< "$streams"
if [[ -n $invalid_reason ]]; then
printf 'INVALID: %q: %s\n' "$file" "$invalid_reason" >&2
return 1
fi
if ((video_count != 1 || audio_count != 1)); then
printf 'INVALID: %q: expected one H.264 video and one AAC audio track; found %d video and %d audio\n' \
"$file" "$video_count" "$audio_count" >&2
return 1
fi
printf 'VALID: %s\n' "$file"
}
while IFS= read -r -d '' file; do
if validate_file "$file"; then
((valid_count += 1))
else
((invalid_count += 1))
fi
done < <(find "$media_root" -type f -iname '*.mp4' -print0)
if ((valid_count == 0)); then
echo "No valid MP4 files were found." >&2
exit 1
fi
if ((invalid_count > 0)); then
printf 'Validation failed: %d valid, %d invalid file(s).\n' "$valid_count" "$invalid_count" >&2
exit 1
fi
printf 'Validation passed: %d MP4 file(s).\n' "$valid_count"