@octane-xplat/camera 0.18.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 (67) hide show
  1. package/README.md +2 -132
  2. package/package.json +108 -103
  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 +194 -118
  7. package/src/CameraView.ios.tsrx +129 -76
  8. package/src/CameraView.macos.tsrx +108 -70
  9. package/src/CameraView.tsrx +2 -0
  10. package/src/CameraView.web.tsrx +160 -125
  11. package/src/CameraView.windows.tsrx +141 -92
  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 +266 -222
  19. package/src/index.ts +28 -26
  20. package/src/index.web.ts +27 -25
  21. package/src/layout-child.ts +88 -79
  22. package/src/layout-child.web.ts +57 -51
  23. package/src/layout-child.windows.ts +82 -71
  24. package/src/movie-metadata.web.ts +87 -74
  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 +118 -68
  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 +1556 -1467
  42. package/src/session-core.ts +925 -711
  43. package/src/session.ts +12 -12
  44. package/src/style-merge.ts +43 -43
  45. package/src/synthetic-session.ts +392 -333
  46. package/src/types.ts +384 -239
  47. package/types/generated/.tsrx-typegen-manifest.json +18 -0
  48. package/types/generated/CameraView.d.ts +2 -0
  49. package/types/generated/CameraView.web.d.ts +4 -0
  50. package/types/generated/camera-host.macos.d.ts +33 -0
  51. package/types/generated/index.d.ts +34 -0
  52. package/types/generated/layout-child.web.d.ts +7 -0
  53. package/types/generated/photo-lifecycle.macos.d.ts +12 -0
  54. package/types/generated/photo-sheet.macos.d.ts +36 -0
  55. package/types/generated/props.d.ts +111 -0
  56. package/types/generated/session-backend.d.ts +6 -0
  57. package/types/{session-core.d.ts → generated/session-core.d.ts} +30 -1
  58. package/types/generated/session.d.ts +16 -0
  59. package/types/{synthetic-session.d.ts → generated/synthetic-session.d.ts} +15 -1
  60. package/types/{types.d.ts → generated/types.d.ts} +145 -2
  61. package/LICENSE +0 -21
  62. package/platforms/macos/src/CameraOwnership.swift +0 -22
  63. package/platforms/macos/src/PhotoCaptureLifecycle.swift +0 -34
  64. package/platforms/macos/src/XplatCameraHost.swift +0 -639
  65. package/platforms/macos/src/XplatPhotoCaptureSheet.swift +0 -192
  66. package/types/index.d.ts +0 -48
  67. package/types/props.d.ts +0 -61
@@ -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
  }