-
Notifications
You must be signed in to change notification settings - Fork 1
/
AVCaptureDevice+Extension.swift
96 lines (85 loc) · 3.29 KB
/
AVCaptureDevice+Extension.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
//
// AVCaptureDevice+Extension.swift
//
// Created by Shuichi Tsutsumi on 4/3/16.
// Copyright © 2016 Shuichi Tsutsumi. All rights reserved.
//
import AVFoundation
extension AVCaptureDevice {
private func availableFormatsFor(preferredFps: Float64) -> [AVCaptureDeviceFormat] {
guard let allFormats = formats as? [AVCaptureDeviceFormat] else {
return []
}
var availableFormats: [AVCaptureDeviceFormat] = []
for format in allFormats
{
guard let ranges = format.videoSupportedFrameRateRanges as? [AVFrameRateRange] else {
continue
}
for range in ranges where range.minFrameRate <= preferredFps && preferredFps <= range.maxFrameRate
{
availableFormats.append(format)
}
}
return availableFormats
}
private func formatWithHighestResolution(_ availableFormats: [AVCaptureDeviceFormat]) -> AVCaptureDeviceFormat?
{
var maxWidth: Int32 = 0
var selectedFormat: AVCaptureDeviceFormat?
for format in availableFormats {
guard let desc = format.formatDescription else {continue}
let dimensions = CMVideoFormatDescriptionGetDimensions(desc)
let width = dimensions.width
if width >= maxWidth {
maxWidth = width
selectedFormat = format
}
}
return selectedFormat
}
private func formatFor(preferredSize: CGSize, availableFormats: [AVCaptureDeviceFormat]) -> AVCaptureDeviceFormat?
{
for format in availableFormats {
guard let desc = format.formatDescription else {continue}
let dimensions = CMVideoFormatDescriptionGetDimensions(desc)
if dimensions.width >= Int32(preferredSize.width) && dimensions.height >= Int32(preferredSize.height)
{
return format
}
}
return nil
}
func updateFormatWithPreferredVideoSpec(preferredSpec: VideoSpec)
{
let availableFormats: [AVCaptureDeviceFormat]
if let preferredFps = preferredSpec.fps {
availableFormats = availableFormatsFor(preferredFps: Float64(preferredFps))
}
else {
guard let allFormats = formats as? [AVCaptureDeviceFormat] else { return }
availableFormats = allFormats
}
var selectedFormat: AVCaptureDeviceFormat?
if let preferredSize = preferredSpec.size {
selectedFormat = formatFor(preferredSize: preferredSize, availableFormats: availableFormats)
} else {
selectedFormat = formatWithHighestResolution(availableFormats)
}
print("selected format: \(selectedFormat)")
if let selectedFormat = selectedFormat {
do {
try lockForConfiguration()
}
catch {
fatalError("")
}
activeFormat = selectedFormat
if let preferredFps = preferredSpec.fps {
activeVideoMinFrameDuration = CMTimeMake(1, preferredFps)
activeVideoMaxFrameDuration = CMTimeMake(1, preferredFps)
unlockForConfiguration()
}
}
}
}