85144adf4590a6d8c42fe05b813fc51fa8b3cb3b
[WebKit-https.git] / Source / WebCore / platform / mediastream / mac / AVVideoCaptureSource.mm
1 /*
2  * Copyright (C) 2013-2019 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 #import "AVVideoCaptureSource.h"
28
29 #if ENABLE(MEDIA_STREAM) && USE(AVFOUNDATION)
30
31 #import "ImageBuffer.h"
32 #import "ImageTransferSessionVT.h"
33 #import "IntRect.h"
34 #import "Logging.h"
35 #import "MediaConstraints.h"
36 #import "MediaSampleAVFObjC.h"
37 #import "PlatformLayer.h"
38 #import "RealtimeMediaSourceCenter.h"
39 #import "RealtimeMediaSourceSettings.h"
40 #import "RealtimeVideoUtilities.h"
41 #import <AVFoundation/AVCaptureDevice.h>
42 #import <AVFoundation/AVCaptureInput.h>
43 #import <AVFoundation/AVCaptureOutput.h>
44 #import <AVFoundation/AVCaptureSession.h>
45 #import <AVFoundation/AVError.h>
46 #import <objc/runtime.h>
47
48 #import "CoreVideoSoftLink.h"
49 #import <pal/cocoa/AVFoundationSoftLink.h>
50 #import <pal/cf/CoreMediaSoftLink.h>
51
52 using namespace WebCore;
53 using namespace PAL;
54
55 @interface WebCoreAVVideoCaptureSourceObserver : NSObject<AVCaptureVideoDataOutputSampleBufferDelegate> {
56     AVVideoCaptureSource* m_callback;
57 }
58
59 -(id)initWithCallback:(AVVideoCaptureSource*)callback;
60 -(void)disconnect;
61 -(void)addNotificationObservers;
62 -(void)removeNotificationObservers;
63 -(void)captureOutput:(AVCaptureOutput*)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection*)connection;
64 -(void)observeValueForKeyPath:keyPath ofObject:(id)object change:(NSDictionary*)change context:(void*)context;
65 #if PLATFORM(IOS_FAMILY)
66 -(void)sessionRuntimeError:(NSNotification*)notification;
67 -(void)beginSessionInterrupted:(NSNotification*)notification;
68 -(void)endSessionInterrupted:(NSNotification*)notification;
69 -(void)deviceConnectedDidChange:(NSNotification*)notification;
70 #endif
71 @end
72
73 namespace WebCore {
74
75 static inline OSType avVideoCapturePixelBufferFormat()
76 {
77     // FIXME: Use preferedPixelBufferFormat() once rdar://problem/44391444 is fixed.
78 #if PLATFORM(MAC)
79     return kCVPixelFormatType_420YpCbCr8Planar;
80 #else
81     return preferedPixelBufferFormat();
82 #endif
83 }
84
85 static dispatch_queue_t globaVideoCaptureSerialQueue()
86 {
87     static dispatch_queue_t globalQueue;
88     static dispatch_once_t onceToken;
89     dispatch_once(&onceToken, ^{
90         globalQueue = dispatch_queue_create_with_target("WebCoreAVVideoCaptureSource video capture queue", DISPATCH_QUEUE_SERIAL, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0));
91     });
92     return globalQueue;
93 }
94
95 class AVVideoPreset : public VideoPreset {
96 public:
97     static Ref<AVVideoPreset> create(IntSize size, Vector<FrameRateRange>&& frameRateRanges, AVCaptureDeviceFormat* format)
98     {
99         return adoptRef(*new AVVideoPreset(size, WTFMove(frameRateRanges), format));
100     }
101
102     AVVideoPreset(IntSize size, Vector<FrameRateRange>&& frameRateRanges, AVCaptureDeviceFormat* format)
103         : VideoPreset(size, WTFMove(frameRateRanges), AVCapture)
104         , format(format)
105     {
106     }
107
108     RetainPtr<AVCaptureDeviceFormat> format;
109 };
110
111 CaptureSourceOrError AVVideoCaptureSource::create(String&& id, String&& hashSalt, const MediaConstraints* constraints)
112 {
113     AVCaptureDevice *device = [PAL::getAVCaptureDeviceClass() deviceWithUniqueID:id];
114     if (!device)
115         return { };
116
117     auto source = adoptRef(*new AVVideoCaptureSource(device, WTFMove(id), WTFMove(hashSalt)));
118     if (constraints) {
119         auto result = source->applyConstraints(*constraints);
120         if (result)
121             return WTFMove(result.value().badConstraint);
122     }
123
124     return CaptureSourceOrError(WTFMove(source));
125 }
126
127 AVVideoCaptureSource::AVVideoCaptureSource(AVCaptureDevice* device, String&& id, String&& hashSalt)
128     : RealtimeVideoSource(device.localizedName, WTFMove(id), WTFMove(hashSalt))
129     , m_objcObserver(adoptNS([[WebCoreAVVideoCaptureSourceObserver alloc] initWithCallback:this]))
130     , m_device(device)
131 {
132 #if PLATFORM(IOS_FAMILY)
133     static_assert(static_cast<int>(InterruptionReason::VideoNotAllowedInBackground) == static_cast<int>(AVCaptureSessionInterruptionReasonVideoDeviceNotAvailableInBackground), "InterruptionReason::VideoNotAllowedInBackground is not AVCaptureSessionInterruptionReasonVideoDeviceNotAvailableInBackground as expected");
134     static_assert(static_cast<int>(InterruptionReason::VideoNotAllowedInSideBySide) == AVCaptureSessionInterruptionReasonVideoDeviceNotAvailableWithMultipleForegroundApps, "InterruptionReason::VideoNotAllowedInSideBySide is not AVCaptureSessionInterruptionReasonVideoDeviceNotAvailableWithMultipleForegroundApps as expected");
135     static_assert(static_cast<int>(InterruptionReason::VideoInUse) == AVCaptureSessionInterruptionReasonVideoDeviceInUseByAnotherClient, "InterruptionReason::VideoInUse is not AVCaptureSessionInterruptionReasonVideoDeviceInUseByAnotherClient as expected");
136     static_assert(static_cast<int>(InterruptionReason::AudioInUse) == AVCaptureSessionInterruptionReasonAudioDeviceInUseByAnotherClient, "InterruptionReason::AudioInUse is not AVCaptureSessionInterruptionReasonAudioDeviceInUseByAnotherClient as expected");
137 #endif
138
139     [m_device.get() addObserver:m_objcObserver.get() forKeyPath:@"suspended" options:NSKeyValueObservingOptionNew context:(void *)nil];
140 }
141
142 AVVideoCaptureSource::~AVVideoCaptureSource()
143 {
144 #if PLATFORM(IOS_FAMILY)
145     RealtimeMediaSourceCenter::singleton().videoCaptureFactory().unsetActiveSource(*this);
146 #endif
147     [m_objcObserver disconnect];
148     [m_device removeObserver:m_objcObserver.get() forKeyPath:@"suspended"];
149
150     if (!m_session)
151         return;
152
153     if ([m_session isRunning])
154         [m_session stopRunning];
155
156     clearSession();
157 }
158
159 void AVVideoCaptureSource::clearSession()
160 {
161     ALWAYS_LOG_IF(loggerPtr(), LOGIDENTIFIER);
162     ASSERT(m_session);
163     [m_session removeObserver:m_objcObserver.get() forKeyPath:@"running"];
164     m_session = nullptr;
165 }
166
167 void AVVideoCaptureSource::startProducingData()
168 {
169     if (!m_session) {
170         if (!setupSession())
171             return;
172     }
173
174     if ([m_session isRunning])
175         return;
176
177     ALWAYS_LOG_IF(loggerPtr(), LOGIDENTIFIER);
178     [m_objcObserver addNotificationObservers];
179     [m_session startRunning];
180 }
181
182 void AVVideoCaptureSource::stopProducingData()
183 {
184     if (!m_session)
185         return;
186
187     ALWAYS_LOG_IF(loggerPtr(), LOGIDENTIFIER);
188     [m_objcObserver removeNotificationObservers];
189
190     if ([m_session isRunning])
191         [m_session stopRunning];
192
193     m_interruption = InterruptionReason::None;
194 #if PLATFORM(IOS_FAMILY)
195     clearSession();
196 #endif
197 }
198
199 void AVVideoCaptureSource::beginConfiguration()
200 {
201     if (m_session)
202         [m_session beginConfiguration];
203 }
204
205 void AVVideoCaptureSource::commitConfiguration()
206 {
207     if (m_session)
208         [m_session commitConfiguration];
209 }
210
211 void AVVideoCaptureSource::settingsDidChange(OptionSet<RealtimeMediaSourceSettings::Flag>)
212 {
213     m_currentSettings = WTF::nullopt;
214 }
215
216 const RealtimeMediaSourceSettings& AVVideoCaptureSource::settings()
217 {
218     if (m_currentSettings)
219         return *m_currentSettings;
220
221     RealtimeMediaSourceSettings settings;
222     if ([device() position] == AVCaptureDevicePositionFront)
223         settings.setFacingMode(RealtimeMediaSourceSettings::User);
224     else if ([device() position] == AVCaptureDevicePositionBack)
225         settings.setFacingMode(RealtimeMediaSourceSettings::Environment);
226     else
227         settings.setFacingMode(RealtimeMediaSourceSettings::Unknown);
228
229     settings.setFrameRate(frameRate());
230
231     auto size = this->size();
232     if (m_sampleRotation == MediaSample::VideoRotation::Left || m_sampleRotation == MediaSample::VideoRotation::Right)
233         size = size.transposedSize();
234     
235     settings.setWidth(size.width());
236     settings.setHeight(size.height());
237     settings.setDeviceId(hashedId());
238
239     RealtimeMediaSourceSupportedConstraints supportedConstraints;
240     supportedConstraints.setSupportsDeviceId(true);
241     supportedConstraints.setSupportsFacingMode([device() position] != AVCaptureDevicePositionUnspecified);
242     supportedConstraints.setSupportsWidth(true);
243     supportedConstraints.setSupportsHeight(true);
244     supportedConstraints.setSupportsAspectRatio(true);
245     supportedConstraints.setSupportsFrameRate(true);
246
247     settings.setSupportedConstraints(supportedConstraints);
248
249     m_currentSettings = WTFMove(settings);
250
251     return *m_currentSettings;
252 }
253
254 const RealtimeMediaSourceCapabilities& AVVideoCaptureSource::capabilities()
255 {
256     if (m_capabilities)
257         return *m_capabilities;
258
259     RealtimeMediaSourceCapabilities capabilities(settings().supportedConstraints());
260     capabilities.setDeviceId(hashedId());
261
262     AVCaptureDevice *videoDevice = device();
263     if ([videoDevice position] == AVCaptureDevicePositionFront)
264         capabilities.addFacingMode(RealtimeMediaSourceSettings::User);
265     if ([videoDevice position] == AVCaptureDevicePositionBack)
266         capabilities.addFacingMode(RealtimeMediaSourceSettings::Environment);
267
268     updateCapabilities(capabilities);
269
270     m_capabilities = WTFMove(capabilities);
271
272     return *m_capabilities;
273 }
274
275 bool AVVideoCaptureSource::prefersPreset(VideoPreset& preset)
276 {
277 #if PLATFORM(IOS_FAMILY)
278     return [static_cast<AVVideoPreset*>(&preset)->format.get() isVideoBinned];
279 #else
280     UNUSED_PARAM(preset);
281 #endif
282
283     return true;
284 }
285
286 void AVVideoCaptureSource::setSizeAndFrameRateWithPreset(IntSize requestedSize, double requestedFrameRate, RefPtr<VideoPreset> preset)
287 {
288     ALWAYS_LOG_IF(loggerPtr(), LOGIDENTIFIER, SizeAndFrameRate { requestedSize.width(), requestedSize.height(), requestedFrameRate });
289
290     auto* avPreset = preset ? downcast<AVVideoPreset>(preset.get()) : nullptr;
291
292     if (!m_session) {
293         m_pendingPreset = avPreset;
294         m_pendingSize = requestedSize;
295         m_pendingFrameRate = requestedFrameRate;
296         return;
297     }
298
299     m_pendingPreset = nullptr;
300     m_pendingFrameRate = 0;
301
302     auto* frameRateRange = frameDurationForFrameRate(requestedFrameRate);
303     ASSERT(frameRateRange);
304     if (!frameRateRange)
305         return;
306
307     if (!avPreset)
308         return;
309
310     ASSERT(avPreset->format);
311
312     NSError *error = nil;
313     [m_session beginConfiguration];
314     @try {
315         if ([device() lockForConfiguration:&error]) {
316             if (!m_currentPreset || ![m_currentPreset->format.get() isEqual:avPreset->format.get()]) {
317                 [device() setActiveFormat:avPreset->format.get()];
318
319                 frameRateRange = frameDurationForFrameRate(requestedFrameRate);
320                 ASSERT(frameRateRange);
321                 if (!frameRateRange)
322                     return;
323
324 #if PLATFORM(MAC)
325                 auto settingsDictionary = @{
326                     (__bridge NSString *)kCVPixelBufferPixelFormatTypeKey: @(avVideoCapturePixelBufferFormat()),
327                     (__bridge NSString *)kCVPixelBufferWidthKey: @(avPreset->size.width()),
328                     (__bridge NSString *)kCVPixelBufferHeightKey: @(avPreset->size.height()),
329                     (__bridge NSString *)kCVPixelBufferIOSurfacePropertiesKey : @{ }
330                 };
331                 [m_videoOutput setVideoSettings:settingsDictionary];
332 #endif
333             }
334
335             ALWAYS_LOG_IF(loggerPtr(), LOGIDENTIFIER, "setting frame rate ", CMTimeGetSeconds([frameRateRange minFrameDuration]), " .. ", CMTimeGetSeconds([frameRateRange maxFrameDuration]));
336             [device() setActiveVideoMinFrameDuration:[frameRateRange minFrameDuration]];
337             [device() setActiveVideoMaxFrameDuration:[frameRateRange maxFrameDuration]];
338             [device() unlockForConfiguration];
339         }
340     } @catch(NSException *exception) {
341         ERROR_LOG_IF(loggerPtr(), LOGIDENTIFIER, "error configuring device ", [[exception name] UTF8String], ", reason : ", [[exception reason] UTF8String]);
342         return;
343     }
344     [m_session commitConfiguration];
345
346     m_currentPreset = avPreset;
347
348     ERROR_LOG_IF(error && loggerPtr(), LOGIDENTIFIER, [[error localizedDescription] UTF8String]);
349 }
350
351 static inline int sensorOrientation(AVCaptureVideoOrientation videoOrientation)
352 {
353 #if PLATFORM(IOS_FAMILY)
354     switch (videoOrientation) {
355     case AVCaptureVideoOrientationPortrait:
356         return 180;
357     case AVCaptureVideoOrientationPortraitUpsideDown:
358         return 0;
359     case AVCaptureVideoOrientationLandscapeRight:
360         return 90;
361     case AVCaptureVideoOrientationLandscapeLeft:
362         return -90;
363     }
364 #else
365     switch (videoOrientation) {
366     case AVCaptureVideoOrientationPortrait:
367         return 0;
368     case AVCaptureVideoOrientationPortraitUpsideDown:
369         return 180;
370     case AVCaptureVideoOrientationLandscapeRight:
371         return 90;
372     case AVCaptureVideoOrientationLandscapeLeft:
373         return -90;
374     }
375 #endif
376 }
377
378 static inline int sensorOrientationFromVideoOutput(AVCaptureVideoDataOutput* videoOutput)
379 {
380     AVCaptureConnection* connection = [videoOutput connectionWithMediaType:AVMediaTypeVideo];
381     return connection ? sensorOrientation([connection videoOrientation]) : 0;
382 }
383
384 bool AVVideoCaptureSource::setupSession()
385 {
386     if (m_session)
387         return true;
388
389     ALWAYS_LOG_IF(loggerPtr(), LOGIDENTIFIER);
390
391     m_session = adoptNS([PAL::allocAVCaptureSessionInstance() init]);
392     [m_session addObserver:m_objcObserver.get() forKeyPath:@"running" options:NSKeyValueObservingOptionNew context:(void *)nil];
393
394     [m_session beginConfiguration];
395     bool success = setupCaptureSession();
396     [m_session commitConfiguration];
397
398     if (!success)
399         captureFailed();
400
401     return success;
402 }
403
404 AVFrameRateRange* AVVideoCaptureSource::frameDurationForFrameRate(double rate)
405 {
406     AVFrameRateRange *bestFrameRateRange = nil;
407     for (AVFrameRateRange *frameRateRange in [[device() activeFormat] videoSupportedFrameRateRanges]) {
408         if (frameRateRangeIncludesRate({ [frameRateRange minFrameRate], [frameRateRange maxFrameRate] }, rate)) {
409             if (!bestFrameRateRange || CMTIME_COMPARE_INLINE([frameRateRange minFrameDuration], >, [bestFrameRateRange minFrameDuration]))
410                 bestFrameRateRange = frameRateRange;
411         }
412     }
413
414     if (!bestFrameRateRange)
415         ERROR_LOG_IF(loggerPtr(), LOGIDENTIFIER, "no frame rate range for rate ", rate);
416
417     return bestFrameRateRange;
418 }
419
420 bool AVVideoCaptureSource::setupCaptureSession()
421 {
422     ALWAYS_LOG_IF(loggerPtr(), LOGIDENTIFIER);
423
424 #if PLATFORM(IOS_FAMILY)
425     RealtimeMediaSourceCenter::singleton().videoCaptureFactory().setActiveSource(*this);
426 #endif
427
428     NSError *error = nil;
429     RetainPtr<AVCaptureDeviceInput> videoIn = adoptNS([PAL::allocAVCaptureDeviceInputInstance() initWithDevice:device() error:&error]);
430     if (error) {
431         ERROR_LOG_IF(loggerPtr(), LOGIDENTIFIER, "failed to allocate AVCaptureDeviceInput ", [[error localizedDescription] UTF8String]);
432         return false;
433     }
434
435     if (![session() canAddInput:videoIn.get()]) {
436         ERROR_LOG_IF(loggerPtr(), LOGIDENTIFIER, "unable to add video input device");
437         return false;
438     }
439     [session() addInput:videoIn.get()];
440
441     m_videoOutput = adoptNS([PAL::allocAVCaptureVideoDataOutputInstance() init]);
442     auto settingsDictionary = adoptNS([[NSMutableDictionary alloc] initWithObjectsAndKeys: [NSNumber numberWithInt:avVideoCapturePixelBufferFormat()], kCVPixelBufferPixelFormatTypeKey, nil]);
443
444     [m_videoOutput setVideoSettings:settingsDictionary.get()];
445     [m_videoOutput setAlwaysDiscardsLateVideoFrames:YES];
446     [m_videoOutput setSampleBufferDelegate:m_objcObserver.get() queue:globaVideoCaptureSerialQueue()];
447
448     if (![session() canAddOutput:m_videoOutput.get()]) {
449         ERROR_LOG_IF(loggerPtr(), LOGIDENTIFIER, "unable to add video output device");
450         return false;
451     }
452     [session() addOutput:m_videoOutput.get()];
453
454     if (m_pendingPreset || m_pendingFrameRate)
455         setSizeAndFrameRateWithPreset(m_pendingSize, m_pendingFrameRate, m_pendingPreset);
456
457     m_sensorOrientation = sensorOrientationFromVideoOutput(m_videoOutput.get());
458     computeSampleRotation();
459
460     return true;
461 }
462
463 void AVVideoCaptureSource::shutdownCaptureSession()
464 {
465     m_buffer = nullptr;
466 }
467
468 void AVVideoCaptureSource::monitorOrientation(OrientationNotifier& notifier)
469 {
470 #if PLATFORM(IOS_FAMILY)
471     notifier.addObserver(*this);
472     orientationChanged(notifier.orientation());
473 #else
474     UNUSED_PARAM(notifier);
475 #endif
476 }
477
478 void AVVideoCaptureSource::orientationChanged(int orientation)
479 {
480     ASSERT(orientation == 0 || orientation == 90 || orientation == -90 || orientation == 180);
481     m_deviceOrientation = orientation;
482     computeSampleRotation();
483 }
484
485 void AVVideoCaptureSource::computeSampleRotation()
486 {
487     bool frontCamera = [device() position] == AVCaptureDevicePositionFront;
488     MediaSample::VideoRotation sampleRotation;
489     switch (m_sensorOrientation - m_deviceOrientation) {
490     case 0:
491         sampleRotation = MediaSample::VideoRotation::None;
492         break;
493     case 180:
494     case -180:
495         sampleRotation = MediaSample::VideoRotation::UpsideDown;
496         break;
497     case 90:
498         sampleRotation = frontCamera ? MediaSample::VideoRotation::Left : MediaSample::VideoRotation::Right;
499         break;
500     case -90:
501     case -270:
502         sampleRotation = frontCamera ? MediaSample::VideoRotation::Right : MediaSample::VideoRotation::Left;
503         break;
504     default:
505         ASSERT_NOT_REACHED();
506         sampleRotation = MediaSample::VideoRotation::None;
507     }
508     if (sampleRotation == m_sampleRotation)
509         return;
510
511     m_sampleRotation = sampleRotation;
512     notifySettingsDidChangeObservers({ RealtimeMediaSourceSettings::Flag::Width, RealtimeMediaSourceSettings::Flag::Height });
513 }
514
515 void AVVideoCaptureSource::processNewFrame(Ref<MediaSample>&& sample)
516 {
517     if (!isProducingData() || muted())
518         return;
519
520     m_buffer = &sample.get();
521     setIntrinsicSize(expandedIntSize(sample->presentationSize()));
522     dispatchMediaSampleToObservers(WTFMove(sample));
523 }
524
525 void AVVideoCaptureSource::captureOutputDidOutputSampleBufferFromConnection(AVCaptureOutput*, CMSampleBufferRef sampleBuffer, AVCaptureConnection* captureConnection)
526 {
527     if (m_framesToDropAtStartup && m_framesToDropAtStartup--)
528         return;
529
530     auto sample = MediaSampleAVFObjC::create(sampleBuffer, m_sampleRotation, [captureConnection isVideoMirrored]);
531     scheduleDeferredTask([this, sample = WTFMove(sample)] () mutable {
532         processNewFrame(WTFMove(sample));
533     });
534 }
535
536 void AVVideoCaptureSource::captureSessionIsRunningDidChange(bool state)
537 {
538     scheduleDeferredTask([this, state] {
539         ALWAYS_LOG_IF(loggerPtr(), LOGIDENTIFIER, state);
540         if ((state == m_isRunning) && (state == !muted()))
541             return;
542
543         m_isRunning = state;
544         if (m_isRunning)
545             m_framesToDropAtStartup = 4;
546
547         notifyMutedChange(!m_isRunning);
548     });
549 }
550
551 void AVVideoCaptureSource::captureDeviceSuspendedDidChange()
552 {
553 #if !PLATFORM(IOS_FAMILY)
554     scheduleDeferredTask([this] {
555         auto isSuspended = [m_device isSuspended];
556         ALWAYS_LOG_IF(loggerPtr(), LOGIDENTIFIER, !!isSuspended);
557         if (isSuspended == muted())
558             return;
559
560         notifyMutedChange(isSuspended);
561     });
562 #endif
563 }
564
565 bool AVVideoCaptureSource::interrupted() const
566 {
567     if (m_interruption != InterruptionReason::None)
568         return true;
569
570     return RealtimeMediaSource::interrupted();
571 }
572
573 void AVVideoCaptureSource::generatePresets()
574 {
575     Vector<Ref<VideoPreset>> presets;
576     for (AVCaptureDeviceFormat* format in [device() formats]) {
577
578         CMVideoDimensions dimensions = CMVideoFormatDescriptionGetDimensions(format.formatDescription);
579         IntSize size = { dimensions.width, dimensions.height };
580         auto index = presets.findMatching([&size](auto& preset) {
581             return size == preset->size;
582         });
583         if (index != notFound)
584             continue;
585
586         Vector<FrameRateRange> frameRates;
587         for (AVFrameRateRange* range in [format videoSupportedFrameRateRanges])
588             frameRates.append({ range.minFrameRate, range.maxFrameRate});
589
590         presets.append(AVVideoPreset::create(size, WTFMove(frameRates), format));
591     }
592
593     setSupportedPresets(WTFMove(presets));
594 }
595
596 #if PLATFORM(IOS_FAMILY)
597 void AVVideoCaptureSource::captureSessionRuntimeError(RetainPtr<NSError> error)
598 {
599     ERROR_LOG_IF(loggerPtr(), LOGIDENTIFIER, [[error localizedDescription] UTF8String]);
600
601     if (!m_isRunning || error.get().code != AVErrorMediaServicesWereReset)
602         return;
603
604     // Try to restart the session, but reset m_isRunning immediately so if it fails we won't try again.
605     [m_session startRunning];
606     m_isRunning = [m_session isRunning];
607 }
608
609 void AVVideoCaptureSource::captureSessionBeginInterruption(RetainPtr<NSNotification> notification)
610 {
611     ALWAYS_LOG_IF(loggerPtr(), LOGIDENTIFIER, [notification.get().userInfo[AVCaptureSessionInterruptionReasonKey] integerValue]);
612     m_interruption = static_cast<AVVideoCaptureSource::InterruptionReason>([notification.get().userInfo[AVCaptureSessionInterruptionReasonKey] integerValue]);
613 }
614
615 void AVVideoCaptureSource::captureSessionEndInterruption(RetainPtr<NSNotification>)
616 {
617     ALWAYS_LOG_IF(loggerPtr(), LOGIDENTIFIER);
618
619     InterruptionReason reason = m_interruption;
620
621     m_interruption = InterruptionReason::None;
622     if (reason != InterruptionReason::VideoNotAllowedInSideBySide || m_isRunning || !m_session)
623         return;
624
625     [m_session startRunning];
626     m_isRunning = [m_session isRunning];
627 }
628 #endif
629
630 void AVVideoCaptureSource::deviceDisconnected(RetainPtr<NSNotification> notification)
631 {
632     ALWAYS_LOG_IF(loggerPtr(), LOGIDENTIFIER);
633     if (this->device() == [notification object])
634         captureFailed();
635 }
636
637
638 } // namespace WebCore
639
640 @implementation WebCoreAVVideoCaptureSourceObserver
641
642 - (id)initWithCallback:(AVVideoCaptureSource*)callback
643 {
644     self = [super init];
645     if (!self)
646         return nil;
647
648     m_callback = callback;
649
650     return self;
651 }
652
653 - (void)disconnect
654 {
655     [NSObject cancelPreviousPerformRequestsWithTarget:self];
656     [self removeNotificationObservers];
657     m_callback = nullptr;
658 }
659
660 - (void)addNotificationObservers
661 {
662     ASSERT(m_callback);
663
664     NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
665
666     [center addObserver:self selector:@selector(deviceConnectedDidChange:) name:AVCaptureDeviceWasDisconnectedNotification object:nil];
667
668 #if PLATFORM(IOS_FAMILY)
669     AVCaptureSession* session = m_callback->session();
670     [center addObserver:self selector:@selector(sessionRuntimeError:) name:AVCaptureSessionRuntimeErrorNotification object:session];
671     [center addObserver:self selector:@selector(beginSessionInterrupted:) name:AVCaptureSessionWasInterruptedNotification object:session];
672     [center addObserver:self selector:@selector(endSessionInterrupted:) name:AVCaptureSessionInterruptionEndedNotification object:session];
673 #endif
674 }
675
676 - (void)removeNotificationObservers
677 {
678     [[NSNotificationCenter defaultCenter] removeObserver:self];
679 }
680
681 - (void)captureOutput:(AVCaptureOutput*)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection*)connection
682 {
683     if (!m_callback)
684         return;
685
686     m_callback->captureOutputDidOutputSampleBufferFromConnection(captureOutput, sampleBuffer, connection);
687 }
688
689 - (void)observeValueForKeyPath:keyPath ofObject:(id)object change:(NSDictionary*)change context:(void*)context
690 {
691     UNUSED_PARAM(object);
692     UNUSED_PARAM(context);
693
694     if (!m_callback)
695         return;
696
697     id newValue = [change valueForKey:NSKeyValueChangeNewKey];
698
699     bool willChange = [[change valueForKey:NSKeyValueChangeNotificationIsPriorKey] boolValue];
700
701 #if !RELEASE_LOG_DISABLED
702     if (m_callback->loggerPtr() && m_callback->logger().willLog(m_callback->logChannel(), WTFLogLevel::Debug)) {
703         auto identifier = Logger::LogSiteIdentifier("AVVideoCaptureSource", "observeValueForKeyPath", m_callback->logIdentifier());
704
705         RetainPtr<NSString> valueString = adoptNS([[NSString alloc] initWithFormat:@"%@", newValue]);
706         m_callback->logger().debug(m_callback->logChannel(), identifier, "did change '", [keyPath UTF8String], "' to ", [valueString.get() UTF8String]);
707     }
708 #endif
709
710     if (!willChange && [keyPath isEqualToString:@"running"])
711         m_callback->captureSessionIsRunningDidChange([newValue boolValue]);
712     if (!willChange && [keyPath isEqualToString:@"suspended"])
713         m_callback->captureDeviceSuspendedDidChange();
714 }
715
716 - (void)deviceConnectedDidChange:(NSNotification*)notification
717 {
718     if (m_callback)
719         m_callback->deviceDisconnected(notification);
720 }
721
722 #if PLATFORM(IOS_FAMILY)
723 - (void)sessionRuntimeError:(NSNotification*)notification
724 {
725     NSError *error = notification.userInfo[AVCaptureSessionErrorKey];
726     if (m_callback)
727         m_callback->captureSessionRuntimeError(error);
728 }
729
730 - (void)beginSessionInterrupted:(NSNotification*)notification
731 {
732     if (m_callback)
733         m_callback->captureSessionBeginInterruption(notification);
734 }
735
736 - (void)endSessionInterrupted:(NSNotification*)notification
737 {
738     if (m_callback)
739         m_callback->captureSessionEndInterruption(notification);
740 }
741 #endif
742
743 @end
744
745 #endif // ENABLE(MEDIA_STREAM)