@octane-xplat/camera 0.13.0 → 0.14.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 (81) hide show
  1. package/README.md +63 -3
  2. package/dist/linux/CameraView.web.tsrx.js +337 -0
  3. package/dist/linux/host-movie.web.js +100 -0
  4. package/dist/linux/index.js +5 -0
  5. package/dist/linux/layout-child.web.js +29 -0
  6. package/dist/linux/movie-metadata.web.js +65 -0
  7. package/dist/linux/octane-client-build.json +8 -0
  8. package/dist/linux/session-backend.linux.js +479 -0
  9. package/dist/linux/session-core.js +368 -0
  10. package/dist/linux/session.js +29 -0
  11. package/dist/linux/synthetic-session.js +280 -0
  12. package/dist/linux/types.js +19 -0
  13. package/dist/native/CameraView.android.js +25 -1
  14. package/dist/native/CameraView.ios.js +24 -1
  15. package/dist/native/CameraView.windows.js +173 -0
  16. package/dist/native/camera-permission.windows.js +43 -0
  17. package/dist/native/camera-session.windows.js +78 -0
  18. package/dist/native/cx.windows.js +9 -0
  19. package/dist/native/index.js +4 -1
  20. package/dist/native/layout-child.windows.js +53 -0
  21. package/dist/native/octane-client-build.json +1 -1
  22. package/dist/native/session-backend.android.js +234 -0
  23. package/dist/native/session-backend.ios.js +682 -0
  24. package/dist/native/session-backend.js +55 -0
  25. package/dist/native/session-backend.windows.js +905 -0
  26. package/dist/native/session-core.js +368 -0
  27. package/dist/native/session.js +29 -0
  28. package/dist/native/synthetic-session.js +280 -0
  29. package/dist/native/types.js +19 -0
  30. package/dist/web/CameraView.web.tsrx.js +27 -7
  31. package/dist/web/host-movie.web.js +100 -0
  32. package/dist/web/index.js +4 -1
  33. package/dist/web/movie-metadata.web.js +65 -0
  34. package/dist/web/movie-storage.web.js +119 -0
  35. package/dist/web/octane-client-build.json +1 -1
  36. package/dist/web/session-backend.web.js +490 -0
  37. package/dist/web/session-core.js +368 -0
  38. package/dist/web/session.js +29 -0
  39. package/dist/web/synthetic-session.js +280 -0
  40. package/dist/web/types.js +19 -0
  41. package/package.json +22 -4
  42. package/platforms/android/AndroidManifest.xml +2 -0
  43. package/platforms/android/include.gradle +1 -0
  44. package/platforms/android/java/com/octanexplat/camera/CameraPreviewView.java +4 -0
  45. package/platforms/android/java/com/octanexplat/camera/CameraSessionBridge.java +363 -0
  46. package/platforms/ios/Info.plist +2 -0
  47. package/platforms/macos/src/XplatCameraHost.swift +513 -0
  48. package/src/CameraView.android.tsrx +21 -1
  49. package/src/CameraView.ios.tsrx +28 -2
  50. package/src/CameraView.macos.tsrx +93 -0
  51. package/src/CameraView.web.tsrx +20 -2
  52. package/src/CameraView.windows.tsrx +124 -0
  53. package/src/camera-permission.windows.ts +76 -0
  54. package/src/camera-session.macos.ts +75 -0
  55. package/src/camera-session.windows.ts +123 -0
  56. package/src/cx.macos.ts +5 -0
  57. package/src/cx.windows.ts +6 -0
  58. package/src/host-movie.web.ts +180 -0
  59. package/src/index.ts +31 -0
  60. package/src/index.web.ts +31 -0
  61. package/src/layout-child.windows.ts +79 -0
  62. package/src/movie-metadata.web.ts +84 -0
  63. package/src/movie-storage.web.ts +164 -0
  64. package/src/props.ts +7 -1
  65. package/src/session-backend.android.ts +397 -0
  66. package/src/session-backend.ios.ts +1092 -0
  67. package/src/session-backend.linux.ts +869 -0
  68. package/src/session-backend.macos.ts +624 -0
  69. package/src/session-backend.ts +57 -0
  70. package/src/session-backend.web.ts +874 -0
  71. package/src/session-backend.windows.ts +1517 -0
  72. package/src/session-core.ts +659 -0
  73. package/src/session.ts +37 -0
  74. package/src/synthetic-session.ts +367 -0
  75. package/src/types.ts +329 -0
  76. package/types/index.d.ts +43 -0
  77. package/types/props.d.ts +7 -1
  78. package/types/session-core.d.ts +129 -0
  79. package/types/synthetic-session.d.ts +48 -0
  80. package/types/types.d.ts +263 -0
  81. package/src/CameraView.windows.ts +0 -5
