@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
@@ -1,891 +1,1205 @@
1
1
  import { CameraCaptureError } from './types'
2
2
  import {
3
- cameraHost,
4
- commitHostMovie,
5
- openHostMovie,
6
- removeHostReservation,
7
- reserveHostMovie,
8
- type CameraHost,
3
+ cameraHost,
4
+ commitHostMovie,
5
+ openHostMovie,
6
+ removeHostReservation,
7
+ reserveHostMovie,
8
+ type CameraHost,
9
9
  } from './host-movie.web'
10
10
 
11
11
  import { commitMovie, openStoredMovie, removeReservation, reserveMovie } from './movie-storage.web'
12
12
  import { inspectMovie } from './movie-metadata.web'
13
+ import { createRecordingVideoSource, supportsRecordingVideoSource } from './recording-source.web'
14
+ import type { RecordingVideoSource } from './recording-source.web'
13
15
  import type {
14
- BackendCaptureSink,
15
- BackendObserver,
16
- BackendPreviewListener,
17
- CameraSessionBackend,
16
+ BackendCaptureSink,
17
+ BackendObserver,
18
+ BackendPreviewListener,
19
+ CameraSessionBackend,
18
20
  } from './session-core'
19
21
 
20
22
  import type {
21
- CameraPermissionKind,
22
- CameraPermissionStatus,
23
- CameraSessionConfig,
24
- CaptureIssue,
25
- EffectiveCaptureConfig,
26
- MovieClip,
23
+ CameraPermissionKind,
24
+ CameraPermissionStatus,
25
+ CameraSessionConfig,
26
+ CameraSelection,
27
+ CaptureIssue,
28
+ EffectiveCaptureConfig,
29
+ MovieClip,
27
30
  } from './types'
28
31
 
29
32
  const mimeCandidates = [
30
- 'video/webm;codecs=vp8,opus',
31
- 'video/webm;codecs=vp9,opus',
32
- 'video/mp4;codecs=avc1.424028,mp4a.40.2',
33
- 'video/mp4',
33
+ 'video/webm;codecs=vp8,opus',
34
+ 'video/webm;codecs=vp9,opus',
35
+ 'video/mp4;codecs=avc1.424028,mp4a.40.2',
36
+ 'video/mp4',
34
37
  ]
35
38
 
36
39
  let owner: object | undefined
37
40
 
38
41
  const error = (kind: CaptureIssue['kind'], operation: string, message: string, cause?: unknown) =>
39
- new CameraCaptureError({ kind, operation, message, cause })
42
+ new CameraCaptureError({ kind, operation, message, cause })
40
43
 
41
44
  const policyAllows = (kind: CameraPermissionKind) => {
42
- const policy =
43
- (
44
- document as Document & {
45
- permissionsPolicy?: { allowsFeature(feature: string): boolean }
46
- featurePolicy?: { allowsFeature(feature: string): boolean }
47
- }
48
- ).permissionsPolicy ?? (document as any).featurePolicy
49
-
50
- return policy?.allowsFeature(kind) !== false
45
+ const policy =
46
+ (
47
+ document as Document & {
48
+ permissionsPolicy?: { allowsFeature(feature: string): boolean }
49
+ featurePolicy?: { allowsFeature(feature: string): boolean }
50
+ }
51
+ ).permissionsPolicy ?? (document as any).featurePolicy
52
+
53
+ return policy?.allowsFeature(kind) !== false
51
54
  }
52
55
 
