#ビデオから無音部分を削除して新しいビデオを作る
import subprocess
import re
import json
import os
import glob

SILENCE_THRESHOLD = "-30dB"
SILENCE_DURATION = 1.0
INPUT = "1.mp4"
for name in glob.glob('*.mp4'):
  INPUT=name
  w= name.split(".")
  OUTPUT=w[0]+"_r.mp4"

# --- Step 1: 無音区間検出 ---
cmd = [
    "ffmpeg", "-i", INPUT,
    "-af", f"silencedetect=noise={SILENCE_THRESHOLD}:d={SILENCE_DURATION}",
    "-f", "null", "-"
]
result = subprocess.run(cmd, stderr=subprocess.PIPE, text=True)
log = result.stderr

silence_starts = [float(x) for x in re.findall(r"silence_start: ([0-9\.]+)", log)]
silence_ends   = [float(x) for x in re.findall(r"silence_end: ([0-9\.]+)", log)]

# --- Step 2: 動画全体の長さ ---
probe = subprocess.run(
    ["ffprobe", "-v", "quiet", "-print_format", "json", "-show_format", INPUT],
    stdout=subprocess.PIPE, text=True
)
duration = float(json.loads(probe.stdout)["format"]["duration"])

# --- Step 3: 無音以外の区間を作成 ---
segments = []
cursor = 0.0
for start, end in zip(silence_starts, silence_ends):
    if cursor < start:
        segments.append((cursor, start))
    cursor = end
if cursor < duration:
    segments.append((cursor, duration))

# --- Step 4: 一時ファイルに切り出し ---
temp_files = []
for i, (s, e) in enumerate(segments):
    temp = f"part_{i}.mp4"
    temp_files.append(temp)
    subprocess.run([
        "ffmpeg", "-y",
        "-i", INPUT,
        "-ss", str(s),
        "-to", str(e),
        "-c", "copy",
        temp
], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)

# --- Step 5: concat用リスト作成 ---
with open("list.txt", "w") as f:
    for t in temp_files:
        f.write(f"file '{t}'\n")

# --- Step 6: 結合 ---
subprocess.run([
    "ffmpeg", "-y",
    "-f", "concat",
    "-safe", "0",
    "-i", "list.txt",
    "-c", "copy",
    OUTPUT
], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)


# --- Step 7: 一時ファイル削除 ---
for t in temp_files:
    os.remove(t)
os.remove("list.txt")

print("完了:", OUTPUT)