@octane-xplat/camera 0.19.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/README.md +2 -132
  2. package/package.json +20 -25
  3. package/platforms/android/java/com/octanexplat/camera/CameraPreviewView.java +24 -0
  4. package/platforms/android/java/com/octanexplat/camera/CameraSessionBridge.java +153 -21
  5. package/platforms/ios/src/XplatSwitchingMovieWriter.swift +557 -0
  6. package/src/CameraView.android.tsrx +187 -154
  7. package/src/CameraView.ios.tsrx +124 -110
  8. package/src/CameraView.macos.tsrx +103 -96
  9. package/src/CameraView.tsrx +2 -0
  10. package/src/CameraView.web.tsrx +157 -146
  11. package/src/CameraView.windows.tsrx +134 -125
  12. package/src/camera-host.macos.ts +1059 -0
  13. package/src/camera-permission.mobile.ts +85 -81
  14. package/src/camera-permission.windows.ts +56 -53
  15. package/src/camera-session.ios.ts +89 -61
  16. package/src/camera-session.macos.ts +51 -49
  17. package/src/camera-session.windows.ts +113 -105
  18. package/src/host-movie.web.ts +257 -231
  19. package/src/index.ts +28 -26
  20. package/src/index.web.ts +27 -25
  21. package/src/layout-child.ts +86 -79
  22. package/src/layout-child.web.ts +54 -53
  23. package/src/layout-child.windows.ts +80 -74
  24. package/src/movie-metadata.web.ts +84 -81
  25. package/src/movie-storage.web.ts +142 -135
  26. package/src/movie-writer.ios.ts +170 -0
  27. package/src/photo-lifecycle.macos.ts +60 -0
  28. package/src/photo-sheet.macos.ts +505 -0
  29. package/src/preview-display.ios.ts +69 -0
  30. package/src/preview-pinch.ts +41 -0
  31. package/src/preview-tap.ts +22 -21
  32. package/src/props.ts +115 -93
  33. package/src/recording-haptics.ios.ts +39 -0
  34. package/src/recording-source.web.ts +159 -0
  35. package/src/session-backend.android.ts +552 -410
  36. package/src/session-backend.ios.ts +1500 -1148
  37. package/src/session-backend.linux.ts +886 -860
  38. package/src/session-backend.macos.ts +697 -679
  39. package/src/session-backend.ts +51 -49
  40. package/src/session-backend.web.ts +1181 -867
  41. package/src/session-backend.windows.ts +1540 -1467
  42. package/src/session-core.ts +925 -714
  43. package/src/session.ts +12 -12
  44. package/src/style-merge.ts +40 -37
  45. package/src/synthetic-session.ts +391 -339
  46. package/src/types.ts +372 -298
  47. package/types/generated/.tsrx-typegen-manifest.json +4 -24
  48. package/types/generated/CameraView.d.ts +2 -0
  49. package/types/generated/camera-host.macos.d.ts +33 -0
  50. package/types/generated/index.d.ts +27 -26
  51. package/types/generated/photo-lifecycle.macos.d.ts +12 -0
  52. package/types/generated/photo-sheet.macos.d.ts +36 -0
  53. package/types/generated/props.d.ts +24 -2
  54. package/types/generated/session-core.d.ts +30 -1
  55. package/types/generated/synthetic-session.d.ts +7 -0
  56. package/types/generated/types.d.ts +75 -1
  57. package/platforms/macos/src/CameraOwnership.swift +0 -22
  58. package/platforms/macos/src/PhotoCaptureLifecycle.swift +0 -34
  59. package/platforms/macos/src/XplatCameraHost.swift +0 -639
  60. package/platforms/macos/src/XplatPhotoCaptureSheet.swift +0 -192
  61. package/types/generated/CameraView.android.d.ts +0 -9
  62. package/types/generated/CameraView.ios.d.ts +0 -5
  63. package/types/generated/CameraView.macos.d.ts +0 -5
  64. package/types/generated/CameraView.mobile.d.ts +0 -5
  65. package/types/generated/CameraView.windows.d.ts +0 -11
  66. package/types/generated/camera-permission.mobile.d.ts +0 -2
  67. package/types/generated/camera-permission.windows.d.ts +0 -6
  68. package/types/generated/camera-session.ios.d.ts +0 -2
  69. package/types/generated/camera-session.macos.d.ts +0 -10
  70. package/types/generated/camera-session.windows.d.ts +0 -9
  71. package/types/generated/host-movie.web.d.ts +0 -100
  72. package/types/generated/index.web.d.ts +0 -7
  73. package/types/generated/layout-child.d.ts +0 -11
  74. package/types/generated/layout-child.windows.d.ts +0 -13
  75. package/types/generated/movie-metadata.web.d.ts +0 -9
  76. package/types/generated/movie-storage.web.d.ts +0 -5
  77. package/types/generated/preview-tap.d.ts +0 -7
  78. package/types/generated/session-backend.android.d.ts +0 -3
  79. package/types/generated/session-backend.ios.d.ts +0 -5
  80. package/types/generated/session-backend.linux.d.ts +0 -3
  81. package/types/generated/session-backend.macos.d.ts +0 -8
  82. package/types/generated/session-backend.web.d.ts +0 -3
  83. package/types/generated/session-backend.windows.d.ts +0 -37
  84. package/types/generated/style-merge.d.ts +0 -8
