@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
@@ -2,22 +2,22 @@ import { Application } from '@nativescript/core'
2
2
  import { CameraCaptureError } from './types'
3
3
  import { canonicalizePath } from './session-core'
4
4
  import type {
5
- BackendCaptureRequest,
6
- BackendCaptureSink,
7
- BackendObserver,
8
- BackendPreviewListener,
9
- CameraSessionBackend,
5
+ BackendCaptureRequest,
6
+ BackendCaptureSink,
7
+ BackendObserver,
8
+ BackendPreviewListener,
9
+ CameraSessionBackend,
10
10
  } from './session-core'
11
11
 
12
12
  import type {
13
- CameraDeviceInfo,
14
- CameraOrientation,
15
- CameraPermissionKind,
16
- CameraPermissionStatus,
17
- CameraSessionConfig,
18
- CaptureIssue,
19
- EffectiveCaptureConfig,
20
- MovieOutputHandle,
13
+ CameraDeviceInfo,
14
+ CameraOrientation,
15
+ CameraPermissionKind,
16
+ CameraPermissionStatus,
17
+ CameraSessionConfig,
18
+ CaptureIssue,
19
+ EffectiveCaptureConfig,
20
+ MovieOutputHandle,
21
21
  } from './types'
22
22
 
23
23
  /** Windows adapter: one `Windows.Media.Capture.MediaCapture` shared between a
@@ -66,245 +66,250 @@ const fileOrientation180 = 180
66
66
  const fileOrientation270 = 270
67
67
 
68
68
  const capabilityNameFor = (kind: CameraPermissionKind): string =>
69
- kind === 'camera' ? 'webcam' : 'microphone'
69
+ kind === 'camera' ? 'webcam' : 'microphone'
70
70
 
71
71
  const minFreeDiskBytes = 64 * 1024 * 1024
72
72
 
73
73
  const projection = (): { Windows?: any; Microsoft?: any; NSWinRT?: any } => {
74
- const host = globalThis as any
75
- return { Windows: host.Windows, Microsoft: host.Microsoft, NSWinRT: host.NSWinRT }
74
+ const host = globalThis as any
75
+
76
+ return { Windows: host.Windows, Microsoft: host.Microsoft, NSWinRT: host.NSWinRT }
76
77
  }
77
78
 
78
79
  const error = (kind: CaptureIssue['kind'], operation: string, message: string, cause?: unknown) =>
79
- new CameraCaptureError({ kind, operation, message, cause })
80
+ new CameraCaptureError({ kind, operation, message, cause })
80
81
 
81
82
  const issue = (
82
- kind: CaptureIssue['kind'],
83
- operation: string,
84
- message: string,
85
- extra?: Partial<CaptureIssue>,
83
+ kind: CaptureIssue['kind'],
84
+ operation: string,
85
+ message: string,
86
+ extra?: Partial<CaptureIssue>,
86
87
  ): CaptureIssue => ({ kind, operation, message, ...extra })
87
88
 
88
89
  /** AppCapabilityAccessStatus → portable permission. `notDeclared` is a
89
90
  * setup error, not a status — callers surface `configurationMissing`. */
90
91
  export const accessStatusToPermission: (
91
- status: number | undefined,
92
+ status: number | undefined,
92
93
  ) => CameraPermissionStatus | 'notDeclared' = (
93
- status: number | undefined,
94
+ status: number | undefined,
94
95
  ): CameraPermissionStatus | 'notDeclared' => {
95
- switch (status) {
96
- case appCapabilityAllowed:
97
- return 'granted'
98
- case appCapabilityDeniedByUser:
99
- return 'denied'
100
- case appCapabilityDeniedBySystem:
101
- return 'restricted'
102
- case appCapabilityUserPromptRequired:
103
- return 'notDetermined'
104
- case appCapabilityNotDeclaredByApp:
105
- return 'notDeclared'
106
- default:
107
- return 'unknown'
108
- }
96
+ switch (status) {
97
+ case appCapabilityAllowed:
98
+ return 'granted'
99
+ case appCapabilityDeniedByUser:
100
+ return 'denied'
101
+ case appCapabilityDeniedBySystem:
102
+ return 'restricted'
103
+ case appCapabilityUserPromptRequired:
104
+ return 'notDetermined'
105
+ case appCapabilityNotDeclaredByApp:
106
+ return 'notDeclared'
107
+ default:
108
+ return 'unknown'
109
+ }
109
110
  }
110
111
 
111
112
  /** DeviceAccessStatus → portable permission for hosts without AppCapability. */
112
113
  export const deviceAccessStatusToPermission: (
113
- status: number | undefined,
114
+ status: number | undefined,
114
115
  ) => CameraPermissionStatus = (status: number | undefined): CameraPermissionStatus => {
115
- switch (status) {
116
- case deviceAccessAllowed:
117
- return 'granted'
118
- case deviceAccessDeniedByUser:
119
- return 'denied'
120
- case deviceAccessDeniedBySystem:
121
- return 'restricted'
122
- case deviceAccessUnspecified:
123
- return 'notDetermined'
124
- default:
125
- return 'unknown'
126
- }
116
+ switch (status) {
117
+ case deviceAccessAllowed:
118
+ return 'granted'
119
+ case deviceAccessDeniedByUser:
120
+ return 'denied'
121
+ case deviceAccessDeniedBySystem:
122
+ return 'restricted'
123
+ case deviceAccessUnspecified:
124
+ return 'notDetermined'
125
+ default:
126
+ return 'unknown'
127
+ }
127
128
  }
128
129
 
129
130
  /** Enclosure panel → facing. Desktop cameras often report no panel — an
130
131
  * external webcam never fabricates front/back semantics. */
131
132
  export const panelToFacing: (panel: number | undefined) => 'front' | 'back' | undefined = (
132
- panel: number | undefined,
133
+ panel: number | undefined,
133
134
  ): 'front' | 'back' | undefined =>
134
- panel === panelFront ? 'front' : panel === panelBack ? 'back' : undefined
135
+ panel === panelFront ? 'front' : panel === panelBack ? 'back' : undefined
135
136
 
136
137
  /** Stored display rotation (degrees CW) → cardinal orientation, matching the
137
138
  * iOS transform mapping. Missing or unrecognized values stay `unspecified`. */
138
139
  export const videoOrientationToOrientation: (degrees: number | undefined) => CameraOrientation = (
139
- degrees: number | undefined,
140
+ degrees: number | undefined,
140
141
  ): CameraOrientation => {
141
- switch (degrees) {
142
- case fileOrientation90:
143
- return 'portrait'
144
- case fileOrientation180:
145
- return 'landscapeLeft'
146
- case fileOrientation270:
147
- return 'portraitUpsideDown'
148
- case fileOrientationNormal:
149
- return 'landscapeRight'
150
- default:
151
- return 'unspecified'
152
- }
142
+ switch (degrees) {
143
+ case fileOrientation90:
144
+ return 'portrait'
145
+ case fileOrientation180:
146
+ return 'landscapeLeft'
147
+ case fileOrientation270:
148
+ return 'portraitUpsideDown'
149
+ case fileOrientationNormal:
150
+ return 'landscapeRight'
151
+ default:
152
+ return 'unspecified'
153
+ }
153
154
  }
154
155
 
155
156
  export const orientationToRotation: (orientation: CameraOrientation) => number | undefined = (
156
- orientation: CameraOrientation,
157
+ orientation: CameraOrientation,
157
158
  ): number | undefined =>
158
- orientation === 'portrait'
159
- ? recordRotation90
160
- : orientation === 'portraitUpsideDown'
161
- ? recordRotation270
162
- : orientation === 'landscapeLeft'
163
- ? recordRotation180
164
- : orientation === 'landscapeRight'
165
- ? recordRotationNone
166
- : undefined
159
+ orientation === 'portrait'
160
+ ? recordRotation90
161
+ : orientation === 'portraitUpsideDown'
162
+ ? recordRotation270
163
+ : orientation === 'landscapeLeft'
164
+ ? recordRotation180
165
+ : orientation === 'landscapeRight'
166
+ ? recordRotationNone
167
+ : undefined
167
168
 
168
169
  export interface WindowsCameraDevice {
169
- id: string
170
- label: string
171
- facing?: 'front' | 'back'
170
+ id: string
171
+ label: string
172
+ facing?: 'front' | 'back'
172
173
  }
173
174
 
174
175
  /** Camera selection: explicit deviceId wins; front/back match the enclosure
175
176
  * panel; `default` takes the OS-preferred camera then the first device. */
176
177
  export const selectCameraDevice: (
177
- camera: CameraSessionConfig['camera'],
178
- devices: WindowsCameraDevice[],
179
- defaultId: string | undefined,
178
+ camera: CameraSessionConfig['camera'],
179
+ devices: WindowsCameraDevice[],
180
+ defaultId: string | undefined,
180
181
  ) => WindowsCameraDevice | undefined = (
181
- camera: CameraSessionConfig['camera'],
182
- devices: WindowsCameraDevice[],
183
- defaultId: string | undefined,
182
+ camera: CameraSessionConfig['camera'],
183
+ devices: WindowsCameraDevice[],
184
+ defaultId: string | undefined,
184
185
  ): WindowsCameraDevice | undefined => {
185
- if (camera && typeof camera === 'object' && 'deviceId' in camera) {
186
- return devices.find((entry) => entry.id === camera.deviceId)
187
- }
188
-
189
- if (camera === 'front' || camera === 'back') {
190
- return devices.find((entry) => entry.facing === camera)
191
- }
192
-
193
- return (
194
- devices.find((entry) => entry.id === defaultId) ??
195
- devices.find((entry) => entry.facing === 'back') ??
196
- devices[0]
197
- )
186
+ if (camera && typeof camera === 'object' && 'deviceId' in camera) {
187
+ return devices.find((entry) => entry.id === camera.deviceId)
188
+ }
189
+
190
+ if (camera === 'front' || camera === 'back') {
191
+ return devices.find((entry) => entry.facing === camera)
192
+ }
193
+
194
+ return (
195
+ devices.find((entry) => entry.id === defaultId) ??
196
+ devices.find((entry) => entry.facing === 'back') ??
197
+ devices[0]
198
+ )
198
199
  }
199
200
 
200
201
  export interface WindowsStreamProfile {
201
- width: number
202
- height: number
203
- frameRate: number
204
- subtype?: string
202
+ width: number
203
+ height: number
204
+ frameRate: number
205
+ subtype?: string
205
206
  }
206
207
 
207
208
  /** Pick the standard profile: 1280x720 @ 30 fps when the source offers it,
208
209
  * otherwise the smallest stream then lowest frame rate. The selected
209
210
  * combination is disclosed — never an idealized 720p claim. */
210
211
  export const chooseStandardProfile: (
211
- profiles: WindowsStreamProfile[],
212
+ profiles: WindowsStreamProfile[],
212
213
  ) => WindowsStreamProfile | undefined = (
213
- profiles: WindowsStreamProfile[],
214
+ profiles: WindowsStreamProfile[],
214
215
  ): WindowsStreamProfile | undefined => {
215
- if (!profiles.length) {
216
- return undefined
217
- }
218
-
219
- const exact = profiles.find(
220
- (entry) => entry.width === 1280 && entry.height === 720 && Math.round(entry.frameRate) === 30,
221
- )
222
-
223
- if (exact) {
224
- return exact
225
- }
226
-
227
- return [...profiles].sort((a, b) => {
228
- const areaDelta = a.width * a.height - b.width * b.height
229
- if (areaDelta !== 0) {
230
- return areaDelta
231
- }
232
-
233
- return a.frameRate - b.frameRate
234
- })[0]
216
+ if (!profiles.length) {
217
+ return undefined
218
+ }
219
+
220
+ const exact = profiles.find(
221
+ (entry) => entry.width === 1280 && entry.height === 720 && Math.round(entry.frameRate) === 30,
222
+ )
223
+
224
+ if (exact) {
225
+ return exact
226
+ }
227
+
228
+ return [...profiles].sort((a, b) => {
229
+ const areaDelta = a.width * a.height - b.width * b.height
230
+
231
+ if (areaDelta !== 0) {
232
+ return areaDelta
233
+ }
234
+
235
+ return a.frameRate - b.frameRate
236
+ })[0]
235
237
  }
236
238
 
237
239
  /** Classify a native failure without depending on projected error shapes.
238
240
  * HRESULTs surface as `number`/`hresult`; MediaCapture failures also carry a
239
241
  * numeric `code`. */
240
242
  export const captureFailureKind: (cause: unknown) => CaptureIssue['kind'] = (
241
- cause: unknown,
243
+ cause: unknown,
242
244
  ): CaptureIssue['kind'] => {
243
- const code = Number(
244
- (cause as any)?.number ?? (cause as any)?.hresult ?? (cause as any)?.code ?? Number.NaN,
245
- )
245
+ const code = Number(
246
+ (cause as any)?.number ?? (cause as any)?.hresult ?? (cause as any)?.code ?? Number.NaN,
247
+ )
248
+
249
+ const message = String((cause as any)?.message ?? cause ?? '').toLowerCase()
246
250
 
247
- const message = String((cause as any)?.message ?? cause ?? '').toLowerCase()
248
- if (code === -2147024891 || /access is denied|unauthorizedaccess|e_accessdenied/.test(message)) {
249
- return 'permissionDenied'
250
- }
251
+ if (code === -2147024891 || /access is denied|unauthorizedaccess|e_accessdenied/.test(message)) {
252
+ return 'permissionDenied'
253
+ }
251
254
 
252
- if (code === -2147024814 || /sharing violation|in use|0x800700aa/.test(message)) {
253
- return 'unavailable'
254
- }
255
+ if (code === -2147024814 || /sharing violation|in use|0x800700aa/.test(message)) {
256
+ return 'unavailable'
257
+ }
255
258
 
256
- if (/no capture devices|device (is )?not (available|found|ready)|cannot find/.test(message)) {
257
- return 'unavailable'
258
- }
259
+ if (/no capture devices|device (is )?not (available|found|ready)|cannot find/.test(message)) {
260
+ return 'unavailable'
261
+ }
259
262
 
260
- if (/quota|disk|storage|no space|insufficient/.test(message)) {
261
- return 'insufficientStorage'
262
- }
263
+ if (/quota|disk|storage|no space|insufficient/.test(message)) {
264
+ return 'insufficientStorage'
265
+ }
263
266
 
264
- return 'captureFailed'
267
+ return 'captureFailed'
265
268
  }
