@octane-xplat/camera 0.18.0 → 0.20.0

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