diff --git a/.github/RELEASING.md b/.github/RELEASING.md index dbdb35b..d9222a2 100644 --- a/.github/RELEASING.md +++ b/.github/RELEASING.md @@ -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`, @@ -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. diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 7bbb571..96c1759 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -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 @@ -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 }} @@ -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 @@ -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 diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index bafdfeb..bdf17e8 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -1,6 +1,7 @@ name: Publish documentation on: + workflow_call: workflow_dispatch: push: tags: ['v*'] @@ -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 diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index c9f7e62..899b642 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -30,6 +30,8 @@ jobs: validate: needs: guard uses: ./.github/workflows/build.yml + with: + full: true pypi: if: inputs.publish_pypi @@ -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 diff --git a/.gitignore b/.gitignore index 1b382ac..238586a 100644 --- a/.gitignore +++ b/.gitignore @@ -161,3 +161,6 @@ cython_debug/ .DS_Store .ruff_cache/ docs/**/* + +# Local benchmark runs +/benchmark-results/ diff --git a/CITATION.cff b/CITATION.cff index 89d0261..755a670 100644 --- a/CITATION.cff +++ b/CITATION.cff @@ -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" diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index f3897e5..053cad6 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -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. @@ -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. @@ -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 @@ -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). @@ -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. diff --git a/README.md b/README.md index 3d4ca02..30e7c1d 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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: @@ -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 diff --git a/conftest.py b/conftest.py index 6f9ece9..f2bcb05 100644 --- a/conftest.py +++ b/conftest.py @@ -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" ) @@ -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: diff --git a/examples/MetalClientExample.py b/examples/MetalClientExample.py index 98f3127..d17f6c6 100644 --- a/examples/MetalClientExample.py +++ b/examples/MetalClientExample.py @@ -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() diff --git a/examples/MetalServerAsyncExample.py b/examples/MetalServerAsyncExample.py new file mode 100644 index 0000000..19e1762 --- /dev/null +++ b/examples/MetalServerAsyncExample.py @@ -0,0 +1,57 @@ +"""Overlap image preparation and Metal publishing; press Ctrl+C to stop.""" + +import time + +import syphon +from syphon.utils.raw import copy_bytes_to_mtl_texture, create_mtl_texture + + +def main(): + with syphon.SyphonMetalServer("Metal Async") as server, syphon.SyphonServerDirectory() as directory: + directory.run_loop_interval = 0.001 + + # Alternate textures so one can be uploaded while the GPU reads the other. + width, height = 640, 480 + textures = [create_mtl_texture(server.device, width, height) for _ in range(2)] + pending = [None, None] + slot = 0 + value = 0 + print("publishing asynchronously... (Ctrl+C to stop)") + + try: + while True: + started = time.monotonic() + + # Prepare the next image while previously submitted GPU work runs. + value = (value + 1) % 255 + pixels = bytes((value, 255 - value, 255, 255)) * (width * height) + + # Wait only before overwriting a texture that is still in use. + if pending[slot] is not None: + pending[slot].waitUntilCompleted() + pending[slot] = None + + copy_bytes_to_mtl_texture(pixels, textures[slot]) + + # Keep the command buffer so we can synchronize this texture's reuse. + buffer = server.command_queue.commandBuffer() + server.publish_frame_texture(textures[slot], command_buffer=buffer, auto_commit=False) + buffer.commit() + pending[slot] = buffer + slot = (slot + 1) % len(textures) + + directory.update_run_loop() + + time.sleep(max(0, 1 / 60 - (time.monotonic() - started))) + finally: + # Finish outstanding work before releasing textures and stopping the server. + for buffer in pending: + if buffer is not None: + buffer.waitUntilCompleted() + + +if __name__ == "__main__": + try: + main() + except KeyboardInterrupt: + pass diff --git a/examples/MetalServerExample.py b/examples/MetalServerExample.py index 98a92e0..de5545e 100644 --- a/examples/MetalServerExample.py +++ b/examples/MetalServerExample.py @@ -17,11 +17,13 @@ def main(): descriptor = Metal.MTLTextureDescriptor.texture2DDescriptorWithPixelFormat_width_height_mipmapped_( Metal.MTLPixelFormatRGBA8Unorm, width, height, False ) + # Create the texture on the server's Metal device. texture = server.device.newTextureWithDescriptor_(descriptor) region = Metal.MTLRegion((0, 0, 0), (width, height, 1)) value = 0 print("publishing... (Ctrl+C to stop)") + while True: started = time.monotonic() diff --git a/examples/MetalServerExampleMini.py b/examples/MetalServerExampleMini.py index 111f70d..4b601d1 100644 --- a/examples/MetalServerExampleMini.py +++ b/examples/MetalServerExampleMini.py @@ -13,19 +13,23 @@ def main(): with syphon.SyphonMetalServer("Demo") as server, syphon.SyphonServerDirectory() as directory: directory.run_loop_interval = 0.001 - # Create a Metal texture and an opaque red NumPy image. + # Create a Metal texture. texture = create_mtl_texture(server.device, 512, 512) + + # Create an opaque red NumPy image. data = np.zeros((512, 512, 4), dtype=np.uint8) data[:, :, 0] = 255 # red data[:, :, 3] = 255 # alpha + print("publishing... (Ctrl+C to stop)") 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(data, texture) server.publish_frame_texture(texture) # Process discovery requests even though there is no window. directory.update_run_loop() + time.sleep(1 / 60) diff --git a/examples/MetalServerVideoExample.py b/examples/MetalServerVideoExample.py index 6abbfad..74ddeae 100644 --- a/examples/MetalServerVideoExample.py +++ b/examples/MetalServerVideoExample.py @@ -1,4 +1,12 @@ +"""Loop a video; press Space to rename the server, or Escape or Q to exit.""" + +import math +import time +from pathlib import Path + import cv2 +import Metal +import numpy as np import syphon from syphon.utils.numpy import copy_image_to_mtl_texture @@ -6,38 +14,71 @@ def main(): - print("starting video server...") - server = syphon.SyphonMetalServer("Metal Video") + path = Path(__file__).resolve().parents[1] / "media/pexels-gamol-8879031.mp4" + video = cv2.VideoCapture(str(path)) + try: + if not video.isOpened(): + print(f"Could not open video: {path}") + return 1 + + # Read the video's dimensions and frame rate. + width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH)) + height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT)) + if width <= 0 or height <= 0: + print("Video has invalid frame dimensions") + return 1 + + fps = video.get(cv2.CAP_PROP_FPS) + fps = fps if math.isfinite(fps) and fps > 0 else 30 + + with syphon.SyphonMetalServer("Metal Video") as server, syphon.SyphonServerDirectory() as directory: + directory.run_loop_interval = 0.001 - # start video and read width and height - video = cv2.VideoCapture("media/pexels-gamol-8879031.mp4") - width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH)) - height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT)) + # Reuse the texture and converted image storage for each frame. + texture = create_mtl_texture(server.device, width, height, Metal.MTLPixelFormatBGRA8Unorm) + bgra_frame = np.empty((height, width, 4), dtype=np.uint8) + name_counter = 0 + print("publishing video... (Space to rename, Escape or Q to stop)") - # create metal texture - texture = create_mtl_texture(server.device, width, height) + while True: + started = time.monotonic() - running = True - while running: - success, frame = video.read() + # Read the next frame, restarting the video at the end. + success, frame = video.read() + if not success: + video.set(cv2.CAP_PROP_POS_FRAMES, 0) + success, frame = video.read() + if not success: + print("Could not read a frame after rewinding the video") + return 1 - if not success: - video.set(cv2.CAP_PROP_POS_FRAMES, 0) - continue + # Convert and upload the image, then publish the texture. + cv2.cvtColor(frame, cv2.COLOR_BGR2BGRA, dst=bgra_frame) + copy_image_to_mtl_texture(bgra_frame, texture) + server.publish_frame_texture(texture, is_flipped=True) - # copy data to texture - bgra_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA) - copy_image_to_mtl_texture(bgra_frame, texture) + directory.update_run_loop() + cv2.imshow("Frame", frame) - # publish texture - server.publish_frame_texture(texture, is_flipped=True) + # Rename the running server without disconnecting its clients. + key = cv2.waitKey(1) & 0xFF + if key == ord(" "): + name_counter += 1 + server.name = f"Metal Video {name_counter}" + print(f"Server renamed to {server.name}") + elif key in (27, ord("q")): + break - cv2.imshow("Frame", frame) - cv2.waitKey(1) + time.sleep(max(0, 1 / fps - (time.monotonic() - started))) - video.release() - server.stop() + return 0 + finally: + video.release() + cv2.destroyAllWindows() if __name__ == "__main__": - main() + try: + raise SystemExit(main()) + except KeyboardInterrupt: + pass diff --git a/examples/OpenGLClientExample.py b/examples/OpenGLClientExample.py index f248255..848a9d4 100644 --- a/examples/OpenGLClientExample.py +++ b/examples/OpenGLClientExample.py @@ -61,34 +61,39 @@ def render(texture: Any, width: int, height: int): def main(): window = init_glfw(640, 480) - - directory = syphon.SyphonServerDirectory() - # servers = directory.servers_matching_name(app_name="Simple Server") - servers = directory.servers - - if not servers: - print("No server found!") - exit(1) - - server = servers[0] - - client = syphon.SyphonOpenGLClient(server) - - while not glfw.window_should_close(window): - if client.has_new_frame: - legacy_surface_image = client.new_frame_image - size = legacy_surface_image.textureSize() - width, height = int(size.width), int(size.height) - texture = legacy_surface_image.textureName() - - render(texture, width, height) - - glfw.poll_events() - glfw.swap_buffers(window) - - client.stop() - glfw.terminate() + if window is None: + return 1 + + try: + with syphon.SyphonServerDirectory() as directory: + server = directory.wait_for_server(timeout=5) + if server is None: + print("No server found!") + return 1 + + with syphon.SyphonOpenGLClient(server) as client: + while not glfw.window_should_close(window) and client.is_valid: + if client.has_new_frame: + image = client.new_frame_image + if image is not None: + try: + size = image.textureSize() + render(image.textureName(), int(size.width), int(size.height)) + finally: + # Release while the OpenGL context is still current. + del image + + glfw.poll_events() + glfw.swap_buffers(window) + + return 0 + finally: + glfw.destroy_window(window) + glfw.terminate() if __name__ == "__main__": - main() + try: + raise SystemExit(main()) + except KeyboardInterrupt: + pass diff --git a/examples/OpenGLServerExample.py b/examples/OpenGLServerExample.py index ce85282..f11c0a0 100644 --- a/examples/OpenGLServerExample.py +++ b/examples/OpenGLServerExample.py @@ -1,4 +1,4 @@ -from itertools import cycle, islice +"""Publish a reusable OpenGL texture; close the window or press Ctrl+C to exit.""" import glfw from OpenGL.GL import ( @@ -15,12 +15,14 @@ glBindTexture, glClear, glClearColor, + glDeleteTextures, glEnable, glEnd, glGenTextures, glTexCoord2f, glTexImage2D, glTexParameteri, + glTexSubImage2D, glVertex2f, ) @@ -30,9 +32,9 @@ def render(texture: GLuint, data: bytes, width: int, height: int): glClear(GL_COLOR_BUFFER_BIT) - # Draw the numpy array image as a texture + # Update the texture allocated once at startup. glBindTexture(GL_TEXTURE_2D, texture) - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data) + glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, data) glBegin(GL_QUADS) glTexCoord2f(0, 0) @@ -52,49 +54,55 @@ def main(): texture_width, texture_height = 640, 480 if not glfw.init(): - return + return 1 window = glfw.create_window(texture_width, texture_height, "OpenGL Demo", None, None) if not window: glfw.terminate() - return + return 1 glfw.make_context_current(window) - # start server - server = syphon.SyphonOpenGLServer("OpenGL Test") - - # Enable vsync - glfw.swap_interval(1) - - # create texture - glEnable(GL_TEXTURE_2D) - texture = glGenTextures(1) - glBindTexture(GL_TEXTURE_2D, texture) - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) - glBindTexture(GL_TEXTURE_2D, 0) - - glClearColor(0, 0, 0, 1) - - value = 0 - print("publishing...") - while not glfw.window_should_close(window): - # generate random pixels - value = (value + 1) % 255 - pixels = bytes(islice(cycle([value, 255 - value, 255, 255]), texture_width * texture_height * 4)) - - glfw.poll_events() - render(texture, pixels, texture_width, texture_height) - - if server.has_clients: - server.publish_frame_texture(texture) - - glfw.swap_buffers(window) - - server.stop() - glfw.terminate() + texture = None + try: + with syphon.SyphonOpenGLServer("OpenGL Test") as server: + glfw.swap_interval(1) + glEnable(GL_TEXTURE_2D) + + # Allocate texture storage once and update its pixels for each frame. + texture = glGenTextures(1) + glBindTexture(GL_TEXTURE_2D, texture) + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texture_width, texture_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, None) + glBindTexture(GL_TEXTURE_2D, 0) + glClearColor(0, 0, 0, 1) + + value = 0 + print("publishing...") + + while not glfw.window_should_close(window): + value = (value + 1) % 255 + pixels = bytes((value, 255 - value, 255, 255)) * (texture_width * texture_height) + + glfw.poll_events() + render(texture, pixels, texture_width, texture_height) + + if server.has_clients: + server.publish_frame_texture(texture, size=(texture_width, texture_height)) + + glfw.swap_buffers(window) + + return 0 + finally: + if texture is not None: + glDeleteTextures([texture]) + glfw.destroy_window(window) + glfw.terminate() if __name__ == "__main__": - main() + try: + raise SystemExit(main()) + except KeyboardInterrupt: + pass diff --git a/pyproject.toml b/pyproject.toml index c115c62..5881596 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "syphon-python" -version = "0.2.0" +version = "0.3.0" description = "Python wrapper for the GPU texture sharing framework Syphon." readme = "README.md" requires-python = ">=3.10" @@ -71,6 +71,7 @@ include = [ ] exclude = [ "/vendor/Syphon/.git", "/vendor/Syphon/build", "/syphon/libs/*.framework", + "/scripts/benchmark.py", "/tests/test_benchmark.py", "/benchmark-results", ] [tool.pytest.ini_options] diff --git a/scripts/benchmark.py b/scripts/benchmark.py new file mode 100644 index 0000000..37e64e6 --- /dev/null +++ b/scripts/benchmark.py @@ -0,0 +1,328 @@ +"""Measure the installed library; save and compare runs from different revisions. + +Run from a development checkout with the NumPy extra. Results are local development +artifacts, not timing assertions. Host measurements isolate Python buffer handling; +Metal measurements include real texture transfers. No historical implementations are +embedded, so this script can also run against an earlier installation of the library. +""" + +import argparse +import gc +import inspect +import json +import math +import platform +import statistics +import time +import tracemalloc +from importlib.metadata import version +from pathlib import Path + +import Metal +import numpy as np +import objc + +import syphon +from syphon.utils import numpy as image_utils, raw + + +class HostTexture: + """CPU storage implementing the texture transfer interface, without a GPU.""" + + def __init__(self, width: int, height: int): + self._width, self._height = width, height + self.pixels = bytearray(width * height * 4) + + def width(self) -> int: + return self._width + + def height(self) -> int: + return self._height + + def pixelFormat(self) -> int: + return Metal.MTLPixelFormatRGBA8Unorm + + def replaceRegion_mipmapLevel_withBytes_bytesPerRow_(self, region, level, data, row): + memoryview(self.pixels)[:] = memoryview(data).cast("B")[: len(self.pixels)] + + def getBytes_bytesPerRow_bytesPerImage_fromRegion_mipmapLevel_slice_(self, buffer, *args): + memoryview(buffer).cast("B")[:] = self.pixels + + +def measure(name, operation, *, iterations, repeats, finish=None) -> dict: + def batch(count): + with objc.autorelease_pool(): + started = time.perf_counter_ns() + for _ in range(count): + operation() + elapsed = (time.perf_counter_ns() - started) / count / 1_000_000 + if finish is not None: + finish() # GPU completion is outside CPU submission timing. + return elapsed + + batch(min(3, iterations)) + samples = [batch(iterations) for _ in range(repeats)] + gc.collect() + with objc.autorelease_pool(): + tracemalloc.start() + try: + result = operation() + peak = tracemalloc.get_traced_memory()[1] + finally: + tracemalloc.stop() + if finish is not None: + finish() + del result + return { + "name": name, + "iterations": iterations, + "repeats": repeats, + "ms": statistics.median(samples), + "peak_mib": peak / (1024 * 1024), + "samples_ms": samples, + } + + +def transfer_cases(label, texture, image, settings, skipped) -> list[dict]: + image_utils.copy_image_to_mtl_texture(image, texture) + np.testing.assert_array_equal(image_utils.copy_mtl_texture_to_image(texture), image) + rows = [ + measure(f"{label}/upload", lambda: image_utils.copy_image_to_mtl_texture(image, texture), **settings), + measure(f"{label}/download", lambda: image_utils.copy_mtl_texture_to_image(texture), **settings), + ] + if "out" in inspect.signature(image_utils.copy_mtl_texture_to_image).parameters: + out = np.empty_like(image) + assert image_utils.copy_mtl_texture_to_image(texture, out=out) is out + np.testing.assert_array_equal(out, image) + rows.append( + measure( + f"{label}/download-reuse", lambda: image_utils.copy_mtl_texture_to_image(texture, out=out), **settings + ) + ) + else: + skipped.append(f"{label}/download-reuse: installed library has no out parameter") + return rows + + +def metal_cases(device, image, settings, skipped) -> list[dict]: + height, width, _ = image.shape + texture = raw.create_mtl_texture(device, width, height) + if texture is None: + raise RuntimeError("Could not allocate the benchmark texture") + rows = transfer_cases("metal", texture, image, settings, skipped) + with syphon.SyphonMetalServer("Transfer benchmark", device=device, is_private=True) as server: + pending = [] + + def publish(*, manual_submit=False, complete=False): + buffer = server.command_queue.commandBuffer() + server.publish_frame_texture(texture, command_buffer=buffer, auto_commit=not manual_submit) + if manual_submit: + buffer.commit() + if complete: + buffer.waitUntilCompleted() + if buffer.error() is not None: + raise RuntimeError(str(buffer.error())) + else: + pending.append(buffer) + + def finish(): + for buffer in pending: + buffer.waitUntilCompleted() + if buffer.error() is not None: + raise RuntimeError(str(buffer.error())) + pending.clear() + + publish(complete=True) + output = server.new_frame_image + if output.storageMode() == Metal.MTLStorageModeManaged: + buffer = server.command_queue.commandBuffer() + encoder = buffer.blitCommandEncoder() + encoder.synchronizeResource_(output) + encoder.endEncoding() + buffer.commit() + buffer.waitUntilCompleted() + expected = image[:, :, [2, 1, 0, 3]].tobytes() + assert raw.copy_mtl_texture_to_bytes(output) == expected + rows.append(measure("metal/publish-complete", lambda: publish(complete=True), **settings)) + rows.append( + measure("metal/publish-async-submission", lambda: publish(manual_submit=True), finish=finish, **settings) + ) + return rows + + +def opengl_cases(width, height, settings, skipped) -> list[dict]: + try: + import AppKit + from OpenGL import GL + except ImportError: + skipped.append("opengl: requires the opengl extra") + return [] + pixel_format = AppKit.NSOpenGLPixelFormat.alloc().initWithAttributes_( + [AppKit.NSOpenGLPFAOpenGLProfile, AppKit.NSOpenGLProfileVersion3_2Core, AppKit.NSOpenGLPFAColorSize, 24, 0] + ) + context = ( + None + if pixel_format is None + else AppKit.NSOpenGLContext.alloc().initWithFormat_shareContext_(pixel_format, None) + ) + if context is None: + skipped.append("opengl: no usable context") + return [] + previous = AppKit.NSOpenGLContext.currentContext() + context.makeCurrentContext() + texture = GL.glGenTextures(1) + try: + pixels = np.empty((height, width, 4), dtype=np.uint8) + pixels[:] = (17, 53, 199, 255) + GL.glBindTexture(GL.GL_TEXTURE_2D, texture) + GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA8, width, height, 0, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, pixels) + GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST) + GL.glFinish() + with syphon.SyphonOpenGLServer("OpenGL benchmark", is_private=True) as server: + return [ + measure( + "opengl/publish-queried-size", + lambda: server.publish_frame_texture(texture), + finish=GL.glFinish, + **settings, + ), + measure( + "opengl/publish-known-size", + lambda: server.publish_frame_texture(texture, size=(width, height)), + finish=GL.glFinish, + **settings, + ), + ] + finally: + GL.glDeleteTextures([texture]) + if previous is None: + AppKit.NSOpenGLContext.clearCurrentContext() + else: + previous.makeCurrentContext() + + +def discovery_cases(skipped) -> list[dict]: + with syphon.SyphonServerDirectory() as directory: + rows = [measure("discovery/servers", lambda: directory.servers, iterations=2, repeats=3)] + if hasattr(type(directory), "server_snapshot"): + rows.append(measure("discovery/snapshot", lambda: directory.server_snapshot, iterations=30, repeats=7)) + else: + skipped.append("discovery/snapshot: installed library has no server_snapshot") + return rows + + +def positive_int(value: str) -> int: + result = int(value) + if result <= 0: + raise argparse.ArgumentTypeError("expected a positive integer") + return result + + +def compare_reports(current: dict, previous: dict) -> tuple[list[dict], list[str]]: + if previous["schema_version"] != 1: + raise ValueError("Unsupported benchmark report schema") + if (current["width"], current["height"]) != (previous["width"], previous["height"]): + raise ValueError("Cannot compare runs with different image dimensions") + if not isinstance(previous["environment"], dict) or not isinstance(previous["results"], list): + raise ValueError("Invalid benchmark report") + baseline = {row["name"]: row for row in previous["results"]} + if len(baseline) != len(previous["results"]): + raise ValueError("Duplicate benchmark case names") + for row in baseline.values(): + if not isinstance(row["ms"], (int, float)) or not math.isfinite(row["ms"]) or row["ms"] <= 0: + raise ValueError("Previous timings must be finite positive numbers") + if not isinstance(row["peak_mib"], (int, float)) or not math.isfinite(row["peak_mib"]) or row["peak_mib"] < 0: + raise ValueError("Previous allocation peaks must be finite nonnegative numbers") + warnings = [ + f"Environment differs: {key} ({previous['environment'].get(key)!r} -> {value!r})" + for key, value in current["environment"].items() + if previous["environment"].get(key) != value + ] + comparisons = [] + for row in current["results"]: + before = baseline.get(row["name"]) + comparisons.append( + { + "name": row["name"], + "previous_ms": None if before is None else before["ms"], + "current_ms": row["ms"], + "previous_peak_mib": None if before is None else before["peak_mib"], + "current_peak_mib": row["peak_mib"], + "speedup": None if before is None else before["ms"] / row["ms"], + } + ) + return comparisons, warnings + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--width", type=positive_int, default=3840) + parser.add_argument("--height", type=positive_int, default=2160) + parser.add_argument("--iterations", type=positive_int, default=30) + parser.add_argument("--repeats", type=positive_int, default=7) + parser.add_argument("--backend", choices=("host", "metal", "all"), default="all") + parser.add_argument("--opengl", action="store_true") + parser.add_argument("--discovery", action="store_true", help="Include the default discovery wait (several seconds)") + parser.add_argument("--output", type=Path) + parser.add_argument("--compare", type=Path, help="Compare with a locally saved run") + args = parser.parse_args(argv) + previous = None + if args.compare is not None: + try: + previous = json.loads(args.compare.read_text()) + compare_reports({"width": args.width, "height": args.height, "environment": {}, "results": []}, previous) + except (OSError, ValueError, KeyError, TypeError) as error: + parser.error(str(error)) + image = np.arange(args.width * args.height * 4, dtype=np.uint8).reshape(args.height, args.width, 4) + settings = {"iterations": args.iterations, "repeats": args.repeats} + rows, skipped = [], [] + device = None + with objc.autorelease_pool(): + if args.backend in ("host", "all"): + rows.extend(transfer_cases("host", HostTexture(args.width, args.height), image, settings, skipped)) + if args.backend in ("metal", "all"): + device = Metal.MTLCreateSystemDefaultDevice() + if device is None: + skipped.append("metal: no device available") + else: + rows.extend(metal_cases(device, image, settings, skipped)) + if args.opengl: + rows.extend(opengl_cases(args.width, args.height, settings, skipped)) + if args.discovery: + rows.extend(discovery_cases(skipped)) + report = { + "schema_version": 1, + "library_version": version("syphon-python"), + "environment": { + "macos": platform.mac_ver()[0], + "architecture": platform.machine(), + "python": platform.python_version(), + "numpy": np.__version__, + "device": None if device is None else str(device.name()), + }, + "width": args.width, + "height": args.height, + "results": rows, + "skipped": skipped, + } + print(f"{'Operation':38} {'ms':>10} {'peak MiB':>10}") + for row in rows: + print(f"{row['name']:38} {row['ms']:10.3f} {row['peak_mib']:10.3f}") + for reason in skipped: + print(f"Skipped: {reason}") + if previous is not None: + comparisons, warnings = compare_reports(report, previous) + report["comparison"], report["comparison_warnings"] = comparisons, warnings + print("\nCompared with saved run:") + for row in comparisons: + print(f"{row['name']}: " + ("new case" if row["speedup"] is None else f"{row['speedup']:.2f}x")) + for warning in warnings: + print(f"Warning: {warning}") + if args.output is not None: + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n") + return 1 if args.backend == "metal" and device is None else 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/ci_test.sh b/scripts/ci_test.sh index 393519a..e64a034 100644 --- a/scripts/ci_test.sh +++ b/scripts/ci_test.sh @@ -4,32 +4,39 @@ set -euo pipefail : "${TEST_PYTHON:?Set TEST_PYTHON to the interpreter executable}" : "${TEST_VARIANT:?Set TEST_VARIANT to standard or free-threaded}" +: "${TEST_PYTHON_VERSION:?Set TEST_PYTHON_VERSION to the expected Python version}" repo_dir="$(cd "$(dirname "$0")/.." && pwd)" test_dir="$(mktemp -d "${TMPDIR:-/tmp}/syphon-ci.XXXXXX")" trap 'rm -rf "$test_dir"' EXIT cd "$repo_dir" -uv export --locked --only-group test --format requirements-txt --output-file "$test_dir/requirements.txt" +uv export --python "$TEST_PYTHON" --locked --only-group test --format requirements-txt --output-file "$test_dir/requirements.txt" > /dev/null wheel_files=("$repo_dir"/dist/*.whl) source_files=("$repo_dir"/dist/*.tar.gz) test "${#wheel_files[@]}" -eq 1 && test -f "${wheel_files[0]}" test "${#source_files[@]}" -eq 1 && test -f "${source_files[0]}" uv venv --python "$TEST_PYTHON" "$test_dir/wheel-env" test_python="$test_dir/wheel-env/bin/python" +"$test_python" -c 'import platform, sys; print("Test interpreter:", sys.executable, sys.version, platform.machine())' uv pip install --python "$test_python" --only-binary :all: -r "$test_dir/requirements.txt" "${wheel_files[0]}" # Avoid importing syphon from the working tree, including in subprocess tests. unset PYTHONPATH cd "$test_dir" "$test_python" -c 'import importlib.util, syphon; assert "site-packages" in syphon.__file__; assert importlib.util.find_spec("OpenGL") is None; assert importlib.util.find_spec("numpy") is None' -"$test_python" -m pytest "$repo_dir/tests" --import-mode=importlib --python-variant "$TEST_VARIANT" -ra +pytest_args=(--import-mode=importlib --python-variant "$TEST_VARIANT" --python-version "$TEST_PYTHON_VERSION" -ra) +"$test_python" -m pytest "$repo_dir/tests" "${pytest_args[@]}" -m 'not metal and not opengl' uv pip install --python "$test_python" --only-binary :all: "${wheel_files[0]}[numpy,opengl]" -"$test_python" -m pytest "$repo_dir/tests" --import-mode=importlib --python-variant "$TEST_VARIANT" -ra +if [[ "${TEST_NATIVE:-true}" == true ]]; then + "$test_python" -m pytest "$repo_dir/tests" "${pytest_args[@]}" +else + "$test_python" -m pytest "$repo_dir/tests" "${pytest_args[@]}" -m 'not metal and not opengl' +fi if [[ "${TEST_SOURCE:-false}" == true ]]; then uv venv --python "$TEST_PYTHON" "$test_dir/source-env" source_python="$test_dir/source-env/bin/python" uv pip install --no-cache --python "$source_python" -r "$test_dir/requirements.txt" "${source_files[0]}[numpy,opengl]" "$source_python" -c 'import syphon; assert "site-packages" in syphon.__file__' - "$source_python" -m pytest "$repo_dir/tests" --import-mode=importlib --python-variant "$TEST_VARIANT" -ra + "$source_python" -m pytest "$repo_dir/tests" "${pytest_args[@]}" -m 'not metal and not opengl' fi diff --git a/syphon/server.py b/syphon/server.py index 7e8a345..e24b897 100644 --- a/syphon/server.py +++ b/syphon/server.py @@ -205,7 +205,7 @@ def publish_frame_texture( is_flipped: bool = False, command_buffer: Optional[Any] = None, auto_commit: bool = True, - ): + ) -> None: """ Publish a frame with the given Metal texture. @@ -215,7 +215,12 @@ def publish_frame_texture( - 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. + - auto_commit (bool, optional): If True, commit the buffer and wait for GPU completion. Defaults to True. + + By default, publishing waits for GPU completion so the CPU can safely reuse + the texture after this method returns. With auto_commit=False, pass a + command_buffer and commit it yourself. Call waitUntilCompleted() before + overwriting its texture from the CPU. """ # create ns-region region, _ = self._prepare_region_and_size(texture, region, size) @@ -224,6 +229,8 @@ def publish_frame_texture( # prepare command buffer if necessary if command_buffer is None: command_buffer = self.command_queue.commandBuffer() + if command_buffer is None: + raise RuntimeError("Could not create a Metal command buffer") # publish actual texture self.context.publishFrameTexture_onCommandBuffer_imageRegion_flipped_( @@ -231,7 +238,8 @@ def publish_frame_texture( ) # commit command buffer if auto_commit: - command_buffer.commitAndWaitUntilSubmitted() + command_buffer.commit() + command_buffer.waitUntilCompleted() def publish(self): """ @@ -373,6 +381,8 @@ def publish_frame_texture( - target (int, optional): The OpenGL texture target. Defaults to GL_TEXTURE_2D. """ # create ns-region + if size is None and target != opengl.GL_TEXTURE_2D: + size = self._get_texture_size(texture, target=target) region, size = self._prepare_region_and_size(texture, region, size) ns_region = Cocoa.NSRect((region[0], region[1]), (region[2], region[3])) ns_size = Cocoa.NSSize(size[0], size[1]) @@ -397,7 +407,7 @@ def has_clients(self) -> bool: """ return self.context.hasClients() - def _get_texture_size(self, texture: Texture) -> Size: + def _get_texture_size(self, texture: Texture, target: int = opengl.GL_TEXTURE_2D) -> Size: """ Get the size of the OpenGL texture. @@ -408,14 +418,17 @@ def _get_texture_size(self, texture: Texture) -> Size: - Size: The size of the texture. """ gl = opengl._require_pyopengl() - gl.glBindTexture(gl.GL_TEXTURE_2D, texture) - - width = gl.GLint() - height = gl.GLint() - - gl.glGetTexLevelParameteriv(gl.GL_TEXTURE_2D, 0, gl.GL_TEXTURE_WIDTH, width) - gl.glGetTexLevelParameteriv(gl.GL_TEXTURE_2D, 0, gl.GL_TEXTURE_HEIGHT, height) - - gl.glBindTexture(gl.GL_TEXTURE_2D, 0) - - return int(width.value), int(height.value) + bindings = { + gl.GL_TEXTURE_2D: gl.GL_TEXTURE_BINDING_2D, + gl.GL_TEXTURE_RECTANGLE: gl.GL_TEXTURE_BINDING_RECTANGLE, + } + if target not in bindings: + raise ValueError("Texture target must be GL_TEXTURE_2D or GL_TEXTURE_RECTANGLE") + previous = int(gl.glGetIntegerv(bindings[target])) + try: + gl.glBindTexture(target, texture) + width = int(gl.glGetTexLevelParameteriv(target, 0, gl.GL_TEXTURE_WIDTH)) + height = int(gl.glGetTexLevelParameteriv(target, 0, gl.GL_TEXTURE_HEIGHT)) + return width, height + finally: + gl.glBindTexture(target, previous) diff --git a/syphon/server_directory.py b/syphon/server_directory.py index 423c55d..37ea461 100644 --- a/syphon/server_directory.py +++ b/syphon/server_directory.py @@ -1,4 +1,6 @@ +import math import threading +import time from dataclasses import dataclass from enum import Enum from typing import Any, Callable, List, Optional @@ -130,19 +132,53 @@ def servers(self) -> List[SyphonServerDescription]: - List[SyphonServerDescription]: A list of SyphonServerDescription objects. """ self.update_run_loop() + return self.server_snapshot + + @property + def server_snapshot(self) -> List[SyphonServerDescription]: + """Read the current server list without waiting or processing Cocoa events.""" directory = self._syphonServerDirectoryObjC.sharedDirectory() servers = directory.servers() return [SyphonServerDescription.from_native(raw) for raw in servers] - def update_run_loop(self): + def update_run_loop(self, timeout: Optional[float] = None) -> None: """ Update the run loop to process events. + + timeout overrides run_loop_interval for this call without changing its default. """ + timeout = self.run_loop_interval if timeout is None else timeout + if not math.isfinite(timeout) or timeout < 0: + raise ValueError("Run-loop timeout must be a finite nonnegative number") NSRunLoop.currentRunLoop().runMode_beforeDate_( - NSDefaultRunLoopMode, NSDate.dateWithTimeIntervalSinceNow_(self.run_loop_interval) + NSDefaultRunLoopMode, NSDate.dateWithTimeIntervalSinceNow_(timeout) ) + def wait_for_server( + self, timeout: float = 5.0, *, name: Optional[str] = None, app_name: Optional[str] = None + ) -> Optional[SyphonServerDescription]: + """Process main-thread Cocoa events until a matching server appears or timeout. + + Return the first match, or None. Filters match either name or app_name, like + servers_matching_name(); omitting both filters accepts any server. + """ + if not math.isfinite(timeout) or timeout < 0: + raise ValueError("timeout must be a finite nonnegative number") + deadline = time.monotonic() + timeout + while True: + for server in self.server_snapshot: + if ( + (name is None and app_name is None) + or (name is not None and name == server.name) + or (app_name is not None and app_name == server.app_name) + ): + return server + remaining = deadline - time.monotonic() + if remaining <= 0: + return None + self.update_run_loop(timeout=min(0.05, remaining)) + def servers_matching_name( self, name: Optional[str] = None, app_name: Optional[str] = None ) -> List[SyphonServerDescription]: diff --git a/syphon/utils/numpy.py b/syphon/utils/numpy.py index b1e8a60..a30ccf1 100644 --- a/syphon/utils/numpy.py +++ b/syphon/utils/numpy.py @@ -1,11 +1,12 @@ from typing import Any import numpy as np +from numpy.typing import NDArray -from syphon.utils.raw import copy_bytes_to_mtl_texture, copy_mtl_texture_to_bytes +from syphon.utils.raw import copy_bytes_to_mtl_texture, copy_mtl_texture_to_buffer -def copy_image_to_mtl_texture(image: np.ndarray, texture: Any): +def copy_image_to_mtl_texture(image: np.ndarray, texture: Any) -> None: """ Copy pixel data from a NumPy array representing an image to a Metal texture. @@ -19,24 +20,27 @@ def copy_image_to_mtl_texture(image: np.ndarray, texture: Any): assert len(image.shape) == 3, "Image has to be of shape (m, n, 4)" assert image.shape[2] == 4, "Image has to be of shape (m, n, 4)" - data = image.tobytes() + # Preserve subclass serialization (e.g. masked arrays) and uncommon dtypes. + borrow = type(image) is np.ndarray and image.dtype == np.uint8 and image.flags.c_contiguous + data = memoryview(image) if borrow else image.tobytes() copy_bytes_to_mtl_texture(data, texture) -def copy_mtl_texture_to_image(texture: Any) -> np.ndarray: +def copy_mtl_texture_to_image(texture: Any, out: NDArray[np.uint8] | None = None) -> NDArray[np.uint8]: """ Copy pixel data from a Metal texture to a NumPy array representing an image. Parameters: - texture (Any): The source Metal texture to copy pixel data from. + - out (NDArray[np.uint8], optional): Reusable writable C-contiguous array matching the texture dimensions. Returns: - - np.ndarray: The resulting image as a NumPy array of shape (height, width, 4). - - Note: - - todo: Add support for buffer re-use. + - NDArray[np.uint8]: The supplied out array, or a newly allocated writable image of shape (height, width, 4). """ - # todo: support buffer re-use - data = copy_mtl_texture_to_bytes(texture) - image = np.frombuffer(data, dtype=np.uint8) - return image.reshape((texture.height(), texture.width(), 4)) + shape = (texture.height(), texture.width(), 4) + if out is None: + out = np.empty(shape, dtype=np.uint8) + elif out.dtype != np.uint8 or out.shape != shape: + raise ValueError("Output must have dtype uint8 and shape (texture.height(), texture.width(), 4)") + copy_mtl_texture_to_buffer(texture, memoryview(out)) + return out diff --git a/syphon/utils/raw.py b/syphon/utils/raw.py index d2a17bf..455b9a1 100644 --- a/syphon/utils/raw.py +++ b/syphon/utils/raw.py @@ -1,8 +1,25 @@ -import ctypes -from typing import Any, Optional +from typing import Any, Optional, TypeVar import Metal +_WritableBuffer = TypeVar("_WritableBuffer", bytearray, memoryview) + + +def _byte_view(buffer: Any, *, writable: bool = False) -> memoryview: + view = memoryview(buffer) + if not view.c_contiguous: + raise ValueError("Buffer must be C-contiguous") + if writable and view.readonly: + raise ValueError("Output buffer must be writable") + return view.cast("B") + + +def _read_layout(texture: Any) -> tuple[int, int, int, int]: + if texture.pixelFormat() not in (Metal.MTLPixelFormatBGRA8Unorm, Metal.MTLPixelFormatRGBA8Unorm): + raise Exception("Not correct pixel format (expected MTLPixelFormatBGRA8Unorm or MTLPixelFormatRGBA8Unorm)") + width, height = texture.width(), texture.height() + return width, height, width * 4, width * height * 4 + def create_mtl_texture(device: Any, width: int, height: int, pixel_format: int = Metal.MTLPixelFormatRGBA8Unorm) -> Any: """ @@ -24,61 +41,67 @@ def create_mtl_texture(device: Any, width: int, height: int, pixel_format: int = return device.newTextureWithDescriptor_(texture_descriptor) -def copy_bytes_to_mtl_texture(data: bytes, texture: Any): +def copy_bytes_to_mtl_texture(data: bytes | bytearray | memoryview, texture: Any) -> None: """ - Copy pixel data from a bytes object to a Metal texture. + Copy packed four-byte pixels from a contiguous buffer to a Metal texture. Parameters: - - data (bytes): The pixel data as bytes. + - data (bytes | bytearray | memoryview): Contiguous pixel data; channel order follows the texture format. - texture (Any): The target Metal texture to copy the pixel data into. """ - region = Metal.MTLRegion((0, 0, 0), (texture.width(), texture.height(), 1)) - bytes_per_row = texture.width() * 4 + width, height = texture.width(), texture.height() + view = _byte_view(data) + expected = width * height * 4 + if view.nbytes < expected: + raise ValueError(f"Buffer is too small (expected at least: {expected}, actual: {view.nbytes})") + region = Metal.MTLRegionMake2D(0, 0, width, height) + bytes_per_row = width * 4 texture.replaceRegion_mipmapLevel_withBytes_bytesPerRow_( region, 0, # mipmapLevel - data, + view, bytes_per_row, ) +def copy_mtl_texture_to_buffer(texture: Any, buffer: _WritableBuffer) -> _WritableBuffer: + """Read RGBA8/BGRA8 pixels into a writable contiguous buffer and return it. + + Supply exactly width * height * 4 bytes. Finish GPU writes before reading; + this helper does not synchronize the GPU or convert channel order. + """ + width, height, row, size = _read_layout(texture) + view = _byte_view(buffer, writable=True) + if view.nbytes != size: + raise ValueError(f"Incorrect buffer size (expected: {size}, actual: {view.nbytes})") + texture.getBytes_bytesPerRow_bytesPerImage_fromRegion_mipmapLevel_slice_( + view, row, size, Metal.MTLRegionMake2D(0, 0, width, height), 0, 0 + ) + return buffer + + def copy_mtl_texture_to_bytes(texture: Any, buffer: Optional[Any] = None) -> bytes: """ Copy pixel data from a Metal texture to a bytes object. Parameters: - texture (Any): The source Metal texture to copy pixel data from. - - buffer (Optional[Any]): The buffer to store the result. If None, a new buffer will be created. + - buffer (Optional[Any]): Writable staging buffer. If None, a new buffer is created. Returns: - - bytes: The resulting pixel data as bytes. + - bytes: An independent immutable copy. Use copy_mtl_texture_to_buffer() to reuse storage without this copy. Raises: - Exception: If the pixel format of the texture is not MTLPixelFormatBGRA8Unorm or MTLPixelFormatRGBA8Unorm. - Exception: If the provided buffer is not big enough. """ - if ( - texture.pixelFormat() != Metal.MTLPixelFormatBGRA8Unorm - and texture.pixelFormat() != Metal.MTLPixelFormatRGBA8Unorm - ): - raise Exception("Not correct pixel format (expected MTLPixelFormatBGRA8Unorm or MTLPixelFormatRGBA8Unorm)") - - bytes_per_row = texture.width() * 4 - bytes_per_image = bytes_per_row * texture.height() - mipmap_level = 0 - slice_number = 0 - region = Metal.MTLRegionMake2D(0, 0, texture.width(), texture.height()) - + _, _, _, bytes_per_image = _read_layout(texture) if buffer is None: - buffer = ctypes.create_string_buffer(bytes_per_image) + buffer = bytearray(bytes_per_image) if len(buffer) != bytes_per_image: raise Exception(f"Buffer is not big enough (expected: {bytes_per_image}, actual: {len(buffer)})") - texture.getBytes_bytesPerRow_bytesPerImage_fromRegion_mipmapLevel_slice_( - buffer, bytes_per_row, bytes_per_image, region, mipmap_level, slice_number - ) - - raw_bytes = bytes(buffer.raw) - return raw_bytes + copy_mtl_texture_to_buffer(texture, memoryview(buffer)) + return bytes(_byte_view(buffer)) diff --git a/tests/test_benchmark.py b/tests/test_benchmark.py new file mode 100644 index 0000000..5729feb --- /dev/null +++ b/tests/test_benchmark.py @@ -0,0 +1,131 @@ +"""Check the repository benchmark tool without imposing timing thresholds.""" + +import importlib.util +import json +import math +import subprocess +import sys +from pathlib import Path + +import pytest + +pytest.importorskip("numpy") +SCRIPT = Path(__file__).resolve().parents[1] / "scripts/benchmark.py" +spec = importlib.util.spec_from_file_location("frame_benchmark", SCRIPT) +benchmark = importlib.util.module_from_spec(spec) +spec.loader.exec_module(benchmark) + + +def run_benchmark(tmp_path, *arguments): + return subprocess.run( + [ + sys.executable, + str(SCRIPT), + "--backend", + "host", + "--width", + "8", + "--height", + "4", + "--iterations", + "2", + "--repeats", + "2", + *arguments, + ], + cwd=tmp_path, + capture_output=True, + text=True, + timeout=15, + ) + + +def test_saved_host_run_and_comparison(tmp_path): + before, after = tmp_path / "runs/before.json", tmp_path / "runs/after.json" + result = run_benchmark(tmp_path, "--output", str(before)) + assert result.returncode == 0, result.stderr + baseline = json.loads(before.read_text()) + assert baseline["environment"]["device"] is None + assert (baseline["width"], baseline["height"]) == (8, 4) + assert {row["name"] for row in baseline["results"]} == {"host/upload", "host/download", "host/download-reuse"} + for row in baseline["results"]: + assert math.isfinite(row["ms"]) and row["ms"] > 0 + assert row["peak_mib"] >= 0 + assert len(row["samples_ms"]) == 2 + result = run_benchmark(tmp_path, "--compare", str(before), "--output", str(after)) + assert result.returncode == 0, result.stderr + report = json.loads(after.read_text()) + assert report["comparison_warnings"] == [] + assert len(report["comparison"]) == 3 + assert all(math.isfinite(row["speedup"]) and row["speedup"] > 0 for row in report["comparison"]) + + +@pytest.mark.metal +def test_metal_run_separates_async_submission_from_completion(tmp_path): + import Metal + + if Metal.MTLCreateSystemDefaultDevice() is None: + pytest.skip("A Metal device is required") + path = tmp_path / "metal.json" + result = run_benchmark(tmp_path, "--backend", "metal", "--output", str(path)) + assert result.returncode == 0, result.stderr + rows = {row["name"] for row in json.loads(path.read_text())["results"]} + assert "metal/publish-complete" in rows + assert "metal/publish-async-submission" in rows + assert "metal/publish-submission" not in rows + + +def report(rows, *, device="Example GPU"): + return {"schema_version": 1, "width": 8, "height": 4, "environment": {"device": device}, "results": rows} + + +def test_comparison_matches_names_and_marks_new_cases(): + previous = report([{"name": "download", "ms": 2, "peak_mib": 8}]) + current = report([{"name": "new", "ms": 1, "peak_mib": 0}, {"name": "download", "ms": 1, "peak_mib": 4}]) + comparisons, warnings = benchmark.compare_reports(current, previous) + assert warnings == [] + assert comparisons[0]["previous_ms"] is None + assert comparisons[0]["speedup"] is None + assert comparisons[1]["speedup"] == 2 + assert comparisons[1]["previous_peak_mib"] == 8 + + +def test_environment_differences_are_flagged(): + _, warnings = benchmark.compare_reports(report([], device="Other GPU"), report([])) + assert len(warnings) == 1 and "Environment differs: device" in warnings[0] + + +@pytest.mark.parametrize("field,value", [("ms", 0), ("ms", -1), ("peak_mib", -1), ("peak_mib", None)]) +def test_invalid_measurements_fail_cleanly(tmp_path, field, value): + row = {"name": "host/upload", "ms": 1, "peak_mib": 0} + row[field] = value + path = tmp_path / "previous.json" + path.write_text(json.dumps(report([row]))) + result = run_benchmark(tmp_path, "--compare", str(path)) + assert result.returncode == 2 + assert "Traceback" not in result.stderr + + +def test_different_dimensions_fail_before_measurement(tmp_path): + previous = report([]) + previous["width"] = 16 + path = tmp_path / "previous.json" + path.write_text(json.dumps(previous)) + result = run_benchmark(tmp_path, "--compare", str(path)) + assert result.returncode == 2 + assert "different image dimensions" in result.stderr + + +@pytest.mark.parametrize("contents", ["not json", "{}", '{"schema_version": 2}']) +def test_invalid_reports_fail_cleanly(tmp_path, contents): + path = tmp_path / "previous.json" + path.write_text(contents) + result = run_benchmark(tmp_path, "--compare", str(path)) + assert result.returncode == 2 + assert "Traceback" not in result.stderr + + +def test_empty_images_are_rejected(tmp_path): + result = run_benchmark(tmp_path, "--width", "0") + assert result.returncode == 2 + assert "positive integer" in result.stderr diff --git a/tests/test_ci_runners.py b/tests/test_ci_runners.py new file mode 100644 index 0000000..1721433 --- /dev/null +++ b/tests/test_ci_runners.py @@ -0,0 +1,19 @@ +"""CI must reject a test interpreter that does not match its matrix entry.""" + +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] + + +def test_wrong_python_version_fails_before_collection(): + result = subprocess.run( + [sys.executable, "-m", "pytest", str(ROOT / "tests/test_runtime.py"), "--python-version", "0.0"], + cwd=ROOT, + capture_output=True, + text=True, + timeout=15, + ) + assert result.returncode == 1 + assert "Expected Python 0.0, but selected Python" in result.stdout + result.stderr diff --git a/tests/test_directory_wait.py b/tests/test_directory_wait.py new file mode 100644 index 0000000..0e80800 --- /dev/null +++ b/tests/test_directory_wait.py @@ -0,0 +1,90 @@ +"""Discovery helpers are opt-in; existing property reads continue processing events.""" + +from unittest.mock import Mock + +import pytest + +from syphon.server_directory import SyphonServerDirectory + + +@pytest.fixture +def directory(): + directory = SyphonServerDirectory.__new__(SyphonServerDirectory) + directory._syphonServerDirectoryObjC = Mock() + directory.update_run_loop = Mock() + return directory + + +def snapshots(directory, values): + directory._syphonServerDirectoryObjC.sharedDirectory.return_value.servers.side_effect = values + + +def test_snapshot_does_not_process_events(directory): + snapshots(directory, [[{"SyphonServerDescriptionNameKey": "Camera"}]]) + assert directory.server_snapshot[0].name == "Camera" + directory.update_run_loop.assert_not_called() + + +def test_existing_property_still_processes_events(directory): + snapshots(directory, [[{"SyphonServerDescriptionNameKey": "Camera"}]]) + assert directory.servers[0].name == "Camera" + directory.update_run_loop.assert_called_once_with() + + +def test_wait_returns_existing_server_without_pumping(directory): + snapshots(directory, [[{"SyphonServerDescriptionNameKey": "Camera"}]]) + assert directory.wait_for_server(timeout=0).name == "Camera" + directory.update_run_loop.assert_not_called() + + +def test_wait_pumps_discovery_and_returns_matching_server(directory, monkeypatch): + import syphon.server_directory as module + + monkeypatch.setattr(module.time, "monotonic", Mock(side_effect=[0, 0.1])) + snapshots(directory, [[], [{"SyphonServerDescriptionNameKey": "Camera"}]]) + assert directory.wait_for_server(name="Camera").name == "Camera" + directory.update_run_loop.assert_called_once_with(timeout=0.05) + + +def test_wait_caps_pump_at_deadline_and_returns_none(directory, monkeypatch): + import syphon.server_directory as module + + monkeypatch.setattr(module.time, "monotonic", Mock(side_effect=[0, 0.99, 1.01])) + snapshots(directory, [[], []]) + assert directory.wait_for_server(timeout=1) is None + assert directory.update_run_loop.call_args.kwargs["timeout"] == pytest.approx(0.01) + + +@pytest.mark.parametrize("timeout", [-1, float("nan"), float("inf")]) +def test_invalid_waits_are_rejected(directory, timeout): + with pytest.raises(ValueError, match="finite nonnegative"): + directory.wait_for_server(timeout) + with pytest.raises(ValueError, match="finite nonnegative"): + SyphonServerDirectory.update_run_loop(directory, timeout) + + +def test_run_loop_timeout_is_explicit_and_default_is_preserved(monkeypatch): + import syphon.server_directory as module + + run_loop = Mock() + monkeypatch.setattr(module, "NSRunLoop", run_loop) + date = Mock() + monkeypatch.setattr(module, "NSDate", date) + directory = SyphonServerDirectory() + directory.update_run_loop() + directory.update_run_loop(timeout=0) + assert [call.args[0] for call in date.dateWithTimeIntervalSinceNow_.call_args_list] == [1.0, 0] + + +@pytest.mark.parametrize("name,app_name", [("Camera", None), (None, "Studio"), ("Missing", "Studio")]) +def test_wait_filters_match_either_field(directory, name, app_name): + snapshots( + directory, + [ + [ + {"SyphonServerDescriptionNameKey": "Other", "SyphonServerDescriptionAppNameKey": "Elsewhere"}, + {"SyphonServerDescriptionNameKey": "Camera", "SyphonServerDescriptionAppNameKey": "Studio"}, + ] + ], + ) + assert directory.wait_for_server(timeout=0, name=name, app_name=app_name).name == "Camera" diff --git a/tests/test_distributions.py b/tests/test_distributions.py index e1603ca..4ed47d4 100644 --- a/tests/test_distributions.py +++ b/tests/test_distributions.py @@ -30,6 +30,9 @@ def test_source_archive_is_self_contained(dist_dir): assert not any( ".git" in name.split("/") or "build" in name.split("/") or ".framework/" in name for name in names ) + assert "scripts/benchmark.py" not in names + assert "tests/test_benchmark.py" not in names + assert not any(name.startswith("benchmark-results/") for name in names) def test_wheel_metadata_and_bundled_framework(dist_dir, tmp_path): @@ -40,6 +43,7 @@ def test_wheel_metadata_and_bundled_framework(dist_dir, tmp_path): assert {str(tag) for tag in tags} == {"py3-none-macosx_12_0_universal2"} with zipfile.ZipFile(wheels[0]) as wheel: names = set(wheel.namelist()) + assert not any(name.startswith(("scripts/", "tests/", "benchmark-results/")) for name in names) wheel_metadata = email.parser.BytesParser().parsebytes( wheel.read(next(n for n in names if n.endswith("/WHEEL"))) ) diff --git a/tests/test_example_cleanup.py b/tests/test_example_cleanup.py new file mode 100644 index 0000000..ed70d5e --- /dev/null +++ b/tests/test_example_cleanup.py @@ -0,0 +1,161 @@ +"""Examples must release native and GUI resources on exit and failed operations.""" + +import runpy +import sys +from pathlib import Path +from unittest.mock import MagicMock, Mock + +import pytest + +import syphon + +EXAMPLES = Path(__file__).resolve().parents[1] / "examples" + + +@pytest.mark.parametrize("scenario", ["quit", "rename", "unopened", "empty", "conversion-error"]) +def test_video_exit_and_failure_cleanup(monkeypatch, scenario): + np = pytest.importorskip("numpy") + cv2 = MagicMock() + video = cv2.VideoCapture.return_value + video.isOpened.return_value = scenario != "unopened" + dimensions = {cv2.CAP_PROP_FRAME_WIDTH: 8, cv2.CAP_PROP_FRAME_HEIGHT: 4, cv2.CAP_PROP_FPS: 30} + video.get.side_effect = dimensions.get + video.read.return_value = (scenario != "empty", np.zeros((4, 8, 3), dtype=np.uint8)) + cv2.waitKey.side_effect = [ord(" "), ord(" "), ord("q")] if scenario == "rename" else [ord("q")] + if scenario == "conversion-error": + cv2.cvtColor.side_effect = RuntimeError("Conversion failed") + monkeypatch.setitem(sys.modules, "cv2", cv2) + server, directory = MagicMock(), MagicMock() + server.__enter__.return_value = server + directory.__enter__.return_value = directory + monkeypatch.setattr(syphon, "SyphonMetalServer", lambda _: server) + monkeypatch.setattr(syphon, "SyphonServerDirectory", lambda: directory) + namespace = runpy.run_path(str(EXAMPLES / "MetalServerVideoExample.py")) + namespace["main"].__globals__["create_mtl_texture"] = MagicMock() + namespace["main"].__globals__["copy_image_to_mtl_texture"] = MagicMock() + if scenario == "conversion-error": + with pytest.raises(RuntimeError, match="Conversion failed"): + namespace["main"]() + else: + assert namespace["main"]() == (0 if scenario in ("quit", "rename") else 1) + video.release.assert_called_once_with() + cv2.destroyAllWindows.assert_called_once_with() + if scenario != "unopened": + server.__exit__.assert_called_once() + directory.__exit__.assert_called_once() + if scenario == "empty": + assert video.read.call_count == 2 # no busy loop on an unreadable video + if scenario == "rename": + assert server.name == "Metal Video 2" + assert server.publish_frame_texture.call_count == 3 + assert cv2.waitKey.call_count == 3 + server.command_queue.commandBuffer.assert_not_called() + + +def test_minimal_image_example_uploads_every_frame(monkeypatch): + pytest.importorskip("numpy") + events = [] + server, directory = MagicMock(), MagicMock() + server.__enter__.return_value = server + directory.__enter__.return_value = directory + server.publish_frame_texture.side_effect = lambda _: events.append("publish") + directory.update_run_loop.side_effect = [None, KeyboardInterrupt] + monkeypatch.setattr(syphon, "SyphonMetalServer", lambda _: server) + monkeypatch.setattr(syphon, "SyphonServerDirectory", lambda: directory) + namespace = runpy.run_path(str(EXAMPLES / "MetalServerExampleMini.py")) + namespace["main"].__globals__["create_mtl_texture"] = Mock() + namespace["main"].__globals__["copy_image_to_mtl_texture"] = Mock(side_effect=lambda *_: events.append("upload")) + namespace["main"].__globals__["time"] = Mock() + + with pytest.raises(KeyboardInterrupt): + namespace["main"]() + + assert events == ["upload", "publish", "upload", "publish"] + server.__exit__.assert_called_once() + + +@pytest.mark.parametrize("upload_error", [False, True]) +def test_async_example_synchronizes_texture_reuse_and_drains_on_exit(monkeypatch, upload_error): + events = [] + textures = [object(), object()] + buffers = [Mock() for _ in range(3)] + for index, buffer in enumerate(buffers): + buffer.commit.side_effect = lambda index=index: events.append(("commit", index)) + buffer.waitUntilCompleted.side_effect = lambda index=index: events.append(("wait", index)) + + server, directory = MagicMock(), MagicMock() + server.__enter__.return_value = server + directory.__enter__.return_value = directory + server.command_queue.commandBuffer.side_effect = buffers + directory.update_run_loop.side_effect = [None, None, KeyboardInterrupt] + monkeypatch.setattr(syphon, "SyphonMetalServer", lambda _: server) + monkeypatch.setattr(syphon, "SyphonServerDirectory", lambda: directory) + namespace = runpy.run_path(str(EXAMPLES / "MetalServerAsyncExample.py")) + namespace["main"].__globals__["create_mtl_texture"] = Mock(side_effect=textures) + namespace["main"].__globals__["time"] = Mock(monotonic=Mock(return_value=0)) + + def upload(pixels, texture): + if upload_error and events.count(("upload", 0)) == 1 and texture is textures[0]: + raise RuntimeError("Upload failed") + events.append(("upload", textures.index(texture))) + + def publish(texture, *, command_buffer, auto_commit): + assert auto_commit is False + events.append(("publish", textures.index(texture), buffers.index(command_buffer))) + + namespace["main"].__globals__["copy_bytes_to_mtl_texture"] = upload + server.publish_frame_texture.side_effect = publish + + with pytest.raises(RuntimeError if upload_error else KeyboardInterrupt): + namespace["main"]() + + expected = [ + ("upload", 0), + ("publish", 0, 0), + ("commit", 0), + ("upload", 1), + ("publish", 1, 1), + ("commit", 1), + ("wait", 0), + ] + if not upload_error: + expected += [("upload", 0), ("publish", 0, 2), ("commit", 2), ("wait", 2)] + assert events == expected + [("wait", 1)] + server.__exit__.assert_called_once() + directory.__exit__.assert_called_once() + + +def test_opengl_server_cleans_up_after_drawing_failure(monkeypatch): + glfw, gl = MagicMock(), MagicMock() + glfw.init.return_value = True + glfw.window_should_close.return_value = False + monkeypatch.setitem(sys.modules, "glfw", glfw) + monkeypatch.setitem(sys.modules, "OpenGL", MagicMock()) + monkeypatch.setitem(sys.modules, "OpenGL.GL", gl) + server = MagicMock() + server.__enter__.return_value = server + monkeypatch.setattr(syphon, "SyphonOpenGLServer", lambda _: server) + namespace = runpy.run_path(str(EXAMPLES / "OpenGLServerExample.py")) + namespace["main"].__globals__["render"] = MagicMock(side_effect=RuntimeError("Drawing failed")) + with pytest.raises(RuntimeError, match="Drawing failed"): + namespace["main"]() + server.__exit__.assert_called_once() + gl.glDeleteTextures.assert_called_once() + glfw.destroy_window.assert_called_once_with(glfw.create_window.return_value) + glfw.terminate.assert_called_once_with() + + +def test_opengl_client_cleans_up_when_no_server_is_found(monkeypatch): + glfw = MagicMock() + monkeypatch.setitem(sys.modules, "glfw", glfw) + monkeypatch.setitem(sys.modules, "OpenGL", MagicMock()) + monkeypatch.setitem(sys.modules, "OpenGL.GL", MagicMock()) + directory = MagicMock() + directory.__enter__.return_value = directory + directory.wait_for_server.return_value = None + monkeypatch.setattr(syphon, "SyphonServerDirectory", lambda: directory) + main = runpy.run_path(str(EXAMPLES / "OpenGLClientExample.py"))["main"] + assert main() == 1 + directory.__exit__.assert_called_once() + glfw.destroy_window.assert_called_once_with(glfw.create_window.return_value) + glfw.terminate.assert_called_once_with() diff --git a/tests/test_example_discovery.py b/tests/test_example_discovery.py index 8f617a8..7f631b5 100644 --- a/tests/test_example_discovery.py +++ b/tests/test_example_discovery.py @@ -1,14 +1,11 @@ """Headless examples must answer discovery requests from clients started later.""" -import runpy import signal import subprocess import sys import textwrap import time from pathlib import Path -from types import SimpleNamespace -from unittest.mock import Mock import pytest @@ -16,7 +13,9 @@ @pytest.mark.metal -@pytest.mark.parametrize("example", ["MetalServerExample.py", "MetalServerExampleMini.py"]) +@pytest.mark.parametrize( + "example", ["MetalServerExample.py", "MetalServerExampleMini.py", "MetalServerAsyncExample.py"] +) def test_late_client_discovers_running_metal_example(example, tmp_path): import Metal @@ -98,18 +97,3 @@ def publish_frame_texture(self, *args, **kwargs): process.wait() output.seek(0) assert process.returncode == 0, output.read() - - -@pytest.mark.parametrize("found", [True, False]) -def test_client_waits_for_discovery_and_times_out(monkeypatch, found): - # Discovery itself does not require OpenCV; avoid pulling GUI dependencies into unit tests. - monkeypatch.setitem(sys.modules, "cv2", Mock()) - monkeypatch.setitem(sys.modules, "syphon.utils.numpy", SimpleNamespace(copy_mtl_texture_to_image=Mock())) - wait = runpy.run_path(str(ROOT / "examples/MetalClientExample.py"))["wait_for_server"] - server = object() - results = iter([[], [server] if found else []]) - directory = type("Directory", (), {"servers": property(lambda _: next(results))})() - clock = SimpleNamespace(monotonic=Mock(side_effect=[0, 0.1, 5]), sleep=Mock()) - wait.__globals__["time"] = clock - assert wait(directory) is (server if found else None) - clock.sleep.assert_called_once_with(0.01) diff --git a/tests/test_metal_integration.py b/tests/test_metal_integration.py index 2ee87b4..129a115 100644 --- a/tests/test_metal_integration.py +++ b/tests/test_metal_integration.py @@ -7,6 +7,53 @@ pytestmark = pytest.mark.metal +@pytest.mark.parametrize("auto_commit", [False, True]) +@pytest.mark.parametrize("bgra", [False, True]) +def test_native_transfer_reuse_and_submission(server, auto_commit, bgra): + import Metal + + np = pytest.importorskip("numpy") + from syphon.utils.numpy import copy_image_to_mtl_texture, copy_mtl_texture_to_image + from syphon.utils.raw import copy_mtl_texture_to_buffer, copy_mtl_texture_to_bytes, create_mtl_texture + + pixel_format = Metal.MTLPixelFormatBGRA8Unorm if bgra else Metal.MTLPixelFormatRGBA8Unorm + texture = create_mtl_texture(server.device, 3, 2, pixel_format) + strided = np.arange(48, dtype=np.uint8).reshape(2, 6, 4)[:, ::2] + out = np.empty((2, 3, 4), dtype=np.uint8) + staging = bytearray(24) + snapshot = None + for image in (strided, np.ascontiguousarray(strided[:, ::-1])): + copy_image_to_mtl_texture(image, texture) + assert copy_mtl_texture_to_bytes(texture) == image.tobytes() + assert copy_mtl_texture_to_buffer(texture, staging) is staging + assert staging == image.tobytes() + assert copy_mtl_texture_to_image(texture, out=out) is out + np.testing.assert_array_equal(out, image) + if snapshot is None: + snapshot = copy_mtl_texture_to_image(texture) + buffer = server.command_queue.commandBuffer() + assert server.publish_frame_texture(texture, command_buffer=buffer, auto_commit=auto_commit) is None + if not auto_commit: + assert buffer.status() == Metal.MTLCommandBufferStatusNotEnqueued + buffer.commit() + buffer.waitUntilCompleted() + else: + assert buffer.status() == Metal.MTLCommandBufferStatusCompleted + assert buffer.error() is None + output = server.new_frame_image + if output.storageMode() == Metal.MTLStorageModeManaged: + sync = server.command_queue.commandBuffer() + encoder = sync.blitCommandEncoder() + encoder.synchronizeResource_(output) + encoder.endEncoding() + sync.commit() + sync.waitUntilCompleted() + expected = image if bgra else image[:, :, [2, 1, 0, 3]] + np.testing.assert_array_equal(copy_mtl_texture_to_image(output), expected) + np.testing.assert_array_equal(snapshot, strided) + assert not np.array_equal(snapshot, out) + + @pytest.fixture def server(): import Metal @@ -80,6 +127,11 @@ def receive(client, rgba): assert client.is_valid for client in clients: receive(client, (17, 53, 199, 255)) + server.name = "Renamed connected output" + assert server.server_description.uuid == description.uuid + assert all(client.is_valid for client in clients) + for client in clients: + receive(client, (41, 83, 167, 255)) clients.pop(0).stop() receive(clients[0], (101, 203, 37, 255)) finally: @@ -147,6 +199,10 @@ def test_public_rename_and_observer_removal(server): import syphon changes = [] + with syphon.SyphonServerDirectory() as directory: + found = directory.wait_for_server(timeout=5, name=server.name) + assert found is not None and found.uuid == server.server_description.uuid + assert any(entry.uuid == found.uuid for entry in directory.server_snapshot) with syphon.SyphonServerDirectory() as directory: directory.run_loop_interval = 0.01 token = directory.add_observer(syphon.SyphonServerNotification.Update, lambda note: changes.append(note)) diff --git a/tests/test_opengl_integration.py b/tests/test_opengl_integration.py index 4e544f5..3c0de28 100644 --- a/tests/test_opengl_integration.py +++ b/tests/test_opengl_integration.py @@ -8,6 +8,66 @@ pytestmark = pytest.mark.opengl +@pytest.mark.parametrize("target", [0x0DE1, 0x84F5]) +def test_texture_publish_queries_correct_target_and_preserves_query_binding(target): + GL = pytest.importorskip("OpenGL.GL") + import AppKit + import objc + + import syphon + + with objc.autorelease_pool(): + fmt = AppKit.NSOpenGLPixelFormat.alloc().initWithAttributes_( + [AppKit.NSOpenGLPFAOpenGLProfile, AppKit.NSOpenGLProfileVersion3_2Core, AppKit.NSOpenGLPFAColorSize, 24, 0] + ) + context = None if fmt is None else AppKit.NSOpenGLContext.alloc().initWithFormat_shareContext_(fmt, None) + if context is None: + pytest.skip("No usable OpenGL context") + previous = AppKit.NSOpenGLContext.currentContext() + context.makeCurrentContext() + textures = list(map(int, GL.glGenTextures(2))) + try: + texture, marker = textures + GL.glBindTexture(target, texture) + pixels = bytes((17, 53, 199, 255)) * 32 + GL.glTexImage2D(target, 0, GL.GL_RGBA8, 8, 4, 0, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, pixels) + GL.glTexParameteri(target, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST) + GL.glBindTexture(target, marker) + GL.glFinish() + with syphon.SyphonOpenGLServer("Texture target test", is_private=True) as server: + assert server._get_texture_size(texture, target=target) == (8, 4) + binding = GL.GL_TEXTURE_BINDING_2D if target == GL.GL_TEXTURE_2D else GL.GL_TEXTURE_BINDING_RECTANGLE + assert int(GL.glGetIntegerv(binding)) == marker + server.publish_frame_texture(texture, target=target) + GL.glFinish() + output = server.new_frame_image + assert tuple(output.textureSize()) == (8, 4) + framebuffer = GL.glGenFramebuffers(1) + previous_framebuffer = GL.glGetIntegerv(GL.GL_READ_FRAMEBUFFER_BINDING) + try: + GL.glBindFramebuffer(GL.GL_READ_FRAMEBUFFER, framebuffer) + GL.glFramebufferTexture2D( + GL.GL_READ_FRAMEBUFFER, + GL.GL_COLOR_ATTACHMENT0, + GL.GL_TEXTURE_RECTANGLE, + output.textureName(), + 0, + ) + GL.glReadBuffer(GL.GL_COLOR_ATTACHMENT0) + assert GL.glCheckFramebufferStatus(GL.GL_READ_FRAMEBUFFER) == GL.GL_FRAMEBUFFER_COMPLETE + assert bytes(GL.glReadPixels(0, 0, 8, 4, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE)) == pixels + finally: + GL.glBindFramebuffer(GL.GL_READ_FRAMEBUFFER, previous_framebuffer) + GL.glDeleteFramebuffers(1, [framebuffer]) + del output + finally: + GL.glDeleteTextures(textures) + if previous is None: + AppKit.NSOpenGLContext.clearCurrentContext() + else: + previous.makeCurrentContext() + + @pytest.mark.parametrize("sample_count", [0, 4]) def test_direct_framebuffer_rendering(sample_count): GL = pytest.importorskip("OpenGL.GL") diff --git a/tests/test_opengl_texture_size.py b/tests/test_opengl_texture_size.py new file mode 100644 index 0000000..aa29c99 --- /dev/null +++ b/tests/test_opengl_texture_size.py @@ -0,0 +1,58 @@ +"""Check target-aware size queries and state preservation without a GL context.""" + +from unittest.mock import Mock, call + +import pytest + +from syphon.server import SyphonOpenGLServer + + +@pytest.fixture +def gl(monkeypatch): + from syphon.utils import opengl + + gl = Mock( + GL_TEXTURE_2D=0x0DE1, + GL_TEXTURE_RECTANGLE=0x84F5, + GL_TEXTURE_BINDING_2D=0x8069, + GL_TEXTURE_BINDING_RECTANGLE=0x84F6, + GL_TEXTURE_WIDTH=0x1000, + GL_TEXTURE_HEIGHT=0x1001, + ) + gl.glGetIntegerv.return_value = 99 + gl.glGetTexLevelParameteriv.side_effect = [8, 4] + monkeypatch.setattr(opengl, "_require_pyopengl", lambda: gl) + return gl + + +@pytest.mark.parametrize("target,binding", [(0x0DE1, 0x8069), (0x84F5, 0x84F6)]) +def test_publish_queries_requested_target_and_restores_binding(gl, target, binding): + server = SyphonOpenGLServer.__new__(SyphonOpenGLServer) + server.context = Mock() + server.publish_frame_texture(7, target=target) + gl.glGetIntegerv.assert_called_once_with(binding) + assert gl.glGetTexLevelParameteriv.call_args_list == [ + call(target, 0, gl.GL_TEXTURE_WIDTH), + call(target, 0, gl.GL_TEXTURE_HEIGHT), + ] + assert gl.glBindTexture.call_args_list == [call(target, 7), call(target, 99)] + args = server.context.publishFrameTexture_textureTarget_imageRegion_textureDimensions_flipped_.call_args.args + assert args[0:2] == (7, target) + assert tuple(args[3]) == (8, 4) + + +def test_failed_query_restores_binding(gl): + gl.glGetTexLevelParameteriv.side_effect = RuntimeError("Driver query failed") + server = SyphonOpenGLServer.__new__(SyphonOpenGLServer) + with pytest.raises(RuntimeError, match="Driver query failed"): + server._get_texture_size(7) + assert gl.glBindTexture.call_args_list == [call(gl.GL_TEXTURE_2D, 7), call(gl.GL_TEXTURE_2D, 99)] + + +def test_known_dimensions_skip_driver_queries(gl): + server = SyphonOpenGLServer.__new__(SyphonOpenGLServer) + server.context = Mock() + server.publish_frame_texture(7, size=(8, 4), target=gl.GL_TEXTURE_RECTANGLE) + gl.glGetIntegerv.assert_not_called() + gl.glGetTexLevelParameteriv.assert_not_called() + gl.glBindTexture.assert_not_called() diff --git a/tests/test_optional_opengl.py b/tests/test_optional_opengl.py index adec1c3..f8a27ed 100644 --- a/tests/test_optional_opengl.py +++ b/tests/test_optional_opengl.py @@ -95,7 +95,7 @@ def test_opengl_publish_preserves_default_and_explicit_targets(): call = context.publishFrameTexture_textureTarget_imageRegion_textureDimensions_flipped_.call_args assert call.args[0:2] == (7, 0x0DE1) assert call.args[-1] is False - publish(server, 9, target=0x84F5, is_flipped=True) # GL_TEXTURE_RECTANGLE + publish(server, 9, size=(8, 4), target=0x84F5, is_flipped=True) # GL_TEXTURE_RECTANGLE call = context.publishFrameTexture_textureTarget_imageRegion_textureDimensions_flipped_.call_args assert call.args[0:2] == (9, 0x84F5) assert call.args[-1] is True diff --git a/tests/test_texture_data.py b/tests/test_texture_data.py index e44a8b6..18a2d4d 100644 --- a/tests/test_texture_data.py +++ b/tests/test_texture_data.py @@ -5,7 +5,7 @@ import Metal import pytest -from syphon.utils.raw import copy_bytes_to_mtl_texture, copy_mtl_texture_to_bytes +from syphon.utils.raw import copy_bytes_to_mtl_texture, copy_mtl_texture_to_buffer, copy_mtl_texture_to_bytes class MemoryTexture: @@ -28,7 +28,7 @@ def replaceRegion_mipmapLevel_withBytes_bytesPerRow_(self, region, level, data, assert tuple(region.size) == (self._width, self._height, 1) assert level == 0 assert row_size == self._width * 4 - self.data = bytes(data) + self.data = bytes(memoryview(data).cast("B")[: self._width * self._height * 4]) def getBytes_bytesPerRow_bytesPerImage_fromRegion_mipmapLevel_slice_( self, buffer, row_size, image_size, region, level, slice_number @@ -37,7 +37,7 @@ def getBytes_bytesPerRow_bytesPerImage_fromRegion_mipmapLevel_slice_( assert image_size == row_size * self._height assert tuple(region.size) == (self._width, self._height, 1) assert (level, slice_number) == (0, 0) - ctypes.memmove(buffer, self.data, len(self.data)) + memoryview(buffer).cast("B")[:] = self.data @pytest.mark.parametrize("pixel_format", [Metal.MTLPixelFormatRGBA8Unorm, Metal.MTLPixelFormatBGRA8Unorm]) @@ -52,14 +52,33 @@ def test_raw_pixels_and_reusable_buffer(pixel_format): def test_unsupported_pixel_format(): - with pytest.raises(Exception, match="pixel format"): + with pytest.raises(Exception, match="pixel format") as error: copy_mtl_texture_to_bytes(MemoryTexture(pixel_format=Metal.MTLPixelFormatR8Unorm)) + assert type(error.value) is Exception @pytest.mark.parametrize("size", [0, 23, 25]) def test_wrong_buffer_size(size): - with pytest.raises(Exception, match="expected: 24"): + with pytest.raises(Exception, match="expected: 24") as error: copy_mtl_texture_to_bytes(MemoryTexture(), ctypes.create_string_buffer(size)) + assert type(error.value) is Exception + + +@pytest.mark.parametrize("size", [0, 4, 23]) +def test_undersized_upload_fails_before_native_call(size): + texture = MemoryTexture() + original = texture.data + with pytest.raises(ValueError, match="at least: 24"): + copy_bytes_to_mtl_texture(bytes(size), texture) + assert texture.data is original + + +@pytest.mark.parametrize("pixel_format", [Metal.MTLPixelFormatRGBA8Unorm_sRGB, Metal.MTLPixelFormatRGBA8Uint]) +def test_upload_preserves_raw_format_and_oversized_buffer_support(pixel_format): + texture = MemoryTexture(pixel_format=pixel_format) + data = bytes(range(32)) + copy_bytes_to_mtl_texture(data, texture) + assert texture.data == data[:24] def test_numpy_roundtrip_handles_noncontiguous_arrays(): @@ -83,3 +102,92 @@ def test_numpy_rejects_invalid_image_shape(shape): with pytest.raises(AssertionError, match="shape"): copy_image_to_mtl_texture(np.zeros(shape, dtype=np.uint8), MemoryTexture()) + + +def test_buffer_read_reuses_storage_and_bytes_result_is_independent(): + texture = MemoryTexture() + out = bytearray(24) + assert copy_mtl_texture_to_buffer(texture, out) is out + assert out == texture.data + snapshot = copy_mtl_texture_to_bytes(texture, out) + out[0] = 255 + assert snapshot == texture.data + + +@pytest.mark.parametrize("writable", [False, True]) +def test_noncontiguous_buffer_is_rejected(writable): + buffer = memoryview(bytearray(48))[::2] + with pytest.raises(ValueError, match="C-contiguous"): + if writable: + copy_mtl_texture_to_buffer(MemoryTexture(), buffer) + else: + copy_bytes_to_mtl_texture(buffer, MemoryTexture()) + + +def test_readonly_output_is_rejected(): + with pytest.raises(ValueError, match="writable"): + copy_mtl_texture_to_buffer(MemoryTexture(), bytes(24)) + + +def test_numpy_upload_borrows_contiguous_array_storage(): + np = pytest.importorskip("numpy") + from syphon.utils.numpy import copy_image_to_mtl_texture + + texture = MemoryTexture() + captured = [] + texture.replaceRegion_mipmapLevel_withBytes_bytesPerRow_ = lambda region, level, data, row: captured.append(data) + image = np.arange(24, dtype=np.uint8).reshape(2, 3, 4) + copy_image_to_mtl_texture(image, texture) + assert captured[0].obj is image + + +@pytest.mark.parametrize("kind", ["masked", "datetime", "uint16"]) +def test_numpy_preserves_existing_serialization_for_other_arrays(kind): + np = pytest.importorskip("numpy") + from syphon.utils.numpy import copy_image_to_mtl_texture + + image = np.arange(24, dtype=np.uint8).reshape(2, 3, 4) + if kind == "masked": + image = np.ma.array(image, mask=False, fill_value=17) + image.mask[0, 0, 0] = True + elif kind == "datetime": + image = image.astype("datetime64[ns]") + else: + image = image.astype(np.uint16) + texture = MemoryTexture() + copy_image_to_mtl_texture(image, texture) + assert texture.data == image.tobytes()[:24] + + +def test_numpy_read_reuses_output_and_default_is_writable(): + np = pytest.importorskip("numpy") + from syphon.utils.numpy import copy_mtl_texture_to_image + + texture = MemoryTexture() + out = np.empty((2, 3, 4), dtype=np.uint8) + assert copy_mtl_texture_to_image(texture, out=out) is out + np.testing.assert_array_equal(out.reshape(-1), np.arange(24)) + result = copy_mtl_texture_to_image(texture) + assert result.flags.writeable + texture.data = bytes(reversed(range(24))) + copy_mtl_texture_to_image(texture, out=out) + assert out.tobytes() == texture.data + assert result.tobytes() != out.tobytes() + + +@pytest.mark.parametrize("kind", ["shape", "dtype", "strided", "readonly"]) +def test_numpy_rejects_invalid_output(kind): + np = pytest.importorskip("numpy") + from syphon.utils.numpy import copy_mtl_texture_to_image + + out = np.empty((2, 3, 4), dtype=np.uint8) + if kind == "shape": + out = out[:1] + elif kind == "dtype": + out = out.astype(np.float32) + elif kind == "strided": + out = np.empty((2, 6, 4), dtype=np.uint8)[:, ::2] + else: + out.flags.writeable = False + with pytest.raises(ValueError): + copy_mtl_texture_to_image(MemoryTexture(), out=out) diff --git a/tests/test_wrappers.py b/tests/test_wrappers.py index 7ccf046..1621dfe 100644 --- a/tests/test_wrappers.py +++ b/tests/test_wrappers.py @@ -1,7 +1,7 @@ """Check wrapper behavior without requiring a GPU or a running Syphon peer.""" from types import SimpleNamespace -from unittest.mock import Mock +from unittest.mock import Mock, call import pytest @@ -24,15 +24,23 @@ def test_region_and_size_defaults(region, size, expected): assert server._prepare_region_and_size(texture, region, size) == expected -@pytest.mark.parametrize("external_buffer,auto_commit", [(False, True), (True, True), (True, False)]) +@pytest.mark.parametrize("external_buffer", [False, True]) +@pytest.mark.parametrize("auto_commit", [False, True]) def test_metal_command_buffer_ownership(external_buffer, auto_commit): server = SyphonMetalServer.__new__(SyphonMetalServer) server.context = Mock() server.command_queue = Mock() buffer = Mock() if external_buffer else None texture = SimpleNamespace(width=lambda: 16, height=lambda: 8) - server.publish_frame_texture( - texture, region=(1, 2, 3, 4), is_flipped=True, command_buffer=buffer, auto_commit=auto_commit + assert ( + server.publish_frame_texture( + texture, + region=(1, 2, 3, 4), + is_flipped=True, + command_buffer=buffer, + auto_commit=auto_commit, + ) + is None ) if external_buffer: server.command_queue.commandBuffer.assert_not_called() @@ -45,7 +53,28 @@ def test_metal_command_buffer_ownership(external_buffer, auto_commit): assert tuple(args[2].origin) == (1, 2) assert tuple(args[2].size) == (3, 4) assert args[3] is True - assert buffer.commitAndWaitUntilSubmitted.call_count == int(auto_commit) + assert buffer.method_calls == ([call.commit(), call.waitUntilCompleted()] if auto_commit else []) + + +def test_metal_submission_default_waits_for_completion_and_returns_none(): + server = SyphonMetalServer.__new__(SyphonMetalServer) + server.context = Mock() + server.command_queue = Mock() + texture = SimpleNamespace(width=lambda: 16, height=lambda: 8) + assert server.publish_frame_texture(texture) is None + buffer = server.command_queue.commandBuffer.return_value + assert buffer.method_calls == [call.commit(), call.waitUntilCompleted()] + + +def test_metal_rejects_missing_command_buffer(): + server = SyphonMetalServer.__new__(SyphonMetalServer) + server.context = Mock() + server.command_queue = Mock() + server.command_queue.commandBuffer.return_value = None + texture = SimpleNamespace(width=lambda: 16, height=lambda: 8) + with pytest.raises(RuntimeError, match="command buffer"): + server.publish_frame_texture(texture) + server.context.publishFrameTexture_onCommandBuffer_imageRegion_flipped_.assert_not_called() @pytest.fixture diff --git a/uv.lock b/uv.lock index 7fb4227..404c04f 100644 --- a/uv.lock +++ b/uv.lock @@ -367,7 +367,7 @@ wheels = [ [[package]] name = "syphon-python" -version = "0.2.0" +version = "0.3.0" source = { editable = "." } dependencies = [ { name = "pyobjc-core" },