syphon.server

  1import threading
  2from abc import ABC, abstractmethod
  3from typing import Any, Optional, Tuple
  4
  5import Cocoa
  6import Metal
  7import objc
  8
  9from syphon._native import cgl_context, server_options
 10from syphon.server_directory import SyphonServerDescription
 11from syphon.types import Region, Size, Texture
 12from syphon.utils import opengl
 13
 14
 15class BaseSyphonServer(ABC):
 16    """
 17    Abstract base class for Syphon servers.
 18
 19    Attributes:
 20    - name (str): The name of the Syphon server.
 21    """
 22
 23    def __init__(self, name: str):
 24        """
 25        Initialize a BaseSyphonServer.
 26
 27        Parameters:
 28        - name (str): The name of the Syphon server.
 29        """
 30        self._name = name
 31        self._lifecycle_lock = threading.RLock()
 32        self._stopped = False
 33        self._bound_thread = None
 34        self.context = None
 35
 36    def _finish_initialization(self, context):
 37        if context is None:
 38            self._stopped = True
 39            raise RuntimeError("Syphon could not create the server")
 40        self.context = context
 41
 42    @property
 43    def name(self) -> str:
 44        """The live native name; assignment updates discovery in other applications."""
 45        return self._name if self.context is None else self.context.name()
 46
 47    @name.setter
 48    def name(self, value: str):
 49        with self._lifecycle_lock:
 50            if self._stopped:
 51                raise RuntimeError("Syphon server is stopped")
 52            self.context.setName_(value)
 53
 54    @property
 55    def server_description(self) -> SyphonServerDescription:
 56        """Complete native connection metadata, also usable for private servers."""
 57        return SyphonServerDescription.from_native(self.context.serverDescription())
 58
 59    @property
 60    def new_frame_image(self) -> Any:
 61        """Current server output, or None; keep it alive while in use. PyObjC owns releases."""
 62        with self._lifecycle_lock:
 63            return None if self._stopped else self.context.newFrameImage()
 64
 65    def __enter__(self):
 66        with self._lifecycle_lock:
 67            if self._stopped:
 68                raise RuntimeError("Syphon server is stopped")
 69        return self
 70
 71    def __exit__(self, exc_type, exc_value, traceback):
 72        self.stop()
 73
 74    @abstractmethod
 75    def publish_frame_texture(
 76        self, texture: Texture, region: Optional[Region] = None, size: Optional[Size] = None, is_flipped: bool = False
 77    ):
 78        """
 79        Publish a frame with the given texture.
 80
 81        Parameters:
 82        - texture (Texture): The texture to publish.
 83        - region (Region, optional): The region of the texture to publish. Defaults to None.
 84        - size (Size, optional): The size of the texture. Defaults to None.
 85        - is_flipped (bool, optional): If True, the frame is flipped. Defaults to False.
 86        """
 87        pass
 88
 89    @abstractmethod
 90    def publish(self):
 91        """
 92        Publish the frame.
 93        """
 94        pass
 95
 96    def stop(self):
 97        """Stop once. An OpenGL framebuffer must be unbound first."""
 98        with self._lifecycle_lock:
 99            if self._stopped:
