@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
@@ -0,0 +1,557 @@
1
+ import AVFoundation
2
+ import CoreImage
3
+ import QuartzCore
4
+
5
+ /// One writer and microphone timeline survive video-input replacement. All sample,
6
+ /// writer and switching state is confined to queue; replies cross to main.
7
+ @objc(XplatSwitchingMovieWriter)
8
+ @objcMembers
9
+ public final class XplatSwitchingMovieWriter: NSObject, AVCaptureVideoDataOutputSampleBufferDelegate, AVCaptureAudioDataOutputSampleBufferDelegate {
10
+ private let queue = DispatchQueue(label: "com.octanexplat.camera.movie")
11
+ private let video = AVCaptureVideoDataOutput()
12
+ private let audio = AVCaptureAudioDataOutput()
13
+ private let audioSession = AVCaptureSession()
14
+ private var audioObservers: [NSObjectProtocol] = []
15
+ private let context = CIContext(options: [.cacheIntermediates: false])
16
+ private weak var session: AVCaptureSession?
17
+ private var writer: AVAssetWriter?
18
+ private var videoWriter: AVAssetWriterInput?
19
+ private var audioWriter: AVAssetWriterInput?
20
+ private var pixels: AVAssetWriterInputPixelBufferAdaptor?
21
+ private var lastFrame: CVPixelBuffer?
22
+ private var origin: CMTime?
23
+ private var lastVideo = CMTime.invalid
24
+ private var lastAudio = CMTime.invalid
25
+ private var lastHost = CMTime.invalid
26
+ private var timer: DispatchSourceTimer?
27
+ private var notify: ((String, String) -> Void)?
28
+ private var sourceObserver: ((Bool) -> Void)?
29
+ private weak var previewLayer: AVCaptureVideoPreviewLayer?
30
+ private let overlay = CALayer()
31
+ private var overlayEpoch = 0 // main queue only
32
+ private var releaseReplies: [() -> Void] = []
33
+ private var previousInput: AVCaptureDeviceInput?
34
+ private var unacknowledgedInput: AVCaptureDeviceInput?
35
+ private var restoringPreview = false
36
+ private var rollingBack = false
37
+ private var switchProblem: String?
38
+ private var sourceReady = false
39
+ private var sourcePrepared = true
40
+ private var sourceEpoch = 0
41
+ private var takeEpoch = 0
42
+ private let elapsedLock = NSLock()
43
+ private var publishedElapsed = 0.0
44
+ private var switchReply: ((String?) -> Void)?
45
+ private var requestedAudio = false
46
+ private var stopping = false
47
+ private var ownsOutput = false
48
+ private var released = false
49
+ private var limit: Double = 0
50
+ private var path = ""
51
+ private var width = 0
52
+ private var height = 0
53
+ private var warning: String?
54
+ private var outputFrames = 0
55
+ private var heldFrames = 0
56
+ private var audioBuffers = 0
57
+ private var audioFirstTime = CMTime.invalid
58
+ private var audioInputDuration: Double = 0
59
+ private var maxAudioInputGap: Double = 0
60
+ private var switching = false
61
+ private var switchEpoch = 0
62
+ private var elapsed: Double = 0
63
+ private var orientation: AVCaptureVideoOrientation = .portrait
64
+ private var expectedCameraID: String?
65
+
66
+ @objc(install:)
67
+ public func install(_ session: AVCaptureSession) -> String? {
68
+ guard session.canAddOutput(video), audioSession.canAddOutput(audio) else { return "Sample outputs are unavailable" }
69
+ video.videoSettings = [kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA]
70
+ video.alwaysDiscardsLateVideoFrames = true
71
+ video.setSampleBufferDelegate(self, queue: queue)
72
+ audio.setSampleBufferDelegate(self, queue: queue)
73
+ session.addOutput(video)
74
+ applyConnection(orientation)
75
+ audioSession.addOutput(audio)
76
+ // Video input changes must not reconfigure the application's microphone.
77
+ session.usesApplicationAudioSession = false
78
+ for name in [NSNotification.Name.AVCaptureSessionWasInterrupted, .AVCaptureSessionRuntimeError] {
79
+ audioObservers.append(NotificationCenter.default.addObserver(forName: name, object: audioSession, queue: nil) { [weak self] notification in
80
+ self?.queue.async { [weak self] in
81
+ guard let self, self.writer != nil, !self.stopping, !self.released else { return }
82
+ self.warning = (notification.userInfo?[AVCaptureSessionErrorKey] as? NSError)?.localizedDescription ?? "Microphone capture interrupted"
83
+ self.emit("sourceLost", self.warning!); self.finish()
84
+ }
85
+ })
86
+ }
87
+ self.session = session
88
+ return nil
89
+ }
90
+
91
+ /// Called on main, like the owning video session's configuration transactions.
92
+ @objc(configureAudio:)
93
+ public func configureAudio(_ enabled: Bool) -> String? {
94
+ guard queue.sync(execute: { writer == nil && !released }) else { return "Audio configuration requires an idle writer" }
95
+ if !enabled {
96
+ audioSession.stopRunning()
97
+ for input in audioSession.inputs { audioSession.removeInput(input) }
98
+ return nil
99
+ }
100
+ do {
101
+ if audioSession.inputs.isEmpty {
102
+ guard let microphone = AVCaptureDevice.default(for: .audio) else { return "Microphone is unavailable" }
103
+ let input = try AVCaptureDeviceInput(device: microphone)
104
+ guard audioSession.canAddInput(input) else { return "Microphone input is incompatible" }
105
+ audioSession.addInput(input)
106
+ }
107
+ if !audioSession.isRunning { audioSession.startRunning() }
108
+ return audioSession.isRunning && !audioSession.isInterrupted ? nil : "Microphone capture is unavailable"
109
+ } catch { return error.localizedDescription }
110
+ }
111
+
112
+ @objc(start:audio:orientation:maximumDurationMs:reply:)
113
+ public func start(_ path: String, audio: Bool, orientation: Int, maximumDurationMs: Double, reply: @escaping (String, String) -> Void) {
114
+ queue.async {
115
+ guard self.writer == nil, !self.released, self.sourceReady else { DispatchQueue.main.async { reply("failed", "Recorder is busy or its source is unavailable") }; return }
116
+ if audio && self.session != nil && (!self.audioSession.isRunning || self.audioSession.isInterrupted) {
117
+ DispatchQueue.main.async { reply("failed", "Microphone capture is unavailable") }; return
118
+ }
119
+ self.path = path
120
+ self.requestedAudio = audio
121
+ self.notify = reply
122
+ self.stopping = false
123
+ self.ownsOutput = false
124
+ self.warning = nil
125
+ self.origin = nil
126
+ self.lastFrame = nil
127
+ self.lastVideo = .invalid
128
+ self.lastAudio = .invalid
129
+ self.elapsed = 0
130
+ self.publishElapsed()
131
+ self.takeEpoch += 1
132
+ self.outputFrames = 0
133
+ self.heldFrames = 0
134
+ self.audioBuffers = 0
135
+ self.audioFirstTime = .invalid; self.audioInputDuration = 0; self.maxAudioInputGap = 0
136
+ self.limit = maximumDurationMs / 1000
137
+ self.orientation = AVCaptureVideoOrientation(rawValue: orientation) ?? .portrait
138
+ self.expectedCameraID = self.session?.inputs.compactMap { $0 as? AVCaptureDeviceInput }.first { $0.device.hasMediaType(.video) }?.device.uniqueID
139
+ if let connection = self.video.connection(with: .video), let value = AVCaptureVideoOrientation(rawValue: orientation), connection.isVideoOrientationSupported, connection.videoOrientation != value { connection.videoOrientation = value }
140
+ let preparationEpoch = self.takeEpoch
141
+ let selectedOrientation = self.orientation
142
+ DispatchQueue.main.async {
143
+ guard self.queue.sync(execute: { self.takeEpoch == preparationEpoch && !self.released }) else { return }
144
+ if let connection = self.previewLayer?.connection, connection.isVideoOrientationSupported, connection.videoOrientation != selectedOrientation { connection.videoOrientation = selectedOrientation }
145
+ }
146
+ do { self.writer = try AVAssetWriter(outputURL: URL(fileURLWithPath: path), fileType: .mov) }
147
+ catch { self.terminal("failed", error.localizedDescription) }
148
+ let epoch = self.takeEpoch
149
+ self.queue.asyncAfter(deadline: .now() + 15) { [weak self] in
150
+ guard let self else { return }
151
+ if self.takeEpoch == epoch && self.writer != nil && self.outputFrames == 0 && !self.stopping {
152
+ self.warning = "No video frame arrived before timeout"; self.finish()
153
+ }
154
+ }
155
+ }
156
+ }
157
+
158
+ private func emit(_ type: String, _ payload: String) {
159
+ guard let notify else { return }
160
+ DispatchQueue.main.async { notify(type, payload) }
161
+ }
162
+
163
+ private func begin(_ buffer: CVPixelBuffer, _ time: CMTime) throws {
164
+ guard let writer else { return }
165
+ width = CVPixelBufferGetWidth(buffer)
166
+ height = CVPixelBufferGetHeight(buffer)
167
+ let input = AVAssetWriterInput(mediaType: .video, outputSettings: [
168
+ AVVideoCodecKey: AVVideoCodecType.h264, AVVideoWidthKey: width, AVVideoHeightKey: height,
169
+ AVVideoCompressionPropertiesKey: [AVVideoAverageBitRateKey: 6_000_000, AVVideoExpectedSourceFrameRateKey: 30, AVVideoAllowFrameReorderingKey: false],
170
+ ])
171
+ input.expectsMediaDataInRealTime = true
172
+ guard writer.canAdd(input) else { throw failure("Video encoding is unavailable") }
173
+ writer.add(input)
174
+ videoWriter = input
175
+ pixels = AVAssetWriterInputPixelBufferAdaptor(assetWriterInput: input, sourcePixelBufferAttributes: [
176
+ kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA,
177
+ kCVPixelBufferWidthKey as String: width, kCVPixelBufferHeightKey as String: height,
178
+ kCVPixelBufferIOSurfacePropertiesKey as String: [:],
179
+ ])
180
+ if requestedAudio {
181
+ let sound = AVAssetWriterInput(mediaType: .audio, outputSettings: [
182
+ AVFormatIDKey: kAudioFormatMPEG4AAC, AVSampleRateKey: 48_000, AVNumberOfChannelsKey: 1, AVEncoderBitRateKey: 128_000,
183
+ ])
184
+ sound.expectsMediaDataInRealTime = true
185
+ guard writer.canAdd(sound) else { throw failure("Audio encoding is unavailable") }
186
+ writer.add(sound)
187
+ audioWriter = sound
188
+ }
189
+ guard writer.startWriting() else { throw writer.error ?? failure("Cannot begin writing") }
190
+ ownsOutput = true
191
+ writer.startSession(atSourceTime: time)
192
+ origin = time
193
+ let pulse = DispatchSource.makeTimerSource(queue: queue)
194
+ pulse.schedule(deadline: .now() + .milliseconds(33), repeating: .milliseconds(33))
195
+ pulse.setEventHandler { [weak self] in self?.holdFrame() }
196
+ timer = pulse
197
+ pulse.resume()
198
+ }
199
+
200
+ private func failure(_ message: String) -> NSError { NSError(domain: "OctaneCamera", code: 1, userInfo: [NSLocalizedDescriptionKey: message]) }
201
+
202
+ private func normalize(_ buffer: CVPixelBuffer) throws -> CVPixelBuffer {
203
+ guard let pool = pixels?.pixelBufferPool else { throw failure("Pixel buffer pool is unavailable") }
204
+ var target: CVPixelBuffer?
205
+ guard CVPixelBufferPoolCreatePixelBuffer(nil, pool, &target) == kCVReturnSuccess, let target else { throw failure("Cannot allocate video frame") }
206
+ let image = CIImage(cvPixelBuffer: buffer)
207
+ let scale = max(CGFloat(width) / image.extent.width, CGFloat(height) / image.extent.height)
208
+ let resized = image.transformed(by: CGAffineTransform(scaleX: scale, y: scale))
209
+ let positioned = resized.transformed(by: CGAffineTransform(translationX: (CGFloat(width) - resized.extent.width) / 2, y: (CGFloat(height) - resized.extent.height) / 2))
210
+ context.render(positioned, to: target, bounds: CGRect(x: 0, y: 0, width: width, height: height), colorSpace: CGColorSpaceCreateDeviceRGB())
211
+ return target
212
+ }
213
+
214
+ private func appendVideo(_ frame: CVPixelBuffer, _ time: CMTime, held: Bool) -> Bool {
215
+ guard let input = videoWriter, let pixels, !stopping else { return false }
216
+ if lastVideo.isValid && time <= lastVideo { return false }
217
+ guard input.isReadyForMoreMediaData else { return false } // Video may drop; audio must not.
218
+ guard pixels.append(frame, withPresentationTime: time) else { warning = writer?.error?.localizedDescription ?? "Video append failed"; finish(); return false }
219
+ lastVideo = time
220
+ lastHost = CMClockGetTime(CMClockGetHostTimeClock())
221
+ lastFrame = frame
222
+ outputFrames += 1
223
+ if held { heldFrames += 1 }
224
+ if let origin { elapsed = max(elapsed, CMTimeGetSeconds(time - origin)); publishElapsed() }
225
+ return true
226
+ }
227
+
228
+ private func holdFrame() {
229
+ guard switching || restoringPreview, !stopping, let frame = lastFrame, lastVideo.isValid else { return }
230
+ let time = requestedAudio ? lastAudio : lastVideo + (CMClockGetTime(CMClockGetHostTimeClock()) - lastHost)
231
+ if time.isValid && CMTimeGetSeconds(time - lastVideo) >= 1.0 / 30 { _ = appendVideo(frame, time, held: true) }
232
+ checkLimit()
233
+ }
234
+
235
+ public func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
236
+ if output === video {
237
+ guard sourcePrepared else { return }
238
+ if let expectedCameraID, !connection.inputPorts.contains(where: { ($0.input as? AVCaptureDeviceInput)?.device.uniqueID == expectedCameraID }) { return }
239
+ setSourceReady(true)
240
+ if restoringPreview { restoringPreview = false; removeOverlay() }
241
+ }
242
+ if output === audio, let session {
243
+ do {
244
+ var timing = CMSampleTimingInfo()
245
+ guard CMSampleBufferGetSampleTimingInfo(sampleBuffer, at: 0, timingInfoOut: &timing) == noErr else { throw failure("Cannot read microphone timing") }
246
+ let from = audioSession.synchronizationClock ?? CMClockGetHostTimeClock()
247
+ let to = session.synchronizationClock ?? CMClockGetHostTimeClock()
248
+ timing.presentationTimeStamp = CMSyncConvertTime(timing.presentationTimeStamp, from: from, to: to)
249
+ if timing.decodeTimeStamp.isValid { timing.decodeTimeStamp = CMSyncConvertTime(timing.decodeTimeStamp, from: from, to: to) }
250
+ var synchronized: CMSampleBuffer?
251
+ guard CMSampleBufferCreateCopyWithNewTiming(allocator: nil, sampleBuffer: sampleBuffer, sampleTimingEntryCount: 1, sampleTimingArray: &timing, sampleBufferOut: &synchronized) == noErr, let synchronized else { throw failure("Cannot synchronize microphone timing") }
252
+ consume(synchronized, isVideo: false)
253
+ } catch { if writer != nil { warning = error.localizedDescription; emit("sourceLost", warning!); finish() } }
254
+ } else { consume(sampleBuffer, isVideo: output === video) }
255
+ }
256
+
257
+ private func consume(_ sampleBuffer: CMSampleBuffer, isVideo: Bool) {
258
+ guard writer != nil, !stopping else { return }
259
+ if writer?.status == .failed || writer?.status == .cancelled { warning = writer?.error?.localizedDescription ?? "Movie writer became unavailable"; finish(); return }
260
+ let time = CMSampleBufferGetPresentationTimeStamp(sampleBuffer)
261
+ if isVideo {
262
+ guard let buffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return }
263
+ let portrait = orientation == .portrait || orientation == .portraitUpsideDown
264
+ if portrait && CVPixelBufferGetWidth(buffer) > CVPixelBufferGetHeight(buffer) { return }
265
+ if !portrait && CVPixelBufferGetHeight(buffer) > CVPixelBufferGetWidth(buffer) { return }
266
+ do {
267
+ if origin == nil { try begin(buffer, time) }
268
+ guard let origin, time >= origin else { return }
269
+ guard videoWriter?.isReadyForMoreMediaData == true else { return }
270
+ if appendVideo(try normalize(buffer), time, held: false) {
271
+ if outputFrames == 1 { emit("started", "{\"width\":\(width),\"height\":\(height)}") }
272
+ if switching, let reply = switchReply {
273
+ let problem = rollingBack ? switchProblem : nil
274
+ completeSwitch(problem, reply: reply)
275
+ }
276
+ }
277
+ } catch { warning = error.localizedDescription; finish() }
278
+ } else if requestedAudio, let origin, time >= origin, let input = audioWriter {
279
+ // A missing microphone interval cannot be repaired by the encoder:
280
+ // it may concatenate packets and hide the gap. Preserve a partial
281
+ // take with a diagnostic rather than silently compress its audio time.
282
+ if lastAudio.isValid && CMTimeGetSeconds(time - lastAudio) > 0.005 {
283
+ maxAudioInputGap = max(maxAudioInputGap, CMTimeGetSeconds(time - lastAudio))
284
+ warning = "Microphone timestamp gap; captured content was finalized"
285
+ emit("sourceLost", warning!); finish(); return
286
+ }
287
+ guard input.isReadyForMoreMediaData, input.append(sampleBuffer) else {
288
+ warning = writer?.error?.localizedDescription ?? "Audio encoder backpressure"; finish(); return
289
+ }
290
+ if !audioFirstTime.isValid { audioFirstTime = time }
291
+ if lastAudio.isValid { maxAudioInputGap = max(maxAudioInputGap, CMTimeGetSeconds(time - lastAudio)) }
292
+ audioBuffers += 1
293
+ let duration = CMSampleBufferGetDuration(sampleBuffer)
294
+ let sampleDuration = duration.isValid ? duration : CMTime(value: 1024, timescale: 48000)
295
+ audioInputDuration += CMTimeGetSeconds(sampleDuration)
296
+ lastAudio = time + sampleDuration
297
+ elapsed = max(elapsed, CMTimeGetSeconds(lastAudio - origin))
298
+ publishElapsed()
299
+ holdFrame()
300
+ }
301
+ checkLimit()
302
+ }
303
+
304
+ private func checkLimit() { if !stopping && limit > 0 && elapsed >= limit { emit("limit", ""); finish() } }
305
+
306
+ @objc(observeSource:)
307
+ public func observeSource(_ observer: @escaping (Bool) -> Void) {
308
+ queue.async { self.sourceObserver = observer; self.sendSourceReady() }
309
+ }
310
+ @objc(setPreviewLayer:)
311
+ public func setPreviewLayer(_ layer: AVCaptureVideoPreviewLayer?) {
312
+ queue.async { self.previewLayer = layer }
313
+ DispatchQueue.main.async {
314
+ if self.overlay.superlayer != nil, let layer { self.overlay.frame = layer.frame }
315
+ }
316
+ }
317
+ @objc(expectCamera:)
318
+ public func expectCamera(_ id: String) {
319
+ queue.async {
320
+ self.sourceEpoch += 1
321
+ let epoch = self.sourceEpoch
322
+ self.expectedCameraID = id; self.sourcePrepared = false; self.setSourceReady(false)
323
+ let orientation = self.orientation
324
+ DispatchQueue.main.async {
325
+ guard self.queue.sync(execute: { self.sourceEpoch == epoch }) else { return }
326
+ self.applyConnection(orientation)
327
+ self.queue.async { if self.sourceEpoch == epoch { self.sourcePrepared = true } }
328
+ }
329
+ }
330
+ }
331
+ private func sendSourceReady() {
332
+ let value = sourceReady
333
+ let epoch = sourceEpoch
334
+ guard let observer = sourceObserver else { return }
335
+ DispatchQueue.main.async {
336
+ guard self.queue.sync(execute: { self.sourceEpoch == epoch && self.sourceReady == value }) else { return }
337
+ observer(value)
338
+ }
339
+ }
340
+ private func setSourceReady(_ ready: Bool) {
341
+ if sourceReady != ready { sourceReady = ready; sendSourceReady() }
342
+ }
343
+ private func publishElapsed() {
344
+ elapsedLock.lock(); publishedElapsed = elapsed * 1000; elapsedLock.unlock()
345
+ }
346
+ private func applyConnection(_ orientation: AVCaptureVideoOrientation) {
347
+ if let connection = video.connection(with: .video) {
348
+ connection.automaticallyAdjustsVideoMirroring = false
349
+ if connection.isVideoMirroringSupported { connection.isVideoMirrored = false }
350
+ if connection.isVideoOrientationSupported { connection.videoOrientation = orientation }
351
+ }
352
+ if let connection = previewLayer?.connection, connection.isVideoOrientationSupported { connection.videoOrientation = orientation }
353
+ }
354
+ private func removeOverlay(_ epoch: Int? = nil) {
355
+ DispatchQueue.main.async {
356
+ if let epoch, self.overlayEpoch != epoch { return }
357
+ self.overlay.removeFromSuperlayer(); self.overlay.contents = nil
358
+ }
359
+ }
360
+ private func completeSwitch(_ problem: String?, reply: ((String?) -> Void)? = nil, keepOverlay: Bool = false) {
361
+ let callback = reply ?? switchReply
362
+ let epoch = switchEpoch
363
+ unacknowledgedInput = problem == nil ? previousInput : nil
364
+ switchEpoch += 1; switching = false; rollingBack = false
365
+ switchReply = nil; previousInput = nil; switchProblem = nil
366
+ DispatchQueue.main.async {
367
+ if problem != nil && !keepOverlay && self.overlayEpoch == epoch { self.overlay.removeFromSuperlayer(); self.overlay.contents = nil }
368
+ callback?(problem)
369
+ }
370
+ }
371
+ /// Session transactions run away from the sample queue. Audio callbacks and
372
+ /// held-frame writes must remain serviceable while AVFoundation reconfigures.
373
+ private func exchangeInput(_ input: AVCaptureDeviceInput, completion: @escaping (Bool) -> Void) {
374
+ guard let session else { completion(false); return }
375
+ sourceEpoch += 1
376
+ let epoch = sourceEpoch
377
+ let orientation = self.orientation
378
+ expectedCameraID = input.device.uniqueID
379
+ sourcePrepared = false; setSourceReady(false)
380
+ DispatchQueue.main.async {
381
+ guard self.queue.sync(execute: { self.sourceEpoch == epoch }) else { return }
382
+ session.beginConfiguration()
383
+ for old in session.inputs.compactMap({ $0 as? AVCaptureDeviceInput }) where old.device.hasMediaType(.video) { session.removeInput(old) }
384
+ let possible = session.canAddInput(input)
385
+ if possible { session.addInput(input) }
386
+ session.commitConfiguration()
387
+ self.applyConnection(orientation)
388
+ self.queue.async {
389
+ guard self.sourceEpoch == epoch else { return }
390
+ self.sourcePrepared = possible
391
+ completion(possible)
392
+ }
393
+ }
394
+ }
395
+
396
+ private func armSwitchTimeout() {
397
+ let epoch = switchEpoch
398
+ queue.asyncAfter(deadline: .now() + 5) { [weak self] in
399
+ guard let self, self.switching, self.switchEpoch == epoch else { return }
400
+ self.failSwitch("Camera did not deliver a frame before timeout")
401
+ }
402
+ }
403
+ private func failSwitch(_ problem: String) {
404
+ guard switching else { return }
405
+ if rollingBack || previousInput == nil {
406
+ sourcePrepared = false; setSourceReady(false)
407
+ warning = "Camera switch and rollback failed: \(problem)"
408
+ completeSwitch(problem)
409
+ emit("sourceLost", warning ?? problem)
410
+ finish()
411
+ return
412
+ }
413
+ rollingBack = true; switchProblem = problem; switchEpoch += 1
414
+ exchangeInput(previousInput!) { possible in
415
+ guard self.switching, self.rollingBack else { return }
416
+ if possible { self.armSwitchTimeout() } else { self.failSwitch("Previous camera input is unavailable") }
417
+ }
418
+ }
419
+ @objc(switchTo:reply:)
420
+ public func switchTo(_ id: String, reply: @escaping (String?) -> Void) {
421
+ queue.async {
422
+ guard !self.stopping, self.writer != nil, self.origin != nil, !self.switching, self.unacknowledgedInput == nil, self.sourceReady,
423
+ let previous = self.session?.inputs.compactMap({ $0 as? AVCaptureDeviceInput }).first(where: { $0.device.hasMediaType(.video) }),
424
+ let device = AVCaptureDevice(uniqueID: id), let frame = self.lastFrame else {
425
+ DispatchQueue.main.async { reply("Switch is unavailable") }; return
426
+ }
427
+ do {
428
+ let next = try AVCaptureDeviceInput(device: device)
429
+ guard let image = self.context.createCGImage(CIImage(cvPixelBuffer: frame), from: CGRect(x: 0, y: 0, width: self.width, height: self.height)) else {
430
+ DispatchQueue.main.async { reply("The last preview frame is unavailable") }; return
431
+ }
432
+ self.switchEpoch += 1
433
+ let epoch = self.switchEpoch
434
+ self.switching = true; self.switchReply = reply; self.previousInput = previous
435
+ self.sourcePrepared = false; self.setSourceReady(false)
436
+ self.rollingBack = false; self.switchProblem = nil
437
+ // Install the hold on main before disturbing the preview connection.
438
+ // Never synchronously wait for main from the sample queue.
439
+ DispatchQueue.main.async {
440
+ guard self.queue.sync(execute: { self.switching && self.switchEpoch == epoch && !self.stopping }) else { return }
441
+ self.overlayEpoch = epoch
442
+ if let layer = self.previewLayer, let parent = layer.superlayer {
443
+ self.overlay.frame = layer.frame; self.overlay.contentsGravity = .resizeAspectFill
444
+ self.overlay.contents = image
445
+ self.overlay.setAffineTransform(CGAffineTransform(scaleX: layer.connection?.isVideoMirrored == true ? -1 : 1, y: 1))
446
+ parent.addSublayer(self.overlay)
447
+ }
448
+ self.queue.async {
449
+ guard self.switching, self.switchEpoch == epoch, !self.stopping else { self.removeOverlay(epoch); return }
450
+ self.exchangeInput(next) { possible in
451
+ guard self.switching, self.switchEpoch == epoch else { return }
452
+ if possible { self.armSwitchTimeout() } else { self.failSwitch("Camera input is incompatible") }
453
+ }
454
+ }
455
+ }
456
+ } catch { DispatchQueue.main.async { reply(error.localizedDescription) } }
457
+ }
458
+ }
459
+ private func cancelSwitchInternal(_ message: String) {
460
+ guard switching || unacknowledgedInput != nil else { return }
461
+ let previous = previousInput ?? unacknowledgedInput
462
+ restoringPreview = true
463
+ if switching { completeSwitch(message, keepOverlay: true) }
464
+ unacknowledgedInput = nil
465
+ if let previous {
466
+ exchangeInput(previous) { possible in
467
+ let epoch = self.sourceEpoch
468
+ self.queue.asyncAfter(deadline: .now() + 5) { [weak self] in
469
+ guard let self, self.sourceEpoch == epoch, self.restoringPreview, !self.released else { return }
470
+ self.restoringPreview = false; self.removeOverlay()
471
+ self.warning = "Camera did not recover after cancellation"
472
+ self.emit("sourceLost", self.warning!); self.finish()
473
+ }
474
+ if !possible { self.restoringPreview = false; self.removeOverlay(); self.warning = "Cannot restore camera after cancellation"; self.emit("sourceLost", self.warning!); self.finish() }
475
+ }
476
+ }
477
+ }
478
+ /// Physical acquisition precedes the JS operation's commit. Until this
479
+ /// acknowledgement, stop must still be able to restore the previous source.
480
+ @objc(confirmSwitch:)
481
+ public func confirmSwitch(_ id: String) {
482
+ queue.async { if self.expectedCameraID == id { self.unacknowledgedInput = nil; self.removeOverlay() } }
483
+ }
484
+ @objc public func cancelSwitch() { queue.async { self.cancelSwitchInternal("Camera switching was cancelled") } }
485
+ @objc public func stop() { queue.async { self.finish() } }
486
+ @objc public func elapsedMs() -> Double {
487
+ elapsedLock.lock(); defer { elapsedLock.unlock() }; return publishedElapsed
488
+ }
489
+ @objc(releaseWithReply:)
490
+ public func releaseWithReply(_ reply: @escaping () -> Void) {
491
+ queue.async {
492
+ self.releaseReplies.append(reply)
493
+ if self.writer != nil { self.finish() } else { self.finishRelease() }
494
+ }
495
+ }
496
+ private func finishRelease() {
497
+ guard !releaseReplies.isEmpty else { return }
498
+ sourceEpoch += 1; switchEpoch += 1; sourcePrepared = false; released = true; sourceReady = false
499
+ timer?.cancel(); timer = nil
500
+ video.setSampleBufferDelegate(nil, queue: nil)
501
+ audio.setSampleBufferDelegate(nil, queue: nil)
502
+ sourceObserver = nil; previewLayer = nil; removeOverlay()
503
+ let replies = releaseReplies; releaseReplies = []
504
+ DispatchQueue.main.async {
505
+ self.audioSession.stopRunning()
506
+ for observer in self.audioObservers { NotificationCenter.default.removeObserver(observer) }
507
+ self.audioObservers = []
508
+ for reply in replies { reply() }
509
+ }
510
+ }
511
+
512
+ private func finish() {
513
+ guard let writer, !stopping else { return }
514
+ stopping = true
515
+ cancelSwitchInternal("Recording is finalizing")
516
+ timer?.cancel(); timer = nil
517
+ emit("finishing", warning == nil ? "" : "captureError")
518
+ guard origin != nil, writer.status == .writing else {
519
+ if !ownsOutput { writer.cancelWriting() }; terminal("failed", warning ?? writer.error?.localizedDescription ?? "No video frames were captured"); return
520
+ }
521
+ videoWriter?.markAsFinished()
522
+ audioWriter?.markAsFinished()
523
+ let epoch = takeEpoch
524
+ queue.asyncAfter(deadline: .now() + 30) { [weak self, weak writer] in
525
+ guard let self, let writer else { return }
526
+ if self.takeEpoch == epoch && self.writer === writer {
527
+ self.terminal("failed", "Movie finalization timed out; output bytes may be incomplete")
528
+ }
529
+ }
530
+ let summary: [String: Any] = ["path": path, "frames": outputFrames, "heldFrames": heldFrames, "audioBuffers": audioBuffers, "audioInputDurationMs": audioInputDuration * 1000, "maxAudioInputGapMs": maxAudioInputGap * 1000, "audioFirstOffsetMs": audioFirstTime.isValid ? CMTimeGetSeconds(audioFirstTime - origin!) * 1000 : 0, "audioLastOffsetMs": lastAudio.isValid ? CMTimeGetSeconds(lastAudio - origin!) * 1000 : 0, "elapsedMs": elapsed * 1000, "warning": warning ?? ""]
531
+ writer.finishWriting { [weak self, weak writer] in
532
+ guard let self, let writer else { return }
533
+ self.queue.async {
534
+ guard self.takeEpoch == epoch, self.writer === writer else { return }
535
+ if writer.status == .completed && self.outputFrames > 0 {
536
+ let data = (try? JSONSerialization.data(withJSONObject: summary)) ?? Data()
537
+ self.terminal("finished", String(data: data, encoding: .utf8) ?? "{}")
538
+ } else { self.terminal("failed", writer.error?.localizedDescription ?? (self.outputFrames == 0 ? "No video frames were captured" : "Movie finalization failed")) }
539
+ }
540
+ }
541
+ }
542
+
543
+ private func terminal(_ type: String, _ payload: String) {
544
+ let reply = notify
545
+ let message: String
546
+ if type == "failed", let data = try? JSONSerialization.data(withJSONObject: ["message": payload, "ownsOutput": ownsOutput, "hasVideo": outputFrames > 0, "canInspectOutput": writer?.status == .completed || writer?.status == .failed]) { message = String(data: data, encoding: .utf8) ?? payload }
547
+ else { message = payload }
548
+ clear()
549
+ DispatchQueue.main.async { reply?(type, message) }
550
+ finishRelease()
551
+ }
552
+
553
+ private func clear() {
554
+ writer = nil; videoWriter = nil; audioWriter = nil; pixels = nil; lastFrame = nil; notify = nil; origin = nil
555
+ }
556
+
557
+ }