@octane-xplat/camera 0.19.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/README.md +2 -132
  2. package/package.json +20 -25
  3. package/platforms/android/java/com/octanexplat/camera/CameraPreviewView.java +24 -0
  4. package/platforms/android/java/com/octanexplat/camera/CameraSessionBridge.java +153 -21
  5. package/platforms/ios/src/XplatSwitchingMovieWriter.swift +557 -0
  6. package/src/CameraView.android.tsrx +187 -154
  7. package/src/CameraView.ios.tsrx +124 -110
  8. package/src/CameraView.macos.tsrx +103 -96
  9. package/src/CameraView.tsrx +2 -0
  10. package/src/CameraView.web.tsrx +157 -146
  11. package/src/CameraView.windows.tsrx +134 -125
  12. package/src/camera-host.macos.ts +1059 -0
  13. package/src/camera-permission.mobile.ts +85 -81
  14. package/src/camera-permission.windows.ts +56 -53
  15. package/src/camera-session.ios.ts +89 -61
  16. package/src/camera-session.macos.ts +51 -49
  17. package/src/camera-session.windows.ts +113 -105
  18. package/src/host-movie.web.ts +257 -231
  19. package/src/index.ts +28 -26
  20. package/src/index.web.ts +27 -25
  21. package/src/layout-child.ts +86 -79
  22. package/src/layout-child.web.ts +54 -53
  23. package/src/layout-child.windows.ts +80 -74
  24. package/src/movie-metadata.web.ts +84 -81
  25. package/src/movie-storage.web.ts +142 -135
  26. package/src/movie-writer.ios.ts +170 -0
  27. package/src/photo-lifecycle.macos.ts +60 -0
  28. package/src/photo-sheet.macos.ts +505 -0
  29. package/src/preview-display.ios.ts +69 -0
  30. package/src/preview-pinch.ts +41 -0
  31. package/src/preview-tap.ts +22 -21
  32. package/src/props.ts +115 -93
  33. package/src/recording-haptics.ios.ts +39 -0
  34. package/src/recording-source.web.ts +159 -0
  35. package/src/session-backend.android.ts +552 -410
  36. package/src/session-backend.ios.ts +1500 -1148
  37. package/src/session-backend.linux.ts +886 -860
  38. package/src/session-backend.macos.ts +697 -679
  39. package/src/session-backend.ts +51 -49
  40. package/src/session-backend.web.ts +1181 -867
  41. package/src/session-backend.windows.ts +1540 -1467
  42. package/src/session-core.ts +925 -714
  43. package/src/session.ts +12 -12
  44. package/src/style-merge.ts +40 -37
  45. package/src/synthetic-session.ts +391 -339
  46. package/src/types.ts +372 -298
  47. package/types/generated/.tsrx-typegen-manifest.json +4 -24
  48. package/types/generated/CameraView.d.ts +2 -0
  49. package/types/generated/camera-host.macos.d.ts +33 -0
  50. package/types/generated/index.d.ts +27 -26
  51. package/types/generated/photo-lifecycle.macos.d.ts +12 -0
  52. package/types/generated/photo-sheet.macos.d.ts +36 -0
  53. package/types/generated/props.d.ts +24 -2
  54. package/types/generated/session-core.d.ts +30 -1
  55. package/types/generated/synthetic-session.d.ts +7 -0
  56. package/types/generated/types.d.ts +75 -1
  57. package/platforms/macos/src/CameraOwnership.swift +0 -22
  58. package/platforms/macos/src/PhotoCaptureLifecycle.swift +0 -34
  59. package/platforms/macos/src/XplatCameraHost.swift +0 -639
  60. package/platforms/macos/src/XplatPhotoCaptureSheet.swift +0 -192
  61. package/types/generated/CameraView.android.d.ts +0 -9
  62. package/types/generated/CameraView.ios.d.ts +0 -5
  63. package/types/generated/CameraView.macos.d.ts +0 -5
  64. package/types/generated/CameraView.mobile.d.ts +0 -5
  65. package/types/generated/CameraView.windows.d.ts +0 -11
  66. package/types/generated/camera-permission.mobile.d.ts +0 -2
  67. package/types/generated/camera-permission.windows.d.ts +0 -6
  68. package/types/generated/camera-session.ios.d.ts +0 -2
  69. package/types/generated/camera-session.macos.d.ts +0 -10
  70. package/types/generated/camera-session.windows.d.ts +0 -9
  71. package/types/generated/host-movie.web.d.ts +0 -100
  72. package/types/generated/index.web.d.ts +0 -7
  73. package/types/generated/layout-child.d.ts +0 -11
  74. package/types/generated/layout-child.windows.d.ts +0 -13
  75. package/types/generated/movie-metadata.web.d.ts +0 -9
  76. package/types/generated/movie-storage.web.d.ts +0 -5
  77. package/types/generated/preview-tap.d.ts +0 -7
  78. package/types/generated/session-backend.android.d.ts +0 -3
  79. package/types/generated/session-backend.ios.d.ts +0 -5
  80. package/types/generated/session-backend.linux.d.ts +0 -3
  81. package/types/generated/session-backend.macos.d.ts +0 -8
  82. package/types/generated/session-backend.web.d.ts +0 -3
  83. package/types/generated/session-backend.windows.d.ts +0 -37
  84. package/types/generated/style-merge.d.ts +0 -8
