kinescript 1.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- kinescript/__init__.py +6 -0
- kinescript/cli.py +167 -0
- kinescript/color.py +89 -0
- kinescript/components.py +272 -0
- kinescript/docs.py +345 -0
- kinescript/ease.py +143 -0
- kinescript/fonts/IBMPlexMono-Bold.ttf +0 -0
- kinescript/fonts/IBMPlexMono-Medium.ttf +0 -0
- kinescript/fonts/IBMPlexMono-OFL.txt +93 -0
- kinescript/fonts/IBMPlexMono-Regular.ttf +0 -0
- kinescript/fonts/IBMPlexMono-SemiBold.ttf +0 -0
- kinescript/fonts/SpaceGrotesk-Bold.ttf +0 -0
- kinescript/fonts/SpaceGrotesk-Medium.ttf +0 -0
- kinescript/fonts/SpaceGrotesk-OFL.txt +93 -0
- kinescript/fonts/SpaceGrotesk-Regular.ttf +0 -0
- kinescript/fonts/SpaceGrotesk-SemiBold.ttf +0 -0
- kinescript/mcp.py +148 -0
- kinescript/media.py +220 -0
- kinescript/mesh.py +390 -0
- kinescript/models.py +339 -0
- kinescript/output.py +370 -0
- kinescript/presets.py +170 -0
- kinescript/props.py +185 -0
- kinescript/render.py +1204 -0
- kinescript/render3d.py +393 -0
- kinescript/scene.py +362 -0
- kinescript/schema.py +701 -0
- kinescript/shaders.py +79 -0
- kinescript/space.py +81 -0
- kinescript/svgpath.py +80 -0
- kinescript/timing.py +169 -0
- kinescript/verify.py +261 -0
- kinescript-1.1.0.dist-info/METADATA +192 -0
- kinescript-1.1.0.dist-info/RECORD +40 -0
- kinescript-1.1.0.dist-info/WHEEL +5 -0
- kinescript-1.1.0.dist-info/entry_points.txt +2 -0
- kinescript-1.1.0.dist-info/licenses/LICENSE +25 -0
- kinescript-1.1.0.dist-info/licenses/kinescript/fonts/IBMPlexMono-OFL.txt +93 -0
- kinescript-1.1.0.dist-info/licenses/kinescript/fonts/SpaceGrotesk-OFL.txt +93 -0
- kinescript-1.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
Copyright 2020 The Space Grotesk Project Authors (https://github.com/floriankarsten/space-grotesk)
|
|
2
|
+
|
|
3
|
+
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
|
4
|
+
This license is copied below, and is also available with a FAQ at:
|
|
5
|
+
http://scripts.sil.org/OFL
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
-----------------------------------------------------------
|
|
9
|
+
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
|
10
|
+
-----------------------------------------------------------
|
|
11
|
+
|
|
12
|
+
PREAMBLE
|
|
13
|
+
The goals of the Open Font License (OFL) are to stimulate worldwide
|
|
14
|
+
development of collaborative font projects, to support the font creation
|
|
15
|
+
efforts of academic and linguistic communities, and to provide a free and
|
|
16
|
+
open framework in which fonts may be shared and improved in partnership
|
|
17
|
+
with others.
|
|
18
|
+
|
|
19
|
+
The OFL allows the licensed fonts to be used, studied, modified and
|
|
20
|
+
redistributed freely as long as they are not sold by themselves. The
|
|
21
|
+
fonts, including any derivative works, can be bundled, embedded,
|
|
22
|
+
redistributed and/or sold with any software provided that any reserved
|
|
23
|
+
names are not used by derivative works. The fonts and derivatives,
|
|
24
|
+
however, cannot be released under any other type of license. The
|
|
25
|
+
requirement for fonts to remain under this license does not apply
|
|
26
|
+
to any document created using the fonts or their derivatives.
|
|
27
|
+
|
|
28
|
+
DEFINITIONS
|
|
29
|
+
"Font Software" refers to the set of files released by the Copyright
|
|
30
|
+
Holder(s) under this license and clearly marked as such. This may
|
|
31
|
+
include source files, build scripts and documentation.
|
|
32
|
+
|
|
33
|
+
"Reserved Font Name" refers to any names specified as such after the
|
|
34
|
+
copyright statement(s).
|
|
35
|
+
|
|
36
|
+
"Original Version" refers to the collection of Font Software components as
|
|
37
|
+
distributed by the Copyright Holder(s).
|
|
38
|
+
|
|
39
|
+
"Modified Version" refers to any derivative made by adding to, deleting,
|
|
40
|
+
or substituting -- in part or in whole -- any of the components of the
|
|
41
|
+
Original Version, by changing formats or by porting the Font Software to a
|
|
42
|
+
new environment.
|
|
43
|
+
|
|
44
|
+
"Author" refers to any designer, engineer, programmer, technical
|
|
45
|
+
writer or other person who contributed to the Font Software.
|
|
46
|
+
|
|
47
|
+
PERMISSION & CONDITIONS
|
|
48
|
+
Permission is hereby granted, free of charge, to any person obtaining
|
|
49
|
+
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
|
50
|
+
redistribute, and sell modified and unmodified copies of the Font
|
|
51
|
+
Software, subject to the following conditions:
|
|
52
|
+
|
|
53
|
+
1) Neither the Font Software nor any of its individual components,
|
|
54
|
+
in Original or Modified Versions, may be sold by itself.
|
|
55
|
+
|
|
56
|
+
2) Original or Modified Versions of the Font Software may be bundled,
|
|
57
|
+
redistributed and/or sold with any software, provided that each copy
|
|
58
|
+
contains the above copyright notice and this license. These can be
|
|
59
|
+
included either as stand-alone text files, human-readable headers or
|
|
60
|
+
in the appropriate machine-readable metadata fields within text or
|
|
61
|
+
binary files as long as those fields can be easily viewed by the user.
|
|
62
|
+
|
|
63
|
+
3) No Modified Version of the Font Software may use the Reserved Font
|
|
64
|
+
Name(s) unless explicit written permission is granted by the corresponding
|
|
65
|
+
Copyright Holder. This restriction only applies to the primary font name as
|
|
66
|
+
presented to the users.
|
|
67
|
+
|
|
68
|
+
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
|
69
|
+
Software shall not be used to promote, endorse or advertise any
|
|
70
|
+
Modified Version, except to acknowledge the contribution(s) of the
|
|
71
|
+
Copyright Holder(s) and the Author(s) or with their explicit written
|
|
72
|
+
permission.
|
|
73
|
+
|
|
74
|
+
5) The Font Software, modified or unmodified, in part or in whole,
|
|
75
|
+
must be distributed entirely under this license, and must not be
|
|
76
|
+
distributed under any other license. The requirement for fonts to
|
|
77
|
+
remain under this license does not apply to any document created
|
|
78
|
+
using the Font Software.
|
|
79
|
+
|
|
80
|
+
TERMINATION
|
|
81
|
+
This license becomes null and void if any of the above conditions are
|
|
82
|
+
not met.
|
|
83
|
+
|
|
84
|
+
DISCLAIMER
|
|
85
|
+
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
86
|
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
|
87
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
|
88
|
+
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
|
89
|
+
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
|
90
|
+
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
|
91
|
+
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|
92
|
+
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
|
93
|
+
OTHER DEALINGS IN THE FONT SOFTWARE.
|
|
Binary file
|
|
Binary file
|
kinescript/mcp.py
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
"""Minimal MCP server (JSON-RPC 2.0 over stdio, newline-delimited). No dependencies.
|
|
2
|
+
|
|
3
|
+
Tools take `scene` as a path to a .json file or as the scene object itself.
|
|
4
|
+
Look and still return the image inline, so an agent with vision sees the frames directly.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import base64
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import sys
|
|
12
|
+
import tempfile
|
|
13
|
+
import traceback
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
from . import __version__
|
|
17
|
+
|
|
18
|
+
_SCENE = {"description": "Path to a scene .json, or the scene object itself", "type": ["string", "object"]}
|
|
19
|
+
TOOLS = [
|
|
20
|
+
{"name": "kine_docs", "description": "Kinescript scene reference: layer types, properties, timing, motions, "
|
|
21
|
+
"components, eases. Read once before writing a scene.", "inputSchema": {"type": "object", "properties": {}}},
|
|
22
|
+
{"name": "kine_check", "description": "Lint a scene: load errors, text off canvas or in the safe margin, overlapping "
|
|
23
|
+
"text, low contrast, tiny text, too little reading time. Returns issues with time ranges and fixes.",
|
|
24
|
+
"inputSchema": {"type": "object", "properties": {"scene": _SCENE, "base": {"type": "string"}}, "required": ["scene"]}},
|
|
25
|
+
{"name": "kine_look", "description": "Contact sheet: `count` frames in one labelled image. boxes=true outlines each "
|
|
26
|
+
"layer with its id. Use it to review motion and layout without watching video.",
|
|
27
|
+
"inputSchema": {"type": "object", "properties": {"scene": _SCENE, "base": {"type": "string"},
|
|
28
|
+
"count": {"type": "integer", "default": 12},
|
|
29
|
+
"times": {"type": "array", "items": {"type": "number"}},
|
|
30
|
+
"boxes": {"type": "boolean", "default": False},
|
|
31
|
+
"width": {"type": "integer", "default": 400}}, "required": ["scene"]}},
|
|
32
|
+
{"name": "kine_still", "description": "One full-size frame at time `at` (seconds), returned as an image.",
|
|
33
|
+
"inputSchema": {"type": "object", "properties": {"scene": _SCENE, "base": {"type": "string"}, "at": {"type": "number"},
|
|
34
|
+
"scale": {"type": "number", "default": 0.5}},
|
|
35
|
+
"required": ["scene", "at"]}},
|
|
36
|
+
{"name": "kine_probe", "description": "Resolved timeline (every layer's in/out) and, with `at`, every visible "
|
|
37
|
+
"layer's screen box, alpha and text at that time.",
|
|
38
|
+
"inputSchema": {"type": "object", "properties": {"scene": _SCENE, "base": {"type": "string"}, "at": {"type": "number"}},
|
|
39
|
+
"required": ["scene"]}},
|
|
40
|
+
{"name": "kine_render", "description": "Render to a file (.mp4, .mov ProRes 4444 alpha, .webm VP9 alpha, .gif, or a "
|
|
41
|
+
".png sequence). quality draft|standard|high; scale <1 for previews; from/to (s) for a range.",
|
|
42
|
+
"inputSchema": {"type": "object", "properties": {"scene": _SCENE, "base": {"type": "string"}, "out": {"type": "string"},
|
|
43
|
+
"quality": {"type": "string", "enum": ["draft", "standard", "high"]},
|
|
44
|
+
"scale": {"type": "number"}, "from": {"type": "number"},
|
|
45
|
+
"to": {"type": "number"}}, "required": ["scene", "out"]}},
|
|
46
|
+
]
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _scene(args: dict):
|
|
50
|
+
from .scene import Scene, load
|
|
51
|
+
sc = args["scene"]
|
|
52
|
+
if isinstance(sc, dict):
|
|
53
|
+
return Scene(sc, args.get("base") or os.getcwd())
|
|
54
|
+
return load(sc)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _image(path: str) -> dict:
|
|
58
|
+
return {"type": "image", "mimeType": "image/png", "data": base64.b64encode(Path(path).read_bytes()).decode()}
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _text(obj) -> dict:
|
|
62
|
+
return {"type": "text", "text": obj if isinstance(obj, str) else json.dumps(obj, indent=1, ensure_ascii=False)}
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def call(name: str, args: dict) -> list[dict]:
|
|
66
|
+
if name == "kine_docs":
|
|
67
|
+
from .docs import reference
|
|
68
|
+
return [_text(reference())]
|
|
69
|
+
if name == "kine_check":
|
|
70
|
+
from .verify import check
|
|
71
|
+
return [_text(check(_scene(args)))]
|
|
72
|
+
if name == "kine_probe":
|
|
73
|
+
from .verify import probe
|
|
74
|
+
return [_text(probe(_scene(args), args.get("at")))]
|
|
75
|
+
if name == "kine_look":
|
|
76
|
+
from .verify import contact_sheet
|
|
77
|
+
out = str(Path(tempfile.gettempdir()) / f"kine_look_{os.getpid()}.png")
|
|
78
|
+
info = contact_sheet(_scene(args), out, int(args.get("count", 12)), None, int(args.get("width", 400)),
|
|
79
|
+
args.get("times"), bool(args.get("boxes")))
|
|
80
|
+
return [_image(out), _text(info)]
|
|
81
|
+
if name == "kine_still":
|
|
82
|
+
from .output import still
|
|
83
|
+
out = str(Path(tempfile.gettempdir()) / f"kine_still_{os.getpid()}.png")
|
|
84
|
+
still(_scene(args), float(args["at"]), out, float(args.get("scale", 0.5)))
|
|
85
|
+
return [_image(out)]
|
|
86
|
+
if name == "kine_render":
|
|
87
|
+
from .output import render
|
|
88
|
+
sc = args["scene"]
|
|
89
|
+
if isinstance(sc, dict):
|
|
90
|
+
sc = _scene(args)
|
|
91
|
+
res = render(sc, args["out"], args.get("quality", "standard"), None, float(args.get("scale", 1.0)),
|
|
92
|
+
args.get("from"), args.get("to"))
|
|
93
|
+
return [_text(res)]
|
|
94
|
+
raise ValueError(f"unknown tool {name}")
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _reply(id_, result=None, error=None):
|
|
98
|
+
msg = {"jsonrpc": "2.0", "id": id_}
|
|
99
|
+
if error is not None:
|
|
100
|
+
msg["error"] = error
|
|
101
|
+
else:
|
|
102
|
+
msg["result"] = result
|
|
103
|
+
sys.stdout.write(json.dumps(msg) + "\n")
|
|
104
|
+
sys.stdout.flush()
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def serve():
|
|
108
|
+
try:
|
|
109
|
+
_serve()
|
|
110
|
+
except OSError: # the client closed its end of the pipe (BrokenPipeError, or EINVAL on Windows)
|
|
111
|
+
sys.stdout = open(os.devnull, "w") # so the interpreter's final flush stays quiet
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _serve():
|
|
115
|
+
for line in sys.stdin:
|
|
116
|
+
line = line.strip()
|
|
117
|
+
if not line:
|
|
118
|
+
continue
|
|
119
|
+
try:
|
|
120
|
+
req = json.loads(line)
|
|
121
|
+
except json.JSONDecodeError:
|
|
122
|
+
_reply(None, error={"code": -32700, "message": "parse error"})
|
|
123
|
+
continue
|
|
124
|
+
method, id_ = req.get("method"), req.get("id")
|
|
125
|
+
if id_ is None:
|
|
126
|
+
continue # notification
|
|
127
|
+
if method == "initialize":
|
|
128
|
+
_reply(id_, {"protocolVersion": req.get("params", {}).get("protocolVersion", "2024-11-05"),
|
|
129
|
+
"capabilities": {"tools": {}},
|
|
130
|
+
"serverInfo": {"name": "kinescript", "version": __version__},
|
|
131
|
+
"instructions": "Kinescript renders motion graphics and video edits from JSON scenes. "
|
|
132
|
+
"Call kine_docs first, then write a scene, kine_check it, kine_look at it, "
|
|
133
|
+
"and kine_render it."})
|
|
134
|
+
elif method == "tools/list":
|
|
135
|
+
_reply(id_, {"tools": TOOLS})
|
|
136
|
+
elif method == "tools/call":
|
|
137
|
+
p = req.get("params", {})
|
|
138
|
+
try:
|
|
139
|
+
_reply(id_, {"content": call(p.get("name"), p.get("arguments") or {})})
|
|
140
|
+
except (ValueError, RuntimeError, FileNotFoundError, KeyError) as e:
|
|
141
|
+
_reply(id_, {"content": [_text(f"error: {e}")], "isError": True})
|
|
142
|
+
except Exception as e: # noqa: BLE001 - report unexpected failures to the client instead of dying
|
|
143
|
+
_reply(id_, {"content": [_text(f"internal error: {e}\n{traceback.format_exc()[-1500:]}")],
|
|
144
|
+
"isError": True})
|
|
145
|
+
elif method == "ping":
|
|
146
|
+
_reply(id_, {})
|
|
147
|
+
else:
|
|
148
|
+
_reply(id_, error={"code": -32601, "message": f"method not found: {method}"})
|
kinescript/media.py
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
"""Footage and image access through ffmpeg/ffprobe pipes."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import shutil
|
|
7
|
+
import queue
|
|
8
|
+
import subprocess
|
|
9
|
+
import threading
|
|
10
|
+
from functools import lru_cache
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
import numpy as np
|
|
14
|
+
import skia
|
|
15
|
+
|
|
16
|
+
FFMPEG = shutil.which("ffmpeg") or "ffmpeg"
|
|
17
|
+
FFPROBE = shutil.which("ffprobe") or "ffprobe"
|
|
18
|
+
_NOWIN = getattr(subprocess, "CREATE_NO_WINDOW", 0)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class MediaError(RuntimeError):
|
|
22
|
+
pass
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _version(src: str) -> tuple:
|
|
26
|
+
"""(path, modification time, size): a cache key that changes when the file does, so the MCP server and
|
|
27
|
+
warm render workers read an edited file again."""
|
|
28
|
+
try:
|
|
29
|
+
st = os.stat(src)
|
|
30
|
+
except OSError:
|
|
31
|
+
return src, 0, -1
|
|
32
|
+
return src, st.st_mtime_ns, st.st_size
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def probe(src: str) -> dict:
|
|
36
|
+
"""{'duration', 'w', 'h', 'fps', 'audio'} for a media file, probed once per file version."""
|
|
37
|
+
return _probe(*_version(src))
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@lru_cache(maxsize=128)
|
|
41
|
+
def _probe(src: str, mtime: int, size: int) -> dict:
|
|
42
|
+
if not Path(src).exists():
|
|
43
|
+
raise MediaError(f"media not found: {src}")
|
|
44
|
+
out = subprocess.run([FFPROBE, "-v", "error", "-show_streams", "-show_format", "-of", "json", src],
|
|
45
|
+
capture_output=True, text=True, creationflags=_NOWIN)
|
|
46
|
+
if out.returncode:
|
|
47
|
+
raise MediaError(f"ffprobe failed on {src}: {out.stderr.strip()[:300]}")
|
|
48
|
+
info = json.loads(out.stdout)
|
|
49
|
+
v = next((s for s in info.get("streams", []) if s.get("codec_type") == "video"), None)
|
|
50
|
+
a = any(s.get("codec_type") == "audio" for s in info.get("streams", []))
|
|
51
|
+
dur = float(info.get("format", {}).get("duration") or (v or {}).get("duration") or 0)
|
|
52
|
+
fps = 0.0
|
|
53
|
+
if v and v.get("avg_frame_rate", "0/0") != "0/0":
|
|
54
|
+
n, d = v["avg_frame_rate"].split("/")
|
|
55
|
+
fps = float(n) / float(d or 1)
|
|
56
|
+
return {"duration": dur, "w": int((v or {}).get("width", 0)), "h": int((v or {}).get("height", 0)),
|
|
57
|
+
"fps": fps, "audio": a, "image": bool(v) and fps == 0 and dur == 0,
|
|
58
|
+
"pix_fmt": (v or {}).get("pix_fmt", ""), "color_space": (v or {}).get("color_space", "")}
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def yuv_matrix(info: dict):
|
|
62
|
+
"""Skia's YUV colour space for a probed clip: its tag, or, untagged, the rule players use
|
|
63
|
+
(BT.709 from 1280 wide or above 576 lines, else BT.601). All limited range."""
|
|
64
|
+
cs = info.get("color_space") or ""
|
|
65
|
+
if cs == "bt709":
|
|
66
|
+
return skia.kRec709_YUVColorSpace
|
|
67
|
+
if cs in ("smpte170m", "bt470bg", "fcc"):
|
|
68
|
+
return skia.kRec601_YUVColorSpace
|
|
69
|
+
if cs.startswith("bt2020"):
|
|
70
|
+
return skia.kBT2020_YUVColorSpace
|
|
71
|
+
return skia.kRec709_YUVColorSpace if info.get("w", 0) >= 1280 or info.get("h", 0) > 576 else skia.kRec601_YUVColorSpace
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def image(src: str) -> skia.Image:
|
|
75
|
+
"""The decoded image, once per file version."""
|
|
76
|
+
return _image(*_version(src))
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@lru_cache(maxsize=64)
|
|
80
|
+
def _image(src: str, mtime: int, size: int) -> skia.Image:
|
|
81
|
+
data = Path(src).read_bytes() if Path(src).exists() else None
|
|
82
|
+
if data is None:
|
|
83
|
+
raise MediaError(f"image not found: {src}")
|
|
84
|
+
img = skia.Image.MakeFromEncoded(skia.Data.MakeWithCopy(data))
|
|
85
|
+
if img is None:
|
|
86
|
+
raise MediaError(f"cannot decode image {src} (png, jpg, webp, gif, bmp are supported)")
|
|
87
|
+
return img
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class VideoSource:
|
|
91
|
+
"""Delivers frames of one clip, already resampled to the scene fps and sized to the
|
|
92
|
+
layer box, so a sequential render reads each frame exactly once. Out-of-order access
|
|
93
|
+
(contact sheets, probes) reopens the pipe at the requested time."""
|
|
94
|
+
|
|
95
|
+
def __init__(self, src: str, w: int, h: int, fps: float, speed: float = 1.0, fit: str = "cover", ctx=None):
|
|
96
|
+
"""ctx: a GPU context. With one, YUV clips without alpha arrive as yuv420p (1.5 bytes a pixel
|
|
97
|
+
instead of 4; ffmpeg converts nothing) and become RGB on the GPU at draw time."""
|
|
98
|
+
self.src, self.w, self.h, self.fps, self.speed, self.fit = src, max(2, w), max(2, h), fps, speed, fit
|
|
99
|
+
self.info = probe(src)
|
|
100
|
+
pf = self.info["pix_fmt"]
|
|
101
|
+
self.ctx = ctx if (ctx is not None and fit != "contain" and pf.startswith(("yuv", "nv", "p0"))
|
|
102
|
+
and not pf.startswith("yuva")) else None
|
|
103
|
+
if self.ctx is not None: # 4:2:0 planes need even sizes
|
|
104
|
+
self.w, self.h = max(2, self.w - self.w % 2), max(2, self.h - self.h % 2)
|
|
105
|
+
self.yuv_info = skia.YUVAInfo((self.w, self.h), skia.YUVAInfo.kY_U_V, skia.YUVAInfo.k420,
|
|
106
|
+
yuv_matrix(self.info))
|
|
107
|
+
self.proc: subprocess.Popen | None = None
|
|
108
|
+
self.t0 = 0.0
|
|
109
|
+
self.index = -1
|
|
110
|
+
self.frame: skia.Image | None = None
|
|
111
|
+
self.nbytes = self.w * self.h * 3 // 2 if self.ctx is not None else self.w * self.h * 4
|
|
112
|
+
|
|
113
|
+
def _vf(self) -> str:
|
|
114
|
+
w, h = self.w, self.h
|
|
115
|
+
if self.ctx is not None: # cover or stretch, kept in YUV and limited range
|
|
116
|
+
fit = ":force_original_aspect_ratio=increase" if self.fit == "cover" else ""
|
|
117
|
+
crop = f",crop={w}:{h}" if self.fit == "cover" else ""
|
|
118
|
+
return f"setpts=(PTS-STARTPTS)/{self.speed},fps={self.fps},scale={w}:{h}{fit}:out_range=tv{crop},format=yuv420p"
|
|
119
|
+
# The same matrix the YUV path uses, so GPU and raster renders of a clip agree.
|
|
120
|
+
m = {skia.kRec709_YUVColorSpace: "bt709", skia.kRec601_YUVColorSpace: "bt601",
|
|
121
|
+
skia.kBT2020_YUVColorSpace: "bt2020"}[yuv_matrix(self.info)]
|
|
122
|
+
cm = f":in_color_matrix={m}" if self.info.get("pix_fmt", "").startswith(("yuv", "nv", "p0")) else ""
|
|
123
|
+
if self.fit == "contain":
|
|
124
|
+
size = (f"scale={w}:{h}{cm}:force_original_aspect_ratio=decrease,format=rgba,"
|
|
125
|
+
f"pad={w}:{h}:(ow-iw)/2:(oh-ih)/2:color=0x00000000")
|
|
126
|
+
elif self.fit == "stretch":
|
|
127
|
+
size = f"scale={w}:{h}{cm},format=rgba"
|
|
128
|
+
else:
|
|
129
|
+
size = f"scale={w}:{h}{cm}:force_original_aspect_ratio=increase,crop={w}:{h},format=rgba"
|
|
130
|
+
return f"setpts=(PTS-STARTPTS)/{self.speed},fps={self.fps},{size}"
|
|
131
|
+
|
|
132
|
+
def _open(self, t: float):
|
|
133
|
+
self.close()
|
|
134
|
+
self.t0 = max(0.0, t)
|
|
135
|
+
cmd = [FFMPEG, "-v", "error", "-ss", f"{self.t0:.4f}", "-i", self.src, "-an", "-vf", self._vf(),
|
|
136
|
+
"-f", "rawvideo", "-pix_fmt", "yuv420p" if self.ctx is not None else "rgba", "-"]
|
|
137
|
+
self.proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
|
|
138
|
+
bufsize=self.nbytes * 2, creationflags=_NOWIN)
|
|
139
|
+
self.index = -1
|
|
140
|
+
# A reader thread keeps up to PREFETCH decoded frames waiting, so ffmpeg decodes the next
|
|
141
|
+
# frames while this process draws the current one instead of both taking turns.
|
|
142
|
+
self.queue = q = queue.Queue(maxsize=self.PREFETCH)
|
|
143
|
+
self.stopping = stop = threading.Event()
|
|
144
|
+
threading.Thread(target=self._pump, args=(self.proc, q, stop, self.nbytes), daemon=True).start()
|
|
145
|
+
|
|
146
|
+
PREFETCH = 6
|
|
147
|
+
|
|
148
|
+
@staticmethod
|
|
149
|
+
def _pump(proc, q, stop, nbytes):
|
|
150
|
+
try:
|
|
151
|
+
while not stop.is_set():
|
|
152
|
+
buf = proc.stdout.read(nbytes)
|
|
153
|
+
item = buf if len(buf) == nbytes else None
|
|
154
|
+
while not stop.is_set():
|
|
155
|
+
try:
|
|
156
|
+
q.put(item, timeout=0.1)
|
|
157
|
+
break
|
|
158
|
+
except queue.Full:
|
|
159
|
+
continue
|
|
160
|
+
if item is None:
|
|
161
|
+
return
|
|
162
|
+
except (OSError, ValueError): # the pipe was closed by close()
|
|
163
|
+
return
|
|
164
|
+
|
|
165
|
+
def _read(self) -> bool:
|
|
166
|
+
buf = self.queue.get()
|
|
167
|
+
if buf is None:
|
|
168
|
+
self.queue.put(None) # stay at end of stream for later calls
|
|
169
|
+
return False
|
|
170
|
+
# No copy: the image (or the planes) wrap the bytes object, which self._buf keeps alive.
|
|
171
|
+
self._buf = buf
|
|
172
|
+
if self.ctx is not None:
|
|
173
|
+
w, h, b = self.w, self.h, np.frombuffer(buf, np.uint8)
|
|
174
|
+
planes = (b[:w * h].reshape(h, w), b[w * h:w * h * 5 // 4].reshape(h // 2, w // 2),
|
|
175
|
+
b[w * h * 5 // 4:].reshape(h // 2, w // 2))
|
|
176
|
+
pms = [skia.Pixmap(skia.ImageInfo.Make(a.shape[1], a.shape[0], skia.kGray_8_ColorType,
|
|
177
|
+
skia.kOpaque_AlphaType), a, a.shape[1]) for a in planes]
|
|
178
|
+
self.frame = skia.Image.MakeFromYUVAPixmaps(
|
|
179
|
+
self.ctx, skia.YUVAPixmaps.FromExternalPixmaps(self.yuv_info, pms + [skia.Pixmap()]))
|
|
180
|
+
else:
|
|
181
|
+
arr = np.frombuffer(buf, np.uint8).reshape(self.h, self.w, 4)
|
|
182
|
+
self.frame = skia.Image.fromarray(arr, colorType=skia.kRGBA_8888_ColorType, copy=False)
|
|
183
|
+
self.index += 1
|
|
184
|
+
return True
|
|
185
|
+
|
|
186
|
+
def at(self, src_t: float) -> skia.Image | None:
|
|
187
|
+
"""Frame showing source time src_t (seconds into the file)."""
|
|
188
|
+
dur = self.info["duration"]
|
|
189
|
+
if dur:
|
|
190
|
+
src_t = min(src_t, max(0.0, dur - 1.5 / max(self.info["fps"] or self.fps, 1)))
|
|
191
|
+
want = round((src_t - self.t0) / self.speed * self.fps)
|
|
192
|
+
if self.proc is None or want < self.index or want > self.index + int(self.fps * 2):
|
|
193
|
+
self._open(src_t)
|
|
194
|
+
want = 0
|
|
195
|
+
while self.index < want:
|
|
196
|
+
if not self._read():
|
|
197
|
+
break
|
|
198
|
+
return self.frame
|
|
199
|
+
|
|
200
|
+
def close(self):
|
|
201
|
+
if self.proc:
|
|
202
|
+
self.stopping.set()
|
|
203
|
+
try:
|
|
204
|
+
self.proc.stdout.close() # type: ignore[union-attr]
|
|
205
|
+
self.proc.kill()
|
|
206
|
+
self.proc.wait(timeout=2)
|
|
207
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
208
|
+
pass
|
|
209
|
+
self.proc = None
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
@lru_cache(maxsize=4)
|
|
213
|
+
def grain_tiles(seed: int = 7, size: int = 256, count: int = 6) -> list[skia.Image]:
|
|
214
|
+
rng = np.random.default_rng(seed)
|
|
215
|
+
tiles = []
|
|
216
|
+
for _ in range(count):
|
|
217
|
+
g = rng.integers(0, 256, (size, size), dtype=np.uint8)
|
|
218
|
+
arr = np.dstack([g, g, g, np.full_like(g, 255)])
|
|
219
|
+
tiles.append(skia.Image.fromarray(np.ascontiguousarray(arr), colorType=skia.kRGBA_8888_ColorType))
|
|
220
|
+
return tiles
|