@@ -1,5 +1,6 @@
1
1
  import { useImperativeHandle, useEffect, useRef } from 'octane'
2
2
  import type { CameraViewProps } from './props'
3
+ import { attachSessionPreview } from './session'
3
4
  import { applyEscapeProps, layoutChildProps } from './layout-child.web'
4
5
 
5
6
  /** Live web preview backed by getUserMedia. */
@@ -13,6 +14,23 @@ export function CameraView(props: CameraViewProps) @{
13
14
  useEffect(() => {
14
15
  const element = video.current
15
16
  if (!element || !active) return
17
+ if (props.session) {
18
+ if (props.facing !== undefined) {
19
+ props.onError?.({ message: 'camera session conflicts with facing' })
20
+ return
21
+ }
22
+
23
+ try {
24
+ return attachSessionPreview(props.session, element, {
25
+ onReady: props.onReady,
26
+ onError: (issue) => props.onError?.({ message: issue.message }),
27
+ })
28
+ } catch (error: any) {
29
+ props.onError?.({ message: error?.message ?? 'camera session error' })
30
+ return
31
+ }
32
+ }
33
+
16
34
  const mediaDevices = navigator.mediaDevices
17
35
  if (!mediaDevices?.getUserMedia) {
18
36
  props.onError?.({ message: 'camera unsupported' })
@@ -51,7 +69,7 @@ export function CameraView(props: CameraViewProps) @{
51
69
  element.srcObject = null
52
70
  if (stream) for (const track of stream.getTracks()) track.stop()
53
71
  }
54
- }, [active, facing])
72
+ }, [active, facing, props.session])
55
73
 
56
74
  useImperativeHandle(props.ref, () => ({ native: hostRef.current }), undefined);
57
75
 
@@ -93,7 +111,7 @@ export function CameraView(props: CameraViewProps) @{
93
111
  transform: facing === 'front' ? 'scaleX(-1)' : undefined,
94
112
  }}
95
113
  onPlaying={() => {
96
- if (readyFired.current) return
114
+ if (props.session || readyFired.current) return
97
115
  readyFired.current = true
98
116
  props.onReady?.()
99
117
  }}
