syphon.client

Syphon clients with native notifications and asyncio frame availability.

  1"""Syphon clients with native notifications and asyncio frame availability."""
  2
  3import asyncio
  4import inspect
  5import logging
  6import math
  7import threading
  8import weakref
  9from abc import ABC
 10from typing import Any, Callable, Optional
 11
 12import Metal
 13import objc
 14
 15from syphon import _native
 16from syphon.server_directory import SyphonServerDescription
 17from syphon.utils import opengl
 18
 19_logger = logging.getLogger(__name__)
 20_native_callback = threading.local()
 21_callback_condition = threading.Condition()
 22_active_native_callbacks = {}
 23
 24
 25class BaseSyphonClient(ABC):
 26    """Common client API. Notifications signal availability, not a queue of every frame.
 27
 28    Handlers receive this Python client. Unless ``callback_loop`` is supplied, they run
 29    on Syphon's background thread and must be short, synchronous, and avoid UI/OpenGL
 30    work. Use ``stop()`` or a context manager for deterministic cleanup.
 31    """
 32
 33    def __init__(self, description, *, new_frame_handler=None, callback_loop=None):
 34        if new_frame_handler is not None and (
 35            not callable(new_frame_handler) or inspect.iscoroutinefunction(new_frame_handler)
 36        ):
 37            raise TypeError("new_frame_handler must be a synchronous callable")
 38        if callback_loop is not None and callback_loop.is_closed():
 39            raise ValueError("callback_loop must not be closed")
 40        self._description = description
 41        self._queue_key = getattr(description, "uuid", None)
 42        self._state_lock = threading.Lock()
 43        self._stopped = False
 44        self._ready = False
 45        self._handler = new_frame_handler
 46        self._callback_loop = callback_loop
 47        self._callback_scheduled = False
 48        self._waiters = set()
 49        self.context = None
 50        reference = weakref.ref(self)
 51        queue_key = self._queue_key
 52
 53        def native_handler(_native_client):
 54            with _callback_condition:
 55                _active_native_callbacks[queue_key] = _active_native_callbacks.get(queue_key, 0) + 1
 56            previous = getattr(_native_callback, "active", False)
 57            _native_callback.active = True
 58            try:
 59                client = reference()
 60                if client is not None:
 61                    client._receive_frame()
 62            except BaseException:
 63                # Python exceptions must never unwind through an Objective-C block.
 64                _logger.exception("Syphon frame notification failed")
 65            finally:
 66                _native_callback.active = previous
 67                with _callback_condition:
 68                    _active_native_callbacks[queue_key] -= 1
 69                    if not _active_native_callbacks[queue_key]:
 70                        del _active_native_callbacks[queue_key]
 71                    _callback_condition.notify_all()
 72
 73        self._native_handler = native_handler
 74
 75    def _finish_initialization(self, context):
 76        with self._state_lock:
 77            self.context = context
 78            self._ready = context is not None
 79            self._stopped = context is None
 80        if context is None:
 81            raise RuntimeError("Syphon could not create the client")
 82
 83    @property
 84    def is_valid(self) -> bool:
 85        """Whether this client has a working connection and has not been stopped."""
 86        with self._state_lock:
 87            context = None if self._stopped else self.context
 88        return context is not None and bool(context.isValid())
 89
 90    @property
 91    def has_new_frame(self) -> bool:
 92        """Whether a frame is available since the last ``new_frame_image`` access."""
 93        with self._state_lock:
 94            context = None if self._stopped else self.context
 95        return context is not None and bool(context.hasNewFrame())
 96
 97    @property
 98    def new_frame_image(self) -> Any:
 99        """Fetch the latest native texture/image, or None. This consumes the new-frame flag.
100
101        Keep the returned object alive during use; PyObjC manages its native ownership.
102        OpenGL access must happen with the appropriate context on the application's thread.
103        """
104        with self._state_lock:
105            context = None if self._stopped else self.context
106        return None if context is None else context.newFrameImage()
107
108    @property
109    def server_description(self) -> SyphonServerDescription:
110        """The native server description, including updates observed by Syphon."""
111        with self._state_lock:
112            if self._stopped or self.context is None:
113                return self._description
114            context = self.context
115        return SyphonServerDescription.from_native(context.serverDescription())
116
117    @staticmethod
118    def _resolve_waiter(future, error=None):
119        if not future.done():
120            if error is None:
121                future.set_result(None)
122            else:
123                future.set_exception(error)
124
125    def _notify_waiters(self, waiters, error=None):
126        for loop, future in waiters:
127            try:
128                loop.call_soon_threadsafe(self._resolve_waiter, future, error)
129            except RuntimeError:
130                # The application's event loop has already closed.
131                pass
132
133    def _receive_frame(self):
134        with self._state_lock:
135            if self._stopped or not self._ready:
136                return
137            waiters = tuple(self._waiters)
138            self._waiters.clear()
139            handler = self._handler
140            loop = self._callback_loop
141            schedule = handler is not None and (loop is None or not self._callback_scheduled)
142            if schedule and loop is not None:
143                self._callback_scheduled = True
144        self._notify_waiters(waiters)
145        if schedule:
146            if loop is None:
147                self._deliver_callback()
148            else:
149                try:
150                    loop.call_soon_threadsafe(self._deliver_callback)
151                except RuntimeError:
152                    with self._state_lock:
153                        self._callback_scheduled = False
154                    _logger.warning("Cannot deliver Syphon callback: callback_loop is closed")
155
156    def _deliver_callback(self):
157        with self._state_lock:
158            self._callback_scheduled = False
159            handler = None if self._stopped else self._handler
160            loop = self._callback_loop
161        if handler is None:
162            return
163        try:
164            result = handler(self)
165            if inspect.isawaitable(result):
166                if inspect.iscoroutine(result):
167                    result.close()
168                raise TypeError("Frame handlers must be synchronous; schedule coroutine work on an asyncio loop")
169        except BaseException as error:
170            if loop is None:
171                _logger.exception("Syphon frame handler failed")
172            else:
173                loop.call_exception_handler(
174                    {"message": "Syphon frame handler failed", "exception": error, "client": self}
175                )
176
177    async def wait_for_frame(self, timeout: Optional[float] = None) -> None:
178        """Wait for availability without fetching a frame; supports concurrent waiters.
179
180        Raises asyncio.TimeoutError on timeout, ConnectionError on disconnect, and
181        RuntimeError on stop. Cancellation only removes the cancelling waiter's registration.
182        Notifications may coalesce, and another consumer may fetch the frame first.
183        """
184        if timeout is not None and (not math.isfinite(timeout) or timeout < 0):
185            raise ValueError("timeout must be a finite nonnegative number or None")
186        loop = asyncio.get_running_loop()
187        future = loop.create_future()
188        waiter = (loop, future)
189        deadline = None if timeout is None else loop.time() + timeout
190        with self._state_lock:
191            if self._stopped:
192                raise RuntimeError("Syphon client is stopped")
193            # Register before checking the native flag to avoid lost wakeups.
194            self._waiters.add(waiter)
195        try:
196            while True:
197                with self._state_lock:
198                    if self._stopped:
199                        raise RuntimeError("Syphon client is stopped")
200                if not self.is_valid:
201                    raise ConnectionError("Syphon server disconnected")
202                if self.has_new_frame:
203                    return
204                if future.done():
205                    return future.result()
206                remaining = None if deadline is None else deadline - loop.time()
207                if remaining is not None and remaining <= 0:
208                    raise asyncio.TimeoutError()
209                # Syphon has no disconnect block; check validity only during active waits.
210                await asyncio.wait({future}, timeout=0.1 if remaining is None else min(0.1, remaining))
211        finally:
212            with self._state_lock:
213                self._waiters.discard(waiter)
214            if future.done() and not future.cancelled():
215                future.exception()  # Retrieve shutdown errors even if another check raised first.
216            else:
217                future.cancel()
218
219    def stop(self):
220        """Stop once and wake pending waits. Never call from a native frame callback."""
221        if getattr(_native_callback, "active", False):
222            raise RuntimeError(
223                "Cannot stop a client from a native frame callback; use the application thread or asyncio"
224            )
225        with self._state_lock:
226            if self._stopped:
227                return
228            self._stopped = True
229            self._handler = None
230            waiters = tuple(self._waiters)
231            self._waiters.clear()
232            context = self.context
233        self._notify_waiters(waiters, RuntimeError("Syphon client is stopped"))
234        # Native stop holds its own lock while synchronously draining the frame queue.
235        # An in-flight callback (including a peer's callback on that queue) might be
236        # reading this client's native properties. Drain Python callbacks first to
237        # avoid a native lock/queue inversion. New callbacks see the stopped flag.
238        with _callback_condition:
239            _callback_condition.wait_for(lambda: _active_native_callbacks.get(self._queue_key, 0) == 0)
240        # Never hold a Python state lock across native shutdown.
241        if context is not None:
242            context.stop()
243
244    def __enter__(self):
245        with self._state_lock:
246            if self._stopped:
247                raise RuntimeError("Syphon client is stopped")
248        return self
249
250    def __exit__(self, exc_type, exc_value, traceback):
251        self.stop()
252
253
254class SyphonMetalClient(BaseSyphonClient):
255    """Receive Metal textures; optional callbacks follow ``BaseSyphonClient`` threading rules."""
256
257    def __init__(
258        self,
259        description: SyphonServerDescription,
260        device: Optional[Any] = None,
261        *,
262        new_frame_handler: Optional[Callable[[BaseSyphonClient], None]] = None,
263        callback_loop: Optional[asyncio.AbstractEventLoop] = None,
264    ):
265        super().__init__(description, new_frame_handler=new_frame_handler, callback_loop=callback_loop)
266        self.device = device if device is not None else Metal.MTLCreateSystemDefaultDevice()
267        if self.device is None:
268            raise RuntimeError("No Metal device is available")
269        native = objc.lookUpClass("SyphonMetalClient")
270        self._finish_initialization(
271            native.alloc().initWithServerDescription_device_options_newFrameHandler_(
272                description.raw, self.device, None, self._native_handler
273            )
274        )
275
276
277class SyphonOpenGLClient(BaseSyphonClient):
278    """Receive OpenGL images. The caller must ensure exclusive access to the CGL context."""
279
280    def __init__(
281        self,
282        description: SyphonServerDescription,
283        cgl_context_obj: Optional[Any] = None,
284        *,
285        new_frame_handler: Optional[Callable[[BaseSyphonClient], None]] = None,
286        callback_loop: Optional[asyncio.AbstractEventLoop] = None,
287    ):
288        super().__init__(description, new_frame_handler=new_frame_handler, callback_loop=callback_loop)
289        opengl._require_pyopengl()
290        self.cgl_context_obj = opengl.get_current_cgl_context_obj() if cgl_context_obj is None else cgl_context_obj
291        native = objc.lookUpClass("SyphonOpenGLClient")
292        self._finish_initialization(
293            native.alloc().initWithServerDescription_context_options_newFrameHandler_(
294                description.raw, _native.cgl_context(self.cgl_context_obj), None, self._native_handler
295            )
296        )
class BaseSyphonClient(abc.ABC):
 26class BaseSyphonClient(ABC):
 27    """Common client API. Notifications signal availability, not a queue of every frame.
 28
 29    Handlers receive this Python client. Unless ``callback_loop`` is supplied, they run
 30    on Syphon's background thread and must be short, synchronous, and avoid UI/OpenGL
 31    work. Use ``stop()`` or a context manager for deterministic cleanup.
 32    """
 33
 34    def __init__(self, description, *, new_frame_handler=None, callback_loop=None):
 35        if new_frame_handler is not None and (
 36            not callable(new_frame_handler) or inspect.iscoroutinefunction(new_frame_handler)
 37        ):
 38            raise TypeError("new_frame_handler must be a synchronous callable")
 39        if callback_loop is not None and callback_loop.is_closed():
 40            raise ValueError("callback_loop must not be closed")
 41        self._description = description
 42        self._queue_key = getattr(description, "uuid", None)
 43        self._state_lock = threading.Lock()
 44        self._stopped = False
 45        self._ready = False
 46        self._handler = new_frame_handler
 47        self._callback_loop = callback_loop
 48        self._callback_scheduled = False
 49        self._waiters = set()
 50        self.context = None
 51        reference = weakref.ref(self)
 52        queue_key = self._queue_key
 53
 54        def native_handler(_native_client):
 55            with _callback_condition:
 56                _active_native_callbacks[queue_key] = _active_native_callbacks.get(queue_key, 0) + 1
 57            previous = getattr(_native_callback, "active", False)
 58            _native_callback.active = True
 59            try:
 60                client = reference()
 61                if client is not None:
 62                    client._receive_frame()
 63            except BaseException:
 64                # Python exceptions must never unwind through an Objective-C block.
 65                _logger.exception("Syphon frame notification failed")
 66            finally:
 67                _native_callback.active = previous
 68                with _callback_condition:
 69                    _active_native_callbacks[queue_key] -= 1
 70                    if not _active_native_callbacks[queue_key]:
 71                        del _active_native_callbacks[queue_key]
 72                    _callback_condition.notify_all()
 73
 74        self._native_handler = native_handler
 75
 76    def _finish_initialization(self, context):
 77        with self._state_lock:
 78            self.context = context
 79            self._ready = context is not None
 80            self._stopped = context is None
 81        if context is None:
 82            raise RuntimeError("Syphon could not create the client")
 83
 84    @property
 85    def is_valid(self) -> bool:
 86        """Whether this client has a working connection and has not been stopped."""
 87        with self._state_lock:
 88            context = None if self._stopped else self.context
 89        return context is not None and bool(context.isValid())
 90
 91    @property
 92    def has_new_frame(self) -> bool:
 93        """Whether a frame is available since the last ``new_frame_image`` access."""
 94        with self._state_lock:
 95            context = None if self._stopped else self.context
 96        return context is not None and bool(context.hasNewFrame())
 97
 98    @property
 99    def new_frame_image(self) -> Any:
100        """Fetch the latest native texture/image, or None. This consumes the new-frame flag.
101
102        Keep the returned object alive during use; PyObjC manages its native ownership.
103        OpenGL access must happen with the appropriate context on the application's thread.
104        """
105        with self._state_lock:
106            context = None if self._stopped else self.context
107        return None if context is None else context.newFrameImage()
108
109    @property
110    def server_description(self) -> SyphonServerDescription:
111        """The native server description, including updates observed by Syphon."""
112        with self._state_lock:
113            if self._stopped or self.context is None:
114                return self._description
115            context = self.context
116        return SyphonServerDescription.from_native(context.serverDescription())
117
118    @staticmethod
119    def _resolve_waiter(future, error=None):
120        if not future.done():
121            if error is None:
122                future.set_result(None)
123            else:
124                future.set_exception(error)
125
126    def _notify_waiters(self, waiters, error=None):
127        for loop, future in waiters:
128            try:
129                loop.call_soon_threadsafe(self._resolve_waiter, future, error)
130            except RuntimeError:
131                # The application's event loop has already closed.
132                pass
133
134    def _receive_frame(self):
135        with self._state_lock:
136            if self._stopped or not self._ready:
137                return
138            waiters = tuple(self._waiters)
139            self._waiters.clear()
140            handler = self._handler
141            loop = self._callback_loop
142            schedule = handler is not None and (loop is None or not self._callback_scheduled)
143            if schedule and loop is not None:
144                self._callback_scheduled = True
145        self._notify_waiters(waiters)
146        if schedule:
147            if loop is None:
148                self._deliver_callback()
149            else:
150                try:
151                    loop.call_soon_threadsafe(self._deliver_callback)
152                except RuntimeError:
153                    with self._state_lock:
154                        self._callback_scheduled = False
155                    _logger.warning("Cannot deliver Syphon callback: callback_loop is closed")
156
157    def _deliver_callback(self):
158        with self._state_lock:
159            self._callback_scheduled = False
160            handler = None if self._stopped else self._handler
161            loop = self._callback_loop
162        if handler is None:
163            return
164        try:
165            result = handler(self)
166            if inspect.isawaitable(result):
167                if inspect.iscoroutine(result):
168                    result.close()
169                raise TypeError("Frame handlers must be synchronous; schedule coroutine work on an asyncio loop")
170        except BaseException as error:
171            if loop is None:
172                _logger.exception("Syphon frame handler failed")
173            else:
174                loop.call_exception_handler(
175                    {"message": "Syphon frame handler failed", "exception": error, "client": self}
176                )
177
178    async def wait_for_frame(self, timeout: Optional[float] = None) -> None:
179        """Wait for availability without fetching a frame; supports concurrent waiters.
180
181        Raises asyncio.TimeoutError on timeout, ConnectionError on disconnect, and
182        RuntimeError on stop. Cancellation only removes the cancelling waiter's registration.
183        Notifications may coalesce, and another consumer may fetch the frame first.
184        """
185        if timeout is not None and (not math.isfinite(timeout) or timeout < 0):
186            raise ValueError("timeout must be a finite nonnegative number or None")
187        loop = asyncio.get_running_loop()
188        future = loop.create_future()
189        waiter = (loop, future)
190        deadline = None if timeout is None else loop.time() + timeout
191        with self._state_lock:
192            if self._stopped:
193                raise RuntimeError("Syphon client is stopped")
194            # Register before checking the native flag to avoid lost wakeups.
195            self._waiters.add(waiter)
196        try:
197            while True:
198                with self._state_lock:
199                    if self._stopped:
200                        raise RuntimeError("Syphon client is stopped")
201                if not self.is_valid:
202                    raise ConnectionError("Syphon server disconnected")
203                if self.has_new_frame:
204                    return
205                if future.done():
206                    return future.result()
207                remaining = None if deadline is None else deadline - loop.time()
208                if remaining is not None and remaining <= 0:
209                    raise asyncio.TimeoutError()
210                # Syphon has no disconnect block; check validity only during active waits.
211                await asyncio.wait({future}, timeout=0.1 if remaining is None else min(0.1, remaining))
212        finally:
213            with self._state_lock:
214                self._waiters.discard(waiter)
215            if future.done() and not future.cancelled():
216                future.exception()  # Retrieve shutdown errors even if another check raised first.
217            else:
218                future.cancel()
219
220    def stop(self):
221        """Stop once and wake pending waits. Never call from a native frame callback."""
222        if getattr(_native_callback, "active", False):
223            raise RuntimeError(
224                "Cannot stop a client from a native frame callback; use the application thread or asyncio"
225            )
226        with self._state_lock:
227            if self._stopped:
228                return
229            self._stopped = True
230            self._handler = None
231            waiters = tuple(self._waiters)
232            self._waiters.clear()
233            context = self.context
234        self._notify_waiters(waiters, RuntimeError("Syphon client is stopped"))
235        # Native stop holds its own lock while synchronously draining the frame queue.
236        # An in-flight callback (including a peer's callback on that queue) might be
237        # reading this client's native properties. Drain Python callbacks first to
238        # avoid a native lock/queue inversion. New callbacks see the stopped flag.
239        with _callback_condition:
240            _callback_condition.wait_for(lambda: _active_native_callbacks.get(self._queue_key, 0) == 0)
241        # Never hold a Python state lock across native shutdown.
242        if context is not None:
243            context.stop()
244
245    def __enter__(self):
246        with self._state_lock:
247            if self._stopped:
248                raise RuntimeError("Syphon client is stopped")
249        return self
250
251    def __exit__(self, exc_type, exc_value, traceback):
252        self.stop()

