[Cocoa] Deactivate the audio session before the WebProcess suspends.
[WebKit-https.git] / Source / WebCore / platform / audio / PlatformMediaSessionManager.cpp
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. 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 #if !RELEASE_LOG_DISABLED
63     , m_logger(AggregateLogger::create(this))
64 #endif
65 {
66     resetRestrictions();
67 }
68
69 void PlatformMediaSessionManager::resetRestrictions()
70 {
71     m_restrictions[PlatformMediaSession::Video] = NoRestrictions;
72     m_restrictions[PlatformMediaSession::Audio] = NoRestrictions;
73     m_restrictions[PlatformMediaSession::VideoAudio] = NoRestrictions;
74     m_restrictions[PlatformMediaSession::WebAudio] = NoRestrictions;
75     m_restrictions[PlatformMediaSession::MediaStreamCapturingAudio] = NoRestrictions;
76 }
77
78 bool PlatformMediaSessionManager::has(PlatformMediaSession::MediaType type) const
79 {
80     ASSERT(type >= PlatformMediaSession::None && type <= PlatformMediaSession::MediaStreamCapturingAudio);
81
82     return anyOfSessions([type] (PlatformMediaSession& session, size_t) {
83         return session.mediaType() == type;
84     });
85 }
86
87 bool PlatformMediaSessionManager::activeAudioSessionRequired() const
88 {
89     return anyOfSessions([] (PlatformMediaSession& session, size_t) {
90         return session.activeAudioSessionRequired();
91     });
92 }
93
94 bool PlatformMediaSessionManager::canProduceAudio() const
95 {
96     return anyOfSessions([] (PlatformMediaSession& session, size_t) {
97         return session.canProduceAudio();
98     });
99 }
100
101 int PlatformMediaSessionManager::count(PlatformMediaSession::MediaType type) const
102 {
103     ASSERT(type >= PlatformMediaSession::None && type <= PlatformMediaSession::MediaStreamCapturingAudio);
104
105     int count = 0;
106     for (auto* session : m_sessions) {
107         if (session->mediaType() == type)
108             ++count;
109     }
110
111     return count;
112 }
113
114 void PlatformMediaSessionManager::beginInterruption(PlatformMediaSession::InterruptionType type)
115 {
116     ALWAYS_LOG(LOGIDENTIFIER);
117
118     m_interrupted = true;
119     forEachSession([type] (PlatformMediaSession& session, size_t) {
120         session.beginInterruption(type);
121     });
122     updateSessionState();
123 }
124
125 void PlatformMediaSessionManager::endInterruption(PlatformMediaSession::EndInterruptionFlags flags)
126 {
127     ALWAYS_LOG(LOGIDENTIFIER);
128
129     m_interrupted = false;
130     forEachSession([flags] (PlatformMediaSession& session, size_t) {
131         session.endInterruption(flags);
132     });
133 }
134
135 void PlatformMediaSessionManager::addSession(PlatformMediaSession& session)
136 {
137     ALWAYS_LOG(LOGIDENTIFIER, session.logIdentifier());
138     
139     m_sessions.append(&session);
140     if (m_interrupted)
141         session.setState(PlatformMediaSession::Interrupted);
142
143     if (!m_remoteCommandListener)
144         m_remoteCommandListener = RemoteCommandListener::create(*this);
145
146     if (!m_audioHardwareListener)
147         m_audioHardwareListener = AudioHardwareListener::create(*this);
148
149 #if !RELEASE_LOG_DISABLED
150     m_logger->addLogger(session.logger());
151 #endif
152
153     updateSessionState();
154 }
155
156 void PlatformMediaSessionManager::removeSession(PlatformMediaSession& session)
157 {
158     ALWAYS_LOG(LOGIDENTIFIER, session.logIdentifier());
159     
160     size_t index = m_sessions.find(&session);
161     if (index == notFound)
162         return;
163
164     if (m_iteratingOverSessions)
165         m_sessions.at(index) = nullptr;
166     else
167         m_sessions.remove(index);
168
169     if (m_sessions.isEmpty() || std::all_of(m_sessions.begin(), m_sessions.end(), std::logical_not<void>())) {
170         m_remoteCommandListener = nullptr;
171         m_audioHardwareListener = nullptr;
172 #if USE(AUDIO_SESSION)
173         if (m_becameActive && shouldDeactivateAudioSession()) {
174             AudioSession::sharedSession().tryToSetActive(false);
175             m_becameActive = false;
176         }
177 #endif
178     }
179
180 #if !RELEASE_LOG_DISABLED
181     m_logger->removeLogger(session.logger());
182 #endif
183
184     updateSessionState();
185 }
186
187 void PlatformMediaSessionManager::addRestriction(PlatformMediaSession::MediaType type, SessionRestrictions restriction)
188 {
189     ASSERT(type > PlatformMediaSession::None && type <= PlatformMediaSession::MediaStreamCapturingAudio);
190     m_restrictions[type] |= restriction;
191 }
192
193 void PlatformMediaSessionManager::removeRestriction(PlatformMediaSession::MediaType type, SessionRestrictions restriction)
194 {
195     ASSERT(type > PlatformMediaSession::None && type <= PlatformMediaSession::MediaStreamCapturingAudio);
196     m_restrictions[type] &= ~restriction;
197 }
198
199 PlatformMediaSessionManager::SessionRestrictions PlatformMediaSessionManager::restrictions(PlatformMediaSession::MediaType type)
200 {
201     ASSERT(type > PlatformMediaSession::None && type <= PlatformMediaSession::MediaStreamCapturingAudio);
202     return m_restrictions[type];
203 }
204
205 bool PlatformMediaSessionManager::sessionWillBeginPlayback(PlatformMediaSession& session)
206 {
207     setCurrentSession(session);
208
209     PlatformMediaSession::MediaType sessionType = session.mediaType();
210     SessionRestrictions restrictions = m_restrictions[sessionType];
211     if (session.state() == PlatformMediaSession::Interrupted && restrictions & InterruptedPlaybackNotPermitted) {
212         ALWAYS_LOG(LOGIDENTIFIER, session.logIdentifier(), " returning false because session.state() is Interrupted, and InterruptedPlaybackNotPermitted");
213         return false;
214     }
215
216     if (m_processIsSuspended) {
217         ALWAYS_LOG(LOGIDENTIFIER, session.logIdentifier(), " returning false because process is suspended");
218         return false;
219     }
220
221 #if USE(AUDIO_SESSION)
222     if (activeAudioSessionRequired() && !AudioSession::sharedSession().tryToSetActive(true)) {
223         ALWAYS_LOG(LOGIDENTIFIER, session.logIdentifier(), " returning false failed to set active AudioSession");
224         return false;
225     }
226
227     m_becameActive = true;
228 #endif
229
230     if (m_interrupted)
231         endInterruption(PlatformMediaSession::NoFlags);
232
233     forEachSession([&] (PlatformMediaSession& oneSession, size_t) {
234         if (&oneSession == &session)
235             return;
236         if (oneSession.mediaType() == sessionType
237             && restrictions & ConcurrentPlaybackNotPermitted
238             && oneSession.state() == PlatformMediaSession::Playing)
239             oneSession.pauseSession();
240     });
241
242     ALWAYS_LOG(LOGIDENTIFIER, session.logIdentifier(), " returning true");
243     return true;
244 }
245     
246 void PlatformMediaSessionManager::sessionWillEndPlayback(PlatformMediaSession& session)
247 {
248     ALWAYS_LOG(LOGIDENTIFIER, session.logIdentifier());
249     
250     if (m_sessions.size() < 2)
251         return;
252     
253     size_t pausingSessionIndex = notFound;
254     size_t lastPlayingSessionIndex = notFound;
255     anyOfSessions([&] (PlatformMediaSession& oneSession, size_t i) {
256         if (&oneSession == &session) {
257             pausingSessionIndex = i;
258             return false;
259         }
260         if (oneSession.state() == PlatformMediaSession::Playing) {
261             lastPlayingSessionIndex = i;
262             return false;
263         }
264         return oneSession.state() != PlatformMediaSession::Playing;
265     });
266     if (lastPlayingSessionIndex == notFound || pausingSessionIndex == notFound)
267         return;
268     
269     if (pausingSessionIndex > lastPlayingSessionIndex)
270         return;
271     
272     m_sessions.remove(pausingSessionIndex);
273     m_sessions.insert(lastPlayingSessionIndex, &session);
274     
275     ALWAYS_LOG(LOGIDENTIFIER, "session moved from index ", pausingSessionIndex, " to ", lastPlayingSessionIndex);
276 }
277
278 void PlatformMediaSessionManager::sessionStateChanged(PlatformMediaSession&)
279 {
280     updateSessionState();
281 }
282
283 void PlatformMediaSessionManager::setCurrentSession(PlatformMediaSession& session)
284 {
285     ALWAYS_LOG(LOGIDENTIFIER, session.logIdentifier());
286     
287     if (m_sessions.size() < 2)
288         return;
289     
290     size_t index = m_sessions.find(&session);
291     ASSERT(index != notFound);
292     if (!index || index == notFound)
293         return;
294
295     m_sessions.remove(index);
296     m_sessions.insert(0, &session);
297     if (m_remoteCommandListener)
298         m_remoteCommandListener->updateSupportedCommands();
299     
300     ALWAYS_LOG(LOGIDENTIFIER, "session moved from index ", index, " to 0");
301 }
302     
303 PlatformMediaSession* PlatformMediaSessionManager::currentSession() const
304 {
305     if (!m_sessions.size())
306         return nullptr;
307
308     return m_sessions[0];
309 }
310
311 Vector<PlatformMediaSession*> PlatformMediaSessionManager::currentSessionsMatching(const WTF::Function<bool(const PlatformMediaSession&)>& filter)
312 {
313     Vector<PlatformMediaSession*> matchingSessions;
314     forEachSession([&] (PlatformMediaSession& session, size_t) {
315         if (filter(session))
316             matchingSessions.append(&session);
317     });
318     return matchingSessions;
319 }
320
321 void PlatformMediaSessionManager::applicationWillBecomeInactive() const
322 {
323     ALWAYS_LOG(LOGIDENTIFIER);
324
325     forEachSession([&] (PlatformMediaSession& session, size_t) {
326         if (m_restrictions[session.mediaType()] & InactiveProcessPlaybackRestricted)
327             session.beginInterruption(PlatformMediaSession::ProcessInactive);
328     });
329 }
330
331 void PlatformMediaSessionManager::applicationDidBecomeActive() const
332 {
333     ALWAYS_LOG(LOGIDENTIFIER);
334
335     forEachSession([&] (PlatformMediaSession& session, size_t) {
336         if (m_restrictions[session.mediaType()] & InactiveProcessPlaybackRestricted)
337             session.endInterruption(PlatformMediaSession::MayResumePlaying);
338     });
339 }
340
341 void PlatformMediaSessionManager::applicationDidEnterBackground(bool suspendedUnderLock) const
342 {
343     ALWAYS_LOG(LOGIDENTIFIER, "suspendedUnderLock: ", suspendedUnderLock);
344
345     if (m_isApplicationInBackground)
346         return;
347
348     m_isApplicationInBackground = true;
349
350     forEachSession([&] (PlatformMediaSession& session, size_t) {
351         if (suspendedUnderLock && m_restrictions[session.mediaType()] & SuspendedUnderLockPlaybackRestricted)
352             session.beginInterruption(PlatformMediaSession::SuspendedUnderLock);
353         else if (m_restrictions[session.mediaType()] & BackgroundProcessPlaybackRestricted)
354             session.beginInterruption(PlatformMediaSession::EnteringBackground);
355     });
356 }
357
358 void PlatformMediaSessionManager::applicationWillEnterForeground(bool suspendedUnderLock) const
359 {
360     ALWAYS_LOG(LOGIDENTIFIER, "suspendedUnderLock: ", suspendedUnderLock);
361
362     if (!m_isApplicationInBackground)
363         return;
364
365     m_isApplicationInBackground = false;
366
367     forEachSession([&] (PlatformMediaSession& session, size_t) {
368         if ((suspendedUnderLock && m_restrictions[session.mediaType()] & SuspendedUnderLockPlaybackRestricted) || m_restrictions[session.mediaType()] & BackgroundProcessPlaybackRestricted)
369             session.endInterruption(PlatformMediaSession::MayResumePlaying);
370     });
371 }
372
373 void PlatformMediaSessionManager::processWillSuspend()
374 {
375     if (m_processIsSuspended)
376         return;
377     m_processIsSuspended = true;
378
379 #if USE(AUDIO_SESSION)
380     if (m_becameActive && shouldDeactivateAudioSession()) {
381         AudioSession::sharedSession().tryToSetActive(false);
382         ALWAYS_LOG(LOGIDENTIFIER, "tried to set inactive AudioSession");
383         m_becameActive = false;
384     }
385 #endif
386 }
387
388 void PlatformMediaSessionManager::processDidResume()
389 {
390     if (!m_processIsSuspended)
391         return;
392     m_processIsSuspended = false;
393
394 #if USE(AUDIO_SESSION)
395     if (!m_becameActive && activeAudioSessionRequired()) {
396         m_becameActive = AudioSession::sharedSession().tryToSetActive(true);
397         ALWAYS_LOG(LOGIDENTIFIER, "tried to set active AudioSession, ", m_becameActive ? "succeeded" : "failed");
398     }
399 #endif
400 }
401
402
403 void PlatformMediaSessionManager::sessionIsPlayingToWirelessPlaybackTargetChanged(PlatformMediaSession& session)
404 {
405     if (!m_isApplicationInBackground || !(m_restrictions[session.mediaType()] & BackgroundProcessPlaybackRestricted))
406         return;
407
408     if (session.state() != PlatformMediaSession::Interrupted)
409         session.beginInterruption(PlatformMediaSession::EnteringBackground);
410 }
411
412 void PlatformMediaSessionManager::sessionCanProduceAudioChanged(PlatformMediaSession&)
413 {
414     updateSessionState();
415 }
416
417 void PlatformMediaSessionManager::didReceiveRemoteControlCommand(PlatformMediaSession::RemoteControlCommandType command, const PlatformMediaSession::RemoteCommandArgument* argument)
418 {
419     PlatformMediaSession* activeSession = currentSession();
420     if (!activeSession || !activeSession->canReceiveRemoteControlCommands())
421         return;
422     activeSession->didReceiveRemoteControlCommand(command, argument);
423 }
424
425 bool PlatformMediaSessionManager::supportsSeeking() const
426 {
427     PlatformMediaSession* activeSession = currentSession();
428     if (!activeSession)
429         return false;
430     return activeSession->supportsSeeking();
431 }
432
433 void PlatformMediaSessionManager::systemWillSleep()
434 {
435     if (m_interrupted)
436         return;
437
438     forEachSession([] (PlatformMediaSession& session, size_t) {
439         session.beginInterruption(PlatformMediaSession::SystemSleep);
440     });
441 }
442
443 void PlatformMediaSessionManager::systemDidWake()
444 {
445     if (m_interrupted)
446         return;
447
448     forEachSession([] (PlatformMediaSession& session, size_t) {
449         session.endInterruption(PlatformMediaSession::MayResumePlaying);
450     });
451 }
452
453 void PlatformMediaSessionManager::audioOutputDeviceChanged()
454 {
455     updateSessionState();
456 }
457
458 void PlatformMediaSessionManager::stopAllMediaPlaybackForDocument(const Document* document)
459 {
460     forEachSession([document] (PlatformMediaSession& session, size_t) {
461         if (session.client().hostingDocument() == document)
462             session.pauseSession();
463     });
464 }
465
466 void PlatformMediaSessionManager::stopAllMediaPlaybackForProcess()
467 {
468     forEachSession([] (PlatformMediaSession& session, size_t) {
469         session.stopSession();
470     });
471 }
472
473 void PlatformMediaSessionManager::suspendAllMediaPlaybackForDocument(const Document& document)
474 {
475     forEachSession([&] (PlatformMediaSession& session, size_t) {
476         if (session.client().hostingDocument() == &document)
477             session.beginInterruption(PlatformMediaSession::PlaybackSuspended);
478     });
479 }
480
481 void PlatformMediaSessionManager::resumeAllMediaPlaybackForDocument(const Document& document)
482 {
483     forEachSession([&] (PlatformMediaSession& session, size_t) {
484         if (session.client().hostingDocument() == &document)
485             session.endInterruption(PlatformMediaSession::MayResumePlaying);
486     });
487 }
488
489 void PlatformMediaSessionManager::suspendAllMediaBufferingForDocument(const Document& document)
490 {
491     forEachSession([&] (PlatformMediaSession& session, size_t) {
492         if (session.client().hostingDocument() == &document)
493             session.suspendBuffering();
494     });
495 }
496
497 void PlatformMediaSessionManager::resumeAllMediaBufferingForDocument(const Document& document)
498 {
499     forEachSession([&] (PlatformMediaSession& session, size_t) {
500         if (session.client().hostingDocument() == &document)
501             session.resumeBuffering();
502     });
503 }
504
505 void PlatformMediaSessionManager::forEachSession(const Function<void(PlatformMediaSession&, size_t)>& predicate) const
506 {
507     ++m_iteratingOverSessions;
508
509     for (size_t i = 0, size = m_sessions.size(); i < size; ++i) {
510         auto session = m_sessions[i];
511         if (!session)
512             continue;
513         predicate(*session, i);
514     }
515
516     --m_iteratingOverSessions;
517     if (!m_iteratingOverSessions)
518         m_sessions.removeAll(nullptr);
519 }
520
521 PlatformMediaSession* PlatformMediaSessionManager::findSession(const Function<bool(PlatformMediaSession&, size_t)>& predicate) const
522 {
523     ++m_iteratingOverSessions;
524
525     PlatformMediaSession* foundSession = nullptr;
526     for (size_t i = 0, size = m_sessions.size(); i < size; ++i) {
527         auto session = m_sessions[i];
528         if (!session)
529             continue;
530
531         if (!predicate(*session, i))
532             continue;
533
534         foundSession = session;
535         break;
536     }
537
538     --m_iteratingOverSessions;
539     if (!m_iteratingOverSessions)
540         m_sessions.removeAll(nullptr);
541
542     return foundSession;
543 }
544
545 static bool& deactivateAudioSession()
546 {
547     static bool deactivate;
548     return deactivate;
549 }
550
551 bool PlatformMediaSessionManager::shouldDeactivateAudioSession()
552 {
553     return deactivateAudioSession();
554 }
555
556 void PlatformMediaSessionManager::setShouldDeactivateAudioSession(bool deactivate)
557 {
558     deactivateAudioSession() = deactivate;
559 }
560
561 #else // ENABLE(VIDEO) || ENABLE(WEB_AUDIO)
562
563 void PlatformMediaSessionManager::updateNowPlayingInfoIfNecessary()
564 {
565
566 }
567
568 #endif // ENABLE(VIDEO) || ENABLE(WEB_AUDIO)
569
570 #if !RELEASE_LOG_DISABLED
571 WTFLogChannel& PlatformMediaSessionManager::logChannel() const
572 {
573     return LogMedia;
574 }
575 #endif
576
577 } // namespace WebCore