package/README.md CHANGED
@@ -1,135 +1,5 @@
1
1
  # `@octane-xplat/camera`
2
2
 
3
- Live camera preview for Octane xplat apps: `getUserMedia` video on web,
4
- `AVCaptureSession` on iOS, CameraX on Android,
5
- `AVCaptureSession` + `AVCaptureVideoPreviewLayer` on macOS (AppKit), and
6
- `MediaCapture` + `CaptureElement` on the Windows (WinUI 3) target.
3
+ [Documentation](https://octane-xplat.goddardai.org/package-camera).
7
4
 
8
- ```sh
9
- bun add @octane-xplat/camera
10
- ```
11
-
12
- ```tsx
13
- import { CameraView } from '@octane-xplat/camera'
14
-
15
- export function Preview() {
16
- return (
17
- <CameraView
18
- facing="back"
19
- active
20
- onReady={() => console.log('Preview running')}
21
- onError={(error) => console.log(error.message)}
22
- />
23
- )
24
- }
25
- ```
26
-
27
- This is the preview surface only — for one-shot still capture and library
28
- picking use [`@octane-xplat/media`](https://github.com/octane-xplat/octane-xplat/blob/main/packages/media/README.md). Permissions are
29
- requested when the session starts; `onError` is how a denial shows up.
30
- `ref` hands you the platform surface (`HTMLVideoElement` on web) for
31
- controls the shared props don't cover, and the `ios`/`android`/`web`/
32
- `windows` escape props apply after the shared props. On macOS the leaf is a
33
- compiled Swift `XplatCameraHost` that owns the capture session; the app bundle
34
- needs `NSCameraUsageDescription` (and `NSMicrophoneUsageDescription` for
35
- audio) declared through `xplat.targets.macos.package.infoPlist`.
36
-
37
- ```tsx
38
- // Preview.web.tsx — browser properties belong in this platform file.
39
- import { CameraView } from '@octane-xplat/camera'
40
-
41
- export function Preview() {
42
- return (
43
- <CameraView
44
- web={{ playsInline: true }}
45
- ref={(handle) => console.log(handle.native)}
46
- onError={(error) => console.log(error.message)}
47
- />
48
- )
49
- }
50
- ```
51
-
52
- ## Tap-to-focus
53
-
54
- `CameraView` reports where the user tapped as a normalized point —
55
- `{x: 0, y: 0}` is the top-left corner of the preview, `{x: 1, y: 1}` the
56
- bottom-right. Hand the point to a session's `focusAtPoint` to meter one
57
- autofocus and auto-exposure pass there:
58
-
59
- ```tsx
60
- import { CameraView, createCameraSession } from '@octane-xplat/camera'
61
-
62
- const session = createCameraSession()
63
-
64
- export function FocusablePreview() {
65
- return <CameraView session={session} onTap={(point) => session.focusAtPoint(point)} />
66
- }
67
- ```
68
-
69
- `onTap` is a pure notification — it never takes over the gesture, so
70
- double-tap and pan recognizers layered over the preview keep working.
71
- `focusAtPoint` needs a session (it drives the camera the preview
72
- attaches) and quietly does nothing on cameras that cannot meter at a
73
- point — front cameras are often fixed-focus. Check
74
- `capabilities().focusPointOfInterest` and `exposurePointOfInterest`
75
- before showing focus UI. Metering lands on iOS, Android, and macOS; the
76
- tap event fires on iOS, Android, and web.
77
-
78
- ## Movie recording
79
-
80
- `createCameraSession` creates a shared camera owner: the same session can
81
- drive a `CameraView` preview and one movie-recording attempt at a time.
82
- Pass the session to `CameraView` instead of `facing`; the preview attaches
83
- the camera the session owns. Recording requires an attached, ready preview.
84
-
85
- ```tsx
86
- import { CameraView, createCameraSession } from '@octane-xplat/camera'
87
-
88
- const session = createCameraSession({ camera: 'default' })
89
-
90
- export function Recorder() {
91
- return <CameraView session={session} />
92
- }
93
- ```
94
-
95
- A take settles after the movie is finalized, metadata is verified, and local
96
- storage is committed. Native output lives in app-private files — including the
97
- packaged Linux WebKitGTK host, which writes under the app's data directory;
98
- Web uses persistent origin storage. Reopen it with `session.openOutput(output)`.
99
-
100
- ```ts
101
- const take = session.startRecording({ maximumDurationMs: 30_000 })
102
- // … later, on a stop press or a maximum-duration limit:
103
- const outcome = await take.stop()
104
- if (outcome.kind === 'clip') {
105
- const clip = outcome.clip
106
- console.log(clip.durationMs, clip.width, clip.height, clip.output)
107
- }
108
- ```
109
-
110
- One preview and one recording per session; a second `startRecording` throws
111
- `CameraCaptureError` with `kind: 'busy'`. Check `session.capabilities()` for
112
- `supported`/`available` before presenting capture UI, and `session.snapshot()`
113
- or `session.subscribe` for state. iOS, Android, Web, macOS, the Windows WinUI
114
- target, and the packaged Linux WebKitGTK host have recording adapters; Web
115
- requires persistent origin storage.
116
- macOS writes app-private MOV files through `AVCaptureMovieFileOutput` and
117
- reports finalized track metadata; on macOS 14+ the four cardinal orientations
118
- are lockable. Inside a qualified `xplat` WKWebView host the Web backend stores
119
- output in the app's private storage root instead of IndexedDB. Windows records
120
- through `MediaCapture` into app-private MP4 files and is pending real-host
121
- qualification. On Linux the GJS/WebKitGTK host owns media permissions and
122
- writes MP4 clips under the app's data directory.
123
- See [Record and reopen a camera movie](https://octane-xplat.goddardai.org/movie-capture) for
124
- explicit permission actions, audio, local output, and qualification limits.
125
-
126
- ```ts
127
- console.log(await session.permissions())
128
- // Call from an app button:
129
- await session.requestPermission('camera')
130
- console.log(await session.capabilities())
131
- ```
132
-
133
- Guide: [Building screens](https://octane-xplat.goddardai.org/primitives) (leaf components);
134
- component index: [`docs/app/components.md`](https://octane-xplat.goddardai.org/components).
135
- Exercised by [`CameraDemo`](https://github.com/octane-xplat/octane-xplat/blob/main/packages/demos/src/CameraDemo.tsrx).
5
+ [API reference](https://octane-xplat.goddardai.org/api-camera).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@octane-xplat/camera",
3
- "version": "0.19.0",
3
+ "version": "0.20.0",
4
4
  "description": "Live camera preview for Octane xplat — web getUserMedia + native capture (AVCapture / CameraX)",
5
5
  "keywords": [
6
6
  "android",
@@ -37,6 +37,11 @@
37
37
  "web": "./src/index.web.ts",
38
38
  "native": "./src/index.ts",
39
39
  "default": "./src/index.ts"
40
+ },
41
+ "./photo-sheet.macos": {
42
+ "types": "./src/photo-sheet.macos.ts",
43
+ "native": "./src/photo-sheet.macos.ts",
44
+ "default": "./src/photo-sheet.macos.ts"
40
45
  }
41
46
  },
42
47
  "publishConfig": {
@@ -45,38 +50,40 @@
45
50
  "scripts": {
46
51
  "typegen": "tsrx-typegen --target camera",
47
52
  "prepack": "bun run typegen && tsrx-typegen --pack-check",
53
+ "test:ios-writer": "node tests/ios-writer-simulator.mjs",
54
+ "test:ios-device": "node tests/ios-device.mjs",
48
55
  "test:packed": "node tests/packed-consumer.mjs",
49
56
  "pack:check": "tsrx-typegen --pack-check",
50
57
  "test": "vitest run && node --test tests/*.test.mjs",
51
- "test:macos-photo": "node tests/photo-native.macos.mjs",
52
- "test:macos-photo-hardware": "node tests/photo-hardware.macos.mjs",
53
58
  "test:web": "node tests/browser-conformance.web.mjs",
54
59
  "test:webkitgtk": "node tests/webkitgtk-conformance.linux.mjs",
55
- "typecheck": "tsrx-tsc --noEmit -p tsconfig.types.json"
60
+ "typecheck": "tsc --runExternalCode --noEmit -p tsconfig.types.json",
61
+ "test:macos-runtime": "node tests/packed-consumer.mjs --macos-native"
56
62
  },
57
63
  "dependencies": {
58
- "@octane-xplat/jsx": "0.19.0",
59
- "@octane-xplat/platform": "0.19.0",
64
+ "@octane-xplat/jsx": "0.20.0",
65
+ "@octane-xplat/platform": "0.20.0",
60
66
  "mediabunny": "1.62.1"
61
67
  },
62
68
  "devDependencies": {
63
69
  "@nativescript-community/octane": "0.2.5",
64
70
  "@nativescript/core": "9.1.3",
65
- "@octane-xplat/macos-renderer": "0.19.0",
71
+ "@octane-xplat/macos-appkit": "0.20.0",
66
72
  "@octanejs/vite-plugin": "0.5.0",
67
73
  "octane": "0.16.3",
68
- "tsrx-typegen": "0.5.0",
69
- "typescript": "5.9.3",
70
- "vite": "8.3.0",
74
+ "tsrx-typegen": "0.6.1",
75
+ "typescript": "7.1.0-beta",
76
+ "vite": "8.3.6",
71
77
  "vitest": "4.1.11",
72
- "@tsrx/typescript-plugin": "0.4.11",
73
- "@nativescript/macos-node-api": "0.4.4-next.2026-08-09-31292056208"
78
+ "@nativescript/macos-node-api": "0.5.0-beta.0",
79
+ "@tsrx/content-mapper": "0.1.2",
80
+ "typescript-classic": "npm:typescript@5.9.3"
74
81
  },
75
82
  "peerDependencies": {
76
83
  "@nativescript-community/octane": ">=0.2.1 <1",
77
84
  "@nativescript/core": ">=9.1.0 <10",
78
85
  "octane": ">=0.6.3 <1",
79
- "@nativescript/macos-node-api": "0.4.4-next.2026-08-09-31292056208"
86
+ "@nativescript/macos-node-api": "0.5.0-beta.0"
80
87
  },
81
88
  "peerDependenciesMeta": {
82
89
  "@nativescript-community/octane": {
@@ -98,17 +105,5 @@
98
105
  "android": "7.0.0"
99
106
  }
100
107
  },
101
- "xplat": {
102
- "macos": {
103
- "swiftHeaderImports": [
104
- "AppKit/AppKit.h"
105
- ],
106
- "frameworks": [
107
- "AVFoundation",
108
- "CoreMedia",
109
- "AppKit"
110
- ]
111
- }
112
- },
113
108
  "types": "./types/generated/index.d.ts"
114
109
  }
@@ -3,6 +3,8 @@ package com.octanexplat.camera;
3
3
  import android.content.Context;
4
4
  import android.view.ViewGroup;
5
5
  import android.widget.FrameLayout;
6
+ import android.widget.ImageView;
7
+ import android.graphics.Bitmap;
6
8
 
7
9
  import androidx.camera.core.MeteringPoint;
8
10
  import androidx.camera.core.Preview;
@@ -14,6 +16,7 @@ import androidx.lifecycle.LifecycleRegistry;
14
16
  public final class CameraPreviewView extends FrameLayout implements LifecycleOwner {
15
17
  private final LifecycleRegistry lifecycle;
16
18
  private final PreviewView previewView;
19
+ private final ImageView heldPreview;
17
20
  private boolean cameraActive = true;
18
21
  private boolean attached;
19
22
 
@@ -22,6 +25,9 @@ public final class CameraPreviewView extends FrameLayout implements LifecycleOwn
22
25
  lifecycle = new LifecycleRegistry(this);
23
26
  lifecycle.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
24
27
  previewView = new PreviewView(context);
28
+ // TextureView permits retaining the last preview frame during a
29
+ // live input swap. The recording itself stays in CameraX.
30
+ previewView.setImplementationMode(PreviewView.ImplementationMode.COMPATIBLE);
25
31
  previewView.setScaleType(PreviewView.ScaleType.FILL_CENTER);
26
32
  addView(
27
33
  previewView,
@@ -30,6 +36,24 @@ public final class CameraPreviewView extends FrameLayout implements LifecycleOwn
30
36
  ViewGroup.LayoutParams.MATCH_PARENT
31
37
  )
32
38
  );
39
+ heldPreview = new ImageView(context);
40
+ heldPreview.setScaleType(ImageView.ScaleType.FIT_XY);
41
+ heldPreview.setVisibility(GONE);
42
+ addView(heldPreview, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
43
+ }
44
+
45
+ /** Retain this camera's already transformed preview pixels in memory;
46
+ * never persist them or use a separate camera acquisition. */
47
+ public boolean holdPreview() {
48
+ Bitmap frame = previewView.getBitmap();
49
+ if (frame == null) return false;
50
+ heldPreview.setImageBitmap(frame);
51
+ heldPreview.setVisibility(VISIBLE);
52
+ return true;
53
+ }
54
+ public void releaseHeldPreview() {
55
+ heldPreview.setVisibility(GONE);
56
+ heldPreview.setImageDrawable(null);
33
57
  }
34
58
 
35
59
  @Override
@@ -20,6 +20,7 @@ import androidx.camera.core.DynamicRange;
20
20
  import androidx.camera.core.FocusMeteringAction;
21
21
  import androidx.camera.core.MeteringPoint;
22
22
  import androidx.camera.core.MirrorMode;
23
+ import androidx.camera.core.ZoomState;
23
24
  import androidx.camera.core.Preview;
24
25
  import androidx.camera.lifecycle.ProcessCameraProvider;
25
26
  import androidx.camera.video.FileOutputOptions;
@@ -82,6 +83,13 @@ public final class CameraSessionBridge implements LifecycleOwner {
82
83
  private String cameraId = "";
83
84
  private String facing;
84
85
  private int rotation;
86
+ private Quality recordingQuality;
87
+ private boolean switching;
88
+ private boolean awaitingSwitchCommit;
89
+ private boolean rollingBack;
90
+ private String switchPrevious;
91
+ private String switchError;
92
+ private Runnable switchTimeout;
85
93
 
86
94
  public CameraSessionBridge(Context context, Listener listener) {
87
95
  this.context = context.getApplicationContext();
@@ -95,8 +103,19 @@ public final class CameraSessionBridge implements LifecycleOwner {
95
103
  * not just that the preview view reports streaming — a stream-state
96
104
  * event can lead the first measured frame, and a stale STREAMING
97
105
  * replayed by LiveData on rebind can precede the new camera's open. */
98
- private void updateReady() { ready(streaming && sourceFrameRate > 0); }
99
- public boolean isReady() { return ready && sourceFrameRate > 0 && !detached && !released; }
106
+ private void updateReady() {
107
+ boolean value = streaming && sourceFrameRate > 0;
108
+ ready(value);
109
+ if (value && switching) {
110
+ boolean restored = rollingBack;
111
+ String failure = switchError;
112
+ awaitingSwitchCommit = !restored;
113
+ clearSwitch(!restored);
114
+ try { emit(restored ? "switchFailed" : "switchFinished", restored ? failure : new JSONObject().put("id", cameraId).put("label", cameraId).put("facing", facing).toString()); }
115
+ catch (Exception cause) { cancelCameraSwitch(); emit("switchFailed", cause.toString()); }
116
+ }
117
+ }
118
+ public boolean isReady() { return ready && streaming && sourceFrameRate > 0 && !detached && !released; }
100
119
  public long elapsedMs() { return elapsed; }
101
120
  private void failure(String stage, String kind, String message) {
102
121
  try { emit("failed", new JSONObject().put("stage", stage).put("kind", kind).put("message", message).toString()); }
@@ -106,7 +125,16 @@ public final class CameraSessionBridge implements LifecycleOwner {
106
125
  public void attach(CameraPreviewView view, String selected) {
107
126
  if (host == view && !detached && preview != null && selection.equals(selected)) return;
108
127
  if (recording != null || released) throw new IllegalStateException("Camera is finalizing or disposed");
109
- unbind();
128
+ bindCamera(view, selected, false);
129
+ }
130
+ private void bindCamera(CameraPreviewView view, String selected, boolean preserveRecording) {
131
+ if (preserveRecording) {
132
+ if (camera != null) camera.getCameraInfo().getCameraState().removeObservers(this);
133
+ if (observedHost != null) { observedHost.getStreamState().removeObservers(this); observedHost = null; }
134
+ provider.unbind(preview, video);
135
+ streaming = false; ready(false);
136
+ if (!switching || recording == null || finalizing || released || detached || backgrounded) return;
137
+ } else unbind();
110
138
  host = view;
111
139
  detached = false;
112
140
  selection = selected;
@@ -125,24 +153,30 @@ public final class CameraSessionBridge implements LifecycleOwner {
125
153
  java.util.List<Quality> qualities = Recorder.getVideoCapabilities(info).getSupportedQualities(DynamicRange.SDR);
126
154
  if (qualities.isEmpty()) throw new IllegalArgumentException("No SDR recording profile");
127
155
  Quality quality = qualities.contains(Quality.HD) ? Quality.HD : qualities.get(0);
128
- Recorder recorder = new Recorder.Builder().setQualitySelector(QualitySelector.from(quality)).build();
129
- rotation = view.getDisplay() == null ? Surface.ROTATION_0 : view.getDisplay().getRotation();
130
- video = new VideoCapture.Builder<>(recorder).setMirrorMode(MirrorMode.MIRROR_MODE_OFF).setTargetRotation(rotation).setTargetFrameRate(new android.util.Range<>(30, 30)).build();
156
+ if (!preserveRecording) {
157
+ recordingQuality = quality;
158
+ Recorder recorder = new Recorder.Builder().setQualitySelector(QualitySelector.from(quality)).build();
159
+ rotation = view.getDisplay() == null ? Surface.ROTATION_0 : view.getDisplay().getRotation();
160
+ video = new VideoCapture.Builder<>(recorder).setMirrorMode(MirrorMode.MIRROR_MODE_OFF).setTargetRotation(rotation).setTargetFrameRate(new android.util.Range<>(30, 30)).build();
161
+ }
131
162
  Preview.Builder previewBuilder = new Preview.Builder().setTargetRotation(rotation);
132
163
  sourceFrameRate = 0; lastFrameTime = 0;
133
164
  new androidx.camera.camera2.interop.Camera2Interop.Extender<>(previewBuilder).setSessionCaptureCallback(new android.hardware.camera2.CameraCaptureSession.CaptureCallback() {
134
165
  @Override public void onCaptureCompleted(android.hardware.camera2.CameraCaptureSession session, android.hardware.camera2.CaptureRequest request, android.hardware.camera2.TotalCaptureResult result) {
135
- if (released || epoch != generation) return;
136
166
  Long timestamp = result.get(android.hardware.camera2.CaptureResult.SENSOR_TIMESTAMP);
137
- if (timestamp != null && timestamp > lastFrameTime) {
138
- if (lastFrameTime > 0) {
139
- boolean firstRate = sourceFrameRate == 0;
140
- sourceFrameRate = 1_000_000_000.0 / (timestamp - lastFrameTime);
141
- // Runs on the camera executor; readiness is emitted on main.
142
- if (firstRate) handler.post(() -> updateReady());
167
+ // Retire callbacks on main alongside rebind/cancellation. An old
168
+ // camera-executor callback must not seed the new source's timing.
169
+ handler.post(() -> {
170
+ if (released || detached || epoch != generation) return;
171
+ if (timestamp != null && timestamp > lastFrameTime) {
172
+ if (lastFrameTime > 0) {
173
+ boolean firstRate = sourceFrameRate == 0;
174
+ sourceFrameRate = 1_000_000_000.0 / (timestamp - lastFrameTime);
175
+ if (firstRate) updateReady();
176
+ }
177
+ lastFrameTime = timestamp;
143
178
  }
144
- lastFrameTime = timestamp;
145
- }
179
+ });
146
180
  }
147
181
  });
148
182
  preview = previewBuilder.build();
@@ -151,16 +185,17 @@ public final class CameraSessionBridge implements LifecycleOwner {
151
185
  camera.getCameraInfo().getCameraState().observe(this, state -> {
152
186
  if (released || epoch != generation) return;
153
187
  if (state.getError() != null) {
188
+ if (switching) { failSwitch("Camera reported an error during switching"); return; }
154
189
  emit("availability", "false");
155
190
  ready(false);
156
- if (recording != null) { emit("interruption", "cameraInUse"); stop(); }
191
+ if (recording != null && !switching) { emit("interruption", "cameraInUse"); stop(); }
157
192
  } else if (state.getType() == CameraState.Type.CLOSED) {
158
193
  // Plain CLOSED is the camera's normal resting state —
159
194
  // every bind starts here and it can be delivered late
160
195
  // relative to stream state — so it must not flip
161
196
  // availability while a live preview keeps streaming.
162
197
  ready(false);
163
- if (recording != null) { emit("interruption", "cameraInUse"); stop(); }
198
+ if (recording != null && !switching) { emit("interruption", "cameraInUse"); stop(); }
164
199
  } else if (state.getType() == CameraState.Type.OPEN) {
165
200
  // An open recovers availability without waiting for a
166
201
  // stream-state cycle, which never re-fires while
@@ -172,16 +207,81 @@ public final class CameraSessionBridge implements LifecycleOwner {
172
207
  observedHost = view;
173
208
  view.getStreamState().observe(this, state -> {
174
209
  if (host != view || detached || released || epoch != generation) return;
210
+ boolean wasStreaming = streaming;
175
211
  streaming = state == androidx.camera.view.PreviewView.StreamState.STREAMING;
212
+ // STREAMING is CameraX's displayed-preview signal: frames are
213
+ // flowing to the PreviewView surface. It is a distinct edge
214
+ // from "ready", which additionally waits on measured frames.
215
+ if (streaming && !wasStreaming) emit("displayed", "true");
176
216
  // Availability/recovery must land before "ready": onReady
177
217
  // consumers may admit recording synchronously, and the
178
218
  // session gates on the flags these events update.
179
219
  if (streaming) { emit("availability", "true"); emit("recovered", "unknown"); }
180
220
  updateReady();
181
221
  });
182
- } catch (Exception cause) { ready(false); emit("previewError", cause.toString()); unbind(); }
222
+ } catch (Exception cause) {
223
+ if (switching) failSwitch(cause.toString());
224
+ else { ready(false); emit("previewError", cause.toString()); unbind(); }
225
+ }
183
226
  }, ContextCompat.getMainExecutor(context));
184
227
  }
228
+ /** Rebind the existing recorder; never pause audio or create a second file. */
229
+ public void switchCamera(String selected) {
230
+ if (recording == null || !started || finalizing || switching || awaitingSwitchCommit || released || detached || backgrounded) throw new IllegalStateException("Camera cannot switch now");
231
+ try {
232
+ CameraSelector selector = selectCamera(selected);
233
+ CameraInfo info = provider.getAvailableCameraInfos().stream().filter(i -> !selector.filter(Collections.singletonList(i)).isEmpty()).findFirst().orElseThrow(() -> new IllegalArgumentException("Selected camera unavailable"));
234
+ if (!Recorder.getVideoCapabilities(info).getSupportedQualities(DynamicRange.SDR).contains(recordingQuality)) throw new IllegalArgumentException("Camera cannot retain this recording profile");
235
+ } catch (Exception cause) { emit("switchFailed", cause.toString()); return; }
236
+ if (!host.holdPreview()) { emit("switchFailed", "The last preview frame is unavailable"); return; }
237
+ switching = true; rollingBack = false; switchPrevious = selection;
238
+ armSwitchTimeout();
239
+ try { bindCamera(host, selected, true); } catch (Exception cause) { failSwitch(cause.toString()); }
240
+ }
241
+ private void armSwitchTimeout() {
242
+ if (switchTimeout != null) handler.removeCallbacks(switchTimeout);
243
+ switchTimeout = () -> { if (switching) failSwitch("Camera did not become ready before timeout"); };
244
+ handler.postDelayed(switchTimeout, 5000);
245
+ }
246
+ private void clearSwitch() {
247
+ clearSwitch(false);
248
+ }
249
+ private void clearSwitch(boolean keepPreview) {
250
+ if (!keepPreview && host != null) host.releaseHeldPreview();
251
+ if (switchTimeout != null) handler.removeCallbacks(switchTimeout);
252
+ switchTimeout = null; switching = false; rollingBack = false;
253
+ }
254
+ private void failSwitch(String message) {
255
+ if (!switching) return;
256
+ if (rollingBack || host == null || released || detached || backgrounded) {
257
+ resumeAfterFinalization = host != null && !released && !detached && !backgrounded;
258
+ clearSwitch();
259
+ emit("switchFailed", message);
260
+ emit("finishing", "cameraUnavailable");
261
+ stop();
262
+ return;
263
+ }
264
+ rollingBack = true; switchError = message;
265
+ armSwitchTimeout();
266
+ try { bindCamera(host, switchPrevious, true); } catch (Exception cause) { failSwitch(cause.toString()); }
267
+ }
268
+ public void cancelCameraSwitch() {
269
+ if (!switching && !awaitingSwitchCommit) return;
270
+ // Cancellation accompanies stop/lifecycle teardown. Restore the selected
271
+ // preview after finalization; never rebind underneath finalizing output.
272
+ selection = switchPrevious;
273
+ awaitingSwitchCommit = false;
274
+ resumeAfterFinalization = host != null && !detached && !released && !backgrounded;
275
+ clearSwitch();
276
+ emit("switchFailed", "Camera switching was cancelled");
277
+ }
278
+ /** Acquisition is provisional until JS rechecks the still-active take. */
279
+ public void confirmCameraSwitch(String id) {
280
+ if (!awaitingSwitchCommit || !id.equals(cameraId) || recording == null || finalizing || released || detached || backgrounded) throw new IllegalStateException("Camera switch is no longer active");
281
+ awaitingSwitchCommit = false;
282
+ switchPrevious = null;
283
+ if (host != null) host.releaseHeldPreview();
284
+ }
185
285
  private CameraSelector selectCamera(String selected) throws androidx.camera.core.CameraInfoUnavailableException {
186
286
  if (selected.startsWith("id:")) return new CameraSelector.Builder().addCameraFilter(infos -> {
187
287
  java.util.List<CameraInfo> found = new java.util.ArrayList<>();
@@ -204,6 +304,7 @@ public final class CameraSessionBridge implements LifecycleOwner {
204
304
  public void foreground() { backgrounded = false; emit("recovered", "background"); if (recording != null) { resumeAfterFinalization = true; } else if (host != null && !detached) { unbind(); attach(host, selection); } }
205
305
  private void unbind() {
206
306
  streaming = false;
307
+ sourceFrameRate = 0; lastFrameTime = 0; ready(false);
207
308
  if (camera != null) camera.getCameraInfo().getCameraState().removeObservers(this);
208
309
  if (observedHost != null) { observedHost.getStreamState().removeObservers(this); observedHost = null; }
209
310
  if (provider != null) {
@@ -231,6 +332,10 @@ public final class CameraSessionBridge implements LifecycleOwner {
231
332
  Size size = video.getResolutionInfo().getResolution();
232
333
  profiles.put(new JSONObject().put("profile", "standard").put("width", size.getWidth()).put("height", size.getHeight()).put("frameRate", Math.round(sourceFrameRate * 100.0) / 100.0));
233
334
  }
335
+ if (camera != null) {
336
+ ZoomState state = camera.getCameraInfo().getZoomState().getValue();
337
+ result.put("zoom", state != null && state.getMaxZoomRatio() > state.getMinZoomRatio());
338
+ }
234
339
  if (camera != null && host != null && host.getWidth() > 0) {
235
340
  MeteringPoint center = host.meteringPoint(0.5f, 0.5f);
236
341
  result.put("focusPointOfInterest", camera.getCameraInfo().isFocusMeteringSupported(
@@ -262,6 +367,29 @@ public final class CameraSessionBridge implements LifecycleOwner {
262
367
  return false;
263
368
  }
264
369
  }
370
+ /** Live zoom state of the bound camera as JSON, or null when no camera
371
+ * is bound — JS maps null to "no zoom control". */
372
+ public String zoom() {
373
+ if (camera == null || released) return null;
374
+ try {
375
+ ZoomState state = camera.getCameraInfo().getZoomState().getValue();
376
+ if (state == null) return null;
377
+ return new JSONObject()
378
+ .put("zoom", state.getZoomRatio())
379
+ .put("minZoom", state.getMinZoomRatio())
380
+ .put("maxZoom", state.getMaxZoomRatio())
381
+ .toString();
382
+ } catch (Exception cause) { return null; }
383
+ }
384
+ /** Writes a CameraX zoom ratio on the bound camera; JS clamps against
385
+ * the live bounds first. Returns false when the write is refused. */
386
+ public boolean setZoom(double ratio) {
387
+ if (camera == null || released) return false;
388
+ try {
389
+ camera.getCameraControl().setZoomRatio((float) ratio);
390
+ return true;
391
+ } catch (Exception cause) { return false; }
392
+ }
265
393
  private String orientation() {
266
394
  // Display rotation is not a cardinal camera orientation on every device.
267
395
  return "unspecified";
@@ -289,7 +417,7 @@ public final class CameraSessionBridge implements LifecycleOwner {
289
417
  staging = new File(directory, UUID.randomUUID() + ".recording.mp4");
290
418
  FileOutputOptions.Builder options = new FileOutputOptions.Builder(staging);
291
419
  if (maximumDurationMs > 0) options.setDurationLimitMillis(maximumDurationMs);
292
- PendingRecording pending = video.getOutput().prepareRecording(context, options.build());
420
+ PendingRecording pending = video.getOutput().prepareRecording(context, options.build()).asPersistentRecording();
293
421
  if (audio) pending = pending.withAudioEnabled();
294
422
  recording = pending.start(ContextCompat.getMainExecutor(context), event -> {
295
423
  if (take != takeGeneration || recording == null) return;
@@ -313,6 +441,7 @@ public final class CameraSessionBridge implements LifecycleOwner {
313
441
  }
314
442
  }
315
443
  public void stop() {
444
+ cancelCameraSwitch();
316
445
  if (recording == null || watchdog != null || finalizing) return;
317
446
  try { recording.stop(); } catch (Exception cause) { cleanup(); failure("capture", "captureFailed", cause.toString()); return; }
318
447
  // A lost native terminal callback cannot leave completion dangling.
@@ -320,6 +449,7 @@ public final class CameraSessionBridge implements LifecycleOwner {
320
449
  handler.postDelayed(watchdog, 30_000);
321
450
  }
322
451
  private void finish(VideoRecordEvent.Finalize event) {
452
+ cancelCameraSwitch();
323
453
  if (recording == null || finalizing) return;
324
454
  finalizing = true;
325
455
  if (watchdog != null) handler.removeCallbacks(watchdog);
@@ -356,8 +486,10 @@ public final class CameraSessionBridge implements LifecycleOwner {
356
486
  handler.post(() -> {
357
487
  staging.delete(); staging = null; destination = null; ownsDestination = false; recording = null; finalizing = false;
358
488
  if (detached || released || backgrounded) unbind();
359
- emit("finished", result);
489
+ // Completion listeners can admit the next take synchronously.
490
+ // Retract readiness and restore the selected preview first.
360
491
  resumePreviewIfNeeded();
492
+ emit("finished", result);
361
493
  });
362
494
  } catch (Exception cause) {
363
495
  final boolean noMedia = staging == null || !staging.isFile() || staging.length() == 0 || !started;
@@ -366,8 +498,8 @@ public final class CameraSessionBridge implements LifecycleOwner {
366
498
  handler.post(() -> {
367
499
  cleanup();
368
500
  if (detached || released || backgrounded) unbind();
369
- failure(failedStage, kind, cause.toString());
370
501
  resumePreviewIfNeeded();
502
+ failure(failedStage, kind, cause.toString());
371
503
  });
372
504
  }
373
505
  }