100                return
101            if self._bound_thread is not None:
102                raise RuntimeError("Unbind and publish the OpenGL framebuffer before stopping")
103            self._stopped = True
104            context = self.context
105        if context is not None:
106            context.stop()
107
108    @property
109    @abstractmethod
110    def has_clients(self) -> bool:
111        """
112        Check if the Syphon server has clients.
113
114        Returns:
115        - bool: True if there are clients, False otherwise.
116        """
117        pass
118
119    @abstractmethod
120    def _get_texture_size(self, texture: Texture) -> Size:
121        """
122        Get the size of the texture.
123
124        Parameters:
125        - texture (Texture): The texture.
126
127        Returns:
128        - Size: The size of the texture.
129        """
130        pass
131
132    def _prepare_region_and_size(
133        self, texture: Texture, region: Optional[Region] = None, size: Optional[Size] = None
134    ) -> Tuple[Region, Size]:
135        """
136        Prepare the region and size for publishing.
137
138        Parameters:
139        - texture (Texture): The texture to publish.
140        - region (Region, optional): The region of the texture to publish. Defaults to None.
141        - size (Size, optional): The size of the texture. Defaults to None.
142
143        Returns:
144        - Tuple[Region, Size]: The prepared region and size.
145        """
146        size = self._get_texture_size(texture) if size is None else size
147        if region is None:
148            region = (0, 0, *size)
149        return region, size
150
151
152class SyphonMetalServer(BaseSyphonServer):
153    """
154    Syphon server for Metal-based rendering.
155
156    Attributes:
157    - name (str): The name of the Syphon server.
158    - device (Any): The Metal device.
159    - command_queue (Any): The Metal command queue.
160    - context (Any): The Syphon-Metal context.
161    """
162
163    def __init__(
164        self, name: str, device: Optional[Any] = None, command_queue: Optional[Any] = None, *, is_private: bool = False
165    ):
166        """
167        Initialize a SyphonMetalServer.
168
169        Parameters:
170        - name (str): The name of the Syphon server.
171        - device (Any, optional): The Metal device. If None, the default system device will be used.
172        - command_queue (Any, optional): The Metal command queue. If None, a new command queue will be created.
173        - is_private (bool): Hide the server from discovery; connect using server_description instead.
174        """
175        super().__init__(name)
176
177        self.device = device
178        self.command_queue = command_queue
179
180        # setup device
181        if self.device is None:
182            self.device = Metal.MTLCreateSystemDefaultDevice()
183
184        if self.device is None:
185            raise RuntimeError("No Metal device is available")
186
187        # setup command queue
188        if self.command_queue is None:
189            self.command_queue = self.device.newCommandQueue()
190
191        if self.command_queue is None:
192            raise RuntimeError("Could not create a Metal command queue")
193
194        # setup syphon-metal context
195        SyphonMetalServerObjC = objc.lookUpClass("SyphonMetalServer")
196        self._finish_initialization(
197            SyphonMetalServerObjC.alloc().initWithName_device_options_(name, self.device, server_options(is_private))
198        )
199
200    def publish_frame_texture(
201        self,
202        texture: Texture,
203        region: Optional[Region] = None,
204        size: Optional[Size] = None,
205        is_flipped: bool = False,
206        command_buffer: Optional[Any] = None,
207        auto_commit: bool = True,
208    ):
209        """
210        Publish a frame with the given Metal texture.
211
212        Parameters:
213        - texture (Texture): The Metal texture to publish.
214        - region (Region, optional): The region of the texture to publish. Defaults to None.
215        - size (Size, optional): The size of the texture. Defaults to None.
216        - is_flipped (bool, optional): If True, the frame is flipped. Defaults to False.
217        - command_buffer (Any, optional): The Metal command buffer. If None, a new command buffer will be created.
218        - auto_commit (bool, optional): If True, the command buffer is committed automatically. Defaults to True.
219        """
220        # create ns-region
221        region, _ = self._prepare_region_and_size(texture, region, size)
222        ns_region = Cocoa.NSRect((region[0], region[1]), (region[2], region[3]))
223
224        # prepare command buffer if necessary
225        if command_buffer is None:
226            command_buffer = self.command_queue.commandBuffer()
227
228        # publish actual texture
229        self.context.publishFrameTexture_onCommandBuffer_imageRegion_flipped_(
230            texture, command_buffer, ns_region, is_flipped
231        )
232        # commit command buffer
233        if auto_commit:
234            command_buffer.commitAndWaitUntilSubmitted()
235
236    def publish(self):
237        """
238        Publish the frame.
239        """
240        self.context.publish()
241
242    @property
243    def has_clients(self) -> bool:
244        """
245        Check if the SyphonMetalServer has clients.
246
247        Returns:
248        - bool: True if there are clients, False otherwise.
249        """
250        return self.context.hasClients()
251
252    def _get_texture_size(self, texture: Texture) -> Tuple[int, int]:
253        """
254        Get the size of the Metal texture.
255
256        Parameters:
257        - texture (Texture): The Metal texture.
258
259        Returns:
260        - Tuple[int, int]: The size of the texture.
261        """
262        return texture.width(), texture.height()
263
264
265class SyphonOpenGLServer(BaseSyphonServer):
266    """
267    Syphon server for OpenGL-based rendering.
268
269    Attributes:
270    - name (str): The name of the Syphon server.
271    - cgl_context_obj (Any): The CGL context object.
272    - context (Any): The Syphon-OpenGL context.
273    """
274
275    def __init__(
276        self,
277        name: str,
278        cgl_context_obj: Optional[Any] = None,
279        *,
280        is_private: bool = False,
281        antialias_sample_count: int = 0,
282        depth_buffer_resolution: int = 0,
283        stencil_buffer_resolution: int = 0,
284    ):
285        """
286        Initialize a SyphonOpenGLServer.
287
288        Parameters:
289        - name (str): The name of the Syphon server.
290        - cgl_context_obj (Any, optional): The CGL context object. If None, the current context will be used.
291        - is_private (bool): Hide the server from discovery; this is not access control.
292        - antialias_sample_count (int): Requested multisample count, or zero to disable it.
293        - depth_buffer_resolution (int): Requested depth bits: 0, 16, 24, or 32.
294        - stencil_buffer_resolution (int): Requested stencil bits: 0, 1, 4, 8, or 16.
295
296        Framebuffer options apply to bind_to_draw_frame/unbind_and_publish. The native
297        driver may choose the nearest supported buffer configuration.
298        """
299        super().__init__(name)
300
301        opengl._require_pyopengl()
302
303        for label, value, allowed in (
304            ("antialias_sample_count", antialias_sample_count, None),
305            ("depth_buffer_resolution", depth_buffer_resolution, (0, 16, 24, 32)),
306            ("stencil_buffer_resolution", stencil_buffer_resolution, (0, 1, 4, 8, 16)),
307        ):
308            if isinstance(value, bool) or not isinstance(value, int) or value < 0 or (allowed and value not in allowed):
309                raise ValueError(f"Invalid {label}: {value}")
310
311        # store CGL context object
312        self.cgl_context_obj = opengl.get_current_cgl_context_obj() if cgl_context_obj is None else cgl_context_obj
313
314        # create syphon gl server
315        SyphonOpenGLServerObjC = objc.lookUpClass("SyphonOpenGLServer")
316        self._finish_initialization(
317            SyphonOpenGLServerObjC.alloc().initWithName_context_options_(
318                name,
319                cgl_context(self.cgl_context_obj),
320                server_options(
321                    is_private,
322                    SyphonServerOptionAntialiasSampleCount=antialias_sample_count,
323                    SyphonServerOptionDepthBufferResolution=depth_buffer_resolution,
324                    SyphonServerOptionStencilBufferResolution=stencil_buffer_resolution,
325                ),
326            )
327        )
328
329    def bind_to_draw_frame(self, size: Size) -> bool:
330        """Bind Syphon's framebuffer. Pair a successful bind with unbind_and_publish().
331
332        Drawing, unbinding, and native context access require exclusive use of the CGL
333        context by the calling thread. A failed bind must not be followed by unbinding.
334        """
335        if len(size) != 2 or any(isinstance(v, bool) or not isinstance(v, int) or v <= 0 for v in size):
336            raise ValueError("Frame size must contain two positive integers")
337        with self._lifecycle_lock:
338            if self._stopped:
339                raise RuntimeError("Syphon server is stopped")
340            if self._bound_thread is not None:
341                raise RuntimeError("Syphon framebuffer is already bound")
342            success = bool(self.context.bindToDrawFrameOfSize_(Cocoa.NSSize(*size)))
343            if success:
344                self._bound_thread = threading.current_thread()
345            return success
346
347    def unbind_and_publish(self):
348        """Publish and unbind on the same thread that successfully bound the framebuffer."""
349        with self._lifecycle_lock:
350            if self._bound_thread is None:
351                raise RuntimeError("No Syphon framebuffer is bound")
352            if self._bound_thread is not threading.current_thread():
353                raise RuntimeError("Unbind on the thread that bound the Syphon framebuffer")
354            self.context.unbindAndPublish()
355            self._bound_thread = None
356
357    def publish_frame_texture(
358        self,
359        texture: int,
360        region: Optional[Region] = None,
361        size: Optional[Size] = None,
362        is_flipped: bool = False,
363        target: int = opengl.GL_TEXTURE_2D,
364    ):
365        """
366        Publish a frame with the given OpenGL texture.
367
368        Parameters:
369        - texture (int): The OpenGL texture identifier to publish.
370        - region (Region, optional): The region of the texture to publish. Defaults to None.
371        - size (Size, optional): The size of the texture. Defaults to None.
372        - is_flipped (bool, optional): If True, the frame is flipped. Defaults to False.
373        - target (int, optional): The OpenGL texture target. Defaults to GL_TEXTURE_2D.
374        """
375        # create ns-region
376        region, size = self._prepare_region_and_size(texture, region, size)
377        ns_region = Cocoa.NSRect((region[0], region[1]), (region[2], region[3]))
378        ns_size = Cocoa.NSSize(size[0], size[1])
379
380        self.context.publishFrameTexture_textureTarget_imageRegion_textureDimensions_flipped_(
381            texture, target, ns_region, ns_size, is_flipped
382        )
383
384    def publish(self):
385        """
386        Publish the frame.
387        """
388        self.context.publish()
389
390    @property
391    def has_clients(self) -> bool:
392        """
393        Check if the SyphonOpenGLServer has clients.
394
395        Returns:
396        - bool: True if there are clients, False otherwise.
397        """
398        return self.context.hasClients()
399
400    def _get_texture_size(self, texture: Texture) -> Size:
401        """
402        Get the size of the OpenGL texture.
403
404        Parameters:
405        - texture (Texture): The OpenGL texture.
406
407        Returns:
408        - Size: The size of the texture.
409        """
410        gl = opengl._require_pyopengl()
411        gl.glBindTexture(gl.GL_TEXTURE_2D, texture)
412
413        width = gl.GLint()
414        height = gl.GLint()
415
416        gl.glGetTexLevelParameteriv(gl.GL_TEXTURE_2D, 0, gl.GL_TEXTURE_WIDTH, width)
417        gl.glGetTexLevelParameteriv(gl.GL_TEXTURE_2D, 0, gl.GL_TEXTURE_HEIGHT, height)
418
419        gl.glBindTexture(gl.GL_TEXTURE_2D, 0)
420
421        return int(width.value), int(height.value)
class BaseSyphonServer(abc.ABC):
 16class BaseSyphonServer(ABC):
 17    """
 18    Abstract base class for Syphon servers.
 19
 20    Attributes:
 21    - name (str): The name of the Syphon server.
 22    """
 23
 24    def __init__(self, name: str):
 25        """
 26        Initialize a BaseSyphonServer.
 27
 28        Parameters:
 29        - name (str): The name of the Syphon server.
 30        """
 31        self._name = name
 32        self._lifecycle_lock = threading.RLock()
 33        self._stopped = False
 34        self._bound_thread = None
 35        self.context = None
 36
 37    def _finish_initialization(self, context):
 38        if context is None:
 39            self._stopped = True
 40            raise RuntimeError("Syphon could not create the server")
 41        self.context = context
 42
 43    @property
 44    def name(self) -> str:
 45        """The live native name; assignment updates discovery in other applications."""
 46        return self._name if self.context is None else self.context.name()
 47
 48    @name.setter
 49    def name(self, value: str):
 50        with self._lifecycle_lock:
 51            if self._stopped:
 52                raise RuntimeError("Syphon server is stopped")
 53            self.context.setName_(value)
 54
 55    @property
 56    def server_description(self) -> SyphonServerDescription:
 57        """Complete native connection metadata, also usable for private servers."""
 58        return SyphonServerDescription.from_native(self.context.serverDescription())
 59
 60    @property
 61    def new_frame_image(self) -> Any:
 62        """Current server output, or None; keep it alive while in use. PyObjC owns releases."""
 63        with self._lifecycle_lock:
 64            return None if self._stopped else self.context.newFrameImage()
 65
 66    def __enter__(self):
 67        with self._lifecycle_lock:
 68            if self._stopped:
 69                raise RuntimeError("Syphon server is stopped")
 70        return self
 71
 72    def __exit__(self, exc_type, exc_value, traceback):
 73        self.stop()
 74
 75    @abstractmethod
 76    def publish_frame_texture(
 77        self, texture: Texture, region: Optional[Region] = None, size: Optional[Size] = None, is_flipped: bool = False
 78    ):
 79        """
 80        Publish a frame with the given texture.
 81
 82        Parameters:
 83        - texture (Texture): The texture to publish.
 84        - region (Region, optional): The region of the texture to publish. Defaults to None.
 85        - size (Size, optional): The size of the texture. Defaults to None.
 86        - is_flipped (bool, optional): If True, the frame is flipped. Defaults to False.
 87        """
 88        pass
 89
 90    @abstractmethod
 91    def publish(self):
 92        """
 93        Publish the frame.
 94        """
 95        pass
 96
 97    def stop(self):
 98        """Stop once. An OpenGL framebuffer must be unbound first."""
 99        with self._lifecycle_lock:
100            if self._stopped:
101                return
102            if self._bound_thread is not None:
103                raise RuntimeError("Unbind and publish the OpenGL framebuffer before stopping")
104            self._stopped = True
105            context = self.context
106        if context is not None:
107            context.stop()
108
109    @property
110    @abstractmethod
111    def has_clients(self) -> bool:
112        """
113        Check if the Syphon server has clients.
114
115        Returns:
116        - bool: True if there are clients, False otherwise.
117        """
118        pass
119
120    @abstractmethod
121    def _get_texture_size(self, texture: Texture) -> Size:
122        """
123        Get the size of the texture.
124
125        Parameters:
126        - texture (Texture): The texture.
127
128        Returns:
129        - Size: The size of the texture.
130        """
131        pass
132
133    def _prepare_region_and_size(
134        self, texture: Texture, region: Optional[Region] = None, size: Optional[Size] = None
135    ) -> Tuple[Region, Size]:
136        """
137        Prepare the region and size for publishing.
138
139        Parameters:
140        - texture (Texture): The texture to publish.
141        - region (Region, optional): The region of the texture to publish. Defaults to None.
142        - size (Size, optional): The size of the texture. Defaults to None.
143
144        Returns:
145        - Tuple[Region, Size]: The prepared region and size.
146        """
147        size = self._get_texture_size(texture) if size is None else size
148        if region is None:
149            region = (0, 0, *size)
150        return region, size

