#!/usr/bin/env python3 # Movie RandomEdit # 指定したフォルダのすべてのムービーを 1 本のタイムラインとみなし、2 → 32 → 2 フレームと # 経過時間に応じてカットの長さを等比的に伸び縮みさせながら、ランダムな位置のカットを繋ぐ(全体で約2分)。 # 各カットの先頭で、テレメトリー(速度・振動・勾配・傾き)から決めた短い減衰音を鳴らす。 # 使用済みフレームは全フレームを使い切るまで再使用しない。実行するたびに結果が変わる。 # # 使い方: python3 movie_randomedit.py # 必要なもの: Homebrew の ffmpeg(brew install ffmpeg)。Python は標準ライブラリのみ。 # 中断に強い分割実行: BUDGET=秒数 JOB=名前 を付けると、時間内に進めて途中経過を保存し、再実行で続きから進む。 import json, os, sys, subprocess, shutil, time, wave, random, bisect, math, array, struct, datetime from fractions import Fraction from concurrent.futures import ThreadPoolExecutor # ---- 設定 MIN_LEN = 2 # 最初と最後のカットのフレーム数 PEAK = 32 # 最長カットのフレーム数 EASE = 1.1 # 1 = 一定の比率。大きいほど短いカットの状態が長く続き、後半で速く伸びる TARGET_SEC = float(os.environ.get("TARGET_SEC", "120")) # 全体の目標の長さ(秒) TONE_FRAMES = 4; DECAY_DB = 60; AR = 48000 SNAP_FRAMES = 8 # 本来のクリップ長がこのフレーム数以上なら、音を映像の切り替わりに合わせる SINE_RATIO, NOISE_RATIO = 7, 1 NOTES = [m for m in range(48, 85) if m % 12 in (0, 2, 4, 5, 7, 9, 11)] # C3〜C6 の白鍵 SPEED_PCT = (5, 95); SINE_VOL = (0.25, 0.50); GRADE_RANGE = (-0.06, 0.06) NOISE_VOL = (0.125, 0.25); PAN_DEG = 15.0 HERE = os.path.dirname(os.path.abspath(__file__)) SRC = os.environ.get("SRC", "ムービーを格納したフォルダのパス名") TMP = os.environ.get("TMP_DIR", os.path.join(HERE, "_tmp")) JOB = os.environ.get("JOB", time.strftime("%Y%m%d_%H%M%S")) JOBDIR = os.path.join(TMP, "curve_" + JOB) OUT = os.environ.get("OUT", os.path.join(HERE, "Movie_RandomEdit_%s.mov" % JOB)) ENC = os.environ.get("ENC", "videotoolbox") # Mac 以外では libx265 BITRATE = os.environ.get("BITRATE", "40M") # 映像の平均ビットレート(小さいほどファイルが小さい) QUALITY = os.environ.get("QUALITY", "") # 指定すると品質固定モード(1-100)で書き出す BUDGET = float(os.environ.get("BUDGET", "0")) # 0 = 一度に最後まで T0 = time.time() EXTS = (".mp4", ".mov") def find(tool): for c in (shutil.which(tool), "/opt/homebrew/bin/" + tool, "/usr/local/bin/" + tool): if c and os.path.exists(c): return c sys.exit(tool + " が見つかりません。 brew install ffmpeg を実行してください。") FFMPEG, FFPROBE = find("ffmpeg"), find("ffprobe") _probe = subprocess.run([FFMPEG, "-v", "error", "-nostdin", "-f", "lavfi", "-i", "nullsrc=s=16x16", "-frames:v", "1", "-fps_mode", "passthrough", "-f", "null", "-"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) VSYNC = ["-fps_mode", "passthrough"] if _probe.returncode == 0 else ["-vsync", "passthrough"] NAMES = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"] def note_name(m): return "%s%d" % (NAMES[m % 12], m // 12 - 1) os.makedirs(JOBDIR, exist_ok=True) # =============== 1. 素材の調査 =============== files = sorted(os.path.join(SRC, f) for f in os.listdir(SRC) if f.lower().endswith(EXTS) and not f.startswith(".")) if not files: sys.exit("ムービーが見つかりません: " + SRC) info_path = os.path.join(JOBDIR, "sources.json") if os.path.exists(info_path): info = json.load(open(info_path)) else: info = [] for f in files: r = subprocess.run([FFPROBE, "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height,r_frame_rate,nb_frames,color_range,color_primaries,color_transfer,color_space", "-of", "json", f], stdout=subprocess.PIPE, check=True) s = json.loads(r.stdout)["streams"][0] if not s.get("nb_frames") or s["nb_frames"] == "N/A": r = subprocess.run([FFPROBE, "-v", "error", "-select_streams", "v:0", "-count_packets", "-show_entries", "stream=nb_read_packets", "-of", "csv=p=0", f], stdout=subprocess.PIPE, check=True) s["nb_frames"] = r.stdout.decode().strip() info.append(s) json.dump(info, open(info_path, "w")) W, H, FPS = info[0]["width"], info[0]["height"], info[0]["r_frame_rate"] for f, s in zip(files, info): if (s["width"], s["height"], s["r_frame_rate"]) != (W, H, FPS): sys.exit("解像度かフレームレートが異なる素材があります: " + f) FR = Fraction(FPS); counts = [int(s["nb_frames"]) for s in info] offs = [0] for c in counts: offs.append(offs[-1] + c) TOTAL = offs[-1]; FS = W * H * 3 // 2 COL = {k: info[0].get(k) for k in ("color_range", "color_primaries", "color_transfer", "color_space")} FULL = COL["color_range"] == "pc" # =============== 2. カットの長さと位置 =============== def schedule(): # 本来の(丸める前の)クリップ長: 上りの経過時間 t(フレーム単位の実数)に対して # ℓ(t) = MIN_LEN × (PEAK/MIN_LEN)^((t/T)^EASE) # 本来のクリップの境界 τ を実数で求め、映像のカットはその境界を最も近いフレームに丸めて作る。 # 音は、本来のクリップ長が SNAP_FRAMES 未満なら本来の境界 τ(サンプル単位)で鳴らし、 # それ以上なら映像の切り替わり(丸めたフレーム)に合わせて鳴らす。下りは上りの鏡像。 r = PEAK / MIN_LEN def up_for(T): taus = [0.0]; ells = []; t = 0.0 while t < T: ell = MIN_LEN * r ** (min(1.0, t / T) ** EASE) if ell >= PEAK: break ells.append(ell); t += ell; taus.append(t) return taus, ells def rnd(x): return int(math.floor(x + 0.5)) def total_for(T): taus, _ = up_for(T); return 2 * rnd(taus[-1]) + PEAK target = TARGET_SEC * float(FR); lo, hi = 10.0, 100000.0; best = None for _ in range(80): T = (lo + hi) / 2; tot = total_for(T) if best is None or abs(tot - target) < abs(best[0] - target): best = (tot, T) if tot < target: lo = T else: hi = T tot, T = best taus, ells = up_for(T); B = [rnd(x) for x in taus]; U = B[-1] up_sizes = [B[i + 1] - B[i] for i in range(len(ells))] sizes = up_sizes + [PEAK] + up_sizes[::-1] onsets, ideal = [], [] for i, ell in enumerate(ells): # 上り onsets.append(float(B[i]) if ell >= SNAP_FRAMES else taus[i]); ideal.append(ell) onsets.append(float(U)); ideal.append(float(PEAK)) # 最長のクリップ for i in reversed(range(len(ells))): # 下り(鏡像) q, f = tot - B[i + 1], tot - taus[i + 1] onsets.append(float(q) if ells[i] >= SNAP_FRAMES else f); ideal.append(ells[i]) return sizes, onsets, ideal, r ** (float(FR) / T) # 比率は「1秒あたりの平均の伸び率」 plan_path = os.path.join(JOBDIR, "plan.json") if os.path.exists(plan_path): plan = json.load(open(plan_path)) else: sizes, onsets, ideal, ratio = schedule() rng = random.SystemRandom(); gaps = [(0, TOTAL)]; resets = 0 def take(size): global gaps, resets w = [max(0, l - size + 1) for _, l in gaps] if sum(w) == 0: gaps = [(0, TOTAL)]; resets += 1; w = [TOTAL - size + 1] cum = []; t = 0 for x in w: t += x; cum.append(t) rr = rng.randrange(t); gi = bisect.bisect_right(cum, rr); off = rr - (cum[gi - 1] if gi else 0) g0, gl = gaps[gi]; pos = g0 + off; new = [] if off > 0: new.append((g0, off)) if gl - off - size > 0: new.append((pos + size, gl - off - size)) gaps[gi:gi + 1] = new return pos plan = {"files": [os.path.basename(f) for f in files], "counts": counts, "fps": FPS, "ratio": ratio, "resets": resets, "segments": [{"size": s, "start": take(s), "onset": round(o, 4), "ideal_size": round(l, 4)} for s, o, l in zip(sizes, onsets, ideal)]} plan["resets"] = resets json.dump(plan, open(plan_path, "w")) segs = plan["segments"] nout = sum(g["size"] for g in segs) print("カット %d 個 / %d フレーム(%.1f 秒) カットの長さは 1 秒あたり平均 %.3f 倍で変化" % (len(segs), nout, nout / float(FR), plan["ratio"]), flush=True) def pieces(start, size): out = [] while size > 0: fi = bisect.bisect_right(offs, start) - 1; loc = start - offs[fi]; n = min(size, counts[fi] - loc) out.append((fi, loc, n)); start += n; size -= n return out def over_budget(margin): return BUDGET and time.time() - T0 > BUDGET - margin # =============== 3. テレメトリー =============== FMT = {'b': 'b', 'B': 'B', 's': 'h', 'S': 'H', 'l': 'i', 'L': 'I', 'f': 'f', 'd': 'd', 'j': 'q', 'J': 'Q'} def klv(b): i = 0 while i + 8 <= len(b): k = b[i:i + 4].decode("latin1"); t = chr(b[i + 4]); s = b[i + 5]; r = struct.unpack(">H", b[i + 6:i + 8])[0] n = s * r; yield k, t, s, r, b[i + 8:i + 8 + n] i += 8 + ((n + 3) // 4) * 4 def parse_gpmf(data): pkts = [] for k, t, s, r, body in klv(data): if k != "DEVC": continue pk = {} for k2, _, _, _, b2 in klv(body): if k2 != "STRM": continue scal = [1]; typ = None for kk, tt, ss, rr, bb in klv(b2): if kk == "SCAL": w = {1: 'b', 2: 'h', 4: 'i'}[ss] if tt in 'bsl' else {1: 'B', 2: 'H', 4: 'I'}[ss] scal = [struct.unpack(">" + w, bb[i * ss:(i + 1) * ss])[0] for i in range(rr)] elif kk == "TYPE": typ = bb.decode("latin1").strip("\0") elif kk in ("GPS9", "GPS5", "ACCL", "GRAV"): f = ">" + ("".join(FMT[c] for c in typ) if tt == "?" else FMT[tt] * (ss // struct.calcsize(FMT[tt]))) vals = [] for i in range(rr): v = struct.unpack(f, bb[i * ss:(i + 1) * ss]) sc = scal if len(scal) == len(v) else [scal[0]] * len(v) vals.append([x / c for x, c in zip(v, sc)]) pk[kk] = vals pkts.append(pk) return pkts def load_telemetry(path, nframes): cp = os.path.join(TMP, os.path.basename(path) + ".telemetry.json") if os.path.exists(cp): return json.load(open(cp)) print("テレメトリー読み込み: " + os.path.basename(path), flush=True) r = subprocess.run([FFPROBE, "-v", "error", "-show_entries", "stream=index,codec_tag_string", "-of", "json", path], stdout=subprocess.PIPE, check=True) idx = [s["index"] for s in json.loads(r.stdout)["streams"] if s.get("codec_tag_string") == "gpmd"] if not idx: return None r = subprocess.run([FFMPEG, "-v", "error", "-nostdin", "-i", path, "-map", "0:%d" % idx[0], "-c", "copy", "-f", "data", "-"], stdout=subprocess.PIPE, check=True) pkts = parse_gpmf(r.stdout) def per_frame(key, width): samples = []; P = len(pkts) for pi, pk in enumerate(pkts): vs = pk.get(key, []) for j, v in enumerate(vs): samples.append(((pi + j / len(vs)) / P, v[:width])) if not samples: return [None] * nframes ts = [s[0] for s in samples] return [samples[min(bisect.bisect_left(ts, (f + 0.5) / nframes), len(samples) - 1)][1] for f in range(nframes)] gkey = "GPS9" if any("GPS9" in p for p in pkts) else "GPS5" tel = {"gps": per_frame(gkey, 9), "accl": per_frame("ACCL", 3), "grav": per_frame("GRAV", 3), "gps_type": gkey} json.dump(tel, open(cp, "w")) return tel def median(xs): s = sorted(xs); n = len(s) return s[n // 2] if n % 2 else 0.5 * (s[n // 2 - 1] + s[n // 2]) def fill(xs): idx = [i for i, x in enumerate(xs) if x is not None] if not idx: return [0.0] * len(xs) out = list(xs) for i in range(len(xs)): if out[i] is None: j = bisect.bisect_left(idx, i) if j == 0: out[i] = xs[idx[0]] elif j == len(idx): out[i] = xs[idx[-1]] else: a, b = idx[j - 1], idx[j]; out[i] = xs[a] + (xs[b] - xs[a]) * (i - a) / (b - a) return out def median_filter(xs, w): h = w // 2; return [median(xs[max(0, i - h):i + h + 1]) for i in range(len(xs))] def moving_mean(xs, w): h = w // 2; c = [0.0] for x in xs: c.append(c[-1] + x) return [(c[min(len(xs), i + h + 1)] - c[max(0, i - h)]) / (min(len(xs), i + h + 1) - max(0, i - h)) for i in range(len(xs))] def hav(a, b): R = 6371000.0; la1, lo1, la2, lo2 = map(math.radians, (a[0], a[1], b[0], b[1])) return 2 * R * math.asin(min(1.0, math.sqrt(math.sin((la2 - la1) / 2) ** 2 + math.cos(la1) * math.cos(la2) * math.sin((lo2 - lo1) / 2) ** 2))) def derive(tel, fps): n = len(tel["gps"]); g = tel["gps"]; nine = tel["gps_type"] == "GPS9" spf = 1.0 / fps # 1フレームあたりの実時間(TimeWarp 等では長くなる)を GPS 時刻から求める if nine: d = [(g[i + 30][6] - g[i][6]) / 30 for i in range(0, n - 30, 30) if g[i] and g[i + 30] and g[i][5] == g[i + 30][5] and g[i][8] >= 2 and g[i + 30][8] >= 2] d = [x for x in d if x > 0] if d: spf = median(d) fps = 1.0 / spf; w = int(round(fps)) | 1; h = max(1, w // 2) ok = [] for i, v in enumerate(g): good = v is not None and (not nine or (v[8] >= 3 and v[7] < 5.0)) and v[3] * 3.6 <= 60 if good: a, b = g[max(0, i - h)], g[min(n - 1, i + h)] dt = (min(n - 1, i + h) - max(0, i - h)) / fps good = a is not None and b is not None and dt > 0 and abs(hav(a, b) / dt - v[3]) * 3.6 <= 10 ok.append(good) spd = median_filter(fill([v[3] if o else None for v, o in zip(g, ok)]), w) alt = moving_mean(median_filter(fill([v[2] if o else None for v, o in zip(g, ok)]), w), 5 * w) dist = [0.0] for s_ in spd: dist.append(dist[-1] + s_ / fps) HH = int(round(10 * fps)); grade = [] for i in range(n): a, b = max(0, i - HH), min(n - 1, i + HH); d = dist[b] - dist[a] grade.append(max(-0.15, min(0.15, (alt[b] - alt[a]) / d)) if d > 30.0 else 0.0) acc = [math.sqrt(sum(c * c for c in v)) if v else 0.0 for v in tel["accl"]] hp = [a - m for a, m in zip(acc, moving_mean(acc, 15))] vib = [math.sqrt(x) for x in moving_mean([x * x for x in hp], 9)] roll = [math.degrees(math.atan2(v[0], v[1])) if v else 0.0 for v in tel["grav"]] r0 = median(roll); roll = moving_mean([r - r0 for r in roll], 9) times = [] for v in g: if nine and v is not None and v[5] > 0: t = datetime.datetime(2000, 1, 1) + datetime.timedelta(days=v[5], seconds=v[6], hours=9) times.append(t.strftime("%Y-%m-%d %H:%M:%S")) else: times.append(None) return {"speed": spd, "grade": grade, "vib": vib, "roll": roll, "time": times} # =============== 4. 映像(分割して書き出し、最後に連結) =============== state_path = os.path.join(JOBDIR, "state.json") state = json.load(open(state_path)) if os.path.exists(state_path) else {"seg": 0, "chunk": 0} def decode_cmd(fi, loc, n): t = max(0.0, float((loc - Fraction(1, 2)) / FR)) return [FFMPEG, "-v", "error", "-nostdin", "-ss", "%.6f" % t, "-i", files[fi], "-map", "0:v:0", "-frames:v", str(n)] + VSYNC + [ "-f", "rawvideo", "-pix_fmt", "yuvj420p" if FULL else "yuv420p", "-"] def read_piece(fi, loc, n): r = subprocess.run(decode_cmd(fi, loc, n), stdout=subprocess.PIPE, stderr=subprocess.PIPE) if r.returncode != 0 or len(r.stdout) != FS * n: raise RuntimeError("デコード失敗 %s frame %d n %d: %s" % (files[fi], loc, n, r.stderr.decode()[-300:])) return r.stdout PREFETCH_FRAMES = int(os.environ.get("PREFETCH_FRAMES", "24")); STREAM_OVER = 8 def stream_piece(fi, loc, n, dst): p = subprocess.Popen(decode_cmd(fi, loc, n), stdout=subprocess.PIPE, stderr=subprocess.PIPE) got = 0 while True: b = p.stdout.read(FS) if not b: break dst.write(b); got += len(b) err = p.stderr.read(); p.wait() if p.returncode != 0 or got != FS * n: raise RuntimeError("デコード失敗 %s frame %d n %d: %s" % (files[fi], loc, n, err.decode()[-300:])) if ENC == "videotoolbox": venc = ["-c:v", "hevc_videotoolbox"] + (["-q:v", QUALITY] if QUALITY else ["-b:v", BITRATE, "-maxrate", BITRATE, "-bufsize", BITRATE]) + ["-tag:v", "hvc1"] else: venc = ["-c:v", "libx265", "-preset", os.environ.get("PRESET", "ultrafast"), "-crf", "18", "-tag:v", "hvc1", "-x265-params", "log-level=error"] tags = []; params = ["range=%s" % ("full" if FULL else "limited")] for opt, key, p in (("-color_primaries", "color_primaries", "color_primaries"), ("-color_trc", "color_transfer", "color_trc"), ("-colorspace", "color_space", "colorspace")): if COL[key] and COL[key] != "unknown": tags += [opt, COL[key]]; params.append("%s=%s" % (p, COL[key])) pool = ThreadPoolExecutor(max_workers=4) while state["seg"] < len(segs): if over_budget(60): print("途中経過を保存しました(%d/%d カット)。もう一度実行すると続きから進みます。" % (state["seg"], len(segs))); sys.exit(0) ci = state["chunk"]; cpath = os.path.join(JOBDIR, "v%04d.mp4" % ci) enc = subprocess.Popen([FFMPEG, "-v", "error", "-nostdin", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-s", "%dx%d" % (W, H), "-framerate", FPS, "-i", "-", "-vf", "setparams=" + ":".join(params)] + venc + ["-color_range", "pc" if FULL else "tv"] + tags + [cpath + ".tmp.mp4"], stdin=subprocess.PIPE) si = state["seg"]; jobs = [] while si < len(segs): jobs.append((si, pieces(segs[si]["start"], segs[si]["size"]))); si += 1 fut = {}; done = state["seg"]; flat = [(s, p) for s, ps in jobs for p in ps] for j, (s, pc) in enumerate(flat): # 先読みはメモリを抑えるため合計 PREFETCH_FRAMES フレームまで。長いピースは先読みせず直接流す pend = sum(flat[k][1][2] for k in fut) for k in range(j + 1, min(j + 8, len(flat))): if k in fut: continue if flat[k][1][2] > STREAM_OVER or pend + flat[k][1][2] > PREFETCH_FRAMES: break fut[k] = pool.submit(read_piece, *flat[k][1]); pend += flat[k][1][2] if j in fut: enc.stdin.write(fut.pop(j).result()) else: stream_piece(*pc, enc.stdin) last_of_seg = j + 1 == len(flat) or flat[j + 1][0] != s if last_of_seg: done = s + 1 if over_budget(60): break for f_ in fut.values(): f_.cancel() enc.stdin.close() if enc.wait() != 0: sys.exit("エンコード失敗") os.rename(cpath + ".tmp.mp4", cpath) state = {"seg": done, "chunk": ci + 1}; json.dump(state, open(state_path, "w")) print("映像 %d/%d カット 経過 %.0f秒" % (done, len(segs), time.time() - T0), flush=True) # =============== 5. 音声(元の音声 + テレメトリーの減衰音) =============== if over_budget(50): print("映像は完了。もう一度実行すると音声と連結に進みます。"); sys.exit(0) used_files = sorted({bisect.bisect_right(offs, g["start"]) - 1 for g in segs}) derived = {} for fi in used_files: tel = load_telemetry(files[fi], counts[fi]) if tel: derived[fi] = derive(tel, float(FR)) events = []; k = 0 for g in segs: fi = bisect.bisect_right(offs, g["start"]) - 1; loc = g["start"] - offs[fi] e = {"frame": k, "onset_frame": g["onset"], "size": g["size"], "ideal_size": g["ideal_size"], "source": os.path.basename(files[fi]), "source_frame": loc} D = derived.get(fi) if D: end = min(counts[fi], loc + max(g["size"], TONE_FRAMES)) e.update({"time": D["time"][loc], "speed_kmh": round(D["speed"][loc] * 3.6, 1), "grade_pct": round(D["grade"][loc] * 100, 1), "vibration": round(sum(D["vib"][loc:end]) / (end - loc), 4), "roll_deg": round(D["roll"][loc], 1)}) else: e.update({"time": None, "speed_kmh": 0.0, "grade_pct": 0.0, "vibration": 0.0, "roll_deg": 0.0}) events.append(e); k += g["size"] N = len(events); n_noise = round(N * NOISE_RATIO / (SINE_RATIO + NOISE_RATIO)) order = sorted(range(N), key=lambda i: events[i]["vibration"], reverse=True); noise_set = set(order[:n_noise]) nv = [events[i]["vibration"] for i in noise_set] or [0]; nlo, nhi = min(nv), max(nv) sp = sorted(events[i]["speed_kmh"] for i in range(N) if i not in noise_set) def pct(p): return sp[min(len(sp) - 1, int(round(p / 100 * (len(sp) - 1))))] slo, shi = pct(SPEED_PCT[0]), pct(SPEED_PCT[1]) def lerp(a, b, t): return a + (b - a) * max(0.0, min(1.0, t)) for i, e in enumerate(events): e["pan"] = round(max(-1.0, min(1.0, e["roll_deg"] / PAN_DEG)), 3) if i in noise_set: e["type"] = "noise"; e["volume"] = round(lerp(NOISE_VOL[0], NOISE_VOL[1], (e["vibration"] - nlo) / (nhi - nlo or 1)), 3) else: e["type"] = "sine"; m = NOTES[int(round(lerp(0, 1, (e["speed_kmh"] - slo) / (shi - slo or 1)) * (len(NOTES) - 1)))] e["midi"] = m; e["note"] = note_name(m) e["volume"] = round(lerp(SINE_VOL[0], SINE_VOL[1], (e["grade_pct"] / 100 - GRADE_RANGE[0]) / (GRADE_RANGE[1] - GRADE_RANGE[0])), 3) def sample_at(k): return int(round(k * AR / FR)) total = sample_at(nout) L_ = array.array("f", bytes(4 * total)); R_ = array.array("f", bytes(4 * total)) # 元の音声(カットと同じ区間) for i, f in enumerate(files): a = os.path.join(TMP, "%s.raw" % os.path.basename(f)) if i in used_files and not os.path.exists(a): print("音声抽出 " + os.path.basename(f), flush=True) r = subprocess.run([FFMPEG, "-v", "error", "-nostdin", "-y", "-i", f, "-map", "0:a:0?", "-ac", "2", "-ar", str(AR), "-f", "s16le", a + ".tmp"]) if r.returncode != 0 or not os.path.exists(a + ".tmp"): open(a + ".tmp", "wb").close() os.rename(a + ".tmp", a) afh = {i: open(os.path.join(TMP, "%s.raw" % os.path.basename(files[i])), "rb") for i in used_files} K = 0 for g in segs: for fi, loc, n in pieces(g["start"], g["size"]): cnt = sample_at(K + n) - sample_at(K); afh[fi].seek(sample_at(loc) * 4); b = afh[fi].read(cnt * 4) if b: pcm = array.array("h"); pcm.frombytes(b[:len(b) // 4 * 4]); s0 = sample_at(K) for j in range(len(pcm) // 2): L_[s0 + j] += pcm[2 * j] / 32767.0; R_[s0 + j] += pcm[2 * j + 1] / 32767.0 K += n # 減衰音 rng = random.Random() for e in events: s0 = int(round(e["onset_frame"] * AR / FR)); n = min(sample_at(TONE_FRAMES), total - s0) rate = -DECAY_DB / 20 * math.log(10) / n th = (e["pan"] + 1) * math.pi / 4; gl, gr = min(1.0, math.cos(th) * math.sqrt(2)), min(1.0, math.sin(th) * math.sqrt(2)) vol = e["volume"] if e["type"] == "sine": w = 2 * math.pi * 440.0 * 2 ** ((e["midi"] - 69) / 12) / AR for i in range(n): x = vol * math.exp(rate * i) * math.sin(w * i); L_[s0 + i] += gl * x; R_[s0 + i] += gr * x else: for i in range(n): x = vol * math.exp(rate * i) * rng.uniform(-1.0, 1.0); L_[s0 + i] += gl * x; R_[s0 + i] += gr * x pcm = array.array("h", bytes(4 * total)) for i in range(total): pcm[2 * i] = max(-32767, min(32767, int(round(L_[i] * 32767)))); pcm[2 * i + 1] = max(-32767, min(32767, int(round(R_[i] * 32767)))) wav_path = os.path.join(JOBDIR, "audio.wav") with wave.open(wav_path, "wb") as w_: w_.setnchannels(2); w_.setsampwidth(2); w_.setframerate(AR); w_.writeframes(pcm.tobytes()) # =============== 6. 連結と書き出し =============== lst = os.path.join(JOBDIR, "list.txt") with open(lst, "w") as f: for ci in range(state["chunk"]): f.write("file '%s'\n" % os.path.join(JOBDIR, "v%04d.mp4" % ci).replace("'", "'\\''")) subprocess.run([FFMPEG, "-v", "error", "-nostdin", "-y", "-f", "concat", "-safe", "0", "-i", lst, "-i", wav_path, "-map", "0:v", "-map", "1:a", "-c:v", "copy", "-tag:v", "hvc1", "-c:a", "aac", "-b:a", "256k", "-movflags", "+faststart", OUT], check=True) base = os.path.splitext(OUT)[0] shutil.copy(plan_path, base + "_plan.json") json.dump({"speed_range_kmh": [slo, shi], "ratio": plan["ratio"], "events": events}, open(base + "_events.json", "w"), ensure_ascii=False, indent=1) shutil.rmtree(JOBDIR) print("完了: %s (%d カット / %d フレーム / %.1f 秒)" % (OUT, len(segs), nout, nout / float(FR)))