@@ -3,92 +3,95 @@ import { CameraCaptureError } from './types'
3
3
 
4
4
  /** Read packet end timestamps and track metadata, never the wall-clock stop time. */
5
5
  export async function inspectMovie(
6
- bytes: Blob,
7
- audioRequested: boolean,
6
+ bytes: Blob,
7
+ audioRequested: boolean,
8
8
  ): Promise<{
9
- durationMs: number
10
- width: number
11
- height: number
12
- hasAudio: boolean
13
- mimeType: string
14
- orientation: 'unspecified'
9
+ durationMs: number
10
+ width: number
11
+ height: number
12
+ hasAudio: boolean
13
+ mimeType: string
14
+ orientation: 'unspecified'
15
15
  }> {
16
- if (!bytes.size) {
17
- throw new CameraCaptureError({
18
- kind: 'noMedia',
19
- operation: 'finalize',
20
- message: 'The recorder produced no movie bytes',
21
- })
22
- }
16
+ if (!bytes.size) {
17
+ throw new CameraCaptureError({
18
+ kind: 'noMedia',
19
+ operation: 'finalize',
20
+ message: 'The recorder produced no movie bytes',
21
+ })
22
+ }
23
23
 
24
- const input = new Input({ source: new BlobSource(bytes), formats: [WEBM, MP4] })
25
- const read = async () => {
26
- const video = await input.getPrimaryVideoTrack()
27
- const audio = await input.getPrimaryAudioTrack()
28
- if (!video) {
29
- throw new CameraCaptureError({
30
- kind: 'noMedia',
31
- operation: 'finalize',
32
- message: 'The movie contains no video track',
33
- })
34
- }
24
+ const input = new Input({ source: new BlobSource(bytes), formats: [WEBM, MP4] })
25
+ const read = async () => {
26
+ const video = await input.getPrimaryVideoTrack()
27
+ const audio = await input.getPrimaryAudioTrack()
35
28
 
36
- const videoDuration = await video.computeDuration()
37
- const hasAudio = audio !== null && (await audio.computeDuration()) > 0
38
- const durationMs = (await input.computeDuration()) * 1000
39
- const width = await video.getDisplayWidth()
40
- const height = await video.getDisplayHeight()
41
- if (
42
- !Number.isFinite(durationMs) ||
43
- durationMs <= 0 ||
44
- videoDuration <= 0 ||
45
- width <= 0 ||
46
- height <= 0
47
- ) {
48
- throw new CameraCaptureError({
49
- kind: 'noMedia',
50
- operation: 'finalize',
51
- message: 'The movie has no usable video media',
52
- })
53
- }
29
+ if (!video) {
30
+ throw new CameraCaptureError({
31
+ kind: 'noMedia',
32
+ operation: 'finalize',
33
+ message: 'The movie contains no video track',
34
+ })
35
+ }
54
36
 
55
- if (audioRequested && !hasAudio) {
56
- throw new CameraCaptureError({
57
- kind: 'captureFailed',
58
- operation: 'finalize',
59
- message: 'Requested audio is absent from the finalized movie',
60
- })
61
- }
37
+ const videoDuration = await video.computeDuration()
38
+ const hasAudio = audio !== null && (await audio.computeDuration()) > 0
39
+ const durationMs = (await input.computeDuration()) * 1000
40
+ const width = await video.getDisplayWidth()
41
+ const height = await video.getDisplayHeight()
62
42
 
63
- return {
64
- durationMs,
65
- width,
66
- height,
67
- hasAudio,
68
- mimeType: await input.getMimeType(),
69
- orientation: 'unspecified' as const,
70
- }
71
- }
43
+ if (
44
+ !Number.isFinite(durationMs) ||
45
+ durationMs <= 0 ||
46
+ videoDuration <= 0 ||
47
+ width <= 0 ||
48
+ height <= 0
49
+ ) {
50
+ throw new CameraCaptureError({
51
+ kind: 'noMedia',
52
+ operation: 'finalize',
53
+ message: 'The movie has no usable video media',
54
+ })
55
+ }
72
56
 
73
- let timer: ReturnType<typeof setTimeout> | undefined
74
- try {
75
- return await Promise.race([
76
- read(),
77
- new Promise<never>((_resolve, reject) => {
78
- timer = setTimeout(() => {
79
- input.dispose()
80
- reject(
81
- new CameraCaptureError({
82
- kind: 'finalizationFailed',
83
- operation: 'metadata',
84
- message: 'Movie metadata verification timed out',
85
- }),
86
- )
87
- }, 30_000)
88
- }),
89
- ])
90
- } finally {
91
- clearTimeout(timer)
92
- input.dispose()
93
- }
57
+ if (audioRequested && !hasAudio) {
58
+ throw new CameraCaptureError({
59
+ kind: 'captureFailed',
60
+ operation: 'finalize',
61
+ message: 'Requested audio is absent from the finalized movie',
62
+ })
63
+ }
64
+
65
+ return {
66
+ durationMs,
67
+ width,
68
+ height,
69
+ hasAudio,
70
+ mimeType: await input.getMimeType(),
71
+ orientation: 'unspecified' as const,
72
+ }
73
+ }
74
+
75
+ let timer: ReturnType<typeof setTimeout> | undefined
76
+
77
+ try {
78
+ return await Promise.race([
79
+ read(),
80
+ new Promise<never>((_resolve, reject) => {
81
+ timer = setTimeout(() => {
82
+ input.dispose()
83
+ reject(
84
+ new CameraCaptureError({
85
+ kind: 'finalizationFailed',
86
+ operation: 'metadata',
87
+ message: 'Movie metadata verification timed out',
88
+ }),
89
+ )
90
+ }, 30_000)
91
+ }),
92
+ ])
93
+ } finally {
94
+ clearTimeout(timer)
95
+ input.dispose()
96
+ }
94
97
  }