Common client API. Notifications signal availability, not a queue of every frame.

Handlers receive this Python client. Unless callback_loop is supplied, they run on Syphon's background thread and must be short, synchronous, and avoid UI/OpenGL work. Use stop() or a context manager for deterministic cleanup.

BaseSyphonClient(description, *, new_frame_handler=None, callback_loop=None)
34    def __init__(self, description, *, new_frame_handler=None, callback_loop=None):
35        if new_frame_handler is not None and (
36            not callable(new_frame_handler) or inspect.iscoroutinefunction(new_frame_handler)
37        ):
38            raise TypeError("new_frame_handler must be a synchronous callable")
39        if callback_loop is not None and callback_loop.is_closed():
40            raise ValueError("callback_loop must not be closed")
41        self._description = description
42        self._queue_key = getattr(description, "uuid", None)
43        self._state_lock = threading.Lock()
44        self._stopped = False
45        self._ready = False
46        self._handler = new_frame_handler
47        self._callback_loop = callback_loop
48        self._callback_scheduled = False
49        self._waiters = set()
50        self.context = None
51        reference = weakref.ref(self)
52        queue_key = self._queue_key
53
54        def native_handler(_native_client):
55            with _callback_condition:
56                _active_native_callbacks[queue_key] = _active_native_callbacks.get(queue_key, 0) + 1
57            previous = getattr(_native_callback, "active", False)
58            _native_callback.active = True
59            try:
60                client = reference()
61                if client is not None:
62                    client._receive_frame()
63            except BaseException:
64                # Python exceptions must never unwind through an Objective-C block.
65                _logger.exception("Syphon frame notification failed")
66            finally:
67                _native_callback.active = previous
68                with _callback_condition:
69                    _active_native_callbacks[queue_key] -= 1
70                    if not _active_native_callbacks[queue_key]:
71                        del _active_native_callbacks[queue_key]
72                    _callback_condition.notify_all()
73
74        self._native_handler = native_handler
context
is_valid: bool
84    @property
85    def is_valid(self) -> bool:
86        """Whether this client has a working connection and has not been stopped."""
87        with self._state_lock:
88            context = None if self._stopped else self.context
89        return context is not None and bool(context.isValid())

