#!/usr/bin/env python3
"""
生成前10句字幕的视频（在字幕间隔中间切换图片）
"""
import sqlite3
import os
import subprocess

# 数据库路径
db_path = "\\\\ll\\D\\xtrssvjj\\dpd.db"

# 输入输出
mp3_path = "\\\\ll\\D\\wxvddata\\师徒一场_张雪峰走好_上.mp3"
frames_dir = os.path.abspath("shitu_frames")
temp_dir = "shitu_temp"
if not os.path.exists(temp_dir):
    os.makedirs(temp_dir)

# 查询前10句字幕
try:
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()

    cursor.execute("SELECT idx, start, end, cn, en FROM srts WHERE adid = 8281 ORDER BY idx ASC LIMIT 10")
    subtitles = cursor.fetchall()

    print(f"处理前 {len(subtitles)} 句字幕")
    print("\n字幕时间:")
    for idx, start, end, cn, en in subtitles:
        print(f"  {idx}: {start}ms - {end}ms ({cn[:20]}...)")

    # 计算每张图片的切换时间点（在间隔中间）
    # 策略：每张图片显示到下一句开始前0.5秒
    switches = []  # (图片索引, 持续时间)
    for i in range(len(subtitles)):
        idx = subtitles[i][0]
        start = subtitles[i][1]
        end = subtitles[i][2]

        if i < len(subtitles) - 1:
            next_start = subtitles[i + 1][1]
            # 在间隔中间切换：持续到 (当前结束 + 下一开始) / 2
            switch_time = (end + next_start) / 2
            duration = (switch_time - start) / 1000
        else:
            # 最后一句：持续到下一句开始前0.5秒的位置
            # 但这里我们直接用字幕的持续时间
            duration = (end - start) / 1000

        switches.append((idx, duration))
        print(f"\n图片{idx}: 持续 {duration:.2f}s")

    # 创建图片列表文件
    list_file = os.path.join(temp_dir, "image_list.txt")

    with open(list_file, 'w', encoding='utf-8') as f:
        for idx, duration in switches:
            frame_path = os.path.join(frames_dir, f"frame_{idx:03d}.jpg")
            frame_path = frame_path.replace('\\', '/')
            f.write(f"file '{frame_path}'\nduration {duration:.2f}\n")

        # 最后一帧重复一次
        last_idx = switches[-1][0]
        last_duration = switches[-1][1]
        last_frame = os.path.join(frames_dir, f"frame_{last_idx:03d}.jpg")
        last_frame = last_frame.replace('\\', '/')
        f.write(f"file '{last_frame}'\nduration {last_duration:.2f}\n")

    total_duration = sum(d for _, d in switches) * 2
    print(f"\n总时长约: {total_duration:.2f}s")

    # 生成视频
    output_video = "shitu_test_first10.mp4"
    cmd = [
        'ffmpeg', '-y',
        '-f', 'concat',
        '-safe', '0',
        '-i', list_file,
        '-i', mp3_path,
        '-shortest',
        '-c:v', 'libx264',
        '-preset', 'fast',
        '-c:a', 'aac',
        '-ar', '44100',
        '-ac', '1',
        '-pix_fmt', 'yuv420p',
        output_video
    ]

    print("\n合成视频...")
    result = subprocess.run(cmd, capture_output=True, text=True, encoding='utf-8', errors='ignore')

    if result.returncode == 0:
        print(f"完成！视频保存在: {output_video}")
    else:
        print(f"错误: {result.stderr[-800:] if result.stderr else '无错误信息'}")

    conn.close()

except Exception as e:
    print(f"错误: {e}")
