summaryrefslogtreecommitdiffstats
path: root/gfx/layers/RemoteTextureMap.cpp
blob: 95db67665153252f217e3232ac2357af75e98870 (plain)
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
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
/* -*- 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 "mozilla/layers/RemoteTextureMap.h"

#include <algorithm>
#include <vector>

#include "CompositableHost.h"
#include "mozilla/ipc/ProtocolUtils.h"
#include "mozilla/gfx/gfxVars.h"
#include "mozilla/layers/AsyncImagePipelineManager.h"
#include "mozilla/layers/BufferTexture.h"
#include "mozilla/layers/CompositorThread.h"
#include "mozilla/layers/ImageDataSerializer.h"
#include "mozilla/layers/RemoteTextureHostWrapper.h"
#include "mozilla/layers/TextureClientSharedSurface.h"
#include "mozilla/layers/WebRenderTextureHost.h"
#include "mozilla/StaticPrefs_gfx.h"
#include "mozilla/StaticPrefs_webgl.h"
#include "mozilla/webgpu/ExternalTexture.h"
#include "mozilla/webrender/RenderThread.h"
#include "SharedSurface.h"

namespace mozilla::layers {

RemoteTextureRecycleBin::RemoteTextureRecycleBin(bool aIsShared)
    : mIsShared(aIsShared) {}

RemoteTextureRecycleBin::~RemoteTextureRecycleBin() = default;

RemoteTextureOwnerClient::RemoteTextureOwnerClient(
    const base::ProcessId aForPid)
    : mForPid(aForPid) {}

RemoteTextureOwnerClient::~RemoteTextureOwnerClient() = default;

bool RemoteTextureOwnerClient::IsRegistered(
    const RemoteTextureOwnerId aOwnerId) {
  auto it = mOwnerIds.find(aOwnerId);
  if (it == mOwnerIds.end()) {
    return false;
  }
  return true;
}

void RemoteTextureOwnerClient::RegisterTextureOwner(
    const RemoteTextureOwnerId aOwnerId, bool aSharedRecycling) {
  MOZ_ASSERT(mOwnerIds.find(aOwnerId) == mOwnerIds.end());
  mOwnerIds.emplace(aOwnerId);
  RefPtr<RemoteTextureRecycleBin> recycleBin;
  if (aSharedRecycling) {
    if (!mSharedRecycleBin) {
      mSharedRecycleBin = new RemoteTextureRecycleBin(true);
    }
    recycleBin = mSharedRecycleBin;
  }
  RemoteTextureMap::Get()->RegisterTextureOwner(aOwnerId, mForPid, recycleBin);
}

void RemoteTextureOwnerClient::UnregisterTextureOwner(
    const RemoteTextureOwnerId aOwnerId) {
  auto it = mOwnerIds.find(aOwnerId);
  if (it == mOwnerIds.end()) {
    return;
  }
  mOwnerIds.erase(it);
  RemoteTextureMap::Get()->UnregisterTextureOwner(aOwnerId, mForPid);
}

void RemoteTextureOwnerClient::UnregisterAllTextureOwners() {
  if (mOwnerIds.empty()) {
    return;
  }
  RemoteTextureMap::Get()->UnregisterTextureOwners(mOwnerIds, mForPid);
  mOwnerIds.clear();
  mSharedRecycleBin = nullptr;
}

bool RemoteTextureOwnerClient::WaitForTxn(const RemoteTextureOwnerId aOwnerId,
                                          RemoteTextureTxnType aTxnType,
                                          RemoteTextureTxnId aTxnId) {
  auto it = mOwnerIds.find(aOwnerId);
  if (it == mOwnerIds.end() || !aTxnType || !aTxnId) {
    return false;
  }
  return RemoteTextureMap::Get()->WaitForTxn(aOwnerId, mForPid, aTxnType,
                                             aTxnId);
}

void RemoteTextureOwnerClient::ClearRecycledTextures() {
  RemoteTextureMap::Get()->ClearRecycledTextures(mOwnerIds, mForPid,
                                                 mSharedRecycleBin);
}

void RemoteTextureOwnerClient::NotifyContextLost(
    const RemoteTextureOwnerIdSet* aOwnerIds) {
  if (aOwnerIds) {
    for (const auto& id : *aOwnerIds) {
      if (mOwnerIds.find(id) == mOwnerIds.end()) {
        MOZ_ASSERT_UNREACHABLE("owner id not registered by client");
        return;
      }
    }
  } else {
    aOwnerIds = &mOwnerIds;
  }
  if (aOwnerIds->empty()) {
    return;
  }
  RemoteTextureMap::Get()->NotifyContextLost(*aOwnerIds, mForPid);
}

void RemoteTextureOwnerClient::NotifyContextRestored(
    const RemoteTextureOwnerIdSet* aOwnerIds) {
  if (aOwnerIds) {
    for (const auto& id : *aOwnerIds) {
      if (mOwnerIds.find(id) == mOwnerIds.end()) {
        MOZ_ASSERT_UNREACHABLE("owner id not registered by client");
        return;
      }
    }
  } else {
    aOwnerIds = &mOwnerIds;
  }
  if (aOwnerIds->empty()) {
    return;
  }
  RemoteTextureMap::Get()->NotifyContextRestored(*aOwnerIds, mForPid);
}

void RemoteTextureOwnerClient::PushTexture(
    const RemoteTextureId aTextureId, const RemoteTextureOwnerId aOwnerId,
    UniquePtr<TextureData>&& aTextureData) {
  MOZ_ASSERT(IsRegistered(aOwnerId));

  RefPtr<TextureHost> textureHost = RemoteTextureMap::CreateRemoteTexture(
      aTextureData.get(), TextureFlags::DEFAULT);
  if (!textureHost) {
    MOZ_ASSERT_UNREACHABLE("unexpected to be called");
    return;
  }

  RemoteTextureMap::Get()->PushTexture(aTextureId, aOwnerId, mForPid,
                                       std::move(aTextureData), textureHost,
                                       /* aResourceWrapper */ nullptr);
}

void RemoteTextureOwnerClient::PushTexture(
    const RemoteTextureId aTextureId, const RemoteTextureOwnerId aOwnerId,
    const std::shared_ptr<gl::SharedSurface>& aSharedSurface,
    const gfx::IntSize& aSize, gfx::SurfaceFormat aFormat,
    const SurfaceDescriptor& aDesc) {
  MOZ_ASSERT(IsRegistered(aOwnerId));

  UniquePtr<TextureData> textureData =
      MakeUnique<SharedSurfaceTextureData>(aDesc, aFormat, aSize);
  RefPtr<TextureHost> textureHost = RemoteTextureMap::CreateRemoteTexture(
      textureData.get(), TextureFlags::DEFAULT);
  if (!textureHost) {
    MOZ_ASSERT_UNREACHABLE("unexpected to be called");
    return;
  }

  RemoteTextureMap::Get()->PushTexture(
      aTextureId, aOwnerId, mForPid, std::move(textureData), textureHost,
      SharedResourceWrapper::SharedSurface(aSharedSurface));
}