@@ -7,158 +7,165 @@ const storeName = 'movies'
7
7
  type StoredMovie = { id: string; clip?: MovieClip; bytes?: Blob }
8
8
 
9
9
  const storageError = (cause: unknown) =>
10
- new CameraCaptureError({
11
- kind:
12
- cause instanceof DOMException && cause.name === 'QuotaExceededError'
13
- ? 'insufficientStorage'
14
- : 'storageFailed',
15
- operation: 'storage',
16
- message: 'The movie could not be committed to origin-local storage',
17
- cause,
18
- })
10
+ new CameraCaptureError({
11
+ kind:
12
+ cause instanceof DOMException && cause.name === 'QuotaExceededError'
13
+ ? 'insufficientStorage'
14
+ : 'storageFailed',
15
+ operation: 'storage',
16
+ message: 'The movie could not be committed to origin-local storage',
17
+ cause,
18
+ })
19
19
 
20
20
  /** Each operation closes its database; playback survives session and page lifetimes. */
21
21
  async function transact<T>(
22
- mode: IDBTransactionMode,
23
- operation: (store: IDBObjectStore, result: (value: T) => void) => void,
22
+ mode: IDBTransactionMode,
23
+ operation: (store: IDBObjectStore, result: (value: T) => void) => void,
24
24
  ): Promise<T> {
25
- return new Promise<T>((resolve, reject) => {
26
- let database: IDBDatabase | undefined
27
- let transaction: IDBTransaction | undefined
28
- let result: T
29
- let done = false
30
- const finish = (cause?: unknown) => {
31
- if (done) {
32
- return
33
- }
34
-
35
- done = true
36
- clearTimeout(timer)
37
- database?.close()
38
- if (cause) {
39
- reject(storageError(cause))
40
- } else {
41
- resolve(result)
42
- }
43
- }
44
-
45
- const timer = setTimeout(() => {
46
- transaction?.abort()
47
- finish(new Error('Storage transaction timed out'))
48
- }, 15_000)
49
-
50
- const request = indexedDB.open(databaseName, 1)
51
- request.onupgradeneeded = () => request.result.createObjectStore(storeName, { keyPath: 'id' })
52
- request.onerror = () => finish(request.error)
53
- request.onblocked = () => finish(new Error('Storage upgrade is blocked by another page'))
54
- request.onsuccess = () => {
55
- database = request.result
56
- if (done) {
57
- database.close()
58
- return
59
- }
60
-
61
- try {
62
- transaction = database.transaction(storeName, mode, { durability: 'strict' })
63
- transaction.oncomplete = () => finish()
64
- transaction.onabort = () =>
65
- finish(transaction?.error ?? new Error('Storage transaction aborted'))
66
-
67
- transaction.onerror = () =>
68
- finish(transaction?.error ?? new Error('Storage transaction failed'))
69
-
70
- operation(transaction.objectStore(storeName), (value) => {
71
- result = value
72
- })
73
- } catch (cause) {
74
- finish(cause)
75
- }
76
- }
77
- })
25
+ return new Promise<T>((resolve, reject) => {
26
+ let database: IDBDatabase | undefined
27
+ let transaction: IDBTransaction | undefined
28
+ let result: T
29
+ let done = false
30
+ const finish = (cause?: unknown) => {
31
+ if (done) {
32
+ return
33
+ }
34
+
35
+ done = true
36
+ clearTimeout(timer)
37
+ database?.close()
38
+ if (cause) {
39
+ reject(storageError(cause))
40
+ } else {
41
+ resolve(result)
42
+ }
43
+ }
44
+
45
+ const timer = setTimeout(() => {
46
+ transaction?.abort()
47
+ finish(new Error('Storage transaction timed out'))
48
+ }, 15_000)
49
+
50
+ const request = indexedDB.open(databaseName, 1)
51
+
52
+ request.onupgradeneeded = () => request.result.createObjectStore(storeName, { keyPath: 'id' })
53
+ request.onerror = () => finish(request.error)
54
+ request.onblocked = () => finish(new Error('Storage upgrade is blocked by another page'))
55
+ request.onsuccess = () => {
56
+ database = request.result
57
+ if (done) {
58
+ database.close()
59
+ return
60
+ }
61
+
62
+ try {
63
+ transaction = database.transaction(storeName, mode, { durability: 'strict' })
64
+ transaction.oncomplete = () => finish()
65
+ transaction.onabort = () =>
66
+ finish(transaction?.error ?? new Error('Storage transaction aborted'))
67
+
68
+ transaction.onerror = () =>
69
+ finish(transaction?.error ?? new Error('Storage transaction failed'))
70
+
71
+ operation(transaction.objectStore(storeName), (value) => {
72
+ result = value
73
+ })
74
+ } catch (cause) {
75
+ finish(cause)
76
+ }
77
+ }
78
+ })
78
79
  }
