File size: 2,895 Bytes
3249e1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""ffmpeg loop helpers for the Loop Maker tab (CPU only; needs ffmpeg via packages.txt)."""
import os, shutil, subprocess, tempfile

ASPECTS = {"keep": None, "9:16 (1080x1920)": (1080, 1920), "16:9 (1920x1080)": (1920, 1080), "1:1 (1080x1080)": (1080, 1080)}


def _run(args, timeout=900):
    if not shutil.which("ffmpeg"):
        raise RuntimeError("ffmpeg is not installed (add 'ffmpeg' to packages.txt).")
    p = subprocess.run(args, capture_output=True, text=True, timeout=timeout)
    if p.returncode != 0:
        raise RuntimeError("ffmpeg failed: " + p.stderr[-600:])


def _duration(path) -> float:
    out = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "default=nw=1:nk=1", path],
                         capture_output=True, text=True).stdout.strip()
    return float(out or 0)


def _scale_filter(aspect):
    size = ASPECTS.get(aspect)
    if not size:
        return "scale=trunc(iw/2)*2:trunc(ih/2)*2"
    w, h = size
    return f"scale={w}:{h}:force_original_aspect_ratio=increase,crop={w}:{h},setsar=1"


def make_loop(video, style="ping-pong", crossfade=0.75, total_seconds=0, audio=None, aspect="keep"):
    """style: 'ping-pong' (forward+reverse) or 'crossfade' (end blends into start).
    total_seconds > 0 repeats the loop to that length (e.g. 3600 for a 1-hour stream).
    audio: optional song file used as the soundtrack (trimmed/looped to the video length)."""
    work = tempfile.mkdtemp(prefix="aiking_loop_")
    base = os.path.join(work, "base.mp4")
    sf = _scale_filter(aspect)
    if style == "ping-pong":
        fc = f"[0:v]{sf},fps=24,split[a][b];[b]reverse[r];[a][r]concat=n=2:v=1:a=0,format=yuv420p[v]"
        _run(["ffmpeg", "-y", "-i", video, "-filter_complex", fc, "-map", "[v]", "-an", "-c:v", "libx264", "-crf", "18", base])
    else:
        d = _duration(video)
        x = max(0.2, min(float(crossfade), d / 3))
        fc = (f"[0:v]{sf},format=yuv420p,split[m][t];"
              f"[m]trim=start={x},setpts=PTS-STARTPTS,fps=24[main];"
              f"[t]trim=end={x},setpts=PTS-STARTPTS,fps=24[head];"
              f"[main][head]xfade=transition=fade:duration={x}:offset={d - 2 * x:.3f}[v]")
        _run(["ffmpeg", "-y", "-i", video, "-filter_complex", fc, "-map", "[v]", "-an", "-c:v", "libx264", "-crf", "18", base])
    out = base
    if total_seconds and float(total_seconds) > 0:
        rep = os.path.join(work, "long.mp4")
        _run(["ffmpeg", "-y", "-stream_loop", "-1", "-i", base, "-t", str(float(total_seconds)), "-c", "copy", rep], timeout=3600)
        out = rep
    if audio:
        withaudio = os.path.join(work, "loop-with-song.mp4")
        _run(["ffmpeg", "-y", "-i", out, "-stream_loop", "-1", "-i", audio, "-map", "0:v", "-map", "1:a",
              "-c:v", "copy", "-c:a", "aac", "-b:a", "192k", "-shortest", withaudio], timeout=3600)
        out = withaudio
    return out