void RemoteTextureOwnerClient::PushTexture(
    const RemoteTextureId aTextureId, const RemoteTextureOwnerId aOwnerId,
    const std::shared_ptr<webgpu::ExternalTexture>& aExternalTexture,
    const gfx::IntSize& aSize, gfx::SurfaceFormat aFormat,
    const SurfaceDescriptor& aDesc) {
  MOZ_ASSERT(IsRegistered(aOwnerId));

  UniquePtr<TextureData> textureData =
      MakeUnique<SharedSurfaceTextureData>(aDesc, aFormat, aSize);
  RefPtr<TextureHost> textureHost = RemoteTextureMap::CreateRemoteTexture(
      textureData.get(), TextureFlags::DEFAULT);
  if (!textureHost) {
    MOZ_ASSERT_UNREACHABLE("unexpected to be called");
    return;
  }

  RemoteTextureMap::Get()->PushTexture(
      aTextureId, aOwnerId, mForPid, std::move(textureData), textureHost,
      SharedResourceWrapper::ExternalTexture(aExternalTexture));
}

void RemoteTextureOwnerClient::PushDummyTexture(
    const RemoteTextureId aTextureId, const RemoteTextureOwnerId aOwnerId) {
  MOZ_ASSERT(IsRegistered(aOwnerId));

  auto flags = TextureFlags::DEALLOCATE_CLIENT | TextureFlags::REMOTE_TEXTURE |
               TextureFlags::DUMMY_TEXTURE;
  auto* rawData = BufferTextureData::Create(
      gfx::IntSize(1, 1), gfx::SurfaceFormat::B8G8R8A8, gfx::BackendType::SKIA,
      LayersBackend::LAYERS_WR, flags, ALLOC_DEFAULT, nullptr);
  if (!rawData) {
    MOZ_ASSERT_UNREACHABLE("unexpected to be called");
    return;
  }

  auto textureData = UniquePtr<TextureData>(rawData);

  RefPtr<TextureHost> textureHost = RemoteTextureMap::CreateRemoteTexture(
      textureData.get(), TextureFlags::DUMMY_TEXTURE);
  if (!textureHost) {
    MOZ_ASSERT_UNREACHABLE("unexpected to be called");
    return;
  }

  RemoteTextureMap::Get()->PushTexture(aTextureId, aOwnerId, mForPid,
                                       std::move(textureData), textureHost,
                                       /* aResourceWrapper */ nullptr);
}

void RemoteTextureOwnerClient::GetLatestBufferSnapshot(
    const RemoteTextureOwnerId aOwnerId, const mozilla::ipc::Shmem& aDestShmem,
    const gfx::IntSize& aSize) {
  MOZ_ASSERT(IsRegistered(aOwnerId));
  RemoteTextureMap::Get()->GetLatestBufferSnapshot(aOwnerId, mForPid,
                                                   aDestShmem, aSize);
}

UniquePtr<TextureData> RemoteTextureOwnerClient::GetRecycledTextureData(
    const gfx::IntSize& aSize, gfx::SurfaceFormat aFormat,
    TextureType aTextureType, RemoteTextureOwnerId aOwnerId) {
  return RemoteTextureMap::Get()->GetRecycledTextureData(
      aOwnerId, mForPid, mSharedRecycleBin, aSize, aFormat, aTextureType);
}

UniquePtr<TextureData>
RemoteTextureOwnerClient::CreateOrRecycleBufferTextureData(
    const gfx::IntSize& aSize, gfx::SurfaceFormat aFormat,
    RemoteTextureOwnerId aOwnerId) {
  auto texture =
      GetRecycledTextureData(aSize, aFormat, TextureType::Unknown, aOwnerId);
  if (texture) {
    return texture;
  }

  auto flags = TextureFlags::DEALLOCATE_CLIENT | TextureFlags::REMOTE_TEXTURE;
  auto* data = BufferTextureData::Create(aSize, aFormat, gfx::BackendType::SKIA,
                                         LayersBackend::LAYERS_WR, flags,
                                         ALLOC_DEFAULT, nullptr);
  return UniquePtr<TextureData>(data);
}

std::shared_ptr<gl::SharedSurface>
RemoteTextureOwnerClient::GetRecycledSharedSurface(
    const gfx::IntSize& aSize, gfx::SurfaceFormat aFormat,
    SurfaceDescriptor::Type aType, RemoteTextureOwnerId aOwnerId) {
  UniquePtr<SharedResourceWrapper> wrapper =
      RemoteTextureMap::Get()->RemoteTextureMap::GetRecycledSharedTexture(
          aOwnerId, mForPid, mSharedRecycleBin, aSize, aFormat, aType);
  if (!wrapper) {
    return nullptr;
  }
  MOZ_ASSERT(wrapper->mSharedSurface);
  return wrapper->mSharedSurface;
}

std::shared_ptr<webgpu::ExternalTexture>
RemoteTextureOwnerClient::GetRecycledExternalTexture(
    const gfx::IntSize& aSize, gfx::SurfaceFormat aFormat,
    SurfaceDescriptor::Type aType, RemoteTextureOwnerId aOwnerId) {
  UniquePtr<SharedResourceWrapper> wrapper =
      RemoteTextureMap::Get()->RemoteTextureMap::GetRecycledSharedTexture(
          aOwnerId, mForPid, mSharedRecycleBin, aSize, aFormat, aType);
  if (!wrapper) {
    return nullptr;
  }
  MOZ_ASSERT(wrapper->mExternalTexture);
  return wrapper->mExternalTexture;
}

StaticAutoPtr<RemoteTextureMap> RemoteTextureMap::sInstance;

/* static */
void RemoteTextureMap::Init() {
  MOZ_ASSERT(!sInstance);
  sInstance = new RemoteTextureMap();
}

/* static */
void RemoteTextureMap::Shutdown() {
  if (sInstance) {
    sInstance = nullptr;
  }
}

RemoteTextureMap::RemoteTextureMap() : mMonitor("RemoteTextureMap::mMonitor") {}

RemoteTextureMap::~RemoteTextureMap() = default;

bool RemoteTextureMap::RecycleTexture(
    const RefPtr<RemoteTextureRecycleBin>& aRecycleBin,
    TextureDataHolder& aHolder, bool aExpireOldTextures) {
  if (!aHolder.mTextureData ||
      (aHolder.mTextureHost &&
       aHolder.mTextureHost->GetFlags() & TextureFlags::DUMMY_TEXTURE)) {
    return false;
  }

  // Expire old textures so they don't sit in the list forever if unused.
  constexpr size_t kSharedTextureLimit = 21;
  constexpr size_t kTextureLimit = 7;
  while (aRecycleBin->mRecycledTextures.size() >=
         (aRecycleBin->mIsShared ? kSharedTextureLimit : kTextureLimit)) {
    if (!aExpireOldTextures) {
      // There are too many textures, and we can't expire any to make room.
      return false;
    }
    aRecycleBin->mRecycledTextures.pop_front();
  }

  TextureData::Info info;
  aHolder.mTextureData->FillInfo(info);
  RemoteTextureRecycleBin::RecycledTextureHolder recycled{info.size,
                                                          info.format};
  if (aHolder.mResourceWrapper) {
    // Recycle shared texture
    SurfaceDescriptor desc;
    if (!aHolder.mTextureData->Serialize(desc)) {
      return false;
    }
    recycled.mType = desc.type();
    recycled.mResourceWrapper = std::move(aHolder.mResourceWrapper);
  } else {
    // Recycle texture data
    recycled.mTextureData = std::move(aHolder.mTextureData);
  }
  if (!StaticPrefs::gfx_remote_texture_recycle_disabled()) {
    aRecycleBin->mRecycledTextures.push_back(std::move(recycled));
  }

  return true;
}