266
269
 
267
270
  /** WinRT TimeSpan marshals as `{ Duration: bigint|number }` of 100-ns ticks;
268
271
  * some projections surface the raw tick count. */
269
272
  const timeSpanToMs = (value: unknown): number => {
270
- const ticks =
271
- typeof value === 'bigint'
272
- ? Number(value)
273
- : typeof value === 'number'
274
- ? value
275
- : Number((value as any)?.Duration ?? (value as any)?.duration ?? Number.NaN)
276
-
277
- return Number.isFinite(ticks) ? ticks / 10_000 : Number.NaN
273
+ const ticks =
274
+ typeof value === 'bigint'
275
+ ? Number(value)
276
+ : typeof value === 'number'
277
+ ? value
278
+ : Number((value as any)?.Duration ?? (value as any)?.duration ?? Number.NaN)
279
+
280
+ return Number.isFinite(ticks) ? ticks / 10_000 : Number.NaN
278
281
  }
279
282
 
280
283
  const toPromise = async (op: any): Promise<any> => {
281
- const { NSWinRT } = projection()
282
- if (NSWinRT?.toPromise && op != null) {
283
- return NSWinRT.toPromise(op)
284
- }
285
-
286
- // Some preview builds expose `.done()` on the projected async op.
287
- if (op?.done) {
288
- return new Promise((resolve, reject) => {
289
- try {
290
- op.done(resolve, reject)
291
- } catch (cause) {
292
- reject(cause)
293
- }
294
- })
295
- }
296
-
297
- return op
284
+ const { NSWinRT } = projection()
285
+
286
+ if (NSWinRT?.toPromise && op != null) {
287
+ return NSWinRT.toPromise(op)
288
+ }
289
+
290
+ // Some preview builds expose `.done()` on the projected async op.
291
+ if (op?.done) {
292
+ return new Promise((resolve, reject) => {
293
+ try {
294
+ op.done(resolve, reject)
295
+ } catch (cause) {
296
+ reject(cause)
297
+ }
298
+ })
299
+ }
300
+
301
+ return op
298
302
  }
299
303
 
300
304
  const vectorToArray = (items: any): any[] => {
301
- const result: any[] = []
302
- const size = Number(items?.Size ?? items?.Count ?? 0)
303
- for (let index = 0; index < size; index += 1) {
304
- result.push(items.GetAt(index))
305
- }
305
+ const result: any[] = []
306
+ const size = Number(items?.Size ?? items?.Count ?? 0)
306
307
 
307
- return result
308
+ for (let index = 0; index < size; index += 1) {
309
+ result.push(items.GetAt(index))
310
+ }
311
+
312
+ return result
308
313
  }
309
314
 
