Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 12 additions & 9 deletions .github/RELEASING.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
# CI and releases

The build workflow checks pushes and pull requests. It builds a universal wheel from the source
archive, checks Ruff and documentation, and tests the installed wheel on Apple Silicon and Intel
with Python 3.10–3.14 and free-threaded 3.13t/3.14t, both with and without optional dependencies.
Python 3.14 also installs and tests the source archive on both architectures. Metal tests skip
when a runner has no Metal device; a passing job with those skips does not validate GPU transfers.
The build workflow checks pull requests and pushes to `main`, avoiding duplicate runs for feature
branch updates. It builds a universal wheel from the source
archive, checks Ruff and documentation, and uses four routine test jobs covering the oldest and
newest supported Python versions, free-threaded Python, Apple Silicon, and Intel. Release validation
and manual full runs use ten test jobs for broader Python coverage. Both tiers test the installed
wheel with and without optional dependencies; native tests run on selected entries, and the full
Apple Silicon Python 3.14 entry also checks a clean source build. Metal tests skip when a runner has
no Metal device; a passing job with those skips does not validate GPU transfers.

To publish, run **Publish release** manually on the default branch and select PyPI, GitHub Releases,
or both. With neither selected, it only builds and validates. All validation jobs must pass before
publication. The version in `pyproject.toml` determines the release tag (`v0.2.0` for this version).
publication. The version in `pyproject.toml` determines the release tag (`v0.3.0` for this version).
Use a new version for each release; existing releases and packages are not overwritten.

