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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
"""
Clip editing helpers for trim/split/merge/caption/export workflows.
"""

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, List, Optional
import subprocess
import tempfile
import threading
import unicodedata
import uuid

from .caption_templates import get_template
from .workflows.language import is_no_space
from .media.ffmpeg import ffmpeg_escape_filter_path, ffprobe_video_size
from .media.source_limits import FPS_EPSILON, MAX_OUTPUT_FPS, probe_video_geometry
from .video_utils import (
    ass_fonts_dir,
    build_assemblyai_ass_subtitles,
    get_words_for_keep_ranges,
    get_words_in_range,
    load_cached_transcript_data,
)


@dataclass
class ExportPreset:
    name: str
    width: int
    height: int
    video_bitrate: str
    audio_bitrate: str


EXPORT_PRESETS = {
    "tiktok": ExportPreset("tiktok", 1080, 1920, "10M", "192k"),
    "reels": ExportPreset("reels", 1080, 1920, "12M", "192k"),
    "shorts": ExportPreset("shorts", 1080, 1920, "10M", "192k"),
}


def _safe_name(prefix: str) -> str:
    return f"{prefix}_{uuid.uuid4().hex[:12]}.mp4"


def _run(command: list[str]) -> None:
    subprocess.run(command, check=True, capture_output=True, text=True)


def _ffprobe_duration(path: Path) -> float:
    result = subprocess.run(
        [
            "ffprobe",
            "-v",
            "error",
            "-show_entries",
            "format=duration",
            "-of",
            "default=noprint_wrappers=1:nokey=1",
            str(path),
        ],
        check=True,
        capture_output=True,
        text=True,
    )
    return max(0.0, float(result.stdout.strip()))


def _ffprobe_size(path: Path) -> tuple[int, int]:
    """Displayed pixel size of the first video stream.

    Caption play resolution and editor scale filters run after ffmpeg's
    default autorotate, so this is the same size ``ffprobe_video_size`` returns.
    """
    return ffprobe_video_size(path)


def _double_bitrate(value: str) -> str:
    normalized = value.strip().lower()
    if normalized.endswith("m"):
        return f"{int(float(normalized[:-1]) * 2)}M"
    if normalized.endswith("k"):
        return f"{int(float(normalized[:-1]) * 2)}k"
    return value


def _encode_args(audio_bitrate: str = "256k") -> list[str]:
    return [
        "-c:v",
        "libx264",
        "-preset",
        "slow",
        "-crf",
        "18",
        "-pix_fmt",
        "yuv420p",
        "-profile:v",
        "high",
        "-c:a",
        "aac",
        "-b:a",
        audio_bitrate,
        "-movflags",
        "+faststart",
    ]


