Video sometimes flickers when playing to AppleTV
[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     scheduleUpdateSessionState();
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     scheduleUpdateSessionState();
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 #if USE(AUDIO_SESSION)
166         AudioSession::sharedSession().tryToSetActive(false);
167 #endif
168     }
169
170     scheduleUpdateSessionState();
171 }
172
173 void PlatformMediaSessionManager::addRestriction(PlatformMediaSession::MediaType type, SessionRestrictions restriction)
174 {
175     ASSERT(type > PlatformMediaSession::None && type <= PlatformMediaSession::MediaStreamCapturingAudio);
176     m_restrictions[type] |= restriction;
177 }
178
179 void PlatformMediaSessionManager::removeRestriction(PlatformMediaSession::MediaType type, SessionRestrictions restriction)
180 {
181     ASSERT(type > PlatformMediaSession::None && type <= PlatformMediaSession::MediaStreamCapturingAudio);
182     m_restrictions[type] &= ~restriction;
183 }
184
185 PlatformMediaSessionManager::SessionRestrictions PlatformMediaSessionManager::restrictions(PlatformMediaSession::MediaType type)
186 {
187     ASSERT(type > PlatformMediaSession::None && type <= PlatformMediaSession::MediaStreamCapturingAudio);
188     return m_restrictions[type];
189 }
190
191 bool PlatformMediaSessionManager::sessionWillBeginPlayback(PlatformMediaSession& session)
192 {
193     LOG(Media, "PlatformMediaSessionManager::sessionWillBeginPlayback - %p", &session);
194     
195     setCurrentSession(session);
196
197     PlatformMediaSession::MediaType sessionType = session.mediaType();
198     SessionRestrictions restrictions = m_restrictions[sessionType];
199     if (session.state() == PlatformMediaSession::Interrupted && restrictions & InterruptedPlaybackNotPermitted)
200         return false;
201
202 #if USE(AUDIO_SESSION)
203     if (activeAudioSessionRequired() && !AudioSession::sharedSession().tryToSetActive(true))
204         return false;
205 #endif
206
207     if (m_interrupted)
208         endInterruption(PlatformMediaSession::NoFlags);
209
210     forEachSession([&] (PlatformMediaSession& oneSession, size_t) {
211         if (&oneSession == &session)
212             return;
213         if (oneSession.mediaType() == sessionType
214             && restrictions & ConcurrentPlaybackNotPermitted
215             && oneSession.state() == PlatformMediaSession::Playing)
216             oneSession.pauseSession();
217     });
218
219     return true;
220 }
221     
222 void PlatformMediaSessionManager::sessionWillEndPlayback(PlatformMediaSession& session)
223 {
224     LOG(Media, "PlatformMediaSessionManager::sessionWillEndPlayback - %p", &session);
225     
226     if (m_sessions.size() < 2)
227         return;
228     
229     size_t pausingSessionIndex = notFound;
230     size_t lastPlayingSessionIndex = notFound;
231     anyOfSessions([&] (PlatformMediaSession& oneSession, size_t i) {
232         if (&oneSession == &session) {
233             pausingSessionIndex = i;
234             return false;
235         }
236         if (oneSession.state() == PlatformMediaSession::Playing) {
237             lastPlayingSessionIndex = i;
238             return false;
239         }
240         return oneSession.state() != PlatformMediaSession::Playing;
241     });
242     if (lastPlayingSessionIndex == notFound || pausingSessionIndex == notFound)
243         return;
244     
245     if (pausingSessionIndex > lastPlayingSessionIndex)
246         return;
247     
248     m_sessions.remove(pausingSessionIndex);
249     m_sessions.insert(lastPlayingSessionIndex, &session);
250     
251     LOG(Media, "PlatformMediaSessionManager::sessionWillEndPlayback - session moved from index %zu to %zu", pausingSessionIndex, lastPlayingSessionIndex);
252 }
253
254 void PlatformMediaSessionManager::sessionStateChanged(PlatformMediaSession&)
255 {
256     scheduleUpdateSessionState();
257 }
258
259 void PlatformMediaSessionManager::setCurrentSession(PlatformMediaSession& session)
260 {
261     LOG(Media, "PlatformMediaSessionManager::setCurrentSession - %p", &session);
262     
263     if (m_sessions.size() < 2)
264         return;
265     
266     size_t index = m_sessions.find(&session);
267     ASSERT(index != notFound);
268     if (!index || index == notFound)
269         return;
270
271     m_sessions.remove(index);
272     m_sessions.insert(0, &session);
273     if (m_remoteCommandListener)
274         m_remoteCommandListener->updateSupportedCommands();
275     
276     LOG(Media, "PlatformMediaSessionManager::setCurrentSession - session moved from index %zu to 0", index);
277 }
278     
279 PlatformMediaSession* PlatformMediaSessionManager::currentSession() const
280 {
281     if (!m_sessions.size())
282         return nullptr;
283
284     return m_sessions[0];
285 }
286
287 Vector<PlatformMediaSession*> PlatformMediaSessionManager::currentSessionsMatching(const WTF::Function<bool(const PlatformMediaSession&)>& filter)
288 {
289     Vector<PlatformMediaSession*> matchingSessions;
290     forEachSession([&] (PlatformMediaSession& session, size_t) {
291         if (filter(session))
292             matchingSessions.append(&session);
293     });
294     return matchingSessions;
295 }
296
297 void PlatformMediaSessionManager::applicationWillBecomeInactive() const
298 {
299     LOG(Media, "PlatformMediaSessionManager::applicationWillBecomeInactive");
300
301     forEachSession([&] (PlatformMediaSession& session, size_t) {
302         if (m_restrictions[session.mediaType()] & InactiveProcessPlaybackRestricted)
303             session.beginInterruption(PlatformMediaSession::ProcessInactive);
304     });
305 }
306
307 void PlatformMediaSessionManager::applicationDidBecomeActive() const
308 {
309     LOG(Media, "PlatformMediaSessionManager::applicationDidBecomeActive");
310
311     forEachSession([&] (PlatformMediaSession& session, size_t) {
312         if (m_restrictions[session.mediaType()] & InactiveProcessPlaybackRestricted)
313             session.endInterruption(PlatformMediaSession::MayResumePlaying);
314     });
315 }
316
317 void PlatformMediaSessionManager::applicationDidEnterBackground(bool suspendedUnderLock) const
318 {
319     LOG(Media, "PlatformMediaSessionManager::applicationDidEnterBackground - suspendedUnderLock(%d)", suspendedUnderLock);
320
321     if (m_isApplicationInBackground)
322         return;
323
324     m_isApplicationInBackground = true;
325
326     forEachSession([&] (PlatformMediaSession& session, size_t) {
327         if (suspendedUnderLock && m_restrictions[session.mediaType()] & SuspendedUnderLockPlaybackRestricted)
328             session.beginInterruption(PlatformMediaSession::SuspendedUnderLock);
329         else if (m_restrictions[session.mediaType()] & BackgroundProcessPlaybackRestricted)
330             session.beginInterruption(PlatformMediaSession::EnteringBackground);
331     });
332 }
333
334 void PlatformMediaSessionManager::applicationWillEnterForeground(bool suspendedUnderLock) const
335 {
336     LOG(Media, "PlatformMediaSessionManager::applicationWillEnterForeground - suspendedUnderLock(%d)", suspendedUnderLock);
337
338     if (!m_isApplicationInBackground)
339         return;
340
341     m_isApplicationInBackground = false;
342
343     forEachSession([&] (PlatformMediaSession& session, size_t) {
344         if ((suspendedUnderLock && m_restrictions[session.mediaType()] & SuspendedUnderLockPlaybackRestricted) || m_restrictions[session.mediaType()] & BackgroundProcessPlaybackRestricted)
345             session.endInterruption(PlatformMediaSession::MayResumePlaying);
346     });
347 }
348
349 void PlatformMediaSessionManager::sessionIsPlayingToWirelessPlaybackTargetChanged(PlatformMediaSession& session)
350 {
351     if (!m_isApplicationInBackground || !(m_restrictions[session.mediaType()] & BackgroundProcessPlaybackRestricted))
352         return;
353
354     if (session.state() != PlatformMediaSession::Interrupted)
355         session.beginInterruption(PlatformMediaSession::EnteringBackground);
356 }
357
358 void PlatformMediaSessionManager::sessionCanProduceAudioChanged(PlatformMediaSession&)
359 {
360     scheduleUpdateSessionState();
361 }
362
363 #if !PLATFORM(COCOA)
364 void PlatformMediaSessionManager::scheduleUpdateSessionState()
365 {
366 }
367 #endif
368
369 void PlatformMediaSessionManager::didReceiveRemoteControlCommand(PlatformMediaSession::RemoteControlCommandType command, const PlatformMediaSession::RemoteCommandArgument* argument)
370 {
371     PlatformMediaSession* activeSession = currentSession();
372     if (!activeSession || !activeSession->canReceiveRemoteControlCommands())
373         return;
374     activeSession->didReceiveRemoteControlCommand(command, argument);
375 }
376
377 bool PlatformMediaSessionManager::supportsSeeking() const
378 {
379     PlatformMediaSession* activeSession = currentSession();
380     if (!activeSession)
381         return false;
382     return activeSession->supportsSeeking();
383 }
384
385 void PlatformMediaSessionManager::systemWillSleep()
386 {
387     if (m_interrupted)
388         return;
389
390     forEachSession([] (PlatformMediaSession& session, size_t) {
391         session.beginInterruption(PlatformMediaSession::SystemSleep);
392     });
393 }
394
395 void PlatformMediaSessionManager::systemDidWake()
396 {
397     if (m_interrupted)
398         return;
399
400     forEachSession([] (PlatformMediaSession& session, size_t) {
401         session.endInterruption(PlatformMediaSession::MayResumePlaying);
402     });
403 }
404
405 void PlatformMediaSessionManager::audioOutputDeviceChanged()
406 {
407     scheduleUpdateSessionState();
408 }
409
410 void PlatformMediaSessionManager::stopAllMediaPlaybackForDocument(const Document* document)
411 {
412     forEachSession([document] (PlatformMediaSession& session, size_t) {
413         if (session.client().hostingDocument() == document)
414             session.pauseSession();
415     });
416 }
417
418 void PlatformMediaSessionManager::stopAllMediaPlaybackForProcess()
419 {
420     forEachSession([] (PlatformMediaSession& session, size_t) {
421         session.stopSession();
422     });
423 }
424
425 void PlatformMediaSessionManager::forEachSession(const Function<void(PlatformMediaSession&, size_t)>& predicate) const
426 {
427     ++m_iteratingOverSessions;
428
429     for (size_t i = 0, size = m_sessions.size(); i < size; ++i) {
430         auto session = m_sessions[i];
431         if (!session)
432             continue;
433         predicate(*session, i);
434     }
435
436     --m_iteratingOverSessions;
437     if (!m_iteratingOverSessions)
438         m_sessions.removeAll(nullptr);
439 }
440
441 PlatformMediaSession* PlatformMediaSessionManager::findSession(const Function<bool(PlatformMediaSession&, size_t)>& predicate) const
442 {
443     ++m_iteratingOverSessions;
444
445     PlatformMediaSession* foundSession = nullptr;
446     for (size_t i = 0, size = m_sessions.size(); i < size; ++i) {
447         auto session = m_sessions[i];
448         if (!session)
449             continue;
450
451         if (!predicate(*session, i))
452             continue;
453
454         foundSession = session;
455         break;
456     }
457
458     --m_iteratingOverSessions;
459     if (!m_iteratingOverSessions)
460         m_sessions.removeAll(nullptr);
461
462     return foundSession;
463 }
464
465 #else // ENABLE(VIDEO) || ENABLE(WEB_AUDIO)
466
467 void PlatformMediaSessionManager::updateNowPlayingInfoIfNecessary()
468 {
469
470 }
471
472 #endif // ENABLE(VIDEO) || ENABLE(WEB_AUDIO)
473
474 } // namespace WebCore