@@ -0,0 +1,124 @@
1
+ /** @jsxImportSource @nativescript-community/octane */
2
+ import { useImperativeHandle, useCallback, useEffect, useRef } from 'octane'
3
+ import { View } from '@nativescript/core'
4
+ import { registerElement } from '@nativescript-community/octane'
5
+ import type { Attributes } from '@nativescript-community/octane/intrinsics'
6
+ import type { CameraViewProps } from './props'
7
+ import { attachSessionPreview } from './session'
8
+ import { cameraHardwarePresent, ensureCameraPermission } from './camera-permission.windows'
9
+ import { startCameraPreview } from './camera-session.windows'
10
+ import { applyEscapeProps, layoutChildProps, nativeAccessibilityRole, nativeAccessibilityState } from './layout-child.windows'
11
+ import { cx } from './cx.windows'
12
+
13
+ class CameraPreview extends View {
14
+ createNativeView() {
15
+ const { Microsoft } = globalThis as any
16
+ return new Microsoft.UI.Xaml.Controls.CaptureElement()
17
+ }
18
+ }
19
+
20
+ declare module '@nativescript-community/octane/intrinsics' {
21
+ interface NativeScriptElements {
22
+ camerapreview: Attributes<typeof CameraPreview>
23
+ }
24
+ }
25
+
26
+ registerElement('camerapreview', CameraPreview)
27
+
28
+ /** Live Windows preview backed by WinUI `CaptureElement` + `MediaCapture`.
29
+ * With `session`, the preview attaches to the session-owned capture so
30
+ * movie recording shares it; without one the view owns its capture. */
31
+ export function CameraView(props: CameraViewProps) @{
32
+ const host = useRef<any>(null)
33
+ const active = props.active !== false
34
+ const facing = props.facing ?? 'back'
35
+ useImperativeHandle(props.ref, () => ({ native: host.current?.nativeViewProtected }), [])
36
+
37
+ const bindHost = useCallback((view: any) => {
38
+ host.current = view
39
+ }, [])
40
+
41
+ useEffect(() => {
42
+ const view = host.current
43
+ if (!view || !active) return
44
+ let disposed = false
45
+ let stopPreview: (() => Promise<void>) | undefined
46
+ const fail = (message: string) => props.onError?.({ message })
47
+
48
+ if (props.session) {
49
+ if (props.facing !== undefined) {
50
+ fail('camera session conflicts with facing')
51
+ return
52
+ }
53
+
54
+ try {
55
+ const detach = attachSessionPreview(props.session, view, {
56
+ onReady: () => {
57
+ if (!disposed) props.onReady?.()
58
+ },
59
+ onError: (issue) => {
60
+ if (!disposed) fail(issue.message)
61
+ },
62
+ })
63
+
64
+ return () => {
65
+ disposed = true
66
+ detach()
67
+ }
68
+ } catch (error: any) {
69
+ fail(error?.message ?? 'camera session error')
70
+ return
71
+ }
72
+ }
73
+
74
+ if (!cameraHardwarePresent()) {
75
+ fail('camera unsupported')
76
+ return
77
+ }
78
+
79
+ ensureCameraPermission().then(async (granted) => {
80
+ if (disposed) return
81
+ if (!granted) {
82
+ fail('camera permission denied')
83
+ return
84
+ }
85
+
86
+ try {
87
+ stopPreview = await startCameraPreview(view, facing, () => {
88
+ if (!disposed) props.onReady?.()
89
+ })
90
+ } catch (error: any) {
91
+ if (!disposed) fail(error?.message ?? 'camera error')
92
+ }
93
+ })
94
+
95
+ return () => {
96
+ disposed = true
97
+ void stopPreview?.()
98
+ }
99
+ }, [active, facing, props.session])
100
+
101
+ useEffect(() => {
102
+ const view = host.current
103
+ if (!view) return
104
+ applyEscapeProps(view.nativeViewProtected, props)
105
+ }, [props.ref, props.windows])
106
+
107
+ <gridlayout
108
+ id={props.id}
109
+ rows="*"
110
+ columns="*"
111
+ className={cx('vx-layers', 'vx-cameraview', props.className)}
112
+ style={{ backgroundColor: '#000', ...props.style }}
113
+ {...layoutChildProps(props)}
114
+ accessible={props.accessible}
115
+ accessibilityLabel={props.accessibilityLabel}
116
+ accessibilityRole={nativeAccessibilityRole(props.accessibilityRole) as any}
117
+ accessibilityHint={props.accessibilityHint}
118
+ accessibilityValue={props.accessibilityValue}
119
+ accessibilityState={nativeAccessibilityState(props.accessibilityState) as any}
120
+ accessibilityLiveRegion={props.accessibilityLiveRegion as any}
121
+ >
122
+ <camerapreview ref={bindHost} row={0} col={0} />
123
+ </gridlayout>
124
+ }
@@ -0,0 +1,76 @@
1
+ /** Windows camera-permission probe for preview-only `CameraView` callers.
2
+ * Uses `AppCapability` when projected and falls back to
3
+ * `DeviceAccessInformation`; both are non-prompting checks — only
4
+ * `RequestAccessAsync` may show the system prompt. */
5
+
6
+ const windows = () => globalThis as any
7
+
8
+ const toPromise = (op: any): Promise<any> => {
9
+ const { NSWinRT } = windows()
10
+ if (NSWinRT?.toPromise && op != null) {
11
+ return NSWinRT.toPromise(op)
12
+ }
13
+
14
+ if (op?.done) {
15
+ return new Promise((resolve, reject) => {
16
+ try {
17
+ op.done(resolve, reject)
18
+ } catch (cause) {
19
+ reject(cause)
20
+ }
21
+ })
22
+ }
23
+
24
+ return Promise.resolve(op)
25
+ }
26
+
27
+ export function cameraHardwarePresent(): boolean {
28
+ const { Windows, Microsoft } = windows()
29
+ return !!(
30
+ Windows?.Media?.Capture?.MediaCapture &&
31
+ Windows?.Devices?.Enumeration?.DeviceInformation &&
32
+ Microsoft?.UI?.Xaml?.Controls?.CaptureElement
33
+ )
34
+ }
35
+
36
+ export async function ensureCameraPermission(): Promise<boolean> {
37
+ try {
38
+ const { Windows } = windows()
39
+ const capability =
40
+ Windows?.Security?.Authorization?.AppCapabilityAccess?.AppCapability?.Create?.('webcam')
41
+
42
+ if (capability) {
43
+ const status = capability.CheckAccess()
44
+ // AppCapabilityAccessStatus: DeniedBySystem=0, NotDeclaredByApp=1,
45
+ // DeniedByUser=2, UserPromptRequired=3, Allowed=4.
46
+ if (status === 4) {
47
+ return true
48
+ }
49
+
50
+ if (status === 3) {
51
+ return (await toPromise(capability.RequestAccessAsync())) === 4
52
+ }
53
+
54
+ return false
55
+ }
56
+
57
+ const enumeration = Windows?.Devices?.Enumeration
58
+ const deviceClass = enumeration?.DeviceClass?.VideoCapture
59
+ const info =
60
+ deviceClass === undefined
61
+ ? undefined
62
+ : enumeration?.DeviceAccessInformation?.CreateFromDeviceClass(deviceClass)
63
+
64
+ if (info) {
65
+ // DeviceAccessStatus: Unspecified=0, Allowed=1, DeniedByUser=2,
66
+ // DeniedBySystem=3. The enumeration API cannot prompt — an
67
+ // Unspecified outcome is resolved by the preview's own
68
+ // InitializeAsync, which runs the OS consent flow.
69
+ return info.CurrentStatus !== 2 && info.CurrentStatus !== 3
70
+ }
71
+ } catch {
72
+ return false
73
+ }
74
+
75
+ return false
76
+ }
@@ -0,0 +1,75 @@
1
+ import '@nativescript/macos-node-api'
2
+
3
+ interface CameraHost {
4
+ attachPreview(view: object): string | null
5
+ detachPreview(): void
6
+ installObserver(emit: (message: string) => void): void
7
+ permissionStatus(kind: string): string
8
+ requestPermissionReply(kind: string, reply: (status: string) => void): void
9
+ devices(): string
10
+ audioDeviceAvailable(): boolean
11
+ configure(options: { cameraId?: string; audio?: boolean; rotationAngle?: number }): string | null
12
+ dispose(): void
13
+ }
14
+
15
+ declare const XplatCameraHost: {
16
+ alloc(): { init(): CameraHost }
17
+ }
18
+
19
+ let helper: CameraHost | undefined
20
+ const helperHost = () => (helper ??= XplatCameraHost.alloc().init())
21
+
22
+ export function cameraHardwarePresent(): boolean {
23
+ try {
24
+ return JSON.parse(helperHost().devices()).length > 0
25
+ } catch {
26
+ return false
27
+ }
28
+ }
29
+
30
+ /** Preview-only permission entry point: prompts once from mount, mirrors the
31
+ * iOS legacy path. Session code should use `session.requestPermission` —
32
+ * explicit actions only. */
33
+ export function ensureCameraPermission(): Promise<boolean> {
34
+ const status = helperHost().permissionStatus('camera')
35
+ if (status === 'granted') {
36
+ return Promise.resolve(true)
37
+ }
38
+
39
+ if (status === 'undeclared') {
40
+ return Promise.resolve(false)
41
+ }
42
+
43
+ return new Promise((resolve) =>
44
+ helperHost().requestPermissionReply('camera', (next) => resolve(next === 'granted')),
45
+ )
46
+ }
47
+
48
+ /** Legacy preview-only path: a dedicated XplatCameraHost owns the preview
49
+ * session — shared with nothing, disposed with the view. The session-backed
50
+ * path goes through `attachSessionPreview` instead. */
51
+ export function startCameraPreview(
52
+ view: object,
53
+ _facing: 'front' | 'back',
54
+ onReady?: () => void,
55
+ ): () => void {
56
+ const host = XplatCameraHost.alloc().init()
57
+ host.installObserver(() => {})
58
+ const configured = host.configure({ audio: false })
59
+ if (configured) {
60
+ host.dispose()
61
+ throw new Error(`camera unavailable: ${configured}`)
62
+ }
63
+
64
+ const failure = host.attachPreview(view)
65
+ if (failure) {
66
+ host.dispose()
67
+ throw new Error(`camera unavailable: ${failure}`)
68
+ }
69
+
70
+ onReady?.()
71
+ return () => {
72
+ host.detachPreview()
73
+ host.dispose()
74
+ }
75
+ }
@@ -0,0 +1,123 @@
1
+ /** Standalone (non-session) WinUI preview for `CameraView` without a
2
+ * `session` prop. Owns a private `MediaCapture` bound to a
3
+ * `CaptureElement`; the returned function stops preview and closes the
4
+ * device. Session-backed previews share their capture through
5
+ * `session-backend.windows.ts` instead. */
6
+
7
+ const windows = () => globalThis as any
8
+
9
+ const toPromise = (op: any): Promise<any> => {
10
+ const { NSWinRT } = windows()
11
+ if (NSWinRT?.toPromise && op != null) {
12
+ return NSWinRT.toPromise(op)
13
+ }
14
+
15
+ if (op?.done) {
16
+ return new Promise((resolve, reject) => {
17
+ try {
18
+ op.done(resolve, reject)
19
+ } catch (cause) {
20
+ reject(cause)
21
+ }
22
+ })
23
+ }
24
+
25
+ return Promise.resolve(op)
26
+ }
27
+
28
+ const vectorToArray = (items: any): any[] => {
29
+ const result: any[] = []
30
+ const size = Number(items?.Size ?? items?.Count ?? 0)
31
+ for (let index = 0; index < size; index += 1) {
32
+ result.push(items.GetAt(index))
33
+ }
34
+
35
+ return result
36
+ }
37
+
38
+ /** Attach a MediaCapture preview to the view's `CaptureElement`.
39
+ * `facing` maps to enclosure panels; desktop cameras without a panel fall
40
+ * back to the OS default — front/back is a preference, never a fabrication. */
41
+ export async function startCameraPreview(
42
+ view: any,
43
+ facing: 'front' | 'back',
44
+ onReady?: () => void,
45
+ ): Promise<() => Promise<void>> {
46
+ const { Windows } = windows()
47
+ const enumeration = Windows?.Devices?.Enumeration
48
+ const captureApi = Windows?.Media?.Capture
49
+ if (!enumeration || !captureApi) {
50
+ throw new Error('camera preview unsupported')
51
+ }
52
+
53
+ const found = await toPromise(
54
+ enumeration.DeviceInformation.FindAllAsync(enumeration.DeviceClass.VideoCapture),
55
+ )
56
+
57
+ const devices = vectorToArray(found)
58
+ if (!devices.length) {
59
+ throw new Error('camera unavailable')
60
+ }
61
+
62
+ const wantedPanel = facing === 'front' ? 1 : 2
63
+ const device =
64
+ devices.find((entry: any) => Number(entry?.EnclosureLocation?.Panel) === wantedPanel) ??
65
+ devices[0]
66
+
67
+ const settings = new captureApi.MediaCaptureInitializationSettings()
68
+ settings.VideoDeviceId = String(device?.Id ?? device?.id ?? '')
69
+ settings.StreamingCaptureMode = 0 // Video
70
+ const capture = new captureApi.MediaCapture()
71
+ try {
72
+ await toPromise(capture.InitializeAsync(settings))
73
+ } catch (cause) {
74
+ try {
75
+ capture.Close()
76
+ } catch {
77
+ try {
78
+ capture.Dispose()
79
+ } catch {
80
+ // GC reclaims the device handle.
81
+ }
82
+ }
83
+
84
+ throw cause instanceof Error ? cause : new Error('camera unavailable')
85
+ }
86
+
87
+ const element = view?.nativeViewProtected ?? view
88
+ element.Source = capture
89
+ try {
90
+ if (Number(device?.EnclosureLocation?.Panel) === 1 && typeof capture.SetPreviewMirroring === 'function') {
91
+ capture.SetPreviewMirroring(true)
92
+ }
93
+ } catch {
94
+ // Mirrored preview is cosmetic.
95
+ }
96
+
97
+ await toPromise(capture.StartPreviewAsync())
98
+ onReady?.()
99
+
100
+ return async () => {
101
+ try {
102
+ element.Source = null
103
+ } catch {
104
+ // The element may already be gone.
105
+ }
106
+
107
+ try {
108
+ await toPromise(capture.StopPreviewAsync())
109
+ } catch {
110
+ // The pipeline may already be down.
111
+ }
112
+
113
+ try {
114
+ capture.Close()
115
+ } catch {
116
+ try {
117
+ capture.Dispose()
118
+ } catch {
119
+ // GC reclaims the device handle.
120
+ }
121
+ }
122
+ }
123
+ }
@@ -0,0 +1,5 @@
1
+ /** Imperative `view.className` writes still need a pre-joined string —
2
+ * normalize arrays here so they stay space separated. */
3
+ export function cx(...parts: any[]): string {
4
+ return parts.flat(Infinity).filter(Boolean).join(' ')
5
+ }
@@ -0,0 +1,6 @@
1
+ /** Imperative `view.className` writes still need a pre-joined string —
2
+ * NativeScript's className setter splits on ' ' only. Normalize arrays here
3
+ * so they stay space separated. */
4
+ export function cx(...parts: any[]): string {
5
+ return parts.flat(Infinity).filter(Boolean).join(' ')
6
+ }
@@ -0,0 +1,180 @@
1
+ import { createHostClient, type HostClient } from '@octane-xplat/platform/host'
2
+ import { createWebKitTransport } from '@octane-xplat/platform/host/web'
3
+ import { CameraCaptureError } from './types'
4
+ import type { MovieOutput, MovieOutputHandle } from './types'
5
+
6
+ // Inside a desktop native webview the typed host channel may expose a
7
+ // `camera` service: truthful macOS privacy status plus app-private durable
8
+ // file storage. Outside a host — or when the service is absent — every probe
9
+ // resolves absent and the adapter keeps its browser storage behavior.
10
+
11
+ export interface CameraHostServices {
12
+ camera: {
13
+ permissionStatus(options: { kind: string }): Promise<{ status: string }>
14
+ requestPermission(options: { kind: string }): Promise<{ status: string }>
15
+ movieDirectory(): Promise<{ fileUrl: string | null }>
16
+ reserveMoviePath(options: {
17
+ fileUrl?: string
18
+ container?: string
19
+ }): Promise<{ reservation: { fileUrl: string } | null }>
20
+ writeMovieFile(options: {
21
+ fileUrl: string
22
+ base64: string
23
+ }): Promise<{ file: { name: string; uri: string } | null }>
24
+ movieFileInfo(options: {
25
+ fileUrl: string
26
+ }): Promise<{ info: { exists: boolean; fileUrl?: string; size?: number } | null }>
27
+ readMovieFile(options: { fileUrl: string }): Promise<{ base64: string | null }>
28
+ deleteMovieFile(options: { fileUrl: string }): Promise<{ removed: boolean }>
29
+ }
30
+ }
31
+
32
+ const requiredMethods = [
33
+ 'permissionStatus',
34
+ 'requestPermission',
35
+ 'movieDirectory',
36
+ 'reserveMoviePath',
37
+ 'writeMovieFile',
38
+ 'movieFileInfo',
39
+ 'readMovieFile',
40
+ 'deleteMovieFile',
41
+ ]
42
+
43
+ export type CameraHost = HostClient<CameraHostServices>
44
+
45
+ let hostProbe: Promise<CameraHost | null> | undefined
46
+
47
+ /** The camera-capable desktop host client, or null outside a qualified host. */
48
+ export function cameraHost(): Promise<CameraHost | null> {
49
+ hostProbe ??= (async () => {
50
+ try {
51
+ const transport = createWebKitTransport()
52
+ if (!transport) {
53
+ return null
54
+ }
55
+
56
+ const client = createHostClient<CameraHostServices>(transport)
57
+ const capabilities = (await client.capabilities().catch(() => null)) as {
58
+ camera?: string[]
59
+ } | null
60
+
61
+ const methods = capabilities?.camera
62
+ if (Array.isArray(methods) && requiredMethods.every((name) => methods.includes(name))) {
63
+ return client
64
+ }
65
+
66
+ client.dispose()
67
+ return null
68
+ } catch {
69
+ return null
70
+ }
71
+ })()
72
+
73
+ return hostProbe
74
+ }
75
+
76
+ const error = (kind: 'destinationUnavailable' | 'storageFailed' | 'unavailable', message: string) =>
77
+ new CameraCaptureError({ kind, operation: 'storage', message })
78
+
79
+ const blobToBase64 = async (bytes: Blob): Promise<string> => {
80
+ const data = new Uint8Array(await bytes.arrayBuffer())
81
+ let binary = ''
82
+ const chunk = 0x8000
83
+ for (let offset = 0; offset < data.length; offset += chunk) {
84
+ binary += String.fromCharCode(...data.subarray(offset, offset + chunk))
85
+ }
86
+
87
+ return btoa(binary)
88
+ }
89
+
90
+ const base64ToBlob = (base64: string, type: string): Blob => {
91
+ const binary = atob(base64)
92
+ const data = new Uint8Array(binary.length)
93
+ for (let index = 0; index < binary.length; index++) {
94
+ data[index] = binary.charCodeAt(index)
95
+ }
96
+
97
+ return new Blob([data], { type })
98
+ }
99
+
100
+ const mimeForFileUrl = (fileUrl: string): string =>
101
+ fileUrl.endsWith('.webm')
102
+ ? 'video/webm'
103
+ : fileUrl.endsWith('.mov')
104
+ ? 'video/quicktime'
105
+ : 'video/mp4'
106
+
107
+ /** Reserve a host-side movie file. `destinationFileUrl` is validated
108
+ * host-side: it must be a new file inside the app-private storage root. */
109
+ export const reserveHostMovie = async (
110
+ host: CameraHost,
111
+ options: { destinationFileUrl?: string; container?: string },
112
+ ): Promise<{ fileUrl: string }> => {
113
+ const { reservation } = await host.call('camera', 'reserveMoviePath', {
114
+ fileUrl: options.destinationFileUrl,
115
+ container: options.container,
116
+ })
117
+
118
+ if (!reservation?.fileUrl) {
119
+ throw error(
120
+ 'destinationUnavailable',
121
+ options.destinationFileUrl
122
+ ? 'destinationFileUrl must be a new file inside the app-private recordings directory'
123
+ : 'The host could not allocate a movie recording file',
124
+ )
125
+ }
126
+
127
+ return reservation
128
+ }
129
+
130
+ /** Commit finalized movie bytes to host-side app-private storage. */
131
+ export const commitHostMovie = async (
132
+ host: CameraHost,
133
+ fileUrl: string,
134
+ bytes: Blob,
135
+ ): Promise<MovieOutput> => {
136
+ const base64 = await blobToBase64(bytes)
137
+ const { file } = await host.call('camera', 'writeMovieFile', { fileUrl, base64 })
138
+ if (!file?.uri) {
139
+ throw error('storageFailed', 'The host could not write the recorded movie')
140
+ }
141
+
142
+ return { kind: 'nativeFile', resourceId: file.uri, fileUrl: file.uri }
143
+ }
144
+
145
+ /** Drop an uncommitted host reservation after a failed attempt. */
146
+ export const removeHostReservation = async (host: CameraHost, fileUrl: string): Promise<void> => {
147
+ await host.call('camera', 'deleteMovieFile', { fileUrl }).catch(() => {})
148
+ }
149
+
150
+ /** Reopen a host-stored movie as a temporary playback URL. The durable
151
+ * reference remains `fileUrl`; the returned url lives until `release()`. */
152
+ export const openHostMovie = async (
153
+ host: CameraHost,
154
+ output: MovieOutput,
155
+ ): Promise<MovieOutputHandle> => {
156
+ if (output.kind !== 'nativeFile' || !output.fileUrl) {
157
+ throw new CameraCaptureError({
158
+ kind: 'invalidArgument',
159
+ operation: 'openOutput',
160
+ message: 'Only file-backed output can be opened through the desktop host',
161
+ })
162
+ }
163
+
164
+ const { info } = await host.call('camera', 'movieFileInfo', { fileUrl: output.fileUrl })
165
+ if (!info?.exists) {
166
+ throw error('unavailable', `Movie file is missing at ${output.fileUrl}`)
167
+ }
168
+
169
+ const { base64 } = await host.call('camera', 'readMovieFile', { fileUrl: output.fileUrl })
170
+ if (!base64) {
171
+ throw error('unavailable', `Movie file could not be read at ${output.fileUrl}`)
172
+ }
173
+
174
+ const url = URL.createObjectURL(base64ToBlob(base64, mimeForFileUrl(output.fileUrl)))
175
+ return {
176
+ url,
177
+ fileUrl: output.fileUrl,
178
+ release: () => URL.revokeObjectURL(url),
179
+ }
180
+ }
package/src/index.ts CHANGED
@@ -2,3 +2,34 @@
2
2
  // the iOS or Android component for the current build target.
