REGRESSION(r175251, Mavericks Only): Playback may stall
[WebKit-https.git] / Source / WebCore / platform / graphics / avfoundation / objc / MediaPlayerPrivateAVFoundationObjC.mm
1 /*
2  * Copyright (C) 2011-2015 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
28 #if ENABLE(VIDEO) && USE(AVFOUNDATION)
29 #import "MediaPlayerPrivateAVFoundationObjC.h"
30
31 #import "AVFoundationSPI.h"
32 #import "AVTrackPrivateAVFObjCImpl.h"
33 #import "AudioSourceProviderAVFObjC.h"
34 #import "AudioTrackPrivateAVFObjC.h"
35 #import "AuthenticationChallenge.h"
36 #import "BlockExceptions.h"
37 #import "CDMSessionAVFoundationObjC.h"
38 #import "Cookie.h"
39 #import "ExceptionCodePlaceholder.h"
40 #import "FloatConversion.h"
41 #import "FloatConversion.h"
42 #import "GraphicsContext.h"
43 #import "GraphicsContextCG.h"
44 #import "InbandMetadataTextTrackPrivateAVF.h"
45 #import "InbandTextTrackPrivateAVFObjC.h"
46 #import "InbandTextTrackPrivateLegacyAVFObjC.h"
47 #import "OutOfBandTextTrackPrivateAVF.h"
48 #import "URL.h"
49 #import "Logging.h"
50 #import "MediaPlaybackTargetMac.h"
51 #import "MediaSelectionGroupAVFObjC.h"
52 #import "MediaTimeAVFoundation.h"
53 #import "PlatformTimeRanges.h"
54 #import "QuartzCoreSPI.h"
55 #import "SecurityOrigin.h"
56 #import "SerializedPlatformRepresentationMac.h"
57 #import "TextEncoding.h"
58 #import "TextTrackRepresentation.h"
59 #import "UUID.h"
60 #import "VideoTrackPrivateAVFObjC.h"
61 #import "WebCoreAVFResourceLoader.h"
62 #import "WebCoreCALayerExtras.h"
63 #import "WebCoreSystemInterface.h"
64 #import <functional>
65 #import <objc/runtime.h>
66 #import <runtime/DataView.h>
67 #import <runtime/JSCInlines.h>
68 #import <runtime/TypedArrayInlines.h>
69 #import <runtime/Uint16Array.h>
70 #import <runtime/Uint32Array.h>
71 #import <runtime/Uint8Array.h>
72 #import <wtf/CurrentTime.h>
73 #import <wtf/ListHashSet.h>
74 #import <wtf/NeverDestroyed.h>
75 #import <wtf/text/CString.h>
76 #import <wtf/text/StringBuilder.h>
77
78 #if ENABLE(AVF_CAPTIONS)
79 #include "TextTrack.h"
80 #endif
81
82 #import <AVFoundation/AVFoundation.h>
83 #if PLATFORM(IOS)
84 #import "WAKAppKitStubs.h"
85 #import <CoreImage/CoreImage.h>
86 #import <mach/mach_port.h>
87 #else
88 #import <Foundation/NSGeometry.h>
89 #import <QuartzCore/CoreImage.h>
90 #endif
91
92 #if USE(VIDEOTOOLBOX)
93 #import <CoreVideo/CoreVideo.h>
94 #import <VideoToolbox/VideoToolbox.h>
95 #endif
96
97 #if USE(CFNETWORK)
98 #include "CFNSURLConnectionSPI.h"
99 #endif
100
101 namespace std {
102 template <> struct iterator_traits<HashSet<RefPtr<WebCore::MediaSelectionOptionAVFObjC>>::iterator> {
103     typedef RefPtr<WebCore::MediaSelectionOptionAVFObjC> value_type;
104 };
105 }
106
107 @interface WebVideoContainerLayer : CALayer
108 @end
109
110 @implementation WebVideoContainerLayer
111
112 - (void)setBounds:(CGRect)bounds
113 {
114     [super setBounds:bounds];
115     for (CALayer* layer in self.sublayers)
116         layer.frame = bounds;
117 }
118
119 - (void)setPosition:(CGPoint)position
120 {
121     if (!CATransform3DIsIdentity(self.transform)) {
122         // Pre-apply the transform added in the WebProcess to fix <rdar://problem/18316542> to the position.
123         position = CGPointApplyAffineTransform(position, CATransform3DGetAffineTransform(self.transform));
124     }
125     [super setPosition:position];
126 }
127 @end
128
129 #if ENABLE(AVF_CAPTIONS)
130 // Note: This must be defined before our SOFT_LINK macros:
131 @class AVMediaSelectionOption;
132 @interface AVMediaSelectionOption (OutOfBandExtensions)
133 @property (nonatomic, readonly) NSString* outOfBandSource;
134 @property (nonatomic, readonly) NSString* outOfBandIdentifier;
135 @end
136 #endif
137
138 @interface AVURLAsset (WebKitExtensions)
139 @property (nonatomic, readonly) NSURL *resolvedURL;
140 @end
141
142 typedef AVPlayer AVPlayerType;
143 typedef AVPlayerItem AVPlayerItemType;
144 typedef AVPlayerItemLegibleOutput AVPlayerItemLegibleOutputType;
145 typedef AVPlayerItemVideoOutput AVPlayerItemVideoOutputType;
146 typedef AVMetadataItem AVMetadataItemType;
147 typedef AVMediaSelectionGroup AVMediaSelectionGroupType;
148 typedef AVMediaSelectionOption AVMediaSelectionOptionType;
149
150 #pragma mark - Soft Linking
151
152 // Soft-linking headers must be included last since they #define functions, constants, etc.
153 #import "CoreMediaSoftLink.h"
154
155 SOFT_LINK_FRAMEWORK_OPTIONAL(AVFoundation)
156 SOFT_LINK_FRAMEWORK_OPTIONAL(CoreImage)
157 SOFT_LINK_FRAMEWORK_OPTIONAL(CoreVideo)
158
159 #if USE(VIDEOTOOLBOX)
160 SOFT_LINK_FRAMEWORK_OPTIONAL(VideoToolbox)
161 #endif
162
163 SOFT_LINK(CoreVideo, CVPixelBufferGetWidth, size_t, (CVPixelBufferRef pixelBuffer), (pixelBuffer))
164 SOFT_LINK(CoreVideo, CVPixelBufferGetHeight, size_t, (CVPixelBufferRef pixelBuffer), (pixelBuffer))
165 SOFT_LINK(CoreVideo, CVPixelBufferGetBaseAddress, void*, (CVPixelBufferRef pixelBuffer), (pixelBuffer))
166 SOFT_LINK(CoreVideo, CVPixelBufferGetBytesPerRow, size_t, (CVPixelBufferRef pixelBuffer), (pixelBuffer))
167 SOFT_LINK(CoreVideo, CVPixelBufferGetDataSize, size_t, (CVPixelBufferRef pixelBuffer), (pixelBuffer))
168 SOFT_LINK(CoreVideo, CVPixelBufferGetPixelFormatType, OSType, (CVPixelBufferRef pixelBuffer), (pixelBuffer))
169 SOFT_LINK(CoreVideo, CVPixelBufferLockBaseAddress, CVReturn, (CVPixelBufferRef pixelBuffer, CVOptionFlags lockFlags), (pixelBuffer, lockFlags))
170 SOFT_LINK(CoreVideo, CVPixelBufferUnlockBaseAddress, CVReturn, (CVPixelBufferRef pixelBuffer, CVOptionFlags lockFlags), (pixelBuffer, lockFlags))
171
172 #if USE(VIDEOTOOLBOX)
173 SOFT_LINK(VideoToolbox, VTPixelTransferSessionCreate, OSStatus, (CFAllocatorRef allocator, VTPixelTransferSessionRef *pixelTransferSessionOut), (allocator, pixelTransferSessionOut))
174 SOFT_LINK(VideoToolbox, VTPixelTransferSessionTransferImage, OSStatus, (VTPixelTransferSessionRef session, CVPixelBufferRef sourceBuffer, CVPixelBufferRef destinationBuffer), (session, sourceBuffer, destinationBuffer))
175 #endif
176
177 SOFT_LINK_CLASS(AVFoundation, AVPlayer)
178 SOFT_LINK_CLASS(AVFoundation, AVPlayerItem)
179 SOFT_LINK_CLASS(AVFoundation, AVPlayerItemVideoOutput)
180 SOFT_LINK_CLASS(AVFoundation, AVPlayerLayer)
181 SOFT_LINK_CLASS(AVFoundation, AVURLAsset)
182 SOFT_LINK_CLASS(AVFoundation, AVAssetImageGenerator)
183 SOFT_LINK_CLASS(AVFoundation, AVMetadataItem)
184
185 SOFT_LINK_CLASS(CoreImage, CIContext)
186 SOFT_LINK_CLASS(CoreImage, CIImage)
187
188 SOFT_LINK_POINTER(AVFoundation, AVAudioTimePitchAlgorithmSpectral, NSString*)
189 SOFT_LINK_POINTER(AVFoundation, AVAudioTimePitchAlgorithmVarispeed, NSString*)
190 SOFT_LINK_POINTER(AVFoundation, AVMediaCharacteristicVisual, NSString *)
191 SOFT_LINK_POINTER(AVFoundation, AVMediaCharacteristicAudible, NSString *)
192 SOFT_LINK_POINTER(AVFoundation, AVMediaTypeClosedCaption, NSString *)
193 SOFT_LINK_POINTER(AVFoundation, AVMediaTypeVideo, NSString *)
194 SOFT_LINK_POINTER(AVFoundation, AVMediaTypeAudio, NSString *)
195 SOFT_LINK_POINTER(AVFoundation, AVMediaTypeMetadata, NSString *)
196 SOFT_LINK_POINTER(AVFoundation, AVPlayerItemDidPlayToEndTimeNotification, NSString *)
197 SOFT_LINK_POINTER(AVFoundation, AVURLAssetInheritURIQueryComponentFromReferencingURIKey, NSString *)
198 SOFT_LINK_POINTER(AVFoundation, AVAssetImageGeneratorApertureModeCleanAperture, NSString *)
199 SOFT_LINK_POINTER(AVFoundation, AVURLAssetReferenceRestrictionsKey, NSString *)
200 SOFT_LINK_POINTER(AVFoundation, AVLayerVideoGravityResizeAspect, NSString *)
201 SOFT_LINK_POINTER(AVFoundation, AVLayerVideoGravityResizeAspectFill, NSString *)
202 SOFT_LINK_POINTER(AVFoundation, AVLayerVideoGravityResize, NSString *)
203 SOFT_LINK_POINTER(CoreVideo, kCVPixelBufferPixelFormatTypeKey, NSString *)
204
205 SOFT_LINK_POINTER_OPTIONAL(AVFoundation, AVURLAssetClientBundleIdentifierKey, NSString *)
206
207 #define AVPlayer getAVPlayerClass()
208 #define AVPlayerItem getAVPlayerItemClass()
209 #define AVPlayerLayer getAVPlayerLayerClass()
210 #define AVURLAsset getAVURLAssetClass()
211 #define AVAssetImageGenerator getAVAssetImageGeneratorClass()
212 #define AVMetadataItem getAVMetadataItemClass()
213
214 #define AVAudioTimePitchAlgorithmSpectral getAVAudioTimePitchAlgorithmSpectral()
215 #define AVAudioTimePitchAlgorithmVarispeed getAVAudioTimePitchAlgorithmVarispeed()
216 #define AVMediaCharacteristicVisual getAVMediaCharacteristicVisual()
217 #define AVMediaCharacteristicAudible getAVMediaCharacteristicAudible()
218 #define AVMediaTypeClosedCaption getAVMediaTypeClosedCaption()
219 #define AVMediaTypeVideo getAVMediaTypeVideo()
220 #define AVMediaTypeAudio getAVMediaTypeAudio()
221 #define AVMediaTypeMetadata getAVMediaTypeMetadata()
222 #define AVPlayerItemDidPlayToEndTimeNotification getAVPlayerItemDidPlayToEndTimeNotification()
223 #define AVURLAssetInheritURIQueryComponentFromReferencingURIKey getAVURLAssetInheritURIQueryComponentFromReferencingURIKey()
224 #define AVURLAssetClientBundleIdentifierKey getAVURLAssetClientBundleIdentifierKey()
225 #define AVAssetImageGeneratorApertureModeCleanAperture getAVAssetImageGeneratorApertureModeCleanAperture()
226 #define AVURLAssetReferenceRestrictionsKey getAVURLAssetReferenceRestrictionsKey()
227 #define AVLayerVideoGravityResizeAspect getAVLayerVideoGravityResizeAspect()
228 #define AVLayerVideoGravityResizeAspectFill getAVLayerVideoGravityResizeAspectFill()
229 #define AVLayerVideoGravityResize getAVLayerVideoGravityResize()
230 #define kCVPixelBufferPixelFormatTypeKey getkCVPixelBufferPixelFormatTypeKey()
231
232 #if HAVE(AVFOUNDATION_MEDIA_SELECTION_GROUP)
233 typedef AVMediaSelectionGroup AVMediaSelectionGroupType;
234 typedef AVMediaSelectionOption AVMediaSelectionOptionType;
235
236 SOFT_LINK_CLASS(AVFoundation, AVPlayerItemLegibleOutput)
237 SOFT_LINK_CLASS(AVFoundation, AVMediaSelectionGroup)
238 SOFT_LINK_CLASS(AVFoundation, AVMediaSelectionOption)
239
240 SOFT_LINK_POINTER(AVFoundation, AVMediaCharacteristicLegible, NSString *)
241 SOFT_LINK_POINTER(AVFoundation, AVMediaTypeSubtitle, NSString *)
242 SOFT_LINK_POINTER(AVFoundation, AVMediaCharacteristicContainsOnlyForcedSubtitles, NSString *)
243 SOFT_LINK_POINTER(AVFoundation, AVPlayerItemLegibleOutputTextStylingResolutionSourceAndRulesOnly, NSString *)
244
245 #define AVPlayerItemLegibleOutput getAVPlayerItemLegibleOutputClass()
246 #define AVMediaSelectionGroup getAVMediaSelectionGroupClass()
247 #define AVMediaSelectionOption getAVMediaSelectionOptionClass()
248 #define AVMediaCharacteristicLegible getAVMediaCharacteristicLegible()
249 #define AVMediaTypeSubtitle getAVMediaTypeSubtitle()
250 #define AVMediaCharacteristicContainsOnlyForcedSubtitles getAVMediaCharacteristicContainsOnlyForcedSubtitles()
251 #define AVPlayerItemLegibleOutputTextStylingResolutionSourceAndRulesOnly getAVPlayerItemLegibleOutputTextStylingResolutionSourceAndRulesOnly()
252 #endif
253
254 #if ENABLE(AVF_CAPTIONS)
255 SOFT_LINK_POINTER(AVFoundation, AVURLAssetHTTPCookiesKey, NSString*)
256 SOFT_LINK_POINTER(AVFoundation, AVURLAssetOutOfBandAlternateTracksKey, NSString*)
257 SOFT_LINK_POINTER(AVFoundation, AVOutOfBandAlternateTrackDisplayNameKey, NSString*)
258 SOFT_LINK_POINTER(AVFoundation, AVOutOfBandAlternateTrackExtendedLanguageTagKey, NSString*)
259 SOFT_LINK_POINTER(AVFoundation, AVOutOfBandAlternateTrackIsDefaultKey, NSString*)
260 SOFT_LINK_POINTER(AVFoundation, AVOutOfBandAlternateTrackMediaCharactersticsKey, NSString*)
261 SOFT_LINK_POINTER(AVFoundation, AVOutOfBandAlternateTrackIdentifierKey, NSString*)
262 SOFT_LINK_POINTER(AVFoundation, AVOutOfBandAlternateTrackSourceKey, NSString*)
263 SOFT_LINK_POINTER(AVFoundation, AVMediaCharacteristicDescribesMusicAndSoundForAccessibility, NSString*)
264 SOFT_LINK_POINTER(AVFoundation, AVMediaCharacteristicTranscribesSpokenDialogForAccessibility, NSString*)
265
266 #define AVURLAssetHTTPCookiesKey getAVURLAssetHTTPCookiesKey()
267 #define AVURLAssetOutOfBandAlternateTracksKey getAVURLAssetOutOfBandAlternateTracksKey()
268 #define AVOutOfBandAlternateTrackDisplayNameKey getAVOutOfBandAlternateTrackDisplayNameKey()
269 #define AVOutOfBandAlternateTrackExtendedLanguageTagKey getAVOutOfBandAlternateTrackExtendedLanguageTagKey()
270 #define AVOutOfBandAlternateTrackIsDefaultKey getAVOutOfBandAlternateTrackIsDefaultKey()
271 #define AVOutOfBandAlternateTrackMediaCharactersticsKey getAVOutOfBandAlternateTrackMediaCharactersticsKey()
272 #define AVOutOfBandAlternateTrackIdentifierKey getAVOutOfBandAlternateTrackIdentifierKey()
273 #define AVOutOfBandAlternateTrackSourceKey getAVOutOfBandAlternateTrackSourceKey()
274 #define AVMediaCharacteristicDescribesMusicAndSoundForAccessibility getAVMediaCharacteristicDescribesMusicAndSoundForAccessibility()
275 #define AVMediaCharacteristicTranscribesSpokenDialogForAccessibility getAVMediaCharacteristicTranscribesSpokenDialogForAccessibility()
276 #endif
277
278 #if ENABLE(DATACUE_VALUE)
279 SOFT_LINK_POINTER(AVFoundation, AVMetadataKeySpaceQuickTimeUserData, NSString*)
280 SOFT_LINK_POINTER_OPTIONAL(AVFoundation, AVMetadataKeySpaceISOUserData, NSString*)
281 SOFT_LINK_POINTER(AVFoundation, AVMetadataKeySpaceQuickTimeMetadata, NSString*)
282 SOFT_LINK_POINTER(AVFoundation, AVMetadataKeySpaceiTunes, NSString*)
283 SOFT_LINK_POINTER(AVFoundation, AVMetadataKeySpaceID3, NSString*)
284
285 #define AVMetadataKeySpaceQuickTimeUserData getAVMetadataKeySpaceQuickTimeUserData()
286 #define AVMetadataKeySpaceISOUserData getAVMetadataKeySpaceISOUserData()
287 #define AVMetadataKeySpaceQuickTimeMetadata getAVMetadataKeySpaceQuickTimeMetadata()
288 #define AVMetadataKeySpaceiTunes getAVMetadataKeySpaceiTunes()
289 #define AVMetadataKeySpaceID3 getAVMetadataKeySpaceID3()
290 #endif
291
292 #if PLATFORM(IOS)
293 SOFT_LINK_POINTER(AVFoundation, AVURLAssetBoundNetworkInterfaceName, NSString *)
294 #define AVURLAssetBoundNetworkInterfaceName getAVURLAssetBoundNetworkInterfaceName()
295 #endif
296
297 using namespace WebCore;
298
299 enum MediaPlayerAVFoundationObservationContext {
300     MediaPlayerAVFoundationObservationContextPlayerItem,
301     MediaPlayerAVFoundationObservationContextPlayerItemTrack,
302     MediaPlayerAVFoundationObservationContextPlayer,
303     MediaPlayerAVFoundationObservationContextAVPlayerLayer,
304 };
305
306 #if HAVE(AVFOUNDATION_MEDIA_SELECTION_GROUP) && HAVE(AVFOUNDATION_LEGIBLE_OUTPUT_SUPPORT)
307 @interface WebCoreAVFMovieObserver : NSObject <AVPlayerItemLegibleOutputPushDelegate>
308 #else
309 @interface WebCoreAVFMovieObserver : NSObject
310 #endif
311 {
312     MediaPlayerPrivateAVFoundationObjC* m_callback;
313     int m_delayCallbacks;
314 }
315 -(id)initWithCallback:(MediaPlayerPrivateAVFoundationObjC*)callback;
316 -(void)disconnect;
317 -(void)metadataLoaded;
318 -(void)didEnd:(NSNotification *)notification;
319 -(void)observeValueForKeyPath:keyPath ofObject:(id)object change:(NSDictionary *)change context:(MediaPlayerAVFoundationObservationContext)context;
320 #if HAVE(AVFOUNDATION_MEDIA_SELECTION_GROUP)
321 - (void)legibleOutput:(id)output didOutputAttributedStrings:(NSArray *)strings nativeSampleBuffers:(NSArray *)nativeSamples forItemTime:(CMTime)itemTime;
322 - (void)outputSequenceWasFlushed:(id)output;
323 #endif
324 @end
325
326 #if HAVE(AVFOUNDATION_LOADER_DELEGATE)
327 @interface WebCoreAVFLoaderDelegate : NSObject<AVAssetResourceLoaderDelegate> {
328     MediaPlayerPrivateAVFoundationObjC* m_callback;
329 }
330 - (id)initWithCallback:(MediaPlayerPrivateAVFoundationObjC*)callback;
331 - (BOOL)resourceLoader:(AVAssetResourceLoader *)resourceLoader shouldWaitForLoadingOfRequestedResource:(AVAssetResourceLoadingRequest *)loadingRequest;
332 - (void)setCallback:(MediaPlayerPrivateAVFoundationObjC*)callback;
333 @end
334 #endif
335
336 #if HAVE(AVFOUNDATION_VIDEO_OUTPUT)
337 @interface WebCoreAVFPullDelegate : NSObject<AVPlayerItemOutputPullDelegate> {
338     MediaPlayerPrivateAVFoundationObjC *m_callback;
339     dispatch_semaphore_t m_semaphore;
340 }
341 - (id)initWithCallback:(MediaPlayerPrivateAVFoundationObjC *)callback;
342 - (void)setCallback:(MediaPlayerPrivateAVFoundationObjC*)callback;
343 - (void)outputMediaDataWillChange:(AVPlayerItemOutput *)sender;
344 - (void)outputSequenceWasFlushed:(AVPlayerItemOutput *)output;
345 @end
346 #endif
347
348 namespace WebCore {
349
350 static NSArray *assetMetadataKeyNames();
351 static NSArray *itemKVOProperties();
352 static NSArray *assetTrackMetadataKeyNames();
353 static NSArray *playerKVOProperties();
354 static AVAssetTrack* firstEnabledTrack(NSArray* tracks);
355
356 #if !LOG_DISABLED
357 static const char *boolString(bool val)
358 {
359     return val ? "true" : "false";
360 }
361 #endif
362
363 #if ENABLE(ENCRYPTED_MEDIA_V2)
364 typedef HashMap<MediaPlayer*, MediaPlayerPrivateAVFoundationObjC*> PlayerToPrivateMapType;
365 static PlayerToPrivateMapType& playerToPrivateMap()
366 {
367     DEPRECATED_DEFINE_STATIC_LOCAL(PlayerToPrivateMapType, map, ());
368     return map;
369 };
370 #endif
371
372 #if HAVE(AVFOUNDATION_LOADER_DELEGATE)
373 static dispatch_queue_t globalLoaderDelegateQueue()
374 {
375     static dispatch_queue_t globalQueue;
376     static dispatch_once_t onceToken;
377     dispatch_once(&onceToken, ^{
378         globalQueue = dispatch_queue_create("WebCoreAVFLoaderDelegate queue", DISPATCH_QUEUE_SERIAL);
379     });
380     return globalQueue;
381 }
382 #endif
383
384 #if HAVE(AVFOUNDATION_VIDEO_OUTPUT)
385 static dispatch_queue_t globalPullDelegateQueue()
386 {
387     static dispatch_queue_t globalQueue;
388     static dispatch_once_t onceToken;
389     dispatch_once(&onceToken, ^{
390         globalQueue = dispatch_queue_create("WebCoreAVFPullDelegate queue", DISPATCH_QUEUE_SERIAL);
391     });
392     return globalQueue;
393 }
394 #endif
395
396 #if USE(CFNETWORK)
397 class WebCoreNSURLAuthenticationChallengeClient : public RefCounted<WebCoreNSURLAuthenticationChallengeClient>, public AuthenticationClient {
398 public:
399     static RefPtr<WebCoreNSURLAuthenticationChallengeClient> create(NSURLAuthenticationChallenge *challenge)
400     {
401         return adoptRef(new WebCoreNSURLAuthenticationChallengeClient(challenge));
402     }
403
404     using RefCounted<WebCoreNSURLAuthenticationChallengeClient>::ref;
405     using RefCounted<WebCoreNSURLAuthenticationChallengeClient>::deref;
406
407 private:
408     WebCoreNSURLAuthenticationChallengeClient(NSURLAuthenticationChallenge *challenge)
409         : m_challenge(challenge)
410     {
411         ASSERT(m_challenge);
412     }
413
414     virtual void refAuthenticationClient() override { ref(); }
415     virtual void derefAuthenticationClient() override { deref(); }
416
417     virtual void receivedCredential(const AuthenticationChallenge&, const Credential& credential)
418     {
419         [[m_challenge sender] useCredential:credential.nsCredential() forAuthenticationChallenge:m_challenge.get()];
420     }
421
422     virtual void receivedRequestToContinueWithoutCredential(const AuthenticationChallenge&)
423     {
424         [[m_challenge sender] continueWithoutCredentialForAuthenticationChallenge:m_challenge.get()];
425     }
426
427     virtual void receivedCancellation(const AuthenticationChallenge&)
428     {
429         [[m_challenge sender] cancelAuthenticationChallenge:m_challenge.get()];
430     }
431
432     virtual void receivedRequestToPerformDefaultHandling(const AuthenticationChallenge&)
433     {
434         if ([[m_challenge sender] respondsToSelector:@selector(performDefaultHandlingForAuthenticationChallenge:)])
435             [[m_challenge sender] performDefaultHandlingForAuthenticationChallenge:m_challenge.get()];
436     }
437
438     virtual void receivedChallengeRejection(const AuthenticationChallenge&)
439     {
440         if ([[m_challenge sender] respondsToSelector:@selector(rejectProtectionSpaceAndContinueWithChallenge:)])
441             [[m_challenge sender] rejectProtectionSpaceAndContinueWithChallenge:m_challenge.get()];
442     }
443
444     RetainPtr<NSURLAuthenticationChallenge> m_challenge;
445 };
446 #endif
447
448 void MediaPlayerPrivateAVFoundationObjC::registerMediaEngine(MediaEngineRegistrar registrar)
449 {
450     if (isAvailable())
451         registrar([](MediaPlayer* player) { return std::make_unique<MediaPlayerPrivateAVFoundationObjC>(player); },
452             getSupportedTypes, supportsType, 0, 0, 0, supportsKeySystem);
453 }
454
455 MediaPlayerPrivateAVFoundationObjC::MediaPlayerPrivateAVFoundationObjC(MediaPlayer* player)
456     : MediaPlayerPrivateAVFoundation(player)
457     , m_weakPtrFactory(this)
458 #if PLATFORM(IOS)
459     , m_videoFullscreenGravity(MediaPlayer::VideoGravityResizeAspect)
460 #endif
461     , m_objcObserver(adoptNS([[WebCoreAVFMovieObserver alloc] initWithCallback:this]))
462     , m_videoFrameHasDrawn(false)
463     , m_haveCheckedPlayability(false)
464 #if HAVE(AVFOUNDATION_VIDEO_OUTPUT)
465     , m_videoOutputDelegate(adoptNS([[WebCoreAVFPullDelegate alloc] initWithCallback:this]))
466     , m_videoOutputSemaphore(nullptr)
467 #endif
468 #if HAVE(AVFOUNDATION_LOADER_DELEGATE)
469     , m_loaderDelegate(adoptNS([[WebCoreAVFLoaderDelegate alloc] initWithCallback:this]))
470 #endif
471     , m_currentTextTrack(0)
472     , m_cachedRate(0)
473     , m_cachedTotalBytes(0)
474     , m_pendingStatusChanges(0)
475     , m_cachedItemStatus(MediaPlayerAVPlayerItemStatusDoesNotExist)
476     , m_cachedLikelyToKeepUp(false)
477     , m_cachedBufferEmpty(false)
478     , m_cachedBufferFull(false)
479     , m_cachedHasEnabledAudio(false)
480     , m_shouldBufferData(true)
481     , m_cachedIsReadyForDisplay(false)
482     , m_haveBeenAskedToCreateLayer(false)
483 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
484     , m_allowsWirelessVideoPlayback(true)
485 #endif
486 {
487 #if ENABLE(ENCRYPTED_MEDIA_V2)
488     playerToPrivateMap().set(player, this);
489 #endif
490 }
491
492 MediaPlayerPrivateAVFoundationObjC::~MediaPlayerPrivateAVFoundationObjC()
493 {
494 #if ENABLE(ENCRYPTED_MEDIA_V2)
495     playerToPrivateMap().remove(player());
496 #endif
497 #if HAVE(AVFOUNDATION_LOADER_DELEGATE)
498     [m_loaderDelegate.get() setCallback:0];
499     [[m_avAsset.get() resourceLoader] setDelegate:nil queue:0];
500
501     for (auto& pair : m_resourceLoaderMap)
502         pair.value->invalidate();
503 #endif
504 #if HAVE(AVFOUNDATION_VIDEO_OUTPUT)
505     [m_videoOutputDelegate setCallback:0];
506     [m_videoOutput setDelegate:nil queue:0];
507     if (m_videoOutputSemaphore)
508         dispatch_release(m_videoOutputSemaphore);
509 #endif
510
511     if (m_videoLayer)
512         destroyVideoLayer();
513
514     cancelLoad();
515 }
516
517 void MediaPlayerPrivateAVFoundationObjC::cancelLoad()
518 {
519     LOG(Media, "MediaPlayerPrivateAVFoundationObjC::cancelLoad(%p)", this);
520     tearDownVideoRendering();
521
522     [[NSNotificationCenter defaultCenter] removeObserver:m_objcObserver.get()];
523     [m_objcObserver.get() disconnect];
524
525     // Tell our observer to do nothing when our cancellation of pending loading calls its completion handler.
526     setIgnoreLoadStateChanges(true);
527     if (m_avAsset) {
528         [m_avAsset.get() cancelLoading];
529         m_avAsset = nil;
530     }
531
532     clearTextTracks();
533
534 #if HAVE(AVFOUNDATION_MEDIA_SELECTION_GROUP) && HAVE(AVFOUNDATION_LEGIBLE_OUTPUT_SUPPORT)
535     if (m_legibleOutput) {
536         if (m_avPlayerItem)
537             [m_avPlayerItem.get() removeOutput:m_legibleOutput.get()];
538         m_legibleOutput = nil;
539     }
540 #endif
541
542     if (m_avPlayerItem) {
543         for (NSString *keyName in itemKVOProperties())
544             [m_avPlayerItem.get() removeObserver:m_objcObserver.get() forKeyPath:keyName];
545         
546         m_avPlayerItem = nil;
547     }
548     if (m_avPlayer) {
549         if (m_timeObserver)
550             [m_avPlayer.get() removeTimeObserver:m_timeObserver.get()];
551         m_timeObserver = nil;
552
553         for (NSString *keyName in playerKVOProperties())
554             [m_avPlayer.get() removeObserver:m_objcObserver.get() forKeyPath:keyName];
555         m_avPlayer = nil;
556     }
557
558     // Reset cached properties
559     m_pendingStatusChanges = 0;
560     m_cachedItemStatus = MediaPlayerAVPlayerItemStatusDoesNotExist;
561     m_cachedSeekableRanges = nullptr;
562     m_cachedLoadedRanges = nullptr;
563     m_cachedHasEnabledAudio = false;
564     m_cachedPresentationSize = FloatSize();
565     m_cachedDuration = MediaTime::zeroTime();
566
567     for (AVPlayerItemTrack *track in m_cachedTracks.get())
568         [track removeObserver:m_objcObserver.get() forKeyPath:@"enabled"];
569     m_cachedTracks = nullptr;
570
571 #if ENABLE(WEB_AUDIO) && USE(MEDIATOOLBOX)
572     if (m_provider) {
573         m_provider->setPlayerItem(nullptr);
574         m_provider->setAudioTrack(nullptr);
575     }
576 #endif
577
578     setIgnoreLoadStateChanges(false);
579 }
580
581 bool MediaPlayerPrivateAVFoundationObjC::hasLayerRenderer() const
582 {
583     return m_haveBeenAskedToCreateLayer;
584 }
585
586 bool MediaPlayerPrivateAVFoundationObjC::hasContextRenderer() const
587 {
588 #if HAVE(AVFOUNDATION_VIDEO_OUTPUT)
589     if (m_videoOutput)
590         return true;
591 #endif
592     return m_imageGenerator;
593 }
594
595 void MediaPlayerPrivateAVFoundationObjC::createContextVideoRenderer()
596 {
597 #if HAVE(AVFOUNDATION_VIDEO_OUTPUT)
598     createVideoOutput();
599 #else
600     createImageGenerator();
601 #endif
602 }
603
604 void MediaPlayerPrivateAVFoundationObjC::createImageGenerator()
605 {
606     LOG(Media, "MediaPlayerPrivateAVFoundationObjC::createImageGenerator(%p)", this);
607
608     if (!m_avAsset || m_imageGenerator)
609         return;
610
611     m_imageGenerator = [AVAssetImageGenerator assetImageGeneratorWithAsset:m_avAsset.get()];
612
613     [m_imageGenerator.get() setApertureMode:AVAssetImageGeneratorApertureModeCleanAperture];
614     [m_imageGenerator.get() setAppliesPreferredTrackTransform:YES];
615     [m_imageGenerator.get() setRequestedTimeToleranceBefore:kCMTimeZero];
616     [m_imageGenerator.get() setRequestedTimeToleranceAfter:kCMTimeZero];
617
618     LOG(Media, "MediaPlayerPrivateAVFoundationObjC::createImageGenerator(%p) - returning %p", this, m_imageGenerator.get());
619 }
620
621 void MediaPlayerPrivateAVFoundationObjC::destroyContextVideoRenderer()
622 {
623 #if HAVE(AVFOUNDATION_VIDEO_OUTPUT)
624     destroyVideoOutput();
625 #endif
626     destroyImageGenerator();
627 }
628
629 void MediaPlayerPrivateAVFoundationObjC::destroyImageGenerator()
630 {
631     if (!m_imageGenerator)
632         return;
633
634     LOG(Media, "MediaPlayerPrivateAVFoundationObjC::destroyImageGenerator(%p) - destroying  %p", this, m_imageGenerator.get());
635
636     m_imageGenerator = 0;
637 }
638
639 void MediaPlayerPrivateAVFoundationObjC::createVideoLayer()
640 {
641     if (!m_avPlayer || m_haveBeenAskedToCreateLayer)
642         return;
643
644     auto weakThis = createWeakPtr();
645     callOnMainThread([this, weakThis] {
646         if (!weakThis)
647             return;
648
649         if (!m_avPlayer || m_haveBeenAskedToCreateLayer)
650             return;
651         m_haveBeenAskedToCreateLayer = true;
652
653         if (!m_videoLayer)
654             createAVPlayerLayer();
655
656 #if USE(VIDEOTOOLBOX) && (!defined(__MAC_OS_X_VERSION_MIN_REQUIRED) || __MAC_OS_X_VERSION_MIN_REQUIRED >= 101000)
657         if (!m_videoOutput)
658             createVideoOutput();
659 #endif
660
661         player()->client().mediaPlayerRenderingModeChanged(player());
662     });
663 }
664
665 void MediaPlayerPrivateAVFoundationObjC::createAVPlayerLayer()
666 {
667     if (!m_avPlayer)
668         return;
669
670     m_videoLayer = adoptNS([allocAVPlayerLayerInstance() init]);
671     [m_videoLayer setPlayer:m_avPlayer.get()];
672     [m_videoLayer setBackgroundColor:cachedCGColor(Color::black, ColorSpaceDeviceRGB)];
673 #ifndef NDEBUG
674     [m_videoLayer setName:@"MediaPlayerPrivate AVPlayerLayer"];
675 #endif
676     [m_videoLayer addObserver:m_objcObserver.get() forKeyPath:@"readyForDisplay" options:NSKeyValueObservingOptionNew context:(void *)MediaPlayerAVFoundationObservationContextAVPlayerLayer];
677     updateVideoLayerGravity();
678     [m_videoLayer setContentsScale:player()->client().mediaPlayerContentsScale()];
679     IntSize defaultSize = player()->client().mediaPlayerContentBoxRect().pixelSnappedSize();
680     LOG(Media, "MediaPlayerPrivateAVFoundationObjC::createVideoLayer(%p) - returning %p", this, m_videoLayer.get());
681
682 #if PLATFORM(IOS)
683     [m_videoLayer web_disableAllActions];
684     m_videoInlineLayer = adoptNS([[WebVideoContainerLayer alloc] init]);
685 #ifndef NDEBUG
686     [m_videoInlineLayer setName:@"WebVideoContainerLayer"];
687 #endif
688     [m_videoInlineLayer setFrame:CGRectMake(0, 0, defaultSize.width(), defaultSize.height())];
689     if (m_videoFullscreenLayer) {
690         [m_videoLayer setFrame:CGRectMake(0, 0, m_videoFullscreenFrame.width(), m_videoFullscreenFrame.height())];
691         [m_videoFullscreenLayer insertSublayer:m_videoLayer.get() atIndex:0];
692     } else {
693         [m_videoInlineLayer insertSublayer:m_videoLayer.get() atIndex:0];
694         [m_videoLayer setFrame:m_videoInlineLayer.get().bounds];
695     }
696     if ([m_videoLayer respondsToSelector:@selector(setEnterOptimizedFullscreenModeEnabled:)])
697         [m_videoLayer setEnterOptimizedFullscreenModeEnabled:(player()->fullscreenMode() & MediaPlayer::VideoFullscreenModeOptimized)];
698 #else
699     [m_videoLayer setFrame:CGRectMake(0, 0, defaultSize.width(), defaultSize.height())];
700 #endif
701 }
702
703 void MediaPlayerPrivateAVFoundationObjC::destroyVideoLayer()
704 {
705     if (!m_videoLayer)
706         return;
707
708     LOG(Media, "MediaPlayerPrivateAVFoundationObjC::destroyVideoLayer(%p) - destroying %p", this, m_videoLayer.get());
709
710     [m_videoLayer.get() removeObserver:m_objcObserver.get() forKeyPath:@"readyForDisplay"];
711     [m_videoLayer.get() setPlayer:nil];
712
713 #if PLATFORM(IOS)
714     if (m_videoFullscreenLayer)
715         [m_videoLayer removeFromSuperlayer];
716     m_videoInlineLayer = nil;
717 #endif
718
719     m_videoLayer = nil;
720 }
721
722 bool MediaPlayerPrivateAVFoundationObjC::hasAvailableVideoFrame() const
723 {
724     if (currentRenderingMode() == MediaRenderingToLayer)
725         return m_cachedIsReadyForDisplay;
726
727     return m_videoFrameHasDrawn;
728 }
729
730 #if ENABLE(AVF_CAPTIONS)
731 static const NSArray* mediaDescriptionForKind(PlatformTextTrack::TrackKind kind)
732 {
733     // FIXME: Match these to correct types:
734     if (kind == PlatformTextTrack::Caption)
735         return [NSArray arrayWithObjects: AVMediaCharacteristicTranscribesSpokenDialogForAccessibility, nil];
736
737     if (kind == PlatformTextTrack::Subtitle)
738         return [NSArray arrayWithObjects: AVMediaCharacteristicTranscribesSpokenDialogForAccessibility, nil];
739
740     if (kind == PlatformTextTrack::Description)
741         return [NSArray arrayWithObjects: AVMediaCharacteristicTranscribesSpokenDialogForAccessibility, AVMediaCharacteristicDescribesMusicAndSoundForAccessibility, nil];
742
743     if (kind == PlatformTextTrack::Forced)
744         return [NSArray arrayWithObjects: AVMediaCharacteristicContainsOnlyForcedSubtitles, nil];
745
746     return [NSArray arrayWithObjects: AVMediaCharacteristicTranscribesSpokenDialogForAccessibility, nil];
747 }
748     
749 void MediaPlayerPrivateAVFoundationObjC::notifyTrackModeChanged()
750 {
751     trackModeChanged();
752 }
753     
754 void MediaPlayerPrivateAVFoundationObjC::synchronizeTextTrackState()
755 {
756     const Vector<RefPtr<PlatformTextTrack>>& outOfBandTrackSources = player()->outOfBandTrackSources();
757     
758     for (auto& textTrack : m_textTracks) {
759         if (textTrack->textTrackCategory() != InbandTextTrackPrivateAVF::OutOfBand)
760             continue;
761         
762         RefPtr<OutOfBandTextTrackPrivateAVF> trackPrivate = static_cast<OutOfBandTextTrackPrivateAVF*>(textTrack.get());
763         RetainPtr<AVMediaSelectionOptionType> currentOption = trackPrivate->mediaSelectionOption();
764         
765         for (auto& track : outOfBandTrackSources) {
766             RetainPtr<CFStringRef> uniqueID = String::number(track->uniqueId()).createCFString();
767             
768             if (![[currentOption.get() outOfBandIdentifier] isEqual: reinterpret_cast<const NSString*>(uniqueID.get())])
769                 continue;
770             
771             InbandTextTrackPrivate::Mode mode = InbandTextTrackPrivate::Hidden;
772             if (track->mode() == PlatformTextTrack::Hidden)
773                 mode = InbandTextTrackPrivate::Hidden;
774             else if (track->mode() == PlatformTextTrack::Disabled)
775                 mode = InbandTextTrackPrivate::Disabled;
776             else if (track->mode() == PlatformTextTrack::Showing)
777                 mode = InbandTextTrackPrivate::Showing;
778             
779             textTrack->setMode(mode);
780             break;
781         }
782     }
783 }
784 #endif
785
786
787 static NSURL *canonicalURL(const String& url)
788 {
789     NSURL *cocoaURL = URL(ParsedURLString, url);
790     if (url.isEmpty())
791         return cocoaURL;
792
793     RetainPtr<NSURLRequest> request = adoptNS([[NSURLRequest alloc] initWithURL:cocoaURL]);
794     if (!request)
795         return cocoaURL;
796
797     NSURLRequest *canonicalRequest = [NSURLProtocol canonicalRequestForRequest:request.get()];
798     if (!canonicalRequest)
799         return cocoaURL;
800
801     return [canonicalRequest URL];
802 }
803
804 #if PLATFORM(IOS)
805 static NSHTTPCookie* toNSHTTPCookie(const Cookie& cookie)
806 {
807     RetainPtr<NSMutableDictionary> properties = adoptNS([[NSMutableDictionary alloc] init]);
808     [properties setDictionary:@{
809         NSHTTPCookieName: cookie.name,
810         NSHTTPCookieValue: cookie.value,
811         NSHTTPCookieDomain: cookie.domain,
812         NSHTTPCookiePath: cookie.path,
813         NSHTTPCookieExpires: [NSDate dateWithTimeIntervalSince1970:(cookie.expires / 1000)],
814     }];
815     if (cookie.secure)
816         [properties setObject:@YES forKey:NSHTTPCookieSecure];
817     if (cookie.session)
818         [properties setObject:@YES forKey:NSHTTPCookieDiscard];
819
820     return [NSHTTPCookie cookieWithProperties:properties.get()];
821 }
822 #endif
823
824 void MediaPlayerPrivateAVFoundationObjC::createAVAssetForURL(const String& url)
825 {
826     if (m_avAsset)
827         return;
828
829     LOG(Media, "MediaPlayerPrivateAVFoundationObjC::createAVAssetForURL(%p) - url = %s", this, url.utf8().data());
830
831     setDelayCallbacks(true);
832
833     RetainPtr<NSMutableDictionary> options = adoptNS([[NSMutableDictionary alloc] init]);    
834
835     [options.get() setObject:[NSNumber numberWithInt:AVAssetReferenceRestrictionForbidRemoteReferenceToLocal | AVAssetReferenceRestrictionForbidLocalReferenceToRemote] forKey:AVURLAssetReferenceRestrictionsKey];
836
837     RetainPtr<NSMutableDictionary> headerFields = adoptNS([[NSMutableDictionary alloc] init]);
838
839     String referrer = player()->referrer();
840     if (!referrer.isEmpty())
841         [headerFields.get() setObject:referrer forKey:@"Referer"];
842
843     String userAgent = player()->userAgent();
844     if (!userAgent.isEmpty())
845         [headerFields.get() setObject:userAgent forKey:@"User-Agent"];
846
847     if ([headerFields.get() count])
848         [options.get() setObject:headerFields.get() forKey:@"AVURLAssetHTTPHeaderFieldsKey"];
849
850     if (player()->doesHaveAttribute("x-itunes-inherit-uri-query-component"))
851         [options.get() setObject: [NSNumber numberWithBool: TRUE] forKey: AVURLAssetInheritURIQueryComponentFromReferencingURIKey];
852
853 #if PLATFORM(IOS)
854     // FIXME: rdar://problem/20354688
855     String identifier = player()->sourceApplicationIdentifier();
856     if (!identifier.isEmpty() && AVURLAssetClientBundleIdentifierKey)
857         [options setObject:identifier forKey:AVURLAssetClientBundleIdentifierKey];
858 #endif
859
860 #if ENABLE(AVF_CAPTIONS)
861     const Vector<RefPtr<PlatformTextTrack>>& outOfBandTrackSources = player()->outOfBandTrackSources();
862     if (!outOfBandTrackSources.isEmpty()) {
863         RetainPtr<NSMutableArray> outOfBandTracks = adoptNS([[NSMutableArray alloc] init]);
864         for (auto& trackSource : outOfBandTrackSources) {
865             RetainPtr<CFStringRef> label = trackSource->label().createCFString();
866             RetainPtr<CFStringRef> language = trackSource->language().createCFString();
867             RetainPtr<CFStringRef> uniqueID = String::number(trackSource->uniqueId()).createCFString();
868             RetainPtr<CFStringRef> url = trackSource->url().createCFString();
869             [outOfBandTracks.get() addObject:@{
870                 AVOutOfBandAlternateTrackDisplayNameKey: reinterpret_cast<const NSString*>(label.get()),
871                 AVOutOfBandAlternateTrackExtendedLanguageTagKey: reinterpret_cast<const NSString*>(language.get()),
872                 AVOutOfBandAlternateTrackIsDefaultKey: trackSource->isDefault() ? @YES : @NO,
873                 AVOutOfBandAlternateTrackIdentifierKey: reinterpret_cast<const NSString*>(uniqueID.get()),
874                 AVOutOfBandAlternateTrackSourceKey: reinterpret_cast<const NSString*>(url.get()),
875                 AVOutOfBandAlternateTrackMediaCharactersticsKey: mediaDescriptionForKind(trackSource->kind()),
876             }];
877         }
878
879         [options.get() setObject:outOfBandTracks.get() forKey:AVURLAssetOutOfBandAlternateTracksKey];
880     }
881 #endif
882
883 #if PLATFORM(IOS)
884     String networkInterfaceName = player()->mediaPlayerNetworkInterfaceName();
885     if (!networkInterfaceName.isEmpty())
886         [options setObject:networkInterfaceName forKey:AVURLAssetBoundNetworkInterfaceName];
887 #endif
888
889 #if PLATFORM(IOS)
890     Vector<Cookie> cookies;
891     if (player()->getRawCookies(URL(ParsedURLString, url), cookies)) {
892         RetainPtr<NSMutableArray> nsCookies = adoptNS([[NSMutableArray alloc] initWithCapacity:cookies.size()]);
893         for (auto& cookie : cookies)
894             [nsCookies addObject:toNSHTTPCookie(cookie)];
895
896         [options setObject:nsCookies.get() forKey:AVURLAssetHTTPCookiesKey];
897     }
898 #endif
899
900     NSURL *cocoaURL = canonicalURL(url);
901     m_avAsset = adoptNS([allocAVURLAssetInstance() initWithURL:cocoaURL options:options.get()]);
902
903 #if HAVE(AVFOUNDATION_LOADER_DELEGATE)
904     [[m_avAsset.get() resourceLoader] setDelegate:m_loaderDelegate.get() queue:globalLoaderDelegateQueue()];
905 #endif
906
907     m_haveCheckedPlayability = false;
908
909     setDelayCallbacks(false);
910 }
911
912 void MediaPlayerPrivateAVFoundationObjC::setAVPlayerItem(AVPlayerItemType *item)
913 {
914     if (!m_avPlayer)
915         return;
916
917     if (pthread_main_np()) {
918         [m_avPlayer replaceCurrentItemWithPlayerItem:item];
919         return;
920     }
921
922     RetainPtr<AVPlayerType> strongPlayer = m_avPlayer.get();
923     RetainPtr<AVPlayerItemType> strongItem = item;
924     dispatch_async(dispatch_get_main_queue(), [strongPlayer, strongItem] {
925         [strongPlayer replaceCurrentItemWithPlayerItem:strongItem.get()];
926     });
927 }
928
929 void MediaPlayerPrivateAVFoundationObjC::createAVPlayer()
930 {
931     if (m_avPlayer)
932         return;
933
934     LOG(Media, "MediaPlayerPrivateAVFoundationObjC::createAVPlayer(%p)", this);
935
936     setDelayCallbacks(true);
937
938     m_avPlayer = adoptNS([allocAVPlayerInstance() init]);
939     for (NSString *keyName in playerKVOProperties())
940         [m_avPlayer.get() addObserver:m_objcObserver.get() forKeyPath:keyName options:NSKeyValueObservingOptionNew context:(void *)MediaPlayerAVFoundationObservationContextPlayer];
941
942 #if HAVE(AVFOUNDATION_MEDIA_SELECTION_GROUP) && HAVE(AVFOUNDATION_LEGIBLE_OUTPUT_SUPPORT)
943     [m_avPlayer.get() setAppliesMediaSelectionCriteriaAutomatically:NO];
944 #endif
945
946 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
947     updateDisableExternalPlayback();
948     [m_avPlayer.get() setAllowsExternalPlayback:m_allowsWirelessVideoPlayback];
949 #endif
950
951 #if ENABLE(WIRELESS_PLAYBACK_TARGET) && !PLATFORM(IOS)
952     if (m_shouldPlayToPlaybackTarget)
953         setShouldPlayToPlaybackTarget(true);
954 #endif
955
956     if (player()->client().mediaPlayerIsVideo())
957         createAVPlayerLayer();
958
959     if (m_avPlayerItem)
960         setAVPlayerItem(m_avPlayerItem.get());
961
962     setDelayCallbacks(false);
963 }
964
965 void MediaPlayerPrivateAVFoundationObjC::createAVPlayerItem()
966 {
967     if (m_avPlayerItem)
968         return;
969
970     LOG(Media, "MediaPlayerPrivateAVFoundationObjC::createAVPlayerItem(%p)", this);
971
972     setDelayCallbacks(true);
973
974     // Create the player item so we can load media data. 
975     m_avPlayerItem = adoptNS([allocAVPlayerItemInstance() initWithAsset:m_avAsset.get()]);
976
977     [[NSNotificationCenter defaultCenter] addObserver:m_objcObserver.get() selector:@selector(didEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:m_avPlayerItem.get()];
978
979     NSKeyValueObservingOptions options = NSKeyValueObservingOptionNew | NSKeyValueObservingOptionPrior;
980     for (NSString *keyName in itemKVOProperties())
981         [m_avPlayerItem.get() addObserver:m_objcObserver.get() forKeyPath:keyName options:options context:(void *)MediaPlayerAVFoundationObservationContextPlayerItem];
982
983     [m_avPlayerItem setAudioTimePitchAlgorithm:(player()->preservesPitch() ? AVAudioTimePitchAlgorithmSpectral : AVAudioTimePitchAlgorithmVarispeed)];
984
985     if (m_avPlayer)
986         setAVPlayerItem(m_avPlayerItem.get());
987
988 #if HAVE(AVFOUNDATION_MEDIA_SELECTION_GROUP) && HAVE(AVFOUNDATION_LEGIBLE_OUTPUT_SUPPORT)
989     const NSTimeInterval legibleOutputAdvanceInterval = 2;
990
991     RetainPtr<NSArray> subtypes = adoptNS([[NSArray alloc] initWithObjects:[NSNumber numberWithUnsignedInt:kCMSubtitleFormatType_WebVTT], nil]);
992     m_legibleOutput = adoptNS([allocAVPlayerItemLegibleOutputInstance() initWithMediaSubtypesForNativeRepresentation:subtypes.get()]);
993     [m_legibleOutput.get() setSuppressesPlayerRendering:YES];
994
995     [m_legibleOutput.get() setDelegate:m_objcObserver.get() queue:dispatch_get_main_queue()];
996     [m_legibleOutput.get() setAdvanceIntervalForDelegateInvocation:legibleOutputAdvanceInterval];
997     [m_legibleOutput.get() setTextStylingResolution:AVPlayerItemLegibleOutputTextStylingResolutionSourceAndRulesOnly];
998     [m_avPlayerItem.get() addOutput:m_legibleOutput.get()];
999 #endif
1000
1001 #if ENABLE(WEB_AUDIO) && USE(MEDIATOOLBOX)
1002     if (m_provider) {
1003         m_provider->setPlayerItem(m_avPlayerItem.get());
1004         m_provider->setAudioTrack(firstEnabledTrack(safeAVAssetTracksForAudibleMedia()));
1005     }
1006 #endif
1007
1008     setDelayCallbacks(false);
1009 }
1010
1011 void MediaPlayerPrivateAVFoundationObjC::checkPlayability()
1012 {
1013     if (m_haveCheckedPlayability)
1014         return;
1015     m_haveCheckedPlayability = true;
1016
1017     LOG(Media, "MediaPlayerPrivateAVFoundationObjC::checkPlayability(%p)", this);
1018     auto weakThis = createWeakPtr();
1019
1020     [m_avAsset.get() loadValuesAsynchronouslyForKeys:[NSArray arrayWithObject:@"playable"] completionHandler:^{
1021         callOnMainThread([weakThis] {
1022             if (weakThis)
1023                 weakThis->scheduleMainThreadNotification(MediaPlayerPrivateAVFoundation::Notification::AssetPlayabilityKnown);
1024         });
1025     }];
1026 }
1027
1028 void MediaPlayerPrivateAVFoundationObjC::beginLoadingMetadata()
1029 {
1030     LOG(Media, "MediaPlayerPrivateAVFoundationObjC::beginLoadingMetadata(%p) - requesting metadata loading", this);
1031
1032     dispatch_group_t metadataLoadingGroup = dispatch_group_create();
1033     dispatch_group_enter(metadataLoadingGroup);
1034     auto weakThis = createWeakPtr();
1035     [m_avAsset.get() loadValuesAsynchronouslyForKeys:assetMetadataKeyNames() completionHandler:^{
1036
1037         callOnMainThread([weakThis, metadataLoadingGroup] {
1038             if (weakThis && [weakThis->m_avAsset.get() statusOfValueForKey:@"tracks" error:nil] == AVKeyValueStatusLoaded) {
1039                 for (AVAssetTrack *track in [weakThis->m_avAsset.get() tracks]) {
1040                     dispatch_group_enter(metadataLoadingGroup);
1041                     [track loadValuesAsynchronouslyForKeys:assetTrackMetadataKeyNames() completionHandler:^{
1042                         dispatch_group_leave(metadataLoadingGroup);
1043                     }];
1044                 }
1045             }
1046             dispatch_group_leave(metadataLoadingGroup);
1047         });
1048     }];
1049
1050     dispatch_group_notify(metadataLoadingGroup, dispatch_get_main_queue(), ^{
1051         callOnMainThread([weakThis] {
1052             if (weakThis)
1053                 [weakThis->m_objcObserver.get() metadataLoaded];
1054         });
1055
1056         dispatch_release(metadataLoadingGroup);
1057     });
1058 }
1059
1060 MediaPlayerPrivateAVFoundation::ItemStatus MediaPlayerPrivateAVFoundationObjC::playerItemStatus() const
1061 {
1062     if (!m_avPlayerItem)
1063         return MediaPlayerPrivateAVFoundation::MediaPlayerAVPlayerItemStatusDoesNotExist;
1064
1065     if (m_cachedItemStatus == AVPlayerItemStatusUnknown)
1066         return MediaPlayerPrivateAVFoundation::MediaPlayerAVPlayerItemStatusUnknown;
1067     if (m_cachedItemStatus == AVPlayerItemStatusFailed)
1068         return MediaPlayerPrivateAVFoundation::MediaPlayerAVPlayerItemStatusFailed;
1069     if (m_cachedLikelyToKeepUp)
1070         return MediaPlayerPrivateAVFoundation::MediaPlayerAVPlayerItemStatusPlaybackLikelyToKeepUp;
1071     if (m_cachedBufferFull)
1072         return MediaPlayerPrivateAVFoundation::MediaPlayerAVPlayerItemStatusPlaybackBufferFull;
1073     if (m_cachedBufferEmpty)
1074         return MediaPlayerPrivateAVFoundation::MediaPlayerAVPlayerItemStatusPlaybackBufferEmpty;
1075
1076     return MediaPlayerPrivateAVFoundation::MediaPlayerAVPlayerItemStatusReadyToPlay;
1077 }
1078
1079 PlatformMedia MediaPlayerPrivateAVFoundationObjC::platformMedia() const
1080 {
1081     LOG(Media, "MediaPlayerPrivateAVFoundationObjC::platformMedia(%p)", this);
1082     PlatformMedia pm;
1083     pm.type = PlatformMedia::AVFoundationMediaPlayerType;
1084     pm.media.avfMediaPlayer = m_avPlayer.get();
1085     return pm;
1086 }
1087
1088 PlatformLayer* MediaPlayerPrivateAVFoundationObjC::platformLayer() const
1089 {
1090 #if PLATFORM(IOS)
1091     return m_haveBeenAskedToCreateLayer ? m_videoInlineLayer.get() : nullptr;
1092 #else
1093     return m_haveBeenAskedToCreateLayer ? m_videoLayer.get() : nullptr;
1094 #endif
1095 }
1096
1097 #if PLATFORM(IOS)
1098 void MediaPlayerPrivateAVFoundationObjC::setVideoFullscreenLayer(PlatformLayer* videoFullscreenLayer)
1099 {
1100     if (m_videoFullscreenLayer == videoFullscreenLayer)
1101         return;
1102
1103     m_videoFullscreenLayer = videoFullscreenLayer;
1104
1105     [CATransaction begin];
1106     [CATransaction setDisableActions:YES];
1107     
1108     CALayer *oldRootLayer = videoFullscreenLayer;
1109     while (oldRootLayer.superlayer)
1110         oldRootLayer = oldRootLayer.superlayer;
1111
1112     CALayer *newRootLayer = nil;
1113     
1114     if (m_videoFullscreenLayer && m_videoLayer) {
1115         [m_videoLayer setFrame:CGRectMake(0, 0, m_videoFullscreenFrame.width(), m_videoFullscreenFrame.height())];
1116         [m_videoLayer removeFromSuperlayer];
1117         [m_videoFullscreenLayer insertSublayer:m_videoLayer.get() atIndex:0];
1118         newRootLayer = m_videoFullscreenLayer.get();
1119     } else if (m_videoInlineLayer && m_videoLayer) {
1120         [m_videoLayer setFrame:[m_videoInlineLayer bounds]];
1121         [m_videoLayer removeFromSuperlayer];
1122         [m_videoInlineLayer insertSublayer:m_videoLayer.get() atIndex:0];
1123         newRootLayer = m_videoInlineLayer.get();
1124     } else if (m_videoLayer)
1125         [m_videoLayer removeFromSuperlayer];
1126
1127     while (newRootLayer.superlayer)
1128         newRootLayer = newRootLayer.superlayer;
1129
1130     if (oldRootLayer && newRootLayer && oldRootLayer != newRootLayer) {
1131         mach_port_t fencePort = 0;
1132         for (CAContext *context in [CAContext allContexts]) {
1133             if (context.layer == oldRootLayer || context.layer == newRootLayer) {
1134                 if (!fencePort)
1135                     fencePort = [context createFencePort];
1136                 else
1137                     [context setFencePort:fencePort];
1138             }
1139         }
1140         mach_port_deallocate(mach_task_self(), fencePort);
1141     }
1142     [CATransaction commit];
1143
1144     if (m_videoFullscreenLayer && m_textTrackRepresentationLayer) {
1145         syncTextTrackBounds();
1146         [m_videoFullscreenLayer addSublayer:m_textTrackRepresentationLayer.get()];
1147     }
1148
1149     updateDisableExternalPlayback();
1150 }
1151
1152 void MediaPlayerPrivateAVFoundationObjC::setVideoFullscreenFrame(FloatRect frame)
1153 {
1154     m_videoFullscreenFrame = frame;
1155     if (!m_videoFullscreenLayer)
1156         return;
1157
1158     if (m_videoLayer) {
1159         [m_videoLayer setStyle:nil]; // This enables actions, i.e. implicit animations.
1160         [CATransaction begin];
1161         [m_videoLayer setFrame:CGRectMake(0, 0, frame.width(), frame.height())];
1162         [CATransaction commit];
1163         [m_videoLayer web_disableAllActions];
1164     }
1165     syncTextTrackBounds();
1166 }
1167
1168 void MediaPlayerPrivateAVFoundationObjC::setVideoFullscreenGravity(MediaPlayer::VideoGravity gravity)
1169 {
1170     m_videoFullscreenGravity = gravity;
1171     if (!m_videoLayer)
1172         return;
1173
1174     NSString *videoGravity = AVLayerVideoGravityResizeAspect;
1175     if (gravity == MediaPlayer::VideoGravityResize)
1176         videoGravity = AVLayerVideoGravityResize;
1177     else if (gravity == MediaPlayer::VideoGravityResizeAspect)
1178         videoGravity = AVLayerVideoGravityResizeAspect;
1179     else if (gravity == MediaPlayer::VideoGravityResizeAspectFill)
1180         videoGravity = AVLayerVideoGravityResizeAspectFill;
1181     else
1182         ASSERT_NOT_REACHED();
1183
1184     [m_videoLayer setVideoGravity:videoGravity];
1185 }
1186
1187 void MediaPlayerPrivateAVFoundationObjC::setVideoFullscreenMode(MediaPlayer::VideoFullscreenMode mode)
1188 {
1189     if (m_videoLayer && [m_videoLayer respondsToSelector:@selector(setEnterOptimizedFullscreenModeEnabled:)])
1190         [m_videoLayer setEnterOptimizedFullscreenModeEnabled:(mode & MediaPlayer::VideoFullscreenModeOptimized)];
1191 }
1192
1193 NSArray *MediaPlayerPrivateAVFoundationObjC::timedMetadata() const
1194 {
1195     if (m_currentMetaData)
1196         return m_currentMetaData.get();
1197     return nil;
1198 }
1199
1200 String MediaPlayerPrivateAVFoundationObjC::accessLog() const
1201 {
1202     if (!m_avPlayerItem)
1203         return emptyString();
1204     
1205     AVPlayerItemAccessLog *log = [m_avPlayerItem.get() accessLog];
1206     RetainPtr<NSString> logString = adoptNS([[NSString alloc] initWithData:[log extendedLogData] encoding:[log extendedLogDataStringEncoding]]);
1207
1208     return logString.get();
1209 }
1210
1211 String MediaPlayerPrivateAVFoundationObjC::errorLog() const
1212 {
1213     if (!m_avPlayerItem)
1214         return emptyString();
1215
1216     AVPlayerItemErrorLog *log = [m_avPlayerItem.get() errorLog];
1217     RetainPtr<NSString> logString = adoptNS([[NSString alloc] initWithData:[log extendedLogData] encoding:[log extendedLogDataStringEncoding]]);
1218
1219     return logString.get();
1220 }
1221 #endif
1222
1223 void MediaPlayerPrivateAVFoundationObjC::platformSetVisible(bool isVisible)
1224 {
1225     [CATransaction begin];
1226     [CATransaction setDisableActions:YES];    
1227     if (m_videoLayer)
1228         [m_videoLayer.get() setHidden:!isVisible];
1229     [CATransaction commit];
1230 }
1231     
1232 void MediaPlayerPrivateAVFoundationObjC::platformPlay()
1233 {
1234     LOG(Media, "MediaPlayerPrivateAVFoundationObjC::platformPlay(%p)", this);
1235     if (!metaDataAvailable())
1236         return;
1237
1238     setDelayCallbacks(true);
1239     m_cachedRate = requestedRate();
1240     [m_avPlayer.get() setRate:requestedRate()];
1241     setDelayCallbacks(false);
1242 }
1243
1244 void MediaPlayerPrivateAVFoundationObjC::platformPause()
1245 {
1246     LOG(Media, "MediaPlayerPrivateAVFoundationObjC::platformPause(%p)", this);
1247     if (!metaDataAvailable())
1248         return;
1249
1250     setDelayCallbacks(true);
1251     m_cachedRate = 0;
1252     [m_avPlayer.get() setRate:0];
1253     setDelayCallbacks(false);
1254 }
1255
1256 MediaTime MediaPlayerPrivateAVFoundationObjC::platformDuration() const
1257 {
1258     // Do not ask the asset for duration before it has been loaded or it will fetch the
1259     // answer synchronously.
1260     if (!m_avAsset || assetStatus() < MediaPlayerAVAssetStatusLoaded)
1261         return MediaTime::invalidTime();
1262     
1263     CMTime cmDuration;
1264     
1265     // Check the AVItem if we have one and it has loaded duration, some assets never report duration.
1266     if (m_avPlayerItem && playerItemStatus() >= MediaPlayerAVPlayerItemStatusReadyToPlay)
1267         cmDuration = [m_avPlayerItem.get() duration];
1268     else
1269         cmDuration = [m_avAsset.get() duration];
1270
1271     if (CMTIME_IS_NUMERIC(cmDuration))
1272         return toMediaTime(cmDuration);
1273
1274     if (CMTIME_IS_INDEFINITE(cmDuration))
1275         return MediaTime::positiveInfiniteTime();
1276
1277     LOG(Media, "MediaPlayerPrivateAVFoundationObjC::platformDuration(%p) - invalid duration, returning %s", this, toString(MediaTime::invalidTime()).utf8().data());
1278     return MediaTime::invalidTime();
1279 }
1280
1281 MediaTime MediaPlayerPrivateAVFoundationObjC::currentMediaTime() const
1282 {
1283     if (!metaDataAvailable() || !m_avPlayerItem)
1284         return MediaTime::zeroTime();
1285
1286     CMTime itemTime = [m_avPlayerItem.get() currentTime];
1287     if (CMTIME_IS_NUMERIC(itemTime))
1288         return std::max(toMediaTime(itemTime), MediaTime::zeroTime());
1289
1290     return MediaTime::zeroTime();
1291 }
1292
1293 void MediaPlayerPrivateAVFoundationObjC::seekToTime(const MediaTime& time, const MediaTime& negativeTolerance, const MediaTime& positiveTolerance)
1294 {
1295     // setCurrentTime generates several event callbacks, update afterwards.
1296     setDelayCallbacks(true);
1297
1298     if (m_metadataTrack)
1299         m_metadataTrack->flushPartialCues();
1300
1301     CMTime cmTime = toCMTime(time);
1302     CMTime cmBefore = toCMTime(negativeTolerance);
1303     CMTime cmAfter = toCMTime(positiveTolerance);
1304
1305     auto weakThis = createWeakPtr();
1306
1307     [m_avPlayerItem.get() seekToTime:cmTime toleranceBefore:cmBefore toleranceAfter:cmAfter completionHandler:^(BOOL finished) {
1308         callOnMainThread([weakThis, finished] {
1309             auto _this = weakThis.get();
1310             if (!_this)
1311                 return;
1312
1313             _this->seekCompleted(finished);
1314         });
1315     }];
1316
1317     setDelayCallbacks(false);
1318 }
1319
1320 void MediaPlayerPrivateAVFoundationObjC::setVolume(float volume)
1321 {
1322 #if PLATFORM(IOS)
1323     UNUSED_PARAM(volume);
1324     return;
1325 #else
1326     if (!metaDataAvailable())
1327         return;
1328
1329     [m_avPlayer.get() setVolume:volume];
1330 #endif
1331 }
1332
1333 void MediaPlayerPrivateAVFoundationObjC::setClosedCaptionsVisible(bool closedCaptionsVisible)
1334 {
1335     UNUSED_PARAM(closedCaptionsVisible);
1336
1337     if (!metaDataAvailable())
1338         return;
1339
1340     LOG(Media, "MediaPlayerPrivateAVFoundationObjC::setClosedCaptionsVisible(%p) - set to %s", this, boolString(closedCaptionsVisible));
1341 }
1342
1343 void MediaPlayerPrivateAVFoundationObjC::setRateDouble(double rate)
1344 {
1345     setDelayCallbacks(true);
1346     m_cachedRate = rate;
1347     [m_avPlayer.get() setRate:rate];
1348     setDelayCallbacks(false);
1349 }
1350
1351 double MediaPlayerPrivateAVFoundationObjC::rate() const
1352 {
1353     if (!metaDataAvailable())
1354         return 0;
1355
1356     return m_cachedRate;
1357 }
1358
1359 void MediaPlayerPrivateAVFoundationObjC::setPreservesPitch(bool preservesPitch)
1360 {
1361     if (m_avPlayerItem)
1362         [m_avPlayerItem setAudioTimePitchAlgorithm:(preservesPitch ? AVAudioTimePitchAlgorithmSpectral : AVAudioTimePitchAlgorithmVarispeed)];
1363 }
1364
1365 std::unique_ptr<PlatformTimeRanges> MediaPlayerPrivateAVFoundationObjC::platformBufferedTimeRanges() const
1366 {
1367     auto timeRanges = std::make_unique<PlatformTimeRanges>();
1368
1369     if (!m_avPlayerItem)
1370         return timeRanges;
1371
1372     for (NSValue *thisRangeValue in m_cachedLoadedRanges.get()) {
1373         CMTimeRange timeRange = [thisRangeValue CMTimeRangeValue];
1374         if (CMTIMERANGE_IS_VALID(timeRange) && !CMTIMERANGE_IS_EMPTY(timeRange))
1375             timeRanges->add(toMediaTime(timeRange.start), toMediaTime(CMTimeRangeGetEnd(timeRange)));
1376     }
1377     return timeRanges;
1378 }
1379
1380 MediaTime MediaPlayerPrivateAVFoundationObjC::platformMinTimeSeekable() const
1381 {
1382     if (!m_cachedSeekableRanges || ![m_cachedSeekableRanges count])
1383         return MediaTime::zeroTime();
1384
1385     MediaTime minTimeSeekable = MediaTime::positiveInfiniteTime();
1386     bool hasValidRange = false;
1387     for (NSValue *thisRangeValue in m_cachedSeekableRanges.get()) {
1388         CMTimeRange timeRange = [thisRangeValue CMTimeRangeValue];
1389         if (!CMTIMERANGE_IS_VALID(timeRange) || CMTIMERANGE_IS_EMPTY(timeRange))
1390             continue;
1391
1392         hasValidRange = true;
1393         MediaTime startOfRange = toMediaTime(timeRange.start);
1394         if (minTimeSeekable > startOfRange)
1395             minTimeSeekable = startOfRange;
1396     }
1397     return hasValidRange ? minTimeSeekable : MediaTime::zeroTime();
1398 }
1399
1400 MediaTime MediaPlayerPrivateAVFoundationObjC::platformMaxTimeSeekable() const
1401 {
1402     if (!m_cachedSeekableRanges)
1403         m_cachedSeekableRanges = [m_avPlayerItem seekableTimeRanges];
1404
1405     MediaTime maxTimeSeekable;
1406     for (NSValue *thisRangeValue in m_cachedSeekableRanges.get()) {
1407         CMTimeRange timeRange = [thisRangeValue CMTimeRangeValue];
1408         if (!CMTIMERANGE_IS_VALID(timeRange) || CMTIMERANGE_IS_EMPTY(timeRange))
1409             continue;
1410         
1411         MediaTime endOfRange = toMediaTime(CMTimeRangeGetEnd(timeRange));
1412         if (maxTimeSeekable < endOfRange)
1413             maxTimeSeekable = endOfRange;
1414     }
1415     return maxTimeSeekable;
1416 }
1417
1418 MediaTime MediaPlayerPrivateAVFoundationObjC::platformMaxTimeLoaded() const
1419 {
1420     if (!m_cachedLoadedRanges)
1421         return MediaTime::zeroTime();
1422
1423     MediaTime maxTimeLoaded;
1424     for (NSValue *thisRangeValue in m_cachedLoadedRanges.get()) {
1425         CMTimeRange timeRange = [thisRangeValue CMTimeRangeValue];
1426         if (!CMTIMERANGE_IS_VALID(timeRange) || CMTIMERANGE_IS_EMPTY(timeRange))
1427             continue;
1428         
1429         MediaTime endOfRange = toMediaTime(CMTimeRangeGetEnd(timeRange));
1430         if (maxTimeLoaded < endOfRange)
1431             maxTimeLoaded = endOfRange;
1432     }
1433
1434     return maxTimeLoaded;   
1435 }
1436
1437 unsigned long long MediaPlayerPrivateAVFoundationObjC::totalBytes() const
1438 {
1439     if (!metaDataAvailable())
1440         return 0;
1441
1442     if (m_cachedTotalBytes)
1443         return m_cachedTotalBytes;
1444
1445     for (AVPlayerItemTrack *thisTrack in m_cachedTracks.get())
1446         m_cachedTotalBytes += [[thisTrack assetTrack] totalSampleDataLength];
1447
1448     return m_cachedTotalBytes;
1449 }
1450
1451 void MediaPlayerPrivateAVFoundationObjC::setAsset(RetainPtr<id> asset)
1452 {
1453     m_avAsset = asset;
1454 }
1455
1456 MediaPlayerPrivateAVFoundation::AssetStatus MediaPlayerPrivateAVFoundationObjC::assetStatus() const
1457 {
1458     if (!m_avAsset)
1459         return MediaPlayerAVAssetStatusDoesNotExist;
1460
1461     for (NSString *keyName in assetMetadataKeyNames()) {
1462         NSError *error = nil;
1463         AVKeyValueStatus keyStatus = [m_avAsset.get() statusOfValueForKey:keyName error:&error];
1464 #if !LOG_DISABLED
1465         if (error)
1466             LOG(Media, "MediaPlayerPrivateAVFoundation::assetStatus - statusOfValueForKey failed for %s, error = %s", [keyName UTF8String], [[error localizedDescription] UTF8String]);
1467 #endif
1468
1469         if (keyStatus < AVKeyValueStatusLoaded)
1470             return MediaPlayerAVAssetStatusLoading;// At least one key is not loaded yet.
1471         
1472         if (keyStatus == AVKeyValueStatusFailed)
1473             return MediaPlayerAVAssetStatusFailed; // At least one key could not be loaded.
1474
1475         if (keyStatus == AVKeyValueStatusCancelled)
1476             return MediaPlayerAVAssetStatusCancelled; // Loading of at least one key was cancelled.
1477     }
1478
1479     if ([[m_avAsset.get() valueForKey:@"playable"] boolValue])
1480         return MediaPlayerAVAssetStatusPlayable;
1481
1482     return MediaPlayerAVAssetStatusLoaded;
1483 }
1484
1485 long MediaPlayerPrivateAVFoundationObjC::assetErrorCode() const
1486 {
1487     if (!m_avAsset)
1488         return 0;
1489
1490     NSError *error = nil;
1491     [m_avAsset statusOfValueForKey:@"playable" error:&error];
1492     return [error code];
1493 }
1494
1495 void MediaPlayerPrivateAVFoundationObjC::paintCurrentFrameInContext(GraphicsContext* context, const FloatRect& rect)
1496 {
1497     if (!metaDataAvailable() || context->paintingDisabled())
1498         return;
1499
1500     setDelayCallbacks(true);
1501     BEGIN_BLOCK_OBJC_EXCEPTIONS;
1502
1503 #if HAVE(AVFOUNDATION_VIDEO_OUTPUT)
1504     if (videoOutputHasAvailableFrame())
1505         paintWithVideoOutput(context, rect);
1506     else
1507 #endif
1508         paintWithImageGenerator(context, rect);
1509
1510     END_BLOCK_OBJC_EXCEPTIONS;
1511     setDelayCallbacks(false);
1512
1513     m_videoFrameHasDrawn = true;
1514 }
1515
1516 void MediaPlayerPrivateAVFoundationObjC::paint(GraphicsContext* context, const FloatRect& rect)
1517 {
1518     if (!metaDataAvailable() || context->paintingDisabled())
1519         return;
1520
1521     // We can ignore the request if we are already rendering to a layer.
1522     if (currentRenderingMode() == MediaRenderingToLayer)
1523         return;
1524
1525     // paint() is best effort, so only paint if we already have an image generator or video output available.
1526     if (!hasContextRenderer())
1527         return;
1528
1529     paintCurrentFrameInContext(context, rect);
1530 }
1531
1532 void MediaPlayerPrivateAVFoundationObjC::paintWithImageGenerator(GraphicsContext* context, const FloatRect& rect)
1533 {
1534     LOG(Media, "MediaPlayerPrivateAVFoundationObjC::paintWithImageGenerator(%p)", this);
1535
1536     RetainPtr<CGImageRef> image = createImageForTimeInRect(currentTime(), rect);
1537     if (image) {
1538         GraphicsContextStateSaver stateSaver(*context);
1539         context->translate(rect.x(), rect.y() + rect.height());
1540         context->scale(FloatSize(1.0f, -1.0f));
1541         context->setImageInterpolationQuality(InterpolationLow);
1542         IntRect paintRect(IntPoint(0, 0), IntSize(rect.width(), rect.height()));
1543         CGContextDrawImage(context->platformContext(), CGRectMake(0, 0, paintRect.width(), paintRect.height()), image.get());
1544         image = 0;
1545     }
1546 }
1547
1548 static bool isUnsupportedMIMEType(const String& type)
1549 {
1550     String lowerCaseType = type.convertToASCIILowercase();
1551
1552     // AVFoundation will return non-video MIME types which it claims to support, but which we
1553     // do not support in the <video> element. Reject all non video/, audio/, and application/ types.
1554     if (!lowerCaseType.startsWith("video/") && !lowerCaseType.startsWith("audio/") && !lowerCaseType.startsWith("application/"))
1555         return true;
1556
1557     // Reject types we know AVFoundation does not support that sites commonly ask about.
1558     if (lowerCaseType == "video/webm" || lowerCaseType == "audio/webm" || lowerCaseType == "video/x-webm")
1559         return true;
1560
1561     if (lowerCaseType == "video/x-flv")
1562         return true;
1563
1564     if (lowerCaseType == "audio/ogg" || lowerCaseType == "video/ogg" || lowerCaseType == "application/ogg")
1565         return true;
1566
1567     if (lowerCaseType == "video/h264")
1568         return true;
1569
1570     return false;
1571 }
1572
1573 static const HashSet<String>& staticMIMETypeList()
1574 {
1575     static NeverDestroyed<HashSet<String>> cache = [] () {
1576         HashSet<String> types;
1577
1578         static const char* typeNames[] = {
1579             "application/vnd.apple.mpegurl",
1580             "application/x-mpegurl",
1581             "audio/3gpp",
1582             "audio/aac",
1583             "audio/aacp",
1584             "audio/aiff",
1585             "audio/basic",
1586             "audio/mp3",
1587             "audio/mp4",
1588             "audio/mpeg",
1589             "audio/mpeg3",
1590             "audio/mpegurl",
1591             "audio/mpg",
1592             "audio/wav",
1593             "audio/wave",
1594             "audio/x-aac",
1595             "audio/x-aiff",
1596             "audio/x-m4a",
1597             "audio/x-mpegurl",
1598             "audio/x-wav",
1599             "video/3gpp",
1600             "video/3gpp2",
1601             "video/mp4",
1602             "video/mpeg",
1603             "video/mpeg2",
1604             "video/mpg",
1605             "video/quicktime",
1606             "video/x-m4v",
1607             "video/x-mpeg",
1608             "video/x-mpg",
1609         };
1610         for (size_t i = 0; i < WTF_ARRAY_LENGTH(typeNames); ++i)
1611             types.add(typeNames[i]);
1612
1613         return types;
1614     }();
1615
1616     return cache;
1617 }
1618
1619 static const HashSet<String>& avfMIMETypes()
1620 {
1621     static NeverDestroyed<HashSet<String>> cache = [] () {
1622         HashSet<String> types;
1623
1624         NSArray *nsTypes = [AVURLAsset audiovisualMIMETypes];
1625         for (NSString *mimeType in nsTypes)
1626             types.add([mimeType lowercaseString]);
1627
1628         return types;
1629     }();
1630
1631     
1632     return cache;
1633 }
1634
1635 RetainPtr<CGImageRef> MediaPlayerPrivateAVFoundationObjC::createImageForTimeInRect(float time, const FloatRect& rect)
1636 {
1637     if (!m_imageGenerator)
1638         createImageGenerator();
1639     ASSERT(m_imageGenerator);
1640
1641 #if !LOG_DISABLED
1642     double start = monotonicallyIncreasingTime();
1643 #endif
1644
1645     [m_imageGenerator.get() setMaximumSize:CGSize(rect.size())];
1646     RetainPtr<CGImageRef> rawImage = adoptCF([m_imageGenerator.get() copyCGImageAtTime:CMTimeMakeWithSeconds(time, 600) actualTime:nil error:nil]);
1647     RetainPtr<CGImageRef> image = adoptCF(CGImageCreateCopyWithColorSpace(rawImage.get(), deviceRGBColorSpaceRef()));
1648
1649 #if !LOG_DISABLED
1650     double duration = monotonicallyIncreasingTime() - start;
1651     LOG(Media, "MediaPlayerPrivateAVFoundationObjC::createImageForTimeInRect(%p) - creating image took %.4f", this, narrowPrecisionToFloat(duration));
1652 #endif
1653
1654     return image;
1655 }
1656
1657 void MediaPlayerPrivateAVFoundationObjC::getSupportedTypes(HashSet<String>& supportedTypes)
1658 {
1659     supportedTypes = avfMIMETypes();
1660
1661
1662 #if ENABLE(ENCRYPTED_MEDIA) || ENABLE(ENCRYPTED_MEDIA_V2)
1663 static bool keySystemIsSupported(const String& keySystem)
1664 {
1665     if (equalIgnoringASCIICase(keySystem, "com.apple.fps") || equalIgnoringASCIICase(keySystem, "com.apple.fps.1_0") || equalIgnoringASCIICase(keySystem, "org.w3c.clearkey"))
1666         return true;
1667     return false;
1668 }
1669 #endif
1670
1671 MediaPlayer::SupportsType MediaPlayerPrivateAVFoundationObjC::supportsType(const MediaEngineSupportParameters& parameters)
1672 {
1673 #if ENABLE(ENCRYPTED_MEDIA)
1674     // From: <http://dvcs.w3.org/hg/html-media/raw-file/eme-v0.1b/encrypted-media/encrypted-media.html#dom-canplaytype>
1675     // In addition to the steps in the current specification, this method must run the following steps:
1676
1677     // 1. Check whether the Key System is supported with the specified container and codec type(s) by following the steps for the first matching condition from the following list:
1678     //    If keySystem is null, continue to the next step.
1679     if (!parameters.keySystem.isNull() && !parameters.keySystem.isEmpty()) {
1680         // "Clear Key" is only supported with HLS:
1681         if (equalIgnoringASCIICase(parameters.keySystem, "org.w3c.clearkey") && !parameters.type.isEmpty() && !equalIgnoringASCIICase(parameters.type, "application/x-mpegurl"))
1682             return MediaPlayer::IsNotSupported;
1683
1684         // If keySystem contains an unrecognized or unsupported Key System, return the empty string
1685         if (!keySystemIsSupported(parameters.keySystem))
1686             return MediaPlayer::IsNotSupported;
1687
1688         // If the Key System specified by keySystem does not support decrypting the container and/or codec specified in the rest of the type string.
1689         // (AVFoundation does not provide an API which would allow us to determine this, so this is a no-op)
1690     }
1691
1692     // 2. Return "maybe" or "probably" as appropriate per the existing specification of canPlayType().
1693 #endif
1694
1695 #if ENABLE(MEDIA_SOURCE)
1696     if (parameters.isMediaSource)
1697         return MediaPlayer::IsNotSupported;
1698 #endif
1699
1700     if (isUnsupportedMIMEType(parameters.type))
1701         return MediaPlayer::IsNotSupported;
1702
1703     if (!staticMIMETypeList().contains(parameters.type) && !avfMIMETypes().contains(parameters.type))
1704         return MediaPlayer::IsNotSupported;
1705
1706     // The spec says:
1707     // "Implementors are encouraged to return "maybe" unless the type can be confidently established as being supported or not."
1708     if (parameters.codecs.isEmpty())
1709         return MediaPlayer::MayBeSupported;
1710
1711     NSString *typeString = [NSString stringWithFormat:@"%@; codecs=\"%@\"", (NSString *)parameters.type, (NSString *)parameters.codecs];
1712     return [AVURLAsset isPlayableExtendedMIMEType:typeString] ? MediaPlayer::IsSupported : MediaPlayer::MayBeSupported;
1713 }
1714
1715 bool MediaPlayerPrivateAVFoundationObjC::supportsKeySystem(const String& keySystem, const String& mimeType)
1716 {
1717 #if ENABLE(ENCRYPTED_MEDIA) || ENABLE(ENCRYPTED_MEDIA_V2)
1718     if (!keySystem.isEmpty()) {
1719         // "Clear Key" is only supported with HLS:
1720         if (equalIgnoringASCIICase(keySystem, "org.w3c.clearkey") && !mimeType.isEmpty() && !equalIgnoringASCIICase(mimeType, "application/x-mpegurl"))
1721             return MediaPlayer::IsNotSupported;
1722
1723         if (!keySystemIsSupported(keySystem))
1724             return false;
1725
1726         if (!mimeType.isEmpty() && isUnsupportedMIMEType(mimeType))
1727             return false;
1728
1729         if (!mimeType.isEmpty() && !staticMIMETypeList().contains(mimeType) && !avfMIMETypes().contains(mimeType))
1730             return false;
1731
1732         return true;
1733     }
1734 #else
1735     UNUSED_PARAM(keySystem);
1736     UNUSED_PARAM(mimeType);
1737 #endif
1738     return false;
1739 }
1740
1741 #if HAVE(AVFOUNDATION_LOADER_DELEGATE)
1742 #if ENABLE(ENCRYPTED_MEDIA_V2)
1743 static void fulfillRequestWithKeyData(AVAssetResourceLoadingRequest *request, ArrayBuffer* keyData)
1744 {
1745     if (AVAssetResourceLoadingContentInformationRequest *infoRequest = [request contentInformationRequest]) {
1746         [infoRequest setContentLength:keyData->byteLength()];
1747         [infoRequest setByteRangeAccessSupported:YES];
1748     }
1749
1750     if (AVAssetResourceLoadingDataRequest *dataRequest = [request dataRequest]) {
1751         long long start = [dataRequest currentOffset];
1752         long long end = std::min<long long>(keyData->byteLength(), [dataRequest currentOffset] + [dataRequest requestedLength]);
1753
1754         if (start < 0 || end < 0 || start >= static_cast<long long>(keyData->byteLength())) {
1755             [request finishLoadingWithError:nil];
1756             return;
1757         }
1758
1759         ASSERT(start <= std::numeric_limits<int>::max());
1760         ASSERT(end <= std::numeric_limits<int>::max());
1761         RefPtr<ArrayBuffer> requestedKeyData = keyData->slice(static_cast<int>(start), static_cast<int>(end));
1762         RetainPtr<NSData> nsData = adoptNS([[NSData alloc] initWithBytes:requestedKeyData->data() length:requestedKeyData->byteLength()]);
1763         [dataRequest respondWithData:nsData.get()];
1764     }
1765
1766     [request finishLoading];
1767 }
1768 #endif
1769
1770 bool MediaPlayerPrivateAVFoundationObjC::shouldWaitForLoadingOfResource(AVAssetResourceLoadingRequest* avRequest)
1771 {
1772     String scheme = [[[avRequest request] URL] scheme];
1773     String keyURI = [[[avRequest request] URL] absoluteString];
1774
1775 #if ENABLE(ENCRYPTED_MEDIA) || ENABLE(ENCRYPTED_MEDIA_V2)
1776     if (scheme == "skd") {
1777         // Create an initData with the following layout:
1778         // [4 bytes: keyURI size], [keyURI size bytes: keyURI]
1779         unsigned keyURISize = keyURI.length() * sizeof(UChar);
1780         RefPtr<ArrayBuffer> initDataBuffer = ArrayBuffer::create(4 + keyURISize, 1);
1781         RefPtr<JSC::DataView> initDataView = JSC::DataView::create(initDataBuffer, 0, initDataBuffer->byteLength());
1782         initDataView->set<uint32_t>(0, keyURISize, true);
1783
1784         RefPtr<Uint16Array> keyURIArray = Uint16Array::create(initDataBuffer, 4, keyURI.length());
1785         keyURIArray->setRange(StringView(keyURI).upconvertedCharacters(), keyURI.length() / sizeof(unsigned char), 0);
1786
1787 #if ENABLE(ENCRYPTED_MEDIA)
1788         if (!player()->keyNeeded("com.apple.lskd", emptyString(), static_cast<const unsigned char*>(initDataBuffer->data()), initDataBuffer->byteLength()))
1789 #elif ENABLE(ENCRYPTED_MEDIA_V2)
1790         RefPtr<Uint8Array> initData = Uint8Array::create(initDataBuffer, 0, initDataBuffer->byteLength());
1791         if (!player()->keyNeeded(initData.get()))
1792 #endif
1793             return false;
1794
1795         m_keyURIToRequestMap.set(keyURI, avRequest);
1796         return true;
1797 #if ENABLE(ENCRYPTED_MEDIA_V2)
1798     } else if (scheme == "clearkey") {
1799         String keyID = [[[avRequest request] URL] resourceSpecifier];
1800         StringView keyIDView(keyID);
1801         CString utf8EncodedKeyId = UTF8Encoding().encode(keyIDView, URLEncodedEntitiesForUnencodables);
1802
1803         RefPtr<Uint8Array> initData = Uint8Array::create(utf8EncodedKeyId.length());
1804         initData->setRange((JSC::Uint8Adaptor::Type*)utf8EncodedKeyId.data(), utf8EncodedKeyId.length(), 0);
1805
1806         auto keyData = player()->cachedKeyForKeyId(keyID);
1807         if (keyData) {
1808             fulfillRequestWithKeyData(avRequest, keyData.get());
1809             return false;
1810         }
1811
1812         if (!player()->keyNeeded(initData.get()))
1813             return false;
1814
1815         m_keyURIToRequestMap.set(keyID, avRequest);
1816         return true;
1817 #endif
1818     }
1819 #endif
1820
1821     RefPtr<WebCoreAVFResourceLoader> resourceLoader = WebCoreAVFResourceLoader::create(this, avRequest);
1822     m_resourceLoaderMap.add(avRequest, resourceLoader);
1823     resourceLoader->startLoading();
1824     return true;
1825 }
1826
1827 bool MediaPlayerPrivateAVFoundationObjC::shouldWaitForResponseToAuthenticationChallenge(NSURLAuthenticationChallenge* nsChallenge)
1828 {
1829 #if USE(CFNETWORK)
1830     RefPtr<WebCoreNSURLAuthenticationChallengeClient> client = WebCoreNSURLAuthenticationChallengeClient::create(nsChallenge);
1831     RetainPtr<CFURLAuthChallengeRef> cfChallenge = adoptCF([nsChallenge _createCFAuthChallenge]);
1832     AuthenticationChallenge challenge(cfChallenge.get(), client.get());
1833 #else
1834     AuthenticationChallenge challenge(nsChallenge);
1835 #endif
1836
1837     return player()->shouldWaitForResponseToAuthenticationChallenge(challenge);
1838 }
1839
1840 void MediaPlayerPrivateAVFoundationObjC::didCancelLoadingRequest(AVAssetResourceLoadingRequest* avRequest)
1841 {
1842     String scheme = [[[avRequest request] URL] scheme];
1843
1844     WebCoreAVFResourceLoader* resourceLoader = m_resourceLoaderMap.get(avRequest);
1845
1846     if (resourceLoader)
1847         resourceLoader->stopLoading();
1848 }
1849
1850 void MediaPlayerPrivateAVFoundationObjC::didStopLoadingRequest(AVAssetResourceLoadingRequest *avRequest)
1851 {
1852     m_resourceLoaderMap.remove(avRequest);
1853 }
1854 #endif
1855
1856 bool MediaPlayerPrivateAVFoundationObjC::isAvailable()
1857 {
1858     return AVFoundationLibrary() && isCoreMediaFrameworkAvailable();
1859 }
1860
1861 MediaTime MediaPlayerPrivateAVFoundationObjC::mediaTimeForTimeValue(const MediaTime& timeValue) const
1862 {
1863     if (!metaDataAvailable())
1864         return timeValue;
1865
1866     // FIXME - impossible to implement until rdar://8721510 is fixed.
1867     return timeValue;
1868 }
1869
1870 double MediaPlayerPrivateAVFoundationObjC::maximumDurationToCacheMediaTime() const
1871 {
1872 #if PLATFORM(IOS) || __MAC_OS_X_VERSION_MIN_REQUIRED >= 1010
1873     return 0;
1874 #else
1875     return 5;
1876 #endif
1877 }
1878
1879 void MediaPlayerPrivateAVFoundationObjC::updateVideoLayerGravity()
1880 {
1881     if (!m_videoLayer)
1882         return;
1883
1884 #if PLATFORM(IOS)
1885     // Do not attempt to change the video gravity while in full screen mode.
1886     // See setVideoFullscreenGravity().
1887     if (m_videoFullscreenLayer)
1888         return;
1889 #endif
1890
1891     [CATransaction begin];
1892     [CATransaction setDisableActions:YES];    
1893     NSString* gravity = shouldMaintainAspectRatio() ? AVLayerVideoGravityResizeAspect : AVLayerVideoGravityResize;
1894     [m_videoLayer.get() setVideoGravity:gravity];
1895     [CATransaction commit];
1896 }
1897
1898 static AVAssetTrack* firstEnabledTrack(NSArray* tracks)
1899 {
1900     NSUInteger index = [tracks indexOfObjectPassingTest:^(id obj, NSUInteger, BOOL *) {
1901         return [static_cast<AVAssetTrack*>(obj) isEnabled];
1902     }];
1903     if (index == NSNotFound)
1904         return nil;
1905     return [tracks objectAtIndex:index];
1906 }
1907
1908 void MediaPlayerPrivateAVFoundationObjC::tracksChanged()
1909 {
1910     String primaryAudioTrackLanguage = m_languageOfPrimaryAudioTrack;
1911     m_languageOfPrimaryAudioTrack = String();
1912
1913     if (!m_avAsset)
1914         return;
1915
1916     setDelayCharacteristicsChangedNotification(true);
1917
1918     bool haveCCTrack = false;
1919     bool hasCaptions = false;
1920
1921     // This is called whenever the tracks collection changes so cache hasVideo and hasAudio since we are
1922     // asked about those fairly fequently.
1923     if (!m_avPlayerItem) {
1924         // We don't have a player item yet, so check with the asset because some assets support inspection
1925         // prior to becoming ready to play.
1926         AVAssetTrack* firstEnabledVideoTrack = firstEnabledTrack([m_avAsset.get() tracksWithMediaCharacteristic:AVMediaCharacteristicVisual]);
1927         setHasVideo(firstEnabledVideoTrack);
1928         setHasAudio(firstEnabledTrack([m_avAsset.get() tracksWithMediaCharacteristic:AVMediaCharacteristicAudible]));
1929 #if !HAVE(AVFOUNDATION_MEDIA_SELECTION_GROUP)
1930         hasCaptions = [[m_avAsset.get() tracksWithMediaType:AVMediaTypeClosedCaption] count];
1931 #endif
1932
1933         presentationSizeDidChange(firstEnabledVideoTrack ? FloatSize(CGSizeApplyAffineTransform([firstEnabledVideoTrack naturalSize], [firstEnabledVideoTrack preferredTransform])) : FloatSize());
1934     } else {
1935         bool hasVideo = false;
1936         bool hasAudio = false;
1937         bool hasMetaData = false;
1938         for (AVPlayerItemTrack *track in m_cachedTracks.get()) {
1939             if ([track isEnabled]) {
1940                 AVAssetTrack *assetTrack = [track assetTrack];
1941                 NSString *mediaType = [assetTrack mediaType];
1942                 if ([mediaType isEqualToString:AVMediaTypeVideo])
1943                     hasVideo = true;
1944                 else if ([mediaType isEqualToString:AVMediaTypeAudio])
1945                     hasAudio = true;
1946                 else if ([mediaType isEqualToString:AVMediaTypeClosedCaption]) {
1947 #if !HAVE(AVFOUNDATION_MEDIA_SELECTION_GROUP)
1948                     hasCaptions = true;
1949 #endif
1950                     haveCCTrack = true;
1951                 } else if ([mediaType isEqualToString:AVMediaTypeMetadata]) {
1952                     hasMetaData = true;
1953                 }
1954             }
1955         }
1956
1957 #if ENABLE(VIDEO_TRACK)
1958         updateAudioTracks();
1959         updateVideoTracks();
1960
1961 #if HAVE(AVFOUNDATION_MEDIA_SELECTION_GROUP)
1962         hasAudio |= (m_audibleGroup && m_audibleGroup->selectedOption());
1963         hasVideo |= (m_visualGroup && m_visualGroup->selectedOption());
1964 #endif
1965 #endif
1966
1967         // Always says we have video if the AVPlayerLayer is ready for diaplay to work around
1968         // an AVFoundation bug which causes it to sometimes claim a track is disabled even
1969         // when it is not.
1970         setHasVideo(hasVideo || m_cachedIsReadyForDisplay);
1971
1972         setHasAudio(hasAudio);
1973 #if ENABLE(DATACUE_VALUE)
1974         if (hasMetaData)
1975             processMetadataTrack();
1976 #endif
1977     }
1978
1979 #if HAVE(AVFOUNDATION_MEDIA_SELECTION_GROUP)
1980     AVMediaSelectionGroupType *legibleGroup = safeMediaSelectionGroupForLegibleMedia();
1981     if (legibleGroup && m_cachedTracks) {
1982         hasCaptions = [[AVMediaSelectionGroup playableMediaSelectionOptionsFromArray:[legibleGroup options]] count];
1983         if (hasCaptions)
1984             processMediaSelectionOptions();
1985     }
1986 #endif
1987
1988 #if !HAVE(AVFOUNDATION_LEGIBLE_OUTPUT_SUPPORT) && HAVE(AVFOUNDATION_MEDIA_SELECTION_GROUP)
1989     if (!hasCaptions && haveCCTrack)
1990         processLegacyClosedCaptionsTracks();
1991 #elif !HAVE(AVFOUNDATION_LEGIBLE_OUTPUT_SUPPORT)
1992     if (haveCCTrack)
1993         processLegacyClosedCaptionsTracks();
1994 #endif
1995
1996     setHasClosedCaptions(hasCaptions);
1997
1998     LOG(Media, "MediaPlayerPrivateAVFoundation:tracksChanged(%p) - hasVideo = %s, hasAudio = %s, hasCaptions = %s",
1999         this, boolString(hasVideo()), boolString(hasAudio()), boolString(hasClosedCaptions()));
2000
2001     sizeChanged();
2002
2003     if (primaryAudioTrackLanguage != languageOfPrimaryAudioTrack())
2004         characteristicsChanged();
2005
2006 #if ENABLE(WEB_AUDIO) && USE(MEDIATOOLBOX)
2007     if (m_provider)
2008         m_provider->setAudioTrack(firstEnabledTrack(safeAVAssetTracksForAudibleMedia()));
2009 #endif
2010
2011     setDelayCharacteristicsChangedNotification(false);
2012 }
2013
2014 #if ENABLE(VIDEO_TRACK)
2015 template <typename RefT, typename PassRefT>
2016 void determineChangedTracksFromNewTracksAndOldItems(NSArray* tracks, NSString* trackType, Vector<RefT>& oldItems, RefT (*itemFactory)(AVPlayerItemTrack*), MediaPlayer* player, void (MediaPlayer::*removedFunction)(PassRefT), void (MediaPlayer::*addedFunction)(PassRefT))
2017 {
2018     RetainPtr<NSSet> newTracks = adoptNS([[NSSet alloc] initWithArray:[tracks objectsAtIndexes:[tracks indexesOfObjectsPassingTest:^(id track, NSUInteger, BOOL*){
2019         return [[[track assetTrack] mediaType] isEqualToString:trackType];
2020     }]]]);
2021     RetainPtr<NSMutableSet> oldTracks = adoptNS([[NSMutableSet alloc] initWithCapacity:oldItems.size()]);
2022
2023     for (auto& oldItem : oldItems) {
2024         if (oldItem->playerItemTrack())
2025             [oldTracks addObject:oldItem->playerItemTrack()];
2026     }
2027
2028     // Find the added & removed AVPlayerItemTracks:
2029     RetainPtr<NSMutableSet> removedTracks = adoptNS([oldTracks mutableCopy]);
2030     [removedTracks minusSet:newTracks.get()];
2031
2032     RetainPtr<NSMutableSet> addedTracks = adoptNS([newTracks mutableCopy]);
2033     [addedTracks minusSet:oldTracks.get()];
2034
2035     typedef Vector<RefT> ItemVector;
2036     ItemVector replacementItems;
2037     ItemVector addedItems;
2038     ItemVector removedItems;
2039     for (auto& oldItem : oldItems) {
2040         if (oldItem->playerItemTrack() && [removedTracks containsObject:oldItem->playerItemTrack()])
2041             removedItems.append(oldItem);
2042         else
2043             replacementItems.append(oldItem);
2044     }
2045
2046     for (AVPlayerItemTrack* track in addedTracks.get())
2047         addedItems.append(itemFactory(track));
2048
2049     replacementItems.appendVector(addedItems);
2050     oldItems.swap(replacementItems);
2051
2052     for (auto& removedItem : removedItems)
2053         (player->*removedFunction)(removedItem);
2054
2055     for (auto& addedItem : addedItems)
2056         (player->*addedFunction)(addedItem);
2057 }
2058
2059 #if HAVE(AVFOUNDATION_MEDIA_SELECTION_GROUP)
2060 template <typename RefT, typename PassRefT>
2061 void determineChangedTracksFromNewTracksAndOldItems(MediaSelectionGroupAVFObjC* group, Vector<RefT>& oldItems, const Vector<String>& characteristics, RefT (*itemFactory)(MediaSelectionOptionAVFObjC&), MediaPlayer* player, void (MediaPlayer::*removedFunction)(PassRefT), void (MediaPlayer::*addedFunction)(PassRefT))
2062 {
2063     group->updateOptions(characteristics);
2064
2065     // Only add selection options which do not have an associated persistant track.
2066     ListHashSet<RefPtr<MediaSelectionOptionAVFObjC>> newSelectionOptions;
2067     for (auto& option : group->options()) {
2068         if (!option)
2069             continue;
2070         AVMediaSelectionOptionType* avOption = option->avMediaSelectionOption();
2071         if (!avOption)
2072             continue;
2073         if (![avOption respondsToSelector:@selector(track)] || ![avOption performSelector:@selector(track)])
2074             newSelectionOptions.add(option);
2075     }
2076
2077     ListHashSet<RefPtr<MediaSelectionOptionAVFObjC>> oldSelectionOptions;
2078     for (auto& oldItem : oldItems) {
2079         if (MediaSelectionOptionAVFObjC *option = oldItem->mediaSelectionOption())
2080             oldSelectionOptions.add(option);
2081     }
2082
2083     // Find the added & removed AVMediaSelectionOptions:
2084     ListHashSet<RefPtr<MediaSelectionOptionAVFObjC>> removedSelectionOptions;
2085     for (auto& oldOption : oldSelectionOptions) {
2086         if (!newSelectionOptions.contains(oldOption))
2087             removedSelectionOptions.add(oldOption);
2088     }
2089
2090     ListHashSet<RefPtr<MediaSelectionOptionAVFObjC>> addedSelectionOptions;
2091     for (auto& newOption : newSelectionOptions) {
2092         if (!oldSelectionOptions.contains(newOption))
2093             addedSelectionOptions.add(newOption);
2094     }
2095
2096     typedef Vector<RefT> ItemVector;
2097     ItemVector replacementItems;
2098     ItemVector addedItems;
2099     ItemVector removedItems;
2100     for (auto& oldItem : oldItems) {
2101         if (oldItem->mediaSelectionOption() && removedSelectionOptions.contains(oldItem->mediaSelectionOption()))
2102             removedItems.append(oldItem);
2103         else
2104             replacementItems.append(oldItem);
2105     }
2106
2107     for (auto& option : addedSelectionOptions)
2108         addedItems.append(itemFactory(*option.get()));
2109
2110     replacementItems.appendVector(addedItems);
2111     oldItems.swap(replacementItems);
2112     
2113     for (auto& removedItem : removedItems)
2114         (player->*removedFunction)(removedItem);
2115     
2116     for (auto& addedItem : addedItems)
2117         (player->*addedFunction)(addedItem);
2118 }
2119 #endif
2120
2121 void MediaPlayerPrivateAVFoundationObjC::updateAudioTracks()
2122 {
2123 #if !LOG_DISABLED
2124     size_t count = m_audioTracks.size();
2125 #endif
2126
2127     determineChangedTracksFromNewTracksAndOldItems(m_cachedTracks.get(), AVMediaTypeAudio, m_audioTracks, &AudioTrackPrivateAVFObjC::create, player(), &MediaPlayer::removeAudioTrack, &MediaPlayer::addAudioTrack);
2128
2129 #if HAVE(AVFOUNDATION_MEDIA_SELECTION_GROUP)
2130     Vector<String> characteristics = player()->preferredAudioCharacteristics();
2131     if (!m_audibleGroup) {
2132         if (AVMediaSelectionGroupType *group = safeMediaSelectionGroupForAudibleMedia())
2133             m_audibleGroup = MediaSelectionGroupAVFObjC::create(m_avPlayerItem.get(), group, characteristics);
2134     }
2135
2136     if (m_audibleGroup)
2137         determineChangedTracksFromNewTracksAndOldItems(m_audibleGroup.get(), m_audioTracks, characteristics, &AudioTrackPrivateAVFObjC::create, player(), &MediaPlayer::removeAudioTrack, &MediaPlayer::addAudioTrack);
2138 #endif
2139
2140     for (auto& track : m_audioTracks)
2141         track->resetPropertiesFromTrack();
2142
2143 #if !LOG_DISABLED
2144     LOG(Media, "MediaPlayerPrivateAVFoundationObjC::updateAudioTracks(%p) - audio track count was %lu, is %lu", this, count, m_audioTracks.size());
2145 #endif
2146 }
2147
2148 void MediaPlayerPrivateAVFoundationObjC::updateVideoTracks()
2149 {
2150 #if !LOG_DISABLED
2151     size_t count = m_videoTracks.size();
2152 #endif
2153
2154     determineChangedTracksFromNewTracksAndOldItems(m_cachedTracks.get(), AVMediaTypeVideo, m_videoTracks, &VideoTrackPrivateAVFObjC::create, player(), &MediaPlayer::removeVideoTrack, &MediaPlayer::addVideoTrack);
2155
2156 #if HAVE(AVFOUNDATION_MEDIA_SELECTION_GROUP)
2157     if (!m_visualGroup) {
2158         if (AVMediaSelectionGroupType *group = safeMediaSelectionGroupForVisualMedia())
2159             m_visualGroup = MediaSelectionGroupAVFObjC::create(m_avPlayerItem.get(), group, Vector<String>());
2160     }
2161
2162     if (m_visualGroup)
2163         determineChangedTracksFromNewTracksAndOldItems(m_visualGroup.get(), m_videoTracks, Vector<String>(), &VideoTrackPrivateAVFObjC::create, player(), &MediaPlayer::removeVideoTrack, &MediaPlayer::addVideoTrack);
2164 #endif
2165
2166     for (auto& track : m_audioTracks)
2167         track->resetPropertiesFromTrack();
2168
2169 #if !LOG_DISABLED
2170     LOG(Media, "MediaPlayerPrivateAVFoundationObjC::updateVideoTracks(%p) - video track count was %lu, is %lu", this, count, m_videoTracks.size());
2171 #endif
2172 }
2173
2174 bool MediaPlayerPrivateAVFoundationObjC::requiresTextTrackRepresentation() const
2175 {
2176 #if PLATFORM(IOS)
2177     if (m_videoFullscreenLayer)
2178         return true;
2179 #endif
2180     return false;
2181 }
2182
2183 void MediaPlayerPrivateAVFoundationObjC::syncTextTrackBounds()
2184 {
2185 #if PLATFORM(IOS)
2186     if (!m_videoFullscreenLayer || !m_textTrackRepresentationLayer)
2187         return;
2188     
2189     CGRect textFrame = m_videoLayer ? [m_videoLayer videoRect] : CGRectMake(0, 0, m_videoFullscreenFrame.width(), m_videoFullscreenFrame.height());
2190     [m_textTrackRepresentationLayer setFrame:textFrame];
2191 #endif
2192 }
2193
2194 void MediaPlayerPrivateAVFoundationObjC::setTextTrackRepresentation(TextTrackRepresentation* representation)
2195 {
2196 #if PLATFORM(IOS)
2197     PlatformLayer* representationLayer = representation ? representation->platformLayer() : nil;
2198     if (representationLayer == m_textTrackRepresentationLayer) {
2199         syncTextTrackBounds();
2200         return;
2201     }
2202
2203     if (m_textTrackRepresentationLayer)
2204         [m_textTrackRepresentationLayer removeFromSuperlayer];
2205
2206     m_textTrackRepresentationLayer = representationLayer;
2207
2208     if (m_videoFullscreenLayer && m_textTrackRepresentationLayer) {
2209         syncTextTrackBounds();
2210         [m_videoFullscreenLayer addSublayer:m_textTrackRepresentationLayer.get()];
2211     }
2212
2213 #else
2214     UNUSED_PARAM(representation);
2215 #endif
2216 }
2217 #endif // ENABLE(VIDEO_TRACK)
2218
2219 #if ENABLE(WEB_AUDIO) && USE(MEDIATOOLBOX)
2220 AudioSourceProvider* MediaPlayerPrivateAVFoundationObjC::audioSourceProvider()
2221 {
2222     if (!m_provider) {
2223         m_provider = AudioSourceProviderAVFObjC::create(m_avPlayerItem.get());
2224         m_provider->setAudioTrack(firstEnabledTrack(safeAVAssetTracksForAudibleMedia()));
2225     }
2226
2227     return m_provider.get();
2228 }
2229 #endif
2230
2231 void MediaPlayerPrivateAVFoundationObjC::sizeChanged()
2232 {
2233     if (!m_avAsset)
2234         return;
2235
2236     setNaturalSize(m_cachedPresentationSize);
2237 }
2238     
2239 bool MediaPlayerPrivateAVFoundationObjC::hasSingleSecurityOrigin() const 
2240 {
2241     if (!m_avAsset || [m_avAsset statusOfValueForKey:@"resolvedURL" error:nullptr] != AVKeyValueStatusLoaded)
2242         return false;
2243     
2244     Ref<SecurityOrigin> resolvedOrigin(SecurityOrigin::create(resolvedURL()));
2245     Ref<SecurityOrigin> requestedOrigin(SecurityOrigin::createFromString(assetURL()));
2246     return resolvedOrigin.get().isSameSchemeHostPort(&requestedOrigin.get());
2247 }
2248
2249 #if HAVE(AVFOUNDATION_VIDEO_OUTPUT)
2250 void MediaPlayerPrivateAVFoundationObjC::createVideoOutput()
2251 {
2252     LOG(Media, "MediaPlayerPrivateAVFoundationObjC::createVideoOutput(%p)", this);
2253
2254     if (!m_avPlayerItem || m_videoOutput)
2255         return;
2256
2257 #if USE(VIDEOTOOLBOX) && (!defined(__MAC_OS_X_VERSION_MIN_REQUIRED) || __MAC_OS_X_VERSION_MIN_REQUIRED >= 101000)
2258     NSDictionary* attributes = nil;
2259 #else
2260     NSDictionary* attributes = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithUnsignedInt:kCVPixelFormatType_32BGRA], kCVPixelBufferPixelFormatTypeKey,
2261                                 nil];
2262 #endif
2263     m_videoOutput = adoptNS([allocAVPlayerItemVideoOutputInstance() initWithPixelBufferAttributes:attributes]);
2264     ASSERT(m_videoOutput);
2265
2266     [m_videoOutput setDelegate:m_videoOutputDelegate.get() queue:globalPullDelegateQueue()];
2267
2268     [m_avPlayerItem.get() addOutput:m_videoOutput.get()];
2269
2270 #if USE(VIDEOTOOLBOX) && (!defined(__MAC_OS_X_VERSION_MIN_REQUIRED) || __MAC_OS_X_VERSION_MIN_REQUIRED < 101000)
2271     waitForVideoOutputMediaDataWillChange();
2272 #endif
2273
2274     LOG(Media, "MediaPlayerPrivateAVFoundationObjC::createVideoOutput(%p) - returning %p", this, m_videoOutput.get());
2275 }
2276
2277 void MediaPlayerPrivateAVFoundationObjC::destroyVideoOutput()
2278 {
2279     if (!m_videoOutput)
2280         return;
2281
2282     if (m_avPlayerItem)
2283         [m_avPlayerItem.get() removeOutput:m_videoOutput.get()];
2284     LOG(Media, "MediaPlayerPrivateAVFoundationObjC::destroyVideoOutput(%p) - destroying  %p", this, m_videoOutput.get());
2285
2286     m_videoOutput = 0;
2287 }
2288
2289 RetainPtr<CVPixelBufferRef> MediaPlayerPrivateAVFoundationObjC::createPixelBuffer()
2290 {
2291     if (!m_videoOutput)
2292         createVideoOutput();
2293     ASSERT(m_videoOutput);
2294
2295 #if !LOG_DISABLED
2296     double start = monotonicallyIncreasingTime();
2297 #endif
2298
2299     CMTime currentTime = [m_avPlayerItem.get() currentTime];
2300
2301     if (![m_videoOutput.get() hasNewPixelBufferForItemTime:currentTime])
2302         return 0;
2303
2304     RetainPtr<CVPixelBufferRef> buffer = adoptCF([m_videoOutput.get() copyPixelBufferForItemTime:currentTime itemTimeForDisplay:nil]);
2305     if (!buffer)
2306         return 0;
2307
2308 #if USE(VIDEOTOOLBOX)
2309     // Create a VTPixelTransferSession, if necessary, as we cannot guarantee timely delivery of ARGB pixels.
2310     if (!m_pixelTransferSession) {
2311         VTPixelTransferSessionRef session = 0;
2312         VTPixelTransferSessionCreate(kCFAllocatorDefault, &session);
2313         m_pixelTransferSession = adoptCF(session);
2314     }
2315
2316     CVPixelBufferRef outputBuffer;
2317     CVPixelBufferCreate(kCFAllocatorDefault, CVPixelBufferGetWidth(buffer.get()), CVPixelBufferGetHeight(buffer.get()), kCVPixelFormatType_32BGRA, 0, &outputBuffer);
2318     VTPixelTransferSessionTransferImage(m_pixelTransferSession.get(), buffer.get(), outputBuffer);
2319     buffer = adoptCF(outputBuffer);
2320 #endif
2321
2322 #if !LOG_DISABLED
2323     double duration = monotonicallyIncreasingTime() - start;
2324     LOG(Media, "MediaPlayerPrivateAVFoundationObjC::createPixelBuffer(%p) - creating buffer took %.4f", this, narrowPrecisionToFloat(duration));
2325 #endif
2326
2327     return buffer;
2328 }
2329
2330 bool MediaPlayerPrivateAVFoundationObjC::videoOutputHasAvailableFrame()
2331 {
2332     if (!m_avPlayerItem)
2333         return false;
2334
2335     if (m_lastImage)
2336         return true;
2337
2338     if (!m_videoOutput)
2339         createVideoOutput();
2340
2341     return [m_videoOutput hasNewPixelBufferForItemTime:[m_avPlayerItem currentTime]];
2342 }
2343
2344 static const void* CVPixelBufferGetBytePointerCallback(void* info)
2345 {
2346     CVPixelBufferRef pixelBuffer = static_cast<CVPixelBufferRef>(info);
2347     CVPixelBufferLockBaseAddress(pixelBuffer, kCVPixelBufferLock_ReadOnly);
2348     return CVPixelBufferGetBaseAddress(pixelBuffer);
2349 }
2350
2351 static void CVPixelBufferReleaseBytePointerCallback(void* info, const void*)
2352 {
2353     CVPixelBufferRef pixelBuffer = static_cast<CVPixelBufferRef>(info);
2354     CVPixelBufferUnlockBaseAddress(pixelBuffer, kCVPixelBufferLock_ReadOnly);
2355 }
2356
2357 static void CVPixelBufferReleaseInfoCallback(void* info)
2358 {
2359     CVPixelBufferRef pixelBuffer = static_cast<CVPixelBufferRef>(info);
2360     CFRelease(pixelBuffer);
2361 }
2362
2363 static RetainPtr<CGImageRef> createImageFromPixelBuffer(CVPixelBufferRef pixelBuffer)
2364 {
2365     // pixelBuffer will be of type kCVPixelFormatType_32BGRA.
2366     ASSERT(CVPixelBufferGetPixelFormatType(pixelBuffer) == kCVPixelFormatType_32BGRA);
2367
2368     size_t width = CVPixelBufferGetWidth(pixelBuffer);
2369     size_t height = CVPixelBufferGetHeight(pixelBuffer);
2370     size_t bytesPerRow = CVPixelBufferGetBytesPerRow(pixelBuffer);
2371     size_t byteLength = CVPixelBufferGetDataSize(pixelBuffer);
2372     CGBitmapInfo bitmapInfo = kCGBitmapByteOrder32Little | kCGImageAlphaFirst;
2373
2374     CFRetain(pixelBuffer); // Balanced by CVPixelBufferReleaseInfoCallback in providerCallbacks.
2375     CGDataProviderDirectCallbacks providerCallbacks = { 0, CVPixelBufferGetBytePointerCallback, CVPixelBufferReleaseBytePointerCallback, 0, CVPixelBufferReleaseInfoCallback };
2376     RetainPtr<CGDataProviderRef> provider = adoptCF(CGDataProviderCreateDirect(pixelBuffer, byteLength, &providerCallbacks));
2377
2378     return adoptCF(CGImageCreate(width, height, 8, 32, bytesPerRow, deviceRGBColorSpaceRef(), bitmapInfo, provider.get(), NULL, false, kCGRenderingIntentDefault));
2379 }
2380
2381 void MediaPlayerPrivateAVFoundationObjC::updateLastImage()
2382 {
2383     RetainPtr<CVPixelBufferRef> pixelBuffer = createPixelBuffer();
2384
2385     // Calls to copyPixelBufferForItemTime:itemTimeForDisplay: may return nil if the pixel buffer
2386     // for the requested time has already been retrieved. In this case, the last valid image (if any)
2387     // should be displayed.
2388     if (pixelBuffer)
2389         m_lastImage = createImageFromPixelBuffer(pixelBuffer.get());
2390 }
2391
2392 void MediaPlayerPrivateAVFoundationObjC::paintWithVideoOutput(GraphicsContext* context, const FloatRect& outputRect)
2393 {
2394 #if (!defined(__MAC_OS_X_VERSION_MIN_REQUIRED) || __MAC_OS_X_VERSION_MIN_REQUIRED >= 101000)
2395     if (m_videoOutput && !m_lastImage && !videoOutputHasAvailableFrame())
2396         waitForVideoOutputMediaDataWillChange();
2397 #endif
2398
2399     updateLastImage();
2400
2401     if (!m_lastImage)
2402         return;
2403
2404     AVAssetTrack* firstEnabledVideoTrack = firstEnabledTrack([m_avAsset.get() tracksWithMediaCharacteristic:AVMediaCharacteristicVisual]);
2405     if (!firstEnabledVideoTrack)
2406         return;
2407
2408     LOG(Media, "MediaPlayerPrivateAVFoundationObjC::paintWithVideoOutput(%p)", this);
2409
2410     GraphicsContextStateSaver stateSaver(*context);
2411     FloatRect imageRect(0, 0, CGImageGetWidth(m_lastImage.get()), CGImageGetHeight(m_lastImage.get()));
2412     AffineTransform videoTransform = [firstEnabledVideoTrack preferredTransform];
2413     FloatRect transformedOutputRect = videoTransform.inverse().mapRect(outputRect);
2414
2415     context->concatCTM(videoTransform);
2416     context->drawNativeImage(m_lastImage.get(), imageRect.size(), ColorSpaceDeviceRGB, transformedOutputRect, imageRect);
2417
2418     // If we have created an AVAssetImageGenerator in the past due to m_videoOutput not having an available
2419     // video frame, destroy it now that it is no longer needed.
2420     if (m_imageGenerator)
2421         destroyImageGenerator();
2422
2423 }
2424
2425 PassNativeImagePtr MediaPlayerPrivateAVFoundationObjC::nativeImageForCurrentTime()
2426 {
2427     updateLastImage();
2428     return m_lastImage.get();
2429 }
2430
2431 void MediaPlayerPrivateAVFoundationObjC::waitForVideoOutputMediaDataWillChange()
2432 {
2433     if (!m_videoOutputSemaphore)
2434         m_videoOutputSemaphore = dispatch_semaphore_create(0);
2435
2436     [m_videoOutput requestNotificationOfMediaDataChangeWithAdvanceInterval:0];
2437
2438     // Wait for 1 second.
2439     long result = dispatch_semaphore_wait(m_videoOutputSemaphore, dispatch_time(0, 1 * NSEC_PER_SEC));
2440
2441     if (result)
2442         LOG(Media, "MediaPlayerPrivateAVFoundationObjC::waitForVideoOutputMediaDataWillChange(%p) timed out", this);
2443 }
2444
2445 void MediaPlayerPrivateAVFoundationObjC::outputMediaDataWillChange(AVPlayerItemVideoOutput*)
2446 {
2447     dispatch_semaphore_signal(m_videoOutputSemaphore);
2448 }
2449 #endif
2450
2451 #if ENABLE(ENCRYPTED_MEDIA)
2452 MediaPlayer::MediaKeyException MediaPlayerPrivateAVFoundationObjC::generateKeyRequest(const String& keySystem, const unsigned char* initDataPtr, unsigned initDataLength)
2453 {
2454     if (!keySystemIsSupported(keySystem))
2455         return MediaPlayer::KeySystemNotSupported;
2456
2457     RefPtr<Uint8Array> initData = Uint8Array::create(initDataPtr, initDataLength);
2458     String keyURI;
2459     String keyID;
2460     RefPtr<Uint8Array> certificate;
2461     if (!extractKeyURIKeyIDAndCertificateFromInitData(initData.get(), keyURI, keyID, certificate))
2462         return MediaPlayer::InvalidPlayerState;
2463
2464     if (!m_keyURIToRequestMap.contains(keyURI))
2465         return MediaPlayer::InvalidPlayerState;
2466
2467     String sessionID = createCanonicalUUIDString();
2468
2469     RetainPtr<AVAssetResourceLoadingRequest> avRequest = m_keyURIToRequestMap.get(keyURI);
2470
2471     RetainPtr<NSData> certificateData = adoptNS([[NSData alloc] initWithBytes:certificate->baseAddress() length:certificate->byteLength()]);
2472     NSString* assetStr = keyID;
2473     RetainPtr<NSData> assetID = [NSData dataWithBytes: [assetStr cStringUsingEncoding:NSUTF8StringEncoding] length:[assetStr lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
2474     NSError* error = 0;
2475     RetainPtr<NSData> keyRequest = [avRequest.get() streamingContentKeyRequestDataForApp:certificateData.get() contentIdentifier:assetID.get() options:nil error:&error];
2476
2477     if (!keyRequest) {
2478         NSError* underlyingError = [[error userInfo] objectForKey:NSUnderlyingErrorKey];
2479         player()->keyError(keySystem, sessionID, MediaPlayerClient::DomainError, [underlyingError code]);
2480         return MediaPlayer::NoError;
2481     }
2482
2483     RefPtr<ArrayBuffer> keyRequestBuffer = ArrayBuffer::create([keyRequest.get() bytes], [keyRequest.get() length]);
2484     RefPtr<Uint8Array> keyRequestArray = Uint8Array::create(keyRequestBuffer, 0, keyRequestBuffer->byteLength());
2485     player()->keyMessage(keySystem, sessionID, keyRequestArray->data(), keyRequestArray->byteLength(), URL());
2486
2487     // Move ownership of the AVAssetResourceLoadingRequestfrom the keyIDToRequestMap to the sessionIDToRequestMap:
2488     m_sessionIDToRequestMap.set(sessionID, avRequest);
2489     m_keyURIToRequestMap.remove(keyURI);
2490
2491     return MediaPlayer::NoError;
2492 }
2493
2494 MediaPlayer::MediaKeyException MediaPlayerPrivateAVFoundationObjC::addKey(const String& keySystem, const unsigned char* keyPtr, unsigned keyLength, const unsigned char* initDataPtr, unsigned initDataLength, const String& sessionID)
2495 {
2496     if (!keySystemIsSupported(keySystem))
2497         return MediaPlayer::KeySystemNotSupported;
2498
2499     if (!m_sessionIDToRequestMap.contains(sessionID))
2500         return MediaPlayer::InvalidPlayerState;
2501
2502     RetainPtr<AVAssetResourceLoadingRequest> avRequest = m_sessionIDToRequestMap.get(sessionID);
2503     RetainPtr<NSData> keyData = adoptNS([[NSData alloc] initWithBytes:keyPtr length:keyLength]);
2504     [[avRequest.get() dataRequest] respondWithData:keyData.get()];
2505     [avRequest.get() finishLoading];
2506     m_sessionIDToRequestMap.remove(sessionID);
2507
2508     player()->keyAdded(keySystem, sessionID);
2509
2510     UNUSED_PARAM(initDataPtr);
2511     UNUSED_PARAM(initDataLength);
2512     return MediaPlayer::NoError;
2513 }
2514
2515 MediaPlayer::MediaKeyException MediaPlayerPrivateAVFoundationObjC::cancelKeyRequest(const String& keySystem, const String& sessionID)
2516 {
2517     if (!keySystemIsSupported(keySystem))
2518         return MediaPlayer::KeySystemNotSupported;
2519
2520     if (!m_sessionIDToRequestMap.contains(sessionID))
2521         return MediaPlayer::InvalidPlayerState;
2522
2523     m_sessionIDToRequestMap.remove(sessionID);
2524     return MediaPlayer::NoError;
2525 }
2526 #endif
2527
2528 #if ENABLE(ENCRYPTED_MEDIA_V2)
2529 RetainPtr<AVAssetResourceLoadingRequest> MediaPlayerPrivateAVFoundationObjC::takeRequestForKeyURI(const String& keyURI)
2530 {
2531     return m_keyURIToRequestMap.take(keyURI);
2532 }
2533
2534 void MediaPlayerPrivateAVFoundationObjC::keyAdded()
2535 {
2536     Vector<String> fulfilledKeyIds;
2537
2538     for (auto& pair : m_keyURIToRequestMap) {
2539         const String& keyId = pair.key;
2540         const RetainPtr<AVAssetResourceLoadingRequest>& request = pair.value;
2541
2542         auto keyData = player()->cachedKeyForKeyId(keyId);
2543         if (!keyData)
2544             continue;
2545
2546         fulfillRequestWithKeyData(request.get(), keyData.get());
2547         fulfilledKeyIds.append(keyId);
2548     }
2549
2550     for (auto& keyId : fulfilledKeyIds)
2551         m_keyURIToRequestMap.remove(keyId);
2552 }
2553
2554 std::unique_ptr<CDMSession> MediaPlayerPrivateAVFoundationObjC::createSession(const String& keySystem)
2555 {
2556     if (!keySystemIsSupported(keySystem))
2557         return nullptr;
2558
2559     return std::make_unique<CDMSessionAVFoundationObjC>(this);
2560 }
2561 #endif
2562
2563 #if !HAVE(AVFOUNDATION_LEGIBLE_OUTPUT_SUPPORT)
2564 void MediaPlayerPrivateAVFoundationObjC::processLegacyClosedCaptionsTracks()
2565 {
2566 #if HAVE(AVFOUNDATION_MEDIA_SELECTION_GROUP)
2567     [m_avPlayerItem.get() selectMediaOption:nil inMediaSelectionGroup:safeMediaSelectionGroupForLegibleMedia()];
2568 #endif
2569
2570     Vector<RefPtr<InbandTextTrackPrivateAVF>> removedTextTracks = m_textTracks;
2571     for (AVPlayerItemTrack *playerItemTrack in m_cachedTracks.get()) {
2572
2573         AVAssetTrack *assetTrack = [playerItemTrack assetTrack];
2574         if (![[assetTrack mediaType] isEqualToString:AVMediaTypeClosedCaption])
2575             continue;
2576
2577         bool newCCTrack = true;
2578         for (unsigned i = removedTextTracks.size(); i > 0; --i) {
2579             if (removedTextTracks[i - 1]->textTrackCategory() != InbandTextTrackPrivateAVF::LegacyClosedCaption)
2580                 continue;
2581
2582             RefPtr<InbandTextTrackPrivateLegacyAVFObjC> track = static_cast<InbandTextTrackPrivateLegacyAVFObjC*>(m_textTracks[i - 1].get());
2583             if (track->avPlayerItemTrack() == playerItemTrack) {
2584                 removedTextTracks.remove(i - 1);
2585                 newCCTrack = false;
2586                 break;
2587             }
2588         }
2589
2590         if (!newCCTrack)
2591             continue;
2592         
2593         m_textTracks.append(InbandTextTrackPrivateLegacyAVFObjC::create(this, playerItemTrack));
2594     }
2595
2596     processNewAndRemovedTextTracks(removedTextTracks);
2597 }
2598 #endif
2599
2600 NSArray* MediaPlayerPrivateAVFoundationObjC::safeAVAssetTracksForAudibleMedia()
2601 {
2602     if (!m_avAsset)
2603         return nil;
2604
2605     if ([m_avAsset.get() statusOfValueForKey:@"tracks" error:NULL] != AVKeyValueStatusLoaded)
2606         return nil;
2607
2608     return [m_avAsset tracksWithMediaCharacteristic:AVMediaCharacteristicAudible];
2609 }
2610
2611 #if HAVE(AVFOUNDATION_MEDIA_SELECTION_GROUP)
2612 bool MediaPlayerPrivateAVFoundationObjC::hasLoadedMediaSelectionGroups()
2613 {
2614     if (!m_avAsset)
2615         return false;
2616
2617     if ([m_avAsset.get() statusOfValueForKey:@"availableMediaCharacteristicsWithMediaSelectionOptions" error:NULL] != AVKeyValueStatusLoaded)
2618         return false;
2619
2620     return true;
2621 }
2622
2623 AVMediaSelectionGroupType* MediaPlayerPrivateAVFoundationObjC::safeMediaSelectionGroupForLegibleMedia()
2624 {
2625     if (!hasLoadedMediaSelectionGroups())
2626         return nil;
2627
2628     return [m_avAsset.get() mediaSelectionGroupForMediaCharacteristic:AVMediaCharacteristicLegible];
2629 }
2630
2631 AVMediaSelectionGroupType* MediaPlayerPrivateAVFoundationObjC::safeMediaSelectionGroupForAudibleMedia()
2632 {
2633     if (!hasLoadedMediaSelectionGroups())
2634         return nil;
2635
2636     return [m_avAsset.get() mediaSelectionGroupForMediaCharacteristic:AVMediaCharacteristicAudible];
2637 }
2638
2639 AVMediaSelectionGroupType* MediaPlayerPrivateAVFoundationObjC::safeMediaSelectionGroupForVisualMedia()
2640 {
2641     if (!hasLoadedMediaSelectionGroups())
2642         return nil;
2643
2644     return [m_avAsset.get() mediaSelectionGroupForMediaCharacteristic:AVMediaCharacteristicVisual];
2645 }
2646
2647 void MediaPlayerPrivateAVFoundationObjC::processMediaSelectionOptions()
2648 {
2649     AVMediaSelectionGroupType *legibleGroup = safeMediaSelectionGroupForLegibleMedia();
2650     if (!legibleGroup) {
2651         LOG(Media, "MediaPlayerPrivateAVFoundationObjC::processMediaSelectionOptions(%p) - nil mediaSelectionGroup", this);
2652         return;
2653     }
2654
2655     // We enabled automatic media selection because we want alternate audio tracks to be enabled/disabled automatically,
2656     // but set the selected legible track to nil so text tracks will not be automatically configured.
2657     if (!m_textTracks.size())
2658         [m_avPlayerItem.get() selectMediaOption:nil inMediaSelectionGroup:safeMediaSelectionGroupForLegibleMedia()];
2659
2660     Vector<RefPtr<InbandTextTrackPrivateAVF>> removedTextTracks = m_textTracks;
2661     NSArray *legibleOptions = [AVMediaSelectionGroup playableMediaSelectionOptionsFromArray:[legibleGroup options]];
2662     for (AVMediaSelectionOptionType *option in legibleOptions) {
2663         bool newTrack = true;
2664         for (unsigned i = removedTextTracks.size(); i > 0; --i) {
2665             if (removedTextTracks[i - 1]->textTrackCategory() == InbandTextTrackPrivateAVF::LegacyClosedCaption)
2666                 continue;
2667             
2668             RetainPtr<AVMediaSelectionOptionType> currentOption;
2669 #if ENABLE(AVF_CAPTIONS)
2670             if (removedTextTracks[i - 1]->textTrackCategory() == InbandTextTrackPrivateAVF::OutOfBand) {
2671                 RefPtr<OutOfBandTextTrackPrivateAVF> track = static_cast<OutOfBandTextTrackPrivateAVF*>(removedTextTracks[i - 1].get());
2672                 currentOption = track->mediaSelectionOption();
2673             } else
2674 #endif
2675             {
2676                 RefPtr<InbandTextTrackPrivateAVFObjC> track = static_cast<InbandTextTrackPrivateAVFObjC*>(removedTextTracks[i - 1].get());
2677                 currentOption = track->mediaSelectionOption();
2678             }
2679             
2680             if ([currentOption.get() isEqual:option]) {
2681                 removedTextTracks.remove(i - 1);
2682                 newTrack = false;
2683                 break;
2684             }
2685         }
2686         if (!newTrack)
2687             continue;
2688
2689 #if ENABLE(AVF_CAPTIONS)
2690         if ([option outOfBandSource]) {
2691             m_textTracks.append(OutOfBandTextTrackPrivateAVF::create(this, option));
2692             m_textTracks.last()->setHasBeenReported(true); // Ignore out-of-band tracks that we passed to AVFoundation so we do not double-count them
2693             continue;
2694         }
2695 #endif
2696
2697         m_textTracks.append(InbandTextTrackPrivateAVFObjC::create(this, option, InbandTextTrackPrivate::Generic));
2698     }
2699
2700     processNewAndRemovedTextTracks(removedTextTracks);
2701 }
2702
2703 void MediaPlayerPrivateAVFoundationObjC::processMetadataTrack()
2704 {
2705     if (m_metadataTrack)
2706         return;
2707
2708     m_metadataTrack = InbandMetadataTextTrackPrivateAVF::create(InbandTextTrackPrivate::Metadata, InbandTextTrackPrivate::Data);
2709     m_metadataTrack->setInBandMetadataTrackDispatchType("com.apple.streaming");
2710     player()->addTextTrack(m_metadataTrack);
2711 }
2712
2713 void MediaPlayerPrivateAVFoundationObjC::processCue(NSArray *attributedStrings, NSArray *nativeSamples, const MediaTime& time)
2714 {
2715     if (!m_currentTextTrack)
2716         return;
2717
2718     m_currentTextTrack->processCue(reinterpret_cast<CFArrayRef>(attributedStrings), reinterpret_cast<CFArrayRef>(nativeSamples), time);
2719 }
2720
2721 void MediaPlayerPrivateAVFoundationObjC::flushCues()
2722 {
2723     LOG(Media, "MediaPlayerPrivateAVFoundationObjC::flushCues(%p)", this);
2724
2725     if (!m_currentTextTrack)
2726         return;
2727     
2728     m_currentTextTrack->resetCueValues();
2729 }
2730 #endif // HAVE(AVFOUNDATION_MEDIA_SELECTION_GROUP)
2731
2732 void MediaPlayerPrivateAVFoundationObjC::setCurrentTextTrack(InbandTextTrackPrivateAVF *track)
2733 {
2734     if (m_currentTextTrack == track)
2735         return;
2736
2737     LOG(Media, "MediaPlayerPrivateAVFoundationObjC::setCurrentTextTrack(%p) - selecting track %p, language = %s", this, track, track ? track->language().string().utf8().data() : "");
2738         
2739     m_currentTextTrack = track;
2740
2741     if (track) {
2742         if (track->textTrackCategory() == InbandTextTrackPrivateAVF::LegacyClosedCaption)
2743             [m_avPlayer.get() setClosedCaptionDisplayEnabled:YES];
2744 #if HAVE(AVFOUNDATION_MEDIA_SELECTION_GROUP)
2745 #if ENABLE(AVF_CAPTIONS)
2746         else if (track->textTrackCategory() == InbandTextTrackPrivateAVF::OutOfBand)
2747             [m_avPlayerItem.get() selectMediaOption:static_cast<OutOfBandTextTrackPrivateAVF*>(track)->mediaSelectionOption() inMediaSelectionGroup:safeMediaSelectionGroupForLegibleMedia()];
2748 #endif
2749         else
2750             [m_avPlayerItem.get() selectMediaOption:static_cast<InbandTextTrackPrivateAVFObjC*>(track)->mediaSelectionOption() inMediaSelectionGroup:safeMediaSelectionGroupForLegibleMedia()];
2751 #endif
2752     } else {
2753 #if HAVE(AVFOUNDATION_MEDIA_SELECTION_GROUP)
2754         [m_avPlayerItem.get() selectMediaOption:0 inMediaSelectionGroup:safeMediaSelectionGroupForLegibleMedia()];
2755 #endif
2756         [m_avPlayer.get() setClosedCaptionDisplayEnabled:NO];
2757     }
2758
2759 }
2760
2761 String MediaPlayerPrivateAVFoundationObjC::languageOfPrimaryAudioTrack() const
2762 {
2763     if (!m_languageOfPrimaryAudioTrack.isNull())
2764         return m_languageOfPrimaryAudioTrack;
2765
2766     if (!m_avPlayerItem.get())
2767         return emptyString();
2768
2769 #if HAVE(AVFOUNDATION_MEDIA_SELECTION_GROUP)
2770     // If AVFoundation has an audible group, return the language of the currently selected audible option.
2771     AVMediaSelectionGroupType *audibleGroup = [m_avAsset.get() mediaSelectionGroupForMediaCharacteristic:AVMediaCharacteristicAudible];
2772     AVMediaSelectionOptionType *currentlySelectedAudibleOption = [m_avPlayerItem.get() selectedMediaOptionInMediaSelectionGroup:audibleGroup];
2773     if (currentlySelectedAudibleOption) {
2774         m_languageOfPrimaryAudioTrack = [[currentlySelectedAudibleOption locale] localeIdentifier];
2775         LOG(Media, "MediaPlayerPrivateAVFoundationObjC::languageOfPrimaryAudioTrack(%p) - returning language of selected audible option: %s", this, m_languageOfPrimaryAudioTrack.utf8().data());
2776
2777         return m_languageOfPrimaryAudioTrack;
2778     }
2779 #endif // HAVE(AVFOUNDATION_MEDIA_SELECTION_GROUP)
2780
2781     // AVFoundation synthesizes an audible group when there is only one ungrouped audio track if there is also a legible group (one or
2782     // 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.
2783     NSArray *tracks = [m_avAsset.get() tracksWithMediaType:AVMediaTypeAudio];
2784     if (!tracks || [tracks count] != 1) {
2785         m_languageOfPrimaryAudioTrack = emptyString();
2786         LOG(Media, "MediaPlayerPrivateAVFoundationObjC::languageOfPrimaryAudioTrack(%p) - %lu audio tracks, returning emptyString()", this, static_cast<unsigned long>(tracks ? [tracks count] : 0));
2787         return m_languageOfPrimaryAudioTrack;
2788     }
2789
2790     AVAssetTrack *track = [tracks objectAtIndex:0];
2791     m_languageOfPrimaryAudioTrack = AVTrackPrivateAVFObjCImpl::languageForAVAssetTrack(track);
2792
2793 #if !LOG_DISABLED
2794     if (m_languageOfPrimaryAudioTrack == emptyString())
2795         LOG(Media, "MediaPlayerPrivateAVFoundationObjC::languageOfPrimaryAudioTrack(%p) - single audio track has no language, returning emptyString()", this);
2796     else
2797         LOG(Media, "MediaPlayerPrivateAVFoundationObjC::languageOfPrimaryAudioTrack(%p) - returning language of single audio track: %s", this, m_languageOfPrimaryAudioTrack.utf8().data());
2798 #endif
2799
2800     return m_languageOfPrimaryAudioTrack;
2801 }
2802
2803 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
2804 bool MediaPlayerPrivateAVFoundationObjC::isCurrentPlaybackTargetWireless() const
2805 {
2806     if (!m_avPlayer)
2807         return false;
2808
2809     bool wirelessTarget = m_avPlayer.get().externalPlaybackActive;
2810     LOG(Media, "MediaPlayerPrivateAVFoundationObjC::isCurrentPlaybackTargetWireless(%p) - returning %s", this, boolString(wirelessTarget));
2811
2812     return wirelessTarget;
2813 }
2814
2815 MediaPlayer::WirelessPlaybackTargetType MediaPlayerPrivateAVFoundationObjC::wirelessPlaybackTargetType() const
2816 {
2817     if (!m_avPlayer)
2818         return MediaPlayer::TargetTypeNone;
2819
2820 #if PLATFORM(IOS)
2821     switch (wkExernalDeviceTypeForPlayer(m_avPlayer.get())) {
2822     case wkExternalPlaybackTypeNone:
2823         return MediaPlayer::TargetTypeNone;
2824     case wkExternalPlaybackTypeAirPlay:
2825         return MediaPlayer::TargetTypeAirPlay;
2826     case wkExternalPlaybackTypeTVOut:
2827         return MediaPlayer::TargetTypeTVOut;
2828     }
2829
2830     ASSERT_NOT_REACHED();
2831     return MediaPlayer::TargetTypeNone;
2832
2833 #else
2834     return MediaPlayer::TargetTypeAirPlay;
2835 #endif
2836 }
2837
2838 String MediaPlayerPrivateAVFoundationObjC::wirelessPlaybackTargetName() const
2839 {
2840     if (!m_avPlayer)
2841         return emptyString();
2842
2843     String wirelessTargetName;
2844 #if !PLATFORM(IOS)
2845     if (m_outputContext)
2846         wirelessTargetName = m_outputContext.get().deviceName;
2847 #else
2848     wirelessTargetName = wkExernalDeviceDisplayNameForPlayer(m_avPlayer.get());
2849 #endif
2850     LOG(Media, "MediaPlayerPrivateAVFoundationObjC::wirelessPlaybackTargetName(%p) - returning %s", this, wirelessTargetName.utf8().data());
2851
2852     return wirelessTargetName;
2853 }
2854
2855 bool MediaPlayerPrivateAVFoundationObjC::wirelessVideoPlaybackDisabled() const
2856 {
2857     if (!m_avPlayer)
2858         return !m_allowsWirelessVideoPlayback;
2859
2860     m_allowsWirelessVideoPlayback = [m_avPlayer.get() allowsExternalPlayback];
2861     LOG(Media, "MediaPlayerPrivateAVFoundationObjC::wirelessVideoPlaybackDisabled(%p) - returning %s", this, boolString(!m_allowsWirelessVideoPlayback));
2862
2863     return !m_allowsWirelessVideoPlayback;
2864 }
2865
2866 void MediaPlayerPrivateAVFoundationObjC::setWirelessVideoPlaybackDisabled(bool disabled)
2867 {
2868     LOG(Media, "MediaPlayerPrivateAVFoundationObjC::setWirelessVideoPlaybackDisabled(%p) - %s", this, boolString(disabled));
2869     m_allowsWirelessVideoPlayback = !disabled;
2870     if (!m_avPlayer)
2871         return;
2872
2873     setDelayCallbacks(true);
2874     [m_avPlayer.get() setAllowsExternalPlayback:!disabled];
2875     setDelayCallbacks(false);
2876 }
2877
2878 #if !PLATFORM(IOS)
2879 void MediaPlayerPrivateAVFoundationObjC::setWirelessPlaybackTarget(Ref<MediaPlaybackTarget>&& target)
2880 {
2881     MediaPlaybackTargetMac* macTarget = toMediaPlaybackTargetMac(&target.get());
2882
2883     m_outputContext = macTarget->outputContext();
2884     LOG(Media, "MediaPlayerPrivateAVFoundationObjC::setWirelessPlaybackTarget(%p) - target = %p, device name = %s", this, m_outputContext.get(), [m_outputContext.get().deviceName UTF8String]);
2885
2886     if (!m_outputContext || !m_outputContext.get().deviceName)
2887         setShouldPlayToPlaybackTarget(false);
2888 }
2889
2890 void MediaPlayerPrivateAVFoundationObjC::setShouldPlayToPlaybackTarget(bool shouldPlay)
2891 {
2892     m_shouldPlayToPlaybackTarget = shouldPlay;
2893
2894     if (!m_avPlayer)
2895         return;
2896
2897     AVOutputContext *newContext = shouldPlay ? m_outputContext.get() : nil;
2898     RetainPtr<AVOutputContext> currentContext = m_avPlayer.get().outputContext;
2899
2900     LOG(Media, "MediaPlayerPrivateAVFoundationObjC::setShouldPlayToPlaybackTarget(%p) - target = %p, shouldPlay = %s", this, newContext, boolString(shouldPlay));
2901
2902     if ((!newContext && !currentContext.get()) || [currentContext.get() isEqual:newContext])
2903         return;
2904
2905     setDelayCallbacks(true);
2906     m_avPlayer.get().outputContext = newContext;
2907     setDelayCallbacks(false);
2908 }
2909 #endif // !PLATFORM(IOS)
2910
2911 void MediaPlayerPrivateAVFoundationObjC::updateDisableExternalPlayback()
2912 {
2913     if (!m_avPlayer)
2914         return;
2915
2916 #if PLATFORM(IOS)
2917     [m_avPlayer setUsesExternalPlaybackWhileExternalScreenIsActive:m_videoFullscreenLayer != nil];
2918 #endif
2919 }
2920 #endif
2921
2922 void MediaPlayerPrivateAVFoundationObjC::playerItemStatusDidChange(int status)
2923 {
2924     m_cachedItemStatus = status;
2925
2926     updateStates();
2927 }
2928
2929 void MediaPlayerPrivateAVFoundationObjC::playbackLikelyToKeepUpWillChange()
2930 {
2931     m_pendingStatusChanges++;
2932 }
2933
2934 void MediaPlayerPrivateAVFoundationObjC::playbackLikelyToKeepUpDidChange(bool likelyToKeepUp)
2935 {
2936     m_cachedLikelyToKeepUp = likelyToKeepUp;
2937
2938     ASSERT(m_pendingStatusChanges);
2939     if (!--m_pendingStatusChanges)
2940         updateStates();
2941 }
2942
2943 void MediaPlayerPrivateAVFoundationObjC::playbackBufferEmptyWillChange()
2944 {
2945     m_pendingStatusChanges++;
2946 }
2947
2948 void MediaPlayerPrivateAVFoundationObjC::playbackBufferEmptyDidChange(bool bufferEmpty)
2949 {
2950     m_cachedBufferEmpty = bufferEmpty;
2951
2952     ASSERT(m_pendingStatusChanges);
2953     if (!--m_pendingStatusChanges)
2954         updateStates();
2955 }
2956
2957 void MediaPlayerPrivateAVFoundationObjC::playbackBufferFullWillChange()
2958 {
2959     m_pendingStatusChanges++;
2960 }
2961
2962 void MediaPlayerPrivateAVFoundationObjC::playbackBufferFullDidChange(bool bufferFull)
2963 {
2964     m_cachedBufferFull = bufferFull;
2965
2966     ASSERT(m_pendingStatusChanges);
2967     if (!--m_pendingStatusChanges)
2968         updateStates();
2969 }
2970
2971 void MediaPlayerPrivateAVFoundationObjC::seekableTimeRangesDidChange(RetainPtr<NSArray> seekableRanges)
2972 {
2973     m_cachedSeekableRanges = seekableRanges;
2974
2975     seekableTimeRangesChanged();
2976     updateStates();
2977 }
2978
2979 void MediaPlayerPrivateAVFoundationObjC::loadedTimeRangesDidChange(RetainPtr<NSArray> loadedRanges)
2980 {
2981     m_cachedLoadedRanges = loadedRanges;
2982
2983     loadedTimeRangesChanged();
2984     updateStates();
2985 }
2986
2987 void MediaPlayerPrivateAVFoundationObjC::firstFrameAvailableDidChange(bool isReady)
2988 {
2989     m_cachedIsReadyForDisplay = isReady;
2990     if (!hasVideo() && isReady)
2991         tracksChanged();
2992     updateStates();
2993 }
2994
2995 void MediaPlayerPrivateAVFoundationObjC::trackEnabledDidChange(bool)
2996 {
2997     tracksChanged();
2998     updateStates();
2999 }
3000
3001 void MediaPlayerPrivateAVFoundationObjC::setShouldBufferData(bool shouldBuffer)
3002 {
3003     LOG(Media, "MediaPlayerPrivateAVFoundationObjC::shouldBufferData(%p) - %s", this, boolString(shouldBuffer));
3004     if (m_shouldBufferData == shouldBuffer)
3005         return;
3006
3007     m_shouldBufferData = shouldBuffer;
3008     
3009     if (!m_avPlayer)
3010         return;
3011
3012     setAVPlayerItem(shouldBuffer ? m_avPlayerItem.get() : nil);
3013 }
3014
3015 #if ENABLE(DATACUE_VALUE)
3016 static const AtomicString& metadataType(NSString *avMetadataKeySpace)
3017 {
3018     static NeverDestroyed<const AtomicString> quickTimeUserData("com.apple.quicktime.udta", AtomicString::ConstructFromLiteral);
3019     static NeverDestroyed<const AtomicString> isoUserData("org.mp4ra", AtomicString::ConstructFromLiteral);
3020     static NeverDestroyed<const AtomicString> quickTimeMetadata("com.apple.quicktime.mdta", AtomicString::ConstructFromLiteral);
3021     static NeverDestroyed<const AtomicString> iTunesMetadata("com.apple.itunes", AtomicString::ConstructFromLiteral);
3022     static NeverDestroyed<const AtomicString> id3Metadata("org.id3", AtomicString::ConstructFromLiteral);
3023
3024     if ([avMetadataKeySpace isEqualToString:AVMetadataKeySpaceQuickTimeUserData])
3025         return quickTimeUserData;
3026     if (AVMetadataKeySpaceISOUserData && [avMetadataKeySpace isEqualToString:AVMetadataKeySpaceISOUserData])
3027         return isoUserData;
3028     if ([avMetadataKeySpace isEqualToString:AVMetadataKeySpaceQuickTimeMetadata])
3029         return quickTimeMetadata;
3030     if ([avMetadataKeySpace isEqualToString:AVMetadataKeySpaceiTunes])
3031         return iTunesMetadata;
3032     if ([avMetadataKeySpace isEqualToString:AVMetadataKeySpaceID3])
3033         return id3Metadata;
3034
3035     return emptyAtom;
3036 }
3037 #endif
3038
3039 void MediaPlayerPrivateAVFoundationObjC::metadataDidArrive(RetainPtr<NSArray> metadata, const MediaTime& mediaTime)
3040 {
3041     m_currentMetaData = metadata && ![metadata isKindOfClass:[NSNull class]] ? metadata : nil;
3042
3043     LOG(Media, "MediaPlayerPrivateAVFoundationObjC::metadataDidArrive(%p) - adding %i cues at time %s", this, m_currentMetaData ? static_cast<int>([m_currentMetaData.get() count]) : 0, toString(mediaTime).utf8().data());
3044
3045 #if ENABLE(DATACUE_VALUE)
3046     if (seeking())
3047         return;
3048
3049     if (!m_metadataTrack)
3050         processMetadataTrack();
3051
3052     if (!metadata || [metadata isKindOfClass:[NSNull class]]) {
3053         m_metadataTrack->updatePendingCueEndTimes(mediaTime);
3054         return;
3055     }
3056
3057     // Set the duration of all incomplete cues before adding new ones.
3058     MediaTime earliestStartTime = MediaTime::positiveInfiniteTime();
3059     for (AVMetadataItemType *item in m_currentMetaData.get()) {
3060         MediaTime start = toMediaTime(item.time);
3061         if (start < earliestStartTime)
3062             earliestStartTime = start;
3063     }
3064     m_metadataTrack->updatePendingCueEndTimes(earliestStartTime);
3065
3066     for (AVMetadataItemType *item in m_currentMetaData.get()) {
3067         MediaTime start = toMediaTime(item.time);
3068         MediaTime end = MediaTime::positiveInfiniteTime();
3069         if (CMTIME_IS_VALID(item.duration))
3070             end = start + toMediaTime(item.duration);
3071
3072         AtomicString type = nullAtom;
3073         if (item.keySpace)
3074             type = metadataType(item.keySpace);
3075
3076         m_metadataTrack->addDataCue(start, end, SerializedPlatformRepresentationMac::create(item), type);
3077     }
3078 #endif
3079 }
3080
3081 void MediaPlayerPrivateAVFoundationObjC::tracksDidChange(RetainPtr<NSArray> tracks)
3082 {
3083     for (AVPlayerItemTrack *track in m_cachedTracks.get())
3084         [track removeObserver:m_objcObserver.get() forKeyPath:@"enabled"];
3085
3086     NSArray *assetTracks = [m_avAsset tracks];
3087
3088     m_cachedTracks = [tracks objectsAtIndexes:[tracks indexesOfObjectsPassingTest:^(id obj, NSUInteger, BOOL*) {
3089         AVAssetTrack* assetTrack = [obj assetTrack];
3090
3091         if ([assetTracks containsObject:assetTrack])
3092             return YES;
3093
3094         // Track is a streaming track. Omit if it belongs to a valid AVMediaSelectionGroup.
3095         if (!hasLoadedMediaSelectionGroups())
3096             return NO;
3097
3098         if ([assetTrack hasMediaCharacteristic:AVMediaCharacteristicAudible] && safeMediaSelectionGroupForAudibleMedia())
3099             return NO;
3100
3101         if ([assetTrack hasMediaCharacteristic:AVMediaCharacteristicVisual] && safeMediaSelectionGroupForVisualMedia())
3102             return NO;
3103
3104         if ([assetTrack hasMediaCharacteristic:AVMediaCharacteristicLegible] && safeMediaSelectionGroupForLegibleMedia())
3105             return NO;
3106
3107         return YES;
3108     }]];
3109
3110     for (AVPlayerItemTrack *track in m_cachedTracks.get())
3111         [track addObserver:m_objcObserver.get() forKeyPath:@"enabled" options:NSKeyValueObservingOptionNew context:(void *)MediaPlayerAVFoundationObservationContextPlayerItemTrack];
3112
3113     m_cachedTotalBytes = 0;
3114
3115     tracksChanged();
3116     updateStates();
3117 }
3118
3119 void MediaPlayerPrivateAVFoundationObjC::hasEnabledAudioDidChange(bool hasEnabledAudio)
3120 {
3121     m_cachedHasEnabledAudio = hasEnabledAudio;
3122
3123     tracksChanged();
3124     updateStates();
3125 }
3126
3127 void MediaPlayerPrivateAVFoundationObjC::presentationSizeDidChange(FloatSize size)
3128 {
3129     m_cachedPresentationSize = size;
3130
3131     sizeChanged();
3132     updateStates();
3133 }
3134
3135 void MediaPlayerPrivateAVFoundationObjC::durationDidChange(const MediaTime& duration)
3136 {
3137     m_cachedDuration = duration;
3138
3139     invalidateCachedDuration();
3140 }
3141
3142 void MediaPlayerPrivateAVFoundationObjC::rateDidChange(double rate)
3143 {
3144     m_cachedRate = rate;
3145
3146     updateStates();
3147     rateChanged();
3148 }
3149     
3150 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
3151 void MediaPlayerPrivateAVFoundationObjC::playbackTargetIsWirelessDidChange()
3152 {
3153     playbackTargetIsWirelessChanged();
3154 }
3155 #endif
3156
3157 void MediaPlayerPrivateAVFoundationObjC::canPlayFastForwardDidChange(bool newValue)
3158 {
3159     m_cachedCanPlayFastForward = newValue;
3160 }
3161
3162 void MediaPlayerPrivateAVFoundationObjC::canPlayFastReverseDidChange(bool newValue)
3163 {
3164     m_cachedCanPlayFastReverse = newValue;
3165 }
3166
3167 URL MediaPlayerPrivateAVFoundationObjC::resolvedURL() const
3168 {
3169     if (!m_avAsset || [m_avAsset statusOfValueForKey:@"resolvedURL" error:nullptr] != AVKeyValueStatusLoaded)
3170         return MediaPlayerPrivateAVFoundation::resolvedURL();
3171
3172     return URL([m_avAsset resolvedURL]);
3173 }
3174
3175 NSArray* assetMetadataKeyNames()
3176 {
3177     static NSArray* keys;
3178     if (!keys) {
3179         keys = [[NSArray alloc] initWithObjects:@"duration",
3180                     @"naturalSize",
3181                     @"preferredTransform",
3182                     @"preferredVolume",
3183                     @"preferredRate",
3184                     @"playable",
3185                     @"resolvedURL",
3186                     @"tracks",
3187                     @"availableMediaCharacteristicsWithMediaSelectionOptions",
3188                    nil];
3189     }
3190     return keys;
3191 }
3192
3193 NSArray* itemKVOProperties()
3194 {
3195     static NSArray* keys;
3196     if (!keys) {
3197         keys = [[NSArray alloc] initWithObjects:@"presentationSize",
3198                 @"status",
3199                 @"asset",
3200                 @"tracks",
3201                 @"seekableTimeRanges",
3202                 @"loadedTimeRanges",
3203                 @"playbackLikelyToKeepUp",
3204                 @"playbackBufferFull",
3205                 @"playbackBufferEmpty",
3206                 @"duration",
3207                 @"hasEnabledAudio",
3208                 @"timedMetadata",
3209                 @"canPlayFastForward",
3210                 @"canPlayFastReverse",
3211                 nil];
3212     }
3213     return keys;
3214 }
3215
3216 NSArray* assetTrackMetadataKeyNames()
3217 {
3218     static NSArray* keys = [[NSArray alloc] initWithObjects:@"totalSampleDataLength", @"mediaType", @"enabled", @"preferredTransform", @"naturalSize", nil];
3219     return keys;
3220 }
3221
3222 NSArray* playerKVOProperties()
3223 {
3224     static NSArray* keys = [[NSArray alloc] initWithObjects:@"rate",
3225 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
3226                             @"externalPlaybackActive", @"allowsExternalPlayback",
3227 #endif
3228                             nil];
3229     return keys;
3230 }
3231 } // namespace WebCore
3232
3233 @implementation WebCoreAVFMovieObserver
3234
3235 - (id)initWithCallback:(MediaPlayerPrivateAVFoundationObjC*)callback
3236 {
3237     self = [super init];
3238     if (!self)
3239         return nil;
3240     m_callback = callback;
3241     return self;
3242 }
3243
3244 - (void)disconnect
3245 {
3246     [NSObject cancelPreviousPerformRequestsWithTarget:self];
3247     m_callback = 0;
3248 }
3249
3250 - (void)metadataLoaded
3251 {
3252     if (!m_callback)
3253         return;
3254
3255     m_callback->scheduleMainThreadNotification(MediaPlayerPrivateAVFoundation::Notification::AssetMetadataLoaded);
3256 }
3257
3258 - (void)didEnd:(NSNotification *)unusedNotification
3259 {
3260     UNUSED_PARAM(unusedNotification);
3261     if (!m_callback)
3262         return;
3263     m_callback->scheduleMainThreadNotification(MediaPlayerPrivateAVFoundation::Notification::ItemDidPlayToEndTime);
3264 }
3265
3266 - (void)observeValueForKeyPath:keyPath ofObject:(id)object change:(NSDictionary *)change context:(MediaPlayerAVFoundationObservationContext)context
3267 {
3268     UNUSED_PARAM(object);
3269     id newValue = [change valueForKey:NSKeyValueChangeNewKey];
3270
3271     if (!m_callback)
3272         return;
3273
3274     bool willChange = [[change valueForKey:NSKeyValueChangeNotificationIsPriorKey] boolValue];
3275
3276 #if !LOG_DISABLED
3277     if (willChange)
3278         LOG(Media, "WebCoreAVFMovieObserver::observeValueForKeyPath(%p) - will change, keyPath = %s", self, [keyPath UTF8String]);
3279     else {
3280         RetainPtr<NSString> valueString = adoptNS([[NSString alloc] initWithFormat:@"%@", newValue]);
3281         LOG(Media, "WebCoreAVFMovieObserver::observeValueForKeyPath(%p) - did change, keyPath = %s, value = %s", self, [keyPath UTF8String], [valueString.get() UTF8String]);
3282     }
3283 #endif
3284
3285     std::function<void ()> function;
3286
3287     if (context == MediaPlayerAVFoundationObservationContextAVPlayerLayer) {
3288         if ([keyPath isEqualToString:@"readyForDisplay"])
3289             function = std::bind(&MediaPlayerPrivateAVFoundationObjC::firstFrameAvailableDidChange, m_callback, [newValue boolValue]);
3290     }
3291
3292     if (context == MediaPlayerAVFoundationObservationContextPlayerItemTrack) {
3293         if ([keyPath isEqualToString:@"enabled"])
3294             function = std::bind(&MediaPlayerPrivateAVFoundationObjC::trackEnabledDidChange, m_callback, [newValue boolValue]);
3295     }
3296
3297     if (context == MediaPlayerAVFoundationObservationContextPlayerItem && willChange) {
3298         if ([keyPath isEqualToString:@"playbackLikelyToKeepUp"])
3299             function = std::bind(&MediaPlayerPrivateAVFoundationObjC::playbackLikelyToKeepUpWillChange, m_callback);
3300         else if ([keyPath isEqualToString:@"playbackBufferEmpty"])
3301             function = std::bind(&MediaPlayerPrivateAVFoundationObjC::playbackBufferEmptyWillChange, m_callback);
3302         else if ([keyPath isEqualToString:@"playbackBufferFull"])
3303             function = std::bind(&MediaPlayerPrivateAVFoundationObjC::playbackBufferFullWillChange, m_callback);
3304     }
3305
3306     if (context == MediaPlayerAVFoundationObservationContextPlayerItem && !willChange) {
3307         // A value changed for an AVPlayerItem
3308         if ([keyPath isEqualToString:@"status"])
3309             function = std::bind(&MediaPlayerPrivateAVFoundationObjC::playerItemStatusDidChange, m_callback, [newValue intValue]);
3310         else if ([keyPath isEqualToString:@"playbackLikelyToKeepUp"])
3311             function = std::bind(&MediaPlayerPrivateAVFoundationObjC::playbackLikelyToKeepUpDidChange, m_callback, [newValue boolValue]);
3312         else if ([keyPath isEqualToString:@"playbackBufferEmpty"])
3313             function = std::bind(&MediaPlayerPrivateAVFoundationObjC::playbackBufferEmptyDidChange, m_callback, [newValue boolValue]);
3314         else if ([keyPath isEqualToString:@"playbackBufferFull"])
3315             function = std::bind(&MediaPlayerPrivateAVFoundationObjC::playbackBufferFullDidChange, m_callback, [newValue boolValue]);
3316         else if ([keyPath isEqualToString:@"asset"])
3317             function = std::bind(&MediaPlayerPrivateAVFoundationObjC::setAsset, m_callback, RetainPtr<id>(newValue));
3318         else if ([keyPath isEqualToString:@"loadedTimeRanges"])
3319             function = std::bind(&MediaPlayerPrivateAVFoundationObjC::loadedTimeRangesDidChange, m_callback, RetainPtr<NSArray>(newValue));
3320         else if ([keyPath isEqualToString:@"seekableTimeRanges"])
3321             function = std::bind(&MediaPlayerPrivateAVFoundationObjC::seekableTimeRangesDidChange, m_callback, RetainPtr<NSArray>(newValue));
3322         else if ([keyPath isEqualToString:@"tracks"])
3323             function = std::bind(&MediaPlayerPrivateAVFoundationObjC::tracksDidChange, m_callback, RetainPtr<NSArray>(newValue));
3324         else if ([keyPath isEqualToString:@"hasEnabledAudio"])
3325             function = std::bind(&MediaPlayerPrivateAVFoundationObjC::hasEnabledAudioDidChange, m_callback, [newValue boolValue]);
3326         else if ([keyPath isEqualToString:@"presentationSize"])
3327             function = std::bind(&MediaPlayerPrivateAVFoundationObjC::presentationSizeDidChange, m_callback, FloatSize([newValue sizeValue]));
3328         else if ([keyPath isEqualToString:@"duration"])
3329             function = std::bind(&MediaPlayerPrivateAVFoundationObjC::durationDidChange, m_callback, toMediaTime([newValue CMTimeValue]));
3330         else if ([keyPath isEqualToString:@"timedMetadata"] && newValue) {
3331             MediaTime now;
3332             CMTime itemTime = [(AVPlayerItemType *)object currentTime];
3333             if (CMTIME_IS_NUMERIC(itemTime))
3334                 now = std::max(toMediaTime(itemTime), MediaTime::zeroTime());
3335             function = std::bind(&MediaPlayerPrivateAVFoundationObjC::metadataDidArrive, m_callback, RetainPtr<NSArray>(newValue), now);
3336         } else if ([keyPath isEqualToString:@"canPlayFastReverse"])
3337             function = std::bind(&MediaPlayerPrivateAVFoundationObjC::canPlayFastReverseDidChange, m_callback, [newValue boolValue]);
3338         else if ([keyPath isEqualToString:@"canPlayFastForward"])
3339             function = std::bind(&MediaPlayerPrivateAVFoundationObjC::canPlayFastForwardDidChange, m_callback, [newValue boolValue]);
3340     }
3341
3342     if (context == MediaPlayerAVFoundationObservationContextPlayer && !willChange) {
3343         // A value changed for an AVPlayer.
3344         if ([keyPath isEqualToString:@"rate"])
3345             function = std::bind(&MediaPlayerPrivateAVFoundationObjC::rateDidChange, m_callback, [newValue doubleValue]);
3346 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
3347         else if ([keyPath isEqualToString:@"externalPlaybackActive"] || [keyPath isEqualToString:@"allowsExternalPlayback"])
3348             function = std::bind(&MediaPlayerPrivateAVFoundationObjC::playbackTargetIsWirelessDidChange, m_callback);
3349 #endif
3350     }
3351     
3352     if (!function)
3353         return;
3354
3355     auto weakThis = m_callback->createWeakPtr();
3356     m_callback->scheduleMainThreadNotification(MediaPlayerPrivateAVFoundation::Notification([weakThis, function]{
3357         // weakThis and function both refer to the same MediaPlayerPrivateAVFoundationObjC instance. If the WeakPtr has
3358         // been cleared, the underlying object has been destroyed, and it is unsafe to call function().
3359         if (!weakThis)
3360             return;
3361         function();
3362     }));
3363 }
3364
3365 #if HAVE(AVFOUNDATION_MEDIA_SELECTION_GROUP)
3366 - (void)legibleOutput:(id)output didOutputAttributedStrings:(NSArray *)strings nativeSampleBuffers:(NSArray *)nativeSamples forItemTime:(CMTime)itemTime
3367 {
3368     UNUSED_PARAM(output);
3369     UNUSED_PARAM(nativeSamples);
3370
3371     if (!m_callback)
3372         return;
3373
3374     RetainPtr<WebCoreAVFMovieObserver> strongSelf = self;
3375     RetainPtr<NSArray> strongStrings = strings;
3376     RetainPtr<NSArray> strongSamples = nativeSamples;
3377     callOnMainThread([strongSelf, strongStrings, strongSamples, itemTime] {
3378         MediaPlayerPrivateAVFoundationObjC* callback = strongSelf->m_callback;
3379         if (!callback)
3380             return;
3381         callback->processCue(strongStrings.get(), strongSamples.get(), toMediaTime(itemTime));
3382     });
3383 }
3384
3385 - (void)outputSequenceWasFlushed:(id)output
3386 {
3387     UNUSED_PARAM(output);
3388
3389     if (!m_callback)
3390         return;
3391     
3392     RetainPtr<WebCoreAVFMovieObserver> strongSelf = self;
3393     callOnMainThread([strongSelf] {
3394         if (MediaPlayerPrivateAVFoundationObjC* callback = strongSelf->m_callback)
3395             callback->flushCues();
3396     });
3397 }
3398 #endif
3399
3400 @end
3401
3402 #if HAVE(AVFOUNDATION_LOADER_DELEGATE)
3403 @implementation WebCoreAVFLoaderDelegate
3404
3405 - (id)initWithCallback:(MediaPlayerPrivateAVFoundationObjC*)callback
3406 {
3407     self = [super init];
3408     if (!self)
3409         return nil;
3410     m_callback = callback;
3411     return self;
3412 }
3413
3414 - (BOOL)resourceLoader:(AVAssetResourceLoader *)resourceLoader shouldWaitForLoadingOfRequestedResource:(AVAssetResourceLoadingRequest *)loadingRequest
3415 {
3416     UNUSED_PARAM(resourceLoader);
3417     if (!m_callback)
3418         return NO;
3419
3420     RetainPtr<WebCoreAVFLoaderDelegate> strongSelf = self;
3421     RetainPtr<AVAssetResourceLoadingRequest> strongRequest = loadingRequest;
3422     callOnMainThread([strongSelf, strongRequest] {
3423         MediaPlayerPrivateAVFoundationObjC* callback = strongSelf->m_callback;
3424         if (!callback) {
3425             [strongRequest finishLoadingWithError:nil];
3426             return;
3427         }
3428
3429         if (!callback->shouldWaitForLoadingOfResource(strongRequest.get()))
3430             [strongRequest finishLoadingWithError:nil];
3431     });
3432
3433     return YES;
3434 }
3435
3436 - (BOOL)resourceLoader:(AVAssetResourceLoader *)resourceLoader shouldWaitForResponseToAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
3437 {
3438     UNUSED_PARAM(resourceLoader);
3439     if (!m_callback)
3440         return NO;
3441
3442     if ([[[challenge protectionSpace] authenticationMethod] isEqualToString:NSURLAuthenticationMethodServerTrust])
3443         return NO;
3444
3445     RetainPtr<WebCoreAVFLoaderDelegate> strongSelf = self;
3446     RetainPtr<NSURLAuthenticationChallenge> strongChallenge = challenge;
3447     callOnMainThread([strongSelf, strongChallenge] {
3448         MediaPlayerPrivateAVFoundationObjC* callback = strongSelf->m_callback;
3449         if (!callback) {
3450             [[strongChallenge sender] cancelAuthenticationChallenge:strongChallenge.get()];
3451             return;
3452         }
3453
3454         if (!callback->shouldWaitForResponseToAuthenticationChallenge(strongChallenge.get()))
3455             [[strongChallenge sender] cancelAuthenticationChallenge:strongChallenge.get()];
3456     });
3457
3458     return YES;
3459 }
3460
3461 - (void)resourceLoader:(AVAssetResourceLoader *)resourceLoader didCancelLoadingRequest:(AVAssetResourceLoadingRequest *)loadingRequest
3462 {
3463     UNUSED_PARAM(reso