79
80
 
80
81
  export async function reserveMovie(): Promise<string> {
81
- const estimate = await navigator.storage.estimate()
82
- if (
83
- estimate.quota !== undefined &&
84
- estimate.usage !== undefined &&
85
- estimate.quota - estimate.usage < 1_048_576
86
- ) {
87
- throw new CameraCaptureError({
88
- kind: 'insufficientStorage',
89
- operation: 'reserve',
90
- message: 'Origin storage has less than 1 MiB free',
91
- })
92
- }
93
-
94
- const id = crypto.randomUUID()
95
- await transact<void>('readwrite', (store) => {
96
- store.add({ id })
97
- })
98
-
99
- return id
82
+ const estimate = await navigator.storage.estimate()
83
+
84
+ if (
85
+ estimate.quota !== undefined &&
86
+ estimate.usage !== undefined &&
87
+ estimate.quota - estimate.usage < 1_048_576
88
+ ) {
89
+ throw new CameraCaptureError({
90
+ kind: 'insufficientStorage',
91
+ operation: 'reserve',
92
+ message: 'Origin storage has less than 1 MiB free',
93
+ })
94
+ }
95
+
96
+ const id = crypto.randomUUID()
97
+
98
+ await transact<void>('readwrite', (store) => {
99
+ store.add({ id })
100
+ })
101
+
102
+ return id
100
103
  }
