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