void RemoteTextureMap::PushTexture(
    const RemoteTextureId aTextureId, const RemoteTextureOwnerId aOwnerId,
    const base::ProcessId aForPid, UniquePtr<TextureData>&& aTextureData,
    RefPtr<TextureHost>& aTextureHost,
    UniquePtr<SharedResourceWrapper>&& aResourceWrapper) {
  MOZ_RELEASE_ASSERT(aTextureHost);

  std::vector<RefPtr<TextureHost>>
      releasingTextures;  // Release outside the monitor
  std::vector<std::function<void(const RemoteTextureInfo&)>>
      renderingReadyCallbacks;  // Call outside the monitor
  {
    MonitorAutoLock lock(mMonitor);

    auto* owner = GetTextureOwner(lock, aOwnerId, aForPid);
    if (!owner) {
      MOZ_ASSERT_UNREACHABLE("unexpected to be called");
      return;
    }

    if (owner->mIsContextLost &&
        !(aTextureHost->GetFlags() & TextureFlags::DUMMY_TEXTURE)) {
      MOZ_ASSERT_UNREACHABLE("unexpected to be called");
      gfxCriticalNoteOnce << "Texture pushed during context lost";
    }

    auto textureData = MakeUnique<TextureDataHolder>(
        aTextureId, aTextureHost, std::move(aTextureData),
        std::move(aResourceWrapper));

    MOZ_ASSERT(owner->mLatestPushedTextureId < aTextureId);
    if (owner->mLatestPushedTextureId < aTextureId) {
      owner->mLatestPushedTextureId = aTextureId;
    }
    MOZ_ASSERT(owner->mLatestUsingTextureId < aTextureId);

    owner->mWaitingTextureDataHolders.push_back(std::move(textureData));

    {
      GetRenderingReadyCallbacks(lock, owner, aTextureId,
                                 renderingReadyCallbacks);
      // Update mRemoteTextureHost.
      // This happens when PushTexture() with RemoteTextureId is called after
      // GetRemoteTexture() with the RemoteTextureId.
      const auto key = std::pair(aForPid, aTextureId);
      auto it = mRemoteTextureHostWrapperHolders.find(key);
      if (it != mRemoteTextureHostWrapperHolders.end()) {
        MOZ_ASSERT(!it->second->mRemoteTextureHost);
        it->second->mRemoteTextureHost = aTextureHost;
      }
    }

    mMonitor.Notify();

    // Release owner->mReleasingRenderedTextureHosts before checking
    // NumCompositableRefs()
    if (!owner->mReleasingRenderedTextureHosts.empty()) {
      std::transform(
          owner->mReleasingRenderedTextureHosts.begin(),
          owner->mReleasingRenderedTextureHosts.end(),
          std::back_inserter(releasingTextures),
          [](CompositableTextureHostRef& aRef) { return aRef.get(); });
      owner->mReleasingRenderedTextureHosts.clear();
    }

    // Drop obsoleted remote textures.
    while (!owner->mUsingTextureDataHolders.empty()) {
      auto& front = owner->mUsingTextureDataHolders.front();
      // If mLatestRenderedTextureHost is last compositable ref of remote
      // texture's TextureHost, its RemoteTextureHostWrapper is already
      // unregistered. It happens when pushed remote textures that follow are
      // not rendered since last mLatestRenderedTextureHost update. In this
      // case, remove the TextureHost from mUsingTextureDataHolders. It is for
      // unblocking remote texture recyclieng.
      if (front->mTextureHost &&
          front->mTextureHost->NumCompositableRefs() == 1 &&
          front->mTextureHost == owner->mLatestRenderedTextureHost) {
        owner->mUsingTextureDataHolders.pop_front();
        continue;
      }
      // When compositable ref of TextureHost becomes 0, the TextureHost is not
      // used by WebRender anymore.
      if (front->mTextureHost &&
          front->mTextureHost->NumCompositableRefs() == 0) {
        owner->mReleasingTextureDataHolders.push_back(std::move(front));
        owner->mUsingTextureDataHolders.pop_front();
      } else if (front->mTextureHost &&
                 front->mTextureHost->NumCompositableRefs() >= 0) {
        // Remote texture is still in use by WebRender.
        break;
      } else {
        MOZ_ASSERT_UNREACHABLE("unexpected to be called");
        owner->mUsingTextureDataHolders.pop_front();
      }
    }
    while (!owner->mReleasingTextureDataHolders.empty()) {
      RecycleTexture(owner->mRecycleBin,
                     *owner->mReleasingTextureDataHolders.front(), true);
      owner->mReleasingTextureDataHolders.pop_front();
    }
  }

  const auto info = RemoteTextureInfo(aTextureId, aOwnerId, aForPid);
  for (auto& callback : renderingReadyCallbacks) {
    callback(info);
  }
}

bool RemoteTextureMap::RemoveTexture(const RemoteTextureId aTextureId,
                                     const RemoteTextureOwnerId aOwnerId,
                                     const base::ProcessId aForPid) {
  MonitorAutoLock lock(mMonitor);

  auto* owner = GetTextureOwner(lock, aOwnerId, aForPid);
  if (!owner) {
    return false;
  }

  for (auto it = owner->mWaitingTextureDataHolders.begin();
       it != owner->mWaitingTextureDataHolders.end(); it++) {
    auto& data = *it;
    if (data->mTextureId == aTextureId) {
      if (mRemoteTextureHostWrapperHolders.find(std::pair(
              aForPid, aTextureId)) != mRemoteTextureHostWrapperHolders.end()) {
        return false;
      }
      if (!RecycleTexture(owner->mRecycleBin, *data, false)) {
        owner->mReleasingTextureDataHolders.push_back(std::move(data));
      }
      owner->mWaitingTextureDataHolders.erase(it);
      return true;
    }
  }

  return false;
}

