Make Remote Control commands testable
[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 "MediaSession.h"
34 #import "NotImplemented.h"
35 #import "SoftLinking.h"
36 #import "WebCoreSystemInterface.h"
37 #import "WebCoreThreadRun.h"
38 #import <AVFoundation/AVAudioSession.h>
39 #import <MediaPlayer/MPMediaItem.h>
40 #import <MediaPlayer/MPNowPlayingInfoCenter.h>
41 #import <UIKit/UIApplication.h>
42 #import <objc/runtime.h>
43 #import <wtf/RetainPtr.h>
44
45 SOFT_LINK_FRAMEWORK(AVFoundation)
46 SOFT_LINK_CLASS(AVFoundation, AVAudioSession)
47 SOFT_LINK_POINTER(AVFoundation, AVAudioSessionInterruptionNotification, NSString *)
48 SOFT_LINK_POINTER(AVFoundation, AVAudioSessionInterruptionTypeKey, NSString *)
49 SOFT_LINK_POINTER(AVFoundation, AVAudioSessionInterruptionOptionKey, NSString *)
50
51 #define AVAudioSession getAVAudioSessionClass()
52 #define AVAudioSessionInterruptionNotification getAVAudioSessionInterruptionNotification()
53 #define AVAudioSessionInterruptionTypeKey getAVAudioSessionInterruptionTypeKey()
54 #define AVAudioSessionInterruptionOptionKey getAVAudioSessionInterruptionOptionKey()
55
56 SOFT_LINK_FRAMEWORK(UIKit)
57 SOFT_LINK_CLASS(UIKit, UIApplication)
58 SOFT_LINK_POINTER(UIKit, UIApplicationWillResignActiveNotification, NSString *)
59 SOFT_LINK_POINTER(UIKit, UIApplicationWillEnterForegroundNotification, NSString *)
60 SOFT_LINK_POINTER(UIKit, UIApplicationDidBecomeActiveNotification, NSString *)
61
62 #define UIApplication getUIApplicationClass()
63 #define UIApplicationWillResignActiveNotification getUIApplicationWillResignActiveNotification()
64 #define UIApplicationWillEnterForegroundNotification getUIApplicationWillEnterForegroundNotification()
65 #define UIApplicationDidBecomeActiveNotification getUIApplicationDidBecomeActiveNotification()
66
67 SOFT_LINK_FRAMEWORK(MediaPlayer)
68 SOFT_LINK_CLASS(MediaPlayer, MPNowPlayingInfoCenter)
69 SOFT_LINK_POINTER(MediaPlayer, MPMediaItemPropertyTitle, NSString *)
70 SOFT_LINK_POINTER(MediaPlayer, MPMediaItemPropertyPlaybackDuration, NSString *)
71 SOFT_LINK_POINTER(MediaPlayer, MPNowPlayingInfoPropertyElapsedPlaybackTime, NSString *)
72 SOFT_LINK_POINTER(MediaPlayer, MPNowPlayingInfoPropertyPlaybackRate, NSString *)
73
74 #define MPMediaItemPropertyTitle getMPMediaItemPropertyTitle()
75 #define MPMediaItemPropertyPlaybackDuration getMPMediaItemPropertyPlaybackDuration()
76 #define MPNowPlayingInfoPropertyElapsedPlaybackTime getMPNowPlayingInfoPropertyElapsedPlaybackTime()
77 #define MPNowPlayingInfoPropertyPlaybackRate getMPNowPlayingInfoPropertyPlaybackRate()
78
79 NSString* WebUIApplicationWillResignActiveNotification = @"WebUIApplicationWillResignActiveNotification";
80 NSString* WebUIApplicationWillEnterForegroundNotification = @"WebUIApplicationWillEnterForegroundNotification";
81 NSString* WebUIApplicationDidBecomeActiveNotification = @"WebUIApplicationDidBecomeActiveNotification";
82
83 using namespace WebCore;
84
85 @interface WebMediaSessionHelper : NSObject {
86     MediaSessionManageriOS* _callback;
87 }
88
89 - (id)initWithCallback:(MediaSessionManageriOS*)callback;
90 - (void)clearCallback;
91 - (void)interruption:(NSNotification *)notification;
92 - (void)applicationWillEnterForeground:(NSNotification *)notification;
93 - (void)applicationWillResignActive:(NSNotification *)notification;
94 @end
95
96 namespace WebCore {
97
98 MediaSessionManager& MediaSessionManager::sharedManager()
99 {
100     DEPRECATED_DEFINE_STATIC_LOCAL(MediaSessionManageriOS, manager, ());
101     return manager;
102 }
103
104 MediaSessionManageriOS::MediaSessionManageriOS()
105     :MediaSessionManager()
106     , m_objcObserver(adoptNS([[WebMediaSessionHelper alloc] initWithCallback:this]))
107 {
108     resetRestrictions();
109 }
110
111 MediaSessionManageriOS::~MediaSessionManageriOS()
112 {
113     [m_objcObserver clearCallback];
114 }
115
116 void MediaSessionManageriOS::resetRestrictions()
117 {
118     MediaSessionManager::resetRestrictions();
119
120     static wkDeviceClass deviceClass = iosDeviceClass();
121     if (deviceClass == wkDeviceClassiPhone || deviceClass == wkDeviceClassiPod)
122         addRestriction(MediaSession::Video, InlineVideoPlaybackRestricted);
123
124     addRestriction(MediaSession::Video, ConcurrentPlaybackNotPermitted);
125     addRestriction(MediaSession::Video, BackgroundPlaybackNotPermitted);
126
127     removeRestriction(MediaSession::Audio, MetadataPreloadingNotPermitted);
128     removeRestriction(MediaSession::Video, MetadataPreloadingNotPermitted);
129     addRestriction(MediaSession::Audio, AutoPreloadingNotPermitted);
130     addRestriction(MediaSession::Video, AutoPreloadingNotPermitted);
131 }
132
133 #if ENABLE(IOS_AIRPLAY)
134 void MediaSessionManageriOS::showPlaybackTargetPicker()
135 {
136     notImplemented();
137 }
138 #endif
139     
140 void MediaSessionManageriOS::sessionWillBeginPlayback(MediaSession& session)
141 {
142     MediaSessionManager::sessionWillBeginPlayback(session);
143     updateNowPlayingInfo();
144 }
145     
146 void MediaSessionManageriOS::sessionWillEndPlayback(MediaSession& session)
147 {
148     MediaSessionManager::sessionWillEndPlayback(session);
149     updateNowPlayingInfo();
150 }
151     
152 void MediaSessionManageriOS::updateNowPlayingInfo()
153 {
154     MPNowPlayingInfoCenter *nowPlaying = (MPNowPlayingInfoCenter *)[getMPNowPlayingInfoCenterClass() defaultCenter];
155     const MediaSession* currentSession = this->currentSession();
156     
157     if (!currentSession) {
158         [nowPlaying setNowPlayingInfo:nil];
159         return;
160     }
161     
162     RetainPtr<NSMutableDictionary> info = adoptNS([[NSMutableDictionary alloc] init]);
163     
164     String title = currentSession->title();
165     if (!title.isEmpty())
166         [info setValue:static_cast<NSString *>(title) forKey:MPMediaItemPropertyTitle];
167     
168     double duration = currentSession->duration();
169     if (std::isfinite(duration) && duration != MediaPlayer::invalidTime())
170         [info setValue:@(duration) forKey:MPMediaItemPropertyPlaybackDuration];
171     
172     double currentTime = currentSession->currentTime();
173     if (std::isfinite(currentTime))
174         [info setValue:@(currentTime) forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime];
175     
176     [info setValue:(currentSession->state() == MediaSession::Playing ? @YES : @NO) forKey:MPNowPlayingInfoPropertyPlaybackRate];
177     [nowPlaying setNowPlayingInfo:info.get()];
178 }
179
180 } // namespace WebCore
181
182 @implementation WebMediaSessionHelper
183
184 - (id)initWithCallback:(MediaSessionManageriOS*)callback
185 {
186     if (!(self = [super init]))
187         return nil;
188     
189     _callback = callback;
190
191     NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
192     [center addObserver:self selector:@selector(interruption:) name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]];
193
194     [center addObserver:self selector:@selector(applicationWillEnterForeground:) name:UIApplicationWillEnterForegroundNotification object:nil];
195     [center addObserver:self selector:@selector(applicationWillEnterForeground:) name:WebUIApplicationWillEnterForegroundNotification object:nil];
196     [center addObserver:self selector:@selector(applicationDidBecomeActive:) name:UIApplicationDidBecomeActiveNotification object:nil];
197     [center addObserver:self selector:@selector(applicationDidBecomeActive:) name:WebUIApplicationDidBecomeActiveNotification object:nil];
198     [center addObserver:self selector:@selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:nil];
199     [center addObserver:self selector:@selector(applicationWillResignActive:) name:WebUIApplicationWillResignActiveNotification object:nil];
200     
201     // Now playing won't work unless we turn on the delivery of remote control events.
202     [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
203     
204     return self;
205 }
206
207 - (void)dealloc
208 {
209     [[NSNotificationCenter defaultCenter] removeObserver:self];
210     [super dealloc];
211 }
212
213 - (void)clearCallback
214 {
215     _callback = nil;
216 }
217
218 - (void)interruption:(NSNotification *)notification
219 {
220     if (!_callback)
221         return;
222
223     NSUInteger type = [[[notification userInfo] objectForKey:AVAudioSessionInterruptionTypeKey] unsignedIntegerValue];
224     MediaSession::EndInterruptionFlags flags = MediaSession::NoFlags;
225
226     if (type == AVAudioSessionInterruptionTypeEnded && [[[notification userInfo] objectForKey:AVAudioSessionInterruptionOptionKey] unsignedIntegerValue] == AVAudioSessionInterruptionOptionShouldResume)
227         flags = MediaSession::MayResumePlaying;
228
229     WebThreadRun(^{
230         if (!_callback)
231             return;
232
233         if (type == AVAudioSessionInterruptionTypeBegan)
234             _callback->beginInterruption();
235         else
236             _callback->endInterruption(flags);
237
238     });
239 }
240
241 - (void)applicationWillEnterForeground:(NSNotification *)notification
242 {
243     UNUSED_PARAM(notification);
244
245     if (!_callback)
246         return;
247
248     WebThreadRun(^{
249         if (!_callback)
250             return;
251
252         _callback->applicationWillEnterForeground();
253     });
254 }
255
256 - (void)applicationDidBecomeActive:(NSNotification *)notification
257 {
258     UNUSED_PARAM(notification);
259
260     if (!_callback)
261         return;
262
263     WebThreadRun(^{
264         if (!_callback)
265             return;
266
267         _callback->applicationWillEnterForeground();
268     });
269 }
270
271 - (void)applicationWillResignActive:(NSNotification *)notification
272 {
273     UNUSED_PARAM(notification);
274
275     if (!_callback)
276         return;
277     
278     WebThreadRun(^{
279         if (!_callback)
280             return;
281         
282         _callback->applicationWillEnterBackground();
283     });
284 }
285
286 @end
287
288 #endif // PLATFORM(IOS)