Before the first PyPI publication, configure a GitHub trusted publisher on PyPI for owner `cansik`,
Expand All @@ -18,6 +21,6 @@ PyPI API token. See the [PyPI trusted publishing guide](https://docs.pypi.org/tr

For documentation hosting, select **GitHub Actions** as the repository's Pages source. The
**Publish documentation** workflow runs manually or on pushed `v*` tags. Tags created by the
release workflow's `GITHUB_TOKEN` do not trigger another workflow, so run documentation publication
manually after those releases.

release workflow's `GITHUB_TOKEN` do not trigger another workflow, so **Publish release** calls the
documentation workflow directly after a successful PyPI publication or GitHub release. Documentation
is built from the same commit as the release; validation-only runs do not deploy it.
50 changes: 45 additions & 5 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,20 @@ name: Build and test

on:
push:
branches: ['**']
branches: [main]
pull_request:
workflow_dispatch:
inputs:
full:
description: Test all supported Python versions
type: boolean
default: false
workflow_call:
inputs:
full:
description: Test all supported Python versions
type: boolean
default: false
outputs:
version:
description: Package version from pyproject.toml
Expand Down Expand Up @@ -61,6 +71,7 @@ jobs:
if-no-files-found: error

test:
if: ${{ !inputs.full }}
needs: build
name: Python ${{ matrix.python }} on ${{ matrix.os }}
runs-on: ${{ matrix.os }}
Expand All @@ -69,8 +80,13 @@ jobs:
fail-fast: false
matrix:
os: [macos-15, macos-15-intel]
python: ['3.10', '3.11', '3.12', '3.13', '3.14', '3.13t', '3.14t']
steps:
python: ['3.10', '3.14', '3.14t']
exclude:
- os: macos-15-intel
python: '3.10'
- os: macos-15-intel
python: '3.14t'
steps: &test-steps
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
Expand All @@ -86,11 +102,35 @@ jobs:
name: python-dist
path: dist
- name: Ensure the Xcode Metal compiler is available for source builds
if: matrix.python == '3.14'
if: inputs.full && matrix.os == 'macos-15' && matrix.python == '3.14'
run: xcrun metal --version || xcodebuild -downloadComponent MetalToolchain
- name: Test installed wheel with and without extras
env:
TEST_PYTHON: ${{ steps.python.outputs.python-path }}
TEST_VARIANT: ${{ endsWith(matrix.python, 't') && 'free-threaded' || 'standard' }}
TEST_SOURCE: ${{ matrix.python == '3.14' && 'true' || 'false' }}
TEST_PYTHON_VERSION: ${{ matrix.python }}
TEST_NATIVE: ${{ (matrix.python == '3.14' || (matrix.os == 'macos-15' && matrix.python == '3.14t')) && 'true' || 'false' }}
TEST_SOURCE: ${{ inputs.full && matrix.os == 'macos-15' && matrix.python == '3.14' && 'true' || 'false' }}
run: bash scripts/ci_test.sh

test-full:
if: ${{ inputs.full }}
needs: build
name: Python ${{ matrix.python }} on ${{ matrix.os }}
runs-on: ${{ matrix.os }}
timeout-minutes: 30
strategy:
fail-fast: false
matrix:
os: [macos-15, macos-15-intel]
python: ['3.10', '3.11', '3.12', '3.13', '3.14', '3.13t', '3.14t']
exclude:
- os: macos-15-intel
python: '3.11'
- os: macos-15-intel
python: '3.12'
- os: macos-15-intel
python: '3.13'
- os: macos-15-intel
python: '3.13t'
steps: *test-steps
2 changes: 2 additions & 0 deletions .github/workflows/docs.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
name: Publish documentation

on:
workflow_call:
workflow_dispatch:
push:
tags: ['v*']
Expand All @@ -19,6 +20,7 @@ jobs:
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ${{ github.sha }}
submodules: recursive
persist-credentials: false
- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
Expand Down
11 changes: 11 additions & 0 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ jobs:
validate:
needs: guard
uses: ./.github/workflows/build.yml
with:
full: true

pypi:
if: inputs.publish_pypi
Expand Down Expand Up @@ -74,3 +76,12 @@ jobs:
test -z "$existing_tag" || { echo "Release tag already exists: $existing_tag"; exit 1; }
gh release create "v$RELEASE_VERSION" dist/*.whl dist/*.tar.gz \
--target "$RELEASE_COMMIT" --title "Version $RELEASE_VERSION" --generate-notes

docs:
needs: [pypi, release]
if: ${{ !cancelled() && (needs.pypi.result == 'success' || needs.release.result == 'success') }}
uses: ./.github/workflows/docs.yml
permissions:
contents: read
pages: write
id-token: write
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -161,3 +161,6 @@ cython_debug/
.DS_Store
.ruff_cache/
docs/**/*

# Local benchmark runs
/benchmark-results/
2 changes: 1 addition & 1 deletion CITATION.cff
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ cff-version: 1.2.0
message: "If you use this software, please cite it using these metadata."
type: software
title: "syphon-python"
version: "0.2.0"
version: "0.3.0"
authors:
- family-names: "Bruggisser"
given-names: "Florian"
Expand Down
44 changes: 43 additions & 1 deletion DOCUMENTATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ texture = ... # MTLTexture or glTexture
server.publish_frame_texture(texture)
```

The `syphon.server.BaseSyphonServer.publish_frame_texture()` contains a flag called `flip` to flip the texture horizontally. This can be set to `True` if the image is upside down on the receiver side.
The `syphon.server.BaseSyphonServer.publish_frame_texture()` contains a flag called `is_flipped` to flip the texture vertically. This can be set to `True` if the image is upside down on the receiver side.

It is also possible to check if a server has connected clients with the `has_clients` property.

Expand All @@ -65,6 +65,28 @@ mtl_command_queue = mtl_device.newCommandQueue()
server = syphon.SyphonMetalServer("Demo", device=mtl_device, command_queue=mtl_command_queue)
```

When an application already renders with Metal, rendering and publishing can share a command buffer.
This keeps the work on the GPU and lets the application control when it is submitted. Publishing
normally waits for GPU completion, so the CPU can safely update the texture for the next frame.
To overlap image preparation with publishing, use `auto_commit=False` and submit the buffer yourself:

```python
buffer = server.command_queue.commandBuffer()
... # encode rendering commands into buffer

server.publish_frame_texture(texture, command_buffer=buffer, auto_commit=False)
buffer.commit()

... # prepare other work while the GPU runs

# wait before overwriting this texture from the CPU
buffer.waitUntilCompleted()
```

Before the CPU overwrites a texture submitted asynchronously, call `buffer.waitUntilCompleted()`.
The [asynchronous publishing example](https://github.com/cansik/syphon-python/blob/main/examples/MetalServerAsyncExample.py) alternates between two
textures and waits only when reusing one, allowing image preparation and GPU work to overlap.

### OpenGL Server
Install `syphon-python[opengl]` to enable OpenGL support. Metal usage does not require this extra.

Expand Down Expand Up @@ -97,6 +119,11 @@ for server in servers:
print(f"{server.app_name} ({server.uuid})")
```

Reading `directory.servers` also processes Cocoa discovery events and can wait. Applications that
already process those events can use `directory.server_snapshot` to read the current list immediately.
For scripts that need to connect before starting their receive loop, `directory.wait_for_server(timeout=5)`
processes events until a server is found, returning its description or `None` on timeout.

It is also possible to listen for events when a server changes its status. However, it is important to update the NSRunLoop to receive messages. This can be done by repeatedly calling `directory.update_run_loop()`.

```python
Expand Down Expand Up @@ -203,6 +230,10 @@ texture = ... # MLTTexture object
data = copy_mtl_texture_to_bytes(texture) # returns bytes
```

For repeated reads, `copy_mtl_texture_to_buffer(texture, buffer)` fills a reusable `bytearray` or
`memoryview` instead of allocating an immutable copy. Pixel data follows the texture's channel order;
uploads do not convert colors.

### Numpy
If you are working with [Numpy](https://numpy.org/) arrays, the `syphon.utils.numpy` package contains helper methods for reading and writing numpy images to and from [MTLTexture](https://developer.apple.com/documentation/metal/mtltexture).

Expand Down Expand Up @@ -234,6 +265,17 @@ texture = ... # MLTTexture object
texture_data = copy_mtl_texture_to_image(texture) # returns numpy array
```

For video receivers, the same output array can be reused while the frame dimensions stay unchanged:

```python
image = np.empty((texture.height(), texture.width(), 4), dtype=np.uint8)
copy_mtl_texture_to_image(texture, out=image)
```

Allocate a new array if the sender changes dimensions. Reusing `image` replaces its previous pixels;
copy it when an earlier frame needs to be kept. On upload, contiguous `uint8` arrays can avoid an
extra copy, while strided images are packed automatically. An unchanged image only needs to be uploaded once.

## Python Binding
As described in the [Objective-C to Python](#objective-c-to-python) chapter, the syphon-python library is based on the [PyObjC](https://pyobjc.readthedocs.io/en/latest/) Python to Objective-C bridge. This means that there is no intermediate wrapper between Python and Objective-C, and it is possible to access and call Objective-C objects directly from Python. This can be useful if a method of the original Syphon framework has not yet been exposed by the wrapper.

Expand Down
17 changes: 15 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,12 +69,13 @@ with syphon.SyphonMetalServer("Demo") as server, syphon.SyphonServerDirectory()

try:
while True:
# copy the image onto the texture and publish it
# copy the current image onto the texture and publish it
copy_image_to_mtl_texture(texture_data, texture)
server.publish_frame_texture(texture)

# process discovery requests without opening a window
directory.update_run_loop()

time.sleep(1 / 60)
except KeyboardInterrupt:
pass
Expand Down Expand Up @@ -127,7 +128,7 @@ The wheel includes the Syphon framework for both Apple Silicon and Intel. The so
the framework sources, so it can also be built without cloning the repository:

```bash
python -m pip install ./dist/syphon_python-0.2.0.tar.gz
python -m pip install ./dist/syphon_python-0.3.0.tar.gz
```

If you change the native framework sources during development, rebuild the editable installation with:
Expand Down Expand Up @@ -177,6 +178,18 @@ uv run ruff format --check .
uv run ruff format .
```

### Benchmarks

From a development checkout, save a run before changing the library and compare it with a later run:

```bash
uv run --extra numpy python -m scripts.benchmark --output benchmark-results/before.json
uv run --extra numpy python -m scripts.benchmark --compare benchmark-results/before.json --output benchmark-results/after.json
```

Results stay local. The benchmark tool is available in the repository, but is not included in release packages.
Use `--help` for backend and image-size options.

### Generate Documentation

```bash
Expand Down
5 changes: 5 additions & 0 deletions conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

def pytest_addoption(parser):
parser.addoption("--dist-dir", help="Validate the wheel and source archive in this directory")
parser.addoption("--python-version", help="Require the intended Python major.minor version (for example 3.13t)")
parser.addoption(
"--python-variant", choices=("standard", "free-threaded"), help="Require the intended Python build variant"
)
Expand All @@ -23,6 +24,10 @@ def dist_dir(request):


def pytest_sessionstart(session):
expected_version = session.config.getoption("--python-version")
actual_version = f"{sys.version_info.major}.{sys.version_info.minor}"
if expected_version and expected_version.removesuffix("t") != actual_version:
pytest.exit(f"Expected Python {expected_version}, but selected Python {actual_version}", returncode=1)
expected = session.config.getoption("--python-variant")
actual = "free-threaded" if sysconfig.get_config_var("Py_GIL_DISABLED") else "standard"
if expected and expected != actual:
Expand Down
32 changes: 17 additions & 15 deletions examples/MetalClientExample.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,48 +3,50 @@
import time

import cv2
import numpy as np

import syphon
from syphon.utils.numpy import copy_mtl_texture_to_image


def wait_for_server(directory, timeout=5):
"""Allow discovery notifications time to arrive instead of taking one snapshot."""
deadline = time.monotonic() + timeout
while True:
servers = directory.servers
if servers:
return servers[0]
if time.monotonic() >= deadline:
return None
time.sleep(0.01)


def main():
try:
with syphon.SyphonServerDirectory() as directory:
directory.run_loop_interval = 0.001

# Wait for a server to announce itself before connecting.
print("Waiting up to five seconds for a Syphon server...")
server = wait_for_server(directory)
server = directory.wait_for_server(timeout=5)
if server is None:
print("No server found. Start a server and try again.")
return 1

print(f"Connected to {server.app_name}: {server.name}. Press Escape or Q to exit.")

with syphon.SyphonMetalClient(server) as client:
image = None

while client.is_valid:
directory.update_run_loop()

if client.has_new_frame:
# Retrieve the latest Metal texture.
texture = client.new_frame_image
if texture is not None:
# Convert the texture to a NumPy image for OpenCV.
image = copy_mtl_texture_to_image(texture)
# Reuse the image buffer until the sender changes dimensions.
shape = (texture.height(), texture.width(), 4)
if image is None or image.shape != shape:
image = np.empty(shape, dtype=np.uint8)

copy_mtl_texture_to_image(texture, out=image)
cv2.imshow("Image", image)

# Process UI events even when no new frame arrives.
if cv2.waitKey(1) & 0xFF in (27, ord("q")):
break

time.sleep(0.001)

return 0
finally:
cv2.destroyAllWindows()
Expand Down
Loading
Loading