void RemoteTextureMap::GetLatestBufferSnapshot(
    const RemoteTextureOwnerId aOwnerId, const base::ProcessId aForPid,
    const mozilla::ipc::Shmem& aDestShmem, const gfx::IntSize& aSize) {
  // The compositable ref of remote texture should be updated in mMonitor lock.
  CompositableTextureHostRef textureHostRef;
  RefPtr<TextureHost> releasingTexture;  // Release outside the monitor
  std::shared_ptr<webgpu::ExternalTexture> externalTexture;
  {
    MonitorAutoLock lock(mMonitor);

    auto* owner = GetTextureOwner(lock, aOwnerId, aForPid);
    if (!owner) {
      MOZ_ASSERT_UNREACHABLE("unexpected to be called");
      return;
    }

    // Get latest TextureHost of remote Texture.
    if (owner->mWaitingTextureDataHolders.empty() &&
        owner->mUsingTextureDataHolders.empty()) {
      return;
    }
    const auto* holder = !owner->mWaitingTextureDataHolders.empty()
                             ? owner->mWaitingTextureDataHolders.back().get()
                             : owner->mUsingTextureDataHolders.back().get();
    TextureHost* textureHost = holder->mTextureHost;

    if (textureHost->GetSize() != aSize) {
      MOZ_ASSERT_UNREACHABLE("unexpected to be called");
      return;
    }
    if (textureHost->GetFormat() != gfx::SurfaceFormat::R8G8B8A8 &&
        textureHost->GetFormat() != gfx::SurfaceFormat::B8G8R8A8) {
      MOZ_ASSERT_UNREACHABLE("unexpected to be called");
      return;
    }
    if (holder->mResourceWrapper &&
        holder->mResourceWrapper->mExternalTexture) {
      // Increment compositable ref to prevent that TextureDataHolder is removed
      // during memcpy.
      textureHostRef = textureHost;
      externalTexture = holder->mResourceWrapper->mExternalTexture;
    } else if (textureHost->AsBufferTextureHost()) {
      // Increment compositable ref to prevent that TextureDataHolder is removed
      // during memcpy.
      textureHostRef = textureHost;
    } else {
      MOZ_ASSERT_UNREACHABLE("unexpected to be called");
      return;
    }
  }

  if (!textureHostRef) {
    return;
  }

  if (externalTexture) {
    externalTexture->GetSnapshot(aDestShmem, aSize);
  } else if (auto* bufferTextureHost = textureHostRef->AsBufferTextureHost()) {
    uint32_t stride = ImageDataSerializer::ComputeRGBStride(
        bufferTextureHost->GetFormat(), aSize.width);
    uint32_t bufferSize = stride * aSize.height;
    uint8_t* dst = aDestShmem.get<uint8_t>();
    uint8_t* src = bufferTextureHost->GetBuffer();

    MOZ_ASSERT(bufferSize <= aDestShmem.Size<uint8_t>());
    memcpy(dst, src, bufferSize);
  }

  {
    MonitorAutoLock lock(mMonitor);
    // Release compositable ref in mMonitor lock, but release RefPtr outside the
    // monitor
    releasingTexture = textureHostRef;
    textureHostRef = nullptr;
  }
}

void RemoteTextureMap::RegisterTextureOwner(
    const RemoteTextureOwnerId aOwnerId, const base::ProcessId aForPid,
    const RefPtr<RemoteTextureRecycleBin>& aRecycleBin) {
  MonitorAutoLock lock(mMonitor);

  const auto key = std::pair(aForPid, aOwnerId);
  auto it = mTextureOwners.find(key);
  if (it != mTextureOwners.end()) {
    MOZ_ASSERT_UNREACHABLE("unexpected to be called");
    return;
  }
  auto owner = MakeUnique<TextureOwner>();
  if (aRecycleBin) {
    owner->mRecycleBin = aRecycleBin;
  } else {
    owner->mRecycleBin = new RemoteTextureRecycleBin(false);
  }

  mTextureOwners.emplace(key, std::move(owner));
}

void RemoteTextureMap::KeepTextureDataAliveForTextureHostIfNecessary(
    const MonitorAutoLock& aProofOfLock, RemoteTextureMap::TextureOwner* aOwner,
    std::deque<UniquePtr<TextureDataHolder>>& aHolders) {
  for (auto& holder : aHolders) {
    // If remote texture of TextureHost still exist, keep
    // SharedResourceWrapper/TextureData alive while the TextureHost is alive.
    if (holder->mTextureHost &&
        holder->mTextureHost->NumCompositableRefs() > 0) {
      RefPtr<nsISerialEventTarget> eventTarget = GetCurrentSerialEventTarget();
      RefPtr<Runnable> runnable = NS_NewRunnableFunction(
          "RemoteTextureMap::UnregisterTextureOwner::Runnable",
          [data = std::move(holder->mTextureData),
           wrapper = std::move(holder->mResourceWrapper)]() {});

      auto destroyedCallback = [eventTarget = std::move(eventTarget),
                                runnable = std::move(runnable)]() mutable {
        eventTarget->Dispatch(runnable.forget());
      };

      holder->mTextureHost->SetDestroyedCallback(destroyedCallback);
    } else {
      RecycleTexture(aOwner->mRecycleBin, *holder, true);
    }
  }
}

UniquePtr<RemoteTextureMap::TextureOwner>
RemoteTextureMap::UnregisterTextureOwner(
    MonitorAutoLock& aProofOfLock, const RemoteTextureOwnerId aOwnerId,
    const base::ProcessId aForPid,
    std::vector<RefPtr<TextureHost>>& aReleasingTextures,
    std::vector<std::function<void(const RemoteTextureInfo&)>>&
        aRenderingReadyCallbacks) {
  const auto key = std::pair(aForPid, aOwnerId);
  auto it = mTextureOwners.find(key);
  if (it == mTextureOwners.end()) {
    MOZ_ASSERT_UNREACHABLE("unexpected to be called");
    return nullptr;
  }

  auto* owner = it->second.get();
  // If waiting for a last use, and it hasn't arrived yet, then defer
  // unregistering.
  if (owner->mWaitForTxn) {
    owner->mDeferUnregister = GetCurrentSerialEventTarget();
    // If another thread is waiting on this owner to produce textures,
    // it must be notified that owner is going away.
    if (!owner->mLatestTextureHost &&
        owner->mWaitingTextureDataHolders.empty()) {
      aProofOfLock.Notify();
    }
    return nullptr;
  }

  if (owner->mLatestTextureHost) {
    // Release CompositableRef in mMonitor
    aReleasingTextures.emplace_back(owner->mLatestTextureHost);
    owner->mLatestTextureHost = nullptr;
  }

  // mReleasingRenderedTextureHosts and mLatestRenderedTextureHost could
  // simply be cleared. Since NumCompositableRefs() > 0 keeps TextureHosts in
  // mUsingTextureDataHolders alive. They need to be cleared before
  // KeepTextureDataAliveForTextureHostIfNecessary() call. The function uses
  // NumCompositableRefs().
  if (!owner->mReleasingRenderedTextureHosts.empty()) {
    std::transform(owner->mReleasingRenderedTextureHosts.begin(),
                   owner->mReleasingRenderedTextureHosts.end(),
                   std::back_inserter(aReleasingTextures),
                   [](CompositableTextureHostRef& aRef) { return aRef.get(); });
    owner->mReleasingRenderedTextureHosts.clear();
  }
  if (owner->mLatestRenderedTextureHost) {
    owner->mLatestRenderedTextureHost = nullptr;
  }

  GetAllRenderingReadyCallbacks(aProofOfLock, owner, aRenderingReadyCallbacks);

  KeepTextureDataAliveForTextureHostIfNecessary(
      aProofOfLock, owner, owner->mWaitingTextureDataHolders);

  KeepTextureDataAliveForTextureHostIfNecessary(
      aProofOfLock, owner, owner->mUsingTextureDataHolders);

  KeepTextureDataAliveForTextureHostIfNecessary(
      aProofOfLock, owner, owner->mReleasingTextureDataHolders);

  UniquePtr<TextureOwner> releasingOwner = std::move(it->second);
  mTextureOwners.erase(it);
  return releasingOwner;
}

