[iOS] cleanup AirPlay code
[WebKit-https.git] / Source / WebCore / platform / audio / ios / MediaSessionManagerIOS.mm
1 /*
2  * Copyright (C) 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. AND ITS CONTRIBUTORS ``AS IS''
14  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23  * THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #import "config.h"
27 #import "MediaSessionManagerIOS.h"
28
29 #if PLATFORM(IOS)
30
31 #import "Logging.h"
32 #import "MediaPlayer.h"
33 #import "MediaPlayerSPI.h"
34 #import "MediaSession.h"
35 #import "SoftLinking.h"
36 #import "SystemMemory.h"
37 #import "WebCoreSystemInterface.h"
38 #import "WebCoreThreadRun.h"
39 #import <AVFoundation/AVAudioSession.h>
40 #import <MediaPlayer/MPMediaItem.h>
41 #import <MediaPlayer/MPNowPlayingInfoCenter.h>
42 #import <MediaPlayer/MPVolumeView.h>
43 #import <UIKit/UIApplication.h>
44 #import <objc/runtime.h>
45 #import <wtf/RetainPtr.h>
46
47 SOFT_LINK_FRAMEWORK(AVFoundation)
48 SOFT_LINK_CLASS(AVFoundation, AVAudioSession)
49 SOFT_LINK_POINTER(AVFoundation, AVAudioSessionInterruptionNotification, NSString *)
50 SOFT_LINK_POINTER(AVFoundation, AVAudioSessionInterruptionTypeKey, NSString *)
51 SOFT_LINK_POINTER(AVFoundation, AVAudioSessionInterruptionOptionKey, NSString *)
52
53 #define AVAudioSession getAVAudioSessionClass()
54 #define AVAudioSessionInterruptionNotification getAVAudioSessionInterruptionNotification()
55 #define AVAudioSessionInterruptionTypeKey getAVAudioSessionInterruptionTypeKey()
56 #define AVAudioSessionInterruptionOptionKey getAVAudioSessionInterruptionOptionKey()
57
58 SOFT_LINK_FRAMEWORK(UIKit)
59 SOFT_LINK_CLASS(UIKit, UIApplication)
60 SOFT_LINK_POINTER(UIKit, UIApplicationWillResignActiveNotification, NSString *)
61 SOFT_LINK_POINTER(UIKit, UIApplicationWillEnterForegroundNotification, NSString *)
62 SOFT_LINK_POINTER(UIKit, UIApplicationDidBecomeActiveNotification, NSString *)
63
64 #define UIApplication getUIApplicationClass()
65 #define UIApplicationWillResignActiveNotification getUIApplicationWillResignActiveNotification()
66 #define UIApplicationWillEnterForegroundNotification getUIApplicationWillEnterForegroundNotification()
67 #define UIApplicationDidBecomeActiveNotification getUIApplicationDidBecomeActiveNotification()
68
69 SOFT_LINK_FRAMEWORK(MediaPlayer)
70 SOFT_LINK_CLASS(MediaPlayer, MPAVRoutingController)
71 SOFT_LINK_CLASS(MediaPlayer, MPNowPlayingInfoCenter)
72 SOFT_LINK_CLASS(MediaPlayer, MPVolumeView)
73 SOFT_LINK_POINTER(MediaPlayer, MPMediaItemPropertyTitle, NSString *)
74 SOFT_LINK_POINTER(MediaPlayer, MPMediaItemPropertyPlaybackDuration, NSString *)
75 SOFT_LINK_POINTER(MediaPlayer, MPNowPlayingInfoPropertyElapsedPlaybackTime, NSString *)
76 SOFT_LINK_POINTER(MediaPlayer, MPNowPlayingInfoPropertyPlaybackRate, NSString *)
77 SOFT_LINK_POINTER(MediaPlayer, MPVolumeViewWirelessRoutesAvailableDidChangeNotification, NSString *)
78
79
80 #define MPMediaItemPropertyTitle getMPMediaItemPropertyTitle()
81 #define MPMediaItemPropertyPlaybackDuration getMPMediaItemPropertyPlaybackDuration()
82 #define MPNowPlayingInfoPropertyElapsedPlaybackTime getMPNowPlayingInfoPropertyElapsedPlaybackTime()
83 #define MPNowPlayingInfoPropertyPlaybackRate getMPNowPlayingInfoPropertyPlaybackRate()
84 #define MPVolumeViewWirelessRoutesAvailableDidChangeNotification getMPVolumeViewWirelessRoutesAvailableDidChangeNotification()
85
86 WEBCORE_EXPORT NSString* WebUIApplicationWillResignActiveNotification = @"WebUIApplicationWillResignActiveNotification";
87 WEBCORE_EXPORT NSString* WebUIApplicationWillEnterForegroundNotification = @"WebUIApplicationWillEnterForegroundNotification";
88 WEBCORE_EXPORT NSString* WebUIApplicationDidBecomeActiveNotification = @"WebUIApplicationDidBecomeActiveNotification";
89
90 using namespace WebCore;
91
92 @interface WebMediaSessionHelper : NSObject {
93     MediaSessionManageriOS* _callback;
94     RetainPtr<MPVolumeView> _volumeView;
95     RetainPtr<MPAVRoutingController> _airPlayPresenceRoutingController;
96 }
97
98 - (id)initWithCallback:(MediaSessionManageriOS*)callback;
99 - (void)allocateVolumeView;
100 - (void)clearCallback;
101 - (void)interruption:(NSNotification *)notification;
102 - (void)applicationWillEnterForeground:(NSNotification *)notification;
103 - (void)applicationWillResignActive:(NSNotification *)notification;
104 - (BOOL)hasWirelessTargetsAvailable;
105 - (void)startMonitoringAirPlayRoutes;
106 - (void)stopMonitoringAirPlayRoutes;
107 @end
108
109 namespace WebCore {
110
111 MediaSessionManager& MediaSessionManager::sharedManager()
112 {
113     DEPRECATED_DEFINE_STATIC_LOCAL(MediaSessionManageriOS, manager, ());
114     return manager;
115 }
116
117 MediaSessionManageriOS::MediaSessionManageriOS()
118     :MediaSessionManager()
119     , m_objcObserver(adoptNS([[WebMediaSessionHelper alloc] initWithCallback:this]))
120 {
121     resetRestrictions();
122 }
123
124 MediaSessionManageriOS::~MediaSessionManageriOS()
125 {
126     [m_objcObserver clearCallback];
127 }
128
129 void MediaSessionManageriOS::resetRestrictions()
130 {
131     static const size_t systemMemoryRequiredForVideoInBackgroundTabs = 1024 * 1024 * 1024;
132
133     LOG(Media, "MediaSessionManageriOS::resetRestrictions");
134
135     MediaSessionManager::resetRestrictions();
136
137     static wkDeviceClass deviceClass = iosDeviceClass();
138     if (deviceClass == wkDeviceClassiPhone || deviceClass == wkDeviceClassiPod)
139         addRestriction(MediaSession::Video, InlineVideoPlaybackRestricted);
140
141     if (systemTotalMemory() < systemMemoryRequiredForVideoInBackgroundTabs) {
142         LOG(Media, "MediaSessionManageriOS::resetRestrictions - restricting video in background tabs because system memory = %zul", systemTotalMemory());
143         addRestriction(MediaSession::Video, BackgroundTabPlaybackRestricted);
144     }
145
146     addRestriction(MediaSession::Video, ConcurrentPlaybackNotPermitted);
147     addRestriction(MediaSession::Video, BackgroundProcessPlaybackRestricted);
148
149     removeRestriction(MediaSession::Audio, ConcurrentPlaybackNotPermitted);
150     removeRestriction(MediaSession::Audio, BackgroundProcessPlaybackRestricted);
151
152     removeRestriction(MediaSession::WebAudio, ConcurrentPlaybackNotPermitted);
153     removeRestriction(MediaSession::WebAudio, BackgroundProcessPlaybackRestricted);
154
155     removeRestriction(MediaSession::Audio, MetadataPreloadingNotPermitted);
156     removeRestriction(MediaSession::Video, MetadataPreloadingNotPermitted);
157
158     addRestriction(MediaSession::Audio, AutoPreloadingNotPermitted);
159     addRestriction(MediaSession::Video, AutoPreloadingNotPermitted);
160 }
161
162 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
163 bool MediaSessionManageriOS::hasWirelessTargetsAvailable()
164 {
165     return [m_objcObserver hasWirelessTargetsAvailable];
166 }
167
168 void MediaSessionManageriOS::configureWireLessTargetMonitoring()
169 {
170     Vector<MediaSession*> sessions = this->sessions();
171     bool requiresMonitoring = false;
172
173     for (auto* session : sessions) {
174         if (session->requiresPlaybackTargetRouteMonitoring()) {
175             requiresMonitoring = true;
176             break;
177         }
178     }
179
180     LOG(Media, "MediaSessionManageriOS::configureWireLessTargetMonitoring - requiresMonitoring = %s", requiresMonitoring ? "true" : "false");
181
182     if (requiresMonitoring)
183         [m_objcObserver startMonitoringAirPlayRoutes];
184     else
185         [m_objcObserver stopMonitoringAirPlayRoutes];
186 }
187 #endif
188     
189 void MediaSessionManageriOS::sessionWillBeginPlayback(MediaSession& session)
190 {
191     MediaSessionManager::sessionWillBeginPlayback(session);
192     updateNowPlayingInfo();
193 }
194     
195 void MediaSessionManageriOS::sessionWillEndPlayback(MediaSession& session)
196 {
197     MediaSessionManager::sessionWillEndPlayback(session);
198     updateNowPlayingInfo();
199 }
200     
201 void MediaSessionManageriOS::updateNowPlayingInfo()
202 {
203     LOG(Media, "MediaSessionManageriOS::updateNowPlayingInfo");
204
205     MPNowPlayingInfoCenter *nowPlaying = (MPNowPlayingInfoCenter *)[getMPNowPlayingInfoCenterClass() defaultCenter];
206     const MediaSession* currentSession = this->currentSession();
207     
208     if (!currentSession) {
209         [nowPlaying setNowPlayingInfo:nil];
210         return;
211     }
212     
213     RetainPtr<NSMutableDictionary> info = adoptNS([[NSMutableDictionary alloc] init]);
214     
215     String title = currentSession->title();
216     if (!title.isEmpty())
217         [info setValue:static_cast<NSString *>(title) forKey:MPMediaItemPropertyTitle];
218     
219     double duration = currentSession->duration();
220     if (std::isfinite(duration) && duration != MediaPlayer::invalidTime())
221         [info setValue:@(duration) forKey:MPMediaItemPropertyPlaybackDuration];
222     
223     double currentTime = currentSession->currentTime();
224     if (std::isfinite(currentTime) && currentTime != MediaPlayer::invalidTime())
225         [info setValue:@(currentTime) forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime];
226     
227     [info setValue:(currentSession->state() == MediaSession::Playing ? @YES : @NO) forKey:MPNowPlayingInfoPropertyPlaybackRate];
228     [nowPlaying setNowPlayingInfo:info.get()];
229 }
230
231 bool MediaSessionManageriOS::sessionCanLoadMedia(const MediaSession& session) const
232 {
233     return session.state() == MediaSession::Playing || !session.isHidden() || session.displayType() == MediaSession::Optimized;
234 }
235
236 } // namespace WebCore
237
238 @implementation WebMediaSessionHelper
239
240 - (void)allocateVolumeView
241 {
242     if (!isMainThread()) {
243         // Call synchronously to the main thread so that _volumeView will be completely setup before the constructor completes
244         // because hasWirelessTargetsAvailable is synchronous and can be called on the WebThread.
245         RetainPtr<WebMediaSessionHelper> strongSelf = self;
246         dispatch_sync(dispatch_get_main_queue(), [strongSelf]() {
247             [strongSelf allocateVolumeView];
248             return;
249         });
250     }
251
252     _volumeView = adoptNS([allocMPVolumeViewInstance() init]);
253     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(wirelessRoutesAvailableDidChange:) name:MPVolumeViewWirelessRoutesAvailableDidChangeNotification object:_volumeView.get()];
254     
255 }
256
257 - (id)initWithCallback:(MediaSessionManageriOS*)callback
258 {
259     LOG(Media, "-[WebMediaSessionHelper initWithCallback]");
260
261     if (!(self = [super init]))
262         return nil;
263     
264     _callback = callback;
265
266     NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
267     [center addObserver:self selector:@selector(interruption:) name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]];
268
269     [center addObserver:self selector:@selector(applicationWillEnterForeground:) name:UIApplicationWillEnterForegroundNotification object:nil];
270     [center addObserver:self selector:@selector(applicationWillEnterForeground:) name:WebUIApplicationWillEnterForegroundNotification object:nil];
271     [center addObserver:self selector:@selector(applicationDidBecomeActive:) name:UIApplicationDidBecomeActiveNotification object:nil];
272     [center addObserver:self selector:@selector(applicationDidBecomeActive:) name:WebUIApplicationDidBecomeActiveNotification object:nil];
273     [center addObserver:self selector:@selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:nil];
274     [center addObserver:self selector:@selector(applicationWillResignActive:) name:WebUIApplicationWillResignActiveNotification object:nil];
275
276     [self allocateVolumeView];
277
278     // Now playing won't work unless we turn on the delivery of remote control events.
279     [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
280     
281     return self;
282 }
283
284 - (void)dealloc
285 {
286     LOG(Media, "-[WebMediaSessionHelper dealloc]");
287
288     if (!isMainThread()) {
289         auto volumeView = WTF::move(_volumeView);
290         auto routingController = WTF::move(_airPlayPresenceRoutingController);
291
292         callOnMainThread([volumeView, routingController] () mutable {
293             LOG(Media, "-[WebMediaSessionHelper dealloc] - dipatched to MainThread");
294
295             volumeView.clear();
296
297             if (!routingController)
298                 return;
299
300             [routingController setDiscoveryMode:MPRouteDiscoveryModeDisabled];
301             routingController.clear();
302         });
303     }
304
305     [[NSNotificationCenter defaultCenter] removeObserver:self];
306     [super dealloc];
307 }
308
309 - (void)clearCallback
310 {
311     LOG(Media, "-[WebMediaSessionHelper clearCallback]");
312     _callback = nil;
313 }
314
315 - (BOOL)hasWirelessTargetsAvailable
316 {
317     LOG(Media, "-[WebMediaSessionHelper hasWirelessTargetsAvailable]");
318     return [_volumeView areWirelessRoutesAvailable];
319 }
320
321 - (void)startMonitoringAirPlayRoutes
322 {
323     if (_airPlayPresenceRoutingController)
324         return;
325
326     LOG(Media, "-[WebMediaSessionHelper startMonitoringAirPlayRoutes]");
327
328     RetainPtr<WebMediaSessionHelper> strongSelf = self;
329     callOnMainThread([strongSelf] () {
330         LOG(Media, "-[WebMediaSessionHelper startMonitoringAirPlayRoutes] - dipatched to MainThread");
331
332         if (strongSelf->_airPlayPresenceRoutingController)
333             return;
334
335         strongSelf->_airPlayPresenceRoutingController = adoptNS([allocMPAVRoutingControllerInstance() initWithName:@"WebCore - HTML media element checking for AirPlay route presence"]);
336         [strongSelf->_airPlayPresenceRoutingController setDiscoveryMode:MPRouteDiscoveryModePresence];
337     });
338 }
339
340 - (void)stopMonitoringAirPlayRoutes
341 {
342     if (!_airPlayPresenceRoutingController)
343         return;
344
345     LOG(Media, "-[WebMediaSessionHelper stopMonitoringAirPlayRoutes]");
346
347     RetainPtr<WebMediaSessionHelper> strongSelf = self;
348     callOnMainThread([strongSelf] () {
349         LOG(Media, "-[WebMediaSessionHelper stopMonitoringAirPlayRoutes] - dipatched to MainThread");
350
351         if (!strongSelf->_airPlayPresenceRoutingController)
352             return;
353
354         [strongSelf->_airPlayPresenceRoutingController setDiscoveryMode:MPRouteDiscoveryModeDisabled];
355         strongSelf->_airPlayPresenceRoutingController = nil;
356     });
357 }
358
359 - (void)interruption:(NSNotification *)notification
360 {
361     if (!_callback)
362         return;
363
364     NSUInteger type = [[[notification userInfo] objectForKey:AVAudioSessionInterruptionTypeKey] unsignedIntegerValue];
365     MediaSession::EndInterruptionFlags flags = MediaSession::NoFlags;
366
367     LOG(Media, "-[WebMediaSessionHelper interruption] - type = %i", (int)type);
368
369     if (type == AVAudioSessionInterruptionTypeEnded && [[[notification userInfo] objectForKey:AVAudioSessionInterruptionOptionKey] unsignedIntegerValue] == AVAudioSessionInterruptionOptionShouldResume)
370         flags = MediaSession::MayResumePlaying;
371
372     WebThreadRun(^{
373         if (!_callback)
374             return;
375
376         if (type == AVAudioSessionInterruptionTypeBegan)
377             _callback->beginInterruption(MediaSession::SystemInterruption);
378         else
379             _callback->endInterruption(flags);
380
381     });
382 }
383
384 - (void)applicationWillEnterForeground:(NSNotification *)notification
385 {
386     UNUSED_PARAM(notification);
387
388     if (!_callback)
389         return;
390
391     LOG(Media, "-[WebMediaSessionHelper applicationWillEnterForeground]");
392
393     WebThreadRun(^{
394         if (!_callback)
395             return;
396
397         _callback->applicationWillEnterForeground();
398     });
399 }
400
401 - (void)applicationDidBecomeActive:(NSNotification *)notification
402 {
403     UNUSED_PARAM(notification);
404
405     if (!_callback)
406         return;
407
408     LOG(Media, "-[WebMediaSessionHelper applicationDidBecomeActive]");
409
410     WebThreadRun(^{
411         if (!_callback)
412             return;
413
414         _callback->applicationWillEnterForeground();
415     });
416 }
417
418 - (void)applicationWillResignActive:(NSNotification *)notification
419 {
420     UNUSED_PARAM(notification);
421
422     if (!_callback)
423         return;
424
425     LOG(Media, "-[WebMediaSessionHelper applicationWillResignActive]");
426
427     WebThreadRun(^{
428         if (!_callback)
429             return;
430         
431         _callback->applicationWillEnterBackground();
432     });
433 }
434
435 - (void)wirelessRoutesAvailableDidChange:(NSNotification *)notification
436 {
437     UNUSED_PARAM(notification);
438
439     if (!_callback)
440         return;
441
442     LOG(Media, "-[WebMediaSessionHelper wirelessRoutesAvailableDidChange]");
443
444     WebThreadRun(^{
445         if (!_callback)
446             return;
447
448         _callback->wirelessRoutesAvailableChanged();
449     });
450 }
451 @end
452
453 #endif // PLATFORM(IOS)