3
3
  export { CameraView } from './CameraView'
4
4
  export type { CameraAccessibilityRole, CameraViewHandle, CameraViewProps } from './props'
5
+ export { createCameraSession } from './session'
6
+ export { CameraCaptureError } from './types'
7
+ export type {
8
+ CameraCaptureErrorKind,
9
+ CameraDeviceInfo,
10
+ CameraFacing,
11
+ CameraInterruptionReason,
12
+ CameraOrientation,
13
+ CameraPermissionKind,
14
+ CameraPermissionStatus,
15
+ CameraProfileCapability,
16
+ CameraRecorderState,
17
+ CameraSelection,
18
+ CameraSession,
19
+ CameraSessionCapabilities,
20
+ CameraSessionConfig,
21
+ CameraSessionEvent,
22
+ CameraSessionSnapshot,
23
+ CaptureIssue,
24
+ EffectiveCaptureConfig,
25
+ MovieClip,
26
+ MovieEndReason,
27
+ MovieOutcome,
28
+ MovieOutput,
29
+ MovieOutputHandle,
30
+ MovieTake,
31
+ StartRecordingOptions,
32
+ } from './types'
33
+
34
+ export { createMemoryCameraStorage, createSyntheticCameraSession } from './synthetic-session'
35
+ export type { SyntheticCameraScript, SyntheticCameraStorage } from './synthetic-session'