void RemoteTextureMap::UnregisterTextureOwner(
    const RemoteTextureOwnerId aOwnerId, const base::ProcessId aForPid) {
  UniquePtr<TextureOwner> releasingOwner;  // Release outside the monitor
  std::vector<RefPtr<TextureHost>>
      releasingTextures;  // Release outside the monitor
  std::vector<std::function<void(const RemoteTextureInfo&)>>
      renderingReadyCallbacks;  // Call outside the monitor
  {
    MonitorAutoLock lock(mMonitor);

    releasingOwner = UnregisterTextureOwner(
        lock, aOwnerId, aForPid, releasingTextures, renderingReadyCallbacks);
    if (!releasingOwner) {
      return;
    }

    mMonitor.Notify();
  }

  const auto info =
      RemoteTextureInfo(RemoteTextureId{0}, RemoteTextureOwnerId{0}, 0);
  for (auto& callback : renderingReadyCallbacks) {
    callback(info);
  }
}

void RemoteTextureMap::UnregisterTextureOwners(
    const RemoteTextureOwnerIdSet& aOwnerIds, const base::ProcessId aForPid) {
  std::vector<UniquePtr<TextureOwner>>
      releasingOwners;  // Release outside the monitor
  std::vector<RefPtr<TextureHost>>
      releasingTextures;  // Release outside the monitor
  std::vector<std::function<void(const RemoteTextureInfo&)>>
      renderingReadyCallbacks;  // Call outside the monitor
  {
    MonitorAutoLock lock(mMonitor);

    for (const auto& id : aOwnerIds) {
      if (auto releasingOwner = UnregisterTextureOwner(
              lock, id, aForPid, releasingTextures, renderingReadyCallbacks)) {
        releasingOwners.push_back(std::move(releasingOwner));
      }
    }

    if (releasingOwners.empty()) {
      return;
    }

    mMonitor.Notify();
  }

  const auto info =
      RemoteTextureInfo(RemoteTextureId{0}, RemoteTextureOwnerId{0}, 0);
  for (auto& callback : renderingReadyCallbacks) {
    callback(info);
  }
}

already_AddRefed<RemoteTextureTxnScheduler>
RemoteTextureMap::RegisterTxnScheduler(base::ProcessId aForPid,
                                       RemoteTextureTxnType aType) {
  MonitorAutoLock lock(mMonitor);

  const auto key = std::pair(aForPid, aType);
  auto it = mTxnSchedulers.find(key);
  if (it != mTxnSchedulers.end()) {
    return do_AddRef(it->second);
  }

  RefPtr<RemoteTextureTxnScheduler> scheduler(
      new RemoteTextureTxnScheduler(aForPid, aType));
  mTxnSchedulers.emplace(key, scheduler.get());
  return scheduler.forget();
}

void RemoteTextureMap::UnregisterTxnScheduler(base::ProcessId aForPid,
                                              RemoteTextureTxnType aType) {
  MonitorAutoLock lock(mMonitor);

  const auto key = std::pair(aForPid, aType);
  auto it = mTxnSchedulers.find(key);
  if (it == mTxnSchedulers.end()) {
    MOZ_ASSERT_UNREACHABLE("Remote texture txn scheduler does not exist.");
    return;
  }
  mTxnSchedulers.erase(it);
}

already_AddRefed<RemoteTextureTxnScheduler> RemoteTextureTxnScheduler::Create(
    mozilla::ipc::IProtocol* aProtocol) {
  if (auto* instance = RemoteTextureMap::Get()) {
    if (auto* toplevel = aProtocol->ToplevelProtocol()) {
      auto pid = toplevel->OtherPidMaybeInvalid();
      if (pid != base::kInvalidProcessId) {
        return instance->RegisterTxnScheduler(pid, toplevel->GetProtocolId());
      }
    }
  }
  return nullptr;
}

RemoteTextureTxnScheduler::~RemoteTextureTxnScheduler() {
  NotifyTxn(std::numeric_limits<RemoteTextureTxnId>::max());
  RemoteTextureMap::Get()->UnregisterTxnScheduler(mForPid, mType);
}

void RemoteTextureTxnScheduler::NotifyTxn(RemoteTextureTxnId aTxnId) {
  MonitorAutoLock lock(RemoteTextureMap::Get()->mMonitor);

  mLastTxnId = aTxnId;

  for (; !mWaits.empty(); mWaits.pop_front()) {
    auto& wait = mWaits.front();
    if (wait.mTxnId > aTxnId) {
      break;
    }
    RemoteTextureMap::Get()->NotifyTxn(lock, wait.mOwnerId, mForPid);
  }
}

bool RemoteTextureTxnScheduler::WaitForTxn(const MonitorAutoLock& aProofOfLock,
                                           RemoteTextureOwnerId aOwnerId,
                                           RemoteTextureTxnId aTxnId) {
  if (aTxnId <= mLastTxnId) {
    return false;
  }
  mWaits.insert(std::upper_bound(mWaits.begin(), mWaits.end(), aTxnId),
                Wait{aOwnerId, aTxnId});
  return true;
}

void RemoteTextureMap::ClearRecycledTextures(
    const RemoteTextureOwnerIdSet& aOwnerIds, const base::ProcessId aForPid,
    const RefPtr<RemoteTextureRecycleBin>& aRecycleBin) {
  std::list<RemoteTextureRecycleBin::RecycledTextureHolder>
      releasingTextures;  // Release outside the monitor
  {
    MonitorAutoLock lock(mMonitor);

    if (aRecycleBin) {
      releasingTextures.splice(releasingTextures.end(),
                               aRecycleBin->mRecycledTextures);
    }

    for (const auto& id : aOwnerIds) {
      const auto key = std::pair(aForPid, id);
      auto it = mTextureOwners.find(key);
      if (it == mTextureOwners.end()) {
        MOZ_ASSERT_UNREACHABLE("unexpected to be called");
        continue;
      }
      auto& owner = it->second;

      releasingTextures.splice(releasingTextures.end(),
                               owner->mRecycleBin->mRecycledTextures);
    }
  }
}

void RemoteTextureMap::NotifyContextLost(
    const RemoteTextureOwnerIdSet& aOwnerIds, const base::ProcessId aForPid) {
  MonitorAutoLock lock(mMonitor);

  bool changed = false;
  for (const auto& id : aOwnerIds) {
    const auto key = std::pair(aForPid, id);
    auto it = mTextureOwners.find(key);
    if (it == mTextureOwners.end()) {
      MOZ_ASSERT_UNREACHABLE("unexpected to be called");
      continue;
    }
    auto& owner = it->second;
    if (!owner->mIsContextLost) {
      owner->mIsContextLost = true;
      changed = true;
    }
  }

  if (changed) {
    mMonitor.Notify();
  }
}

void RemoteTextureMap::NotifyContextRestored(
    const RemoteTextureOwnerIdSet& aOwnerIds, const base::ProcessId aForPid) {
  MonitorAutoLock lock(mMonitor);

  bool changed = false;
  for (const auto& id : aOwnerIds) {
    const auto key = std::pair(aForPid, id);
    auto it = mTextureOwners.find(key);
    if (it == mTextureOwners.end()) {
      MOZ_ASSERT_UNREACHABLE("unexpected to be called");
      continue;
    }
    auto& owner = it->second;
    if (owner->mIsContextLost) {
      owner->mIsContextLost = false;
      changed = true;
    }
  }

  if (changed) {
    mMonitor.Notify();
  }
}

