-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAVPlayer.swift
More file actions
272 lines (232 loc) · 9.71 KB
/
AVPlayer.swift
File metadata and controls
272 lines (232 loc) · 9.71 KB
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
import AVFoundation
import Combine
import Foundation
// MARK: - Helpers
extension AVPlayer {
/// Returns whether the current item has audio tracks. Will only return accurate data once the duration of the player has been populated.
public var hasAudio: Bool {
currentItem?.tracks.compactMap(\.assetTrack).contains { $0.mediaType == .audio } ?? false
}
/// Returns the duration of the current item only if it is non-nil and non-NaN.
public var validDuration: Double? {
guard let duration = currentItem?.duration.seconds, !duration.isNaN else {
return nil
}
return duration
}
/// Seeks to the beginning of the current item and begins playing.
public func restart() {
seek(to: .zero)
play()
}
/// Seeks to the beginning of the current item and pauses.
public func reset() {
seek(to: .zero)
pause()
}
}
// MARK: - Basic Player Publishers
extension AVPlayer {
/// A publisher of changes to an AVPlayer's duration.
public var durationPublisher: AnyPublisher<Double?, Never> {
publisher(for: \.currentItem?.duration)
.map { $0?.seconds }
.replaceError(with: nil)
.removeDuplicates()
.eraseToAnyPublisher()
}
/// A publisher that fires periodically as an AVPlayer plays.
/// - Parameter interval: The interval for which to report video playback
/// - Returns: A publisher that fires periodically as an AVPlayer plays.
func periodicTimePublisher(interval: Double) -> AnyPublisher<Double, Never> {
PeriodicTimePublisher(player: self, interval: .init(seconds: interval, preferredTimescale: .init(NSEC_PER_SEC)))
.map(\.seconds)
.prepend(0.0)
.eraseToAnyPublisher()
}
/// A publisher of changes to an AVPlayer's time control status.
var timeControlStatusPublisher: AnyPublisher<AVPlayer.TimeControlStatus, Never> {
publisher(for: \.timeControlStatus)
.replaceError(with: .waitingToPlayAtSpecifiedRate)
.removeDuplicates()
.eraseToAnyPublisher()
}
/// A publisher of changes to an AVPlayer's status.
var statusPublisher: AnyPublisher<AVPlayer.Status, Never> {
publisher(for: \.status)
.replaceError(with: .unknown)
.removeDuplicates()
.eraseToAnyPublisher()
}
}
// MARK: - Player Progress
extension AVPlayer {
/// A publisher of changes to an AVPlayer's playback progress percentage.
/// - Parameter interval: The rate at which player progress should be reported.
/// - Returns: A publisher of changes to an AVPlayer's playback progress.
public func playerProgressPublisher(interval: Double) -> AnyPublisher<Double, Never> {
durationPublisher.combineLatest(
periodicTimePublisher(interval: interval)
)
.map { Self.playerProgress(duration: $0, periodicTime: $1) }
.eraseToAnyPublisher()
}
/// A publisher that triggers when the player progress clears requested completion percentage gates.
/// - Parameters:
/// - percentGates: A set of playback completion percentages to trigger events for.
/// - interval: The rate at which completion gates should be polled.
/// - shouldRetriggerGates: A flag indicating whether gates should be retriggered if playback restarts or is rewound.
/// - Returns: A publisher that triggers when the player progress clears requested completion percentage gates.
public func completionGatesClearedPublisher(percentGates: Set<Double>, interval: Double = 1.0, shouldRetriggerGates: Bool = true) -> AnyPublisher<Double, Never> {
let percentGates = percentGates.sorted()
return playerProgressPublisher(interval: interval)
.scan((Set<Double>(), Set<Double>(), 0.0)) { state, currentPercent in
let (alreadyCleared, _, previousPercent) = state
var toBroadcast = Set<Double>()
for gate in percentGates {
if previousPercent < gate && currentPercent >= gate && (shouldRetriggerGates || !alreadyCleared.contains(gate)) {
toBroadcast.insert(gate)
}
}
return (alreadyCleared.union(toBroadcast), toBroadcast, currentPercent)
}
.compactMap { state -> Set<Double>? in
let (_, toBroadcast, _) = state
guard !toBroadcast.isEmpty else { return nil }
return toBroadcast
}
.flatMap { toBroadcast in
toBroadcast.publisher
}
.eraseToAnyPublisher()
}
static func playerProgress(duration: Double?, periodicTime: Double) -> Double {
guard let duration, duration > 0 else { return 0 }
return max(0, min(1, periodicTime / duration))
}
}
// MARK: - Player State
/// Represents the state that a video player can be in.
public enum VideoPlayerState: Equatable {
/// Represents the initial loading state of the player.
case loading
/// Represents an error state.
case error
/// Represents the player being ready, unfinished, but paused.
case paused
/// Represents the player loading after initial playback.
case stalled
/// Represents the player playing.
case playing
/// Represents the player having finished playing its video.
case finished
}
/// Holds the components that make up a `VideoPlayerState`.
public struct VideoPlayerStateComponents: Equatable {
/// The duration of the current player item.
public let duration: Double?
/// The current time of the current player item.
public let periodicTime: Double
/// The time control status of the player.
public let timeControlStatus: AVPlayer.TimeControlStatus
/// The status of the player.
public let status: AVPlayer.Status
/// The player state derived from components.
public var playerState: VideoPlayerState {
guard status != .unknown else { return .loading }
guard timeControlStatus != .waitingToPlayAtSpecifiedRate else { return .stalled }
guard status != .failed else { return .error }
if timeControlStatus == .playing {
return .playing
} else {
if let duration, !duration.isNaN, periodicTime >= duration {
return .finished
} else {
return .paused
}
}
}
}
extension AVPlayer {
/// The current components of the player that make up the player state.
public var playerStateComponents: VideoPlayerStateComponents {
VideoPlayerStateComponents(
duration: currentItem?.duration.seconds,
periodicTime: currentTime().seconds,
timeControlStatus: timeControlStatus,
status: status
)
}
/// The current state of a video player.
public var playerState: VideoPlayerState {
playerStateComponents.playerState
}
/// A publisher of changes to an AVPlayer's player state components.
public func playerStateComponentsPublisher(interval: Double) -> AnyPublisher<VideoPlayerStateComponents, Never> {
durationPublisher.combineLatest(
periodicTimePublisher(interval: interval),
timeControlStatusPublisher,
statusPublisher
)
.map { values in
let (duration, periodicTime, timeControlStatus, status) = values
return VideoPlayerStateComponents(
duration: duration,
periodicTime: periodicTime,
timeControlStatus: timeControlStatus,
status: status
)
}
.prepend(playerStateComponents)
.removeDuplicates()
.eraseToAnyPublisher()
}
/// A publisher of changes to an AVPlayer's player state.
public func playerStatePublisher(interval: Double) -> AnyPublisher<VideoPlayerState, Never> {
playerStateComponentsPublisher(interval: interval)
.map { components -> VideoPlayerState in
components.playerState
}
.prepend(playerState)
.removeDuplicates()
.eraseToAnyPublisher()
}
}
// MARK: - Periodic Time Publisher
extension AVPlayer {
private struct PeriodicTimePublisher: Publisher {
typealias Output = CMTime
typealias Failure = Never
var player: AVPlayer
var interval: CMTime
init(player: AVPlayer, interval: CMTime) {
self.player = player
self.interval = interval
}
func receive<S>(subscriber: S) where S: Subscriber, S.Input == Output, S.Failure == Failure {
let subscription = CMTime.Subscription(subscriber: subscriber, player: player, forInterval: interval)
subscriber.receive(subscription: subscription)
}
}
}
private extension CMTime {
final class Subscription<SubscriberType: Subscriber>: Combine.Subscription where SubscriberType.Input == CMTime, SubscriberType.Failure == Never {
var player: AVPlayer?
var observer: Any?
init(subscriber: SubscriberType, player: AVPlayer, forInterval interval: CMTime) {
self.player = player
self.observer = player.addPeriodicTimeObserver(forInterval: interval, queue: nil) { time in
_ = subscriber.receive(time)
}
}
// We have no demand, and simply wait for events to trigger.
func request(_ demand: Subscribers.Demand) {}
func cancel() {
if let observer {
player?.removeTimeObserver(observer)
}
observer = nil
player = nil
}
}
}