杨锴
2025-04-16 09a372bc45fde16fd42257ab6f78b8deeecf720b
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
//
//  CLPlayerView.swift
//  CLPlayer
//
//  Created by Chen JmoVxia on 2021/10/26.
//
 
import AVFoundation
import SnapKit
import UIKit
import JQTools
 
extension CLPlayerView {
    enum CLWaitReadyToPlayState {
        case nomal
        case pause
        case play
    }
}
 
class CLPlayerView: UIView {
    init(config: CLPlayerConfigure) {
        super.init(frame: .zero)
        self.config = config
        initSubViews()
        makeConstraints()
        (layer as? AVPlayerLayer)?.videoGravity = self.config.videoGravity
    }
 
    @available(*, unavailable)
    required init?(coder _: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
 
    deinit {
        NotificationCenter.default.removeObserver(self, name: UIDevice.orientationDidChangeNotification, object: nil)
        NotificationCenter.default.removeObserver(self, name: UIApplication.willResignActiveNotification, object: nil)
        NotificationCenter.default.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil)
    }
 
    private(set) lazy var contentView: CLPlayerContentView = {
        let view = CLPlayerContentView(config: config)
        view.delegate = self
        return view
    }()
 
    private let keyWindow: UIWindow? = {
        if #available(iOS 13.0, *) {
            return UIApplication.shared.windows.filter { $0.isKeyWindow }.last
        } else {
            return UIApplication.shared.keyWindow
        }
    }()
 
    private var waitReadyToPlayState: CLWaitReadyToPlayState = .nomal
 
    private var sliderTimer: CLGCDTimer?
 
    private var bufferTimer: CLGCDTimer?
 
    private var config = CLPlayerConfigure()
 
    private var animationTransitioning: CLAnimationTransitioning?
 
    private var fullScreenController: CLFullScreenController?
 
    private var statusObserve: NSKeyValueObservation?
 
    private var loadedTimeRangesObserve: NSKeyValueObservation?
 
    private var playbackBufferEmptyObserve: NSKeyValueObservation?
 
    private var isUserPause: Bool = false
 
    private var isEnterBackground: Bool = false
 
    private var player: AVPlayer?
 
    private var playerItem: AVPlayerItem? {
        didSet {
            guard playerItem != oldValue else { return }
            if let oldPlayerItem = oldValue {
                NotificationCenter.default.removeObserver(self, name: .AVPlayerItemDidPlayToEndTime, object: oldPlayerItem)
            }
            guard let playerItem = playerItem else { return }
            NotificationCenter.default.addObserver(self, selector: #selector(didPlaybackEnds), name: .AVPlayerItemDidPlayToEndTime, object: playerItem)
 
            statusObserve = playerItem.observe(\.status, options: [.new]) { [weak self] _, _ in
                self?.observeStatusAction()
            }
        }
    }
 
    private(set) var totalDuration: TimeInterval = .zero {
        didSet {
            guard totalDuration != oldValue else { return }
            contentView.setTotalDuration(totalDuration)
        }
    }
 
    private(set) var currentDuration: TimeInterval = .zero {
        didSet {
            guard currentDuration != oldValue else { return }
            contentView.setCurrentDuration(min(currentDuration, totalDuration))
        }
    }
 
    private(set) var playbackProgress: CGFloat = .zero {
        didSet {
            guard playbackProgress != oldValue else { return }
            contentView.setSliderProgress(Float(playbackProgress), animated: false)
            let oldIntValue = Int(oldValue * 100)
            let intValue = Int(playbackProgress * 100)
            if intValue != oldIntValue {
                DispatchQueue.main.async {
                    self.playProgressChanged?(CGFloat(intValue) / 100)
                }
            }
        }
    }
 
    private(set) var rate: Float = 1.0 {
        didSet {
            guard rate != oldValue else { return }
            play()
        }
    }
 
    var isFullScreen: Bool {
        return contentView.screenState == .fullScreen
    }
 
    var isPlaying: Bool {
        return contentView.playState == .playing
    }
 
    var isBuffering: Bool {
        return contentView.playState == .buffering
    }
 
    var isFailed: Bool {
        return contentView.playState == .failed
    }
 
    var isPaused: Bool {
        return contentView.playState == .pause
    }
 
    var isEnded: Bool {
        return contentView.playState == .ended
    }
 
    var title: NSMutableAttributedString? {
        didSet {
            guard let title = title else { return }
            contentView.title = title
        }
    }
 
    var url: URL? {
        didSet {
            guard let url = url else { return }
            stop()
            let session = AVAudioSession.sharedInstance()
            do {
                try session.setCategory(.playback)
                try session.setActive(true)
            } catch {
                print("set session error:\(error)")
            }
            playerItem = AVPlayerItem(asset: .init(url: url))
            player = AVPlayer(playerItem: playerItem)
            (layer as? AVPlayerLayer)?.player = player
        }
    }
 
    weak var placeholder: UIView? {
        didSet {
            contentView.placeholderView = placeholder
        }
    }
 
    var backButtonTappedHandler: (() -> Void)?
 
    var playToEndHandler: (() -> Void)?
 
    var playProgressChanged: ((CGFloat) -> Void)?
 
    var playFailed: ((Error?) -> Void)?
}
 