101
104
 
102
105
  export async function commitMovie(id: string, bytes: Blob, clip: MovieClip): Promise<void> {
103
- if (!(await navigator.storage.persisted())) {
104
- throw new CameraCaptureError({
105
- kind: 'destinationUnavailable',
106
- operation: 'storage',
107
- message: 'Persistent origin storage is no longer granted',
108
- })
109
- }
110
-
111
- await transact<void>('readwrite', (store) => {
112
- store.put({ id, bytes, clip } satisfies StoredMovie)
113
- })
114
-
115
- // Reopen the committed entry before handing ownership to the app.
116
- const stored = await readMovie(id)
117
- if (!stored.bytes || stored.bytes.size !== bytes.size || !stored.clip) {
118
- throw storageError(new Error('Committed movie cannot be reopened'))
119
- }
106
+ if (!(await navigator.storage.persisted())) {
107
+ throw new CameraCaptureError({
108
+ kind: 'destinationUnavailable',
109
+ operation: 'storage',
110
+ message: 'Persistent origin storage is no longer granted',
111
+ })
112
+ }
113
+
114
+ await transact<void>('readwrite', (store) => {
115
+ store.put({ id, bytes, clip } satisfies StoredMovie)
116
+ })
117
+
118
+ // Reopen the committed entry before handing ownership to the app.
119
+ const stored = await readMovie(id)
120
+
121
+ if (!stored.bytes || stored.bytes.size !== bytes.size || !stored.clip) {
122
+ throw storageError(new Error('Committed movie cannot be reopened'))
123
+ }
120
124
  }
121
125
 
122
126
  export async function removeReservation(id: string): Promise<void> {
123
- await transact<void>('readwrite', (store) => {
124
- store.delete(id)
125
- })
127
+ await transact<void>('readwrite', (store) => {
128
+ store.delete(id)
129
+ })
126
130
  }
127
131
 
128
132
  async function readMovie(id: string): Promise<StoredMovie> {
129
- return transact<StoredMovie>('readonly', (store, result) => {
130
- const request = store.get(id)
131
- request.onsuccess = () => result(request.result ?? { id })
132
- })
133
+ return transact<StoredMovie>('readonly', (store, result) => {
134
+ const request = store.get(id)
135
+
136
+ request.onsuccess = () => result(request.result ?? { id })
137
+ })
133
138
  }
