File: MPRISServiceHandler.cpp

package info (click to toggle)
firefox 147.0.3-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 4,683,320 kB
  • sloc: cpp: 7,607,359; javascript: 6,533,295; ansic: 3,775,223; python: 1,415,500; xml: 634,561; asm: 438,949; java: 186,241; sh: 62,752; makefile: 18,079; objc: 13,092; perl: 12,808; yacc: 4,583; cs: 3,846; pascal: 3,448; lex: 1,720; ruby: 1,003; php: 436; lisp: 258; awk: 247; sql: 66; sed: 54; csh: 10; exp: 6
file content (1075 lines) | stat: -rw-r--r-- 36,067 bytes parent folder | download
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "MPRISServiceHandler.h"

#include <stdint.h>
#include <inttypes.h>
#include <unordered_map>

#include "MPRISInterfaceDescription.h"
#include "mozilla/dom/MediaControlUtils.h"
#include "mozilla/GRefPtr.h"
#include "mozilla/GUniquePtr.h"
#include "mozilla/Maybe.h"
#include "mozilla/ScopeExit.h"
#include "mozilla/Sprintf.h"
#include "mozilla/XREAppData.h"
#include "nsXULAppAPI.h"
#include "nsIXULAppInfo.h"
#include "nsIOutputStream.h"
#include "nsNetUtil.h"
#include "nsServiceManagerUtils.h"
#include "WidgetUtilsGtk.h"
#include "AsyncDBus.h"
#include "prio.h"
#include "nsAppRunner.h"

