/
MediaPlayerPrivateAVFoundationObjC.mm
4463 lines (3612 loc) · 160 KB
/
MediaPlayerPrivateAVFoundationObjC.mm
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) 2011-2023 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import "config.h"
#import "MediaPlayerPrivateAVFoundationObjC.h"
#if ENABLE(VIDEO) && USE(AVFOUNDATION)
#import "AVAssetMIMETypeCache.h"
#import "AVAssetTrackUtilities.h"
#import "AVTrackPrivateAVFObjCImpl.h"
#import "AudioSourceProviderAVFObjC.h"
#import "AudioTrackPrivateAVFObjC.h"
#import "AuthenticationChallenge.h"
#import "CDMInstanceFairPlayStreamingAVFObjC.h"
#import "CDMSessionAVFoundationObjC.h"
#import "CVUtilities.h"
#import "ColorSpaceCG.h"
#import "ContentTypeUtilities.h"
#import "Cookie.h"
#import "FloatConversion.h"
#import "FourCC.h"
#import "GraphicsContext.h"
#import "IOSurface.h"
#import "ImageRotationSessionVT.h"
#import "InbandChapterTrackPrivateAVFObjC.h"
#import "InbandMetadataTextTrackPrivateAVF.h"
#import "InbandTextTrackPrivateAVFObjC.h"
#import "Logging.h"
#import "MediaPlaybackTargetCocoa.h"
#import "MediaPlaybackTargetMock.h"
#import "MediaSelectionGroupAVFObjC.h"
#import "MediaSessionManagerCocoa.h"
#import "OutOfBandTextTrackPrivateAVF.h"
#import "PixelBufferConformerCV.h"
#import "PlatformMediaResourceLoader.h"
#import "PlatformScreen.h"
#import "PlatformTextTrack.h"
#import "PlatformTimeRanges.h"
#import "QueuedVideoOutput.h"
#import "RuntimeApplicationChecks.h"
#import "ScriptDisallowedScope.h"
#import "SecurityOrigin.h"
#import "SerializedPlatformDataCueMac.h"
#import "SharedBuffer.h"
#import "SourceBufferParserWebM.h"
#import "TextTrack.h"
#import "TextTrackRepresentation.h"
#import "UTIUtilities.h"
#import "VideoFrameCV.h"
#import "VideoLayerManagerObjC.h"
#import "VideoTrackPrivateAVFObjC.h"
#import "WebCoreAVFResourceLoader.h"
#import "WebCoreCALayerExtras.h"
#import "WebCoreNSURLExtras.h"
#import "WebCoreNSURLSession.h"
#import <AVFoundation/AVAssetImageGenerator.h>
#import <AVFoundation/AVAssetTrack.h>
#import <AVFoundation/AVMediaSelectionGroup.h>
#import <AVFoundation/AVMetadataItem.h>
#import <AVFoundation/AVPlayer.h>
#import <AVFoundation/AVPlayerItem.h>
#import <AVFoundation/AVPlayerItemOutput.h>
#import <AVFoundation/AVPlayerItemTrack.h>
#import <AVFoundation/AVPlayerLayer.h>
#import <AVFoundation/AVTime.h>
#import <CoreVideo/CoreVideo.h>
#import <JavaScriptCore/DataView.h>
#import <JavaScriptCore/JSCInlines.h>
#import <JavaScriptCore/TypedArrayInlines.h>
#import <JavaScriptCore/Uint16Array.h>
#import <JavaScriptCore/Uint32Array.h>
#import <JavaScriptCore/Uint8Array.h>
#import <VideoToolbox/VideoToolbox.h>
#import <functional>
#import <objc/runtime.h>
#import <pal/avfoundation/MediaTimeAVFoundation.h>
#import <pal/avfoundation/OutputContext.h>
#import <pal/spi/cocoa/AVFoundationSPI.h>
#import <pal/spi/cocoa/QuartzCoreSPI.h>
#import <pal/text/TextCodecUTF8.h>
#import <wtf/BlockObjCExceptions.h>
#import <wtf/FileSystem.h>
#import <wtf/ListHashSet.h>
#import <wtf/NativePromise.h>
#import <wtf/NeverDestroyed.h>
#import <wtf/OSObjectPtr.h>
#import <wtf/URL.h>
#import <wtf/WorkQueue.h>
#import <wtf/cocoa/VectorCocoa.h>
#import <wtf/text/CString.h>
#import <wtf/threads/BinarySemaphore.h>
#if ENABLE(WIRELESS_PLAYBACK_TARGET)
#import "MediaPlaybackTarget.h"
#endif
#if PLATFORM(IOS_FAMILY)
#import "LocalizedDeviceModel.h"
#import "WAKAppKitStubs.h"
#import <CoreImage/CoreImage.h>
#import <UIKit/UIDevice.h>
#import <mach/mach_port.h>
#import <pal/ios/UIKitSoftLink.h>
#else
#import <Foundation/NSGeometry.h>
#import <QuartzCore/CoreImage.h>
#endif
#import "CoreVideoSoftLink.h"
#import "MediaRemoteSoftLink.h"
#import <pal/cocoa/MediaToolboxSoftLink.h>
namespace std {
template <> struct iterator_traits<HashSet<RefPtr<WebCore::MediaSelectionOptionAVFObjC>>::iterator> {
typedef RefPtr<WebCore::MediaSelectionOptionAVFObjC> value_type;
};
}
// Note: This must be defined before our SOFT_LINK macros:
@class AVMediaSelectionOption;
@interface AVMediaSelectionOption (OutOfBandExtensions)
@property (nonatomic, readonly) NSString* outOfBandSource;
@property (nonatomic, readonly) NSString* outOfBandIdentifier;
@end
@interface AVURLAsset (WebKitExtensions)
@property (nonatomic, readonly) NSURL *resolvedURL;
@end
@interface AVPlayer (Staging_100128644)
@property (assign, nonatomic) BOOL preventsAutomaticBackgroundingDuringVideoPlayback;
@end
#import <pal/cf/CoreMediaSoftLink.h>
#import <pal/cocoa/AVFoundationSoftLink.h>
SOFT_LINK_FRAMEWORK(MediaToolbox)
SOFT_LINK_OPTIONAL(MediaToolbox, MTEnableCaption2015Behavior, Boolean, (), ())
#if PLATFORM(IOS_FAMILY)
#if HAVE(CELESTIAL)
SOFT_LINK_PRIVATE_FRAMEWORK(Celestial)
SOFT_LINK_CONSTANT(Celestial, AVController_RouteDescriptionKey_RouteCurrentlyPicked, NSString *)
SOFT_LINK_CONSTANT(Celestial, AVController_RouteDescriptionKey_RouteName, NSString *)
SOFT_LINK_CONSTANT(Celestial, AVController_RouteDescriptionKey_AVAudioRouteName, NSString *)
#define AVController_RouteDescriptionKey_RouteCurrentlyPicked getAVController_RouteDescriptionKey_RouteCurrentlyPicked()
#define AVController_RouteDescriptionKey_RouteName getAVController_RouteDescriptionKey_RouteName()
#define AVController_RouteDescriptionKey_AVAudioRouteName getAVController_RouteDescriptionKey_AVAudioRouteName()
#endif // HAVE(CELESTIAL)
#endif // PLATFORM(IOS_FAMILY)
using namespace WebCore;
enum MediaPlayerAVFoundationObservationContext {
MediaPlayerAVFoundationObservationContextPlayerItem,
MediaPlayerAVFoundationObservationContextPlayerItemTrack,
MediaPlayerAVFoundationObservationContextPlayer,
MediaPlayerAVFoundationObservationContextAVPlayerLayer,
};
@interface WebCoreAVFMovieObserver : NSObject <AVPlayerItemLegibleOutputPushDelegate, AVPlayerItemMetadataOutputPushDelegate, AVPlayerItemMetadataCollectorPushDelegate>
{
ThreadSafeWeakPtr<MediaPlayerPrivateAVFoundationObjC> m_player;
int m_delayCallbacks;
RefPtr<WorkQueue> m_backgroundQueue;
}
-(id)initWithPlayer:(ThreadSafeWeakPtr<MediaPlayerPrivateAVFoundationObjC>&&)callback;
-(void)disconnect;
-(void)metadataLoaded;
-(void)didEnd:(NSNotification *)notification;
-(void)chapterMetadataDidChange:(NSNotification *)notification;
-(void)observeValueForKeyPath:keyPath ofObject:(id)object change:(NSDictionary *)change context:(MediaPlayerAVFoundationObservationContext)context;
- (void)legibleOutput:(id)output didOutputAttributedStrings:(NSArray *)strings nativeSampleBuffers:(NSArray *)nativeSamples forItemTime:(CMTime)itemTime;
- (void)outputSequenceWasFlushed:(id)output;
- (void)metadataCollector:(AVPlayerItemMetadataCollector *)metadataCollector didCollectDateRangeMetadataGroups:(NSArray<AVDateRangeMetadataGroup *> *)metadataGroups indexesOfNewGroups:(NSIndexSet *)indexesOfNewGroups indexesOfModifiedGroups:(NSIndexSet *)indexesOfModifiedGroups;
- (void)metadataOutput:(AVPlayerItemMetadataOutput *)output didOutputTimedMetadataGroups:(NSArray<AVTimedMetadataGroup *> *)groups fromPlayerItemTrack:(AVPlayerItemTrack *)track;
@end
@interface WebCoreAVFLoaderDelegate : NSObject<AVAssetResourceLoaderDelegate> {
ThreadSafeWeakPtr<MediaPlayerPrivateAVFoundationObjC> m_player;
}
- (id)initWithPlayer:(ThreadSafeWeakPtr<MediaPlayerPrivateAVFoundationObjC>&&)player;
- (BOOL)resourceLoader:(AVAssetResourceLoader *)resourceLoader shouldWaitForLoadingOfRequestedResource:(AVAssetResourceLoadingRequest *)loadingRequest;
@end
namespace WebCore {
static String convertEnumerationToString(AVPlayerTimeControlStatus enumerationValue)
{
static const NeverDestroyed<String> values[] = {
MAKE_STATIC_STRING_IMPL("AVPlayerTimeControlStatusPaused"),
MAKE_STATIC_STRING_IMPL("AVPlayerTimeControlStatusWaitingToPlayAtSpecifiedRate"),
MAKE_STATIC_STRING_IMPL("AVPlayerTimeControlStatusPlaying"),
};
static_assert(!static_cast<size_t>(AVPlayerTimeControlStatusPaused), "AVPlayerTimeControlStatusPaused is not 0 as expected");
static_assert(static_cast<size_t>(AVPlayerTimeControlStatusWaitingToPlayAtSpecifiedRate) == 1, "AVPlayerTimeControlStatusWaitingToPlayAtSpecifiedRate is not 1 as expected");
static_assert(static_cast<size_t>(AVPlayerTimeControlStatusPlaying) == 2, "AVPlayerTimeControlStatusPlaying is not 2 as expected");
ASSERT(static_cast<size_t>(enumerationValue) < std::size(values));
return values[static_cast<size_t>(enumerationValue)];
}
}
namespace WTF {
template<typename Type>
struct LogArgument;
template <>
struct LogArgument<AVPlayerTimeControlStatus> {
static String toString(const AVPlayerTimeControlStatus status)
{
return convertEnumerationToString(status);
}
};
}; // namespace WTF
namespace WebCore {
static NSArray *assetMetadataKeyNames();
static NSArray *itemKVOProperties();
static NSArray *assetTrackMetadataKeyNames();
static NSArray *playerKVOProperties();
static dispatch_queue_t globalLoaderDelegateQueue()
{
static dispatch_queue_t globalQueue;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
globalQueue = dispatch_queue_create("WebCoreAVFLoaderDelegate queue", DISPATCH_QUEUE_SERIAL);
});
return globalQueue;
}
static void registerFormatReaderIfNecessary()
{
#if ENABLE(WEBM_FORMAT_READER)
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
// Like we do for other media formats, allow the format reader to run in the WebContent or GPU process
// (which is already appropriately sandboxed) rather than in a separate MediaToolbox XPC service.
RELEASE_ASSERT(isInGPUProcess() || isInWebProcess());
MTRegisterPluginFormatReaderBundleDirectory((__bridge CFURLRef)NSBundle.mainBundle.builtInPlugInsURL);
MTPluginFormatReaderDisableSandboxing();
});
#endif
}
class MediaPlayerPrivateAVFoundationObjC::Factory final : public MediaPlayerFactory {
public:
Factory()
{
MediaSessionManagerCocoa::ensureCodecsRegistered();
}
private:
MediaPlayerEnums::MediaEngineIdentifier identifier() const final { return MediaPlayerEnums::MediaEngineIdentifier::AVFoundation; };
Ref<MediaPlayerPrivateInterface> createMediaEnginePlayer(MediaPlayer* player) const final
{
return adoptRef(*new MediaPlayerPrivateAVFoundationObjC(player));
}
void getSupportedTypes(HashSet<String>& types) const final
{
return MediaPlayerPrivateAVFoundationObjC::getSupportedTypes(types);
}
MediaPlayer::SupportsType supportsTypeAndCodecs(const MediaEngineSupportParameters& parameters) const final
{
return MediaPlayerPrivateAVFoundationObjC::supportsTypeAndCodecs(parameters);
}
HashSet<SecurityOriginData> originsInMediaCache(const String& path) const final
{
return MediaPlayerPrivateAVFoundationObjC::originsInMediaCache(path);
}
void clearMediaCache(const String& path, WallTime modifiedSince) const final
{
return MediaPlayerPrivateAVFoundationObjC::clearMediaCache(path, modifiedSince);
}
void clearMediaCacheForOrigins(const String& path, const HashSet<SecurityOriginData>& origins) const final
{
return MediaPlayerPrivateAVFoundationObjC::clearMediaCacheForOrigins(path, origins);
}
bool supportsKeySystem(const String& keySystem, const String& mimeType) const final
{
return MediaPlayerPrivateAVFoundationObjC::supportsKeySystem(keySystem, mimeType);
}
};
void MediaPlayerPrivateAVFoundationObjC::registerMediaEngine(MediaEngineRegistrar registrar)
{
if (!isAvailable())
return;
ASSERT(AVAssetMIMETypeCache::singleton().isAvailable());
registrar(makeUnique<Factory>());
}
static AVAssetCache *assetCacheForPath(const String& path)
{
if (path.isEmpty())
return nil;
return [PAL::getAVAssetCacheClass() assetCacheWithURL:[NSURL fileURLWithPath:path isDirectory:YES]];
}
static AVAssetCache *ensureAssetCacheExistsForPath(const String& path)
{
if (path.isEmpty())
return nil;
auto fileType = FileSystem::fileTypeFollowingSymlinks(path);
if (fileType && *fileType != FileSystem::FileType::Directory) {
// Non-directory file already exists at the path location; bail.
ASSERT_NOT_REACHED();
return nil;
}
if (!fileType && !FileSystem::makeAllDirectories(path)) {
// Could not create a directory at the specified location; bail.
ASSERT_NOT_REACHED();
return nil;
}
return assetCacheForPath(path);
}
HashSet<SecurityOriginData> MediaPlayerPrivateAVFoundationObjC::originsInMediaCache(const String& path)
{
HashSet<SecurityOriginData> origins;
AVAssetCache* assetCache = assetCacheForPath(path);
if (!assetCache)
return origins;
for (NSString *key in [assetCache allKeys]) {
URL keyAsURL { key };
if (keyAsURL.isValid())
origins.add(SecurityOriginData::fromURL(keyAsURL));
}
return origins;
}
static WallTime toSystemClockTime(NSDate *date)
{
ASSERT(date);
return WallTime::fromRawSeconds(date.timeIntervalSince1970);
}
void MediaPlayerPrivateAVFoundationObjC::clearMediaCache(const String& path, WallTime modifiedSince)
{
AVAssetCache* assetCache = assetCacheForPath(path);
if (!assetCache)
return;
for (NSString *key in [assetCache allKeys]) {
if (toSystemClockTime([assetCache lastModifiedDateOfEntryForKey:key]) > modifiedSince)
[assetCache removeEntryForKey:key];
}
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *baseURL = [assetCache URL];
if (modifiedSince <= WallTime::fromRawSeconds(0)) {
[fileManager removeItemAtURL:baseURL error:nil];
return;
}
NSArray *propertyKeys = @[NSURLNameKey, NSURLContentModificationDateKey, NSURLIsRegularFileKey];
NSDirectoryEnumerator *enumerator = [fileManager enumeratorAtURL:baseURL includingPropertiesForKeys:
propertyKeys options:NSDirectoryEnumerationSkipsSubdirectoryDescendants
errorHandler:nil];
RetainPtr<NSMutableArray> urlsToDelete = adoptNS([[NSMutableArray alloc] init]);
for (NSURL *fileURL : enumerator) {
NSDictionary *fileAttributes = [fileURL resourceValuesForKeys:propertyKeys error:nil];
if (![fileAttributes[NSURLNameKey] hasPrefix:@"CachedMedia-"])
continue;
if (![fileAttributes[NSURLIsRegularFileKey] boolValue])
continue;
if (toSystemClockTime(fileAttributes[NSURLContentModificationDateKey]) <= modifiedSince)
continue;
[urlsToDelete addObject:fileURL];
}
for (NSURL *fileURL in urlsToDelete.get())
[fileManager removeItemAtURL:fileURL error:nil];
}
void MediaPlayerPrivateAVFoundationObjC::clearMediaCacheForOrigins(const String& path, const HashSet<SecurityOriginData>& origins)
{
AVAssetCache* assetCache = assetCacheForPath(path);
if (!assetCache)
return;
for (NSString *key in [assetCache allKeys]) {
URL keyAsURL { key };
if (keyAsURL.isValid()) {
if (origins.contains(SecurityOriginData::fromURL(keyAsURL)))
[assetCache removeEntryForKey:key];
}
}
}
MediaPlayerPrivateAVFoundationObjC::MediaPlayerPrivateAVFoundationObjC(MediaPlayer* player)
: MediaPlayerPrivateAVFoundation(player)
, m_videoLayerManager(makeUnique<VideoLayerManagerObjC>(logger(), logIdentifier()))
, m_objcObserver(adoptNS([[WebCoreAVFMovieObserver alloc] initWithPlayer:*this]))
, m_loaderDelegate(adoptNS([[WebCoreAVFLoaderDelegate alloc] initWithPlayer:*this]))
, m_cachedItemStatus(MediaPlayerAVPlayerItemStatusDoesNotExist)
{
ALWAYS_LOG(LOGIDENTIFIER);
m_muted = player->muted();
#if HAVE(SPATIAL_TRACKING_LABEL)
m_defaultSpatialTrackingLabel = player->defaultSpatialTrackingLabel();
m_spatialTrackingLabel = player->spatialTrackingLabel();
#endif
}
MediaPlayerPrivateAVFoundationObjC::~MediaPlayerPrivateAVFoundationObjC()
{
[[m_avAsset resourceLoader] setDelegate:nil queue:0];
for (auto& pair : m_resourceLoaderMap) {
m_targetQueue->dispatch([loader = pair.value] () mutable {
loader->stopLoading();
});
}
if (m_videoOutput)
m_videoOutput->invalidate();
if (m_videoLayer)
destroyVideoLayer();
cancelLoad();
}
void MediaPlayerPrivateAVFoundationObjC::cancelLoad()
{
ALWAYS_LOG(LOGIDENTIFIER);
tearDownVideoRendering();
[[NSNotificationCenter defaultCenter] removeObserver:m_objcObserver.get()];
[m_objcObserver disconnect];
// Tell our observer to do nothing when our cancellation of pending loading calls its completion handler.
setIgnoreLoadStateChanges(true);
if (m_avAsset) {
[m_avAsset cancelLoading];
m_avAsset = nil;
}
clearTextTracks();
if (m_legibleOutput) {
if (m_avPlayerItem)
[m_avPlayerItem removeOutput:m_legibleOutput.get()];
m_legibleOutput = nil;
}
if (m_metadataCollector) {
// FIXME - removeMediaDataCollector sometimes crashes, do not uncomment this until rdar://56617504 has been fixed.
// if (m_avPlayerItem)
// [m_avPlayerItem removeMediaDataCollector:m_metadataCollector.get()];
m_metadataCollector = nil;
}
if (m_metadataOutput) {
if (m_avPlayerItem)
[m_avPlayerItem removeOutput:m_metadataOutput.get()];
m_metadataOutput = nil;
}
if (m_avPlayerItem) {
for (NSString *keyName in itemKVOProperties())
[m_avPlayerItem removeObserver:m_objcObserver.get() forKeyPath:keyName];
m_avPlayerItem = nil;
}
if (m_avPlayer) {
if (m_timeObserver)
[m_avPlayer removeTimeObserver:m_timeObserver.get()];
m_timeObserver = nil;
for (NSString *keyName in playerKVOProperties())
[m_avPlayer removeObserver:m_objcObserver.get() forKeyPath:keyName];
setShouldObserveTimeControlStatus(false);
[m_avPlayer replaceCurrentItemWithPlayerItem:nil];
#if !PLATFORM(IOS_FAMILY)
[m_avPlayer setOutputContext:nil];
#endif
if (m_currentTimeObserver)
[m_avPlayer removeTimeObserver:m_currentTimeObserver.get()];
m_currentTimeObserver = nil;
if (m_videoFrameMetadataGatheringObserver) {
[m_avPlayer removeTimeObserver:m_videoFrameMetadataGatheringObserver.get()];
m_videoFrameMetadataGatheringObserver = nil;
}
m_avPlayer = nil;
}
// Reset cached properties
m_createAssetPending = false;
m_haveCheckedPlayability = false;
m_pendingStatusChanges = 0;
m_cachedItemStatus = MediaPlayerAVPlayerItemStatusDoesNotExist;
m_cachedSeekableRanges = nullptr;
m_cachedHasEnabledAudio = false;
m_cachedHasEnabledVideo = false;
m_cachedPresentationSize = FloatSize();
m_cachedDuration = MediaTime::zeroTime();
m_buffered.clear();
for (AVPlayerItemTrack *track in m_cachedTracks.get())
[track removeObserver:m_objcObserver.get() forKeyPath:@"enabled"];
m_cachedTracks = nullptr;
m_chapterTracks.clear();
#if ENABLE(WEB_AUDIO) && USE(MEDIATOOLBOX)
if (m_provider) {
m_provider->setPlayerItem(nullptr);
m_provider->setAudioTrack(nullptr);
}
#endif
setIgnoreLoadStateChanges(false);
}
bool MediaPlayerPrivateAVFoundationObjC::hasLayerRenderer() const
{
return m_haveBeenAskedToCreateLayer;
}
bool MediaPlayerPrivateAVFoundationObjC::hasContextRenderer() const
{
return m_videoOutput || m_imageGenerator;
}
void MediaPlayerPrivateAVFoundationObjC::createContextVideoRenderer()
{
createVideoOutput();
}
void MediaPlayerPrivateAVFoundationObjC::createImageGenerator()
{
INFO_LOG(LOGIDENTIFIER);
if (!m_avAsset || m_imageGenerator)
return;
m_imageGenerator = [PAL::getAVAssetImageGeneratorClass() assetImageGeneratorWithAsset:m_avAsset.get()];
[m_imageGenerator setApertureMode:AVAssetImageGeneratorApertureModeCleanAperture];
[m_imageGenerator setAppliesPreferredTrackTransform:YES];
[m_imageGenerator setRequestedTimeToleranceBefore:PAL::kCMTimeZero];
[m_imageGenerator setRequestedTimeToleranceAfter:PAL::kCMTimeZero];
}
void MediaPlayerPrivateAVFoundationObjC::destroyContextVideoRenderer()
{
destroyVideoOutput();
destroyImageGenerator();
}
void MediaPlayerPrivateAVFoundationObjC::destroyImageGenerator()
{
if (!m_imageGenerator)
return;
INFO_LOG(LOGIDENTIFIER);
m_imageGenerator = 0;
}
void MediaPlayerPrivateAVFoundationObjC::createVideoLayer()
{
if (!m_avPlayer || m_haveBeenAskedToCreateLayer)
return;
ensureOnMainThread([this, weakThis = ThreadSafeWeakPtr { *this }] {
assertIsMainThread();
RefPtr protectedThis = weakThis.get();
if (!protectedThis)
return;
if (!m_avPlayer || m_haveBeenAskedToCreateLayer)
return;
m_haveBeenAskedToCreateLayer = true;
if (!m_videoLayer)
createAVPlayerLayer();
if (!m_videoOutput)
createVideoOutput();
});
}
void MediaPlayerPrivateAVFoundationObjC::createAVPlayerLayer()
{
assertIsMainThread();
if (!m_avPlayer)
return;
auto player = this->player();
if (!player)
return;
ALWAYS_LOG(LOGIDENTIFIER);
m_videoLayer = adoptNS([PAL::allocAVPlayerLayerInstance() init]);
[m_videoLayer setPlayer:m_avPlayer.get()];
[m_videoLayer setName:@"MediaPlayerPrivate AVPlayerLayer"];
[m_videoLayer addObserver:m_objcObserver.get() forKeyPath:@"readyForDisplay" options:NSKeyValueObservingOptionNew context:(void *)MediaPlayerAVFoundationObservationContextAVPlayerLayer];
updateVideoLayerGravity();
[m_videoLayer setContentsScale:player->playerContentsScale()];
m_videoLayerManager->setVideoLayer(m_videoLayer.get(), player->presentationSize());
#if PLATFORM(IOS_FAMILY) && !PLATFORM(WATCHOS) && !PLATFORM(APPLETV)
if ([m_videoLayer respondsToSelector:@selector(setPIPModeEnabled:)])
[m_videoLayer setPIPModeEnabled:(player->fullscreenMode() & MediaPlayer::VideoFullscreenModePictureInPicture)];
#endif
setNeedsRenderingModeChanged();
}
void MediaPlayerPrivateAVFoundationObjC::destroyVideoLayer()
{
assertIsMainThread();
if (!m_videoLayer)
return;
ALWAYS_LOG(LOGIDENTIFIER);
[m_videoLayer removeObserver:m_objcObserver.get() forKeyPath:@"readyForDisplay"];
[m_videoLayer setPlayer:nil];
m_videoLayerManager->didDestroyVideoLayer();
m_videoLayer = nil;
m_haveBeenAskedToCreateLayer = false;
setNeedsRenderingModeChanged();
}
MediaTime MediaPlayerPrivateAVFoundationObjC::getStartDate() const
{
// Date changes as the track's playback position changes. Must subtract currentTime (offset in seconds) from date offset to get date beginning
double date = [[m_avPlayerItem currentDate] timeIntervalSince1970];
// No live streams were made during the epoch (1970). AVFoundation returns 0 if the media file doesn't have a start date
if (!date)
return MediaTime::invalidTime();
double currentTime = PAL::CMTimeGetSeconds([m_avPlayerItem currentTime]);
// Rounding due to second offset error when subtracting.
return MediaTime::createWithDouble(round(date - currentTime));
}
bool MediaPlayerPrivateAVFoundationObjC::hasAvailableVideoFrame() const
{
if (currentRenderingMode() == MediaRenderingMode::MediaRenderingToLayer)
return m_cachedIsReadyForDisplay;
if (m_videoOutput && (m_lastPixelBuffer || m_videoOutput->hasImageForTime(currentTime())))
return true;
return m_videoFrameHasDrawn;
}
static const NSArray *mediaDescriptionForKind(PlatformTextTrackData::TrackKind kind)
{
static bool manualSelectionMode = MTEnableCaption2015BehaviorPtr() && MTEnableCaption2015BehaviorPtr()();
if (manualSelectionMode)
return @[ AVMediaCharacteristicIsAuxiliaryContent ];
// FIXME: Match these to correct types:
if (kind == PlatformTextTrackData::TrackKind::Caption)
return @[ AVMediaCharacteristicTranscribesSpokenDialogForAccessibility ];
if (kind == PlatformTextTrackData::TrackKind::Subtitle)
return @[ AVMediaCharacteristicTranscribesSpokenDialogForAccessibility ];
if (kind == PlatformTextTrackData::TrackKind::Description)
return @[ AVMediaCharacteristicTranscribesSpokenDialogForAccessibility, AVMediaCharacteristicDescribesMusicAndSoundForAccessibility ];
if (kind == PlatformTextTrackData::TrackKind::Forced)
return @[ AVMediaCharacteristicContainsOnlyForcedSubtitles ];
return @[ AVMediaCharacteristicTranscribesSpokenDialogForAccessibility ];
}
void MediaPlayerPrivateAVFoundationObjC::notifyTrackModeChanged()
{
trackModeChanged();
}
void MediaPlayerPrivateAVFoundationObjC::synchronizeTextTrackState()
{
auto player = this->player();
if (!player)
return;
const auto& outOfBandTrackSources = player->outOfBandTrackSources();
for (auto& textTrack : m_textTracks) {
if (textTrack->textTrackCategory() != InbandTextTrackPrivateAVF::OutOfBand)
continue;
RefPtr<OutOfBandTextTrackPrivateAVF> trackPrivate = static_cast<OutOfBandTextTrackPrivateAVF*>(textTrack.get());
RetainPtr<AVMediaSelectionOption> currentOption = trackPrivate->mediaSelectionOption();
for (auto& track : outOfBandTrackSources) {
RetainPtr<CFStringRef> uniqueID = String::number(track->uniqueId()).createCFString();
if (![[currentOption outOfBandIdentifier] isEqual:(__bridge NSString *)uniqueID.get()])
continue;
InbandTextTrackPrivate::Mode mode = InbandTextTrackPrivate::Mode::Hidden;
switch (track->mode()) {
case PlatformTextTrackData::TrackMode::Hidden:
mode = InbandTextTrackPrivate::Mode::Hidden;
break;
case PlatformTextTrackData::TrackMode::Disabled:
mode = InbandTextTrackPrivate::Mode::Disabled;
break;
case PlatformTextTrackData::TrackMode::Showing:
mode = InbandTextTrackPrivate::Mode::Showing;
break;
}
textTrack->setMode(mode);
break;
}
}
}
static NSURL *canonicalURL(const URL& url)
{
NSURL *cocoaURL = url;
if (url.isEmpty())
return cocoaURL;
return URLByCanonicalizingURL(cocoaURL);
}
void MediaPlayerPrivateAVFoundationObjC::createAVAssetForURL(const URL& url)
{
if (m_avAsset || m_createAssetPending)
return;
m_createAssetPending = true;
RetainPtr<NSMutableDictionary> options = adoptNS([[NSMutableDictionary alloc] init]);
#if PLATFORM(IOS_FAMILY)
if (!PAL::canLoad_AVFoundation_AVURLAssetHTTPCookiesKey()) {
createAVAssetForURL(url, WTFMove(options));
return;
}
auto player = this->player();
if (!player)
return;
player->getRawCookies(url, [this, weakThis = ThreadSafeWeakPtr { *this }, options = WTFMove(options), url] (auto cookies) mutable {
RefPtr protectedThis = weakThis.get();
if (!protectedThis)
return;
if (cookies.size()) {
auto nsCookies = createNSArray(cookies, [] (auto& cookie) -> NSHTTPCookie * {
return cookie;
});
[options setObject:nsCookies.get() forKey:AVURLAssetHTTPCookiesKey];
}
createAVAssetForURL(url, WTFMove(options));
});
#else
createAVAssetForURL(url, WTFMove(options));
#endif
}
static bool willUseWebMFormatReaderForType(const String& type)
{
#if ENABLE(WEBM_FORMAT_READER)
if (!SourceBufferParserWebM::isWebMFormatReaderAvailable())
return false;
return equalLettersIgnoringASCIICase(type, "video/webm"_s) || equalLettersIgnoringASCIICase(type, "audio/webm"_s);
#else
UNUSED_PARAM(type);
return false;
#endif
}
static URL conformFragmentIdentifierForURL(const URL& url)
{
#if PLATFORM(MAC)
// On some versions of macOS, Photos.framework has overriden utility methods from AVFoundation that cause
// a exception to be thrown when parsing fragment identifiers from a URL. Their implementation requires
// an even number of components when splitting the fragment identifier with separator characters ['&','='].
// Work around this broken implementation by pre-parsing the fragment and ensuring that it meets their
// criteria. Problematic strings from the TC0051.html test include "t=3&", and this problem generally is
// with subtrings between the '&' character not including an equal sign.
auto hasInvalidNumberOfEqualCharacters = [](StringView fragmentParameter) {
auto results = fragmentParameter.splitAllowingEmptyEntries('=');
auto iterator = results.begin();
return iterator == results.end() || ++iterator == results.end() || ++iterator != results.end();
};
StringBuilder replacementFragmentIdentifierBuilder;
bool firstParameter = true;
bool hasInvalidFragmentIdentifier = false;
for (auto fragmentParameter : url.fragmentIdentifier().splitAllowingEmptyEntries('&')) {
if (hasInvalidNumberOfEqualCharacters(fragmentParameter)) {
hasInvalidFragmentIdentifier = true;
continue;
}
if (!firstParameter)
replacementFragmentIdentifierBuilder.append('&');
else
firstParameter = false;
replacementFragmentIdentifierBuilder.append(fragmentParameter);
}
if (!hasInvalidFragmentIdentifier)
return url;
URL validURL = url;
if (replacementFragmentIdentifierBuilder.isEmpty())
validURL.removeFragmentIdentifier();
else
validURL.setFragmentIdentifier(replacementFragmentIdentifierBuilder.toString());
return validURL;
#else
ASSERT_NOT_REACHED();
return url;
#endif
}
void MediaPlayerPrivateAVFoundationObjC::createAVAssetForURL(const URL& url, RetainPtr<NSMutableDictionary> options)
{
ALWAYS_LOG(LOGIDENTIFIER);
auto player = this->player();
if (!player)
return;
m_createAssetPending = false;
if (m_avAsset)
return;
[options setObject:@(AVAssetReferenceRestrictionForbidRemoteReferenceToLocal | AVAssetReferenceRestrictionForbidLocalReferenceToRemote) forKey:AVURLAssetReferenceRestrictionsKey];
RetainPtr<NSMutableDictionary> headerFields = adoptNS([[NSMutableDictionary alloc] init]);
String referrer = player->referrer();
if (!referrer.isEmpty())
[headerFields setObject:referrer forKey:@"Referer"];
String userAgent = player->userAgent();
if (!userAgent.isEmpty())
[headerFields setObject:userAgent forKey:@"User-Agent"];
if ([headerFields count])
[options setObject:headerFields.get() forKey:@"AVURLAssetHTTPHeaderFieldsKey"];
if (shouldEnableInheritURIQueryComponent())
[options setObject:@YES forKey:AVURLAssetInheritURIQueryComponentFromReferencingURIKey];
if (PAL::canLoad_AVFoundation_AVURLAssetUseClientURLLoadingExclusively())
[options setObject:@YES forKey:AVURLAssetUseClientURLLoadingExclusively];
#if PLATFORM(IOS_FAMILY)
else if (PAL::canLoad_AVFoundation_AVURLAssetRequiresCustomURLLoadingKey())
[options setObject:@YES forKey:AVURLAssetRequiresCustomURLLoadingKey];
// FIXME: rdar://problem/20354688
String identifier = player->sourceApplicationIdentifier();
if (!identifier.isEmpty())
[options setObject:identifier forKey:AVURLAssetClientBundleIdentifierKey];
#endif
if (player->prefersSandboxedParsing() && PAL::canLoad_AVFoundation_AVAssetPrefersSandboxedParsingOptionKey())
[options setObject:@YES forKey:AVAssetPrefersSandboxedParsingOptionKey];
if (player->inPrivateBrowsingMode() && PAL::canLoad_AVFoundation_AVURLAssetDoNotLogURLsKey())
[options setObject:@YES forKey:AVURLAssetDoNotLogURLsKey];
auto type = player->contentMIMEType();
// Don't advertise WebM MIME types or the format reader won't be loaded until rdar://72405127 is fixed.
auto willUseWebMFormatReader = willUseWebMFormatReaderForType(type);
if (PAL::canLoad_AVFoundation_AVURLAssetOutOfBandMIMETypeKey() && !type.isEmpty() && !player->contentMIMETypeWasInferredFromExtension() && !willUseWebMFormatReader) {
auto codecs = player->contentTypeCodecs();
if (!codecs.isEmpty()) {
NSString *typeString = [NSString stringWithFormat:@"%@; codecs=\"%@\"", (NSString *)type, (NSString *)codecs];
[options setObject:typeString forKey:AVURLAssetOutOfBandMIMETypeKey];
} else
[options setObject:(NSString *)type forKey:AVURLAssetOutOfBandMIMETypeKey];
}
auto outOfBandTrackSources = player->outOfBandTrackSources();
if (!outOfBandTrackSources.isEmpty()) {
auto outOfBandTracks = createNSArray(outOfBandTrackSources, [] (auto& trackSource) {
return @{
AVOutOfBandAlternateTrackDisplayNameKey: trackSource->label(),
AVOutOfBandAlternateTrackExtendedLanguageTagKey: trackSource->language(),
AVOutOfBandAlternateTrackIsDefaultKey: trackSource->isDefault() ? @YES : @NO,
AVOutOfBandAlternateTrackIdentifierKey: String::number(trackSource->uniqueId()),
AVOutOfBandAlternateTrackSourceKey: trackSource->url(),
AVOutOfBandAlternateTrackMediaCharactersticsKey: mediaDescriptionForKind(trackSource->kind()),
};
});
[options setObject:outOfBandTracks.get() forKey:AVURLAssetOutOfBandAlternateTracksKey];
}
#if PLATFORM(IOS_FAMILY)
String networkInterfaceName = player->mediaPlayerNetworkInterfaceName();
if (!networkInterfaceName.isEmpty())
[options setObject:networkInterfaceName forKey:AVURLAssetBoundNetworkInterfaceName];
#endif
bool usePersistentCache = player->shouldUsePersistentCache();
[options setObject:@(!usePersistentCache) forKey:AVURLAssetUsesNoPersistentCacheKey];
if (usePersistentCache) {
if (auto* assetCache = ensureAssetCacheExistsForPath(player->mediaCacheDirectory()))
[options setObject:assetCache forKey:AVURLAssetCacheKey];
else
[options setObject:@NO forKey:AVURLAssetUsesNoPersistentCacheKey];
}
auto allowedMediaContainerTypes = player->allowedMediaContainerTypes();
if (allowedMediaContainerTypes && PAL::canLoad_AVFoundation_AVURLAssetAllowableTypeCategoriesKey()) {
auto nsTypes = adoptNS([[NSMutableArray alloc] init]);
for (auto type : *allowedMediaContainerTypes)
[nsTypes addObject:(NSString *)UTIFromMIMEType(type)];
[options setObject:nsTypes.get() forKey:AVURLAssetAllowableTypeCategoriesKey];
}
auto allowedMediaAudioCodecIDs = player->allowedMediaAudioCodecIDs();
if (allowedMediaAudioCodecIDs && PAL::canLoad_AVFoundation_AVURLAssetAllowableAudioCodecTypesKey()) {
auto nsTypes = adoptNS([[NSMutableArray alloc] init]);
for (auto type : *allowedMediaAudioCodecIDs)
[nsTypes addObject:@(type.value)];
[options setObject:nsTypes.get() forKey:AVURLAssetAllowableAudioCodecTypesKey];
}
auto allowedMediaVideoCodecIDs = player->allowedMediaVideoCodecIDs();
if (allowedMediaVideoCodecIDs && PAL::canLoad_AVFoundation_AVURLAssetAllowableVideoCodecTypesKey()) {
auto nsTypes = adoptNS([[NSMutableArray alloc] init]);
for (auto type : *allowedMediaVideoCodecIDs)
[nsTypes addObject:@(type.value)];