53
56
  export function createSessionBackend(config: CameraSessionConfig): CameraSessionBackend {
54
- let currentConfig = { ...config }
55
- let observer: BackendObserver | undefined
56
- let host: HTMLVideoElement | undefined
57
- let listener: BackendPreviewListener | undefined
58
- let stream: MediaStream | undefined
59
- let ready = false
60
- let released = false
61
- let generation = 0
62
- let persistent = false
63
- let recorder: MediaRecorder | undefined
64
- let sink: BackendCaptureSink | undefined
65
- let startedAt = 0
66
- let stoppedAt = 0
67
- let stopTimer: ReturnType<typeof setTimeout> | undefined
68
- let watchdog: ReturnType<typeof setTimeout> | undefined
69
- let recordingAudio = false
70
- let captureFailure: ((cause: unknown) => Promise<void>) | undefined
71
- // Desktop native webview probe: 'unknown' until the capability request
72
- // settles; 'available' means app-private file storage and honest host
73
- // permission status replace browser storage and permission queries.
74
- let hostState: 'unknown' | 'available' | 'absent' = 'unknown'
75
- const hostProbe = cameraHost().then((host) => {
76
- hostState = host ? 'available' : 'absent'
77
- return host
78
- })
79
-
80
- const lease = {}
81
- const known: Record<CameraPermissionKind, CameraPermissionStatus> = {
82
- camera: 'unknown',
83
- microphone: 'unknown',
84
- }
85
-
86
- const browserStorage = () => typeof indexedDB !== 'undefined' && !!navigator.storage?.persisted
87
-
88
- // A settled desktop-host probe means app-private file storage replaces
89
- // IndexedDB. While the probe is pending keep the browser answer;
90
- // `capabilities()` awaits the probe for the settled result.
91
- const supported = () =>
92
- typeof navigator !== 'undefined' &&
93
- globalThis.isSecureContext === true &&
94
- !!navigator.mediaDevices?.getUserMedia &&
95
- typeof MediaRecorder !== 'undefined' &&
96
- !!mimeType() &&
97
- (hostState === 'available' || browserStorage())
98
-
99
- const mimeType = () =>
100
- typeof MediaRecorder === 'undefined'
101
- ? ''
102
- : (mimeCandidates.find((mime) => MediaRecorder.isTypeSupported(mime)) ?? '')
103
-
104
- const markReady = (value: boolean) => {
105
- ready = value
106
- observer?.previewReady(value)
107
- }
108
-
109
- const dropStream = () => {
110
- if (host) {
111
- host.srcObject = null
112
- }
113
-
114
- stream?.getTracks().forEach((track) => track.stop())
115
- stream = undefined
116
- markReady(false)
117
- if (owner === lease) {
118
- owner = undefined
119
- }
120
- }
121
-
122
- const onVisibility = () => {
123
- if (document.visibilityState === 'hidden') {
124
- markReady(false)
125
- observer?.interruption('began', 'background')
126
- } else {
127
- observer?.interruption('ended', 'background')
128
- markReady(!!host && stream?.getVideoTracks()[0]?.readyState === 'live')
129
- }
130
- }
131
-
132
- const onPageHide = () => {
133
- markReady(false)
134
- observer?.interruption('began', 'background')
135
- }
136
-
137
- // Track-caused interruptions (ended/mute) need an explicit 'ended' —
138
- // a fresh live stream resolves them, and without the event the core
139
- // keeps interrupted=true until the session is recreated.
140
- let deviceInterrupted = false
141
-
142
- const observeTracks = (target: MediaStream) => {
143
- for (const track of target.getTracks()) {
144
- track.addEventListener('ended', () => {
145
- if (track.kind === 'audio' && (!sink || !recordingAudio)) {
146
- return
147
- }
148
-
149
- if (stream !== target) {
150
- return
151
- }
152
-
153
- markReady(false)
154
- deviceInterrupted = true
155
- observer?.availability(false)
156
- observer?.interruption('began', 'unknown')
157
- })
158
-
159
- track.addEventListener('mute', () => {
160
- if (track.kind === 'audio' && (!sink || !recordingAudio)) {
161
- return
162
- }
163
-
164
- if (stream === target) {
165
- markReady(false)
166
- deviceInterrupted = true
167
- observer?.interruption('began', 'unknown')
168
- }
169
- })
170
-
171
- track.addEventListener('unmute', () => {
172
- if (stream === target && document.visibilityState !== 'hidden') {
173
- deviceInterrupted = false
174
- observer?.interruption('ended', 'unknown')
175
- observer?.availability(true)
176
- markReady(!!host)
177
- }
178
- })
179
- }
180
- }
181
-
182
- const constraints = (): MediaTrackConstraints => {
183
- const camera = currentConfig.camera
184
- return {
185
- width: { ideal: 1280 },
186
- height: { ideal: 720 },
187
- frameRate: { ideal: 30 },
188
- ...(typeof camera === 'object'
189
- ? { deviceId: { exact: camera.deviceId } }
190
- : camera === 'front' || camera === 'back'
191
- ? { facingMode: { exact: camera === 'front' ? 'user' : 'environment' } }
192
- : {}),
193
- }
194
- }
195
-
196
- let acquisition: Promise<void> | undefined
197
- const acquireCameraOnce = async () => {
198
- if (stream?.getVideoTracks()[0]?.readyState === 'live') {
199
- return
200
- }
201
-
202
- if (owner && owner !== lease) {
203
- throw error('busy', 'preview', 'Another camera session still owns the source')
204
- }
205
-
206
- owner = lease
207
- const epoch = generation
208
- try {
209
- const acquired = await navigator.mediaDevices.getUserMedia({
210
- video: constraints(),
211
- audio: false,
212
- })
213
-
214
- if (released || epoch !== generation) {
215
- acquired.getTracks().forEach((track) => track.stop())
216
- if (!stream && owner === lease) {
217
- owner = undefined
218
- }
219
-
220
- return
221
- }
222
-
223
- for (const track of stream?.getAudioTracks() ?? []) {
224
- acquired.addTrack(track)
225
- }
226
-
227
- stream = acquired
228
- known.camera = 'granted'
229
- observeTracks(acquired)
230
- if (deviceInterrupted) {
231
- deviceInterrupted = false
232
- observer?.interruption('ended', 'unknown')
233
- }
234
-
235
- observer?.availability(true)
236
- } catch (cause) {
237
- if (owner === lease) {
238
- owner = undefined
239
- }
240
-
241
- throw cause
242
- }
243
- }
244
-
245
- const acquireCamera = () => {
246
- acquisition ??= acquireCameraOnce().finally(() => {
247
- acquisition = undefined
248
- })
249
-
250
- return acquisition
251
- }
252
-
253
- const showPreview = async () => {
254
- if (!host || released) {
255
- return
256
- }
257
-
258
- const element = host
259
- const epoch = generation
260
- if ((await checkPermission('camera')) !== 'granted') {
261
- listener?.onError?.(
262
- error(
263
- 'permissionBlocked',
264
- 'preview',
265
- 'Request camera access from a user action before activating this preview',
266
- ),
267
- )
268
-
269
- return
270
- }
271
-
272
- await acquireCamera()
273
- if (host !== element || !stream || released || epoch !== generation) {
274
- return
275
- }
276
-
277
- element.srcObject = stream
278
- element.muted = true
279
- const facing = stream.getVideoTracks()[0]?.getSettings().facingMode
280
- element.style.transform = facing === 'user' ? 'scaleX(-1)' : ''
281
- await element.play()
282
- if (host !== element || released || epoch !== generation) {
283
- return
284
- }
285
-
286
- markReady(document.visibilityState !== 'hidden')
287
- listener?.onReady?.()
288
- }
289
-
290
- const hostMediaKind = (kind: CameraPermissionKind) =>
291
- kind === 'microphone' ? 'microphone' : 'camera'
292
-
293
- async function checkPermission(kind: CameraPermissionKind): Promise<CameraPermissionStatus> {
294
- if (globalThis.isSecureContext !== true || !navigator.mediaDevices?.getUserMedia) {
295
- return 'unavailable'
296
- }
297
-
298
- if (!policyAllows(kind)) {
299
- return 'blocked'
300
- }
301
-
302
- const desktop = await hostProbe
303
- if (desktop) {
304
- try {
305
- const { status } = await desktop.call('camera', 'permissionStatus', {
306
- kind: hostMediaKind(kind),
307
- })
308
-
309
- if (status === 'granted' || status === 'notDetermined') {
310
- return status
311
- }
312
-
313
- if (status === 'restricted') {
314
- return 'restricted'
315
- }
316
-
317
- if (status === 'denied' || status === 'blocked') {
318
- return 'denied'
319
- }
320
-
321
- // 'undeclared' and unknown statuses stay honest but unadorned.
322
- return 'unknown'
323
- } catch {
324
- return 'unknown'
325
- }
326
- }
327
-
328
- try {
329
- const status = await navigator.permissions.query({ name: kind as PermissionName })
330
- return status.state === 'granted'
331
- ? 'granted'
332
- : status.state === 'denied'
333
- ? 'blocked'
334
- : known[kind] === 'blocked'
335
- ? 'blocked'
336
- : 'notDetermined'
337
- } catch {
338
- if (known[kind] !== 'granted') {
339
- return known[kind]
340
- }
341
-
342
- const tracks = kind === 'camera' ? stream?.getVideoTracks() : stream?.getAudioTracks()
343
- return tracks?.some((track) => track.readyState === 'live') ? 'granted' : 'unknown'
344
- }
345
- }
346
-
347
- const settle = (value: Parameters<BackendCaptureSink['settled']>[0], expected = sink) => {
348
- const target = sink
349
- if (!target || target !== expected) {
350
- return
351
- }
352
-
353
- sink = undefined
354
- recorder = undefined
355
- captureFailure = undefined
356
- clearTimeout(stopTimer)
357
- clearTimeout(watchdog)
358
- if (!host) {
359
- dropStream()
360
- }
361
-
362
- target.settled(value)
363
- }
364
-
365
- const stop = () => {
366
- if (!recorder || !sink) {
367
- return
368
- }
369
-
370
- stoppedAt ||= performance.now()
371
- clearTimeout(watchdog)
372
- const target = sink
373
- const fail = captureFailure
374
- watchdog = setTimeout(() => {
375
- if (sink !== target) {
376
- return
377
- }
378
-
379
- dropStream()
380
- void fail?.(error('finalizationFailed', 'stop', 'Recorder finalization callback timed out'))
381
- }, 30_000)
382
-
383
- if (recorder.state === 'inactive') {
384
- return
385
- }
386
-
387
- try {
388
- recorder.stop()
389
- } catch (cause) {
390
- void fail?.(error('captureFailed', 'stop', 'The recorder could not stop', cause))
391
- }
392
- }
393
-
394
- return {
395
- platform: 'web',
396
- get supported() {
397
- return supported()
398
- },
399
- checkPermission,
400
- requestPermission: async (kind) => {
401
- const status = await checkPermission(kind)
402
- if (status === 'blocked' || status === 'unavailable') {
403
- return status
404
- }
405
-
406
- if (navigator.userActivation && !navigator.userActivation.isActive && status !== 'granted') {
407
- return 'blocked'
408
- }
409
-
410
- // Persistence and device prompts run only inside an explicit app action.
411
- persistent = (await navigator.storage?.persisted?.().catch(() => false)) ?? false
412
- if (!persistent && (!navigator.userActivation || navigator.userActivation.isActive)) {
413
- persistent = (await navigator.storage?.persist?.().catch(() => false)) ?? false
414
- }
415
-
416
- const desktop = await hostProbe
417
- if (desktop) {
418
- const { status: hostStatus } = await desktop.call('camera', 'requestPermission', {
419
- kind: hostMediaKind(kind),
420
- })
421
-
422
- if (hostStatus === 'undeclared') {
423
- throw error(
424
- 'configurationMissing',
425
- 'requestPermission',
426
- `Missing ${kind === 'camera' ? 'NSCameraUsageDescription' : 'NSMicrophoneUsageDescription'} in the host app's Info.plist`,
427
- )
428
- }
429
-
430
- if (hostStatus !== 'granted') {
431
- known[kind] =
432
- hostStatus === 'denied' || hostStatus === 'blocked'
433
- ? 'denied'
434
- : hostStatus === 'restricted'
435
- ? 'restricted'
436
- : 'unknown'
437
-
438
- return known[kind]
439
- }
440
- // The system permission is granted — the capture delegate grants
441
- // this trusted origin, so the acquisition below gets the track.
442
- }
443
-
444
- try {
445
- if (kind === 'camera') {
446
- await acquireCamera()
447
- } else if (!stream?.getAudioTracks().some((track) => track.readyState === 'live')) {
448
- const epoch = generation
449
- const audio = await navigator.mediaDevices.getUserMedia({ audio: true, video: false })
450
- if (released || epoch !== generation) {
451
- audio.getTracks().forEach((track) => track.stop())
452
- return 'unavailable'
453
- }
454
-
455
- if (!stream) {
456
- stream = new MediaStream()
457
- }
458
-
459
- for (const track of audio.getAudioTracks()) {
460
- stream.addTrack(track)
461
- }
462
-
463
- observeTracks(stream)
464
- }
465
-
466
- known[kind] = 'granted'
467
- if (host) {
468
- await showPreview()
469
- }
470
-
471
- return 'granted'
472
- } catch (cause) {
473
- known[kind] =
474
- cause instanceof DOMException &&
475
- (cause.name === 'NotAllowedError' || cause.name === 'SecurityError')
476
- ? 'blocked'
477
- : 'unavailable'
478
-
479
- return known[kind]
480
- }
481
- },
482
- getCapabilities: async () => {
483
- const desktop = await hostProbe
484
- persistent = (await navigator.storage?.persisted?.().catch(() => false)) ?? false
485
- const devices = (await navigator.mediaDevices?.enumerateDevices?.().catch(() => [])) ?? []
486
- const settings = stream?.getVideoTracks()[0]?.getSettings()
487
- const mime = mimeType()
488
- const storageReady = persistent || !!desktop
489
- return {
490
- supported: supported(),
491
- available: ready && storageReady,
492
- reason: !supported()
493
- ? 'Secure media capture, a supported WebM/MP4 codec, and durable storage are required'
494
- : !storageReady
495
- ? 'Persistent origin storage must be granted before recording'
496
- : !ready
497
- ? 'An active permitted preview is required'
498
- : undefined,
499
- cameras: devices
500
- .filter((device) => device.kind === 'videoinput')
501
- .map((device) => ({ id: device.deviceId, label: device.label })),
502
- profiles:
503
- settings?.width && settings.height && settings.frameRate
504
- ? [
505
- {
506
- profile: 'standard' as const,
507
- width: settings.width,
508
- height: settings.height,
509
- frameRate: settings.frameRate,
510
- },
511
- ]
512
- : [],
513
- audio: devices.some((device) => device.kind === 'audioinput'),
514
- // The `pointsOfInterest` track constraint is not wired into
515
- // the adapter — report honestly rather than fabricate.
516
- focusPointOfInterest: false,
517
- exposurePointOfInterest: false,
518
- orientations: [],
519
- durationLimit: 'bestEffort',
520
- elapsedTime: 'estimated',
521
- output: {
522
- mimeType: mime,
523
- container: !mime ? '' : mime.startsWith('video/mp4') ? 'mp4' : 'webm',
524
- storage: desktop ? 'appPrivateFile' : 'originLocal',
525
- destinationFileUrl: !!desktop,
526
- },
527
- }
528
- },
529
- previewReady: () => ready && !!host && !released,
530
- validateStart: (options) => {
531
- // Once the desktop-host probe settles absent, browser storage rules
532
- // apply synchronously. A pending probe defers both checks to the
533
- // async start path, which knows the real storage owner.
534
- if (hostState === 'absent') {
535
- if (!persistent) {
536
- throw error(
537
- 'destinationUnavailable',
538
- 'startRecording',
539
- 'Persistent origin storage has not been granted; check capabilities after a user permission action',
540
- )
541
- }
542
-
543
- if (options.destinationFileUrl) {
544
- throw error(
545
- 'unsupportedConfiguration',
546
- 'startRecording',
547
- 'Browser output does not accept native file URLs',
548
- )
549
- }
550
- }
551
-
552
- if (options.orientation && options.orientation !== 'unspecified') {
553
- throw error(
554
- 'unsupportedConfiguration',
555
- 'startRecording',
556
- 'This browser cannot lock a recording orientation',
557
- )
558
- }
559
- },
560
- attachPreview: (target, callbacks) => {
561
- if (released || sink) {
562
- throw error('invalidState', 'attachPreview', 'The camera is disposed or still finalizing')
563
- }
564
-
565
- host = target as HTMLVideoElement
566
- listener = callbacks
567
- document.addEventListener('visibilitychange', onVisibility)
568
- globalThis.addEventListener('pagehide', onPageHide)
569
- void showPreview().catch((cause) =>
570
- callbacks?.onError?.(
571
- error('unavailable', 'preview', 'Could not activate camera preview', cause),
572
- ),
573
- )
574
-
575
- return () => {
576
- if (host) {
577
- host.srcObject = null
578
- }
579
-
580
- host = undefined
581
- listener = undefined
582
- generation += 1
583
- markReady(false)
584
- document.removeEventListener('visibilitychange', onVisibility)
585
- globalThis.removeEventListener('pagehide', onPageHide)
586
- if (!sink) {
587
- dropStream()
588
- }
589
- }
590
- },
591
- configure: (next) => {
592
- const sourceChanged =
593
- JSON.stringify(next.camera) !== JSON.stringify(currentConfig.camera) ||
594
- next.profile !== currentConfig.profile
595
-
596
- currentConfig = { ...next }
597
- if (sourceChanged) {
598
- generation += 1
599
- dropStream()
600
- if (host) {
601
- void showPreview().catch((cause) =>
602
- listener?.onError?.(
603
- error('unavailable', 'configure', 'Could not change camera', cause),
604
- ),
605
- )
606
- }
607
- }
608
- },
609
- startCapture: (request, target) => {
610
- sink = target
611
- recordingAudio = request.audio
612
- startedAt = 0
613
- stoppedAt = 0
614
- const source = stream
615
- const video = source?.getVideoTracks()[0]
616
- const audio = source?.getAudioTracks().filter((track) => track.readyState === 'live') ?? []
617
- if (!video || (request.audio && !audio.length)) {
618
- settle({
619
- kind: 'failed',
620
- stage: 'preparation',
621
- issue: error(
622
- request.audio ? 'permissionDenied' : 'unavailable',
623
- 'startRecording',
624
- request.audio
625
- ? 'Requested microphone access is missing'
626
- : 'Video source is unavailable',
627
- ),
628
- })
629
-
630
- return
631
- }
632
-
633
- const recordingStream = new MediaStream([video, ...(request.audio ? audio : [])])
634
- let desktop: CameraHost | null = null
635
- let reservation: string | undefined
636
- let stage: 'preparation' | 'capture' | 'finalization' | 'storage' = 'preparation'
637
- const chunks: Blob[] = []
638
- let captureError: unknown
639
- let limitReached = false
640
- let failing = false
641
- let didStart = false
642
- captureFailure = fail
643
- void (async () => {
644
- try {
645
- desktop = await hostProbe
646
- if (request.destinationPath && !desktop) {
647
- throw error(
648
- 'unsupportedConfiguration',
649
- 'startRecording',
650
- 'Web recordings do not accept native file destinations',
651
- )
652
- }
653
-
654
- if (desktop) {
655
- reservation = (
656
- await reserveHostMovie(desktop, {
657
- destinationFileUrl: request.destinationPath
658
- ? `file://${request.destinationPath.split('/').map(encodeURIComponent).join('/')}`
659
- : undefined,
660
- container: mimeType().startsWith('video/mp4') ? 'mp4' : 'webm',
661
- })
662
- ).fileUrl
663
- } else {
664
- if (!(await navigator.storage?.persisted?.())) {
665
- throw error(
666
- 'destinationUnavailable',
667
- 'startRecording',
668
- 'Persistent storage is unavailable',
669
- )
670
- }
671
-
672
- reservation = await reserveMovie()
673
- }
674
-
675
- if (!source || video.readyState !== 'live' || document.visibilityState === 'hidden') {
676
- throw error(
677
- 'unavailable',
678
- 'startRecording',
679
- 'Camera source became inactive before recording',
680
- )
681
- }
682
-
683
- const activeRecorder = new MediaRecorder(recordingStream, { mimeType: mimeType() })
684
- recorder = activeRecorder
685
- activeRecorder.ondataavailable = (event) => {
686
- if (sink !== target || failing) {
687
- return
688
- }
689
-
690
- if (event.data.size) {
691
- chunks.push(event.data)
692
- }
693
- }
694
-
695
- activeRecorder.onerror = (event) => {
696
- if (sink !== target || failing) {
697
- return
698
- }
699
-
700
- captureError = event
701
- stop()
702
- }
703
-
704
- activeRecorder.onstart = () => {
705
- if (sink !== target || failing) {
706
- return
707
- }
708
-
709
- if (didStart) {
710
- return
711
- }
712
-
713
- didStart = true
714
- clearTimeout(watchdog)
715
- startedAt = performance.now()
716
- stage = 'capture'
717
- const settings = video.getSettings()
718
- const effective: EffectiveCaptureConfig = {
719
- cameraId: settings.deviceId ?? '',
720
- audio: request.audio,
721
- width: settings.width ?? 0,
722
- height: settings.height ?? 0,
723
- frameRate: settings.frameRate ?? 0,
724
- orientation: 'unspecified',
725
- mimeType: activeRecorder.mimeType,
726
- container: activeRecorder.mimeType.startsWith('video/mp4') ? 'mp4' : 'webm',
727
- }
728
-
729
- // The adapter owns a limit even when capabilities() was not called.
730
- if (request.maximumDurationMs) {
731
- const limit = request.maximumDurationMs
732
- const checkLimit = () => {
733
- if (sink !== target || failing) {
734
- return
735
- }
736
-
737
- const remaining = limit - (performance.now() - startedAt)
738
- if (remaining > 0) {
739
- stopTimer = setTimeout(checkLimit, Math.min(remaining, 2_147_483_647))
740
- } else {
741
- limitReached = true
742
- stop()
743
- }
744
- }
745
-
746
- stopTimer = setTimeout(checkLimit, Math.min(limit, 2_147_483_647))
747
- }
748
-
749
- target.started(effective)
750
- }
751
-
752
- activeRecorder.onstop = () => {
753
- if (sink !== target || failing) {
754
- return
755
- }
756
-
757
- target.finishing(
758
- captureError ? 'captureError' : limitReached ? 'maximumDuration' : undefined,
759
- )
760
-
761
- stoppedAt ||= performance.now()
762
- clearTimeout(stopTimer)
763
- clearTimeout(watchdog)
764
- void (async () => {
765
- try {
766
- stage = 'finalization'
767
- if (!startedAt) {
768
- throw error('noMedia', 'finalize', 'No recording start was observed')
769
- }
770
-
771
- const bytes = new Blob(chunks, { type: activeRecorder.mimeType })
772
- const metadata = await inspectMovie(bytes, request.audio)
773
- if (sink !== target || failing) {
774
- return
775
- }
776
-
777
- stage = 'storage'
778
- const output = desktop
779
- ? await commitHostMovie(desktop, reservation!, bytes)
780
- : {
781
- kind: 'browserStorage' as const,
782
- resourceId: reservation!,
783
- retention: 'persistent' as const,
784
- }
785
-
786
- const clip: MovieClip = { ...metadata, output }
787
- if (!desktop) {
788
- await commitMovie(reservation!, bytes, clip)
789
- }
790
-
791
- settle(
792
- {
793
- kind: 'clip',
794
- ...clip,
795
- limitReached,
796
- warning: captureError
797
- ? error(
798
- 'captureFailed',
799
- 'capture',
800
- 'Recorder reported an error; finalized media was verified',
801
- captureError,
802
- )
803
- : undefined,
804
- },
805
- target,
806
- )
807
- } catch (cause) {
808
- await fail(cause)
809
- }
810
- })()
811
- }
812
-
813
- activeRecorder.start(1000)
814
- watchdog = setTimeout(() => {
815
- if (!startedAt && sink === target) {
816
- stop()
817
- void fail(
818
- error('captureFailed', 'startRecording', 'Recorder start callback timed out'),
819
- )
820
- }
821
- }, 15_000)
822
- } catch (cause) {
823
- await fail(cause)
824
- }
825
- })()
826
-
827
- async function fail(cause: unknown) {
828
- if (sink !== target || failing) {
829
- return
830
- }
831
-
832
- failing = true
833
- if (reservation) {
834
- await (desktop
835
- ? removeHostReservation(desktop, reservation)
836
- : removeReservation(reservation).catch(() => {}))
837
- }
838
-
839
- settle(
840
- {
841
- kind: 'failed',
842
- stage,
843
- issue:
844
- cause instanceof CameraCaptureError
845
- ? cause
846
- : error(
847
- stage === 'storage'
848
- ? 'storageFailed'
849
- : stage === 'preparation' || stage === 'capture'
850
- ? 'captureFailed'
851
- : 'finalizationFailed',
852
- stage,
853
- 'Movie recording could not complete',
854
- cause,
855
- ),
856
- },
857
- target,
858
- )
859
- }
860
- },
861
- stopCapture: stop,
862
- elapsedMs: () => (startedAt ? Math.max(0, (stoppedAt || performance.now()) - startedAt) : 0),
863
- openOutput: async (output) => {
864
- if (output.kind === 'nativeFile') {
865
- const desktop = await hostProbe
866
- if (!desktop) {
867
- throw error(
868
- 'unavailable',
869
- 'openOutput',
870
- 'File-backed output requires the desktop host that recorded it',
871
- )
872
- }
873
-
874
- return openHostMovie(desktop, output)
875
- }
876
-
877
- return openStoredMovie(output)
878
- },
879
- release: async () => {
880
- released = true
881
- generation += 1
882
- document.removeEventListener('visibilitychange', onVisibility)
883
- globalThis.removeEventListener('pagehide', onPageHide)
884
- dropStream()
885
- host = undefined
886
- },
887
- setObserver: (value) => {
888
- observer = value
889
- },
890
- }
57
+ let currentConfig = { ...config }
58
+ let observer: BackendObserver | undefined
59
+ let host: HTMLVideoElement | undefined
60
+ let listener: BackendPreviewListener | undefined
61
+ let stream: MediaStream | undefined
62
+ let ready = false
63
+ let released = false
64
+ let generation = 0
65
+ let persistent = false
66
+ let recorder: MediaRecorder | undefined
67
+ let sink: BackendCaptureSink | undefined
68
+ let startedAt = 0
69
+ let stoppedAt = 0
70
+ let stopTimer: ReturnType<typeof setTimeout> | undefined
71
+ let watchdog: ReturnType<typeof setTimeout> | undefined
72
+ let recordingAudio = false
73
+ let recordingVideo: RecordingVideoSource | undefined
74
+ let switchWarning: CaptureIssue | undefined
75
+ let pendingSwitch: { cancel: () => void } | undefined
76
+ let captureFailure: ((cause: unknown) => Promise<void>) | undefined
77
+ // Desktop native webview probe: 'unknown' until the capability request
78
+ // settles; 'available' means app-private file storage and honest host
79
+ // permission status replace browser storage and permission queries.
80
+ let hostState: 'unknown' | 'available' | 'absent' = 'unknown'
81
+ const hostProbe = cameraHost().then((host) => {
82
+ hostState = host ? 'available' : 'absent'
83
+ return host
84
+ })
85
+
86
+ const lease = {}
87
+ const known: Record<CameraPermissionKind, CameraPermissionStatus> = {
88
+ camera: 'unknown',
89
+ microphone: 'unknown',
90
+ }
91
+
92
+ const browserStorage = () => typeof indexedDB !== 'undefined' && !!navigator.storage?.persisted
93
+
94
+ // A settled desktop-host probe means app-private file storage replaces
95
+ // IndexedDB. While the probe is pending keep the browser answer;
96
+ // `capabilities()` awaits the probe for the settled result.
97
+ const supported = () =>
98
+ typeof navigator !== 'undefined' &&
99
+ globalThis.isSecureContext === true &&
100
+ !!navigator.mediaDevices?.getUserMedia &&
101
+ typeof MediaRecorder !== 'undefined' &&
102
+ !!mimeType() &&
103
+ (hostState === 'available' || browserStorage())
104
+
105
+ const mimeType = () =>
106
+ typeof MediaRecorder === 'undefined'
107
+ ? ''
108
+ : (mimeCandidates.find((mime) => MediaRecorder.isTypeSupported(mime)) ?? '')
109
+
110
+ const markReady = (value: boolean) => {
111
+ ready = value
112
+ observer?.previewReady(value)
113
+ }
114
+
115
+ /** MediaTrack `zoom` is a camera-control constraint some browsers
116
+ * expose; absent track capabilities mean no zoom control. */
117
+ const readZoom = () => {
118
+ const track = stream?.getVideoTracks()[0]
119
+ const zoom = (track?.getCapabilities?.() as any)?.zoom
120
+
121
+ if (!track || typeof zoom?.min !== 'number' || typeof zoom?.max !== 'number') {
122
+ return undefined
123
+ }
124
+
125
+ const current = (track.getSettings?.() as any)?.zoom
126
+
127
+ return {
128
+ zoom: typeof current === 'number' ? current : zoom.min,
129
+ minZoom: zoom.min,
130
+ maxZoom: zoom.max,
131
+ }
132
+ }
133
+
134
+ const dropStream = () => {
135
+ if (host) {
136
+ host.srcObject = null
137
+ }
138
+
139
+ stream?.getTracks().forEach((track) => track.stop())
140
+ stream = undefined
141
+ markReady(false)
142
+ if (owner === lease) {
143
+ owner = undefined
144
+ }
145
+ }
146
+
147
+ const onVisibility = () => {
148
+ if (document.visibilityState === 'hidden') {
149
+ markReady(false)
150
+ observer?.interruption('began', 'background')
151
+ } else {
152
+ observer?.interruption('ended', 'background')
153
+ markReady(!!host && stream?.getVideoTracks()[0]?.readyState === 'live')
154
+ }
155
+ }
156
+
157
+ const onPageHide = () => {
158
+ markReady(false)
159
+ observer?.interruption('began', 'background')
160
+ }
161
+
162
+ // Track-caused interruptions (ended/mute) need an explicit 'ended' —
163
+ // a fresh live stream resolves them, and without the event the core
164
+ // keeps interrupted=true until the session is recreated.
165
+ let deviceInterrupted = false
166
+
167
+ const observeTracks = (target: MediaStream) => {
168
+ for (const track of target.getTracks()) {
169
+ track.addEventListener('ended', () => {
170
+ if (track.kind === 'audio' && (!sink || !recordingAudio)) {
171
+ return
172
+ }
173
+
174
+ if (stream !== target) {
175
+ return
176
+ }
177
+
178
+ markReady(false)
179
+ deviceInterrupted = true
180
+ observer?.availability(false)
181
+ observer?.interruption('began', 'unknown')
182
+ })
183
+
184
+ track.addEventListener('mute', () => {
185
+ if (track.kind === 'audio' && (!sink || !recordingAudio)) {
186
+ return
187
+ }
188
+
189
+ if (stream === target) {
190
+ markReady(false)
191
+ deviceInterrupted = true
192
+ observer?.interruption('began', 'unknown')
193
+ }
194
+ })
195
+
196
+ track.addEventListener('unmute', () => {
197
+ if (stream === target && document.visibilityState !== 'hidden') {
198
+ deviceInterrupted = false
199
+ observer?.interruption('ended', 'unknown')
200
+ observer?.availability(true)
201
+ markReady(!!host)
202
+ }
203
+ })
204
+ }
205
+ }
206
+
207
+ const constraints = (camera = currentConfig.camera): MediaTrackConstraints => {
208
+ return {
209
+ width: { ideal: 1280 },
210
+ height: { ideal: 720 },
211
+ frameRate: { ideal: 30 },
212
+ ...(typeof camera === 'object'
213
+ ? { deviceId: { exact: camera.deviceId } }
214
+ : camera === 'front' || camera === 'back'
215
+ ? { facingMode: { exact: camera === 'front' ? 'user' : 'environment' } }
216
+ : {}),
217
+ }
218
+ }
219
+
220
+ let acquisition: Promise<void> | undefined
221
+ const acquireCameraOnce = async () => {
222
+ if (stream?.getVideoTracks()[0]?.readyState === 'live') {
223
+ return
224
+ }
225
+
226
+ if (owner && owner !== lease) {
227
+ throw error('busy', 'preview', 'Another camera session still owns the source')
228
+ }
229
+
230
+ owner = lease
231
+
232
+ const epoch = generation
233
+
234
+ try {
235
+ const acquired = await navigator.mediaDevices.getUserMedia({
236
+ video: constraints(),
237
+ audio: false,
238
+ })
239
+
240
+ if (released || epoch !== generation) {
241
+ acquired.getTracks().forEach((track) => track.stop())
242
+ if (!stream && owner === lease) {
243
+ owner = undefined
244
+ }
245
+
246
+ return
247
+ }
248
+
249
+ for (const track of stream?.getAudioTracks() ?? []) {
250
+ acquired.addTrack(track)
251
+ }
252
+
253
+ stream = acquired
254
+ known.camera = 'granted'
255
+ observeTracks(acquired)
256
+ if (deviceInterrupted) {
257
+ deviceInterrupted = false
258
+ observer?.interruption('ended', 'unknown')
259
+ }
260
+
261
+ observer?.availability(true)
262
+ } catch (cause) {
263
+ if (owner === lease) {
264
+ owner = undefined
265
+ }
266
+
267
+ throw cause
268
+ }
269
+ }
270
+
271
+ const acquireCamera = () => {
272
+ acquisition ??= acquireCameraOnce().finally(() => {
273
+ acquisition = undefined
274
+ })
275
+
276
+ return acquisition
277
+ }
278
+
279
+ const showPreview = async (notify = true) => {
280
+ if (!host || released) {
281
+ return
282
+ }
283
+
284
+ const element = host
285
+ const epoch = generation
286
+
287
+ if ((await checkPermission('camera')) !== 'granted') {
288
+ listener?.onError?.(
289
+ error(
290
+ 'permissionBlocked',
291
+ 'preview',
292
+ 'Request camera access from a user action before activating this preview',
293
+ ),
294
+ )
295
+
296
+ return
297
+ }
298
+
299
+ await acquireCamera()
300
+ if (host !== element || !stream || released || epoch !== generation) {
301
+ return
302
+ }
303
+
304
+ element.srcObject = stream
305
+ element.muted = true
306
+
307
+ const facing = stream.getVideoTracks()[0]?.getSettings().facingMode
308
+
309
+ element.style.transform = facing === 'user' ? 'scaleX(-1)' : ''
310
+ await element.play()
311
+ if (host !== element || released || epoch !== generation) {
312
+ return
313
+ }
314
+
315
+ markReady(document.visibilityState !== 'hidden')
316
+ if (notify) {
317
+ listener?.onReady?.()
318
+ }
319
+
320
+ // Display readiness is its own edge: requestVideoFrameCallback fires
321
+ // on the first presented frame; without it, a resolved play() is the
322
+ // only display confirmation the element exposes.
323
+ if (typeof element.requestVideoFrameCallback === 'function') {
324
+ element.requestVideoFrameCallback(() => {
325
+ if (host === element && !released && epoch === generation) {
326
+ listener?.onDisplayReady?.()
327
+ }
328
+ })
329
+ } else {
330
+ listener?.onDisplayReady?.()
331
+ }
332
+ }
333
+
334
+ const hostMediaKind = (kind: CameraPermissionKind) =>
335
+ kind === 'microphone' ? 'microphone' : 'camera'
336
+
337
+ async function checkPermission(kind: CameraPermissionKind): Promise<CameraPermissionStatus> {
338
+ if (globalThis.isSecureContext !== true || !navigator.mediaDevices?.getUserMedia) {
339
+ return 'unavailable'
340
+ }
341
+
342
+ if (!policyAllows(kind)) {
343
+ return 'blocked'
344
+ }
345
+
346
+ const desktop = await hostProbe
347
+
348
+ if (desktop) {
349
+ try {
350
+ const { status } = await desktop.call('camera', 'permissionStatus', {
351
+ kind: hostMediaKind(kind),
352
+ })
353
+
354
+ if (status === 'granted' || status === 'notDetermined') {
355
+ return status
356
+ }
357
+
358
+ if (status === 'restricted') {
359
+ return 'restricted'
360
+ }
361
+
362
+ if (status === 'denied' || status === 'blocked') {
363
+ return 'denied'
364
+ }
365
+
366
+ // 'undeclared' and unknown statuses stay honest but unadorned.
367
+ return 'unknown'
368
+ } catch {
369
+ return 'unknown'
370
+ }
371
+ }
372
+
373
+ try {
374
+ const status = await navigator.permissions.query({ name: kind as PermissionName })
375
+
376
+ return status.state === 'granted'
377
+ ? 'granted'
378
+ : status.state === 'denied'
379
+ ? 'blocked'
380
+ : known[kind] === 'blocked'
381
+ ? 'blocked'
382
+ : 'notDetermined'
383
+ } catch {
384
+ if (known[kind] !== 'granted') {
385
+ return known[kind]
386
+ }
387
+
388
+ const tracks = kind === 'camera' ? stream?.getVideoTracks() : stream?.getAudioTracks()
389
+
390
+ return tracks?.some((track) => track.readyState === 'live') ? 'granted' : 'unknown'
391
+ }
392
+ }
393
+
394
+ const settle = (value: Parameters<BackendCaptureSink['settled']>[0], expected = sink) => {
395
+ const target = sink
396
+
397
+ if (!target || target !== expected) {
398
+ return
399
+ }
400
+
401
+ sink = undefined
402
+ recorder = undefined
403
+ captureFailure = undefined
404
+ if (recordingVideo) {
405
+ if (host) {
406
+ host.srcObject = stream ?? null
407
+ void host.play().catch(() => {})
408
+ }
409
+
410
+ recordingVideo.release()
411
+ recordingVideo = undefined
412
+ }
413
+
414
+ clearTimeout(stopTimer)
415
+ clearTimeout(watchdog)
416
+ if (!host) {
417
+ dropStream()
418
+ }
419
+
420
+ target.settled(value)
421
+ if (host && !released && stream?.getVideoTracks()[0]?.readyState !== 'live') {
422
+ void showPreview(false).catch(() => observer?.availability(false))
423
+ }
424
+ }
425
+
426
+ const stop = () => {
427
+ pendingSwitch?.cancel()
428
+ if (!recorder || !sink) {
429
+ return
430
+ }
431
+
432
+ stoppedAt ||= performance.now()
433
+ clearTimeout(watchdog)
434
+
435
+ const target = sink
436
+ const fail = captureFailure
437
+
438
+ watchdog = setTimeout(() => {
439
+ if (sink !== target) {
440
+ return
441
+ }
442
+
443
+ dropStream()
444
+ void fail?.(error('finalizationFailed', 'stop', 'Recorder finalization callback timed out'))
445
+ }, 30_000)
446
+
447
+ if (recorder.state === 'inactive') {
448
+ return
449
+ }
450
+
451
+ try {
452
+ recorder.stop()
453
+ } catch (cause) {
454
+ void fail?.(error('captureFailed', 'stop', 'The recorder could not stop', cause))
455
+ }
456
+ }
457
+
458
+ return {
459
+ platform: 'web',
460
+ get supported() {
461
+ return supported()
462
+ },
463
+ checkPermission,
464
+ requestPermission: async (kind) => {
465
+ const status = await checkPermission(kind)
466
+
467
+ if (status === 'blocked' || status === 'unavailable') {
468
+ return status
469
+ }
470
+
471
+ if (navigator.userActivation && !navigator.userActivation.isActive && status !== 'granted') {
472
+ return 'blocked'
473
+ }
474
+
475
+ // Persistence and device prompts run only inside an explicit app action.
476
+ persistent = (await navigator.storage?.persisted?.().catch(() => false)) ?? false
477
+ if (!persistent && (!navigator.userActivation || navigator.userActivation.isActive)) {
478
+ persistent = (await navigator.storage?.persist?.().catch(() => false)) ?? false
479
+ }
480
+
481
+ const desktop = await hostProbe
482
+
483
+ if (desktop) {
484
+ const { status: hostStatus } = await desktop.call('camera', 'requestPermission', {
485
+ kind: hostMediaKind(kind),
486
+ })
487
+
488
+ if (hostStatus === 'undeclared') {
489
+ throw error(
490
+ 'configurationMissing',
491
+ 'requestPermission',
492
+ `Missing ${kind === 'camera' ? 'NSCameraUsageDescription' : 'NSMicrophoneUsageDescription'} in the host app's Info.plist`,
493
+ )
494
+ }
495
+
496
+ if (hostStatus !== 'granted') {
497
+ known[kind] =
498
+ hostStatus === 'denied' || hostStatus === 'blocked'
499
+ ? 'denied'
500
+ : hostStatus === 'restricted'
501
+ ? 'restricted'
502
+ : 'unknown'
503
+
504
+ return known[kind]
505
+ }
506
+ // The system permission is granted — the capture delegate grants
507
+ // this trusted origin, so the acquisition below gets the track.
508
+ }
509
+
510
+ try {
511
+ if (kind === 'camera') {
512
+ await acquireCamera()
513
+ } else if (!stream?.getAudioTracks().some((track) => track.readyState === 'live')) {
514
+ const epoch = generation
515
+ const audio = await navigator.mediaDevices.getUserMedia({ audio: true, video: false })
516
+
517
+ if (released || epoch !== generation) {
518
+ audio.getTracks().forEach((track) => track.stop())
519
+ return 'unavailable'
520
+ }
521
+
522
+ if (!stream) {
523
+ stream = new MediaStream()
524
+ }
525
+
526
+ for (const track of audio.getAudioTracks()) {
527
+ stream.addTrack(track)
528
+ }
529
+
530
+ observeTracks(stream)
531
+ }
532
+
533
+ known[kind] = 'granted'
534
+ if (host) {
535
+ await showPreview()
536
+ }
537
+
538
+ return 'granted'
539
+ } catch (cause) {
540
+ known[kind] =
541
+ cause instanceof DOMException &&
542
+ (cause.name === 'NotAllowedError' || cause.name === 'SecurityError')
543
+ ? 'blocked'
544
+ : 'unavailable'
545
+
546
+ return known[kind]
547
+ }
548
+ },
549
+ getCapabilities: async () => {
550
+ const desktop = await hostProbe
551
+
552
+ persistent = (await navigator.storage?.persisted?.().catch(() => false)) ?? false
553
+
554
+ const devices = (await navigator.mediaDevices?.enumerateDevices?.().catch(() => [])) ?? []
555
+ const settings = stream?.getVideoTracks()[0]?.getSettings()
556
+ const mime = mimeType()
557
+ const storageReady = persistent || !!desktop
558
+
559
+ return {
560
+ supported: supported(),
561
+ available: ready && storageReady && stream?.getVideoTracks()[0]?.readyState === 'live',
562
+ reason: !supported()
563
+ ? 'Secure media capture, a supported WebM/MP4 codec, and durable storage are required'
564
+ : !storageReady
565
+ ? 'Persistent origin storage must be granted before recording'
566
+ : !ready
567
+ ? 'An active permitted preview is required'
568
+ : undefined,
569
+ cameras: devices
570
+ .filter((device) => device.kind === 'videoinput')
571
+ .map((device) => ({ id: device.deviceId, label: device.label })),
572
+ profiles:
573
+ settings?.width && settings.height && settings.frameRate
574
+ ? [
575
+ {
576
+ profile: 'standard' as const,
577
+ width: settings.width,
578
+ height: settings.height,
579
+ frameRate: settings.frameRate,
580
+ },
581
+ ]
582
+ : [],
583
+ audio: devices.some((device) => device.kind === 'audioinput'),
584
+ // The `pointsOfInterest` track constraint is not wired into
585
+ // the adapter — report honestly rather than fabricate.
586
+ focusPointOfInterest: false,
587
+ exposurePointOfInterest: false,
588
+ zoom: (() => {
589
+ const state = readZoom()
590
+
591
+ return !!state && state.maxZoom > state.minZoom
592
+ })(),
593
+ orientations: [],
594
+ cameraSwitchDuringRecording: supportsRecordingVideoSource(),
595
+ durationLimit: 'bestEffort',
596
+ elapsedTime: 'estimated',
597
+ output: {
598
+ mimeType: mime,
599
+ container: !mime ? '' : mime.startsWith('video/mp4') ? 'mp4' : 'webm',
600
+ storage: desktop ? 'appPrivateFile' : 'originLocal',
601
+ destinationFileUrl: !!desktop,
602
+ },
603
+ }
604
+ },
605
+ previewReady: () =>
606
+ ready && !!host && !released && stream?.getVideoTracks()[0]?.readyState === 'live',
607
+ validateStart: (options) => {
608
+ // Once the desktop-host probe settles absent, browser storage rules
609
+ // apply synchronously. A pending probe defers both checks to the
610
+ // async start path, which knows the real storage owner.
611
+ if (hostState === 'absent') {
612
+ if (!persistent) {
613
+ throw error(
614
+ 'destinationUnavailable',
615
+ 'startRecording',
616
+ 'Persistent origin storage has not been granted; check capabilities after a user permission action',
617
+ )
618
+ }
619
+
620
+ if (options.destinationFileUrl) {
621
+ throw error(
622
+ 'unsupportedConfiguration',
623
+ 'startRecording',
624
+ 'Browser output does not accept native file URLs',
625
+ )
626
+ }
627
+ }
628
+
629
+ if (options.orientation && options.orientation !== 'unspecified') {
630
+ throw error(
631
+ 'unsupportedConfiguration',
632
+ 'startRecording',
633
+ 'This browser cannot lock a recording orientation',
634
+ )
635
+ }
636
+ },
637
+ attachPreview: (target, callbacks) => {
638
+ if (released || sink) {
639
+ throw error('invalidState', 'attachPreview', 'The camera is disposed or still finalizing')
640
+ }
641
+
642
+ host = target as HTMLVideoElement
643
+ listener = callbacks
644
+ document.addEventListener('visibilitychange', onVisibility)
645
+ globalThis.addEventListener('pagehide', onPageHide)
646
+ void showPreview().catch((cause) =>
647
+ callbacks?.onError?.(
648
+ error('unavailable', 'preview', 'Could not activate camera preview', cause),
649
+ ),
650
+ )
651
+
652
+ return () => {
653
+ if (host) {
654
+ host.srcObject = null
655
+ }
656
+
657
+ host = undefined
658
+ listener = undefined
659
+ generation += 1
660
+ markReady(false)
661
+ document.removeEventListener('visibilitychange', onVisibility)
662
+ globalThis.removeEventListener('pagehide', onPageHide)
663
+ if (!sink) {
664
+ dropStream()
665
+ }
666
+ }
667
+ },
668
+ configure: (next) => {
669
+ const sourceChanged =
670
+ JSON.stringify(next.camera) !== JSON.stringify(currentConfig.camera) ||
671
+ next.profile !== currentConfig.profile
672
+
673
+ currentConfig = { ...next }
674
+ if (sourceChanged) {
675
+ generation += 1
676
+ dropStream()
677
+ if (host) {
678
+ void showPreview().catch((cause) =>
679
+ listener?.onError?.(
680
+ error('unavailable', 'configure', 'Could not change camera', cause),
681
+ ),
682
+ )
683
+ }
684
+ }
685
+ },
686
+ switchCamera: (camera: CameraSelection) => {
687
+ if (!sink || !recordingVideo || pendingSwitch) {
688
+ throw error('invalidState', 'switchCamera', 'The recording source cannot switch now')
689
+ }
690
+
691
+ if (
692
+ (camera === 'front' || camera === 'back') &&
693
+ !navigator.mediaDevices.getSupportedConstraints().facingMode
694
+ ) {
695
+ throw error(
696
+ 'unsupportedConfiguration',
697
+ 'switchCamera',
698
+ 'This browser cannot select by facing; choose a listed camera device ID',
699
+ )
700
+ }
701
+
702
+ const videoSource = recordingVideo
703
+ const previous = currentConfig.camera
704
+ const microphones = stream?.getAudioTracks() ?? []
705
+ let cancelled = false
706
+ let acquired = false
707
+ let rejectCancellation: (error: Error) => void = () => {}
708
+ const cancellation = new Promise<never>((_resolve, reject) => {
709
+ rejectCancellation = reject
710
+ })
711
+
712
+ const operation = {
713
+ cancel: () => {
714
+ if (cancelled || pendingSwitch !== operation) {
715
+ return
716
+ }
717
+
718
+ cancelled = true
719
+ videoSource.hold()
720
+ stream?.getVideoTracks().forEach((track) => track.stop())
721
+ markReady(false)
722
+ pendingSwitch = undefined
723
+ rejectCancellation(
724
+ error('invalidState', 'switchCamera', 'Camera switching was cancelled'),
725
+ )
726
+ },
727
+ }
728
+
729
+ pendingSwitch = operation
730
+
731
+ const check = () => {
732
+ if (cancelled || released || recordingVideo !== videoSource || !sink) {
733
+ throw error('invalidState', 'switchCamera', 'The recording is no longer active')
734
+ }
735
+ }
736
+
737
+ const obtain = async (selection: CameraSelection | undefined) => {
738
+ let expired = false
739
+ let timeout: ReturnType<typeof setTimeout> | undefined
740
+ const acquisition = navigator.mediaDevices
741
+ .getUserMedia({ video: constraints(selection), audio: false })
742
+ .then((value) => {
743
+ if (expired || cancelled || released) {
744
+ value.getTracks().forEach((track) => track.stop())
745
+ throw error('invalidState', 'switchCamera', 'Camera acquisition was retired')
746
+ }
747
+
748
+ return value
749
+ })
750
+
751
+ try {
752
+ return await Promise.race([
753
+ acquisition,
754
+ cancellation,
755
+ new Promise<never>((_resolve, reject) => {
756
+ timeout = setTimeout(
757
+ () => reject(error('unavailable', 'switchCamera', 'Camera acquisition timed out')),
758
+ 5000,
759
+ )
760
+ }),
761
+ ])
762
+ } finally {
763
+ expired = true
764
+ clearTimeout(timeout)
765
+ }
766
+ }
767
+
768
+ const install = async (selection: CameraSelection | undefined) => {
769
+ check()
770
+
771
+ const acquired = await obtain(selection)
772
+
773
+ try {
774
+ check()
775
+
776
+ const settings = acquired.getVideoTracks()[0]!.getSettings()
777
+ const expectedFacing =
778
+ selection === 'front' ? 'user' : selection === 'back' ? 'environment' : undefined
779
+
780
+ if (expectedFacing && settings.facingMode !== expectedFacing) {
781
+ throw error(
782
+ 'unsupportedConfiguration',
783
+ 'switchCamera',
784
+ 'The requested camera facing could not be confirmed; choose a device ID',
785
+ )
786
+ }
787
+
788
+ for (const microphone of microphones) {
789
+ acquired.addTrack(microphone)
790
+ }
791
+
792
+ stream = acquired
793
+ observeTracks(acquired)
794
+ await videoSource.setSource(acquired)
795
+ check()
796
+ if (host) {
797
+ host.style.transform = settings.facingMode === 'user' ? 'scaleX(-1)' : ''
798
+ }
799
+
800
+ markReady(true)
801
+ check()
802
+ return {
803
+ id: settings.deviceId ?? '',
804
+ label: acquired.getVideoTracks()[0]!.label,
805
+ facing:
806
+ settings.facingMode === 'user'
807
+ ? ('front' as const)
808
+ : settings.facingMode === 'environment'
809
+ ? ('back' as const)
810
+ : undefined,
811
+ }
812
+ } catch (cause) {
813
+ acquired.getVideoTracks().forEach((track) => track.stop())
814
+ throw cause
815
+ }
816
+ }
817
+
818
+ const completion = (async () => {
819
+ videoSource.hold()
820
+ stream?.getVideoTracks().forEach((track) => track.stop())
821
+ stream = new MediaStream(microphones)
822
+ observeTracks(stream)
823
+ markReady(false)
824
+ try {
825
+ const selected = await install(camera)
826
+
827
+ acquired = true
828
+ return selected
829
+ } catch (cause) {
830
+ if (!cancelled && !released) {
831
+ try {
832
+ await install(previous)
833
+ } catch (rollback) {
834
+ switchWarning = error(
835
+ 'captureFailed',
836
+ 'switchCamera',
837
+ 'Camera switching and rollback failed; the captured take was finalized',
838
+ rollback,
839
+ )
840
+
841
+ sink?.finishing('cameraUnavailable')
842
+ stop()
843
+ }
844
+ }
845
+
846
+ throw cause instanceof CameraCaptureError
847
+ ? cause
848
+ : error('unavailable', 'switchCamera', 'Could not acquire the requested camera', cause)
849
+ } finally {
850
+ if (!acquired && pendingSwitch === operation) {
851
+ pendingSwitch = undefined
852
+ }
853
+ }
854
+ })()
855
+
856
+ return {
857
+ completion,
858
+ commit: () => {
859
+ check()
860
+ if (!acquired || pendingSwitch !== operation) {
861
+ throw error(
862
+ 'invalidState',
863
+ 'switchCamera',
864
+ 'Camera switching was cancelled before commit',
865
+ )
866
+ }
867
+
868
+ currentConfig = { ...currentConfig, camera }
869
+ pendingSwitch = undefined
870
+ },
871
+ cancel: operation.cancel,
872
+ }
873
+ },
874
+ startCapture: (request, target) => {
875
+ sink = target
876
+ recordingAudio = request.audio
877
+ switchWarning = undefined
878
+ startedAt = 0
879
+ stoppedAt = 0
880
+
881
+ const source = stream
882
+ const video = source?.getVideoTracks()[0]
883
+ const audio = source?.getAudioTracks().filter((track) => track.readyState === 'live') ?? []
884
+
885
+ if (!video || (request.audio && !audio.length)) {
886
+ settle({
887
+ kind: 'failed',
888
+ stage: 'preparation',
889
+ issue: error(
890
+ request.audio ? 'permissionDenied' : 'unavailable',
891
+ 'startRecording',
892
+ request.audio
893
+ ? 'Requested microphone access is missing'
894
+ : 'Video source is unavailable',
895
+ ),
896
+ })
897
+
898
+ return
899
+ }
900
+
901
+ let recordingStream = new MediaStream([video, ...(request.audio ? audio : [])])
902
+ let desktop: CameraHost | null = null
903
+ let reservation: string | undefined
904
+ let stage: 'preparation' | 'capture' | 'finalization' | 'storage' = 'preparation'
905
+ const chunks: Blob[] = []
906
+ let captureError: unknown
907
+ let limitReached = false
908
+ let failing = false
909
+ let didStart = false
910
+
911
+ captureFailure = fail
912
+ void (async () => {
913
+ try {
914
+ desktop = await hostProbe
915
+ if (request.destinationPath && !desktop) {
916
+ throw error(
917
+ 'unsupportedConfiguration',
918
+ 'startRecording',
919
+ 'Web recordings do not accept native file destinations',
920
+ )
921
+ }
922
+
923
+ if (desktop) {
924
+ reservation = (
925
+ await reserveHostMovie(desktop, {
926
+ destinationFileUrl: request.destinationPath
927
+ ? `file://${request.destinationPath.split('/').map(encodeURIComponent).join('/')}`
928
+ : undefined,
929
+ container: mimeType().startsWith('video/mp4') ? 'mp4' : 'webm',
930
+ })
931
+ ).fileUrl
932
+ } else {
933
+ if (!(await navigator.storage?.persisted?.())) {
934
+ throw error(
935
+ 'destinationUnavailable',
936
+ 'startRecording',
937
+ 'Persistent storage is unavailable',
938
+ )
939
+ }
940
+
941
+ reservation = await reserveMovie()
942
+ }
943
+
944
+ if (!source || video.readyState !== 'live' || document.visibilityState === 'hidden') {
945
+ throw error(
946
+ 'unavailable',
947
+ 'startRecording',
948
+ 'Camera source became inactive before recording',
949
+ )
950
+ }
951
+
952
+ if (supportsRecordingVideoSource()) {
953
+ const settings = video.getSettings()
954
+
955
+ recordingVideo = createRecordingVideoSource(
956
+ settings.width ?? 1280,
957
+ settings.height ?? 720,
958
+ settings.frameRate ?? 30,
959
+ )
960
+
961
+ await recordingVideo.setSource(source)
962
+ recordingStream = new MediaStream([
963
+ ...recordingVideo.stream.getVideoTracks(),
964
+ ...(request.audio ? audio : []),
965
+ ])
966
+
967
+ if (host) {
968
+ host.srcObject = recordingVideo.stream
969
+ await host.play()
970
+ }
971
+ }
972
+
973
+ const activeRecorder = new MediaRecorder(recordingStream, { mimeType: mimeType() })
974
+
975
+ recorder = activeRecorder
976
+ activeRecorder.ondataavailable = (event) => {
977
+ if (sink !== target || failing) {
978
+ return
979
+ }
980
+
981
+ if (event.data.size) {
982
+ chunks.push(event.data)
983
+ }
984
+ }
985
+
986
+ activeRecorder.onerror = (event) => {
987
+ if (sink !== target || failing) {
988
+ return
989
+ }
990
+
991
+ captureError = event
992
+ stop()
993
+ }
994
+
995
+ activeRecorder.onstart = () => {
996
+ if (sink !== target || failing) {
997
+ return
998
+ }
999
+
1000
+ if (didStart) {
1001
+ return
1002
+ }
1003
+
1004
+ didStart = true
1005
+ clearTimeout(watchdog)
1006
+ startedAt = performance.now()
1007
+ stage = 'capture'
1008
+
1009
+ const settings = video.getSettings()
1010
+ const effective: EffectiveCaptureConfig = {
1011
+ cameraId: settings.deviceId ?? '',
1012
+ facing:
1013
+ settings.facingMode === 'user'
1014
+ ? 'front'
1015
+ : settings.facingMode === 'environment'
1016
+ ? 'back'
1017
+ : undefined,
1018
+ audio: request.audio,
1019
+ width: settings.width ?? 0,
1020
+ height: settings.height ?? 0,
1021
+ frameRate: settings.frameRate ?? 0,
1022
+ orientation: 'unspecified',
1023
+ mimeType: activeRecorder.mimeType,
1024
+ container: activeRecorder.mimeType.startsWith('video/mp4') ? 'mp4' : 'webm',
1025
+ }
1026
+
1027
+ // The adapter owns a limit even when capabilities() was not called.
1028
+ if (request.maximumDurationMs) {
1029
+ const limit = request.maximumDurationMs
1030
+ const checkLimit = () => {
1031
+ if (sink !== target || failing) {
1032
+ return
1033
+ }
1034
+
1035
+ const remaining = limit - (performance.now() - startedAt)
1036
+
1037
+ if (remaining > 0) {
1038
+ stopTimer = setTimeout(checkLimit, Math.min(remaining, 2_147_483_647))
1039
+ } else {
1040
+ limitReached = true
1041
+ stop()
1042
+ }
1043
+ }
1044
+
1045
+ stopTimer = setTimeout(checkLimit, Math.min(limit, 2_147_483_647))
1046
+ }
1047
+
1048
+ target.started(effective)
1049
+ }
1050
+
1051
+ activeRecorder.onstop = () => {
1052
+ if (sink !== target || failing) {
1053
+ return
1054
+ }
1055
+
1056
+ target.finishing(
1057
+ captureError ? 'captureError' : limitReached ? 'maximumDuration' : undefined,
1058
+ )
1059
+
1060
+ stoppedAt ||= performance.now()
1061
+ clearTimeout(stopTimer)
1062
+ clearTimeout(watchdog)
1063
+ void (async () => {
1064
+ try {
1065
+ stage = 'finalization'
1066
+ if (!startedAt) {
1067
+ throw error('noMedia', 'finalize', 'No recording start was observed')
1068
+ }
1069
+
1070
+ const bytes = new Blob(chunks, { type: activeRecorder.mimeType })
1071
+ const metadata = await inspectMovie(bytes, request.audio)
1072
+
1073
+ if (sink !== target || failing) {
1074
+ return
1075
+ }
1076
+
1077
+ stage = 'storage'
1078
+
1079
+ const output = desktop
1080
+ ? await commitHostMovie(desktop, reservation!, bytes)
1081
+ : {
1082
+ kind: 'browserStorage' as const,
1083
+ resourceId: reservation!,
1084
+ retention: 'persistent' as const,
1085
+ }
1086
+
1087
+ const clip: MovieClip = { ...metadata, output }
1088
+
1089
+ if (!desktop) {
1090
+ await commitMovie(reservation!, bytes, clip)
1091
+ }
1092
+
1093
+ settle(
1094
+ {
1095
+ kind: 'clip',
1096
+ ...clip,
1097
+ limitReached,
1098
+ warning:
1099
+ switchWarning ??
1100
+ (captureError
1101
+ ? error(
1102
+ 'captureFailed',
1103
+ 'capture',
1104
+ 'Recorder reported an error; finalized media was verified',
1105
+ captureError,
1106
+ )
1107
+ : undefined),
1108
+ },
1109
+ target,
1110
+ )
1111
+ } catch (cause) {
1112
+ await fail(cause)
1113
+ }
1114
+ })()
1115
+ }
1116
+
1117
+ activeRecorder.start(1000)
1118
+ watchdog = setTimeout(() => {
1119
+ if (!startedAt && sink === target) {
1120
+ stop()
1121
+ void fail(
1122
+ error('captureFailed', 'startRecording', 'Recorder start callback timed out'),
1123
+ )
1124
+ }
1125
+ }, 15_000)
1126
+ } catch (cause) {
1127
+ await fail(cause)
1128
+ }
1129
+ })()
1130
+
1131
+ async function fail(cause: unknown) {
1132
+ if (sink !== target || failing) {
1133
+ return
1134
+ }
1135
+
1136
+ failing = true
1137
+ if (reservation) {
1138
+ await (desktop
1139
+ ? removeHostReservation(desktop, reservation)
1140
+ : removeReservation(reservation).catch(() => {}))
1141
+ }
1142
+
1143
+ settle(
1144
+ {
1145
+ kind: 'failed',
1146
+ stage,
1147
+ issue:
1148
+ cause instanceof CameraCaptureError
1149
+ ? cause
1150
+ : error(
1151
+ stage === 'storage'
1152
+ ? 'storageFailed'
1153
+ : stage === 'preparation' || stage === 'capture'
1154
+ ? 'captureFailed'
1155
+ : 'finalizationFailed',
1156
+ stage,
1157
+ 'Movie recording could not complete',
1158
+ cause,
1159
+ ),
1160
+ },
1161
+ target,
1162
+ )
1163
+ }
1164
+ },
1165
+ stopCapture: stop,
1166
+ elapsedMs: () => (startedAt ? Math.max(0, (stoppedAt || performance.now()) - startedAt) : 0),
1167
+ zoomState: () => readZoom(),
1168
+ setZoom: (ratio) => {
1169
+ const track = stream?.getVideoTracks()[0]
1170
+ const applied = track?.applyConstraints?.({
1171
+ advanced: [{ zoom: ratio } as any],
1172
+ })
1173
+
1174
+ applied?.catch?.(() => {})
1175
+ },
1176
+ openOutput: async (output) => {
1177
+ if (output.kind === 'nativeFile') {
1178
+ const desktop = await hostProbe
1179
+
1180
+ if (!desktop) {
1181
+ throw error(
1182
+ 'unavailable',
1183
+ 'openOutput',
1184
+ 'File-backed output requires the desktop host that recorded it',
1185
+ )
1186
+ }
1187
+
1188
+ return openHostMovie(desktop, output)
1189
+ }
1190
+
1191
+ return openStoredMovie(output)
1192
+ },
1193
+ release: async () => {
1194
+ released = true
1195
+ generation += 1
1196
+ document.removeEventListener('visibilitychange', onVisibility)
1197
+ globalThis.removeEventListener('pagehide', onPageHide)
1198
+ dropStream()
1199
+ host = undefined
1200
+ },
1201
+ setObserver: (value) => {
1202
+ observer = value
1203
+ },
1204
+ }
891
1205
  }