// MARK: - JmoVxia---override
 
extension CLPlayerView {
    override class var layerClass: AnyClass {
        return AVPlayerLayer.classForCoder()
    }
}
 
// MARK: - JmoVxia---布局
 
private extension CLPlayerView {
    func initSubViews() {
        backgroundColor = .black
        addSubview(contentView)
        NotificationCenter.default.addObserver(self, selector: #selector(appDidEnterBackground), name: UIApplication.willResignActiveNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(appDidEnterPlayground), name: UIApplication.didBecomeActiveNotification, object: nil)
        if !UIDevice.current.isGeneratingDeviceOrientationNotifications {
            UIDevice.current.beginGeneratingDeviceOrientationNotifications()
        }
        NotificationCenter.default.addObserver(self, selector: #selector(deviceOrientationDidChange), name: UIDevice.orientationDidChangeNotification, object: nil)
    }
 
    func makeConstraints() {
        contentView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
}
 
// MARK: - JmoVxia---objc
 
@objc private extension CLPlayerView {
    func didPlaybackEnds() {
        currentDuration = totalDuration
        playbackProgress = 1.0
        contentView.playState = .ended
        sliderTimer?.pause()
        DispatchQueue.main.async {
            self.playToEndHandler?()
        }
    }
 
    func deviceOrientationDidChange() {
        guard config.rotateStyle != .none else { return }
        if config.rotateStyle == .small, isFullScreen { return }
        if config.rotateStyle == .fullScreen, !isFullScreen { return }
 
        if let vc = JQ_currentViewController() as? CourseVC,vc.pageViewController.currentPage == 1{
            switch UIDevice.current.orientation {
                case .portrait:
                    dismiss()
                case .landscapeLeft:
                    presentWithOrientation(.left)
                case .landscapeRight:
                    presentWithOrientation(.right)
                default:
                    break
            }
        }
    }
 
    func appDidEnterBackground() {
        isEnterBackground = true
        pause()
    }
 
    func appDidEnterPlayground() {
        isEnterBackground = false
        guard contentView.playState != .ended else { return }
        play()
    }
}
 
// MARK: - JmoVxia---observe
 
private extension CLPlayerView {
    func observeStatusAction() {
        guard let playerItem = playerItem else { return }
        if playerItem.status == .readyToPlay {
            contentView.playState = .readyToPlay
            totalDuration = TimeInterval(playerItem.duration.value) / TimeInterval(playerItem.duration.timescale)
 
            sliderTimer = CLGCDTimer(interval: 0.1)
            sliderTimer?.run { [weak self] _ in
                self?.sliderTimerAction()
            }
 
            loadedTimeRangesObserve = playerItem.observe(\.loadedTimeRanges, options: [.new]) { [weak self] _, _ in
                self?.observeLoadedTimeRangesAction()
            }
 
            playbackBufferEmptyObserve = playerItem.observe(\.isPlaybackBufferEmpty, options: [.new]) { [weak self] _, _ in
                self?.observePlaybackBufferEmptyAction()
            }
 
            switch waitReadyToPlayState {
            case .nomal:
                break
            case .pause:
                pause()
            case .play:
                play()
            }
        } else if playerItem.status == .failed {
            contentView.playState = .failed
            DispatchQueue.main.async {
                self.playFailed?(playerItem.error)
            }
        }
    }
 
    func observeLoadedTimeRangesAction() {
        guard let timeInterval = availableDuration() else { return }
        guard let duration = playerItem?.duration else { return }
        let totalDuration = TimeInterval(CMTimeGetSeconds(duration))
        contentView.setProgress(Float(timeInterval / totalDuration), animated: false)
    }
 
    func observePlaybackBufferEmptyAction() {
        guard playerItem?.isPlaybackBufferEmpty ?? false else { return }
        bufferingSomeSecond()
    }
}
 
private extension CLPlayerView {
    func availableDuration() -> TimeInterval? {
        guard let timeRange = playerItem?.loadedTimeRanges.first?.timeRangeValue else { return nil }
        let startSeconds = CMTimeGetSeconds(timeRange.start)
        let durationSeconds = CMTimeGetSeconds(timeRange.duration)
        return .init(startSeconds + durationSeconds)
    }
 
    func bufferingSomeSecond() {
        guard playerItem?.status == .readyToPlay else { return }
        guard contentView.playState != .failed else { return }
 
        player?.pause()
        sliderTimer?.pause()
 
        contentView.playState = .buffering
        bufferTimer = CLGCDTimer(interval: 3.0, initialDelay: 3.0)
        bufferTimer?.run { [weak self] _ in
            guard let playerItem = self?.playerItem else { return }
            self?.bufferTimer = nil
            if playerItem.isPlaybackLikelyToKeepUp {
                self?.play()
            } else {
                self?.bufferingSomeSecond()
            }
        }
    }
 
    func sliderTimerAction() {
        guard let playerItem = playerItem else { return }
        guard playerItem.duration.timescale != .zero else { return }
 
        currentDuration = CMTimeGetSeconds(playerItem.currentTime())
        playbackProgress = currentDuration / totalDuration
    }
}
 
// MARK: - JmoVxia---Screen
 
private extension CLPlayerView {
    func dismiss() {
        guard Thread.isMainThread else { return DispatchQueue.main.async { self.dismiss() } }
        guard contentView.screenState == .fullScreen else { return }
        guard let controller = fullScreenController else { return }
        contentView.screenState = .animating
        controller.dismiss(animated: true, completion: {
            self.contentView.screenState = .small
            self.fullScreenController = nil
            UIViewController.attemptRotationToDeviceOrientation()
        })
    }
 
    func presentWithOrientation(_ orientation: CLAnimationTransitioning.AnimationOrientation) {
        guard Thread.isMainThread else { return DispatchQueue.main.async { self.presentWithOrientation(orientation) } }
        guard superview != nil else { return }
        guard fullScreenController == nil else { return }
        guard contentView.screenState == .small else { return }
        guard let rootViewController = keyWindow?.rootViewController else { return }
        contentView.screenState = .animating
 
        animationTransitioning = CLAnimationTransitioning(playerView: self, animationOrientation: orientation)
 
        fullScreenController = orientation == .right ? CLFullScreenLeftController() : CLFullScreenRightController()
        fullScreenController?.transitioningDelegate = self
        fullScreenController?.modalPresentationStyle = .fullScreen
        rootViewController.present(fullScreenController!, animated: true, completion: {
            self.contentView.screenState = .fullScreen
            UIViewController.attemptRotationToDeviceOrientation()
        })
    }
}
 
// MARK: - JmoVxia---公共方法
 
extension CLPlayerView {
    func play() {
        guard !isEnterBackground else { return }
        guard !isUserPause else { return }
        guard let playerItem = playerItem else { return }
        guard playerItem.status == .readyToPlay else {
            contentView.playState = .waiting
            waitReadyToPlayState = .play
            return
        }
        guard playerItem.isPlaybackLikelyToKeepUp else {
            bufferingSomeSecond()
            return
        }
        if contentView.playState == .ended {
            player?.seek(to: CMTimeMake(value: 0, timescale: 1), toleranceBefore: .zero, toleranceAfter: .zero)
        }
        contentView.playState = .playing
        player?.play()
        player?.rate = rate
        sliderTimer?.resume()
        waitReadyToPlayState = .nomal
        bufferTimer = nil
    }
 
    func pause() {
        guard playerItem?.status == .readyToPlay else {
            waitReadyToPlayState = .pause
            return
        }
        contentView.playState = .pause
        player?.pause()
        sliderTimer?.pause()
        bufferTimer = nil
        waitReadyToPlayState = .nomal
    }
 
    func stop() {
        statusObserve?.invalidate()
        loadedTimeRangesObserve?.invalidate()
        playbackBufferEmptyObserve?.invalidate()
 
        statusObserve = nil
        loadedTimeRangesObserve = nil
        playbackBufferEmptyObserve = nil
 
        playerItem = nil
        player = nil
 
        isUserPause = false
 
        waitReadyToPlayState = .nomal
 
        contentView.playState = .unknow
        contentView.setProgress(0, animated: false)
        playbackProgress = 0
        totalDuration = 0
        currentDuration = 0
        sliderTimer = nil
    }
}
 
// MARK: - JmoVxia---UIViewControllerTransitioningDelegate
 
extension CLPlayerView: UIViewControllerTransitioningDelegate {
    func animationController(forPresented _: UIViewController, presenting _: UIViewController, source _: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        animationTransitioning?.animationType = .present
        return animationTransitioning
    }
 
    func animationController(forDismissed _: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        animationTransitioning?.animationType = .dismiss
        return animationTransitioning
    }
}
 
// MARK: - JmoVxia---CLPlayerContentViewDelegate
 
extension CLPlayerView: CLPlayerContentViewDelegate {
    func contentView(_ contentView: CLPlayerContentView, didClickPlayButton isPlay: Bool) {
        isUserPause = isPlay
        isPlay ? pause() : play()
    }
 
    func contentView(_ contentView: CLPlayerContentView, didClickFullButton isFull: Bool) {
        isFull ? dismiss() : presentWithOrientation(.fullRight)
    }
 
    func contentView(_ contentView: CLPlayerContentView, didChangeRate rate: Float) {
        self.rate = rate
    }
 
    func contentView(_ contentView: CLPlayerContentView, didChangeVideoGravity videoGravity: AVLayerVideoGravity) {
        (layer as? AVPlayerLayer)?.videoGravity = videoGravity
    }
 
    func contentView(_ contentView: CLPlayerContentView, sliderTouchBegan slider: CLSlider) {
        pause()
    }
 
    func contentView(_ contentView: CLPlayerContentView, sliderValueChanged slider: CLSlider) {
        currentDuration = totalDuration * TimeInterval(slider.value)
        let dragedCMTime = CMTimeMake(value: Int64(ceil(currentDuration)), timescale: 1)
        player?.seek(to: dragedCMTime, toleranceBefore: .zero, toleranceAfter: .zero)
    }
 
    func contentView(_ contentView: CLPlayerContentView, sliderTouchEnded slider: CLSlider) {
        guard let playerItem = playerItem else { return }
        if slider.value == 1 {
            didPlaybackEnds()
        } else if playerItem.isPlaybackLikelyToKeepUp {
            play()
        } else {
            bufferingSomeSecond()
        }
    }
 
    func didClickFailButton(in _: CLPlayerContentView) {
        guard let url = url else { return }
        self.url = url
    }
 
    func didClickBackButton(in contentView: CLPlayerContentView) {
        guard contentView.screenState == .fullScreen else { return }
        DispatchQueue.main.async {
            self.dismiss()
            self.backButtonTappedHandler?()
        }
    }
}