#define LOGMPRIS(msg, ...)                   \
  MOZ_LOG(gMediaControlLog, LogLevel::Debug, \
          ("MPRISServiceHandler=%p, " msg, this, ##__VA_ARGS__))

namespace mozilla {
namespace widget {

// A global counter tracking the total images saved in the system and it will be
// used to form a unique image file name.
static uint32_t gImageNumber = 0;

static inline Maybe<dom::MediaControlKey> GetMediaControlKey(
    const gchar* aMethodName) {
  const std::unordered_map<std::string, dom::MediaControlKey> map = {
      {"Raise", dom::MediaControlKey::Focus},
      {"Next", dom::MediaControlKey::Nexttrack},
      {"Previous", dom::MediaControlKey::Previoustrack},
      {"Pause", dom::MediaControlKey::Pause},
      {"PlayPause", dom::MediaControlKey::Playpause},
      {"Stop", dom::MediaControlKey::Stop},
      {"Play", dom::MediaControlKey::Play},
      {"SetPosition", dom::MediaControlKey::Seekto},
      {"Seek", dom::MediaControlKey::Seekforward}};

  auto it = map.find(aMethodName);
  return it == map.end() ? Nothing() : Some(it->second);
}

static void HandleMethodCall(GDBusConnection* aConnection, const gchar* aSender,
                             const gchar* aObjectPath,
                             const gchar* aInterfaceName,
                             const gchar* aMethodName, GVariant* aParameters,
                             GDBusMethodInvocation* aInvocation,
                             gpointer aUserData) {
  MOZ_ASSERT(aUserData);
  MOZ_ASSERT(NS_IsMainThread());

  Maybe<dom::MediaControlKey> key = GetMediaControlKey(aMethodName);
  if (key.isNothing()) {
    g_dbus_method_invocation_return_error(
        aInvocation, G_DBUS_ERROR, G_DBUS_ERROR_NOT_SUPPORTED,
        "Method %s.%s.%s not supported", aObjectPath, aInterfaceName,
        aMethodName);
    return;
  }

  dom::SeekDetails seekDetails{};
  if (key.value() == dom::MediaControlKey::Seekto ||
      key.value() == dom::MediaControlKey::Seekforward) {
    RefPtr<GVariant> child = dont_AddRef(g_variant_get_child_value(
        aParameters, key.value() == dom::MediaControlKey::Seekto));
    double seekValue;
    if (g_variant_is_of_type(child, G_VARIANT_TYPE_INT64)) {
      seekValue = (double)g_variant_get_int64(child) / 1000000.0;
    } else {
      g_dbus_method_invocation_return_error(
          aInvocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
          "Invalid arguments for %s.%s.%s", aObjectPath, aInterfaceName,
          aMethodName);
      return;
    }
    if (key.value() == dom::MediaControlKey::Seekto) {
      seekDetails = dom::SeekDetails(seekValue, false /* fast seek */);
    } else if (seekValue > 0.0) {
      seekDetails = dom::SeekDetails(seekValue);
    } else {
      key = Some(dom::MediaControlKey::Seekbackward);
      seekDetails = dom::SeekDetails(-1 * seekValue);
    }
  }

  MPRISServiceHandler* handler = static_cast<MPRISServiceHandler*>(aUserData);
  if (handler->PressKey(dom::MediaControlAction(key.value(), seekDetails))) {
    g_dbus_method_invocation_return_value(aInvocation, nullptr);
  } else {
    g_dbus_method_invocation_return_error(
        aInvocation, G_DBUS_ERROR, G_DBUS_ERROR_FAILED,
        "%s.%s.%s is not available now", aObjectPath, aInterfaceName,
        aMethodName);
  }
}

enum class Property : uint8_t {
  eIdentity,
  eDesktopEntry,
  eHasTrackList,
  eCanRaise,
  eCanQuit,
  eSupportedUriSchemes,
  eSupportedMimeTypes,
  eCanGoNext,
  eCanGoPrevious,
  eCanPlay,
  eCanPause,
  eCanSeek,
  eCanControl,
  eGetPlaybackStatus,
  eGetMetadata,
  eGetPosition,
  eGetRate,
};

static inline Maybe<dom::MediaControlKey> GetPairedKey(Property aProperty) {
  switch (aProperty) {
    case Property::eCanRaise:
      return Some(dom::MediaControlKey::Focus);
    case Property::eCanGoNext:
      return Some(dom::MediaControlKey::Nexttrack);
    case Property::eCanGoPrevious:
      return Some(dom::MediaControlKey::Previoustrack);
    case Property::eCanPlay:
      return Some(dom::MediaControlKey::Play);
    case Property::eCanPause:
      return Some(dom::MediaControlKey::Pause);
    case Property::eCanSeek:
      return Some(dom::MediaControlKey::Seekto);
    default:
      return Nothing();
  }
}

static inline Maybe<Property> GetProperty(const gchar* aPropertyName) {
  const std::unordered_map<std::string, Property> map = {
      // org.mpris.MediaPlayer2 properties
      {"Identity", Property::eIdentity},
      {"DesktopEntry", Property::eDesktopEntry},
      {"HasTrackList", Property::eHasTrackList},
      {"CanRaise", Property::eCanRaise},
      {"CanQuit", Property::eCanQuit},
      {"SupportedUriSchemes", Property::eSupportedUriSchemes},
      {"SupportedMimeTypes", Property::eSupportedMimeTypes},
      // org.mpris.MediaPlayer2.Player properties
      {"CanGoNext", Property::eCanGoNext},
      {"CanGoPrevious", Property::eCanGoPrevious},
      {"CanPlay", Property::eCanPlay},
      {"CanPause", Property::eCanPause},
      {"CanSeek", Property::eCanSeek},
      {"CanControl", Property::eCanControl},
      {"PlaybackStatus", Property::eGetPlaybackStatus},
      {"Metadata", Property::eGetMetadata},
      {"Position", Property::eGetPosition},
      {"Rate", Property::eGetRate}};

  auto it = map.find(aPropertyName);
  return (it == map.end() ? Nothing() : Some(it->second));
}

static GVariant* HandleGetProperty(GDBusConnection* aConnection,
                                   const gchar* aSender,
                                   const gchar* aObjectPath,
                                   const gchar* aInterfaceName,
                                   const gchar* aPropertyName, GError** aError,
                                   gpointer aUserData) {
  MOZ_ASSERT(aUserData);
  MOZ_ASSERT(NS_IsMainThread());

  Maybe<Property> property = GetProperty(aPropertyName);
  if (property.isNothing()) {
    g_set_error(aError, G_DBUS_ERROR, G_DBUS_ERROR_NOT_SUPPORTED,
                "%s.%s %s is not supported", aObjectPath, aInterfaceName,
                aPropertyName);
    return nullptr;
  }

  MPRISServiceHandler* handler = static_cast<MPRISServiceHandler*>(aUserData);
  switch (property.value()) {
    case Property::eSupportedUriSchemes:
    case Property::eSupportedMimeTypes:
      // No plan to implement OpenUri for now
      return g_variant_new_strv(nullptr, 0);
    case Property::eGetPlaybackStatus:
      return handler->GetPlaybackStatus();
    case Property::eGetMetadata:
      return handler->GetMetadataAsGVariant();
    case Property::eGetPosition: {
      CheckedInt64 position =
          CheckedInt64((int64_t)handler->GetPositionSeconds()) * 1000000;
      return g_variant_new_int64(position.isValid() ? position.value() : 0);
    }
    case Property::eGetRate:
      return g_variant_new_double(handler->GetPlaybackRate());
    case Property::eIdentity:
      return g_variant_new_string(handler->Identity());
    case Property::eDesktopEntry:
      return g_variant_new_string(handler->DesktopEntry());
    case Property::eHasTrackList:
    case Property::eCanQuit:
      return g_variant_new_boolean(false);
    // Play/Pause would be blocked if CanControl is false
    case Property::eCanControl:
      return g_variant_new_boolean(true);
    case Property::eCanRaise:
    case Property::eCanGoNext:
    case Property::eCanGoPrevious:
    case Property::eCanPlay:
    case Property::eCanPause:
    case Property::eCanSeek:
      Maybe<dom::MediaControlKey> key = GetPairedKey(property.value());
      MOZ_ASSERT(key.isSome());
      return g_variant_new_boolean(handler->IsMediaKeySupported(key.value()));
  }

  MOZ_ASSERT_UNREACHABLE("Switch statement is incomplete");
  return nullptr;
}

static gboolean HandleSetProperty(GDBusConnection* aConnection,
                                  const gchar* aSender,
                                  const gchar* aObjectPath,
                                  const gchar* aInterfaceName,
                                  const gchar* aPropertyName, GVariant* aValue,
                                  GError** aError, gpointer aUserData) {
  MOZ_ASSERT(aUserData);
  MOZ_ASSERT(NS_IsMainThread());
  g_set_error(aError, G_IO_ERROR, G_IO_ERROR_FAILED,
              "%s:%s setting is not supported", aInterfaceName, aPropertyName);
  return false;
}

static const GDBusInterfaceVTable gInterfaceVTable = {
    HandleMethodCall, HandleGetProperty, HandleSetProperty};

void MPRISServiceHandler::OnNameAcquiredStatic(GDBusConnection* aConnection,
                                               const gchar* aName,
                                               gpointer aUserData) {
  MOZ_ASSERT(aUserData);
  static_cast<MPRISServiceHandler*>(aUserData)->OnNameAcquired(aConnection,
                                                               aName);
}

void MPRISServiceHandler::OnNameLostStatic(GDBusConnection* aConnection,
                                           const gchar* aName,
                                           gpointer aUserData) {
  MOZ_ASSERT(aUserData);
  static_cast<MPRISServiceHandler*>(aUserData)->OnNameLost(aConnection, aName);
}

void MPRISServiceHandler::OnBusAcquiredStatic(GDBusConnection* aConnection,
                                              const gchar* aName,
                                              gpointer aUserData) {
  MOZ_ASSERT(aUserData);
  static_cast<MPRISServiceHandler*>(aUserData)->OnBusAcquired(aConnection,
                                                              aName);
}

void MPRISServiceHandler::OnNameAcquired(GDBusConnection* aConnection,
                                         const gchar* aName) {
  LOGMPRIS("OnNameAcquired: %s", aName);
  mConnection = aConnection;
}

void MPRISServiceHandler::OnNameLost(GDBusConnection* aConnection,
                                     const gchar* aName) {
  LOGMPRIS("OnNameLost: %s", aName);
  mConnection = nullptr;
  if (!mRootRegistrationId) {
    return;
  }

  if (!aConnection) {
    return;
  }

  if (g_dbus_connection_unregister_object(aConnection, mRootRegistrationId)) {
    mRootRegistrationId = 0;
  } else {
    // Note: Most code examples in the internet probably dont't even check the
    // result here, but
    // according to the spec it _can_ return false.
    LOGMPRIS("Unable to unregister root object from within onNameLost!");
  }

  if (!mPlayerRegistrationId) {
    return;
  }

  if (g_dbus_connection_unregister_object(aConnection, mPlayerRegistrationId)) {
    mPlayerRegistrationId = 0;
  } else {
    // Note: Most code examples in the internet probably dont't even check the
    // result here, but
    // according to the spec it _can_ return false.
    LOGMPRIS("Unable to unregister object from within onNameLost!");
  }
}

void MPRISServiceHandler::OnBusAcquired(GDBusConnection* aConnection,
                                        const gchar* aName) {
  GUniquePtr<GError> error;
  LOGMPRIS("OnBusAcquired: %s", aName);

  mRootRegistrationId = g_dbus_connection_register_object(
      aConnection, DBUS_MPRIS_OBJECT_PATH, mIntrospectionData->interfaces[0],
      &gInterfaceVTable, this,  /* user_data */
      nullptr,                  /* user_data_free_func */
      getter_Transfers(error)); /* GError** */

  if (mRootRegistrationId == 0) {
    LOGMPRIS("Failed at root registration: %s",
             error ? error->message : "Unknown Error");
    return;
  }

  mPlayerRegistrationId = g_dbus_connection_register_object(
      aConnection, DBUS_MPRIS_OBJECT_PATH, mIntrospectionData->interfaces[1],
      &gInterfaceVTable, this,  /* user_data */
      nullptr,                  /* user_data_free_func */
      getter_Transfers(error)); /* GError** */

  if (mPlayerRegistrationId == 0) {
    LOGMPRIS("Failed at object registration: %s",
             error ? error->message : "Unknown Error");
  }
}

void MPRISServiceHandler::SetServiceName(const char* aName) {
  nsCString dbusName(aName);
  dbusName.ReplaceChar(':', '_');
  dbusName.ReplaceChar('.', '_');
  mServiceName =
      nsCString(DBUS_MPRIS_SERVICE_NAME) + nsCString(".instance") + dbusName;
}

const char* MPRISServiceHandler::GetServiceName() { return mServiceName.get(); }

/* static */
void g_bus_get_callback(GObject* aSourceObject, GAsyncResult* aRes,
                        gpointer aUserData) {
  GUniquePtr<GError> error;

  GDBusConnection* conn = g_bus_get_finish(aRes, getter_Transfers(error));
  if (!conn) {
    if (!IsCancelledGError(error.get())) {
      NS_WARNING(nsPrintfCString("Failure at g_bus_get_finish: %s",
                                 error ? error->message : "Unknown Error")
                     .get());
    }
    return;
  }

  MPRISServiceHandler* handler = static_cast<MPRISServiceHandler*>(aUserData);
  if (!handler) {
    NS_WARNING(
        nsPrintfCString("Failure to get a MPRISServiceHandler*: %p", handler)
            .get());
    return;
  }

  handler->OwnName(conn);
}

void MPRISServiceHandler::OwnName(GDBusConnection* aConnection) {
  MOZ_ASSERT(NS_IsMainThread());

  SetServiceName(g_dbus_connection_get_unique_name(aConnection));

  GUniquePtr<GError> error;

  InitIdentity();
  mOwnerId = g_bus_own_name_on_connection(
      aConnection, GetServiceName(),
      // Enter a waiting queue until this service name is free
      // (likely another FF instance is running/has been crashed)
      G_BUS_NAME_OWNER_FLAGS_NONE, OnNameAcquiredStatic, OnNameLostStatic, this,
      nullptr);

  /* parse introspection data */
  mIntrospectionData = dont_AddRef(
      g_dbus_node_info_new_for_xml(introspection_xml, getter_Transfers(error)));

  if (!mIntrospectionData) {
    LOGMPRIS("Failed at parsing XML Interface definition: %s",
             error ? error->message : "Unknown Error");
    return;
  }

  OnBusAcquired(aConnection, GetServiceName());
}

bool MPRISServiceHandler::Open() {
  MOZ_ASSERT(!mInitialized);
  MOZ_ASSERT(NS_IsMainThread());

  mDBusGetCancellable = dont_AddRef(g_cancellable_new());
  g_bus_get(G_BUS_TYPE_SESSION, mDBusGetCancellable, g_bus_get_callback, this);

  mInitialized = true;
  return true;
}

MPRISServiceHandler::MPRISServiceHandler() = default;
MPRISServiceHandler::~MPRISServiceHandler() {
  MOZ_ASSERT(!mInitialized, "Close hasn't been called!");
}

void MPRISServiceHandler::Close() {
  // Reset playback state and metadata before disconnect from dbus.
  SetPlaybackState(dom::MediaSessionPlaybackState::None);
  ClearMetadata();

  OnNameLost(mConnection, GetServiceName());

  if (mDBusGetCancellable) {
    g_cancellable_cancel(mDBusGetCancellable);
    mDBusGetCancellable = nullptr;
  }

  if (mOwnerId != 0) {
    g_bus_unown_name(mOwnerId);
  }

  mIntrospectionData = nullptr;

  mInitialized = false;
  MediaControlKeySource::Close();
}

bool MPRISServiceHandler::IsOpened() const { return mInitialized; }

void MPRISServiceHandler::InitIdentity() {
  nsresult rv;
  nsCOMPtr<nsIXULAppInfo> appInfo =
      do_GetService("@mozilla.org/xre/app-info;1", &rv);
  MOZ_ASSERT(NS_SUCCEEDED(rv));

  rv = appInfo->GetVendor(mIdentity);
  MOZ_ASSERT(NS_SUCCEEDED(rv));

  if (gAppData) {
    mDesktopEntry = gAppData->remotingName;
  } else {
    rv = appInfo->GetName(mDesktopEntry);
    MOZ_ASSERT(NS_SUCCEEDED(rv));
  }

  mIdentity.Append(' ');
  mIdentity.Append(mDesktopEntry);

  LOGMPRIS("InitIdentity() MPRIS desktop ID %s", mDesktopEntry.get());
}

const char* MPRISServiceHandler::Identity() const {
  NS_WARNING_ASSERTION(mInitialized,
                       "MPRISServiceHandler should have been initialized.");
  return mIdentity.get();
}

const char* MPRISServiceHandler::DesktopEntry() const {
  NS_WARNING_ASSERTION(mInitialized,
                       "MPRISServiceHandler should have been initialized.");
  return mDesktopEntry.get();
}

bool MPRISServiceHandler::PressKey(
    const dom::MediaControlAction& aAction) const {
  MOZ_ASSERT(mInitialized);
  if (!IsMediaKeySupported(aAction.mKey.value())) {
    LOGMPRIS("%s is not supported",
             dom::GetEnumString(aAction.mKey.value()).get());
    return false;
  }
  LOGMPRIS("Press %s", dom::GetEnumString(aAction.mKey.value()).get());
  EmitEvent(aAction);
  return true;
}

void MPRISServiceHandler::SetPlaybackState(
    dom::MediaSessionPlaybackState aState) {
  LOGMPRIS("SetPlaybackState");
  if (mPlaybackState == aState) {
    return;
  }

  MediaControlKeySource::SetPlaybackState(aState);

  GVariant* state = GetPlaybackStatus();
  GVariantBuilder builder;
  g_variant_builder_init(&builder, G_VARIANT_TYPE("a{sv}"));
  g_variant_builder_add(&builder, "{sv}", "PlaybackStatus", state);

  GVariant* parameters = g_variant_new(
      "(sa{sv}as)", DBUS_MPRIS_PLAYER_INTERFACE, &builder, nullptr);

  LOGMPRIS("Emitting MPRIS property changes for 'PlaybackStatus'");
  (void)EmitPropertiesChangedSignal(parameters);
}

GVariant* MPRISServiceHandler::GetPlaybackStatus() const {
  switch (GetPlaybackState()) {
    case dom::MediaSessionPlaybackState::Playing:
      return g_variant_new_string("Playing");
    case dom::MediaSessionPlaybackState::Paused:
      return g_variant_new_string("Paused");
    case dom::MediaSessionPlaybackState::None:
      return g_variant_new_string("Stopped");
    default:
      MOZ_ASSERT_UNREACHABLE("Invalid Playback State");
      return nullptr;
  }
}

void MPRISServiceHandler::SetMediaMetadata(
    const dom::MediaMetadataBase& aMetadata) {
  // Reset the index of the next available image to be fetched in the artwork,
  // before checking the fetching process should be started or not. The image
  // fetching process could be skipped if the image being fetching currently is
  // in the artwork. If the current image fetching fails, the next availabe
  // candidate should be the first image in the latest artwork
  mNextImageIndex = 0;

  // No need to fetch a MPRIS image if
  // 1) MPRIS image is being fetched, and the one in fetching is in the artwork
  // 2) MPRIS image is not being fetched, and the one in use is in the artwork
  if (!mFetchingUrl.IsEmpty()) {
    if (dom::IsImageIn(aMetadata.mArtwork, mFetchingUrl)) {
      LOGMPRIS(
          "No need to load MPRIS image. The one being processed is in the "
          "artwork");
      // Set MPRIS without the image first. The image will be loaded to MPRIS
      // asynchronously once it's fetched and saved into a local file
      SetMediaMetadataInternal(aMetadata);
      return;
    }
  } else if (!mCurrentImageUrl.IsEmpty()) {
    if (dom::IsImageIn(aMetadata.mArtwork, mCurrentImageUrl)) {
      LOGMPRIS("No need to load MPRIS image. The one in use is in the artwork");
      SetMediaMetadataInternal(aMetadata, false);
      return;
    }
  }

  // Set MPRIS without the image first then load the image to MPRIS
  // asynchronously
  SetMediaMetadataInternal(aMetadata);
  LoadImageAtIndex(mNextImageIndex++);
}

bool MPRISServiceHandler::EmitMetadataChanged() const {
  GVariantBuilder builder;
  g_variant_builder_init(&builder, G_VARIANT_TYPE("a{sv}"));
  g_variant_builder_add(&builder, "{sv}", "Metadata", GetMetadataAsGVariant());

  GVariant* parameters = g_variant_new(
      "(sa{sv}as)", DBUS_MPRIS_PLAYER_INTERFACE, &builder, nullptr);

  LOGMPRIS("Emit MPRIS property changes for 'Metadata'");
  return EmitPropertiesChangedSignal(parameters);
}

void MPRISServiceHandler::SetMediaMetadataInternal(
    const dom::MediaMetadataBase& aMetadata, bool aClearArtUrl) {
  mMPRISMetadata.UpdateFromMetadataBase(aMetadata);
  if (aClearArtUrl) {
    mMPRISMetadata.mArtUrl.Truncate();
  }
  EmitMetadataChanged();
}

void MPRISServiceHandler::ClearMetadata() {
  mMPRISMetadata.Clear();
  mImageFetchRequest.DisconnectIfExists();
  RemoveAllLocalImages();
  mCurrentImageUrl.Truncate();
  mFetchingUrl.Truncate();
  mNextImageIndex = 0;
  mSupportedKeys = 0;
  EmitMetadataChanged();
}

void MPRISServiceHandler::LoadImageAtIndex(const size_t aIndex) {
  MOZ_ASSERT(NS_IsMainThread());

  if (aIndex >= mMPRISMetadata.mArtwork.Length()) {
    LOGMPRIS("Stop loading image to MPRIS. No available image");
    mImageFetchRequest.DisconnectIfExists();
    return;
  }

  const dom::MediaImage& image = mMPRISMetadata.mArtwork[aIndex];

  if (!dom::IsValidImageUrl(image.mSrc)) {
    LOGMPRIS("Skip the image with invalid URL. Try next image");
    LoadImageAtIndex(mNextImageIndex++);
    return;
  }

  mImageFetchRequest.DisconnectIfExists();
  mFetchingUrl = image.mSrc;

  mImageFetcher = MakeUnique<dom::FetchImageHelper>(image);
  RefPtr<MPRISServiceHandler> self = this;
  mImageFetcher->FetchImage()
      ->Then(
          AbstractThread::MainThread(), __func__,
          [this, self](const nsCOMPtr<imgIContainer>& aImage) {
            LOGMPRIS("The image is fetched successfully");
            mImageFetchRequest.Complete();

            uint32_t size = 0;
            char* data = nullptr;
            // Only used to hold the image data
            nsCOMPtr<nsIInputStream> inputStream;
            nsresult rv = dom::GetEncodedImageBuffer(
                aImage, mMimeType, getter_AddRefs(inputStream), &size, &data);
            if (NS_FAILED(rv) || !inputStream || size == 0 || !data) {
              LOGMPRIS("Failed to get the image buffer info. Try next image");
              LoadImageAtIndex(mNextImageIndex++);
              return;
            }

            if (SetImageToDisplay(data, size)) {
              mCurrentImageUrl = mFetchingUrl;
              LOGMPRIS("The MPRIS image is updated to the image from: %s",
                       NS_ConvertUTF16toUTF8(mCurrentImageUrl).get());
            } else {
              LOGMPRIS("Failed to set image to MPRIS");
              mCurrentImageUrl.Truncate();
            }

            mFetchingUrl.Truncate();
          },
          [this, self](bool) {
            LOGMPRIS("Failed to fetch image. Try next image");
            mImageFetchRequest.Complete();
            mFetchingUrl.Truncate();
            LoadImageAtIndex(mNextImageIndex++);
          })
      ->Track(mImageFetchRequest);
}

bool MPRISServiceHandler::SetImageToDisplay(const char* aImageData,
                                            uint32_t aDataSize) {
  if (!RenewLocalImageFile(aImageData, aDataSize)) {
    return false;
  }
  MOZ_ASSERT(mLocalImageFile);

  mMPRISMetadata.mArtUrl = nsCString("file://");
  mMPRISMetadata.mArtUrl.Append(mLocalImageFile->NativePath());

  LOGMPRIS("The image file is created at %s", mMPRISMetadata.mArtUrl.get());
  return EmitMetadataChanged();
}

bool MPRISServiceHandler::RenewLocalImageFile(const char* aImageData,
                                              uint32_t aDataSize) {
  MOZ_ASSERT(aImageData);
  MOZ_ASSERT(aDataSize != 0);

  if (!InitLocalImageFile()) {
    LOGMPRIS("Failed to create a new image");
    return false;
  }

  MOZ_ASSERT(mLocalImageFile);
  nsCOMPtr<nsIOutputStream> out;
  nsresult rv =
      NS_NewLocalFileOutputStream(getter_AddRefs(out), mLocalImageFile,
                                  PR_RDWR | PR_CREATE_FILE | PR_TRUNCATE);
  uint32_t written;
  if (NS_SUCCEEDED(rv)) {
    rv = out->Write(aImageData, aDataSize, &written);
  }
  if (NS_FAILED(rv) || written != aDataSize) {
    LOGMPRIS("Failed to write an image file");
    RemoveAllLocalImages();
    return false;
  }

  return true;
}

static const char* GetImageFileExtension(const char* aMimeType) {
  MOZ_ASSERT(strcmp(aMimeType, IMAGE_PNG) == 0);
  return "png";
}

bool MPRISServiceHandler::InitLocalImageFile() {
  RemoveAllLocalImages();

  if (!InitLocalImageFolder()) {
    return false;
  }

  MOZ_ASSERT(mLocalImageFolder);
  MOZ_ASSERT(!mLocalImageFile);
  nsresult rv = mLocalImageFolder->Clone(getter_AddRefs(mLocalImageFile));
  if (NS_FAILED(rv)) {
    LOGMPRIS("Failed to get the image folder");
    return false;
  }

  auto cleanup =
      MakeScopeExit([this, self = RefPtr<MPRISServiceHandler>(this)] {
        mLocalImageFile = nullptr;
      });

  // Create an unique file name to work around the file caching mechanism in the
  // Ubuntu. Once the image X specified by the filename Y is used in Ubuntu's
  // MPRIS, this pair will be cached. As long as the filename is same, even the
  // file content specified by Y is changed to Z, the image will stay unchanged.
  // The image shown in the Ubuntu's notification is still X instead of Z.
  // Changing the filename constantly works around this problem
  char filename[64];
  SprintfLiteral(filename, "%d_%d.%s", getpid(), gImageNumber++,
                 GetImageFileExtension(mMimeType.get()));

  rv = mLocalImageFile->Append(NS_ConvertUTF8toUTF16(filename));
  if (NS_FAILED(rv)) {
    LOGMPRIS("Failed to create an image filename");
    return false;
  }

  rv = mLocalImageFile->Create(nsIFile::NORMAL_FILE_TYPE, 0600);
  if (NS_FAILED(rv)) {
    LOGMPRIS("Failed to create an image file");
    return false;
  }

  cleanup.release();
  return true;
}

bool MPRISServiceHandler::InitLocalImageFolder() {
  if (mLocalImageFolder && LocalImageFolderExists()) {
    return true;
  }

  nsresult rv = NS_ERROR_FAILURE;
  if (IsRunningUnderFlatpak()) {
    // The XDG_DATA_HOME points to the same location in the host and guest
    // filesystem.
    if (const auto* xdgDataHome = g_getenv("XDG_DATA_HOME")) {
      rv = NS_NewNativeLocalFile(nsDependentCString(xdgDataHome),
                                 getter_AddRefs(mLocalImageFolder));
    }
  } else {
    rv = NS_GetSpecialDirectory(XRE_USER_APP_DATA_DIR,
                                getter_AddRefs(mLocalImageFolder));
  }

  if (NS_FAILED(rv) || !mLocalImageFolder) {
    LOGMPRIS("Failed to get the image folder");
    return false;
  }

  auto cleanup = MakeScopeExit([&] { mLocalImageFolder = nullptr; });

  rv = mLocalImageFolder->Append(u"firefox-mpris"_ns);
  if (NS_FAILED(rv)) {
    LOGMPRIS("Failed to name an image folder");
    return false;
  }

  if (!LocalImageFolderExists()) {
    rv = mLocalImageFolder->Create(nsIFile::DIRECTORY_TYPE, 0700);
    if (NS_FAILED(rv)) {
      LOGMPRIS("Failed to create an image folder");
      return false;
    }
  }

  cleanup.release();
  return true;
}

void MPRISServiceHandler::RemoveAllLocalImages() {
  if (!mLocalImageFolder || !LocalImageFolderExists()) {
    return;
  }

  nsresult rv = mLocalImageFolder->Remove(/* aRecursive */ true);
  if (NS_FAILED(rv)) {
    // It's ok to fail. The next removal is called when updating the
    // media-session image, or closing the MPRIS.
    LOGMPRIS("Failed to remove images");
  }

  LOGMPRIS("Abandon %s",
           mLocalImageFile ? mLocalImageFile->NativePath().get() : "nothing");
  mMPRISMetadata.mArtUrl.Truncate();
  mLocalImageFile = nullptr;
  mLocalImageFolder = nullptr;
}

bool MPRISServiceHandler::LocalImageFolderExists() {
  MOZ_ASSERT(mLocalImageFolder);

  bool exists;
  nsresult rv = mLocalImageFolder->Exists(&exists);
  return NS_SUCCEEDED(rv) && exists;
}

GVariant* MPRISServiceHandler::GetMetadataAsGVariant() const {
  GVariantBuilder builder;
  g_variant_builder_init(&builder, G_VARIANT_TYPE("a{sv}"));
  g_variant_builder_add(&builder, "{sv}", "mpris:trackid",
                        g_variant_new("o", DBUS_MPRIS_TRACK_PATH));

  g_variant_builder_add(
      &builder, "{sv}", "xesam:title",
      g_variant_new_string(static_cast<const gchar*>(
          NS_ConvertUTF16toUTF8(mMPRISMetadata.mTitle).get())));

  g_variant_builder_add(
      &builder, "{sv}", "xesam:album",
      g_variant_new_string(static_cast<const gchar*>(
          NS_ConvertUTF16toUTF8(mMPRISMetadata.mAlbum).get())));

  GVariantBuilder artistBuilder;
  g_variant_builder_init(&artistBuilder, G_VARIANT_TYPE("as"));
  g_variant_builder_add(
      &artistBuilder, "s",
      static_cast<const gchar*>(
          NS_ConvertUTF16toUTF8(mMPRISMetadata.mArtist).get()));
  g_variant_builder_add(&builder, "{sv}", "xesam:artist",
                        g_variant_builder_end(&artistBuilder));

  if (!mMPRISMetadata.mArtUrl.IsEmpty()) {
    g_variant_builder_add(&builder, "{sv}", "mpris:artUrl",
                          g_variant_new_string(static_cast<const gchar*>(
                              mMPRISMetadata.mArtUrl.get())));
  }
  if (!mMPRISMetadata.mUrl.IsEmpty()) {
    g_variant_builder_add(&builder, "{sv}", "xesam:url",
                          g_variant_new_string(static_cast<const gchar*>(
                              mMPRISMetadata.mUrl.get())));
  }
  if (mPositionState.isSome()) {
    CheckedInt64 length =
        CheckedInt64((int64_t)mPositionState.value().mDuration) * 1000000;
    if (length.isValid()) {
      g_variant_builder_add(&builder, "{sv}", "mpris:length",
                            g_variant_new_int64(length.value()));
    }
  }

  return g_variant_builder_end(&builder);
}

void MPRISServiceHandler::EmitEvent(
    const dom::MediaControlAction& aAction) const {
  for (const auto& listener : mListeners) {
    listener->OnActionPerformed(aAction);
  }
}

struct InterfaceProperty {
  const char* interface;
  const char* property;
};
MOZ_RUNINIT static const std::unordered_map<dom::MediaControlKey,
                                            InterfaceProperty>
    gKeyProperty = {
        {dom::MediaControlKey::Focus, {DBUS_MPRIS_INTERFACE, "CanRaise"}},
        {dom::MediaControlKey::Nexttrack,
         {DBUS_MPRIS_PLAYER_INTERFACE, "CanGoNext"}},
        {dom::MediaControlKey::Previoustrack,
         {DBUS_MPRIS_PLAYER_INTERFACE, "CanGoPrevious"}},
        {dom::MediaControlKey::Play, {DBUS_MPRIS_PLAYER_INTERFACE, "CanPlay"}},
        {dom::MediaControlKey::Pause,
         {DBUS_MPRIS_PLAYER_INTERFACE, "CanPause"}}};

void MPRISServiceHandler::SetSupportedMediaKeys(
    const MediaKeysArray& aSupportedKeys) {
  uint32_t supportedKeys = 0;
  for (const dom::MediaControlKey& key : aSupportedKeys) {
    supportedKeys |= GetMediaKeyMask(key);
  }

  if (mSupportedKeys == supportedKeys) {
    LOGMPRIS("Supported keys stay the same");
    return;
  }

  uint32_t oldSupportedKeys = mSupportedKeys;
  mSupportedKeys = supportedKeys;

  // Emit related property changes
  for (auto it : gKeyProperty) {
    bool keyWasSupported = oldSupportedKeys & GetMediaKeyMask(it.first);
    bool keyIsSupported = mSupportedKeys & GetMediaKeyMask(it.first);
    if (keyWasSupported != keyIsSupported) {
      LOGMPRIS("Emit PropertiesChanged signal: %s.%s=%s", it.second.interface,
               it.second.property, keyIsSupported ? "true" : "false");
      EmitSupportedKeyChanged(it.first, keyIsSupported);
    }
  }
}

void MPRISServiceHandler::SetPositionState(
    const Maybe<dom::PositionState>& aState) {
  bool rateChanged = false;
  bool durationChanged = false;
  bool positionChanged = mPositionState.isSome() || aState.isSome();
  if (mPositionState.isSome() && aState.isSome()) {
    rateChanged = mPositionState->mPlaybackRate != aState->mPlaybackRate;
    durationChanged = mPositionState->mDuration != aState->mDuration;
  } else if (mPositionState.isNothing() && aState.isSome()) {
    rateChanged = aState->mPlaybackRate != 1.0;
    durationChanged = true;
  } else if (mPositionState.isSome() && aState.isNothing()) {
    rateChanged = mPositionState->mPlaybackRate != 1.0;
    durationChanged = true;
  }

  mPositionState = aState;

  if (rateChanged || durationChanged) {
    EmitPositionStateChanges(rateChanged, durationChanged);
  }
  if (positionChanged) {
    EmitSeekedSignal();
  }
}

double MPRISServiceHandler::GetPositionSeconds() const {
  if (mPositionState.isSome()) {
    return mPositionState.value().CurrentPlaybackPosition();
  }
  return 0.0;
}

double MPRISServiceHandler::GetPlaybackRate() const {
  if (mPositionState.isSome()) {
    return mPositionState->mPlaybackRate;
  }
  return 1.0;
}

bool MPRISServiceHandler::IsMediaKeySupported(dom::MediaControlKey aKey) const {
  return mSupportedKeys & GetMediaKeyMask(aKey);
}

bool MPRISServiceHandler::EmitSupportedKeyChanged(dom::MediaControlKey aKey,
                                                  bool aSupported) const {
  auto it = gKeyProperty.find(aKey);
  if (it == gKeyProperty.end()) {
    LOGMPRIS("No property for %s", dom::GetEnumString(aKey).get());
    return false;
  }

  GVariantBuilder builder;
  g_variant_builder_init(&builder, G_VARIANT_TYPE("a{sv}"));
  g_variant_builder_add(&builder, "{sv}",
                        static_cast<const gchar*>(it->second.property),
                        g_variant_new_boolean(aSupported));

  GVariant* parameters = g_variant_new(
      "(sa{sv}as)", static_cast<const gchar*>(it->second.interface), &builder,
      nullptr);

  LOGMPRIS("Emit MPRIS property changes for '%s.%s'", it->second.interface,
           it->second.property);
  return EmitPropertiesChangedSignal(parameters);
}

bool MPRISServiceHandler::EmitPositionStateChanges(
    bool aRateChanged, bool aDurationChanged) const {
  GVariantBuilder builder;
  g_variant_builder_init(&builder, G_VARIANT_TYPE("a{sv}"));
  if (aRateChanged) {
    double rate = 1.0;
    if (mPositionState.isSome()) {
      rate = mPositionState->mPlaybackRate;
    }
    g_variant_builder_add(&builder, "{sv}", "Rate", g_variant_new_double(rate));
  }
  if (aDurationChanged) {
    g_variant_builder_add(&builder, "{sv}", "Metadata",
                          GetMetadataAsGVariant());
  }

  GVariant* parameters = g_variant_new(
      "(sa{sv}as)", "org.mpris.MediaPlayer2.Player", &builder, nullptr);

  return EmitPropertiesChangedSignal(parameters);
}

bool MPRISServiceHandler::EmitPropertiesChangedSignal(
    GVariant* aParameters) const {
  if (!mConnection) {
    LOGMPRIS("No D-Bus Connection. Cannot emit properties changed signal");
    return false;
  }

  GError* error = nullptr;
  if (!g_dbus_connection_emit_signal(
          mConnection, nullptr, DBUS_MPRIS_OBJECT_PATH,
          "org.freedesktop.DBus.Properties", "PropertiesChanged", aParameters,
          &error)) {
    LOGMPRIS("Failed to emit MPRIS property changes: %s",
             error ? error->message : "Unknown Error");
    if (error) {
      g_error_free(error);
    }
    return false;
  }

  return true;
}

bool MPRISServiceHandler::EmitSeekedSignal() const {
  if (!mConnection) {
    LOGMPRIS("No D-Bus Connection. Cannot emit seeked signal");
    return false;
  }
  if (mPositionState.isNothing()) {
    LOGMPRIS("No position state. Cannot emit seeked signal");
    return false;
  }

  constexpr double kMaxMicroseconds =
      static_cast<double>(std::numeric_limits<gint64>::max());

  double currentPositionSec = mPositionState->CurrentPlaybackPosition();
  double currentPositionUs = currentPositionSec * 1.e6;
  if (currentPositionUs > kMaxMicroseconds) {
    LOGMPRIS("Failed to convert %f microseconds to gint64 (overflow)",
             currentPositionUs);
    return false;
  }

  GVariant* position =
      g_variant_new("(x)", static_cast<gint64>(currentPositionUs));

  GError* error = nullptr;
  if (!g_dbus_connection_emit_signal(
          mConnection, nullptr, DBUS_MPRIS_OBJECT_PATH,
          "org.mpris.MediaPlayer2.Player", "Seeked", position, &error)) {
    LOGMPRIS("Failed to emit MPRIS player seeked: %s",
             error ? error->message : "Unknown Error");
    if (error) {
      g_error_free(error);
    }
    return false;
  }

  return true;
}

#undef LOGMPRIS

}  // namespace widget
}  // namespace mozilla