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
|
/*
* Copyright (C) 2021 Igalia S.L
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "config.h"
#include "MediaSessionGLib.h"
#if USE(GLIB) && ENABLE(MEDIA_SESSION)
#include "ApplicationGLib.h"
#include "MediaSessionManagerGLib.h"
#include <gio/gio.h>
#include <wtf/SortedArrayMap.h>
#include <wtf/TZoneMallocInlines.h>
#include <wtf/glib/GUniquePtr.h>
#include <wtf/text/MakeString.h>
namespace WebCore {
WTF_MAKE_TZONE_ALLOCATED_IMPL(MediaSessionGLib);
#define DBUS_MPRIS_OBJECT_PATH "/org/mpris/MediaPlayer2"
#define DBUS_MPRIS_PLAYER_INTERFACE "org.mpris.MediaPlayer2.Player"
#define DBUS_MPRIS_TRACK_PATH "/org/mpris/MediaPlayer2/webkit"
static std::optional<PlatformMediaSession::RemoteControlCommandType> getCommand(const char* name)
{
static const std::pair<ComparableASCIILiteral, PlatformMediaSession::RemoteControlCommandType> commandList[] = {
{ "Next"_s, PlatformMediaSession::RemoteControlCommandType::NextTrackCommand },
{ "Pause"_s, PlatformMediaSession::RemoteControlCommandType::PauseCommand },
{ "Play"_s, PlatformMediaSession::RemoteControlCommandType::PlayCommand },
{ "PlayPause"_s, PlatformMediaSession::RemoteControlCommandType::TogglePlayPauseCommand },
{ "Previous"_s, PlatformMediaSession::RemoteControlCommandType::PreviousTrackCommand },
{ "Seek"_s, PlatformMediaSession::RemoteControlCommandType::SeekToPlaybackPositionCommand },
{ "Stop"_s, PlatformMediaSession::RemoteControlCommandType::StopCommand }
};
static const SortedArrayMap map { commandList };
auto value = map.get(StringView::fromLatin1(name), PlatformMediaSession::RemoteControlCommandType::NoCommand);
if (value == PlatformMediaSession::RemoteControlCommandType::NoCommand)
return { };
return value;
}
static void handleMethodCall(GDBusConnection* /* connection */, const char* /* sender */, const char* objectPath, const char* interfaceName, const char* methodName, GVariant* parameters, GDBusMethodInvocation* invocation, gpointer userData)
{
ASSERT(isMainThread());
auto command = getCommand(methodName);
if (!command) {
g_dbus_method_invocation_return_error(invocation, G_DBUS_ERROR, G_DBUS_ERROR_FAILED, "%s.%s.%s is not available now", objectPath, interfaceName, methodName);
return;
}
auto& session = *reinterpret_cast<MediaSessionGLib*>(userData);
auto& manager = session.manager();
PlatformMediaSession::RemoteCommandArgument argument;
if (*command == PlatformMediaSession::RemoteControlCommandType::SeekToPlaybackPositionCommand) {
int64_t offset;
g_variant_get(parameters, "(x)", &offset);
argument.time = offset / 1000000;
}
manager.dispatch(*command, argument);
g_dbus_method_invocation_return_value(invocation, nullptr);
}
enum class MprisProperty : uint8_t {
NoProperty,
CanControl,
CanGoNext,
CanGoPrevious,
CanPause,
CanPlay,
CanQuit,
CanRaise,
CanSeek,
DesktopEntry,
GetMetadata,
GetPlaybackStatus,
GetPosition,
HasTrackList,
Identity,
SupportedMimeTypes,
SupportedUriSchemes,
};
static std::optional<MprisProperty> getMprisProperty(const char* propertyName)
{
static constexpr std::pair<ComparableASCIILiteral, MprisProperty> propertiesList[] {
{ "CanControl"_s, MprisProperty::CanControl },
{ "CanGoNext"_s, MprisProperty::CanGoNext },
{ "CanGoPrevious"_s, MprisProperty::CanGoPrevious },
{ "CanPause"_s, MprisProperty::CanPause },
{ "CanPlay"_s, MprisProperty::CanPlay },
{ "CanQuit"_s, MprisProperty::CanQuit },
{ "CanRaise"_s, MprisProperty::CanRaise },
{ "CanSeek"_s, MprisProperty::CanSeek },
{ "DesktopEntry"_s, MprisProperty::DesktopEntry },
{ "HasTrackList"_s, MprisProperty::HasTrackList },
{ "Identity"_s, MprisProperty::Identity },
{ "Metadata"_s, MprisProperty::GetMetadata },
{ "PlaybackStatus"_s, MprisProperty::GetPlaybackStatus },
{ "Position"_s, MprisProperty::GetPosition },
{ "SupportedMimeTypes"_s, MprisProperty::SupportedMimeTypes },
{ "SupportedUriSchemes"_s, MprisProperty::SupportedUriSchemes }
};
static constexpr SortedArrayMap map { propertiesList };
auto value = map.get(StringView::fromLatin1(propertyName), MprisProperty::NoProperty);
if (value == MprisProperty::NoProperty)
return { };
return value;
}
static GVariant* handleGetProperty(GDBusConnection*, const char* /* sender */, const char* objectPath, const char* interfaceName, const char* propertyName, GError** error, gpointer userData)
{
ASSERT(isMainThread());
auto property = getMprisProperty(propertyName);
if (!property) {
g_set_error(error, G_DBUS_ERROR, G_DBUS_ERROR_NOT_SUPPORTED, "%s.%s %s is not supported", objectPath, interfaceName, propertyName);
return nullptr;
}
auto& session = *reinterpret_cast<MediaSessionGLib*>(userData);
switch (property.value()) {
case MprisProperty::NoProperty:
break;
case MprisProperty::SupportedUriSchemes:
case MprisProperty::SupportedMimeTypes:
return g_variant_new_strv(nullptr, 0);
case MprisProperty::GetPlaybackStatus:
return session.getPlaybackStatusAsGVariant({ });
case MprisProperty::GetMetadata:
return session.getMetadataAsGVariant({ });
case MprisProperty::GetPosition:
return session.getPositionAsGVariant();
case MprisProperty::Identity:
return g_variant_new_string(getApplicationName().ascii().data());
case MprisProperty::DesktopEntry:
return g_variant_new_string("");
case MprisProperty::CanSeek:
return session.canSeekAsGVariant();
case MprisProperty::HasTrackList:
case MprisProperty::CanQuit:
case MprisProperty::CanRaise:
return g_variant_new_boolean(false);
case MprisProperty::CanControl:
case MprisProperty::CanGoNext:
case MprisProperty::CanGoPrevious:
case MprisProperty::CanPlay:
case MprisProperty::CanPause:
return g_variant_new_boolean(true);
}
return nullptr;
}
static gboolean handleSetProperty(GDBusConnection*, const char* /* sender */, const char* /* objectPath */, const char* interfaceName, const char* propertyName, GVariant*, GError** error, gpointer)
{
ASSERT(isMainThread());
g_set_error(error, G_IO_ERROR, G_IO_ERROR_FAILED, "%s:%s setting is not supported", interfaceName, propertyName);
return FALSE;
}
static const GDBusInterfaceVTable gInterfaceVTable = {
handleMethodCall, handleGetProperty, handleSetProperty, { nullptr }
};
std::unique_ptr<MediaSessionGLib> MediaSessionGLib::create(MediaSessionManagerGLib& manager, MediaSessionIdentifier identifier)
{
if (!manager.areDBusNotificationsEnabled())
return makeUnique<MediaSessionGLib>(manager, nullptr, identifier);
GUniqueOutPtr<GError> error;
GUniquePtr<char> address(g_dbus_address_get_for_bus_sync(G_BUS_TYPE_SESSION, nullptr, &error.outPtr()));
if (error) {
g_warning("Unable to get session D-Bus address: %s", error->message);
return nullptr;
}
auto connection = adoptGRef(reinterpret_cast<GDBusConnection*>(g_object_new(G_TYPE_DBUS_CONNECTION,
"address", address.get(),
"flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT | G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
"exit-on-close", TRUE, nullptr)));
g_initable_init(G_INITABLE(connection.get()), nullptr, &error.outPtr());
if (error) {
g_warning("Unable to connect to D-Bus session bus: %s", error->message);
return nullptr;
}
return makeUnique<MediaSessionGLib>(manager, WTFMove(connection), identifier);
}
MediaSessionGLib::MediaSessionGLib(MediaSessionManagerGLib& manager, GRefPtr<GDBusConnection>&& connection, MediaSessionIdentifier identifier)
: m_identifier(identifier)
, m_manager(manager)
, m_connection(WTFMove(connection))
{
}
MediaSessionGLib::~MediaSessionGLib()
{
unregisterMprisSession();
}
bool MediaSessionGLib::ensureMprisSessionRegistered()
{
if (!m_connection || mprisRegistrationEligibility() == MediaSessionGLibMprisRegistrationEligiblilty::NotEligible)
return false;
if (m_ownerId)
return true;
const auto& mprisInterface = m_manager.mprisInterface();
GUniqueOutPtr<GError> error;
m_rootRegistrationId = g_dbus_connection_register_object(m_connection.get(), DBUS_MPRIS_OBJECT_PATH, mprisInterface->interfaces[0],
&gInterfaceVTable, this, nullptr, &error.outPtr());
if (!m_rootRegistrationId) {
g_warning("Failed to register MPRIS D-Bus object: %s", error->message);
return false;
}
WTF_ALLOW_UNSAFE_BUFFER_USAGE_BEGIN // GLib port
m_playerRegistrationId = g_dbus_connection_register_object(m_connection.get(), DBUS_MPRIS_OBJECT_PATH, mprisInterface->interfaces[1],
&gInterfaceVTable, this, nullptr, &error.outPtr());
WTF_ALLOW_UNSAFE_BUFFER_USAGE_END
if (!m_playerRegistrationId) {
g_warning("Failed at MPRIS object registration: %s", error->message);
return false;
}
const auto& applicationID = getApplicationID();
m_instanceId = applicationID.isEmpty() ? makeString("org.mpris.MediaPlayer2.webkit.instance"_s, getpid(), '-', m_identifier.toUInt64()) : makeString("org.mpris.MediaPlayer2."_s, applicationID.ascii().span(), ".Sandboxed.instance-"_s, m_identifier.toUInt64());
m_ownerId = g_bus_own_name_on_connection(m_connection.get(), m_instanceId.ascii().data(), G_BUS_NAME_OWNER_FLAGS_NONE, nullptr, nullptr, this, nullptr);
return true;
}
void MediaSessionGLib::unregisterMprisSession()
{
if (m_connection) {
if (m_rootRegistrationId && !g_dbus_connection_unregister_object(m_connection.get(), m_rootRegistrationId))
g_warning("Unable to unregister MPRIS D-Bus object.");
m_rootRegistrationId = 0;
if (m_playerRegistrationId && !g_dbus_connection_unregister_object(m_connection.get(), m_playerRegistrationId))
g_warning("Unable to unregister MPRIS D-Bus player object.");
m_playerRegistrationId = 0;
}
if (m_ownerId) {
g_bus_unown_name(m_ownerId);
m_ownerId = 0;
}
// This session will only be eligible again once it is set to the primary session.
setMprisRegistrationEligibility(MprisRegistrationEligiblilty::NotEligible);
}
void MediaSessionGLib::emitPositionChanged(double time)
{
if (!m_connection)
return;
if (!ensureMprisSessionRegistered())
return;
GUniqueOutPtr<GError> error;
int64_t position = time * 1000000;
if (!g_dbus_connection_emit_signal(m_connection.get(), nullptr, DBUS_MPRIS_OBJECT_PATH, DBUS_MPRIS_PLAYER_INTERFACE, "Seeked", g_variant_new("(x)", position), &error.outPtr()))
g_warning("Failed to emit MPRIS Seeked signal: %s", error->message);
}
void MediaSessionGLib::updateNowPlaying(NowPlayingInfo& nowPlayingInfo)
{
if (!m_connection)
return;
GVariantBuilder propertiesBuilder;
g_variant_builder_init(&propertiesBuilder, G_VARIANT_TYPE("a{sv}"));
g_variant_builder_add(&propertiesBuilder, "{sv}", "Metadata", getMetadataAsGVariant(nowPlayingInfo));
GRefPtr properties = g_variant_new("(sa{sv}as)", DBUS_MPRIS_PLAYER_INTERFACE, &propertiesBuilder, nullptr);
emitPropertiesChanged(WTFMove(properties));
g_variant_builder_clear(&propertiesBuilder);
}
GVariant* MediaSessionGLib::getMetadataAsGVariant(std::optional<NowPlayingInfo> info)
{
if (!info)
info = nowPlayingInfo();
GVariantBuilder builder;
g_variant_builder_init(&builder, G_VARIANT_TYPE("a{sv}"));
if (!info)
return g_variant_builder_end(&builder);
g_variant_builder_add(&builder, "{sv}", "mpris:trackid", g_variant_new("o", DBUS_MPRIS_TRACK_PATH));
g_variant_builder_add(&builder, "{sv}", "mpris:length", g_variant_new_int64(info->duration * 1000000));
g_variant_builder_add(&builder, "{sv}", "xesam:title", g_variant_new_string(info->metadata.title.utf8().data()));
g_variant_builder_add(&builder, "{sv}", "xesam:album", g_variant_new_string(info->metadata.album.utf8().data()));
if (info->metadata.artwork)
g_variant_builder_add(&builder, "{sv}", "mpris:artUrl", g_variant_new_string(info->metadata.artwork->src.utf8().data()));
GVariantBuilder artistBuilder;
g_variant_builder_init(&artistBuilder, G_VARIANT_TYPE("as"));
g_variant_builder_add(&artistBuilder, "s", info->metadata.artist.utf8().data());
g_variant_builder_add(&builder, "{sv}", "xesam:artist", g_variant_builder_end(&artistBuilder));
return g_variant_builder_end(&builder);
}
GVariant* MediaSessionGLib::getPlaybackStatusAsGVariant(std::optional<const PlatformMediaSession*> session)
{
auto state = [this, session = WTFMove(session)]() -> PlatformMediaSession::State {
if (session)
return session.value()->state();
auto nowPlayingSession = m_manager.nowPlayingEligibleSession();
if (nowPlayingSession)
return nowPlayingSession->state();
return PlatformMediaSession::State::Idle;
}();
switch (state) {
case PlatformMediaSession::State::Autoplaying:
case PlatformMediaSession::State::Playing:
return g_variant_new_string("Playing");
case PlatformMediaSession::State::Paused:
return g_variant_new_string("Paused");
case PlatformMediaSession::State::Idle:
case PlatformMediaSession::State::Interrupted:
return g_variant_new_string("Stopped");
}
ASSERT_NOT_REACHED();
return nullptr;
}
void MediaSessionGLib::emitPropertiesChanged(GRefPtr<GVariant>&& parameters)
{
if (!m_connection)
return;
if (!ensureMprisSessionRegistered())
return;
GUniqueOutPtr<GError> error;
if (!g_dbus_connection_emit_signal(m_connection.get(), nullptr, DBUS_MPRIS_OBJECT_PATH, "org.freedesktop.DBus.Properties", "PropertiesChanged", parameters.get(), &error.outPtr()))
g_warning("Failed to emit MPRIS properties changed: %s", error->message);
}
void MediaSessionGLib::playbackStatusChanged(PlatformMediaSession& platformSession)
{
if (!m_connection)
return;
GVariantBuilder builder;
g_variant_builder_init(&builder, G_VARIANT_TYPE("a{sv}"));
g_variant_builder_add(&builder, "{sv}", "PlaybackStatus", getPlaybackStatusAsGVariant(&platformSession));
GRefPtr properties = g_variant_new("(sa{sv}as)", DBUS_MPRIS_PLAYER_INTERFACE, &builder, nullptr);
emitPropertiesChanged(WTFMove(properties));
g_variant_builder_clear(&builder);
}
std::optional<NowPlayingInfo> MediaSessionGLib::nowPlayingInfo()
{
std::optional<NowPlayingInfo> nowPlayingInfo;
m_manager.forEachMatchingSession([&](auto& session) {
return session.mediaSessionIdentifier() == m_identifier;
}, [&](auto& session) {
nowPlayingInfo = session.nowPlayingInfo();
});
return nowPlayingInfo;
}
GVariant* MediaSessionGLib::getPositionAsGVariant()
{
auto info = nowPlayingInfo();
return g_variant_new_int64(info ? info->currentTime * 1000000 : 0);
}
GVariant* MediaSessionGLib::canSeekAsGVariant()
{
bool canSeek = false;
m_manager.forEachMatchingSession([&](auto& session) {
return session.mediaSessionIdentifier() == m_identifier;
}, [&](auto& session) {
canSeek = session.supportsSeeking();
});
return g_variant_new_boolean(canSeek);
}
} // namespace WebCore
#endif // USE(GLIB) && ENABLE(MEDIA_SESSION)
|