/
NextLevel.swift
3285 lines (2759 loc) · 120 KB
/
NextLevel.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// NextLevel.swift
// NextLevel (http://github.com/NextLevel/)
//
// Copyright (c) 2016-present patrick piemonte (http://patrickpiemonte.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import UIKit
import Foundation
import AVFoundation
import CoreImage
import CoreVideo
import Metal
#if USE_ARKIT
import ARKit
#endif
// MARK: - types
public enum NextLevelAuthorizationStatus: Int, CustomStringConvertible {
case notDetermined = 0
case notAuthorized
case authorized
public var description: String {
get {
switch self {
case .notDetermined:
return "Not Determined"
case .notAuthorized:
return "Not Authorized"
case .authorized:
return "Authorized"
}
}
}
}
public enum NextLevelDeviceType: Int, CustomStringConvertible {
case microphone = 0
case wideAngleCamera
case telephotoCamera
case duoCamera
case dualWideCamera
case ultraWideAngleCamera
case tripleCamera
#if USE_TRUE_DEPTH
case trueDepthCamera
#endif
public var avfoundationType: AVCaptureDevice.DeviceType {
switch self {
case .microphone:
return AVCaptureDevice.DeviceType.builtInMicrophone
case .telephotoCamera:
return AVCaptureDevice.DeviceType.builtInTelephotoCamera
case .wideAngleCamera:
return AVCaptureDevice.DeviceType.builtInWideAngleCamera
case .duoCamera:
return AVCaptureDevice.DeviceType.builtInDualCamera
#if USE_TRUE_DEPTH
case .trueDepthCamera:
return AVCaptureDevice.DeviceType.builtInTrueDepthCamera
#endif
case .dualWideCamera:
return AVCaptureDevice.DeviceType.builtInDualWideCamera
case .ultraWideAngleCamera:
return AVCaptureDevice.DeviceType.builtInUltraWideCamera
case .tripleCamera:
return AVCaptureDevice.DeviceType.builtInTripleCamera
}
}
public var description: String {
get {
switch self {
case .microphone:
return "Microphone"
case .wideAngleCamera:
return "Wide Angle Camera"
case .telephotoCamera:
return "Telephoto Camera"
case .duoCamera:
return "Duo Camera"
case .dualWideCamera:
return "Dual Wide Camera"
case .ultraWideAngleCamera:
return "Ultra Wide Angle Camera"
case .tripleCamera:
return "Triple Camera"
#if USE_TRUE_DEPTH
case .trueDepthCamera:
return "True Depth Camera"
#endif
}
}
}
}
/// Operation modes for NextLevel.
/// Note: video, audio, and videoWithoutAudio options support multi clip recording.
/// Movie is strictly for single clip recording.
public enum NextLevelCaptureMode: Int, CustomStringConvertible {
case video = 0
case photo
case audio
case videoWithoutAudio
case movie
case arKit
case arKitWithoutAudio
public var description: String {
get {
switch self {
case .video:
return "Video"
case .videoWithoutAudio:
return "Video without audio"
case .photo:
return "Photo"
case .audio:
return "Audio"
case .movie:
return "Movie"
case .arKit:
return "ARKit"
case .arKitWithoutAudio:
return "ARKit without Audio"
}
}
}
}
public typealias NextLevelDeviceOrientation = AVCaptureVideoOrientation
public typealias NextLevelDevicePosition = AVCaptureDevice.Position
public typealias NextLevelFocusMode = AVCaptureDevice.FocusMode
public typealias NextLevelExposureMode = AVCaptureDevice.ExposureMode
public typealias NextLevelWhiteBalanceMode = AVCaptureDevice.WhiteBalanceMode
public typealias NextLevelFlashMode = AVCaptureDevice.FlashMode
public typealias NextLevelTorchMode = AVCaptureDevice.TorchMode
public typealias NextLevelVideoStabilizationMode = AVCaptureVideoStabilizationMode
public enum NextLevelMirroringMode: Int, CustomStringConvertible {
case off = 0
case on
case auto
public var description: String {
get {
switch self {
case .off:
return "Off"
case .on:
return "On"
case .auto:
return "Auto"
}
}
}
}
// MARK: - error types
/// Error domain for all Next Level errors.
public let NextLevelErrorDomain = "NextLevelErrorDomain"
/// Error types.
public enum NextLevelError: Error, CustomStringConvertible {
case unknown
case started
case deviceNotAvailable
case authorization
case fileExists
case nothingRecorded
case notReadyToRecord
public var description: String {
get {
switch self {
case .unknown:
return "Unknown"
case .started:
return "NextLevel already started"
case .fileExists:
return "File exists"
case .authorization:
return "Authorization has not been requested"
case .deviceNotAvailable:
return "Device Not Available"
case .nothingRecorded:
return "Nothing recorded"
case .notReadyToRecord:
return "NextLevel is not ready to record"
}
}
}
}
private let NextLevelCaptureSessionQueueIdentifier = "engineering.NextLevel.CaptureSession"
private let NextLevelCaptureSessionQueueSpecificKey = DispatchSpecificKey<()>()
#if USE_TRUE_DEPTH
private let NextLevelDepthDataQueueIdentifier = "engineering.NextLevel.DepthData"
#endif
private let NextLevelRequiredMinimumStorageSpaceInBytes: UInt64 = 49999872 // ~47 MB
// MARK: - NextLevel state
/// ⬆️ NextLevel, Rad Media Capture in Swift (http://github.com/NextLevel)
public class NextLevel: NSObject {
// delegates
public weak var delegate: NextLevelDelegate?
public weak var previewDelegate: NextLevelPreviewDelegate?
public weak var deviceDelegate: NextLevelDeviceDelegate?
public weak var flashDelegate: NextLevelFlashAndTorchDelegate?
public weak var videoDelegate: NextLevelVideoDelegate?
public weak var photoDelegate: NextLevelPhotoDelegate?
#if USE_TRUE_DEPTH
public weak var depthDataDelegate: NextLevelDepthDataDelegate?
#endif
public weak var portraitEffectsMatteDelegate: NextLevelPortraitEffectsMatteDelegate?
public weak var metadataObjectsDelegate: NextLevelMetadataOutputObjectsDelegate?
// preview
/// Live camera preview, add as a sublayer to the UIView's primary layer.
public var previewLayer: AVCaptureVideoPreviewLayer
// capture configuration
/// Configuration for video
public var videoConfiguration: NextLevelVideoConfiguration
/// Configuration for audio
public var audioConfiguration: NextLevelAudioConfiguration
/// Configuration for photos
public var photoConfiguration: NextLevelPhotoConfiguration
/// Configuration property for augmented reality
public var arConfiguration: NextLevelARConfiguration? {
get {
self._arConfiguration as? NextLevelARConfiguration
}
}
// audio configuration
/// Indicates whether the capture session automatically changes settings in the app’s shared audio session. By default, is `true`.
public var automaticallyConfiguresApplicationAudioSession: Bool = true
// camera configuration
/// The current capture mode of the device.
public var captureMode: NextLevelCaptureMode = .video {
didSet {
guard
self.captureMode != oldValue
else {
return
}
self.delegate?.nextLevelCaptureModeWillChange(self)
self.executeClosureAsyncOnSessionQueueIfNecessary {
self.configureSession()
self.configureSessionDevices()
self.configureMetadataObjects()
self.updateVideoOrientation()
self.delegate?.nextLevelCaptureModeDidChange(self)
}
}
}
/// The current device position.
public var devicePosition: NextLevelDevicePosition = .back {
didSet {
self.executeClosureAsyncOnSessionQueueIfNecessary {
self.configureSessionDevices()
self.updateVideoOrientation()
}
}
}
/// When `true` actives device orientation updates
public var automaticallyUpdatesDeviceOrientation: Bool = false
/// The current orientation of the device.
public var deviceOrientation: NextLevelDeviceOrientation = .portrait {
didSet {
automaticallyUpdatesDeviceOrientation = false
_sessionQueue.sync {
updateVideoOrientation()
}
}
}
// stabilization
/// When `true`, enables photo capture stabilization.
public var photoStabilizationEnabled: Bool = false
/// Video stabilization mode
public var videoStabilizationMode: NextLevelVideoStabilizationMode = .auto {
didSet {
self.executeClosureAsyncOnSessionQueueIfNecessary {
self.beginConfiguration()
self.updateVideoOutputSettings()
self.commitConfiguration()
}
}
}
// depth data
/// When `true`, enables streaming depth data capture (use PhotoConfiguration for photos)
#if USE_TRUE_DEPTH
public var depthDataCaptureEnabled: Bool = false
#endif
// portrait effects matte data
/// When `true`, enables streaming of portrait effects matte data capture (use PhotoConfiguration for photos)
public var portraitEffectsMatteCaptureEnabled: Bool = false
/// Specifies types of metadata objects to detect
public var metadataObjectTypes: [AVMetadataObject.ObjectType]?
// state
/// Checks if the system is recording.
public var isRecording: Bool {
get {
self._recording
}
}
/// Checks if the current capture session is running
public var isRunning: Bool {
get {
switch self.captureMode {
#if USE_ARKIT
case .arKit:
return self._arRunning
case .arKitWithoutAudio:
return self._arRunning
#endif
default:
if let session = self._captureSession {
return session.isRunning
}
return false
}
}
}
/// The current recording session, a powerful means for modifying and editing previously recorded clips.
/// The session provides features such as 'undo'.
public var session: NextLevelSession? {
get {
self._recordingSession
}
}
/// Shared Core Image rendering context.
public var sharedCIContext: CIContext? {
set {
self._ciContext = newValue
}
get {
if self._ciContext == nil {
self._ciContext = CIContext.createDefaultCIContext()
}
return self._ciContext
}
}
// MARK: - private instance vars
internal var _sessionQueue: DispatchQueue
internal var _sessionConfigurationCount: Int = 0
internal var _recording: Bool = false
internal var _recordingSession: NextLevelSession?
internal var _lastVideoFrameTimeInterval: TimeInterval = 0
internal var _videoCustomContextRenderingEnabled: Bool = false
internal var _sessionVideoCustomContextImageBuffer: CVPixelBuffer?
// AVFoundation
internal var _captureSession: AVCaptureSession?
internal var _videoInput: AVCaptureDeviceInput?
internal var _audioInput: AVCaptureDeviceInput?
internal var _videoOutput: AVCaptureVideoDataOutput?
internal var _audioOutput: AVCaptureAudioDataOutput?
internal var _movieFileOutput: AVCaptureMovieFileOutput?
internal var _photoOutput: AVCapturePhotoOutput?
#if USE_TRUE_DEPTH
internal var _depthDataOutput: Any?
internal var depthDataOutput: AVCaptureDepthDataOutput? {
get {
self._depthDataOutput as? AVCaptureDepthDataOutput
}
set {
self._depthDataOutput = newValue
}
}
#endif
internal var _metadataOutput: AVCaptureMetadataOutput?
internal var _currentDevice: AVCaptureDevice?
internal var _requestedDevice: AVCaptureDevice?
internal var _observers = [NSKeyValueObservation]()
internal var _captureOutputObservers = [NSKeyValueObservation]()
internal var _lastVideoFrame: CMSampleBuffer?
internal var _lastAudioFrame: CMSampleBuffer?
internal var _ciContext: CIContext?
// ARKit
internal var _arRunning: Bool = false
internal var _arConfiguration: NextLevelConfiguration?
internal var _lastARFrame: CVPixelBuffer?
// MARK: - singleton
/// Method for providing a NextLevel singleton. This isn't required for use.
public static let shared = NextLevel()
// MARK: - object lifecycle
override public init() {
self.previewLayer = AVCaptureVideoPreviewLayer()
self.previewLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
self._sessionQueue = DispatchQueue(label: NextLevelCaptureSessionQueueIdentifier, qos: .userInteractive, target: DispatchQueue.global())
self._sessionQueue.setSpecific(key: NextLevelCaptureSessionQueueSpecificKey, value: ())
self.videoConfiguration = NextLevelVideoConfiguration()
self.audioConfiguration = NextLevelAudioConfiguration()
self.photoConfiguration = NextLevelPhotoConfiguration()
#if USE_ARKIT
self._arConfiguration = NextLevelARConfiguration()
#endif
super.init()
self.addApplicationObservers()
self.addSessionObservers()
self.addDeviceObservers()
}
deinit {
self.delegate = nil
self.previewDelegate = nil
self.deviceDelegate = nil
self.flashDelegate = nil
self.videoDelegate = nil
self.photoDelegate = nil
#if USE_TRUE_DEPTH
self.depthDataDelegate = nil
#endif
self.metadataObjectsDelegate = nil
self.removeApplicationObservers()
self.removeSessionObservers()
self.removeDeviceObservers()
if let session = self._captureSession {
self.beginConfiguration()
self.removeInputs(session: session)
self.removeOutputs(session: session)
self.commitConfiguration()
}
self.previewLayer.session = nil
self._currentDevice = nil
self._recordingSession = nil
self._captureSession = nil
self.sharedCIContext = nil
}
}
// MARK: - authorization
extension NextLevel {
/// Checks the current authorization status for the desired media type.
///
/// - Parameter mediaType: Specified media type (i.e. AVMediaTypeVideo, AVMediaTypeAudio, etc.)
/// - Returns: Authorization status for the desired media type.
public static func authorizationStatus(forMediaType mediaType: AVMediaType) -> NextLevelAuthorizationStatus {
let status = AVCaptureDevice.authorizationStatus(for: mediaType)
var nextLevelStatus: NextLevelAuthorizationStatus = .notDetermined
switch status {
case .denied, .restricted:
nextLevelStatus = .notAuthorized
break
case .authorized:
nextLevelStatus = .authorized
break
case .notDetermined:
break
@unknown default:
debugPrint("unknown authorization type")
break
}
return nextLevelStatus
}
/// Requests authorization permission.
///
/// - Parameters:
/// - mediaType: Specified media type (i.e. AVMediaTypeVideo, AVMediaTypeAudio, etc.)
/// - completionHandler: A block called with the responding access request result
public static func requestAuthorization(forMediaType mediaType: AVMediaType, completionHandler: @escaping ((AVMediaType, NextLevelAuthorizationStatus) -> Void) ) {
AVCaptureDevice.requestAccess(for: mediaType) { (granted: Bool) in
// According to documentation, requestAccess runs on an arbitary queue
DispatchQueue.main.async {
completionHandler(mediaType, (granted ? .authorized : .notAuthorized))
}
}
}
internal func authorizationStatusForCurrentCaptureMode() -> NextLevelAuthorizationStatus {
switch self.captureMode {
case .audio:
return NextLevel.authorizationStatus(forMediaType: AVMediaType.audio)
case .videoWithoutAudio:
return NextLevel.authorizationStatus(forMediaType: AVMediaType.video)
case .arKit:
let audioStatus = NextLevel.authorizationStatus(forMediaType: AVMediaType.audio)
let videoStatus = NextLevel.authorizationStatus(forMediaType: AVMediaType.video)
return (audioStatus == .authorized && videoStatus == .authorized) ? .authorized : .notAuthorized
case .arKitWithoutAudio:
return NextLevel.authorizationStatus(forMediaType: AVMediaType.video)
case .movie:
fallthrough
case .video:
let audioStatus = NextLevel.authorizationStatus(forMediaType: AVMediaType.audio)
let videoStatus = NextLevel.authorizationStatus(forMediaType: AVMediaType.video)
return (audioStatus == .authorized && videoStatus == .authorized) ? .authorized : .notAuthorized
case .photo:
return NextLevel.authorizationStatus(forMediaType: AVMediaType.video)
}
}
}
// MARK: - session start/stop
extension NextLevel {
/// Starts the current recording session.
///
/// - Throws: 'NextLevelError.authorization' when permissions are not authorized, 'NextLevelError.started' when the session has already started.
public func start() throws {
guard self.authorizationStatusForCurrentCaptureMode() == .authorized else {
throw NextLevelError.authorization
}
switch self.captureMode {
#if USE_ARKIT
case .arKit, .arKitWithoutAudio:
setupARSession()
#endif
default:
guard self._captureSession == nil else {
throw NextLevelError.started
}
setupAVSession()
}
}
/// Stops the current recording session.
public func stop() {
if let session = self._captureSession {
self.executeClosureAsyncOnSessionQueueIfNecessary {
if session.isRunning == true {
session.stopRunning()
}
self.beginConfiguration()
self.removeInputs(session: session)
self.removeOutputs(session: session)
self.commitConfiguration()
self._recordingSession = nil
self._captureSession = nil
self._currentDevice = nil
}
}
#if USE_ARKIT
if self.captureMode == .arKit || self.captureMode == .arKitWithoutAudio {
self.executeClosureAsyncOnSessionQueueIfNecessary {
self.arConfiguration?.session?.pause()
self._arRunning = false
self._recordingSession = nil
}
}
#endif
}
internal func setupAVSession() {
// Note: use nextLevelSessionDidStart to ensure a device and session are available for configuration or format changes
self.executeClosureAsyncOnSessionQueueIfNecessary {
// setup AV capture sesssion
self._captureSession = AVCaptureSession()
self._sessionConfigurationCount = 0
// setup NL recording session
self._recordingSession = NextLevelSession(queue: self._sessionQueue, queueKey: NextLevelCaptureSessionQueueSpecificKey)
if let session = self._captureSession {
session.automaticallyConfiguresApplicationAudioSession = self.automaticallyConfiguresApplicationAudioSession
self.beginConfiguration()
self.previewLayer.session = session
self.configureSession()
self.configureSessionDevices()
self.configureMetadataObjects()
self.updateVideoOrientation()
self.commitConfiguration()
if session.isRunning == false {
self.delegate?.nextLevelSessionWillStart(self)
session.startRunning()
self.previewDelegate?.nextLevelWillStartPreview(self)
// nextLevelSessionDidStart is called from AVFoundation
}
}
}
}
internal func setupARSession() {
#if USE_ARKIT
self.executeClosureAsyncOnSessionQueueIfNecessary {
guard let config = self.arConfiguration?.config,
let options = self.arConfiguration?.runOptions else {
return
}
if self._captureSession == nil {
self._captureSession = AVCaptureSession() // AV session is needed for device management and configuration
self._sessionConfigurationCount = 0
}
// setup NL recording session
if self._recordingSession == nil {
self._recordingSession = NextLevelSession(queue: self._sessionQueue, queueKey: NextLevelCaptureSessionQueueSpecificKey)
self.arConfiguration?.session?.delegateQueue = self._sessionQueue
}
if let session = self._captureSession {
session.automaticallyConfiguresApplicationAudioSession = self.automaticallyConfiguresApplicationAudioSession
self.beginConfiguration()
self.configureSession()
self.configureSessionDevices()
self.updateVideoOrientation()
self.commitConfiguration()
}
self.delegate?.nextLevelSessionWillStart(self)
self.arConfiguration?.session?.run(config, options: options)
self._arRunning = true
DispatchQueue.main.async {
self.delegate?.nextLevelSessionDidStart(self)
}
}
#endif
}
}
// MARK: - private session configuration support
extension NextLevel {
// re-entrant configuration lock, thanks to SCRecorder
internal func beginConfiguration() {
guard let session = self._captureSession else {
return
}
self._sessionConfigurationCount += 1
if self._sessionConfigurationCount == 1 {
session.beginConfiguration()
}
}
internal func commitConfiguration() {
guard let session = self._captureSession else {
return
}
self._sessionConfigurationCount -= 1
if self._sessionConfigurationCount == 0 {
session.commitConfiguration()
}
}
internal func configureSessionDevices() {
guard let _ = self._captureSession else {
return
}
self.beginConfiguration()
var shouldConfigureVideo = false
var shouldConfigureAudio = false
switch self.captureMode {
case .photo:
shouldConfigureVideo = true
break
case .audio:
shouldConfigureAudio = true
break
case .video:
shouldConfigureVideo = true
shouldConfigureAudio = true
break
case .videoWithoutAudio:
shouldConfigureVideo = true
break
case .movie:
// TODO
break
case .arKit:
shouldConfigureAudio = true
shouldConfigureVideo = true
break
case .arKitWithoutAudio:
shouldConfigureVideo = true
break
}
if shouldConfigureVideo == true {
var captureDevice: AVCaptureDevice?
if let requestedDevice = self._requestedDevice {
captureDevice = requestedDevice
} else if let videoDevice = AVCaptureDevice.primaryVideoDevice(forPosition: self.devicePosition) {
captureDevice = videoDevice
}
if let captureDevice = captureDevice {
if captureDevice != self._currentDevice {
self.configureDevice(captureDevice: captureDevice, mediaType: AVMediaType.video)
let changingPosition = (captureDevice.position != self._currentDevice?.position)
if changingPosition {
DispatchQueue.main.async {
self.deviceDelegate?.nextLevelDevicePositionWillChange(self)
}
}
self.willChangeValue(forKey: "currentDevice")
self._currentDevice = captureDevice
self.didChangeValue(forKey: "currentDevice")
self._requestedDevice = nil
if changingPosition {
DispatchQueue.main.async {
self.deviceDelegate?.nextLevelDevicePositionDidChange(self)
}
}
}
}
}
if shouldConfigureAudio {
if let audioDevice = AVCaptureDevice.audioDevice() {
self.configureDevice(captureDevice: audioDevice, mediaType: AVMediaType.audio)
}
}
self.commitConfiguration()
if shouldConfigureVideo {
DispatchQueue.main.async {
self.delegate?.nextLevel(self, didUpdateVideoConfiguration: self.videoConfiguration)
}
}
if shouldConfigureAudio {
DispatchQueue.main.async {
self.delegate?.nextLevel(self, didUpdateAudioConfiguration: self.audioConfiguration)
}
}
}
internal func configureSession() {
guard let session = self._captureSession else {
return
}
self.beginConfiguration()
// setup preset and mode
self.removeUnusedOutputsForCurrentCameraMode(session: session)
switch self.captureMode {
case .video:
fallthrough
case .videoWithoutAudio:
if session.sessionPreset != self.videoConfiguration.preset {
if session.canSetSessionPreset(self.videoConfiguration.preset) {
session.sessionPreset = self.videoConfiguration.preset
} else {
print("NextLevel, could not set preset on session")
}
}
if self.captureMode == .video {
_ = self.addAudioOuput()
}
_ = self.addVideoOutput()
#if USE_TRUE_DEPTH
if self.depthDataCaptureEnabled {
_ = self.addDepthDataOutput()
}
#endif
break
case .photo:
if session.sessionPreset != self.photoConfiguration.preset {
if session.canSetSessionPreset(self.photoConfiguration.preset) {
session.sessionPreset = self.photoConfiguration.preset
} else {
print("NextLevel, could not set preset on session")
}
}
_ = self.addPhotoOutput()
#if USE_TRUE_DEPTH
if self.depthDataCaptureEnabled {
_ = self.addDepthDataOutput()
// portrait effects matte needs depth to work
if self.portraitEffectsMatteCaptureEnabled {
_ = self.addPortraitEffectsMatteOutput()
}
}
#endif
break
case .audio:
_ = self.addAudioOuput()
break
case .movie:
// TODO
break
case .arKit, .arKitWithoutAudio:
// no AV inputs to setup
break
}
self.commitConfiguration()
}
private func configureMetadataObjects() {
guard let session = self._captureSession else {
return
}
guard let metadataObjectTypes = metadataObjectTypes,
metadataObjectTypes.count > 0 else {
return
}
if self._metadataOutput == nil {
self._metadataOutput = AVCaptureMetadataOutput()
}
guard let metadataOutput = self._metadataOutput else {
return
}
if !session.outputs.contains(metadataOutput),
session.canAddOutput(metadataOutput) {
session.addOutput(metadataOutput)
metadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
let availableTypes = metadataObjectTypes.filter { type in
metadataOutput.availableMetadataObjectTypes.contains(type)
}
metadataOutput.metadataObjectTypes = availableTypes
}
}
// inputs
private func configureDevice(captureDevice: AVCaptureDevice, mediaType: AVMediaType) {
if let session = self._captureSession,
let currentDeviceInput = AVCaptureDeviceInput.deviceInput(withMediaType: mediaType, captureSession: session) {
if currentDeviceInput.device == captureDevice {
return
}
}
if mediaType == AVMediaType.video {
do {
try captureDevice.lockForConfiguration()
if captureDevice.isFocusModeSupported(.continuousAutoFocus) {
captureDevice.focusMode = .continuousAutoFocus
if captureDevice.isSmoothAutoFocusSupported {
captureDevice.isSmoothAutoFocusEnabled = true
}
}
if captureDevice.isExposureModeSupported(.continuousAutoExposure) {
captureDevice.exposureMode = .continuousAutoExposure
}
if captureDevice.isWhiteBalanceModeSupported(.continuousAutoWhiteBalance) {
captureDevice.whiteBalanceMode = .continuousAutoWhiteBalance
}
captureDevice.isSubjectAreaChangeMonitoringEnabled = true
if captureDevice.isLowLightBoostSupported {
captureDevice.automaticallyEnablesLowLightBoostWhenAvailable = true
}
captureDevice.unlockForConfiguration()
} catch {
print("NextLevel, low light failed to lock device for configuration")
}
}
if let session = self._captureSession {
if let currentDeviceInput = AVCaptureDeviceInput.deviceInput(withMediaType: mediaType, captureSession: session) {
session.removeInput(currentDeviceInput)
if currentDeviceInput.device.hasMediaType(AVMediaType.video) {
self.removeCaptureDeviceObservers(currentDeviceInput.device)
}
}
_ = self.addInput(session: session, device: captureDevice)
}
}
private func addInput(session: AVCaptureSession, device: AVCaptureDevice) -> Bool {
do {
let input = try AVCaptureDeviceInput(device: device)
if session.canAddInput(input) {
session.addInput(input)
if input.device.hasMediaType(AVMediaType.video) {
self.addCaptureDeviceObservers(input.device)
self._videoInput = input
} else {
self._audioInput = input
}
return true
}
} catch {
print("NextLevel, failure adding input device")
}
return false
}