def _ass_timestamp(seconds: float) -> str:
    seconds = max(0.0, seconds)
    hours = int(seconds // 3600)
    minutes = int((seconds % 3600) // 60)
    secs = seconds - (hours * 3600) - (minutes * 60)
    return f"{hours}:{minutes:02d}:{secs:05.2f}"


def _ass_color(hex_color: str) -> str:
    value = (hex_color or "#FFFFFF").strip().lstrip("#")
    if len(value) != 6:
        value = "FFFFFF"
    red, green, blue = value[0:2], value[2:4], value[4:6]
    return f"&H00{blue}{green}{red}&"


def _escape_ass_text(value: str) -> str:
    return value.replace("\\", "\\\\").replace("{", "\\{").replace("}", "\\}")


def _escape_filter_path(path: Path) -> str:
    return ffmpeg_escape_filter_path(path)


def trim_clip_file(
    input_path: Path, output_dir: Path, start_offset: float, end_offset: float
) -> Path:
    output_dir.mkdir(parents=True, exist_ok=True)
    output_path = output_dir / _safe_name("trim")
    duration = _ffprobe_duration(input_path)
    start = max(0.0, start_offset)
    end = max(start + 0.1, duration - max(end_offset, 0.0))
    end = min(end, duration)

    _run(
        [
            "ffmpeg",
            "-y",
            "-ss",
            f"{start:.3f}",
            "-i",
            str(input_path),
            "-t",
            f"{end - start:.3f}",
            *_encode_args(),
            str(output_path),
        ]
    )
    return output_path


def split_clip_file(
    input_path: Path, output_dir: Path, split_time: float
) -> tuple[Path, Path]:
    output_dir.mkdir(parents=True, exist_ok=True)
    duration = _ffprobe_duration(input_path)
    split_at = max(0.2, min(split_time, duration - 0.2))
    first_path = output_dir / _safe_name("split_a")
    second_path = output_dir / _safe_name("split_b")

    _run(
        [
            "ffmpeg",
            "-y",
            "-i",
            str(input_path),
            "-t",
            f"{split_at:.3f}",
            *_encode_args(),
            str(first_path),
        ]
    )
    _run(
        [
            "ffmpeg",
            "-y",
            "-ss",
            f"{split_at:.3f}",
            "-i",
            str(input_path),
            "-t",
            f"{duration - split_at:.3f}",
            *_encode_args(),
            str(second_path),
        ]
    )
    return first_path, second_path


def merge_clip_files(paths: Iterable[Path], output_dir: Path) -> Path:
    output_dir.mkdir(parents=True, exist_ok=True)
    output_path = output_dir / _safe_name("merge")
    input_paths = list(paths)
    if not input_paths:
        raise ValueError("No clips provided for merge")

    with tempfile.NamedTemporaryFile(
        "w", suffix=".txt", prefix="supoclip_concat_", delete=False
    ) as handle:
        list_path = Path(handle.name)
        for path in input_paths:
            escaped = str(path).replace("'", "'\\''")
            handle.write(f"file '{escaped}'\n")

    try:
        _run(
            [
                "ffmpeg",
                "-y",
                "-f",
                "concat",
                "-safe",
                "0",
                "-i",
                str(list_path),
                *_encode_args(),
                str(output_path),
            ]
        )
    finally:
        list_path.unlink(missing_ok=True)

    return output_path


def overlay_custom_captions(
    input_path: Path,
    output_dir: Path,
    caption_text: str,
    position: str,
    highlight_words: List[str],
    *,
    font_family: Optional[str] = None,
    font_size: Optional[int] = None,
    font_color: Optional[str] = None,
    caption_template: str = "default",
    transcript_video_path: Optional[Path] = None,
    source_ranges: Optional[List[tuple[float, float]]] = None,
    position_y: Optional[float] = None,
    output_offsets: Optional[List[float]] = None,
) -> Path:
    """Burn edited captions onto ``input_path``.

    ``output_offsets`` are where each source range starts in the clip; planned
    workflow clips pass the offsets they were rendered with (fades, beats out
    of source order) so captions stay on the audio at every junction.
    """
    output_dir.mkdir(parents=True, exist_ok=True)
    output_path = output_dir / _safe_name("caption")
    if not caption_text.strip():
        _run(["ffmpeg", "-y", "-i", str(input_path), *_encode_args(), str(output_path)])
        return output_path

    width, height = _ffprobe_size(input_path)
    duration = _ffprobe_duration(input_path)
    position_y = position_y if position_y is not None else {
        "top": 0.18,
        "middle": 0.52,
        "bottom": 0.78,
    }.get(position, 0.78)
    ass_path = output_dir / f"captions_{uuid.uuid4().hex[:12]}.ass"

    transcript_path = transcript_video_path or input_path
    transcript_data = load_cached_transcript_data(transcript_path)
    timed_words: List[Dict[str, Any]] = []
    if transcript_data and transcript_data.get("words"):
        if source_ranges:
            timed_words = get_words_for_keep_ranges(transcript_data, source_ranges, output_offsets)
        else:
            timed_words = get_words_in_range(transcript_data, 0.0, duration)

    words = caption_tokens(caption_text, timed_words)
    caption_words = _caption_words_with_timings(words, timed_words, duration)
    if not build_assemblyai_ass_subtitles(
        input_path,
        clip_start=0.0,
        clip_end=duration,
        video_width=width,
        video_height=height,
        output_ass_path=ass_path,
        font_family=font_family,
        font_size=font_size,
        font_color=font_color,
        caption_template=caption_template,
        caption_words=caption_words,
        position_y_override=position_y,
        highlight_words=highlight_words,
    ):
        raise RuntimeError("Failed to build edited captions")

    try:
        effective_font_family = (
            font_family or get_template(caption_template)["font_family"]
        )
        fonts_dir = ass_fonts_dir(effective_font_family)
        subtitle_filter = f"subtitles=filename={_escape_filter_path(ass_path)}"
        if fonts_dir:
            subtitle_filter += f":fontsdir={_escape_filter_path(fonts_dir)}"
        _run(
            [
                "ffmpeg",
                "-y",
                "-i",
                str(input_path),
                "-vf",
                subtitle_filter,
                *_encode_args(),
                str(output_path),
            ]
        )
    finally:
        ass_path.unlink(missing_ok=True)

    return output_path


def caption_tokens(text: str, timed_words: List[Dict[str, Any]]) -> List[str]:
    """Words of a clip's caption text, ready for per-word timing.

    Chinese, Japanese and Thai clips store text without spaces, which would
    otherwise read as a single word held for the whole clip. Unedited text gets
    the transcript's own words back; edited text is split by character.
    """
    tokens = text.split()
    if not is_no_space(None, "".join(tokens)):
        return tokens
    spoken = [str(word.get("text", "")).strip() for word in timed_words]
    spoken = [word for word in spoken if word]
    if "".join(spoken) == "".join(tokens):
        return spoken
    characters: List[str] = []
    for character in "".join(tokens):
        # Combining marks (Thai vowels and tones) stay on their base character.
        if characters and unicodedata.category(character).startswith("M"):
            characters[-1] += character
        else:
            characters.append(character)
    return characters


def _caption_words_with_timings(
    words: List[str],
    timed_words: List[Dict[str, Any]],
    duration: float,
) -> List[Dict[str, Any]]:
    """Apply edited text to source timings, or evenly split when none exist."""
    if timed_words:
        source_count = len(timed_words)
        edited_count = len(words)
        if edited_count == source_count:
            return [
                {
                    "text": word,
                    "start": float(timed["start"]),
                    "end": float(timed["end"]),
                    "confidence": timed.get("confidence", 1.0),
                }
                for word, timed in zip(words, timed_words)
            ]

        # Word counts differ: spread the edited words proportionally across the
        # spoken span so timings stay strictly increasing (no stacked words).
        span_start = float(timed_words[0]["start"])
        span_end = max(float(timed_words[-1]["end"]), span_start + 0.05 * edited_count)
        step = (span_end - span_start) / edited_count
        return [
            {
                "text": word,
                "start": span_start + index * step,
                "end": span_start + (index + 1) * step,
                "confidence": 1.0,
            }
            for index, word in enumerate(words)
        ]

    word_duration = max(duration / max(len(words), 1), 0.1)
    return [
        {
            "text": word,
            "start": index * word_duration,
            "end": min(duration, (index + 1) * word_duration),
            "confidence": 1.0,
        }
        for index, word in enumerate(words)
    ]


class ExportCancelled(RuntimeError):
    """The caller asked an in-progress preset export to stop."""


def _ffmpeg_clock_seconds(value: str) -> Optional[float]:
    pieces = value.strip().split(":")
    if len(pieces) != 3:
        return None
    try:
        hours = int(pieces[0])
        minutes = int(pieces[1])
        seconds = float(pieces[2])
    except ValueError:
        return None
    if minutes < 0 or seconds < 0:
        return None
    return hours * 3600 + minutes * 60 + seconds


def _export_with_progress(
    command: list[str],
    input_path: Path,
    on_progress: Optional[Callable[[int], None]],
    should_stop: Optional[Callable[[], bool]],
) -> None:
    """Run ffmpeg and report encode percent from its progress clock.

    The synchronous download route keeps the original command. This path is
    only used by the queued export, which needs a percentage for clients.
    """
    try:
        duration = _ffprobe_duration(input_path)
    except (subprocess.CalledProcessError, ValueError, OSError):
        duration = 0.0
    progress_command = [*command[:-1], "-progress", "pipe:1", "-nostats", command[-1]]
    process = subprocess.Popen(
        progress_command,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True,
    )
    stderr_parts: list[str] = []

    def _drain_stderr() -> None:
        if process.stderr is not None:
            stderr_parts.append(process.stderr.read())

    drain = threading.Thread(target=_drain_stderr, daemon=True)
    drain.start()
    last_percent = -1
    cancelled = False
    try:
        assert process.stdout is not None
        for line in process.stdout:
            if should_stop is not None and should_stop():
                cancelled = True
                break
            if on_progress is None or duration <= 0 or not line.startswith("out_time="):
                continue
            clock = _ffmpeg_clock_seconds(line.split("=", 1)[1])
            if clock is None:
                continue
            percent = min(99, int(clock / duration * 100))
            if percent != last_percent:
                last_percent = percent
                on_progress(percent)
    finally:
        if process.poll() is None:
            if not cancelled:
                try:
                    process.wait(timeout=30)
                except subprocess.TimeoutExpired:
                    process.kill()
                    process.wait()
            if process.poll() is None:
                process.terminate()
                try:
                    process.wait(timeout=10)
                except subprocess.TimeoutExpired:
                    process.kill()
                    process.wait()
        drain.join(timeout=5)
    if cancelled:
        raise ExportCancelled("Export was cancelled.")
    if process.returncode != 0:
        raise subprocess.CalledProcessError(
            process.returncode or 1,
            progress_command,
            stderr="".join(stderr_parts)[-4000:],
        )


def export_with_preset(
    input_path: Path,
    output_dir: Path,
    preset_name: str,
    *,
    output_path: Optional[Path] = None,
    on_progress: Optional[Callable[[int], None]] = None,
    should_stop: Optional[Callable[[], bool]] = None,
) -> Path:
    output_dir.mkdir(parents=True, exist_ok=True)
    preset = EXPORT_PRESETS.get(preset_name)
    if not preset:
        raise ValueError(f"Unknown export preset: {preset_name}")

    destination = output_path or (output_dir / _safe_name(preset.name))
    destination.parent.mkdir(parents=True, exist_ok=True)
    scale_filter = (
        f"scale={preset.width}:{preset.height}:"
        "force_original_aspect_ratio=decrease:flags=lanczos,"
        f"pad={preset.width}:{preset.height}:(ow-iw)/2:(oh-ih)/2,"
        "setsar=1"
    )
    geometry = probe_video_geometry(input_path)
    if geometry and geometry.fps is not None and geometry.fps > MAX_OUTPUT_FPS + FPS_EPSILON:
        scale_filter = f"fps={MAX_OUTPUT_FPS},{scale_filter}"
    command = [
        "ffmpeg",
        "-y",
        "-i",
        str(input_path),
        "-vf",
        scale_filter,
        "-c:v",
        "libx264",
        "-preset",
        "slow",
        "-crf",
        "18",
        "-maxrate",
        preset.video_bitrate,
        "-bufsize",
        _double_bitrate(preset.video_bitrate),
        "-pix_fmt",
        "yuv420p",
        "-profile:v",
        "high",
        "-c:a",
        "aac",
        "-b:a",
        preset.audio_bitrate,
        "-ar",
        "48000",
        "-movflags",
        "+faststart",
        str(destination),
    ]
    if on_progress is None and should_stop is None:
        _run(command)
    else:
        _export_with_progress(command, input_path, on_progress, should_stop)
    return destination