Abstract base class for Syphon servers.

Attributes:

  • name (str): The name of the Syphon server.
BaseSyphonServer(name: str)
24    def __init__(self, name: str):
25        """
26        Initialize a BaseSyphonServer.
27
28        Parameters:
29        - name (str): The name of the Syphon server.
30        """
31        self._name = name
32        self._lifecycle_lock = threading.RLock()
33        self._stopped = False
34        self._bound_thread = None
35        self.context = None

Initialize a BaseSyphonServer.

Parameters:

  • name (str): The name of the Syphon server.
context
name: str
43    @property
44    def name(self) -> str:
45        """The live native name; assignment updates discovery in other applications."""
46        return self._name if self.context is None else self.context.name()

The live native name; assignment updates discovery in other applications.

server_description: syphon.server_directory.SyphonServerDescription
55    @property
56    def server_description(self) -> SyphonServerDescription:
57        """Complete native connection metadata, also usable for private servers."""
58        return SyphonServerDescription.from_native(self.context.serverDescription())

Complete native connection metadata, also usable for private servers.

new_frame_image: Any
60    @property
61    def new_frame_image(self) -> Any:
62        """Current server output, or None; keep it alive while in use. PyObjC owns releases."""
63        with self._lifecycle_lock:
64            return None if self._stopped else self.context.newFrameImage()

Current server output, or None; keep it alive while in use. PyObjC owns releases.

@abstractmethod
def publish_frame_texture( self, texture: Any, region: Tuple[int, int, int, int] | None = None, size: Tuple[int, int] | None = None, is_flipped: bool = False):
75    @abstractmethod
76    def publish_frame_texture(
77        self, texture: Texture, region: Optional[Region] = None, size: Optional[Size] = None, is_flipped: bool = False
78    ):
79        """
80        Publish a frame with the given texture.
81
82        Parameters:
83        - texture (Texture): The texture to publish.
84        - region (Region, optional): The region of the texture to publish. Defaults to None.
85        - size (Size, optional): The size of the texture. Defaults to None.
86        - is_flipped (bool, optional): If True, the frame is flipped. Defaults to False.
87        """
88        pass

Publish a frame with the given texture.

Parameters:

  • texture (Texture): The texture to publish.
  • region (Region, optional): The region of the texture to publish. Defaults to None.
  • size (Size, optional): The size of the texture. Defaults to None.
  • is_flipped (bool, optional): If True, the frame is flipped. Defaults to False.
@abstractmethod
def publish(self):
90    @abstractmethod
91    def publish(self):
92        """
93        Publish the frame.
94        """
95        pass

Publish the frame.

def stop(self):
 97    def stop(self):
 98        """Stop once. An OpenGL framebuffer must be unbound first."""
 99        with self._lifecycle_lock:
100            if self._stopped:
101                return
102            if self._bound_thread is not None:
103                raise RuntimeError("Unbind and publish the OpenGL framebuffer before stopping")
104            self._stopped = True
105            context = self.context
106        if context is not None:
107            context.stop()

Stop once. An OpenGL framebuffer must be unbound first.

has_clients: bool
109    @property
110    @abstractmethod
111    def has_clients(self) -> bool:
112        """
113        Check if the Syphon server has clients.
114
115        Returns:
116        - bool: True if there are clients, False otherwise.
117        """
118        pass

Check if the Syphon server has clients.

Returns:

  • bool: True if there are clients, False otherwise.