Whether this client has a working connection and has not been stopped.

has_new_frame: bool
91    @property
92    def has_new_frame(self) -> bool:
93        """Whether a frame is available since the last ``new_frame_image`` access."""
94        with self._state_lock:
95            context = None if self._stopped else self.context
96        return context is not None and bool(context.hasNewFrame())

Whether a frame is available since the last new_frame_image access.

new_frame_image: Any
 98    @property
 99    def new_frame_image(self) -> Any:
100        """Fetch the latest native texture/image, or None. This consumes the new-frame flag.
101
102        Keep the returned object alive during use; PyObjC manages its native ownership.
103        OpenGL access must happen with the appropriate context on the application's thread.
104        """
105        with self._state_lock:
106            context = None if self._stopped else self.context
107        return None if context is None else context.newFrameImage()

Fetch the latest native texture/image, or None. This consumes the new-frame flag.

Keep the returned object alive during use; PyObjC manages its native ownership. OpenGL access must happen with the appropriate context on the application's thread.

server_description: syphon.server_directory.SyphonServerDescription
109    @property
110    def server_description(self) -> SyphonServerDescription:
111        """The native server description, including updates observed by Syphon."""
112        with self._state_lock:
113            if self._stopped or self.context is None:
114                return self._description
115            context = self.context
116        return SyphonServerDescription.from_native(context.serverDescription())

