71140ba2eab3f79fe4a3566eefab35a4fa7561b8
[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     ALWAYS_LOG(LOGIDENTIFIER, session.logIdentifier());
208     
209     setCurrentSession(session);
210
211     PlatformMediaSession::MediaType sessionType = session.mediaType();
212     SessionRestrictions restrictions = m_restrictions[sessionType];
213     if (session.state() == PlatformMediaSession::Interrupted && restrictions & InterruptedPlaybackNotPermitted)
214         return false;
215
216 #if USE(AUDIO_SESSION)
217     if (activeAudioSessionRequired() && !AudioSession::sharedSession().tryToSetActive(true))
218         return false;
219
220     m_becameActive = true;
221 #endif
222
223     if (m_interrupted)
224         endInterruption(PlatformMediaSession::NoFlags);
225
226     forEachSession([&] (PlatformMediaSession& oneSession, size_t) {
227         if (&oneSession == &session)
228             return;
229         if (oneSession.mediaType() == sessionType
230             && restrictions & ConcurrentPlaybackNotPermitted
231             && oneSession.state() == PlatformMediaSession::Playing)
232             oneSession.pauseSession();
233     });
234
235     return true;
236 }
237     
238 void PlatformMediaSessionManager::sessionWillEndPlayback(PlatformMediaSession& session)
239 {
240     ALWAYS_LOG(LOGIDENTIFIER, session.logIdentifier());
241     
242     if (m_sessions.size() < 2)
243         return;
244     
245     size_t pausingSessionIndex = notFound;
246     size_t lastPlayingSessionIndex = notFound;
247     anyOfSessions([&] (PlatformMediaSession& oneSession, size_t i) {
248         if (&oneSession == &session) {
249             pausingSessionIndex = i;
250             return false;
251         }
252         if (oneSession.state() == PlatformMediaSession::Playing) {
253             lastPlayingSessionIndex = i;
254             return false;
255         }
256         return oneSession.state() != PlatformMediaSession::Playing;
257     });
258     if (lastPlayingSessionIndex == notFound || pausingSessionIndex == notFound)
259         return;
260     
261     if (pausingSessionIndex > lastPlayingSessionIndex)
262         return;
263     
264     m_sessions.remove(pausingSessionIndex);
265     m_sessions.insert(lastPlayingSessionIndex, &session);
266     
267     ALWAYS_LOG(LOGIDENTIFIER, "session moved from index ", pausingSessionIndex, " to ", lastPlayingSessionIndex);
268 }
269
270 void PlatformMediaSessionManager::sessionStateChanged(PlatformMediaSession&)
271 {
272     updateSessionState();
273 }
274
275 void PlatformMediaSessionManager::setCurrentSession(PlatformMediaSession& session)
276 {
277     ALWAYS_LOG(LOGIDENTIFIER, session.logIdentifier());
278     
279     if (m_sessions.size() < 2)
280         return;
281     
282     size_t index = m_sessions.find(&session);
283     ASSERT(index != notFound);
284     if (!index || index == notFound)
285         return;
286
287     m_sessions.remove(index);
288     m_sessions.insert(0, &session);
289     if (m_remoteCommandListener)
290         m_remoteCommandListener->updateSupportedCommands();
291     
292     ALWAYS_LOG(LOGIDENTIFIER, "session moved from index ", index, " to 0");
293 }
294     
295 PlatformMediaSession* PlatformMediaSessionManager::currentSession() const
296 {
297     if (!m_sessions.size())
298         return nullptr;
299
300     return m_sessions[0];
301 }
302
303 Vector<PlatformMediaSession*> PlatformMediaSessionManager::currentSessionsMatching(const WTF::Function<bool(const PlatformMediaSession&)>& filter)
304 {
305     Vector<PlatformMediaSession*> matchingSessions;
306     forEachSession([&] (PlatformMediaSession& session, size_t) {
307         if (filter(session))
308             matchingSessions.append(&session);
309     });
310     return matchingSessions;
311 }
312
313 void PlatformMediaSessionManager::applicationWillBecomeInactive() const
314 {
315     ALWAYS_LOG(LOGIDENTIFIER);
316
317     forEachSession([&] (PlatformMediaSession& session, size_t) {
318         if (m_restrictions[session.mediaType()] & InactiveProcessPlaybackRestricted)
319             session.beginInterruption(PlatformMediaSession::ProcessInactive);
320     });
321 }
322
323 void PlatformMediaSessionManager::applicationDidBecomeActive() const
324 {
325     ALWAYS_LOG(LOGIDENTIFIER);
326
327     forEachSession([&] (PlatformMediaSession& session, size_t) {
328         if (m_restrictions[session.mediaType()] & InactiveProcessPlaybackRestricted)
329             session.endInterruption(PlatformMediaSession::MayResumePlaying);
330     });
331 }
332
333 void PlatformMediaSessionManager::applicationDidEnterBackground(bool suspendedUnderLock) const
334 {
335     ALWAYS_LOG(LOGIDENTIFIER, "suspendedUnderLock: ", suspendedUnderLock);
336
337     if (m_isApplicationInBackground)
338         return;
339
340     m_isApplicationInBackground = true;
341
342     forEachSession([&] (PlatformMediaSession& session, size_t) {
343         if (suspendedUnderLock && m_restrictions[session.mediaType()] & SuspendedUnderLockPlaybackRestricted)
344             session.beginInterruption(PlatformMediaSession::SuspendedUnderLock);
345         else if (m_restrictions[session.mediaType()] & BackgroundProcessPlaybackRestricted)
346             session.beginInterruption(PlatformMediaSession::EnteringBackground);
347     });
348 }
349
350 void PlatformMediaSessionManager::applicationWillEnterForeground(bool suspendedUnderLock) const
351 {
352     ALWAYS_LOG(LOGIDENTIFIER, "suspendedUnderLock: ", suspendedUnderLock);
353
354     if (!m_isApplicationInBackground)
355         return;
356
357     m_isApplicationInBackground = false;
358
359     forEachSession([&] (PlatformMediaSession& session, size_t) {
360         if ((suspendedUnderLock && m_restrictions[session.mediaType()] & SuspendedUnderLockPlaybackRestricted) || m_restrictions[session.mediaType()] & BackgroundProcessPlaybackRestricted)
361             session.endInterruption(PlatformMediaSession::MayResumePlaying);
362     });
363 }
364
365 void PlatformMediaSessionManager::sessionIsPlayingToWirelessPlaybackTargetChanged(PlatformMediaSession& session)
366 {
367     if (!m_isApplicationInBackground || !(m_restrictions[session.mediaType()] & BackgroundProcessPlaybackRestricted))
368         return;
369
370     if (session.state() != PlatformMediaSession::Interrupted)
371         session.beginInterruption(PlatformMediaSession::EnteringBackground);
372 }
373
374 void PlatformMediaSessionManager::sessionCanProduceAudioChanged(PlatformMediaSession&)
375 {
376     updateSessionState();
377 }
378
379 void PlatformMediaSessionManager::didReceiveRemoteControlCommand(PlatformMediaSession::RemoteControlCommandType command, const PlatformMediaSession::RemoteCommandArgument* argument)
380 {
381     PlatformMediaSession* activeSession = currentSession();
382     if (!activeSession || !activeSession->canReceiveRemoteControlCommands())
383         return;
384     activeSession->didReceiveRemoteControlCommand(command, argument);
385 }
386
387 bool PlatformMediaSessionManager::supportsSeeking() const
388 {
389     PlatformMediaSession* activeSession = currentSession();
390     if (!activeSession)
391         return false;
392     return activeSession->supportsSeeking();
393 }
394
395 void PlatformMediaSessionManager::systemWillSleep()
396 {
397     if (m_interrupted)
398         return;
399
400     forEachSession([] (PlatformMediaSession& session, size_t) {
401         session.beginInterruption(PlatformMediaSession::SystemSleep);
402     });
403 }
404
405 void PlatformMediaSessionManager::systemDidWake()
406 {
407     if (m_interrupted)
408         return;
409
410     forEachSession([] (PlatformMediaSession& session, size_t) {
411         session.endInterruption(PlatformMediaSession::MayResumePlaying);
412     });
413 }
414
415 void PlatformMediaSessionManager::audioOutputDeviceChanged()
416 {
417     updateSessionState();
418 }
419
420 void PlatformMediaSessionManager::stopAllMediaPlaybackForDocument(const Document* document)
421 {
422     forEachSession([document] (PlatformMediaSession& session, size_t) {
423         if (session.client().hostingDocument() == document)
424             session.pauseSession();
425     });
426 }
427
428 void PlatformMediaSessionManager::stopAllMediaPlaybackForProcess()
429 {
430     forEachSession([] (PlatformMediaSession& session, size_t) {
431         session.stopSession();
432     });
433 }
434
435 void PlatformMediaSessionManager::suspendAllMediaPlaybackForDocument(const Document& document)
436 {
437     forEachSession([&] (PlatformMediaSession& session, size_t) {
438         if (session.client().hostingDocument() == &document)
439             session.beginInterruption(PlatformMediaSession::PlaybackSuspended);
440     });
441 }
442
443 void PlatformMediaSessionManager::resumeAllMediaPlaybackForDocument(const Document& document)
444 {
445     forEachSession([&] (PlatformMediaSession& session, size_t) {
446         if (session.client().hostingDocument() == &document)
447             session.endInterruption(PlatformMediaSession::MayResumePlaying);
448     });
449 }
450
451 void PlatformMediaSessionManager::suspendAllMediaBufferingForDocument(const Document& document)
452 {
453     forEachSession([&] (PlatformMediaSession& session, size_t) {
454         if (session.client().hostingDocument() == &document)
455             session.suspendBuffering();
456     });
457 }
458
459 void PlatformMediaSessionManager::resumeAllMediaBufferingForDocument(const Document& document)
460 {
461     forEachSession([&] (PlatformMediaSession& session, size_t) {
462         if (session.client().hostingDocument() == &document)
463             session.resumeBuffering();
464     });
465 }
466
467 void PlatformMediaSessionManager::forEachSession(const Function<void(PlatformMediaSession&, size_t)>& predicate) const
468 {
469     ++m_iteratingOverSessions;
470
471     for (size_t i = 0, size = m_sessions.size(); i < size; ++i) {
472         auto session = m_sessions[i];
473         if (!session)
474             continue;
475         predicate(*session, i);
476     }
477
478     --m_iteratingOverSessions;
479     if (!m_iteratingOverSessions)
480         m_sessions.removeAll(nullptr);
481 }
482
483 PlatformMediaSession* PlatformMediaSessionManager::findSession(const Function<bool(PlatformMediaSession&, size_t)>& predicate) const
484 {
485     ++m_iteratingOverSessions;
486
487     PlatformMediaSession* foundSession = nullptr;
488     for (size_t i = 0, size = m_sessions.size(); i < size; ++i) {
489         auto session = m_sessions[i];
490         if (!session)
491             continue;
492
493         if (!predicate(*session, i))
494             continue;
495
496         foundSession = session;
497         break;
498     }
499
500     --m_iteratingOverSessions;
501     if (!m_iteratingOverSessions)
502         m_sessions.removeAll(nullptr);
503
504     return foundSession;
505 }
506
507 static bool& deactivateAudioSession()
508 {
509     static bool deactivate;
510     return deactivate;
511 }
512
513 bool PlatformMediaSessionManager::shouldDeactivateAudioSession()
514 {
515     return deactivateAudioSession();
516 }
517
518 void PlatformMediaSessionManager::setShouldDeactivateAudioSession(bool deactivate)
519 {
520     deactivateAudioSession() = deactivate;
521 }
522
523 #else // ENABLE(VIDEO) || ENABLE(WEB_AUDIO)
524
525 void PlatformMediaSessionManager::updateNowPlayingInfoIfNecessary()
526 {
527
528 }
529
530 #endif // ENABLE(VIDEO) || ENABLE(WEB_AUDIO)
531
532 #if !RELEASE_LOG_DISABLED
533 WTFLogChannel& PlatformMediaSessionManager::logChannel() const
534 {
535     return LogMedia;
536 }
537 #endif
538
539 } // namespace WebCore