class SyphonMetalServer(BaseSyphonServer):
153class SyphonMetalServer(BaseSyphonServer):
154    """
155    Syphon server for Metal-based rendering.
156
157    Attributes:
158    - name (str): The name of the Syphon server.
159    - device (Any): The Metal device.
160    - command_queue (Any): The Metal command queue.
161    - context (Any): The Syphon-Metal context.
162    """
163
164    def __init__(
165        self, name: str, device: Optional[Any] = None, command_queue: Optional[Any] = None, *, is_private: bool = False
166    ):
167        """
168        Initialize a SyphonMetalServer.
169
170        Parameters:
171        - name (str): The name of the Syphon server.
172        - device (Any, optional): The Metal device. If None, the default system device will be used.
173        - command_queue (Any, optional): The Metal command queue. If None, a new command queue will be created.
174        - is_private (bool): Hide the server from discovery; connect using server_description instead.
175        """
176        super().__init__(name)
177
178        self.device = device
179        self.command_queue = command_queue
180
181        # setup device
182        if self.device is None:
183            self.device = Metal.MTLCreateSystemDefaultDevice()
184
185        if self.device is None:
186            raise RuntimeError("No Metal device is available")
187
188        # setup command queue
189        if self.command_queue is None:
190            self.command_queue = self.device.newCommandQueue()
191
192        if self.command_queue is None:
193            raise RuntimeError("Could not create a Metal command queue")
194
195        # setup syphon-metal context
196        SyphonMetalServerObjC = objc.lookUpClass("SyphonMetalServer")
197        self._finish_initialization(
198            SyphonMetalServerObjC.alloc().initWithName_device_options_(name, self.device, server_options(is_private))
199        )
200
201    def publish_frame_texture(
202        self,
203        texture: Texture,
204        region: Optional[Region] = None,
205        size: Optional[Size] = None,
206        is_flipped: bool = False,
207        command_buffer: Optional[Any] = None,
208        auto_commit: bool = True,
209    ):
210        """
211        Publish a frame with the given Metal texture.
212
213        Parameters:
214        - texture (Texture): The Metal texture to publish.
215        - region (Region, optional): The region of the texture to publish. Defaults to None.
216        - size (Size, optional): The size of the texture. Defaults to None.
217        - is_flipped (bool, optional): If True, the frame is flipped. Defaults to False.
218        - command_buffer (Any, optional): The Metal command buffer. If None, a new command buffer will be created.
219        - auto_commit (bool, optional): If True, the command buffer is committed automatically. Defaults to True.
220        """
221        # create ns-region
222        region, _ = self._prepare_region_and_size(texture, region, size)
223        ns_region = Cocoa.NSRect((region[0], region[1]), (region[2], region[3]))
224
225        # prepare command buffer if necessary
226        if command_buffer is None:
227            command_buffer = self.command_queue.commandBuffer()
228
229        # publish actual texture
230        self.context.publishFrameTexture_onCommandBuffer_imageRegion_flipped_(
231            texture, command_buffer, ns_region, is_flipped
232        )
233        # commit command buffer
234        if auto_commit:
235            command_buffer.commitAndWaitUntilSubmitted()
236
237    def publish(self):
238        """
239        Publish the frame.
240        """
241        self.context.publish()
242
243    @property
244    def has_clients(self) -> bool:
245        """
246        Check if the SyphonMetalServer has clients.
247
248        Returns:
249        - bool: True if there are clients, False otherwise.
250        """
251        return self.context.hasClients()
252
253    def _get_texture_size(self, texture: Texture) -> Tuple[int, int]:
254        """
255        Get the size of the Metal texture.
256
257        Parameters:
258        - texture (Texture): The Metal texture.
259
260        Returns:
261        - Tuple[int, int]: The size of the texture.
262        """
263        return texture.width(), texture.height()

Syphon server for Metal-based rendering.

Attributes:

  • name (str): The name of the Syphon server.
  • device (Any): The Metal device.
  • command_queue (Any): The Metal command queue.
  • context (Any): The Syphon-Metal context.
SyphonMetalServer( name: str, device: Any | None = None, command_queue: Any | None = None, *, is_private: bool = False)
164    def __init__(
165        self, name: str, device: Optional[Any] = None, command_queue: Optional[Any] = None, *, is_private: bool = False
166    ):
167        """
168        Initialize a SyphonMetalServer.
169
170        Parameters:
171        - name (str): The name of the Syphon server.
172        - device (Any, optional): The Metal device. If None, the default system device will be used.
173        - command_queue (Any, optional): The Metal command queue. If None, a new command queue will be created.
174        - is_private (bool): Hide the server from discovery; connect using server_description instead.
175        """
176        super().__init__(name)
177
178        self.device = device
179        self.command_queue = command_queue
180
181        # setup device
182        if self.device is None:
183            self.device = Metal.MTLCreateSystemDefaultDevice()
184
185        if self.device is None:
186            raise RuntimeError("No Metal device is available")
187
188        # setup command queue
189        if self.command_queue is None:
190            self.command_queue = self.device.newCommandQueue()
191
192        if self.command_queue is None:
193            raise RuntimeError("Could not create a Metal command queue")
194
195        # setup syphon-metal context
196        SyphonMetalServerObjC = objc.lookUpClass("SyphonMetalServer")
197        self._finish_initialization(
198            SyphonMetalServerObjC.alloc().initWithName_device_options_(name, self.device, server_options(is_private))
199        )

Initialize a SyphonMetalServer.

Parameters:

  • name (str): The name of the Syphon server.
  • device (Any, optional): The Metal device. If None, the default system device will be used.
  • command_queue (Any, optional): The Metal command queue. If None, a new command queue will be created.
  • is_private (bool): Hide the server from discovery; connect using server_description instead.