The native server description, including updates observed by Syphon.

async def wait_for_frame(self, timeout: float | None = None) -> None:
178    async def wait_for_frame(self, timeout: Optional[float] = None) -> None:
179        """Wait for availability without fetching a frame; supports concurrent waiters.
180
181        Raises asyncio.TimeoutError on timeout, ConnectionError on disconnect, and
182        RuntimeError on stop. Cancellation only removes the cancelling waiter's registration.
183        Notifications may coalesce, and another consumer may fetch the frame first.
184        """
185        if timeout is not None and (not math.isfinite(timeout) or timeout < 0):
186            raise ValueError("timeout must be a finite nonnegative number or None")
187        loop = asyncio.get_running_loop()
188        future = loop.create_future()
189        waiter = (loop, future)
190        deadline = None if timeout is None else loop.time() + timeout
191        with self._state_lock:
192            if self._stopped:
193                raise RuntimeError("Syphon client is stopped")
194            # Register before checking the native flag to avoid lost wakeups.
195            self._waiters.add(waiter)
196        try:
197            while True:
198                with self._state_lock:
199                    if self._stopped:
200                        raise RuntimeError("Syphon client is stopped")
201                if not self.is_valid:
202                    raise ConnectionError("Syphon server disconnected")
203                if self.has_new_frame:
204                    return
205                if future.done():
206                    return future.result()
207                remaining = None if deadline is None else deadline - loop.time()
208                if remaining is not None and remaining <= 0:
209                    raise asyncio.TimeoutError()
210                # Syphon has no disconnect block; check validity only during active waits.
211                await asyncio.wait({future}, timeout=0.1 if remaining is None else min(0.1, remaining))
212        finally:
213            with self._state_lock:
214                self._waiters.discard(waiter)
215            if future.done() and not future.cancelled():
216                future.exception()  # Retrieve shutdown errors even if another check raised first.
217            else:
218                future.cancel()

