trackwright 0.3.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.
- trackwright/__init__.py +13 -0
- trackwright/__main__.py +7 -0
- trackwright/bridge.py +323 -0
- trackwright/cli.py +203 -0
- trackwright/commands.py +397 -0
- trackwright/config.py +149 -0
- trackwright/core/__init__.py +1 -0
- trackwright/core/automation.py +410 -0
- trackwright/core/base.py +313 -0
- trackwright/core/commanding.py +300 -0
- trackwright/core/exporting.py +143 -0
- trackwright/core/importing.py +127 -0
- trackwright/core/lifecycle.py +74 -0
- trackwright/core/models.py +467 -0
- trackwright/core/policy.py +58 -0
- trackwright/core/presets.py +88 -0
- trackwright/core/project.py +221 -0
- trackwright/core/ranges.py +355 -0
- trackwright/core/reading.py +229 -0
- trackwright/core/refs.py +88 -0
- trackwright/core/saving.py +72 -0
- trackwright/core/service.py +27 -0
- trackwright/core/settings.py +80 -0
- trackwright/core/writing.py +390 -0
- trackwright/coremidi.py +307 -0
- trackwright/cubase/Trackwright_Bridge.js +1130 -0
- trackwright/cubase/__init__.py +83 -0
- trackwright/doctor.py +69 -0
- trackwright/errors.py +120 -0
- trackwright/exports.py +54 -0
- trackwright/fake.py +1112 -0
- trackwright/host.py +238 -0
- trackwright/hostport.py +74 -0
- trackwright/installer.py +305 -0
- trackwright/launcher.py +150 -0
- trackwright/logs.py +50 -0
- trackwright/ops.py +46 -0
- trackwright/protocol.py +182 -0
- trackwright/py.typed +0 -0
- trackwright/server.py +472 -0
- trackwright/transport.py +130 -0
- trackwright-0.3.0.dist-info/METADATA +190 -0
- trackwright-0.3.0.dist-info/RECORD +46 -0
- trackwright-0.3.0.dist-info/WHEEL +4 -0
- trackwright-0.3.0.dist-info/entry_points.txt +3 -0
- trackwright-0.3.0.dist-info/licenses/LICENSE +661 -0
trackwright/coremidi.py
ADDED
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
"""MIDI transport on macOS CoreMIDI through ``ctypes`` (TW-1302): pure Python, nothing to compile.
|
|
2
|
+
|
|
3
|
+
Same contract as :class:`trackwright.transport.MidiTransport` (mido + python-rtmidi), which is kept as an
|
|
4
|
+
alternative (``[bridge] backend = "rtmidi"``), for instance for other platforms:
|
|
5
|
+
|
|
6
|
+
- ``to_cubase`` is a CoreMIDI *virtual source* (``MIDISourceCreate``): Cubase sees it as an input. Data is
|
|
7
|
+
sent with ``MIDIReceived``.
|
|
8
|
+
- ``from_cubase`` is a *virtual destination* (``MIDIDestinationCreate`` with a read callback): Cubase sees
|
|
9
|
+
it as an output.
|
|
10
|
+
|
|
11
|
+
SysEx may arrive split over several packets or callbacks; :class:`SysExAssembler` rebuilds each message.
|
|
12
|
+
The callback runs on a CoreMIDI thread: it never raises, and the ``ctypes`` callback object is kept
|
|
13
|
+
alive for the lifetime of the port.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import ctypes
|
|
19
|
+
import platform
|
|
20
|
+
import threading
|
|
21
|
+
from collections.abc import Callable, Iterator, Sequence
|
|
22
|
+
from typing import Any
|
|
23
|
+
|
|
24
|
+
from loguru import logger
|
|
25
|
+
|
|
26
|
+
from trackwright.errors import TransportError
|
|
27
|
+
from trackwright.protocol import is_ours
|
|
28
|
+
from trackwright.transport import Receiver, TransportStats
|
|
29
|
+
|
|
30
|
+
COREMIDI = "/System/Library/Frameworks/CoreMIDI.framework/CoreMIDI"
|
|
31
|
+
COREFOUNDATION = "/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation"
|
|
32
|
+
UTF8 = 0x08000100 # kCFStringEncodingUTF8
|
|
33
|
+
SYSEX_START, SYSEX_END = 0xF0, 0xF7
|
|
34
|
+
PACKET_HEADER = 10 # MIDITimeStamp (UInt64) + length (UInt16)
|
|
35
|
+
|
|
36
|
+
MIDIObjectRef = ctypes.c_uint32
|
|
37
|
+
OSStatus = ctypes.c_int32
|
|
38
|
+
ReadProc = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class SysExAssembler:
|
|
42
|
+
"""Rebuild SysEx messages from a MIDI byte stream (``F0 … F7``, which may be split anywhere)."""
|
|
43
|
+
|
|
44
|
+
def __init__(self) -> None:
|
|
45
|
+
self._buffer: list[int] | None = None
|
|
46
|
+
self.non_sysex = 0
|
|
47
|
+
|
|
48
|
+
def feed(self, data: bytes | Sequence[int]) -> Iterator[list[int]]:
|
|
49
|
+
"""Yield the data bytes (without ``F0``/``F7``) of every message completed by ``data``."""
|
|
50
|
+
for byte in data:
|
|
51
|
+
if byte == SYSEX_START:
|
|
52
|
+
self._buffer = []
|
|
53
|
+
elif byte >= 0xF8: # real-time bytes may appear anywhere, even inside SysEx
|
|
54
|
+
continue
|
|
55
|
+
elif self._buffer is not None:
|
|
56
|
+
if byte == SYSEX_END:
|
|
57
|
+
done, self._buffer = self._buffer, None
|
|
58
|
+
yield done
|
|
59
|
+
elif byte & 0x80: # another status byte: the SysEx was cut
|
|
60
|
+
self._buffer = None
|
|
61
|
+
self.non_sysex += 1
|
|
62
|
+
else:
|
|
63
|
+
self._buffer.append(byte)
|
|
64
|
+
elif byte & 0x80:
|
|
65
|
+
self.non_sysex += 1 # a channel or system message we do not use
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def packets(packet_list: int, *, aligned: bool | None = None) -> Iterator[bytes]:
|
|
69
|
+
"""The data of each ``MIDIPacket`` in a ``MIDIPacketList`` at address ``packet_list``.
|
|
70
|
+
|
|
71
|
+
Layout (``#pragma pack(4)``): ``UInt32 numPackets`` then packets of ``UInt64 timeStamp``, ``UInt16
|
|
72
|
+
length`` and the data. On ARM the next packet starts at a 4-byte boundary (``MIDIPacketNext``).
|
|
73
|
+
"""
|
|
74
|
+
align = platform.machine().startswith(("arm", "aarch")) if aligned is None else aligned
|
|
75
|
+
count = ctypes.c_uint32.from_address(packet_list).value
|
|
76
|
+
address = packet_list + 4
|
|
77
|
+
for _ in range(count):
|
|
78
|
+
length = ctypes.c_uint16.from_address(address + 8).value
|
|
79
|
+
yield ctypes.string_at(address + PACKET_HEADER, length)
|
|
80
|
+
address += PACKET_HEADER + length
|
|
81
|
+
if align:
|
|
82
|
+
address = (address + 3) & ~3
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class CoreMidiApi:
|
|
86
|
+
"""The few CoreMIDI and CoreFoundation calls the transport needs (replaceable in tests)."""
|
|
87
|
+
|
|
88
|
+
def __init__(self) -> None:
|
|
89
|
+
self.midi = ctypes.cdll.LoadLibrary(COREMIDI)
|
|
90
|
+
self.cf = ctypes.cdll.LoadLibrary(COREFOUNDATION)
|
|
91
|
+
self.cf.CFStringCreateWithCString.restype = ctypes.c_void_p
|
|
92
|
+
self.cf.CFStringCreateWithCString.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_uint32]
|
|
93
|
+
self.cf.CFStringGetCString.restype = ctypes.c_bool
|
|
94
|
+
self.cf.CFStringGetCString.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_long, ctypes.c_uint32]
|
|
95
|
+
self.cf.CFRelease.argtypes = [ctypes.c_void_p]
|
|
96
|
+
m = self.midi
|
|
97
|
+
m.MIDIClientCreate.restype = OSStatus
|
|
98
|
+
m.MIDIClientCreate.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.POINTER(MIDIObjectRef)]
|
|
99
|
+
m.MIDISourceCreate.restype = OSStatus
|
|
100
|
+
m.MIDISourceCreate.argtypes = [MIDIObjectRef, ctypes.c_void_p, ctypes.POINTER(MIDIObjectRef)]
|
|
101
|
+
m.MIDIDestinationCreate.restype = OSStatus
|
|
102
|
+
m.MIDIDestinationCreate.argtypes = [
|
|
103
|
+
MIDIObjectRef,
|
|
104
|
+
ctypes.c_void_p,
|
|
105
|
+
ReadProc,
|
|
106
|
+
ctypes.c_void_p,
|
|
107
|
+
ctypes.POINTER(MIDIObjectRef),
|
|
108
|
+
]
|
|
109
|
+
m.MIDIPacketListInit.restype = ctypes.c_void_p
|
|
110
|
+
m.MIDIPacketListInit.argtypes = [ctypes.c_void_p]
|
|
111
|
+
m.MIDIPacketListAdd.restype = ctypes.c_void_p
|
|
112
|
+
m.MIDIPacketListAdd.argtypes = [
|
|
113
|
+
ctypes.c_void_p,
|
|
114
|
+
ctypes.c_ulong,
|
|
115
|
+
ctypes.c_void_p,
|
|
116
|
+
ctypes.c_uint64,
|
|
117
|
+
ctypes.c_ulong,
|
|
118
|
+
ctypes.c_char_p,
|
|
119
|
+
]
|
|
120
|
+
m.MIDIReceived.restype = OSStatus
|
|
121
|
+
m.MIDIReceived.argtypes = [MIDIObjectRef, ctypes.c_void_p]
|
|
122
|
+
m.MIDIEndpointDispose.restype = OSStatus
|
|
123
|
+
m.MIDIEndpointDispose.argtypes = [MIDIObjectRef]
|
|
124
|
+
m.MIDIClientDispose.restype = OSStatus
|
|
125
|
+
m.MIDIClientDispose.argtypes = [MIDIObjectRef]
|
|
126
|
+
m.MIDIGetNumberOfSources.restype = ctypes.c_ulong
|
|
127
|
+
m.MIDIGetNumberOfDestinations.restype = ctypes.c_ulong
|
|
128
|
+
m.MIDIGetSource.restype = MIDIObjectRef
|
|
129
|
+
m.MIDIGetSource.argtypes = [ctypes.c_ulong]
|
|
130
|
+
m.MIDIGetDestination.restype = MIDIObjectRef
|
|
131
|
+
m.MIDIGetDestination.argtypes = [ctypes.c_ulong]
|
|
132
|
+
m.MIDIObjectGetStringProperty.restype = OSStatus
|
|
133
|
+
m.MIDIObjectGetStringProperty.argtypes = [MIDIObjectRef, ctypes.c_void_p, ctypes.POINTER(ctypes.c_void_p)]
|
|
134
|
+
self._name_property = ctypes.c_void_p.in_dll(m, "kMIDIPropertyName")
|
|
135
|
+
|
|
136
|
+
@staticmethod
|
|
137
|
+
def _check(status: int, what: str) -> None:
|
|
138
|
+
if status != 0:
|
|
139
|
+
raise TransportError(f"CoreMIDI {what} failed (OSStatus {status})", details={"status": status})
|
|
140
|
+
|
|
141
|
+
def _cfstring(self, text: str) -> int:
|
|
142
|
+
ref = self.cf.CFStringCreateWithCString(None, text.encode(), UTF8)
|
|
143
|
+
if not ref:
|
|
144
|
+
raise TransportError(f"cannot create a CFString for {text!r}")
|
|
145
|
+
return int(ref)
|
|
146
|
+
|
|
147
|
+
def _string(self, ref: int) -> str:
|
|
148
|
+
buffer = ctypes.create_string_buffer(512)
|
|
149
|
+
return buffer.value.decode() if self.cf.CFStringGetCString(ref, buffer, len(buffer), UTF8) else ""
|
|
150
|
+
|
|
151
|
+
def _with_name(self, name: str, create: Callable[[int], int]) -> int:
|
|
152
|
+
cf_name = self._cfstring(name)
|
|
153
|
+
try:
|
|
154
|
+
return create(cf_name)
|
|
155
|
+
finally:
|
|
156
|
+
self.cf.CFRelease(cf_name)
|
|
157
|
+
|
|
158
|
+
def client(self, name: str) -> int:
|
|
159
|
+
def create(cf_name: int) -> int:
|
|
160
|
+
ref = MIDIObjectRef()
|
|
161
|
+
self._check(self.midi.MIDIClientCreate(cf_name, None, None, ctypes.byref(ref)), "MIDIClientCreate")
|
|
162
|
+
return int(ref.value)
|
|
163
|
+
|
|
164
|
+
return self._with_name(name, create)
|
|
165
|
+
|
|
166
|
+
def source(self, client: int, name: str) -> int:
|
|
167
|
+
def create(cf_name: int) -> int:
|
|
168
|
+
ref = MIDIObjectRef()
|
|
169
|
+
self._check(self.midi.MIDISourceCreate(client, cf_name, ctypes.byref(ref)), "MIDISourceCreate")
|
|
170
|
+
return int(ref.value)
|
|
171
|
+
|
|
172
|
+
return self._with_name(name, create)
|
|
173
|
+
|
|
174
|
+
def destination(self, client: int, name: str, read_proc: Any) -> int:
|
|
175
|
+
def create(cf_name: int) -> int:
|
|
176
|
+
ref = MIDIObjectRef()
|
|
177
|
+
status = self.midi.MIDIDestinationCreate(client, cf_name, read_proc, None, ctypes.byref(ref))
|
|
178
|
+
self._check(status, "MIDIDestinationCreate")
|
|
179
|
+
return int(ref.value)
|
|
180
|
+
|
|
181
|
+
return self._with_name(name, create)
|
|
182
|
+
|
|
183
|
+
def received(self, source: int, data: bytes) -> None:
|
|
184
|
+
"""Publish ``data`` (one complete message) on a virtual source."""
|
|
185
|
+
size = len(data) + 64
|
|
186
|
+
buffer = ctypes.create_string_buffer(size)
|
|
187
|
+
packet = self.midi.MIDIPacketListInit(buffer)
|
|
188
|
+
packet = self.midi.MIDIPacketListAdd(buffer, size, packet, 0, len(data), data)
|
|
189
|
+
if not packet:
|
|
190
|
+
raise TransportError("the message does not fit in a MIDI packet list")
|
|
191
|
+
self._check(self.midi.MIDIReceived(source, buffer), "MIDIReceived")
|
|
192
|
+
|
|
193
|
+
def endpoint_names(self) -> tuple[set[str], set[str]]:
|
|
194
|
+
"""Names of every MIDI source and destination in the system."""
|
|
195
|
+
names: list[set[str]] = []
|
|
196
|
+
for count, get in ((self.midi.MIDIGetNumberOfSources, self.midi.MIDIGetSource),
|
|
197
|
+
(self.midi.MIDIGetNumberOfDestinations, self.midi.MIDIGetDestination)): # fmt: skip
|
|
198
|
+
found = set()
|
|
199
|
+
for index in range(count()):
|
|
200
|
+
ref = ctypes.c_void_p()
|
|
201
|
+
status = self.midi.MIDIObjectGetStringProperty(get(index), self._name_property, ctypes.byref(ref))
|
|
202
|
+
if status == 0 and ref.value:
|
|
203
|
+
found.add(self._string(ref.value))
|
|
204
|
+
self.cf.CFRelease(ref.value)
|
|
205
|
+
names.append(found)
|
|
206
|
+
return names[0], names[1]
|
|
207
|
+
|
|
208
|
+
def dispose_endpoint(self, ref: int) -> None:
|
|
209
|
+
self.midi.MIDIEndpointDispose(ref)
|
|
210
|
+
|
|
211
|
+
def dispose_client(self, ref: int) -> None:
|
|
212
|
+
self.midi.MIDIClientDispose(ref)
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
class CoreMidiTransport:
|
|
216
|
+
"""Real transport over CoreMIDI. ``api`` is injectable for tests."""
|
|
217
|
+
|
|
218
|
+
name = "coremidi-ctypes"
|
|
219
|
+
|
|
220
|
+
def __init__(self, to_cubase: str, from_cubase: str, *, api: Any | None = None) -> None:
|
|
221
|
+
self.to_cubase = to_cubase
|
|
222
|
+
self.from_cubase = from_cubase
|
|
223
|
+
self._api = api
|
|
224
|
+
self._client: int | None = None
|
|
225
|
+
self._source: int | None = None
|
|
226
|
+
self._destination: int | None = None
|
|
227
|
+
self._read_proc: Any = None # must outlive the destination
|
|
228
|
+
self._send_lock = threading.Lock()
|
|
229
|
+
self._stats = TransportStats()
|
|
230
|
+
self._assembler = SysExAssembler()
|
|
231
|
+
|
|
232
|
+
def _core(self) -> Any:
|
|
233
|
+
if self._api is None:
|
|
234
|
+
self._api = CoreMidiApi()
|
|
235
|
+
return self._api
|
|
236
|
+
|
|
237
|
+
def _on_packets(self, packet_list: int | None, _ref: object = None, _src: object = None) -> None:
|
|
238
|
+
if not packet_list:
|
|
239
|
+
return
|
|
240
|
+
try:
|
|
241
|
+
for chunk in packets(packet_list):
|
|
242
|
+
for data in self._assembler.feed(chunk):
|
|
243
|
+
self._deliver(data)
|
|
244
|
+
self._stats.non_sysex_messages = self._assembler.non_sysex
|
|
245
|
+
except Exception: # never let an exception reach the CoreMIDI thread
|
|
246
|
+
logger.exception("error reading MIDI packets")
|
|
247
|
+
|
|
248
|
+
def _deliver(self, data: list[int]) -> None:
|
|
249
|
+
if not is_ours(data):
|
|
250
|
+
self._stats.foreign_frames += 1
|
|
251
|
+
logger.trace("ignoring foreign SysEx {}", data[:8])
|
|
252
|
+
return
|
|
253
|
+
self._stats.received_frames += 1
|
|
254
|
+
try:
|
|
255
|
+
self._receiver(data)
|
|
256
|
+
except Exception:
|
|
257
|
+
logger.exception("receiver failed")
|
|
258
|
+
|
|
259
|
+
def open(self, receiver: Receiver) -> None:
|
|
260
|
+
api = self._core()
|
|
261
|
+
sources, destinations = api.endpoint_names()
|
|
262
|
+
if self.to_cubase in sources or self.from_cubase in destinations:
|
|
263
|
+
raise TransportError(
|
|
264
|
+
"virtual ports with these names already exist: is another bridge running?",
|
|
265
|
+
details={"to_cubase": self.to_cubase, "from_cubase": self.from_cubase},
|
|
266
|
+
)
|
|
267
|
+
self._receiver = receiver
|
|
268
|
+
self._read_proc = ReadProc(self._on_packets)
|
|
269
|
+
try:
|
|
270
|
+
self._client = api.client("Trackwright")
|
|
271
|
+
self._source = api.source(self._client, self.to_cubase)
|
|
272
|
+
self._destination = api.destination(self._client, self.from_cubase, self._read_proc)
|
|
273
|
+
except Exception as exc:
|
|
274
|
+
self.close()
|
|
275
|
+
raise TransportError(f"cannot create virtual ports: {exc}") from exc
|
|
276
|
+
logger.info("virtual MIDI ports open (CoreMIDI): '{}' (to Cubase), '{}' (from Cubase)",
|
|
277
|
+
self.to_cubase, self.from_cubase) # fmt: skip
|
|
278
|
+
|
|
279
|
+
def send_sysex(self, data: Sequence[int]) -> None:
|
|
280
|
+
if self._source is None:
|
|
281
|
+
raise TransportError("transport is not open")
|
|
282
|
+
with self._send_lock:
|
|
283
|
+
self._core().received(self._source, bytes([SYSEX_START, *data, SYSEX_END]))
|
|
284
|
+
self._stats.sent_frames += 1
|
|
285
|
+
|
|
286
|
+
def close(self) -> None:
|
|
287
|
+
api = self._api
|
|
288
|
+
for ref in (self._destination, self._source):
|
|
289
|
+
if ref is not None and api is not None:
|
|
290
|
+
try:
|
|
291
|
+
api.dispose_endpoint(ref)
|
|
292
|
+
except Exception:
|
|
293
|
+
logger.exception("error closing MIDI endpoint")
|
|
294
|
+
if self._client is not None and api is not None:
|
|
295
|
+
try:
|
|
296
|
+
api.dispose_client(self._client)
|
|
297
|
+
except Exception:
|
|
298
|
+
logger.exception("error closing MIDI client")
|
|
299
|
+
self._client = self._source = self._destination = None
|
|
300
|
+
|
|
301
|
+
def stats(self) -> dict[str, int]:
|
|
302
|
+
return {
|
|
303
|
+
"sent_frames": self._stats.sent_frames,
|
|
304
|
+
"received_frames": self._stats.received_frames,
|
|
305
|
+
"foreign_frames": self._stats.foreign_frames,
|
|
306
|
+
"non_sysex_messages": self._stats.non_sysex_messages,
|
|
307
|
+
}
|