device
command_queue
def publish_frame_texture( self, texture: Any, region: Tuple[int, int, int, int] | None = None, size: Tuple[int, int] | None = None, is_flipped: bool = False, command_buffer: Any | None = None, auto_commit: bool = True):
201    def publish_frame_texture(
202        self,
203        texture: Texture,
204        region: Optional[Region] = None,
205        size: Optional[Size] = None,
206        is_flipped: bool = False,
207        command_buffer: Optional[Any] = None,
208        auto_commit: bool = True,
209    ):
210        """
211        Publish a frame with the given Metal texture.
212
213        Parameters:
214        - texture (Texture): The Metal texture to publish.
215        - region (Region, optional): The region of the texture to publish. Defaults to None.
216        - size (Size, optional): The size of the texture. Defaults to None.
217        - is_flipped (bool, optional): If True, the frame is flipped. Defaults to False.
218        - command_buffer (Any, optional): The Metal command buffer. If None, a new command buffer will be created.
219        - auto_commit (bool, optional): If True, the command buffer is committed automatically. Defaults to True.
220        """
221        # create ns-region
222        region, _ = self._prepare_region_and_size(texture, region, size)
223        ns_region = Cocoa.NSRect((region[0], region[1]), (region[2], region[3]))
224
225        # prepare command buffer if necessary
226        if command_buffer is None:
227            command_buffer = self.command_queue.commandBuffer()
228
229        # publish actual texture
230        self.context.publishFrameTexture_onCommandBuffer_imageRegion_flipped_(
231            texture, command_buffer, ns_region, is_flipped
232        )
233        # commit command buffer
234        if auto_commit:
235            command_buffer.commitAndWaitUntilSubmitted()

Publish a frame with the given Metal texture.

Parameters:

  • texture (Texture): The Metal texture to publish.
  • region (Region, optional): The region of the texture to publish. Defaults to None.
  • size (Size, optional): The size of the texture. Defaults to None.
  • is_flipped (bool, optional): If True, the frame is flipped. Defaults to False.
  • command_buffer (Any, optional): The Metal command buffer. If None, a new command buffer will be created.
  • auto_commit (bool, optional): If True, the command buffer is committed automatically. Defaults to True.
def publish(self):
237    def publish(self):
238        """
239        Publish the frame.
240        """
241        self.context.publish()

Publish the frame.

has_clients: bool
243    @property
244    def has_clients(self) -> bool:
245        """
246        Check if the SyphonMetalServer has clients.
247
248        Returns:
249        - bool: True if there are clients, False otherwise.
250        """
251        return self.context.hasClients()

Check if the SyphonMetalServer has clients.

Returns:

  • bool: True if there are clients, False otherwise.
