/
MediaSessionManagerCocoa.mm
452 lines (375 loc) · 17.6 KB
/
MediaSessionManagerCocoa.mm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
/*
* Copyright (C) 2013-2021 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#import "config.h"
#import "MediaSessionManagerCocoa.h"
#if USE(AUDIO_SESSION) && PLATFORM(COCOA)
#import "AudioSession.h"
#import "AudioUtilities.h"
#import "DeprecatedGlobalSettings.h"
#import "HTMLMediaElement.h"
#import "Logging.h"
#import "MediaPlayer.h"
#import "MediaStrategy.h"
#import "NowPlayingInfo.h"
#import "PlatformMediaSession.h"
#import "PlatformStrategies.h"
#import "SharedBuffer.h"
#import "VP9UtilitiesCocoa.h"
#import <wtf/BlockObjCExceptions.h>
#import <wtf/Function.h>
#import "MediaRemoteSoftLink.h"
static const size_t kLowPowerVideoBufferSize = 4096;
namespace WebCore {
#if PLATFORM(MAC)
std::unique_ptr<PlatformMediaSessionManager> PlatformMediaSessionManager::create()
{
return makeUnique<MediaSessionManagerCocoa>();
}
#endif // !PLATFORM(MAC)
MediaSessionManagerCocoa::MediaSessionManagerCocoa()
: m_nowPlayingManager(platformStrategies()->mediaStrategy().createNowPlayingManager())
, m_defaultBufferSize(AudioSession::sharedSession().preferredBufferSize())
{
ensureCodecsRegistered();
}
void MediaSessionManagerCocoa::ensureCodecsRegistered()
{
#if ENABLE(VP9)
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
if (shouldEnableVP9Decoder())
registerSupplementalVP9Decoder();
if (shouldEnableVP8Decoder())
registerWebKitVP8Decoder();
if (shouldEnableVP9SWDecoder())
registerWebKitVP9Decoder();
});
#endif
}
#if ENABLE(MEDIA_SOURCE) && HAVE(AVSAMPLEBUFFERVIDEOOUTPUT)
static bool s_mediaSourceInlinePaintingEnabled = false;
void MediaSessionManagerCocoa::setMediaSourceInlinePaintingEnabled(bool enabled)
{
s_mediaSourceInlinePaintingEnabled = enabled;
}
bool MediaSessionManagerCocoa::mediaSourceInlinePaintingEnabled()
{
return s_mediaSourceInlinePaintingEnabled;
}
#endif
void MediaSessionManagerCocoa::updateSessionState()
{
int videoCount = 0;
int videoAudioCount = 0;
int audioCount = 0;
int webAudioCount = 0;
int captureCount = countActiveAudioCaptureSources();
bool hasAudibleAudioOrVideoMediaType = false;
bool isPlayingAudio = false;
forEachSession([&] (auto& session) mutable {
auto type = session.mediaType();
switch (type) {
case PlatformMediaSession::MediaType::None:
break;
case PlatformMediaSession::MediaType::Video:
++videoCount;
break;
case PlatformMediaSession::MediaType::VideoAudio:
++videoAudioCount;
break;
case PlatformMediaSession::MediaType::Audio:
++audioCount;
break;
case PlatformMediaSession::MediaType::WebAudio:
if (session.canProduceAudio()) {
++webAudioCount;
isPlayingAudio |= session.isPlaying();
}
break;
}
if (!hasAudibleAudioOrVideoMediaType) {
bool isPotentiallyAudible = session.isPlayingToWirelessPlaybackTarget() || ((type == PlatformMediaSession::MediaType::VideoAudio || type == PlatformMediaSession::MediaType::Audio) && session.canProduceAudio() && session.hasPlayedSinceLastInterruption());
if (isPotentiallyAudible) {
hasAudibleAudioOrVideoMediaType = true;
isPlayingAudio |= session.isPlaying();
}
}
});
ALWAYS_LOG(LOGIDENTIFIER, "types: "
"AudioCapture(", captureCount, "), "
"Video(", videoCount, "), "
"Audio(", audioCount, "), "
"VideoAudio(", videoAudioCount, "), "
"WebAudio(", webAudioCount, ")");
size_t bufferSize = m_defaultBufferSize;
if (webAudioCount)
bufferSize = AudioUtilities::renderQuantumSize;
else if (captureCount) {
// In case of audio capture, we want to grab 20 ms chunks to limit the latency so that it is not noticeable by users
// while having a large enough buffer so that the audio rendering remains stable, hence a computation based on sample rate.
bufferSize = AudioSession::sharedSession().sampleRate() / 50;
} else if (m_supportedAudioHardwareBufferSizes && DeprecatedGlobalSettings::lowPowerVideoAudioBufferSizeEnabled())
bufferSize = m_supportedAudioHardwareBufferSizes.nearest(kLowPowerVideoBufferSize);
AudioSession::sharedSession().setPreferredBufferSize(bufferSize);
if (!DeprecatedGlobalSettings::shouldManageAudioSessionCategory())
return;
RouteSharingPolicy policy = RouteSharingPolicy::Default;
auto category = AudioSession::CategoryType::None;
if (captureCount || (isPlayingAudio && AudioSession::sharedSession().category() == AudioSession::CategoryType::PlayAndRecord))
category = AudioSession::CategoryType::PlayAndRecord;
else if (hasAudibleAudioOrVideoMediaType) {
category = AudioSession::CategoryType::MediaPlayback;
policy = RouteSharingPolicy::LongFormAudio;
} else if (webAudioCount)
category = AudioSession::CategoryType::AmbientSound;
ALWAYS_LOG(LOGIDENTIFIER, "setting category = ", category, ", policy = ", policy);
AudioSession::sharedSession().setCategory(category, policy);
}
void MediaSessionManagerCocoa::beginInterruption(PlatformMediaSession::InterruptionType type)
{
if (type == PlatformMediaSession::InterruptionType::SystemInterruption) {
forEachSession([] (auto& session) {
session.clearHasPlayedSinceLastInterruption();
});
}
PlatformMediaSessionManager::beginInterruption(type);
}
void MediaSessionManagerCocoa::prepareToSendUserMediaPermissionRequest()
{
providePresentingApplicationPIDIfNecessary();
}
void MediaSessionManagerCocoa::scheduleSessionStatusUpdate()
{
callOnMainThread([this] () mutable {
m_nowPlayingManager->setSupportsSeeking(computeSupportsSeeking());
updateNowPlayingInfo();
forEachSession([] (auto& session) {
session.updateMediaUsageIfChanged();
});
});
}
bool MediaSessionManagerCocoa::sessionWillBeginPlayback(PlatformMediaSession& session)
{
if (!PlatformMediaSessionManager::sessionWillBeginPlayback(session))
return false;
scheduleSessionStatusUpdate();
return true;
}
void MediaSessionManagerCocoa::sessionDidEndRemoteScrubbing(PlatformMediaSession&)
{
scheduleSessionStatusUpdate();
}
void MediaSessionManagerCocoa::addSession(PlatformMediaSession& session)
{
m_nowPlayingManager->addClient(*this);
if (!m_audioHardwareListener) {
m_audioHardwareListener = AudioHardwareListener::create(*this);
m_supportedAudioHardwareBufferSizes = m_audioHardwareListener->supportedBufferSizes();
}
PlatformMediaSessionManager::addSession(session);
}
void MediaSessionManagerCocoa::removeSession(PlatformMediaSession& session)
{
PlatformMediaSessionManager::removeSession(session);
if (hasNoSession()) {
m_nowPlayingManager->removeClient(*this);
m_audioHardwareListener = nullptr;
}
scheduleSessionStatusUpdate();
}
void MediaSessionManagerCocoa::setCurrentSession(PlatformMediaSession& session)
{
PlatformMediaSessionManager::setCurrentSession(session);
m_nowPlayingManager->updateSupportedCommands();
}
void MediaSessionManagerCocoa::sessionWillEndPlayback(PlatformMediaSession& session, DelayCallingUpdateNowPlaying delayCallingUpdateNowPlaying)
{
PlatformMediaSessionManager::sessionWillEndPlayback(session, delayCallingUpdateNowPlaying);
callOnMainThread([weakSession = makeWeakPtr(session)] {
if (weakSession)
weakSession->updateMediaUsageIfChanged();
});
if (delayCallingUpdateNowPlaying == DelayCallingUpdateNowPlaying::No)
updateNowPlayingInfo();
else {
callOnMainThread([this] {
updateNowPlayingInfo();
});
}
}
void MediaSessionManagerCocoa::clientCharacteristicsChanged(PlatformMediaSession& session)
{
ALWAYS_LOG(LOGIDENTIFIER, session.logIdentifier());
scheduleSessionStatusUpdate();
}
void MediaSessionManagerCocoa::sessionCanProduceAudioChanged()
{
ALWAYS_LOG(LOGIDENTIFIER);
PlatformMediaSessionManager::sessionCanProduceAudioChanged();
scheduleSessionStatusUpdate();
}
void MediaSessionManagerCocoa::addSupportedCommand(PlatformMediaSession::RemoteControlCommandType command)
{
m_nowPlayingManager->addSupportedCommand(command);
}
void MediaSessionManagerCocoa::removeSupportedCommand(PlatformMediaSession::RemoteControlCommandType command)
{
m_nowPlayingManager->removeSupportedCommand(command);
}
RemoteCommandListener::RemoteCommandsSet MediaSessionManagerCocoa::supportedCommands() const
{
return m_nowPlayingManager->supportedCommands();
}
void MediaSessionManagerCocoa::clearNowPlayingInfo()
{
if (!isMediaRemoteFrameworkAvailable())
return;
if (canLoad_MediaRemote_MRMediaRemoteSetNowPlayingVisibility())
MRMediaRemoteSetNowPlayingVisibility(MRMediaRemoteGetLocalOrigin(), MRNowPlayingClientVisibilityNeverVisible);
MRMediaRemoteSetCanBeNowPlayingApplication(false);
MRMediaRemoteSetNowPlayingInfo(nullptr);
MRMediaRemoteSetNowPlayingApplicationPlaybackStateForOrigin(MRMediaRemoteGetLocalOrigin(), kMRPlaybackStateStopped, dispatch_get_main_queue(), ^(MRMediaRemoteError error) {
#if LOG_DISABLED
UNUSED_PARAM(error);
#else
if (error)
WTFLogAlways("MRMediaRemoteSetNowPlayingApplicationPlaybackStateForOrigin(stopped) failed with error %d", error);
#endif
});
}
void MediaSessionManagerCocoa::setNowPlayingInfo(bool setAsNowPlayingApplication, const NowPlayingInfo& nowPlayingInfo)
{
if (!isMediaRemoteFrameworkAvailable())
return;
if (setAsNowPlayingApplication)
MRMediaRemoteSetCanBeNowPlayingApplication(true);
auto info = adoptCF(CFDictionaryCreateMutable(kCFAllocatorDefault, 4, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
CFDictionarySetValue(info.get(), kMRMediaRemoteNowPlayingInfoArtist, nowPlayingInfo.artist.createCFString().get());
CFDictionarySetValue(info.get(), kMRMediaRemoteNowPlayingInfoAlbum, nowPlayingInfo.album.createCFString().get());
CFDictionarySetValue(info.get(), kMRMediaRemoteNowPlayingInfoTitle, nowPlayingInfo.title.createCFString().get());
if (std::isfinite(nowPlayingInfo.duration) && nowPlayingInfo.duration != MediaPlayer::invalidTime()) {
auto cfDuration = adoptCF(CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &nowPlayingInfo.duration));
CFDictionarySetValue(info.get(), kMRMediaRemoteNowPlayingInfoDuration, cfDuration.get());
}
double rate = nowPlayingInfo.isPlaying ? 1 : 0;
auto cfRate = adoptCF(CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &rate));
CFDictionarySetValue(info.get(), kMRMediaRemoteNowPlayingInfoPlaybackRate, cfRate.get());
// FIXME: This is a workaround Control Center not updating the artwork when refreshed.
// We force the identifier to be reloaded to the new artwork if available.
auto lastUpdatedNowPlayingInfoUniqueIdentifier = nowPlayingInfo.artwork ? nowPlayingInfo.artwork->src.hash() : nowPlayingInfo.uniqueIdentifier.toUInt64();
auto cfIdentifier = adoptCF(CFNumberCreate(kCFAllocatorDefault, kCFNumberLongLongType, &lastUpdatedNowPlayingInfoUniqueIdentifier));
CFDictionarySetValue(info.get(), kMRMediaRemoteNowPlayingInfoUniqueIdentifier, cfIdentifier.get());
if (std::isfinite(nowPlayingInfo.currentTime) && nowPlayingInfo.currentTime != MediaPlayer::invalidTime() && nowPlayingInfo.supportsSeeking) {
auto cfCurrentTime = adoptCF(CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &nowPlayingInfo.currentTime));
CFDictionarySetValue(info.get(), kMRMediaRemoteNowPlayingInfoElapsedTime, cfCurrentTime.get());
}
if (nowPlayingInfo.artwork && nowPlayingInfo.artwork->imageData) {
auto nsArtwork = nowPlayingInfo.artwork->imageData->createNSData();
CFDictionarySetValue(info.get(), kMRMediaRemoteNowPlayingInfoArtworkData, nsArtwork.get());
CFDictionarySetValue(info.get(), kMRMediaRemoteNowPlayingInfoArtworkMIMEType, nowPlayingInfo.artwork->mimeType.createCFString().get());
CFDictionarySetValue(info.get(), kMRMediaRemoteNowPlayingInfoArtworkIdentifier, String::number(nowPlayingInfo.artwork->src.hash()).createCFString().get());
}
if (canLoad_MediaRemote_MRMediaRemoteSetParentApplication() && !nowPlayingInfo.sourceApplicationIdentifier.isEmpty())
MRMediaRemoteSetParentApplication(MRMediaRemoteGetLocalOrigin(), nowPlayingInfo.sourceApplicationIdentifier.createCFString().get());
MRPlaybackState playbackState = (nowPlayingInfo.isPlaying) ? kMRPlaybackStatePlaying : kMRPlaybackStatePaused;
MRMediaRemoteSetNowPlayingApplicationPlaybackStateForOrigin(MRMediaRemoteGetLocalOrigin(), playbackState, dispatch_get_main_queue(), ^(MRMediaRemoteError error) {
#if LOG_DISABLED
UNUSED_PARAM(error);
#else
if (error)
WTFLogAlways("MRMediaRemoteSetNowPlayingApplicationPlaybackStateForOrigin(playing) failed with error %d", error);
#endif
});
MRMediaRemoteSetNowPlayingInfoWithMergePolicy(info.get(), MRMediaRemoteMergePolicyReplace);
if (canLoad_MediaRemote_MRMediaRemoteSetNowPlayingVisibility()) {
MRNowPlayingClientVisibility visibility = nowPlayingInfo.allowsNowPlayingControlsVisibility ? MRNowPlayingClientVisibilityAlwaysVisible : MRNowPlayingClientVisibilityNeverVisible;
MRMediaRemoteSetNowPlayingVisibility(MRMediaRemoteGetLocalOrigin(), visibility);
}
}
PlatformMediaSession* MediaSessionManagerCocoa::nowPlayingEligibleSession()
{
// FIXME: Fix this layering violation.
if (auto element = HTMLMediaElement::bestMediaElementForRemoteControls(MediaElementSession::PlaybackControlsPurpose::NowPlaying))
return &element->mediaSession();
return nullptr;
}
void MediaSessionManagerCocoa::updateNowPlayingInfo()
{
if (!isMediaRemoteFrameworkAvailable())
return;
BEGIN_BLOCK_OBJC_EXCEPTIONS
std::optional<NowPlayingInfo> nowPlayingInfo;
if (auto* session = nowPlayingEligibleSession())
nowPlayingInfo = session->nowPlayingInfo();
if (!nowPlayingInfo) {
if (m_registeredAsNowPlayingApplication) {
ALWAYS_LOG(LOGIDENTIFIER, "clearing now playing info");
m_nowPlayingManager->clearNowPlayingInfo();
}
m_registeredAsNowPlayingApplication = false;
m_nowPlayingActive = false;
m_lastUpdatedNowPlayingTitle = emptyString();
m_lastUpdatedNowPlayingDuration = NAN;
m_lastUpdatedNowPlayingElapsedTime = NAN;
m_lastUpdatedNowPlayingInfoUniqueIdentifier = { };
return;
}
m_haveEverRegisteredAsNowPlayingApplication = true;
if (m_nowPlayingManager->setNowPlayingInfo(*nowPlayingInfo)) {
#ifdef LOG_DISABLED
String src = "src";
String title = "title";
#else
String src = nowPlayingInfo->artwork ? nowPlayingInfo->artwork->src : String();
String title = nowPlayingInfo->title;
#endif
ALWAYS_LOG(LOGIDENTIFIER, "title = \"", title, "\", isPlaying = ", nowPlayingInfo->isPlaying, ", duration = ", nowPlayingInfo->duration, ", now = ", nowPlayingInfo->currentTime, ", id = ", nowPlayingInfo->uniqueIdentifier.toUInt64(), ", registered = ", m_registeredAsNowPlayingApplication, ", src = \"", src, "\"");
}
if (!m_registeredAsNowPlayingApplication) {
m_registeredAsNowPlayingApplication = true;
providePresentingApplicationPIDIfNecessary();
}
if (!nowPlayingInfo->title.isEmpty())
m_lastUpdatedNowPlayingTitle = nowPlayingInfo->title;
double duration = nowPlayingInfo->duration;
if (std::isfinite(duration) && duration != MediaPlayer::invalidTime())
m_lastUpdatedNowPlayingDuration = duration;
m_lastUpdatedNowPlayingInfoUniqueIdentifier = nowPlayingInfo->uniqueIdentifier;
double currentTime = nowPlayingInfo->currentTime;
if (std::isfinite(currentTime) && currentTime != MediaPlayer::invalidTime() && nowPlayingInfo->supportsSeeking)
m_lastUpdatedNowPlayingElapsedTime = currentTime;
m_nowPlayingActive = nowPlayingInfo->allowsNowPlayingControlsVisibility;
END_BLOCK_OBJC_EXCEPTIONS
}
void MediaSessionManagerCocoa::audioOutputDeviceChanged()
{
ASSERT(m_audioHardwareListener);
m_supportedAudioHardwareBufferSizes = m_audioHardwareListener->supportedBufferSizes();
m_defaultBufferSize = AudioSession::sharedSession().preferredBufferSize();
AudioSession::sharedSession().audioOutputDeviceChanged();
updateSessionState();
}
} // namespace WebCore
#endif // USE(AUDIO_SESSION) && PLATFORM(COCOA)