/* static */
RefPtr<TextureHost> RemoteTextureMap::CreateRemoteTexture(
    TextureData* aTextureData, TextureFlags aTextureFlags) {
  SurfaceDescriptor desc;
  DebugOnly<bool> ret = aTextureData->Serialize(desc);
  MOZ_ASSERT(ret);
  TextureFlags flags = aTextureFlags | TextureFlags::REMOTE_TEXTURE |
                       TextureFlags::DEALLOCATE_CLIENT;

  Maybe<wr::ExternalImageId> externalImageId = Nothing();
  RefPtr<TextureHost> textureHost =
      TextureHost::Create(desc, null_t(), nullptr, LayersBackend::LAYERS_WR,
                          flags, externalImageId);
  MOZ_ASSERT(textureHost);
  if (!textureHost) {
    gfxCriticalNoteOnce << "Failed to create remote texture";
    return nullptr;
  }

  textureHost->EnsureRenderTexture(Nothing());

  return textureHost;
}

void RemoteTextureMap::UpdateTexture(const MonitorAutoLock& aProofOfLock,
                                     RemoteTextureMap::TextureOwner* aOwner,
                                     const RemoteTextureId aTextureId) {
  MOZ_ASSERT(CompositorThreadHolder::IsInCompositorThread());
  MOZ_ASSERT(aOwner);
  MOZ_ASSERT(aTextureId >= aOwner->mLatestUsingTextureId);

  if (aTextureId == aOwner->mLatestUsingTextureId) {
    // No need to update texture.
    return;
  }

  // Move remote textures to mUsingTextureDataHolders.
  while (!aOwner->mWaitingTextureDataHolders.empty()) {
    auto& front = aOwner->mWaitingTextureDataHolders.front();
    if (aTextureId < front->mTextureId) {
      break;
    }
    MOZ_RELEASE_ASSERT(front->mTextureHost);
    aOwner->mLatestTextureHost = front->mTextureHost;
    aOwner->mLatestUsingTextureId = front->mTextureId;

    UniquePtr<TextureDataHolder> holder = std::move(front);
    aOwner->mWaitingTextureDataHolders.pop_front();
    // If there are textures not being used by the compositor that will be
    // obsoleted by this new texture, then queue them for removal later on
    // the creating thread.
    while (!aOwner->mUsingTextureDataHolders.empty()) {
      auto& back = aOwner->mUsingTextureDataHolders.back();
      if (back->mTextureHost &&
          back->mTextureHost->NumCompositableRefs() == 0) {
        if (!RecycleTexture(aOwner->mRecycleBin, *back, false)) {
          aOwner->mReleasingTextureDataHolders.push_back(std::move(back));
        }
        aOwner->mUsingTextureDataHolders.pop_back();
        continue;
      }
      break;
    }
    aOwner->mUsingTextureDataHolders.push_back(std::move(holder));
  }
}

void RemoteTextureMap::GetRenderingReadyCallbacks(
    const MonitorAutoLock& aProofOfLock, RemoteTextureMap::TextureOwner* aOwner,
    const RemoteTextureId aTextureId,
    std::vector<std::function<void(const RemoteTextureInfo&)>>& aFunctions) {
  MOZ_ASSERT(aOwner);

  while (!aOwner->mRenderingReadyCallbackHolders.empty()) {
    auto& front = aOwner->mRenderingReadyCallbackHolders.front();
    if (aTextureId < front->mTextureId) {
      break;
    }
    if (front->mCallback) {
      aFunctions.push_back(std::move(front->mCallback));
    }
    aOwner->mRenderingReadyCallbackHolders.pop_front();
  }
}

void RemoteTextureMap::GetAllRenderingReadyCallbacks(
    const MonitorAutoLock& aProofOfLock, RemoteTextureMap::TextureOwner* aOwner,
    std::vector<std::function<void(const RemoteTextureInfo&)>>& aFunctions) {
  GetRenderingReadyCallbacks(aProofOfLock, aOwner, RemoteTextureId::Max(),
                             aFunctions);
  MOZ_ASSERT(aOwner->mRenderingReadyCallbackHolders.empty());
}

bool RemoteTextureMap::WaitForRemoteTextureOwner(
    RemoteTextureHostWrapper* aTextureHostWrapper) {
  MOZ_ASSERT(CompositorThreadHolder::IsInCompositorThread());
  MOZ_ASSERT(aTextureHostWrapper);

  const auto& ownerId = aTextureHostWrapper->mOwnerId;
  const auto& forPid = aTextureHostWrapper->mForPid;

  MonitorAutoLock lock(mMonitor);

  auto* owner = GetTextureOwner(lock, ownerId, forPid);
  // If there is no texture owner yet, then we might need to wait for one to
  // be created, if allowed. If so, we must also wait for an initial texture
  // host to be created so we can use it.
  if (!owner || (!owner->mLatestTextureHost &&
                 owner->mWaitingTextureDataHolders.empty())) {
    const TimeDuration timeout = TimeDuration::FromMilliseconds(10000);
    while (!owner || (!owner->mLatestTextureHost &&
                      owner->mWaitingTextureDataHolders.empty())) {
      if (owner && (owner->mIsContextLost || owner->mDeferUnregister)) {
        // If the context was lost, no further updates are expected.
        return false;
      }
      CVStatus status = mMonitor.Wait(timeout);
      if (status == CVStatus::Timeout) {
        return false;
      }
      owner = GetTextureOwner(lock, ownerId, forPid);
    }
  }
  return true;
}

bool RemoteTextureMap::GetRemoteTexture(
    RemoteTextureHostWrapper* aTextureHostWrapper,
    std::function<void(const RemoteTextureInfo&)>&& aReadyCallback) {
  MOZ_ASSERT(CompositorThreadHolder::IsInCompositorThread());
  MOZ_ASSERT(aTextureHostWrapper);

  if (aTextureHostWrapper->IsReadyForRendering()) {
    return false;
  }

  const auto& textureId = aTextureHostWrapper->mTextureId;
  const auto& ownerId = aTextureHostWrapper->mOwnerId;
  const auto& forPid = aTextureHostWrapper->mForPid;
  const auto& size = aTextureHostWrapper->mSize;

  RefPtr<TextureHost> textureHost;
  {
    MonitorAutoLock lock(mMonitor);

    auto* owner = GetTextureOwner(lock, ownerId, forPid);
    if (!owner) {
      return false;
    }

    UpdateTexture(lock, owner, textureId);

    if (owner->mLatestTextureHost &&
        (owner->mLatestTextureHost->GetFlags() & TextureFlags::DUMMY_TEXTURE)) {
      // Remote texture allocation was failed.
      return false;
    }

    if (textureId == owner->mLatestUsingTextureId) {
      MOZ_ASSERT(owner->mLatestTextureHost);
      MOZ_ASSERT(owner->mLatestTextureHost->GetSize() == size);
      if (owner->mLatestTextureHost->GetSize() != size) {
        gfxCriticalNoteOnce << "unexpected remote texture size: "
                            << owner->mLatestTextureHost->GetSize()
                            << " expected: " << size;
      }
      textureHost = owner->mLatestTextureHost;
    } else {
      if (aReadyCallback) {
        auto callbackHolder = MakeUnique<RenderingReadyCallbackHolder>(
            textureId, std::move(aReadyCallback));
        owner->mRenderingReadyCallbackHolders.push_back(
            std::move(callbackHolder));
        return true;
      }
    }

    // Update mRemoteTextureHost
    if (textureId == owner->mLatestUsingTextureId) {
      const auto key = std::pair(forPid, textureId);
      auto it = mRemoteTextureHostWrapperHolders.find(key);
      if (it != mRemoteTextureHostWrapperHolders.end() &&
          !it->second->mRemoteTextureHost) {
        it->second->mRemoteTextureHost = owner->mLatestTextureHost;
      } else {
        MOZ_ASSERT(it->second->mRemoteTextureHost == owner->mLatestTextureHost);
      }
    }

    if (textureHost) {
      aTextureHostWrapper->SetRemoteTextureHost(lock, textureHost);
      aTextureHostWrapper->ApplyTextureFlagsToRemoteTexture();
    }
  }

  return false;
}