class SyphonOpenGLServer(BaseSyphonServer):
266class SyphonOpenGLServer(BaseSyphonServer):
267    """
268    Syphon server for OpenGL-based rendering.
269
270    Attributes:
271    - name (str): The name of the Syphon server.
272    - cgl_context_obj (Any): The CGL context object.
273    - context (Any): The Syphon-OpenGL context.
274    """
275
276    def __init__(
277        self,
278        name: str,
279        cgl_context_obj: Optional[Any] = None,
280        *,
281        is_private: bool = False,
282        antialias_sample_count: int = 0,
283        depth_buffer_resolution: int = 0,
284        stencil_buffer_resolution: int = 0,
285    ):
286        """
287        Initialize a SyphonOpenGLServer.
288
289        Parameters:
290        - name (str): The name of the Syphon server.
291        - cgl_context_obj (Any, optional): The CGL context object. If None, the current context will be used.
292        - is_private (bool): Hide the server from discovery; this is not access control.
293        - antialias_sample_count (int): Requested multisample count, or zero to disable it.
294        - depth_buffer_resolution (int): Requested depth bits: 0, 16, 24, or 32.
295        - stencil_buffer_resolution (int): Requested stencil bits: 0, 1, 4, 8, or 16.
296
297        Framebuffer options apply to bind_to_draw_frame/unbind_and_publish. The native
298        driver may choose the nearest supported buffer configuration.
299        """
300        super().__init__(name)
301
302        opengl._require_pyopengl()
303
304        for label, value, allowed in (
305            ("antialias_sample_count", antialias_sample_count, None),
306            ("depth_buffer_resolution", depth_buffer_resolution, (0, 16, 24, 32)),
307            ("stencil_buffer_resolution", stencil_buffer_resolution, (0, 1, 4, 8, 16)),
308        ):
309            if isinstance(value, bool) or not isinstance(value, int) or value < 0 or (allowed and value not in allowed):
310                raise ValueError(f"Invalid {label}: {value}")
311
312        # store CGL context object
313        self.cgl_context_obj = opengl.get_current_cgl_context_obj() if cgl_context_obj is None else cgl_context_obj
314
315        # create syphon gl server
316        SyphonOpenGLServerObjC = objc.lookUpClass("SyphonOpenGLServer")
317        self._finish_initialization(
318            SyphonOpenGLServerObjC.alloc().initWithName_context_options_(
319                name,
320                cgl_context(self.cgl_context_obj),
321                server_options(
322                    is_private,
323                    SyphonServerOptionAntialiasSampleCount=antialias_sample_count,
324                    SyphonServerOptionDepthBufferResolution=depth_buffer_resolution,
325                    SyphonServerOptionStencilBufferResolution=stencil_buffer_resolution,
326                ),
327            )
328        )
329
330    def bind_to_draw_frame(self, size: Size) -> bool:
331        """Bind Syphon's framebuffer. Pair a successful bind with unbind_and_publish().
332
333        Drawing, unbinding, and native context access require exclusive use of the CGL
334        context by the calling thread. A failed bind must not be followed by unbinding.
335        """
336        if len(size) != 2 or any(isinstance(v, bool) or not isinstance(v, int) or v <= 0 for v in size):
337            raise ValueError("Frame size must contain two positive integers")
338        with self._lifecycle_lock:
339            if self._stopped:
340                raise RuntimeError("Syphon server is stopped")
341            if self._bound_thread is not None:
342                raise RuntimeError("Syphon framebuffer is already bound")
343            success = bool(self.context.bindToDrawFrameOfSize_(Cocoa.NSSize(*size)))
344            if success:
345                self._bound_thread = threading.current_thread()
346            return success
347
348    def unbind_and_publish(self):
349        """Publish and unbind on the same thread that successfully bound the framebuffer."""
350        with self._lifecycle_lock:
351            if self._bound_thread is None:
352                raise RuntimeError("No Syphon framebuffer is bound")
353            if self._bound_thread is not threading.current_thread():
354                raise RuntimeError("Unbind on the thread that bound the Syphon framebuffer")
355            self.context.unbindAndPublish()
356            self._bound_thread = None
357
358    def publish_frame_texture(
359        self,
360        texture: int,
361        region: Optional[Region] = None,
362        size: Optional[Size] = None,
363        is_flipped: bool = False,
364        target: int = opengl.GL_TEXTURE_2D,
365    ):
366        """
367        Publish a frame with the given OpenGL texture.
368
369        Parameters:
370        - texture (int): The OpenGL texture identifier to publish.
371        - region (Region, optional): The region of the texture to publish. Defaults to None.
372        - size (Size, optional): The size of the texture. Defaults to None.
373        - is_flipped (bool, optional): If True, the frame is flipped. Defaults to False.
374        - target (int, optional): The OpenGL texture target. Defaults to GL_TEXTURE_2D.
375        """
376        # create ns-region
377        region, size = self._prepare_region_and_size(texture, region, size)
378        ns_region = Cocoa.NSRect((region[0], region[1]), (region[2], region[3]))
379        ns_size = Cocoa.NSSize(size[0], size[1])
380
381        self.context.publishFrameTexture_textureTarget_imageRegion_textureDimensions_flipped_(
382            texture, target, ns_region, ns_size, is_flipped
383        )
384
385    def publish(self):
386        """
387        Publish the frame.
388        """
389        self.context.publish()
390
391    @property
392    def has_clients(self) -> bool:
393        """
394        Check if the SyphonOpenGLServer has clients.
395
396        Returns:
397        - bool: True if there are clients, False otherwise.
398        """
399        return self.context.hasClients()
400
401    def _get_texture_size(self, texture: Texture) -> Size:
402        """
403        Get the size of the OpenGL texture.
404
405        Parameters:
406        - texture (Texture): The OpenGL texture.
407
408        Returns:
409        - Size: The size of the texture.
410        """
411        gl = opengl._require_pyopengl()
412        gl.glBindTexture(gl.GL_TEXTURE_2D, texture)
413
414        width = gl.GLint()
415        height = gl.GLint()
416
417        gl.glGetTexLevelParameteriv(gl.GL_TEXTURE_2D, 0, gl.GL_TEXTURE_WIDTH, width)
418        gl.glGetTexLevelParameteriv(gl.GL_TEXTURE_2D, 0, gl.GL_TEXTURE_HEIGHT, height)
419
420        gl.glBindTexture(gl.GL_TEXTURE_2D, 0)
421
422        return int(width.value), int(height.value)

Syphon server for OpenGL-based rendering.

Attributes:

  • name (str): The name of the Syphon server.
  • cgl_context_obj (Any): The CGL context object.
  • context (Any): The Syphon-OpenGL context.
SyphonOpenGLServer( name: str, cgl_context_obj: Any | None = None, *, is_private: bool = False, antialias_sample_count: int = 0, depth_buffer_resolution: int = 0, stencil_buffer_resolution: int = 0)
276    def __init__(
277        self,
278        name: str,
279        cgl_context_obj: Optional[Any] = None,
280        *,
281        is_private: bool = False,
282        antialias_sample_count: int = 0,
283        depth_buffer_resolution: int = 0,
284        stencil_buffer_resolution: int = 0,
285    ):
286        """
287        Initialize a SyphonOpenGLServer.
288
289        Parameters:
290        - name (str): The name of the Syphon server.
291        - cgl_context_obj (Any, optional): The CGL context object. If None, the current context will be used.
292        - is_private (bool): Hide the server from discovery; this is not access control.
293        - antialias_sample_count (int): Requested multisample count, or zero to disable it.
294        - depth_buffer_resolution (int): Requested depth bits: 0, 16, 24, or 32.
295        - stencil_buffer_resolution (int): Requested stencil bits: 0, 1, 4, 8, or 16.
296
297        Framebuffer options apply to bind_to_draw_frame/unbind_and_publish. The native
298        driver may choose the nearest supported buffer configuration.
299        """
300        super().__init__(name)
301
302        opengl._require_pyopengl()
303
304        for label, value, allowed in (
305            ("antialias_sample_count", antialias_sample_count, None),
306            ("depth_buffer_resolution", depth_buffer_resolution, (0, 16, 24, 32)),
307            ("stencil_buffer_resolution", stencil_buffer_resolution, (0, 1, 4, 8, 16)),
308        ):
309            if isinstance(value, bool) or not isinstance(value, int) or value < 0 or (allowed and value not in allowed):
310                raise ValueError(f"Invalid {label}: {value}")
311
312        # store CGL context object
313        self.cgl_context_obj = opengl.get_current_cgl_context_obj() if cgl_context_obj is None else cgl_context_obj
314
315        # create syphon gl server
316        SyphonOpenGLServerObjC = objc.lookUpClass("SyphonOpenGLServer")
317        self._finish_initialization(
318            SyphonOpenGLServerObjC.alloc().initWithName_context_options_(
319                name,
320                cgl_context(self.cgl_context_obj),
321                server_options(
322                    is_private,
323                    SyphonServerOptionAntialiasSampleCount=antialias_sample_count,
324                    SyphonServerOptionDepthBufferResolution=depth_buffer_resolution,
325                    SyphonServerOptionStencilBufferResolution=stencil_buffer_resolution,
326                ),
327            )
328        )

