File: RemoteMediaManagerChild.cpp

package info (click to toggle)
firefox 148.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 4,719,656 kB
  • sloc: cpp: 7,618,171; javascript: 6,701,506; ansic: 3,781,787; python: 1,418,364; xml: 638,647; asm: 438,962; java: 186,285; sh: 62,885; makefile: 19,010; objc: 13,092; perl: 12,763; 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 (1230 lines) | stat: -rw-r--r-- 48,697 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
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* 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 "RemoteMediaManagerChild.h"

#include "EMEDecoderModule.h"
#include "ErrorList.h"
#include "MP4Decoder.h"
#include "PDMFactory.h"
#include "PEMFactory.h"
#include "PlatformDecoderModule.h"
#include "PlatformEncoderModule.h"
#include "RemoteAudioDecoder.h"
#include "RemoteCDMChild.h"
#include "RemoteMediaDataDecoder.h"
#include "RemoteMediaDataEncoderChild.h"
#include "RemoteVideoDecoder.h"
#include "VideoUtils.h"
#include "mozilla/DataMutex.h"
#include "mozilla/MozPromise.h"
#include "mozilla/RemoteDecodeUtils.h"
#include "mozilla/StaticPrefs_media.h"
#include "mozilla/StaticPtr.h"
#include "mozilla/SyncRunnable.h"
#include "mozilla/dom/ContentChild.h"  // for launching RDD w/ ContentChild
#include "mozilla/gfx/2D.h"
#include "mozilla/gfx/DataSurfaceHelpers.h"
#include "mozilla/ipc/BackgroundChild.h"
#include "mozilla/ipc/Endpoint.h"
#include "mozilla/ipc/PBackgroundChild.h"
#include "mozilla/ipc/UtilityMediaServiceChild.h"
#include "mozilla/layers/ISurfaceAllocator.h"
#include "nsContentUtils.h"
#include "nsIObserver.h"
#include "nsPrintfCString.h"

#ifdef MOZ_WMF_MEDIA_ENGINE
#  include "MFMediaEngineChild.h"
#endif

#ifdef MOZ_WMF_CDM
#  include "MFCDMChild.h"
#endif

