File size: 14,310 Bytes
57c7939
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
#!/usr/bin/env python3
"""Rebuild anchor (edited) audio from native audio + replay manifest.

Reproduces, for each record in ``anchor_manifest.jsonl``, the edit that
produced the anchor recording from its native source:

  addition      overlay sound events at SNR-calibrated volume
  deletion      hard silence or blurred masking of regions
  modification  region-scoped volume or speed change

Only ``ffmpeg``/``ffprobe`` are required. Replay is exact except for
blur_mask, whose rendering params were randomized in the original pipeline
and are replaced with fixed defaults (the masked regions stay exact, which
is what the questions depend on).

Usage:
    python prepare_anchor.py [--manifest metadata/media/anchor/anchor_manifest.jsonl]
                             [--root .] [--only OPERATION] [--overwrite] [--dry-run]
"""

import argparse
import json
import math
import os
import re
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path

def ffprobe_format(path: Path) -> tuple[int, int]:
    """Return (sample_rate, channels) of the first audio stream."""
    proc = subprocess.run(
        ["ffprobe", "-v", "error", "-select_streams", "a:0",
         "-show_entries", "stream=sample_rate,channels",
         "-of", "csv=p=0", str(path)],
        stdout=subprocess.PIPE, stderr=subprocess.PIPE,
    )
    rate, ch = proc.stdout.decode().strip().split(",")
    return int(rate), int(ch)


def read_jsonl(path: Path) -> list[dict]:
    with open(path, encoding="utf-8") as fh:
        return [json.loads(line) for line in fh if line.strip()]


def run(cmd: list[str], dry_run: bool = False) -> None:
    if dry_run:
        print("    [dry-run] " + " ".join(cmd[:8]) + " ...")
        return
    proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if proc.returncode != 0:
        err = proc.stderr.decode("utf-8", errors="replace").strip()
        raise RuntimeError(f"command failed (rc={proc.returncode}): {' '.join(cmd[:6])}...\n{err[-800:]}")


def ffprobe_duration(path: Path) -> float:
    proc = subprocess.run(
        ["ffprobe", "-v", "error", "-show_entries", "format=duration",
         "-of", "default=noprint_wrappers=1:nokey=1", str(path)],
        stdout=subprocess.PIPE, stderr=subprocess.PIPE,
    )
    return float(proc.stdout.decode().strip())


def analyze_rms_db(path: Path, start: float | None = None, dur: float | None = None) -> float:
    """Return RMS loudness (dB) of a file or a region of it."""
    cmd = ["ffmpeg", "-hide_banner", "-loglevel", "info"]
    if start is not None:
        cmd += ["-ss", f"{start}"]
    if dur is not None:
        cmd += ["-t", f"{dur}"]
    cmd += ["-i", str(path), "-af", "volumedetect", "-f", "null", "-"]
    proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    text = proc.stderr.decode("utf-8", errors="replace")
    m = re.search(r"mean_volume: ([-\d.]+) dB", text)
    return float(m.group(1)) if m else -30.0


def out_codec_args(rate: int | None = None, channels: int | None = None) -> list[str]:
    args = ["-c:a", "flac"]
    if rate is not None:
        args += ["-ar", str(rate)]
    if channels is not None:
        args += ["-ac", str(channels)]
    return args


def resolve_event(manifest_path: str, events_dir: Path) -> Path:
    """Map a manifest event path to the local audio/events/ file."""
    return events_dir / Path(manifest_path).name


def replay_addition(rec: dict, native: Path, out: Path, events_dir: Path, dry_run: bool,
                    fmt: tuple[int, int] | None = None) -> None:
    positions = rec["params"]["positions"]
    inputs = ["-i", str(native)]
    filter_parts = []
    mix_inputs = ["[0:a]"]

    for idx, pos in enumerate(positions, start=1):
        event_path = resolve_event(pos["event_audio_path"], events_dir)
        if not event_path.is_file() and not dry_run:
            raise FileNotFoundError(f"event audio missing: {event_path}")
        inputs += ["-i", str(event_path)]

        offset_ms = int(float(pos["position_sec"]) * 1000)
        volume_db = pos.get("volume_db")
        if volume_db is None:
            snr = float(pos["snr_db"])
            region_dur = float(pos.get("duration_sec") or 3.0)
            bg_rms = analyze_rms_db(native, float(pos["position_sec"]), region_dur) if not dry_run else -25.0
            ev_rms = analyze_rms_db(event_path) if not dry_run else -25.0
            volume_db = round((bg_rms + snr) - ev_rms, 1)
            volume_db = max(-30.0, min(30.0, volume_db))

        label = f"evt{idx}"
        filter_parts.append(f"[{idx}:a]adelay={offset_ms}|{offset_ms},volume={volume_db}dB[{label}]")
        mix_inputs.append(f"[{label}]")

    weights = " ".join(["1"] * len(mix_inputs))
    filter_parts.append(
        f"{''.join(mix_inputs)}amix=inputs={len(mix_inputs)}:duration=first"
        f":dropout_transition=0:normalize=0:weights={weights}[mixed]"
    )
    rate, channels = fmt if fmt else (None, None)
    cmd = ["ffmpeg", "-hide_banner", "-loglevel", "error", "-y", *inputs,
           "-filter_complex", ";".join(filter_parts), "-map", "[mixed]",
           *out_codec_args(rate, channels), str(out)]
    run(cmd, dry_run)


