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