Remove workaround for compilers not supporting explicit override control
[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/AVFoundation.h>
46 #import <objc/runtime.h>
47 #import <wtf/text/AtomicString.h>
48 #import <wtf/text/CString.h>
49 #import <wtf/HashCountedSet.h>
50 #import <wtf/WeakPtr.h>
51 #import <map>
52
53 #pragma mark -
54 #pragma mark Soft Linking
55
56 SOFT_LINK_FRAMEWORK_OPTIONAL(AVFoundation)
57 SOFT_LINK_FRAMEWORK_OPTIONAL(CoreMedia)
58
59 SOFT_LINK_CLASS(AVFoundation, AVAssetTrack)
60 SOFT_LINK_CLASS(AVFoundation, AVStreamDataParser)
61 SOFT_LINK_CLASS(AVFoundation, AVSampleBufferAudioRenderer)
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
111 @interface AVStreamDataParser : NSObject
112 - (void)setDelegate:(id)delegate;
113 - (void)appendStreamData:(NSData *)data;
114 - (void)setShouldProvideMediaData:(BOOL)shouldProvideMediaData forTrackID:(CMPersistentTrackID)trackID;
115 - (BOOL)shouldProvideMediaDataForTrackID:(CMPersistentTrackID)trackID;
116 @end
117
118 #pragma mark -
119 #pragma mark AVSampleBufferAudioRenderer
120
121 #if PLATFORM(IOS) || __MAC_OS_X_VERSION_MIN_REQUIRED <= 1090
122 @interface AVSampleBufferAudioRenderer : NSObject
123 - (NSInteger)status;
124 - (NSError*)error;
125 - (void)enqueueSampleBuffer:(CMSampleBufferRef)sampleBuffer;
126 - (void)flush;
127 - (BOOL)isReadyForMoreMediaData;
128 - (void)requestMediaDataWhenReadyOnQueue:(dispatch_queue_t)queue usingBlock:(void (^)(void))block;
129 - (void)stopRequestingMediaData;
130 @end
131 #endif
132
133 #pragma mark -
134 #pragma mark WebAVStreamDataParserListener
135
136 @interface WebAVStreamDataParserListener : NSObject {
137     WebCore::SourceBufferPrivateAVFObjC* _parent;
138     AVStreamDataParser* _parser;
139 }
140 - (id)initWithParser:(AVStreamDataParser*)parser parent:(WebCore::SourceBufferPrivateAVFObjC*)parent;
141 @end
142
143 @implementation WebAVStreamDataParserListener
144 - (id)initWithParser:(AVStreamDataParser*)parser parent:(WebCore::SourceBufferPrivateAVFObjC*)parent
145 {
146     self = [super init];
147     if (!self)
148         return nil;
149
150     ASSERT(parent);
151     _parent = parent;
152     _parser = parser;
153     [_parser setDelegate:self];
154     return self;
155 }
156
157 - (void)dealloc
158 {
159     [_parser setDelegate:nil];
160     [super dealloc];
161 }
162
163 - (void)streamDataParser:(AVStreamDataParser *)streamDataParser didParseStreamDataAsAsset:(AVAsset *)asset
164 {
165 #if ASSERT_DISABLED
166     UNUSED_PARAM(streamDataParser);
167 #endif
168     ASSERT(streamDataParser == _parser);
169     _parent->didParseStreamDataAsAsset(asset);
170 }
171
172 - (void)streamDataParser:(AVStreamDataParser *)streamDataParser didFailToParseStreamDataWithError:(NSError *)error
173 {
174 #if ASSERT_DISABLED
175     UNUSED_PARAM(streamDataParser);
176 #endif
177     ASSERT(streamDataParser == _parser);
178     _parent->didFailToParseStreamDataWithError(error);
179 }
180
181 - (void)streamDataParser:(AVStreamDataParser *)streamDataParser didProvideMediaData:(CMSampleBufferRef)mediaData forTrackID:(CMPersistentTrackID)trackID mediaType:(NSString *)mediaType flags:(NSUInteger)flags
182 {
183 #if ASSERT_DISABLED
184     UNUSED_PARAM(streamDataParser);
185 #endif
186     ASSERT(streamDataParser == _parser);
187     _parent->didProvideMediaDataForTrackID(trackID, mediaData, mediaType, flags);
188 }
189
190 - (void)streamDataParser:(AVStreamDataParser *)streamDataParser didReachEndOfTrackWithTrackID:(CMPersistentTrackID)trackID mediaType:(NSString *)mediaType
191 {
192 #if ASSERT_DISABLED
193     UNUSED_PARAM(streamDataParser);
194 #endif
195     ASSERT(streamDataParser == _parser);
196     _parent->didReachEndOfTrackWithTrackID(trackID, mediaType);
197 }
198 @end
199
200 namespace WebCore {
201
202 #pragma mark -
203 #pragma mark MediaSampleAVFObjC
204
205 class MediaSampleAVFObjC FINAL : public MediaSample {
206 public:
207     static RefPtr<MediaSampleAVFObjC> create(CMSampleBufferRef sample, int trackID) { return adoptRef(new MediaSampleAVFObjC(sample, trackID)); }
208     virtual ~MediaSampleAVFObjC() { }
209
210     virtual MediaTime presentationTime() const override { return toMediaTime(CMSampleBufferGetPresentationTimeStamp(m_sample.get())); }
211     virtual MediaTime decodeTime() const override { return toMediaTime(CMSampleBufferGetDecodeTimeStamp(m_sample.get())); }
212     virtual MediaTime duration() const override { return toMediaTime(CMSampleBufferGetDuration(m_sample.get())); }
213     virtual AtomicString trackID() const override { return m_id; }
214
215     virtual SampleFlags flags() const override;
216     virtual PlatformSample platformSample() override;
217
218 protected:
219     MediaSampleAVFObjC(CMSampleBufferRef sample, int trackID)
220         : m_sample(sample)
221         , m_id(String::format("%d", trackID))
222     {
223     }
224
225     RetainPtr<CMSampleBufferRef> m_sample;
226     AtomicString m_id;
227 };
228
229 PlatformSample MediaSampleAVFObjC::platformSample()
230 {
231     PlatformSample sample = { PlatformSample::CMSampleBufferType, { .cmSampleBuffer = m_sample.get() } };
232     return sample;
233 }
234
235 static bool CMSampleBufferIsRandomAccess(CMSampleBufferRef sample)
236 {
237     CFArrayRef attachments = CMSampleBufferGetSampleAttachmentsArray(sample, false);
238     if (!attachments)
239         return true;
240
241     for (CFIndex i = 0, count = CFArrayGetCount(attachments); i < count; ++i) {
242         CFDictionaryRef attachmentDict = (CFDictionaryRef)CFArrayGetValueAtIndex(attachments, i);
243         if (CFDictionaryContainsKey(attachmentDict, kCMSampleAttachmentKey_NotSync))
244             return false;
245     }
246     return true;
247 }
248
249 MediaSample::SampleFlags MediaSampleAVFObjC::flags() const
250 {
251     int returnValue = MediaSample::None;
252
253     if (CMSampleBufferIsRandomAccess(m_sample.get()))
254         returnValue |= MediaSample::IsSync;
255
256     return SampleFlags(returnValue);
257 }
258
259 #pragma mark -
260 #pragma mark MediaDescriptionAVFObjC
261
262 class MediaDescriptionAVFObjC FINAL : public MediaDescription {
263 public:
264     static RefPtr<MediaDescriptionAVFObjC> create(AVAssetTrack* track) { return adoptRef(new MediaDescriptionAVFObjC(track)); }
265     virtual ~MediaDescriptionAVFObjC() { }
266
267     virtual AtomicString codec() const override { return m_codec; }
268     virtual bool isVideo() const override { return m_isVideo; }
269     virtual bool isAudio() const override { return m_isAudio; }
270     virtual bool isText() const override { return m_isText; }
271     
272 protected:
273     MediaDescriptionAVFObjC(AVAssetTrack* track)
274         : m_isVideo([track hasMediaCharacteristic:AVMediaCharacteristicVisual])
275         , m_isAudio([track hasMediaCharacteristic:AVMediaCharacteristicAudible])
276         , m_isText([track hasMediaCharacteristic:AVMediaCharacteristicLegible])
277     {
278         NSArray* formatDescriptions = [track formatDescriptions];
279         CMFormatDescriptionRef description = [formatDescriptions count] ? (CMFormatDescriptionRef)[formatDescriptions objectAtIndex:0] : 0;
280         if (description) {
281             FourCharCode codec = CMFormatDescriptionGetMediaSubType(description);
282             m_codec = AtomicString(reinterpret_cast<LChar*>(&codec), 4);
283         }
284     }
285
286     AtomicString m_codec;
287     bool m_isVideo;
288     bool m_isAudio;
289     bool m_isText;
290 };
291
292 #pragma mark -
293 #pragma mark SourceBufferPrivateAVFObjC
294
295 RefPtr<SourceBufferPrivateAVFObjC> SourceBufferPrivateAVFObjC::create(MediaSourcePrivateAVFObjC* parent)
296 {
297     return adoptRef(new SourceBufferPrivateAVFObjC(parent));
298 }
299
300 SourceBufferPrivateAVFObjC::SourceBufferPrivateAVFObjC(MediaSourcePrivateAVFObjC* parent)
301     : m_parser(adoptNS([[getAVStreamDataParserClass() alloc] init]))
302     , m_delegate(adoptNS([[WebAVStreamDataParserListener alloc] initWithParser:m_parser.get() parent:this]))
303     , m_mediaSource(parent)
304     , m_client(0)
305     , m_parsingSucceeded(true)
306     , m_enabledVideoTrackID(-1)
307 {
308 }
309
310 SourceBufferPrivateAVFObjC::~SourceBufferPrivateAVFObjC()
311 {
312     destroyRenderers();
313 }
314
315 void SourceBufferPrivateAVFObjC::didParseStreamDataAsAsset(AVAsset* asset)
316 {
317     LOG(Media, "SourceBufferPrivateAVFObjC::didParseStreamDataAsAsset(%p)", this);
318
319     m_asset = asset;
320
321     m_videoTracks.clear();
322     m_audioTracks.clear();
323
324     SourceBufferPrivateClient::InitializationSegment segment;
325     segment.duration = toMediaTime([m_asset duration]);
326
327     for (AVAssetTrack* track in [m_asset tracks]) {
328         if ([track hasMediaCharacteristic:AVMediaCharacteristicVisual]) {
329             SourceBufferPrivateClient::InitializationSegment::VideoTrackInformation info;
330             RefPtr<VideoTrackPrivateMediaSourceAVFObjC> videoTrack = VideoTrackPrivateMediaSourceAVFObjC::create(track, this);
331             info.track = videoTrack;
332             m_videoTracks.append(videoTrack);
333             info.description = MediaDescriptionAVFObjC::create(track);
334             segment.videoTracks.append(info);
335         } else if ([track hasMediaCharacteristic:AVMediaCharacteristicAudible]) {
336             SourceBufferPrivateClient::InitializationSegment::AudioTrackInformation info;
337             RefPtr<AudioTrackPrivateMediaSourceAVFObjC> audioTrack = AudioTrackPrivateMediaSourceAVFObjC::create(track, this);
338             info.track = audioTrack;
339             m_audioTracks.append(audioTrack);
340             info.description = MediaDescriptionAVFObjC::create(track);
341             segment.audioTracks.append(info);
342         }
343
344         // FIXME(125161): Add TextTrack support
345     }
346
347     if (!m_videoTracks.isEmpty())
348         m_mediaSource->player()->sizeChanged();
349
350     if (m_client)
351         m_client->sourceBufferPrivateDidReceiveInitializationSegment(this, segment);
352 }
353
354 void SourceBufferPrivateAVFObjC::didFailToParseStreamDataWithError(NSError* error)
355 {
356 #if LOG_DISABLED
357     UNUSED_PARAM(error);
358 #endif
359     LOG(Media, "SourceBufferPrivateAVFObjC::didFailToParseStreamDataWithError(%p) - error:\"%s\"", this, String([error description]).utf8().data());
360
361     m_parsingSucceeded = false;
362 }
363
364 struct ProcessCodedFrameInfo {
365     SourceBufferPrivateAVFObjC* sourceBuffer;
366     int trackID;
367     const String& mediaType;
368 };
369
370 void SourceBufferPrivateAVFObjC::didProvideMediaDataForTrackID(int trackID, CMSampleBufferRef sampleBuffer, const String& mediaType, unsigned flags)
371 {
372     UNUSED_PARAM(flags);
373
374     processCodedFrame(trackID, sampleBuffer, mediaType);
375 }
376
377 bool SourceBufferPrivateAVFObjC::processCodedFrame(int trackID, CMSampleBufferRef sampleBuffer, const String&)
378 {
379     if (m_client)
380         m_client->sourceBufferPrivateDidReceiveSample(this, MediaSampleAVFObjC::create(sampleBuffer, trackID));
381
382     return true;
383 }
384
385 void SourceBufferPrivateAVFObjC::didReachEndOfTrackWithTrackID(int trackID, const String& mediaType)
386 {
387     UNUSED_PARAM(mediaType);
388     UNUSED_PARAM(trackID);
389     notImplemented();
390 }
391
392 void SourceBufferPrivateAVFObjC::setClient(SourceBufferPrivateClient* client)
393 {
394     m_client = client;
395 }
396
397 SourceBufferPrivate::AppendResult SourceBufferPrivateAVFObjC::append(const unsigned char* data, unsigned length)
398 {
399     m_parsingSucceeded = true;
400
401     LOG(Media, "SourceBufferPrivateAVFObjC::append(%p) - data:%p, length:%d", this, data, length);
402     [m_parser appendStreamData:[NSData dataWithBytes:data length:length]];
403
404     if (m_parsingSucceeded && m_mediaSource)
405         m_mediaSource->player()->setLoadingProgresssed(true);
406
407     return m_parsingSucceeded ? AppendSucceeded : ParsingFailed;
408 }
409
410 void SourceBufferPrivateAVFObjC::abort()
411 {
412     notImplemented();
413 }
414
415 void SourceBufferPrivateAVFObjC::destroyRenderers()
416 {
417     if (m_displayLayer) {
418         if (m_mediaSource)
419             m_mediaSource->player()->removeDisplayLayer(m_displayLayer.get());
420         [m_displayLayer flush];
421         [m_displayLayer stopRequestingMediaData];
422         m_displayLayer = nullptr;
423     }
424
425     for (auto it = m_audioRenderers.begin(), end = m_audioRenderers.end(); it != end; ++it) {
426         AVSampleBufferAudioRenderer* renderer = it->second.get();
427         if (m_mediaSource)
428             m_mediaSource->player()->removeAudioRenderer(renderer);
429         [renderer flush];
430         [renderer stopRequestingMediaData];
431     }
432
433     m_audioRenderers.clear();
434 }
435
436 void SourceBufferPrivateAVFObjC::removedFromMediaSource()
437 {
438     destroyRenderers();
439
440     if (m_mediaSource)
441         m_mediaSource->removeSourceBuffer(this);
442 }
443
444 MediaPlayer::ReadyState SourceBufferPrivateAVFObjC::readyState() const
445 {
446     return m_mediaSource ? m_mediaSource->player()->readyState() : MediaPlayer::HaveNothing;
447 }
448
449 void SourceBufferPrivateAVFObjC::setReadyState(MediaPlayer::ReadyState readyState)
450 {
451     if (m_mediaSource)
452         m_mediaSource->player()->setReadyState(readyState);
453 }
454
455 void SourceBufferPrivateAVFObjC::evictCodedFrames()
456 {
457     notImplemented();
458 }
459
460 bool SourceBufferPrivateAVFObjC::isFull()
461 {
462     notImplemented();
463     return false;
464 }
465
466
467 bool SourceBufferPrivateAVFObjC::hasVideo() const
468 {
469     if (!m_client)
470         return false;
471
472     return m_client->sourceBufferPrivateHasVideo(this);
473 }
474
475 bool SourceBufferPrivateAVFObjC::hasAudio() const
476 {
477     if (!m_client)
478         return false;
479
480     return m_client->sourceBufferPrivateHasAudio(this);
481 }
482
483 void SourceBufferPrivateAVFObjC::trackDidChangeEnabled(VideoTrackPrivateMediaSourceAVFObjC* track)
484 {
485     int trackID = track->trackID();
486     if (!track->selected() && m_enabledVideoTrackID == trackID) {
487         m_enabledVideoTrackID = -1;
488         [m_parser setShouldProvideMediaData:NO forTrackID:trackID];
489         if (m_mediaSource)
490             m_mediaSource->player()->removeDisplayLayer(m_displayLayer.get());
491     } else if (track->selected()) {
492         m_enabledVideoTrackID = trackID;
493         [m_parser setShouldProvideMediaData:YES forTrackID:trackID];
494         if (!m_displayLayer) {
495             m_displayLayer = [[getAVSampleBufferDisplayLayerClass() alloc] init];
496             [m_displayLayer requestMediaDataWhenReadyOnQueue:dispatch_get_main_queue() usingBlock:^{
497                 didBecomeReadyForMoreSamples(trackID);
498             }];
499         }
500         if (m_mediaSource)
501             m_mediaSource->player()->addDisplayLayer(m_displayLayer.get());
502     }
503 }
504
505 void SourceBufferPrivateAVFObjC::trackDidChangeEnabled(AudioTrackPrivateMediaSourceAVFObjC* track)
506 {
507     int trackID = track->trackID();
508
509     if (!track->enabled()) {
510         AVSampleBufferAudioRenderer* renderer = m_audioRenderers[trackID].get();
511         [m_parser setShouldProvideMediaData:NO forTrackID:trackID];
512         if (m_mediaSource)
513             m_mediaSource->player()->removeAudioRenderer(renderer);
514     } else {
515         [m_parser setShouldProvideMediaData:YES forTrackID:trackID];
516         AVSampleBufferAudioRenderer* renderer;
517         if (!m_audioRenderers.count(trackID)) {
518             renderer = [[getAVSampleBufferAudioRendererClass() alloc] init];
519             [renderer requestMediaDataWhenReadyOnQueue:dispatch_get_main_queue() usingBlock:^{
520                 didBecomeReadyForMoreSamples(trackID);
521             }];
522             m_audioRenderers[trackID] = renderer;
523         } else
524             renderer = m_audioRenderers[trackID].get();
525
526         if (m_mediaSource)
527             m_mediaSource->player()->addAudioRenderer(renderer);
528     }
529 }
530
531 static RetainPtr<CMSampleBufferRef> createNonDisplayingCopy(CMSampleBufferRef sampleBuffer)
532 {
533     CMSampleBufferRef newSampleBuffer = 0;
534     CMSampleBufferCreateCopy(kCFAllocatorDefault, sampleBuffer, &newSampleBuffer);
535     if (!newSampleBuffer)
536         return sampleBuffer;
537
538     CFArrayRef attachmentsArray = CMSampleBufferGetSampleAttachmentsArray(newSampleBuffer, true);
539     for (CFIndex i = 0; i < CFArrayGetCount(attachmentsArray); ++i) {
540         CFMutableDictionaryRef attachments = (CFMutableDictionaryRef)CFArrayGetValueAtIndex(attachmentsArray, i);
541         CFDictionarySetValue(attachments, kCMSampleAttachmentKey_DoNotDisplay, kCFBooleanTrue);
542     }
543
544     return adoptCF(newSampleBuffer);
545 }
546
547 void SourceBufferPrivateAVFObjC::flushAndEnqueueNonDisplayingSamples(Vector<RefPtr<MediaSample>> mediaSamples, AtomicString trackIDString)
548 {
549     int trackID = trackIDString.toInt();
550     LOG(Media, "SourceBufferPrivateAVFObjC::flushAndEnqueueNonDisplayingSamples(%p) samples: %d samples, trackId: %d", this, mediaSamples.size(), trackID);
551
552     if (trackID == m_enabledVideoTrackID)
553         flushAndEnqueueNonDisplayingSamples(mediaSamples, m_displayLayer.get());
554     else if (m_audioRenderers.count(trackID))
555         flushAndEnqueueNonDisplayingSamples(mediaSamples, m_audioRenderers[trackID].get());
556 }
557
558 void SourceBufferPrivateAVFObjC::flushAndEnqueueNonDisplayingSamples(Vector<RefPtr<MediaSample>> mediaSamples, AVSampleBufferAudioRenderer* renderer)
559 {
560     [renderer flush];
561
562     for (auto it = mediaSamples.begin(), end = mediaSamples.end(); it != end; ++it) {
563         RefPtr<MediaSample>& mediaSample = *it;
564
565         PlatformSample platformSample = mediaSample->platformSample();
566         ASSERT(platformSample.type == PlatformSample::CMSampleBufferType);
567
568         RetainPtr<CMSampleBufferRef> sampleBuffer = createNonDisplayingCopy(platformSample.sample.cmSampleBuffer);
569
570         [renderer enqueueSampleBuffer:sampleBuffer.get()];
571     }
572 }
573
574 void SourceBufferPrivateAVFObjC::flushAndEnqueueNonDisplayingSamples(Vector<RefPtr<MediaSample>> mediaSamples, AVSampleBufferDisplayLayer* layer)
575 {
576     [layer flush];
577
578     for (auto it = mediaSamples.begin(), end = mediaSamples.end(); it != end; ++it) {
579         RefPtr<MediaSample>& mediaSample = *it;
580
581         PlatformSample platformSample = mediaSample->platformSample();
582         ASSERT(platformSample.type == PlatformSample::CMSampleBufferType);
583
584         RetainPtr<CMSampleBufferRef> sampleBuffer = createNonDisplayingCopy(platformSample.sample.cmSampleBuffer);
585
586         [layer enqueueSampleBuffer:sampleBuffer.get()];
587     }
588
589     if (m_mediaSource)
590         m_mediaSource->player()->setHasAvailableVideoFrame(false);
591 }
592
593 void SourceBufferPrivateAVFObjC::enqueueSample(PassRefPtr<MediaSample> prpMediaSample, AtomicString trackIDString)
594 {
595     int trackID = trackIDString.toInt();
596     if (trackID != m_enabledVideoTrackID && !m_audioRenderers.count(trackID))
597         return;
598
599     RefPtr<MediaSample> mediaSample = prpMediaSample;
600
601     PlatformSample platformSample = mediaSample->platformSample();
602     if (platformSample.type != PlatformSample::CMSampleBufferType)
603         return;
604
605     if (trackID == m_enabledVideoTrackID) {
606         [m_displayLayer enqueueSampleBuffer:platformSample.sample.cmSampleBuffer];
607         if (m_mediaSource)
608             m_mediaSource->player()->setHasAvailableVideoFrame(true);
609     } else
610         [m_audioRenderers[trackID] enqueueSampleBuffer:platformSample.sample.cmSampleBuffer];
611 }
612
613 bool SourceBufferPrivateAVFObjC::isReadyForMoreSamples(AtomicString trackIDString)
614 {
615     int trackID = trackIDString.toInt();
616     if (trackID == m_enabledVideoTrackID)
617         return [m_displayLayer isReadyForMoreMediaData];
618     else if (m_audioRenderers.count(trackID))
619         return [m_audioRenderers[trackID] isReadyForMoreMediaData];
620     else
621         ASSERT_NOT_REACHED();
622
623     return false;
624 }
625
626 void SourceBufferPrivateAVFObjC::setActive(bool isActive)
627 {
628     if (m_mediaSource)
629         m_mediaSource->sourceBufferPrivateDidChangeActiveState(this, isActive);
630 }
631
632 MediaTime SourceBufferPrivateAVFObjC::fastSeekTimeForMediaTime(MediaTime time, MediaTime negativeThreshold, MediaTime positiveThreshold)
633 {
634     if (m_client)
635         return m_client->sourceBufferPrivateFastSeekTimeForMediaTime(this, time, negativeThreshold, positiveThreshold);
636     return time;
637 }
638
639 void SourceBufferPrivateAVFObjC::seekToTime(MediaTime time)
640 {
641     if (m_client)
642         m_client->sourceBufferPrivateSeekToTime(this, time);
643 }
644
645 IntSize SourceBufferPrivateAVFObjC::naturalSize()
646 {
647     for (auto videoTrack : m_videoTracks) {
648         if (videoTrack->selected())
649             return videoTrack->naturalSize();
650     }
651
652     return IntSize();
653 }
654
655 void SourceBufferPrivateAVFObjC::didBecomeReadyForMoreSamples(int trackID)
656 {
657     if (trackID == m_enabledVideoTrackID)
658         [m_displayLayer stopRequestingMediaData];
659     else if (m_audioRenderers.count(trackID))
660         [m_audioRenderers[trackID] stopRequestingMediaData];
661     else {
662         ASSERT_NOT_REACHED();
663         return;
664     }
665
666     if (m_client)
667         m_client->sourceBufferPrivateDidBecomeReadyForMoreSamples(this, AtomicString::number(trackID));
668 }
669
670 void SourceBufferPrivateAVFObjC::notifyClientWhenReadyForMoreSamples(AtomicString trackIDString)
671 {
672     int trackID = trackIDString.toInt();
673     if (trackID == m_enabledVideoTrackID) {
674         [m_displayLayer requestMediaDataWhenReadyOnQueue:dispatch_get_main_queue() usingBlock:^{
675             didBecomeReadyForMoreSamples(trackID);
676         }];
677     } else if (m_audioRenderers.count(trackID)) {
678         [m_audioRenderers[trackID] requestMediaDataWhenReadyOnQueue:dispatch_get_main_queue() usingBlock:^{
679             didBecomeReadyForMoreSamples(trackID);
680         }];
681     } else
682         ASSERT_NOT_REACHED();
683 }
684
685 }
686
687 #endif // ENABLE(MEDIA_SOURCE) && USE(AVFOUNDATION)