#!/bin/bash
# 三段成片拼接：
#   1) 12 帧（0.5s）交叉溶像版（隐藏人物比例跳变）：总长 31.5s
#   2) 硬切版（保留分段原貌）：总长 32.5s
# 用法: bash assemble_film.sh <工作目录> <段1.mp4> <段2.mp4> <段3.mp4>
set -e
DIR="$1"; S1="$2"; S2="$3"; S3="$4"
FPS=24
# 260 帧/段，溶像 12 帧 → offset1 = (260-12)/24，offset2 = (2*260-12-12)/24
OFF1=$(python3 -c "print((260-12)/24)")
OFF2=$(python3 -c "print((520-12-12)/24)")

DISSOLVE="$DIR/成片_三段交叉溶像_31s.mp4"
ffmpeg -y -v error -i "$DIR/$S1" -i "$DIR/$S2" -i "$DIR/$S3" -filter_complex \
"[0:v][1:v]xfade=transition=fade:duration=0.5:offset=${OFF1}[v01]; \
 [v01][2:v]xfade=transition=fade:duration=0.5:offset=${OFF2}[v]; \
 [0:a][1:a]acrossfade=d=0.5:c1=tri:c2=tri[a01]; \
 [a01][2:a]acrossfade=d=0.5:c1=tri:c2=tri[a]" \
 -map "[v]" -map "[a]" -c:v libx264 -crf 14 -pix_fmt yuv420p -c:a aac \
 -movflags +faststart "$DISSOLVE"

HARDCUT="$DIR/成片_三段硬切_32s.mp4"
printf "file '%s'\nfile '%s'\nfile '%s'\n" \
  "$(realpath "$DIR/$S1")" "$(realpath "$DIR/$S2")" "$(realpath "$DIR/$S3")" > "$DIR/_hard.txt"
ffmpeg -y -v error -f concat -safe 0 -i "$DIR/_hard.txt" -c copy "$HARDCUT"

for f in "$DISSOLVE" "$HARDCUT"; do
  printf "%s : " "$(basename "$f")"
  ffprobe -v error -select_streams v:0 -count_frames \
    -show_entries stream=nb_read_frames,width,height -show_entries format=duration \
    -of csv=p=0 "$f" | tr '\n' ' '
  echo
done
echo "OK → $DISSOLVE / $HARDCUT"
