This repository has been archived by the owner on Nov 24, 2021. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 57
/
VideoView.swift
374 lines (307 loc) · 14.5 KB
/
VideoView.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
import UIKit
import AVFoundation
import AVKit
#if os(iOS)
import Photos
#endif
protocol VideoViewDelegate: class {
func videoViewDidStartPlaying(_ videoView: VideoView)
func videoView(_ videoView: VideoView, didChangeProgress progress: Double, duration: Double)
func videoViewDidFinishPlaying(_ videoView: VideoView, error: NSError?)
}
class VideoView: UIView {
static let playerItemStatusKeyPath = "status"
static let audioSessionVolumeKeyPath = "outputVolume"
weak var delegate: VideoViewDelegate?
var playerCurrentItemStatus = AVPlayerItem.Status.unknown
fileprivate lazy var playerLayer: AVPlayerLayer = {
let playerLayer = AVPlayerLayer()
playerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
return playerLayer
}()
var image: UIImage?
private lazy var loadingIndicator: UIActivityIndicatorView = {
let view = UIActivityIndicatorView(style: .whiteLarge)
view.autoresizingMask = [.flexibleLeftMargin, .flexibleTopMargin]
return view
}()
private lazy var loadingIndicatorBackground: UIImageView = {
let view = UIImageView(image: .darkCircle)
view.alpha = 0
return view
}()
fileprivate var shouldRegisterForStatusNotifications = true
fileprivate var shouldRegisterForFailureOrEndingNotifications = true
fileprivate var shouldRegisterForOutputVolume = true
fileprivate var playbackProgressTimeObserver: Any?
override init(frame: CGRect) {
super.init(frame: frame)
self.autoresizingMask = [.flexibleLeftMargin, .flexibleTopMargin, .flexibleWidth, .flexibleHeight]
self.isUserInteractionEnabled = false
self.layer.addSublayer(self.playerLayer)
self.addSubview(self.loadingIndicatorBackground)
self.addSubview(self.loadingIndicator)
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// Proposed workaround to fix some issues with observers called after being deallocated.
// Error description:
// Fatal Exception: NSInternalInconsistencyException
// An instance 0x15ed87220 of class AVPlayerItem was deallocated while key value observers were still registered with it.
deinit {
self.removeBeforePlayingObservers()
self.removeWhilePlayingObservers()
}
override func layoutSubviews() {
super.layoutSubviews()
guard let image = self.image else { return }
self.frame = image.centeredFrame()
var playerLayerFrame = image.centeredFrame()
playerLayerFrame.origin.x = 0
playerLayerFrame.origin.y = 0
self.playerLayer.frame = playerLayerFrame
let loadingBackgroundHeight = self.loadingIndicatorBackground.frame.size.height
let loadingBackgroundWidth = self.loadingIndicatorBackground.frame.size.width
self.loadingIndicatorBackground.frame = CGRect(x: (self.frame.size.width - loadingBackgroundWidth) / 2, y: (self.frame.size.height - loadingBackgroundHeight) / 2, width: loadingBackgroundWidth, height: loadingBackgroundHeight)
let loadingHeight = self.loadingIndicator.frame.size.height
let loadingWidth = self.loadingIndicator.frame.size.width
self.loadingIndicator.frame = CGRect(x: (self.frame.size.width - loadingWidth) / 2, y: (self.frame.size.height - loadingHeight) / 2, width: loadingWidth, height: loadingHeight)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change _: [NSKeyValueChangeKey: Any]?, context _: UnsafeMutableRawPointer?) {
if keyPath == VideoView.audioSessionVolumeKeyPath {
#if os(iOS)
try? AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [])
#endif
return
}
guard let playerItem = object as? AVPlayerItem else { return }
self.playerCurrentItemStatus = playerItem.status
if let error = playerItem.error {
self.handleError(error as NSError)
} else {
guard let player = self.playerLayer.player else {
let error = NSError(domain: ViewerController.domain, code: 0, userInfo: [NSLocalizedDescriptionKey: "Player not found."])
self.handleError(error)
return
}
guard keyPath == VideoView.playerItemStatusKeyPath else { return }
guard playerItem.status == .readyToPlay else { return }
self.playerLayer.player?.pause()
self.removeBeforePlayingObservers()
if self.playerLayer.isHidden == false {
player.play()
self.delegate?.videoViewDidStartPlaying(self)
}
if let playbackProgressTimeObserver = self.playbackProgressTimeObserver {
player.removeTimeObserver(playbackProgressTimeObserver)
self.playbackProgressTimeObserver = nil
}
let interval = CMTime(seconds: 1 / 60, preferredTimescale: Int32(NSEC_PER_SEC))
self.playbackProgressTimeObserver = player.addPeriodicTimeObserver(forInterval: interval, queue: nil) { _ in
self.loadingIndicator.stopAnimating()
self.loadingIndicatorBackground.alpha = 0
let duration = CMTimeGetSeconds(playerItem.asset.duration)
let currentTime = CMTimeGetSeconds(player.currentTime())
// In some cases the video will start playing with negative current time.
if currentTime > 0 {
self.delegate?.videoView(self, didChangeProgress: currentTime, duration: duration)
}
}
}
}
func handleError(_ error: NSError) {
self.playerLayer.player?.pause()
self.removeBeforePlayingObservers()
self.removeWhilePlayingObservers()
self.delegate?.videoViewDidFinishPlaying(self, error: error as NSError?)
}
func prepare(using viewable: Viewable, completion: @escaping () -> Void) {
self.addPlayer(using: viewable) {
if self.shouldRegisterForStatusNotifications {
guard let player = self.playerLayer.player else { return }
guard let currentItem = player.currentItem else { return }
self.shouldRegisterForStatusNotifications = false
currentItem.addObserver(self, forKeyPath: VideoView.playerItemStatusKeyPath, options: [], context: nil)
do {
let audioSession = AVAudioSession.sharedInstance()
try audioSession.setActive(true)
audioSession.addObserver(self, forKeyPath: VideoView.audioSessionVolumeKeyPath, options: .new, context: nil)
self.shouldRegisterForOutputVolume = false
} catch {
print("Failed to activate audio session")
}
}
if self.shouldRegisterForFailureOrEndingNotifications {
self.shouldRegisterForFailureOrEndingNotifications = false
NotificationCenter.default.addObserver(self, selector: #selector(self.videoFinishedPlaying), name: .AVPlayerItemDidPlayToEndTime, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.itemPlaybackStalled), name: .AVPlayerItemPlaybackStalled, object: nil)
}
completion()
}
}
func `repeat`() {
self.playerLayer.player?.seek(to: CMTime.zero)
self.playerLayer.player?.play()
}
func stop() {
self.removeBeforePlayingObservers()
self.removeWhilePlayingObservers()
self.playerLayer.isHidden = true
self.playerLayer.player?.pause()
self.playerLayer.player?.seek(to: CMTime.zero)
self.playerLayer.player = nil
#if os(iOS)
try? AVAudioSession.sharedInstance().setCategory(.soloAmbient, mode: .default, options: [])
#endif
}
func play() {
guard let player = self.playerLayer.player else {
let error = NSError(domain: ViewerController.domain, code: 0, userInfo: [NSLocalizedDescriptionKey: "No player was found."])
self.handleError(error)
return
}
if player.status == .unknown {
self.loadingIndicator.startAnimating()
self.loadingIndicatorBackground.alpha = 1
}
self.playerLayer.player?.play()
self.playerLayer.isHidden = false
}
func pause() {
self.playerLayer.player?.pause()
}
func isPlaying() -> Bool {
if let player = self.playerLayer.player {
let isPlaying = player.rate != 0 && player.error == nil
return isPlaying
}
return false
}
// Source:
// Technical Q&A QA1820
// How do I achieve smooth video scrubbing with AVPlayer seekToTime:?
// https://developer.apple.com/library/content/qa/qa1820/_index.html
var isSeekInProgress = false
var chaseTime = CMTime.zero
func stopPlayingAndSeekSmoothlyToTime(duration: Double) {
guard let timescale = self.playerLayer.player?.currentItem?.currentTime().timescale else { return }
let newChaseTime = CMTime(seconds: duration, preferredTimescale: timescale)
self.playerLayer.player?.pause()
if CMTimeCompare(newChaseTime, self.chaseTime) != 0 {
self.chaseTime = newChaseTime
if self.isSeekInProgress == false {
self.trySeekToChaseTime()
}
}
}
func trySeekToChaseTime() {
switch self.playerCurrentItemStatus {
case .unknown:
// wait until item becomes ready (KVO player.currentItem.status)
break
case .readyToPlay:
self.actuallySeekToTime()
case .failed:
break
@unknown default:
break
}
}
func actuallySeekToTime() {
self.isSeekInProgress = true
let seekTimeInProgress = self.chaseTime
self.playerLayer.player?.seek(to: seekTimeInProgress, toleranceBefore: CMTime.zero, toleranceAfter: CMTime.zero) { _ in
if CMTimeCompare(seekTimeInProgress, self.chaseTime) == 0 {
self.isSeekInProgress = false
} else {
self.trySeekToChaseTime()
}
}
}
}
extension VideoView {
fileprivate func addPlayer(using viewable: Viewable, completion: @escaping () -> Void) {
if let assetID = viewable.assetID {
#if os(iOS)
let result = PHAsset.fetchAssets(withLocalIdentifiers: [assetID], options: nil)
guard let asset = result.firstObject else {
let error = NSError(domain: ViewerController.domain, code: 0, userInfo: [NSLocalizedDescriptionKey: "Couldn't get asset for id: \(assetID)."])
self.handleError(error)
return
}
let requestOptions = PHVideoRequestOptions()
requestOptions.isNetworkAccessAllowed = true
PHImageManager.default().requestPlayerItem(forVideo: asset, options: requestOptions) { playerItem, info in
guard let playerItem = playerItem else {
let error = NSError(domain: ViewerController.domain, code: 0, userInfo: [NSLocalizedDescriptionKey: "Couldn't create player: \(String(describing: info))."])
self.handleError(error)
return
}
if let player = self.playerLayer.player {
player.replaceCurrentItem(with: playerItem)
} else {
let player = AVPlayer(playerItem: playerItem)
player.rate = Float(playerItem.preferredPeakBitRate)
self.playerLayer.player = player
self.playerLayer.isHidden = true
}
DispatchQueue.main.async {
completion()
}
}
#endif
} else if let url = viewable.url {
DispatchQueue.global(qos: .background).async {
let streamingURL = URL(string: url)!
self.playerLayer.player = AVPlayer(url: streamingURL)
self.playerLayer.isHidden = true
DispatchQueue.main.async {
completion()
}
}
}
}
fileprivate func removeBeforePlayingObservers() {
if self.shouldRegisterForStatusNotifications == false {
guard let player = self.playerLayer.player else { return }
guard let currentItem = player.currentItem else { return }
self.shouldRegisterForStatusNotifications = true
currentItem.removeObserver(self, forKeyPath: VideoView.playerItemStatusKeyPath)
}
}
fileprivate func removeWhilePlayingObservers() {
if let playbackProgressTimeObserver = self.playbackProgressTimeObserver {
self.playerLayer.player?.removeTimeObserver(playbackProgressTimeObserver)
self.playbackProgressTimeObserver = nil
}
if self.shouldRegisterForFailureOrEndingNotifications == false {
self.shouldRegisterForFailureOrEndingNotifications = true
NotificationCenter.default.removeObserver(self, name: .AVPlayerItemPlaybackStalled, object: nil)
NotificationCenter.default.removeObserver(self, name: .AVPlayerItemDidPlayToEndTime, object: nil)
}
if self.shouldRegisterForOutputVolume == false {
self.shouldRegisterForOutputVolume = true
AVAudioSession.sharedInstance().removeObserver(self, forKeyPath: VideoView.audioSessionVolumeKeyPath)
}
}
// When the video is having troubles buffering it might trigger the "AVPlayerItemPlaybackStalled" notification
// the ideal scenario here, is that we'll pause the video, display the loading indicator for a while,
// then continue the play back.
// The current workaround just pauses the video and tries to play again, this might cause a shuddering video playback,
// is not perfect but does the job for now.
@objc fileprivate func itemPlaybackStalled() {
if let player = self.playerLayer.player {
player.pause()
player.play()
}
}
@objc fileprivate func videoFinishedPlaying() {
self.delegate?.videoViewDidFinishPlaying(self, error: nil)
}
}
extension CMTime {
public init(seconds: Double, preferredTimescale: CMTimeScale) {
self = CMTimeMakeWithSeconds(seconds, preferredTimescale: preferredTimescale)
}
}