134
139
 
135
140
  export async function openStoredMovie(output: MovieOutput): Promise<MovieOutputHandle> {
136
- if (output.kind !== 'browserStorage' || output.synthetic) {
137
- throw new CameraCaptureError({
138
- kind: 'invalidArgument',
139
- operation: 'openOutput',
140
- message: 'Expected an origin-local movie reference',
141
- })
142
- }
143
-
144
- const stored = await readMovie(output.resourceId)
145
- if (!stored.bytes || !stored.clip) {
146
- throw new CameraCaptureError({
147
- kind: 'destinationUnavailable',
148
- operation: 'openOutput',
149
- message: 'Movie is missing or site data was cleared',
150
- })
151
- }
152
-
153
- const url = URL.createObjectURL(stored.bytes)
154
- let released = false
155
- return {
156
- url,
157
- release: () => {
158
- if (!released) {
159
- released = true
160
- URL.revokeObjectURL(url)
161
- }
162
- },
163
- }
141
+ if (output.kind !== 'browserStorage' || output.synthetic) {
142
+ throw new CameraCaptureError({
143
+ kind: 'invalidArgument',
144
+ operation: 'openOutput',
145
+ message: 'Expected an origin-local movie reference',
146
+ })
147
+ }
148
+
149
+ const stored = await readMovie(output.resourceId)
150
+
151
+ if (!stored.bytes || !stored.clip) {
152
+ throw new CameraCaptureError({
153
+ kind: 'destinationUnavailable',
154
+ operation: 'openOutput',
155
+ message: 'Movie is missing or site data was cleared',
156
+ })
157
+ }
158
+
159
+ const url = URL.createObjectURL(stored.bytes)
160
+ let released = false
161
+
162
+ return {
163
+ url,
164
+ release: () => {
165
+ if (!released) {
166
+ released = true
167
+ URL.revokeObjectURL(url)
168
+ }
169
+ },
170
+ }
164
171
  }
