conformtools 0.6.5 → 0.6.7
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.
- package/README.md +18 -13
- package/dist/account-DJTD3KYK.js +3 -0
- package/dist/arriraw-YIJ3BYNN.js +525 -0
- package/dist/avid-panel/MANIFEST.json +11 -0
- package/dist/avid-panel/avid-manifest.json +46 -0
- package/dist/avid-panel/icon.svg +4 -0
- package/dist/avid-panel/icons/conformtools.svg +4 -0
- package/dist/avid-panel/index.html +26 -0
- package/dist/avid-panel/panel.css +12 -0
- package/dist/avid-panel/panel.js +7 -0
- package/dist/bridge-JQF4V3V2.js +3 -0
- package/dist/browser/timeline_core_bg.wasm +0 -0
- package/dist/chunk-2BPR6LK6.js +3 -0
- package/dist/chunk-3D3Z4TBR.js +3 -0
- package/dist/chunk-55BKURYP.js +378 -0
- package/dist/chunk-5WEZRGXG.js +39 -0
- package/dist/chunk-6V4OEOOX.js +3 -0
- package/dist/chunk-7D7H6VFW.js +3 -0
- package/dist/chunk-A7FNR3T5.js +3 -0
- package/dist/chunk-AACY2V3L.js +3 -0
- package/dist/chunk-AMRJXYL4.js +3 -0
- package/dist/chunk-C2ESM27Z.js +3 -0
- package/dist/chunk-D4WPRRBT.js +3 -0
- package/dist/chunk-D6YDLKSA.js +3 -0
- package/dist/chunk-DKGGJM6Z.js +3 -0
- package/dist/chunk-EUBXH67N.js +7 -0
- package/dist/chunk-GK4YYKJ6.js +19 -0
- package/dist/chunk-GM6QKY7W.js +3 -0
- package/dist/chunk-J2JXLEAI.js +3 -0
- package/dist/chunk-JV7TZDKJ.js +3 -0
- package/dist/chunk-NAFLOZER.js +9 -0
- package/dist/chunk-NFJHWZJX.js +3 -0
- package/dist/chunk-NU3X7P4N.js +3 -0
- package/dist/chunk-P2LL3JMC.js +20 -0
- package/dist/chunk-PFISREY4.js +3 -0
- package/dist/chunk-PFZVET7S.js +3 -0
- package/dist/chunk-PHAMF4JF.js +4 -0
- package/dist/chunk-PLRB2YXJ.js +3 -0
- package/dist/chunk-PSANHDZM.js +3 -0
- package/dist/chunk-RGMTLNMF.js +3 -0
- package/dist/chunk-RJ6JA2LZ.js +3 -0
- package/dist/chunk-S5JDS5PQ.js +5 -0
- package/dist/chunk-SGLQY53R.js +3 -0
- package/dist/chunk-SKFMOLUO.js +8 -0
- package/dist/chunk-SNTAZJ5A.js +6 -0
- package/dist/chunk-TK55FA56.js +3 -0
- package/dist/chunk-TXQR2HI2.js +4 -0
- package/dist/chunk-VIBEEWPC.js +10 -0
- package/dist/chunk-WN53ARHJ.js +3 -0
- package/dist/chunk-XLEINKFL.js +5 -0
- package/dist/claude-setup-IIWUB4CE.js +5 -0
- package/dist/cli.js +17 -0
- package/dist/clip-state-B6JOX3JE.js +3 -0
- package/dist/conformtools-analyze +0 -0
- package/dist/conformtools-decode +0 -0
- package/dist/cr3-wasm-HLJWEV2S.js +3 -0
- package/dist/dng-wasm-CQDLPM5V.js +3 -0
- package/dist/dpx-wasm-TLGMM7BO.js +3 -0
- package/dist/engine-P6H5P6HP.js +5 -0
- package/dist/esm-SFFBP7PS.js +3 -0
- package/dist/exr-wasm-2NPKPTVB.js +3 -0
- package/dist/flame/hook/conformtools_flame/__init__.py +10 -0
- package/dist/flame/hook/conformtools_flame/building.py +191 -0
- package/dist/flame/hook/conformtools_flame/hook.py +177 -0
- package/dist/flame/hook/conformtools_flame/render.py +622 -0
- package/dist/flame/hook/conformtools_flame/util.py +33 -0
- package/dist/flame/hook/conformtools_flame/verbs.py +1037 -0
- package/dist/flame/hook/conformtools_flame_hook.py +42 -0
- package/dist/fonts/gfx/BarlowCondensed-Bold.ttf +0 -0
- package/dist/fonts/gfx/BarlowCondensed-Regular.ttf +0 -0
- package/dist/fonts/gfx/InstrumentSerif-Regular.ttf +0 -0
- package/dist/fonts/gfx/Inter-Bold.ttf +0 -0
- package/dist/fonts/gfx/Inter-Regular.ttf +0 -0
- package/dist/fonts/gfx/JetBrainsMono-Bold.ttf +0 -0
- package/dist/fonts/gfx/JetBrainsMono-Regular.ttf +0 -0
- package/dist/fonts/gfx/OFL.txt +100 -0
- package/dist/framing-SWOD4CWB.js +3 -0
- package/dist/gfx-worker.js +3 -0
- package/dist/h264-JJMZSUWW.js +3 -0
- package/dist/h264-mxf-DCUOGLDU.js +3 -0
- package/dist/host-relink-TWAF6WIG.js +10 -0
- package/dist/hosts-Z666EF7V.js +3 -0
- package/dist/http.js +5 -0
- package/dist/i2o-transfer +0 -0
- package/dist/inspect-FJKYPEXL.js +68 -0
- package/dist/isobmff-VJOWP4MH.js +3 -0
- package/dist/mc-video-5MGGOQN4.js +3 -0
- package/dist/mcp.js +13 -0
- package/dist/media-NZYVREUF.js +3 -0
- package/dist/media_core-YZ3PABEG.js +9 -0
- package/dist/media_core_bg-FDL7GJZP.js +3 -0
- package/dist/media_core_bg-XRBVKQZH.js +3 -0
- package/dist/mxf-FJSRFLJC.js +3 -0
- package/dist/nuke/panel/python/Startup/conformtools_nuke_startup.py +44 -0
- package/dist/nuke/panel/python/conformtools_nuke/__init__.py +10 -0
- package/dist/nuke/panel/python/conformtools_nuke/panel.py +217 -0
- package/dist/nuke/panel/python/conformtools_nuke/verbs.py +837 -0
- package/dist/ops-X7NAREC4.js +3 -0
- package/dist/peer-kit/ctpeer/__init__.py +21 -0
- package/dist/peer-kit/ctpeer/client.py +247 -0
- package/dist/peer-kit/ctpeer/neutral.py +178 -0
- package/dist/peer-kit/ctpeer/pairing.py +139 -0
- package/dist/peer-kit/ctpeer/protocol.py +209 -0
- package/dist/peer-kit/ctpeer/websocket.py +289 -0
- package/dist/premiere-uxp/icons/panel.png +0 -0
- package/dist/premiere-uxp/icons/panel@2x.png +0 -0
- package/dist/premiere-uxp/icons/plugin.png +0 -0
- package/dist/premiere-uxp/icons/plugin@2x.png +0 -0
- package/dist/premiere-uxp/index.html +38 -0
- package/dist/premiere-uxp/index.js +93 -0
- package/dist/premiere-uxp/lib/clipmeta.js +170 -0
- package/dist/premiere-uxp/lib/ctx.js +68 -0
- package/dist/premiere-uxp/lib/edit.js +516 -0
- package/dist/premiere-uxp/lib/handles.js +57 -0
- package/dist/premiere-uxp/lib/markers.js +198 -0
- package/dist/premiere-uxp/lib/pairing.js +67 -0
- package/dist/premiere-uxp/lib/premiere.js +91 -0
- package/dist/premiere-uxp/lib/probe.js +452 -0
- package/dist/premiere-uxp/lib/protocol.js +165 -0
- package/dist/premiere-uxp/lib/render.js +45 -0
- package/dist/premiere-uxp/lib/session.js +85 -0
- package/dist/premiere-uxp/lib/sizing.js +325 -0
- package/dist/premiere-uxp/lib/time.js +88 -0
- package/dist/premiere-uxp/lib/timeline.js +336 -0
- package/dist/premiere-uxp/lib/verbs.js +21 -0
- package/dist/premiere-uxp/lib/write.js +97 -0
- package/dist/premiere-uxp/manifest.json +102 -0
- package/dist/probe-F7WQHMIA.js +3 -0
- package/dist/prores-RIG37OIH.js +526 -0
- package/dist/r3d-CXUNG6VS.js +1025 -0
- package/dist/r3d-T5O6IIZZ.js +3 -0
- package/dist/resolve-bridge.py +2286 -0
- package/dist/resolve-presets/conform.tools.xml +127 -0
- package/dist/source-QGWWLMME.js +3 -0
- package/dist/statusline-GMMCFMOA.js +4 -0
- package/dist/statusline.js +3 -0
- package/dist/still-P4JJNTEO.js +3 -0
- package/dist/still-wasm-DN5LPASS.js +3 -0
- package/dist/store-7IOEBOZY.js +3 -0
- package/dist/tiff-wasm-BPRDR6EB.js +3 -0
- package/dist/timeline-DQG6TVPF.js +3 -0
- package/dist/timeline_core-IOENXK4Z.js +3 -0
- package/dist/timeline_core_bg-JW42YM3G.js +3 -0
- package/dist/udf_bg-B37GKRIH.js +3 -0
- package/dist/wasm/media_core_bg.wasm +0 -0
- package/dist/wasm/udf_bg.wasm +0 -0
- package/dist/wasm-threads/media_core_bg.wasm +0 -0
- package/dist/wav-64SC6P7U.js +3 -0
- package/package.json +6 -4
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
"""Protocol 1, peer side: the handle table and the verb dispatcher.
|
|
2
|
+
|
|
3
|
+
The app sends `{"type":"request","id":N,"method":"<capability>.<verb>",
|
|
4
|
+
"params":{...}}`; the peer answers `{"type":"response","id":N,"ok":true,
|
|
5
|
+
"result":...}` or `{"ok":false,"error":{"code","message"}}`. The dispatcher
|
|
6
|
+
here is the ONLY thing that turns a request into a call, and it can only call
|
|
7
|
+
a function the host plugin put in its verb table under that exact method name,
|
|
8
|
+
for a capability the plugin announced. Nothing a request carries is evaluated,
|
|
9
|
+
imported, opened as a path to run, or used to pick an attribute by name.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import inspect
|
|
15
|
+
import itertools
|
|
16
|
+
import threading
|
|
17
|
+
from typing import Any, Callable, Dict, Iterable, List, Optional
|
|
18
|
+
|
|
19
|
+
PROTOCOL_VERSION = 1
|
|
20
|
+
H = "$h"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class PeerError(Exception):
|
|
24
|
+
"""A refusal the app should see with its own code (`no_timeline`,
|
|
25
|
+
`bad_handle`, `read_only`, ...)."""
|
|
26
|
+
|
|
27
|
+
def __init__(self, code: str, message: str = ""):
|
|
28
|
+
super().__init__(message or code)
|
|
29
|
+
self.code = code or "peer_error"
|
|
30
|
+
self.message = message or code
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class Handles:
|
|
34
|
+
"""Host objects behind ids this peer mints: `{"$h": "seq:3"}`. The app
|
|
35
|
+
only ever hands an id back. Ids are stable for the life of the peer, so a
|
|
36
|
+
tool can reuse one across calls. `key` says when two Python wrappers are
|
|
37
|
+
the same host object (Flame and Hiero hand out fresh wrappers per access),
|
|
38
|
+
defaulting to the object itself when it is hashable, else its id()."""
|
|
39
|
+
|
|
40
|
+
def __init__(self) -> None:
|
|
41
|
+
self._by_id: Dict[str, Any] = {}
|
|
42
|
+
self._by_key: Dict[Any, str] = {}
|
|
43
|
+
self._n = itertools.count(1)
|
|
44
|
+
self._lock = threading.Lock()
|
|
45
|
+
|
|
46
|
+
def wrap(self, kind: str, obj: Any, key: Any = None) -> Optional[Dict[str, str]]:
|
|
47
|
+
if obj is None:
|
|
48
|
+
return None
|
|
49
|
+
if key is None:
|
|
50
|
+
try:
|
|
51
|
+
hash(obj)
|
|
52
|
+
key = ("obj", obj)
|
|
53
|
+
except TypeError:
|
|
54
|
+
key = ("id", id(obj))
|
|
55
|
+
key = (kind, key)
|
|
56
|
+
with self._lock:
|
|
57
|
+
hid = self._by_key.get(key)
|
|
58
|
+
if hid is None:
|
|
59
|
+
hid = f"{kind}:{next(self._n)}"
|
|
60
|
+
self._by_key[key] = hid
|
|
61
|
+
self._by_id[hid] = obj # the latest wrapper for that object
|
|
62
|
+
return {H: hid}
|
|
63
|
+
|
|
64
|
+
def get(self, handle: Any, *kinds: str) -> Any:
|
|
65
|
+
hid = handle.get(H) if isinstance(handle, dict) else None
|
|
66
|
+
if not isinstance(hid, str) or not hid:
|
|
67
|
+
raise PeerError("bad_handle", "not a handle")
|
|
68
|
+
kind = hid.split(":", 1)[0]
|
|
69
|
+
if kinds and kind not in kinds:
|
|
70
|
+
raise PeerError("bad_handle", f"expected a {' or '.join(kinds)}, got {hid}")
|
|
71
|
+
with self._lock:
|
|
72
|
+
if hid not in self._by_id:
|
|
73
|
+
raise PeerError("bad_handle", f"unknown handle {hid}")
|
|
74
|
+
return self._by_id[hid]
|
|
75
|
+
|
|
76
|
+
@staticmethod
|
|
77
|
+
def kind_of(handle: Any) -> str:
|
|
78
|
+
hid = handle.get(H) if isinstance(handle, dict) else None
|
|
79
|
+
return hid.split(":", 1)[0] if isinstance(hid, str) else ""
|
|
80
|
+
|
|
81
|
+
@staticmethod
|
|
82
|
+
def id_of(handle: Any) -> str:
|
|
83
|
+
return str(handle.get(H) or "") if isinstance(handle, dict) else ""
|
|
84
|
+
|
|
85
|
+
def clear(self) -> None:
|
|
86
|
+
with self._lock:
|
|
87
|
+
self._by_id.clear()
|
|
88
|
+
self._by_key.clear()
|
|
89
|
+
|
|
90
|
+
def __len__(self) -> int:
|
|
91
|
+
return len(self._by_id)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
#: The attribute `off_main` sets (read through bound methods too).
|
|
95
|
+
OFF_MAIN_ATTR = "ctpeer_off_main"
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def off_main(fn: Callable[..., Any]) -> Callable[..., Any]:
|
|
99
|
+
"""Mark a verb that must NOT wait for the host's main thread: it touches
|
|
100
|
+
no host API (a job table, the file system) and has to answer while the
|
|
101
|
+
main thread is busy - Flame's foreground export holds it for the whole
|
|
102
|
+
render, and a status poll queued behind it would time out. The
|
|
103
|
+
Dispatcher runs a marked verb directly on its worker thread."""
|
|
104
|
+
setattr(fn, OFF_MAIN_ATTR, True)
|
|
105
|
+
return fn
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _accepted_params(fn: Callable[..., Any]) -> Optional[frozenset]:
|
|
109
|
+
"""The keyword names `fn` takes, or None when it takes **kwargs."""
|
|
110
|
+
try:
|
|
111
|
+
sig = inspect.signature(fn)
|
|
112
|
+
except (TypeError, ValueError):
|
|
113
|
+
return None
|
|
114
|
+
names = set()
|
|
115
|
+
for p in sig.parameters.values():
|
|
116
|
+
if p.kind == p.VAR_KEYWORD:
|
|
117
|
+
return None
|
|
118
|
+
if p.kind in (p.POSITIONAL_OR_KEYWORD, p.KEYWORD_ONLY):
|
|
119
|
+
names.add(p.name)
|
|
120
|
+
return frozenset(names)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
class Dispatcher:
|
|
124
|
+
"""`handle(message) -> response`. Never raises."""
|
|
125
|
+
|
|
126
|
+
def __init__(self, verbs: Dict[str, Callable[..., Any]], capabilities: Iterable[str],
|
|
127
|
+
run_on_main: Optional[Callable[[Callable[[], Any]], Any]] = None,
|
|
128
|
+
log: Optional[Callable[[str], None]] = None):
|
|
129
|
+
self.verbs = dict(verbs)
|
|
130
|
+
self.capabilities = list(capabilities)
|
|
131
|
+
self.run_on_main = run_on_main or (lambda fn: fn())
|
|
132
|
+
self.log = log or (lambda line: None)
|
|
133
|
+
self._accepts = {m: _accepted_params(fn) for m, fn in self.verbs.items()}
|
|
134
|
+
self.calls: List[str] = []
|
|
135
|
+
|
|
136
|
+
def handle(self, message: Any) -> Dict[str, Any]:
|
|
137
|
+
rid = message.get("id") if isinstance(message, dict) else None
|
|
138
|
+
if not isinstance(message, dict) or message.get("type") != "request":
|
|
139
|
+
return _error(rid, "bad_request", "not a request")
|
|
140
|
+
method = message.get("method")
|
|
141
|
+
if not isinstance(method, str):
|
|
142
|
+
return _error(rid, "bad_request", "method is not a string")
|
|
143
|
+
params = message.get("params") or {}
|
|
144
|
+
if not isinstance(params, dict):
|
|
145
|
+
return _error(rid, "bad_request", "params is not an object")
|
|
146
|
+
capability = method.split(".", 1)[0]
|
|
147
|
+
if capability not in self.capabilities:
|
|
148
|
+
return _error(rid, "capability_missing", f"{capability} is not supported")
|
|
149
|
+
fn = self.verbs.get(method)
|
|
150
|
+
if fn is None:
|
|
151
|
+
return _error(rid, "unknown_method", method)
|
|
152
|
+
accepts = self._accepts.get(method)
|
|
153
|
+
# A param this verb does not take is dropped (an app newer than the
|
|
154
|
+
# plugin may add an optional one), never passed through by name.
|
|
155
|
+
kwargs = {str(k): v for k, v in params.items() if accepts is None or str(k) in accepts}
|
|
156
|
+
self.calls.append(method)
|
|
157
|
+
try:
|
|
158
|
+
if getattr(fn, OFF_MAIN_ATTR, False):
|
|
159
|
+
result = fn(**kwargs) # touches no host API (see `off_main`)
|
|
160
|
+
else:
|
|
161
|
+
result = self.run_on_main(lambda: fn(**kwargs))
|
|
162
|
+
except PeerError as e:
|
|
163
|
+
return _error(rid, e.code, e.message)
|
|
164
|
+
except TypeError as e:
|
|
165
|
+
self.log(f"{method}: {e}")
|
|
166
|
+
return _error(rid, "bad_params", str(e))
|
|
167
|
+
except Exception as e: # a plugin answers with an error, it does not die
|
|
168
|
+
self.log(f"{method}: {type(e).__name__}: {e}")
|
|
169
|
+
return _error(rid, getattr(e, "code", None) or "peer_error", str(e) or type(e).__name__)
|
|
170
|
+
return {"type": "response", "id": rid, "ok": True, "result": result}
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _error(rid: Any, code: str, message: str) -> Dict[str, Any]:
|
|
174
|
+
return {"type": "response", "id": rid, "ok": False, "error": {"code": str(code), "message": str(message)}}
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def hello(token: str, host: Dict[str, Any], capabilities: Iterable[str], optional_verbs: Iterable[str] = ()) -> Dict[str, Any]:
|
|
178
|
+
return {"type": "hello", "protocol": PROTOCOL_VERSION, "token": token, "host": dict(host),
|
|
179
|
+
"capabilities": list(capabilities), "optional_verbs": list(optional_verbs)}
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def idle_marshaller(schedule: Callable[[Callable[[], None]], Any], timeout: float = 25.0) -> Callable[[Callable[[], Any]], Any]:
|
|
183
|
+
"""A `run_on_main` built from a host's "run this on the main thread later"
|
|
184
|
+
(Flame: `flame.schedule_idle_event`; Qt: a single-shot timer). The calling
|
|
185
|
+
thread waits for the result; an exception is re-raised here. When called
|
|
186
|
+
ON the main thread it runs inline (waiting would deadlock)."""
|
|
187
|
+
|
|
188
|
+
def run_on_main(fn: Callable[[], Any]) -> Any:
|
|
189
|
+
if threading.current_thread() is threading.main_thread():
|
|
190
|
+
return fn()
|
|
191
|
+
done = threading.Event()
|
|
192
|
+
box: Dict[str, Any] = {}
|
|
193
|
+
|
|
194
|
+
def task() -> None:
|
|
195
|
+
try:
|
|
196
|
+
box["result"] = fn()
|
|
197
|
+
except BaseException as e: # carried back to the waiting thread
|
|
198
|
+
box["error"] = e
|
|
199
|
+
finally:
|
|
200
|
+
done.set()
|
|
201
|
+
|
|
202
|
+
schedule(task)
|
|
203
|
+
if not done.wait(timeout):
|
|
204
|
+
raise PeerError("main_thread_busy", f"the host's main thread did not run the call within {timeout:g} s")
|
|
205
|
+
if "error" in box:
|
|
206
|
+
raise box["error"]
|
|
207
|
+
return box.get("result")
|
|
208
|
+
|
|
209
|
+
return run_on_main
|
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
"""A small RFC 6455 WebSocket CLIENT on the standard library only.
|
|
2
|
+
|
|
3
|
+
Flame and Nuke ship their own Pythons (3.9 - 3.13) and we may not install a
|
|
4
|
+
package into either, so this is the whole transport: a TCP socket to the app's
|
|
5
|
+
loopback bridge, the HTTP upgrade, and text frames. Only what the host bridge
|
|
6
|
+
uses is here - no TLS (loopback only; `connect` refuses anything that is not
|
|
7
|
+
`ws://127.0.0.1` or `ws://localhost`), no extensions, no binary messages.
|
|
8
|
+
|
|
9
|
+
* Client frames are MASKED (RFC 6455 5.3) with a fresh key from `os.urandom`.
|
|
10
|
+
* Server frames must NOT be masked; a masked one is a protocol error.
|
|
11
|
+
* Fragmented messages are reassembled; control frames may interleave.
|
|
12
|
+
* A ping is answered with a pong carrying the same payload.
|
|
13
|
+
* `max_message` caps a reassembled message (the bridge's own cap is 8 MiB).
|
|
14
|
+
* A close frame is answered once and ends the conversation.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import base64
|
|
20
|
+
import hashlib
|
|
21
|
+
import os
|
|
22
|
+
import socket
|
|
23
|
+
import struct
|
|
24
|
+
import threading
|
|
25
|
+
from typing import Optional, Tuple
|
|
26
|
+
from urllib.parse import urlparse
|
|
27
|
+
|
|
28
|
+
GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
|
|
29
|
+
MAX_MESSAGE_BYTES = 8 * 1024 * 1024
|
|
30
|
+
|
|
31
|
+
OP_CONT, OP_TEXT, OP_BINARY, OP_CLOSE, OP_PING, OP_PONG = 0x0, 0x1, 0x2, 0x8, 0x9, 0xA
|
|
32
|
+
LOOPBACK_HOSTS = ("127.0.0.1", "localhost")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class WebSocketError(Exception):
|
|
36
|
+
"""The connection failed or the peer broke the protocol."""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class ConnectionClosed(WebSocketError):
|
|
40
|
+
def __init__(self, code: int = 1000, reason: str = ""):
|
|
41
|
+
super().__init__(f"closed ({code}) {reason}".strip())
|
|
42
|
+
self.code = code
|
|
43
|
+
self.reason = reason
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def parse_loopback_url(url: str) -> Tuple[str, int, str]:
|
|
47
|
+
"""`ws://127.0.0.1:48127/host-bridge` -> (host, port, path). Anything that
|
|
48
|
+
is not plain ws:// on loopback is refused: this client never leaves the
|
|
49
|
+
machine."""
|
|
50
|
+
u = urlparse(str(url or ""))
|
|
51
|
+
if u.scheme != "ws":
|
|
52
|
+
raise WebSocketError(f"not a ws:// url: {url!r}")
|
|
53
|
+
host = (u.hostname or "").lower()
|
|
54
|
+
if host not in LOOPBACK_HOSTS:
|
|
55
|
+
raise WebSocketError(f"refusing a non-loopback host: {host!r}")
|
|
56
|
+
if not u.port:
|
|
57
|
+
raise WebSocketError("the url has no port")
|
|
58
|
+
return host, int(u.port), u.path or "/"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def accept_key(key: str) -> str:
|
|
62
|
+
return base64.b64encode(hashlib.sha1((key + GUID).encode("ascii")).digest()).decode("ascii")
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def mask(payload: bytes, key: bytes) -> bytes:
|
|
66
|
+
if not payload:
|
|
67
|
+
return b""
|
|
68
|
+
# XOR in one go: int arithmetic is much faster than a per-byte loop on 8 MiB.
|
|
69
|
+
n = len(payload)
|
|
70
|
+
k = (key * (n // 4 + 1))[:n]
|
|
71
|
+
return (int.from_bytes(payload, "big") ^ int.from_bytes(k, "big")).to_bytes(n, "big")
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def encode_frame(opcode: int, payload: bytes, masked: bool = True, fin: bool = True, key: Optional[bytes] = None) -> bytes:
|
|
75
|
+
head = bytearray([(0x80 if fin else 0) | (opcode & 0x0F)])
|
|
76
|
+
n = len(payload)
|
|
77
|
+
mbit = 0x80 if masked else 0
|
|
78
|
+
if n < 126:
|
|
79
|
+
head.append(mbit | n)
|
|
80
|
+
elif n < 1 << 16:
|
|
81
|
+
head.append(mbit | 126)
|
|
82
|
+
head += struct.pack("!H", n)
|
|
83
|
+
else:
|
|
84
|
+
head.append(mbit | 127)
|
|
85
|
+
head += struct.pack("!Q", n)
|
|
86
|
+
if masked:
|
|
87
|
+
key = key or os.urandom(4)
|
|
88
|
+
return bytes(head) + key + mask(payload, key)
|
|
89
|
+
return bytes(head) + payload
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class WebSocket:
|
|
93
|
+
"""One client connection. `recv()` returns the next TEXT message (str) or
|
|
94
|
+
raises `ConnectionClosed`; `send_text` is thread-safe."""
|
|
95
|
+
|
|
96
|
+
def __init__(self, sock: socket.socket, max_message: int = MAX_MESSAGE_BYTES):
|
|
97
|
+
self.sock = sock
|
|
98
|
+
self.max_message = int(max_message)
|
|
99
|
+
self._send_lock = threading.Lock()
|
|
100
|
+
self._buf = b""
|
|
101
|
+
self.closed = False
|
|
102
|
+
|
|
103
|
+
# -- connecting ------------------------------------------------------
|
|
104
|
+
@classmethod
|
|
105
|
+
def connect(cls, url: str, timeout: float = 5.0, max_message: int = MAX_MESSAGE_BYTES) -> "WebSocket":
|
|
106
|
+
host, port, path = parse_loopback_url(url)
|
|
107
|
+
try:
|
|
108
|
+
sock = socket.create_connection((host, port), timeout=timeout)
|
|
109
|
+
except OSError as e:
|
|
110
|
+
raise WebSocketError(f"cannot reach {host}:{port}: {e}") from e
|
|
111
|
+
try:
|
|
112
|
+
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
|
|
113
|
+
key = base64.b64encode(os.urandom(16)).decode("ascii")
|
|
114
|
+
# No Origin header: the bridge refuses browser origins, and a native
|
|
115
|
+
# client has none (host_bridge.rs `origin_allowed`).
|
|
116
|
+
request = (
|
|
117
|
+
f"GET {path} HTTP/1.1\r\n"
|
|
118
|
+
f"Host: {host}:{port}\r\n"
|
|
119
|
+
"Upgrade: websocket\r\n"
|
|
120
|
+
"Connection: Upgrade\r\n"
|
|
121
|
+
f"Sec-WebSocket-Key: {key}\r\n"
|
|
122
|
+
"Sec-WebSocket-Version: 13\r\n\r\n"
|
|
123
|
+
)
|
|
124
|
+
sock.sendall(request.encode("ascii"))
|
|
125
|
+
ws = cls(sock, max_message)
|
|
126
|
+
head = ws._read_http_head()
|
|
127
|
+
status, headers = _parse_http_head(head)
|
|
128
|
+
if status != 101:
|
|
129
|
+
raise WebSocketError(f"upgrade refused: HTTP {status}")
|
|
130
|
+
if headers.get("upgrade", "").lower() != "websocket" or "upgrade" not in headers.get("connection", "").lower():
|
|
131
|
+
raise WebSocketError("the server did not switch to websocket")
|
|
132
|
+
if headers.get("sec-websocket-accept", "") != accept_key(key):
|
|
133
|
+
raise WebSocketError("bad Sec-WebSocket-Accept")
|
|
134
|
+
sock.settimeout(None)
|
|
135
|
+
return ws
|
|
136
|
+
except BaseException:
|
|
137
|
+
try:
|
|
138
|
+
sock.close()
|
|
139
|
+
except OSError:
|
|
140
|
+
pass
|
|
141
|
+
raise
|
|
142
|
+
|
|
143
|
+
def _read_http_head(self) -> bytes:
|
|
144
|
+
while b"\r\n\r\n" not in self._buf:
|
|
145
|
+
if len(self._buf) > 16384:
|
|
146
|
+
raise WebSocketError("HTTP head too large")
|
|
147
|
+
chunk = self.sock.recv(4096)
|
|
148
|
+
if not chunk:
|
|
149
|
+
raise WebSocketError("connection closed during the upgrade")
|
|
150
|
+
self._buf += chunk
|
|
151
|
+
head, _, rest = self._buf.partition(b"\r\n\r\n")
|
|
152
|
+
self._buf = rest
|
|
153
|
+
return head
|
|
154
|
+
|
|
155
|
+
# -- low level -------------------------------------------------------
|
|
156
|
+
def _read_exact(self, n: int) -> bytes:
|
|
157
|
+
while len(self._buf) < n:
|
|
158
|
+
try:
|
|
159
|
+
chunk = self.sock.recv(max(65536, n - len(self._buf)))
|
|
160
|
+
except OSError as e:
|
|
161
|
+
raise ConnectionClosed(1006, str(e)) from e
|
|
162
|
+
if not chunk:
|
|
163
|
+
raise ConnectionClosed(1006, "connection lost")
|
|
164
|
+
self._buf += chunk
|
|
165
|
+
out, self._buf = self._buf[:n], self._buf[n:]
|
|
166
|
+
return out
|
|
167
|
+
|
|
168
|
+
def _read_frame(self) -> Tuple[bool, int, bytes]:
|
|
169
|
+
b1, b2 = self._read_exact(2)
|
|
170
|
+
fin = bool(b1 & 0x80)
|
|
171
|
+
if b1 & 0x70:
|
|
172
|
+
raise WebSocketError("reserved bits set (no extension was negotiated)")
|
|
173
|
+
opcode = b1 & 0x0F
|
|
174
|
+
masked = bool(b2 & 0x80)
|
|
175
|
+
n = b2 & 0x7F
|
|
176
|
+
if n == 126:
|
|
177
|
+
(n,) = struct.unpack("!H", self._read_exact(2))
|
|
178
|
+
elif n == 127:
|
|
179
|
+
(n,) = struct.unpack("!Q", self._read_exact(8))
|
|
180
|
+
if masked:
|
|
181
|
+
raise WebSocketError("a server frame must not be masked")
|
|
182
|
+
if opcode >= 0x8 and (n > 125 or not fin):
|
|
183
|
+
raise WebSocketError("bad control frame")
|
|
184
|
+
if n > self.max_message:
|
|
185
|
+
raise WebSocketError(f"frame of {n} bytes exceeds the {self.max_message} byte cap")
|
|
186
|
+
return fin, opcode, self._read_exact(n)
|
|
187
|
+
|
|
188
|
+
def _send_frame(self, opcode: int, payload: bytes) -> None:
|
|
189
|
+
data = encode_frame(opcode, payload, masked=True)
|
|
190
|
+
with self._send_lock:
|
|
191
|
+
if self.closed and opcode != OP_CLOSE:
|
|
192
|
+
raise ConnectionClosed(1006, "already closed")
|
|
193
|
+
try:
|
|
194
|
+
self.sock.sendall(data)
|
|
195
|
+
except OSError as e:
|
|
196
|
+
raise ConnectionClosed(1006, str(e)) from e
|
|
197
|
+
|
|
198
|
+
# -- public ----------------------------------------------------------
|
|
199
|
+
def send_text(self, text: str) -> None:
|
|
200
|
+
payload = text.encode("utf-8")
|
|
201
|
+
if len(payload) > self.max_message:
|
|
202
|
+
raise WebSocketError(f"message of {len(payload)} bytes exceeds the {self.max_message} byte cap")
|
|
203
|
+
self._send_frame(OP_TEXT, payload)
|
|
204
|
+
|
|
205
|
+
def ping(self, payload: bytes = b"") -> None:
|
|
206
|
+
self._send_frame(OP_PING, payload[:125])
|
|
207
|
+
|
|
208
|
+
def recv(self) -> str:
|
|
209
|
+
"""The next complete text message. Pings are answered, pongs ignored,
|
|
210
|
+
a close is acknowledged and raised as `ConnectionClosed`."""
|
|
211
|
+
parts = []
|
|
212
|
+
size = 0
|
|
213
|
+
opcode0 = None
|
|
214
|
+
while True:
|
|
215
|
+
fin, opcode, payload = self._read_frame()
|
|
216
|
+
if opcode == OP_PING:
|
|
217
|
+
self._send_frame(OP_PONG, payload)
|
|
218
|
+
continue
|
|
219
|
+
if opcode == OP_PONG:
|
|
220
|
+
continue
|
|
221
|
+
if opcode == OP_CLOSE:
|
|
222
|
+
code = struct.unpack("!H", payload[:2])[0] if len(payload) >= 2 else 1005
|
|
223
|
+
reason = payload[2:].decode("utf-8", "replace")
|
|
224
|
+
self._close_reply(payload[:2] if len(payload) >= 2 else b"")
|
|
225
|
+
raise ConnectionClosed(code, reason)
|
|
226
|
+
if opcode == OP_CONT:
|
|
227
|
+
if opcode0 is None:
|
|
228
|
+
raise WebSocketError("continuation without a first frame")
|
|
229
|
+
elif opcode in (OP_TEXT, OP_BINARY):
|
|
230
|
+
if opcode0 is not None:
|
|
231
|
+
raise WebSocketError("new message inside a fragmented one")
|
|
232
|
+
opcode0 = opcode
|
|
233
|
+
else:
|
|
234
|
+
raise WebSocketError(f"unknown opcode {opcode}")
|
|
235
|
+
size += len(payload)
|
|
236
|
+
if size > self.max_message:
|
|
237
|
+
raise WebSocketError(f"message exceeds the {self.max_message} byte cap")
|
|
238
|
+
parts.append(payload)
|
|
239
|
+
if fin:
|
|
240
|
+
if opcode0 == OP_BINARY:
|
|
241
|
+
raise WebSocketError("binary messages are not part of the protocol")
|
|
242
|
+
try:
|
|
243
|
+
return b"".join(parts).decode("utf-8")
|
|
244
|
+
except UnicodeDecodeError as e:
|
|
245
|
+
raise WebSocketError("text frame is not UTF-8") from e
|
|
246
|
+
|
|
247
|
+
def _close_reply(self, code: bytes) -> None:
|
|
248
|
+
if self.closed:
|
|
249
|
+
return
|
|
250
|
+
try:
|
|
251
|
+
self._send_frame(OP_CLOSE, code)
|
|
252
|
+
except WebSocketError:
|
|
253
|
+
pass
|
|
254
|
+
self.closed = True
|
|
255
|
+
self._shutdown()
|
|
256
|
+
|
|
257
|
+
def close(self, code: int = 1000, reason: str = "") -> None:
|
|
258
|
+
if self.closed:
|
|
259
|
+
return
|
|
260
|
+
try:
|
|
261
|
+
self._send_frame(OP_CLOSE, struct.pack("!H", code) + reason.encode("utf-8")[:120])
|
|
262
|
+
except WebSocketError:
|
|
263
|
+
pass
|
|
264
|
+
self.closed = True
|
|
265
|
+
self._shutdown()
|
|
266
|
+
|
|
267
|
+
def _shutdown(self) -> None:
|
|
268
|
+
try:
|
|
269
|
+
self.sock.shutdown(socket.SHUT_RDWR)
|
|
270
|
+
except OSError:
|
|
271
|
+
pass
|
|
272
|
+
try:
|
|
273
|
+
self.sock.close()
|
|
274
|
+
except OSError:
|
|
275
|
+
pass
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def _parse_http_head(head: bytes):
|
|
279
|
+
lines = head.decode("latin-1").split("\r\n")
|
|
280
|
+
try:
|
|
281
|
+
status = int(lines[0].split(" ", 2)[1])
|
|
282
|
+
except (IndexError, ValueError) as e:
|
|
283
|
+
raise WebSocketError(f"bad HTTP status line: {lines[0]!r}") from e
|
|
284
|
+
headers = {}
|
|
285
|
+
for line in lines[1:]:
|
|
286
|
+
k, sep, v = line.partition(":")
|
|
287
|
+
if sep:
|
|
288
|
+
headers[k.strip().lower()] = v.strip()
|
|
289
|
+
return status, headers
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
<!DOCTYPE html>
|
|
2
|
+
<html>
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="utf-8" />
|
|
5
|
+
<style>
|
|
6
|
+
body { margin: 0; padding: 10px; font: 12px/1.4 -apple-system, "Segoe UI", sans-serif; color: #d4d4d4; background: #1e1e1e; }
|
|
7
|
+
h1 { font-size: 13px; letter-spacing: .04em; margin: 0 0 8px; text-transform: uppercase; }
|
|
8
|
+
h1 b { color: #FF3C00; }
|
|
9
|
+
.row { display: flex; align-items: center; gap: 8px; margin: 6px 0; }
|
|
10
|
+
.dot { width: 10px; height: 10px; border-radius: 2px; background: #555; flex: none; }
|
|
11
|
+
.dot.on { background: #34d399; } .dot.wait { background: #FFDE00; } .dot.off { background: #FF3C00; }
|
|
12
|
+
.muted { color: #8a8a8a; } .mono { font-family: ui-monospace, Menlo, monospace; font-size: 11px; }
|
|
13
|
+
button { background: #2a2a2a; color: #d4d4d4; border: 1px solid #444; border-radius: 4px; padding: 4px 8px; font-size: 11px; cursor: pointer; }
|
|
14
|
+
button.primary { background: #FF3C00; border-color: #FF3C00; color: #fff; }
|
|
15
|
+
textarea { width: 100%; box-sizing: border-box; background: #141414; color: #ccc; border: 1px solid #333; border-radius: 4px; font-size: 11px; min-height: 48px; }
|
|
16
|
+
#log { margin-top: 8px; background: #141414; border: 1px solid #333; border-radius: 4px; padding: 6px; height: 140px; overflow: auto; white-space: pre-wrap; }
|
|
17
|
+
details { margin-top: 8px; } summary { cursor: pointer; color: #8a8a8a; }
|
|
18
|
+
</style>
|
|
19
|
+
</head>
|
|
20
|
+
<body>
|
|
21
|
+
<h1>CONFORM<b>.</b>TOOLS</h1>
|
|
22
|
+
<div class="row"><span id="dot" class="dot"></span><span id="state">Starting…</span></div>
|
|
23
|
+
<div class="row muted mono" id="detail"></div>
|
|
24
|
+
<div class="row">
|
|
25
|
+
<button id="reconnect">Reconnect</button>
|
|
26
|
+
<button id="pick">Pick pairing folder…</button>
|
|
27
|
+
<button id="forget" title="Forget the pasted pairing and the picked folder">Forget</button>
|
|
28
|
+
</div>
|
|
29
|
+
<details>
|
|
30
|
+
<summary>Paste pairing (local only)</summary>
|
|
31
|
+
<p class="muted">conform.tools › Settings › Developer › Host bridge › “Show pairing” — paste the JSON here. It stays on this machine.</p>
|
|
32
|
+
<textarea id="paste" placeholder='{"protocol":1,"url":"ws://127.0.0.1:…/host-bridge","port":…,"token":"…"}'></textarea>
|
|
33
|
+
<div class="row"><button id="save" class="primary">Use this pairing</button></div>
|
|
34
|
+
</details>
|
|
35
|
+
<div id="log" class="mono"></div>
|
|
36
|
+
<script src="index.js"></script>
|
|
37
|
+
</body>
|
|
38
|
+
</html>
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// Panel entry: wires the bridge client to the Premiere verbs and to the UI.
|
|
2
|
+
"use strict";
|
|
3
|
+
|
|
4
|
+
const { BridgeClient } = require("./lib/protocol");
|
|
5
|
+
const { makeReader, dataDirs, maskToken } = require("./lib/pairing");
|
|
6
|
+
const P = require("./lib/premiere");
|
|
7
|
+
|
|
8
|
+
const { VERBS, CAPABILITIES, OPTIONAL_VERBS } = require("./lib/verbs");
|
|
9
|
+
|
|
10
|
+
const $ = (id) => document.getElementById(id);
|
|
11
|
+
const lines = [];
|
|
12
|
+
function log(line) {
|
|
13
|
+
const ts = new Date().toISOString().slice(11, 19);
|
|
14
|
+
lines.push(`${ts} ${line}`);
|
|
15
|
+
while (lines.length > 200) lines.shift();
|
|
16
|
+
const el = $("log");
|
|
17
|
+
if (el) { el.textContent = lines.join("\n"); el.scrollTop = el.scrollHeight; }
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const uxp = P.uxp();
|
|
21
|
+
const lfs = uxp && uxp.storage && uxp.storage.localFileSystem;
|
|
22
|
+
const os = (() => { try { return require("os"); } catch (_) { return null; } })();
|
|
23
|
+
const home = os && os.homedir ? os.homedir() : "";
|
|
24
|
+
const platform = P.platform();
|
|
25
|
+
|
|
26
|
+
async function entryAt(path) {
|
|
27
|
+
if (!lfs) throw new Error("no file system access");
|
|
28
|
+
return lfs.getEntryWithUrl(platform === "win32" ? `file:///${path.replace(/\\/g, "/")}` : `file://${path}`);
|
|
29
|
+
}
|
|
30
|
+
const readFileAt = async (path) => (await entryAt(path)).read();
|
|
31
|
+
const mtimeAt = async (path) => +new Date((await (await entryAt(path)).getMetadata()).dateModified);
|
|
32
|
+
|
|
33
|
+
async function pickedFolderRead() {
|
|
34
|
+
const token = localStorage.getItem("conformtools.pairingFolder");
|
|
35
|
+
if (!token || !lfs) return null;
|
|
36
|
+
const folder = await lfs.getEntryForPersistentToken(token);
|
|
37
|
+
const entry = await folder.getEntry("pairing.json");
|
|
38
|
+
return entry.read();
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const readPairing = makeReader({
|
|
42
|
+
candidates: () => (home ? dataDirs(home, platform) : []),
|
|
43
|
+
readFileAt, mtimeAt, pickedFolderRead, storage: localStorage,
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
const client = new BridgeClient({
|
|
47
|
+
makeSocket: (url) => new WebSocket(url),
|
|
48
|
+
readPairing: async () => {
|
|
49
|
+
const p = await readPairing();
|
|
50
|
+
$("detail").textContent = `${p.url} token ${maskToken(p.token)} (${p.source})`;
|
|
51
|
+
return p;
|
|
52
|
+
},
|
|
53
|
+
host: { id: "premiere", name: "Premiere Pro", version: P.hostVersion() || "unknown", platform },
|
|
54
|
+
capabilities: CAPABILITIES,
|
|
55
|
+
optionalVerbs: OPTIONAL_VERBS,
|
|
56
|
+
verbs: VERBS,
|
|
57
|
+
log,
|
|
58
|
+
onState: (state, detail) => {
|
|
59
|
+
const dot = $("dot");
|
|
60
|
+
const text = { idle: "Idle", unpaired: "Not paired", connecting: "Connecting…", hello: "Pairing…", connected: "Connected to conform.tools", closed: "Disconnected", refused: "Refused by conform.tools", stopped: "Stopped" }[state] || state;
|
|
61
|
+
$("state").textContent = detail ? `${text} - ${detail}` : text;
|
|
62
|
+
dot.className = "dot " + (state === "connected" ? "on" : state === "connecting" || state === "hello" ? "wait" : state === "refused" || state === "unpaired" ? "off" : "");
|
|
63
|
+
log(`state: ${state}${detail ? " (" + detail + ")" : ""}`);
|
|
64
|
+
},
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
$("reconnect").addEventListener("click", () => { client.stop(); client.start(); });
|
|
68
|
+
$("pick").addEventListener("click", async () => {
|
|
69
|
+
if (!lfs) return log("no file system access");
|
|
70
|
+
const folder = await lfs.getFolder();
|
|
71
|
+
if (!folder) return;
|
|
72
|
+
localStorage.setItem("conformtools.pairingFolder", await lfs.createPersistentToken(folder));
|
|
73
|
+
log(`pairing folder: ${folder.nativePath || folder.name}`);
|
|
74
|
+
client.stop(); client.start();
|
|
75
|
+
});
|
|
76
|
+
$("forget").addEventListener("click", () => {
|
|
77
|
+
localStorage.removeItem("conformtools.pairingFolder");
|
|
78
|
+
localStorage.removeItem("conformtools.pairing");
|
|
79
|
+
$("paste").value = "";
|
|
80
|
+
log("forgot pasted pairing and picked folder");
|
|
81
|
+
});
|
|
82
|
+
$("save").addEventListener("click", () => {
|
|
83
|
+
try {
|
|
84
|
+
const { parsePairing } = require("./lib/pairing");
|
|
85
|
+
parsePairing($("paste").value);
|
|
86
|
+
localStorage.setItem("conformtools.pairing", $("paste").value.trim());
|
|
87
|
+
log("pairing saved (local)");
|
|
88
|
+
client.stop(); client.start();
|
|
89
|
+
} catch (e) { log(`pairing rejected: ${e.message}`); }
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
log(`conform.tools panel · Premiere ${P.hostVersion() || "?"} · ${platform}`);
|
|
93
|
+
client.start();
|