From d112a3ef2efd5187fdc6b0c5a60cae51ee804ca9 Mon Sep 17 00:00:00 2001 From: AAA <35992542+TNTcraftHIM@users.noreply.github.com> Date: Fri, 30 Oct 2026 20:21:28 -0400 Subject: [PATCH] feat(android): capture screens through shared Rust media owners Keep MediaProjection consent and playback audio on the page-owned capture lease. Reuse native frame admission, encoding outputs, cancellation and room routes; normalize normal pre-frame cancellation without platform-specific UI rules. --- docs/research/channel-network-design.md | 2 +- docs/status.md | 6 +- docs/todo.md | 2 + docs/verification-status.md | 6 +- mobile/README.md | 13 +- .../android/app/src/main/AndroidManifest.xml | 5 +- .../tv/piik/android/AppRuntimeService.java | 5 +- .../java/tv/piik/android/CapturePlatform.java | 158 ++++ .../java/tv/piik/android/MainActivity.java | 50 +- prototype/channel-android/Cargo.lock | 736 +++++++++++++++++- prototype/channel-android/Cargo.toml | 2 +- prototype/channel-native/Cargo.lock | 57 ++ prototype/channel-native/Cargo.toml | 15 +- prototype/channel-native/README.md | 5 + .../src/capture/android/audio.rs | 198 +++++ .../src/capture/android/encoding.rs | 419 ++++++++++ .../src/capture/android/frames.rs | 111 +++ .../src/capture/android/graphics.rs | 385 +++++++++ .../channel-native/src/capture/android/mod.rs | 32 + .../src/capture/android/platform.rs | 91 +++ .../src/capture/android/source.rs | 149 ++++ .../channel-native/src/capture/cadence.rs | 4 +- .../src/capture/linux/source.rs | 4 +- .../src/capture/macos/source.rs | 2 +- prototype/channel-native/src/capture/mod.rs | 20 +- .../channel-native/src/capture/windows.rs | 2 +- prototype/channel-native/src/hosted_room.rs | 41 +- prototype/channel-native/src/input/tests.rs | 2 +- prototype/channel-native/src/media/local.rs | 2 +- .../src/media/local/encodings.rs | 22 +- prototype/channel-native/src/peer/input.rs | 33 +- prototype/channel-native/src/session.rs | 26 +- prototype/channel-server/Cargo.lock | 58 +- prototype/channel-server/Cargo.toml | 3 - prototype/channel-server/src/app.rs | 168 ++-- .../channel-server/tests/native_session.rs | 188 +++-- src/client/channel/app-link.ts | 47 +- .../components/ChannelShareControl.tsx | 11 +- .../components/channel-share-control.css | 2 +- src/client/channel/session.ts | 20 +- src/client/channel/types.ts | 3 +- src/client/channel/use-channel.ts | 1 + src/client/native/activation.ts | 2 + src/client/native/wire.ts | 2 +- tests/channel-session.test.ts | 78 +- tests/native-activation.test.ts | 10 + tests/native-client.test.ts | 11 +- 47 files changed, 3009 insertions(+), 200 deletions(-) create mode 100644 mobile/android/app/src/main/java/tv/piik/android/CapturePlatform.java create mode 100644 prototype/channel-native/src/capture/android/audio.rs create mode 100644 prototype/channel-native/src/capture/android/encoding.rs create mode 100644 prototype/channel-native/src/capture/android/frames.rs create mode 100644 prototype/channel-native/src/capture/android/graphics.rs create mode 100644 prototype/channel-native/src/capture/android/mod.rs create mode 100644 prototype/channel-native/src/capture/android/platform.rs create mode 100644 prototype/channel-native/src/capture/android/source.rs diff --git a/docs/research/channel-network-design.md b/docs/research/channel-network-design.md index 68d8f16c9..ccbef4bcb 100644 --- a/docs/research/channel-network-design.md +++ b/docs/research/channel-network-design.md @@ -694,7 +694,7 @@ PulseAudio monitor pipeline. App enables this capture feature; Server forwarding has no desktop capture dependency. Platform acceptance is tracked in [verification status](../verification-status.md#device-evidence-boundary). -Android is planned at this same producer boundary. One user-approved +Android uses this same producer boundary. One user-approved [MediaProjection](https://developer.android.com/media/grow/media-projection) owns one VirtualDisplay and image source. Independent MediaCodec encodings consume owned immutable snapshots, retaining the existing source clock and output owners; diff --git a/docs/status.md b/docs/status.md index b84a9d032..134916dc1 100644 --- a/docs/status.md +++ b/docs/status.md @@ -52,8 +52,10 @@ Windows keyboard, mouse and optional gamepad input use the selected screen route and shared control UI, with one App desktop executor, page-owned consent and a process-only stop hotkey. The isolated Android shell starts the same Rust App through JNI and opens the -system Browser, using Android certificate trust for site connections. Native -Android capture and release packaging remain part of the platform work. +system Browser, using Android certificate trust for site connections. Its system +picker supplies screen capture and optional playback sound to the same Native +producer; permission and first-frame waits retain the page's capture lease. +Android release packaging remains part of the platform work. [TODO](./todo.md) owns remaining Native media/input and platform work. Both prototype surfaces share URL bookmarks; automatic address discovery is not planned. Work stays on `feat/channel-prototype`, without changing the production 2.x contract. diff --git a/docs/todo.md b/docs/todo.md index 305756d74..218d66700 100644 --- a/docs/todo.md +++ b/docs/todo.md @@ -11,6 +11,8 @@ own behavior; research and Git/PRs own evidence and completed history. and [room-data model](./research/channel-storage-and-identity.md) in cohesive Rust owners. Complete Native low-bandwidth adaptation, capture/input on the remaining platforms and packaging over the shared UI and Native participant. + Complete Android playback-sound, independent-encoding and system-picker + cancellation acceptance before replacing its packaging path. Resolve the recorded GNOME cancellation cleanup defect before Linux packaging. Complete Browser-to-Native recovery acceptance of the [combined Native candidate](../prototype/channel-native/README.md#rtc-dependency), diff --git a/docs/verification-status.md b/docs/verification-status.md index f222a616e..9e74ec04e 100644 --- a/docs/verification-status.md +++ b/docs/verification-status.md @@ -38,7 +38,11 @@ phases, including NAT and Auto codec behavior. its Portal sessions and stream. The GNOME cancellation cleanup defect is recorded in the [network design](./research/channel-network-design.md#implementation-boundary). Hardware encoding and physical sound remain platform acceptance work. -- Android's system-browser App passed emulator screen/camera sharing +- The isolated 3.0 Android Rust App passes NDK/JNI builds and emulator use through + Firefox: App linkage, system screen selection, continuous decoded preview, + pending-page cancellation and capture stop preserve the running room. + [TODO](./todo.md) owns remaining Android acceptance and packaging. +- The published 2.x Android system-browser App passed emulator screen/camera sharing with concurrent room voice. Browser consent returns to the same tab; source replacement, cancellation and background return preserve the share. Local/public startup and launcher reentry also have emulator evidence. Full-App checks now diff --git a/mobile/README.md b/mobile/README.md index 7d54aed7a..62ca84439 100644 --- a/mobile/README.md +++ b/mobile/README.md @@ -20,6 +20,14 @@ and Android's certificate trust. Gradle reads the paired Android artifact version from the JNI crate's Cargo lock. No Go business core or gomobile AAR is used by this shell. The independent cloudflared helper remains Go-built. +Screen/app selection uses Android's system picker. One MediaProjection owns the +image source and optional playback sound; Rust encodings use the shared Native +producer and source clock. Permission and first-frame waits belong to the +selecting page and use the same stop operation as active capture. The +[network design](../docs/research/channel-network-design.md#implementation-boundary) +owns that boundary. Android does not expose a controlled keyboard/mouse endpoint; +Browser camera and room voice keep their Browser permissions. + ## Development build Use Rust 1.91 with `aarch64-linux-android`, NDK 30.0.16248370, JDK 17, @@ -57,8 +65,3 @@ Gradle reads signing material from `PIIK_ANDROID_KEYSTORE` (an absolute path), back up the signing key securely. Updates to an installed package must retain its application ID and signing key. The experimental application ID above keeps this runtime separate from the published 2.x App. - -This step does not implement MediaProjection, MediaCodec capture/encoding, -playback sound or Android native input. Their accepted producer and permission -boundary is in the [network design](../docs/research/channel-network-design.md#implementation-boundary). -Browser camera and voice continue to use browser permissions. diff --git a/mobile/android/app/src/main/AndroidManifest.xml b/mobile/android/app/src/main/AndroidManifest.xml index ece062bc5..a2ff826af 100644 --- a/mobile/android/app/src/main/AndroidManifest.xml +++ b/mobile/android/app/src/main/AndroidManifest.xml @@ -4,14 +4,17 @@ + + + - + diff --git a/mobile/android/app/src/main/java/tv/piik/android/AppRuntimeService.java b/mobile/android/app/src/main/java/tv/piik/android/AppRuntimeService.java index a45cf907a..8c0a3140a 100644 --- a/mobile/android/app/src/main/java/tv/piik/android/AppRuntimeService.java +++ b/mobile/android/app/src/main/java/tv/piik/android/AppRuntimeService.java @@ -15,6 +15,8 @@ public final class AppRuntimeService extends Service { NativeRuntime runtime; CompletableFuture startup; Throwable failure; + final java.util.ArrayDeque captureRequests = new java.util.ArrayDeque<>(); + int projections; @Override public void onCreate() { @@ -45,7 +47,8 @@ public final class AppRuntimeService extends Service { startForeground( 3, notification(), - Build.VERSION.SDK_INT >= 34 ? ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE : 0); + (Build.VERSION.SDK_INT >= 34 ? ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE : 0) + | (projections > 0 ? ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION : 0)); } void refreshNotification() { diff --git a/mobile/android/app/src/main/java/tv/piik/android/CapturePlatform.java b/mobile/android/app/src/main/java/tv/piik/android/CapturePlatform.java new file mode 100644 index 000000000..d23384ee7 --- /dev/null +++ b/mobile/android/app/src/main/java/tv/piik/android/CapturePlatform.java @@ -0,0 +1,158 @@ +package tv.piik.android; + +import android.app.Activity; +import android.content.*; +import android.content.pm.PackageManager; +import android.graphics.SurfaceTexture; +import android.hardware.display.*; +import android.media.*; +import android.media.projection.*; +import android.os.*; +import android.util.DisplayMetrics; +import android.view.*; + +/** OS permission and callback facts for one Rust-owned Capture. No codec or media queue. */ +public final class CapturePlatform implements AutoCloseable { + private final Context context; + private final SurfaceTexture texture = new SurfaceTexture(false); + private final Surface surface = new Surface(texture); + private MediaProjection projection; + private VirtualDisplay display; + private boolean closed, frame, audioRequested, audioDenied, foreground; + private int width, height, density; + private String error; + private AudioRecord audio; + private AppRuntimeService service; + private java.lang.ref.WeakReference permissionActivity; + private final DisplayManager.DisplayListener resize = new DisplayManager.DisplayListener() { + public void onDisplayAdded(int id) {} + public void onDisplayRemoved(int id) {} + public void onDisplayChanged(int id) { if (Build.VERSION.SDK_INT < 34) screenSize(); } + }; + + public CapturePlatform(Context context, boolean audioRequested) { + this.context = context.getApplicationContext(); + this.audioRequested = audioRequested; + screenSize(); + texture.setOnFrameAvailableListener(ignored -> { + synchronized (this) { if (!closed) { frame = true; notifyAll(); } } + }, AppRuntimeService.main); + AppRuntimeService.main.post(() -> { + synchronized (this) { + if (closed) return; + service = AppRuntimeService.instance; + if (service == null) { fail("App runtime stopped"); return; } + service.captureRequests.add(this); + service.notifyActivity(); + } + }); + } + public SurfaceTexture texture() { return texture; } + public synchronized boolean isClosed() { return closed; } + synchronized boolean needsAudioPermission() { + return audioRequested && !audioDenied && context.checkSelfPermission(android.Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED; + } + synchronized void audioPermission(boolean granted) { audioDenied = !granted; notifyAll(); } + synchronized void presented(MainActivity activity) { permissionActivity = new java.lang.ref.WeakReference<>(activity); } + void grant(int result, Intent data) { + synchronized (this) { permissionActivity = null; } + if (result != Activity.RESULT_OK || data == null) { close(); return; } + synchronized (this) { + if (closed) return; + try { + if (service == null || AppRuntimeService.instance != service) throw new IllegalStateException("App runtime stopped"); + service.projections++; + foreground = true; + service.foreground(); + projection = context.getSystemService(MediaProjectionManager.class).getMediaProjection(result, data); + projection.registerCallback(new MediaProjection.Callback() { + @Override public void onStop() { close(); } + @Override public void onCapturedContentResize(int w, int h) { size(w, h); } + }, AppRuntimeService.main); + notifyAll(); + } catch (RuntimeException failure) { fail(failure.toString()); } + } + } + private void screenSize() { + DisplayMetrics metrics = new DisplayMetrics(); + context.getSystemService(WindowManager.class).getDefaultDisplay().getRealMetrics(metrics); + synchronized (this) { density = metrics.densityDpi; } + size(metrics.widthPixels, metrics.heightPixels); + } + private synchronized void size(int w, int h) { + if (closed || w <= 0 || h <= 0 || (width == w && height == h)) return; + width = w; height = h; + texture.setDefaultBufferSize(w, h); + if (display != null) display.resize(w, h, density); + } + /** Called once on the source worker; the native stop handle wakes this wait. */ + public synchronized void start() throws InterruptedException { + while (!closed && projection == null) wait(); + check(); + if (closed) return; + display = projection.createVirtualDisplay("Piik", width, height, density, + DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, surface, null, AppRuntimeService.main); + if (display == null) throw new IllegalStateException("VirtualDisplay unavailable"); + context.getSystemService(DisplayManager.class).registerDisplayListener(resize, AppRuntimeService.main); + } + /** One coalesced OS notification; Rust owns the latest immutable image. */ + public synchronized long nextFrame() throws InterruptedException { + while (!closed && !frame) wait(); + check(); + if (closed) return 0; + frame = false; + return ((long) width << 32) | (height & 0xffffffffL); + } + /** AudioRecord is constructed here because PlaybackCaptureConfiguration is Java-only. + * Rust owns reads, timestamps, PCM framing and the audio worker lifetime. */ + public synchronized AudioRecord audio() throws InterruptedException { + while (!closed && !audioDenied && (projection == null || needsAudioPermission())) wait(); + check(); + if (closed) throw new IllegalStateException("capture stopped"); + if (audioDenied) throw new IllegalStateException("audio_authorization_cancelled"); + if (audio != null) throw new IllegalStateException("source audio already opened"); + AudioFormat format = new AudioFormat.Builder().setEncoding(AudioFormat.ENCODING_PCM_FLOAT) + .setSampleRate(48000).setChannelMask(AudioFormat.CHANNEL_IN_STEREO).build(); + AudioPlaybackCaptureConfiguration capture = new AudioPlaybackCaptureConfiguration.Builder(projection) + .addMatchingUsage(AudioAttributes.USAGE_MEDIA).addMatchingUsage(AudioAttributes.USAGE_GAME) + .addMatchingUsage(AudioAttributes.USAGE_UNKNOWN).build(); + int buffer = Math.max(960 * 2 * 4 * 2, AudioRecord.getMinBufferSize(48000, AudioFormat.CHANNEL_IN_STEREO, AudioFormat.ENCODING_PCM_FLOAT)); + audio = new AudioRecord.Builder().setAudioFormat(format).setBufferSizeInBytes(buffer) + .setAudioPlaybackCaptureConfig(capture).build(); + audio.startRecording(); + return audio; + } + public synchronized void stopAudio() { + audioDenied = true; notifyAll(); + if (audio != null && audio.getRecordingState() == AudioRecord.RECORDSTATE_RECORDING) audio.stop(); + } + public synchronized void releaseAudio() { + stopAudio(); + if (audio != null) { audio.release(); audio = null; } + } + private synchronized void check() { if (error != null) throw new IllegalStateException(error); } + private synchronized void fail(String message) { error = message; close(); } + @Override public synchronized void close() { + if (closed) return; + closed = true; notifyAll(); + stopAudio(); + context.getSystemService(DisplayManager.class).unregisterDisplayListener(resize); + if (display != null) { display.release(); display = null; } + if (projection != null) { projection.stop(); projection = null; } + AppRuntimeService.main.post(() -> { + if (service != null) { + service.captureRequests.remove(this); + if (foreground) { + service.projections--; foreground = false; + if (AppRuntimeService.instance == service) service.foreground(); + } + service = null; + } + MainActivity activity = permissionActivity == null ? null : permissionActivity.get(); + permissionActivity = null; + if (activity != null) activity.captureClosed(this); + }); + } + /** Only after the native SurfaceTexture reader has detached and joined. */ + public synchronized void dispose() { close(); surface.release(); texture.release(); } +} diff --git a/mobile/android/app/src/main/java/tv/piik/android/MainActivity.java b/mobile/android/app/src/main/java/tv/piik/android/MainActivity.java index 586dba2d6..9b21a6d83 100644 --- a/mobile/android/app/src/main/java/tv/piik/android/MainActivity.java +++ b/mobile/android/app/src/main/java/tv/piik/android/MainActivity.java @@ -10,6 +10,10 @@ public final class MainActivity extends Activity { static MainActivity current; boolean visible, notificationRequest; static final int NOTIFICATIONS = 13; + static final int PROJECTION = 14, SOURCE_AUDIO = 15; + CapturePlatform capture; + boolean projectionRequest, audioRequest; + boolean mediaEntry() { return getIntent().getData() != null && "piik://media".equals(getIntent().getData().toString()); } boolean wakeEntry() { return getIntent().getData() != null && "piik://app".equals(getIntent().getData().toString()); } @@ -22,7 +26,7 @@ public final class MainActivity extends Activity { notificationRequest = state.getBoolean("notificationRequest"); } Uri requested = getIntent().getData(); - if (requested != null && !wakeEntry()) { + if (requested != null && !wakeEntry() && !mediaEntry()) { finish(); return; } @@ -70,6 +74,7 @@ public final class MainActivity extends Activity { } var owner = service.runtime; if (owner == null) return; + if (mediaEntry()) { captureAvailable(); return; } if (wakeEntry()) { finish(); return; @@ -96,11 +101,54 @@ public final class MainActivity extends Activity { notificationRequest = false; startForegroundService(new Intent(this, AppRuntimeService.class)); } + if (request == SOURCE_AUDIO) audioRequest = false; + if (request == SOURCE_AUDIO && capture != null) { + capture.audioPermission(results.length > 0 && results[0] == android.content.pm.PackageManager.PERMISSION_GRANTED); + captureAvailable(); + } + } + + void captureAvailable() { + if (!visible || !mediaEntry()) return; + AppRuntimeService service = AppRuntimeService.instance; + if (service == null) return; + if (capture == null) { + capture = service.captureRequests.poll(); + if (capture != null) capture.presented(this); + } + if (capture == null || capture.isClosed() || projectionRequest || audioRequest) return; + if (capture.needsAudioPermission()) { + audioRequest = true; + requestPermissions(new String[] {android.Manifest.permission.RECORD_AUDIO}, SOURCE_AUDIO); + return; + } + projectionRequest = true; + startActivityForResult(getSystemService(android.media.projection.MediaProjectionManager.class).createScreenCaptureIntent(), PROJECTION); + } + void captureClosed(CapturePlatform owner) { + if (capture != owner) return; + if (projectionRequest) finishActivity(PROJECTION); + capture = null; + finish(); + } + @Override protected void onActivityResult(int request, int result, Intent data) { + super.onActivityResult(request, result, data); + if (request != PROJECTION) return; + projectionRequest = false; + CapturePlatform owner = capture; + capture = null; + if (owner != null) { + AppRuntimeService service = AppRuntimeService.instance; + if (service != null) service.captureRequests.remove(owner); + owner.grant(result, data); + } + finish(); } @Override protected void onDestroy() { if (current == this) current = null; + if (capture != null && isFinishing()) capture.close(); super.onDestroy(); } diff --git a/prototype/channel-android/Cargo.lock b/prototype/channel-android/Cargo.lock index ccb4f1a66..0ffddb988 100644 --- a/prototype/channel-android/Cargo.lock +++ b/prototype/channel-android/Cargo.lock @@ -82,6 +82,21 @@ dependencies = [ "password-hash", ] +[[package]] +name = "ashpd" +version = "0.13.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb8421aaa9644a5faf26735f258b669b15f063313ef8f8e2bdb28912a1a6f111" +dependencies = [ + "enumflags2", + "futures-util", + "getrandom 0.4.3", + "serde", + "serde_repr", + "tokio", + "zbus", +] + [[package]] name = "asn1-rs" version = "0.6.2" @@ -173,6 +188,17 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "async-recursion" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f8abc12baad266b1c8cec146854c195b5864b4221d4b2ca7296a7ae82d9e451" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "async-trait" version = "0.1.92" @@ -190,6 +216,12 @@ version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" +[[package]] +name = "atomic_refcell" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21e4227379beff4205943696e6c3e0cd809bacdf3f0edd6e3dd153e2269571a4" + [[package]] name = "attohttpc" version = "0.30.1" @@ -420,6 +452,16 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c" +[[package]] +name = "cfg-expr" +version = "0.20.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ba9e9ec16c447027685b1f897b720e18e9a8afd00bd7332c483537e38086c9f" +dependencies = [ + "smallvec", + "target-lexicon", +] + [[package]] name = "cfg-if" version = "1.0.5" @@ -457,6 +499,23 @@ dependencies = [ "windows-link", ] +[[package]] +name = "cidre" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fde4542e9dfd21498f5366a5ad60963879fd1885743a18980f6dbb27f525895" +dependencies = [ + "cc", + "cidre-macros", + "parking_lot", +] + +[[package]] +name = "cidre-macros" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a85776177a885b3cd2cda74d634cabe7fa05fecfde8ded8779c0b34110a44dcb" + [[package]] name = "cipher" version = "0.4.4" @@ -569,6 +628,25 @@ dependencies = [ "rustc_version", ] +[[package]] +name = "crossbeam-deque" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" +dependencies = [ + "crossbeam-utils", +] + [[package]] name = "crossbeam-utils" version = "0.8.23" @@ -797,6 +875,33 @@ version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" +[[package]] +name = "endi" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" + +[[package]] +name = "enumflags2" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef" +dependencies = [ + "enumflags2_derive", + "serde", +] + +[[package]] +name = "enumflags2_derive" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "equivalent" version = "1.0.3" @@ -1078,6 +1183,209 @@ dependencies = [ "polyval", ] +[[package]] +name = "gio-sys" +version = "0.21.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0071fe88dba8e40086c8ff9bbb62622999f49628344b1d1bf490a48a29d80f22" +dependencies = [ + "glib-sys", + "gobject-sys", + "libc", + "system-deps", + "windows-sys 0.52.0", +] + +[[package]] +name = "glib" +version = "0.21.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16de123c2e6c90ce3b573b7330de19be649080ec612033d397d72da265f1bd8b" +dependencies = [ + "bitflags 2.13.2", + "futures-channel", + "futures-core", + "futures-executor", + "futures-task", + "futures-util", + "gio-sys", + "glib-macros", + "glib-sys", + "gobject-sys", + "libc", + "memchr", + "smallvec", +] + +[[package]] +name = "glib-macros" +version = "0.21.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf59b675301228a696fe01c3073974643365080a76cc3ed5bc2cbc466ad87f17" +dependencies = [ + "heck", + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "glib-sys" +version = "0.21.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d95e1a3a19ae464a7286e14af9a90683c64d70c02532d88d87ce95056af3e6c" +dependencies = [ + "libc", + "system-deps", +] + +[[package]] +name = "glow" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5e5ea60d70410161c8bf5da3fdfeaa1c72ed2c15f8bbb9d19fe3a4fad085f08" +dependencies = [ + "js-sys", + "slotmap", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "gobject-sys" +version = "0.21.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2dca35da0d19a18f4575f3cb99fe1c9e029a2941af5662f326f738a21edaf294" +dependencies = [ + "glib-sys", + "libc", + "system-deps", +] + +[[package]] +name = "gstreamer" +version = "0.24.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e8251db223ca38d9aefaf3d19f6f11581a9123cd12dacebd8b9e182da965023" +dependencies = [ + "cfg-if", + "futures-channel", + "futures-core", + "futures-util", + "glib", + "gstreamer-sys", + "itertools", + "kstring", + "libc", + "muldiv", + "num-integer", + "num-rational", + "option-operations", + "pastey", + "pin-project-lite", + "smallvec", + "thiserror 2.0.21", +] + +[[package]] +name = "gstreamer-app" +version = "0.24.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3da7017b2a2fa5cdf9123b1603947ea24174f6d8cea0ea673411df824c811921" +dependencies = [ + "futures-core", + "futures-sink", + "glib", + "gstreamer", + "gstreamer-app-sys", + "gstreamer-base", + "libc", +] + +[[package]] +name = "gstreamer-app-sys" +version = "0.24.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fa9f1b12b546aea543c15a0fdbc5a53617902a74f6d357a32b6a9fb4bc4725c" +dependencies = [ + "glib-sys", + "gstreamer-base-sys", + "gstreamer-sys", + "libc", + "system-deps", +] + +[[package]] +name = "gstreamer-base" +version = "0.24.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9375f9a12120a8ee17b765c816c9b23861ce258def77b0ee40a05acb00c74972" +dependencies = [ + "atomic_refcell", + "cfg-if", + "glib", + "gstreamer", + "gstreamer-base-sys", + "libc", +] + +[[package]] +name = "gstreamer-base-sys" +version = "0.24.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b844f3559b6ab0379b4b771261643783ae4e0ffa71d5f5f46e33b7acf66b752" +dependencies = [ + "glib-sys", + "gobject-sys", + "gstreamer-sys", + "libc", + "system-deps", +] + +[[package]] +name = "gstreamer-sys" +version = "0.24.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5d37c1a599ae57b8186948bd5699f2dbfc044baea9d400228b489a85bcf2759" +dependencies = [ + "cfg-if", + "glib-sys", + "gobject-sys", + "libc", + "system-deps", +] + +[[package]] +name = "gstreamer-video" +version = "0.24.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72d9ba5295b206563a990a087c6541d57f650dcd4be4ca8a5a149a758e8df8a0" +dependencies = [ + "cfg-if", + "futures-channel", + "glib", + "gstreamer", + "gstreamer-base", + "gstreamer-video-sys", + "libc", + "thiserror 2.0.21", +] + +[[package]] +name = "gstreamer-video-sys" +version = "0.24.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20236fa412d7a50e59aa234b46828a99e3e5f06c4f80d271a49ecd2a1d3bfcbe" +dependencies = [ + "glib-sys", + "gobject-sys", + "gstreamer-base-sys", + "gstreamer-sys", + "libc", + "system-deps", +] + [[package]] name = "h2" version = "0.4.20" @@ -1446,6 +1754,15 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + [[package]] name = "itoa" version = "1.0.18" @@ -1537,6 +1854,25 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "khronos-egl" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6aae1df220ece3c0ada96b8153459b67eebe9ae9212258bb0134ae60416fdf76" +dependencies = [ + "libc", + "pkg-config", +] + +[[package]] +name = "kstring" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "558bf9508a558512042d3095138b1f7b8fe90c5467d94f9f1da28b3731c5dbd1" +dependencies = [ + "static_assertions", +] + [[package]] name = "lazy_static" version = "1.5.1" @@ -1581,6 +1917,15 @@ version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + [[package]] name = "log" version = "0.4.34" @@ -1679,6 +2024,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "muldiv" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "956787520e75e9bd233246045d19f42fb73242759cc57fba9611d940ae96d4b0" + [[package]] name = "munge" version = "0.4.7" @@ -1753,12 +2104,36 @@ dependencies = [ "slotmap", ] +[[package]] +name = "ndk" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4" +dependencies = [ + "bitflags 2.13.2", + "jni-sys 0.3.1", + "log", + "ndk-sys", + "num_enum", + "raw-window-handle", + "thiserror 1.0.69", +] + [[package]] name = "ndk-context" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" +[[package]] +name = "ndk-sys" +version = "0.6.0+11769913" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873" +dependencies = [ + "jni-sys 0.3.1", +] + [[package]] name = "netdev" version = "0.46.3" @@ -1938,6 +2313,16 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-rational" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" +dependencies = [ + "num-integer", + "num-traits", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -2108,12 +2493,54 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" +[[package]] +name = "option-operations" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aca39cf52b03268400c16eeb9b56382ea3c3353409309b63f5c8f0b1faf42754" +dependencies = [ + "pastey", +] + +[[package]] +name = "ordered-stream" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50" +dependencies = [ + "futures-core", + "pin-project-lite", +] + [[package]] name = "parking" version = "2.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + [[package]] name = "password-hash" version = "0.5.0" @@ -2125,6 +2552,12 @@ dependencies = [ "subtle", ] +[[package]] +name = "pastey" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" + [[package]] name = "pem" version = "3.0.6" @@ -2183,11 +2616,21 @@ version = "0.1.0" dependencies = [ "aes-gcm", "anyhow", + "ashpd", "async-trait", "base64 0.22.1", + "cidre", "futures-util", "getrandom 0.3.4", + "glow", + "gstreamer", + "gstreamer-app", + "gstreamer-video", + "jni 0.22.4", + "khronos-egl", "libc", + "ndk", + "ndk-context", "netwatch", "objc2-app-kit", "objc2-application-services", @@ -2195,9 +2638,12 @@ dependencies = [ "objc2-core-graphics", "piik-channel-core", "portmapper", + "reis", "rtc", + "rustix", "rustls", "rustls-platform-verifier", + "rusty-opus", "serde", "serde_json", "sha2", @@ -2206,8 +2652,10 @@ dependencies = [ "tokio-tungstenite", "uuid", "vigem-rust", + "wasapi", "webrtc", "windows", + "windows-capture", "windows-core", ] @@ -2227,7 +2675,6 @@ dependencies = [ "ring", "rtc", "rusqlite", - "rustix", "rustls", "serde", "serde_json", @@ -2512,6 +2959,32 @@ version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" +[[package]] +name = "raw-window-handle" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539" + +[[package]] +name = "rayon" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + [[package]] name = "rcgen" version = "0.14.10" @@ -2526,6 +2999,15 @@ dependencies = [ "yasna", ] +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags 2.13.2", +] + [[package]] name = "redox_users" version = "0.5.3" @@ -2553,6 +3035,17 @@ version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" +[[package]] +name = "reis" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b967ec6489a42067a20724f11987bb96178ea796873cbe1afd25fb93ee6f85f" +dependencies = [ + "enumflags2", + "log", + "rustix", +] + [[package]] name = "rend" version = "0.5.4" @@ -2980,6 +3473,12 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" +[[package]] +name = "rusty-opus" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46604e6809c06441da1cfdde1f0cc25a4f2bf42c7d005aa387c2875c02d78762" + [[package]] name = "ryu" version = "1.0.23" @@ -3016,6 +3515,12 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294" +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + [[package]] name = "security-framework" version = "3.7.0" @@ -3105,6 +3610,26 @@ dependencies = [ "serde_core", ] +[[package]] +name = "serde_repr" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_spanned" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c" +dependencies = [ + "serde_core", +] + [[package]] name = "serde_urlencoded" version = "0.7.1" @@ -3253,6 +3778,12 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + [[package]] name = "substring" version = "1.4.5" @@ -3318,6 +3849,38 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "system-deps" +version = "7.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "396a35feb67335377e0251fcbc1092fc85c484bd4e3a7a54319399da127796e7" +dependencies = [ + "cfg-expr", + "heck", + "pkg-config", + "toml", + "version-compare", +] + +[[package]] +name = "target-lexicon" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca" + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.3.4", + "once_cell", + "rustix", + "windows-sys 0.52.0", +] + [[package]] name = "thiserror" version = "1.0.69" @@ -3426,6 +3989,7 @@ dependencies = [ "signal-hook-registry", "socket2", "tokio-macros", + "tracing", "windows-sys 0.61.2", ] @@ -3481,6 +4045,21 @@ dependencies = [ "tokio", ] +[[package]] +name = "toml" +version = "1.1.8+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20489e00e4d8741d6be680764cc12e270655e375a20d1011e844a9c3379e678d" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + [[package]] name = "toml_datetime" version = "1.1.2+spec-1.1.0" @@ -3511,6 +4090,12 @@ dependencies = [ "winnow", ] +[[package]] +name = "toml_writer" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770" + [[package]] name = "tower" version = "0.5.3" @@ -3656,6 +4241,17 @@ version = "1.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" +[[package]] +name = "uds_windows" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" +dependencies = [ + "memoffset", + "tempfile", + "windows-sys 0.61.2", +] + [[package]] name = "unicase" version = "2.10.0" @@ -3737,6 +4333,12 @@ version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" +[[package]] +name = "version-compare" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03c2856837ef78f57382f06b2b8563a2f512f7185d732608fd9176cb3b8edf0e" + [[package]] name = "version_check" version = "0.9.5" @@ -3773,6 +4375,19 @@ dependencies = [ "try-lock", ] +[[package]] +name = "wasapi" +version = "0.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b5f8804a710cf7a18b07610225abb127e562f3249a1f3ed88a6f045c5444910" +dependencies = [ + "log", + "num-integer", + "thiserror 2.0.21", + "windows", + "windows-core", +] + [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" @@ -3950,6 +4565,19 @@ dependencies = [ "windows-numerics", ] +[[package]] +name = "windows-capture" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09046acbe9b6d039cde50e8c8178d95bb0f9b33ed7feccc4465dadc5404b31b4" +dependencies = [ + "parking_lot", + "rayon", + "thiserror 2.0.21", + "windows", + "windows-future", +] + [[package]] name = "windows-collections" version = "0.3.2" @@ -4315,6 +4943,71 @@ dependencies = [ "synstructure 0.14.0", ] +[[package]] +name = "zbus" +version = "5.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5db4be7c075cb421e4b7ee645541604239bd243ba7c357511f4ff3a74b555907" +dependencies = [ + "async-broadcast", + "async-recursion", + "async-trait", + "enumflags2", + "event-listener", + "futures-core", + "futures-lite", + "hex", + "libc", + "ordered-stream", + "rustix", + "serde", + "serde_repr", + "tokio", + "tracing", + "uds_windows", + "uuid", + "windows-sys 0.61.2", + "winnow", + "zbus_macros", + "zbus_names", + "zvariant", +] + +[[package]] +name = "zbus_macros" +version = "5.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.9", + "zbus_names", + "zvariant", + "zvariant_utils", +] + +[[package]] +name = "zbus_names" +version = "4.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812a12be4ead7a59e18ea8f047d08add0066b73bc62fc1467066a2472ae088dd" +dependencies = [ + "serde", + "winnow", + "zvariant", +] + +[[package]] +name = "zcheapstr" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "939f186d9ecebe044315a5cb6d6f78568bbc21152adc954d5a0c2f58bdbc9920" +dependencies = [ + "serde", +] + [[package]] name = "zerocopy" version = "0.8.63" @@ -4400,3 +5093,44 @@ name = "zmij" version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zvariant" +version = "5.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80bf6d6cd6a4b601acb64cfb8284cdc643fcfa75ef26ae3c46ec8aa4e8a1fbb7" +dependencies = [ + "endi", + "enumflags2", + "serde", + "winnow", + "zcheapstr", + "zvariant_derive", + "zvariant_utils", +] + +[[package]] +name = "zvariant_derive" +version = "5.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef2672456ba1cb54b5eaec136e63135b3c7495fb938e53b28a62e633496d486d" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.9", + "zvariant_utils", +] + +[[package]] +name = "zvariant_utils" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bad0294361a320b694a328460dc73add56c306150f5cb6bfafc44446120008a3" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "syn 3.0.9", + "winnow", +] diff --git a/prototype/channel-android/Cargo.toml b/prototype/channel-android/Cargo.toml index f02710262..db78d1d9b 100644 --- a/prototype/channel-android/Cargo.toml +++ b/prototype/channel-android/Cargo.toml @@ -15,7 +15,7 @@ anyhow = "1" jni = "0.22" ndk-context = "0.1" rustls-platform-verifier = "=0.7.1" -piik-channel-prototype = { path = "../channel-server" } +piik-channel-prototype = { path = "../channel-server", features = ["capture"] } tokio = { version = "1", features = ["rt-multi-thread", "sync", "net"] } # Workspace-root patch; match channel-native and channel-server. diff --git a/prototype/channel-native/Cargo.lock b/prototype/channel-native/Cargo.lock index f99a073ff..6ad853c82 100644 --- a/prototype/channel-native/Cargo.lock +++ b/prototype/channel-native/Cargo.lock @@ -1123,6 +1123,18 @@ dependencies = [ "system-deps", ] +[[package]] +name = "glow" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5e5ea60d70410161c8bf5da3fdfeaa1c72ed2c15f8bbb9d19fe3a4fad085f08" +dependencies = [ + "js-sys", + "slotmap", + "wasm-bindgen", + "web-sys", +] + [[package]] name = "gobject-sys" version = "0.21.5" @@ -1702,6 +1714,16 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "khronos-egl" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6aae1df220ece3c0ada96b8153459b67eebe9ae9212258bb0134ae60416fdf76" +dependencies = [ + "libc", + "pkg-config", +] + [[package]] name = "kstring" version = "2.0.2" @@ -1911,12 +1933,36 @@ dependencies = [ "slotmap", ] +[[package]] +name = "ndk" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4" +dependencies = [ + "bitflags 2.13.2", + "jni-sys 0.3.1", + "log", + "ndk-sys", + "num_enum", + "raw-window-handle", + "thiserror 1.0.69", +] + [[package]] name = "ndk-context" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" +[[package]] +name = "ndk-sys" +version = "0.6.0+11769913" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873" +dependencies = [ + "jni-sys 0.3.1", +] + [[package]] name = "netdev" version = "0.46.3" @@ -2387,10 +2433,15 @@ dependencies = [ "cidre", "futures-util", "getrandom 0.3.4", + "glow", "gstreamer", "gstreamer-app", "gstreamer-video", + "jni 0.22.4", + "khronos-egl", "libc", + "ndk", + "ndk-context", "netwatch", "objc2-app-kit", "objc2-application-services", @@ -2693,6 +2744,12 @@ version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" +[[package]] +name = "raw-window-handle" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539" + [[package]] name = "rayon" version = "1.12.0" diff --git a/prototype/channel-native/Cargo.toml b/prototype/channel-native/Cargo.toml index 4c1a5aac9..15d9fc3cc 100644 --- a/prototype/channel-native/Cargo.toml +++ b/prototype/channel-native/Cargo.toml @@ -10,7 +10,7 @@ default-run = "piik-channel-native" [features] default = ["capture"] -capture = ["dep:ashpd", "dep:reis", "dep:rustix", "dep:gst", "dep:gst-app", "dep:gst-video", "dep:cidre", "dep:windows-capture", "dep:wasapi", "dep:rusty-opus"] +capture = ["dep:ashpd", "dep:reis", "dep:gst", "dep:gst-app", "dep:gst-video", "dep:cidre", "dep:windows-capture", "dep:wasapi", "dep:rusty-opus", "dep:ndk", "dep:ndk-context", "dep:jni", "dep:khronos-egl", "dep:glow"] [dependencies] piik-channel-core = { path = "../channel-core", features = ["sqlite"] } @@ -33,9 +33,18 @@ sha2 = "=0.10.9" subtle = "=2.6.1" [target.'cfg(target_os = "android")'.dependencies] +ndk = { version = "=0.9.0", optional = true, features = ["api-level-29", "media"] } +ndk-context = { version = "0.1", optional = true } +jni = { version = "0.22", optional = true } +khronos-egl = { version = "=6.0.0", optional = true, features = ["static", "no-pkg-config"] } +glow = { version = "=0.16.0", optional = true } +libc = "0.2" rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] } rustls-platform-verifier = "=0.7.1" +[target.'cfg(unix)'.dependencies] +rustix = { version = "1", features = ["fs"] } + [target.'cfg(target_os = "macos")'.dependencies] cidre = { version = "=0.29.0", optional = true, default-features = false, features = ["sc", "vt", "async", "io_surface", "macos_13_0"] } libc = "0.2" @@ -47,12 +56,12 @@ objc2-app-kit = { version = "=0.3.2", default-features = false, features = ["std [target.'cfg(target_os = "linux")'.dependencies] ashpd = { version = "=0.13.13", optional = true, default-features = false, features = ["tokio", "screencast", "remote_desktop"] } reis = { version = "=0.7.1", optional = true } -rustix = { version = "1", optional = true, features = ["time", "net"] } +rustix = { version = "1", features = ["time", "net"] } gst = { package = "gstreamer", version = "=0.24.5", optional = true, features = ["v1_20"] } gst-app = { package = "gstreamer-app", version = "=0.24.5", optional = true, features = ["v1_20"] } gst-video = { package = "gstreamer-video", version = "=0.24.5", optional = true, features = ["v1_20"] } -[target.'cfg(any(target_os = "windows", target_os = "macos", target_os = "linux"))'.dependencies] +[target.'cfg(any(target_os = "windows", target_os = "macos", target_os = "linux", target_os = "android"))'.dependencies] rusty-opus = { version = "=1.0.2", optional = true } # Remove after upstream webrtc-rs/rtc#296 and #298 are released; see README.md. diff --git a/prototype/channel-native/README.md b/prototype/channel-native/README.md index 50cd74133..cb7b046d3 100644 --- a/prototype/channel-native/README.md +++ b/prototype/channel-native/README.md @@ -54,6 +54,11 @@ owns platform acceptance. `ashpd` and the `reis` input bindings use MIT licensin the GStreamer Rust bindings use MIT/Apache-2.0. GStreamer and system-installed plugins retain their own licenses. +Android uses MediaProjection and independent NDK MediaCodec encodings through +the Rust JNI, NDK and EGL bindings. The [Android runtime](../../mobile/README.md) +owns the system-browser shell and build inputs; source permission and capture +retain the same selecting-page lease. + The App's source picker starts that producer on its existing Native endpoint. Local and received sources share the same encoded outputs and room routes. Each local output packetizes complete access units on its own stable RTP clock; diff --git a/prototype/channel-native/src/capture/android/audio.rs b/prototype/channel-native/src/capture/android/audio.rs new file mode 100644 index 000000000..4636683f1 --- /dev/null +++ b/prototype/channel-native/src/capture/android/audio.rs @@ -0,0 +1,198 @@ +use super::{frames::Clock, platform::Platform}; +use crate::capture::AudioFrame; +use anyhow::{anyhow, ensure, Context as _, Result}; +use jni::{jni_sig, jni_str}; +use std::{ + sync::{ + atomic::{AtomicBool, Ordering}, + Arc, + }, + thread, +}; +use tokio::sync::{mpsc, oneshot}; + +#[derive(Clone)] +pub struct AudioControl { + stopped: Arc, + platform: Platform, +} +impl AudioControl { + pub fn stop(&self) { + self.stopped.store(true, Ordering::Release); + if let Err(error) = self.platform.with(|env, object| { + env.call_method(object, jni_str!("stopAudio"), jni_sig!(() -> void), &[])?; + Ok(()) + }) { + eprintln!("Android audio stop: {error:#}"); + } + } + pub fn is_stopped(&self) -> bool { + self.stopped.load(Ordering::Acquire) + } +} +pub struct AudioCapture { + control: AudioControl, + ready: Option>>, + frames: mpsc::Receiver, + completion: Option>>, + thread: Option>, +} +impl AudioCapture { + pub(super) fn start(platform: Platform, clock: Clock) -> Result { + let control = AudioControl { + stopped: Arc::new(AtomicBool::new(false)), + platform, + }; + let worker = control.clone(); + let (frames, receiver) = mpsc::channel(2); + let (ready, started) = oneshot::channel(); + let (complete, completion) = oneshot::channel(); + let thread = thread::Builder::new() + .name("piik-android-audio".into()) + .spawn(move || { + let mut ready = Some(ready); + let result = run(&worker, clock, frames, &mut ready); + if let Some(ready) = ready { + let _ = ready.send(Err(anyhow!(result + .as_ref() + .err() + .map(|e| format!("{e:#}")) + .unwrap_or_else(|| "audio stopped before startup".into())))); + } + worker.stopped.store(true, Ordering::Release); + let released = worker.platform.with(|env, object| { + env.call_method(object, jni_str!("releaseAudio"), jni_sig!(() -> void), &[])?; + Ok(()) + }); + let _ = complete.send(result.and(released)); + })?; + Ok(Self { + control, + ready: Some(started), + frames: receiver, + completion: Some(completion), + thread: Some(thread), + }) + } + pub fn control(&self) -> AudioControl { + self.control.clone() + } + pub async fn ready(&mut self) -> Result<()> { + self.ready + .take() + .context("audio startup already observed")? + .await + .context("audio stopped during startup")? + } + pub async fn recv(&mut self) -> Option> { + match self.frames.recv().await { + Some(frame) => Some(Ok(frame)), + None => self.completion.take()?.await.ok()?.err().map(Err), + } + } + pub fn stop(mut self) -> Result<()> { + self.control.stop(); + self.join() + } + fn join(&mut self) -> Result<()> { + self.thread.take().map_or(Ok(()), |thread| { + thread.join().map_err(|_| anyhow!("audio worker panicked")) + }) + } +} +impl Drop for AudioCapture { + fn drop(&mut self) { + self.control.stop(); + if let Err(error) = self.join() { + eprintln!("Android audio cleanup: {error:#}"); + } + } +} + +fn run( + control: &AudioControl, + clock: Clock, + frames: mpsc::Sender, + ready: &mut Option>>, +) -> Result<()> { + control.platform.with(|env, object| { + let record = env + .call_method( + object, + jni_str!("audio"), + jni_sig!(() -> android.media.AudioRecord), + &[], + )? + .l()?; + let timestamp = env.new_object( + jni_str!("android/media/AudioTimestamp"), + jni_sig!(() -> void), + &[], + )?; + if let Some(ready) = ready.take() { + let _ = ready.send(Ok(())); + } + let mut samples = vec![0.0f32; 960 * 2]; + let mut filled = 0usize; + let mut position = 0i64; + while !control.is_stopped() { + // Java uses this direct view only during the synchronous read call. + let count = env.with_local_frame(8, |env| -> Result { + let bytes = unsafe { + env.new_direct_byte_buffer( + samples.as_mut_ptr().add(filled).cast(), + (samples.len() - filled) * 4, + ) + }?; + Ok(env + .call_method( + &record, + jni_str!("read"), + jni_sig!((java.nio.ByteBuffer,int,int) -> int), + &[ + (&bytes).into(), + (((samples.len() - filled) * 4) as i32).into(), + 0.into(), + ], + )? + .i()?) + })?; + if control.is_stopped() { + break; + } + ensure!( + count > 0 && count % 8 == 0, + "AudioRecord read failed: {count}" + ); + filled += count as usize / 4; + position += i64::from(count) / 8; + if filled < samples.len() { + continue; + } + let status = env + .call_method( + &record, + jni_str!("getTimestamp"), + jni_sig!((android.media.AudioTimestamp,int) -> int), + &[(×tamp).into(), 0.into()], + )? + .i()?; + if status == 0 { + let capture_position = env + .get_field(×tamp, jni_str!("framePosition"), jni_sig!(long))? + .j()?; + let nanos = env + .get_field(×tamp, jni_str!("nanoTime"), jni_sig!(long))? + .j()?; + let first = nanos + (position - 960 - capture_position) * 1_000_000_000 / 48_000; + // Source timestamps advance even when the existing bounded PCM queue is full. + let _ = frames.try_send(AudioFrame { + samples: samples.clone(), + presentation_time: clock.project(first), + }); + } + filled = 0; + } + Ok(()) + }) +} diff --git a/prototype/channel-native/src/capture/android/encoding.rs b/prototype/channel-native/src/capture/android/encoding.rs new file mode 100644 index 000000000..3cef1a08a --- /dev/null +++ b/prototype/channel-native/src/capture/android/encoding.rs @@ -0,0 +1,419 @@ +//! One MediaCodec/GL owner per encoding; one submitted image and two complete AUs. +use super::{ + frames::{Clock, Frames, RawFrame}, + graphics::Graphics, +}; +use crate::capture::{EncodedFrame, Settings}; +use anyhow::{anyhow, ensure, Result}; +use ndk::media::{ + media_codec::{DequeuedOutputBufferInfoResult, MediaCodec, MediaCodecDirection}, + media_format::MediaFormat, +}; +use std::{ + collections::VecDeque, + sync::{Arc, Mutex}, + thread, + time::Duration, +}; +use tokio::sync::Notify; + +#[derive(Default)] +struct State { + stop: bool, + done: bool, + error: Option, + force: bool, + bitrate: Option, + output: VecDeque, +} +struct Shared { + state: Mutex, + changed: Notify, + available: Notify, +} +impl Shared { + fn stop(&self) { + let mut state = self.state.lock().unwrap(); + state.stop = true; + state.output.clear(); + drop(state); + self.changed.notify_waiters(); + self.available.notify_waiters(); + } + fn finish(&self, result: &Result<()>) { + let mut state = self.state.lock().unwrap(); + state.stop = true; + state.done = true; + state.error = result.as_ref().err().map(|error| format!("{error:#}")); + state.output.clear(); + drop(state); + self.changed.notify_waiters(); + self.available.notify_waiters(); + } +} +#[derive(Clone)] +pub struct EncodingControl(Arc); +impl EncodingControl { + pub fn stop(&self) { + self.0.stop(); + } + pub fn is_stopped(&self) -> bool { + self.0.state.lock().unwrap().stop + } + pub fn force_keyframe(&self) -> Result<()> { + let mut state = self.0.state.lock().unwrap(); + ensure!(!state.stop, "encoding stopped"); + state.force = true; + drop(state); + self.0.changed.notify_waiters(); + Ok(()) + } + pub fn set_bitrate(&self, bitrate: u32) -> Result<()> { + ensure!(bitrate > 0, "invalid bitrate"); + let mut state = self.0.state.lock().unwrap(); + ensure!(!state.stop, "encoding stopped"); + state.bitrate = Some(bitrate); + drop(state); + self.0.changed.notify_waiters(); + Ok(()) + } +} +pub struct Encoding { + shared: Arc, + thread: Option>>, +} +impl Encoding { + pub(super) fn start(frames: Frames, settings: Settings) -> Result { + settings.validate()?; + ensure!(settings.fps <= i32::MAX as u32, "invalid encoder FPS"); + ensure!( + settings.bitrate <= i32::MAX as u32, + "invalid encoder bitrate" + ); + let runtime = tokio::runtime::Handle::try_current()?; + let shared = Arc::new(Shared { + state: Mutex::new(State { + force: true, + ..State::default() + }), + changed: Notify::new(), + available: Notify::new(), + }); + let worker = shared.clone(); + let thread = thread::Builder::new() + .name("piik-android-encoding".into()) + .spawn(move || { + let result = run(&worker, frames, settings, &runtime); + worker.finish(&result); + result + })?; + Ok(Self { + shared, + thread: Some(thread), + }) + } + pub fn control(&self) -> EncodingControl { + EncodingControl(self.shared.clone()) + } + pub async fn recv(&mut self) -> Option> { + loop { + let ready = self.shared.available.notified(); + tokio::pin!(ready); + ready.as_mut().enable(); + { + let mut state = self.shared.state.lock().unwrap(); + if let Some(frame) = state.output.pop_front() { + self.shared.changed.notify_waiters(); + return Some(Ok(frame)); + } + if state.done { + return state.error.take().map(|error| Err(anyhow!(error))); + } + } + ready.await; + } + } + /// Call from a blocking owner, outside media/input locks. + pub fn stop(mut self) -> Result<()> { + self.shared.stop(); + self.thread + .take() + .unwrap() + .join() + .map_err(|_| anyhow!("encoding worker panicked"))? + } +} + +struct Codec { + // Destroy the window EGL surface before releasing the codec's native window. + graphics: Graphics, + _window: ndk::native_window::NativeWindow, + codec: MediaCodec, + size: (u32, u32), + config: Vec, +} +impl Codec { + fn new(frames: &Frames, settings: Settings) -> Result { + let codec = MediaCodec::from_encoder_type("video/avc") + .ok_or_else(|| anyhow!("H264 encoder unavailable"))?; + let mut format = MediaFormat::new(); + format.set_str("mime", "video/avc"); + for (key, value) in [ + ("width", settings.width as i32), + ("height", settings.height as i32), + ("frame-rate", settings.fps as i32), + ("bitrate", settings.bitrate as i32), + ("color-format", 0x7F000789), + ("i-frame-interval", 2), + ("bitrate-mode", 2), + ("max-bframes", 0), + ("priority", 0), + ] { + format.set_i32(key, value); + } + codec.configure(&format, None, MediaCodecDirection::Encoder)?; + let window = codec.create_input_surface()?; + let graphics = Graphics::new(frames.display.clone(), Some(&window), false)?; + codec.start()?; + Ok(Self { + graphics, + _window: window, + codec, + size: (settings.width, settings.height), + config: Vec::new(), + }) + } + fn bitrate(&self, value: u32) -> Result<()> { + let mut params = MediaFormat::new(); + params.set_i32("video-bitrate", value.try_into()?); + self.codec.set_parameters(params)?; + Ok(()) + } + fn encode( + &mut self, + shared: &Shared, + frames: &Frames, + raw: &RawFrame, + nanos: i64, + force: bool, + ) -> Result> { + if force { + let mut params = MediaFormat::new(); + params.set_i32("request-sync", 0); + self.codec.set_parameters(params)?; + } + self.graphics.submit(&raw.image, self.size, nanos)?; + let mut bytes = Vec::new(); + let mut keyframe = false; + loop { + if shared.state.lock().unwrap().stop || frames.is_stopped() { + return Ok(None); + } + match self + .codec + .dequeue_output_buffer(Duration::from_millis(10))? + { + DequeuedOutputBufferInfoResult::OutputFormatChanged => { + let format = self.codec.output_format(); + self.config.clear(); + for key in ["csd-0", "csd-1"] { + if let Some(data) = format.buffer(key) { + self.config.extend_from_slice(data); + } + } + } + DequeuedOutputBufferInfoResult::Buffer(buffer) => { + let info = buffer.info(); + let offset: usize = info.offset().try_into()?; + let length: usize = info.size().try_into()?; + let flags = info.flags(); + let pts = info.presentation_time_us(); + let data = buffer + .buffer() + .get(offset..offset + length) + .ok_or_else(|| anyhow!("invalid codec buffer range"))?; + if flags & 2 != 0 { + self.config = data.to_vec(); + } else { + bytes.extend_from_slice(data); + keyframe |= flags & 1 != 0; + } + self.codec.release_output_buffer(buffer, false)?; + ensure!( + bytes.len() + if keyframe { self.config.len() } else { 0 } + <= 4 * 1024 * 1024, + "H264 access unit exceeds source limit" + ); + if flags & 2 != 0 || flags & 8 != 0 { + continue; + } + ensure!(flags & 4 == 0, "unexpected encoder end of stream"); + if bytes.is_empty() { + return Ok(None); + } + ensure!( + bytes.starts_with(&[0, 0, 1]) || bytes.starts_with(&[0, 0, 0, 1]), + "encoder did not produce Annex B H264" + ); + if keyframe && !self.config.is_empty() { + let mut complete = self.config.clone(); + complete.extend(bytes); + bytes = complete; + } + return Ok(Some(EncodedFrame { + bytes, + keyframe, + presentation_time: frames.clock.project(pts * 1000), + })); + } + _ => {} + } + } + } +} +impl Drop for Codec { + fn drop(&mut self) { + let _ = self.codec.stop(); + } +} + +fn run( + shared: &Shared, + frames: Frames, + settings: Settings, + runtime: &tokio::runtime::Handle, +) -> Result<()> { + let mut codec: Option = None; + let mut last = None; + let mut bitrate = settings.bitrate; + let mut pending_keyframe = true; + let mut cadence = crate::capture::cadence::Cadence::new(settings.fps); + let mut rate = crate::capture::cadence::AdmissionRate::default(); + let mut dropper = crate::capture::frame_dropper::FrameDropper::new(); + dropper.set_rates(bitrate as f32 / 1000., settings.fps as f32); + while let Some(work) = runtime.block_on(next(shared, &frames, last))? { + let (raw, explicit) = match work { + Work::Bitrate(value) => { + bitrate = value; + dropper.set_rates( + value as f32 / 1000., + rate.fps.unwrap_or(settings.fps as f32), + ); + if let Some(codec) = &codec { + codec.bitrate(value)?; + } + continue; + } + Work::Frame(raw, force) => (raw, force), + }; + let fresh = last.is_none_or(|last| raw.nanos > last); + // Explicit local-capture PLI may present the current static image once. + let nanos = if explicit && !fresh { + Clock::now()? + } else { + raw.nanos + }; + last = Some(nanos); + let mut force = explicit || pending_keyframe; + if !force && !cadence.accept(nanos / 100) { + continue; + } + if fresh { + if let Some(fps) = rate.observe(nanos / 100) { + dropper.set_rates(bitrate as f32 / 1000., fps); + } + dropper.leak(rate.fps.unwrap_or(settings.fps as f32).round().max(1.) as u32); + } + if !force && dropper.drop_frame() { + continue; + } + let (w, h) = raw.image.size(); + let fitted = Settings { + bitrate, + ..settings.fitted(w as f64, h as f64) + }; + if codec + .as_ref() + .is_none_or(|codec| codec.size != (fitted.width, fitted.height)) + { + drop(codec.take()); + codec = Some(Codec::new(&frames, fitted)?); + force = true; + } + if let Some(frame) = codec + .as_mut() + .unwrap() + .encode(shared, &frames, &raw, nanos, force)? + { + pending_keyframe = force && !frame.keyframe; + dropper.fill(frame.bytes.len(), !frame.keyframe); + let mut state = shared.state.lock().unwrap(); + if state.stop { + break; + } + state.output.push_back(frame); + drop(state); + shared.available.notify_waiters(); + } else { + pending_keyframe = force; + } + } + Ok(()) +} +impl Drop for Encoding { + fn drop(&mut self) { + self.shared.stop(); + if let Some(thread) = self.thread.take() { + if let Err(error) = thread + .join() + .map_err(|_| anyhow!("encoding worker panicked")) + .and_then(|result| result) + { + eprintln!("Android encoding cleanup: {error:#}"); + } + } + } +} + +enum Work { + Bitrate(u32), + Frame(RawFrame, bool), +} +async fn next(shared: &Shared, frames: &Frames, previous: Option) -> Result> { + loop { + let changed = shared.changed.notified(); + tokio::pin!(changed); + changed.as_mut().enable(); + let (force, has_room) = { + let mut state = shared.state.lock().unwrap(); + if state.stop { + return Ok(None); + } + if let Some(bitrate) = state.bitrate.take() { + return Ok(Some(Work::Bitrate(bitrate))); + } + (state.force, state.output.len() < 2) + }; + if has_room { + tokio::select! { + raw = frames.recv_after(if force { None } else { previous }) => { + let Some(raw) = raw? else { return Ok(None); }; + let mut state = shared.state.lock().unwrap(); + if state.stop { return Ok(None); } + return Ok(Some(Work::Frame(raw, std::mem::take(&mut state.force)))); + }, + _ = &mut changed => {}, + } + } else { + tokio::select! { + _ = frames.stopped() => { + // Preserve the source's existing terminal error without a + // second error/watch owner, even while AU output is full. + frames.recv_after(None).await?; + return Ok(None); + }, + _ = &mut changed => {}, + } + } + } +} diff --git a/prototype/channel-native/src/capture/android/frames.rs b/prototype/channel-native/src/capture/android/frames.rs new file mode 100644 index 000000000..966d03a03 --- /dev/null +++ b/prototype/channel-native/src/capture/android/frames.rs @@ -0,0 +1,111 @@ +use super::graphics::{Display, Image}; +use anyhow::{anyhow, ensure, Result}; +use std::{ + sync::Arc, + time::{Duration, Instant}, +}; +use tokio::sync::watch; + +/// SurfaceFlinger/SurfaceTexture and AudioRecord TIMEBASE_MONOTONIC share this clock. +#[derive(Clone, Copy)] +pub(super) struct Clock { + nanos: i64, + instant: Instant, +} +impl Clock { + pub fn new() -> Result { + Ok(Self { + nanos: Self::now()?, + instant: Instant::now(), + }) + } + pub fn now() -> Result { + let mut time = libc::timespec { + tv_sec: 0, + tv_nsec: 0, + }; + ensure!( + unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut time) } == 0, + "clock_gettime failed" + ); + Ok(time.tv_sec * 1_000_000_000 + time.tv_nsec) + } + pub fn project(self, nanos: i64) -> Instant { + let delta = nanos - self.nanos; + let duration = Duration::from_nanos(delta.unsigned_abs()); + if delta >= 0 { + self.instant + duration + } else { + self.instant - duration + } + } +} + +#[derive(Clone)] +pub(super) struct RawFrame { + pub image: Image, + pub nanos: i64, +} +#[derive(Clone)] +enum State { + Live(Option), + Stopped(Option), +} +#[derive(Clone)] +pub(super) struct Frames { + state: Arc>, + pub display: Arc, + pub clock: Clock, +} +impl Frames { + pub fn new() -> Result { + Ok(Self { + state: Arc::new(watch::channel(State::Live(None)).0), + display: Display::new()?, + clock: Clock::new()?, + }) + } + pub fn stop(&self, error: Option) { + self.state.send_if_modified(|state| { + if matches!(state, State::Stopped(_)) { + return false; + } + *state = State::Stopped(error); + true + }); + } + pub fn is_stopped(&self) -> bool { + matches!(*self.state.borrow(), State::Stopped(_)) + } + pub fn publish(&self, frame: RawFrame) { + self.state.send_if_modified(|state| { + if matches!(state, State::Stopped(_)) { + return false; + } + *state = State::Live(Some(frame)); + true + }); + } + pub async fn recv_after(&self, previous: Option) -> Result> { + let mut changed = self.state.subscribe(); + loop { + match &*changed.borrow_and_update() { + State::Stopped(Some(error)) => return Err(anyhow!(error.clone())), + State::Stopped(None) => return Ok(None), + State::Live(Some(frame)) if previous.is_none_or(|last| frame.nanos > last) => { + return Ok(Some(frame.clone())) + } + _ => {} + } + changed.changed().await?; + } + } + pub async fn stopped(&self) { + let mut changed = self.state.subscribe(); + while !matches!(*changed.borrow_and_update(), State::Stopped(_)) { + if changed.changed().await.is_err() { + break; + } + } + } +} diff --git a/prototype/channel-native/src/capture/android/graphics.rs b/prototype/channel-native/src/capture/android/graphics.rs new file mode 100644 index 000000000..c0b730491 --- /dev/null +++ b/prototype/channel-native/src/capture/android/graphics.rs @@ -0,0 +1,385 @@ +//! EGL contexts never leave their workers. Only completed immutable pixels do. +use anyhow::{anyhow, ensure, Context as _, Result}; +use glow::HasContext; +use khronos_egl as egl; +use ndk::{ + hardware_buffer::{HardwareBuffer, HardwareBufferDesc, HardwareBufferRef, HardwareBufferUsage}, + hardware_buffer_format::HardwareBufferFormat, + native_window::NativeWindow, +}; +use std::{ffi::c_void, sync::Arc}; + +#[link(name = "EGL")] +extern "C" {} + +const EGL: egl::Instance = egl::Instance::new(egl::Static); +const EXTERNAL: u32 = 0x8D65; +const IDENTITY: [f32; 16] = [ + 1., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1., +]; + +pub(super) struct Display(egl::Display); +// EGLDisplay is a process connection, not a current context. EGL permits concurrent +// contexts on one display; the last Arc terminates it after all workers have joined. +unsafe impl Send for Display {} +unsafe impl Sync for Display {} +impl Display { + pub fn new() -> Result> { + let display = + unsafe { EGL.get_display(egl::DEFAULT_DISPLAY) }.context("EGL display unavailable")?; + EGL.initialize(display)?; + Ok(Arc::new(Self(display))) + } +} +impl Drop for Display { + fn drop(&mut self) { + let _ = EGL.terminate(self.0); + } +} + +#[derive(Clone)] +pub(super) struct Image(Arc); +// Allocation is exclusively written by the source context, glFinish completes +// that copy before publication. No mutable image API escapes; AHB retain/release +// is thread-safe. This does not assert Send for any EGL context or MediaCodec. +unsafe impl Send for Image {} +unsafe impl Sync for Image {} +impl Image { + pub fn size(&self) -> (u32, u32) { + let d = self.0.describe(); + (d.width, d.height) + } +} + +pub(super) struct Graphics { + display: Arc, + context: egl::Context, + surface: egl::Surface, + gl: glow::Context, + program: glow::Program, + external: bool, + vao: glow::VertexArray, +} +impl Graphics { + pub fn new( + display: Arc, + window: Option<&NativeWindow>, + external: bool, + ) -> Result { + EGL.bind_api(egl::OPENGL_ES_API)?; + let config = EGL + .choose_first_config( + display.0, + &[ + egl::SURFACE_TYPE, + egl::PBUFFER_BIT | egl::WINDOW_BIT, + egl::RENDERABLE_TYPE, + egl::OPENGL_ES3_BIT, + egl::RED_SIZE, + 8, + egl::GREEN_SIZE, + 8, + egl::BLUE_SIZE, + 8, + 0x3142, + 1, // EGL_RECORDABLE_ANDROID: codec input Surface. + egl::NONE, + ], + )? + .context("recordable EGL config unavailable")?; + let context = EGL.create_context( + display.0, + config, + None, + &[egl::CONTEXT_CLIENT_VERSION, 3, egl::NONE], + )?; + let surface = match window { + Some(window) => unsafe { + EGL.create_window_surface(display.0, config, window.ptr().as_ptr().cast(), None) + }, + None => EGL.create_pbuffer_surface( + display.0, + config, + &[egl::WIDTH, 1, egl::HEIGHT, 1, egl::NONE], + ), + }; + let surface = match surface { + Ok(value) => value, + Err(error) => { + let _ = EGL.destroy_context(display.0, context); + return Err(error.into()); + } + }; + if let Err(error) = EGL.make_current(display.0, Some(surface), Some(surface), Some(context)) + { + let _ = EGL.destroy_surface(display.0, surface); + let _ = EGL.destroy_context(display.0, context); + return Err(error.into()); + } + let gl = unsafe { + glow::Context::from_loader_function(|name| { + EGL.get_proc_address(name) + .map_or(std::ptr::null(), |f| f as *const c_void) + }) + }; + let resources = (|| { + let program = unsafe { gl.create_program().map_err(|e| anyhow!(e))? }; + match unsafe { gl.create_vertex_array() } { + Ok(vao) => Ok((program, vao)), + Err(error) => { + unsafe { + gl.delete_program(program); + } + Err(anyhow!(error)) + } + } + })(); + let (program, vao) = match resources { + Ok(value) => value, + Err(error) => { + let _ = EGL.make_current(display.0, None, None, None); + let _ = EGL.destroy_surface(display.0, surface); + let _ = EGL.destroy_context(display.0, context); + return Err(error); + } + }; + let value = Self { + display, + context, + surface, + gl, + program, + external, + vao, + }; + value.compile()?; + Ok(value) + } + fn compile(&self) -> Result<()> { + let vertex = "#version 300 es\nuniform mat4 transform; out vec2 uv; void main(){ vec2 p=vec2((gl_VertexID<<1)&2,gl_VertexID&2); uv=(transform*vec4(p,0,1)).xy; gl_Position=vec4(p*2.0-1.0,0,1); }"; + let fragment = if self.external { + "#version 300 es\n#extension GL_OES_EGL_image_external_essl3 : require\nprecision mediump float; uniform samplerExternalOES pixels; in vec2 uv; out vec4 color; void main(){color=texture(pixels,uv);}" + } else { + "#version 300 es\nprecision mediump float; uniform sampler2D pixels; in vec2 uv; out vec4 color; void main(){color=texture(pixels,uv);}" + }; + unsafe { + for (kind, text) in [ + (glow::VERTEX_SHADER, vertex), + (glow::FRAGMENT_SHADER, fragment), + ] { + let shader = self.gl.create_shader(kind).map_err(|e| anyhow!(e))?; + self.gl.shader_source(shader, text); + self.gl.compile_shader(shader); + let compiled = self.gl.get_shader_compile_status(shader); + let error = self.gl.get_shader_info_log(shader); + if compiled { + self.gl.attach_shader(self.program, shader); + } + self.gl.delete_shader(shader); + ensure!(compiled, "GL shader: {error}"); + } + self.gl.link_program(self.program); + ensure!( + self.gl.get_program_link_status(self.program), + "GL link: {}", + self.gl.get_program_info_log(self.program) + ); + } + Ok(()) + } + pub fn external_texture(&self) -> Result { + let texture = unsafe { self.gl.create_texture().map_err(|e| anyhow!(e))? }; + Ok(texture) + } + fn import(&self, image: &Image) -> Result<(egl::Image, glow::Texture)> { + type GetBuffer = unsafe extern "system" fn(*const c_void) -> *mut c_void; + type BindImage = unsafe extern "system" fn(u32, *mut c_void); + let get: GetBuffer = unsafe { + std::mem::transmute( + EGL.get_proc_address("eglGetNativeClientBufferANDROID") + .context("EGL native buffer unavailable")?, + ) + }; + let bind: BindImage = unsafe { + std::mem::transmute( + EGL.get_proc_address("glEGLImageTargetTexture2DOES") + .context("GL image import unavailable")?, + ) + }; + let buffer = unsafe { egl::ClientBuffer::from_ptr(get(image.0.as_ptr().cast())) }; + let egl_image = EGL.create_image( + self.display.0, + unsafe { egl::Context::from_ptr(egl::NO_CONTEXT) }, + 0x3140, + buffer, + &[ + egl::IMAGE_PRESERVED as usize, + egl::TRUE as usize, + egl::ATTRIB_NONE, + ], + )?; + let texture = match unsafe { self.gl.create_texture() } { + Ok(texture) => texture, + Err(error) => { + let _ = EGL.destroy_image(self.display.0, egl_image); + return Err(anyhow!(error)); + } + }; + unsafe { + self.gl.bind_texture(glow::TEXTURE_2D, Some(texture)); + bind(glow::TEXTURE_2D, egl_image.as_ptr()); + self.gl.tex_parameter_i32( + glow::TEXTURE_2D, + glow::TEXTURE_MIN_FILTER, + glow::LINEAR as i32, + ); + self.gl.tex_parameter_i32( + glow::TEXTURE_2D, + glow::TEXTURE_MAG_FILTER, + glow::LINEAR as i32, + ); + self.gl.tex_parameter_i32( + glow::TEXTURE_2D, + glow::TEXTURE_WRAP_S, + glow::CLAMP_TO_EDGE as i32, + ); + self.gl.tex_parameter_i32( + glow::TEXTURE_2D, + glow::TEXTURE_WRAP_T, + glow::CLAMP_TO_EDGE as i32, + ); + } + Ok((egl_image, texture)) + } + fn draw(&self, texture: glow::Texture, size: (u32, u32), transform: &[f32; 16]) { + unsafe { + self.gl.viewport(0, 0, size.0 as i32, size.1 as i32); + self.gl.use_program(Some(self.program)); + self.gl.active_texture(glow::TEXTURE0); + self.gl.bind_texture( + if self.external { + EXTERNAL + } else { + glow::TEXTURE_2D + }, + Some(texture), + ); + self.gl.uniform_1_i32( + self.gl + .get_uniform_location(self.program, "pixels") + .as_ref(), + 0, + ); + self.gl.uniform_matrix_4_f32_slice( + self.gl + .get_uniform_location(self.program, "transform") + .as_ref(), + false, + transform, + ); + self.gl.bind_vertex_array(Some(self.vao)); + self.gl.draw_arrays(glow::TRIANGLES, 0, 3); + } + } + pub fn snapshot( + &self, + texture: glow::Texture, + size: (u32, u32), + transform: &[f32; 16], + ) -> Result { + let image = Image(Arc::new(HardwareBuffer::allocate(HardwareBufferDesc { + width: size.0, + height: size.1, + layers: 1, + format: HardwareBufferFormat::R8G8B8A8_UNORM, + usage: HardwareBufferUsage::GPU_COLOR_OUTPUT | HardwareBufferUsage::GPU_SAMPLED_IMAGE, + stride: 0, + })?)); + let (import, destination) = self.import(&image)?; + let framebuffer = match unsafe { self.gl.create_framebuffer() } { + Ok(value) => value, + Err(error) => { + unsafe { + self.gl.delete_texture(destination); + } + let _ = EGL.destroy_image(self.display.0, import); + return Err(anyhow!(error)); + } + }; + let result = (|| { + unsafe { + self.gl + .bind_framebuffer(glow::FRAMEBUFFER, Some(framebuffer)); + self.gl.framebuffer_texture_2d( + glow::FRAMEBUFFER, + glow::COLOR_ATTACHMENT0, + glow::TEXTURE_2D, + Some(destination), + 0, + ); + ensure!( + self.gl.check_framebuffer_status(glow::FRAMEBUFFER) + == glow::FRAMEBUFFER_COMPLETE, + "incomplete source framebuffer" + ); + } + self.draw(texture, size, transform); + unsafe { + self.gl.finish(); + ensure!( + self.gl.get_error() == glow::NO_ERROR, + "source image copy failed" + ); + } + Ok(()) + })(); + unsafe { + self.gl.bind_framebuffer(glow::FRAMEBUFFER, None); + self.gl.delete_framebuffer(framebuffer); + self.gl.delete_texture(destination); + } + EGL.destroy_image(self.display.0, import)?; + result?; + Ok(image) + } + pub fn submit(&self, image: &Image, size: (u32, u32), nanos: i64) -> Result<()> { + let (import, texture) = self.import(image)?; + self.draw(texture, size, &IDENTITY); + type Presentation = unsafe extern "system" fn(*mut c_void, *mut c_void, i64) -> u32; + let result = (|| { + ensure!( + unsafe { self.gl.get_error() } == glow::NO_ERROR, + "encoder image render failed" + ); + let present: Presentation = unsafe { + std::mem::transmute( + EGL.get_proc_address("eglPresentationTimeANDROID") + .context("EGL presentation time unavailable")?, + ) + }; + ensure!( + unsafe { present(self.display.0.as_ptr(), self.surface.as_ptr(), nanos) } != 0, + "presentation time failed" + ); + EGL.swap_buffers(self.display.0, self.surface)?; + Ok(()) + })(); + unsafe { + self.gl.finish(); + self.gl.delete_texture(texture); + } + EGL.destroy_image(self.display.0, import)?; + result + } +} +impl Drop for Graphics { + fn drop(&mut self) { + unsafe { + self.gl.delete_vertex_array(self.vao); + self.gl.delete_program(self.program); + } + let _ = EGL.make_current(self.display.0, None, None, None); + let _ = EGL.destroy_surface(self.display.0, self.surface); + let _ = EGL.destroy_context(self.display.0, self.context); + } +} diff --git a/prototype/channel-native/src/capture/android/mod.rs b/prototype/channel-native/src/capture/android/mod.rs new file mode 100644 index 000000000..0a60b1925 --- /dev/null +++ b/prototype/channel-native/src/capture/android/mod.rs @@ -0,0 +1,32 @@ +//! One authorized projection, immutable source images and independent codec workers. +mod audio; +mod encoding; +mod frames; +mod graphics; +mod platform; +mod source; + +use crate::capture::{AudioCapabilities, Target, TargetKind}; +use anyhow::Result; +pub use audio::{AudioCapture, AudioControl}; +pub use encoding::{Encoding, EncodingControl}; +pub use source::{Capture, Control}; + +pub fn targets() -> Result> { + Ok(vec![Target { + kind: TargetKind::Picker, + source_id: "0".into(), + title: "Screen or app".into(), + pid: 0, + creation_time: None, + }]) +} +pub fn audio_capabilities() -> AudioCapabilities { + AudioCapabilities { + process_audio: false, + system_audio: true, + } +} +pub(super) fn activation_url() -> Result { + platform::activation_url() +} diff --git a/prototype/channel-native/src/capture/android/platform.rs b/prototype/channel-native/src/capture/android/platform.rs new file mode 100644 index 000000000..99f9be37e --- /dev/null +++ b/prototype/channel-native/src/capture/android/platform.rs @@ -0,0 +1,91 @@ +//! JNI objects stay attached to their owning capture; no native callback pointers. +use anyhow::Result; +use jni::{ + jni_sig, jni_str, + objects::{JObject, JString}, + refs::{Cast, Global}, + Env, JavaVM, +}; +use std::sync::Arc; + +pub(super) fn activation_url() -> Result { + let context = ndk_context::android_context(); + let vm = unsafe { JavaVM::from_raw(context.vm().cast()) }; + vm.attach_current_thread(|env| { + let raw = context.context().cast(); + let app = unsafe { Cast::::from_raw(env, &raw) }?; + let package = env + .call_method( + &app, + jni_str!("getPackageName"), + jni_sig!(() -> java.lang.String), + &[], + )? + .l()?; + let package = JString::cast_local(env, package)? + .mutf8_chars(env)? + .to_string(); + Ok(format!( + "intent://media#Intent;scheme=piik;package={package};end" + )) + }) +} + +#[derive(Clone)] +pub(super) struct Platform { + pub object: Arc>>, + vm: Arc, +} +impl Platform { + pub fn new(audio: bool) -> Result { + let context = ndk_context::android_context(); + // Application global reference and VM are installed before app::serve starts. + let vm = Arc::new(unsafe { JavaVM::from_raw(context.vm().cast()) }); + let object = vm.attach_current_thread(|env| -> Result<_> { + let raw = context.context().cast(); + let app = unsafe { Cast::::from_raw(env, &raw) }?; + let loader = env + .call_method( + &app, + jni_str!("getClassLoader"), + jni_sig!(() -> java.lang.ClassLoader), + &[], + )? + .l()?; + let name = JString::from_str(env, "tv.piik.android.CapturePlatform")?; + let class = env + .call_method( + &loader, + jni_str!("loadClass"), + jni_sig!((java.lang.String) -> java.lang.Class), + &[(&name).into()], + )? + .l()?; + let class = jni::objects::JClass::cast_local(env, class)?; + let instance = env.new_object( + class, + jni_sig!((android.content.Context, boolean) -> void), + &[(&*app).into(), audio.into()], + )?; + Ok(env.new_global_ref(instance)?) + })?; + Ok(Self { + object: Arc::new(object), + vm, + }) + } + pub fn with( + &self, + f: impl FnOnce(&mut Env, &Global>) -> Result, + ) -> Result { + self.vm.attach_current_thread(|env| f(env, &self.object)) + } + pub fn stop(&self) { + if let Err(error) = self.with(|env, object| { + env.call_method(object, jni_str!("close"), jni_sig!(() -> void), &[])?; + Ok(()) + }) { + eprintln!("Android projection close: {error:#}"); + } + } +} diff --git a/prototype/channel-native/src/capture/android/source.rs b/prototype/channel-native/src/capture/android/source.rs new file mode 100644 index 000000000..fc305032b --- /dev/null +++ b/prototype/channel-native/src/capture/android/source.rs @@ -0,0 +1,149 @@ +use super::{ + audio::AudioCapture, + encoding::Encoding, + frames::{Frames, RawFrame}, + graphics::Graphics, + platform::Platform, +}; +use crate::capture::{cadence::Cadence, Settings, Target, TargetKind}; +use anyhow::{anyhow, ensure, Context as _, Result}; +use jni::{jni_sig, jni_str}; +use ndk::surface_texture::SurfaceTexture; +use std::thread; + +#[derive(Clone)] +pub struct Control { + frames: Frames, + platform: Platform, +} +impl Control { + pub fn stop(&self) { + self.frames.stop(None); + self.platform.stop(); + } + pub fn is_stopped(&self) -> bool { + self.frames.is_stopped() + } + pub async fn stopped(&self) { + self.frames.stopped().await; + } +} +pub struct Capture { + frames: Frames, + platform: Platform, + thread: Option>>, +} +impl Capture { + pub fn start(target: Target, fps: u32, audio: bool) -> Result { + ensure!( + matches!(target.kind, TargetKind::Picker), + "Android capture uses the system picker" + ); + ensure!(fps > 0, "invalid source FPS"); + let frames = Frames::new()?; + let platform = Platform::new(audio)?; + let worker = frames.clone(); + let projection = platform.clone(); + let thread = thread::Builder::new() + .name("piik-android-source".into()) + .spawn(move || { + let result = run(&projection, &worker, fps); + worker.stop(result.as_ref().err().map(|e| format!("{e:#}"))); + projection.stop(); + let disposed = projection.with(|env, object| { + env.call_method(object, jni_str!("dispose"), jni_sig!(() -> void), &[])?; + Ok(()) + }); + result.and(disposed) + })?; + Ok(Self { + frames, + platform, + thread: Some(thread), + }) + } + pub fn audio(&self, _target: Target) -> Result { + AudioCapture::start(self.platform.clone(), self.frames.clock) + } + pub fn encode(&self, settings: Settings) -> Result { + Encoding::start(self.frames.clone(), settings) + } + pub fn control(&self) -> Control { + Control { + frames: self.frames.clone(), + platform: self.platform.clone(), + } + } + pub fn stop(mut self) -> Result<()> { + self.control().stop(); + self.join() + } + fn join(&mut self) -> Result<()> { + self.thread.take().map_or(Ok(()), |t| { + t.join() + .map_err(|_| anyhow!("Android capture worker panicked"))? + }) + } +} +impl Drop for Capture { + fn drop(&mut self) { + self.control().stop(); + if let Err(e) = self.join() { + eprintln!("Android capture cleanup: {e:#}"); + } + } +} + +fn run(platform: &Platform, frames: &Frames, fps: u32) -> Result<()> { + let mut cadence = Cadence::new(fps); + let graphics = Graphics::new(frames.display.clone(), None, true)?; + let (texture, java_texture) = platform.with(|env, object| { + let texture = env + .call_method( + object, + jni_str!("texture"), + jni_sig!(() -> android.graphics.SurfaceTexture), + &[], + )? + .l()?; + let native = unsafe { + SurfaceTexture::from_surface_texture(env.get_raw().cast(), texture.as_raw().cast()) + } + .context("missing SurfaceTexture")?; + Ok((native, env.new_global_ref(texture)?)) + })?; + let external = graphics.external_texture()?; + texture.attach_to_gl_context(external.0.get())?; + let result = (|| { + platform.with(|env, object| { + env.call_method(object, jni_str!("start"), jni_sig!(() -> void), &[])?; + Ok(()) + })?; + loop { + let size = platform.with(|env, object| { + Ok(env + .call_method(object, jni_str!("nextFrame"), jni_sig!(() -> long), &[])? + .j()?) + })?; + if size == 0 || frames.is_stopped() { + break; + } + texture.update_tex_image()?; + let nanos: i64 = texture.timestamp().as_nanos().try_into()?; + if !cadence.accept(nanos / 100) { + continue; + } + let image = graphics.snapshot( + external, + ((size >> 32) as u32, size as u32), + &texture.transform_matrix(), + )?; + frames.publish(RawFrame { image, nanos }); + } + Ok(()) + })(); + let detached = texture.detach_from_gl_context(); + drop(texture); + drop(java_texture); + result.and(detached.map_err(Into::into)) +} diff --git a/prototype/channel-native/src/capture/cadence.rs b/prototype/channel-native/src/capture/cadence.rs index 1785235b6..593e38882 100644 --- a/prototype/channel-native/src/capture/cadence.rs +++ b/prototype/channel-native/src/capture/cadence.rs @@ -28,14 +28,14 @@ impl Cadence { // Encoder admission only: after its Cadence, before FrameDropper/MFT input. // Dropped inputs count; repeated static-IDR requests do not call observe(). -#[cfg(all(feature = "capture", target_os = "windows"))] +#[cfg(all(feature = "capture", any(target_os = "windows", target_os = "android")))] #[derive(Default)] pub(super) struct AdmissionRate { first: Option, intervals: u32, pub fps: Option, } -#[cfg(all(feature = "capture", target_os = "windows"))] +#[cfg(all(feature = "capture", any(target_os = "windows", target_os = "android")))] impl AdmissionRate { pub fn observe(&mut self, qpc: i64) -> Option { if let Some(first) = self.first { diff --git a/prototype/channel-native/src/capture/linux/source.rs b/prototype/channel-native/src/capture/linux/source.rs index b23ff0d0c..c61f947e4 100644 --- a/prototype/channel-native/src/capture/linux/source.rs +++ b/prototype/channel-native/src/capture/linux/source.rs @@ -98,7 +98,7 @@ impl Capture { super::AudioCapture::start(target) } - pub fn start(target: Target, fps: u32) -> Result { + pub fn start(target: Target, fps: u32, _audio: bool) -> Result { ensure!( matches!(target.kind, TargetKind::Picker), "Linux capture uses the system picker" @@ -573,7 +573,7 @@ mod tests { .into_iter() .next() .context("no system picker")?; - let capture = Capture::start(target.clone(), 30)?; + let capture = Capture::start(target.clone(), 30, false)?; eprintln!("Portal check: select a source for the first capture"); let frame = tokio::time::timeout(Duration::from_secs(90), capture.frames.recv_after(None)) .await?? diff --git a/prototype/channel-native/src/capture/macos/source.rs b/prototype/channel-native/src/capture/macos/source.rs index f10a7d0aa..355db8c7a 100644 --- a/prototype/channel-native/src/capture/macos/source.rs +++ b/prototype/channel-native/src/capture/macos/source.rs @@ -15,7 +15,7 @@ impl Capture { super::AudioCapture::start(target) } - pub fn start(target: Target, fps: u32) -> Result { + pub fn start(target: Target, fps: u32, _audio: bool) -> Result { ensure!(fps > 0 && fps <= i32::MAX as u32, "invalid source FPS"); let runtime = tokio::runtime::Handle::try_current()?; let frames = Frames::new(); diff --git a/prototype/channel-native/src/capture/mod.rs b/prototype/channel-native/src/capture/mod.rs index e5c58604d..e12d87526 100644 --- a/prototype/channel-native/src/capture/mod.rs +++ b/prototype/channel-native/src/capture/mod.rs @@ -1,11 +1,29 @@ //! Native capture producers, independent of rooms and RTP. +#[cfg(all(feature = "capture", target_os = "android"))] +mod android; +#[cfg(all(feature = "capture", target_os = "android"))] +pub use android::{ + audio_capabilities, targets, AudioCapture, AudioControl, Capture, Control, Encoding, + EncodingControl, +}; + +/// Foreground handoff supplied by the installed App, separate from capture consent. +pub fn activation_url() -> anyhow::Result> { + #[cfg(all(feature = "capture", target_os = "android"))] + return android::activation_url().map(Some); + #[cfg(not(all(feature = "capture", target_os = "android")))] + Ok(None) +} #[cfg(all(feature = "capture", target_os = "windows"))] mod audio; #[cfg(any(feature = "capture", test))] mod cadence; #[cfg(all(feature = "capture", target_os = "windows"))] mod converter; -#[cfg(any(all(feature = "capture", target_os = "windows"), test))] +#[cfg(any( + all(feature = "capture", any(target_os = "windows", target_os = "android")), + test +))] mod frame_dropper; #[cfg(all(feature = "capture", target_os = "windows"))] mod gpu; diff --git a/prototype/channel-native/src/capture/windows.rs b/prototype/channel-native/src/capture/windows.rs index ac68130f5..85f043b03 100644 --- a/prototype/channel-native/src/capture/windows.rs +++ b/prototype/channel-native/src/capture/windows.rs @@ -110,7 +110,7 @@ impl Capture { super::AudioCapture::start(target) } - pub fn start(target: Target, fps: u32) -> Result { + pub fn start(target: Target, fps: u32, _audio: bool) -> Result { ensure!(fps > 0, "capture fps must be positive"); let clock = CaptureClock::new()?; let shared = Arc::new(Shared::default()); diff --git a/prototype/channel-native/src/hosted_room.rs b/prototype/channel-native/src/hosted_room.rs index 6ffeb3a56..449305a09 100644 --- a/prototype/channel-native/src/hosted_room.rs +++ b/prototype/channel-native/src/hosted_room.rs @@ -7,6 +7,7 @@ use piik_channel_core::{ }; use std::{ fs::File, + io, path::{Path, PathBuf}, }; use uuid::Uuid; @@ -86,6 +87,16 @@ impl HostedRoom { } } +/// The caller keeps the file open for the lifetime of its exclusive ownership. +pub fn try_lock_file(file: &File) -> io::Result<()> { + // std's Unix implementation omits Android on the pinned Rust toolchain. + #[cfg(unix)] + return rustix::fs::flock(file, rustix::fs::FlockOperation::NonBlockingLockExclusive) + .map_err(io::Error::from); + #[cfg(not(unix))] + file.try_lock().map_err(io::Error::from) +} + fn lock(path: &Path, room_id: &str) -> Result { let mut lock_path = path.as_os_str().to_os_string(); lock_path.push(".lock"); @@ -95,9 +106,33 @@ fn lock(path: &Path, room_id: &str) -> Result { .read(true) .write(true) .open(lock_path)?; - match file.try_lock() { + match try_lock_file(&file) { Ok(()) => Ok(file), - Err(std::fs::TryLockError::WouldBlock) => bail!("room_storage_in_use: {room_id}"), - Err(std::fs::TryLockError::Error(error)) => Err(error.into()), + Err(error) if error.kind() == io::ErrorKind::WouldBlock => { + bail!("room_storage_in_use: {room_id}") + } + Err(error) => Err(error.into()), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn room_lock_is_exclusive_until_its_file_closes() -> Result<()> { + let directory = std::env::temp_dir().join(format!("piik-room-lock-{}", Uuid::new_v4())); + std::fs::create_dir(&directory)?; + let path = directory.join("room.sqlite"); + let owner = lock(&path, "test-room")?; + assert_eq!( + lock(&path, "test-room").unwrap_err().to_string(), + "room_storage_in_use: test-room" + ); + drop(owner); + drop(lock(&path, "test-room")?); + std::fs::remove_file(directory.join("room.sqlite.lock"))?; + std::fs::remove_dir(directory)?; + Ok(()) } } diff --git a/prototype/channel-native/src/input/tests.rs b/prototype/channel-native/src/input/tests.rs index 802f0db48..4afd4346f 100644 --- a/prototype/channel-native/src/input/tests.rs +++ b/prototype/channel-native/src/input/tests.rs @@ -829,7 +829,7 @@ async fn linux_portal_grant_delivers_encrypted_input_to_owned_window() -> Result .into_iter() .next() .ok_or_else(|| anyhow!("no system picker"))?; - let capture = crate::capture::Capture::start(target.clone(), 30)?; + let capture = crate::capture::Capture::start(target.clone(), 30, false)?; let desktop = Desktop::new()?; let (source, mut replies, _) = desktop.source(Uuid::new_v4(), Uuid::new_v4(), target)?; let control = capture.control(); diff --git a/prototype/channel-native/src/media/local.rs b/prototype/channel-native/src/media/local.rs index d550ea565..deb8f83f3 100644 --- a/prototype/channel-native/src/media/local.rs +++ b/prototype/channel-native/src/media/local.rs @@ -101,7 +101,7 @@ impl Producer { // Both source reports project original capture PTS through this one pair. let now = Instant::now(); let clock = SystemInstant::now(now); - let capture = Capture::start(target.clone(), settings.fps)?; + let capture = Capture::start(target.clone(), settings.fps, audio)?; let encoding = capture.encode(settings)?; let video_control = capture.control(); let (audio_error, warning) = if audio { diff --git a/prototype/channel-native/src/media/local/encodings.rs b/prototype/channel-native/src/media/local/encodings.rs index 108a098b6..61ec06a64 100644 --- a/prototype/channel-native/src/media/local/encodings.rs +++ b/prototype/channel-native/src/media/local/encodings.rs @@ -1,7 +1,7 @@ //! One producer selects and retires the actual encoders used by its Outputs. use super::*; use crate::capture::{Encoding, EncodingControl}; -use futures_util::{stream::FuturesUnordered, StreamExt}; +use futures_util::{future::Aborted, stream::FuturesUnordered, StreamExt}; use std::{collections::HashMap, future::Future, pin::Pin, sync::Arc}; use tokio::sync::Notify; @@ -146,7 +146,10 @@ pub(super) async fn run( let frame = tokio::select! { _ = control.video.stopped() => return Ok(()), _ = cancelled.changed() => return Ok(()), - frame = initial.as_mut().unwrap().recv() => frame.ok_or_else(|| anyhow!("capture ended before its first frame"))??, + frame = initial.as_mut().unwrap().recv() => match frame { + Some(frame) => frame?, + None => return Ok(()), + }, }; let mut sps = H264Sps::default(); sps.access_unit(&frame.bytes)?; @@ -261,9 +264,11 @@ pub(super) async fn run( entry.retire(); } while pumps.next().await.is_some() {} - if let Some(encoding) = initial { - let _ = stop(encoding).await; - } + let result = if let Some(encoding) = initial { + result.and(stop(encoding).await) + } else { + result + }; let joined = tokio::task::spawn_blocking(move || capture.stop()) .await .map_err(anyhow::Error::from) @@ -273,11 +278,10 @@ pub(super) async fn run( eprintln!("Native audio task failed: {error}"); } } - let error = result.and(joined).err().map(|error| format!("{error:#}")); + let result = result.and(joined); + let error = result.as_ref().err().map(|error| format!("{error:#}")); if let Some(ready) = ready { - let _ = ready.send(Err(anyhow!(error - .clone() - .unwrap_or_else(|| "capture ended before its first frame".into())))); + let _ = ready.send(result.and(Err(Aborted.into()))); } if !*cancelled.borrow() { tokio::select! { diff --git a/prototype/channel-native/src/peer/input.rs b/prototype/channel-native/src/peer/input.rs index a286ca9b8..0cec9a2e5 100644 --- a/prototype/channel-native/src/peer/input.rs +++ b/prototype/channel-native/src/peer/input.rs @@ -1,9 +1,6 @@ //! Opaque input follows the core's selected lineage on the existing pair. use super::*; -#[cfg(all( - any(feature = "capture", test), - any(target_os = "windows", target_os = "macos", target_os = "linux") -))] +#[cfg(any(feature = "capture", test))] use crate::input::SourceView; use crate::input::{Desktop, Registration, Reply, Source as InputSource}; use futures_util::{stream::SelectAll, Stream}; @@ -13,10 +10,7 @@ use serde::Deserialize; pub(super) struct Inputs { local: Uuid, snapshot: watch::Receiver>, - #[cfg(all( - any(feature = "capture", test), - any(target_os = "windows", target_os = "macos", target_os = "linux") - ))] + #[cfg(any(feature = "capture", test))] desktop: Option, bindings: HashMap<(Uuid, Uuid), InputBinding>, registrations: Vec, @@ -36,19 +30,19 @@ impl Inputs { snapshot: watch::Receiver>, desktop: Option, ) -> Self { - #[cfg(not(all( - any(feature = "capture", test), - any(target_os = "windows", target_os = "macos", target_os = "linux") - )))] + #[cfg(not(any(feature = "capture", test)))] let _ = desktop; Self { local, snapshot, - #[cfg(all( - any(feature = "capture", test), - any(target_os = "windows", target_os = "macos", target_os = "linux") - ))] - desktop, + #[cfg(any(feature = "capture", test))] + desktop: desktop.filter(|_| { + cfg!(any( + target_os = "windows", + target_os = "macos", + target_os = "linux" + )) + }), bindings: HashMap::new(), registrations: vec![], sources: HashMap::new(), @@ -56,10 +50,7 @@ impl Inputs { } } - #[cfg(all( - any(feature = "capture", test), - any(target_os = "windows", target_os = "macos", target_os = "linux") - ))] + #[cfg(any(feature = "capture", test))] pub fn source( &mut self, publication: Uuid, diff --git a/prototype/channel-native/src/session.rs b/prototype/channel-native/src/session.rs index 16516c6d3..a8ff11f19 100644 --- a/prototype/channel-native/src/session.rs +++ b/prototype/channel-native/src/session.rs @@ -740,14 +740,10 @@ impl Session { match result { RoomResult::Done => self.finish_capture(request, socket).await?, RoomResult::Error { code } => { - let publication_id = request.publication_id; let _ = request.result.send(Err(code)); - self.unpublish_capture(publication_id, socket).await?; } _ => { - let publication_id = request.publication_id; let _ = request.result.send(Err("invalid_capture_reply".into())); - self.unpublish_capture(publication_id, socket).await?; } } } @@ -758,9 +754,7 @@ impl Session { .and_then(|id| self.pending_captures.remove(id)) { let request = request.request; - let publication_id = request.publication_id; let _ = request.result.send(Err(code)); - self.unpublish_capture(publication_id, socket).await?; return Ok(()); } if request_id.as_ref().is_some_and(|id| { @@ -797,6 +791,22 @@ impl Session { let _ = request.result.send(Err("capture_unavailable".into())); return Ok(()); } + if self + .pending_captures + .values() + .any(|pending| pending.request.publication_id == request.publication_id) + || self.live.as_ref().is_some_and(|live| { + live.room.snapshot.borrow().as_ref().is_some_and(|state| { + state + .publications + .iter() + .any(|publication| publication.id == request.publication_id) + }) + }) + { + let _ = request.result.send(Err("capture_already_active".into())); + return Ok(()); + } let binding_id = self.live.as_ref().and_then(|live| { live.room .snapshot @@ -857,7 +867,9 @@ impl Session { }); if !current || request.result.is_closed() { let _ = request.result.send(Err("publication_unavailable".into())); - self.unpublish_capture(publication_id, socket).await?; + if current { + self.unpublish_capture(publication_id, socket).await?; + } return Ok(()); } let result = await_peer( diff --git a/prototype/channel-server/Cargo.lock b/prototype/channel-server/Cargo.lock index b055d9c27..bdfb7a476 100644 --- a/prototype/channel-server/Cargo.lock +++ b/prototype/channel-server/Cargo.lock @@ -1240,6 +1240,18 @@ dependencies = [ "system-deps", ] +[[package]] +name = "glow" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5e5ea60d70410161c8bf5da3fdfeaa1c72ed2c15f8bbb9d19fe3a4fad085f08" +dependencies = [ + "js-sys", + "slotmap", + "wasm-bindgen", + "web-sys", +] + [[package]] name = "gobject-sys" version = "0.21.5" @@ -1842,6 +1854,16 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "khronos-egl" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6aae1df220ece3c0ada96b8153459b67eebe9ae9212258bb0134ae60416fdf76" +dependencies = [ + "libc", + "pkg-config", +] + [[package]] name = "kstring" version = "2.0.2" @@ -2082,12 +2104,36 @@ dependencies = [ "slotmap", ] +[[package]] +name = "ndk" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4" +dependencies = [ + "bitflags 2.13.2", + "jni-sys 0.3.1", + "log", + "ndk-sys", + "num_enum", + "raw-window-handle", + "thiserror 1.0.69", +] + [[package]] name = "ndk-context" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" +[[package]] +name = "ndk-sys" +version = "0.6.0+11769913" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873" +dependencies = [ + "jni-sys 0.3.1", +] + [[package]] name = "netdev" version = "0.46.3" @@ -2564,10 +2610,15 @@ dependencies = [ "cidre", "futures-util", "getrandom 0.3.4", + "glow", "gstreamer", "gstreamer-app", "gstreamer-video", + "jni 0.22.4", + "khronos-egl", "libc", + "ndk", + "ndk-context", "netwatch", "objc2-app-kit", "objc2-application-services", @@ -2612,7 +2663,6 @@ dependencies = [ "ring", "rtc", "rusqlite", - "rustix", "rustls", "serde", "serde_json", @@ -2899,6 +2949,12 @@ version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" +[[package]] +name = "raw-window-handle" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539" + [[package]] name = "rayon" version = "1.12.0" diff --git a/prototype/channel-server/Cargo.toml b/prototype/channel-server/Cargo.toml index fe620ee21..521316ebf 100644 --- a/prototype/channel-server/Cargo.toml +++ b/prototype/channel-server/Cargo.toml @@ -40,9 +40,6 @@ rcgen = { version = "=0.14.10", default-features = false, features = ["ring"] } rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] } ring = "0.17" -[target.'cfg(unix)'.dependencies] -rustix = { version = "1", features = ["fs"] } - [dev-dependencies] tokio-tungstenite = "0.29" tokio-rustls = { version = "0.26", default-features = false, features = ["ring", "tls12"] } diff --git a/prototype/channel-server/src/app.rs b/prototype/channel-server/src/app.rs index 39668e002..9d7525049 100644 --- a/prototype/channel-server/src/app.rs +++ b/prototype/channel-server/src/app.rs @@ -19,7 +19,11 @@ use axum::{ routing::{get, post}, Json, Router, }; -use futures_util::{stream::FuturesUnordered, SinkExt, StreamExt}; +use futures_util::{ + future::{AbortHandle, Abortable, Aborted}, + stream::FuturesUnordered, + SinkExt, StreamExt, +}; use piik_channel_core::RoomState; use piik_channel_native::{ capture::{Settings, Target}, @@ -265,15 +269,9 @@ fn lock_directory(directory: &std::path::Path) -> Result { .create(true) .truncate(false) .open(directory.join("app.lock"))?; - // std's Unix implementation omits Android on the pinned Rust toolchain. - #[cfg(unix)] - let locked = rustix::fs::flock(&owner, rustix::fs::FlockOperation::NonBlockingLockExclusive) - .map_err(std::io::Error::from); - #[cfg(not(unix))] - let locked = owner.try_lock().map_err(std::io::Error::from); - locked.map_err(|error| match error.kind() { + piik_channel_native::hosted_room::try_lock_file(&owner).map_err(|error| match error.kind() { std::io::ErrorKind::WouldBlock => anyhow!("This App data directory is already in use"), - _ => anyhow!("Cannot lock App data directory: {error}"), + _ => error.into(), })?; Ok(owner) } @@ -613,6 +611,7 @@ enum Operation { }, Targets, StartCapture { + publication_id: Uuid, room_id: String, target: Target, #[serde(default)] @@ -638,6 +637,27 @@ enum Operation { key: u8, }, } + +enum Capture { + Pending(AbortHandle), + Active(CaptureLease), +} +impl Capture { + fn lease(&self) -> Option<&CaptureLease> { + match self { + Self::Active(lease) if !lease.is_stopped() => Some(lease), + _ => None, + } + } +} +impl Drop for Capture { + fn drop(&mut self) { + if let Self::Pending(request) = self { + request.abort(); + } + } +} + async fn connection( socket: WebSocket, app: &App, @@ -660,12 +680,12 @@ async fn connection( }; let processing = async { let mut host = None; - let mut captures: BTreeMap = BTreeMap::new(); + let mut captures: BTreeMap = BTreeMap::new(); + let mut capture_starts = FuturesUnordered::new(); let mut audio_errors = FuturesUnordered::new(); let mut input_states = FuturesUnordered::new(); let mut input_policies = FuturesUnordered::new(); loop { - let mut initial_input = None; let message = tokio::select! { message = async { if host.is_some() { Ok(queue.recv().await) } @@ -673,7 +693,7 @@ async fn connection( } => message?, Some((publication_id, error)) = audio_errors.next(), if !audio_errors.is_empty() => { let error: Option = error; - if error.is_some() && captures.get(&publication_id).is_some_and(|lease| !lease.is_stopped()) { + if error.is_some() && captures.get(&publication_id).and_then(Capture::lease).is_some() { let event = json!({"type":"capture_audio_failed","publicationId":publication_id}); timeout(IO_TIMEOUT, writer.send(Message::Text(event.to_string().into()))).await??; } @@ -681,7 +701,7 @@ async fn connection( } Some((publication_id, changed, state)) = input_states.next(), if !input_states.is_empty() => { let state: Option = state; - if let Some(state) = state.filter(|_| captures.get(&publication_id).is_some_and(|lease| !lease.is_stopped())) { + if let Some(state) = state.filter(|_| captures.get(&publication_id).and_then(Capture::lease).is_some()) { let event = json!({"type":"input_state","publicationId":publication_id,"state":state}); timeout(IO_TIMEOUT, writer.send(Message::Text(event.to_string().into()))).await??; input_states.push(next_input_state(publication_id, changed)); @@ -693,6 +713,45 @@ async fn connection( timeout(IO_TIMEOUT, writer.send(Message::Text(response.to_string().into()))).await??; continue; } + Some((id, publication_id, request, result)) = capture_starts.next(), if !capture_starts.is_empty() => { + let request: AbortHandle = request; + let result: Result = result; + let mut initial_input = None; + let result = if request.is_aborted() { + // Stop already retired this request, including a completed + // future that had not yet been observed by the processor. + drop(result); + Err(anyhow!("capture_cancelled")) + } else { + match result { + Ok(mut lease) => { + if let Some(error) = lease.audio_error.take() { + audio_errors.push(async move { (publication_id, error.await.ok()) }); + } + if let Some(state) = &lease.input_state { + initial_input = Some(state.borrow().clone()); + input_states.push(next_input_state(publication_id, state.clone())); + } + captures.insert(publication_id, Capture::Active(lease)); + Ok(()) + } + Err(error) => Err(error), + } + }; + let response = match result { + Ok(()) => json!({"id":id,"result":null}), + Err(error) => { + if !request.is_aborted() { captures.remove(&publication_id); } + json!({"id":id,"error":error.to_string()}) + } + }; + timeout(IO_TIMEOUT, writer.send(Message::Text(response.to_string().into()))).await??; + if let Some(state) = initial_input { + let event = json!({"type":"input_state","publicationId":publication_id,"state":state}); + timeout(IO_TIMEOUT, writer.send(Message::Text(event.to_string().into()))).await??; + } + continue; + } }; let Some(text) = message else { break }; let value: Value = serde_json::from_str(&text)?; @@ -735,40 +794,38 @@ async fn connection( None => Err(anyhow!("hello_required")), }, Operation::StartCapture { + publication_id, room_id, target, audio, } => match &host { Some(commands) => { - captures.retain(|_, lease| !lease.is_stopped()); - let publication_id = Uuid::new_v4(); - match start_capture( - commands, - publication_id, - room_id, - target, - audio, - ) - .await - { - Ok(mut lease) => { - if let Some(error) = lease.audio_error.take() { - audio_errors.push(async move { - (publication_id, error.await.ok()) - }); - } - if let Some(state) = &lease.input_state { - initial_input = - Some((publication_id, state.borrow().clone())); - input_states.push(next_input_state( + captures.retain(|_, capture| !matches!(capture, Capture::Active(lease) if lease.is_stopped())); + if captures.contains_key(&publication_id) { + Err(anyhow!("capture_already_active")) + } else { + let (cancel, registration) = AbortHandle::new_pair(); + captures.insert( + publication_id, + Capture::Pending(cancel.clone()), + ); + let commands = commands.clone(); + capture_starts.push(async move { + let result = Abortable::new( + start_capture( + &commands, publication_id, - state.clone(), - )); - } - captures.insert(publication_id, lease); - Ok(json!({"publicationId":publication_id})) - } - Err(error) => Err(error), + room_id, + target, + audio, + ), + registration, + ) + .await + .unwrap_or_else(|_| Err(anyhow!("capture_cancelled"))); + (request.id, publication_id, cancel, result) + }); + continue; } } None => Err(anyhow!("hello_required")), @@ -785,7 +842,7 @@ async fn connection( } => { let policy = captures .get(&publication_id) - .filter(|lease| !lease.is_stopped()) + .and_then(Capture::lease) .ok_or_else(|| anyhow!("input_source_unavailable")) .and_then(|lease| { lease.set_input_policy(mode, password, simultaneous) @@ -811,7 +868,7 @@ async fn connection( } => (|| -> Result { let lease = captures .get(&publication_id) - .filter(|lease| !lease.is_stopped()) + .and_then(Capture::lease) .ok_or_else(|| anyhow!("input_source_unavailable"))?; let source = lease .remote @@ -826,7 +883,7 @@ async fn connection( } => (|| -> Result { let lease = captures .get(&publication_id) - .filter(|lease| !lease.is_stopped()) + .and_then(Capture::lease) .ok_or_else(|| anyhow!("input_source_unavailable"))?; if lease.remote.is_none() { bail!("input_source_unavailable"); @@ -847,15 +904,6 @@ async fn connection( writer.send(Message::Text(response.to_string().into())), ) .await??; - if let Some((publication_id, state)) = initial_input { - let event = - json!({"type":"input_state","publicationId":publication_id,"state":state}); - timeout( - IO_TIMEOUT, - writer.send(Message::Text(event.to_string().into())), - ) - .await??; - } } Ok(()) }; @@ -902,7 +950,11 @@ async fn capture_targets() -> Result { tokio::task::spawn_blocking(|| { let sources = piik_channel_native::capture::targets()?; let audio = piik_channel_native::capture::audio_capabilities(); - Ok(json!({"sources": sources, "processAudio": audio.process_audio, "systemAudio": audio.system_audio})) + let mut result = json!({"sources": sources, "processAudio": audio.process_audio, "systemAudio": audio.system_audio}); + if let Some(activation) = piik_channel_native::capture::activation_url()? { + result["activationURL"] = json!(activation); + } + Ok(result) }).await? } #[cfg(not(feature = "capture"))] @@ -937,6 +989,12 @@ async fn start_capture( .await .map_err(|_| anyhow!("hosting_unavailable"))? .map_err(anyhow::Error::msg)?; - lease.ready().await.map_err(|_| anyhow!("capture_failed"))?; + lease.ready().await.map_err(|error| { + if error.is::() { + anyhow!("capture_cancelled") + } else { + anyhow!("capture_failed") + } + })?; Ok(lease) } diff --git a/prototype/channel-server/tests/native_session.rs b/prototype/channel-server/tests/native_session.rs index e00cd0e8c..77dbea3f0 100644 --- a/prototype/channel-server/tests/native_session.rs +++ b/prototype/channel-server/tests/native_session.rs @@ -587,7 +587,7 @@ async fn app_host_outlives_its_page_and_restores_rooms_only_after_real_admission use piik_channel_core::host::HostAction; let target = json!({"kind":"window","sourceId":"0","title":"Unopened test target","pid":0}); page.send(Message::Text( - json!({"id":"missing-capture-room","type":"start_capture", + json!({"id":"missing-capture-room","type":"start_capture","publicationId":Uuid::new_v4(), "roomId":"missing-capture-room","target":target}) .to_string() .into(), @@ -599,66 +599,166 @@ async fn app_host_outlives_its_page_and_restores_rooms_only_after_real_admission .unwrap(); assert_eq!(denied["error"], "room_unavailable"); - // Close the control socket while its Publish response is deliberately - // withheld. The independent reader must cancel the caller immediately. - page.send(Message::Text( - json!({"id":"cancelled-capture","type":"start_capture", + // Both explicit stop and socket close must cancel before the RoomReply. + for close in [false, true] { + let publication_id = Uuid::new_v4(); + page.send(Message::Text( + json!({"id":"cancelled-capture","type":"start_capture","publicationId":publication_id, "roomId":room,"target":target}) .to_string() .into(), )) .await .unwrap(); - let input = domain + let input = domain .until(|_, event| { matches!(event, Event::HostInput {input, ..} if matches!(&input.action, HostAction::Command {context, command:Command::Publish {..}} if context.request_id.is_some())) }) .await; - let Event::HostInput { input, .. } = input else { - unreachable!() - }; - let HostAction::Command { - context, - command: Command::Publish { publication }, - } = input.action - else { - unreachable!() - }; - assert_ne!( - context.request_id.as_deref(), - Some(room.as_str()), - "capture and room-registration replies have separate request owners" - ); - assert!( - tokio::time::timeout(Duration::from_millis(50), page.next()) + let Event::HostInput { input, .. } = input else { + unreachable!() + }; + let HostAction::Command { + context, + command: Command::Publish { publication }, + } = input.action + else { + unreachable!() + }; + assert_eq!(publication.id, publication_id); + assert_ne!( + context.request_id.as_deref(), + Some(room.as_str()), + "capture and room-registration replies have separate request owners" + ); + let held_reply = tokio::time::timeout(Duration::from_secs(5), async { + loop { + let message = domain.socket.next().await.unwrap().unwrap(); + let Message::Text(text) = message else { continue }; + let request = Request::parse(&text).unwrap(); + domain.commands.push(request.command.clone()); + let mut effects = domain.authority.handle(domain.connection, request, domain.now); + let reply = effects.events.iter().position(|(_, event)| { + matches!(event, Event::RoomReply {request_id, ..} if request_id == &context.request_id) + }).map(|index| effects.events.remove(index)); + domain.apply(effects).await; + if let Some(reply) = reply { break reply; } + } + }).await.expect("the real room must commit its publication"); + assert!(matches!( + &held_reply.1, + Event::RoomReply { + result: piik_channel_core::host::RoomResult::Done, + .. + } + )); + assert!(domain.events.iter().any(|(_, event)| { + matches!(event, Event::State {state} if state.publications.iter().any(|p| p.id == publication_id)) + }), "the first publication is real while only its caller's reply is withheld"); + assert!( + tokio::time::timeout(Duration::from_millis(50), page.next()) + .await + .is_err(), + "capture cannot return success before its real RoomReply" + ); + page.send(Message::Text(hello(&credential).to_string().into())) .await - .is_err(), - "capture cannot return success before its real RoomReply" - ); - page.close(None).await.unwrap(); - tokio::time::timeout(Duration::from_secs(2), async { - while page.next().await.is_some() {} - }) - .await - .expect("control close must not wait for the room-host reply"); - domain.room_turn(&room).await; - tokio::time::timeout(Duration::from_secs(5), async { + .unwrap(); + let concurrent: Value = serde_json::from_str( + &tokio::time::timeout(Duration::from_secs(2), page.next()) + .await + .expect("a pending capture must not block other page commands") + .unwrap() + .unwrap() + .into_text() + .unwrap(), + ) + .unwrap(); + assert_eq!(concurrent["error"], "already_initialized"); + if !close { + // The Native endpoint is shared by pages; another page cannot + // republish an ID whose first startup is still owned here. + let (mut other, _) = connect_async(upgrade(address, token)).await.unwrap(); + other + .send(Message::Text(hello(&credential).to_string().into())) + .await + .unwrap(); + other.next().await.unwrap().unwrap(); + other + .send(Message::Text( + json!({"id":"duplicate-capture","type":"start_capture","publicationId":publication_id, + "roomId":room,"target":target}).to_string().into(), + )) + .await + .unwrap(); + let duplicate: Value = serde_json::from_str( + &tokio::time::timeout(Duration::from_secs(2), other.next()) + .await + .expect("another page must not replace the pending publication") + .unwrap() + .unwrap() + .into_text() + .unwrap(), + ) + .unwrap(); + assert_eq!(duplicate["error"], "capture_already_active"); + other.close(None).await.unwrap(); + } + if close { + page.close(None).await.unwrap(); + tokio::time::timeout(Duration::from_secs(2), async { + while page.next().await.is_some() {} + }) + .await + .expect("control close must not wait for the room-host reply"); + } else { + page.send(Message::Text( + json!({"id":"stop-pending","type":"stop_capture","publicationId":publication_id}) + .to_string().into(), + )).await.unwrap(); + let mut replies = std::collections::BTreeMap::new(); + for _ in 0..2 { + let reply: Value = serde_json::from_str( + &tokio::time::timeout(Duration::from_secs(2), page.next()) + .await + .expect("same-page stop must not wait for capture readiness") + .unwrap() + .unwrap() + .into_text() + .unwrap(), + ) + .unwrap(); + replies.insert(reply["id"].as_str().unwrap().to_owned(), reply); + } + assert_eq!(replies["stop-pending"]["result"], Value::Null); + assert_eq!(replies["cancelled-capture"]["error"], "capture_cancelled"); + } + domain + .apply(Effects { + events: vec![held_reply], + ..Effects::default() + }) + .await; + tokio::time::timeout(Duration::from_secs(5), async { while !domain.commands.iter().any(|command| matches!(command, Command::Unpublish {publication_id} if *publication_id == publication.id)) { domain.step().await; } }).await.expect("a cancelled, confirmed publication is explicitly retired"); - domain.room_turn(&room).await; - let (next, _) = connect_async(upgrade(address, token)).await.unwrap(); - page = next; - page.send(Message::Text(hello(&credential).to_string().into())) - .await - .unwrap(); - let reopened: Value = - serde_json::from_str(&page.next().await.unwrap().unwrap().into_text().unwrap()) - .unwrap(); - assert!(reopened.get("result").is_some()); + domain.room_turn(&room).await; + if close { + let (next, _) = connect_async(upgrade(address, token)).await.unwrap(); + page = next; + page.send(Message::Text(hello(&credential).to_string().into())) + .await + .unwrap(); + let reopened: Value = + serde_json::from_str(&page.next().await.unwrap().unwrap().into_text().unwrap()) + .unwrap(); + assert!(reopened.get("result").is_some()); + } + } assert!( HostedRoom::open(&room_directory.join(format!("{room}.sqlite")), &room, user).is_err(), "cancelled capture must retain the existing Native room runtime lock" diff --git a/src/client/channel/app-link.ts b/src/client/channel/app-link.ts index ece1a5e63..4f036b210 100644 --- a/src/client/channel/app-link.ts +++ b/src/client/channel/app-link.ts @@ -3,13 +3,15 @@ import { z } from "zod"; import { appApprovalURL, discoverLocalApp, type AppDiscovery, type AppDiscoveryOptions } from "../native/discovery"; import { nativeCaptureTargetSchema, remoteControlStateSchema, remoteStopShortcutSchema, type NativeCaptureTarget, type RemoteStopShortcut } from "../native/wire"; import { remoteShortcutKeySchema, type RemoteControlMode } from "../remote-control/protocol"; +import { activateNativePicker } from "../native/activation"; const identitySchema = z.object({ service: z.literal("piik-channel-app"), protocol: z.number().int().positive(), port: z.number().int().min(1).max(65535) }); const healthSchema = identitySchema.extend({ protocol: z.literal(1), token: z.string().min(1).max(256).regex(/^[A-Za-z0-9_-]+$/) }); type AppHealth = z.infer; const captureSourcesSchema = z.object({ sources: z.array(nativeCaptureTargetSchema), - processAudio: z.boolean(), systemAudio: z.boolean() }).strict(); + processAudio: z.boolean(), systemAudio: z.boolean(), activationURL: z.string().url().max(512).optional() }).strict(); export type NativeCaptureSources = z.infer; +export type NativeCaptureRequest = { publicationId: string; activationURL: string }; const captureAudioFailureSchema = z.object({ type: z.literal("capture_audio_failed"), publicationId: z.uuid() }).strict(); const inputControlStateSchema = remoteControlStateSchema.extend({ canSetStopShortcut: z.boolean(), stopShortcut: remoteShortcutKeySchema.nullable().optional(), @@ -17,6 +19,7 @@ const inputControlStateSchema = remoteControlStateSchema.extend({ export type ChannelRemoteControlState = z.infer; const inputStateSchema = z.object({ type: z.literal("input_state"), publicationId: z.uuid(), state: inputControlStateSchema }).strict(); class AppCompatibilityError extends Error {} +type AppCommand = { type: string; publicationId?: string; roomId?: string; [key: string]: unknown }; function identity(body: unknown, port: number): void { const value = identitySchema.parse(body); @@ -43,16 +46,26 @@ export const channelAppDiscovery: AppDiscovery = { /** Hosting survives this link; captures selected through it belong to this page. */ export class ChannelApp { private socket: WebSocket; - private requests = new Map(); + private requests = new Map(); readonly ready: Promise; private rejectReady!: (error: Error) => void; private timer: ReturnType; private authenticated = false; private captures = new Set(); + private activationURL?: string; get connected(): boolean { return this.authenticated && this.socket.readyState === WebSocket.OPEN; } get screens(): ReadonlySet { return this.captures; } + captureRequest(roomId: string): NativeCaptureRequest | undefined { + if (!this.activationURL) return; + for (const { command } of this.requests.values()) { + if (command.type === "start_capture" && command.roomId === roomId && command.publicationId && this.captures.has(command.publicationId)) { + return { publicationId: command.publicationId, activationURL: this.activationURL }; + } + } + } + constructor(health: AppHealth, channelId: string, userId: string, credential: string, name: string, onClose: () => void, onAudioFailure: (publicationId: string) => void, onInputState: (publicationId: string, state: ChannelRemoteControlState) => void = () => {}) { @@ -85,8 +98,8 @@ export class ChannelApp { const request = this.requests.get(reply.id); if (!request) return; this.requests.delete(reply.id); - if (reply.error) request.reject(reply.error === "input_authorization_cancelled" - ? new DOMException("Input authorization cancelled", "AbortError") : new Error(reply.error)); + if (reply.error) request.reject(reply.error === "input_authorization_cancelled" || reply.error === "capture_cancelled" + ? new DOMException(reply.error, "AbortError") : new Error(reply.error)); else request.resolve(reply.result); } catch { lost(); } }; @@ -94,11 +107,11 @@ export class ChannelApp { socket.onerror = () => { /* Close retires the connection and its requests. */ }; } - private request(command: object): Promise { + private request(command: AppCommand): Promise { if (this.socket.readyState !== WebSocket.OPEN) return Promise.reject(new Error("app_disconnected")); const id = crypto.randomUUID(); return new Promise((resolve, reject) => { - this.requests.set(id, { resolve: value => resolve(value as T), reject }); + this.requests.set(id, { command, resolve: value => resolve(value as T), reject }); this.socket.send(JSON.stringify({ ...command, id })); }); } @@ -110,15 +123,23 @@ export class ChannelApp { async sources(): Promise { await this.ready; - return captureSourcesSchema.parse(await this.request({ type: "targets" })); + const sources = captureSourcesSchema.parse(await this.request({ type: "targets" })); + this.activationURL = sources.activationURL; + return sources; } - async startCapture(roomId: string, target: NativeCaptureTarget, audio = false): Promise { - await this.ready; - const result = z.object({ publicationId: z.uuid() }).strict() - .parse(await this.request({ type: "start_capture", roomId, target, audio })); - this.captures.add(result.publicationId); - return result.publicationId; + async startCapture(publicationId: string, roomId: string, target: NativeCaptureTarget, audio = false): Promise { + if (!this.connected) throw new Error("app_disconnected"); + this.captures.add(publicationId); + try { + const pending = this.request({ type: "start_capture", publicationId, roomId, target, audio }); + activateNativePicker(this.activationURL); + await pending; + if (!this.captures.has(publicationId)) throw new DOMException("Capture cancelled", "AbortError"); + } catch (error) { + await this.stopCapture(publicationId).catch(() => {}); + throw error; + } } async stopCapture(publicationId: string): Promise { diff --git a/src/client/channel/components/ChannelShareControl.tsx b/src/client/channel/components/ChannelShareControl.tsx index eaaff1a60..02b6c2892 100644 --- a/src/client/channel/components/ChannelShareControl.tsx +++ b/src/client/channel/components/ChannelShareControl.tsx @@ -3,6 +3,7 @@ import { CaptureSourcePicker, type NativeSourceList } from "../../components/liv import { Btn } from "../../components/living/primitives"; import { useAnchoredPopover } from "../../components/living/use-anchored-popover"; import { useCopy } from "../../ui/copy"; +import { activateNativePicker } from "../../native/activation"; import type { ChannelController } from "../types"; import "./channel-share-control.css"; @@ -21,6 +22,7 @@ export function ChannelShareControl({ channel, roomId, disabled }: { const { appConnected, nativeSources, startNativeScreen, startScreen } = channel; const browserSupported = typeof navigator !== "undefined" && typeof navigator.mediaDevices?.getDisplayMedia === "function"; const busy = channel.pending.has(`screen:${roomId}`); + const captureRequest = channel.nativeCaptureRequest(roomId); const available = browserSupported || appConnected; const label = lang === "zh" ? "分享屏幕" : "Share screen"; useAnchoredPopover(trigger, panel, { maxHeight: 560, minVisibleHeight: 240 }); @@ -47,11 +49,16 @@ export function ChannelShareControl({ channel, roomId, disabled }: { }; return <> - + activateNativePicker(captureRequest.activationURL)} /> + { void channel.stopScreen(captureRequest.publicationId).catch(() => {}); }} /> + : { if (!appConnected) start(() => startScreen(roomId)); }} /> + onClick={() => { if (!appConnected) start(() => startScreen(roomId)); }} />}
setOpen(event.newState === "open")}> diff --git a/src/client/channel/components/channel-share-control.css b/src/client/channel/components/channel-share-control.css index ca6d7bd8f..fedcbe72d 100644 --- a/src/client/channel/components/channel-share-control.css +++ b/src/client/channel/components/channel-share-control.css @@ -1,4 +1,4 @@ -.c3-share-control { display: inline-flex; } +.c3-share-control { display: inline-flex; gap: 8px; } .lr-anchored-card.c3-share-picker { width: min(720px, calc(100vw - 16px)); height: min(560px, calc(100dvh - 16px)); diff --git a/src/client/channel/session.ts b/src/client/channel/session.ts index ebf2e95a2..c32e35e03 100644 --- a/src/client/channel/session.ts +++ b/src/client/channel/session.ts @@ -673,18 +673,24 @@ export class ChannelSession { await this.publish("screen", roomId, stream); }); nativeSources = async (): Promise => (await this.connectApp()).sources(); + nativeCaptureRequest = (roomId: string) => this.app?.captureRequest(roomId); startNativeScreen = (roomId: string, target: NativeCaptureTarget, audio = false): Promise => this.action(`screen:${roomId}`, async () => { const epoch = this.captureEpoch; const app = await this.connectApp(); if (epoch !== this.captureEpoch) throw new Error("closed"); - const id = await app.startCapture(roomId, target, audio); - if (epoch !== this.captureEpoch || this.app !== app) { - await app.stopCapture(id); - throw new Error("closed"); - } + const id = crypto.randomUUID(); + const starting = app.startCapture(id, roomId, target, audio); this.patch({}); - // Native owns the source; this page previews it through the ordinary route. - await this.watch(id, roomId); + await starting; + this.patch({}); + try { + if (epoch !== this.captureEpoch || this.app !== app) throw new Error("closed"); + // Native owns the source; this page previews it through the ordinary route. + await this.watch(id, roomId); + } catch (error) { + await app.stopCapture(id).catch(() => {}); + throw error; + } }); stopScreen = (publicationId: string): Promise => this.action(`stop:${publicationId}`, async () => { if (this.app?.screens.has(publicationId)) { diff --git a/src/client/channel/types.ts b/src/client/channel/types.ts index 8eb6138e5..700e29a22 100644 --- a/src/client/channel/types.ts +++ b/src/client/channel/types.ts @@ -1,7 +1,7 @@ import type { ChannelMessage, ChannelSnapshot, ChannelUser, RoomSettings } from "./protocol"; import type { ChannelAttachments, DraftFile } from "./attachments"; import type { NativeCaptureTarget } from "../native/wire"; -import type { NativeCaptureSources, ChannelRemoteControlState } from "./app-link"; +import type { NativeCaptureRequest, NativeCaptureSources, ChannelRemoteControlState } from "./app-link"; import type { RemoteStopShortcut } from "../native/wire"; import type { InputTransport } from "../remote-control/input-route"; import type { RemoteControlMode } from "../remote-control/protocol"; @@ -49,6 +49,7 @@ export interface ChannelActions { setRoles(userId: string, roles: string[]): Promise; startScreen(roomId: string): Promise; nativeSources(): Promise; + nativeCaptureRequest(roomId: string): NativeCaptureRequest | undefined; startNativeScreen(roomId: string, target: NativeCaptureTarget, audio?: boolean): Promise; stopScreen(publicationId: string): Promise; watch(publicationId: string): Promise; diff --git a/src/client/channel/use-channel.ts b/src/client/channel/use-channel.ts index 1a5335db7..9cb81de04 100644 --- a/src/client/channel/use-channel.ts +++ b/src/client/channel/use-channel.ts @@ -33,6 +33,7 @@ export function useChannel(onInvitation?: (roomId: string) => void): ChannelCont attachments: session.attachments, loadHistory: session.loadHistory, loadLatestHistory: session.loadLatestHistory, setRoles: session.setRoles, startScreen: session.startScreen, nativeSources: session.nativeSources, startNativeScreen: session.startNativeScreen, + nativeCaptureRequest: session.nativeCaptureRequest, stopScreen: session.stopScreen, watch: session.watch, unwatch: session.unwatch, screenPresentation: session.screenPresentation, inputPolicy: session.inputPolicy, inputDecide: session.inputDecide, inputSimultaneous: session.inputSimultaneous, inputShortcut: session.inputShortcut, joinVoice: session.joinVoice, leaveVoice: session.leaveVoice, setMuted: session.setMuted, diff --git a/src/client/native/activation.ts b/src/client/native/activation.ts index fee2a9038..6d2f97120 100644 --- a/src/client/native/activation.ts +++ b/src/client/native/activation.ts @@ -1,6 +1,8 @@ // Android intents only foreground Piik. App-owned pending requests still own // permission, and the normal loopback approval/health checks own Site access. export function androidAppIntent(action: unknown, userAgent = typeof navigator === "undefined" ? "" : navigator.userAgent): string | null { + // A connected App can name its installed package without frontend version rules. + if (typeof action === "string" && /^intent:\/\/media#Intent;scheme=piik;package=[A-Za-z0-9_.]+;end$/.test(action)) return action; if (action !== "piik://app" && action !== "piik://media") return null; // A connected App supplies its own media action. Android tablets can report // a desktop UA; only an unconnected cold wake needs the browser OS hint. diff --git a/src/client/native/wire.ts b/src/client/native/wire.ts index e105e1aac..131c86740 100644 --- a/src/client/native/wire.ts +++ b/src/client/native/wire.ts @@ -94,7 +94,7 @@ const nativeDisplayTargetSchema = z const nativePickerTargetSchema = z .object({ kind: z.literal("picker"), - sourceId: decimalIdentifierSchema, + sourceId: decimalIdentifierSchema.or(z.literal("0")), title: z.string().min(1).max(4096), }) .strict(); diff --git a/tests/channel-session.test.ts b/tests/channel-session.test.ts index b6af22eb4..9306ef2d4 100644 --- a/tests/channel-session.test.ts +++ b/tests/channel-session.test.ts @@ -3,6 +3,7 @@ import { ChannelConversation } from "../src/client/channel/conversation"; import { ChannelSession } from "../src/client/channel/session"; import * as hosting from "../src/client/channel/hosting"; import * as appLink from "../src/client/channel/app-link"; +import * as nativeActivation from "../src/client/native/activation"; import * as launchSession from "../src/client/lib/session"; import { ChannelMedia } from "../src/client/channel/media"; import { ChannelTransport } from "../src/client/channel/transport"; @@ -281,11 +282,11 @@ test("local stop does not retire another capture acknowledged before its authori }); test("Native capture previews before its snapshot, keeps picture on audio failure, and stops through its App owner", async () => { + vi.stubGlobal("navigator", { userAgent: "test", userActivation: { isActive: false } }); vi.mocked(launchSession.isClientActivated).mockReturnValue(true); vi.spyOn(appLink, "discoverChannelAppHealth").mockResolvedValue({ service: "piik-channel-app", protocol: 1, port: 8793, token: "approved" }); const { session, socket } = await setup(); const app = ChannelSocket.current; - const publicationId = crypto.randomUUID(); try { await app.onopen?.(); app.receive({ id: app.sent.at(-1)!.id, result: null }); @@ -293,14 +294,19 @@ test("Native capture previews before its snapshot, keeps picture on audio failur const target = { kind: "display" as const, sourceId: "1", title: "Test display" }; const listing = session.nativeSources(); await vi.waitFor(() => expect(app.sent.at(-1)?.type).toBe("targets")); - const sources = { sources: [target], processAudio: false, systemAudio: true }; + const activationURL = "intent://media#Intent;scheme=piik;package=tv.piik.android.test;end"; + const sources = { sources: [target], processAudio: false, systemAudio: true, activationURL }; app.receive({ id: app.sent.at(-1)!.id, result: sources }); await expect(listing).resolves.toEqual(sources); const starting = session.startNativeScreen("first", target, true); await vi.waitFor(() => expect(app.sent.at(-1)?.type).toBe("start_capture")); - expect(app.sent.at(-1)).toMatchObject({ type: "start_capture", roomId: "first", target, audio: true }); - app.receive({ id: app.sent.at(-1)!.id, result: { publicationId } }); + const publicationId = app.sent.at(-1)!.publicationId as string; + expect(app.sent.at(-1)).toMatchObject({ type: "start_capture", publicationId, roomId: "first", target, audio: true }); + expect(session.nativeCaptureRequest("first")).toEqual({ publicationId, activationURL }); + app.receive({ id: app.sent.at(-1)!.id, result: null }); await vi.waitFor(() => expect(socket.sent.at(-1)?.type).toBe("subscribe")); + expect(session.nativeCaptureRequest("first")).toBeUndefined(); + expect(session.getSnapshot().pending.has("screen:first")).toBe(true); const watch = socket.sent.at(-1)!; const state = session.getSnapshot().state!; socket.receive({ type: "state", state }); @@ -315,7 +321,7 @@ test("Native capture previews before its snapshot, keeps picture on audio failur expect(session.getSnapshot().state?.subscriptions).toEqual([publicationId]); const controllerSessionId = crypto.randomUUID(), intent = crypto.randomUUID().replaceAll("-", ""); - const remote = { mode: "ask", platform: "windows", requests: [{ id: intent, peerId: controllerSessionId, state: "pending" }] }; + const remote = { mode: "ask", platform: "windows", canSetStopShortcut: false, requests: [{ id: intent, peerId: controllerSessionId, state: "pending" }] }; app.receive({ type: "input_state", publicationId, state: remote }); expect(session.getSnapshot().remoteControls.get(publicationId)).toEqual(remote); await expect(session.inputShortcut(publicationId)).resolves.toEqual({ key: 10, available: false }); @@ -363,6 +369,68 @@ test("Native capture previews before its snapshot, keeps picture on audio failur } finally { session.close(); } }); +test("pending Native capture stays page-owned through same-page stop and close", async () => { + vi.mocked(launchSession.isClientActivated).mockReturnValue(true); + vi.spyOn(appLink, "discoverChannelAppHealth").mockResolvedValue({ service: "piik-channel-app", protocol: 1, port: 8793, token: "approved" }); + const { session, socket } = await setup(); + const app = ChannelSocket.current; + try { + await app.onopen?.(); + app.receive({ id: app.sent.at(-1)!.id, result: null }); + await vi.waitFor(() => expect(session.getSnapshot().appConnected).toBe(true)); + const target = { kind: "display" as const, sourceId: "1", title: "Test display" }; + const activationURL = "intent://media#Intent;scheme=piik;package=tv.piik.android.test;end"; + const sources = { sources: [target], processAudio: false, systemAudio: true, activationURL }; + const capabilities = session.nativeSources(); + await vi.waitFor(() => expect(app.sent.at(-1)?.type).toBe("targets")); + app.receive({ id: app.sent.at(-1)!.id, result: sources }); + await capabilities; + const activate = vi.spyOn(nativeActivation, "activateNativePicker").mockImplementation(() => { + expect(app.sent.at(-1)?.type).toBe("start_capture"); + }); + const starting = session.startNativeScreen("first", target).catch(error => error); + await vi.waitFor(() => expect(app.sent.at(-1)?.type).toBe("start_capture")); + const request = app.sent.at(-1)!; + const publicationId = request.publicationId as string; + expect(publicationId).toEqual(expect.any(String)); + expect(session.getSnapshot().ownedScreens.has(publicationId)).toBe(true); + expect(session.nativeCaptureRequest("first")).toEqual({ publicationId, activationURL }); + expect(activate).toHaveBeenCalledWith(activationURL); + + const listing = session.nativeSources(); + await vi.waitFor(() => expect(app.sent.at(-1)?.type).toBe("targets")); + app.receive({ id: app.sent.at(-1)!.id, result: sources }); + await listing; + const stopping = session.stopScreen(publicationId); + expect(app.sent.at(-1)).toMatchObject({ type: "stop_capture", publicationId }); + app.receive({ id: app.sent.at(-1)!.id, result: null }); + app.receive({ id: request.id, error: "capture_cancelled" }); + await stopping; + expect(await starting).toMatchObject({ name: "AbortError" }); + expect(session.getSnapshot().ownedScreens.size).toBe(0); + expect(session.nativeCaptureRequest("first")).toBeUndefined(); + expect(session.getSnapshot().error).toBeNull(); + expect(socket.sent.some(command => command.type === "subscribe")).toBe(false); + + const failed = session.startNativeScreen("first", target).catch(error => error); + await vi.waitFor(() => expect(app.sent.at(-1)?.type).toBe("start_capture")); + app.receive({ id: app.sent.at(-1)!.id, error: "capture_failed" }); + await vi.waitFor(() => expect(app.sent.at(-1)?.type).toBe("stop_capture")); + expect(session.nativeCaptureRequest("first")).toBeUndefined(); + app.receive({ id: app.sent.at(-1)!.id, result: null }); + expect((await failed).message).toBe("capture_failed"); + + const closing = session.startNativeScreen("first", target).catch(error => error); + await vi.waitFor(() => expect(app.sent.at(-1)?.type).toBe("start_capture")); + expect(session.getSnapshot().ownedScreens.size).toBe(1); + session.close(); + expect((await closing).message).toBe("app_disconnected"); + expect(app.readyState).toBe(3); + expect(session.getSnapshot().ownedScreens.size).toBe(0); + expect(session.nativeCaptureRequest("first")).toBeUndefined(); + } finally { session.close(); } +}); + test("remembered App intent does not prevent Browser hosting when no App is connected", async () => { vi.mocked(launchSession.isClientActivated).mockReturnValue(true); const discovery = vi.spyOn(appLink, "discoverChannelAppHealth").mockResolvedValue(null); diff --git a/tests/native-activation.test.ts b/tests/native-activation.test.ts index 0777f2457..1083a488f 100644 --- a/tests/native-activation.test.ts +++ b/tests/native-activation.test.ts @@ -41,6 +41,16 @@ describe("Android App foreground actions", () => { expect(androidAppIntent("piik://app", desktop)).toBeNull(); }); + it("uses a connected App's complete package-specific media capability", () => { + const activation = "intent://media#Intent;scheme=piik;package=tv.piik.android.test;end"; + const assign = vi.fn(); + vi.stubGlobal("navigator", { userAgent: "desktop", userActivation: { isActive: true } }); + vi.stubGlobal("window", { location: { assign } }); + activateNativePicker(activation); + expect(assign).toHaveBeenCalledWith(activation); + expect(androidAppIntent(activation.replace(";end", ";S.extra=value;end"))).toBeNull(); + }); + it("keeps activation optional and validates the known health extension", () => { const health = { protocol: NATIVE_CLIENT_PROTOCOL, service: "piik-client", port: NATIVE_CLIENT_PORT_START, instanceToken: "a".repeat(43), nativeMedia: {} }; diff --git a/tests/native-client.test.ts b/tests/native-client.test.ts index e8f557660..8f269dbd1 100644 --- a/tests/native-client.test.ts +++ b/tests/native-client.test.ts @@ -898,7 +898,7 @@ describe("native App private wire", () => { } finally { client.close(); } }); - it("keeps 64-bit Windows identities as exact decimal strings", () => { + it("keeps exact positive physical identities and accepts system picker zero", () => { expect( nativeCaptureTargetSchema.safeParse({ kind: "window", @@ -931,6 +931,15 @@ describe("native App private wire", () => { title: "System picker", }).success, ).toBe(true); + expect(nativeCaptureTargetSchema.safeParse({ + kind: "picker", sourceId: "0", title: "System picker", + }).success).toBe(true); + expect(nativeCaptureTargetSchema.safeParse({ + kind: "display", sourceId: "0", title: "Display", + }).success).toBe(false); + expect(nativeCaptureTargetSchema.safeParse({ + kind: "window", sourceId: "0", pid: 1234, creationTime: "134327999999999999", title: "Game", + }).success).toBe(false); }); it("fences native events by share and connection identity", () => {