Use Optional::valueOr() instead of Optional::value_or()
[WebKit-https.git] / Source / WebCore / platform / graphics / avfoundation / objc / MediaPlayerPrivateAVFoundationObjC.mm
1 /*
2  * Copyright (C) 2011-2018 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
17  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
24  */
25
26 #import "config.h"
27 #import "MediaPlayerPrivateAVFoundationObjC.h"
28
29 #if ENABLE(VIDEO) && USE(AVFOUNDATION)
30
31 #import "AVAssetTrackUtilities.h"
32 #import "AVFoundationMIMETypeCache.h"
33 #import "AVTrackPrivateAVFObjCImpl.h"
34 #import "AudioSourceProviderAVFObjC.h"
35 #import "AudioTrackPrivateAVFObjC.h"
36 #import "AuthenticationChallenge.h"
37 #import "CDMInstanceFairPlayStreamingAVFObjC.h"
38 #import "CDMSessionAVFoundationObjC.h"
39 #import "Cookie.h"
40 #import "DeprecatedGlobalSettings.h"
41 #import "Extensions3D.h"
42 #import "FloatConversion.h"
43 #import "GraphicsContext.h"
44 #import "GraphicsContext3D.h"
45 #import "GraphicsContextCG.h"
46 #import "InbandMetadataTextTrackPrivateAVF.h"
47 #import "InbandTextTrackPrivateAVFObjC.h"
48 #import "InbandTextTrackPrivateLegacyAVFObjC.h"
49 #import "Logging.h"
50 #import "MediaPlaybackTargetMac.h"
51 #import "MediaPlaybackTargetMock.h"
52 #import "MediaSelectionGroupAVFObjC.h"
53 #import "OutOfBandTextTrackPrivateAVF.h"
54 #import "PixelBufferConformerCV.h"
55 #import "PlatformTimeRanges.h"
56 #import "SecurityOrigin.h"
57 #import "SerializedPlatformRepresentationMac.h"
58 #import "SharedBuffer.h"
59 #import "TextEncoding.h"
60 #import "TextTrackRepresentation.h"
61 #import "TextureCacheCV.h"
62 #import "VideoFullscreenLayerManagerObjC.h"
63 #import "VideoTextureCopierCV.h"
64 #import "VideoTrackPrivateAVFObjC.h"
65 #import "WebCoreAVFResourceLoader.h"
66 #import "WebCoreCALayerExtras.h"
67 #import "WebCoreNSURLSession.h"
68 #import <JavaScriptCore/DataView.h>
69 #import <JavaScriptCore/JSCInlines.h>
70 #import <JavaScriptCore/TypedArrayInlines.h>
71 #import <JavaScriptCore/Uint16Array.h>
72 #import <JavaScriptCore/Uint32Array.h>
73 #import <JavaScriptCore/Uint8Array.h>
74 #import <functional>
75 #import <objc/runtime.h>
76 #import <pal/avfoundation/MediaTimeAVFoundation.h>
77 #import <pal/spi/cocoa/QuartzCoreSPI.h>
78 #import <pal/spi/mac/AVFoundationSPI.h>
79 #import <wtf/BlockObjCExceptions.h>
80 #import <wtf/ListHashSet.h>
81 #import <wtf/NeverDestroyed.h>
82 #import <wtf/OSObjectPtr.h>
83 #import <wtf/URL.h>
84 #import <wtf/text/CString.h>
85
86 #if ENABLE(AVF_CAPTIONS)
87 #include "TextTrack.h"
88 #endif
89
90 #import <AVFoundation/AVAssetImageGenerator.h>
91 #import <AVFoundation/AVAssetTrack.h>
92 #import <AVFoundation/AVMediaSelectionGroup.h>
93 #import <AVFoundation/AVMetadataItem.h>
94 #import <AVFoundation/AVPlayer.h>
95 #import <AVFoundation/AVPlayerItem.h>
96 #import <AVFoundation/AVPlayerItemOutput.h>
97 #import <AVFoundation/AVPlayerItemTrack.h>
98 #import <AVFoundation/AVPlayerLayer.h>
99 #import <AVFoundation/AVTime.h>
100
101 #if PLATFORM(IOS_FAMILY)
102 #import "WAKAppKitStubs.h"
103 #import <CoreImage/CoreImage.h>
104 #import <UIKit/UIDevice.h>
105 #import <mach/mach_port.h>
106 #else
107 #import <Foundation/NSGeometry.h>
108 #import <QuartzCore/CoreImage.h>
109 #endif
110
111 #if USE(VIDEOTOOLBOX)
112 #import <CoreVideo/CoreVideo.h>
113 #import <VideoToolbox/VideoToolbox.h>
114 #endif
115
116 #import "CoreVideoSoftLink.h"
117 #import "MediaRemoteSoftLink.h"
118
119 namespace std {
120 template <> struct iterator_traits<HashSet<RefPtr<WebCore::MediaSelectionOptionAVFObjC>>::iterator> {
121     typedef RefPtr<WebCore::MediaSelectionOptionAVFObjC> value_type;
122 };
123 }
124
125 #if ENABLE(AVF_CAPTIONS)
126 // Note: This must be defined before our SOFT_LINK macros:
127 @class AVMediaSelectionOption;
128 @interface AVMediaSelectionOption (OutOfBandExtensions)
129 @property (nonatomic, readonly) NSString* outOfBandSource;
130 @property (nonatomic, readonly) NSString* outOfBandIdentifier;
131 @end
132 #endif
133
134 @interface AVURLAsset (WebKitExtensions)
135 @property (nonatomic, readonly) NSURL *resolvedURL;
136 @end
137
138 typedef AVPlayer AVPlayerType;
139 typedef AVPlayerItem AVPlayerItemType;
140 typedef AVPlayerItemLegibleOutput AVPlayerItemLegibleOutputType;
141 typedef AVPlayerItemVideoOutput AVPlayerItemVideoOutputType;
142 typedef AVMetadataItem AVMetadataItemType;
143 typedef AVMediaSelectionGroup AVMediaSelectionGroupType;
144 typedef AVMediaSelectionOption AVMediaSelectionOptionType;
145 typedef AVAssetCache AVAssetCacheType;
146
147 #pragma mark - Soft Linking
148
149 // Soft-linking headers must be included last since they #define functions, constants, etc.
150 #import <pal/cf/CoreMediaSoftLink.h>
151
152 SOFT_LINK_FRAMEWORK_OPTIONAL(AVFoundation)
153
154 SOFT_LINK_FRAMEWORK_OPTIONAL(CoreImage)
155
156 SOFT_LINK_CLASS_FOR_SOURCE(WebCore, AVFoundation, AVPlayer)
157 SOFT_LINK_CLASS_FOR_SOURCE(WebCore, AVFoundation, AVPlayerItem)
158 SOFT_LINK_CLASS_FOR_SOURCE(WebCore, AVFoundation, AVPlayerItemVideoOutput)
159 SOFT_LINK_CLASS_FOR_SOURCE(WebCore, AVFoundation, AVPlayerLayer)
160 SOFT_LINK_CLASS_FOR_SOURCE(WebCore, AVFoundation, AVURLAsset)
161 SOFT_LINK_CLASS_FOR_SOURCE(WebCore, AVFoundation, AVAssetImageGenerator)
162 SOFT_LINK_CLASS_FOR_SOURCE(WebCore, AVFoundation, AVMetadataItem)
163 SOFT_LINK_CLASS_FOR_SOURCE(WebCore, AVFoundation, AVAssetCache)
164
165 SOFT_LINK_CLASS(CoreImage, CIContext)
166 SOFT_LINK_CLASS(CoreImage, CIImage)
167
168 SOFT_LINK_CONSTANT(AVFoundation, AVAudioTimePitchAlgorithmSpectral, NSString *)
169 SOFT_LINK_CONSTANT(AVFoundation, AVAudioTimePitchAlgorithmVarispeed, NSString *)
170 SOFT_LINK_CONSTANT(AVFoundation, AVMediaCharacteristicVisual, NSString *)
171 SOFT_LINK_CONSTANT(AVFoundation, AVMediaCharacteristicAudible, NSString *)
172 SOFT_LINK_CONSTANT(AVFoundation, AVMediaTypeClosedCaption, NSString *)
173 SOFT_LINK_CONSTANT(AVFoundation, AVMediaTypeVideo, NSString *)
174 SOFT_LINK_CONSTANT(AVFoundation, AVMediaTypeAudio, NSString *)
175 SOFT_LINK_CONSTANT(AVFoundation, AVMediaTypeMetadata, NSString *)
176 SOFT_LINK_CONSTANT(AVFoundation, AVPlayerItemDidPlayToEndTimeNotification, NSString *)
177 SOFT_LINK_CONSTANT(AVFoundation, AVURLAssetInheritURIQueryComponentFromReferencingURIKey, NSString *)
178 SOFT_LINK_CONSTANT(AVFoundation, AVAssetImageGeneratorApertureModeCleanAperture, NSString *)
179 SOFT_LINK_CONSTANT(AVFoundation, AVURLAssetReferenceRestrictionsKey, NSString *)
180 SOFT_LINK_CONSTANT(AVFoundation, AVLayerVideoGravityResizeAspect, NSString *)
181 SOFT_LINK_CONSTANT(AVFoundation, AVLayerVideoGravityResizeAspectFill, NSString *)
182 SOFT_LINK_CONSTANT(AVFoundation, AVLayerVideoGravityResize, NSString *)
183 SOFT_LINK_CONSTANT(AVFoundation, AVStreamingKeyDeliveryContentKeyType, NSString *)
184
185 SOFT_LINK_CONSTANT_MAY_FAIL(AVFoundation, AVURLAssetOutOfBandMIMETypeKey, NSString *)
186 SOFT_LINK_CONSTANT_MAY_FAIL(AVFoundation, AVURLAssetUseClientURLLoadingExclusively, NSString *)
187
188 #define AVPlayer initAVPlayer()
189 #define AVPlayerItem initAVPlayerItem()
190 #define AVPlayerLayer initAVPlayerLayer()
191 #define AVURLAsset initAVURLAsset()
192 #define AVAssetImageGenerator initAVAssetImageGenerator()
193 #define AVPlayerItemVideoOutput initAVPlayerItemVideoOutput()
194 #define AVMetadataItem initAVMetadataItem()
195 #define AVAssetCache initAVAssetCache()
196
197 #define AVAudioTimePitchAlgorithmSpectral getAVAudioTimePitchAlgorithmSpectral()
198 #define AVAudioTimePitchAlgorithmVarispeed getAVAudioTimePitchAlgorithmVarispeed()
199 #define AVMediaCharacteristicVisual getAVMediaCharacteristicVisual()
200 #define AVMediaCharacteristicAudible getAVMediaCharacteristicAudible()
201 #define AVMediaTypeClosedCaption getAVMediaTypeClosedCaption()
202 #define AVMediaTypeVideo getAVMediaTypeVideo()
203 #define AVMediaTypeAudio getAVMediaTypeAudio()
204 #define AVMediaTypeMetadata getAVMediaTypeMetadata()
205 #define AVPlayerItemDidPlayToEndTimeNotification getAVPlayerItemDidPlayToEndTimeNotification()
206 #define AVURLAssetInheritURIQueryComponentFromReferencingURIKey getAVURLAssetInheritURIQueryComponentFromReferencingURIKey()
207 #define AVURLAssetOutOfBandMIMETypeKey getAVURLAssetOutOfBandMIMETypeKey()
208 #define AVURLAssetUseClientURLLoadingExclusively getAVURLAssetUseClientURLLoadingExclusively()
209 #define AVAssetImageGeneratorApertureModeCleanAperture getAVAssetImageGeneratorApertureModeCleanAperture()
210 #define AVURLAssetReferenceRestrictionsKey getAVURLAssetReferenceRestrictionsKey()
211 #define AVLayerVideoGravityResizeAspect getAVLayerVideoGravityResizeAspect()
212 #define AVLayerVideoGravityResizeAspectFill getAVLayerVideoGravityResizeAspectFill()
213 #define AVLayerVideoGravityResize getAVLayerVideoGravityResize()
214 #define AVStreamingKeyDeliveryContentKeyType getAVStreamingKeyDeliveryContentKeyType()
215
216 #if HAVE(AVFOUNDATION_MEDIA_SELECTION_GROUP)
217
218 typedef AVMediaSelectionGroup AVMediaSelectionGroupType;
219 typedef AVMediaSelectionOption AVMediaSelectionOptionType;
220
221 SOFT_LINK_CLASS(AVFoundation, AVPlayerItemLegibleOutput)
222 SOFT_LINK_CLASS(AVFoundation, AVMediaSelectionGroup)
223 SOFT_LINK_CLASS(AVFoundation, AVMediaSelectionOption)
224 SOFT_LINK_CLASS(AVFoundation, AVOutputContext)
225
226 SOFT_LINK_CONSTANT(AVFoundation, AVMediaCharacteristicLegible, NSString *)
227 SOFT_LINK_CONSTANT(AVFoundation, AVMediaTypeSubtitle, NSString *)
228 SOFT_LINK_CONSTANT(AVFoundation, AVMediaCharacteristicContainsOnlyForcedSubtitles, NSString *)
229 SOFT_LINK_CONSTANT(AVFoundation, AVPlayerItemLegibleOutputTextStylingResolutionSourceAndRulesOnly, NSString *)
230
231 #define AVPlayerItemLegibleOutput getAVPlayerItemLegibleOutputClass()
232 #define AVMediaSelectionGroup getAVMediaSelectionGroupClass()
233 #define AVMediaSelectionOption getAVMediaSelectionOptionClass()
234 #define AVMediaCharacteristicLegible getAVMediaCharacteristicLegible()
235 #define AVMediaTypeSubtitle getAVMediaTypeSubtitle()
236 #define AVMediaCharacteristicContainsOnlyForcedSubtitles getAVMediaCharacteristicContainsOnlyForcedSubtitles()
237 #define AVPlayerItemLegibleOutputTextStylingResolutionSourceAndRulesOnly getAVPlayerItemLegibleOutputTextStylingResolutionSourceAndRulesOnly()
238
239 #endif
240
241 #if ENABLE(AVF_CAPTIONS)
242
243 SOFT_LINK_CONSTANT(AVFoundation, AVURLAssetCacheKey, NSString *)
244 SOFT_LINK_CONSTANT(AVFoundation, AVURLAssetOutOfBandAlternateTracksKey, NSString *)
245 SOFT_LINK_CONSTANT(AVFoundation, AVURLAssetUsesNoPersistentCacheKey, NSString *)
246 SOFT_LINK_CONSTANT(AVFoundation, AVOutOfBandAlternateTrackDisplayNameKey, NSString *)
247 SOFT_LINK_CONSTANT(AVFoundation, AVOutOfBandAlternateTrackExtendedLanguageTagKey, NSString *)
248 SOFT_LINK_CONSTANT(AVFoundation, AVOutOfBandAlternateTrackIsDefaultKey, NSString *)
249 SOFT_LINK_CONSTANT(AVFoundation, AVOutOfBandAlternateTrackMediaCharactersticsKey, NSString *)
250 SOFT_LINK_CONSTANT(AVFoundation, AVOutOfBandAlternateTrackIdentifierKey, NSString *)
251 SOFT_LINK_CONSTANT(AVFoundation, AVOutOfBandAlternateTrackSourceKey, NSString *)
252 SOFT_LINK_CONSTANT(AVFoundation, AVMediaCharacteristicDescribesMusicAndSoundForAccessibility, NSString *)
253 SOFT_LINK_CONSTANT(AVFoundation, AVMediaCharacteristicTranscribesSpokenDialogForAccessibility, NSString *)
254 SOFT_LINK_CONSTANT(AVFoundation, AVMediaCharacteristicIsAuxiliaryContent, NSString *)
255
256 #define AVURLAssetOutOfBandAlternateTracksKey getAVURLAssetOutOfBandAlternateTracksKey()
257 #define AVURLAssetCacheKey getAVURLAssetCacheKey()
258 #define AVURLAssetUsesNoPersistentCacheKey getAVURLAssetUsesNoPersistentCacheKey()
259 #define AVOutOfBandAlternateTrackDisplayNameKey getAVOutOfBandAlternateTrackDisplayNameKey()
260 #define AVOutOfBandAlternateTrackExtendedLanguageTagKey getAVOutOfBandAlternateTrackExtendedLanguageTagKey()
261 #define AVOutOfBandAlternateTrackIsDefaultKey getAVOutOfBandAlternateTrackIsDefaultKey()
262 #define AVOutOfBandAlternateTrackMediaCharactersticsKey getAVOutOfBandAlternateTrackMediaCharactersticsKey()
263 #define AVOutOfBandAlternateTrackIdentifierKey getAVOutOfBandAlternateTrackIdentifierKey()
264 #define AVOutOfBandAlternateTrackSourceKey getAVOutOfBandAlternateTrackSourceKey()
265 #define AVMediaCharacteristicDescribesMusicAndSoundForAccessibility getAVMediaCharacteristicDescribesMusicAndSoundForAccessibility()
266 #define AVMediaCharacteristicTranscribesSpokenDialogForAccessibility getAVMediaCharacteristicTranscribesSpokenDialogForAccessibility()
267 #define AVMediaCharacteristicIsAuxiliaryContent getAVMediaCharacteristicIsAuxiliaryContent()
268
269 #endif
270
271 #if ENABLE(DATACUE_VALUE)
272
273 SOFT_LINK_CONSTANT(AVFoundation, AVMetadataKeySpaceQuickTimeUserData, NSString *)
274 SOFT_LINK_CONSTANT_MAY_FAIL(AVFoundation, AVMetadataKeySpaceISOUserData, NSString *)
275 SOFT_LINK_CONSTANT(AVFoundation, AVMetadataKeySpaceQuickTimeMetadata, NSString *)
276 SOFT_LINK_CONSTANT(AVFoundation, AVMetadataKeySpaceiTunes, NSString *)
277 SOFT_LINK_CONSTANT(AVFoundation, AVMetadataKeySpaceID3, NSString *)
278
279 #define AVMetadataKeySpaceQuickTimeUserData getAVMetadataKeySpaceQuickTimeUserData()
280 #define AVMetadataKeySpaceISOUserData getAVMetadataKeySpaceISOUserData()
281 #define AVMetadataKeySpaceQuickTimeMetadata getAVMetadataKeySpaceQuickTimeMetadata()
282 #define AVMetadataKeySpaceiTunes getAVMetadataKeySpaceiTunes()
283 #define AVMetadataKeySpaceID3 getAVMetadataKeySpaceID3()
284
285 #endif
286
287 #if PLATFORM(IOS_FAMILY)
288
289 SOFT_LINK_CONSTANT(AVFoundation, AVURLAssetBoundNetworkInterfaceName, NSString *)
290 SOFT_LINK_CONSTANT_MAY_FAIL(AVFoundation, AVURLAssetClientBundleIdentifierKey, NSString *)
291 SOFT_LINK_CONSTANT_MAY_FAIL(AVFoundation, AVURLAssetHTTPCookiesKey, NSString *)
292 SOFT_LINK_CONSTANT_MAY_FAIL(AVFoundation, AVURLAssetRequiresCustomURLLoadingKey, NSString *)
293
294 #define AVURLAssetBoundNetworkInterfaceName getAVURLAssetBoundNetworkInterfaceName()
295 #define AVURLAssetClientBundleIdentifierKey getAVURLAssetClientBundleIdentifierKey()
296 #define AVURLAssetHTTPCookiesKey getAVURLAssetHTTPCookiesKey()
297 #define AVURLAssetRequiresCustomURLLoadingKey getAVURLAssetRequiresCustomURLLoadingKey()
298
299 #endif
300
301 SOFT_LINK_FRAMEWORK(MediaToolbox)
302 SOFT_LINK_OPTIONAL(MediaToolbox, MTEnableCaption2015Behavior, Boolean, (), ())
303
304 #if PLATFORM(IOS_FAMILY)
305
306 #if HAVE(CELESTIAL)
307
308 SOFT_LINK_PRIVATE_FRAMEWORK(Celestial)
309 SOFT_LINK_CONSTANT(Celestial, AVController_RouteDescriptionKey_RouteCurrentlyPicked, NSString *)
310 SOFT_LINK_CONSTANT(Celestial, AVController_RouteDescriptionKey_RouteName, NSString *)
311 SOFT_LINK_CONSTANT(Celestial, AVController_RouteDescriptionKey_AVAudioRouteName, NSString *)
312 #define AVController_RouteDescriptionKey_RouteCurrentlyPicked getAVController_RouteDescriptionKey_RouteCurrentlyPicked()
313 #define AVController_RouteDescriptionKey_RouteName getAVController_RouteDescriptionKey_RouteName()
314 #define AVController_RouteDescriptionKey_AVAudioRouteName getAVController_RouteDescriptionKey_AVAudioRouteName()
315
316 #endif // HAVE(CELESTIAL)
317
318 SOFT_LINK_FRAMEWORK(UIKit)
319 SOFT_LINK_CLASS(UIKit, UIDevice)
320 #define UIDevice getUIDeviceClass()
321
322 #endif // PLATFORM(IOS_FAMILY)
323
324 using namespace WebCore;
325
326 enum MediaPlayerAVFoundationObservationContext {
327     MediaPlayerAVFoundationObservationContextPlayerItem,
328     MediaPlayerAVFoundationObservationContextPlayerItemTrack,
329     MediaPlayerAVFoundationObservationContextPlayer,
330     MediaPlayerAVFoundationObservationContextAVPlayerLayer,
331 };
332
333 #if HAVE(AVFOUNDATION_MEDIA_SELECTION_GROUP) && HAVE(AVFOUNDATION_LEGIBLE_OUTPUT_SUPPORT)
334 @interface WebCoreAVFMovieObserver : NSObject <AVPlayerItemLegibleOutputPushDelegate>
335 #else
336 @interface WebCoreAVFMovieObserver : NSObject
337 #endif
338 {
339     WeakPtr<MediaPlayerPrivateAVFoundationObjC> m_player;
340     GenericTaskQueue<Timer, std::atomic<unsigned>> m_taskQueue;
341     int m_delayCallbacks;
342 }
343 -(id)initWithPlayer:(WeakPtr<MediaPlayerPrivateAVFoundationObjC>&&)callback;
344 -(void)disconnect;
345 -(void)metadataLoaded;
346 -(void)didEnd:(NSNotification *)notification;
347 -(void)observeValueForKeyPath:keyPath ofObject:(id)object change:(NSDictionary *)change context:(MediaPlayerAVFoundationObservationContext)context;
348 #if HAVE(AVFOUNDATION_MEDIA_SELECTION_GROUP)
349 - (void)legibleOutput:(id)output didOutputAttributedStrings:(NSArray *)strings nativeSampleBuffers:(NSArray *)nativeSamples forItemTime:(CMTime)itemTime;
350 - (void)outputSequenceWasFlushed:(id)output;
351 #endif
352 @end
353
354 #if HAVE(AVFOUNDATION_LOADER_DELEGATE)
355 @interface WebCoreAVFLoaderDelegate : NSObject<AVAssetResourceLoaderDelegate> {
356     WeakPtr<MediaPlayerPrivateAVFoundationObjC> m_player;
357     GenericTaskQueue<Timer, std::atomic<unsigned>> m_taskQueue;
358 }
359 - (id)initWithPlayer:(WeakPtr<MediaPlayerPrivateAVFoundationObjC>&&)player;
360 - (BOOL)resourceLoader:(AVAssetResourceLoader *)resourceLoader shouldWaitForLoadingOfRequestedResource:(AVAssetResourceLoadingRequest *)loadingRequest;
361 @end
362 #endif
363
364 #if HAVE(AVFOUNDATION_VIDEO_OUTPUT)
365 @interface WebCoreAVFPullDelegate : NSObject<AVPlayerItemOutputPullDelegate> {
366     WeakPtr<MediaPlayerPrivateAVFoundationObjC> m_player;
367 }
368 - (id)initWithPlayer:(WeakPtr<MediaPlayerPrivateAVFoundationObjC>&&)player;
369 - (void)outputMediaDataWillChange:(AVPlayerItemOutput *)sender;
370 - (void)outputSequenceWasFlushed:(AVPlayerItemOutput *)output;
371 @end
372 #endif
373
374 namespace WebCore {
375 using namespace PAL;
376
377 static NSArray *assetMetadataKeyNames();
378 static NSArray *itemKVOProperties();
379 static NSArray *assetTrackMetadataKeyNames();
380 static NSArray *playerKVOProperties();
381 static AVAssetTrack* firstEnabledTrack(NSArray* tracks);
382
383 #if HAVE(AVFOUNDATION_LOADER_DELEGATE)
384 static dispatch_queue_t globalLoaderDelegateQueue()
385 {
386     static dispatch_queue_t globalQueue;
387     static dispatch_once_t onceToken;
388     dispatch_once(&onceToken, ^{
389         globalQueue = dispatch_queue_create("WebCoreAVFLoaderDelegate queue", DISPATCH_QUEUE_SERIAL);
390     });
391     return globalQueue;
392 }
393 #endif
394
395 #if HAVE(AVFOUNDATION_VIDEO_OUTPUT)
396 static dispatch_queue_t globalPullDelegateQueue()
397 {
398     static dispatch_queue_t globalQueue;
399     static dispatch_once_t onceToken;
400     dispatch_once(&onceToken, ^{
401         globalQueue = dispatch_queue_create("WebCoreAVFPullDelegate queue", DISPATCH_QUEUE_SERIAL);
402     });
403     return globalQueue;
404 }
405 #endif
406
407 void MediaPlayerPrivateAVFoundationObjC::registerMediaEngine(MediaEngineRegistrar registrar)
408 {
409     if (!isAvailable())
410         return;
411
412     registrar([](MediaPlayer* player) { return std::make_unique<MediaPlayerPrivateAVFoundationObjC>(player); },
413             getSupportedTypes, supportsType, originsInMediaCache, clearMediaCache, clearMediaCacheForOrigins, supportsKeySystem);
414     ASSERT(AVFoundationMIMETypeCache::singleton().isAvailable());
415 }
416
417 static AVAssetCacheType *assetCacheForPath(const String& path)
418 {
419     NSURL *assetCacheURL;
420     
421     if (path.isEmpty())
422         assetCacheURL = [[NSURL fileURLWithPath:NSTemporaryDirectory()] URLByAppendingPathComponent:@"MediaCache" isDirectory:YES];
423     else
424         assetCacheURL = [NSURL fileURLWithPath:path isDirectory:YES];
425
426     return [initAVAssetCache() assetCacheWithURL:assetCacheURL];
427 }
428
429 HashSet<RefPtr<SecurityOrigin>> MediaPlayerPrivateAVFoundationObjC::originsInMediaCache(const String& path)
430 {
431     HashSet<RefPtr<SecurityOrigin>> origins;
432     for (NSString *key in [assetCacheForPath(path) allKeys]) {
433         URL keyAsURL = URL(URL(), key);
434         if (keyAsURL.isValid())
435             origins.add(SecurityOrigin::create(keyAsURL));
436     }
437     return origins;
438 }
439
440 static WallTime toSystemClockTime(NSDate *date)
441 {
442     ASSERT(date);
443     return WallTime::fromRawSeconds(date.timeIntervalSince1970);
444 }
445
446 void MediaPlayerPrivateAVFoundationObjC::clearMediaCache(const String& path, WallTime modifiedSince)
447 {
448     AVAssetCacheType* assetCache = assetCacheForPath(path);
449     
450     for (NSString *key in [assetCache allKeys]) {
451         if (toSystemClockTime([assetCache lastModifiedDateOfEntryForKey:key]) > modifiedSince)
452             [assetCache removeEntryForKey:key];
453     }
454
455     NSFileManager *fileManager = [NSFileManager defaultManager];
456     NSURL *baseURL = [assetCache URL];
457
458     if (modifiedSince <= WallTime::fromRawSeconds(0)) {
459         [fileManager removeItemAtURL:baseURL error:nil];
460         return;
461     }
462     
463     NSArray *propertyKeys = @[NSURLNameKey, NSURLContentModificationDateKey, NSURLIsRegularFileKey];
464     NSDirectoryEnumerator *enumerator = [fileManager enumeratorAtURL:baseURL includingPropertiesForKeys:
465         propertyKeys options:NSDirectoryEnumerationSkipsSubdirectoryDescendants
466         errorHandler:nil];
467     
468     RetainPtr<NSMutableArray> urlsToDelete = adoptNS([[NSMutableArray alloc] init]);
469     for (NSURL *fileURL : enumerator) {
470         NSDictionary *fileAttributes = [fileURL resourceValuesForKeys:propertyKeys error:nil];
471     
472         if (![fileAttributes[NSURLNameKey] hasPrefix:@"CachedMedia-"])
473             continue;
474         
475         if (![fileAttributes[NSURLIsRegularFileKey] boolValue])
476             continue;
477         
478         if (toSystemClockTime(fileAttributes[NSURLContentModificationDateKey]) <= modifiedSince)
479             continue;
480         
481         [urlsToDelete addObject:fileURL];
482     }
483     
484     for (NSURL *fileURL in urlsToDelete.get())
485         [fileManager removeItemAtURL:fileURL error:nil];
486 }
487
488 void MediaPlayerPrivateAVFoundationObjC::clearMediaCacheForOrigins(const String& path, const HashSet<RefPtr<SecurityOrigin>>& origins)
489 {
490     AVAssetCacheType* assetCache = assetCacheForPath(path);
491     for (NSString *key in [assetCache allKeys]) {
492         URL keyAsURL = URL(URL(), key);
493         if (keyAsURL.isValid()) {
494             if (origins.contains(SecurityOrigin::create(keyAsURL)))
495                 [assetCache removeEntryForKey:key];
496         }
497     }
498 }
499
500 MediaPlayerPrivateAVFoundationObjC::MediaPlayerPrivateAVFoundationObjC(MediaPlayer* player)
501     : MediaPlayerPrivateAVFoundation(player)
502     , m_videoFullscreenLayerManager(std::make_unique<VideoFullscreenLayerManagerObjC>())
503     , m_videoFullscreenGravity(MediaPlayer::VideoGravityResizeAspect)
504     , m_objcObserver(adoptNS([[WebCoreAVFMovieObserver alloc] initWithPlayer:m_weakPtrFactory.createWeakPtr(*this)]))
505     , m_videoFrameHasDrawn(false)
506     , m_haveCheckedPlayability(false)
507 #if HAVE(AVFOUNDATION_VIDEO_OUTPUT)
508     , m_videoOutputDelegate(adoptNS([[WebCoreAVFPullDelegate alloc] initWithPlayer:m_weakPtrFactory.createWeakPtr(*this)]))
509 #endif
510 #if HAVE(AVFOUNDATION_LOADER_DELEGATE)
511     , m_loaderDelegate(adoptNS([[WebCoreAVFLoaderDelegate alloc] initWithPlayer:m_weakPtrFactory.createWeakPtr(*this)]))
512 #endif
513     , m_currentTextTrack(0)
514     , m_cachedRate(0)
515     , m_cachedTotalBytes(0)
516     , m_pendingStatusChanges(0)
517     , m_cachedItemStatus(MediaPlayerAVPlayerItemStatusDoesNotExist)
518     , m_cachedLikelyToKeepUp(false)
519     , m_cachedBufferEmpty(false)
520     , m_cachedBufferFull(false)
521     , m_cachedHasEnabledAudio(false)
522     , m_shouldBufferData(true)
523     , m_cachedIsReadyForDisplay(false)
524     , m_haveBeenAskedToCreateLayer(false)
525 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
526     , m_allowsWirelessVideoPlayback(true)
527 #endif
528 {
529 }
530
531 MediaPlayerPrivateAVFoundationObjC::~MediaPlayerPrivateAVFoundationObjC()
532 {
533     m_weakPtrFactory.revokeAll();
534
535 #if HAVE(AVFOUNDATION_LOADER_DELEGATE)
536     [[m_avAsset.get() resourceLoader] setDelegate:nil queue:0];
537
538     for (auto& pair : m_resourceLoaderMap)
539         pair.value->invalidate();
540 #endif
541 #if HAVE(AVFOUNDATION_VIDEO_OUTPUT)
542     [m_videoOutput setDelegate:nil queue:0];
543 #endif
544
545     if (m_videoLayer)
546         destroyVideoLayer();
547
548     cancelLoad();
549 }
550
551 void MediaPlayerPrivateAVFoundationObjC::cancelLoad()
552 {
553     INFO_LOG(LOGIDENTIFIER);
554     tearDownVideoRendering();
555
556     [[NSNotificationCenter defaultCenter] removeObserver:m_objcObserver.get()];
557     [m_objcObserver.get() disconnect];
558
559     // Tell our observer to do nothing when our cancellation of pending loading calls its completion handler.
560     setIgnoreLoadStateChanges(true);
561     if (m_avAsset) {
562         [m_avAsset.get() cancelLoading];
563         m_avAsset = nil;
564     }
565
566     clearTextTracks();
567
568 #if HAVE(AVFOUNDATION_MEDIA_SELECTION_GROUP) && HAVE(AVFOUNDATION_LEGIBLE_OUTPUT_SUPPORT)
569     if (m_legibleOutput) {
570         if (m_avPlayerItem)
571             [m_avPlayerItem.get() removeOutput:m_legibleOutput.get()];
572         m_legibleOutput = nil;
573     }
574 #endif
575
576     if (m_avPlayerItem) {
577         for (NSString *keyName in itemKVOProperties())
578             [m_avPlayerItem.get() removeObserver:m_objcObserver.get() forKeyPath:keyName];
579         
580         m_avPlayerItem = nil;
581     }
582     if (m_avPlayer) {
583         if (m_timeObserver)
584             [m_avPlayer.get() removeTimeObserver:m_timeObserver.get()];
585         m_timeObserver = nil;
586
587         for (NSString *keyName in playerKVOProperties())
588             [m_avPlayer.get() removeObserver:m_objcObserver.get() forKeyPath:keyName];
589
590         [m_avPlayer replaceCurrentItemWithPlayerItem:nil];
591         m_avPlayer = nil;
592     }
593
594     // Reset cached properties
595     m_pendingStatusChanges = 0;
596     m_cachedItemStatus = MediaPlayerAVPlayerItemStatusDoesNotExist;
597     m_cachedSeekableRanges = nullptr;
598     m_cachedLoadedRanges = nullptr;
599     m_cachedHasEnabledAudio = false;
600     m_cachedPresentationSize = FloatSize();
601     m_cachedDuration = MediaTime::zeroTime();
602
603     for (AVPlayerItemTrack *track in m_cachedTracks.get())
604         [track removeObserver:m_objcObserver.get() forKeyPath:@"enabled"];
605     m_cachedTracks = nullptr;
606
607 #if ENABLE(WEB_AUDIO) && USE(MEDIATOOLBOX)
608     if (m_provider) {
609         m_provider->setPlayerItem(nullptr);
610         m_provider->setAudioTrack(nullptr);
611     }
612 #endif
613
614     setIgnoreLoadStateChanges(false);
615 }
616
617 bool MediaPlayerPrivateAVFoundationObjC::hasLayerRenderer() const
618 {
619     return m_haveBeenAskedToCreateLayer;
620 }
621
622 bool MediaPlayerPrivateAVFoundationObjC::hasContextRenderer() const
623 {
624 #if HAVE(AVFOUNDATION_VIDEO_OUTPUT)
625     if (m_videoOutput)
626         return true;
627 #endif
628     return m_imageGenerator;
629 }
630
631 void MediaPlayerPrivateAVFoundationObjC::createContextVideoRenderer()
632 {
633 #if HAVE(AVFOUNDATION_VIDEO_OUTPUT)
634     createVideoOutput();
635 #else
636     createImageGenerator();
637 #endif
638 }
639
640 void MediaPlayerPrivateAVFoundationObjC::createImageGenerator()
641 {
642     using namespace PAL;
643     INFO_LOG(LOGIDENTIFIER);
644
645     if (!m_avAsset || m_imageGenerator)
646         return;
647
648     m_imageGenerator = [AVAssetImageGenerator assetImageGeneratorWithAsset:m_avAsset.get()];
649
650     [m_imageGenerator.get() setApertureMode:AVAssetImageGeneratorApertureModeCleanAperture];
651     [m_imageGenerator.get() setAppliesPreferredTrackTransform:YES];
652     [m_imageGenerator.get() setRequestedTimeToleranceBefore:kCMTimeZero];
653     [m_imageGenerator.get() setRequestedTimeToleranceAfter:kCMTimeZero];
654 }
655
656 void MediaPlayerPrivateAVFoundationObjC::destroyContextVideoRenderer()
657 {
658 #if HAVE(AVFOUNDATION_VIDEO_OUTPUT)
659     destroyVideoOutput();
660 #endif
661     destroyImageGenerator();
662 }
663
664 void MediaPlayerPrivateAVFoundationObjC::destroyImageGenerator()
665 {
666     if (!m_imageGenerator)
667         return;
668
669     INFO_LOG(LOGIDENTIFIER);
670
671     m_imageGenerator = 0;
672 }
673
674 void MediaPlayerPrivateAVFoundationObjC::createVideoLayer()
675 {
676     if (!m_avPlayer || m_haveBeenAskedToCreateLayer)
677         return;
678
679     callOnMainThread([this, weakThis = makeWeakPtr(*this)] {
680         if (!weakThis)
681             return;
682
683         if (!m_avPlayer || m_haveBeenAskedToCreateLayer)
684             return;
685         m_haveBeenAskedToCreateLayer = true;
686
687         if (!m_videoLayer)
688             createAVPlayerLayer();
689
690 #if USE(VIDEOTOOLBOX) && HAVE(AVFOUNDATION_VIDEO_OUTPUT)
691         if (!m_videoOutput)
692             createVideoOutput();
693 #endif
694
695         player()->client().mediaPlayerRenderingModeChanged(player());
696     });
697 }
698
699 void MediaPlayerPrivateAVFoundationObjC::createAVPlayerLayer()
700 {
701     if (!m_avPlayer)
702         return;
703
704     m_videoLayer = adoptNS([[AVPlayerLayer alloc] init]);
705     [m_videoLayer setPlayer:m_avPlayer.get()];
706
707 #ifndef NDEBUG
708     [m_videoLayer setName:@"MediaPlayerPrivate AVPlayerLayer"];
709 #endif
710     [m_videoLayer addObserver:m_objcObserver.get() forKeyPath:@"readyForDisplay" options:NSKeyValueObservingOptionNew context:(void *)MediaPlayerAVFoundationObservationContextAVPlayerLayer];
711     updateVideoLayerGravity();
712     [m_videoLayer setContentsScale:player()->client().mediaPlayerContentsScale()];
713     IntSize defaultSize = snappedIntRect(player()->client().mediaPlayerContentBoxRect()).size();
714     INFO_LOG(LOGIDENTIFIER);
715
716     m_videoFullscreenLayerManager->setVideoLayer(m_videoLayer.get(), defaultSize);
717
718 #if PLATFORM(IOS_FAMILY) && !PLATFORM(WATCHOS)
719     if ([m_videoLayer respondsToSelector:@selector(setPIPModeEnabled:)])
720         [m_videoLayer setPIPModeEnabled:(player()->fullscreenMode() & MediaPlayer::VideoFullscreenModePictureInPicture)];
721 #endif
722 }
723
724 void MediaPlayerPrivateAVFoundationObjC::destroyVideoLayer()
725 {
726     if (!m_videoLayer)
727         return;
728
729     INFO_LOG(LOGIDENTIFIER);
730
731     [m_videoLayer removeObserver:m_objcObserver.get() forKeyPath:@"readyForDisplay"];
732     [m_videoLayer setPlayer:nil];
733     m_videoFullscreenLayerManager->didDestroyVideoLayer();
734
735     m_videoLayer = nil;
736 }
737
738 MediaTime MediaPlayerPrivateAVFoundationObjC::getStartDate() const
739 {
740     // Date changes as the track's playback position changes. Must subtract currentTime (offset in seconds) from date offset to get date beginning
741     double date = [[m_avPlayerItem currentDate] timeIntervalSince1970] * 1000;
742
743     // No live streams were made during the epoch (1970). AVFoundation returns 0 if the media file doesn't have a start date
744     if (!date)
745         return MediaTime::invalidTime();
746
747     double currentTime = CMTimeGetSeconds([m_avPlayerItem currentTime]) * 1000;
748
749     // Rounding due to second offset error when subtracting.
750     return MediaTime::createWithDouble(round(date - currentTime));
751 }
752
753 bool MediaPlayerPrivateAVFoundationObjC::hasAvailableVideoFrame() const
754 {
755     if (currentRenderingMode() == MediaRenderingToLayer)
756         return m_cachedIsReadyForDisplay;
757
758 #if HAVE(AVFOUNDATION_VIDEO_OUTPUT)
759     if (m_videoOutput && (m_lastPixelBuffer || [m_videoOutput hasNewPixelBufferForItemTime:[m_avPlayerItem currentTime]]))
760         return true;
761 #endif
762
763     return m_videoFrameHasDrawn;
764 }
765
766 #if ENABLE(AVF_CAPTIONS)
767 static const NSArray* mediaDescriptionForKind(PlatformTextTrack::TrackKind kind)
768 {
769     static bool manualSelectionMode = MTEnableCaption2015BehaviorPtr() && MTEnableCaption2015BehaviorPtr()();
770     if (manualSelectionMode)
771         return @[ AVMediaCharacteristicIsAuxiliaryContent ];
772
773     // FIXME: Match these to correct types:
774     if (kind == PlatformTextTrack::Caption)
775         return [NSArray arrayWithObjects: AVMediaCharacteristicTranscribesSpokenDialogForAccessibility, nil];
776
777     if (kind == PlatformTextTrack::Subtitle)
778         return [NSArray arrayWithObjects: AVMediaCharacteristicTranscribesSpokenDialogForAccessibility, nil];
779
780     if (kind == PlatformTextTrack::Description)
781         return [NSArray arrayWithObjects: AVMediaCharacteristicTranscribesSpokenDialogForAccessibility, AVMediaCharacteristicDescribesMusicAndSoundForAccessibility, nil];
782
783     if (kind == PlatformTextTrack::Forced)
784         return [NSArray arrayWithObjects: AVMediaCharacteristicContainsOnlyForcedSubtitles, nil];
785
786     return [NSArray arrayWithObjects: AVMediaCharacteristicTranscribesSpokenDialogForAccessibility, nil];
787 }
788     
789 void MediaPlayerPrivateAVFoundationObjC::notifyTrackModeChanged()
790 {
791     trackModeChanged();
792 }
793     
794 void MediaPlayerPrivateAVFoundationObjC::synchronizeTextTrackState()
795 {
796     const Vector<RefPtr<PlatformTextTrack>>& outOfBandTrackSources = player()->outOfBandTrackSources();
797     
798     for (auto& textTrack : m_textTracks) {
799         if (textTrack->textTrackCategory() != InbandTextTrackPrivateAVF::OutOfBand)
800             continue;
801         
802         RefPtr<OutOfBandTextTrackPrivateAVF> trackPrivate = static_cast<OutOfBandTextTrackPrivateAVF*>(textTrack.get());
803         RetainPtr<AVMediaSelectionOptionType> currentOption = trackPrivate->mediaSelectionOption();
804         
805         for (auto& track : outOfBandTrackSources) {
806             RetainPtr<CFStringRef> uniqueID = String::number(track->uniqueId()).createCFString();
807             
808             if (![[currentOption.get() outOfBandIdentifier] isEqual:(__bridge NSString *)uniqueID.get()])
809                 continue;
810             
811             InbandTextTrackPrivate::Mode mode = InbandTextTrackPrivate::Hidden;
812             if (track->mode() == PlatformTextTrack::Hidden)
813                 mode = InbandTextTrackPrivate::Hidden;
814             else if (track->mode() == PlatformTextTrack::Disabled)
815                 mode = InbandTextTrackPrivate::Disabled;
816             else if (track->mode() == PlatformTextTrack::Showing)
817                 mode = InbandTextTrackPrivate::Showing;
818             
819             textTrack->setMode(mode);
820             break;
821         }
822     }
823 }
824 #endif
825
826
827 static NSURL *canonicalURL(const URL& url)
828 {
829     NSURL *cocoaURL = url;
830     if (url.isEmpty())
831         return cocoaURL;
832
833     RetainPtr<NSURLRequest> request = adoptNS([[NSURLRequest alloc] initWithURL:cocoaURL]);
834     if (!request)
835         return cocoaURL;
836
837     NSURLRequest *canonicalRequest = [NSURLProtocol canonicalRequestForRequest:request.get()];
838     if (!canonicalRequest)
839         return cocoaURL;
840
841     return [canonicalRequest URL];
842 }
843
844 #if PLATFORM(IOS_FAMILY)
845 static NSHTTPCookie* toNSHTTPCookie(const Cookie& cookie)
846 {
847     RetainPtr<NSMutableDictionary> properties = adoptNS([[NSMutableDictionary alloc] init]);
848     [properties setDictionary:@{
849         NSHTTPCookieName: cookie.name,
850         NSHTTPCookieValue: cookie.value,
851         NSHTTPCookieDomain: cookie.domain,
852         NSHTTPCookiePath: cookie.path,
853         NSHTTPCookieExpires: [NSDate dateWithTimeIntervalSince1970:(cookie.expires / 1000)],
854     }];
855     if (cookie.secure)
856         [properties setObject:@YES forKey:NSHTTPCookieSecure];
857     if (cookie.session)
858         [properties setObject:@YES forKey:NSHTTPCookieDiscard];
859
860     return [NSHTTPCookie cookieWithProperties:properties.get()];
861 }
862 #endif
863
864 void MediaPlayerPrivateAVFoundationObjC::createAVAssetForURL(const URL& url)
865 {
866     if (m_avAsset)
867         return;
868
869     INFO_LOG(LOGIDENTIFIER);
870
871     setDelayCallbacks(true);
872
873     RetainPtr<NSMutableDictionary> options = adoptNS([[NSMutableDictionary alloc] init]);    
874
875     [options.get() setObject:[NSNumber numberWithInt:AVAssetReferenceRestrictionForbidRemoteReferenceToLocal | AVAssetReferenceRestrictionForbidLocalReferenceToRemote] forKey:AVURLAssetReferenceRestrictionsKey];
876
877     RetainPtr<NSMutableDictionary> headerFields = adoptNS([[NSMutableDictionary alloc] init]);
878
879     String referrer = player()->referrer();
880     if (!referrer.isEmpty())
881         [headerFields.get() setObject:referrer forKey:@"Referer"];
882
883     String userAgent = player()->userAgent();
884     if (!userAgent.isEmpty())
885         [headerFields.get() setObject:userAgent forKey:@"User-Agent"];
886
887     if ([headerFields.get() count])
888         [options.get() setObject:headerFields.get() forKey:@"AVURLAssetHTTPHeaderFieldsKey"];
889
890     if (player()->doesHaveAttribute("x-itunes-inherit-uri-query-component"))
891         [options.get() setObject:@YES forKey: AVURLAssetInheritURIQueryComponentFromReferencingURIKey];
892
893     if (canLoadAVURLAssetUseClientURLLoadingExclusively())
894         [options setObject:@YES forKey:AVURLAssetUseClientURLLoadingExclusively];
895 #if PLATFORM(IOS_FAMILY)
896     else if (canLoadAVURLAssetRequiresCustomURLLoadingKey())
897         [options setObject:@YES forKey:AVURLAssetRequiresCustomURLLoadingKey];
898     // FIXME: rdar://problem/20354688
899     String identifier = player()->sourceApplicationIdentifier();
900     if (!identifier.isEmpty() && canLoadAVURLAssetClientBundleIdentifierKey())
901         [options setObject:identifier forKey:AVURLAssetClientBundleIdentifierKey];
902 #endif
903
904     auto type = player()->contentMIMEType();
905     if (canLoadAVURLAssetOutOfBandMIMETypeKey() && !type.isEmpty() && !player()->contentMIMETypeWasInferredFromExtension()) {
906         auto codecs = player()->contentTypeCodecs();
907         if (!codecs.isEmpty()) {
908             NSString *typeString = [NSString stringWithFormat:@"%@; codecs=\"%@\"", (NSString *)type, (NSString *)codecs];
909             [options setObject:typeString forKey:AVURLAssetOutOfBandMIMETypeKey];
910         } else
911             [options setObject:(NSString *)type forKey:AVURLAssetOutOfBandMIMETypeKey];
912     }
913
914 #if ENABLE(AVF_CAPTIONS)
915     const Vector<RefPtr<PlatformTextTrack>>& outOfBandTrackSources = player()->outOfBandTrackSources();
916     if (!outOfBandTrackSources.isEmpty()) {
917         RetainPtr<NSMutableArray> outOfBandTracks = adoptNS([[NSMutableArray alloc] init]);
918         for (auto& trackSource : outOfBandTrackSources) {
919             RetainPtr<CFStringRef> label = trackSource->label().createCFString();
920             RetainPtr<CFStringRef> language = trackSource->language().createCFString();
921             RetainPtr<CFStringRef> uniqueID = String::number(trackSource->uniqueId()).createCFString();
922             RetainPtr<CFStringRef> url = trackSource->url().createCFString();
923             [outOfBandTracks.get() addObject:@{
924                 AVOutOfBandAlternateTrackDisplayNameKey: (__bridge NSString *)label.get(),
925                 AVOutOfBandAlternateTrackExtendedLanguageTagKey: (__bridge NSString *)language.get(),
926                 AVOutOfBandAlternateTrackIsDefaultKey: trackSource->isDefault() ? @YES : @NO,
927                 AVOutOfBandAlternateTrackIdentifierKey: (__bridge NSString *)uniqueID.get(),
928                 AVOutOfBandAlternateTrackSourceKey: (__bridge NSString *)url.get(),
929                 AVOutOfBandAlternateTrackMediaCharactersticsKey: mediaDescriptionForKind(trackSource->kind()),
930             }];
931         }
932
933         [options.get() setObject:outOfBandTracks.get() forKey:AVURLAssetOutOfBandAlternateTracksKey];
934     }
935 #endif
936
937 #if PLATFORM(IOS_FAMILY)
938     String networkInterfaceName = player()->mediaPlayerNetworkInterfaceName();
939     if (!networkInterfaceName.isEmpty())
940         [options setObject:networkInterfaceName forKey:AVURLAssetBoundNetworkInterfaceName];
941 #endif
942
943 #if PLATFORM(IOS_FAMILY)
944     Vector<Cookie> cookies;
945     if (player()->getRawCookies(url, cookies)) {
946         RetainPtr<NSMutableArray> nsCookies = adoptNS([[NSMutableArray alloc] initWithCapacity:cookies.size()]);
947         for (auto& cookie : cookies)
948             [nsCookies addObject:toNSHTTPCookie(cookie)];
949
950         if (canLoadAVURLAssetHTTPCookiesKey())
951             [options setObject:nsCookies.get() forKey:AVURLAssetHTTPCookiesKey];
952     }
953 #endif
954
955     bool usePersistentCache = player()->client().mediaPlayerShouldUsePersistentCache();
956     [options setObject:@(!usePersistentCache) forKey:AVURLAssetUsesNoPersistentCacheKey];
957     
958     if (usePersistentCache)
959         [options setObject:assetCacheForPath(player()->client().mediaPlayerMediaCacheDirectory()) forKey:AVURLAssetCacheKey];
960
961     NSURL *cocoaURL = canonicalURL(url);
962     m_avAsset = adoptNS([[AVURLAsset alloc] initWithURL:cocoaURL options:options.get()]);
963
964 #if HAVE(AVFOUNDATION_LOADER_DELEGATE)
965     AVAssetResourceLoader *resourceLoader = m_avAsset.get().resourceLoader;
966     [resourceLoader setDelegate:m_loaderDelegate.get() queue:globalLoaderDelegateQueue()];
967
968     if (DeprecatedGlobalSettings::isAVFoundationNSURLSessionEnabled()
969         && [resourceLoader respondsToSelector:@selector(setURLSession:)]
970         && [resourceLoader respondsToSelector:@selector(URLSessionDataDelegate)]
971         && [resourceLoader respondsToSelector:@selector(URLSessionDataDelegateQueue)]) {
972         RefPtr<PlatformMediaResourceLoader> mediaResourceLoader = player()->createResourceLoader();
973         if (mediaResourceLoader)
974             resourceLoader.URLSession = (NSURLSession *)[[[WebCoreNSURLSession alloc] initWithResourceLoader:*mediaResourceLoader delegate:resourceLoader.URLSessionDataDelegate delegateQueue:resourceLoader.URLSessionDataDelegateQueue] autorelease];
975     }
976
977 #endif
978
979     m_haveCheckedPlayability = false;
980
981     setDelayCallbacks(false);
982 }
983
984 void MediaPlayerPrivateAVFoundationObjC::setAVPlayerItem(AVPlayerItemType *item)
985 {
986     if (!m_avPlayer)
987         return;
988
989     if (pthread_main_np()) {
990         [m_avPlayer replaceCurrentItemWithPlayerItem:item];
991         return;
992     }
993
994     RetainPtr<AVPlayerType> strongPlayer = m_avPlayer.get();
995     RetainPtr<AVPlayerItemType> strongItem = item;
996     dispatch_async(dispatch_get_main_queue(), [strongPlayer, strongItem] {
997         [strongPlayer replaceCurrentItemWithPlayerItem:strongItem.get()];
998     });
999 }
1000
1001 void MediaPlayerPrivateAVFoundationObjC::createAVPlayer()
1002 {
1003     if (m_avPlayer)
1004         return;
1005
1006     INFO_LOG(LOGIDENTIFIER);
1007
1008     setDelayCallbacks(true);
1009
1010     m_avPlayer = adoptNS([[AVPlayer alloc] init]);
1011     for (NSString *keyName in playerKVOProperties())
1012         [m_avPlayer.get() addObserver:m_objcObserver.get() forKeyPath:keyName options:NSKeyValueObservingOptionNew context:(void *)MediaPlayerAVFoundationObservationContextPlayer];
1013
1014 #if HAVE(AVFOUNDATION_MEDIA_SELECTION_GROUP) && HAVE(AVFOUNDATION_LEGIBLE_OUTPUT_SUPPORT)
1015     [m_avPlayer.get() setAppliesMediaSelectionCriteriaAutomatically:NO];
1016 #endif
1017
1018 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
1019     updateDisableExternalPlayback();
1020     [m_avPlayer.get() setAllowsExternalPlayback:m_allowsWirelessVideoPlayback];
1021 #endif
1022
1023 #if ENABLE(WIRELESS_PLAYBACK_TARGET) && !PLATFORM(IOS_FAMILY)
1024     if (m_shouldPlayToPlaybackTarget) {
1025         // Clear m_shouldPlayToPlaybackTarget so doesn't return without doing anything.
1026         m_shouldPlayToPlaybackTarget = false;
1027         setShouldPlayToPlaybackTarget(true);
1028     }
1029 #endif
1030
1031 #if PLATFORM(IOS_FAMILY) && !PLATFORM(IOS_FAMILY_SIMULATOR) && !PLATFORM(IOSMAC)
1032     setShouldDisableSleep(player()->shouldDisableSleep());
1033 #endif
1034
1035     if (m_muted) {
1036         // Clear m_muted so setMuted doesn't return without doing anything.
1037         m_muted = false;
1038         [m_avPlayer.get() setMuted:m_muted];
1039     }
1040
1041     if (player()->client().mediaPlayerIsVideo())
1042         createAVPlayerLayer();
1043
1044     if (m_avPlayerItem)
1045         setAVPlayerItem(m_avPlayerItem.get());
1046
1047     setDelayCallbacks(false);
1048 }
1049
1050 void MediaPlayerPrivateAVFoundationObjC::createAVPlayerItem()
1051 {
1052     if (m_avPlayerItem)
1053         return;
1054
1055     INFO_LOG(LOGIDENTIFIER);
1056
1057     setDelayCallbacks(true);
1058
1059     // Create the player item so we can load media data. 
1060     m_avPlayerItem = adoptNS([[AVPlayerItem alloc] initWithAsset:m_avAsset.get()]);
1061
1062     [[NSNotificationCenter defaultCenter] addObserver:m_objcObserver.get() selector:@selector(didEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:m_avPlayerItem.get()];
1063
1064     NSKeyValueObservingOptions options = NSKeyValueObservingOptionNew | NSKeyValueObservingOptionPrior;
1065     for (NSString *keyName in itemKVOProperties())
1066         [m_avPlayerItem.get() addObserver:m_objcObserver.get() forKeyPath:keyName options:options context:(void *)MediaPlayerAVFoundationObservationContextPlayerItem];
1067
1068     [m_avPlayerItem setAudioTimePitchAlgorithm:(player()->preservesPitch() ? AVAudioTimePitchAlgorithmSpectral : AVAudioTimePitchAlgorithmVarispeed)];
1069
1070     if (m_avPlayer)
1071         setAVPlayerItem(m_avPlayerItem.get());
1072
1073 #if HAVE(AVFOUNDATION_MEDIA_SELECTION_GROUP) && HAVE(AVFOUNDATION_LEGIBLE_OUTPUT_SUPPORT)
1074     const NSTimeInterval legibleOutputAdvanceInterval = 2;
1075
1076     RetainPtr<NSArray> subtypes = adoptNS([[NSArray alloc] initWithObjects:[NSNumber numberWithUnsignedInt:kCMSubtitleFormatType_WebVTT], nil]);
1077     m_legibleOutput = adoptNS([[AVPlayerItemLegibleOutput alloc] initWithMediaSubtypesForNativeRepresentation:subtypes.get()]);
1078     [m_legibleOutput.get() setSuppressesPlayerRendering:YES];
1079
1080     [m_legibleOutput.get() setDelegate:m_objcObserver.get() queue:dispatch_get_main_queue()];
1081     [m_legibleOutput.get() setAdvanceIntervalForDelegateInvocation:legibleOutputAdvanceInterval];
1082     [m_legibleOutput.get() setTextStylingResolution:AVPlayerItemLegibleOutputTextStylingResolutionSourceAndRulesOnly];
1083     [m_avPlayerItem.get() addOutput:m_legibleOutput.get()];
1084 #endif
1085
1086 #if ENABLE(WEB_AUDIO) && USE(MEDIATOOLBOX)
1087     if (m_provider) {
1088         m_provider->setPlayerItem(m_avPlayerItem.get());
1089         m_provider->setAudioTrack(firstEnabledTrack(safeAVAssetTracksForAudibleMedia()));
1090     }
1091 #endif
1092
1093 #if HAVE(AVFOUNDATION_VIDEO_OUTPUT)
1094     createVideoOutput();
1095 #endif
1096
1097     setDelayCallbacks(false);
1098 }
1099
1100 void MediaPlayerPrivateAVFoundationObjC::checkPlayability()
1101 {
1102     if (m_haveCheckedPlayability)
1103         return;
1104     m_haveCheckedPlayability = true;
1105
1106     INFO_LOG(LOGIDENTIFIER);
1107     auto weakThis = makeWeakPtr(*this);
1108
1109     [m_avAsset.get() loadValuesAsynchronouslyForKeys:[NSArray arrayWithObjects:@"playable", @"tracks", nil] completionHandler:^{
1110         callOnMainThread([weakThis] {
1111             if (weakThis)
1112                 weakThis->scheduleMainThreadNotification(MediaPlayerPrivateAVFoundation::Notification::AssetPlayabilityKnown);
1113         });
1114     }];
1115 }
1116
1117 void MediaPlayerPrivateAVFoundationObjC::beginLoadingMetadata()
1118 {
1119     INFO_LOG(LOGIDENTIFIER);
1120
1121     OSObjectPtr<dispatch_group_t> metadataLoadingGroup = adoptOSObject(dispatch_group_create());
1122     dispatch_group_enter(metadataLoadingGroup.get());
1123     auto weakThis = makeWeakPtr(*this);
1124     [m_avAsset.get() loadValuesAsynchronouslyForKeys:assetMetadataKeyNames() completionHandler:^{
1125
1126         callOnMainThread([weakThis, metadataLoadingGroup] {
1127             if (weakThis && [weakThis->m_avAsset.get() statusOfValueForKey:@"tracks" error:nil] == AVKeyValueStatusLoaded) {
1128                 for (AVAssetTrack *track in [weakThis->m_avAsset.get() tracks]) {
1129                     dispatch_group_enter(metadataLoadingGroup.get());
1130                     [track loadValuesAsynchronouslyForKeys:assetTrackMetadataKeyNames() completionHandler:^{
1131                         dispatch_group_leave(metadataLoadingGroup.get());
1132                     }];
1133                 }
1134             }
1135             dispatch_group_leave(metadataLoadingGroup.get());
1136         });
1137     }];
1138
1139     dispatch_group_notify(metadataLoadingGroup.get(), dispatch_get_main_queue(), ^{
1140         callOnMainThread([weakThis] {
1141             if (weakThis)
1142                 [weakThis->m_objcObserver.get() metadataLoaded];
1143         });
1144     });
1145 }
1146
1147 MediaPlayerPrivateAVFoundation::ItemStatus MediaPlayerPrivateAVFoundationObjC::playerItemStatus() const
1148 {
1149     if (!m_avPlayerItem)
1150         return MediaPlayerPrivateAVFoundation::MediaPlayerAVPlayerItemStatusDoesNotExist;
1151
1152     if (m_cachedItemStatus == AVPlayerItemStatusUnknown)
1153         return MediaPlayerPrivateAVFoundation::MediaPlayerAVPlayerItemStatusUnknown;
1154     if (m_cachedItemStatus == AVPlayerItemStatusFailed)
1155         return MediaPlayerPrivateAVFoundation::MediaPlayerAVPlayerItemStatusFailed;
1156     if (m_cachedLikelyToKeepUp)
1157         return MediaPlayerPrivateAVFoundation::MediaPlayerAVPlayerItemStatusPlaybackLikelyToKeepUp;
1158     if (m_cachedBufferFull)
1159         return MediaPlayerPrivateAVFoundation::MediaPlayerAVPlayerItemStatusPlaybackBufferFull;
1160     if (m_cachedBufferEmpty)
1161         return MediaPlayerPrivateAVFoundation::MediaPlayerAVPlayerItemStatusPlaybackBufferEmpty;
1162
1163     return MediaPlayerPrivateAVFoundation::MediaPlayerAVPlayerItemStatusReadyToPlay;
1164 }
1165
1166 PlatformLayer* MediaPlayerPrivateAVFoundationObjC::platformLayer() const
1167 {
1168     return m_videoFullscreenLayerManager->videoInlineLayer();
1169 }
1170
1171 void MediaPlayerPrivateAVFoundationObjC::updateVideoFullscreenInlineImage()
1172 {
1173 #if HAVE(AVFOUNDATION_VIDEO_OUTPUT)
1174     updateLastImage(UpdateType::UpdateSynchronously);
1175     m_videoFullscreenLayerManager->updateVideoFullscreenInlineImage(m_lastImage);
1176 #endif
1177 }
1178
1179 void MediaPlayerPrivateAVFoundationObjC::setVideoFullscreenLayer(PlatformLayer* videoFullscreenLayer, Function<void()>&& completionHandler)
1180 {
1181 #if HAVE(AVFOUNDATION_VIDEO_OUTPUT)
1182     updateLastImage(UpdateType::UpdateSynchronously);
1183     m_videoFullscreenLayerManager->setVideoFullscreenLayer(videoFullscreenLayer, WTFMove(completionHandler), m_lastImage);
1184 #else
1185     m_videoFullscreenLayerManager->setVideoFullscreenLayer(videoFullscreenLayer, WTFMove(completionHandler), nil);
1186 #endif
1187     updateDisableExternalPlayback();
1188 }
1189
1190 void MediaPlayerPrivateAVFoundationObjC::setVideoFullscreenFrame(FloatRect frame)
1191 {
1192     m_videoFullscreenLayerManager->setVideoFullscreenFrame(frame);
1193 }
1194
1195 void MediaPlayerPrivateAVFoundationObjC::setVideoFullscreenGravity(MediaPlayer::VideoGravity gravity)
1196 {
1197     m_videoFullscreenGravity = gravity;
1198
1199     if (!m_videoLayer)
1200         return;
1201
1202     NSString *videoGravity = AVLayerVideoGravityResizeAspect;
1203     if (gravity == MediaPlayer::VideoGravityResize)
1204         videoGravity = AVLayerVideoGravityResize;
1205     else if (gravity == MediaPlayer::VideoGravityResizeAspect)
1206         videoGravity = AVLayerVideoGravityResizeAspect;
1207     else if (gravity == MediaPlayer::VideoGravityResizeAspectFill)
1208         videoGravity = AVLayerVideoGravityResizeAspectFill;
1209     else
1210         ASSERT_NOT_REACHED();
1211     
1212     if ([m_videoLayer videoGravity] == videoGravity)
1213         return;
1214
1215     [m_videoLayer setVideoGravity:videoGravity];
1216     syncTextTrackBounds();
1217 }
1218
1219 void MediaPlayerPrivateAVFoundationObjC::setVideoFullscreenMode(MediaPlayer::VideoFullscreenMode mode)
1220 {
1221 #if PLATFORM(IOS_FAMILY) && !PLATFORM(WATCHOS)
1222     if ([m_videoLayer respondsToSelector:@selector(setPIPModeEnabled:)])
1223         [m_videoLayer setPIPModeEnabled:(mode & MediaPlayer::VideoFullscreenModePictureInPicture)];
1224     updateDisableExternalPlayback();
1225 #else
1226     UNUSED_PARAM(mode);
1227 #endif
1228 }
1229     
1230 void MediaPlayerPrivateAVFoundationObjC::videoFullscreenStandbyChanged()
1231 {
1232 #if PLATFORM(IOS_FAMILY) && !PLATFORM(WATCHOS)
1233     updateDisableExternalPlayback();
1234 #endif
1235 }
1236
1237 #if PLATFORM(IOS_FAMILY)
1238 NSArray *MediaPlayerPrivateAVFoundationObjC::timedMetadata() const
1239 {
1240     if (m_currentMetaData)
1241         return m_currentMetaData.get();
1242     return nil;
1243 }
1244
1245 String MediaPlayerPrivateAVFoundationObjC::accessLog() const
1246 {
1247     if (!m_avPlayerItem)
1248         return emptyString();
1249     
1250     AVPlayerItemAccessLog *log = [m_avPlayerItem.get() accessLog];
1251     RetainPtr<NSString> logString = adoptNS([[NSString alloc] initWithData:[log extendedLogData] encoding:[log extendedLogDataStringEncoding]]);
1252
1253     return logString.get();
1254 }
1255
1256 String MediaPlayerPrivateAVFoundationObjC::errorLog() const
1257 {
1258     if (!m_avPlayerItem)
1259         return emptyString();
1260
1261     AVPlayerItemErrorLog *log = [m_avPlayerItem.get() errorLog];
1262     RetainPtr<NSString> logString = adoptNS([[NSString alloc] initWithData:[log extendedLogData] encoding:[log extendedLogDataStringEncoding]]);
1263
1264     return logString.get();
1265 }
1266 #endif
1267
1268 void MediaPlayerPrivateAVFoundationObjC::platformSetVisible(bool isVisible)
1269 {
1270     [CATransaction begin];
1271     [CATransaction setDisableActions:YES];    
1272     if (m_videoLayer)
1273         [m_videoLayer.get() setHidden:!isVisible];
1274     [CATransaction commit];
1275 }
1276     
1277 void MediaPlayerPrivateAVFoundationObjC::platformPlay()
1278 {
1279     INFO_LOG(LOGIDENTIFIER);
1280     if (!metaDataAvailable())
1281         return;
1282
1283     setDelayCallbacks(true);
1284     m_cachedRate = requestedRate();
1285     [m_avPlayer.get() setRate:requestedRate()];
1286     setDelayCallbacks(false);
1287 }
1288
1289 void MediaPlayerPrivateAVFoundationObjC::platformPause()
1290 {
1291     INFO_LOG(LOGIDENTIFIER);
1292     if (!metaDataAvailable())
1293         return;
1294
1295     setDelayCallbacks(true);
1296     m_cachedRate = 0;
1297     [m_avPlayer.get() setRate:0];
1298     setDelayCallbacks(false);
1299 }
1300
1301 MediaTime MediaPlayerPrivateAVFoundationObjC::platformDuration() const
1302 {
1303     // Do not ask the asset for duration before it has been loaded or it will fetch the
1304     // answer synchronously.
1305     if (!m_avAsset || assetStatus() < MediaPlayerAVAssetStatusLoaded)
1306         return MediaTime::invalidTime();
1307     
1308     CMTime cmDuration;
1309     
1310     // Check the AVItem if we have one and it has loaded duration, some assets never report duration.
1311     if (m_avPlayerItem && playerItemStatus() >= MediaPlayerAVPlayerItemStatusReadyToPlay)
1312         cmDuration = [m_avPlayerItem.get() duration];
1313     else
1314         cmDuration = [m_avAsset.get() duration];
1315
1316     if (CMTIME_IS_NUMERIC(cmDuration))
1317         return PAL::toMediaTime(cmDuration);
1318
1319     if (CMTIME_IS_INDEFINITE(cmDuration))
1320         return MediaTime::positiveInfiniteTime();
1321
1322     INFO_LOG(LOGIDENTIFIER, "returning invalid time");
1323     return MediaTime::invalidTime();
1324 }
1325
1326 MediaTime MediaPlayerPrivateAVFoundationObjC::currentMediaTime() const
1327 {
1328     if (!metaDataAvailable() || !m_avPlayerItem)
1329         return MediaTime::zeroTime();
1330
1331     CMTime itemTime = [m_avPlayerItem.get() currentTime];
1332     if (CMTIME_IS_NUMERIC(itemTime))
1333         return std::max(PAL::toMediaTime(itemTime), MediaTime::zeroTime());
1334
1335     return MediaTime::zeroTime();
1336 }
1337
1338 void MediaPlayerPrivateAVFoundationObjC::seekToTime(const MediaTime& time, const MediaTime& negativeTolerance, const MediaTime& positiveTolerance)
1339 {
1340     // setCurrentTime generates several event callbacks, update afterwards.
1341     setDelayCallbacks(true);
1342
1343     if (m_metadataTrack)
1344         m_metadataTrack->flushPartialCues();
1345
1346     CMTime cmTime = PAL::toCMTime(time);
1347     CMTime cmBefore = PAL::toCMTime(negativeTolerance);
1348     CMTime cmAfter = PAL::toCMTime(positiveTolerance);
1349
1350     // [AVPlayerItem seekToTime] will throw an exception if toleranceBefore is negative.
1351     if (CMTimeCompare(cmBefore, kCMTimeZero) < 0)
1352         cmBefore = kCMTimeZero;
1353     
1354     auto weakThis = makeWeakPtr(*this);
1355
1356     [m_avPlayerItem.get() seekToTime:cmTime toleranceBefore:cmBefore toleranceAfter:cmAfter completionHandler:^(BOOL finished) {
1357         callOnMainThread([weakThis, finished] {
1358             auto _this = weakThis.get();
1359             if (!_this)
1360                 return;
1361
1362             _this->seekCompleted(finished);
1363         });
1364     }];
1365
1366     setDelayCallbacks(false);
1367 }
1368
1369 void MediaPlayerPrivateAVFoundationObjC::setVolume(float volume)
1370 {
1371 #if PLATFORM(IOS_FAMILY)
1372     UNUSED_PARAM(volume);
1373     return;
1374 #else
1375     if (!m_avPlayer)
1376         return;
1377
1378     [m_avPlayer.get() setVolume:volume];
1379 #endif
1380 }
1381
1382 void MediaPlayerPrivateAVFoundationObjC::setMuted(bool muted)
1383 {
1384     if (m_muted == muted)
1385         return;
1386
1387     INFO_LOG(LOGIDENTIFIER, "- ", muted);
1388
1389     m_muted = muted;
1390
1391     if (!m_avPlayer)
1392         return;
1393
1394     [m_avPlayer.get() setMuted:m_muted];
1395 }
1396
1397 void MediaPlayerPrivateAVFoundationObjC::setClosedCaptionsVisible(bool closedCaptionsVisible)
1398 {
1399     UNUSED_PARAM(closedCaptionsVisible);
1400
1401     if (!metaDataAvailable())
1402         return;
1403
1404     INFO_LOG(LOGIDENTIFIER, "- ", closedCaptionsVisible);
1405 }
1406
1407 void MediaPlayerPrivateAVFoundationObjC::setRateDouble(double rate)
1408 {
1409     setDelayCallbacks(true);
1410     m_cachedRate = rate;
1411     [m_avPlayer.get() setRate:rate];
1412     setDelayCallbacks(false);
1413 }
1414
1415 double MediaPlayerPrivateAVFoundationObjC::rate() const
1416 {
1417     if (!metaDataAvailable())
1418         return 0;
1419
1420     return m_cachedRate;
1421 }
1422
1423 double MediaPlayerPrivateAVFoundationObjC::seekableTimeRangesLastModifiedTime() const
1424 {
1425 #if (PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101300) || (PLATFORM(IOS_FAMILY) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000)
1426     return [m_avPlayerItem seekableTimeRangesLastModifiedTime];
1427 #else
1428     return 0;
1429 #endif
1430 }
1431
1432 double MediaPlayerPrivateAVFoundationObjC::liveUpdateInterval() const
1433 {
1434 #if (PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101300) || (PLATFORM(IOS_FAMILY) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000)
1435     return [m_avPlayerItem liveUpdateInterval];
1436 #else
1437     return 0;
1438 #endif
1439 }
1440
1441 void MediaPlayerPrivateAVFoundationObjC::setPreservesPitch(bool preservesPitch)
1442 {
1443     if (m_avPlayerItem)
1444         [m_avPlayerItem setAudioTimePitchAlgorithm:(preservesPitch ? AVAudioTimePitchAlgorithmSpectral : AVAudioTimePitchAlgorithmVarispeed)];
1445 }
1446
1447 std::unique_ptr<PlatformTimeRanges> MediaPlayerPrivateAVFoundationObjC::platformBufferedTimeRanges() const
1448 {
1449     auto timeRanges = std::make_unique<PlatformTimeRanges>();
1450
1451     if (!m_avPlayerItem)
1452         return timeRanges;
1453
1454     for (NSValue *thisRangeValue in m_cachedLoadedRanges.get()) {
1455         CMTimeRange timeRange = [thisRangeValue CMTimeRangeValue];
1456         if (CMTIMERANGE_IS_VALID(timeRange) && !CMTIMERANGE_IS_EMPTY(timeRange))
1457             timeRanges->add(PAL::toMediaTime(timeRange.start), PAL::toMediaTime(CMTimeRangeGetEnd(timeRange)));
1458     }
1459     return timeRanges;
1460 }
1461
1462 MediaTime MediaPlayerPrivateAVFoundationObjC::platformMinTimeSeekable() const
1463 {
1464     if (!m_cachedSeekableRanges || ![m_cachedSeekableRanges count])
1465         return MediaTime::zeroTime();
1466
1467     MediaTime minTimeSeekable = MediaTime::positiveInfiniteTime();
1468     bool hasValidRange = false;
1469     for (NSValue *thisRangeValue in m_cachedSeekableRanges.get()) {
1470         CMTimeRange timeRange = [thisRangeValue CMTimeRangeValue];
1471         if (!CMTIMERANGE_IS_VALID(timeRange) || CMTIMERANGE_IS_EMPTY(timeRange))
1472             continue;
1473
1474         hasValidRange = true;
1475         MediaTime startOfRange = PAL::toMediaTime(timeRange.start);
1476         if (minTimeSeekable > startOfRange)
1477             minTimeSeekable = startOfRange;
1478     }
1479     return hasValidRange ? minTimeSeekable : MediaTime::zeroTime();
1480 }
1481
1482 MediaTime MediaPlayerPrivateAVFoundationObjC::platformMaxTimeSeekable() const
1483 {
1484     if (!m_cachedSeekableRanges)
1485         m_cachedSeekableRanges = [m_avPlayerItem seekableTimeRanges];
1486
1487     MediaTime maxTimeSeekable;
1488     for (NSValue *thisRangeValue in m_cachedSeekableRanges.get()) {
1489         CMTimeRange timeRange = [thisRangeValue CMTimeRangeValue];
1490         if (!CMTIMERANGE_IS_VALID(timeRange) || CMTIMERANGE_IS_EMPTY(timeRange))
1491             continue;
1492         
1493         MediaTime endOfRange = PAL::toMediaTime(CMTimeRangeGetEnd(timeRange));
1494         if (maxTimeSeekable < endOfRange)
1495             maxTimeSeekable = endOfRange;
1496     }
1497     return maxTimeSeekable;
1498 }
1499
1500 MediaTime MediaPlayerPrivateAVFoundationObjC::platformMaxTimeLoaded() const
1501 {
1502     if (!m_cachedLoadedRanges)
1503         return MediaTime::zeroTime();
1504
1505     MediaTime maxTimeLoaded;
1506     for (NSValue *thisRangeValue in m_cachedLoadedRanges.get()) {
1507         CMTimeRange timeRange = [thisRangeValue CMTimeRangeValue];
1508         if (!CMTIMERANGE_IS_VALID(timeRange) || CMTIMERANGE_IS_EMPTY(timeRange))
1509             continue;
1510         
1511         MediaTime endOfRange = PAL::toMediaTime(CMTimeRangeGetEnd(timeRange));
1512         if (maxTimeLoaded < endOfRange)
1513             maxTimeLoaded = endOfRange;
1514     }
1515
1516     return maxTimeLoaded;   
1517 }
1518
1519 unsigned long long MediaPlayerPrivateAVFoundationObjC::totalBytes() const
1520 {
1521     if (!metaDataAvailable())
1522         return 0;
1523
1524     if (m_cachedTotalBytes)
1525         return m_cachedTotalBytes;
1526
1527     for (AVPlayerItemTrack *thisTrack in m_cachedTracks.get())
1528         m_cachedTotalBytes += [[thisTrack assetTrack] totalSampleDataLength];
1529
1530     return m_cachedTotalBytes;
1531 }
1532
1533 void MediaPlayerPrivateAVFoundationObjC::setAsset(RetainPtr<id>&& asset)
1534 {
1535     m_avAsset = WTFMove(asset);
1536 }
1537
1538 MediaPlayerPrivateAVFoundation::AssetStatus MediaPlayerPrivateAVFoundationObjC::assetStatus() const
1539 {
1540     if (!m_avAsset)
1541         return MediaPlayerAVAssetStatusDoesNotExist;
1542
1543     for (NSString *keyName in assetMetadataKeyNames()) {
1544         NSError *error = nil;
1545         AVKeyValueStatus keyStatus = [m_avAsset.get() statusOfValueForKey:keyName error:&error];
1546
1547         if (error)
1548             ERROR_LOG(LOGIDENTIFIER, "failed for ", [keyName UTF8String], ", error = ", [[error localizedDescription] UTF8String]);
1549
1550         if (keyStatus < AVKeyValueStatusLoaded)
1551             return MediaPlayerAVAssetStatusLoading;// At least one key is not loaded yet.
1552         
1553         if (keyStatus == AVKeyValueStatusFailed)
1554             return MediaPlayerAVAssetStatusFailed; // At least one key could not be loaded.
1555
1556         if (keyStatus == AVKeyValueStatusCancelled)
1557             return MediaPlayerAVAssetStatusCancelled; // Loading of at least one key was cancelled.
1558     }
1559
1560     if (!player()->shouldCheckHardwareSupport())
1561         m_tracksArePlayable = true;
1562
1563     if (!m_tracksArePlayable) {
1564         m_tracksArePlayable = true;
1565         for (AVAssetTrack *track in [m_avAsset tracks]) {
1566             if (!assetTrackMeetsHardwareDecodeRequirements(track, player()->mediaContentTypesRequiringHardwareSupport())) {
1567                 m_tracksArePlayable = false;
1568                 break;
1569             }
1570         }
1571     }
1572
1573     if ([[m_avAsset.get() valueForKey:@"playable"] boolValue] && m_tracksArePlayable.value())
1574         return MediaPlayerAVAssetStatusPlayable;
1575
1576     return MediaPlayerAVAssetStatusLoaded;
1577 }
1578
1579 long MediaPlayerPrivateAVFoundationObjC::assetErrorCode() const
1580 {
1581     if (!m_avAsset)
1582         return 0;
1583
1584     NSError *error = nil;
1585     [m_avAsset statusOfValueForKey:@"playable" error:&error];
1586     return [error code];
1587 }
1588
1589 void MediaPlayerPrivateAVFoundationObjC::paintCurrentFrameInContext(GraphicsContext& context, const FloatRect& rect)
1590 {
1591     if (!metaDataAvailable() || context.paintingDisabled())
1592         return;
1593
1594     setDelayCallbacks(true);
1595     BEGIN_BLOCK_OBJC_EXCEPTIONS;
1596
1597 #if HAVE(AVFOUNDATION_VIDEO_OUTPUT)
1598     if (videoOutputHasAvailableFrame())
1599         paintWithVideoOutput(context, rect);
1600     else
1601 #endif
1602         paintWithImageGenerator(context, rect);
1603
1604     END_BLOCK_OBJC_EXCEPTIONS;
1605     setDelayCallbacks(false);
1606
1607     m_videoFrameHasDrawn = true;
1608 }
1609
1610 void MediaPlayerPrivateAVFoundationObjC::paint(GraphicsContext& context, const FloatRect& rect)
1611 {
1612     if (!metaDataAvailable() || context.paintingDisabled())
1613         return;
1614
1615     // We can ignore the request if we are already rendering to a layer.
1616     if (currentRenderingMode() == MediaRenderingToLayer)
1617         return;
1618
1619     // paint() is best effort, so only paint if we already have an image generator or video output available.
1620     if (!hasContextRenderer())
1621         return;
1622
1623     paintCurrentFrameInContext(context, rect);
1624 }
1625
1626 void MediaPlayerPrivateAVFoundationObjC::paintWithImageGenerator(GraphicsContext& context, const FloatRect& rect)
1627 {
1628     INFO_LOG(LOGIDENTIFIER);
1629
1630     RetainPtr<CGImageRef> image = createImageForTimeInRect(currentTime(), rect);
1631     if (image) {
1632         GraphicsContextStateSaver stateSaver(context);
1633         context.translate(rect.x(), rect.y() + rect.height());
1634         context.scale(FloatSize(1.0f, -1.0f));
1635         context.setImageInterpolationQuality(InterpolationLow);
1636         IntRect paintRect(IntPoint(0, 0), IntSize(rect.width(), rect.height()));
1637         CGContextDrawImage(context.platformContext(), CGRectMake(0, 0, paintRect.width(), paintRect.height()), image.get());
1638     }
1639 }
1640
1641 RetainPtr<CGImageRef> MediaPlayerPrivateAVFoundationObjC::createImageForTimeInRect(float time, const FloatRect& rect)
1642 {
1643     if (!m_imageGenerator)
1644         createImageGenerator();
1645     ASSERT(m_imageGenerator);
1646
1647 #if !RELEASE_LOG_DISABLED
1648     MonotonicTime start = MonotonicTime::now();
1649 #endif
1650
1651     [m_imageGenerator.get() setMaximumSize:CGSize(rect.size())];
1652     RetainPtr<CGImageRef> rawImage = adoptCF([m_imageGenerator.get() copyCGImageAtTime:CMTimeMakeWithSeconds(time, 600) actualTime:nil error:nil]);
1653     RetainPtr<CGImageRef> image = adoptCF(CGImageCreateCopyWithColorSpace(rawImage.get(), sRGBColorSpaceRef()));
1654
1655 #if !RELEASE_LOG_DISABLED
1656     DEBUG_LOG(LOGIDENTIFIER, "creating image took ", (MonotonicTime::now() - start).seconds());
1657 #endif
1658
1659     return image;
1660 }
1661
1662 void MediaPlayerPrivateAVFoundationObjC::getSupportedTypes(HashSet<String, ASCIICaseInsensitiveHash>& supportedTypes)
1663 {
1664     supportedTypes = AVFoundationMIMETypeCache::singleton().types();
1665
1666
1667 #if ENABLE(LEGACY_ENCRYPTED_MEDIA)
1668 static bool keySystemIsSupported(const String& keySystem)
1669 {
1670     if (equalIgnoringASCIICase(keySystem, "com.apple.fps") || equalIgnoringASCIICase(keySystem, "com.apple.fps.1_0") || equalIgnoringASCIICase(keySystem, "org.w3c.clearkey"))
1671         return true;
1672     return false;
1673 }
1674 #endif
1675
1676 MediaPlayer::SupportsType MediaPlayerPrivateAVFoundationObjC::supportsType(const MediaEngineSupportParameters& parameters)
1677 {
1678 #if ENABLE(MEDIA_SOURCE)
1679     if (parameters.isMediaSource)
1680         return MediaPlayer::IsNotSupported;
1681 #endif
1682 #if ENABLE(MEDIA_STREAM)
1683     if (parameters.isMediaStream)
1684         return MediaPlayer::IsNotSupported;
1685 #endif
1686
1687     auto containerType = parameters.type.containerType();
1688     if (isUnsupportedMIMEType(containerType))
1689         return MediaPlayer::IsNotSupported;
1690
1691     if (!staticMIMETypeList().contains(containerType) && !AVFoundationMIMETypeCache::singleton().canDecodeType(containerType))
1692         return MediaPlayer::IsNotSupported;
1693
1694     // The spec says:
1695     // "Implementors are encouraged to return "maybe" unless the type can be confidently established as being supported or not."
1696     if (parameters.type.codecs().isEmpty())
1697         return MediaPlayer::MayBeSupported;
1698
1699     if (!contentTypeMeetsHardwareDecodeRequirements(parameters.type, parameters.contentTypesRequiringHardwareSupport))
1700         return MediaPlayer::IsNotSupported;
1701
1702     NSString *typeString = [NSString stringWithFormat:@"%@; codecs=\"%@\"", (NSString *)containerType, (NSString *)parameters.type.parameter(ContentType::codecsParameter())];
1703     return [AVURLAsset isPlayableExtendedMIMEType:typeString] ? MediaPlayer::IsSupported : MediaPlayer::MayBeSupported;
1704 }
1705
1706 bool MediaPlayerPrivateAVFoundationObjC::supportsKeySystem(const String& keySystem, const String& mimeType)
1707 {
1708 #if ENABLE(LEGACY_ENCRYPTED_MEDIA)
1709     if (!keySystem.isEmpty()) {
1710         // "Clear Key" is only supported with HLS:
1711         if (equalIgnoringASCIICase(keySystem, "org.w3c.clearkey") && !mimeType.isEmpty() && !equalIgnoringASCIICase(mimeType, "application/x-mpegurl"))
1712             return MediaPlayer::IsNotSupported;
1713
1714         if (!keySystemIsSupported(keySystem))
1715             return false;
1716
1717         if (!mimeType.isEmpty() && isUnsupportedMIMEType(mimeType))
1718             return false;
1719
1720         if (!mimeType.isEmpty() && !staticMIMETypeList().contains(mimeType) && !AVFoundationMIMETypeCache::singleton().canDecodeType(mimeType))
1721             return false;
1722
1723         return true;
1724     }
1725 #else
1726     UNUSED_PARAM(keySystem);
1727     UNUSED_PARAM(mimeType);
1728 #endif
1729     return false;
1730 }
1731
1732 #if HAVE(AVFOUNDATION_LOADER_DELEGATE)
1733 #if ENABLE(LEGACY_ENCRYPTED_MEDIA)
1734 static void fulfillRequestWithKeyData(AVAssetResourceLoadingRequest *request, ArrayBuffer* keyData)
1735 {
1736     if (AVAssetResourceLoadingContentInformationRequest *infoRequest = [request contentInformationRequest]) {
1737         [infoRequest setContentLength:keyData->byteLength()];
1738         [infoRequest setByteRangeAccessSupported:YES];
1739     }
1740
1741     if (AVAssetResourceLoadingDataRequest *dataRequest = [request dataRequest]) {
1742         long long start = [dataRequest currentOffset];
1743         long long end = std::min<long long>(keyData->byteLength(), [dataRequest currentOffset] + [dataRequest requestedLength]);
1744
1745         if (start < 0 || end < 0 || start >= static_cast<long long>(keyData->byteLength())) {
1746             [request finishLoadingWithError:nil];
1747             return;
1748         }
1749
1750         ASSERT(start <= std::numeric_limits<int>::max());
1751         ASSERT(end <= std::numeric_limits<int>::max());
1752         RefPtr<ArrayBuffer> requestedKeyData = keyData->slice(static_cast<int>(start), static_cast<int>(end));
1753         RetainPtr<NSData> nsData = adoptNS([[NSData alloc] initWithBytes:requestedKeyData->data() length:requestedKeyData->byteLength()]);
1754         [dataRequest respondWithData:nsData.get()];
1755     }
1756
1757     [request finishLoading];
1758 }
1759 #endif
1760
1761 bool MediaPlayerPrivateAVFoundationObjC::shouldWaitForLoadingOfResource(AVAssetResourceLoadingRequest* avRequest)
1762 {
1763     String scheme = [[[avRequest request] URL] scheme];
1764     String keyURI = [[[avRequest request] URL] absoluteString];
1765
1766 #if ENABLE(LEGACY_ENCRYPTED_MEDIA) || ENABLE(ENCRYPTED_MEDIA)
1767     if (scheme == "skd") {
1768 #if ENABLE(LEGACY_ENCRYPTED_MEDIA)
1769         // Create an initData with the following layout:
1770         // [4 bytes: keyURI size], [keyURI size bytes: keyURI]
1771         unsigned keyURISize = keyURI.length() * sizeof(UChar);
1772         auto initDataBuffer = ArrayBuffer::create(4 + keyURISize, 1);
1773         unsigned byteLength = initDataBuffer->byteLength();
1774         auto initDataView = JSC::DataView::create(initDataBuffer.copyRef(), 0, byteLength);
1775         initDataView->set<uint32_t>(0, keyURISize, true);
1776
1777         auto keyURIArray = Uint16Array::create(initDataBuffer.copyRef(), 4, keyURI.length());
1778         keyURIArray->setRange(StringView(keyURI).upconvertedCharacters(), keyURI.length() / sizeof(unsigned char), 0);
1779
1780         auto initData = Uint8Array::create(WTFMove(initDataBuffer), 0, byteLength);
1781         if (!player()->keyNeeded(initData.ptr()))
1782             return false;
1783 #endif
1784         m_keyURIToRequestMap.set(keyURI, avRequest);
1785 #if ENABLE(ENCRYPTED_MEDIA) && HAVE(AVCONTENTKEYSESSION)
1786         if (m_cdmInstance)
1787             return false;
1788
1789         RetainPtr<NSData> keyURIData = [keyURI dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
1790         m_keyID = SharedBuffer::create(keyURIData.get());
1791         player()->initializationDataEncountered("skd"_s, m_keyID->tryCreateArrayBuffer());
1792         setWaitingForKey(true);
1793 #endif
1794         return true;
1795     }
1796
1797 #if ENABLE(LEGACY_ENCRYPTED_MEDIA)
1798     if (scheme == "clearkey") {
1799         String keyID = [[[avRequest request] URL] resourceSpecifier];
1800         auto encodedKeyId = UTF8Encoding().encode(keyID, UnencodableHandling::URLEncodedEntities);
1801
1802         auto initData = Uint8Array::create(encodedKeyId.size());
1803         initData->setRange(encodedKeyId.data(), encodedKeyId.size(), 0);
1804
1805         auto keyData = player()->cachedKeyForKeyId(keyID);
1806         if (keyData) {
1807             fulfillRequestWithKeyData(avRequest, keyData.get());
1808             return false;
1809         }
1810
1811         if (!player()->keyNeeded(initData.ptr()))
1812             return false;
1813
1814         m_keyURIToRequestMap.set(keyID, avRequest);
1815         return true;
1816     }
1817 #endif
1818 #endif
1819
1820     RefPtr<WebCoreAVFResourceLoader> resourceLoader = WebCoreAVFResourceLoader::create(this, avRequest);
1821     m_resourceLoaderMap.add((__bridge CFTypeRef)avRequest, resourceLoader);
1822     resourceLoader->startLoading();
1823     return true;
1824 }
1825
1826 void MediaPlayerPrivateAVFoundationObjC::didCancelLoadingRequest(AVAssetResourceLoadingRequest* avRequest)
1827 {
1828     String scheme = [[[avRequest request] URL] scheme];
1829
1830     WebCoreAVFResourceLoader* resourceLoader = m_resourceLoaderMap.get((__bridge CFTypeRef)avRequest);
1831
1832     if (resourceLoader)
1833         resourceLoader->stopLoading();
1834 }
1835
1836 void MediaPlayerPrivateAVFoundationObjC::didStopLoadingRequest(AVAssetResourceLoadingRequest *avRequest)
1837 {
1838     m_resourceLoaderMap.remove((__bridge CFTypeRef)avRequest);
1839 }
1840 #endif
1841
1842 bool MediaPlayerPrivateAVFoundationObjC::isAvailable()
1843 {
1844     return AVFoundationLibrary() && isCoreMediaFrameworkAvailable();
1845 }
1846
1847 MediaTime MediaPlayerPrivateAVFoundationObjC::mediaTimeForTimeValue(const MediaTime& timeValue) const
1848 {
1849     if (!metaDataAvailable())
1850         return timeValue;
1851
1852     // FIXME - impossible to implement until rdar://8721510 is fixed.
1853     return timeValue;
1854 }
1855
1856 double MediaPlayerPrivateAVFoundationObjC::maximumDurationToCacheMediaTime() const
1857 {
1858     return 0;
1859 }
1860
1861 void MediaPlayerPrivateAVFoundationObjC::updateVideoLayerGravity()
1862 {
1863     if (!m_videoLayer)
1864         return;
1865
1866     // Do not attempt to change the video gravity while in full screen mode.
1867     // See setVideoFullscreenGravity().
1868     if (m_videoFullscreenLayerManager->videoFullscreenLayer())
1869         return;
1870
1871     [CATransaction begin];
1872     [CATransaction setDisableActions:YES];    
1873     NSString* gravity = shouldMaintainAspectRatio() ? AVLayerVideoGravityResizeAspect : AVLayerVideoGravityResize;
1874     [m_videoLayer.get() setVideoGravity:gravity];
1875     [CATransaction commit];
1876 }
1877
1878 static AVAssetTrack* firstEnabledTrack(NSArray* tracks)
1879 {
1880     NSUInteger index = [tracks indexOfObjectPassingTest:^(id obj, NSUInteger, BOOL *) {
1881         return [static_cast<AVAssetTrack*>(obj) isEnabled];
1882     }];
1883     if (index == NSNotFound)
1884         return nil;
1885     return [tracks objectAtIndex:index];
1886 }
1887
1888 void MediaPlayerPrivateAVFoundationObjC::tracksChanged()
1889 {
1890     String primaryAudioTrackLanguage = m_languageOfPrimaryAudioTrack;
1891     m_languageOfPrimaryAudioTrack = String();
1892
1893     if (!m_avAsset)
1894         return;
1895
1896     setDelayCharacteristicsChangedNotification(true);
1897
1898     bool haveCCTrack = false;
1899     bool hasCaptions = false;
1900
1901     // This is called whenever the tracks collection changes so cache hasVideo and hasAudio since we are
1902     // asked about those fairly fequently.
1903     if (!m_avPlayerItem) {
1904         // We don't have a player item yet, so check with the asset because some assets support inspection
1905         // prior to becoming ready to play.
1906         AVAssetTrack* firstEnabledVideoTrack = firstEnabledTrack([m_avAsset.get() tracksWithMediaCharacteristic:AVMediaCharacteristicVisual]);
1907         setHasVideo(firstEnabledVideoTrack);
1908         setHasAudio(firstEnabledTrack([m_avAsset.get() tracksWithMediaCharacteristic:AVMediaCharacteristicAudible]));
1909 #if !HAVE(AVFOUNDATION_MEDIA_SELECTION_GROUP)
1910         hasCaptions = [[m_avAsset.get() tracksWithMediaType:AVMediaTypeClosedCaption] count];
1911 #endif
1912         auto size = firstEnabledVideoTrack ? FloatSize(CGSizeApplyAffineTransform([firstEnabledVideoTrack naturalSize], [firstEnabledVideoTrack preferredTransform])) : FloatSize();
1913         // For videos with rotation tag set, the transformation above might return a CGSize instance with negative width or height.
1914         // See https://bugs.webkit.org/show_bug.cgi?id=172648.
1915         if (size.width() < 0)
1916             size.setWidth(-size.width());
1917         if (size.height() < 0)
1918             size.setHeight(-size.height());
1919         presentationSizeDidChange(size);
1920     } else {
1921         bool hasVideo = false;
1922         bool hasAudio = false;
1923         bool hasMetaData = false;
1924         for (AVPlayerItemTrack *track in m_cachedTracks.get()) {
1925             if ([track isEnabled]) {
1926                 AVAssetTrack *assetTrack = [track assetTrack];
1927                 NSString *mediaType = [assetTrack mediaType];
1928                 if ([mediaType isEqualToString:AVMediaTypeVideo])
1929                     hasVideo = true;
1930                 else if ([mediaType isEqualToString:AVMediaTypeAudio])
1931                     hasAudio = true;
1932                 else if ([mediaType isEqualToString:AVMediaTypeClosedCaption]) {
1933 #if !HAVE(AVFOUNDATION_MEDIA_SELECTION_GROUP)
1934                     hasCaptions = true;
1935 #endif
1936                     haveCCTrack = true;
1937                 } else if ([mediaType isEqualToString:AVMediaTypeMetadata]) {
1938                     hasMetaData = true;
1939                 }
1940             }
1941         }
1942
1943 #if ENABLE(VIDEO_TRACK)
1944         updateAudioTracks();
1945         updateVideoTracks();
1946
1947 #if HAVE(AVFOUNDATION_MEDIA_SELECTION_GROUP)
1948         hasAudio |= (m_audibleGroup && m_audibleGroup->selectedOption());
1949         hasVideo |= (m_visualGroup && m_visualGroup->selectedOption());
1950 #endif
1951 #endif
1952
1953         // Always says we have video if the AVPlayerLayer is ready for diaplay to work around
1954         // an AVFoundation bug which causes it to sometimes claim a track is disabled even
1955         // when it is not.
1956         setHasVideo(hasVideo || m_cachedIsReadyForDisplay);
1957
1958         setHasAudio(hasAudio);
1959 #if ENABLE(DATACUE_VALUE)
1960         if (hasMetaData)
1961             processMetadataTrack();
1962 #endif
1963     }
1964
1965 #if HAVE(AVFOUNDATION_MEDIA_SELECTION_GROUP)
1966     AVMediaSelectionGroupType *legibleGroup = safeMediaSelectionGroupForLegibleMedia();
1967     if (legibleGroup && m_cachedTracks) {
1968         hasCaptions = [[AVMediaSelectionGroup playableMediaSelectionOptionsFromArray:[legibleGroup options]] count];
1969         if (hasCaptions)
1970             processMediaSelectionOptions();
1971     }
1972 #endif
1973
1974 #if !HAVE(AVFOUNDATION_LEGIBLE_OUTPUT_SUPPORT) && HAVE(AVFOUNDATION_MEDIA_SELECTION_GROUP)
1975     if (!hasCaptions && haveCCTrack)
1976         processLegacyClosedCaptionsTracks();
1977 #elif !HAVE(AVFOUNDATION_LEGIBLE_OUTPUT_SUPPORT)
1978     if (haveCCTrack)
1979         processLegacyClosedCaptionsTracks();
1980 #endif
1981
1982     setHasClosedCaptions(hasCaptions);
1983
1984     INFO_LOG(LOGIDENTIFIER, "has video = ", hasVideo(), ", has audio = ", hasAudio(), ", has captions = ", hasClosedCaptions());
1985
1986     sizeChanged();
1987
1988     if (primaryAudioTrackLanguage != languageOfPrimaryAudioTrack())
1989         characteristicsChanged();
1990
1991 #if ENABLE(WEB_AUDIO) && USE(MEDIATOOLBOX)
1992     if (m_provider)
1993         m_provider->setAudioTrack(firstEnabledTrack(safeAVAssetTracksForAudibleMedia()));
1994 #endif
1995
1996     setDelayCharacteristicsChangedNotification(false);
1997 }
1998
1999 #if ENABLE(VIDEO_TRACK)
2000
2001 template <typename RefT, typename PassRefT>
2002 void determineChangedTracksFromNewTracksAndOldItems(NSArray* tracks, NSString* trackType, Vector<RefT>& oldItems, RefT (*itemFactory)(AVPlayerItemTrack*), MediaPlayer* player, void (MediaPlayer::*removedFunction)(PassRefT), void (MediaPlayer::*addedFunction)(PassRefT))
2003 {
2004     RetainPtr<NSSet> newTracks = adoptNS([[NSSet alloc] initWithArray:[tracks objectsAtIndexes:[tracks indexesOfObjectsPassingTest:^(id track, NSUInteger, BOOL*){
2005         return [[[track assetTrack] mediaType] isEqualToString:trackType];
2006     }]]]);
2007     RetainPtr<NSMutableSet> oldTracks = adoptNS([[NSMutableSet alloc] initWithCapacity:oldItems.size()]);
2008
2009     for (auto& oldItem : oldItems) {
2010         if (oldItem->playerItemTrack())
2011             [oldTracks addObject:oldItem->playerItemTrack()];
2012     }
2013
2014     // Find the added & removed AVPlayerItemTracks:
2015     RetainPtr<NSMutableSet> removedTracks = adoptNS([oldTracks mutableCopy]);
2016     [removedTracks minusSet:newTracks.get()];
2017
2018     RetainPtr<NSMutableSet> addedTracks = adoptNS([newTracks mutableCopy]);
2019     [addedTracks minusSet:oldTracks.get()];
2020
2021     typedef Vector<RefT> ItemVector;
2022     ItemVector replacementItems;
2023     ItemVector addedItems;
2024     ItemVector removedItems;
2025     for (auto& oldItem : oldItems) {
2026         if (oldItem->playerItemTrack() && [removedTracks containsObject:oldItem->playerItemTrack()])
2027             removedItems.append(oldItem);
2028         else
2029             replacementItems.append(oldItem);
2030     }
2031
2032     for (AVPlayerItemTrack* track in addedTracks.get())
2033         addedItems.append(itemFactory(track));
2034
2035     replacementItems.appendVector(addedItems);
2036     oldItems.swap(replacementItems);
2037
2038     for (auto& removedItem : removedItems)
2039         (player->*removedFunction)(*removedItem);
2040
2041     for (auto& addedItem : addedItems)
2042         (player->*addedFunction)(*addedItem);
2043 }
2044
2045 #if HAVE(AVFOUNDATION_MEDIA_SELECTION_GROUP)
2046
2047 template <typename RefT, typename PassRefT>
2048 void determineChangedTracksFromNewTracksAndOldItems(MediaSelectionGroupAVFObjC* group, Vector<RefT>& oldItems, const Vector<String>& characteristics, RefT (*itemFactory)(MediaSelectionOptionAVFObjC&), MediaPlayer* player, void (MediaPlayer::*removedFunction)(PassRefT), void (MediaPlayer::*addedFunction)(PassRefT))
2049 {
2050     group->updateOptions(characteristics);
2051
2052     ListHashSet<RefPtr<MediaSelectionOptionAVFObjC>> newSelectionOptions;
2053     for (auto& option : group->options()) {
2054         if (!option)
2055             continue;
2056         AVMediaSelectionOptionType* avOption = option->avMediaSelectionOption();
2057         if (!avOption)
2058             continue;
2059         newSelectionOptions.add(option);
2060     }
2061
2062     ListHashSet<RefPtr<MediaSelectionOptionAVFObjC>> oldSelectionOptions;
2063     for (auto& oldItem : oldItems) {
2064         if (MediaSelectionOptionAVFObjC *option = oldItem->mediaSelectionOption())
2065             oldSelectionOptions.add(option);
2066     }
2067
2068     // Find the added & removed AVMediaSelectionOptions:
2069     ListHashSet<RefPtr<MediaSelectionOptionAVFObjC>> removedSelectionOptions;
2070     for (auto& oldOption : oldSelectionOptions) {
2071         if (!newSelectionOptions.contains(oldOption))
2072             removedSelectionOptions.add(oldOption);
2073     }
2074
2075     ListHashSet<RefPtr<MediaSelectionOptionAVFObjC>> addedSelectionOptions;
2076     for (auto& newOption : newSelectionOptions) {
2077         if (!oldSelectionOptions.contains(newOption))
2078             addedSelectionOptions.add(newOption);
2079     }
2080
2081     typedef Vector<RefT> ItemVector;
2082     ItemVector replacementItems;
2083     ItemVector addedItems;
2084     ItemVector removedItems;
2085     for (auto& oldItem : oldItems) {
2086         if (!oldItem->mediaSelectionOption())
2087             removedItems.append(oldItem);
2088         else if (removedSelectionOptions.contains(oldItem->mediaSelectionOption()))
2089             removedItems.append(oldItem);
2090         else
2091             replacementItems.append(oldItem);
2092     }
2093
2094     for (auto& option : addedSelectionOptions)
2095         addedItems.append(itemFactory(*option.get()));
2096
2097     replacementItems.appendVector(addedItems);
2098     oldItems.swap(replacementItems);
2099     
2100     for (auto& removedItem : removedItems)
2101         (player->*removedFunction)(*removedItem);
2102
2103     for (auto& addedItem : addedItems)
2104         (player->*addedFunction)(*addedItem);
2105 }
2106
2107 #endif
2108
2109 void MediaPlayerPrivateAVFoundationObjC::updateAudioTracks()
2110 {
2111 #if !RELEASE_LOG_DISABLED
2112     size_t count = m_audioTracks.size();
2113 #endif
2114
2115 #if HAVE(AVFOUNDATION_MEDIA_SELECTION_GROUP)
2116     Vector<String> characteristics = player()->preferredAudioCharacteristics();
2117     if (!m_audibleGroup) {
2118         if (AVMediaSelectionGroupType *group = safeMediaSelectionGroupForAudibleMedia())
2119             m_audibleGroup = MediaSelectionGroupAVFObjC::create(m_avPlayerItem.get(), group, characteristics);
2120     }
2121
2122     if (m_audibleGroup)
2123         determineChangedTracksFromNewTracksAndOldItems(m_audibleGroup.get(), m_audioTracks, characteristics, &AudioTrackPrivateAVFObjC::create, player(), &MediaPlayer::removeAudioTrack, &MediaPlayer::addAudioTrack);
2124     else
2125 #endif
2126         determineChangedTracksFromNewTracksAndOldItems(m_cachedTracks.get(), AVMediaTypeAudio, m_audioTracks, &AudioTrackPrivateAVFObjC::create, player(), &MediaPlayer::removeAudioTrack, &MediaPlayer::addAudioTrack);
2127
2128     for (auto& track : m_audioTracks)
2129         track->resetPropertiesFromTrack();
2130
2131 #if !RELEASE_LOG_DISABLED
2132     INFO_LOG(LOGIDENTIFIER, "track count was ", count, ", is ", m_audioTracks.size());
2133 #endif
2134 }
2135
2136 void MediaPlayerPrivateAVFoundationObjC::updateVideoTracks()
2137 {
2138 #if !RELEASE_LOG_DISABLED
2139     size_t count = m_videoTracks.size();
2140 #endif
2141
2142     determineChangedTracksFromNewTracksAndOldItems(m_cachedTracks.get(), AVMediaTypeVideo, m_videoTracks, &VideoTrackPrivateAVFObjC::create, player(), &MediaPlayer::removeVideoTrack, &MediaPlayer::addVideoTrack);
2143
2144 #if HAVE(AVFOUNDATION_MEDIA_SELECTION_GROUP)
2145     if (!m_visualGroup) {
2146         if (AVMediaSelectionGroupType *group = safeMediaSelectionGroupForVisualMedia())
2147             m_visualGroup = MediaSelectionGroupAVFObjC::create(m_avPlayerItem.get(), group, Vector<String>());
2148     }
2149
2150     if (m_visualGroup)
2151         determineChangedTracksFromNewTracksAndOldItems(m_visualGroup.get(), m_videoTracks, Vector<String>(), &VideoTrackPrivateAVFObjC::create, player(), &MediaPlayer::removeVideoTrack, &MediaPlayer::addVideoTrack);
2152 #endif
2153
2154     for (auto& track : m_audioTracks)
2155         track->resetPropertiesFromTrack();
2156
2157 #if !RELEASE_LOG_DISABLED
2158     INFO_LOG(LOGIDENTIFIER, "track count was ", count, ", is ", m_videoTracks.size());
2159 #endif
2160 }
2161
2162 bool MediaPlayerPrivateAVFoundationObjC::requiresTextTrackRepresentation() const
2163 {
2164     return m_videoFullscreenLayerManager->requiresTextTrackRepresentation();
2165 }
2166
2167 void MediaPlayerPrivateAVFoundationObjC::syncTextTrackBounds()
2168 {
2169     m_videoFullscreenLayerManager->syncTextTrackBounds();
2170 }
2171
2172 void MediaPlayerPrivateAVFoundationObjC::setTextTrackRepresentation(TextTrackRepresentation* representation)
2173 {
2174     m_videoFullscreenLayerManager->setTextTrackRepresentation(representation);
2175 }
2176
2177 #endif // ENABLE(VIDEO_TRACK)
2178
2179 #if ENABLE(WEB_AUDIO) && USE(MEDIATOOLBOX)
2180
2181 AudioSourceProvider* MediaPlayerPrivateAVFoundationObjC::audioSourceProvider()
2182 {
2183     if (!m_provider) {
2184         m_provider = AudioSourceProviderAVFObjC::create(m_avPlayerItem.get());
2185         m_provider->setAudioTrack(firstEnabledTrack(safeAVAssetTracksForAudibleMedia()));
2186     }
2187     return m_provider.get();
2188 }
2189
2190 #endif
2191
2192 void MediaPlayerPrivateAVFoundationObjC::sizeChanged()
2193 {
2194     if (!m_avAsset)
2195         return;
2196
2197     setNaturalSize(m_cachedPresentationSize);
2198 }
2199
2200 void MediaPlayerPrivateAVFoundationObjC::resolvedURLChanged()
2201 {
2202     setResolvedURL(m_avAsset ? URL([m_avAsset resolvedURL]) : URL());
2203 }
2204
2205 bool MediaPlayerPrivateAVFoundationObjC::didPassCORSAccessCheck() const
2206 {
2207     AVAssetResourceLoader *resourceLoader = m_avAsset.get().resourceLoader;
2208     if (!DeprecatedGlobalSettings::isAVFoundationNSURLSessionEnabled()
2209         || ![resourceLoader respondsToSelector:@selector(URLSession)])
2210         return false;
2211
2212     WebCoreNSURLSession *session = (WebCoreNSURLSession *)resourceLoader.URLSession;
2213     if ([session isKindOfClass:[WebCoreNSURLSession class]])
2214         return session.didPassCORSAccessChecks;
2215
2216     return false;
2217 }
2218
2219 Optional<bool> MediaPlayerPrivateAVFoundationObjC::wouldTaintOrigin(const SecurityOrigin& origin) const
2220 {
2221     AVAssetResourceLoader *resourceLoader = m_avAsset.get().resourceLoader;
2222     if (!DeprecatedGlobalSettings::isAVFoundationNSURLSessionEnabled()
2223         || ![resourceLoader respondsToSelector:@selector(URLSession)])
2224         return false;
2225
2226     WebCoreNSURLSession *session = (WebCoreNSURLSession *)resourceLoader.URLSession;
2227     if ([session isKindOfClass:[WebCoreNSURLSession class]])
2228         return [session wouldTaintOrigin:origin];
2229
2230     return WTF::nullopt;
2231 }
2232
2233
2234 #if HAVE(AVFOUNDATION_VIDEO_OUTPUT)
2235
2236 void MediaPlayerPrivateAVFoundationObjC::createVideoOutput()
2237 {
2238     INFO_LOG(LOGIDENTIFIER);
2239
2240     if (!m_avPlayerItem || m_videoOutput)
2241         return;
2242
2243 #if USE(VIDEOTOOLBOX)
2244     NSDictionary* attributes = nil;
2245 #else
2246     NSDictionary* attributes = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithUnsignedInt:kCVPixelFormatType_32BGRA], kCVPixelBufferPixelFormatTypeKey, nil];
2247 #endif
2248     m_videoOutput = adoptNS([[AVPlayerItemVideoOutput alloc] initWithPixelBufferAttributes:attributes]);
2249     ASSERT(m_videoOutput);
2250
2251     [m_videoOutput setDelegate:m_videoOutputDelegate.get() queue:globalPullDelegateQueue()];
2252
2253     [m_avPlayerItem.get() addOutput:m_videoOutput.get()];
2254 }
2255
2256 void MediaPlayerPrivateAVFoundationObjC::destroyVideoOutput()
2257 {
2258     if (!m_videoOutput)
2259         return;
2260
2261     if (m_avPlayerItem)
2262         [m_avPlayerItem.get() removeOutput:m_videoOutput.get()];
2263
2264     INFO_LOG(LOGIDENTIFIER);
2265
2266     m_videoOutput = 0;
2267 }
2268
2269 bool MediaPlayerPrivateAVFoundationObjC::updateLastPixelBuffer()
2270 {
2271     if (!m_avPlayerItem)
2272         return false;
2273
2274     if (!m_videoOutput)
2275         createVideoOutput();
2276     ASSERT(m_videoOutput);
2277
2278     CMTime currentTime = [m_avPlayerItem.get() currentTime];
2279
2280     if (![m_videoOutput.get() hasNewPixelBufferForItemTime:currentTime])
2281         return false;
2282
2283     m_lastPixelBuffer = adoptCF([m_videoOutput.get() copyPixelBufferForItemTime:currentTime itemTimeForDisplay:nil]);
2284     m_lastImage = nullptr;
2285     return true;
2286 }
2287
2288 bool MediaPlayerPrivateAVFoundationObjC::videoOutputHasAvailableFrame()
2289 {
2290     if (!m_avPlayerItem)
2291         return false;
2292
2293     if (m_lastImage)
2294         return true;
2295
2296     if (!m_videoOutput)
2297         createVideoOutput();
2298
2299     return [m_videoOutput hasNewPixelBufferForItemTime:[m_avPlayerItem currentTime]];
2300 }
2301
2302 void MediaPlayerPrivateAVFoundationObjC::updateLastImage(UpdateType type)
2303 {
2304 #if HAVE(CORE_VIDEO)
2305     if (!m_avPlayerItem)
2306         return;
2307
2308     if (type == UpdateType::UpdateSynchronously && !m_lastImage && !videoOutputHasAvailableFrame())
2309         waitForVideoOutputMediaDataWillChange();
2310
2311     // Calls to copyPixelBufferForItemTime:itemTimeForDisplay: may return nil if the pixel buffer
2312     // for the requested time has already been retrieved. In this case, the last valid image (if any)
2313     // should be displayed.
2314     if (!updateLastPixelBuffer() && (m_lastImage || !m_lastPixelBuffer))
2315         return;
2316
2317     if (!m_pixelBufferConformer) {
2318 #if USE(VIDEOTOOLBOX)
2319         NSDictionary *attributes = @{ (__bridge NSString *)kCVPixelBufferPixelFormatTypeKey: @(kCVPixelFormatType_32BGRA) };
2320 #else
2321         NSDictionary *attributes = nil;
2322 #endif
2323         m_pixelBufferConformer = std::make_unique<PixelBufferConformerCV>((__bridge CFDictionaryRef)attributes);
2324     }
2325
2326 #if !RELEASE_LOG_DISABLED
2327     MonotonicTime start = MonotonicTime::now();
2328 #endif
2329
2330     m_lastImage = m_pixelBufferConformer->createImageFromPixelBuffer(m_lastPixelBuffer.get());
2331
2332 #if !RELEASE_LOG_DISABLED
2333     DEBUG_LOG(LOGIDENTIFIER, "creating buffer took ", (MonotonicTime::now() - start).seconds());
2334 #endif
2335 #endif // HAVE(CORE_VIDEO)
2336 }
2337
2338 void MediaPlayerPrivateAVFoundationObjC::paintWithVideoOutput(GraphicsContext& context, const FloatRect& outputRect)
2339 {
2340     updateLastImage(UpdateType::UpdateSynchronously);
2341     if (!m_lastImage)
2342         return;
2343
2344     AVAssetTrack* firstEnabledVideoTrack = firstEnabledTrack([m_avAsset.get() tracksWithMediaCharacteristic:AVMediaCharacteristicVisual]);
2345     if (!firstEnabledVideoTrack)
2346         return;
2347
2348     INFO_LOG(LOGIDENTIFIER);
2349
2350     GraphicsContextStateSaver stateSaver(context);
2351     FloatRect imageRect(0, 0, CGImageGetWidth(m_lastImage.get()), CGImageGetHeight(m_lastImage.get()));
2352     AffineTransform videoTransform = [firstEnabledVideoTrack preferredTransform];
2353     FloatRect transformedOutputRect = videoTransform.inverse().valueOr(AffineTransform()).mapRect(outputRect);
2354
2355     context.concatCTM(videoTransform);
2356     context.drawNativeImage(m_lastImage.get(), imageRect.size(), transformedOutputRect, imageRect);
2357
2358     // If we have created an AVAssetImageGenerator in the past due to m_videoOutput not having an available
2359     // video frame, destroy it now that it is no longer needed.
2360     if (m_imageGenerator)
2361         destroyImageGenerator();
2362
2363 }
2364
2365 bool MediaPlayerPrivateAVFoundationObjC::copyVideoTextureToPlatformTexture(GraphicsContext3D* context, Platform3DObject outputTexture, GC3Denum outputTarget, GC3Dint level, GC3Denum internalFormat, GC3Denum format, GC3Denum type, bool premultiplyAlpha, bool flipY)
2366 {
2367     ASSERT(context);
2368
2369     updateLastPixelBuffer();
2370     if (!m_lastPixelBuffer)
2371         return false;
2372
2373     size_t width = CVPixelBufferGetWidth(m_lastPixelBuffer.get());
2374     size_t height = CVPixelBufferGetHeight(m_lastPixelBuffer.get());
2375
2376     if (!m_videoTextureCopier)
2377         m_videoTextureCopier = std::make_unique<VideoTextureCopierCV>(*context);
2378
2379     return m_videoTextureCopier->copyImageToPlatformTexture(m_lastPixelBuffer.get(), width, height, outputTexture, outputTarget, level, internalFormat, format, type, premultiplyAlpha, flipY);
2380 }
2381
2382 NativeImagePtr MediaPlayerPrivateAVFoundationObjC::nativeImageForCurrentTime()
2383 {
2384     updateLastImage();
2385     return m_lastImage;
2386 }
2387
2388 void MediaPlayerPrivateAVFoundationObjC::waitForVideoOutputMediaDataWillChange()
2389 {
2390     [m_videoOutput requestNotificationOfMediaDataChangeWithAdvanceInterval:0];
2391
2392     // Wait for 1 second.
2393     bool satisfied = m_videoOutputSemaphore.waitFor(1_s);
2394     if (!satisfied)
2395         ERROR_LOG(LOGIDENTIFIER, "timed out");
2396 }
2397
2398 void MediaPlayerPrivateAVFoundationObjC::outputMediaDataWillChange(AVPlayerItemVideoOutputType *)
2399 {
2400     m_videoOutputSemaphore.signal();
2401 }
2402
2403 #endif
2404
2405 #if ENABLE(LEGACY_ENCRYPTED_MEDIA)
2406
2407 RetainPtr<AVAssetResourceLoadingRequest> MediaPlayerPrivateAVFoundationObjC::takeRequestForKeyURI(const String& keyURI)
2408 {
2409     return m_keyURIToRequestMap.take(keyURI);
2410 }
2411
2412 void MediaPlayerPrivateAVFoundationObjC::keyAdded()
2413 {
2414     Vector<String> fulfilledKeyIds;
2415
2416     for (auto& pair : m_keyURIToRequestMap) {
2417         const String& keyId = pair.key;
2418         const RetainPtr<AVAssetResourceLoadingRequest>& request = pair.value;
2419
2420         auto keyData = player()->cachedKeyForKeyId(keyId);
2421         if (!keyData)
2422             continue;
2423
2424         fulfillRequestWithKeyData(request.get(), keyData.get());
2425         fulfilledKeyIds.append(keyId);
2426     }
2427
2428     for (auto& keyId : fulfilledKeyIds)
2429         m_keyURIToRequestMap.remove(keyId);
2430 }
2431
2432 void MediaPlayerPrivateAVFoundationObjC::removeSession(LegacyCDMSession& session)
2433 {
2434     ASSERT_UNUSED(session, &session == m_session);
2435     m_session = nullptr;
2436 }
2437
2438 std::unique_ptr<LegacyCDMSession> MediaPlayerPrivateAVFoundationObjC::createSession(const String& keySystem, LegacyCDMSessionClient* client)
2439 {
2440     if (!keySystemIsSupported(keySystem))
2441         return nullptr;
2442     auto session = std::make_unique<CDMSessionAVFoundationObjC>(this, client);
2443     m_session = makeWeakPtr(*session);
2444     return WTFMove(session);
2445 }
2446 #endif
2447
2448 #if ENABLE(ENCRYPTED_MEDIA) || ENABLE(LEGACY_ENCRYPTED_MEDIA)
2449 void MediaPlayerPrivateAVFoundationObjC::outputObscuredDueToInsufficientExternalProtectionChanged(bool newValue)
2450 {
2451 #if ENABLE(LEGACY_ENCRYPTED_MEDIA)
2452     if (m_session && newValue)
2453         m_session->playerDidReceiveError([NSError errorWithDomain:@"com.apple.WebKit" code:'HDCP' userInfo:nil]);
2454 #endif
2455
2456 #if ENABLE(ENCRYPTED_MEDIA) && HAVE(AVCONTENTKEYSESSION)
2457     if (m_cdmInstance)
2458         m_cdmInstance->outputObscuredDueToInsufficientExternalProtectionChanged(newValue);
2459 #elif !ENABLE(LEGACY_ENCRYPTED_MEDIA)
2460     UNUSED_PARAM(newValue);
2461 #endif
2462 }
2463 #endif
2464
2465 #if ENABLE(ENCRYPTED_MEDIA)
2466 void MediaPlayerPrivateAVFoundationObjC::cdmInstanceAttached(CDMInstance& instance)
2467 {
2468 #if HAVE(AVCONTENTKEYSESSION)
2469     if (!is<CDMInstanceFairPlayStreamingAVFObjC>(instance))
2470         return;
2471
2472     auto& fpsInstance = downcast<CDMInstanceFairPlayStreamingAVFObjC>(instance);
2473     if (&fpsInstance == m_cdmInstance)
2474         return;
2475
2476     if (m_cdmInstance)
2477         cdmInstanceDetached(*m_cdmInstance);
2478
2479     m_cdmInstance = &fpsInstance;
2480 #else
2481     UNUSED_PARAM(instance);
2482 #endif
2483 }
2484
2485 void MediaPlayerPrivateAVFoundationObjC::cdmInstanceDetached(CDMInstance& instance)
2486 {
2487 #if HAVE(AVCONTENTKEYSESSION)
2488     ASSERT_UNUSED(instance, m_cdmInstance && m_cdmInstance == &instance);
2489     m_cdmInstance = nullptr;
2490 #else
2491     UNUSED_PARAM(instance);
2492 #endif
2493 }
2494
2495 void MediaPlayerPrivateAVFoundationObjC::attemptToDecryptWithInstance(CDMInstance&)
2496 {
2497 #if HAVE(AVCONTENTKEYSESSION)
2498     if (!m_keyID || !m_cdmInstance)
2499         return;
2500
2501     auto instanceSession = m_cdmInstance->sessionForKeyIDs(Vector<Ref<SharedBuffer>>::from(*m_keyID));
2502     if (!instanceSession)
2503         return;
2504
2505     [instanceSession->contentKeySession() addContentKeyRecipient:m_avAsset.get()];
2506
2507     auto keyURIToRequestMap = WTFMove(m_keyURIToRequestMap);
2508     for (auto& request : keyURIToRequestMap.values()) {
2509         if (auto *infoRequest = request.get().contentInformationRequest)
2510             infoRequest.contentType = AVStreamingKeyDeliveryContentKeyType;
2511         [request finishLoading];
2512     }
2513     setWaitingForKey(false);
2514 #endif
2515 }
2516
2517 void MediaPlayerPrivateAVFoundationObjC::setWaitingForKey(bool waitingForKey)
2518 {
2519     if (m_waitingForKey == waitingForKey)
2520         return;
2521
2522     m_waitingForKey = waitingForKey;
2523     player()->waitingForKeyChanged();
2524 }
2525 #endif
2526
2527 #if !HAVE(AVFOUNDATION_LEGIBLE_OUTPUT_SUPPORT)
2528
2529 void MediaPlayerPrivateAVFoundationObjC::processLegacyClosedCaptionsTracks()
2530 {
2531 #if HAVE(AVFOUNDATION_MEDIA_SELECTION_GROUP)
2532     [m_avPlayerItem.get() selectMediaOption:nil inMediaSelectionGroup:safeMediaSelectionGroupForLegibleMedia()];
2533 #endif
2534
2535     Vector<RefPtr<InbandTextTrackPrivateAVF>> removedTextTracks = m_textTracks;
2536     for (AVPlayerItemTrack *playerItemTrack in m_cachedTracks.get()) {
2537
2538         AVAssetTrack *assetTrack = [playerItemTrack assetTrack];
2539         if (![[assetTrack mediaType] isEqualToString:AVMediaTypeClosedCaption])
2540             continue;
2541
2542         bool newCCTrack = true;
2543         for (unsigned i = removedTextTracks.size(); i > 0; --i) {
2544             if (removedTextTracks[i - 1]->textTrackCategory() != InbandTextTrackPrivateAVF::LegacyClosedCaption)
2545                 continue;
2546
2547             RefPtr<InbandTextTrackPrivateLegacyAVFObjC> track = static_cast<InbandTextTrackPrivateLegacyAVFObjC*>(m_textTracks[i - 1].get());
2548             if (track->avPlayerItemTrack() == playerItemTrack) {
2549                 removedTextTracks.remove(i - 1);
2550                 newCCTrack = false;
2551                 break;
2552             }
2553         }
2554
2555         if (!newCCTrack)
2556             continue;
2557         
2558         m_textTracks.append(InbandTextTrackPrivateLegacyAVFObjC::create(this, playerItemTrack));
2559     }
2560
2561     processNewAndRemovedTextTracks(removedTextTracks);
2562 }
2563
2564 #endif
2565
2566 NSArray* MediaPlayerPrivateAVFoundationObjC::safeAVAssetTracksForAudibleMedia()
2567 {
2568     if (!m_avAsset)
2569         return nil;
2570
2571     if ([m_avAsset.get() statusOfValueForKey:@"tracks" error:NULL] != AVKeyValueStatusLoaded)
2572         return nil;
2573
2574     return [m_avAsset tracksWithMediaCharacteristic:AVMediaCharacteristicAudible];
2575 }
2576
2577 #if HAVE(AVFOUNDATION_MEDIA_SELECTION_GROUP)
2578
2579 bool MediaPlayerPrivateAVFoundationObjC::hasLoadedMediaSelectionGroups()
2580 {
2581     if (!m_avAsset)
2582         return false;
2583
2584     if ([m_avAsset.get() statusOfValueForKey:@"availableMediaCharacteristicsWithMediaSelectionOptions" error:NULL] != AVKeyValueStatusLoaded)
2585         return false;
2586
2587     return true;
2588 }
2589
2590 AVMediaSelectionGroupType* MediaPlayerPrivateAVFoundationObjC::safeMediaSelectionGroupForLegibleMedia()
2591 {
2592     if (!hasLoadedMediaSelectionGroups())
2593         return nil;
2594
2595     return [m_avAsset.get() mediaSelectionGroupForMediaCharacteristic:AVMediaCharacteristicLegible];
2596 }
2597
2598 AVMediaSelectionGroupType* MediaPlayerPrivateAVFoundationObjC::safeMediaSelectionGroupForAudibleMedia()
2599 {
2600     if (!hasLoadedMediaSelectionGroups())
2601         return nil;
2602
2603     return [m_avAsset.get() mediaSelectionGroupForMediaCharacteristic:AVMediaCharacteristicAudible];
2604 }
2605
2606 AVMediaSelectionGroupType* MediaPlayerPrivateAVFoundationObjC::safeMediaSelectionGroupForVisualMedia()
2607 {
2608     if (!hasLoadedMediaSelectionGroups())
2609         return nil;
2610
2611     return [m_avAsset.get() mediaSelectionGroupForMediaCharacteristic:AVMediaCharacteristicVisual];
2612 }
2613
2614 void MediaPlayerPrivateAVFoundationObjC::processMediaSelectionOptions()
2615 {
2616     AVMediaSelectionGroupType *legibleGroup = safeMediaSelectionGroupForLegibleMedia();
2617     if (!legibleGroup) {
2618         INFO_LOG(LOGIDENTIFIER, "no mediaSelectionGroup");
2619         return;
2620     }
2621
2622     // We enabled automatic media selection because we want alternate audio tracks to be enabled/disabled automatically,
2623     // but set the selected legible track to nil so text tracks will not be automatically configured.
2624     if (!m_textTracks.size())
2625         [m_avPlayerItem.get() selectMediaOption:nil inMediaSelectionGroup:safeMediaSelectionGroupForLegibleMedia()];
2626
2627     Vector<RefPtr<InbandTextTrackPrivateAVF>> removedTextTracks = m_textTracks;
2628     NSArray *legibleOptions = [AVMediaSelectionGroup playableMediaSelectionOptionsFromArray:[legibleGroup options]];
2629     for (AVMediaSelectionOptionType *option in legibleOptions) {
2630         bool newTrack = true;
2631         for (unsigned i = removedTextTracks.size(); i > 0; --i) {
2632             if (removedTextTracks[i - 1]->textTrackCategory() == InbandTextTrackPrivateAVF::LegacyClosedCaption)
2633                 continue;
2634             
2635             RetainPtr<AVMediaSelectionOptionType> currentOption;
2636 #if ENABLE(AVF_CAPTIONS)
2637             if (removedTextTracks[i - 1]->textTrackCategory() == InbandTextTrackPrivateAVF::OutOfBand) {
2638                 RefPtr<OutOfBandTextTrackPrivateAVF> track = static_cast<OutOfBandTextTrackPrivateAVF*>(removedTextTracks[i - 1].get());
2639                 currentOption = track->mediaSelectionOption();
2640             } else
2641 #endif
2642             {
2643                 RefPtr<InbandTextTrackPrivateAVFObjC> track = static_cast<InbandTextTrackPrivateAVFObjC*>(removedTextTracks[i - 1].get());
2644                 currentOption = track->mediaSelectionOption();
2645             }
2646             
2647             if ([currentOption.get() isEqual:option]) {
2648                 removedTextTracks.remove(i - 1);
2649                 newTrack = false;
2650                 break;
2651             }
2652         }
2653         if (!newTrack)
2654             continue;
2655
2656 #if ENABLE(AVF_CAPTIONS)
2657         if ([option outOfBandSource]) {
2658             m_textTracks.append(OutOfBandTextTrackPrivateAVF::create(this, option));
2659             m_textTracks.last()->setHasBeenReported(true); // Ignore out-of-band tracks that we passed to AVFoundation so we do not double-count them
2660             continue;
2661         }
2662 #endif
2663
2664         m_textTracks.append(InbandTextTrackPrivateAVFObjC::create(this, option, InbandTextTrackPrivate::Generic));
2665     }
2666
2667     processNewAndRemovedTextTracks(removedTextTracks);
2668 }
2669
2670 void MediaPlayerPrivateAVFoundationObjC::processMetadataTrack()
2671 {
2672     if (m_metadataTrack)
2673         return;
2674
2675     m_metadataTrack = InbandMetadataTextTrackPrivateAVF::create(InbandTextTrackPrivate::Metadata, InbandTextTrackPrivate::Data);
2676     m_metadataTrack->setInBandMetadataTrackDispatchType("com.apple.streaming");
2677     player()->addTextTrack(*m_metadataTrack);
2678 }
2679
2680 void MediaPlayerPrivateAVFoundationObjC::processCue(NSArray *attributedStrings, NSArray *nativeSamples, const MediaTime& time)
2681 {
2682     ASSERT(time >= MediaTime::zeroTime());
2683
2684     if (!m_currentTextTrack)
2685         return;
2686
2687     m_currentTextTrack->processCue((__bridge CFArrayRef)attributedStrings, (__bridge CFArrayRef)nativeSamples, time);
2688 }
2689
2690 void MediaPlayerPrivateAVFoundationObjC::flushCues()
2691 {
2692     INFO_LOG(LOGIDENTIFIER);
2693
2694     if (!m_currentTextTrack)
2695         return;
2696     
2697     m_currentTextTrack->resetCueValues();
2698 }
2699
2700 #endif // HAVE(AVFOUNDATION_MEDIA_SELECTION_GROUP)
2701
2702 void MediaPlayerPrivateAVFoundationObjC::setCurrentTextTrack(InbandTextTrackPrivateAVF *track)
2703 {
2704     if (m_currentTextTrack == track)
2705         return;
2706
2707     INFO_LOG(LOGIDENTIFIER, "selecting track with language ", track ? track->language() : "");
2708
2709     m_currentTextTrack = track;
2710
2711     if (track) {
2712         if (track->textTrackCategory() == InbandTextTrackPrivateAVF::LegacyClosedCaption)
2713             ALLOW_DEPRECATED_DECLARATIONS_BEGIN
2714             [m_avPlayer.get() setClosedCaptionDisplayEnabled:YES];
2715             ALLOW_DEPRECATED_DECLARATIONS_END
2716 #if HAVE(AVFOUNDATION_MEDIA_SELECTION_GROUP)
2717 #if ENABLE(AVF_CAPTIONS)
2718         else if (track->textTrackCategory() == InbandTextTrackPrivateAVF::OutOfBand)
2719             [m_avPlayerItem.get() selectMediaOption:static_cast<OutOfBandTextTrackPrivateAVF*>(track)->mediaSelectionOption() inMediaSelectionGroup:safeMediaSelectionGroupForLegibleMedia()];
2720 #endif
2721         else
2722             [m_avPlayerItem.get() selectMediaOption:static_cast<InbandTextTrackPrivateAVFObjC*>(track)->mediaSelectionOption() inMediaSelectionGroup:safeMediaSelectionGroupForLegibleMedia()];
2723 #endif
2724     } else {
2725 #if HAVE(AVFOUNDATION_MEDIA_SELECTION_GROUP)
2726         [m_avPlayerItem.get() selectMediaOption:0 inMediaSelectionGroup:safeMediaSelectionGroupForLegibleMedia()];
2727 #endif
2728         ALLOW_DEPRECATED_DECLARATIONS_BEGIN
2729         [m_avPlayer.get() setClosedCaptionDisplayEnabled:NO];
2730         ALLOW_DEPRECATED_DECLARATIONS_END
2731     }
2732
2733 }
2734
2735 String MediaPlayerPrivateAVFoundationObjC::languageOfPrimaryAudioTrack() const
2736 {
2737     if (!m_languageOfPrimaryAudioTrack.isNull())
2738         return m_languageOfPrimaryAudioTrack;
2739
2740     if (!m_avPlayerItem.get())
2741         return emptyString();
2742
2743 #if HAVE(AVFOUNDATION_MEDIA_SELECTION_GROUP)
2744     // If AVFoundation has an audible group, return the language of the currently selected audible option.
2745     AVMediaSelectionGroupType *audibleGroup = [m_avAsset.get() mediaSelectionGroupForMediaCharacteristic:AVMediaCharacteristicAudible];
2746     ALLOW_DEPRECATED_DECLARATIONS_BEGIN
2747     AVMediaSelectionOptionType *currentlySelectedAudibleOption = [m_avPlayerItem.get() selectedMediaOptionInMediaSelectionGroup:audibleGroup];
2748     ALLOW_DEPRECATED_DECLARATIONS_END
2749     if (currentlySelectedAudibleOption) {
2750         m_languageOfPrimaryAudioTrack = [[currentlySelectedAudibleOption locale] localeIdentifier];
2751         INFO_LOG(LOGIDENTIFIER, "language of selected audible option ", m_languageOfPrimaryAudioTrack);
2752
2753         return m_languageOfPrimaryAudioTrack;
2754     }
2755 #endif // HAVE(AVFOUNDATION_MEDIA_SELECTION_GROUP)
2756
2757     // AVFoundation synthesizes an audible group when there is only one ungrouped audio track if there is also a legible group (one or
2758     // more in-band text tracks). It doesn't know about out-of-band tracks, so if there is a single audio track return its language.
2759     NSArray *tracks = [m_avAsset.get() tracksWithMediaType:AVMediaTypeAudio];
2760     if (!tracks || [tracks count] != 1) {
2761         m_languageOfPrimaryAudioTrack = emptyString();
2762         INFO_LOG(LOGIDENTIFIER, tracks ? [tracks count] : 0, " audio tracks, returning empty");
2763         return m_languageOfPrimaryAudioTrack;
2764     }
2765
2766     AVAssetTrack *track = [tracks objectAtIndex:0];
2767     m_languageOfPrimaryAudioTrack = AVTrackPrivateAVFObjCImpl::languageForAVAssetTrack(track);
2768
2769     INFO_LOG(LOGIDENTIFIER, "single audio track has language \"", m_languageOfPrimaryAudioTrack, "\"");
2770
2771     return m_languageOfPrimaryAudioTrack;
2772 }
2773
2774 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
2775 bool MediaPlayerPrivateAVFoundationObjC::isCurrentPlaybackTargetWireless() const
2776 {
2777     bool wirelessTarget = false;
2778
2779 #if !PLATFORM(IOS_FAMILY)
2780     if (m_playbackTarget) {
2781         if (m_playbackTarget->targetType() == MediaPlaybackTarget::AVFoundation)
2782             wirelessTarget = m_avPlayer && m_avPlayer.get().externalPlaybackActive;
2783         else
2784             wirelessTarget = m_shouldPlayToPlaybackTarget && m_playbackTarget->hasActiveRoute();
2785     }
2786 #else
2787     wirelessTarget = m_avPlayer && m_avPlayer.get().externalPlaybackActive;
2788 #endif
2789
2790     INFO_LOG(LOGIDENTIFIER, "- ", wirelessTarget);
2791
2792     return wirelessTarget;
2793 }
2794
2795 MediaPlayer::WirelessPlaybackTargetType MediaPlayerPrivateAVFoundationObjC::wirelessPlaybackTargetType() const
2796 {
2797     if (!m_avPlayer)
2798         return MediaPlayer::TargetTypeNone;
2799
2800 #if PLATFORM(IOS_FAMILY)
2801     if (!AVFoundationLibrary())
2802         return MediaPlayer::TargetTypeNone;
2803
2804     switch ([m_avPlayer externalPlaybackType]) {
2805     case AVPlayerExternalPlaybackTypeNone:
2806         return MediaPlayer::TargetTypeNone;
2807     case AVPlayerExternalPlaybackTypeAirPlay:
2808         return MediaPlayer::TargetTypeAirPlay;
2809     case AVPlayerExternalPlaybackTypeTVOut:
2810         return MediaPlayer::TargetTypeTVOut;
2811     }
2812
2813     ASSERT_NOT_REACHED();
2814     return MediaPlayer::TargetTypeNone;
2815
2816 #else
2817     return MediaPlayer::TargetTypeAirPlay;
2818 #endif
2819 }
2820     
2821 #if PLATFORM(IOS_FAMILY)
2822 static NSString *exernalDeviceDisplayNameForPlayer(AVPlayerType *player)
2823 {
2824 #if HAVE(CELESTIAL)
2825     if (!AVFoundationLibrary())
2826         return nil;
2827
2828     if ([getAVOutputContextClass() respondsToSelector:@selector(sharedAudioPresentationOutputContext)]) {
2829         AVOutputContext *outputContext = [getAVOutputContextClass() sharedAudioPresentationOutputContext];
2830
2831         if (![outputContext respondsToSelector:@selector(supportsMultipleOutputDevices)]
2832             || ![outputContext supportsMultipleOutputDevices]
2833             || ![outputContext respondsToSelector:@selector(outputDevices)])
2834             return [outputContext deviceName];
2835
2836         auto outputDeviceNames = adoptNS([[NSMutableArray alloc] init]);
2837         for (AVOutputDevice *outputDevice in [outputContext outputDevices]) {
2838 ALLOW_DEPRECATED_DECLARATIONS_BEGIN
2839             auto outputDeviceName = adoptNS([[outputDevice name] copy]);
2840 ALLOW_DEPRECATED_DECLARATIONS_END
2841             [outputDeviceNames addObject:outputDeviceName.get()];
2842         }
2843
2844         return [outputDeviceNames componentsJoinedByString:@" + "];
2845     }
2846
2847     if (player.externalPlaybackType != AVPlayerExternalPlaybackTypeAirPlay)
2848         return nil;
2849
2850     NSArray *pickableRoutes = CFBridgingRelease(MRMediaRemoteCopyPickableRoutes());
2851     if (!pickableRoutes.count)
2852         return nil;
2853
2854     NSString *displayName = nil;
2855     for (NSDictionary *pickableRoute in pickableRoutes) {
2856         if (![pickableRoute[AVController_RouteDescriptionKey_RouteCurrentlyPicked] boolValue])
2857             continue;
2858
2859         displayName = pickableRoute[AVController_RouteDescriptionKey_RouteName];
2860
2861         NSString *routeName = pickableRoute[AVController_RouteDescriptionKey_AVAudioRouteName];
2862         if (![routeName isEqualToString:@"Speaker"] && ![routeName isEqualToString:@"HDMIOutput"])
2863             break;
2864
2865         // The route is a speaker or HDMI out, override the name to be the localized device model.
2866         NSString *localizedDeviceModel = [[UIDevice currentDevice] localizedModel];
2867
2868         // In cases where a route with that name already exists, prefix the name with the model.
2869         BOOL includeLocalizedDeviceModelName = NO;
2870         for (NSDictionary *otherRoute in pickableRoutes) {
2871             if (otherRoute == pickableRoute)
2872                 continue;
2873
2874             if ([otherRoute[AVController_RouteDescriptionKey_RouteName] rangeOfString:displayName].location != NSNotFound) {
2875                 includeLocalizedDeviceModelName = YES;
2876                 break;
2877             }
2878         }
2879
2880         if (includeLocalizedDeviceModelName)
2881             displayName =  [NSString stringWithFormat:@"%@ %@", localizedDeviceModel, displayName];
2882         else
2883             displayName = localizedDeviceModel;
2884
2885         break;
2886     }
2887
2888     return displayName;
2889 #else
2890     UNUSED_PARAM(player);
2891     return nil;
2892 #endif
2893 }
2894 #endif
2895
2896 String MediaPlayerPrivateAVFoundationObjC::wirelessPlaybackTargetName() const
2897 {
2898     if (!m_avPlayer)
2899         return emptyString();
2900
2901     String wirelessTargetName;
2902 #if !PLATFORM(IOS_FAMILY)
2903     if (m_playbackTarget)
2904         wirelessTargetName = m_playbackTarget->deviceName();
2905 #else
2906     wirelessTargetName = exernalDeviceDisplayNameForPlayer(m_avPlayer.get());
2907 #endif
2908
2909     return wirelessTargetName;
2910 }
2911
2912 bool MediaPlayerPrivateAVFoundationObjC::wirelessVideoPlaybackDisabled() const
2913 {
2914     if (!m_avPlayer)
2915         return !m_allowsWirelessVideoPlayback;
2916
2917     m_allowsWirelessVideoPlayback = [m_avPlayer.get() allowsExternalPlayback];
2918     INFO_LOG(LOGIDENTIFIER, "- ", !m_allowsWirelessVideoPlayback);
2919
2920     return !m_allowsWirelessVideoPlayback;
2921 }
2922
2923 void MediaPlayerPrivateAVFoundationObjC::setWirelessVideoPlaybackDisabled(bool disabled)
2924 {
2925     INFO_LOG(LOGIDENTIFIER, "- ", disabled);
2926     m_allowsWirelessVideoPlayback = !disabled;
2927     if (!m_avPlayer)
2928         return;
2929
2930     setDelayCallbacks(true);
2931     [m_avPlayer.get() setAllowsExternalPlayback:!disabled];
2932     setDelayCallbacks(false);
2933 }
2934
2935 #if !PLATFORM(IOS_FAMILY)
2936
2937 void MediaPlayerPrivateAVFoundationObjC::setWirelessPlaybackTarget(Ref<MediaPlaybackTarget>&& target)
2938 {
2939     m_playbackTarget = WTFMove(target);
2940
2941     m_outputContext = m_playbackTarget->targetType() == MediaPlaybackTarget::AVFoundation ? toMediaPlaybackTargetMac(m_playbackTarget.get())->outputContext() : nullptr;
2942
2943     INFO_LOG(LOGIDENTIFIER);
2944
2945     if (!m_playbackTarget->hasActiveRoute())
2946         setShouldPlayToPlaybackTarget(false);
2947 }
2948
2949 void MediaPlayerPrivateAVFoundationObjC::setShouldPlayToPlaybackTarget(bool shouldPlay)
2950 {
2951     if (m_shouldPlayToPlaybackTarget == shouldPlay)
2952         return;
2953
2954     m_shouldPlayToPlaybackTarget = shouldPlay;
2955
2956     if (!m_playbackTarget)
2957         return;
2958
2959     INFO_LOG(LOGIDENTIFIER, "- ", shouldPlay);
2960
2961     if (m_playbackTarget->targetType() == MediaPlaybackTarget::AVFoundation) {
2962         AVOutputContext *newContext = shouldPlay ? m_outputContext.get() : nil;
2963
2964         if (!m_avPlayer)
2965             return;
2966
2967         RetainPtr<AVOutputContext> currentContext = m_avPlayer.get().outputContext;
2968         if ((!newContext && !currentContext.get()) || [currentContext.get() isEqual:newContext])
2969             return;
2970
2971         setDelayCallbacks(true);
2972         m_avPlayer.get().outputContext = newContext;
2973         setDelayCallbacks(false);
2974
2975         return;
2976     }
2977
2978     ASSERT(m_playbackTarget->targetType() == MediaPlaybackTarget::Mock);
2979
2980     setDelayCallbacks(true);
2981     auto weakThis = makeWeakPtr(*this);
2982     scheduleMainThreadNotification(MediaPlayerPrivateAVFoundation::Notification([weakThis] {
2983         if (!weakThis)
2984             return;
2985         weakThis->playbackTargetIsWirelessDidChange();
2986     }));
2987     setDelayCallbacks(false);
2988 }
2989
2990 #endif // !PLATFORM(IOS_FAMILY)
2991
2992 void MediaPlayerPrivateAVFoundationObjC::updateDisableExternalPlayback()
2993 {
2994 #if PLATFORM(IOS_FAMILY)
2995     if (!m_avPlayer)
2996         return;
2997
2998     if ([m_avPlayer respondsToSelector:@selector(setUsesExternalPlaybackWhileExternalScreenIsActive:)])
2999         [m_avPlayer setUsesExternalPlaybackWhileExternalScreenIsActive:(player()->fullscreenMode() == MediaPlayer::VideoFullscreenModeStandard) || player()->isVideoFullscreenStandby()];
3000 #endif
3001 }
3002
3003 #endif
3004
3005 void MediaPlayerPrivateAVFoundationObjC::playerItemStatusDidChange(int status)
3006 {
3007     m_cachedItemStatus = status;
3008
3009     updateStates();
3010 }
3011
3012 void MediaPlayerPrivateAVFoundationObjC::playbackLikelyToKeepUpWillChange()
3013 {
3014     m_pendingStatusChanges++;
3015 }
3016
3017 void MediaPlayerPrivateAVFoundationObjC::playbackLikelyToKeepUpDidChange(bool likelyToKeepUp)
3018 {
3019     m_cachedLikelyToKeepUp = likelyToKeepUp;
3020
3021     ASSERT(m_pendingStatusChanges);
3022     if (!--m_pendingStatusChanges)
3023         updateStates();
3024 }
3025
3026 void MediaPlayerPrivateAVFoundationObjC::playbackBufferEmptyWillChange()
3027 {
3028     m_pendingStatusChanges++;
3029 }
3030
3031 void MediaPlayerPrivateAVFoundationObjC::playbackBufferEmptyDidChange(bool bufferEmpty)
3032 {
3033     m_cachedBufferEmpty = bufferEmpty;
3034
3035     ASSERT(m_pendingStatusChanges);
3036     if (!--m_pendingStatusChanges)
3037         updateStates();
3038 }
3039
3040 void MediaPlayerPrivateAVFoundationObjC::playbackBufferFullWillChange()
3041 {
3042     m_pendingStatusChanges++;
3043 }
3044
3045 void MediaPlayerPrivateAVFoundationObjC::playbackBufferFullDidChange(bool bufferFull)
3046 {
3047     m_cachedBufferFull = bufferFull;
3048
3049     ASSERT(m_pendingStatusChanges);
3050     if (!--m_pendingStatusChanges)
3051         updateStates();
3052 }
3053
3054 void MediaPlayerPrivateAVFoundationObjC::seekableTimeRangesDidChange(RetainPtr<NSArray>&& seekableRanges)
3055 {
3056     m_cachedSeekableRanges = WTFMove(seekableRanges);
3057
3058     seekableTimeRangesChanged();
3059     updateStates();
3060 }
3061