[WebKitLegacy] Media playback pauses on scroll
[WebKit-https.git] / Source / WebCore / platform / audio / PlatformMediaSessionManager.cpp
1 /*
2  * Copyright (C) 2013-2015 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 #include "config.h"
27 #include "PlatformMediaSessionManager.h"
28
29 #include "AudioSession.h"
30 #include "Document.h"
31 #include "Logging.h"
32 #include "PlatformMediaSession.h"
33
34 namespace WebCore {
35
36 #if ENABLE(VIDEO) || ENABLE(WEB_AUDIO)
37
38 #if !PLATFORM(COCOA)
39 static PlatformMediaSessionManager* platformMediaSessionManager = nullptr;
40
41 PlatformMediaSessionManager& PlatformMediaSessionManager::sharedManager()
42 {
43     if (!platformMediaSessionManager)
44         platformMediaSessionManager = new PlatformMediaSessionManager;
45     return *platformMediaSessionManager;
46 }
47
48 PlatformMediaSessionManager* PlatformMediaSessionManager::sharedManagerIfExists()
49 {
50     return platformMediaSessionManager;
51 }
52 #endif // !PLATFORM(COCOA)
53
54 void PlatformMediaSessionManager::updateNowPlayingInfoIfNecessary()
55 {
56     if (auto existingManager = PlatformMediaSessionManager::sharedManagerIfExists())
57         existingManager->scheduleUpdateNowPlayingInfo();
58 }
59
60 PlatformMediaSessionManager::PlatformMediaSessionManager()
61     : m_systemSleepListener(PAL::SystemSleepListener::create(*this))
62 {
63     resetRestrictions();
64 }
65
66 void PlatformMediaSessionManager::resetRestrictions()
67 {
68     m_restrictions[PlatformMediaSession::Video] = NoRestrictions;
69     m_restrictions[PlatformMediaSession::Audio] = NoRestrictions;
70     m_restrictions[PlatformMediaSession::VideoAudio] = NoRestrictions;
71     m_restrictions[PlatformMediaSession::WebAudio] = NoRestrictions;
72     m_restrictions[PlatformMediaSession::MediaStreamCapturingAudio] = NoRestrictions;
73 }
74
75 bool PlatformMediaSessionManager::has(PlatformMediaSession::MediaType type) const
76 {
77     ASSERT(type >= PlatformMediaSession::None && type <= PlatformMediaSession::MediaStreamCapturingAudio);
78
79     return anyOfSessions([type] (PlatformMediaSession& session, size_t) {
80         return session.mediaType() == type;
81     });
82 }
83
84 bool PlatformMediaSessionManager::activeAudioSessionRequired() const
85 {
86     return anyOfSessions([] (PlatformMediaSession& session, size_t) {
87         return session.activeAudioSessionRequired();
88     });
89 }
90
91 bool PlatformMediaSessionManager::canProduceAudio() const
92 {
93     return anyOfSessions([] (PlatformMediaSession& session, size_t) {
94         return session.canProduceAudio();
95     });
96 }
97
98 int PlatformMediaSessionManager::count(PlatformMediaSession::MediaType type) const
99 {
100     ASSERT(type >= PlatformMediaSession::None && type <= PlatformMediaSession::MediaStreamCapturingAudio);
101
102     int count = 0;
103     for (auto* session : m_sessions) {
104         if (session->mediaType() == type)
105             ++count;
106     }
107
108     return count;
109 }
110
111 void PlatformMediaSessionManager::beginInterruption(PlatformMediaSession::InterruptionType type)
112 {
113     LOG(Media, "PlatformMediaSessionManager::beginInterruption");
114
115     m_interrupted = true;
116     forEachSession([type] (PlatformMediaSession& session, size_t) {
117         session.beginInterruption(type);
118     });
119     updateSessionState();
120 }
121
122 void PlatformMediaSessionManager::endInterruption(PlatformMediaSession::EndInterruptionFlags flags)
123 {
124     LOG(Media, "PlatformMediaSessionManager::endInterruption");
125
126     m_interrupted = false;
127     forEachSession([flags] (PlatformMediaSession& session, size_t) {
128         session.endInterruption(flags);
129     });
130 }
131
132 void PlatformMediaSessionManager::addSession(PlatformMediaSession& session)
133 {
134     LOG(Media, "PlatformMediaSessionManager::addSession - %p", &session);
135     
136     m_sessions.append(&session);
137     if (m_interrupted)
138         session.setState(PlatformMediaSession::Interrupted);
139
140     if (!m_remoteCommandListener)
141         m_remoteCommandListener = RemoteCommandListener::create(*this);
142
143     if (!m_audioHardwareListener)
144         m_audioHardwareListener = AudioHardwareListener::create(*this);
145
146     updateSessionState();
147 }
148
149 void PlatformMediaSessionManager::removeSession(PlatformMediaSession& session)
150 {
151     LOG(Media, "PlatformMediaSessionManager::removeSession - %p", &session);
152     
153     size_t index = m_sessions.find(&session);
154     if (index == notFound)
155         return;
156
157     if (m_iteratingOverSessions)
158         m_sessions.at(index) = nullptr;
159     else
160         m_sessions.remove(index);
161
162     if (m_sessions.isEmpty() || std::all_of(m_sessions.begin(), m_sessions.end(), std::logical_not<void>())) {
163         m_remoteCommandListener = nullptr;
164         m_audioHardwareListener = nullptr;
165     }
166
167     updateSessionState();
168 }
169
170 void PlatformMediaSessionManager::addRestriction(PlatformMediaSession::MediaType type, SessionRestrictions restriction)
171 {
172     ASSERT(type > PlatformMediaSession::None && type <= PlatformMediaSession::MediaStreamCapturingAudio);
173     m_restrictions[type] |= restriction;
174 }
175
176 void PlatformMediaSessionManager::removeRestriction(PlatformMediaSession::MediaType type, SessionRestrictions restriction)
177 {
178     ASSERT(type > PlatformMediaSession::None && type <= PlatformMediaSession::MediaStreamCapturingAudio);
179     m_restrictions[type] &= ~restriction;
180 }
181
182 PlatformMediaSessionManager::SessionRestrictions PlatformMediaSessionManager::restrictions(PlatformMediaSession::MediaType type)
183 {
184     ASSERT(type > PlatformMediaSession::None && type <= PlatformMediaSession::MediaStreamCapturingAudio);
185     return m_restrictions[type];
186 }
187
188 bool PlatformMediaSessionManager::sessionWillBeginPlayback(PlatformMediaSession& session)
189 {
190     LOG(Media, "PlatformMediaSessionManager::sessionWillBeginPlayback - %p", &session);
191     
192     setCurrentSession(session);
193
194     PlatformMediaSession::MediaType sessionType = session.mediaType();
195     SessionRestrictions restrictions = m_restrictions[sessionType];
196     if (session.state() == PlatformMediaSession::Interrupted && restrictions & InterruptedPlaybackNotPermitted)
197         return false;
198
199 #if USE(AUDIO_SESSION)
200     if (activeAudioSessionRequired() && !AudioSession::sharedSession().tryToSetActive(true))
201         return false;
202 #endif
203
204     if (m_interrupted)
205         endInterruption(PlatformMediaSession::NoFlags);
206
207     forEachSession([&] (PlatformMediaSession& oneSession, size_t) {
208         if (&oneSession == &session)
209             return;
210         if (oneSession.mediaType() == sessionType
211             && restrictions & ConcurrentPlaybackNotPermitted
212             && oneSession.state() == PlatformMediaSession::Playing)
213             oneSession.pauseSession();
214     });
215
216     return true;
217 }
218     
219 void PlatformMediaSessionManager::sessionWillEndPlayback(PlatformMediaSession& session)
220 {
221     LOG(Media, "PlatformMediaSessionManager::sessionWillEndPlayback - %p", &session);
222     
223     if (m_sessions.size() < 2)
224         return;
225     
226     size_t pausingSessionIndex = notFound;
227     size_t lastPlayingSessionIndex = notFound;
228     anyOfSessions([&] (PlatformMediaSession& oneSession, size_t i) {
229         if (&oneSession == &session) {
230             pausingSessionIndex = i;
231             return false;
232         }
233         if (oneSession.state() == PlatformMediaSession::Playing) {
234             lastPlayingSessionIndex = i;
235             return false;
236         }
237         return oneSession.state() != PlatformMediaSession::Playing;
238     });
239     if (lastPlayingSessionIndex == notFound || pausingSessionIndex == notFound)
240         return;
241     
242     if (pausingSessionIndex > lastPlayingSessionIndex)
243         return;
244     
245     m_sessions.remove(pausingSessionIndex);
246     m_sessions.insert(lastPlayingSessionIndex, &session);
247     
248     LOG(Media, "PlatformMediaSessionManager::sessionWillEndPlayback - session moved from index %zu to %zu", pausingSessionIndex, lastPlayingSessionIndex);
249 }
250
251 void PlatformMediaSessionManager::sessionStateChanged(PlatformMediaSession&)
252 {
253     updateSessionState();
254 }
255
256 void PlatformMediaSessionManager::setCurrentSession(PlatformMediaSession& session)
257 {
258     LOG(Media, "PlatformMediaSessionManager::setCurrentSession - %p", &session);
259     
260     if (m_sessions.size() < 2)
261         return;
262     
263     size_t index = m_sessions.find(&session);
264     ASSERT(index != notFound);
265     if (!index || index == notFound)
266         return;
267
268     m_sessions.remove(index);
269     m_sessions.insert(0, &session);
270     if (m_remoteCommandListener)
271         m_remoteCommandListener->updateSupportedCommands();
272     
273     LOG(Media, "PlatformMediaSessionManager::setCurrentSession - session moved from index %zu to 0", index);
274 }
275     
276 PlatformMediaSession* PlatformMediaSessionManager::currentSession() const
277 {
278     if (!m_sessions.size())
279         return nullptr;
280
281     return m_sessions[0];
282 }
283
284 Vector<PlatformMediaSession*> PlatformMediaSessionManager::currentSessionsMatching(const WTF::Function<bool(const PlatformMediaSession&)>& filter)
285 {
286     Vector<PlatformMediaSession*> matchingSessions;
287     forEachSession([&] (PlatformMediaSession& session, size_t) {
288         if (filter(session))
289             matchingSessions.append(&session);
290     });
291     return matchingSessions;
292 }
293
294 void PlatformMediaSessionManager::applicationWillBecomeInactive() const
295 {
296     LOG(Media, "PlatformMediaSessionManager::applicationWillBecomeInactive");
297
298     forEachSession([&] (PlatformMediaSession& session, size_t) {
299         if (m_restrictions[session.mediaType()] & InactiveProcessPlaybackRestricted)
300             session.beginInterruption(PlatformMediaSession::ProcessInactive);
301     });
302 }
303
304 void PlatformMediaSessionManager::applicationDidBecomeActive() const
305 {
306     LOG(Media, "PlatformMediaSessionManager::applicationDidBecomeActive");
307
308     forEachSession([&] (PlatformMediaSession& session, size_t) {
309         if (m_restrictions[session.mediaType()] & InactiveProcessPlaybackRestricted)
310             session.endInterruption(PlatformMediaSession::MayResumePlaying);
311     });
312 }
313
314 void PlatformMediaSessionManager::applicationDidEnterBackground(bool suspendedUnderLock) const
315 {
316     LOG(Media, "PlatformMediaSessionManager::applicationDidEnterBackground - suspendedUnderLock(%d)", suspendedUnderLock);
317
318     if (m_isApplicationInBackground)
319         return;
320
321     m_isApplicationInBackground = true;
322
323     forEachSession([&] (PlatformMediaSession& session, size_t) {
324         if (suspendedUnderLock && m_restrictions[session.mediaType()] & SuspendedUnderLockPlaybackRestricted)
325             session.beginInterruption(PlatformMediaSession::SuspendedUnderLock);
326         else if (m_restrictions[session.mediaType()] & BackgroundProcessPlaybackRestricted)
327             session.beginInterruption(PlatformMediaSession::EnteringBackground);
328     });
329 }
330
331 void PlatformMediaSessionManager::applicationWillEnterForeground(bool suspendedUnderLock) const
332 {
333     LOG(Media, "PlatformMediaSessionManager::applicationWillEnterForeground - suspendedUnderLock(%d)", suspendedUnderLock);
334
335     if (!m_isApplicationInBackground)
336         return;
337
338     m_isApplicationInBackground = false;
339
340     forEachSession([&] (PlatformMediaSession& session, size_t) {
341         if ((suspendedUnderLock && m_restrictions[session.mediaType()] & SuspendedUnderLockPlaybackRestricted) || m_restrictions[session.mediaType()] & BackgroundProcessPlaybackRestricted)
342             session.endInterruption(PlatformMediaSession::MayResumePlaying);
343     });
344 }
345
346 void PlatformMediaSessionManager::sessionIsPlayingToWirelessPlaybackTargetChanged(PlatformMediaSession& session)
347 {
348     if (!m_isApplicationInBackground || !(m_restrictions[session.mediaType()] & BackgroundProcessPlaybackRestricted))
349         return;
350
351     if (session.state() != PlatformMediaSession::Interrupted)
352         session.beginInterruption(PlatformMediaSession::EnteringBackground);
353 }
354
355 void PlatformMediaSessionManager::sessionCanProduceAudioChanged(PlatformMediaSession&)
356 {
357     updateSessionState();
358 }
359
360 void PlatformMediaSessionManager::didReceiveRemoteControlCommand(PlatformMediaSession::RemoteControlCommandType command, const PlatformMediaSession::RemoteCommandArgument* argument)
361 {
362     PlatformMediaSession* activeSession = currentSession();
363     if (!activeSession || !activeSession->canReceiveRemoteControlCommands())
364         return;
365     activeSession->didReceiveRemoteControlCommand(command, argument);
366 }
367
368 bool PlatformMediaSessionManager::supportsSeeking() const
369 {
370     PlatformMediaSession* activeSession = currentSession();
371     if (!activeSession)
372         return false;
373     return activeSession->supportsSeeking();
374 }
375
376 void PlatformMediaSessionManager::systemWillSleep()
377 {
378     if (m_interrupted)
379         return;
380
381     forEachSession([] (PlatformMediaSession& session, size_t) {
382         session.beginInterruption(PlatformMediaSession::SystemSleep);
383     });
384 }
385
386 void PlatformMediaSessionManager::systemDidWake()
387 {
388     if (m_interrupted)
389         return;
390
391     forEachSession([] (PlatformMediaSession& session, size_t) {
392         session.endInterruption(PlatformMediaSession::MayResumePlaying);
393     });
394 }
395
396 void PlatformMediaSessionManager::audioOutputDeviceChanged()
397 {
398     updateSessionState();
399 }
400
401 void PlatformMediaSessionManager::stopAllMediaPlaybackForDocument(const Document* document)
402 {
403     forEachSession([document] (PlatformMediaSession& session, size_t) {
404         if (session.client().hostingDocument() == document)
405             session.pauseSession();
406     });
407 }
408
409 void PlatformMediaSessionManager::stopAllMediaPlaybackForProcess()
410 {
411     forEachSession([] (PlatformMediaSession& session, size_t) {
412         session.stopSession();
413     });
414 }
415
416 void PlatformMediaSessionManager::suspendAllMediaPlaybackForDocument(const Document& document)
417 {
418     forEachSession([&] (PlatformMediaSession& session, size_t) {
419         if (session.client().hostingDocument() == &document)
420             session.beginInterruption(PlatformMediaSession::PlaybackSuspended);
421     });
422 }
423
424 void PlatformMediaSessionManager::resumeAllMediaPlaybackForDocument(const Document& document)
425 {
426     forEachSession([&] (PlatformMediaSession& session, size_t) {
427         if (session.client().hostingDocument() == &document)
428             session.endInterruption(PlatformMediaSession::MayResumePlaying);
429     });
430 }
431
432 void PlatformMediaSessionManager::forEachSession(const Function<void(PlatformMediaSession&, size_t)>& predicate) const
433 {
434     ++m_iteratingOverSessions;
435
436     for (size_t i = 0, size = m_sessions.size(); i < size; ++i) {
437         auto session = m_sessions[i];
438         if (!session)
439             continue;
440         predicate(*session, i);
441     }
442
443     --m_iteratingOverSessions;
444     if (!m_iteratingOverSessions)
445         m_sessions.removeAll(nullptr);
446 }
447
448 PlatformMediaSession* PlatformMediaSessionManager::findSession(const Function<bool(PlatformMediaSession&, size_t)>& predicate) const
449 {
450     ++m_iteratingOverSessions;
451
452     PlatformMediaSession* foundSession = nullptr;
453     for (size_t i = 0, size = m_sessions.size(); i < size; ++i) {
454         auto session = m_sessions[i];
455         if (!session)
456             continue;
457
458         if (!predicate(*session, i))
459             continue;
460
461         foundSession = session;
462         break;
463     }
464
465     --m_iteratingOverSessions;
466     if (!m_iteratingOverSessions)
467         m_sessions.removeAll(nullptr);
468
469     return foundSession;
470 }
471
472 #else // ENABLE(VIDEO) || ENABLE(WEB_AUDIO)
473
474 void PlatformMediaSessionManager::updateNowPlayingInfoIfNecessary()
475 {
476
477 }
478
479 #endif // ENABLE(VIDEO) || ENABLE(WEB_AUDIO)
480
481 } // namespace WebCore