def replay_deletion(rec: dict, native: Path, out: Path, dry_run: bool) -> None:
    mask_type = rec["params"].get("mask_type", "hard_mask")
    regions = rec["params"]["regions"]

    if mask_type == "hard_mask":
        filters = [f"volume=enable='between(t,{s},{e})':volume=0" for s, e in regions]
        cmd = ["ffmpeg", "-hide_banner", "-loglevel", "error", "-y", "-i", str(native),
               "-af", ",".join(filters), *out_codec_args(), str(out)]
        run(cmd, dry_run)
        return

    if mask_type == "blur_mask":
        _replay_blur_mask(native, out, regions, dry_run)
        return

    raise ValueError(f"unsupported mask_type: {mask_type}")


def _replay_blur_mask(native: Path, out: Path, regions: list, dry_run: bool) -> None:
    """Deterministic blur mask (original used randomized params; regions are exact)."""
    lowpass_freq = 300
    blur_attenuation_db = -6.0
    noise_level_db = -8.0
    fade_sec = 0.5
    noise_color = "pink"
    dynamic_noise = True
    fluct_db = 3.0
    fluct_rate = 0.8

    blur_gain = 10 ** (blur_attenuation_db / 20)
    noise_gain = 10 ** (noise_level_db / 20)

    if dynamic_noise:
        lo = noise_gain * (10 ** (-fluct_db / 20))
        hi = noise_gain * (10 ** (+fluct_db / 20))
        rng = hi - lo
        r1 = 2 * math.pi * fluct_rate
        r2 = 2 * math.pi * (fluct_rate * 2.3)
        noise_expr = f"{lo:.8f}+({rng:.8f})*(0.5+0.3*sin({r1}*t)+0.2*sin({r2}*t))"
    else:
        noise_expr = f"{noise_gain:.6f}"

    valid = [(float(s), float(e)) for s, e in regions if float(e) > float(s)]
    total_duration = ffprobe_duration(native) if not dry_run else 300.0

    orig_parts, blur_parts = [], []
    for s, e in valid:
        seg_dur = e - s
        eff_fade = min(fade_sec, seg_dur / 2.5)
        fie, fos = s + eff_fade, e - eff_fade
        orig_parts.append(
            f"if(between(t,{s},{fie}),(({fie}-t)/{eff_fade:.4f}),"
            f"if(between(t,{fie},{fos}),0,"
            f"if(between(t,{fos},{e}),((t-{fos})/{eff_fade:.4f}),1)))"
        )
        blur_parts.append(
            f"if(between(t,{s},{fie}),((t-{s})/{eff_fade:.4f}),"
            f"if(between(t,{fie},{fos}),1,"
            f"if(between(t,{fos},{e}),(({e}-t)/{eff_fade:.4f}),0)))"
        )

    if len(valid) == 1:
        orig_env, blur_env = orig_parts[0], blur_parts[0]
    else:
        orig_env, blur_env = "1", "0"
        for i in range(len(valid) - 1, -1, -1):
            s, e = valid[i]
            orig_env = f"if(between(t,{s},{e}),{orig_parts[i]},{orig_env})"
            blur_env = f"if(between(t,{s},{e}),{blur_parts[i]},{blur_env})"

    filter_complex = (
        f"[0:a]asplit=2[orig][to_blur];"
        f"[to_blur]lowpass=f={lowpass_freq},volume={blur_gain:.6f}[blurred];"
        f"[1:a]volume='{noise_expr}':eval=frame[noise_scaled];"
        f"[blurred][noise_scaled]amix=inputs=2:duration=first:weights=3 1[blur_noise];"
        f"[orig]volume='{orig_env}':eval=frame[orig_env];"
        f"[blur_noise]volume='{blur_env}':eval=frame[blur_env];"
        f"[orig_env][blur_env]amix=inputs=2:duration=first:normalize=0[out]"
    )
    cmd = ["ffmpeg", "-hide_banner", "-loglevel", "error", "-y",
           "-i", str(native),
           "-f", "lavfi", "-i",
           f"anoisesrc=color={noise_color}:duration={total_duration:.2f}:sample_rate=16000",
           "-filter_complex", filter_complex, "-map", "[out]",
           *out_codec_args(), str(out)]
    run(cmd, dry_run)


def _atempo_chain(factor: float) -> str:
    parts = []
    remaining = factor
    while remaining > 2.0:
        parts.append("atempo=2.0")
        remaining /= 2.0
    while remaining < 0.5:
        parts.append("atempo=0.5")
        remaining /= 0.5
    parts.append(f"atempo={remaining:.4f}")
    return ",".join(parts)