namespace mozilla {

#define LOG(msg, ...) \
  MOZ_LOG(gRemoteDecodeLog, LogLevel::Debug, (msg, ##__VA_ARGS__))

using namespace layers;
using namespace gfx;

using media::EncodeSupport;
using media::EncodeSupportSet;

// Used so that we only ever attempt to check if the RDD/GPU/Utility processes
// should be launched serially. Protects sLaunchPromise
StaticMutex sLaunchMutex;
static EnumeratedArray<RemoteMediaIn, StaticRefPtr<GenericNonExclusivePromise>,
                       size_t(RemoteMediaIn::SENTINEL)>
    sLaunchPromises MOZ_GUARDED_BY(sLaunchMutex);

// Only modified on the main-thread, read on any thread. While it could be read
// on the main thread directly, for clarity we force access via the DataMutex
// wrapper.
MOZ_RUNINIT static StaticDataMutex<StaticRefPtr<nsIThread>>
    sRemoteMediaManagerChildThread("sRemoteMediaManagerChildThread");

// Only accessed from sRemoteMediaManagerChildThread
static EnumeratedArray<RemoteMediaIn, StaticRefPtr<RemoteMediaManagerChild>,
                       size_t(RemoteMediaIn::SENTINEL)>
    sRemoteMediaManagerChildForProcesses;

static StaticAutoPtr<nsTArray<RefPtr<Runnable>>> sRecreateTasks;

// Used for protecting codec support information collected from different remote
// processes.
StaticMutex sProcessSupportedMutex;
MOZ_GLOBINIT static EnumeratedArray<RemoteMediaIn,
                                    Maybe<media::MediaCodecsSupported>,
                                    size_t(RemoteMediaIn::SENTINEL)>
    sProcessSupported MOZ_GUARDED_BY(sProcessSupportedMutex);

class ShutdownObserver final : public nsIObserver {
 public:
  NS_DECL_ISUPPORTS
  NS_DECL_NSIOBSERVER

 protected:
  ~ShutdownObserver() = default;
};
NS_IMPL_ISUPPORTS(ShutdownObserver, nsIObserver);

NS_IMETHODIMP
ShutdownObserver::Observe(nsISupports* aSubject, const char* aTopic,
                          const char16_t* aData) {
  MOZ_ASSERT(!strcmp(aTopic, NS_XPCOM_SHUTDOWN_OBSERVER_ID));
  RemoteMediaManagerChild::Shutdown();
  return NS_OK;
}

StaticRefPtr<ShutdownObserver> sObserver;

/* static */
void RemoteMediaManagerChild::Init() {
  LOG("RemoteMediaManagerChild Init");

  auto remoteDecoderManagerThread = sRemoteMediaManagerChildThread.Lock();
  if (!*remoteDecoderManagerThread) {
    LOG("RemoteMediaManagerChild's thread is created");
    // We can't use a MediaThreadType::SUPERVISOR as the RemoteDecoderModule
    // runs on it and dispatch synchronous tasks to the manager thread, should
    // more than 4 concurrent videos being instantiated at the same time, we
    // could end up in a deadlock.
    RefPtr<nsIThread> childThread;
    nsresult rv = NS_NewNamedThread(
        "RemVidChild", getter_AddRefs(childThread),
        NS_NewRunnableFunction(
            "RemoteMediaManagerChild::InitPBackground", []() {
              ipc::PBackgroundChild* bgActor =
                  ipc::BackgroundChild::GetOrCreateForCurrentThread();
              NS_WARNING_ASSERTION(bgActor,
                                   "Failed to start Background channel");
              (void)bgActor;
            }));

    NS_ENSURE_SUCCESS_VOID(rv);
    *remoteDecoderManagerThread = childThread;
    sRecreateTasks = new nsTArray<RefPtr<Runnable>>();
    sObserver = new ShutdownObserver();
    nsContentUtils::RegisterShutdownObserver(sObserver);
  }
}

/* static */
void RemoteMediaManagerChild::InitForGPUProcess(
    Endpoint<PRemoteMediaManagerChild>&& aVideoManager) {
  MOZ_ASSERT(NS_IsMainThread());

  Init();

  auto remoteDecoderManagerThread = sRemoteMediaManagerChildThread.Lock();
  MOZ_ALWAYS_SUCCEEDS(
      (*remoteDecoderManagerThread)
          ->Dispatch(NewRunnableFunction(
              "InitForContentRunnable", &OpenRemoteMediaManagerChildForProcess,
              std::move(aVideoManager), RemoteMediaIn::GpuProcess)));
}

/* static */
void RemoteMediaManagerChild::Shutdown() {
  MOZ_ASSERT(NS_IsMainThread());
  LOG("RemoteMediaManagerChild Shutdown");

  if (sObserver) {
    nsContentUtils::UnregisterShutdownObserver(sObserver);
    sObserver = nullptr;
  }

  nsCOMPtr<nsIThread> childThread;
  {
    auto remoteDecoderManagerThread = sRemoteMediaManagerChildThread.Lock();
    childThread = remoteDecoderManagerThread->forget();
    LOG("RemoteMediaManagerChild's thread is released");
  }
  if (childThread) {
    MOZ_ALWAYS_SUCCEEDS(childThread->Dispatch(
        NS_NewRunnableFunction("dom::RemoteMediaManagerChild::Shutdown", []() {
          for (auto& p : sRemoteMediaManagerChildForProcesses) {
            if (p && p->CanSend()) {
              p->Close();
            }
            p = nullptr;
          }
          {
            StaticMutexAutoLock lock(sLaunchMutex);
            for (auto& p : sLaunchPromises) {
              p = nullptr;
            }
          }
          ipc::BackgroundChild::CloseForCurrentThread();
        })));
    childThread->Shutdown();
    sRecreateTasks = nullptr;
  }
}

/* static */ void RemoteMediaManagerChild::RunWhenGPUProcessRecreated(
    const RemoteMediaManagerChild* aDyingManager,
    already_AddRefed<Runnable> aTask) {
  nsCOMPtr<nsISerialEventTarget> managerThread = GetManagerThread();
  if (!managerThread) {
    // We've been shutdown, bail.
    return;
  }
  MOZ_ASSERT(managerThread->IsOnCurrentThread());

  // If we've already been recreated, then run the task immediately.
  auto* manager = GetSingleton(RemoteMediaIn::GpuProcess);
  if (manager && manager != aDyingManager && manager->CanSend()) {
    RefPtr<Runnable> task = aTask;
    task->Run();
  } else {
    sRecreateTasks->AppendElement(aTask);
  }
}

/* static */
RemoteMediaManagerChild* RemoteMediaManagerChild::GetSingleton(
    RemoteMediaIn aLocation) {
  nsCOMPtr<nsISerialEventTarget> managerThread = GetManagerThread();
  if (!managerThread) {
    // We've been shutdown, bail.
    return nullptr;
  }
  MOZ_ASSERT(managerThread->IsOnCurrentThread());
  switch (aLocation) {
    case RemoteMediaIn::GpuProcess:
    case RemoteMediaIn::RddProcess:
    case RemoteMediaIn::UtilityProcess_Generic:
    case RemoteMediaIn::UtilityProcess_AppleMedia:
    case RemoteMediaIn::UtilityProcess_WMF:
    case RemoteMediaIn::UtilityProcess_MFMediaEngineCDM:
      return sRemoteMediaManagerChildForProcesses[aLocation];
    default:
      MOZ_CRASH("Unexpected RemoteMediaIn variant");
      return nullptr;
  }
}

/* static */
nsCOMPtr<nsISerialEventTarget> RemoteMediaManagerChild::GetManagerThread() {
  auto remoteDecoderManagerThread = sRemoteMediaManagerChildThread.Lock();
  return nsCOMPtr<nsISerialEventTarget>(*remoteDecoderManagerThread);
}

/* static */
bool RemoteMediaManagerChild::Supports(RemoteMediaIn aLocation,
                                       const SupportDecoderParams& aParams,
                                       DecoderDoctorDiagnostics* aDiagnostics) {
  Maybe<media::MediaCodecsSupported> supported;
  switch (aLocation) {
    case RemoteMediaIn::GpuProcess:
    case RemoteMediaIn::RddProcess:
    case RemoteMediaIn::UtilityProcess_AppleMedia:
    case RemoteMediaIn::UtilityProcess_Generic:
    case RemoteMediaIn::UtilityProcess_WMF:
    case RemoteMediaIn::UtilityProcess_MFMediaEngineCDM: {
      StaticMutexAutoLock lock(sProcessSupportedMutex);
      supported = sProcessSupported[aLocation];
      break;
    }
    default:
      return false;
  }
  if (!supported) {
    // We haven't received the correct information yet from either the GPU or
    // the RDD process nor the Utility process.
    if (aLocation == RemoteMediaIn::UtilityProcess_Generic ||
        aLocation == RemoteMediaIn::UtilityProcess_AppleMedia ||
        aLocation == RemoteMediaIn::UtilityProcess_WMF ||
        aLocation == RemoteMediaIn::UtilityProcess_MFMediaEngineCDM) {
      LaunchUtilityProcessIfNeeded(aLocation);
    }
    if (aLocation == RemoteMediaIn::RddProcess) {
      // Ensure the RDD process got started.
      // TODO: This can be removed once bug 1684991 is fixed.
      LaunchRDDProcessIfNeeded();
    }

    // Assume the format is supported to prevent false negative, if the remote
    // process supports that specific track type.
    const bool isVideo = aParams.mConfig.IsVideo();
    const bool isAudio = aParams.mConfig.IsAudio();
    const auto trackSupport = GetTrackSupport(aLocation);
    if (isVideo) {
      // Special condition for HEVC, which can only be supported in specific
      // process. As HEVC support is still a experimental feature, we don't want
      // to report support for it arbitrarily.
      if (MP4Decoder::IsHEVC(aParams.mConfig.mMimeType)) {
        if (!StaticPrefs::media_hevc_enabled()) {
          return false;
        }
#if defined(XP_WIN)
        return aLocation == RemoteMediaIn::UtilityProcess_MFMediaEngineCDM ||
               aLocation == RemoteMediaIn::GpuProcess;
#else
        return trackSupport.contains(TrackSupport::DecodeVideo);
#endif
      }
      return trackSupport.contains(TrackSupport::DecodeVideo);
    }
    if (isAudio) {
      return trackSupport.contains(TrackSupport::DecodeAudio);
    }
    MOZ_ASSERT_UNREACHABLE("Not audio and video?!");
    return false;
  }

  // We can ignore the SupportDecoderParams argument for now as creation of the
  // decoder will actually fail later and fallback PDMs will be tested on later.
  return !PDMFactory::SupportsMimeType(aParams.MimeType(), *supported,
                                       aLocation)
              .isEmpty();
}

/* static */
RefPtr<PlatformDecoderModule::CreateDecoderPromise>
RemoteMediaManagerChild::CreateAudioDecoder(const CreateDecoderParams& aParams,
                                            RemoteMediaIn aLocation) {
  nsCOMPtr<nsISerialEventTarget> managerThread = GetManagerThread();
  if (!managerThread) {
    // We got shutdown.
    return PlatformDecoderModule::CreateDecoderPromise::CreateAndReject(
        NS_ERROR_DOM_MEDIA_CANCELED, __func__);
  }

  if (!GetTrackSupport(aLocation).contains(TrackSupport::DecodeAudio)) {
    return PlatformDecoderModule::CreateDecoderPromise::CreateAndReject(
        MediaResult(NS_ERROR_DOM_MEDIA_CANCELED,
                    nsPrintfCString("%s doesn't support audio decoding",
                                    RemoteMediaInToStr(aLocation))
                        .get()),
        __func__);
  }

  if (!aParams.mMediaEngineId &&
      aLocation == RemoteMediaIn::UtilityProcess_MFMediaEngineCDM) {
    return PlatformDecoderModule::CreateDecoderPromise::CreateAndReject(
        MediaResult(NS_ERROR_DOM_MEDIA_NOT_SUPPORTED_ERR,
                    nsPrintfCString("%s only support for media engine playback",
                                    RemoteMediaInToStr(aLocation))
                        .get()),
        __func__);
  }

  RefPtr<GenericNonExclusivePromise> launchPromise;
  if (StaticPrefs::media_utility_process_enabled() &&
      (aLocation == RemoteMediaIn::UtilityProcess_Generic ||
       aLocation == RemoteMediaIn::UtilityProcess_AppleMedia ||
       aLocation == RemoteMediaIn::UtilityProcess_WMF)) {
    launchPromise = LaunchUtilityProcessIfNeeded(aLocation);
  } else if (aLocation == RemoteMediaIn::UtilityProcess_MFMediaEngineCDM) {
    launchPromise = LaunchUtilityProcessIfNeeded(aLocation);
  } else if (StaticPrefs::media_allow_audio_non_utility() || aParams.mCDM) {
    launchPromise = LaunchRDDProcessIfNeeded();
  } else {
    return PlatformDecoderModule::CreateDecoderPromise::CreateAndReject(
        MediaResult(
            NS_ERROR_DOM_MEDIA_DENIED_IN_NON_UTILITY,
            nsPrintfCString("%s is not allowed to perform audio decoding",
                            RemoteMediaInToStr(aLocation))
                .get()),
        __func__);
  }
  LOG("Create audio decoder in %s", RemoteMediaInToStr(aLocation));

  return launchPromise->Then(
      managerThread, __func__,
      [params = CreateDecoderParamsForAsync(aParams), aLocation](bool) mutable {
        auto child = MakeRefPtr<RemoteAudioDecoderChild>(aLocation);
        MediaResult result =
            child->InitIPDL(params.AudioConfig(), params.mOptions,
                            params.mMediaEngineId, params.mCDM);
        if (NS_FAILED(result)) {
          return PlatformDecoderModule::CreateDecoderPromise::CreateAndReject(
              result, __func__);
        }
        return Construct(std::move(child), std::move(params), aLocation);
      },
      [aLocation](nsresult aResult) {
        return PlatformDecoderModule::CreateDecoderPromise::CreateAndReject(
            MediaResult(aResult,
                        aLocation == RemoteMediaIn::GpuProcess
                            ? "Couldn't start GPU process"
                            : (aLocation == RemoteMediaIn::RddProcess
                                   ? "Couldn't start RDD process"
                                   : "Couldn't start Utility process")),
            __func__);
      });
}

/* static */
RefPtr<PlatformDecoderModule::CreateDecoderPromise>
RemoteMediaManagerChild::CreateVideoDecoder(const CreateDecoderParams& aParams,
                                            RemoteMediaIn aLocation) {
  nsCOMPtr<nsISerialEventTarget> managerThread = GetManagerThread();
  if (!managerThread) {
    // We got shutdown.
    return PlatformDecoderModule::CreateDecoderPromise::CreateAndReject(
        NS_ERROR_DOM_MEDIA_CANCELED, __func__);
  }

  if (!aParams.mKnowsCompositor && aLocation == RemoteMediaIn::GpuProcess) {
    // We don't have an image bridge; don't attempt to decode in the GPU
    // process.
    return PlatformDecoderModule::CreateDecoderPromise::CreateAndReject(
        NS_ERROR_DOM_MEDIA_NOT_SUPPORTED_ERR, __func__);
  }

  if (!GetTrackSupport(aLocation).contains(TrackSupport::DecodeVideo)) {
    return PlatformDecoderModule::CreateDecoderPromise::CreateAndReject(
        MediaResult(NS_ERROR_DOM_MEDIA_CANCELED,
                    nsPrintfCString("%s doesn't support video decoding",
                                    RemoteMediaInToStr(aLocation))
                        .get()),
        __func__);
  }

  if (!aParams.mMediaEngineId &&
      aLocation == RemoteMediaIn::UtilityProcess_MFMediaEngineCDM) {
    return PlatformDecoderModule::CreateDecoderPromise::CreateAndReject(
        MediaResult(NS_ERROR_DOM_MEDIA_NOT_SUPPORTED_ERR,
                    nsPrintfCString("%s only support for media engine playback",
                                    RemoteMediaInToStr(aLocation))
                        .get()),
        __func__);
  }

  MOZ_ASSERT(aLocation != RemoteMediaIn::Unspecified);

  RefPtr<GenericNonExclusivePromise> p;
  if (aLocation == RemoteMediaIn::GpuProcess) {
    p = GenericNonExclusivePromise::CreateAndResolve(true, __func__);
  } else if (aLocation == RemoteMediaIn::UtilityProcess_MFMediaEngineCDM) {
    p = LaunchUtilityProcessIfNeeded(aLocation);
  } else {
    p = LaunchRDDProcessIfNeeded();
  }
  LOG("Create video decoder in %s", RemoteMediaInToStr(aLocation));

  return p->Then(
      managerThread, __func__,
      [aLocation, params = CreateDecoderParamsForAsync(aParams)](bool) mutable {
        auto child = MakeRefPtr<RemoteVideoDecoderChild>(aLocation);
        MediaResult result = child->InitIPDL(
            params.VideoConfig(), params.mRate.mValue, params.mOptions,
            params.mKnowsCompositor
                ? Some(params.mKnowsCompositor->GetTextureFactoryIdentifier())
                : Nothing(),
            params.mMediaEngineId, params.mTrackingId, params.mCDM);
        if (NS_FAILED(result)) {
          return PlatformDecoderModule::CreateDecoderPromise::CreateAndReject(
              result, __func__);
        }
        return Construct(std::move(child), std::move(params), aLocation);
      },
      [](nsresult aResult) {
        return PlatformDecoderModule::CreateDecoderPromise::CreateAndReject(
            MediaResult(aResult, "Couldn't start RDD process"), __func__);
      });
}

/* static */
RefPtr<RemoteCDMChild> RemoteMediaManagerChild::CreateCDM(
    RemoteMediaIn aLocation, dom::MediaKeys* aKeys, const nsAString& aKeySystem,
    bool aDistinctiveIdentifierRequired, bool aPersistentStateRequired) {
  MOZ_ASSERT(NS_IsMainThread());

  if (NS_WARN_IF(aLocation != RemoteMediaIn::RddProcess)) {
    MOZ_ASSERT_UNREACHABLE("Cannot use CDM outside RDD process");
    return nullptr;
  }

  if (!StaticPrefs::media_ffvpx_hw_enabled()) {
    return nullptr;
  }

  nsCOMPtr<nsISerialEventTarget> managerThread = GetManagerThread();
  if (!managerThread) {
    // We got shutdown.
    return nullptr;
  }

  if (!GetTrackSupport(aLocation).contains(TrackSupport::DecodeVideo)) {
    return nullptr;
  }

  RefPtr<GenericNonExclusivePromise> p = LaunchRDDProcessIfNeeded();
  LOG("Create CDM in %s", RemoteMediaInToStr(aLocation));

  return MakeRefPtr<RemoteCDMChild>(
      std::move(managerThread), std::move(p), aLocation, aKeys, aKeySystem,
      aDistinctiveIdentifierRequired, aPersistentStateRequired);
}

/* static */
RefPtr<PlatformDecoderModule::CreateDecoderPromise>
RemoteMediaManagerChild::Construct(RefPtr<RemoteDecoderChild>&& aChild,
                                   CreateDecoderParamsForAsync&& aParams,
                                   RemoteMediaIn aLocation) {
  nsCOMPtr<nsISerialEventTarget> managerThread = GetManagerThread();
  if (!managerThread) {
    // We got shutdown.
    return PlatformDecoderModule::CreateDecoderPromise::CreateAndReject(
        NS_ERROR_DOM_MEDIA_CANCELED, __func__);
  }
  MOZ_ASSERT(managerThread->IsOnCurrentThread());

  RefPtr<PlatformDecoderModule::CreateDecoderPromise> p =
      aChild->SendConstruct()->Then(
          managerThread, __func__,
          [child = std::move(aChild),
           params = std::move(aParams)](MediaResult aResult) {
            if (NS_FAILED(aResult)) {
              // We will never get to use this remote decoder, tear it down.
              child->DestroyIPDL();
              return PlatformDecoderModule::CreateDecoderPromise::
                  CreateAndReject(aResult, __func__);
            }
            if (params.mCDM) {
              if (auto* cdmChild = params.mCDM->AsPRemoteCDMChild()) {
                return PlatformDecoderModule::CreateDecoderPromise::
                    CreateAndResolve(
                        MakeRefPtr<EMEMediaDataDecoderProxy>(
                            params,
                            MakeAndAddRef<RemoteMediaDataDecoder>(child),
                            static_cast<RemoteCDMChild*>(cdmChild)),
                        __func__);
              }
              return PlatformDecoderModule::CreateDecoderPromise::
                  CreateAndReject(
                      NS_ERROR_DOM_MEDIA_CDM_PROXY_NOT_SUPPORTED_ERR, __func__);
            }
            return PlatformDecoderModule::CreateDecoderPromise::
                CreateAndResolve(MakeRefPtr<RemoteMediaDataDecoder>(child),
                                 __func__);
          },
          [aLocation](const mozilla::ipc::ResponseRejectReason& aReason) {
            // The parent has died.
            nsresult err = NS_ERROR_DOM_MEDIA_REMOTE_CRASHED_UTILITY_ERR;
            if (aLocation == RemoteMediaIn::GpuProcess ||
                aLocation == RemoteMediaIn::RddProcess) {
              err = NS_ERROR_DOM_MEDIA_REMOTE_CRASHED_RDD_OR_GPU_ERR;
            } else if (aLocation ==
                       RemoteMediaIn::UtilityProcess_MFMediaEngineCDM) {
              err = NS_ERROR_DOM_MEDIA_REMOTE_CRASHED_MF_CDM_ERR;
            }
            return PlatformDecoderModule::CreateDecoderPromise::CreateAndReject(
                err, __func__);
          });
  return p;
}

/* static */
EncodeSupportSet RemoteMediaManagerChild::Supports(RemoteMediaIn aLocation,
                                                   CodecType aCodec) {
  Maybe<media::MediaCodecsSupported> supported;
  switch (aLocation) {
    case RemoteMediaIn::GpuProcess:
    case RemoteMediaIn::RddProcess:
    case RemoteMediaIn::UtilityProcess_AppleMedia:
    case RemoteMediaIn::UtilityProcess_Generic:
    case RemoteMediaIn::UtilityProcess_WMF:
    case RemoteMediaIn::UtilityProcess_MFMediaEngineCDM: {
      StaticMutexAutoLock lock(sProcessSupportedMutex);
      supported = sProcessSupported[aLocation];
      break;
    }
    default:
      return EncodeSupportSet{};
  }
  if (!supported) {
    // We haven't received the correct information yet from either the GPU or
    // the RDD process nor the Utility process.
    if (aLocation == RemoteMediaIn::UtilityProcess_Generic ||
        aLocation == RemoteMediaIn::UtilityProcess_AppleMedia ||
        aLocation == RemoteMediaIn::UtilityProcess_WMF ||
        aLocation == RemoteMediaIn::UtilityProcess_MFMediaEngineCDM) {
      LaunchUtilityProcessIfNeeded(aLocation);
    }
    if (aLocation == RemoteMediaIn::RddProcess) {
      // Ensure the RDD process got started.
      // TODO: This can be removed once bug 1684991 is fixed.
      LaunchRDDProcessIfNeeded();
    }

    // Assume the format is supported to prevent false negative, if the remote
    // process supports that specific track type.
    const auto trackSupport = GetTrackSupport(aLocation);
    if (IsVideo(aCodec)) {
      // Special condition for HEVC, which can only be supported in specific
      // process. As HEVC support is still a experimental feature, we don't want
      // to report support for it arbitrarily.
      bool supported = trackSupport.contains(TrackSupport::EncodeVideo);
      if (aCodec == CodecType::H265) {
        if (!StaticPrefs::media_hevc_enabled()) {
          return EncodeSupportSet{};
        }
#if defined(XP_WIN)
        supported = aLocation == RemoteMediaIn::GpuProcess;
#endif
      }
      return supported ? EncodeSupportSet{EncodeSupport::SoftwareEncode}
                       : EncodeSupportSet{};
    }
    if (IsAudio(aCodec)) {
      return trackSupport.contains(TrackSupport::EncodeAudio)
                 ? EncodeSupportSet{EncodeSupport::SoftwareEncode}
                 : EncodeSupportSet{};
    }
    MOZ_ASSERT_UNREACHABLE("Not audio and video?!");
    return EncodeSupportSet{};
  }

  // We can ignore the rest of EncoderConfig for now as creation of the encoder
  // will actually fail later and fallback PEMs will be tested on later.
  return PEMFactory::SupportsCodec(aCodec, *supported, aLocation);
}

/* static */ RefPtr<PlatformEncoderModule::CreateEncoderPromise>
RemoteMediaManagerChild::InitializeEncoder(
    RefPtr<RemoteMediaDataEncoderChild>&& aEncoder,
    const EncoderConfig& aConfig) {
  RemoteMediaIn location = aEncoder->GetLocation();

  TrackSupport required;
  if (aConfig.IsAudio()) {
    required = TrackSupport::EncodeAudio;
  } else if (aConfig.IsVideo()) {
    required = TrackSupport::EncodeVideo;
  } else {
    return PlatformEncoderModule::CreateEncoderPromise::CreateAndReject(
        MediaResult(NS_ERROR_DOM_MEDIA_CANCELED,
                    nsPrintfCString("%s doesn't support encoding",
                                    RemoteMediaInToStr(location))
                        .get()),
        __func__);
  }

  if (!GetTrackSupport(location).contains(required)) {
    return PlatformEncoderModule::CreateEncoderPromise::CreateAndReject(
        MediaResult(NS_ERROR_DOM_MEDIA_CANCELED,
                    nsPrintfCString("%s doesn't support encoding",
                                    RemoteMediaInToStr(location))
                        .get()),
        __func__);
  }

  auto managerThread = aEncoder->GetManagerThread();
  if (!managerThread) {
    return PlatformEncoderModule::CreateEncoderPromise::CreateAndReject(
        MediaResult(NS_ERROR_DOM_MEDIA_CANCELED, "Thread shutdown"_ns),
        __func__);
  }

  MOZ_ASSERT(location != RemoteMediaIn::Unspecified);

  RefPtr<GenericNonExclusivePromise> p;
  if (location == RemoteMediaIn::UtilityProcess_Generic ||
      location == RemoteMediaIn::UtilityProcess_AppleMedia ||
      location == RemoteMediaIn::UtilityProcess_WMF) {
    p = LaunchUtilityProcessIfNeeded(location);
  } else if (location == RemoteMediaIn::GpuProcess) {
    p = GenericNonExclusivePromise::CreateAndResolve(true, __func__);
  } else if (location == RemoteMediaIn::RddProcess) {
    p = LaunchRDDProcessIfNeeded();
  } else {
    p = GenericNonExclusivePromise::CreateAndReject(
        NS_ERROR_DOM_MEDIA_DENIED_IN_NON_UTILITY, __func__);
  }
  LOG("Creating %s encoder type %d in %s",
      aConfig.IsAudio() ? "audio" : "video", static_cast<int>(aConfig.mCodec),
      RemoteMediaInToStr(location));

  return p->Then(
      managerThread, __func__,
      [encoder = std::move(aEncoder), aConfig](bool) {
        auto* manager = GetSingleton(encoder->GetLocation());
        if (!manager) {
          LOG("Create encoder in %s failed, shutdown",
              RemoteMediaInToStr(encoder->GetLocation()));
          // We got shutdown.
          return PlatformEncoderModule::CreateEncoderPromise::CreateAndReject(
              MediaResult(NS_ERROR_DOM_MEDIA_CANCELED,
                          "Remote manager not available"),
              __func__);
        }
        if (!manager->SendPRemoteEncoderConstructor(encoder, aConfig)) {
          LOG("Create encoder in %s failed, send failed",
              RemoteMediaInToStr(encoder->GetLocation()));
          return PlatformEncoderModule::CreateEncoderPromise::CreateAndReject(
              MediaResult(NS_ERROR_NOT_AVAILABLE,
                          "Failed to construct encoder actor"),
              __func__);
        }
        return encoder->Construct();
      },
      [location](nsresult aResult) {
        LOG("Create encoder in %s failed, cannot start process",
            RemoteMediaInToStr(location));
        return PlatformEncoderModule::CreateEncoderPromise::CreateAndReject(
            MediaResult(aResult, "Couldn't start encode process"), __func__);
      });
}

/* static */
RefPtr<GenericNonExclusivePromise>
RemoteMediaManagerChild::LaunchRDDProcessIfNeeded() {
  MOZ_DIAGNOSTIC_ASSERT(XRE_IsContentProcess(),
                        "Only supported from a content process.");

  nsCOMPtr<nsISerialEventTarget> managerThread = GetManagerThread();
  if (!managerThread) {
    // We got shutdown.
    return GenericNonExclusivePromise::CreateAndReject(NS_ERROR_FAILURE,
                                                       __func__);
  }

  StaticMutexAutoLock lock(sLaunchMutex);
  auto& rddLaunchPromise = sLaunchPromises[RemoteMediaIn::RddProcess];
  if (rddLaunchPromise) {
    return rddLaunchPromise;
  }

  // We have a couple possible states here.  We are in a content process
  // and:
  // 1) the RDD process has never been launched.  RDD should be launched
  //    and the IPC connections setup.
  // 2) the RDD process has been launched, but this particular content
  //    process has not setup (or has lost) its IPC connection.
  // In the code below, we assume we need to launch the RDD process and
  // setup the IPC connections.  However, if the manager thread for
  // RemoteMediaManagerChild is available we do a quick check to see
  // if we can send (meaning the IPC channel is open).  If we can send,
  // then no work is necessary.  If we can't send, then we call
  // LaunchRDDProcess which will launch RDD if necessary, and setup the
  // IPC connections between *this* content process and the RDD process.

  RefPtr<GenericNonExclusivePromise> p = InvokeAsync(
      managerThread, __func__, []() -> RefPtr<GenericNonExclusivePromise> {
        auto* rps = GetSingleton(RemoteMediaIn::RddProcess);
        if (rps && rps->CanSend()) {
          return GenericNonExclusivePromise::CreateAndResolve(true, __func__);
        }
        nsCOMPtr<nsISerialEventTarget> managerThread = GetManagerThread();
        ipc::PBackgroundChild* bgActor =
            ipc::BackgroundChild::GetForCurrentThread();
        if (!managerThread || NS_WARN_IF(!bgActor)) {
          return GenericNonExclusivePromise::CreateAndReject(NS_ERROR_FAILURE,
                                                             __func__);
        }

        return bgActor->SendEnsureRDDProcessAndCreateBridge()->Then(
            managerThread, __func__,
            [](ipc::PBackgroundChild::EnsureRDDProcessAndCreateBridgePromise::
                   ResolveOrRejectValue&& aResult) {
              nsCOMPtr<nsISerialEventTarget> managerThread = GetManagerThread();
              if (!managerThread || aResult.IsReject()) {
                // The parent process died or we got shutdown
                return GenericNonExclusivePromise::CreateAndReject(
                    NS_ERROR_FAILURE, __func__);
              }
              nsresult rv = std::get<0>(aResult.ResolveValue());
              if (NS_FAILED(rv)) {
                return GenericNonExclusivePromise::CreateAndReject(rv,
                                                                   __func__);
              }
              OpenRemoteMediaManagerChildForProcess(
                  std::get<1>(std::move(aResult.ResolveValue())),
                  RemoteMediaIn::RddProcess);
              return GenericNonExclusivePromise::CreateAndResolve(true,
                                                                  __func__);
            });
      });

  // This should not be dispatched to a threadpool thread, so use managerThread
  p = p->Then(
      managerThread, __func__,
      [](const GenericNonExclusivePromise::ResolveOrRejectValue& aResult) {
        StaticMutexAutoLock lock(sLaunchMutex);
        sLaunchPromises[RemoteMediaIn::RddProcess] = nullptr;
        return GenericNonExclusivePromise::CreateAndResolveOrReject(aResult,
                                                                    __func__);
      });

  rddLaunchPromise = p;
  return rddLaunchPromise;
}

/* static */
RefPtr<GenericNonExclusivePromise>
RemoteMediaManagerChild::LaunchUtilityProcessIfNeeded(RemoteMediaIn aLocation) {
  MOZ_DIAGNOSTIC_ASSERT(XRE_IsContentProcess(),
                        "Only supported from a content process.");

  nsCOMPtr<nsISerialEventTarget> managerThread = GetManagerThread();
  if (!managerThread) {
    // We got shutdown.
    return GenericNonExclusivePromise::CreateAndReject(NS_ERROR_FAILURE,
                                                       __func__);
  }

  MOZ_ASSERT(aLocation == RemoteMediaIn::UtilityProcess_Generic ||
             aLocation == RemoteMediaIn::UtilityProcess_AppleMedia ||
             aLocation == RemoteMediaIn::UtilityProcess_WMF ||
             aLocation == RemoteMediaIn::UtilityProcess_MFMediaEngineCDM);
  StaticMutexAutoLock lock(sLaunchMutex);
  auto& utilityLaunchPromise = sLaunchPromises[aLocation];

  if (utilityLaunchPromise) {
    return utilityLaunchPromise;
  }

  // We have a couple possible states here.  We are in a content process
  // and:
  // 1) the Utility process has never been launched.  Utility should be launched
  //    and the IPC connections setup.
  // 2) the Utility process has been launched, but this particular content
  //    process has not setup (or has lost) its IPC connection.
  // In the code below, we assume we need to launch the Utility process and
  // setup the IPC connections.  However, if the manager thread for
  // RemoteMediaManagerChild is available we do a quick check to see
  // if we can send (meaning the IPC channel is open).  If we can send,
  // then no work is necessary.  If we can't send, then we call
  // LaunchUtilityProcess which will launch Utility if necessary, and setup the
  // IPC connections between *this* content process and the Utility process.

  RefPtr<GenericNonExclusivePromise> p = InvokeAsync(
      managerThread, __func__,
      [aLocation]() -> RefPtr<GenericNonExclusivePromise> {
        auto* rps = GetSingleton(aLocation);
        if (rps && rps->CanSend()) {
          return GenericNonExclusivePromise::CreateAndResolve(true, __func__);
        }
        nsCOMPtr<nsISerialEventTarget> managerThread = GetManagerThread();
        ipc::PBackgroundChild* bgActor =
            ipc::BackgroundChild::GetForCurrentThread();
        if (!managerThread || NS_WARN_IF(!bgActor)) {
          return GenericNonExclusivePromise::CreateAndReject(NS_ERROR_FAILURE,
                                                             __func__);
        }

        return bgActor->SendEnsureUtilityProcessAndCreateBridge(aLocation)
            ->Then(managerThread, __func__,
                   [aLocation](ipc::PBackgroundChild::
                                   EnsureUtilityProcessAndCreateBridgePromise::
                                       ResolveOrRejectValue&& aResult)
                       -> RefPtr<GenericNonExclusivePromise> {
                     nsCOMPtr<nsISerialEventTarget> managerThread =
                         GetManagerThread();
                     if (!managerThread || aResult.IsReject()) {
                       // The parent process died or we got shutdown
                       return GenericNonExclusivePromise::CreateAndReject(
                           NS_ERROR_FAILURE, __func__);
                     }
                     nsresult rv = std::get<0>(aResult.ResolveValue());
                     if (NS_FAILED(rv)) {
                       return GenericNonExclusivePromise::CreateAndReject(
                           rv, __func__);
                     }
                     OpenRemoteMediaManagerChildForProcess(
                         std::get<1>(std::move(aResult.ResolveValue())),
                         aLocation);
                     return GenericNonExclusivePromise::CreateAndResolve(
                         true, __func__);
                   });
      });

  // Let's make sure this promise is also run on the managerThread to avoid
  // situations where it would be run on a threadpool thread.
  // During bug 1794988 this was happening when enabling Utility for audio on
  // Android when running the sequence of tests
  //   dom/media/test/test_access_control.html
  //   dom/media/test/test_arraybuffer.html
  //
  // We would have a launched utility process but the promises would not have
  // been cleared, so any subsequent tentative to perform audio decoding would
  // think the process is not yet ran and it would try to wait on the pending
  // promises.
  p = p->Then(
      managerThread, __func__,
      [aLocation](
          const GenericNonExclusivePromise::ResolveOrRejectValue& aResult) {
        StaticMutexAutoLock lock(sLaunchMutex);
        sLaunchPromises[aLocation] = nullptr;
        return GenericNonExclusivePromise::CreateAndResolveOrReject(aResult,
                                                                    __func__);
      });
  utilityLaunchPromise = p;
  return utilityLaunchPromise;
}

/* static */
TrackSupportSet RemoteMediaManagerChild::GetTrackSupport(
    RemoteMediaIn aLocation) {
  TrackSupportSet s{TrackSupport::None};
  switch (aLocation) {
    case RemoteMediaIn::GpuProcess:
      s = TrackSupport::DecodeVideo;
      if (StaticPrefs::media_use_remote_encoder_video()) {
        s += TrackSupport::EncodeVideo;
      }
      break;
    case RemoteMediaIn::RddProcess:
      s = TrackSupport::DecodeVideo;
      if (StaticPrefs::media_use_remote_encoder_video()) {
        s += TrackSupport::EncodeVideo;
      }
#ifndef ANDROID
      // Only use RDD for audio coding if we don't have the utility process. If
      // we have a CDM (which we can't determine here) on Android, then we want
      // to perform both the video and audio decoding in the RDD so that they
      // can share the CDM instance.
      if (!StaticPrefs::media_utility_process_enabled())
#endif
      {
        s += TrackSupport::DecodeAudio;
        if (StaticPrefs::media_use_remote_encoder_audio()) {
          s += TrackSupport::EncodeAudio;
        }
      }
      break;
    case RemoteMediaIn::UtilityProcess_Generic:
    case RemoteMediaIn::UtilityProcess_AppleMedia:
    case RemoteMediaIn::UtilityProcess_WMF:
      if (StaticPrefs::media_utility_process_enabled()) {
        s = TrackSupport::DecodeAudio;
        if (StaticPrefs::media_use_remote_encoder_audio()) {
          s += TrackSupport::EncodeAudio;
        }
      }
      break;
    case RemoteMediaIn::UtilityProcess_MFMediaEngineCDM:
#ifdef MOZ_WMF_MEDIA_ENGINE
      // When we enable the media engine, it would need both tracks to
      // synchronize the a/v playback.
      if (StaticPrefs::media_wmf_media_engine_enabled()) {
        s = TrackSupportSet{TrackSupport::DecodeAudio,
                            TrackSupport::DecodeVideo};
      }
#endif
      break;
    default:
      MOZ_ASSERT_UNREACHABLE("Undefined location!");
      break;
  }
  return s;
}

PRemoteDecoderChild* RemoteMediaManagerChild::AllocPRemoteDecoderChild(
    const RemoteDecoderInfoIPDL& /* not used */,
    const CreateDecoderParams::OptionSet& aOptions,
    const Maybe<layers::TextureFactoryIdentifier>& aIdentifier,
    const Maybe<uint64_t>& aMediaEngineId, const Maybe<TrackingId>& aTrackingId,
    PRemoteCDMChild* aCDM) {
  // RemoteDecoderModule is responsible for creating RemoteDecoderChild
  // classes.
  MOZ_ASSERT(false,
             "RemoteMediaManagerChild cannot create "
             "RemoteDecoderChild classes");
  return nullptr;
}

bool RemoteMediaManagerChild::DeallocPRemoteDecoderChild(
    PRemoteDecoderChild* actor) {
  RemoteDecoderChild* child = static_cast<RemoteDecoderChild*>(actor);
  child->IPDLActorDestroyed();
  return true;
}

PMFMediaEngineChild* RemoteMediaManagerChild::AllocPMFMediaEngineChild() {
  MOZ_ASSERT_UNREACHABLE(
      "RemoteMediaManagerChild cannot create MFMediaEngineChild classes");
  return nullptr;
}

bool RemoteMediaManagerChild::DeallocPMFMediaEngineChild(
    PMFMediaEngineChild* actor) {
#ifdef MOZ_WMF_MEDIA_ENGINE
  MFMediaEngineChild* child = static_cast<MFMediaEngineChild*>(actor);
  child->IPDLActorDestroyed();
#endif
  return true;
}

PMFCDMChild* RemoteMediaManagerChild::AllocPMFCDMChild(const nsAString&) {
  MOZ_ASSERT_UNREACHABLE(
      "RemoteMediaManagerChild cannot create PMFContentDecryptionModuleChild "
      "classes");
  return nullptr;
}

bool RemoteMediaManagerChild::DeallocPMFCDMChild(PMFCDMChild* actor) {
#ifdef MOZ_WMF_CDM
  static_cast<MFCDMChild*>(actor)->IPDLActorDestroyed();
#endif
  return true;
}

RemoteMediaManagerChild::RemoteMediaManagerChild(RemoteMediaIn aLocation)
    : mLocation(aLocation) {
  MOZ_ASSERT(mLocation == RemoteMediaIn::GpuProcess ||
             mLocation == RemoteMediaIn::RddProcess ||
             mLocation == RemoteMediaIn::UtilityProcess_Generic ||
             mLocation == RemoteMediaIn::UtilityProcess_AppleMedia ||
             mLocation == RemoteMediaIn::UtilityProcess_WMF ||
             mLocation == RemoteMediaIn::UtilityProcess_MFMediaEngineCDM);
}

/* static */
void RemoteMediaManagerChild::OpenRemoteMediaManagerChildForProcess(
    Endpoint<PRemoteMediaManagerChild>&& aEndpoint, RemoteMediaIn aLocation) {
  nsCOMPtr<nsISerialEventTarget> managerThread = GetManagerThread();
  if (!managerThread) {
    // We've been shutdown, bail.
    return;
  }
  MOZ_ASSERT(managerThread->IsOnCurrentThread());

  // For GPU process, make sure we always dispatch everything in sRecreateTasks,
  // even if we fail since this is as close to being recreated as we will ever
  // be.
  auto runRecreateTasksIfNeeded = MakeScopeExit([aLocation]() {
    if (aLocation == RemoteMediaIn::GpuProcess) {
      for (Runnable* task : *sRecreateTasks) {
        task->Run();
      }
      sRecreateTasks->Clear();
    }
  });

  // Only create RemoteMediaManagerChild, bind new endpoint and init
  // ipdl if:
  // 1) haven't init'd sRemoteMediaManagerChildForProcesses[aLocation]
  // or
  // 2) if ActorDestroy was called meaning the other end of the ipc channel was
  //    torn down
  // But for GPU process, we always recreate a new manager child.
  MOZ_ASSERT(aLocation != RemoteMediaIn::SENTINEL);
  auto& remoteDecoderManagerChild =
      sRemoteMediaManagerChildForProcesses[aLocation];
  if (aLocation != RemoteMediaIn::GpuProcess && remoteDecoderManagerChild &&
      remoteDecoderManagerChild->CanSend()) {
    return;
  }
  remoteDecoderManagerChild = nullptr;
  if (aEndpoint.IsValid()) {
    RefPtr<RemoteMediaManagerChild> manager =
        new RemoteMediaManagerChild(aLocation);
    if (aEndpoint.Bind(manager)) {
      remoteDecoderManagerChild = manager;
    }
  }
}

bool RemoteMediaManagerChild::DeallocShmem(mozilla::ipc::Shmem& aShmem) {
  nsCOMPtr<nsISerialEventTarget> managerThread = GetManagerThread();
  if (!managerThread) {
    return false;
  }
  if (!managerThread->IsOnCurrentThread()) {
    MOZ_ALWAYS_SUCCEEDS(managerThread->Dispatch(NS_NewRunnableFunction(
        "RemoteMediaManagerChild::DeallocShmem",
        [self = RefPtr{this}, shmem = aShmem]() mutable {
          if (self->CanSend()) {
            self->PRemoteMediaManagerChild::DeallocShmem(shmem);
          }
        })));
    return true;
  }
  return PRemoteMediaManagerChild::DeallocShmem(aShmem);
}

struct SurfaceDescriptorUserData {
  SurfaceDescriptorUserData(RemoteMediaManagerChild* aAllocator,
                            SurfaceDescriptor& aSD)
      : mAllocator(aAllocator), mSD(aSD) {}
  ~SurfaceDescriptorUserData() { DestroySurfaceDescriptor(mAllocator, &mSD); }

  RefPtr<RemoteMediaManagerChild> mAllocator;
  SurfaceDescriptor mSD;
};

void DeleteSurfaceDescriptorUserData(void* aClosure) {
  SurfaceDescriptorUserData* sd =
      reinterpret_cast<SurfaceDescriptorUserData*>(aClosure);
  delete sd;
}

already_AddRefed<SourceSurface> RemoteMediaManagerChild::Readback(
    const SurfaceDescriptorGPUVideo& aSD) {
  // We can't use NS_DispatchAndSpinEventLoopUntilComplete here since that will
  // spin the event loop while it waits. This function can be called from JS and
  // we don't want that to happen.
  nsCOMPtr<nsISerialEventTarget> managerThread = GetManagerThread();
  if (!managerThread) {
    return nullptr;
  }

  SurfaceDescriptor sd;
  RefPtr<Runnable> task =
      NS_NewRunnableFunction("RemoteMediaManagerChild::Readback", [&]() {
        if (CanSend()) {
          SendReadback(aSD, &sd);
        }
      });
  SyncRunnable::DispatchToThread(managerThread, task);

  if (!IsSurfaceDescriptorValid(sd)) {
    return nullptr;
  }

  RefPtr<DataSourceSurface> source = GetSurfaceForDescriptor(sd);
  if (!source) {
    DestroySurfaceDescriptor(this, &sd);
    NS_WARNING("Failed to map SurfaceDescriptor in Readback");
    return nullptr;
  }

  static UserDataKey sSurfaceDescriptor;
  source->AddUserData(&sSurfaceDescriptor,
                      new SurfaceDescriptorUserData(this, sd),
                      DeleteSurfaceDescriptorUserData);

  return source.forget();
}

already_AddRefed<Image> RemoteMediaManagerChild::TransferToImage(
    const SurfaceDescriptorGPUVideo& aSD, const IntSize& aSize,
    const ColorDepth& aColorDepth, YUVColorSpace aYUVColorSpace,
    ColorSpace2 aColorPrimaries, TransferFunction aTransferFunction,
    ColorRange aColorRange) {
  // The Image here creates a TextureData object that takes ownership
  // of the SurfaceDescriptor, and is responsible for making sure that
  // it gets deallocated.
  SurfaceDescriptorGPUVideo sd(aSD);
  sd.get_SurfaceDescriptorRemoteDecoder().source() =
      Some(GetVideoBridgeSourceFromRemoteMediaIn(mLocation));
  return MakeAndAddRef<GPUVideoImage>(this, sd, aSize, aColorDepth,
                                      aYUVColorSpace, aColorPrimaries,
                                      aTransferFunction, aColorRange);
}

void RemoteMediaManagerChild::DeallocateSurfaceDescriptor(
    const SurfaceDescriptorGPUVideo& aSD) {
  nsCOMPtr<nsISerialEventTarget> managerThread = GetManagerThread();
  if (!managerThread) {
    return;
  }
  MOZ_ALWAYS_SUCCEEDS(managerThread->Dispatch(NS_NewRunnableFunction(
      "RemoteMediaManagerChild::DeallocateSurfaceDescriptor",
      [ref = RefPtr{this}, sd = aSD]() {
        if (ref->CanSend()) {
          ref->SendDeallocateSurfaceDescriptorGPUVideo(sd);
        }
      })));
}

void RemoteMediaManagerChild::OnSetCurrent(
    const SurfaceDescriptorGPUVideo& aSD) {
  nsCOMPtr<nsISerialEventTarget> managerThread = GetManagerThread();
  if (!managerThread) {
    return;
  }
  MOZ_ALWAYS_SUCCEEDS(managerThread->Dispatch(
      NS_NewRunnableFunction("RemoteMediaManagerChild::OnSetCurrent",
                             [ref = RefPtr{this}, sd = aSD]() {
                               if (ref->CanSend()) {
                                 ref->SendOnSetCurrent(sd);
                               }
                             })));
}

/* static */ void RemoteMediaManagerChild::HandleRejectionError(
    const RemoteMediaManagerChild* aDyingManager, RemoteMediaIn aLocation,
    const ipc::ResponseRejectReason& aReason,
    std::function<void(const MediaResult&)>&& aCallback) {
  // If the channel goes down and CanSend() returns false, the IPDL promise will
  // be rejected with SendError rather than ActorDestroyed. Both means the same
  // thing and we can consider that the parent has crashed. The child can no
  // longer be used.

  if (aLocation == RemoteMediaIn::GpuProcess) {
    // The GPU process will get automatically restarted by the parent process.
    // Once it has been restarted the ContentChild will receive the message and
    // will call GetManager()->InitForGPUProcess.
    // We defer reporting an error until we've recreated the RemoteDecoder
    // manager so that it'll be safe for MediaFormatReader to recreate decoders
    RunWhenGPUProcessRecreated(
        aDyingManager,
        NS_NewRunnableFunction(
            "RemoteMediaManagerChild::HandleRejectionError",
            [callback = std::move(aCallback)]() {
              MediaResult error(
                  NS_ERROR_DOM_MEDIA_REMOTE_CRASHED_RDD_OR_GPU_ERR, __func__);
              callback(error);
            }));
    return;
  }

  nsresult err = NS_ERROR_DOM_MEDIA_REMOTE_CRASHED_UTILITY_ERR;
  if (aLocation == RemoteMediaIn::RddProcess) {
    err = NS_ERROR_DOM_MEDIA_REMOTE_CRASHED_RDD_OR_GPU_ERR;
  } else if (aLocation == RemoteMediaIn::UtilityProcess_MFMediaEngineCDM) {
    err = NS_ERROR_DOM_MEDIA_REMOTE_CRASHED_MF_CDM_ERR;
  }
  // The RDD/utility process is restarted on demand and asynchronously, we can
  // immediately inform the caller that a new en/decoder is needed. The process
  // will then be restarted during the new en/decoder creation by
  aCallback(MediaResult(err, __func__));
}

void RemoteMediaManagerChild::HandleFatalError(const char* aMsg) {
  dom::ContentChild::FatalErrorIfNotUsingGPUProcess(aMsg, OtherChildID());
}

void RemoteMediaManagerChild::SetSupported(
    RemoteMediaIn aLocation, const media::MediaCodecsSupported& aSupported) {
  switch (aLocation) {
    case RemoteMediaIn::GpuProcess:
    case RemoteMediaIn::RddProcess:
    case RemoteMediaIn::UtilityProcess_AppleMedia:
    case RemoteMediaIn::UtilityProcess_Generic:
    case RemoteMediaIn::UtilityProcess_WMF:
    case RemoteMediaIn::UtilityProcess_MFMediaEngineCDM: {
      StaticMutexAutoLock lock(sProcessSupportedMutex);
      sProcessSupported[aLocation] = Some(aSupported);
      break;
    }
    default:
      MOZ_CRASH("Not to be used for any other process");
  }
}

#undef LOG

}  // namespace mozilla