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