-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathSRGMediaPlayerController.m
2187 lines (1808 loc) · 92.7 KB
/
SRGMediaPlayerController.m
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
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Copyright (c) SRG SSR. All rights reserved.
//
// License information is available from the LICENSE file.
//
#import "SRGMediaPlayerController.h"
#import "AVAudioSession+SRGMediaPlayer.h"
#import "AVMediaSelectionGroup+SRGMediaPlayer.h"
#import "AVPlayerItem+SRGMediaPlayer.h"
#import "CMTime+SRGMediaPlayer.h"
#import "CMTimeRange+SRGMediaPlayer.h"
#import "MAKVONotificationCenter+SRGMediaPlayer.h"
#import "NSBundle+SRGMediaPlayer.h"
#import "NSTimer+SRGMediaPlayer.h"
#import "SRGActivityGestureRecognizer.h"
#import "SRGMediaAccessibility.h"
#import "SRGMediaPlayerError.h"
#import "SRGMediaPlayerLogger.h"
#import "SRGMediaPlayerView.h"
#import "SRGMediaPlayerView+Private.h"
#import "SRGPeriodicTimeObserver.h"
#import "SRGPlayer.h"
#import "SRGSegment+Private.h"
#import "SRGTimePosition.h"
#import "UIDevice+SRGMediaPlayer.h"
#import "UIScreen+SRGMediaPlayer.h"
#import <libextobjc/libextobjc.h>
#import <MAKVONotificationCenter/MAKVONotificationCenter.h>
#import <objc/runtime.h>
static const NSTimeInterval SRGSegmentSeekOffsetInSeconds = 0.1;
static NSError *SRGMediaPlayerControllerError(NSError *underlyingError);
static NSString *SRGMediaPlayerControllerNameForPlaybackState(SRGMediaPlayerPlaybackState playbackState);
static NSString *SRGMediaPlayerControllerNameForMediaType(SRGMediaPlayerMediaType mediaType);
static NSString *SRGMediaPlayerControllerNameForStreamType(SRGMediaPlayerStreamType streamType);
static SRGTimePosition *SRGMediaPlayerControllerOffset(SRGTimePosition *position, CMTime offset);
static SRGTimePosition *SRGMediaPlayerControllerPositionInTimeRange(SRGTimePosition *position, CMTimeRange timeRange);
static AVMediaSelectionOption *SRGMediaPlayerControllerAutomaticAudioDefaultOption(NSArray<AVMediaSelectionOption *> *audioOptions);
static AVMediaSelectionOption *SRGMediaPlayerControllerAutomaticSubtitleDefaultOption(NSArray<AVMediaSelectionOption *> *subtitleOptions, AVMediaSelectionOption *audioOption);
static AVMediaSelectionOption *SRGMediaPlayerControllerSubtitleDefaultOption(NSArray<AVMediaSelectionOption *> *subtitleOptions, AVMediaSelectionOption *audioOption);
static AVMediaSelectionOption *SRGMediaPlayerControllerSubtitleDefaultLanguageOption(NSArray<AVMediaSelectionOption *> *subtitleOptions, NSString *language);
@interface SRGMediaPlayerController () <SRGMediaPlayerViewDelegate, SRGPlayerDelegate> {
@private
SRGMediaPlayerPlaybackState _playbackState;
BOOL _selected;
}
@property (nonatomic) SRGPlayer *player;
@property (nonatomic) NSURL *contentURL;
@property (nonatomic) AVURLAsset *URLAsset;
@property (nonatomic) NSDictionary *userInfo;
@property (nonatomic, copy) void (^playerCreationBlock)(AVPlayer *player);
@property (nonatomic, copy) void (^playerConfigurationBlock)(AVPlayer *player);
@property (nonatomic, copy) void (^playerDestructionBlock)(AVPlayer *player);
@property (nonatomic, copy) AVMediaSelectionOption * (^audioConfigurationBlock)(NSArray<AVMediaSelectionOption *> *audioOptions, AVMediaSelectionOption *defaultAudioOption);
@property (nonatomic, copy) AVMediaSelectionOption * (^subtitleConfigurationBlock)(NSArray<AVMediaSelectionOption *> *subtitleOptions, AVMediaSelectionOption *audioOption, AVMediaSelectionOption *defaultAudioOption);
@property (nonatomic) SRGMediaPlayerViewBackgroundBehavior viewBackgroundBehavior;
@property (nonatomic, readonly) SRGMediaPlayerPlaybackState playbackState;
@property (nonatomic) NSArray<id<SRGSegment>> *loadedSegments;
@property (nonatomic) NSArray<id<SRGSegment>> *visibleSegments;
@property (nonatomic) NSMutableDictionary<NSString *, SRGPeriodicTimeObserver *> *periodicTimeObservers;
@property (nonatomic) id playerPeriodicTimeObserver; // AVPlayer time observer, needs to be retained according to the documentation
@property (nonatomic, weak) id controllerPeriodicTimeObserver;
@property (nonatomic) SRGMediaPlayerMediaType mediaType;
@property (nonatomic) CMTimeRange timeRange;
@property (nonatomic, getter=isTimeRangeCached) BOOL timeRangeCached;
@property (nonatomic) SRGMediaPlayerStreamType streamType;
@property (nonatomic, getter=isStreamTypeCached) BOOL streamTypeCached;
@property (nonatomic, getter=isLive) BOOL live;
@property (nonatomic) CMTime referenceTime;
@property (nonatomic) NSDate *referenceDate;
@property (nonatomic) NSTimer *stallDetectionTimer;
@property (nonatomic) CMTime lastPlaybackTime;
@property (nonatomic) NSDate *lastStallDetectionDate;
// Saved values supplied when playback is started
@property (nonatomic, weak) id<SRGSegment> initialTargetSegment;
@property (nonatomic) SRGPosition *initialPosition;
@property (nonatomic, weak) id<SRGSegment> previousSegment;
@property (nonatomic, weak) id<SRGSegment> targetSegment; // Will be nilled when reached
@property (nonatomic, weak) id<SRGSegment> currentSegment;
#if TARGET_OS_IOS
@property (nonatomic) AVPictureInPictureController *pictureInPictureController;
@property (nonatomic, copy) void (^pictureInPictureControllerCreationBlock)(AVPictureInPictureController *pictureInPictureController);
@property (nonatomic) NSNumber *savedAllowsExternalPlayback;
#endif
@property (nonatomic) NSNumber *savedPreventsDisplaySleepDuringVideoPlayback API_AVAILABLE(ios(12.0), tvos(12.0));
@property (nonatomic) SRGPosition *startPosition; // Will be nilled when reached
@property (nonatomic, copy) void (^startCompletionHandler)(void);
@property (nonatomic) NSValue *presentationSizeValue;
@property (nonatomic) AVMediaSelectionOption *audioOption;
@property (nonatomic) AVMediaSelectionOption *subtitleOption;
@property (nonatomic, weak) AVPlayerViewController *playerViewController;
@end
@implementation SRGMediaPlayerController
@synthesize view = _view;
#if TARGET_OS_IOS
@synthesize pictureInPictureController = _pictureInPictureController;
#endif
#pragma mark Object lifecycle
- (instancetype)init
{
if (self = [super init]) {
_playbackState = SRGMediaPlayerPlaybackStateIdle;
self.liveTolerance = SRGMediaPlayerDefaultLiveTolerance;
self.endTolerance = SRGMediaPlayerDefaultEndTolerance;
self.endToleranceRatio = SRGMediaPlayerDefaultEndToleranceRatio;
self.periodicTimeObservers = [NSMutableDictionary dictionary];
self.lastPlaybackTime = kCMTimeIndefinite;
}
return self;
}
- (void)dealloc
{
[self reset];
}
#pragma mark Getters and setters
- (void)setPlayer:(SRGPlayer *)player
{
BOOL hadPlayer = (_player != nil);
if (_player) {
[self unregisterTimeObserversForPlayer:_player];
[_player removeObserver:self keyPath:@keypath(_player.currentItem.status)];
[_player removeObserver:self keyPath:@keypath(_player.rate)];
[_player removeObserver:self keyPath:@keypath(_player.externalPlaybackActive)];
[_player removeObserver:self keyPath:@keypath(_player.currentItem.playbackLikelyToKeepUp)];
[_player removeObserver:self keyPath:@keypath(_player.currentItem.presentationSize)];
[NSNotificationCenter.defaultCenter removeObserver:self
name:AVPlayerItemDidPlayToEndTimeNotification
object:_player.currentItem];
[NSNotificationCenter.defaultCenter removeObserver:self
name:AVPlayerItemFailedToPlayToEndTimeNotification
object:_player.currentItem];
[NSNotificationCenter.defaultCenter removeObserver:self
name:UIApplicationDidEnterBackgroundNotification
object:nil];
[NSNotificationCenter.defaultCenter removeObserver:self
name:UIApplicationWillEnterForegroundNotification
object:nil];
self.playerDestructionBlock ? self.playerDestructionBlock(_player) : nil;
}
_player = player;
[self attachPlayer:player toView:self.view];
if (player) {
if (! hadPlayer) {
self.playerCreationBlock ? self.playerCreationBlock(player) : nil;
}
[self registerTimeObserversForPlayer:player];
@weakify(self) @weakify(player)
[player srg_addMainThreadObserver:self keyPath:@keypath(player.currentItem.status) options:0 block:^(MAKVONotification *notification) {
@strongify(self) @strongify(player)
AVPlayerItem *playerItem = player.currentItem;
if (playerItem.status == AVPlayerItemStatusReadyToPlay) {
[self updatePlaybackInformationForPlayer:player];
// Playback start. Use received start parameters, do not update the playback state yet, wait until the
// completion handler has been executed (since it might immediately start playback)
if (self.startPosition) {
void (^completionBlock)(BOOL) = ^(BOOL finished) {
if (! finished) {
return;
}
self.view.playbackViewHidden = NO;
// Reset start time first so that the playback state induced change made in the completion handler
// does not loop back here
self.startPosition = nil;
self.startCompletionHandler ? self.startCompletionHandler() : nil;
self.startCompletionHandler = nil;
// If the state of the player was not changed in the completion handler (still preparing), update
// it
if (self.playbackState == SRGMediaPlayerPlaybackStatePreparing) {
[self setPlaybackState:(player.rate == 0.f) ? SRGMediaPlayerPlaybackStatePaused : SRGMediaPlayerPlaybackStatePlaying withUserInfo:nil];
}
};
SRGTimePosition *startTimePosition = [self streamTimePositionForPosition:self.startPosition];
// Default position. Nothing to do.
if (CMTIME_COMPARE_INLINE(startTimePosition.time, ==, kCMTimeZero) && ! self.targetSegment) {
completionBlock(YES);
}
// Non-default start position. Calculate a valid position to seek to.
else {
// If a segment is targeted, add a small offset so that playback is guaranteed to start within the segment
if (self.targetSegment) {
startTimePosition = SRGMediaPlayerControllerOffset(startTimePosition, CMTimeMakeWithSeconds(SRGSegmentSeekOffsetInSeconds, NSEC_PER_SEC));
}
// Take into account tolerance at the end of the content being played. If near the end enough, start
// at the default position instead.
CMTimeRange timeRange = self.targetSegment ? [self streamTimeRangeForMarkRange:self.targetSegment.srg_markRange] : self.timeRange;
CMTime tolerance = SRGMediaPlayerEffectiveEndTolerance(self.endTolerance, self.endToleranceRatio, CMTimeGetSeconds(timeRange.duration));
CMTime toleratedStartTime = CMTIME_COMPARE_INLINE(startTimePosition.time, >=, CMTimeSubtract(timeRange.duration, tolerance)) ? kCMTimeZero : startTimePosition.time;
// Positions in segments are relative. If not within a segment, they are absolute (relative positions
// are misleading for a DVR stream with a sliding window, and match the absolute position in other cases)
if (self.targetSegment) {
toleratedStartTime = CMTimeAdd(toleratedStartTime, timeRange.start);
}
SRGTimePosition *toleratedTimePosition = [SRGTimePosition positionWithTime:toleratedStartTime toleranceBefore:startTimePosition.toleranceBefore toleranceAfter:startTimePosition.toleranceAfter];
SRGTimePosition *seekTimePosition = SRGMediaPlayerControllerPositionInTimeRange(toleratedTimePosition, timeRange);
if (self.streamType != SRGMediaPlayerStreamTypeDVR || CMTIME_COMPARE_INLINE(seekTimePosition.time, !=, kCMTimeZero)) {
[player seekToTime:seekTimePosition.time toleranceBefore:seekTimePosition.toleranceBefore toleranceAfter:seekTimePosition.toleranceAfter notify:NO completionHandler:^(BOOL finished) {
completionBlock(finished);
}];
}
else {
completionBlock(YES);
}
}
}
}
else if (playerItem.status == AVPlayerItemStatusFailed) {
[self stopWithUserInfo:nil];
NSError *error = SRGMediaPlayerControllerError(playerItem.error);
[NSNotificationCenter.defaultCenter postNotificationName:SRGMediaPlayerPlaybackDidFailNotification
object:self
userInfo:@{ SRGMediaPlayerErrorKey: error }];
SRGMediaPlayerLogDebug(@"Controller", @"Playback did fail with error: %@", error);
}
}];
[player srg_addMainThreadObserver:self keyPath:@keypath(player.rate) options:0 block:^(MAKVONotification *notification) {
@strongify(self) @strongify(player)
AVPlayerItem *playerItem = player.currentItem;
// Only respond to rate changes when the item is ready to play
if (playerItem.status != AVPlayerItemStatusReadyToPlay) {
return;
}
CMTime currentTime = playerItem.currentTime;
CMTimeRange timeRange = self.timeRange;
// Update the playback state immediately, except when reaching the end or seeking. Non-streamed medias will namely reach the paused state right before
// the item end notification is received. We can eliminate this pause by checking if we are at the end or not. Also update the state for
// live streams (empty range)
if (self.playbackState != SRGMediaPlayerPlaybackStateEnded
&& self.playbackState != SRGMediaPlayerPlaybackStateSeeking
&& (CMTIMERANGE_IS_EMPTY(timeRange) || CMTIME_COMPARE_INLINE(currentTime, !=, CMTimeRangeGetEnd(timeRange)))) {
[self setPlaybackState:(player.rate == 0.f) ? SRGMediaPlayerPlaybackStatePaused : SRGMediaPlayerPlaybackStatePlaying withUserInfo:nil];
}
// Playback restarted after it ended (see -play and -pause)
else if (self.playbackState == SRGMediaPlayerPlaybackStateEnded && player.rate != 0.f) {
[self setPlaybackState:SRGMediaPlayerPlaybackStatePlaying withUserInfo:nil];
}
}];
[player srg_addMainThreadObserver:self keyPath:@keypath(player.externalPlaybackActive) options:0 block:^(MAKVONotification *notification) {
@strongify(self)
#if TARGET_OS_IOS
@strongify(player)
// Pause playback when toggling off external playback with the app in background, if settings prevent playback to continue in background
if (! player.externalPlaybackActive && self.mediaType == SRGMediaPlayerMediaTypeVideo && UIApplication.sharedApplication.applicationState == UIApplicationStateBackground) {
BOOL supportsBackgroundVideoPlayback = self.viewBackgroundBehavior == SRGMediaPlayerViewBackgroundBehaviorDetached
|| (self.viewBackgroundBehavior == SRGMediaPlayerViewBackgroundBehaviorDetachedWhenDeviceLocked && UIDevice.srg_mediaPlayer_isLocked);
if (! supportsBackgroundVideoPlayback) {
[player pause];
}
}
#endif
[self reloadPlayerConfiguration];
[NSNotificationCenter.defaultCenter postNotificationName:SRGMediaPlayerExternalPlaybackStateDidChangeNotification object:self];
}];
[player srg_addMainThreadObserver:self keyPath:@keypath(player.currentItem.playbackLikelyToKeepUp) options:0 block:^(MAKVONotification *notification) {
@strongify(self) @strongify(player)
if (player.currentItem.playbackLikelyToKeepUp && self.playbackState == SRGMediaPlayerPlaybackStateStalled) {
[self setPlaybackState:(player.rate == 0.f) ? SRGMediaPlayerPlaybackStatePaused : SRGMediaPlayerPlaybackStatePlaying withUserInfo:nil];
}
}];
[player srg_addMainThreadObserver:self keyPath:@keypath(player.currentItem.presentationSize) options:0 block:^(MAKVONotification * _Nonnull notification) {
@strongify(self) @strongify(player)
self.presentationSizeValue = [NSValue valueWithCGSize:player.currentItem.presentationSize];
[self updateMediaTypeForPlayer:player];
}];
[NSNotificationCenter.defaultCenter addObserver:self
selector:@selector(srg_mediaPlayerController_playerItemDidPlayToEndTime:)
name:AVPlayerItemDidPlayToEndTimeNotification
object:player.currentItem];
[NSNotificationCenter.defaultCenter addObserver:self
selector:@selector(srg_mediaPlayerController_playerItemFailedToPlayToEndTime:)
name:AVPlayerItemFailedToPlayToEndTimeNotification
object:player.currentItem];
[NSNotificationCenter.defaultCenter addObserver:self
selector:@selector(srg_mediaPlayerController_applicationDidEnterBackground:)
name:UIApplicationDidEnterBackgroundNotification
object:nil];
[NSNotificationCenter.defaultCenter addObserver:self
selector:@selector(srg_mediaPlayerController_applicationWillEnterForeground:)
name:UIApplicationWillEnterForegroundNotification
object:nil];
[self reloadPlayerConfiguration];
}
}
- (void)setStallDetectionTimer:(NSTimer *)stallDetectionTimer
{
[_stallDetectionTimer invalidate];
_stallDetectionTimer = stallDetectionTimer;
}
- (AVPlayerLayer *)playerLayer
{
return self.view.playerLayer;
}
- (void)setPlaybackState:(SRGMediaPlayerPlaybackState)playbackState withUserInfo:(NSDictionary *)userInfo
{
NSAssert(NSThread.isMainThread, @"Not the main thread. Ensure important changes must be notified on the main thread. Fix");
if (_playbackState == playbackState) {
return;
}
SRGMediaPlayerPlaybackState previousPlaybackState = _playbackState;
NSMutableDictionary *fullUserInfo = @{ SRGMediaPlayerPlaybackStateKey : @(playbackState),
SRGMediaPlayerPreviousPlaybackStateKey: @(previousPlaybackState) }.mutableCopy;
fullUserInfo[SRGMediaPlayerSelectionKey] = @(self.targetSegment && ! self.targetSegment.srg_blocked);
if (userInfo) {
[fullUserInfo addEntriesFromDictionary:userInfo];
}
[self willChangeValueForKey:@keypath(self.playbackState)];
_playbackState = playbackState;
[self didChangeValueForKey:@keypath(self.playbackState)];
[self updateStallDetectionTimerForPlaybackState:playbackState];
[self updateSegmentStatusForPlaybackState:playbackState previousPlaybackState:previousPlaybackState time:self.currentTime];
[NSNotificationCenter.defaultCenter postNotificationName:SRGMediaPlayerPlaybackStateDidChangeNotification
object:self
userInfo:fullUserInfo.copy];
SRGMediaPlayerLogDebug(@"Controller", @"Playback state did change to %@ with info %@", SRGMediaPlayerControllerNameForPlaybackState(playbackState), fullUserInfo);
}
- (void)setMediaType:(SRGMediaPlayerMediaType)mediaType
{
if (mediaType == _mediaType) {
return;
}
[self willChangeValueForKey:@keypath(self.mediaType)];
_mediaType = mediaType;
[self didChangeValueForKey:@keypath(self.mediaType)];
}
- (void)setTimeRange:(CMTimeRange)timeRange
{
if (CMTimeRangeEqual(timeRange, _timeRange)) {
return;
}
[self willChangeValueForKey:@keypath(self.timeRange)];
_timeRange = timeRange;
[self didChangeValueForKey:@keypath(self.timeRange)];
}
- (void)setStreamType:(SRGMediaPlayerStreamType)streamType
{
if (streamType == _streamType) {
return;
}
[self willChangeValueForKey:@keypath(self.streamType)];
_streamType = streamType;
[self didChangeValueForKey:@keypath(self.streamType)];
}
- (void)setLive:(BOOL)live
{
if (live == _live) {
return;
}
[self willChangeValueForKey:@keypath(self.live)];
_live = live;
[self didChangeValueForKey:@keypath(self.live)];
}
- (NSArray<id<SRGSegment>> *)segments
{
return self.loadedSegments;
}
- (void)setSegments:(NSArray<id<SRGSegment>> *)segments
{
self.loadedSegments = segments;
[self updateSegmentStatusForPlaybackState:self.playbackState previousPlaybackState:self.playbackState time:self.currentTime];
}
- (void)setLoadedSegments:(NSArray<id<SRGSegment>> *)segments
{
if (segments && self.previousSegment) {
NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(id<SRGSegment> _Nonnull segment, NSDictionary<NSString *, id> *_Nullable bindings) {
return SRGMediaPlayerAreEqualSegments(segment, self.previousSegment);
}];
// Only update if a segment equivalent to the previous one was found (segment transition processing will update
// the previous segment otherwise)
id<SRGSegment> segment = [segments filteredArrayUsingPredicate:predicate].firstObject;
if (segment) {
self.previousSegment = segment;
}
}
if (segments && self.targetSegment) {
NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(id<SRGSegment> _Nonnull segment, NSDictionary<NSString *, id> *_Nullable bindings) {
return SRGMediaPlayerAreEqualSegments(segment, self.targetSegment);
}];
// Similar to comment above
id<SRGSegment> segment = [segments filteredArrayUsingPredicate:predicate].firstObject;
if (segment) {
self.targetSegment = segment;
}
}
if (segments && self.currentSegment) {
NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(id<SRGSegment> _Nonnull segment, NSDictionary<NSString *, id> *_Nullable bindings) {
return SRGMediaPlayerAreEqualSegments(segment, self.currentSegment);
}];
// Similar to comment above
id<SRGSegment> segment = [segments filteredArrayUsingPredicate:predicate].firstObject;
if (segment) {
self.currentSegment = segment;
}
}
_loadedSegments = segments;
// Reset the cached visible segment list
_visibleSegments = nil;
}
- (NSArray<id<SRGSegment>> *)visibleSegments
{
// Cached for faster access
if (! _visibleSegments) {
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"srg_hidden == NO"];
_visibleSegments = [self.segments filteredArrayUsingPredicate:predicate];
}
return _visibleSegments;
}
// Called when installing the view by binding it in a storyboard or xib
- (void)setView:(SRGMediaPlayerView *)view
{
if (_view != view) {
_view = view;
[self setupView:view];
}
}
// Called when lazily creating the view, not binding it
- (UIView *)view
{
if (! _view) {
_view = [[SRGMediaPlayerView alloc] init];
[self setupView:_view];
}
return _view;
}
- (void)setupView:(SRGMediaPlayerView *)view
{
view.delegate = self;
#if TARGET_OS_IOS
@weakify(self)
[view srg_addMainThreadObserver:self keyPath:@keypath(view.readyForDisplay) options:0 block:^(MAKVONotification * _Nonnull notification) {
@strongify(self)
[self updatePictureInPictureForView:view];
}];
[self updatePictureInPictureForView:view];
#endif
[self attachPlayer:self.player toView:view];
}
- (CMTimeRange)timeRangeForPlayerItem:(AVPlayerItem *)playerItem
{
if (playerItem.status != AVPlayerStatusReadyToPlay) {
return kCMTimeRangeInvalid;
}
NSValue *firstSeekableTimeRangeValue = [playerItem.seekableTimeRanges firstObject];
NSValue *lastSeekableTimeRangeValue = [playerItem.seekableTimeRanges lastObject];
CMTimeRange firstSeekableTimeRange = [firstSeekableTimeRangeValue CMTimeRangeValue];
CMTimeRange lastSeekableTimeRange = [lastSeekableTimeRangeValue CMTimeRangeValue];
if (! firstSeekableTimeRangeValue || CMTIMERANGE_IS_INVALID(firstSeekableTimeRange)
|| ! lastSeekableTimeRangeValue || CMTIMERANGE_IS_INVALID(lastSeekableTimeRange)) {
return (playerItem.loadedTimeRanges.count != 0) ? kCMTimeRangeZero : kCMTimeRangeInvalid;
}
CMTimeRange timeRange = CMTimeRangeFromTimeToTime(firstSeekableTimeRange.start, CMTimeRangeGetEnd(lastSeekableTimeRange));
// DVR window size too small. Check that we the stream is not an on-demand one first, of course
if (CMTIME_IS_INDEFINITE(playerItem.duration) && CMTimeGetSeconds(timeRange.duration) < self.minimumDVRWindowLength) {
return CMTimeRangeMake(timeRange.start, kCMTimeZero);
}
else {
return timeRange;
}
}
- (void)updatePlaybackInformationForPlayer:(AVPlayer *)player
{
[self updateMediaTypeForPlayer:player];
[self updateTimeRangeForPlayer:player];
[self updateStreamTypeForPlayer:player];
[self updateLiveForPlayer:player];
[self updateReferenceForPlayer:player];
}
- (void)updateMediaTypeForPlayer:(AVPlayer *)player
{
if (self.mediaType != SRGMediaPlayerMediaTypeUnknown) {
return;
}
// The presentation size is zero before the item is ready to play, see `presentationSize` documentation.
if (player.currentItem.status != AVPlayerStatusReadyToPlay) {
return;
}
// Cannot reliably determine the media type with AirPlay, most notably when playing a media while an AirPlay
// connection has already been established.
if ([AVAudioSession srg_isAirPlayActive]) {
return;
}
NSValue *presentationSizeValue = self.presentationSizeValue;
if (! presentationSizeValue) {
return;
}
self.mediaType = CGSizeEqualToSize(presentationSizeValue.CGSizeValue, CGSizeZero) ? SRGMediaPlayerMediaTypeAudio : SRGMediaPlayerMediaTypeVideo;
}
- (void)updateTimeRangeForPlayer:(AVPlayer *)player
{
if (self.timeRangeCached) {
return;
}
AVPlayerItem *playerItem = player.currentItem;
self.timeRange = [self timeRangeForPlayerItem:playerItem];
// On-demand time ranges are cached because they might become unreliable in some situations (e.g. when AirPlay is
// connected or disconnected)
if (SRG_CMTIME_IS_DEFINITE(playerItem.duration) && SRG_CMTIMERANGE_IS_NOT_EMPTY(self.timeRange)) {
self.timeRangeCached = YES;
}
}
- (void)updateStreamTypeForPlayer:(AVPlayer *)player
{
CMTimeRange timeRange = self.timeRange;
if (self.streamTypeCached || CMTIMERANGE_IS_INVALID(timeRange)) {
return;
}
if (CMTIMERANGE_IS_EMPTY(timeRange)) {
self.streamType = SRGMediaPlayerStreamTypeLive;
}
else {
CMTime duration = player.currentItem.duration;
if (CMTIME_IS_INDEFINITE(duration)) {
self.streamType = SRGMediaPlayerStreamTypeDVR;
}
else if (CMTIME_COMPARE_INLINE(duration, !=, kCMTimeZero)) {
self.streamType = SRGMediaPlayerStreamTypeOnDemand;
self.streamTypeCached = YES;
}
else {
self.streamType = SRGMediaPlayerStreamTypeLive;
}
}
}
- (void)updateLiveForPlayer:(AVPlayer *)player
{
if (self.streamType == SRGMediaPlayerStreamTypeLive) {
self.live = YES;
}
else if (self.streamType == SRGMediaPlayerStreamTypeDVR) {
AVPlayerItem *playerItem = player.currentItem;
self.live = CMTimeGetSeconds(CMTimeSubtract(CMTimeRangeGetEnd(self.timeRange), playerItem.currentTime)) < self.liveTolerance;
}
else {
self.live = NO;
}
}
- (void)updateReferenceForPlayer:(AVPlayer *)player
{
// We store synchronized current date and playhead position information for livestreams and update both regularly at the
// same time. When seeking, these two values might namely be briefly misaligned when read from the player item directly
// (provided the stream embedds date information, of course), leading to unreliable calculations using both values.
//
// If the stream does not embed date information, we use the current date as reference date, mapped to the end of
// the DVR window. This is less accurate or might be completely incorrect, especially if stream and device clocks are
// entirely different, but this is the best we can do.
if (self.streamType == SRGMediaPlayerStreamTypeDVR || self.streamType == SRGMediaPlayerStreamTypeLive) {
AVPlayerItem *playerItem = player.currentItem;
NSDate *currentDate = playerItem.currentDate;
if (currentDate) {
self.referenceDate = currentDate;
self.referenceTime = playerItem.currentTime;
}
else {
self.referenceDate = NSDate.date;
self.referenceTime = CMTimeRangeGetEnd(self.timeRange);
}
}
else {
self.referenceDate = nil;
self.referenceTime = kCMTimeIndefinite;
}
}
- (CMTime)currentTime
{
// If `AVPlayer` is idle (e.g. right after creation), its time is zero. Use the same convention here when no
// player is available.
return self.player ? self.player.currentTime : kCMTimeZero;
}
- (NSDate *)currentDate
{
return [self streamDateForTime:self.currentTime];
}
- (CMTime)seekStartTime
{
return self.player ? self.player.seekStartTime : kCMTimeIndefinite;
}
- (CMTime)seekTargetTime
{
return self.player ? self.player.seekTargetTime : kCMTimeIndefinite;
}
- (void)setMinimumDVRWindowLength:(NSTimeInterval)minimumDVRWindowLength
{
if (minimumDVRWindowLength < 0.) {
SRGMediaPlayerLogWarning(@"Controller", @"The minimum DVR window length cannot be negative. Set to 0");
_minimumDVRWindowLength = 0.;
}
else {
_minimumDVRWindowLength = minimumDVRWindowLength;
}
}
- (void)setLiveTolerance:(NSTimeInterval)liveTolerance
{
if (liveTolerance < 0.) {
SRGMediaPlayerLogWarning(@"Controller", @"Live tolerance cannot be negative. Set to 0");
_liveTolerance = 0.;
}
else {
_liveTolerance = liveTolerance;
}
}
- (void)setEndTolerance:(NSTimeInterval)endTolerance
{
if (endTolerance < 0.) {
SRGMediaPlayerLogWarning(@"Controller", @"End tolerance cannot be negative. Set to 0");
_endTolerance = 0.;
}
else {
_endTolerance = endTolerance;
}
}
- (void)setEndToleranceRatio:(float)endToleranceRatio
{
if (endToleranceRatio < 0.) {
SRGMediaPlayerLogWarning(@"Controller", @"End tolerance ratio cannot be negative. Set to 0");
_endToleranceRatio = 0.f;
}
else if (endToleranceRatio > 1.) {
SRGMediaPlayerLogWarning(@"Controller", @"End tolerance ratio cannot be larger than 1. Set to 1");
_endToleranceRatio = 1.f;
}
else {
_endToleranceRatio = endToleranceRatio;
}
}
- (void)setTextStyleRules:(NSArray<AVTextStyleRule *> *)textStyleRules
{
_textStyleRules = textStyleRules.copy;
self.player.currentItem.textStyleRules = _textStyleRules;
}
#if TARGET_OS_IOS
- (AVPictureInPictureController *)pictureInPictureController
{
if (self.playerViewController) {
return nil;
}
else {
return _pictureInPictureController;
}
}
- (void)setPictureInPictureController:(AVPictureInPictureController *)pictureInPictureController
{
if (_pictureInPictureController) {
[_pictureInPictureController removeObserver:self keyPath:@keypath(_pictureInPictureController.pictureInPicturePossible)];
[_pictureInPictureController removeObserver:self keyPath:@keypath(_pictureInPictureController.pictureInPictureActive)];
}
_pictureInPictureController = pictureInPictureController;
[NSNotificationCenter.defaultCenter postNotificationName:SRGMediaPlayerPictureInPictureStateDidChangeNotification object:self];
if (pictureInPictureController) {
@weakify(self)
[pictureInPictureController srg_addMainThreadObserver:self keyPath:@keypath(pictureInPictureController.pictureInPicturePossible) options:0 block:^(MAKVONotification * _Nonnull notification) {
@strongify(self)
[NSNotificationCenter.defaultCenter postNotificationName:SRGMediaPlayerPictureInPictureStateDidChangeNotification object:self];
}];
[pictureInPictureController srg_addMainThreadObserver:self keyPath:@keypath(pictureInPictureController.pictureInPictureActive) options:0 block:^(MAKVONotification * _Nonnull notification) {
@strongify(self)
[self reloadPlayerConfiguration];
[NSNotificationCenter.defaultCenter postNotificationName:SRGMediaPlayerPictureInPictureStateDidChangeNotification object:self];
}];
}
}
- (void)updatePictureInPictureForView:(SRGMediaPlayerView *)view
{
AVPlayerLayer *playerLayer = view.playerLayer;
if (playerLayer.readyForDisplay) {
if (self.pictureInPictureController.playerLayer != playerLayer) {
self.pictureInPictureController = [[AVPictureInPictureController alloc] initWithPlayerLayer:playerLayer];
self.pictureInPictureControllerCreationBlock ? self.pictureInPictureControllerCreationBlock(self.pictureInPictureController) : nil;
}
}
else {
self.pictureInPictureController = nil;
}
}
#endif
- (BOOL)allowsExternalNonMirroredPlayback
{
AVPlayer *player = self.player;
if (! player) {
return NO;
}
if (! player.allowsExternalPlayback) {
return NO;
}
if (! UIScreen.srg_isMirroring) {
return YES;
}
// If the player switches to external playback, then it does not mirror the display
return player.usesExternalPlaybackWhileExternalScreenIsActive;
}
- (BOOL)isExternalNonMirroredPlaybackActive
{
if (! AVAudioSession.srg_isAirPlayActive) {
return NO;
}
AVPlayer *player = self.player;
if (! player) {
return NO;
}
// We do not test the `externalPlaybackActive` property here, on purpose: The fact that AirPlay is active was
// tested just above, and the `externalPlaybackActive` property is less reliable in some cases where AirPlay
// settings are changed, but AirPlay is still active
if (! player.allowsExternalPlayback) {
return NO;
}
if (! UIScreen.srg_isMirroring) {
return player.externalPlaybackActive;
}
// If the player switches to external playback, then it does not mirror the display
return player.usesExternalPlaybackWhileExternalScreenIsActive;
}
#pragma mark Conversions
- (CMTime)streamTimeForMark:(SRGMark *)mark
{
CMTime time = [self streamTimeForDate:mark.date];
if (SRG_CMTIME_IS_DEFINITE(time)) {
return time;
}
else {
return [mark timeForMediaPlayerController:nil];
}
}
- (CMTimeRange)streamTimeRangeForMarkRange:(SRGMarkRange *)markRange
{
CMTime fromTime = [self streamTimeForMark:markRange.fromMark];
CMTime toTime = [self streamTimeForMark:markRange.toMark];
return CMTimeRangeFromTimeToTime(fromTime, toTime);
}
- (SRGTimePosition *)streamTimePositionForPosition:(SRGPosition *)position
{
if (! position) {
position = SRGPosition.defaultPosition;
}
CMTime time = [self streamTimeForMark:position.mark];
return [SRGTimePosition positionWithTime:time toleranceBefore:position.toleranceBefore toleranceAfter:position.toleranceAfter];
}
- (CMTime)streamTimeForDate:(NSDate *)date
{
if (date && self.referenceDate) {
NSTimeInterval offset = [date timeIntervalSinceDate:self.referenceDate];
return CMTimeAdd(self.referenceTime, CMTimeMakeWithSeconds(offset, NSEC_PER_SEC));
}
else {
return kCMTimeIndefinite;
}
}
- (NSDate *)streamDateForTime:(CMTime)time
{
if (self.referenceDate) {
NSTimeInterval offset = CMTimeGetSeconds(CMTimeSubtract(time, self.referenceTime));
return [self.referenceDate dateByAddingTimeInterval:offset];
}
else {
return nil;
}
}
#pragma mark Playback
- (void)prepareToPlayURL:(NSURL *)URL
atPosition:(SRGPosition *)position
withSegments:(NSArray<id<SRGSegment>> *)segments
userInfo:(NSDictionary *)userInfo
completionHandler:(void (^)(void))completionHandler
{
[self prepareToPlayURLAsset:nil URL:URL atPosition:position withSegments:segments targetSegment:nil userInfo:userInfo completionHandler:completionHandler];
}
- (void)prepareToPlayURLAsset:(AVURLAsset *)URLAsset
atPosition:(SRGPosition *)position
withSegments:(NSArray<id<SRGSegment>> *)segments
userInfo:(NSDictionary *)userInfo
completionHandler:(void (^)(void))completionHandler
{
[self prepareToPlayURLAsset:URLAsset URL:nil atPosition:position withSegments:segments targetSegment:nil userInfo:userInfo completionHandler:completionHandler];
}
- (void)play
{
// Player is available
if (self.player) {
// Normal conditions. Simply forward to the player
if (self.playbackState != SRGMediaPlayerPlaybackStateEnded) {
[self.player playImmediatelyIfPossible];
}
// Playback ended. Restart at the beginning
else {
[self.player seekToTime:kCMTimeZero toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero notify:NO completionHandler:^(BOOL finished) {
if (finished) {
[self.player playImmediatelyIfPossible];
}
}];
}
}
// Player has been removed (e.g. after a -stop). Restart playback with the same conditions (if not cleared)
else if (self.contentURL) {
[self prepareToPlayURLAsset:nil URL:self.contentURL atPosition:self.initialPosition withSegments:self.segments targetSegment:self.initialTargetSegment userInfo:self.userInfo completionHandler:^{
[self play];
}];
}
else if (self.URLAsset) {
[self prepareToPlayURLAsset:self.URLAsset.copy URL:nil atPosition:self.initialPosition withSegments:self.segments targetSegment:self.initialTargetSegment userInfo:self.userInfo completionHandler:^{
[self play];
}];
}
}
- (void)pause
{
// Won't do anything if called after playback has ended
[self.player pause];
}
- (void)stop
{
[self stopWithUserInfo:nil];
}
- (void)seekToPosition:(SRGPosition *)position withCompletionHandler:(void (^)(BOOL))completionHandler
{
[self seekToPosition:position inTargetSegment:nil completionHandler:completionHandler];
}
- (void)reset
{
// Save previous state information
NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
if (self.contentURL) {
userInfo[SRGMediaPlayerPreviousContentURLKey] = self.contentURL;
}
if (self.URLAsset) {
userInfo[SRGMediaPlayerPreviousURLAssetKey] = self.URLAsset;
}
if (self.userInfo) {
userInfo[SRGMediaPlayerPreviousUserInfoKey] = self.userInfo;
}
// Reset input values (so that any state change notification reflects this new state)
self.contentURL = nil;
self.URLAsset = nil;
self.loadedSegments = nil;
self.userInfo = nil;