Initialize a SyphonOpenGLServer.

Parameters:

  • name (str): The name of the Syphon server.
  • cgl_context_obj (Any, optional): The CGL context object. If None, the current context will be used.
  • is_private (bool): Hide the server from discovery; this is not access control.
  • antialias_sample_count (int): Requested multisample count, or zero to disable it.
  • depth_buffer_resolution (int): Requested depth bits: 0, 16, 24, or 32.
  • stencil_buffer_resolution (int): Requested stencil bits: 0, 1, 4, 8, or 16.

Framebuffer options apply to bind_to_draw_frame/unbind_and_publish. The native driver may choose the nearest supported buffer configuration.

cgl_context_obj
def bind_to_draw_frame(self, size: Tuple[int, int]) -> bool:
330    def bind_to_draw_frame(self, size: Size) -> bool:
331        """Bind Syphon's framebuffer. Pair a successful bind with unbind_and_publish().
332
333        Drawing, unbinding, and native context access require exclusive use of the CGL
334        context by the calling thread. A failed bind must not be followed by unbinding.
335        """
336        if len(size) != 2 or any(isinstance(v, bool) or not isinstance(v, int) or v <= 0 for v in size):
337            raise ValueError("Frame size must contain two positive integers")
338        with self._lifecycle_lock:
339            if self._stopped:
340                raise RuntimeError("Syphon server is stopped")
341            if self._bound_thread is not None:
342                raise RuntimeError("Syphon framebuffer is already bound")
343            success = bool(self.context.bindToDrawFrameOfSize_(Cocoa.NSSize(*size)))
344            if success:
345                self._bound_thread = threading.current_thread()
346            return success

Bind Syphon's framebuffer. Pair a successful bind with unbind_and_publish().

Drawing, unbinding, and native context access require exclusive use of the CGL context by the calling thread. A failed bind must not be followed by unbinding.

def unbind_and_publish(self):
348    def unbind_and_publish(self):
349        """Publish and unbind on the same thread that successfully bound the framebuffer."""
350        with self._lifecycle_lock:
351            if self._bound_thread is None:
352                raise RuntimeError("No Syphon framebuffer is bound")
353            if self._bound_thread is not threading.current_thread():
354                raise RuntimeError("Unbind on the thread that bound the Syphon framebuffer")
355            self.context.unbindAndPublish()
356            self._bound_thread = None

Publish and unbind on the same thread that successfully bound the framebuffer.

def publish_frame_texture( self, texture: int, region: Tuple[int, int, int, int] | None = None, size: Tuple[int, int] | None = None, is_flipped: bool = False, target: int = 3553):
358    def publish_frame_texture(
359        self,
360        texture: int,
361        region: Optional[Region] = None,
362        size: Optional[Size] = None,
363        is_flipped: bool = False,
364        target: int = opengl.GL_TEXTURE_2D,
365    ):
366        """
367        Publish a frame with the given OpenGL texture.
368
369        Parameters:
370        - texture (int): The OpenGL texture identifier to publish.
371        - region (Region, optional): The region of the texture to publish. Defaults to None.
372        - size (Size, optional): The size of the texture. Defaults to None.
373        - is_flipped (bool, optional): If True, the frame is flipped. Defaults to False.
374        - target (int, optional): The OpenGL texture target. Defaults to GL_TEXTURE_2D.
375        """
376        # create ns-region
377        region, size = self._prepare_region_and_size(texture, region, size)
378        ns_region = Cocoa.NSRect((region[0], region[1]), (region[2], region[3]))
379        ns_size = Cocoa.NSSize(size[0], size[1])
380
381        self.context.publishFrameTexture_textureTarget_imageRegion_textureDimensions_flipped_(
382            texture, target, ns_region, ns_size, is_flipped
383        )

Publish a frame with the given OpenGL texture.

Parameters:

  • texture (int): The OpenGL texture identifier to publish.
  • region (Region, optional): The region of the texture to publish. Defaults to None.
  • size (Size, optional): The size of the texture. Defaults to None.
  • is_flipped (bool, optional): If True, the frame is flipped. Defaults to False.
  • target (int, optional): The OpenGL texture target. Defaults to GL_TEXTURE_2D.
def publish(self):
385    def publish(self):
386        """
387        Publish the frame.
388        """
389        self.context.publish()

Publish the frame.

has_clients: bool
391    @property
392    def has_clients(self) -> bool:
393        """
394        Check if the SyphonOpenGLServer has clients.
395
396        Returns:
397        - bool: True if there are clients, False otherwise.
398        """
399        return self.context.hasClients()

Check if the SyphonOpenGLServer has clients.

Returns:

  • bool: True if there are clients, False otherwise.