Wait for availability without fetching a frame; supports concurrent waiters.

Raises asyncio.TimeoutError on timeout, ConnectionError on disconnect, and RuntimeError on stop. Cancellation only removes the cancelling waiter's registration. Notifications may coalesce, and another consumer may fetch the frame first.

def stop(self):
220    def stop(self):
221        """Stop once and wake pending waits. Never call from a native frame callback."""
222        if getattr(_native_callback, "active", False):
223            raise RuntimeError(
224                "Cannot stop a client from a native frame callback; use the application thread or asyncio"
225            )
226        with self._state_lock:
227            if self._stopped:
228                return
229            self._stopped = True
230            self._handler = None
231            waiters = tuple(self._waiters)
232            self._waiters.clear()
233            context = self.context
234        self._notify_waiters(waiters, RuntimeError("Syphon client is stopped"))
235        # Native stop holds its own lock while synchronously draining the frame queue.
236        # An in-flight callback (including a peer's callback on that queue) might be
237        # reading this client's native properties. Drain Python callbacks first to
238        # avoid a native lock/queue inversion. New callbacks see the stopped flag.
239        with _callback_condition:
240            _callback_condition.wait_for(lambda: _active_native_callbacks.get(self._queue_key, 0) == 0)
241        # Never hold a Python state lock across native shutdown.
242        if context is not None:
243            context.stop()