310
315
  /** The first backend that initializes a device claims it — a new owner
@@ -312,1304 +317,1372 @@ const vectorToArray = (items: any): any[] => {
312
317
  const claimedDevices = new Map<string, object>()
313
318
 
314
319
  const normalizePath = (value: string): string => {
315
- let next = value.replace(/\//g, '\\')
316
- // file:///C:/dir/file.mp4 decodes to /C:/dir/file.mp4 — strip the leading
317
- // separator before a drive letter.
318
- next = next.replace(/^\\(?=[A-Za-z]:)/, '')
319
- return next
320
+ let next = value.replace(/\//g, '\\')
321
+
322
+ // file:///C:/dir/file.mp4 decodes to /C:/dir/file.mp4 — strip the leading
323
+ // separator before a drive letter.
324
+ next = next.replace(/^\\(?=[A-Za-z]:)/, '')
325
+ return next
320
326
  }
321
327
 
322
328
  const fileUrlForPath = (value: string): string =>
323
- `file:///${value.replace(/\\/g, '/').replace(/^\/+/, '')}`
329
+ `file:///${value.replace(/\\/g, '/').replace(/^\/+/, '')}`
324
330
 
325
331
  export function createSessionBackend(config: CameraSessionConfig): CameraSessionBackend {
326
- let currentConfig = { ...config }
327
- let observer: BackendObserver | undefined
328
- let host: any
329
- let listener: BackendPreviewListener | undefined
330
- let capture: any
331
- let captureElement: any
332
- let captureDevice: WindowsCameraDevice | undefined
333
- let captureAudioMode = false
334
- let previewReadyFlag = false
335
- let interrupted = false
336
- let released = false
337
- let generation = 0
338
- let watcher: any
339
- let watcherDelegates: { event: string; delegate: any }[] = []
340
- let captureDelegates: { event: string; delegate: any }[] = []
341
- let sink: BackendCaptureSink | undefined
342
- let request: BackendCaptureRequest | undefined
343
- let recordFile: any
344
- let recordStartedAt = 0
345
- let wantStop = false
346
- let finalizing = false
347
- const lease = {}
348
-
349
- const projectionAvailable = () => {
350
- const { Windows, Microsoft } = projection()
351
- return !!(
352
- Windows?.Media?.Capture?.MediaCapture &&
353
- Windows?.Media?.Capture?.MediaCaptureInitializationSettings &&
354
- Windows?.Devices?.Enumeration?.DeviceInformation &&
355
- Windows?.Storage?.ApplicationData &&
356
- Microsoft?.UI?.Xaml?.Controls?.CaptureElement
357
- )
358
- }
359
-
360
- const markReady = (value: boolean) => {
361
- if (previewReadyFlag === value) {
362
- return
363
- }
364
-
365
- previewReadyFlag = value
366
- observer?.previewReady(value)
367
- }
368
-
369
- const appCapability = (kind: CameraPermissionKind): any => {
370
- try {
371
- return projection().Windows?.Security?.Authorization?.AppCapabilityAccess?.AppCapability?.Create(
372
- capabilityNameFor(kind),
373
- )
374
- } catch {
375
- return undefined
376
- }
377
- }
378
-
379
- const deviceAccessInfo = (kind: CameraPermissionKind): any => {
380
- try {
381
- const enumeration = projection().Windows?.Devices?.Enumeration
382
- const deviceClass =
383
- kind === 'camera'
384
- ? enumeration?.DeviceClass?.VideoCapture
385
- : enumeration?.DeviceClass?.AudioCapture
386
-
387
- return deviceClass === undefined
388
- ? undefined
389
- : enumeration?.DeviceAccessInformation?.CreateFromDeviceClass(deviceClass)
390
- } catch {
391
- return undefined
392
- }
393
- }
394
-
395
- const checkPermission = async (kind: CameraPermissionKind): Promise<CameraPermissionStatus> => {
396
- const capability = appCapability(kind)
397
- if (capability) {
398
- try {
399
- const mapped = accessStatusToPermission(capability.CheckAccess())
400
- // A missing manifest declaration is a setup error, not a
401
- // status — expose it as unknown here and as
402
- // `configurationMissing` on request.
403
- return mapped === 'notDeclared' ? 'unknown' : mapped
404
- } catch {
405
- // Fall through to the enumeration-based probe.
406
- }
407
- }
408
-
409
- const info = deviceAccessInfo(kind)
410
- if (info) {
411
- try {
412
- return deviceAccessStatusToPermission(info.CurrentStatus)
413
- } catch {
414
- return 'unknown'
415
- }
416
- }
417
-
418
- return 'unknown'
419
- }
420
-
421
- let permissionChain: Promise<unknown> = Promise.resolve()
422
- const requestPermission = (kind: CameraPermissionKind): Promise<CameraPermissionStatus> => {
423
- const result = permissionChain.then(async () => {
424
- const status = await checkPermission(kind)
425
- if (status !== 'notDetermined') {
426
- if (status === 'unknown') {
427
- try {
428
- if (accessStatusToPermission(appCapability(kind)?.CheckAccess()) === 'notDeclared') {
429
- throw error(
430
- 'configurationMissing',
431
- 'requestPermission',
432
- `Missing '${capabilityNameFor(kind)}' device capability in the host app's Package.appxmanifest`,
433
- { permission: kind },
434
- )
435
- }
436
- } catch (cause) {
437
- if (cause instanceof CameraCaptureError) {
438
- throw cause
439
- }
440
- }
441
- }
442
-
443
- return status
444
- }
445
-
446
- const capability = appCapability(kind)
447
- if (!capability?.RequestAccessAsync) {
448
- return 'unknown'
449
- }
450
-
451
- try {
452
- const next = accessStatusToPermission(await toPromise(capability.RequestAccessAsync()))
453
- return next === 'notDeclared' ? 'unknown' : next
454
- } catch (cause) {
455
- throw error(
456
- 'unavailable',
457
- 'requestPermission',
458
- `The system ${kind} permission request could not run`,
459
- cause,
460
- )
461
- }
462
- })
463
-
464
- permissionChain = result.catch(() => {})
465
- return result
466
- }
467
-
468
- const listDevices = async (): Promise<WindowsCameraDevice[]> => {
469
- const enumeration = projection().Windows?.Devices?.Enumeration
470
- const deviceClass = enumeration?.DeviceClass?.VideoCapture
471
- if (!enumeration?.DeviceInformation?.FindAllAsync || deviceClass === undefined) {
472
- return []
473
- }
474
-
475
- const found = await toPromise(enumeration.DeviceInformation.FindAllAsync(deviceClass))
476
- return vectorToArray(found).map((device: any) => ({
477
- id: String(device?.Id ?? device?.id ?? ''),
478
- label: String(device?.Name ?? device?.name ?? device?.Id ?? ''),
479
- facing: panelToFacing(
480
- Number(device?.EnclosureLocation?.Panel ?? device?.EnclosureLocation?.panel),
481
- ),
482
- }))
483
- }
484
-
485
- const listAudioDevices = async (): Promise<number> => {
486
- try {
487
- const enumeration = projection().Windows?.Devices?.Enumeration
488
- const deviceClass = enumeration?.DeviceClass?.AudioCapture
489
- if (!enumeration?.DeviceInformation?.FindAllAsync || deviceClass === undefined) {
490
- return 0
491
- }
492
-
493
- const found = await toPromise(enumeration.DeviceInformation.FindAllAsync(deviceClass))
494
- return Number(found?.Size ?? found?.Count ?? 0)
495
- } catch {
496
- return 0
497
- }
498
- }
499
-
500
- const defaultDeviceId = (): string | undefined => {
501
- try {
502
- const devices = projection().Windows?.Media?.Devices
503
- const kind = devices?.AudioVideoCaptureDeviceKind?.Video
504
- const id = devices?.MediaDevice?.GetDefaultVideoCaptureId?.(kind)
505
- return typeof id === 'string' && id ? id : undefined
506
- } catch {
507
- return undefined
508
- }
509
- }
510
-
511
- const streamProfiles = (target: any, streamKind: any): WindowsStreamProfile[] => {
512
- const controller = target?.VideoDeviceController
513
- if (!controller?.GetAvailableMediaStreamProperties || streamKind === undefined) {
514
- return []
515
- }
516
-
517
- try {
518
- return vectorToArray(controller.GetAvailableMediaStreamProperties(streamKind))
519
- .map((entry: any) => ({
520
- width: Number(entry?.Width ?? 0),
521
- height: Number(entry?.Height ?? 0),
522
- frameRate:
523
- Number(entry?.FrameRate?.Numerator ?? 0) /
524
- Math.max(1, Number(entry?.FrameRate?.Denominator ?? 1)),
525
- subtype: typeof entry?.Subtype === 'string' ? entry.Subtype : undefined,
526
- }))
527
- .filter((entry: WindowsStreamProfile) => entry.width > 0 && entry.height > 0)
528
- } catch {
529
- return []
530
- }
531
- }
532
-
533
- const recordStreamProfiles = (): WindowsStreamProfile[] =>
534
- streamProfiles(capture, projection().Windows?.Media?.Capture?.MediaStreamType?.VideoRecord)
535
-
536
- const detachCaptureDelegates = () => {
537
- for (const entry of captureDelegates) {
538
- try {
539
- capture[entry.event] = null
540
- } catch {
541
- // The projection may not accept null — dropping the
542
- // references still detaches our handlers.
543
- }
544
- }
545
-
546
- captureDelegates = []
547
- }
548
-
549
- const onCaptureFailed = (_sender: any, args: any) => {
550
- const message = String(args?.Message ?? args?.message ?? 'Camera capture failed')
551
- markReady(false)
552
- observer?.availability(false)
553
- observer?.interruption(
554
- 'began',
555
- /in use|denied|access/i.test(message) ? 'cameraInUse' : 'unknown',
556
- )
557
-
558
- if (sink) {
559
- // The pipeline died under a live take — try to finalize the
560
- // partial media instead of discarding it outright. wantStop
561
- // makes the early stop stick while
562
- // StartRecordToStorageFileAsync is still in flight, and the
563
- // deadline settles the take if that call never resolves.
564
- wantStop = true
565
- armSettleDeadline(sink)
566
- sink.finishing(/device|available|found/i.test(message) ? 'cameraUnavailable' : 'captureError')
567
- void stopRecording()
568
- }
569
- }
570
-
571
- const onRecordLimitationExceeded = () => {
572
- // The OS-level recording limitation ended the take — finalize the
573
- // usable media and keep first-cause semantics from the core.
574
- wantStop = true
575
- armSettleDeadline(sink)
576
- sink?.finishing('interrupted')
577
- void stopRecording()
578
- }
579
-
580
- const attachCaptureDelegates = (target: any) => {
581
- const { NSWinRT } = projection()
582
- const subscribe = (event: string, type: string, handler: (...args: any[]) => void) => {
583
- try {
584
- const delegate = NSWinRT?.asDelegate ? NSWinRT.asDelegate(type, handler) : handler
585
- target[event] = delegate
586
- captureDelegates.push({ event, delegate })
587
- } catch {
588
- try {
589
- target[event] = handler
590
- captureDelegates.push({ event, delegate: handler })
591
- } catch {
592
- // The event is unsubscribable on this projection — the
593
- // adapter still functions without that notification.
594
- }
595
- }
596
- }
597
-
598
- subscribe(
599
- 'Failed',
600
- 'Windows.Foundation.TypedEventHandler`2<Windows.Media.Capture.MediaCapture,Windows.Media.Capture.MediaCaptureFailedEventArgs>',
601
- onCaptureFailed,
602
- )
603
-
604
- subscribe(
605
- 'RecordLimitationExceeded',
606
- 'Windows.Media.Capture.RecordLimitationExceededEventHandler',
607
- onRecordLimitationExceeded,
608
- )
609
- }
610
-
611
- const stopWatcher = () => {
612
- if (!watcher) {
613
- return
614
- }
615
-
616
- for (const entry of watcherDelegates) {
617
- try {
618
- watcher[entry.event] = null
619
- } catch {
620
- // See detachCaptureDelegates.
621
- }
622
- }
623
-
624
- watcherDelegates = []
625
- try {
626
- watcher.Stop()
627
- } catch {
628
- // A stopped or failed watcher still releases cleanly.
629
- }
630
-
631
- watcher = undefined
632
- }
633
-
634
- const ensureWatcher = () => {
635
- if (watcher) {
636
- return
637
- }
638
-
639
- const enumeration = projection().Windows?.Devices?.Enumeration
640
- const deviceClass = enumeration?.DeviceClass?.VideoCapture
641
- if (!enumeration?.DeviceInformation?.CreateWatcher || deviceClass === undefined) {
642
- return
643
- }
644
-
645
- try {
646
- const target = enumeration.DeviceInformation.CreateWatcher(deviceClass)
647
- const { NSWinRT } = projection()
648
- const subscribe = (event: string, type: string, handler: (...args: any[]) => void) => {
649
- const delegate = NSWinRT?.asDelegate ? NSWinRT.asDelegate(type, handler) : handler
650
- target[event] = delegate
651
- watcherDelegates.push({ event, delegate })
652
- }
653
-
654
- subscribe(
655
- 'Removed',
656
- 'Windows.Foundation.TypedEventHandler`2<Windows.Devices.Enumeration.DeviceWatcher,Windows.Devices.Enumeration.DeviceInformationUpdate>',
657
- (_sender: any, update: any) => {
658
- const id = String(update?.Id ?? update?.id ?? '')
659
- if (!id || id === captureDevice?.id) {
660
- observer?.availability(false)
661
- }
662
- },
663
- )
664
-
665
- subscribe(
666
- 'Added',
667
- 'Windows.Foundation.TypedEventHandler`2<Windows.Devices.Enumeration.DeviceWatcher,Windows.Devices.Enumeration.DeviceInformation>',
668
- () => observer?.availability(true),
669
- )
670
-
671
- target.Start()
672
- watcher = target
673
- } catch {
674
- watcher = undefined
675
- watcherDelegates = []
676
- }
677
- }
678
-
679
- const applyStreamProperties = async (target: any) => {
680
- const streamType = projection().Windows?.Media?.Capture?.MediaStreamType
681
- const controller = target?.VideoDeviceController
682
- const candidates = streamProfiles(target, streamType?.VideoRecord)
683
- const chosen = chooseStandardProfile(candidates)
684
- if (!controller?.SetMediaStreamPropertiesAsync || !chosen || !streamType) {
685
- return
686
- }
687
-
688
- const props = candidates.length
689
- ? vectorToArray(controller.GetAvailableMediaStreamProperties(streamType.VideoRecord)).find(
690
- (entry: any) =>
691
- Number(entry?.Width) === chosen.width && Number(entry?.Height) === chosen.height,
692
- )
693
- : undefined
694
-
695
- if (!props) {
696
- return
697
- }
698
-
699
- try {
700
- await toPromise(controller.SetMediaStreamPropertiesAsync(streamType.VideoRecord, props))
701
- try {
702
- await toPromise(controller.SetMediaStreamPropertiesAsync(streamType.VideoPreview, props))
703
- } catch {
704
- // A preview format mismatch must not block recording.
705
- }
706
- } catch {
707
- // The driver rejected the format request — the device default
708
- // still records and capabilities disclose what was measured.
709
- }
710
- }
711
-
712
- const releaseClaim = () => {
713
- if (captureDevice && claimedDevices.get(captureDevice.id) === lease) {
714
- claimedDevices.delete(captureDevice.id)
715
- }
716
- }
717
-
718
- const closeCapture = () => {
719
- detachCaptureDelegates()
720
- releaseClaim()
721
- const target = capture
722
- capture = undefined
723
- captureDevice = undefined
724
- captureAudioMode = false
725
- if (!target) {
726
- return
727
- }
728
-
729
- try {
730
- target.Close()
731
- } catch {
732
- try {
733
- target.Dispose()
734
- } catch {
735
- // GC reclaims the device handle.
736
- }
737
- }
738
- }
739
-
740
- const ensureCapture = async (): Promise<any> => {
741
- const epoch = generation
742
- if (capture) {
743
- return capture
744
- }
745
-
746
- const { Windows } = projection()
747
- const devices = await listDevices()
748
- const selected = selectCameraDevice(currentConfig.camera, devices, defaultDeviceId())
749
- if (!selected) {
750
- throw error('unavailable', 'startPreview', 'No camera device is available')
751
- }
752
-
753
- const owner = claimedDevices.get(selected.id)
754
- if (owner && owner !== lease) {
755
- throw error('busy', 'startPreview', 'Another camera session still owns this device')
756
- }
757
-
758
- const settings = new Windows.Media.Capture.MediaCaptureInitializationSettings()
759
- settings.VideoDeviceId = selected.id
760
- settings.StreamingCaptureMode =
761
- currentConfig.audio === true ? captureModeAudioAndVideo : captureModeVideo
762
-
763
- const target = new Windows.Media.Capture.MediaCapture()
764
- try {
765
- await toPromise(target.InitializeAsync(settings))
766
- } catch (cause) {
767
- try {
768
- target.Close()
769
- } catch {
770
- // See closeCapture.
771
- }
772
-
773
- throw error(
774
- captureFailureKind(cause),
775
- 'startPreview',
776
- 'The camera could not be initialized',
777
- cause,
778
- )
779
- }
780
-
781
- if (epoch !== generation || released) {
782
- try {
783
- target.Close()
784
- } catch {
785
- // See closeCapture.
786
- }
787
-
788
- throw error('unavailable', 'startPreview', 'The camera session was released')
789
- }
790
-
791
- capture = target
792
- captureDevice = selected
793
- captureAudioMode = currentConfig.audio === true
794
- claimedDevices.set(selected.id, lease)
795
- attachCaptureDelegates(target)
796
- ensureWatcher()
797
- await applyStreamProperties(target)
798
- try {
799
- if (selected.facing === 'front' && typeof target.SetPreviewMirroring === 'function') {
800
- target.SetPreviewMirroring(true)
801
- }
802
- } catch {
803
- // Mirrored preview is cosmetic; recorded output stays unmirrored.
804
- }
805
-
806
- return target
807
- }
808
-
809
- const activate = async (): Promise<void> => {
810
- const epoch = ++generation
811
- try {
812
- const target = await ensureCapture()
813
- if (!captureElement || epoch !== generation) {
814
- return
815
- }
816
-
817
- try {
818
- captureElement.Source = target
819
- } catch (cause) {
820
- throw error('unavailable', 'startPreview', 'The preview element rejected the source', cause)
821
- }
822
-
823
- await toPromise(target.StartPreviewAsync())
824
- if (epoch !== generation) {
825
- return
826
- }
827
-
828
- markReady(true)
829
- listener?.onReady?.()
830
- } catch (cause) {
831
- if (epoch === generation) {
832
- markReady(false)
833
- listener?.onError?.(
834
- cause instanceof CameraCaptureError
835
- ? cause
836
- : error('unavailable', 'startPreview', 'Camera preview could not start', cause),
837
- )
838
- }
839
- }
840
- }
841
-
842
- const deactivate = async () => {
843
- generation += 1
844
- markReady(false)
845
- const target = capture
846
- if (captureElement) {
847
- try {
848
- captureElement.Source = null
849
- } catch {
850
- // Detach is best-effort — the element may already be gone.
851
- }
852
- }
853
-
854
- if (target && !sink) {
855
- try {
856
- await toPromise(target.StopPreviewAsync())
857
- } catch {
858
- // The pipeline may already be down.
859
- }
860
- }
861
- }
862
-
863
- const recordingsFolder = async (): Promise<any> => {
864
- const storage = projection().Windows?.Storage
865
- const folder = storage?.ApplicationData?.Current?.LocalFolder
866
- if (!folder?.CreateFolderAsync) {
867
- throw error('destinationUnavailable', 'startRecording', 'App-private storage is unavailable')
868
- }
869
-
870
- return toPromise(folder.CreateFolderAsync('octane-camera', collisionOpenIfExists))
871
- }
872
-
873
- const reserveDestination = async (destinationPath: string | undefined): Promise<any> => {
874
- const storage = projection().Windows?.Storage
875
- if (!destinationPath) {
876
- const folder = await recordingsFolder()
877
- const name = `clip-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.mp4`
878
- return toPromise(folder.CreateFileAsync(name, collisionGenerateUniqueName))
879
- }
880
-
881
- // Durable output stays app-private like every other leaf — resolve
882
- // against LocalFolder, canonicalizing first so '..' cannot escape it.
883
- const filePath = canonicalizePath(normalizePath(destinationPath), '\\')
884
- const localRoot = normalizePath(
885
- String(storage?.ApplicationData?.Current?.LocalFolder?.Path ?? ''),
886
- )
887
-
888
- if (!localRoot || !filePath.toLowerCase().startsWith(`${localRoot.toLowerCase()}\\`)) {
889
- throw error(
890
- 'destinationUnavailable',
891
- 'startRecording',
892
- 'destinationFileUrl must resolve inside app-private storage',
893
- )
894
- }
895
-
896
- const directory = filePath.slice(0, filePath.lastIndexOf('\\'))
897
- const name = filePath.slice(filePath.lastIndexOf('\\') + 1)
898
- if (!directory || !name) {
899
- throw error(
900
- 'destinationUnavailable',
901
- 'startRecording',
902
- 'destinationFileUrl is not a file path',
903
- )
904
- }
905
-
906
- const tempPath = String(storage?.ApplicationData?.Current?.TemporaryFolder?.Path ?? '')
907
- if (tempPath && filePath.toLowerCase().startsWith(tempPath.toLowerCase())) {
908
- throw error(
909
- 'destinationUnavailable',
910
- 'startRecording',
911
- 'Temporary storage does not satisfy durable output',
912
- )
913
- }
914
-
915
- const folder = await toPromise(storage.StorageFolder.GetFolderFromPathAsync(directory)).catch(
916
- (cause: unknown) => {
917
- throw error(
918
- 'destinationUnavailable',
919
- 'startRecording',
920
- 'destinationFileUrl directory is not writable',
921
- cause,
922
- )
923
- },
924
- )
925
-
926
- return toPromise(folder.CreateFileAsync(name, collisionFailIfExists)).catch(
927
- (cause: unknown) => {
928
- throw error(
929
- 'destinationUnavailable',
930
- 'startRecording',
931
- 'destinationFileUrl already exists or cannot be created',
932
- cause,
933
- )
934
- },
935
- )
936
- }
937
-
938
- const freeDiskBytes = async (): Promise<number> => {
939
- try {
940
- const folder = projection().Windows?.Storage?.ApplicationData?.Current?.LocalFolder
941
- const result = await toPromise(
942
- folder.Properties.RetrievePropertiesAsync(['System.FreeSpace']),
943
- )
944
-
945
- const value = result?.['System.FreeSpace'] ?? result?.Lookup?.('System.FreeSpace')
946
- return Number.isFinite(Number(value)) ? Number(value) : Number.MAX_SAFE_INTEGER
947
- } catch {
948
- return Number.MAX_SAFE_INTEGER
949
- }
950
- }
951
-
952
- const removeFileQuietly = async (file: any) => {
953
- if (!file) {
954
- return
955
- }
956
-
957
- try {
958
- await toPromise(file.DeleteAsync())
959
- } catch {
960
- // Temporary leftovers are reclaimed by the OS.
961
- }
962
- }
963
-
964
- const nativeVideoMetadata = async (file: any, audioRequested: boolean) => {
965
- const { Windows } = projection()
966
- const basic = await toPromise(file.GetBasicPropertiesAsync())
967
- const size = Number(basic?.Size ?? 0)
968
- if (!(size > 0)) {
969
- throw error('noMedia', 'finalize', 'The recorder produced an empty movie file')
970
- }
971
-
972
- const video = await toPromise(file.Properties.GetVideoPropertiesAsync())
973
- const width = Number(video?.Width ?? 0)
974
- const height = Number(video?.Height ?? 0)
975
- let durationMs = timeSpanToMs(video?.Duration)
976
- let hasAudio = false
977
- let audioKnown = true
978
- try {
979
- const source = Windows.Media.Core.MediaSource.CreateFromStorageFile(file)
980
- const item = new Windows.Media.Playback.MediaPlaybackItem(source)
981
- const audioTracks = item?.AudioTracks
982
- hasAudio = Number(audioTracks?.Size ?? audioTracks?.Count ?? 0) > 0
983
- if (!Number.isFinite(durationMs) || durationMs <= 0) {
984
- durationMs = timeSpanToMs(source?.Duration)
985
- }
986
- } catch {
987
- // The audio-track probe is mandatory for requested audio — the
988
- // byte-level reader must prove the track instead of guessing.
989
- audioKnown = false
990
- }
991
-
992
- if (audioRequested && !audioKnown) {
993
- throw error(
994
- 'finalizationFailed',
995
- 'finalize',
996
- 'The audio track could not be verified in the finalized movie',
997
- )
998
- }
999
-
1000
- return {
1001
- durationMs,
1002
- width,
1003
- height,
1004
- hasAudio: audioKnown && hasAudio,
1005
- orientation: videoOrientationToOrientation(Number(video?.Orientation)),
1006
- }
1007
- }
1008
-
1009
- const mediabunnyMetadata = async (file: any) => {
1010
- const { Windows } = projection()
1011
- const buffer = await toPromise(Windows.Storage.FileIO.ReadBufferAsync(file))
1012
- const length = Number(buffer?.Length ?? 0)
1013
- if (!(length > 0)) {
1014
- throw error('noMedia', 'finalize', 'The recorder produced an empty movie file')
1015
- }
1016
-
1017
- const reader = Windows.Storage.Streams.DataReader.FromBuffer(buffer)
1018
- const bytes = new Uint8Array(length)
1019
- reader.ReadBytes(bytes)
1020
- const { BufferSource, BlobSource, Input, MP4 } = await import('mediabunny')
1021
- const Source = BufferSource ?? BlobSource
1022
- const input = new Input({ source: new Source(bytes as any), formats: [MP4] })
1023
- try {
1024
- const video = await input.getPrimaryVideoTrack()
1025
- if (!video) {
1026
- throw error('noMedia', 'finalize', 'The movie contains no video track')
1027
- }
1028
-
1029
- const audio = await input.getPrimaryAudioTrack()
1030
- const hasAudio = audio !== null && (await audio.computeDuration()) > 0
1031
- const durationMs = (await input.computeDuration()) * 1000
1032
- const width = await video.getDisplayWidth()
1033
- const height = await video.getDisplayHeight()
1034
- return {
1035
- durationMs,
1036
- width,
1037
- height,
1038
- hasAudio,
1039
- orientation: 'unspecified' as CameraOrientation,
1040
- }
1041
- } finally {
1042
- input.dispose()
1043
- }
1044
- }
1045
-
1046
- const teardown = () => {
1047
- if (!host) {
1048
- void deactivate().then(() => {
1049
- if (!host && !sink) {
1050
- closeCapture()
1051
- }
1052
- })
1053
- }
1054
- }
1055
-
1056
- const finishWithError = (
1057
- stage: 'preparation' | 'capture' | 'finalization' | 'storage',
1058
- cause: CaptureIssue,
1059
- ) => {
1060
- const target = sink
1061
- sink = undefined
1062
- request = undefined
1063
- finalizing = false
1064
- wantStop = false
1065
- recordStartedAt = 0
1066
- if (settleDeadline !== undefined) {
1067
- clearTimeout(settleDeadline)
1068
- }
1069
-
1070
- const file = recordFile
1071
- recordFile = undefined
1072
- void removeFileQuietly(file)
1073
- target?.settled({ kind: 'failed', stage, issue: cause })
1074
- teardown()
1075
- }
1076
-
1077
- // Same 30s settle deadline the web/linux adapters carry — once
1078
- // finalization starts, a hung native call must still settle the take.
1079
- let settleDeadline: ReturnType<typeof setTimeout> | undefined
1080
- const armSettleDeadline = (target: BackendCaptureSink | undefined) => {
1081
- if (settleDeadline !== undefined) {
1082
- clearTimeout(settleDeadline)
1083
- }
1084
-
1085
- if (!target) {
1086
- return
1087
- }
1088
-
1089
- settleDeadline = setTimeout(() => {
1090
- if (sink !== target) {
1091
- return
1092
- }
1093
-
1094
- finishWithError(
1095
- 'finalization',
1096
- error('finalizationFailed', 'finalize', 'Movie finalization timed out'),
1097
- )
1098
- }, 30_000)
1099
- }
1100
-
1101
- const settleClip = async (file: any) => {
1102
- const target = sink
1103
- const take = request
1104
- if (!target || !take) {
1105
- return
1106
- }
1107
-
1108
- if (settleDeadline !== undefined) {
1109
- clearTimeout(settleDeadline)
1110
- }
1111
-
1112
- try {
1113
- let metadata: Awaited<ReturnType<typeof nativeVideoMetadata>>
1114
- try {
1115
- metadata = await nativeVideoMetadata(file, take.audio)
1116
- } catch (nativeCause) {
1117
- if (nativeCause instanceof CameraCaptureError && nativeCause.kind === 'noMedia') {
1118
- throw nativeCause
1119
- }
1120
-
1121
- metadata = await mediabunnyMetadata(file)
1122
- }
1123
-
1124
- if (!(metadata.durationMs > 0) || !(metadata.width > 0) || !(metadata.height > 0)) {
1125
- throw error('noMedia', 'finalize', 'The finalized movie has no usable video media')
1126
- }
1127
-
1128
- if (take.audio && !metadata.hasAudio) {
1129
- throw error(
1130
- 'captureFailed',
1131
- 'finalize',
1132
- 'Requested audio is absent from the finalized movie',
1133
- )
1134
- }
1135
-
1136
- const filePath = String(file?.Path ?? '')
1137
- sink = undefined
1138
- request = undefined
1139
- recordFile = undefined
1140
- finalizing = false
1141
- wantStop = false
1142
- target.settled({
1143
- kind: 'clip',
1144
- output: {
1145
- kind: 'nativeFile',
1146
- resourceId: `file:${filePath}`,
1147
- fileUrl: fileUrlForPath(filePath),
1148
- },
1149
- mimeType: 'video/mp4',
1150
- durationMs: Math.round(metadata.durationMs),
1151
- width: metadata.width,
1152
- height: metadata.height,
1153
- orientation:
1154
- take.orientation && take.orientation !== 'unspecified'
1155
- ? take.orientation
1156
- : metadata.orientation,
1157
- hasAudio: take.audio && metadata.hasAudio,
1158
- })
1159
- } catch (cause) {
1160
- sink = undefined
1161
- request = undefined
1162
- recordFile = undefined
1163
- finalizing = false
1164
- wantStop = false
1165
- void removeFileQuietly(file)
1166
- target.settled({
1167
- kind: 'failed',
1168
- stage: 'finalization',
1169
- issue:
1170
- cause instanceof CameraCaptureError
1171
- ? cause
1172
- : issue(
1173
- 'finalizationFailed',
1174
- 'finalize',
1175
- cause instanceof Error ? cause.message : String(cause),
1176
- { cause },
1177
- ),
1178
- })
1179
- }
1180
-
1181
- recordStartedAt = 0
1182
- teardown()
1183
- }
1184
-
1185
- const stopRecording = async () => {
1186
- const target = capture
1187
- const file = recordFile
1188
- // recordStartedAt stays 0 while StartRecordToStorageFileAsync is in
1189
- // flight — an early stop is honored by `wantStop` once it resolves.
1190
- if (!target || !file || finalizing || recordStartedAt === 0) {
1191
- return
1192
- }
1193
-
1194
- finalizing = true
1195
- armSettleDeadline(sink)
1196
- try {
1197
- await toPromise(target.StopRecordAsync())
1198
- } catch (cause) {
1199
- finishWithError(
1200
- 'finalization',
1201
- error('finalizationFailed', 'finalize', 'The movie could not be finalized', cause),
1202
- )
1203
-
1204
- return
1205
- }
1206
-
1207
- await settleClip(file)
1208
- }
1209
-
1210
- const onSuspend = () => {
1211
- interrupted = true
1212
- markReady(false)
1213
- observer?.interruption('began', 'background')
1214
- }
1215
-
1216
- const onResume = () => {
1217
- interrupted = false
1218
- observer?.interruption('ended', 'background')
1219
- if (capture) {
1220
- observer?.availability(true)
1221
- markReady(!!captureElement)
1222
- }
1223
- }
1224
-
1225
- let lifecycleBound = false
1226
- const bindLifecycle = () => {
1227
- if (lifecycleBound) {
1228
- return
1229
- }
1230
-
1231
- lifecycleBound = true
1232
- try {
1233
- Application.on(Application.suspendEvent, onSuspend)
1234
- Application.on(Application.resumeEvent, onResume)
1235
- } catch {
1236
- // The windows core may not emit suspend/resume — capture
1237
- // still works without lifecycle notifications.
1238
- }
1239
- }
1240
-
1241
- const unbindLifecycle = () => {
1242
- if (!lifecycleBound) {
1243
- return
1244
- }
1245
-
1246
- lifecycleBound = false
1247
- try {
1248
- Application.off(Application.suspendEvent, onSuspend)
1249
- Application.off(Application.resumeEvent, onResume)
1250
- } catch {
1251
- // See bindLifecycle.
1252
- }
1253
- }
1254
-
1255
- return {
1256
- platform: 'windows',
1257
- get supported() {
1258
- return projectionAvailable()
1259
- },
1260
- checkPermission,
1261
- requestPermission: async (kind) => {
1262
- const status = await requestPermission(kind)
1263
- if (kind === 'camera' && status === 'granted' && host && !sink && !released && !capture) {
1264
- try {
1265
- await activate()
1266
- } catch {
1267
- // Activation reports through the preview listener.
1268
- }
1269
- }
1270
-
1271
- return status
1272
- },
1273
- getCapabilities: async () => {
1274
- const devices = await listDevices()
1275
- const cameras: CameraDeviceInfo[] = devices.map((entry) => ({
1276
- id: entry.id,
1277
- label: entry.label,
1278
- facing: entry.facing,
1279
- }))
1280
-
1281
- const supported = projectionAvailable() && cameras.length > 0
1282
- const cameraStatus = await checkPermission('camera')
1283
- const available = supported && cameraStatus === 'granted'
1284
- const measured = capture ? chooseStandardProfile(recordStreamProfiles()) : undefined
1285
- const profile = measured ?? { width: 1280, height: 720, frameRate: 30 }
1286
- return {
1287
- supported,
1288
- reason: !projectionAvailable()
1289
- ? 'The WinUI camera runtime is unavailable'
1290
- : cameras.length === 0
1291
- ? 'No camera device is available on this host'
1292
- : cameraStatus !== 'granted'
1293
- ? 'Camera permission has not been granted'
1294
- : undefined,
1295
- available,
1296
- cameras,
1297
- profiles: [{ profile: 'standard', ...profile }],
1298
- audio: (await listAudioDevices()) > 0,
1299
- // WinUI MediaCapture focus regions are not wired into the
1300
- // adapter — report honestly rather than fabricate.
1301
- focusPointOfInterest: false,
1302
- exposurePointOfInterest: false,
1303
- orientations:
1304
- capture && typeof capture.SetRecordRotationAsync === 'function'
1305
- ? ['portrait', 'portraitUpsideDown', 'landscapeLeft', 'landscapeRight']
1306
- : [],
1307
- durationLimit: 'bestEffort',
1308
- elapsedTime: 'estimated',
1309
- output: {
1310
- mimeType: 'video/mp4',
1311
- container: 'mp4',
1312
- storage: 'appPrivateFile',
1313
- destinationFileUrl: true,
1314
- },
1315
- }
1316
- },
1317
- previewReady: () => previewReadyFlag && !interrupted,
1318
- validateStart: (options) => {
1319
- if (
1320
- options.orientation &&
1321
- options.orientation !== 'unspecified' &&
1322
- (!capture || typeof capture.SetRecordRotationAsync !== 'function')
1323
- ) {
1324
- throw error(
1325
- 'unsupportedConfiguration',
1326
- 'startRecording',
1327
- 'Fixed cardinal orientation has not been qualified on this Windows source',
1328
- )
1329
- }
1330
- },
1331
- attachPreview: (target, callbacks) => {
1332
- if (released || sink) {
1333
- throw error('invalidState', 'attachPreview', 'The camera is disposed or finalizing')
1334
- }
1335
-
1336
- host = target
1337
- listener = callbacks
1338
- const view = target as any
1339
- captureElement = view?.nativeViewProtected ?? view
1340
- bindLifecycle()
1341
- void checkPermission('camera').then((status) => {
1342
- if (released || !host) {
1343
- return
1344
- }
1345
-
1346
- if (status !== 'granted') {
1347
- listener?.onError?.(
1348
- error(
1349
- status === 'restricted' ? 'permissionRestricted' : 'permissionDenied',
1350
- 'preview',
1351
- 'Request camera permission before activating this preview',
1352
- { permission: 'camera' },
1353
- ),
1354
- )
1355
-
1356
- return
1357
- }
1358
-
1359
- void activate()
1360
- })
1361
-
1362
- return () => {
1363
- host = undefined
1364
- listener = undefined
1365
- captureElement = undefined
1366
- void deactivate().then(() => {
1367
- if (!sink) {
1368
- closeCapture()
1369
- }
1370
- })
1371
- }
1372
- },
1373
- configure: (next) => {
1374
- const changed =
1375
- JSON.stringify(next.camera) !== JSON.stringify(currentConfig.camera) ||
1376
- (next.audio ?? false) !== (currentConfig.audio ?? false)
1377
-
1378
- currentConfig = { ...next }
1379
- if (!changed || !capture) {
1380
- return
1381
- }
1382
-
1383
- // A camera or audio-mode change cannot mutate a live MediaCapture —
1384
- // rebuild it and restore the attached preview.
1385
- const hadPreview = !!captureElement
1386
- void deactivate()
1387
- .then(() => {
1388
- closeCapture()
1389
- if (hadPreview && host) {
1390
- return activate()
1391
- }
1392
- })
1393
- .catch(() => {
1394
- observer?.availability(false)
1395
- })
1396
- },
1397
- startCapture: (take, target) => {
1398
- if (!capture || !captureDevice || !previewReadyFlag || interrupted) {
1399
- target.settled({
1400
- kind: 'failed',
1401
- stage: 'preparation',
1402
- issue: issue('unavailable', 'startRecording', 'The camera preview is not running'),
1403
- })
1404
-
1405
- return
1406
- }
1407
-
1408
- sink = target
1409
- request = take
1410
- const active = capture
1411
- const run = async () => {
1412
- if (take.audio) {
1413
- const micStatus = await checkPermission('microphone')
1414
- if (micStatus !== 'granted') {
1415
- throw error(
1416
- micStatus === 'restricted'
1417
- ? 'permissionRestricted'
1418
- : micStatus === 'unavailable'
1419
- ? 'unavailable'
1420
- : 'permissionDenied',
1421
- 'startRecording',
1422
- `Microphone permission is ${micStatus}`,
1423
- { permission: 'microphone' },
1424
- )
1425
- }
1426
-
1427
- if (!captureAudioMode) {
1428
- throw error(
1429
- 'unsupportedConfiguration',
1430
- 'startRecording',
1431
- 'This session was created without audio; configure audio before recording',
1432
- )
1433
- }
1434
- }
1435
-
1436
- if ((await freeDiskBytes()) < minFreeDiskBytes) {
1437
- throw error(
1438
- 'insufficientStorage',
1439
- 'startRecording',
1440
- 'Not enough local storage for a movie recording',
1441
- )
1442
- }
1443
-
1444
- if (take.orientation) {
1445
- const rotation = orientationToRotation(take.orientation)
1446
- if (rotation === undefined || typeof active.SetRecordRotationAsync !== 'function') {
1447
- throw error(
1448
- 'unsupportedConfiguration',
1449
- 'startRecording',
1450
- `Orientation '${take.orientation}' is not supported by this camera`,
1451
- )
1452
- }
1453
-
1454
- try {
1455
- await toPromise(active.SetRecordRotationAsync(rotation))
1456
- } catch (cause) {
1457
- throw error(
1458
- 'unsupportedConfiguration',
1459
- 'startRecording',
1460
- `Orientation '${take.orientation}' was rejected by this camera`,
1461
- cause,
1462
- )
1463
- }
1464
- }
1465
-
1466
- const file = await reserveDestination(take.destinationPath)
1467
- const media = projection().Windows?.Media
1468
- const profile = media?.MediaProperties?.MediaEncodingProfile?.CreateMp4(
1469
- media?.MediaProperties?.VideoEncodingQuality?.Auto ?? 0,
1470
- )
1471
-
1472
- if (!profile) {
1473
- await removeFileQuietly(file)
1474
- throw error(
1475
- 'unsupportedPlatform',
1476
- 'startRecording',
1477
- 'MP4 encoding profiles are unavailable on this host',
1478
- )
1479
- }
1480
-
1481
- const chosen = chooseStandardProfile(recordStreamProfiles())
1482
- try {
1483
- if (chosen && profile.Video) {
1484
- profile.Video.Width = chosen.width
1485
- profile.Video.Height = chosen.height
1486
- if (profile.Video.FrameRate) {
1487
- profile.Video.FrameRate.Numerator = Math.max(1, Math.round(chosen.frameRate * 1000))
1488
- profile.Video.FrameRate.Denominator = 1000
1489
- }
1490
- }
1491
- } catch {
1492
- // The auto profile still describes a real encoding.
1493
- }
1494
-
1495
- if (!take.audio) {
1496
- try {
1497
- profile.Audio = null
1498
- } catch {
1499
- // A projection without property writes still records;
1500
- // silence is verified from the finalized movie.
1501
- }
1502
- }
1503
-
1504
- recordFile = file
1505
- wantStop = false
1506
- try {
1507
- await toPromise(active.StartRecordToStorageFileAsync(profile, file))
1508
- } catch (cause) {
1509
- recordFile = undefined
1510
- await removeFileQuietly(file)
1511
- throw error(
1512
- captureFailureKind(cause),
1513
- 'startRecording',
1514
- 'MediaCapture could not begin recording',
1515
- cause,
1516
- )
1517
- }
1518
-
1519
- recordStartedAt = Date.now()
1520
- const stream = chooseStandardProfile(recordStreamProfiles())
1521
- const configuration: EffectiveCaptureConfig = {
1522
- cameraId: captureDevice!.id,
1523
- facing: captureDevice!.facing,
1524
- audio: take.audio && captureAudioMode,
1525
- width: stream?.width ?? chosen?.width ?? 0,
1526
- height: stream?.height ?? chosen?.height ?? 0,
1527
- frameRate: stream?.frameRate ?? chosen?.frameRate ?? 0,
1528
- orientation: take.orientation ?? 'unspecified',
1529
- mimeType: 'video/mp4',
1530
- container: 'mp4',
1531
- }
1532
-
1533
- target.started(configuration)
1534
- if (wantStop) {
1535
- void stopRecording()
1536
- }
1537
- }
1538
-
1539
- run().catch((cause: unknown) => {
1540
- finishWithError(
1541
- 'preparation',
1542
- cause instanceof CameraCaptureError
1543
- ? cause
1544
- : issue(
1545
- 'captureFailed',
1546
- 'startRecording',
1547
- cause instanceof Error ? cause.message : String(cause),
1548
- { cause },
1549
- ),
1550
- )
1551
- })
1552
- },
1553
- stopCapture: () => {
1554
- wantStop = true
1555
- void stopRecording()
1556
- },
1557
- elapsedMs: () => (recordStartedAt > 0 ? Math.max(0, Date.now() - recordStartedAt) : 0),
1558
- openOutput: async (output) => {
1559
- if (output.kind !== 'nativeFile' || output.synthetic) {
1560
- throw error('invalidArgument', 'openOutput', 'Expected a native Windows movie reference')
1561
- }
1562
-
1563
- const filePath = normalizePath(output.fileUrl.slice('file://'.length))
1564
- const storage = projection().Windows?.Storage
1565
- try {
1566
- await toPromise(storage.StorageFile.GetFileFromPathAsync(filePath))
1567
- } catch (cause) {
1568
- throw error(
1569
- 'unavailable',
1570
- 'openOutput',
1571
- `Movie file is missing at ${output.fileUrl}`,
1572
- cause,
1573
- )
1574
- }
1575
-
1576
- const handle: MovieOutputHandle = {
1577
- url: output.fileUrl,
1578
- fileUrl: output.fileUrl,
1579
- release: () => {},
1580
- }
1581
-
1582
- return handle
1583
- },
1584
- release: async () => {
1585
- released = true
1586
- generation += 1
1587
- unbindLifecycle()
1588
- if (settleDeadline !== undefined) {
1589
- clearTimeout(settleDeadline)
1590
- }
1591
-
1592
- sink = undefined
1593
- request = undefined
1594
- wantStop = false
1595
- finalizing = false
1596
- recordStartedAt = 0
1597
- const file = recordFile
1598
- recordFile = undefined
1599
- void removeFileQuietly(file)
1600
- markReady(false)
1601
- await deactivate()
1602
- stopWatcher()
1603
- closeCapture()
1604
- host = undefined
1605
- captureElement = undefined
1606
- },
1607
- onPreviewDetached: () => {
1608
- // Finalization still owns the device while a settle is in
1609
- // flight; the detach path already released it otherwise.
1610
- },
1611
- setObserver: (next) => {
1612
- observer = next
1613
- },
1614
- }
332
+ let currentConfig = { ...config }
333
+ let observer: BackendObserver | undefined
334
+ let host: any
335
+ let listener: BackendPreviewListener | undefined
336
+ let capture: any
337
+ let captureElement: any
338
+ let captureDevice: WindowsCameraDevice | undefined
339
+ let captureAudioMode = false
340
+ let previewReadyFlag = false
341
+ let interrupted = false
342
+ let released = false
343
+ let generation = 0
344
+ let watcher: any
345
+ let watcherDelegates: { event: string; delegate: any }[] = []
346
+ let captureDelegates: { event: string; delegate: any }[] = []
347
+ let sink: BackendCaptureSink | undefined
348
+ let request: BackendCaptureRequest | undefined
349
+ let recordFile: any
350
+ let recordStartedAt = 0
351
+ let wantStop = false
352
+ let finalizing = false
353
+ const lease = {}
354
+
355
+ const projectionAvailable = () => {
356
+ const { Windows, Microsoft } = projection()
357
+
358
+ return !!(
359
+ Windows?.Media?.Capture?.MediaCapture &&
360
+ Windows?.Media?.Capture?.MediaCaptureInitializationSettings &&
361
+ Windows?.Devices?.Enumeration?.DeviceInformation &&
362
+ Windows?.Storage?.ApplicationData &&
363
+ Microsoft?.UI?.Xaml?.Controls?.CaptureElement
364
+ )
365
+ }
366
+
367
+ const markReady = (value: boolean) => {
368
+ if (previewReadyFlag === value) {
369
+ return
370
+ }
371
+
372
+ previewReadyFlag = value
373
+ observer?.previewReady(value)
374
+ }
375
+
376
+ const appCapability = (kind: CameraPermissionKind): any => {
377
+ try {
378
+ return projection().Windows?.Security?.Authorization?.AppCapabilityAccess?.AppCapability?.Create(
379
+ capabilityNameFor(kind),
380
+ )
381
+ } catch {
382
+ return undefined
383
+ }
384
+ }
385
+
386
+ const deviceAccessInfo = (kind: CameraPermissionKind): any => {
387
+ try {
388
+ const enumeration = projection().Windows?.Devices?.Enumeration
389
+ const deviceClass =
390
+ kind === 'camera'
391
+ ? enumeration?.DeviceClass?.VideoCapture
392
+ : enumeration?.DeviceClass?.AudioCapture
393
+
394
+ return deviceClass === undefined
395
+ ? undefined
396
+ : enumeration?.DeviceAccessInformation?.CreateFromDeviceClass(deviceClass)
397
+ } catch {
398
+ return undefined
399
+ }
400
+ }
401
+
402
+ const checkPermission = async (kind: CameraPermissionKind): Promise<CameraPermissionStatus> => {
403
+ const capability = appCapability(kind)
404
+
405
+ if (capability) {
406
+ try {
407
+ const mapped = accessStatusToPermission(capability.CheckAccess())
408
+
409
+ // A missing manifest declaration is a setup error, not a
410
+ // status — expose it as unknown here and as
411
+ // `configurationMissing` on request.
412
+ return mapped === 'notDeclared' ? 'unknown' : mapped
413
+ } catch {
414
+ // Fall through to the enumeration-based probe.
415
+ }
416
+ }
417
+
418
+ const info = deviceAccessInfo(kind)
419
+
420
+ if (info) {
421
+ try {
422
+ return deviceAccessStatusToPermission(info.CurrentStatus)
423
+ } catch {
424
+ return 'unknown'
425
+ }
426
+ }
427
+
428
+ return 'unknown'
429
+ }
430
+
431
+ let permissionChain: Promise<unknown> = Promise.resolve()
432
+ const requestPermission = (kind: CameraPermissionKind): Promise<CameraPermissionStatus> => {
433
+ const result = permissionChain.then(async () => {
434
+ const status = await checkPermission(kind)
435
+
436
+ if (status !== 'notDetermined') {
437
+ if (status === 'unknown') {
438
+ try {
439
+ if (accessStatusToPermission(appCapability(kind)?.CheckAccess()) === 'notDeclared') {
440
+ throw error(
441
+ 'configurationMissing',
442
+ 'requestPermission',
443
+ `Missing '${capabilityNameFor(kind)}' device capability in the host app's Package.appxmanifest`,
444
+ { permission: kind },
445
+ )
446
+ }
447
+ } catch (cause) {
448
+ if (cause instanceof CameraCaptureError) {
449
+ throw cause
450
+ }
451
+ }
452
+ }
453
+
454
+ return status
455
+ }
456
+
457
+ const capability = appCapability(kind)
458
+
459
+ if (!capability?.RequestAccessAsync) {
460
+ return 'unknown'
461
+ }
462
+
463
+ try {
464
+ const next = accessStatusToPermission(await toPromise(capability.RequestAccessAsync()))
465
+
466
+ return next === 'notDeclared' ? 'unknown' : next
467
+ } catch (cause) {
468
+ throw error(
469
+ 'unavailable',
470
+ 'requestPermission',
471
+ `The system ${kind} permission request could not run`,
472
+ cause,
473
+ )
474
+ }
475
+ })
476
+
477
+ permissionChain = result.catch(() => {})
478
+ return result
479
+ }
480
+
481
+ const listDevices = async (): Promise<WindowsCameraDevice[]> => {
482
+ const enumeration = projection().Windows?.Devices?.Enumeration
483
+ const deviceClass = enumeration?.DeviceClass?.VideoCapture
484
+
485
+ if (!enumeration?.DeviceInformation?.FindAllAsync || deviceClass === undefined) {
486
+ return []
487
+ }
488
+
489
+ const found = await toPromise(enumeration.DeviceInformation.FindAllAsync(deviceClass))
490
+
491
+ return vectorToArray(found).map((device: any) => ({
492
+ id: String(device?.Id ?? device?.id ?? ''),
493
+ label: String(device?.Name ?? device?.name ?? device?.Id ?? ''),
494
+ facing: panelToFacing(
495
+ Number(device?.EnclosureLocation?.Panel ?? device?.EnclosureLocation?.panel),
496
+ ),
497
+ }))
498
+ }
499
+
500
+ const listAudioDevices = async (): Promise<number> => {
501
+ try {
502
+ const enumeration = projection().Windows?.Devices?.Enumeration
503
+ const deviceClass = enumeration?.DeviceClass?.AudioCapture
504
+
505
+ if (!enumeration?.DeviceInformation?.FindAllAsync || deviceClass === undefined) {
506
+ return 0
507
+ }
508
+
509
+ const found = await toPromise(enumeration.DeviceInformation.FindAllAsync(deviceClass))
510
+
511
+ return Number(found?.Size ?? found?.Count ?? 0)
512
+ } catch {
513
+ return 0
514
+ }
515
+ }
516
+
517
+ const defaultDeviceId = (): string | undefined => {
518
+ try {
519
+ const devices = projection().Windows?.Media?.Devices
520
+ const kind = devices?.AudioVideoCaptureDeviceKind?.Video
521
+ const id = devices?.MediaDevice?.GetDefaultVideoCaptureId?.(kind)
522
+
523
+ return typeof id === 'string' && id ? id : undefined
524
+ } catch {
525
+ return undefined
526
+ }
527
+ }
528
+
529
+ const streamProfiles = (target: any, streamKind: any): WindowsStreamProfile[] => {
530
+ const controller = target?.VideoDeviceController
531
+
532
+ if (!controller?.GetAvailableMediaStreamProperties || streamKind === undefined) {
533
+ return []
534
+ }
535
+
536
+ try {
537
+ return vectorToArray(controller.GetAvailableMediaStreamProperties(streamKind))
538
+ .map((entry: any) => ({
539
+ width: Number(entry?.Width ?? 0),
540
+ height: Number(entry?.Height ?? 0),
541
+ frameRate:
542
+ Number(entry?.FrameRate?.Numerator ?? 0) /
543
+ Math.max(1, Number(entry?.FrameRate?.Denominator ?? 1)),
544
+ subtype: typeof entry?.Subtype === 'string' ? entry.Subtype : undefined,
545
+ }))
546
+ .filter((entry: WindowsStreamProfile) => entry.width > 0 && entry.height > 0)
547
+ } catch {
548
+ return []
549
+ }
550
+ }
551
+
552
+ const recordStreamProfiles = (): WindowsStreamProfile[] =>
553
+ streamProfiles(capture, projection().Windows?.Media?.Capture?.MediaStreamType?.VideoRecord)
554
+
555
+ const detachCaptureDelegates = () => {
556
+ for (const entry of captureDelegates) {
557
+ try {
558
+ capture[entry.event] = null
559
+ } catch {
560
+ // The projection may not accept null — dropping the
561
+ // references still detaches our handlers.
562
+ }
563
+ }
564
+
565
+ captureDelegates = []
566
+ }
567
+
568
+ const onCaptureFailed = (_sender: any, args: any) => {
569
+ const message = String(args?.Message ?? args?.message ?? 'Camera capture failed')
570
+
571
+ markReady(false)
572
+ observer?.availability(false)
573
+ observer?.interruption(
574
+ 'began',
575
+ /in use|denied|access/i.test(message) ? 'cameraInUse' : 'unknown',
576
+ )
577
+
578
+ if (sink) {
579
+ // The pipeline died under a live take — try to finalize the
580
+ // partial media instead of discarding it outright. wantStop
581
+ // makes the early stop stick while
582
+ // StartRecordToStorageFileAsync is still in flight, and the
583
+ // deadline settles the take if that call never resolves.
584
+ wantStop = true
585
+ armSettleDeadline(sink)
586
+ sink.finishing(/device|available|found/i.test(message) ? 'cameraUnavailable' : 'captureError')
587
+ void stopRecording()
588
+ }
589
+ }
590
+
591
+ const onRecordLimitationExceeded = () => {
592
+ // The OS-level recording limitation ended the take — finalize the
593
+ // usable media and keep first-cause semantics from the core.
594
+ wantStop = true
595
+ armSettleDeadline(sink)
596
+ sink?.finishing('interrupted')
597
+ void stopRecording()
598
+ }
599
+
600
+ const attachCaptureDelegates = (target: any) => {
601
+ const { NSWinRT } = projection()
602
+ const subscribe = (event: string, type: string, handler: (...args: any[]) => void) => {
603
+ try {
604
+ const delegate = NSWinRT?.asDelegate ? NSWinRT.asDelegate(type, handler) : handler
605
+
606
+ target[event] = delegate
607
+ captureDelegates.push({ event, delegate })
608
+ } catch {
609
+ try {
610
+ target[event] = handler
611
+ captureDelegates.push({ event, delegate: handler })
612
+ } catch {
613
+ // The event is unsubscribable on this projection — the
614
+ // adapter still functions without that notification.
615
+ }
616
+ }
617
+ }
618
+
619
+ subscribe(
620
+ 'Failed',
621
+ 'Windows.Foundation.TypedEventHandler`2<Windows.Media.Capture.MediaCapture,Windows.Media.Capture.MediaCaptureFailedEventArgs>',
622
+ onCaptureFailed,
623
+ )
624
+
625
+ subscribe(
626
+ 'RecordLimitationExceeded',
627
+ 'Windows.Media.Capture.RecordLimitationExceededEventHandler',
628
+ onRecordLimitationExceeded,
629
+ )
630
+ }
631
+
632
+ const stopWatcher = () => {
633
+ if (!watcher) {
634
+ return
635
+ }
636
+
637
+ for (const entry of watcherDelegates) {
638
+ try {
639
+ watcher[entry.event] = null
640
+ } catch {
641
+ // See detachCaptureDelegates.
642
+ }
643
+ }
644
+
645
+ watcherDelegates = []
646
+ try {
647
+ watcher.Stop()
648
+ } catch {
649
+ // A stopped or failed watcher still releases cleanly.
650
+ }
651
+
652
+ watcher = undefined
653
+ }
654
+
655
+ const ensureWatcher = () => {
656
+ if (watcher) {
657
+ return
658
+ }
659
+
660
+ const enumeration = projection().Windows?.Devices?.Enumeration
661
+ const deviceClass = enumeration?.DeviceClass?.VideoCapture
662
+
663
+ if (!enumeration?.DeviceInformation?.CreateWatcher || deviceClass === undefined) {
664
+ return
665
+ }
666
+
667
+ try {
668
+ const target = enumeration.DeviceInformation.CreateWatcher(deviceClass)
669
+ const { NSWinRT } = projection()
670
+ const subscribe = (event: string, type: string, handler: (...args: any[]) => void) => {
671
+ const delegate = NSWinRT?.asDelegate ? NSWinRT.asDelegate(type, handler) : handler
672
+
673
+ target[event] = delegate
674
+ watcherDelegates.push({ event, delegate })
675
+ }
676
+
677
+ subscribe(
678
+ 'Removed',
679
+ 'Windows.Foundation.TypedEventHandler`2<Windows.Devices.Enumeration.DeviceWatcher,Windows.Devices.Enumeration.DeviceInformationUpdate>',
680
+ (_sender: any, update: any) => {
681
+ const id = String(update?.Id ?? update?.id ?? '')
682
+
683
+ if (!id || id === captureDevice?.id) {
684
+ observer?.availability(false)
685
+ }
686
+ },
687
+ )
688
+
689
+ subscribe(
690
+ 'Added',
691
+ 'Windows.Foundation.TypedEventHandler`2<Windows.Devices.Enumeration.DeviceWatcher,Windows.Devices.Enumeration.DeviceInformation>',
692
+ () => observer?.availability(true),
693
+ )
694
+
695
+ target.Start()
696
+ watcher = target
697
+ } catch {
698
+ watcher = undefined
699
+ watcherDelegates = []
700
+ }
701
+ }
702
+
703
+ const applyStreamProperties = async (target: any) => {
704
+ const streamType = projection().Windows?.Media?.Capture?.MediaStreamType
705
+ const controller = target?.VideoDeviceController
706
+ const candidates = streamProfiles(target, streamType?.VideoRecord)
707
+ const chosen = chooseStandardProfile(candidates)
708
+
709
+ if (!controller?.SetMediaStreamPropertiesAsync || !chosen || !streamType) {
710
+ return
711
+ }
712
+
713
+ const props = candidates.length
714
+ ? vectorToArray(controller.GetAvailableMediaStreamProperties(streamType.VideoRecord)).find(
715
+ (entry: any) =>
716
+ Number(entry?.Width) === chosen.width && Number(entry?.Height) === chosen.height,
717
+ )
718
+ : undefined
719
+
720
+ if (!props) {
721
+ return
722
+ }
723
+
724
+ try {
725
+ await toPromise(controller.SetMediaStreamPropertiesAsync(streamType.VideoRecord, props))
726
+ try {
727
+ await toPromise(controller.SetMediaStreamPropertiesAsync(streamType.VideoPreview, props))
728
+ } catch {
729
+ // A preview format mismatch must not block recording.
730
+ }
731
+ } catch {
732
+ // The driver rejected the format request — the device default
733
+ // still records and capabilities disclose what was measured.
734
+ }
735
+ }
736
+
737
+ const releaseClaim = () => {
738
+ if (captureDevice && claimedDevices.get(captureDevice.id) === lease) {
739
+ claimedDevices.delete(captureDevice.id)
740
+ }
741
+ }
742
+
743
+ const closeCapture = () => {
744
+ detachCaptureDelegates()
745
+ releaseClaim()
746
+
747
+ const target = capture
748
+
749
+ capture = undefined
750
+ captureDevice = undefined
751
+ captureAudioMode = false
752
+ if (!target) {
753
+ return
754
+ }
755
+
756
+ try {
757
+ target.Close()
758
+ } catch {
759
+ try {
760
+ target.Dispose()
761
+ } catch {
762
+ // GC reclaims the device handle.
763
+ }
764
+ }
765
+ }
766
+
767
+ const ensureCapture = async (): Promise<any> => {
768
+ const epoch = generation
769
+
770
+ if (capture) {
771
+ return capture
772
+ }
773
+
774
+ const { Windows } = projection()
775
+ const devices = await listDevices()
776
+ const selected = selectCameraDevice(currentConfig.camera, devices, defaultDeviceId())
777
+
778
+ if (!selected) {
779
+ throw error('unavailable', 'startPreview', 'No camera device is available')
780
+ }
781
+
782
+ const owner = claimedDevices.get(selected.id)
783
+
784
+ if (owner && owner !== lease) {
785
+ throw error('busy', 'startPreview', 'Another camera session still owns this device')
786
+ }
787
+
788
+ const settings = new Windows.Media.Capture.MediaCaptureInitializationSettings()
789
+
790
+ settings.VideoDeviceId = selected.id
791
+ settings.StreamingCaptureMode =
792
+ currentConfig.audio === true ? captureModeAudioAndVideo : captureModeVideo
793
+
794
+ const target = new Windows.Media.Capture.MediaCapture()
795
+
796
+ try {
797
+ await toPromise(target.InitializeAsync(settings))
798
+ } catch (cause) {
799
+ try {
800
+ target.Close()
801
+ } catch {
802
+ // See closeCapture.
803
+ }
804
+
805
+ throw error(
806
+ captureFailureKind(cause),
807
+ 'startPreview',
808
+ 'The camera could not be initialized',
809
+ cause,
810
+ )
811
+ }
812
+
813
+ if (epoch !== generation || released) {
814
+ try {
815
+ target.Close()
816
+ } catch {
817
+ // See closeCapture.
818
+ }
819
+
820
+ throw error('unavailable', 'startPreview', 'The camera session was released')
821
+ }
822
+
823
+ capture = target
824
+ captureDevice = selected
825
+ captureAudioMode = currentConfig.audio === true
826
+ claimedDevices.set(selected.id, lease)
827
+ attachCaptureDelegates(target)
828
+ ensureWatcher()
829
+ await applyStreamProperties(target)
830
+ try {
831
+ if (selected.facing === 'front' && typeof target.SetPreviewMirroring === 'function') {
832
+ target.SetPreviewMirroring(true)
833
+ }
834
+ } catch {
835
+ // Mirrored preview is cosmetic; recorded output stays unmirrored.
836
+ }
837
+
838
+ return target
839
+ }
840
+
841
+ const activate = async (): Promise<void> => {
842
+ const epoch = ++generation
843
+
844
+ try {
845
+ const target = await ensureCapture()
846
+
847
+ if (!captureElement || epoch !== generation) {
848
+ return
849
+ }
850
+
851
+ try {
852
+ captureElement.Source = target
853
+ } catch (cause) {
854
+ throw error('unavailable', 'startPreview', 'The preview element rejected the source', cause)
855
+ }
856
+
857
+ await toPromise(target.StartPreviewAsync())
858
+ if (epoch !== generation) {
859
+ return
860
+ }
861
+
862
+ markReady(true)
863
+ listener?.onReady?.()
864
+ } catch (cause) {
865
+ if (epoch === generation) {
866
+ markReady(false)
867
+ listener?.onError?.(
868
+ cause instanceof CameraCaptureError
869
+ ? cause
870
+ : error('unavailable', 'startPreview', 'Camera preview could not start', cause),
871
+ )
872
+ }
873
+ }
874
+ }
875
+
876
+ const deactivate = async () => {
877
+ generation += 1
878
+ markReady(false)
879
+
880
+ const target = capture
881
+
882
+ if (captureElement) {
883
+ try {
884
+ captureElement.Source = null
885
+ } catch {
886
+ // Detach is best-effort — the element may already be gone.
887
+ }
888
+ }
889
+
890
+ if (target && !sink) {
891
+ try {
892
+ await toPromise(target.StopPreviewAsync())
893
+ } catch {
894
+ // The pipeline may already be down.
895
+ }
896
+ }
897
+ }
898
+
899
+ const recordingsFolder = async (): Promise<any> => {
900
+ const storage = projection().Windows?.Storage
901
+ const folder = storage?.ApplicationData?.Current?.LocalFolder
902
+
903
+ if (!folder?.CreateFolderAsync) {
904
+ throw error('destinationUnavailable', 'startRecording', 'App-private storage is unavailable')
905
+ }
906
+
907
+ return toPromise(folder.CreateFolderAsync('octane-camera', collisionOpenIfExists))
908
+ }
909
+
910
+ const reserveDestination = async (destinationPath: string | undefined): Promise<any> => {
911
+ const storage = projection().Windows?.Storage
912
+
913
+ if (!destinationPath) {
914
+ const folder = await recordingsFolder()
915
+ const name = `clip-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.mp4`
916
+
917
+ return toPromise(folder.CreateFileAsync(name, collisionGenerateUniqueName))
918
+ }
919
+
920
+ // Durable output stays app-private like every other leaf — resolve
921
+ // against LocalFolder, canonicalizing first so '..' cannot escape it.
922
+ const filePath = canonicalizePath(normalizePath(destinationPath), '\\')
923
+ const localRoot = normalizePath(
924
+ String(storage?.ApplicationData?.Current?.LocalFolder?.Path ?? ''),
925
+ )
926
+
927
+ if (!localRoot || !filePath.toLowerCase().startsWith(`${localRoot.toLowerCase()}\\`)) {
928
+ throw error(
929
+ 'destinationUnavailable',
930
+ 'startRecording',
931
+ 'destinationFileUrl must resolve inside app-private storage',
932
+ )
933
+ }
934
+
935
+ const directory = filePath.slice(0, filePath.lastIndexOf('\\'))
936
+ const name = filePath.slice(filePath.lastIndexOf('\\') + 1)
937
+
938
+ if (!directory || !name) {
939
+ throw error(
940
+ 'destinationUnavailable',
941
+ 'startRecording',
942
+ 'destinationFileUrl is not a file path',
943
+ )
944
+ }
945
+
946
+ const tempPath = String(storage?.ApplicationData?.Current?.TemporaryFolder?.Path ?? '')
947
+
948
+ if (tempPath && filePath.toLowerCase().startsWith(tempPath.toLowerCase())) {
949
+ throw error(
950
+ 'destinationUnavailable',
951
+ 'startRecording',
952
+ 'Temporary storage does not satisfy durable output',
953
+ )
954
+ }
955
+
956
+ const folder = await toPromise(storage.StorageFolder.GetFolderFromPathAsync(directory)).catch(
957
+ (cause: unknown) => {
958
+ throw error(
959
+ 'destinationUnavailable',
960
+ 'startRecording',
961
+ 'destinationFileUrl directory is not writable',
962
+ cause,
963
+ )
964
+ },
965
+ )
966
+
967
+ return toPromise(folder.CreateFileAsync(name, collisionFailIfExists)).catch(
968
+ (cause: unknown) => {
969
+ throw error(
970
+ 'destinationUnavailable',
971
+ 'startRecording',
972
+ 'destinationFileUrl already exists or cannot be created',
973
+ cause,
974
+ )
975
+ },
976
+ )
977
+ }
978
+
979
+ const freeDiskBytes = async (): Promise<number> => {
980
+ try {
981
+ const folder = projection().Windows?.Storage?.ApplicationData?.Current?.LocalFolder
982
+ const result = await toPromise(
983
+ folder.Properties.RetrievePropertiesAsync(['System.FreeSpace']),
984
+ )
985
+
986
+ const value = result?.['System.FreeSpace'] ?? result?.Lookup?.('System.FreeSpace')
987
+
988
+ return Number.isFinite(Number(value)) ? Number(value) : Number.MAX_SAFE_INTEGER
989
+ } catch {
990
+ return Number.MAX_SAFE_INTEGER
991
+ }
992
+ }
993
+
994
+ const removeFileQuietly = async (file: any) => {
995
+ if (!file) {
996
+ return
997
+ }
998
+
999
+ try {
1000
+ await toPromise(file.DeleteAsync())
1001
+ } catch {
1002
+ // Temporary leftovers are reclaimed by the OS.
1003
+ }
1004
+ }
1005
+
1006
+ const nativeVideoMetadata = async (file: any, audioRequested: boolean) => {
1007
+ const { Windows } = projection()
1008
+ const basic = await toPromise(file.GetBasicPropertiesAsync())
1009
+ const size = Number(basic?.Size ?? 0)
1010
+
1011
+ if (!(size > 0)) {
1012
+ throw error('noMedia', 'finalize', 'The recorder produced an empty movie file')
1013
+ }
1014
+
1015
+ const video = await toPromise(file.Properties.GetVideoPropertiesAsync())
1016
+ const width = Number(video?.Width ?? 0)
1017
+ const height = Number(video?.Height ?? 0)
1018
+ let durationMs = timeSpanToMs(video?.Duration)
1019
+ let hasAudio = false
1020
+ let audioKnown = true
1021
+
1022
+ try {
1023
+ const source = Windows.Media.Core.MediaSource.CreateFromStorageFile(file)
1024
+ const item = new Windows.Media.Playback.MediaPlaybackItem(source)
1025
+ const audioTracks = item?.AudioTracks
1026
+
1027
+ hasAudio = Number(audioTracks?.Size ?? audioTracks?.Count ?? 0) > 0
1028
+ if (!Number.isFinite(durationMs) || durationMs <= 0) {
1029
+ durationMs = timeSpanToMs(source?.Duration)
1030
+ }
1031
+ } catch {
1032
+ // The audio-track probe is mandatory for requested audio — the
1033
+ // byte-level reader must prove the track instead of guessing.
1034
+ audioKnown = false
1035
+ }
1036
+
1037
+ if (audioRequested && !audioKnown) {
1038
+ throw error(
1039
+ 'finalizationFailed',
1040
+ 'finalize',
1041
+ 'The audio track could not be verified in the finalized movie',
1042
+ )
1043
+ }
1044
+
1045
+ return {
1046
+ durationMs,
1047
+ width,
1048
+ height,
1049
+ hasAudio: audioKnown && hasAudio,
1050
+ orientation: videoOrientationToOrientation(Number(video?.Orientation)),
1051
+ }
1052
+ }
1053
+
1054
+ const mediabunnyMetadata = async (file: any) => {
1055
+ const { Windows } = projection()
1056
+ const buffer = await toPromise(Windows.Storage.FileIO.ReadBufferAsync(file))
1057
+ const length = Number(buffer?.Length ?? 0)
1058
+
1059
+ if (!(length > 0)) {
1060
+ throw error('noMedia', 'finalize', 'The recorder produced an empty movie file')
1061
+ }
1062
+
1063
+ const reader = Windows.Storage.Streams.DataReader.FromBuffer(buffer)
1064
+ const bytes = new Uint8Array(length)
1065
+
1066
+ reader.ReadBytes(bytes)
1067
+
1068
+ const { BufferSource, BlobSource, Input, MP4 } = await import('mediabunny')
1069
+ const Source = BufferSource ?? BlobSource
1070
+ const input = new Input({ source: new Source(bytes as any), formats: [MP4] })
1071
+
1072
+ try {
1073
+ const video = await input.getPrimaryVideoTrack()
1074
+
1075
+ if (!video) {
1076
+ throw error('noMedia', 'finalize', 'The movie contains no video track')
1077
+ }
1078
+
1079
+ const audio = await input.getPrimaryAudioTrack()
1080
+ const hasAudio = audio !== null && (await audio.computeDuration()) > 0
1081
+ const durationMs = (await input.computeDuration()) * 1000
1082
+ const width = await video.getDisplayWidth()
1083
+ const height = await video.getDisplayHeight()
1084
+
1085
+ return {
1086
+ durationMs,
1087
+ width,
1088
+ height,
1089
+ hasAudio,
1090
+ orientation: 'unspecified' as CameraOrientation,
1091
+ }
1092
+ } finally {
1093
+ input.dispose()
1094
+ }
1095
+ }
1096
+
1097
+ const teardown = () => {
1098
+ if (!host) {
1099
+ void deactivate().then(() => {
1100
+ if (!host && !sink) {
1101
+ closeCapture()
1102
+ }
1103
+ })
1104
+ }
1105
+ }
1106
+
1107
+ const finishWithError = (
1108
+ stage: 'preparation' | 'capture' | 'finalization' | 'storage',
1109
+ cause: CaptureIssue,
1110
+ ) => {
1111
+ const target = sink
1112
+
1113
+ sink = undefined
1114
+ request = undefined
1115
+ finalizing = false
1116
+ wantStop = false
1117
+ recordStartedAt = 0
1118
+ if (settleDeadline !== undefined) {
1119
+ clearTimeout(settleDeadline)
1120
+ }
1121
+
1122
+ const file = recordFile
1123
+
1124
+ recordFile = undefined
1125
+ void removeFileQuietly(file)
1126
+ target?.settled({ kind: 'failed', stage, issue: cause })
1127
+ teardown()
1128
+ }
1129
+
1130
+ // Same 30s settle deadline the web/linux adapters carry — once
1131
+ // finalization starts, a hung native call must still settle the take.
1132
+ let settleDeadline: ReturnType<typeof setTimeout> | undefined
1133
+ const armSettleDeadline = (target: BackendCaptureSink | undefined) => {
1134
+ if (settleDeadline !== undefined) {
1135
+ clearTimeout(settleDeadline)
1136
+ }
1137
+
1138
+ if (!target) {
1139
+ return
1140
+ }
1141
+
1142
+ settleDeadline = setTimeout(() => {
1143
+ if (sink !== target) {
1144
+ return
1145
+ }
1146
+
1147
+ finishWithError(
1148
+ 'finalization',
1149
+ error('finalizationFailed', 'finalize', 'Movie finalization timed out'),
1150
+ )
1151
+ }, 30_000)
1152
+ }
1153
+
1154
+ const settleClip = async (file: any) => {
1155
+ const target = sink
1156
+ const take = request
1157
+
1158
+ if (!target || !take) {
1159
+ return
1160
+ }
1161
+
1162
+ if (settleDeadline !== undefined) {
1163
+ clearTimeout(settleDeadline)
1164
+ }
1165
+
1166
+ try {
1167
+ let metadata: Awaited<ReturnType<typeof nativeVideoMetadata>>
1168
+
1169
+ try {
1170
+ metadata = await nativeVideoMetadata(file, take.audio)
1171
+ } catch (nativeCause) {
1172
+ if (nativeCause instanceof CameraCaptureError && nativeCause.kind === 'noMedia') {
1173
+ throw nativeCause
1174
+ }
1175
+
1176
+ metadata = await mediabunnyMetadata(file)
1177
+ }
1178
+
1179
+ if (!(metadata.durationMs > 0) || !(metadata.width > 0) || !(metadata.height > 0)) {
1180
+ throw error('noMedia', 'finalize', 'The finalized movie has no usable video media')
1181
+ }
1182
+
1183
+ if (take.audio && !metadata.hasAudio) {
1184
+ throw error(
1185
+ 'captureFailed',
1186
+ 'finalize',
1187
+ 'Requested audio is absent from the finalized movie',
1188
+ )
1189
+ }
1190
+
1191
+ const filePath = String(file?.Path ?? '')
1192
+
1193
+ sink = undefined
1194
+ request = undefined
1195
+ recordFile = undefined
1196
+ finalizing = false
1197
+ wantStop = false
1198
+ target.settled({
1199
+ kind: 'clip',
1200
+ output: {
1201
+ kind: 'nativeFile',
1202
+ resourceId: `file:${filePath}`,
1203
+ fileUrl: fileUrlForPath(filePath),
1204
+ },
1205
+ mimeType: 'video/mp4',
1206
+ durationMs: Math.round(metadata.durationMs),
1207
+ width: metadata.width,
1208
+ height: metadata.height,
1209
+ orientation:
1210
+ take.orientation && take.orientation !== 'unspecified'
1211
+ ? take.orientation
1212
+ : metadata.orientation,
1213
+ hasAudio: take.audio && metadata.hasAudio,
1214
+ })
1215
+ } catch (cause) {
1216
+ sink = undefined
1217
+ request = undefined
1218
+ recordFile = undefined
1219
+ finalizing = false
1220
+ wantStop = false
1221
+ void removeFileQuietly(file)
1222
+ target.settled({
1223
+ kind: 'failed',
1224
+ stage: 'finalization',
1225
+ issue:
1226
+ cause instanceof CameraCaptureError
1227
+ ? cause
1228
+ : issue(
1229
+ 'finalizationFailed',
1230
+ 'finalize',
1231
+ cause instanceof Error ? cause.message : String(cause),
1232
+ { cause },
1233
+ ),
1234
+ })
1235
+ }
1236
+
1237
+ recordStartedAt = 0
1238
+ teardown()
1239
+ }
1240
+
1241
+ const stopRecording = async () => {
1242
+ const target = capture
1243
+ const file = recordFile
1244
+
1245
+ // recordStartedAt stays 0 while StartRecordToStorageFileAsync is in
1246
+ // flight — an early stop is honored by `wantStop` once it resolves.
1247
+ if (!target || !file || finalizing || recordStartedAt === 0) {
1248
+ return
1249
+ }
1250
+
1251
+ finalizing = true
1252
+ armSettleDeadline(sink)
1253
+ try {
1254
+ await toPromise(target.StopRecordAsync())
1255
+ } catch (cause) {
1256
+ finishWithError(
1257
+ 'finalization',
1258
+ error('finalizationFailed', 'finalize', 'The movie could not be finalized', cause),
1259
+ )
1260
+
1261
+ return
1262
+ }
1263
+
1264
+ await settleClip(file)
1265
+ }
1266
+
1267
+ const onSuspend = () => {
1268
+ interrupted = true
1269
+ markReady(false)
1270
+ observer?.interruption('began', 'background')
1271
+ }
1272
+
1273
+ const onResume = () => {
1274
+ interrupted = false
1275
+ observer?.interruption('ended', 'background')
1276
+ if (capture) {
1277
+ observer?.availability(true)
1278
+ markReady(!!captureElement)
1279
+ }
1280
+ }
1281
+
1282
+ let lifecycleBound = false
1283
+ const bindLifecycle = () => {
1284
+ if (lifecycleBound) {
1285
+ return
1286
+ }
1287
+
1288
+ lifecycleBound = true
1289
+ try {
1290
+ Application.on(Application.suspendEvent, onSuspend)
1291
+ Application.on(Application.resumeEvent, onResume)
1292
+ } catch {
1293
+ // The windows core may not emit suspend/resume — capture
1294
+ // still works without lifecycle notifications.
1295
+ }
1296
+ }
1297
+
1298
+ const unbindLifecycle = () => {
1299
+ if (!lifecycleBound) {
1300
+ return
1301
+ }
1302
+
1303
+ lifecycleBound = false
1304
+ try {
1305
+ Application.off(Application.suspendEvent, onSuspend)
1306
+ Application.off(Application.resumeEvent, onResume)
1307
+ } catch {
1308
+ // See bindLifecycle.
1309
+ }
1310
+ }
1311
+
1312
+ return {
1313
+ platform: 'windows',
1314
+ get supported() {
1315
+ return projectionAvailable()
1316
+ },
1317
+ checkPermission,
1318
+ requestPermission: async (kind) => {
1319
+ const status = await requestPermission(kind)
1320
+
1321
+ if (kind === 'camera' && status === 'granted' && host && !sink && !released && !capture) {
1322
+ try {
1323
+ await activate()
1324
+ } catch {
1325
+ // Activation reports through the preview listener.
1326
+ }
1327
+ }
1328
+
1329
+ return status
1330
+ },
1331
+ getCapabilities: async () => {
1332
+ const devices = await listDevices()
1333
+ const cameras: CameraDeviceInfo[] = devices.map((entry) => ({
1334
+ id: entry.id,
1335
+ label: entry.label,
1336
+ facing: entry.facing,
1337
+ }))
1338
+
1339
+ const supported = projectionAvailable() && cameras.length > 0
1340
+ const cameraStatus = await checkPermission('camera')
1341
+ const available = supported && cameraStatus === 'granted'
1342
+ const measured = capture ? chooseStandardProfile(recordStreamProfiles()) : undefined
1343
+ const profile = measured ?? { width: 1280, height: 720, frameRate: 30 }
1344
+
1345
+ return {
1346
+ supported,
1347
+ reason: !projectionAvailable()
1348
+ ? 'The WinUI camera runtime is unavailable'
1349
+ : cameras.length === 0
1350
+ ? 'No camera device is available on this host'
1351
+ : cameraStatus !== 'granted'
1352
+ ? 'Camera permission has not been granted'
1353
+ : undefined,
1354
+ available,
1355
+ cameras,
1356
+ profiles: [{ profile: 'standard', ...profile }],
1357
+ audio: (await listAudioDevices()) > 0,
1358
+ // WinUI MediaCapture focus regions are not wired into the
1359
+ // adapter — report honestly rather than fabricate.
1360
+ focusPointOfInterest: false,
1361
+ exposurePointOfInterest: false,
1362
+ // MediaCapture zoom controls are not wired into the adapter.
1363
+ zoom: false,
1364
+ orientations:
1365
+ capture && typeof capture.SetRecordRotationAsync === 'function'
1366
+ ? ['portrait', 'portraitUpsideDown', 'landscapeLeft', 'landscapeRight']
1367
+ : [],
1368
+ cameraSwitchDuringRecording: false,
1369
+ durationLimit: 'bestEffort',
1370
+ elapsedTime: 'estimated',
1371
+ output: {
1372
+ mimeType: 'video/mp4',
1373
+ container: 'mp4',
1374
+ storage: 'appPrivateFile',
1375
+ destinationFileUrl: true,
1376
+ },
1377
+ }
1378
+ },
1379
+ previewReady: () => previewReadyFlag && !interrupted,
1380
+ validateStart: (options) => {
1381
+ if (
1382
+ options.orientation &&
1383
+ options.orientation !== 'unspecified' &&
1384
+ (!capture || typeof capture.SetRecordRotationAsync !== 'function')
1385
+ ) {
1386
+ throw error(
1387
+ 'unsupportedConfiguration',
1388
+ 'startRecording',
1389
+ 'Fixed cardinal orientation has not been qualified on this Windows source',
1390
+ )
1391
+ }
1392
+ },
1393
+ attachPreview: (target, callbacks) => {
1394
+ if (released || sink) {
1395
+ throw error('invalidState', 'attachPreview', 'The camera is disposed or finalizing')
1396
+ }
1397
+
1398
+ host = target
1399
+ listener = callbacks
1400
+
1401
+ const view = target as any
1402
+
1403
+ captureElement = view?.nativeViewProtected ?? view
1404
+ bindLifecycle()
1405
+ void checkPermission('camera').then((status) => {
1406
+ if (released || !host) {
1407
+ return
1408
+ }
1409
+
1410
+ if (status !== 'granted') {
1411
+ listener?.onError?.(
1412
+ error(
1413
+ status === 'restricted' ? 'permissionRestricted' : 'permissionDenied',
1414
+ 'preview',
1415
+ 'Request camera permission before activating this preview',
1416
+ { permission: 'camera' },
1417
+ ),
1418
+ )
1419
+
1420
+ return
1421
+ }
1422
+
1423
+ void activate()
1424
+ })
1425
+
1426
+ return () => {
1427
+ host = undefined
1428
+ listener = undefined
1429
+ captureElement = undefined
1430
+ void deactivate().then(() => {
1431
+ if (!sink) {
1432
+ closeCapture()
1433
+ }
1434
+ })
1435
+ }
1436
+ },
1437
+ configure: (next) => {
1438
+ const changed =
1439
+ JSON.stringify(next.camera) !== JSON.stringify(currentConfig.camera) ||
1440
+ (next.audio ?? false) !== (currentConfig.audio ?? false)
1441
+
1442
+ currentConfig = { ...next }
1443
+ if (!changed || !capture) {
1444
+ return
1445
+ }
1446
+
1447
+ // A camera or audio-mode change cannot mutate a live MediaCapture —
1448
+ // rebuild it and restore the attached preview.
1449
+ const hadPreview = !!captureElement
1450
+
1451
+ void deactivate()
1452
+ .then(() => {
1453
+ closeCapture()
1454
+ if (hadPreview && host) {
1455
+ return activate()
1456
+ }
1457
+ })
1458
+ .catch(() => {
1459
+ observer?.availability(false)
1460
+ })
1461
+ },
1462
+ startCapture: (take, target) => {
1463
+ if (!capture || !captureDevice || !previewReadyFlag || interrupted) {
1464
+ target.settled({
1465
+ kind: 'failed',
1466
+ stage: 'preparation',
1467
+ issue: issue('unavailable', 'startRecording', 'The camera preview is not running'),
1468
+ })
1469
+
1470
+ return
1471
+ }
1472
+
1473
+ sink = target
1474
+ request = take
1475
+
1476
+ const active = capture
1477
+ const run = async () => {
1478
+ if (take.audio) {
1479
+ const micStatus = await checkPermission('microphone')
1480
+
1481
+ if (micStatus !== 'granted') {
1482
+ throw error(
1483
+ micStatus === 'restricted'
1484
+ ? 'permissionRestricted'
1485
+ : micStatus === 'unavailable'
1486
+ ? 'unavailable'
1487
+ : 'permissionDenied',
1488
+ 'startRecording',
1489
+ `Microphone permission is ${micStatus}`,
1490
+ { permission: 'microphone' },
1491
+ )
1492
+ }
1493
+
1494
+ if (!captureAudioMode) {
1495
+ throw error(
1496
+ 'unsupportedConfiguration',
1497
+ 'startRecording',
1498
+ 'This session was created without audio; configure audio before recording',
1499
+ )
1500
+ }
1501
+ }
1502
+
1503
+ if ((await freeDiskBytes()) < minFreeDiskBytes) {
1504
+ throw error(
1505
+ 'insufficientStorage',
1506
+ 'startRecording',
1507
+ 'Not enough local storage for a movie recording',
1508
+ )
1509
+ }
1510
+
1511
+ if (take.orientation) {
1512
+ const rotation = orientationToRotation(take.orientation)
1513
+
1514
+ if (rotation === undefined || typeof active.SetRecordRotationAsync !== 'function') {
1515
+ throw error(
1516
+ 'unsupportedConfiguration',
1517
+ 'startRecording',
1518
+ `Orientation '${take.orientation}' is not supported by this camera`,
1519
+ )
1520
+ }
1521
+
1522
+ try {
1523
+ await toPromise(active.SetRecordRotationAsync(rotation))
1524
+ } catch (cause) {
1525
+ throw error(
1526
+ 'unsupportedConfiguration',
1527
+ 'startRecording',
1528
+ `Orientation '${take.orientation}' was rejected by this camera`,
1529
+ cause,
1530
+ )
1531
+ }
1532
+ }
1533
+
1534
+ const file = await reserveDestination(take.destinationPath)
1535
+ const media = projection().Windows?.Media
1536
+ const profile = media?.MediaProperties?.MediaEncodingProfile?.CreateMp4(
1537
+ media?.MediaProperties?.VideoEncodingQuality?.Auto ?? 0,
1538
+ )
1539
+
1540
+ if (!profile) {
1541
+ await removeFileQuietly(file)
1542
+ throw error(
1543
+ 'unsupportedPlatform',
1544
+ 'startRecording',
1545
+ 'MP4 encoding profiles are unavailable on this host',
1546
+ )
1547
+ }
1548
+
1549
+ const chosen = chooseStandardProfile(recordStreamProfiles())
1550
+
1551
+ try {
1552
+ if (chosen && profile.Video) {
1553
+ profile.Video.Width = chosen.width
1554
+ profile.Video.Height = chosen.height
1555
+ if (profile.Video.FrameRate) {
1556
+ profile.Video.FrameRate.Numerator = Math.max(1, Math.round(chosen.frameRate * 1000))
1557
+ profile.Video.FrameRate.Denominator = 1000
1558
+ }
1559
+ }
1560
+ } catch {
1561
+ // The auto profile still describes a real encoding.
1562
+ }
1563
+
1564
+ if (!take.audio) {
1565
+ try {
1566
+ profile.Audio = null
1567
+ } catch {
1568
+ // A projection without property writes still records;
1569
+ // silence is verified from the finalized movie.
1570
+ }
1571
+ }
1572
+
1573
+ recordFile = file
1574
+ wantStop = false
1575
+ try {
1576
+ await toPromise(active.StartRecordToStorageFileAsync(profile, file))
1577
+ } catch (cause) {
1578
+ recordFile = undefined
1579
+ await removeFileQuietly(file)
1580
+ throw error(
1581
+ captureFailureKind(cause),
1582
+ 'startRecording',
1583
+ 'MediaCapture could not begin recording',
1584
+ cause,
1585
+ )
1586
+ }
1587
+
1588
+ recordStartedAt = Date.now()
1589
+
1590
+ const stream = chooseStandardProfile(recordStreamProfiles())
1591
+ const configuration: EffectiveCaptureConfig = {
1592
+ cameraId: captureDevice!.id,
1593
+ facing: captureDevice!.facing,
1594
+ audio: take.audio && captureAudioMode,
1595
+ width: stream?.width ?? chosen?.width ?? 0,
1596
+ height: stream?.height ?? chosen?.height ?? 0,
1597
+ frameRate: stream?.frameRate ?? chosen?.frameRate ?? 0,
1598
+ orientation: take.orientation ?? 'unspecified',
1599
+ mimeType: 'video/mp4',
1600
+ container: 'mp4',
1601
+ }
1602
+
1603
+ target.started(configuration)
1604
+ if (wantStop) {
1605
+ void stopRecording()
1606
+ }
1607
+ }
1608
+
1609
+ run().catch((cause: unknown) => {
1610
+ finishWithError(
1611
+ 'preparation',
1612
+ cause instanceof CameraCaptureError
1613
+ ? cause
1614
+ : issue(
1615
+ 'captureFailed',
1616
+ 'startRecording',
1617
+ cause instanceof Error ? cause.message : String(cause),
1618
+ { cause },
1619
+ ),
1620
+ )
1621
+ })
1622
+ },
1623
+ stopCapture: () => {
1624
+ wantStop = true
1625
+ void stopRecording()
1626
+ },
1627
+ elapsedMs: () => (recordStartedAt > 0 ? Math.max(0, Date.now() - recordStartedAt) : 0),
1628
+ openOutput: async (output) => {
1629
+ if (output.kind !== 'nativeFile' || output.synthetic) {
1630
+ throw error('invalidArgument', 'openOutput', 'Expected a native Windows movie reference')
1631
+ }
1632
+
1633
+ const filePath = normalizePath(output.fileUrl.slice('file://'.length))
1634
+ const storage = projection().Windows?.Storage
1635
+
1636
+ try {
1637
+ await toPromise(storage.StorageFile.GetFileFromPathAsync(filePath))
1638
+ } catch (cause) {
1639
+ throw error(
1640
+ 'unavailable',
1641
+ 'openOutput',
1642
+ `Movie file is missing at ${output.fileUrl}`,
1643
+ cause,
1644
+ )
1645
+ }
1646
+
1647
+ const handle: MovieOutputHandle = {
1648
+ url: output.fileUrl,
1649
+ fileUrl: output.fileUrl,
1650
+ release: () => {},
1651
+ }
1652
+
1653
+ return handle
1654
+ },
1655
+ release: async () => {
1656
+ released = true
1657
+ generation += 1
1658
+ unbindLifecycle()
1659
+ if (settleDeadline !== undefined) {
1660
+ clearTimeout(settleDeadline)
1661
+ }
1662
+
1663
+ sink = undefined
1664
+ request = undefined
1665
+ wantStop = false
1666
+ finalizing = false
1667
+ recordStartedAt = 0
1668
+
1669
+ const file = recordFile
1670
+
1671
+ recordFile = undefined
1672
+ void removeFileQuietly(file)
1673
+ markReady(false)
1674
+ await deactivate()
1675
+ stopWatcher()
1676
+ closeCapture()
1677
+ host = undefined
1678
+ captureElement = undefined
1679
+ },
1680
+ onPreviewDetached: () => {
1681
+ // Finalization still owns the device while a settle is in
1682
+ // flight; the detach path already released it otherwise.
1683
+ },
1684
+ setObserver: (next) => {
1685
+ observer = next
1686
+ },
1687
+ }
1615
1688
  }