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