def replay_modification(rec: dict, native: Path, out: Path, dry_run: bool) -> None:
    kind = rec["params"]["kind"]
    regions = rec["params"]["regions"]

    if kind == "volume":
        filters = []
        for region in regions:
            s, e = region["region_sec"]
            gain = 10 ** (float(region["delta_db"]) / 20)
            filters.append(f"volume=enable='between(t,{s},{e})':volume={gain}")
        cmd = ["ffmpeg", "-hide_banner", "-loglevel", "error", "-y", "-i", str(native),
               "-af", ",".join(filters), *out_codec_args(), str(out)]
        run(cmd, dry_run)
        return

    if kind == "speed":
        _replay_speed(native, out, regions, dry_run)
        return

    raise ValueError(f"unsupported modification kind: {kind}")


def _replay_speed(native: Path, out: Path, regions: list, dry_run: bool) -> None:
    """Apply region-scoped atempo and re-concatenate. Regions use original timeline."""
    total = ffprobe_duration(native) if not dry_run else 600.0
    segs = sorted(regions, key=lambda r: r["region_sec"][0])

    # Build a clip plan: (kind, start, end, factor)
    plan = []
    cursor = 0.0
    for region in segs:
        s, e = region["region_sec"]
        factor = float(region["speed_factor"])
        if s > cursor + 0.05:
            plan.append(("copy", cursor, s, None))
        plan.append(("atempo", s, e, factor))
        cursor = e
    if cursor < total - 0.05:
        plan.append(("copy", cursor, total, None))

    if dry_run:
        print(f"    [dry-run] speed modification: {len(plan)} clips")
        return

    tmpdir = tempfile.mkdtemp(prefix="anchor_speed_")
    try:
        clip_paths = []
        for i, (kind, s, e, factor) in enumerate(plan):
            seg_path = os.path.join(tmpdir, f"seg_{i:03d}.flac")
            extract = ["ffmpeg", "-hide_banner", "-loglevel", "error", "-y",
                       "-ss", f"{s}", "-to", f"{e}", "-i", str(native),
                       *out_codec_args(), seg_path]
            run(extract)
            if kind == "atempo":
                tempo_path = os.path.join(tmpdir, f"seg_{i:03d}_tempo.flac")
                run(["ffmpeg", "-hide_banner", "-loglevel", "error", "-y",
                     "-i", seg_path, "-af", _atempo_chain(factor),
                     *out_codec_args(), tempo_path])
                clip_paths.append(tempo_path)
            else:
                clip_paths.append(seg_path)

        concat_list = os.path.join(tmpdir, "concat.txt")
        with open(concat_list, "w", encoding="utf-8") as fh:
            for p in clip_paths:
                fh.write(f"file '{p}'\n")
        run(["ffmpeg", "-hide_banner", "-loglevel", "error", "-y",
             "-f", "concat", "-safe", "0", "-i", concat_list,
             *out_codec_args(), str(out)])
    finally:
        shutil.rmtree(tmpdir, ignore_errors=True)


def process_record(rec: dict, root: Path, overwrite: bool, dry_run: bool) -> str:
    media_id = rec["media_id"]
    operation = rec["operation"]
    native = root / "audio" / "native" / Path(rec["native_audio_path"]).name
    out = root / "audio" / "anchor" / Path(rec["target_audio_path"]).name
    events_dir = root / "audio" / "events"

    if out.is_file() and not overwrite and not dry_run:
        return "skip"
    if not native.is_file() and not dry_run:
        return "missing-native"

    out.parent.mkdir(parents=True, exist_ok=True)
    if operation == "addition":
        fmt = None if dry_run else ffprobe_format(native)
        replay_addition(rec, native, out, events_dir, dry_run, fmt)
    elif operation == "deletion":
        replay_deletion(rec, native, out, dry_run)
    elif operation == "modification":
        replay_modification(rec, native, out, dry_run)
    else:
        return f"unknown-operation:{operation}"
    return "ok"


def main():
    parser = argparse.ArgumentParser(description="Rebuild anchor audio from manifest")
    parser.add_argument("--manifest", default="metadata/media/anchor/anchor_manifest.jsonl")
    parser.add_argument("--root", default=".", help="release root (contains audio/ + prepare/)")
    parser.add_argument("--only", choices=["addition", "deletion", "modification"],
                        help="process only this operation")
    parser.add_argument("--overwrite", action="store_true")
    parser.add_argument("--dry-run", action="store_true")
    parser.add_argument("--limit", type=int, default=0, help="process at most N records (debug)")
    args = parser.parse_args()

    root = Path(args.root).resolve()
    manifest_path = root / args.manifest
    if not manifest_path.is_file():
        print(f"ERROR: manifest not found: {manifest_path}", file=sys.stderr)
        sys.exit(1)

    records = read_jsonl(manifest_path)
    if args.only:
        records = [r for r in records if r["operation"] == args.only]
    if args.limit:
        records = records[:args.limit]

    print(f"Processing {len(records)} anchor records (root={root})")
    counts = {}
    for rec in records:
        status = process_record(rec, root, args.overwrite, args.dry_run)
        counts[status] = counts.get(status, 0) + 1
        if status not in ("ok", "skip"):
            print(f"  [{status}] {rec['media_id']} ({rec['operation']})")

    print("Summary:", counts)


if __name__ == "__main__":
    main()