#!/bin/bash
# encode_vcd_set.sh —— 把提取出的 MPEG-PS 母版转成 MP4（参照 66-VCD转录 的命名规范）
# 用法: bash encode_vcd_set.sh <mpeg目录> <输出目录>
set -uo pipefail
MPEG="${1:?mpeg 目录}"
OUT="${2:?输出目录}"
mkdir -p "$OUT"

# 封底 VCD 曲目名（按 AVSEQ 顺序 01-09）
declare -A TITLES=(
  [01]="Ballade Pour Adeline 艾德琳的诗（广场）"
  [02]="Diva 迪娃"
  [03]="Forgetting 遗忘"
  [04]="Friends 朋友"
  [05]="Place De Sun Airport - Listen To The Sea 日光机场·听海"
  [06]="Aquarello 水彩画"
  [07]="Desperado 亡命之徒"
  [08]="Piano Concerto No.1 Tchaikovsky 柴可夫斯基第一钢琴协奏曲"
  [09]="Memory 记忆"
)

echo "=== 转码 $(date '+%T')"
LIST=""
for f in "$MPEG"/avseq*.mpg; do
  [[ -e "$f" ]] || continue
  n=$(basename "$f" | grep -oE '[0-9]+' | head -1)
  n2=$(printf '%02d' "$((10#$n))")
  title="${TITLES[$n2]:-曲目$n2}"
  dur=$(ffprobe -v error -show_entries format=duration -of csv=p=0 "$f")
  durmm=$(python3 -c "d=float('$dur'); print(f'{int(d//60)}分{int(d%60):02d}秒')")
  dst="$OUT/VCD-${n2}-${title}-${durmm}.mp4"
  echo "--- AVSEQ${n2}: ${durmm}  ->  $(basename "$dst")"
  ffmpeg -y -v error -i "$f" \
    -c:v libx264 -preset slow -crf 16 -pix_fmt yuv420p -vf "scale=352:288,setsar=1" \
    -c:a aac -b:a 224k -ar 44100 -ac 2 "$dst" || { echo "  ❌ 失败"; continue; }
  echo "  ✅ $(stat -c %s "$dst" | awk '{printf "%.1f MB", $1/1048576}')  $(ffprobe -v error -show_entries stream=width,height,r_frame_rate -of csv=p=0 "$dst" | head -1)"
  LIST="$LIST$dst"$'\n'
done
echo "$LIST" | grep -v '^$' > "$OUT/播放顺序.txt"
echo "=== 完成 $(date '+%T')"
ls -la "$OUT"/*.mp4 2>/dev/null | awk '{printf "  %8.1f MB  %s\n", $5/1048576, $9}'
