-
-
Notifications
You must be signed in to change notification settings - Fork 340
/
Copy pathAVCaptureDevice+Extension.swift
84 lines (74 loc) · 2.85 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
//
// 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) -> [AVCaptureDevice.Format] {
var availableFormats: [AVCaptureDevice.Format] = []
for format in formats
{
let ranges = format.videoSupportedFrameRateRanges
for range in ranges where range.minFrameRate <= preferredFps && preferredFps <= range.maxFrameRate
{
availableFormats.append(format)
}
}
return availableFormats
}
private func formatWithHighestResolution(_ availableFormats: [AVCaptureDevice.Format]) -> AVCaptureDevice.Format?
{
var maxWidth: Int32 = 0
var selectedFormat: AVCaptureDevice.Format?
for format in availableFormats {
let dimensions = CMVideoFormatDescriptionGetDimensions(format.formatDescription)
let width = dimensions.width
if width >= maxWidth {
maxWidth = width
selectedFormat = format
}
}
return selectedFormat
}
private func formatFor(preferredSize: CGSize, availableFormats: [AVCaptureDevice.Format]) -> AVCaptureDevice.Format?
{
for format in availableFormats {
let dimensions = CMVideoFormatDescriptionGetDimensions(format.formatDescription)
if dimensions.width >= Int32(preferredSize.width) && dimensions.height >= Int32(preferredSize.height)
{
return format
}
}
return nil
}
func updateFormatWithPreferredVideoSpec(preferredSpec: VideoSpec)
{
let availableFormats: [AVCaptureDevice.Format]
if let preferredFps = preferredSpec.fps {
availableFormats = availableFormatsFor(preferredFps: Float64(preferredFps))
} else {
availableFormats = formats
}
var format: AVCaptureDevice.Format?
if let preferredSize = preferredSpec.size {
format = formatFor(preferredSize: preferredSize, availableFormats: availableFormats)
} else {
format = formatWithHighestResolution(availableFormats)
}
guard let selectedFormat = format else {return}
print("selected format: \(selectedFormat)")
do {
try lockForConfiguration()
} catch {
fatalError("")
}
activeFormat = selectedFormat
if let preferredFps = preferredSpec.fps {
activeVideoMinFrameDuration = CMTimeMake(value: 1, timescale: preferredFps)
activeVideoMaxFrameDuration = CMTimeMake(value: 1, timescale: preferredFps)
unlockForConfiguration()
}
}
}