Stop once and wake pending waits. Never call from a native frame callback.

class SyphonMetalClient(BaseSyphonClient):
255class SyphonMetalClient(BaseSyphonClient):
256    """Receive Metal textures; optional callbacks follow ``BaseSyphonClient`` threading rules."""
257
258    def __init__(
259        self,
260        description: SyphonServerDescription,
261        device: Optional[Any] = None,
262        *,
263        new_frame_handler: Optional[Callable[[BaseSyphonClient], None]] = None,
264        callback_loop: Optional[asyncio.AbstractEventLoop] = None,
265    ):
266        super().__init__(description, new_frame_handler=new_frame_handler, callback_loop=callback_loop)
267        self.device = device if device is not None else Metal.MTLCreateSystemDefaultDevice()
268        if self.device is None:
269            raise RuntimeError("No Metal device is available")
270        native = objc.lookUpClass("SyphonMetalClient")
271        self._finish_initialization(
272            native.alloc().initWithServerDescription_device_options_newFrameHandler_(
273                description.raw, self.device, None, self._native_handler
274            )
275        )

Receive Metal textures; optional callbacks follow BaseSyphonClient threading rules.

SyphonMetalClient( description: syphon.server_directory.SyphonServerDescription, device: Any | None = None, *, new_frame_handler: Callable[[BaseSyphonClient], NoneType] | None = None, callback_loop: asyncio.events.AbstractEventLoop | None = None)
258    def __init__(
259        self,
260        description: SyphonServerDescription,
261        device: Optional[Any] = None,
262        *,
263        new_frame_handler: Optional[Callable[[BaseSyphonClient], None]] = None,
264        callback_loop: Optional[asyncio.AbstractEventLoop] = None,
265    ):
266        super().__init__(description, new_frame_handler=new_frame_handler, callback_loop=callback_loop)
267        self.device = device if device is not None else Metal.MTLCreateSystemDefaultDevice()
268        if self.device is None:
269            raise RuntimeError("No Metal device is available")
270        native = objc.lookUpClass("SyphonMetalClient")
271        self._finish_initialization(
272            native.alloc().initWithServerDescription_device_options_newFrameHandler_(
273                description.raw, self.device, None, self._native_handler
274            )
275        )
device
class SyphonOpenGLClient(BaseSyphonClient):
278class SyphonOpenGLClient(BaseSyphonClient):
279    """Receive OpenGL images. The caller must ensure exclusive access to the CGL context."""
280
281    def __init__(
282        self,
283        description: SyphonServerDescription,
284        cgl_context_obj: Optional[Any] = None,
285        *,
286        new_frame_handler: Optional[Callable[[BaseSyphonClient], None]] = None,
287        callback_loop: Optional[asyncio.AbstractEventLoop] = None,
288    ):
289        super().__init__(description, new_frame_handler=new_frame_handler, callback_loop=callback_loop)
290        opengl._require_pyopengl()
291        self.cgl_context_obj = opengl.get_current_cgl_context_obj() if cgl_context_obj is None else cgl_context_obj
292        native = objc.lookUpClass("SyphonOpenGLClient")
293        self._finish_initialization(
294            native.alloc().initWithServerDescription_context_options_newFrameHandler_(
295                description.raw, _native.cgl_context(self.cgl_context_obj), None, self._native_handler
296            )
297        )

Receive OpenGL images. The caller must ensure exclusive access to the CGL context.

SyphonOpenGLClient( description: syphon.server_directory.SyphonServerDescription, cgl_context_obj: Any | None = None, *, new_frame_handler: Callable[[BaseSyphonClient], NoneType] | None = None, callback_loop: asyncio.events.AbstractEventLoop | None = None)
281    def __init__(
282        self,
283        description: SyphonServerDescription,
284        cgl_context_obj: Optional[Any] = None,
285        *,
286        new_frame_handler: Optional[Callable[[BaseSyphonClient], None]] = None,
287        callback_loop: Optional[asyncio.AbstractEventLoop] = None,
288    ):
289        super().__init__(description, new_frame_handler=new_frame_handler, callback_loop=callback_loop)
290        opengl._require_pyopengl()
291        self.cgl_context_obj = opengl.get_current_cgl_context_obj() if cgl_context_obj is None else cgl_context_obj
292        native = objc.lookUpClass("SyphonOpenGLClient")
293        self._finish_initialization(
294            native.alloc().initWithServerDescription_context_options_newFrameHandler_(
295                description.raw, _native.cgl_context(self.cgl_context_obj), None, self._native_handler
296            )
297        )
cgl_context_obj