@@ -0,0 +1,170 @@
1
+ import { CameraCaptureError } from './types'
2
+ import type { BackendCameraSwitch } from './session-core'
3
+ import type { CameraDeviceInfo } from './types'
4
+
5
+ /** Internal bridge to the native sample writer. */
6
+ export interface IOSMovieWriter {
7
+ install(session: unknown): string | null
8
+ configureAudio(enabled: boolean): string | null
9
+ observeSource(callback: (ready: boolean) => void): void
10
+ setPreviewLayer(layer: unknown): void
11
+ expectCamera(id: string): void
12
+ startAudioOrientationMaximumDurationMsReply(
13
+ path: string,
14
+ audio: boolean,
15
+ orientation: number,
16
+ limit: number,
17
+ callback: (type: string, payload: string) => void,
18
+ ): void
19
+ switchToReply(id: string, callback: (problem: string | null) => void): void
20
+ confirmSwitch(id: string): void
21
+ cancelSwitch(): void
22
+ stop(): void
23
+ elapsedMs(): number
24
+ releaseWithReply(callback: () => void): void
25
+ }
26
+
27
+ const problem = (kind: 'invalidState' | 'unavailable', message: string) =>
28
+ new CameraCaptureError({ kind, operation: 'switchCamera', message })
29
+
30
+ /** Retires callbacks before terminal delivery: listeners may admit another take. */
31
+ export class IOSMovieWriterDriver {
32
+ private epoch = 0
33
+ private active = false
34
+ private stopping = false
35
+ private released = false
36
+ private releasing: Promise<void> | undefined
37
+ private provisional: { token: object; reject: (error: Error) => void } | undefined
38
+ private pending: { reject: (error: Error) => void; token: object } | undefined
39
+ private native: IOSMovieWriter
40
+
41
+ constructor(native: IOSMovieWriter) {
42
+ this.native = native
43
+ }
44
+
45
+ start(
46
+ path: string,
47
+ audio: boolean,
48
+ orientation: number,
49
+ limit: number,
50
+ event: (type: string, payload: string) => void,
51
+ ): void {
52
+ if (this.released || this.active) {
53
+ throw problem('invalidState', 'The writer is disposed or already recording')
54
+ }
55
+
56
+ const epoch = ++this.epoch
57
+
58
+ this.active = true
59
+ this.stopping = false
60
+ try {
61
+ this.native.startAudioOrientationMaximumDurationMsReply(
62
+ path,
63
+ audio,
64
+ orientation,
65
+ limit,
66
+ (type, payload) => {
67
+ if (!this.active || this.released || epoch !== this.epoch) {
68
+ return
69
+ }
70
+
71
+ if (['finishing', 'limit', 'sourceLost', 'finished', 'failed'].includes(type)) {
72
+ this.stopping = true
73
+ this.cancelSwitch()
74
+ }
75
+
76
+ if (type === 'finished' || type === 'failed') {
77
+ this.active = false
78
+ this.cancelSwitch()
79
+ }
80
+
81
+ event(type, payload)
82
+ },
83
+ )
84
+ } catch (error) {
85
+ this.active = false
86
+ throw error
87
+ }
88
+ }
89
+
90
+ switchCamera(camera: CameraDeviceInfo): BackendCameraSwitch {
91
+ if (!this.active || this.stopping || this.released || this.pending || this.provisional) {
92
+ throw problem('invalidState', 'The writer cannot switch now')
93
+ }
94
+
95
+ const token = {}
96
+ const completion = new Promise<CameraDeviceInfo>((resolve, reject) => {
97
+ this.pending = { token, reject }
98
+ try {
99
+ this.native.switchToReply(camera.id, (message) => {
100
+ if (this.pending?.token !== token || this.released) {
101
+ return
102
+ }
103
+
104
+ this.pending = undefined
105
+ if (message) {
106
+ reject(problem('unavailable', message))
107
+ } else {
108
+ this.provisional = { token, reject }
109
+ resolve({ ...camera })
110
+ }
111
+ })
112
+ } catch (error) {
113
+ this.pending = undefined
114
+ reject(error)
115
+ }
116
+ })
117
+
118
+ return {
119
+ completion,
120
+ commit: () => {
121
+ if (this.provisional?.token !== token || this.stopping || this.released) {
122
+ throw problem('invalidState', 'Camera switching was cancelled before commit')
123
+ }
124
+
125
+ this.native.confirmSwitch(camera.id)
126
+ this.provisional = undefined
127
+ },
128
+ cancel: () => {
129
+ if (this.pending?.token === token || this.provisional?.token === token) {
130
+ this.cancelSwitch()
131
+ }
132
+ },
133
+ }
134
+ }
135
+
136
+ private cancelSwitch(): void {
137
+ const pending = this.pending ?? this.provisional
138
+
139
+ this.pending = undefined
140
+ this.provisional = undefined
141
+ if (!pending) {
142
+ return
143
+ }
144
+
145
+ pending.reject(problem('invalidState', 'Camera switching was cancelled'))
146
+ try {
147
+ this.native.cancelSwitch()
148
+ } catch {
149
+ /* Stop/finalization retain ownership. */
150
+ }
151
+ }
152
+
153
+ stop(): void {
154
+ this.stopping = true
155
+ this.cancelSwitch()
156
+ this.native.stop()
157
+ }
158
+
159
+ release(): Promise<void> {
160
+ this.releasing ??= this.releaseNative()
161
+ return this.releasing
162
+ }
163
+
164
+ private async releaseNative(): Promise<void> {
165
+ this.released = true
166
+ this.epoch++
167
+ this.cancelSwitch()
168
+ await new Promise<void>((resolve) => this.native.releaseWithReply(resolve))
169
+ }
170
+ }