File size: 3,210 Bytes
851e5ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/local/bin/python
"""Space-only FFmpeg wrapper: serialize processes without changing codecs/quality."""
import errno
import os
from pathlib import Path
import re
import sys
import time

REAL_FFMPEG = "/usr/bin/ffmpeg"
QUERIES = {"-version", "-h", "-help", "-formats", "-encoders", "-decoders", "-filters", "-hwaccels", "-codecs", "-buildconf", "-devices", "-protocols"}


def limited_arguments(arguments, threads):
    if not 1 <= threads <= 2:
        raise ValueError("HF_FFMPEG_THREADS must be1 or2 on CPU Basic")
    if not arguments or any(argument in QUERIES for argument in arguments):
        return list(arguments)
    result = []
    index = 0
    while index < len(arguments):
        argument = arguments[index]
        if re.fullmatch(r"-(?:threads(?::[vas](?::\d+)?)?|filter_threads|filter_complex_threads)", argument):
            if index + 1 >= len(arguments):
                raise ValueError("Missing FFmpeg thread value")
            result.extend([argument, str(threads)])
            index += 2
        elif argument == "-i":
            # Decoder options reset for each input in a multi-range/crossfade job.
            result.extend(["-threads", str(threads), argument])
            index += 1
        else:
            result.append(argument)
            index += 1
    prefix = ["-threads", str(threads), "-filter_threads", str(threads), "-filter_complex_threads", str(threads)]
    # SupoClip's FFmpeg commands have one final output target, including '-'.
    # The prefix caps decoding, and the output-scoped option caps encoding.
    if "-i" in result and result:
        result[-1:-1] = ["-threads", str(threads)]
    return prefix + result


def main():
    arguments = sys.argv[1:]
    command = [REAL_FFMPEG, *limited_arguments(arguments, int(os.environ.get("HF_FFMPEG_THREADS", "1")))]
    if not arguments or any(argument in QUERIES for argument in arguments):
        os.execv(REAL_FFMPEG, command)
    import fcntl

    directory = Path(os.environ.get("HF_RUNTIME_DIR", "/home/user/runtime"))
    directory.mkdir(parents=True, exist_ok=True)
    descriptor = os.open(directory / "ffmpeg.lock", os.O_CREAT | os.O_RDWR | getattr(os, "O_NOFOLLOW", 0), 0o600)
    timeout = float(os.environ.get("HF_FFMPEG_LOCK_TIMEOUT", "900"))
    if not 1 <= timeout <= 3600:
        raise ValueError("HF_FFMPEG_LOCK_TIMEOUT must be between1 and3600 seconds")
    deadline = time.monotonic() + timeout
    try:
        while True:
            try:
                fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB)
                break
            except OSError as error:
                if error.errno not in (errno.EAGAIN, errno.EACCES):
                    raise
                if time.monotonic() >= deadline:
                    raise TimeoutError("Another media operation is busy; try again when it finishes")
                time.sleep(0.2)
        os.set_inheritable(descriptor, True)
        os.execv(REAL_FFMPEG, command)
    finally:
        os.close(descriptor)


if __name__ == "__main__":
    try:
        main()
    except (OSError, ValueError, TimeoutError) as error:
        print(f"FFmpeg resource guard: {error}", file=sys.stderr)
        raise SystemExit(1)