-
Notifications
You must be signed in to change notification settings - Fork 13
/
ApiVideoLiveStream.swift
263 lines (229 loc) · 9.67 KB
/
ApiVideoLiveStream.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
//
// ApiVideoLiveStream.swift
//
import AVFoundation
import Foundation
import HaishinKit
import VideoToolbox
public class ApiVideoLiveStream {
private var mthkView: MTHKView?
private var streamKey: String = ""
private var url: String = ""
private let rtmpStream: RTMPStream
private let rtmpConnection = RTMPConnection()
public var onConnectionSuccess: (() -> Void)?
public var onConnectionFailed: ((String) -> Void)?
public var onDisconnect: (() -> Void)?
/// Getter and Setter for an AudioConfig
/// Can't be updated
public var audioConfig: AudioConfig? {
didSet {
if let audioConfig = audioConfig {
prepareAudio(audioConfig: audioConfig)
}
}
}
/// Getter and Setter for a VideoConfig
/// Can't be updated
public var videoConfig: VideoConfig? {
didSet {
if let videoConfig = videoConfig {
prepareVideo(videoConfig: videoConfig)
}
}
}
/// Getter and Setter for the Bitrate number for the video
public var videoBitrate: Int {
get {
return rtmpStream.videoSettings[.bitrate] as! Int
}
set(newValue) {
rtmpStream.videoSettings[.bitrate] = newValue
}
}
/// Camera position
public var camera: AVCaptureDevice.Position = .back {
didSet {
attachCamera()
}
}
/// Audio mute or not.
public var isMuted: Bool {
get {
return rtmpStream.audioSettings[.muted] as! Bool
}
set(newValue) {
rtmpStream.audioSettings[.muted] = newValue
}
}
/// init a new ApiVideoLiveStream
/// - Parameters:
/// - initialAudioConfig: The ApiVideoLiveStream's new AudioConfig
/// - initialVideoConfig: The ApiVideoLiveStream's new VideoConfig
/// - preview: UiView to display the preview of camera
public init(initialAudioConfig: AudioConfig?, initialVideoConfig: VideoConfig?, preview: UIView?) throws {
let session = AVAudioSession.sharedInstance()
// https://stackoverflow.com/questions/51010390/avaudiosession-setcategory-swift-4-2-ios-12-play-sound-on-silent
if #available(iOS 10.0, *) {
try session.setCategory(.playAndRecord, mode: .default, options: [.defaultToSpeaker, .allowBluetooth])
} else {
session.perform(NSSelectorFromString("setCategory:withOptions:error:"), with: AVAudioSession.Category.playAndRecord, with: [
AVAudioSession.CategoryOptions.allowBluetooth,
AVAudioSession.CategoryOptions.defaultToSpeaker,
])
try session.setMode(.default)
}
try session.setActive(true)
audioConfig = initialAudioConfig
videoConfig = initialVideoConfig
rtmpStream = RTMPStream(connection: rtmpConnection)
if let orientation = DeviceUtil.videoOrientation(by: UIApplication.shared.statusBarOrientation) {
rtmpStream.orientation = orientation
}
NotificationCenter.default.addObserver(self, selector: #selector(orientationDidChange(_:)), name: UIDevice.orientationDidChangeNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(didEnterBackground(_:)), name: UIApplication.didEnterBackgroundNotification, object: nil)
attachCamera()
if let videoConfig = videoConfig {
prepareVideo(videoConfig: videoConfig)
}
attachAudio()
if let audioConfig = audioConfig {
prepareAudio(audioConfig: audioConfig)
}
if preview != nil {
mthkView = MTHKView(frame: preview!.bounds)
mthkView!.translatesAutoresizingMaskIntoConstraints = false
mthkView!.videoGravity = AVLayerVideoGravity.resizeAspectFill
mthkView!.attachStream(rtmpStream)
preview!.addSubview(mthkView!)
let maxWidth = mthkView!.widthAnchor.constraint(lessThanOrEqualTo: preview!.widthAnchor)
let maxHeight = mthkView!.heightAnchor.constraint(lessThanOrEqualTo: preview!.heightAnchor)
let width = mthkView!.widthAnchor.constraint(equalTo: preview!.widthAnchor)
let height = mthkView!.heightAnchor.constraint(equalTo: preview!.heightAnchor)
let centerX = mthkView!.centerXAnchor.constraint(equalTo: preview!.centerXAnchor)
let centerY = mthkView!.centerYAnchor.constraint(equalTo: preview!.centerYAnchor)
width.priority = .defaultHigh
height.priority = .defaultHigh
NSLayoutConstraint.activate([
maxWidth, maxHeight, width, height, centerX, centerY,
])
}
}
deinit {
NotificationCenter.default.removeObserver(self, name: UIDevice.orientationDidChangeNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIApplication.didEnterBackgroundNotification, object: nil)
}
private func attachCamera() {
rtmpStream.captureSettings[.isVideoMirrored] = camera == .front
rtmpStream.attachCamera(DeviceUtil.device(withPosition: camera)) { error in
print("======== Camera error ==========")
print(error.description)
}
}
private func prepareVideo(videoConfig: VideoConfig) {
rtmpStream.captureSettings = [
.sessionPreset: AVCaptureSession.Preset.high,
.fps: videoConfig.fps,
.continuousAutofocus: true,
.continuousExposure: true,
// .preferredVideoStabilizationMode: AVCaptureVideoStabilizationMode.auto // Add latency to video
]
rtmpStream.videoSettings = [
.width: rtmpStream.orientation.isLandscape ? videoConfig.resolution.instance.width : videoConfig.resolution.instance.height,
.height: rtmpStream.orientation.isLandscape ? videoConfig.resolution.instance.height : videoConfig.resolution.instance.width,
.profileLevel: kVTProfileLevel_H264_Baseline_5_2,
.bitrate: videoConfig.bitrate,
.maxKeyFrameIntervalDuration: 1,
]
}
private func attachAudio() {
rtmpStream.attachAudio(AVCaptureDevice.default(for: AVMediaType.audio)) { error in
print("======== Audio error ==========")
print(error.description)
}
}
private func prepareAudio(audioConfig: AudioConfig) {
rtmpStream.audioSettings = [
.bitrate: audioConfig.bitrate,
]
}
/// Start your livestream
/// - Parameters:
/// - streamKey: The key of your live
/// - url: The url of your rtmp server, by default it's rtmp://broadcast.api.video/s
/// - Returns: Void
public func startStreaming(streamKey: String, url: String = "rtmp://broadcast.api.video/s") throws {
if streamKey.isEmpty {
throw LiveStreamError.IllegalArgumentError("Stream key must not be empty")
}
if audioConfig == nil || videoConfig == nil {
throw LiveStreamError.IllegalArgumentError("Missing audio and/or video configuration")
}
self.streamKey = streamKey
self.url = url
rtmpConnection.addEventListener(.rtmpStatus, selector: #selector(rtmpStatusHandler), observer: self)
rtmpConnection.addEventListener(.ioError, selector: #selector(rtmpErrorHandler), observer: self)
rtmpConnection.connect(url)
}
/// Stop your livestream
/// - Returns: Void
public func stopStreaming() {
rtmpConnection.close()
rtmpConnection.removeEventListener(.rtmpStatus, selector: #selector(rtmpStatusHandler), observer: self)
rtmpConnection.removeEventListener(.ioError, selector: #selector(rtmpErrorHandler), observer: self)
}
@objc private func rtmpStatusHandler(_ notification: Notification) {
let e = Event.from(notification)
guard let data: ASObject = e.data as? ASObject, let code: String = data["code"] as? String else {
return
}
switch code {
case RTMPConnection.Code.connectSuccess.rawValue:
if onConnectionSuccess != nil {
onConnectionSuccess!()
}
rtmpStream.publish(streamKey)
case RTMPConnection.Code.connectFailed.rawValue:
if onConnectionFailed != nil {
onConnectionFailed!(code)
}
case RTMPConnection.Code.connectClosed.rawValue:
if onDisconnect != nil {
onDisconnect!()
}
default:
break
}
}
@objc
private func rtmpErrorHandler(_ notification: Notification) {
let e = Event.from(notification)
print("rtmpErrorHandler: \(e)")
DispatchQueue.main.async {
self.rtmpConnection.connect(self.url)
}
}
@objc
private func orientationDidChange(_: Notification) {
guard let orientation = DeviceUtil.videoOrientation(by: UIApplication.shared.statusBarOrientation) else {
return
}
rtmpStream.orientation = orientation
if let videoConfig = videoConfig {
rtmpStream.videoSettings = [
.width: rtmpStream.orientation.isLandscape ? videoConfig.resolution.instance.width : videoConfig.resolution.instance.height,
.height: rtmpStream.orientation.isLandscape ? videoConfig.resolution.instance.height : videoConfig.resolution.instance.width,
]
}
}
@objc
private func didEnterBackground(_: Notification) {
stopStreaming()
}
}
extension AVCaptureVideoOrientation {
var isLandscape: Bool { return self == .landscapeLeft || self == .landscapeRight }
}
public enum LiveStreamError: Error {
case IllegalArgumentError(String)
}