void RemoteTextureMap::NotifyTxn(const MonitorAutoLock& aProofOfLock,
                                 const RemoteTextureOwnerId aOwnerId,
                                 const base::ProcessId aForPid) {
  if (auto* owner = GetTextureOwner(aProofOfLock, aOwnerId, aForPid)) {
    if (!owner->mWaitForTxn) {
      MOZ_ASSERT_UNREACHABLE("Expected texture owner to wait for txn.");
      return;
    }
    owner->mWaitForTxn = false;
    if (!owner->mDeferUnregister) {
      // If unregistering was not deferred, then don't try to force
      // unregistering yet.
      return;
    }
    owner->mDeferUnregister->Dispatch(NS_NewRunnableFunction(
        "RemoteTextureMap::SetLastRemoteTextureUse::Runnable",
        [aOwnerId, aForPid]() {
          RemoteTextureMap::Get()->UnregisterTextureOwner(aOwnerId, aForPid);
        }));
  }
}

bool RemoteTextureMap::WaitForTxn(const RemoteTextureOwnerId aOwnerId,
                                  const base::ProcessId aForPid,
                                  RemoteTextureTxnType aTxnType,
                                  RemoteTextureTxnId aTxnId) {
  MonitorAutoLock lock(mMonitor);
  if (auto* owner = GetTextureOwner(lock, aOwnerId, aForPid)) {
    if (owner->mDeferUnregister) {
      MOZ_ASSERT_UNREACHABLE(
          "Texture owner must wait for txn before unregistering.");
      return false;
    }
    if (owner->mWaitForTxn) {
      MOZ_ASSERT_UNREACHABLE("Texture owner already waiting for txn.");
      return false;
    }
    const auto key = std::pair(aForPid, aTxnType);
    auto it = mTxnSchedulers.find(key);
    if (it == mTxnSchedulers.end()) {
      // During shutdown, different toplevel protocols may go away in
      // disadvantageous orders, causing us to sometimes be processing
      // waits even though the source of transactions upon which the
      // wait depends shut down. This is generally harmless to ignore,
      // as it means no further transactions will be generated of that
      // type and all such transactions have been processed before it
      // unregistered.
      NS_WARNING("Could not find scheduler for txn type.");
      return false;
    }
    if (it->second->WaitForTxn(lock, aOwnerId, aTxnId)) {
      owner->mWaitForTxn = true;
    }
    return true;
  }
  return false;
}

void RemoteTextureMap::ReleaseRemoteTextureHost(
    RemoteTextureHostWrapper* aTextureHostWrapper) {
  MOZ_ASSERT(CompositorThreadHolder::IsInCompositorThread());
  MOZ_ASSERT(aTextureHostWrapper);

  RefPtr<TextureHost> releasingTexture;  // Release outside the mutex
  {
    MonitorAutoLock lock(mMonitor);
    releasingTexture = aTextureHostWrapper->GetRemoteTextureHost(lock);
    aTextureHostWrapper->ClearRemoteTextureHost(lock);
  }
}

RefPtr<TextureHost> RemoteTextureMap::GetOrCreateRemoteTextureHostWrapper(
    const RemoteTextureId aTextureId, const RemoteTextureOwnerId aOwnerId,
    const base::ProcessId aForPid, const gfx::IntSize& aSize,
    const TextureFlags aFlags) {
  MOZ_ASSERT(CompositorThreadHolder::IsInCompositorThread());
  MonitorAutoLock lock(mMonitor);

  const auto key = std::pair(aForPid, aTextureId);
  auto it = mRemoteTextureHostWrapperHolders.find(key);
  if (it != mRemoteTextureHostWrapperHolders.end()) {
    return it->second->mRemoteTextureHostWrapper;
  }

  auto wrapper = RemoteTextureHostWrapper::Create(aTextureId, aOwnerId, aForPid,
                                                  aSize, aFlags);
  auto wrapperHolder = MakeUnique<RemoteTextureHostWrapperHolder>(wrapper);

  mRemoteTextureHostWrapperHolders.emplace(key, std::move(wrapperHolder));

  return wrapper;
}

void RemoteTextureMap::UnregisterRemoteTextureHostWrapper(
    const RemoteTextureId aTextureId, const RemoteTextureOwnerId aOwnerId,
    const base::ProcessId aForPid) {
  MOZ_ASSERT(CompositorThreadHolder::IsInCompositorThread());

  std::vector<RefPtr<TextureHost>>
      releasingTextures;  // Release outside the monitor
  {
    MonitorAutoLock lock(mMonitor);

    const auto key = std::pair(aForPid, aTextureId);
    auto it = mRemoteTextureHostWrapperHolders.find(key);
    if (it == mRemoteTextureHostWrapperHolders.end()) {
      MOZ_ASSERT_UNREACHABLE("unexpected to be called");
      return;
    }
    releasingTextures.emplace_back(it->second->mRemoteTextureHostWrapper);
    if (it->second->mRemoteTextureHost) {
      releasingTextures.emplace_back(it->second->mRemoteTextureHost);
    }

    mRemoteTextureHostWrapperHolders.erase(it);
    mMonitor.Notify();
  }
}

bool RemoteTextureMap::CheckRemoteTextureReady(
    const RemoteTextureInfo& aInfo,
    std::function<void(const RemoteTextureInfo&)>&& aCallback) {
  MOZ_ASSERT(CompositorThreadHolder::IsInCompositorThread());

  MonitorAutoLock lock(mMonitor);

  auto* owner = GetTextureOwner(lock, aInfo.mOwnerId, aInfo.mForPid);
  if (!owner || owner->mIsContextLost) {
    // Owner is already removed or context lost. No need to wait texture ready.
    return true;
  }

  const auto key = std::pair(aInfo.mForPid, aInfo.mTextureId);
  auto it = mRemoteTextureHostWrapperHolders.find(key);
  if (it == mRemoteTextureHostWrapperHolders.end()) {
    MOZ_ASSERT_UNREACHABLE("unexpected to be called");
    gfxCriticalNoteOnce << "Remote texture does not exist id:"
                        << uint64_t(aInfo.mTextureId);
    return true;
  }

  if (owner->mLatestPushedTextureId >= aInfo.mTextureId) {
    return true;
  }

  auto callbackHolder = MakeUnique<RenderingReadyCallbackHolder>(
      aInfo.mTextureId, std::move(aCallback));
  owner->mRenderingReadyCallbackHolders.push_back(std::move(callbackHolder));

  return false;
}

