[MSE][Mac] Crash when removing MediaSource from HTMLMediaElement.
[WebKit-https.git] / Source / WebCore / platform / graphics / avfoundation / objc / SourceBufferPrivateAVFObjC.mm
1 /*
2  * Copyright (C) 2013 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 COMPUTER, 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 COMPUTER, 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 #import "SourceBufferPrivateAVFObjC.h"
28
29 #if ENABLE(MEDIA_SOURCE) && USE(AVFOUNDATION)
30
31 #import "ExceptionCodePlaceholder.h"
32 #import "Logging.h"
33 #import "MediaDescription.h"
34 #import "MediaPlayerPrivateMediaSourceAVFObjC.h"
35 #import "MediaSample.h"
36 #import "MediaSourcePrivateAVFObjC.h"
37 #import "MediaTimeMac.h"
38 #import "NotImplemented.h"
39 #import "SoftLinking.h"
40 #import "SourceBufferPrivateClient.h"
41 #import "TimeRanges.h"
42 #import "AudioTrackPrivateMediaSourceAVFObjC.h"
43 #import "VideoTrackPrivateMediaSourceAVFObjC.h"
44 #import "InbandTextTrackPrivateAVFObjC.h"
45 #import <AVFoundation/AVAssetTrack.h>
46 #import <AVFoundation/AVSampleBufferDisplayLayer.h>
47 #import <objc/runtime.h>
48 #import <wtf/text/AtomicString.h>
49 #import <wtf/text/CString.h>
50 #import <wtf/HashCountedSet.h>
51 #import <wtf/WeakPtr.h>
52 #import <map>
53
54 #pragma mark -
55 #pragma mark Soft Linking
56
57 SOFT_LINK_FRAMEWORK_OPTIONAL(AVFoundation)
58 SOFT_LINK_FRAMEWORK_OPTIONAL(CoreMedia)
59
60 SOFT_LINK_CLASS(AVFoundation, AVAssetTrack)
61 SOFT_LINK_CLASS(AVFoundation, AVStreamDataParser)
62 SOFT_LINK_CLASS(AVFoundation, AVSampleBufferDisplayLayer)
63
64 SOFT_LINK_POINTER_OPTIONAL(AVFoundation, AVMediaTypeVideo, NSString *)
65 SOFT_LINK_POINTER_OPTIONAL(AVFoundation, AVMediaTypeAudio, NSString *)
66 SOFT_LINK_POINTER_OPTIONAL(AVFoundation, AVMediaTypeText, NSString *)
67
68 SOFT_LINK_CONSTANT(CoreMedia, kCMTimeZero, CMTime);
69 SOFT_LINK_CONSTANT(CoreMedia, kCMTimeInvalid, CMTime);
70 SOFT_LINK_CONSTANT(CoreMedia, kCMSampleAttachmentKey_DoNotDisplay, CFStringRef)
71 SOFT_LINK_CONSTANT(CoreMedia, kCMSampleAttachmentKey_NotSync, CFStringRef)
72 SOFT_LINK_CONSTANT(CoreMedia, kCMSampleBufferAttachmentKey_DrainAfterDecoding, CFStringRef)
73 SOFT_LINK_CONSTANT(CoreMedia, kCMSampleBufferAttachmentKey_ResetDecoderBeforeDecoding, CFStringRef)
74 SOFT_LINK_CONSTANT(CoreMedia, kCMSampleBufferAttachmentKey_EmptyMedia, CFStringRef)
75 SOFT_LINK_CONSTANT(CoreMedia, kCMSampleBufferAttachmentKey_DisplayEmptyMediaImmediately, CFStringRef)
76
77 SOFT_LINK_CONSTANT(AVFoundation, AVMediaCharacteristicVisual, NSString*)
78 SOFT_LINK_CONSTANT(AVFoundation, AVMediaCharacteristicAudible, NSString*)
79 SOFT_LINK_CONSTANT(AVFoundation, AVMediaCharacteristicLegible, NSString*)
80
81 SOFT_LINK(CoreMedia, CMFormatDescriptionGetMediaType, CMMediaType, (CMFormatDescriptionRef desc), (desc))
82 SOFT_LINK(CoreMedia, CMSampleBufferCreate, OSStatus, (CFAllocatorRef allocator, CMBlockBufferRef dataBuffer, Boolean dataReady, CMSampleBufferMakeDataReadyCallback makeDataReadyCallback, void *makeDataReadyRefcon, CMFormatDescriptionRef formatDescription, CMItemCount numSamples, CMItemCount numSampleTimingEntries, const CMSampleTimingInfo *sampleTimingArray, CMItemCount numSampleSizeEntries, const size_t *sampleSizeArray, CMSampleBufferRef *sBufOut), (allocator, dataBuffer, dataReady, makeDataReadyCallback, makeDataReadyRefcon, formatDescription, numSamples, numSampleTimingEntries, sampleTimingArray, numSampleSizeEntries, sampleSizeArray, sBufOut))
83 SOFT_LINK(CoreMedia, CMSampleBufferCreateCopy, OSStatus, (CFAllocatorRef allocator, CMSampleBufferRef sbuf, CMSampleBufferRef *sbufCopyOut), (allocator, sbuf, sbufCopyOut))
84 SOFT_LINK(CoreMedia, CMSampleBufferCallForEachSample, OSStatus, (CMSampleBufferRef sbuf, OSStatus (*callback)( CMSampleBufferRef sampleBuffer, CMItemCount index, void *refcon), void *refcon), (sbuf, callback, refcon))
85 SOFT_LINK(CoreMedia, CMSampleBufferGetDecodeTimeStamp, CMTime, (CMSampleBufferRef sbuf), (sbuf))
86 SOFT_LINK(CoreMedia, CMSampleBufferGetDuration, CMTime, (CMSampleBufferRef sbuf), (sbuf))
87 SOFT_LINK(CoreMedia, CMSampleBufferGetPresentationTimeStamp, CMTime, (CMSampleBufferRef sbuf), (sbuf))
88 SOFT_LINK(CoreMedia, CMSampleBufferGetSampleAttachmentsArray, CFArrayRef, (CMSampleBufferRef sbuf, Boolean createIfNecessary), (sbuf, createIfNecessary))
89 SOFT_LINK(CoreMedia, CMFormatDescriptionGetMediaSubType, FourCharCode, (CMFormatDescriptionRef desc), (desc))
90 SOFT_LINK(CoreMedia, CMSetAttachment, void, (CMAttachmentBearerRef target, CFStringRef key, CFTypeRef value, CMAttachmentMode attachmentMode), (target, key, value, attachmentMode))
91
92 #define AVMediaTypeVideo getAVMediaTypeVideo()
93 #define AVMediaTypeAudio getAVMediaTypeAudio()
94 #define AVMediaTypeText getAVMediaTypeText()
95 #define kCMTimeZero getkCMTimeZero()
96 #define kCMTimeInvalid getkCMTimeInvalid()
97 #define kCMSampleAttachmentKey_NotSync getkCMSampleAttachmentKey_NotSync()
98 #define kCMSampleAttachmentKey_DoNotDisplay getkCMSampleAttachmentKey_DoNotDisplay()
99 #define kCMSampleBufferAttachmentKey_ResetDecoderBeforeDecoding getkCMSampleBufferAttachmentKey_ResetDecoderBeforeDecoding()
100 #define kCMSampleBufferAttachmentKey_DrainAfterDecoding getkCMSampleBufferAttachmentKey_DrainAfterDecoding()
101 #define kCMSampleBufferAttachmentKey_EmptyMedia getkCMSampleBufferAttachmentKey_EmptyMedia()
102 #define kCMSampleBufferAttachmentKey_DisplayEmptyMediaImmediately getkCMSampleBufferAttachmentKey_DisplayEmptyMediaImmediately()
103
104 #define AVMediaCharacteristicVisual getAVMediaCharacteristicVisual()
105 #define AVMediaCharacteristicAudible getAVMediaCharacteristicAudible()
106 #define AVMediaCharacteristicLegible getAVMediaCharacteristicLegible()
107
108 #pragma mark -
109 #pragma mark AVStreamDataParser
110 @class AVStreamDataParserInternal;
111
112 NS_CLASS_AVAILABLE(TBD, TBD)
113 @interface AVStreamDataParser : NSObject
114 - (void)setDelegate:(id)delegate;
115 - (void)appendStreamData:(NSData *)data;
116 - (void)setShouldProvideMediaData:(BOOL)shouldProvideMediaData forTrackID:(CMPersistentTrackID)trackID;
117 - (BOOL)shouldProvideMediaDataForTrackID:(CMPersistentTrackID)trackID;
118 @end
119
120 #pragma mark -
121 #pragma mark WebAVStreamDataParserListener
122
123 @interface WebAVStreamDataParserListener : NSObject {
124     WebCore::SourceBufferPrivateAVFObjC* _parent;
125     AVStreamDataParser* _parser;
126 }
127 - (id)initWithParser:(AVStreamDataParser*)parser parent:(WebCore::SourceBufferPrivateAVFObjC*)parent;
128 @end
129
130 @implementation WebAVStreamDataParserListener
131 - (id)initWithParser:(AVStreamDataParser*)parser parent:(WebCore::SourceBufferPrivateAVFObjC*)parent
132 {
133     self = [super init];
134     if (!self)
135         return nil;
136
137     ASSERT(parent);
138     _parent = parent;
139     _parser = parser;
140     [_parser setDelegate:self];
141     return self;
142 }
143
144 - (void)dealloc
145 {
146     [_parser setDelegate:nil];
147     [super dealloc];
148 }
149
150 - (void)streamDataParser:(AVStreamDataParser *)streamDataParser didParseStreamDataAsAsset:(AVAsset *)asset
151 {
152 #if ASSERT_DISABLED
153     UNUSED_PARAM(streamDataParser);
154 #endif
155     ASSERT(streamDataParser == _parser);
156     _parent->didParseStreamDataAsAsset(asset);
157 }
158
159 - (void)streamDataParser:(AVStreamDataParser *)streamDataParser didFailToParseStreamDataWithError:(NSError *)error
160 {
161 #if ASSERT_DISABLED
162     UNUSED_PARAM(streamDataParser);
163 #endif
164     ASSERT(streamDataParser == _parser);
165     _parent->didFailToParseStreamDataWithError(error);
166 }
167
168 - (void)streamDataParser:(AVStreamDataParser *)streamDataParser didProvideMediaData:(CMSampleBufferRef)mediaData forTrackID:(CMPersistentTrackID)trackID mediaType:(NSString *)mediaType flags:(NSUInteger)flags
169 {
170 #if ASSERT_DISABLED
171     UNUSED_PARAM(streamDataParser);
172 #endif
173     ASSERT(streamDataParser == _parser);
174     _parent->didProvideMediaDataForTrackID(trackID, mediaData, mediaType, flags);
175 }
176
177 - (void)streamDataParser:(AVStreamDataParser *)streamDataParser didReachEndOfTrackWithTrackID:(CMPersistentTrackID)trackID mediaType:(NSString *)mediaType
178 {
179 #if ASSERT_DISABLED
180     UNUSED_PARAM(streamDataParser);
181 #endif
182     ASSERT(streamDataParser == _parser);
183     _parent->didReachEndOfTrackWithTrackID(trackID, mediaType);
184 }
185 @end
186
187 namespace WebCore {
188
189 #pragma mark -
190 #pragma mark MediaSampleAVFObjC
191
192 class MediaSampleAVFObjC FINAL : public MediaSample {
193 public:
194     static RefPtr<MediaSampleAVFObjC> create(CMSampleBufferRef sample, int trackID) { return adoptRef(new MediaSampleAVFObjC(sample, trackID)); }
195     virtual ~MediaSampleAVFObjC() { }
196
197     virtual MediaTime presentationTime() const OVERRIDE { return toMediaTime(CMSampleBufferGetPresentationTimeStamp(m_sample.get())); }
198     virtual MediaTime decodeTime() const OVERRIDE { return toMediaTime(CMSampleBufferGetDecodeTimeStamp(m_sample.get())); }
199     virtual MediaTime duration() const OVERRIDE { return toMediaTime(CMSampleBufferGetDuration(m_sample.get())); }
200     virtual AtomicString trackID() const OVERRIDE { return m_id; }
201
202     virtual SampleFlags flags() const OVERRIDE;
203     virtual PlatformSample platformSample() OVERRIDE;
204
205 protected:
206     MediaSampleAVFObjC(CMSampleBufferRef sample, int trackID)
207         : m_sample(sample)
208         , m_id(String::format("%d", trackID))
209     {
210     }
211
212     RetainPtr<CMSampleBufferRef> m_sample;
213     AtomicString m_id;
214 };
215
216 PlatformSample MediaSampleAVFObjC::platformSample()
217 {
218     PlatformSample sample = { PlatformSample::CMSampleBufferType, { .cmSampleBuffer = m_sample.get() } };
219     return sample;
220 }
221
222 static bool CMSampleBufferIsRandomAccess(CMSampleBufferRef sample)
223 {
224     CFArrayRef attachments = CMSampleBufferGetSampleAttachmentsArray(sample, false);
225     for (CFIndex i = 0, count = CFArrayGetCount(attachments); i < count; ++i) {
226         CFDictionaryRef attachmentDict = (CFDictionaryRef)CFArrayGetValueAtIndex(attachments, i);
227         if (!CFDictionaryContainsKey(attachmentDict, kCMSampleAttachmentKey_NotSync))
228             return true;
229     }
230     return false;
231 }
232
233 MediaSample::SampleFlags MediaSampleAVFObjC::flags() const
234 {
235     int returnValue = MediaSample::None;
236
237     if (CMSampleBufferIsRandomAccess(m_sample.get()))
238         returnValue |= MediaSample::IsSync;
239
240     return SampleFlags(returnValue);
241 }
242
243 #pragma mark -
244 #pragma mark MediaDescriptionAVFObjC
245
246 class MediaDescriptionAVFObjC FINAL : public MediaDescription {
247 public:
248     static RefPtr<MediaDescriptionAVFObjC> create(AVAssetTrack* track) { return adoptRef(new MediaDescriptionAVFObjC(track)); }
249     virtual ~MediaDescriptionAVFObjC() { }
250
251     virtual AtomicString codec() const OVERRIDE { return m_codec; }
252     virtual bool isVideo() const OVERRIDE { return m_isVideo; }
253     virtual bool isAudio() const OVERRIDE { return m_isAudio; }
254     virtual bool isText() const OVERRIDE { return m_isText; }
255     
256 protected:
257     MediaDescriptionAVFObjC(AVAssetTrack* track)
258         : m_isVideo([track hasMediaCharacteristic:AVMediaCharacteristicVisual])
259         , m_isAudio([track hasMediaCharacteristic:AVMediaCharacteristicAudible])
260         , m_isText([track hasMediaCharacteristic:AVMediaCharacteristicLegible])
261     {
262         NSArray* formatDescriptions = [track formatDescriptions];
263         CMFormatDescriptionRef description = [formatDescriptions count] ? (CMFormatDescriptionRef)[formatDescriptions objectAtIndex:0] : 0;
264         if (description) {
265             FourCharCode codec = CMFormatDescriptionGetMediaSubType(description);
266             m_codec = AtomicString(reinterpret_cast<LChar*>(&codec), 4);
267         }
268     }
269
270     AtomicString m_codec;
271     bool m_isVideo;
272     bool m_isAudio;
273     bool m_isText;
274 };
275
276 #pragma mark -
277 #pragma mark SourceBufferPrivateAVFObjC
278
279 RefPtr<SourceBufferPrivateAVFObjC> SourceBufferPrivateAVFObjC::create(MediaSourcePrivateAVFObjC* parent)
280 {
281     return adoptRef(new SourceBufferPrivateAVFObjC(parent));
282 }
283
284 SourceBufferPrivateAVFObjC::SourceBufferPrivateAVFObjC(MediaSourcePrivateAVFObjC* parent)
285     : m_parser(adoptNS([[getAVStreamDataParserClass() alloc] init]))
286     , m_delegate(adoptNS([[WebAVStreamDataParserListener alloc] initWithParser:m_parser.get() parent:this]))
287     , m_mediaSource(parent)
288     , m_client(0)
289     , m_parsingSucceeded(true)
290 {
291 }
292
293 SourceBufferPrivateAVFObjC::~SourceBufferPrivateAVFObjC()
294 {
295     if (m_displayLayer) {
296         if (m_mediaSource)
297             m_mediaSource->player()->removeDisplayLayer(m_displayLayer.get());
298         [m_displayLayer flushAndRemoveImage];
299         [m_displayLayer stopRequestingMediaData];
300         m_displayLayer = nullptr;
301     }
302 }
303
304 void SourceBufferPrivateAVFObjC::didParseStreamDataAsAsset(AVAsset* asset)
305 {
306     LOG(Media, "SourceBufferPrivateAVFObjC::didParseStreamDataAsAsset(%p)", this);
307
308     m_asset = asset;
309
310     SourceBufferPrivateClient::InitializationSegment segment;
311     segment.duration = toMediaTime([m_asset duration]);
312
313     for (AVAssetTrack* track in [m_asset tracks]) {
314         if ([track hasMediaCharacteristic:AVMediaCharacteristicVisual]) {
315             SourceBufferPrivateClient::InitializationSegment::VideoTrackInformation info;
316             info.track = VideoTrackPrivateMediaSourceAVFObjC::create(track, this);
317             info.description = MediaDescriptionAVFObjC::create(track);
318             segment.videoTracks.append(info);
319         } else if ([track hasMediaCharacteristic:AVMediaCharacteristicAudible]) {
320             SourceBufferPrivateClient::InitializationSegment::AudioTrackInformation info;
321             info.track = AudioTrackPrivateMediaSourceAVFObjC::create(track, this);
322             info.description = MediaDescriptionAVFObjC::create(track);
323             segment.audioTracks.append(info);
324         }
325
326         // FIXME(125161): Add TextTrack support
327     }
328
329     if (m_client)
330         m_client->sourceBufferPrivateDidReceiveInitializationSegment(this, segment);
331 }
332
333 void SourceBufferPrivateAVFObjC::didFailToParseStreamDataWithError(NSError* error)
334 {
335 #if LOG_DISABLED
336     UNUSED_PARAM(error);
337 #endif
338     LOG(Media, "SourceBufferPrivateAVFObjC::didFailToParseStreamDataWithError(%p) - error:\"%s\"", this, String([error description]).utf8().data());
339
340     m_parsingSucceeded = false;
341 }
342
343 struct ProcessCodedFrameInfo {
344     SourceBufferPrivateAVFObjC* sourceBuffer;
345     int trackID;
346     const String& mediaType;
347 };
348
349 static OSStatus callProcessCodedFrameForEachSample(CMSampleBufferRef sampleBuffer, CMItemCount, void *refcon)
350 {
351     ProcessCodedFrameInfo* info = static_cast<ProcessCodedFrameInfo*>(refcon);
352     return info->sourceBuffer->processCodedFrame(info->trackID, sampleBuffer, info->mediaType);
353 }
354
355 void SourceBufferPrivateAVFObjC::didProvideMediaDataForTrackID(int trackID, CMSampleBufferRef sampleBuffer, const String& mediaType, unsigned flags)
356 {
357     UNUSED_PARAM(flags);
358
359     ProcessCodedFrameInfo info = {this, trackID, mediaType};
360     CMSampleBufferCallForEachSample(sampleBuffer, &callProcessCodedFrameForEachSample, &info);
361 }
362
363 bool SourceBufferPrivateAVFObjC::processCodedFrame(int trackID, CMSampleBufferRef sampleBuffer, const String&)
364 {
365     if (m_client)
366         m_client->sourceBufferPrivateDidReceiveSample(this, MediaSampleAVFObjC::create(sampleBuffer, trackID));
367
368     return true;
369 }
370
371 void SourceBufferPrivateAVFObjC::didReachEndOfTrackWithTrackID(int trackID, const String& mediaType)
372 {
373     UNUSED_PARAM(mediaType);
374     UNUSED_PARAM(trackID);
375     notImplemented();
376 }
377
378 void SourceBufferPrivateAVFObjC::setClient(SourceBufferPrivateClient* client)
379 {
380     m_client = client;
381 }
382
383 SourceBufferPrivate::AppendResult SourceBufferPrivateAVFObjC::append(const unsigned char* data, unsigned length)
384 {
385     m_parsingSucceeded = true;
386
387     LOG(Media, "SourceBufferPrivateAVFObjC::append(%p) - data:%p, length:%d", this, data, length);
388     [m_parser appendStreamData:[NSData dataWithBytes:data length:length]];
389
390     if (m_parsingSucceeded && m_mediaSource)
391         m_mediaSource->player()->setLoadingProgresssed(true);
392
393     return m_parsingSucceeded ? AppendSucceeded : ParsingFailed;
394 }
395
396 void SourceBufferPrivateAVFObjC::abort()
397 {
398     notImplemented();
399 }
400
401 void SourceBufferPrivateAVFObjC::removedFromMediaSource()
402 {
403     if (m_displayLayer) {
404         if (m_mediaSource)
405             m_mediaSource->player()->removeDisplayLayer(m_displayLayer.get());
406         [m_displayLayer flush];
407         [m_displayLayer stopRequestingMediaData];
408         m_displayLayer = nullptr;
409     }
410
411     if (m_mediaSource)
412         m_mediaSource->removeSourceBuffer(this);
413 }
414
415 MediaPlayer::ReadyState SourceBufferPrivateAVFObjC::readyState() const
416 {
417     return m_mediaSource ? m_mediaSource->player()->readyState() : MediaPlayer::HaveNothing;
418 }
419
420 void SourceBufferPrivateAVFObjC::setReadyState(MediaPlayer::ReadyState readyState)
421 {
422     if (m_mediaSource)
423         m_mediaSource->player()->setReadyState(readyState);
424 }
425
426 void SourceBufferPrivateAVFObjC::evictCodedFrames()
427 {
428     notImplemented();
429 }
430
431 bool SourceBufferPrivateAVFObjC::isFull()
432 {
433     notImplemented();
434     return false;
435 }
436
437
438 bool SourceBufferPrivateAVFObjC::hasVideo() const
439 {
440     if (!m_client)
441         return false;
442
443     return m_client->sourceBufferPrivateHasVideo(this);
444 }
445
446 bool SourceBufferPrivateAVFObjC::hasAudio() const
447 {
448     if (!m_client)
449         return false;
450
451     return m_client->sourceBufferPrivateHasAudio(this);
452 }
453
454 void SourceBufferPrivateAVFObjC::trackDidChangeEnabled(VideoTrackPrivateMediaSourceAVFObjC* track)
455 {
456     int trackID = track->trackID();
457     if (!track->selected() && m_enabledVideoTrackID == trackID) {
458         m_enabledVideoTrackID = -1;
459         [m_parser setShouldProvideMediaData:NO forTrackID:trackID];
460         if (m_mediaSource)
461             m_mediaSource->player()->removeDisplayLayer(m_displayLayer.get());
462     } else if (track->selected()) {
463         m_enabledVideoTrackID = trackID;
464         [m_parser setShouldProvideMediaData:YES forTrackID:trackID];
465         if (!m_displayLayer) {
466             m_displayLayer = [[getAVSampleBufferDisplayLayerClass() alloc] init];
467             [m_displayLayer requestMediaDataWhenReadyOnQueue:dispatch_get_main_queue() usingBlock:^{
468                 if (m_client)
469                     m_client->sourceBufferPrivateDidBecomeReadyForMoreSamples(this);
470             }];
471             if (m_mediaSource)
472                 m_mediaSource->player()->addDisplayLayer(m_displayLayer.get());
473         }
474     }
475 }
476
477 void SourceBufferPrivateAVFObjC::trackDidChangeEnabled(AudioTrackPrivateMediaSourceAVFObjC*)
478 {
479     // No-op.
480 }
481
482 static RetainPtr<CMSampleBufferRef> createNonDisplayingCopy(CMSampleBufferRef sampleBuffer)
483 {
484     CMSampleBufferRef newSampleBuffer = 0;
485     CMSampleBufferCreateCopy(kCFAllocatorDefault, sampleBuffer, &newSampleBuffer);
486     if (!newSampleBuffer)
487         return sampleBuffer;
488
489     CFArrayRef attachmentsArray = CMSampleBufferGetSampleAttachmentsArray(newSampleBuffer, true);
490     for (CFIndex i = 0; i < CFArrayGetCount(attachmentsArray); ++i) {
491         CFMutableDictionaryRef attachments = (CFMutableDictionaryRef)CFArrayGetValueAtIndex(attachmentsArray, i);
492         CFDictionarySetValue(attachments, kCMSampleAttachmentKey_DoNotDisplay, kCFBooleanTrue);
493     }
494
495     return adoptCF(newSampleBuffer);
496 }
497
498 void SourceBufferPrivateAVFObjC::flushAndEnqueueNonDisplayingSamples(Vector<RefPtr<MediaSample>> mediaSamples, AtomicString trackID)
499 {
500     if (trackID.toInt() != m_enabledVideoTrackID)
501         return;
502
503     LOG(Media, "SourceBufferPrivateAVFObjC::flushAndEnqueueNonDisplayingSamples(%p) samples: %d samples, trackId: %d", this, mediaSamples.size(), trackID.toInt());
504
505     [m_displayLayer flush];
506
507     for (auto it = mediaSamples.begin(), end = mediaSamples.end(); it != end; ++it) {
508         RefPtr<MediaSample>& mediaSample = *it;
509
510         PlatformSample platformSample = mediaSample->platformSample();
511         ASSERT(platformSample.type == PlatformSample::CMSampleBufferType);
512
513         RetainPtr<CMSampleBufferRef> sampleBuffer = createNonDisplayingCopy(platformSample.sample.cmSampleBuffer);
514
515         [m_displayLayer enqueueSampleBuffer:sampleBuffer.get()];
516     }
517
518     if (m_mediaSource)
519         m_mediaSource->player()->setHasAvailableVideoFrame(false);
520 }
521
522 void SourceBufferPrivateAVFObjC::enqueueSample(PassRefPtr<MediaSample> prpMediaSample, AtomicString trackID)
523 {
524     if (trackID.toInt() != m_enabledVideoTrackID)
525         return;
526
527     RefPtr<MediaSample> mediaSample = prpMediaSample;
528
529     PlatformSample platformSample = mediaSample->platformSample();
530     if (platformSample.type != PlatformSample::CMSampleBufferType)
531         return;
532
533     [m_displayLayer enqueueSampleBuffer:platformSample.sample.cmSampleBuffer];
534     if (m_mediaSource)
535         m_mediaSource->player()->setHasAvailableVideoFrame(true);
536 }
537
538 bool SourceBufferPrivateAVFObjC::isReadyForMoreSamples()
539 {
540     return [m_displayLayer isReadyForMoreMediaData];
541 }
542
543 void SourceBufferPrivateAVFObjC::setActive(bool isActive)
544 {
545     if (m_mediaSource)
546         m_mediaSource->sourceBufferPrivateDidChangeActiveState(this, isActive);
547 }
548
549 MediaTime SourceBufferPrivateAVFObjC::fastSeekTimeForMediaTime(MediaTime time, MediaTime negativeThreshold, MediaTime positiveThreshold)
550 {
551     if (m_client)
552         return m_client->sourceBufferPrivateFastSeekTimeForMediaTime(this, time, negativeThreshold, positiveThreshold);
553     return time;
554 }
555
556 void SourceBufferPrivateAVFObjC::seekToTime(MediaTime time)
557 {
558     if (m_client)
559         m_client->sourceBufferPrivateSeekToTime(this, time);
560 }
561
562 }
563
564 #endif // ENABLE(MEDIA_SOURCE) && USE(AVFOUNDATION)