-
Notifications
You must be signed in to change notification settings - Fork 9
/
PlaybackView.swift
968 lines (851 loc) · 27.8 KB
/
PlaybackView.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
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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
//
// Copyright (c) SRG SSR. All rights reserved.
//
// License information is available from the LICENSE file.
//
import AVFoundation
import CoreMedia
import PillarboxMonitoring
import PillarboxPlayer
import SwiftUI
#if os(iOS)
// Behavior: h-exp, v-exp
private struct MainView: View {
@ObservedObject var player: Player
@Binding var layout: PlaybackView.Layout
let supportsPictureInPicture: Bool
let progressTracker: ProgressTracker
@StateObject private var visibilityTracker = VisibilityTracker()
@State private var metricsCollector = MetricsCollector(interval: .init(value: 1, timescale: 1), limit: 90)
@State private var layoutInfo: LayoutInfo = .none
@State private var isPresentingMetrics = false
@State private var selectedGravity: AVLayerVideoGravity = .resizeAspect
@State private var isInteracting = false
private var prioritizesVideoDevices: Bool {
player.mediaType == .video
}
private var shouldHideInterface: Bool {
isUserInterfaceHidden || (isInteracting && !shouldKeepControlsAlwaysVisible)
}
private var shouldKeepControlsAlwaysVisible: Bool {
player.isExternalPlaybackActive || player.mediaType != .video
}
var body: some View {
AdaptiveSheetContainer(isPresenting: $isPresentingMetrics) {
ZStack {
main()
bottomBar()
topBar()
}
.animation(.defaultLinear, value: shouldHideInterface)
} sheet: {
MetricsView(metricsCollector: metricsCollector)
}
.statusBarHidden(isFullScreen ? isUserInterfaceHidden : false)
.bind(visibilityTracker, to: player)
.bind(metricsCollector, to: player)
}
private var isFullScreen: Bool {
layout == .inline || layout == .maximized
}
private var gravity: AVLayerVideoGravity {
layoutInfo.isOverCurrentContext ? selectedGravity : .resizeAspect
}
private var toggleGestureMask: GestureMask {
!isInteracting ? .all : .subviews
}
private var magnificationGestureMask: GestureMask {
layoutInfo.isOverCurrentContext ? .all : .subviews
}
private var isUserInterfaceHidden: Bool {
visibilityTracker.isUserInterfaceHidden && !shouldKeepControlsAlwaysVisible && !player.canReplay()
}
private var title: String? {
player.metadata.title
}
private var subtitle: String? {
player.metadata.subtitle
}
private var isMonoscopic: Bool {
player.metadata.viewport == .monoscopic
}
private func toggleGesture() -> some Gesture {
TapGesture()
.onEnded(visibilityTracker.toggle)
}
private func magnificationGesture() -> some Gesture {
MagnificationGesture()
.onChanged { scale in
selectedGravity = scale > 1.0 ? .resizeAspectFill : .resizeAspect
}
}
private func visibilityResetGesture() -> some Gesture {
TapGesture()
.onEnded(visibilityTracker.reset)
}
@ViewBuilder
private func main() -> some View {
ZStack {
video()
.accessibilityElement()
.accessibilityLabel("Video")
.accessibilityHint("Double tap to toggle controls")
.accessibilityAction(.default, visibilityTracker.toggle)
.accessibilityHidden(shouldKeepControlsAlwaysVisible)
controls()
}
.ignoresSafeArea()
.animation(.defaultLinear, values: isUserInterfaceHidden, isInteracting)
.readLayout(into: $layoutInfo)
.gesture(toggleGesture(), including: toggleGestureMask)
.gesture(magnificationGesture(), including: magnificationGestureMask)
.simultaneousGesture(visibilityResetGesture())
.supportsHighSpeed(!isMonoscopic, for: player)
}
@ViewBuilder
private func metadata() -> some View {
VStack(alignment: .leading) {
HStack {
LiveLabel(player: player, progressTracker: progressTracker)
if let subtitle {
Text(subtitle)
.font(.footnote)
.fontWeight(.semibold)
.lineLimit(2)
}
}
if let title {
Text(title)
.font(.title2)
.fontWeight(.bold)
.lineLimit(1)
}
}
.frame(maxWidth: .infinity, alignment: .leading)
.foregroundStyle(.white)
.opacity(shouldHideInterface ? 0 : 1)
}
@ViewBuilder
private func bottomBar() -> some View {
VStack(spacing: 20) {
skipButton()
bottomControls()
}
.animation(.defaultLinear, values: isUserInterfaceHidden, isInteracting)
.padding(.horizontal)
.padding(.vertical, 10)
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottom)
}
@ViewBuilder
private func bottomControls() -> some View {
VStack(spacing: 0) {
HStack(alignment: .bottom) {
metadata()
if isFullScreen {
bottomButtons()
}
}
HStack(spacing: 20) {
TimeBar(player: player, visibilityTracker: visibilityTracker, isInteracting: $isInteracting)
if !isFullScreen {
bottomButtons()
}
}
}
.preventsTouchPropagation()
.opacity(isUserInterfaceHidden ? 0 : 1)
}
@ViewBuilder
private func bottomButtons() -> some View {
HStack(spacing: 20) {
LiveButton(player: player, progressTracker: progressTracker)
SettingsMenu(player: player, isPresentingMetrics: $isPresentingMetrics)
FullScreenButton(layout: $layout)
}
.opacity(isFullScreen && shouldHideInterface ? 0 : 1)
}
@ViewBuilder
private func topBar() -> some View {
HStack {
HStack(spacing: 20) {
CloseButton()
if supportsPictureInPicture {
PiPButton()
}
routePickerView()
}
.opacity(shouldHideInterface ? 0 : 1)
Spacer()
HStack(spacing: 20) {
LoadingIndicator(player: player)
if !shouldHideInterface {
VolumeButton(player: player)
}
}
}
.topBarStyle()
.preventsTouchPropagation()
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)
}
@ViewBuilder
private func routePickerView() -> some View {
RoutePickerView(prioritizesVideoDevices: prioritizesVideoDevices)
.tint(.white)
.aspectRatio(contentMode: .fit)
.frame(width: 20)
}
@ViewBuilder
private func artwork(for imageSource: ImageSource) -> some View {
LazyImage(source: imageSource) { image in
image
.resizable()
.aspectRatio(contentMode: .fit)
}
.animation(.easeIn(duration: 0.2), value: imageSource)
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
@ViewBuilder
private func video() -> some View {
ZStack {
if player.mediaType == .audio {
artwork(for: player.metadata.imageSource)
}
else if player.isExternalPlaybackActive {
image(name: "tv")
}
else if isMonoscopic {
MonoscopicVideoView(player: player)
}
else {
VideoView(player: player)
.gravity(gravity)
.supportsPictureInPicture(supportsPictureInPicture)
}
}
.opacity(player.mediaType != .unknown ? 1 : 0)
.animation(.easeIn(duration: 0.2), values: player.mediaType, player.isExternalPlaybackActive)
}
@ViewBuilder
private func controls() -> some View {
ZStack {
Color(white: 0, opacity: 0.5)
.ignoresSafeArea()
ControlsView(player: player, progressTracker: progressTracker)
}
.opacity(shouldHideInterface ? 0 : 1)
}
@ViewBuilder
private func skipButton() -> some View {
SkipButton(player: player, progressTacker: progressTracker)
.padding(.trailing, 20)
.frame(maxWidth: .infinity, alignment: .trailing)
}
@ViewBuilder
private func image(name: String) -> some View {
Image(systemName: name)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(maxWidth: .infinity, maxHeight: .infinity)
// https://www.hackingwithswift.com/quick-start/swiftui/how-to-control-the-tappable-area-of-a-view-using-contentshape
.contentShape(Rectangle())
.foregroundColor(.white)
.padding(60)
}
}
private struct SkipButton: View {
let player: Player
@ObservedObject var progressTacker: ProgressTracker
private var skippableTimeRange: TimeRange? {
player.skippableTimeRange(at: progressTacker.time)
}
var body: some View {
Button(action: skip) {
Text("Skip")
.font(.subheadline)
.bold()
.foregroundStyle(.white)
.padding(.vertical, 8)
.padding(.horizontal, 10)
.background {
RoundedRectangle(cornerRadius: 2)
.fill(Color(white: 0.1))
RoundedRectangle(cornerRadius: 2)
.stroke(lineWidth: 2.0)
.foregroundStyle(Color(white: 0.3))
}
}
.opacity(skippableTimeRange != nil ? 1 : 0)
.animation(.easeInOut, value: skippableTimeRange)
}
private func skip() {
guard let skippableTimeRange else { return }
player.seek(to: skippableTimeRange.end)
}
}
private struct ControlsView: View {
@ObservedObject var player: Player
@ObservedObject var progressTracker: ProgressTracker
var body: some View {
HStack(spacing: 30) {
SkipBackwardButton(player: player, progressTracker: progressTracker)
PlaybackButton(player: player)
SkipForwardButton(player: player, progressTracker: progressTracker)
}
._debugBodyCounter(color: .green)
.animation(.defaultLinear, value: player.playbackState)
.bind(progressTracker, to: player)
}
}
// Behavior: h-hug, v-hug
private struct SkipBackwardButton: View {
@ObservedObject var player: Player
@ObservedObject var progressTracker: ProgressTracker
var body: some View {
Button(action: skipBackward) {
Image(systemName: "gobackward.10")
.resizable()
.tint(.white)
}
.aspectRatio(contentMode: .fit)
.frame(height: 45)
.opacity(player.canSkipBackward() ? 1 : 0)
.animation(.defaultLinear, value: player.canSkipBackward())
.keyboardShortcut("s", modifiers: [])
}
private func skipBackward() {
player.skipBackward()
}
}
// Behavior: h-hug, v-hug
private struct SkipForwardButton: View {
@ObservedObject var player: Player
@ObservedObject var progressTracker: ProgressTracker
var body: some View {
Button(action: skipForward) {
Image(systemName: "goforward.10")
.resizable()
.tint(.white)
}
.aspectRatio(contentMode: .fit)
.frame(height: 45)
.opacity(player.canSkipForward() ? 1 : 0)
.animation(.defaultLinear, value: player.canSkipForward())
.keyboardShortcut("d", modifiers: [])
}
private func skipForward() {
player.skipForward()
}
}
// Behavior: h-hug, v-hug
private struct FullScreenButton: View {
@Binding var layout: PlaybackView.Layout
var body: some View {
if let imageName {
Button(action: toggleFullScreen) {
Image(systemName: imageName)
.tint(.white)
.font(.system(size: 20))
}
.keyboardShortcut("f", modifiers: [])
}
}
private var imageName: String? {
switch layout {
case .inline:
return nil
case .minimized:
return "arrow.up.left.and.arrow.down.right"
case .maximized:
return "arrow.down.right.and.arrow.up.left"
}
}
private func toggleFullScreen() {
switch layout {
case .minimized:
layout = .maximized
case .maximized:
layout = .minimized
default:
break
}
}
}
// Behavior: h-hug, v-hug
private struct VolumeButton: View {
@ObservedObject var player: Player
var body: some View {
Button(action: toggleMuted) {
Image(systemName: imageName)
.tint(.white)
.font(.system(size: 20))
}
.keyboardShortcut("m", modifiers: [])
}
private var imageName: String {
player.isMuted ? "speaker.slash.fill" : "speaker.wave.3.fill"
}
private func toggleMuted() {
player.isMuted.toggle()
}
}
private struct SettingsMenu: View {
let player: Player
@Binding var isPresentingMetrics: Bool
var body: some View {
Menu {
player.standardSettingMenu()
QualityMenu(player: player)
metricsMenu()
} label: {
Image(systemName: "ellipsis.circle")
.font(.system(size: 20))
.tint(.white)
}
.menuOrder(.fixed)
}
@ViewBuilder
private func metricsMenu() -> some View {
if !isPresentingMetrics {
Button(action: showMetrics) {
Label("Metrics", systemImage: "chart.bar")
}
}
}
private func showMetrics() {
isPresentingMetrics = true
}
}
private struct QualityMenu: View {
let player: Player
@AppStorage(UserDefaults.DemoSettingKey.qualitySetting.rawValue)
private var qualitySetting: QualitySetting = .high
var body: some View {
Menu {
Picker("Quality", selection: $qualitySetting) {
ForEach(QualitySetting.allCases, id: \.self) { quality in
Text(quality.name).tag(quality)
}
}
.pickerStyle(.inline)
} label: {
Label {
Text("Quality")
} icon: {
Image(systemName: "person.and.background.dotted")
}
}
}
}
// Behavior: h-hug, v-hug
private struct LoadingIndicator: View {
let player: Player
@State private var isBuffering = false
var body: some View {
ProgressView()
.tint(.white)
.opacity(isBuffering ? 1 : 0)
.animation(.linear(duration: 0.1), value: isBuffering)
.accessibilityHidden(true)
.onReceive(player: player, assign: \.isBuffering, to: $isBuffering)
}
}
// Behavior: h-hug, v-hug
private struct LiveLabel: View {
@ObservedObject var player: Player
@ObservedObject var progressTracker: ProgressTracker
@State private var streamType: StreamType = .unknown
private var canSkipToLive: Bool {
player.canSkipToDefault()
}
private var liveButtonColor: Color {
canSkipToLive && streamType == .dvr ? .gray : .red
}
var body: some View {
Group {
if streamType == .dvr || streamType == .live {
Text("LIVE")
.font(.footnote)
.padding(.horizontal, 7)
.background(liveButtonColor)
.foregroundColor(.white)
.clipShape(.capsule)
}
}
.onReceive(player: player, assign: \.streamType, to: $streamType)
}
}
// Behavior: h-hug, v-hug
private struct LiveButton: View {
@ObservedObject var player: Player
@ObservedObject var progressTracker: ProgressTracker
@State private var streamType: StreamType = .unknown
private var canSkipToLive: Bool {
streamType == .dvr && player.canSkipToDefault()
}
var body: some View {
Group {
if canSkipToLive {
Button(action: skipToLive) {
Image(systemName: "forward.end.fill")
.foregroundStyle(.white)
.fontWeight(.ultraLight)
.font(.system(size: 20))
}
.accessibilityLabel("Jump to live")
}
}
.onReceive(player: player, assign: \.streamType, to: $streamType)
}
private func skipToLive() {
player.skipToDefault()
}
}
// Behavior: h-exp, v-hug
private struct TimeBar: View {
@ObservedObject var player: Player
@ObservedObject var visibilityTracker: VisibilityTracker
@Binding var isInteracting: Bool
@StateObject private var progressTracker = ProgressTracker(
interval: CMTime(value: 1, timescale: 10),
seekBehavior: UserDefaults.standard.seekBehavior
)
var body: some View {
TimeSlider(player: player, progressTracker: progressTracker, visibilityTracker: visibilityTracker)
.onChange(of: progressTracker.isInteracting) { isInteracting = $0 }
.bind(progressTracker, to: player)
}
}
// Behavior: h-exp, v-hug
private struct TimeSlider: View {
private static let shortFormatter: DateComponentsFormatter = {
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.second, .minute]
formatter.zeroFormattingBehavior = .pad
return formatter
}()
private static let longFormatter: DateComponentsFormatter = {
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.second, .minute, .hour]
formatter.zeroFormattingBehavior = .pad
return formatter
}()
private static let timeFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .none
formatter.timeStyle = .medium
return formatter
}()
@ObservedObject var player: Player
@ObservedObject var progressTracker: ProgressTracker
@ObservedObject var visibilityTracker: VisibilityTracker
@State private var streamType: StreamType = .unknown
private var formattedElapsedTime: String? {
if streamType == .onDemand {
return Self.formattedTime((progressTracker.time - progressTracker.timeRange.start), duration: progressTracker.timeRange.duration)
}
else if let date = progressTracker.date() {
return Self.timeFormatter.string(from: date)
}
else {
return nil
}
}
private var formattedTotalTime: String? {
guard streamType == .onDemand else { return nil }
return Self.formattedTime(progressTracker.timeRange.duration, duration: progressTracker.timeRange.duration)
}
private var isVisible: Bool {
progressTracker.isProgressAvailable && streamType != .unknown
}
var body: some View {
PlaybackSlider(
progressTracker: progressTracker,
timeRanges: player.metadata.timeRanges,
minimumValueLabel: {
label(withText: formattedElapsedTime)
},
maximumValueLabel: {
label(withText: formattedTotalTime)
},
onDragging: {
if UserDefaults.standard.seekBehavior == .deferred {
visibilityTracker.reset()
}
}
)
.foregroundColor(.white)
.tint(.white)
.shadow(color: .init(white: 0.2, opacity: 0.8), radius: 15)
.opacity(isVisible ? 1 : 0)
._debugBodyCounter(color: .blue)
.onReceive(player: player, assign: \.streamType, to: $streamType)
}
private static func formattedTime(_ time: CMTime, duration: CMTime) -> String? {
guard time.isValid, duration.isValid else { return nil }
if duration.seconds < 60 * 60 {
return shortFormatter.string(from: time.seconds)!
}
else {
return longFormatter.string(from: time.seconds)!
}
}
@ViewBuilder
private func label(withText text: String?) -> some View {
if let text {
Text(text)
.font(.caption)
.monospacedDigit()
.foregroundColor(.white)
.shadow(color: .init(white: 0.2, opacity: 0.8), radius: 15)
}
}
}
private struct AdaptiveSheetContainer<Content, Sheet>: View where Content: View, Sheet: View {
@Binding var isPresenting: Bool
@ViewBuilder let content: () -> Content
@ViewBuilder let sheet: () -> Sheet
@Environment(\.horizontalSizeClass) private var horizontalSizeClass
var body: some View {
switch horizontalSizeClass {
case .compact:
compactView()
default:
defaultView()
}
}
private func compactView() -> some View {
content()
.sheet(isPresented: $isPresenting) {
NavigationStack {
sheet()
}
.presentationDetents([.medium, .large])
}
}
private func defaultView() -> some View {
HStack(spacing: 0) {
content()
if isPresenting {
NavigationStack {
sheet()
.toolbar(content: toolbarContent)
}
.frame(width: 420)
}
}
.animation(.default, value: isPresenting)
}
private func toolbarContent() -> some ToolbarContent {
ToolbarItem(placement: .topBarLeading) {
Button("Hide", action: close)
}
}
private func close() {
isPresenting = false
}
}
#else
private struct MainSystemView: View {
let player: Player
let supportsPictureInPicture: Bool
@ObservedObject var progressTracker: ProgressTracker
private var contextualActions: [ContextualAction] {
if let skippableTimeRange = player.skippableTimeRange(at: progressTracker.time) {
return [
.init(title: "Skip") {
player.seek(to: skippableTimeRange.end)
}
]
}
else {
return []
}
}
var body: some View {
SystemVideoView(player: player)
.supportsPictureInPicture(supportsPictureInPicture)
.contextualActions(contextualActions)
.ignoresSafeArea()
}
}
#endif
// Behavior: h-hug, v-hug
private struct PlaybackMessageView: View {
let title: String
let subtitle: String?
var body: some View {
VStack {
Text(title)
.foregroundColor(.white)
.font(.body)
if let subtitle {
Text(subtitle)
.foregroundColor(Color(uiColor: .lightGray))
.font(.subheadline)
#if os(iOS)
.textSelection(.enabled)
#endif
}
}
.padding()
.multilineTextAlignment(.center)
}
init(title: String, subtitle: String? = nil) {
self.title = title
self.subtitle = subtitle
}
}
// Behavior: h-hug, v-hug
private struct PlaybackButton: View {
@ObservedObject var player: Player
private var imageName: String {
if player.canReplay() {
return "arrow.counterclockwise.circle.fill"
}
else if player.shouldPlay {
return "pause.circle.fill"
}
else {
return "play.circle.fill"
}
}
private var accessibilityLabel: String {
if player.canReplay() {
return "Restart"
}
else if player.shouldPlay {
return "Pause"
}
else {
return "Play"
}
}
var body: some View {
Button(action: play) {
Image(systemName: imageName)
.resizable()
.tint(.white)
}
#if os(iOS)
.keyboardShortcut(.space, modifiers: [])
#endif
.aspectRatio(contentMode: .fit)
.frame(minWidth: 120, maxHeight: 90)
.accessibilityLabel(accessibilityLabel)
}
private func play() {
if player.canReplay() {
player.replay()
}
else {
player.togglePlayPause()
}
}
}
private struct ErrorView: View {
let description: String
@ObservedObject var player: Player
private var subtitle: String? {
let sessionIdentifiers = player.currentSessionIdentifiers(trackedBy: MetricsTracker.self)
guard !sessionIdentifiers.isEmpty else { return nil }
return "Monitoring: \(sessionIdentifiers.joined(separator: ", "))"
}
var body: some View {
VStack {
PlaybackButton(player: player)
PlaybackMessageView(title: description, subtitle: subtitle)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.overlay(alignment: .topLeading) {
CloseButton(topBarStyle: true)
}
}
}
/// A playback view with standard controls. Requires an ancestor view to own the player to be used.
/// Behavior: h-exp, v-exp
struct PlaybackView: View {
enum Layout {
case inline
case minimized
case maximized
}
@ObservedObject private var player: Player
@Binding private var layout: Layout
@State private var progressTracker = ProgressTracker(interval: CMTime(value: 1, timescale: 1))
private var supportsPictureInPicture = false
var body: some View {
ZStack {
if let error = player.error {
ErrorView(description: error.localizedDescription, player: player)
}
else if !player.items.isEmpty {
mainView()
.persistentSystemOverlays(.hidden)
}
else {
PlaybackMessageView(title: "No content")
.frame(maxWidth: .infinity, maxHeight: .infinity)
.overlay(alignment: .topLeading) {
CloseButton(topBarStyle: true)
}
}
}
.background(.black)
.bind(progressTracker, to: player)
}
private var isMonoscopic: Bool {
player.metadata.viewport == .monoscopic
}
init(player: Player, layout: Binding<Layout> = .constant(.inline)) {
self.player = player
_layout = layout
}
@ViewBuilder
private func mainView() -> some View {
ZStack {
#if os(iOS)
MainView(
player: player,
layout: $layout,
supportsPictureInPicture: supportsPictureInPicture,
progressTracker: progressTracker
)
#else
if isMonoscopic {
VideoView(player: player)
.ignoresSafeArea()
}
else {
MainSystemView(
player: player,
supportsPictureInPicture: supportsPictureInPicture,
progressTracker: progressTracker
)
}
#endif
}
._debugBodyCounter()
}
}
extension PlaybackView {
func supportsPictureInPicture(_ supportsPictureInPicture: Bool = true) -> PlaybackView {
var view = self
view.supportsPictureInPicture = supportsPictureInPicture
return view
}
}
private extension Player {
func skippableTimeRange(at time: CMTime) -> TimeRange? {
metadata.timeRanges.first { timeRange in
if case .credits = timeRange.kind, timeRange.containsTime(time) {
return true
}
else {
return false
}
}
}
}
#Preview {
PlaybackView(player: Player(item: URLMedia.onDemandVideoLocalHLS.item()))
}