bool RemoteTextureMap::WaitRemoteTextureReady(const RemoteTextureInfo& aInfo) {
  MOZ_ASSERT(CompositorThreadHolder::IsInCompositorThread());

  MonitorAutoLock lock(mMonitor);

  auto* owner = GetTextureOwner(lock, aInfo.mOwnerId, aInfo.mForPid);
  if (!owner || owner->mIsContextLost) {
    // Owner is already removed or context lost.
    return false;
  }

  const auto key = std::pair(aInfo.mForPid, aInfo.mTextureId);
  auto it = mRemoteTextureHostWrapperHolders.find(key);
  if (it == mRemoteTextureHostWrapperHolders.end()) {
    MOZ_ASSERT_UNREACHABLE("unexpected to be called");
    gfxCriticalNoteOnce << "Remote texture does not exist id:"
                        << uint64_t(aInfo.mTextureId);
    return false;
  }

  const TimeDuration timeout = TimeDuration::FromMilliseconds(1000);

  while (owner->mLatestPushedTextureId < aInfo.mTextureId) {
    CVStatus status = mMonitor.Wait(timeout);
    if (status == CVStatus::Timeout) {
      MOZ_ASSERT_UNREACHABLE("unexpected to be called");
      gfxCriticalNoteOnce << "Remote texture wait time out id:"
                          << uint64_t(aInfo.mTextureId);
      return false;
    }

    auto it = mRemoteTextureHostWrapperHolders.find(key);
    if (it == mRemoteTextureHostWrapperHolders.end()) {
      MOZ_ASSERT_UNREACHABLE("unexpected to be called");
      return false;
    }

    auto* owner = GetTextureOwner(lock, aInfo.mOwnerId, aInfo.mForPid);
    // When owner is alreay unregistered, remote texture will not be pushed.
    if (!owner || owner->mIsContextLost) {
      // This could happen with IPC abnormal shutdown
      return false;
    }
  }

  return true;
}

void RemoteTextureMap::SuppressRemoteTextureReadyCheck(
    const RemoteTextureId aTextureId, const base::ProcessId aForPid) {
  MOZ_ASSERT(CompositorThreadHolder::IsInCompositorThread());
  MonitorAutoLock lock(mMonitor);

  const auto key = std::pair(aForPid, aTextureId);
  auto it = mRemoteTextureHostWrapperHolders.find(key);
  if (it == mRemoteTextureHostWrapperHolders.end()) {
    MOZ_ASSERT_UNREACHABLE("unexpected to be called");
    return;
  }
  it->second->mReadyCheckSuppressed = true;
}

UniquePtr<TextureData> RemoteTextureMap::GetRecycledTextureData(
    const RemoteTextureOwnerId aOwnerId, const base::ProcessId aForPid,
    const RefPtr<RemoteTextureRecycleBin>& aRecycleBin,
    const gfx::IntSize& aSize, gfx::SurfaceFormat aFormat,
    TextureType aTextureType) {
  MonitorAutoLock lock(mMonitor);

  RefPtr<RemoteTextureRecycleBin> bin;
  if (aOwnerId.IsValid()) {
    if (auto* owner = GetTextureOwner(lock, aOwnerId, aForPid)) {
      bin = owner->mRecycleBin;
    }
  } else {
    bin = aRecycleBin;
  }
  if (!bin) {
    return nullptr;
  }

  for (auto it = bin->mRecycledTextures.begin();
       it != bin->mRecycledTextures.end(); it++) {
    auto& holder = *it;
    if (holder.mTextureData &&
        holder.mTextureData->GetTextureType() == aTextureType &&
        holder.mSize == aSize && holder.mFormat == aFormat) {
      UniquePtr<TextureData> texture = std::move(holder.mTextureData);
      bin->mRecycledTextures.erase(it);
      return texture;
    }
  }

  return nullptr;
}

UniquePtr<SharedResourceWrapper> RemoteTextureMap::GetRecycledSharedTexture(
    const RemoteTextureOwnerId aOwnerId, const base::ProcessId aForPid,
    const RefPtr<RemoteTextureRecycleBin>& aRecycleBin,
    const gfx::IntSize& aSize, const gfx::SurfaceFormat aFormat,
    SurfaceDescriptor::Type aType) {
  MonitorAutoLock lock(mMonitor);

  RefPtr<RemoteTextureRecycleBin> bin;
  if (aOwnerId.IsValid()) {
    if (auto* owner = GetTextureOwner(lock, aOwnerId, aForPid)) {
      bin = owner->mRecycleBin;
    }
  } else {
    bin = aRecycleBin;
  }
  if (!bin) {
    return nullptr;
  }

  for (auto it = bin->mRecycledTextures.begin();
       it != bin->mRecycledTextures.end(); it++) {
    auto& holder = *it;
    if (holder.mType == aType && holder.mSize == aSize &&
        holder.mFormat == aFormat) {
      UniquePtr<SharedResourceWrapper> wrapper =
          std::move(holder.mResourceWrapper);
      bin->mRecycledTextures.erase(it);
      return wrapper;
    }
  }

  return nullptr;
}

RemoteTextureMap::TextureOwner* RemoteTextureMap::GetTextureOwner(
    const MonitorAutoLock& aProofOfLock, const RemoteTextureOwnerId aOwnerId,
    const base::ProcessId aForPid) {
  const auto key = std::pair(aForPid, aOwnerId);
  auto it = mTextureOwners.find(key);
  if (it == mTextureOwners.end()) {
    return nullptr;
  }
  return it->second.get();
}

RemoteTextureMap::TextureDataHolder::TextureDataHolder(
    const RemoteTextureId aTextureId, RefPtr<TextureHost> aTextureHost,
    UniquePtr<TextureData>&& aTextureData,
    UniquePtr<SharedResourceWrapper>&& aResourceWrapper)
    : mTextureId(aTextureId),
      mTextureHost(aTextureHost),
      mTextureData(std::move(aTextureData)),
      mResourceWrapper(std::move(aResourceWrapper)) {}

RemoteTextureMap::RenderingReadyCallbackHolder::RenderingReadyCallbackHolder(
    const RemoteTextureId aTextureId,
    std::function<void(const RemoteTextureInfo&)>&& aCallback)
    : mTextureId(aTextureId), mCallback(aCallback) {}

RemoteTextureMap::RemoteTextureHostWrapperHolder::
    RemoteTextureHostWrapperHolder(
        RefPtr<TextureHost> aRemoteTextureHostWrapper)
    : mRemoteTextureHostWrapper(aRemoteTextureHostWrapper) {}

}  // namespace mozilla::layers