File: iosurface_image_backing.mm

package info (click to toggle)
chromium 139.0.7258.127-2
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 6,122,156 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (2036 lines) | stat: -rw-r--r-- 78,001 bytes parent folder | download | duplicates (3)
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
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifdef UNSAFE_BUFFERS_BUILD
// TODO(crbug.com/40285824): Remove this and convert code to safer constructs.
#pragma allow_unsafe_buffers
#endif

#include "gpu/command_buffer/service/shared_image/iosurface_image_backing.h"

#include <EGL/egl.h>
#include <EGL/eglext.h>
#import <Metal/Metal.h>
#include <dawn/native/MetalBackend.h>
#include <dawn/webgpu_cpp.h>

#include "base/apple/scoped_cftyperef.h"
#include "base/apple/scoped_nsobject.h"
#include "base/memory/scoped_policy.h"
#include "base/trace_event/memory_dump_manager.h"
#include "components/viz/common/resources/resource_sizes.h"
#include "components/viz/common/resources/shared_image_format_utils.h"
#include "gpu/command_buffer/common/shared_image_trace_utils.h"
#include "gpu/command_buffer/common/shared_image_usage.h"
#include "gpu/command_buffer/service/dawn_context_provider.h"
#include "gpu/command_buffer/service/metal_context_provider.h"
#include "gpu/command_buffer/service/shared_context_state.h"
#include "gpu/command_buffer/service/shared_image/copy_image_plane.h"
#include "gpu/command_buffer/service/shared_image/dawn_fallback_image_representation.h"
#include "gpu/command_buffer/service/shared_image/iosurface_image_backing_factory.h"
#include "gpu/command_buffer/service/shared_image/shared_image_format_service_utils.h"
#include "gpu/command_buffer/service/shared_image/shared_image_gl_utils.h"
#include "gpu/command_buffer/service/shared_image/skia_graphite_dawn_image_representation.h"
#include "gpu/command_buffer/service/skia_utils.h"
#include "gpu/config/gpu_finch_features.h"
#include "third_party/angle/include/EGL/eglext_angle.h"
#include "third_party/skia/include/core/SkColorSpace.h"
#include "third_party/skia/include/gpu/ganesh/GrContextThreadSafeProxy.h"
#include "third_party/skia/include/gpu/ganesh/SkSurfaceGanesh.h"
#include "third_party/skia/include/gpu/graphite/Recorder.h"
#include "third_party/skia/include/gpu/graphite/Surface.h"
#include "third_party/skia/include/private/chromium/GrPromiseImageTexture.h"
#include "ui/gl/egl_surface_io_surface.h"
#include "ui/gl/gl_context.h"
#include "ui/gl/gl_display.h"
#include "ui/gl/gl_fence.h"
#include "ui/gl/gl_gl_api_implementation.h"
#include "ui/gl/gl_implementation.h"
#include "ui/gl/scoped_binders.h"
#include "ui/gl/scoped_make_current.h"
#include "ui/gl/scoped_restore_texture.h"

namespace gpu {

namespace {
using GraphiteTextureHolder = SkiaImageRepresentation::GraphiteTextureHolder;

struct ScopedIOSurfaceLock {
  ScopedIOSurfaceLock(IOSurfaceRef iosurface, IOSurfaceLockOptions options)
      : io_surface_(iosurface), options_(options) {
    kern_return_t r = IOSurfaceLock(io_surface_, options_, /*seed=*/nullptr);
    CHECK_EQ(KERN_SUCCESS, r);
  }
  ~ScopedIOSurfaceLock() {
    kern_return_t r = IOSurfaceUnlock(io_surface_, options_, /*seed=*/nullptr);
    CHECK_EQ(KERN_SUCCESS, r);
  }

  ScopedIOSurfaceLock(const ScopedIOSurfaceLock&) = delete;
  ScopedIOSurfaceLock& operator=(const ScopedIOSurfaceLock&) = delete;

 private:
  const IOSurfaceRef io_surface_;
  const IOSurfaceLockOptions options_;
};

// Returns BufferFormat for given multiplanar `format`.
gfx::BufferFormat GetBufferFormatForPlane(viz::SharedImageFormat format,
                                          int plane) {
  DCHECK(format.is_multi_plane());
  DCHECK(format.IsValidPlaneIndex(plane));

  // IOSurfaceBacking does not support external sampler use cases.
  int num_channels = format.NumChannelsInPlane(plane);
  DCHECK_LE(num_channels, 2);
  switch (format.channel_format()) {
    case viz::SharedImageFormat::ChannelFormat::k8:
      return num_channels == 2 ? gfx::BufferFormat::RG_88
                               : gfx::BufferFormat::R_8;
    case viz::SharedImageFormat::ChannelFormat::k10:
    case viz::SharedImageFormat::ChannelFormat::k16:
    case viz::SharedImageFormat::ChannelFormat::k16F:
      return num_channels == 2 ? gfx::BufferFormat::RG_1616
                               : gfx::BufferFormat::R_16;
  }
  NOTREACHED();
}

wgpu::Texture CreateWGPUTexture(wgpu::SharedTextureMemory shared_texture_memory,
                                SharedImageUsageSet shared_image_usage,
                                const gfx::Size& io_surface_size,
                                wgpu::TextureFormat wgpu_format,
                                std::vector<wgpu::TextureFormat> view_formats,
                                wgpu::TextureUsage wgpu_texture_usage,
                                wgpu::TextureUsage internal_usage) {
  const std::string debug_label =
      "IOSurface(" + CreateLabelForSharedImageUsage(shared_image_usage) + ")";

  wgpu::TextureDescriptor texture_descriptor;
  texture_descriptor.label = debug_label.c_str();
  texture_descriptor.format = wgpu_format;
  texture_descriptor.usage =
      static_cast<wgpu::TextureUsage>(wgpu_texture_usage);
  texture_descriptor.dimension = wgpu::TextureDimension::e2D;
  texture_descriptor.size = {static_cast<uint32_t>(io_surface_size.width()),
                             static_cast<uint32_t>(io_surface_size.height()),
                             1};
  texture_descriptor.mipLevelCount = 1;
  texture_descriptor.sampleCount = 1;
  texture_descriptor.viewFormatCount = view_formats.size();
  texture_descriptor.viewFormats = view_formats.data();

  wgpu::DawnTextureInternalUsageDescriptor internalDesc;
  internalDesc.internalUsage = internal_usage;

  texture_descriptor.nextInChain = &internalDesc;

  return shared_texture_memory.CreateTexture(&texture_descriptor);
}

#if BUILDFLAG(SKIA_USE_METAL)

base::apple::scoped_nsprotocol<id<MTLTexture>> CreateMetalTexture(
    id<MTLDevice> mtl_device,
    IOSurfaceRef io_surface,
    const gfx::Size& size,
    viz::SharedImageFormat format,
    int plane_index) {
  TRACE_EVENT0("gpu", "IOSurfaceImageBackingFactory::CreateMetalTexture");
  base::apple::scoped_nsprotocol<id<MTLTexture>> mtl_texture;
  MTLPixelFormat mtl_pixel_format =
      static_cast<MTLPixelFormat>(ToMTLPixelFormat(format, plane_index));
  if (mtl_pixel_format == MTLPixelFormatInvalid) {
    return mtl_texture;
  }

  base::apple::scoped_nsobject<MTLTextureDescriptor> mtl_tex_desc(
      [[MTLTextureDescriptor alloc] init]);
  [mtl_tex_desc.get() setTextureType:MTLTextureType2D];
  [mtl_tex_desc.get()
      setUsage:MTLTextureUsageShaderRead | MTLTextureUsageRenderTarget];
  [mtl_tex_desc.get() setPixelFormat:mtl_pixel_format];
  [mtl_tex_desc.get() setWidth:size.width()];
  [mtl_tex_desc.get() setHeight:size.height()];
  [mtl_tex_desc.get() setDepth:1];
  [mtl_tex_desc.get() setMipmapLevelCount:1];
  [mtl_tex_desc.get() setArrayLength:1];
  [mtl_tex_desc.get() setSampleCount:1];
  // TODO(crbug.com/40622826): For zero-copy resources that are populated
  // on the CPU (e.g, video frames), it may be that MTLStorageModeManaged will
  // be more appropriate.
#if BUILDFLAG(IS_IOS)
  // On iOS we are using IOSurfaces which must use MTLStorageModeShared.
  [mtl_tex_desc.get() setStorageMode:MTLStorageModeShared];
#else
  [mtl_tex_desc.get() setStorageMode:MTLStorageModeManaged];
#endif
  mtl_texture.reset([mtl_device newTextureWithDescriptor:mtl_tex_desc.get()
                                               iosurface:io_surface
                                                   plane:plane_index]);
  DCHECK(mtl_texture);
  return mtl_texture;
}

std::vector<scoped_refptr<GraphiteTextureHolder>> CreateGraphiteMetalTextures(
    std::vector<base::apple::scoped_nsprotocol<id<MTLTexture>>> mtl_textures,
    const viz::SharedImageFormat format,
    const gfx::Size& size) {
  int num_planes = format.NumberOfPlanes();
  std::vector<scoped_refptr<GraphiteTextureHolder>> graphite_textures;
  graphite_textures.reserve(num_planes);
  for (int plane = 0; plane < num_planes; plane++) {
    SkISize sk_size = gfx::SizeToSkISize(format.GetPlaneSize(plane, size));
    graphite_textures.emplace_back(base::MakeRefCounted<GraphiteTextureHolder>(
        skgpu::graphite::BackendTextures::MakeMetal(
            sk_size, mtl_textures[plane].get())));
  }
  return graphite_textures;
}
#endif

id<MTLDevice> QueryMetalDeviceFromANGLE(gl::GLDisplayEGL* display) {
  id<MTLDevice> metal_device = nil;
  if (gl::GetANGLEImplementation() == gl::ANGLEImplementation::kMetal) {
    EGLAttrib angle_device_attrib = 0;
    if (eglQueryDisplayAttribEXT(display->GetDisplay(), EGL_DEVICE_EXT,
                                 &angle_device_attrib)) {
      EGLDeviceEXT angle_device =
          reinterpret_cast<EGLDeviceEXT>(angle_device_attrib);
      EGLAttrib metal_device_attrib = 0;
      if (eglQueryDeviceAttribEXT(angle_device, EGL_METAL_DEVICE_ANGLE,
                                  &metal_device_attrib)) {
        metal_device = (__bridge id)(void*)metal_device_attrib;
      }
    }
  }
  return metal_device;
}

class BackpressureMetalSharedEventImpl final
    : public BackpressureMetalSharedEvent {
 public:
  BackpressureMetalSharedEventImpl(
      base::apple::scoped_nsprotocol<id<MTLSharedEvent>> shared_event,
      uint64_t signaled_value)
      : shared_event_(std::move(shared_event)),
        signaled_value_(signaled_value) {}
  ~BackpressureMetalSharedEventImpl() override = default;

  BackpressureMetalSharedEventImpl(
      const BackpressureMetalSharedEventImpl& other) = delete;
  BackpressureMetalSharedEventImpl(BackpressureMetalSharedEventImpl&& other) =
      delete;
  BackpressureMetalSharedEventImpl& operator=(
      const BackpressureMetalSharedEventImpl& other) = delete;

  bool HasCompleted() const override {
    if (shared_event_) {
      return shared_event_.get().signaledValue >= signaled_value_;
    }
    return true;
  }

  id<MTLSharedEvent> shared_event() const { return shared_event_.get(); }

  // This is the value which will be signaled on the associated MTLSharedEvent.
  uint64_t signaled_value() const { return signaled_value_; }

 private:
  base::apple::scoped_nsprotocol<id<MTLSharedEvent>> shared_event_;
  uint64_t signaled_value_;
};

}  // namespace

///////////////////////////////////////////////////////////////////////////////
// IOSurfaceBackingEGLState

IOSurfaceBackingEGLState::IOSurfaceBackingEGLState(
    Client* client,
    EGLDisplay egl_display,
    gl::GLContext* gl_context,
    gl::GLSurface* gl_surface,
    GLuint gl_target,
    std::vector<scoped_refptr<gles2::TexturePassthrough>> gl_textures)
    : client_(client),
      egl_display_(egl_display),
      context_(gl_context),
      surface_(gl_surface),
      gl_target_(gl_target),
      gl_textures_(std::move(gl_textures)),
      created_task_runner_(base::SingleThreadTaskRunner::GetCurrentDefault()) {
  client_->IOSurfaceBackingEGLStateBeingCreated(this);
}

IOSurfaceBackingEGLState::~IOSurfaceBackingEGLState() {
  // To use ui::ScopedMakeCurrent, this funciton must be called on the same
  // thread where it got its current context context during creation.
  ui::ScopedMakeCurrent smc(context_.get(), surface_.get());
  if (client_) {
    // IOSurfaceBackingEGLState is destroyed directly from the same thread.
    client_->IOSurfaceBackingEGLStateBeingDestroyed(this, !context_lost_);
    DCHECK(gl_textures_.empty());
  } else {
    // ~IOSurfaceBackingEGLState is posted from the other thread when the
    // client_ (IOSurfaceImageBacking) was destroyed.
    if (context_lost_) {
      for (const auto& texture : gl_textures_) {
        texture->MarkContextLost();
      }
    }
    gl_textures_.clear();
    egl_surfaces_.clear();
  }
}

GLuint IOSurfaceBackingEGLState::GetGLServiceId(int plane_index) const {
  return GetGLTexture(plane_index)->service_id();
}

bool IOSurfaceBackingEGLState::BeginAccess(bool readonly) {
  gl::GLDisplayEGL* display = gl::GLDisplayEGL::GetDisplayForCurrentContext();
  CHECK(display);
  CHECK(display->GetDisplay() == egl_display_);
  return client_->IOSurfaceBackingEGLStateBeginAccess(this, readonly);
}

void IOSurfaceBackingEGLState::EndAccess(bool readonly) {
  client_->IOSurfaceBackingEGLStateEndAccess(this, readonly);
}

void IOSurfaceBackingEGLState::WillRelease(bool have_context) {
  if (!have_context) {
    context_lost_ = true;
  }
}

void IOSurfaceBackingEGLState::RemoveClient() {
  client_ = nullptr;
}

///////////////////////////////////////////////////////////////////////////////
// GLTextureIRepresentation
class IOSurfaceImageBacking::GLTextureIRepresentation final
    : public GLTexturePassthroughImageRepresentation {
 public:
  GLTextureIRepresentation(SharedImageManager* manager,
                           SharedImageBacking* backing,
                           scoped_refptr<IOSurfaceBackingEGLState> egl_state,
                           MemoryTypeTracker* tracker)
      : GLTexturePassthroughImageRepresentation(manager, backing, tracker),
        egl_state_(egl_state) {}
  ~GLTextureIRepresentation() override {
    egl_state_->WillRelease(has_context());
    AutoLock auto_lock(backing());
    egl_state_.reset();
  }

 private:
  // GLTexturePassthroughImageRepresentation:
  const scoped_refptr<gles2::TexturePassthrough>& GetTexturePassthrough(
      int plane_index) override {
    return egl_state_->GetGLTexture(plane_index);
  }

  bool BeginAccess(GLenum mode) override {
    DCHECK(mode_ == 0);
    AutoLock auto_lock(backing());
    mode_ = mode;
    bool readonly = mode_ != GL_SHARED_IMAGE_ACCESS_MODE_READWRITE_CHROMIUM;
    return egl_state_->BeginAccess(readonly);
  }

  void EndAccess() override {
    DCHECK(mode_ != 0);
    AutoLock auto_lock(backing());
    GLenum current_mode = mode_;
    mode_ = 0;
    egl_state_->EndAccess(current_mode !=
                          GL_SHARED_IMAGE_ACCESS_MODE_READWRITE_CHROMIUM);
  }

  scoped_refptr<IOSurfaceBackingEGLState> egl_state_;
  GLenum mode_ = 0;
};

///////////////////////////////////////////////////////////////////////////////
// SkiaGaneshRepresentation

class IOSurfaceImageBacking::SkiaGaneshRepresentation final
    : public SkiaGaneshImageRepresentation {
 public:
  SkiaGaneshRepresentation(
      SharedImageManager* manager,
      SharedImageBacking* backing,
      scoped_refptr<IOSurfaceBackingEGLState> egl_state,
      scoped_refptr<SharedContextState> context_state,
      std::vector<sk_sp<GrPromiseImageTexture>> promise_textures,
      MemoryTypeTracker* tracker);
  ~SkiaGaneshRepresentation() override;

 private:
  // SkiaGaneshImageRepresentation:
  std::vector<sk_sp<SkSurface>> BeginWriteAccess(
      int final_msaa_count,
      const SkSurfaceProps& surface_props,
      const gfx::Rect& update_rect,
      std::vector<GrBackendSemaphore>* begin_semaphores,
      std::vector<GrBackendSemaphore>* end_semaphores,
      std::unique_ptr<skgpu::MutableTextureState>* end_state) override;
  std::vector<sk_sp<GrPromiseImageTexture>> BeginWriteAccess(
      std::vector<GrBackendSemaphore>* begin_semaphores,
      std::vector<GrBackendSemaphore>* end_semaphore,
      std::unique_ptr<skgpu::MutableTextureState>* end_state) override;
  void EndWriteAccess() override;
  std::vector<sk_sp<GrPromiseImageTexture>> BeginReadAccess(
      std::vector<GrBackendSemaphore>* begin_semaphores,
      std::vector<GrBackendSemaphore>* end_semaphores,
      std::unique_ptr<skgpu::MutableTextureState>* end_state) override;
  void EndReadAccess() override;
  bool SupportsMultipleConcurrentReadAccess() override;

  void CheckContext();

  scoped_refptr<IOSurfaceBackingEGLState> egl_state_;
  const scoped_refptr<SharedContextState> context_state_;
  std::vector<sk_sp<GrPromiseImageTexture>> promise_textures_;
  std::vector<sk_sp<SkSurface>> write_surfaces_;
#if DCHECK_IS_ON()
  raw_ptr<gl::GLContext> context_ = nullptr;
#endif
};

IOSurfaceImageBacking::SkiaGaneshRepresentation::SkiaGaneshRepresentation(
    SharedImageManager* manager,
    SharedImageBacking* backing,
    scoped_refptr<IOSurfaceBackingEGLState> egl_state,
    scoped_refptr<SharedContextState> context_state,
    std::vector<sk_sp<GrPromiseImageTexture>> promise_textures,
    MemoryTypeTracker* tracker)
    : SkiaGaneshImageRepresentation(context_state->gr_context(),
                                    manager,
                                    backing,
                                    tracker),
      egl_state_(egl_state),
      context_state_(std::move(context_state)),
      promise_textures_(promise_textures) {
  DCHECK(!promise_textures_.empty());
#if DCHECK_IS_ON()
  if (context_state_->GrContextIsGL())
    context_ = gl::GLContext::GetCurrent();
#endif
}

IOSurfaceImageBacking::SkiaGaneshRepresentation::~SkiaGaneshRepresentation() {
  if (!write_surfaces_.empty()) {
    DLOG(ERROR) << "SkiaImageRepresentation was destroyed while still "
                << "open for write access.";
  }

  promise_textures_.clear();
  if (egl_state_) {
    DCHECK(context_state_->GrContextIsGL());
    egl_state_->WillRelease(has_context());

    AutoLock auto_lock(backing());
    egl_state_.reset();
  }
}

std::vector<sk_sp<SkSurface>>
IOSurfaceImageBacking::SkiaGaneshRepresentation::BeginWriteAccess(
    int final_msaa_count,
    const SkSurfaceProps& surface_props,
    const gfx::Rect& update_rect,
    std::vector<GrBackendSemaphore>* begin_semaphores,
    std::vector<GrBackendSemaphore>* end_semaphores,
    std::unique_ptr<skgpu::MutableTextureState>* end_state) {
  AutoLock auto_lock(backing());
  CheckContext();

  if (egl_state_) {
    DCHECK(context_state_->GrContextIsGL());
    if (!egl_state_->BeginAccess(/*readonly=*/false)) {
      return {};
    }
  }

  if (!write_surfaces_.empty()) {
    return {};
  }

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

  DCHECK_EQ(static_cast<int>(promise_textures_.size()),
            format().NumberOfPlanes());
  std::vector<sk_sp<SkSurface>> surfaces;
  for (int plane_index = 0; plane_index < format().NumberOfPlanes();
       plane_index++) {
    // Use the color type per plane for multiplanar formats.
    SkColorType sk_color_type =
        viz::ToClosestSkColorType(format(), plane_index);
    // Gray is not a renderable single channel format, but alpha is.
    if (sk_color_type == kGray_8_SkColorType) {
      sk_color_type = kAlpha_8_SkColorType;
    }
    auto surface = SkSurfaces::WrapBackendTexture(
        context_state_->gr_context(),
        promise_textures_[plane_index]->backendTexture(), surface_origin(),
        final_msaa_count, sk_color_type,
        backing()->color_space().GetAsFullRangeRGB().ToSkColorSpace(),
        &surface_props);
    if (!surface) {
      return {};
    }
    surfaces.push_back(surface);
  }

  write_surfaces_ = surfaces;
  return surfaces;
}

std::vector<sk_sp<GrPromiseImageTexture>>
IOSurfaceImageBacking::SkiaGaneshRepresentation::BeginWriteAccess(
    std::vector<GrBackendSemaphore>* begin_semaphores,
    std::vector<GrBackendSemaphore>* end_semaphores,
    std::unique_ptr<skgpu::MutableTextureState>* end_state) {
  AutoLock auto_lock(backing());
  CheckContext();

  if (egl_state_) {
    DCHECK(context_state_->GrContextIsGL());
    if (!egl_state_->BeginAccess(/*readonly=*/false)) {
      return {};
    }
  }
  if (promise_textures_.empty()) {
    return {};
  }
  return promise_textures_;
}

void IOSurfaceImageBacking::SkiaGaneshRepresentation::EndWriteAccess() {
  AutoLock auto_lock(backing());
#if DCHECK_IS_ON()
  for (auto& surface : write_surfaces_) {
    DCHECK(surface->unique());
  }
#endif

  CheckContext();
  write_surfaces_.clear();

  if (egl_state_)
    egl_state_->EndAccess(/*readonly=*/false);
}

std::vector<sk_sp<GrPromiseImageTexture>>
IOSurfaceImageBacking::SkiaGaneshRepresentation::BeginReadAccess(
    std::vector<GrBackendSemaphore>* begin_semaphores,
    std::vector<GrBackendSemaphore>* end_semaphores,
    std::unique_ptr<skgpu::MutableTextureState>* end_state) {
  AutoLock auto_lock(backing());
  CheckContext();

  if (egl_state_) {
    DCHECK(context_state_->GrContextIsGL());
    if (!egl_state_->BeginAccess(/*readonly=*/true)) {
      return {};
    }
  }
  if (promise_textures_.empty()) {
    return {};
  }
  return promise_textures_;
}

void IOSurfaceImageBacking::SkiaGaneshRepresentation::EndReadAccess() {
  AutoLock auto_lock(backing());

  if (egl_state_) {
    egl_state_->EndAccess(/*readonly=*/true);
  }
}

bool IOSurfaceImageBacking::SkiaGaneshRepresentation::
    SupportsMultipleConcurrentReadAccess() {
  return true;
}

void IOSurfaceImageBacking::SkiaGaneshRepresentation::CheckContext() {
#if DCHECK_IS_ON()
  if (!context_state_->context_lost() && context_)
    DCHECK(gl::GLContext::GetCurrent() == context_);
#endif
}

#if BUILDFLAG(SKIA_USE_METAL)
///////////////////////////////////////////////////////////////////////////////
// SkiaGraphiteMetalRepresentation

class IOSurfaceImageBacking::SkiaGraphiteMetalRepresentation final
    : public SkiaGraphiteImageRepresentation {
 public:
  // Graphite does not keep track of the MetalTexture like Ganesh, so the
  // representation/backing needs to keep the Metal texture alive.
  SkiaGraphiteMetalRepresentation(
      SharedImageManager* manager,
      SharedImageBacking* backing,
      MemoryTypeTracker* tracker,
      skgpu::graphite::Recorder* recorder,
      std::vector<base::apple::scoped_nsprotocol<id<MTLTexture>>> mtl_textures)
      : SkiaGraphiteImageRepresentation(manager, backing, tracker),
        recorder_(recorder),
        mtl_textures_(std::move(mtl_textures)) {
    CHECK_EQ(mtl_textures_.size(), NumPlanesExpected());
  }

  ~SkiaGraphiteMetalRepresentation() override {
    if (!write_surfaces_.empty()) {
      DLOG(ERROR) << "SkiaImageRepresentation was destroyed while still "
                  << "open for write access.";
    }
  }

 private:
  // SkiaGraphiteImageRepresentation:
  std::vector<sk_sp<SkSurface>> BeginWriteAccess(
      const SkSurfaceProps& surface_props,
      const gfx::Rect& update_rect) override;
  std::vector<scoped_refptr<GraphiteTextureHolder>> BeginWriteAccess() override;
  void EndWriteAccess() override;
  std::vector<scoped_refptr<GraphiteTextureHolder>> BeginReadAccess() override;
  void EndReadAccess() override;

  IOSurfaceImageBacking* backing_impl() const {
    return static_cast<IOSurfaceImageBacking*>(backing());
  }

  const raw_ptr<skgpu::graphite::Recorder> recorder_;
  std::vector<base::apple::scoped_nsprotocol<id<MTLTexture>>> mtl_textures_;
  std::vector<sk_sp<SkSurface>> write_surfaces_;
};

std::vector<sk_sp<SkSurface>>
IOSurfaceImageBacking::SkiaGraphiteMetalRepresentation::BeginWriteAccess(
    const SkSurfaceProps& surface_props,
    const gfx::Rect& update_rect) {
  AutoLock auto_lock(backing_impl());

  if (!write_surfaces_.empty()) {
    // Write access is already in progress.
    return {};
  }

  if (!backing_impl()->BeginAccess(/*readonly=*/false)) {
    return {};
  }

  int num_planes = format().NumberOfPlanes();
  write_surfaces_.reserve(num_planes);
  for (int plane = 0; plane < num_planes; plane++) {
    SkColorType sk_color_type = viz::ToClosestSkColorType(format(), plane);
    // Gray is not a renderable single channel format, but alpha is.
    if (sk_color_type == kGray_8_SkColorType) {
      sk_color_type = kAlpha_8_SkColorType;
    }
    SkISize sk_size = gfx::SizeToSkISize(format().GetPlaneSize(plane, size()));

    auto backend_texture = skgpu::graphite::BackendTextures::MakeMetal(
        sk_size, mtl_textures_[plane].get());
    auto surface = SkSurfaces::WrapBackendTexture(
        recorder_, backend_texture, sk_color_type,
        backing()->color_space().GetAsFullRangeRGB().ToSkColorSpace(),
        &surface_props);
    write_surfaces_.emplace_back(std::move(surface));
  }
  return write_surfaces_;
}

std::vector<scoped_refptr<GraphiteTextureHolder>>
IOSurfaceImageBacking::SkiaGraphiteMetalRepresentation::BeginWriteAccess() {
  AutoLock auto_lock(backing_impl());

  if (!backing_impl()->BeginAccess(/*readonly=*/false)) {
    return {};
  }
  return CreateGraphiteMetalTextures(mtl_textures_, format(), size());
}

void IOSurfaceImageBacking::SkiaGraphiteMetalRepresentation::EndWriteAccess() {
  AutoLock auto_lock(backing_impl());
#if DCHECK_IS_ON()
  for (auto& surface : write_surfaces_) {
    DCHECK(surface->unique());
  }
#endif
  write_surfaces_.clear();
  backing_impl()->EndAccess(/*readonly=*/false);
}

std::vector<scoped_refptr<GraphiteTextureHolder>>
IOSurfaceImageBacking::SkiaGraphiteMetalRepresentation::BeginReadAccess() {
  AutoLock auto_lock(backing_impl());
  if (!backing_impl()->BeginAccess(/*readonly=*/true)) {
    return {};
  }
  return CreateGraphiteMetalTextures(mtl_textures_, format(), size());
}

void IOSurfaceImageBacking::SkiaGraphiteMetalRepresentation::EndReadAccess() {
  AutoLock auto_lock(backing_impl());
  backing_impl()->EndAccess(/*readonly=*/true);
}
#endif

///////////////////////////////////////////////////////////////////////////////
// OverlayRepresentation

class IOSurfaceImageBacking::OverlayRepresentation final
    : public OverlayImageRepresentation {
 public:
  OverlayRepresentation(SharedImageManager* manager,
                        SharedImageBacking* backing,
                        MemoryTypeTracker* tracker,
                        gfx::ScopedIOSurface io_surface)
      : OverlayImageRepresentation(manager, backing, tracker),
        io_surface_(std::move(io_surface)) {}
  ~OverlayRepresentation() override = default;

 private:
  bool BeginReadAccess(gfx::GpuFenceHandle& acquire_fence) override;
  void EndReadAccess(gfx::GpuFenceHandle release_fence) override;
  gfx::ScopedIOSurface GetIOSurface() const override;
  bool IsInUseByWindowServer() const override;

  gfx::ScopedIOSurface io_surface_;
};

bool IOSurfaceImageBacking::OverlayRepresentation::BeginReadAccess(
    gfx::GpuFenceHandle& acquire_fence) {
  auto* iosurface_backing = static_cast<IOSurfaceImageBacking*>(backing());
  AutoLock auto_lock(iosurface_backing);

  if (!iosurface_backing->BeginAccess(/*readonly=*/true)) {
    return false;
  }

  // This will transition the image to be accessed by CoreAnimation.
  iosurface_backing->WaitForCommandsToBeScheduled();

  gl::GLContext* context = gl::GLContext::GetCurrent();
  if (context) {
    std::vector<std::unique_ptr<BackpressureMetalSharedEvent>>
        backpressure_events;
    for (const auto& [shared_event, signaled_value] :
         iosurface_backing->exclusive_shared_events_) {
      backpressure_events.push_back(
          std::make_unique<BackpressureMetalSharedEventImpl>(shared_event,
                                                             signaled_value));
    }
    context->AddMetalSharedEventsForBackpressure(
        std::move(backpressure_events));
  }

  return true;
}

void IOSurfaceImageBacking::OverlayRepresentation::EndReadAccess(
    gfx::GpuFenceHandle release_fence) {
  auto* iosurface_backing = static_cast<IOSurfaceImageBacking*>(backing());
  AutoLock auto_lock(iosurface_backing);
  DCHECK(release_fence.is_null());

  iosurface_backing->EndAccess(/*readonly=*/true);
}

gfx::ScopedIOSurface
IOSurfaceImageBacking::OverlayRepresentation::GetIOSurface() const {
  return io_surface_;
}

bool IOSurfaceImageBacking::OverlayRepresentation::IsInUseByWindowServer()
    const {
  // IOSurfaceIsInUse() will always return true if the IOSurface is wrapped in
  // a CVPixelBuffer. Ignore the signal for such IOSurfaces (which are the
  // ones output by hardware video decode and video capture).
  if (backing()->usage().Has(SHARED_IMAGE_USAGE_MACOS_VIDEO_TOOLBOX)) {
    return false;
  }

  return IOSurfaceIsInUse(io_surface_.get());
}

///////////////////////////////////////////////////////////////////////////////
// DawnRepresentation

class IOSurfaceImageBacking::DawnRepresentation final
    : public DawnImageRepresentation {
 public:
  DawnRepresentation(SharedImageManager* manager,
                     SharedImageBacking* backing,
                     MemoryTypeTracker* tracker,
                     wgpu::Device device,
                     wgpu::SharedTextureMemory shared_texture_memory,
                     const gfx::Size& io_surface_size,
                     wgpu::TextureFormat wgpu_format,
                     std::vector<wgpu::TextureFormat> view_formats)
      : DawnImageRepresentation(manager, backing, tracker),
        device_(std::move(device)),
        shared_texture_memory_(shared_texture_memory),
        io_surface_size_(io_surface_size),
        wgpu_format_(wgpu_format),
        view_formats_(std::move(view_formats)) {
    CHECK(device_);
    CHECK(device_.HasFeature(wgpu::FeatureName::SharedTextureMemoryIOSurface));
    CHECK(shared_texture_memory);
  }
  ~DawnRepresentation() override { EndAccess(); }

  wgpu::Texture BeginAccess(wgpu::TextureUsage usage,
                            wgpu::TextureUsage internal_usage) final;
  void EndAccess() final;

 private:
  static constexpr wgpu::TextureUsage kReadOnlyUsage =
      wgpu::TextureUsage::CopySrc | wgpu::TextureUsage::TextureBinding;
  const wgpu::Device device_;
  wgpu::SharedTextureMemory shared_texture_memory_;
  const gfx::Size io_surface_size_;
  const wgpu::TextureFormat wgpu_format_;
  const std::vector<wgpu::TextureFormat> view_formats_;

  // NOTE: `usage_`, `internal_usage_`, and `texture_` are valid only within
  // the duration of a BeginAccess()/EndAccess() pair.
  wgpu::TextureUsage usage_;
  wgpu::TextureUsage internal_usage_;
  wgpu::Texture texture_;
};

wgpu::Texture IOSurfaceImageBacking::DawnRepresentation::BeginAccess(
    wgpu::TextureUsage wgpu_texture_usage,
    wgpu::TextureUsage internal_usage) {
  IOSurfaceImageBacking* iosurface_backing =
      static_cast<IOSurfaceImageBacking*>(backing());
  AutoLock auto_lock(iosurface_backing);

  const bool readonly = (wgpu_texture_usage & ~kReadOnlyUsage) == 0 &&
                        (internal_usage & ~kReadOnlyUsage) == 0;

  if (!iosurface_backing->BeginAccess(readonly)) {
    return {};
  }

  usage_ = wgpu_texture_usage;
  internal_usage_ = internal_usage;

  texture_ = iosurface_backing->GetDawnTextureCache()->GetCachedWGPUTexture(
      device_, usage_, internal_usage_, view_formats_);
  if (!texture_) {
    texture_ = CreateWGPUTexture(shared_texture_memory_, usage(),
                                 io_surface_size_, wgpu_format_, view_formats_,
                                 wgpu_texture_usage, internal_usage);
    iosurface_backing->GetDawnTextureCache()->MaybeCacheWGPUTexture(
        device_, texture_, usage_, internal_usage_, view_formats_);
  }

  // If there is already an ongoing Dawn access for this texture, then the
  // necessary work for starting the access (i.e., waiting on fences and
  // informing SharedTextureMemory) already happened as part of the initial
  // BeginAccess().
  // NOTE: SharedTextureMemory does not allow a BeginAccess() call on a texture
  // that already has an ongoing access (at the internal wgpu::Texture
  // level), so short-circuiting out here is not simply an optimization but
  // is actually necessary.
  int num_accesses_already_present =
      iosurface_backing->TrackBeginAccessToWGPUTexture(texture_);
  if (num_accesses_already_present > 0) {
    return texture_;
  }

  // IOSurface might be written on a different GPU. We need to wait for previous
  // Dawn and ANGLE commands to be scheduled first.
  iosurface_backing->WaitForCommandsToBeScheduled(
      dawn::native::metal::GetMTLDevice(device_.Get()));

  bool is_cleared = iosurface_backing->IsClearedInternal();
  wgpu::SharedTextureMemoryBeginAccessDescriptor begin_access_desc = {};
  begin_access_desc.initialized = is_cleared;

  // NOTE: WebGPU allows reads of uncleared textures, in which case Dawn clears
  // the texture on its initial access. Such reads must take exclusive access.
  begin_access_desc.concurrentRead = readonly && is_cleared;

  std::vector<wgpu::SharedFence> shared_fences;
  std::vector<uint64_t> signaled_values;

  // Synchronize with all of the MTLSharedEvents that have been stored in the
  // backing as a consequence of earlier BeginAccess/EndAccess calls against
  // other representations.
  iosurface_backing->ProcessSharedEventsForBeginAccess(
      readonly, [&](id<MTLSharedEvent> shared_event, uint64_t signaled_value) {
        wgpu::SharedFenceMTLSharedEventDescriptor shared_event_desc;
        shared_event_desc.sharedEvent = shared_event;

        wgpu::SharedFenceDescriptor fence_desc;
        fence_desc.nextInChain = &shared_event_desc;

        shared_fences.push_back(device_.ImportSharedFence(&fence_desc));
        signaled_values.push_back(signaled_value);
      });

  // Populate `begin_access_desc` with the fence data.
  CHECK(shared_fences.size() == signaled_values.size());
  begin_access_desc.fenceCount = shared_fences.size();
  begin_access_desc.fences = shared_fences.data();
  begin_access_desc.signaledValues = signaled_values.data();

  if (shared_texture_memory_.BeginAccess(texture_, &begin_access_desc) !=
      wgpu::Status::Success) {
    // NOTE: WebGPU CTS tests intentionally pass in formats that are
    // incompatible with the format of the backing IOSurface to check error
    // handling.
    LOG(ERROR) << "SharedTextureMemory::BeginAccess() failed";
    iosurface_backing->TrackEndAccessToWGPUTexture(texture_);
    iosurface_backing->GetDawnTextureCache()->RemoveWGPUTextureFromCache(
        device_, texture_);
    texture_ = nullptr;

    iosurface_backing->EndAccess(readonly);
  }

  return texture_;
}

void IOSurfaceImageBacking::DawnRepresentation::EndAccess() {
  IOSurfaceImageBacking* iosurface_backing =
      static_cast<IOSurfaceImageBacking*>(backing());
  AutoLock auto_lock(iosurface_backing);

  if (!texture_) {
    // The only valid cases in which this could occur are (a) if
    // SharedTextureMemory::BeginAccess() failed, in which case we already
    // called EndAccess() on the backing when we detected the failure, or (b)
    // this is a call from the destructor after another EndAccess() had already
    // been made, in which case we already executed the below code on the first
    // call (resulting in setting `texture_` to null).
    return;
  }

  // Inform the backing that an access has ended so that it can properly update
  // its state tracking.
  const bool readonly = (usage_ & ~kReadOnlyUsage) == 0 &&
                        (internal_usage_ & ~kReadOnlyUsage) == 0;

  iosurface_backing->EndAccess(readonly);
  int num_outstanding_accesses =
      iosurface_backing->TrackEndAccessToWGPUTexture(texture_);

  // However, if there is still an ongoing Dawn access on this texture,
  // short-circuit out of doing any other work. In particular, do not consume
  // fences or end the access at the level of SharedTextureMemory. That work
  // will happen when the last ongoing Dawn access finishes.
  if (num_outstanding_accesses > 0) {
    texture_ = nullptr;
    usage_ = internal_usage_ = wgpu::TextureUsage::None;
    return;
  }

  wgpu::SharedTextureMemoryEndAccessState end_access_desc;
  CHECK_EQ(shared_texture_memory_.EndAccess(texture_, &end_access_desc),
           wgpu::Status::Success);

  if (end_access_desc.initialized) {
    iosurface_backing->SetClearedInternal();
  }

  // Dawn's Metal backend has enqueued MTLSharedEvents which consumers of the
  // IOSurface must wait upon before attempting to use that IOSurface on
  // another MTLDevice. Store these events in the underlying
  // SharedImageBacking.
  for (size_t i = 0; i < end_access_desc.fenceCount; i++) {
    auto fence = end_access_desc.fences[i];
    auto signaled_value = end_access_desc.signaledValues[i];

    wgpu::SharedFenceExportInfo fence_export_info;
    wgpu::SharedFenceMTLSharedEventExportInfo fence_mtl_export_info;
    fence_export_info.nextInChain = &fence_mtl_export_info;
    fence.ExportInfo(&fence_export_info);
    auto shared_event =
        static_cast<id<MTLSharedEvent>>(fence_mtl_export_info.sharedEvent);
    iosurface_backing->AddSharedEventForEndAccess(shared_event, signaled_value,
                                                  readonly);
  }

  iosurface_backing->GetDawnTextureCache()->DestroyWGPUTextureIfNotCached(
      device_, texture_);

  if (end_access_desc.fenceCount > 0) {
    // For write access, we would need to WaitForCommandsToBeScheduled
    // before the image is used by CoreAnimation or WebGL later.
    // However, when it's not thread safe (DrDC is disabled), we defer the wait
    // on this device until CoreAnimation or WebGL actually needs to access the
    // image. This could avoid repeated and unnecessary waits.
    // TODO(b/328411251): Investigate whether this is needed if the access
    // is readonly.
    if (iosurface_backing->is_thread_safe()) {
      dawn::native::metal::WaitForCommandsToBeScheduled(device_.Get());
    } else {
      iosurface_backing->AddWGPUDeviceWithPendingCommands(device_);
    }
  }

  texture_ = nullptr;
  usage_ = internal_usage_ = wgpu::TextureUsage::None;
}

///////////////////////////////////////////////////////////////////////////////
// SkiaGraphiteDawnMetalRepresentation

class IOSurfaceImageBacking::SkiaGraphiteDawnMetalRepresentation
    : public SkiaGraphiteDawnImageRepresentation {
 public:
  using SkiaGraphiteDawnImageRepresentation::
      SkiaGraphiteDawnImageRepresentation;
  ~SkiaGraphiteDawnMetalRepresentation() override = default;

  bool SupportsMultipleConcurrentReadAccess() final;
};

// Enabling this functionality reduces overhead in the compositor by lowering
// the frequency of begin/end access pairs. The semantic constraints for a
// representation being able to return true are the following:
// * It is valid to call BeginScopedReadAccess() concurrently on two
//   different representations of the same image
// * The backing supports true concurrent read access rather than emulating
//   concurrent reads by "pausing" a first read when a second read of a
//   different representation type begins, which requires that the second
//   representation's read finish within the scope of its GPU task in order
//   to ensure that nothing actually accesses the first representation
//   while it is paused. Some backings that support only exclusive access
//   from the SI perspective do the latter (e.g.,
//   ExternalVulkanImageBacking as its "support" of concurrent GL and
//   Vulkan access). SupportsMultipleConcurrentReadAccess() results in the
//   compositor's read access being long-lived (i.e., beyond the scope of
//   a single GPU task).
// This representation meets both of the above constraints.
bool IOSurfaceImageBacking::SkiaGraphiteDawnMetalRepresentation::
    SupportsMultipleConcurrentReadAccess() {
  return true;
}

///////////////////////////////////////////////////////////////////////////////
// IOSurfaceImageBacking

IOSurfaceImageBacking::IOSurfaceImageBacking(
    gfx::ScopedIOSurface io_surface,
    gfx::GenericSharedMemoryId io_surface_id,
    const Mailbox& mailbox,
    viz::SharedImageFormat format,
    const gfx::Size& size,
    const gfx::ColorSpace& color_space,
    GrSurfaceOrigin surface_origin,
    SkAlphaType alpha_type,
    gpu::SharedImageUsageSet usage,
    std::string debug_label,
    GLenum gl_target,
    bool framebuffer_attachment_angle,
    bool is_cleared,
    bool is_thread_safe,
    GrContextType gr_context_type,
    std::optional<gfx::BufferUsage> buffer_usage)
    : ClearTrackingSharedImageBacking(mailbox,
                                      format,
                                      size,
                                      color_space,
                                      surface_origin,
                                      alpha_type,
                                      usage,
                                      std::move(debug_label),
                                      format.EstimatedSizeInBytes(size),
                                      is_thread_safe,
                                      std::move(buffer_usage)),
      io_surface_(std::move(io_surface)),
      io_surface_size_(IOSurfaceGetWidth(io_surface_.get()),
                       IOSurfaceGetHeight(io_surface_.get())),
      io_surface_format_(IOSurfaceGetPixelFormat(io_surface_.get())),
      io_surface_id_(io_surface_id),
      dawn_texture_cache_(base::MakeRefCounted<DawnSharedTextureCache>()),
      gl_target_(gl_target),
      framebuffer_attachment_angle_(framebuffer_attachment_angle),
      weak_factory_(this) {
  CHECK(io_surface_);
  CHECK(!is_thread_safe ||
        base::FeatureList::IsEnabled(features::kIOSurfaceMultiThreading));

  // If this will be bound to different GL backends, then make RetainGLTexture
  // and ReleaseGLTexture actually create and destroy the texture.
  // https://crbug.com/1251724
  if (usage.Has(SHARED_IMAGE_USAGE_HIGH_PERFORMANCE_GPU)) {
    return;
  }

  SetClearedRectInternal((is_cleared ? gfx::Rect(size) : gfx::Rect()));

  // NOTE: Mac currently retains GLTexture and reuses it. This might lead to
  // issues with context losses, but is also beneficial to performance at
  // least on perf benchmarks.
  if (gr_context_type == GrContextType::kGL) {
    // NOTE: We do not CHECK here that the current GL context is that of the
    // SharedContextState due to not having easy access to the
    // SharedContextState here. However, all codepaths that create SharedImage
    // backings make the SharedContextState's context current before doing so.
    egl_state_for_skia_gl_context_ = RetainGLTexture();
  }
}

IOSurfaceImageBacking::~IOSurfaceImageBacking() {
  AutoLock auto_lock(this);
  if (egl_state_for_skia_gl_context_) {
    egl_state_for_skia_gl_context_->WillRelease(have_context());

    if (egl_state_for_skia_gl_context_->created_task_runner()
            ->BelongsToCurrentThread()) {
      egl_state_for_skia_gl_context_ = nullptr;
    } else {
      // Remove `egl_state` from `egl_state_map_`.
      IOSurfaceBackingEGLState* egl_state =
          egl_state_for_skia_gl_context_.get();
      auto key = std::make_pair(egl_state->egl_display_,
                                egl_state->created_task_runner());
      auto found = egl_state_map_.find(key);
      CHECK(found != egl_state_map_.end());
      CHECK(found->second == egl_state);
      egl_state_map_.erase(found);

      // Send egl_state to the original thread for delete. Making
      // the original context current can only be done on the same thread.
      egl_state_for_skia_gl_context_->RemoveClient();
      base::SingleThreadTaskRunner* task_runner =
          egl_state_for_skia_gl_context_->created_task_runner_.get();
      task_runner->PostTask(FROM_HERE, base::DoNothingWithBoundArgs(std::move(
                                           egl_state_for_skia_gl_context_)));
    }
  }
  DCHECK(egl_state_map_.empty());
}

bool IOSurfaceImageBacking::ReadbackToMemory(
    const std::vector<SkPixmap>& pixmaps) {
  AutoLock auto_lock(this);
  CHECK_LE(pixmaps.size(), 3u);

  // Make sure any pending ANGLE EGLDisplays and Dawn devices are flushed.
  WaitForCommandsToBeScheduled();

  ScopedIOSurfaceLock io_surface_lock(io_surface_.get(),
                                      kIOSurfaceLockReadOnly);

  for (int plane_index = 0; plane_index < static_cast<int>(pixmaps.size());
       ++plane_index) {
    const gfx::Size plane_size = format().GetPlaneSize(plane_index, size());

    const void* io_surface_base_address =
        IOSurfaceGetBaseAddressOfPlane(io_surface_.get(), plane_index);
    DCHECK_EQ(plane_size.width(), static_cast<int>(IOSurfaceGetWidthOfPlane(
                                      io_surface_.get(), plane_index)));
    DCHECK_EQ(plane_size.height(), static_cast<int>(IOSurfaceGetHeightOfPlane(
                                       io_surface_.get(), plane_index)));

    int io_surface_row_bytes = 0;
    int dst_bytes_per_row = 0;

    base::CheckedNumeric<int> checked_io_surface_row_bytes =
        IOSurfaceGetBytesPerRowOfPlane(io_surface_.get(), plane_index);
    base::CheckedNumeric<int> checked_dst_bytes_per_row =
        pixmaps[plane_index].rowBytes();

    if (!checked_io_surface_row_bytes.AssignIfValid(&io_surface_row_bytes) ||
        !checked_dst_bytes_per_row.AssignIfValid(&dst_bytes_per_row)) {
      return false;
    }

    const uint8_t* src_ptr =
        static_cast<const uint8_t*>(io_surface_base_address);
    uint8_t* dst_ptr =
        static_cast<uint8_t*>(pixmaps[plane_index].writable_addr());

    const int copy_bytes =
        static_cast<int>(pixmaps[plane_index].info().minRowBytes());
    DCHECK_LE(copy_bytes, io_surface_row_bytes);
    DCHECK_LE(copy_bytes, dst_bytes_per_row);

    CopyImagePlane(src_ptr, io_surface_row_bytes, dst_ptr, dst_bytes_per_row,
                   copy_bytes, plane_size.height());
  }

  return true;
}

bool IOSurfaceImageBacking::UploadFromMemory(
    const std::vector<SkPixmap>& pixmaps) {
  AutoLock auto_lock(this);
  CHECK_LE(pixmaps.size(), 3u);

  // Make sure any pending ANGLE EGLDisplays and Dawn devices are flushed.
  WaitForCommandsToBeScheduled();

  ScopedIOSurfaceLock io_surface_lock(io_surface_.get(), /*options=*/0);

  for (int plane_index = 0; plane_index < static_cast<int>(pixmaps.size());
       ++plane_index) {
    const gfx::Size plane_size = format().GetPlaneSize(plane_index, size());

    void* io_surface_base_address =
        IOSurfaceGetBaseAddressOfPlane(io_surface_.get(), plane_index);
    DCHECK_EQ(plane_size.width(), static_cast<int>(IOSurfaceGetWidthOfPlane(
                                      io_surface_.get(), plane_index)));
    DCHECK_EQ(plane_size.height(), static_cast<int>(IOSurfaceGetHeightOfPlane(
                                       io_surface_.get(), plane_index)));

    int io_surface_row_bytes = 0;
    int src_bytes_per_row = 0;

    base::CheckedNumeric<int> checked_io_surface_row_bytes =
        IOSurfaceGetBytesPerRowOfPlane(io_surface_.get(), plane_index);
    base::CheckedNumeric<int> checked_src_bytes_per_row =
        pixmaps[plane_index].rowBytes();

    if (!checked_io_surface_row_bytes.AssignIfValid(&io_surface_row_bytes) ||
        !checked_src_bytes_per_row.AssignIfValid(&src_bytes_per_row)) {
      return false;
    }

    const uint8_t* src_ptr =
        static_cast<const uint8_t*>(pixmaps[plane_index].addr());

    const int copy_bytes =
        static_cast<int>(pixmaps[plane_index].info().minRowBytes());
    DCHECK_LE(copy_bytes, src_bytes_per_row);
    DCHECK_LE(copy_bytes, io_surface_row_bytes);

    uint8_t* dst_ptr = static_cast<uint8_t*>(io_surface_base_address);

    CopyImagePlane(src_ptr, src_bytes_per_row, dst_ptr, io_surface_row_bytes,
                   copy_bytes, plane_size.height());
  }

  return true;
}

scoped_refptr<IOSurfaceBackingEGLState>
IOSurfaceImageBacking::RetainGLTexture() {
  AutoLock auto_lock(this);

  gl::GLContext* context = gl::GLContext::GetCurrent();
  gl::GLDisplayEGL* display = context ? context->GetGLDisplayEGL() : nullptr;
  if (!display) {
    LOG(ERROR) << "No GLDisplayEGL current.";
    return nullptr;
  }
  const EGLDisplay egl_display = display->GetDisplay();

  auto key = std::make_pair(egl_display,
                            base::SingleThreadTaskRunner::GetCurrentDefault());
  auto found = egl_state_map_.find(key);
  if (found != egl_state_map_.end())
    return found->second;

  std::vector<scoped_refptr<gles2::TexturePassthrough>> gl_textures;
  for (int plane_index = 0; plane_index < format().NumberOfPlanes();
       plane_index++) {
    // Allocate the GL texture.
    scoped_refptr<gles2::TexturePassthrough> gl_texture;
    MakeTextureAndSetParameters(gl_target_, framebuffer_attachment_angle_,
                                &gl_texture, nullptr);
    // Set the IOSurface to be initially unbound from the GL texture.
    gl_texture->SetEstimatedSize(format().EstimatedSizeInBytes(size()));

    gl_textures.push_back(std::move(gl_texture));
  }

  scoped_refptr<IOSurfaceBackingEGLState> egl_state =
      new IOSurfaceBackingEGLState(this, egl_display, context,
                                   gl::GLSurface::GetCurrent(), gl_target_,
                                   std::move(gl_textures));
  egl_state->set_bind_pending();
  return egl_state;
}

void IOSurfaceImageBacking::ReleaseGLTexture(
    IOSurfaceBackingEGLState* egl_state,
    bool have_context) {
  AssertLockAcquired();
  DCHECK_EQ(static_cast<int>(egl_state->gl_textures_.size()),
            format().NumberOfPlanes());
  DCHECK(egl_state->egl_surfaces_.empty() ||
         static_cast<int>(egl_state->egl_surfaces_.size()) ==
             format().NumberOfPlanes());

  if (!have_context) {
    for (const auto& texture : egl_state->gl_textures_) {
      texture->MarkContextLost();
    }
  }
  egl_state->gl_textures_.clear();
}

base::trace_event::MemoryAllocatorDump* IOSurfaceImageBacking::OnMemoryDump(
    const std::string& dump_name,
    base::trace_event::MemoryAllocatorDumpGuid client_guid,
    base::trace_event::ProcessMemoryDump* pmd,
    uint64_t client_tracing_id) {
  auto* dump = SharedImageBacking::OnMemoryDump(dump_name, client_guid, pmd,
                                                client_tracing_id);

  size_t size_bytes = 0u;
  for (int plane = 0; plane < format().NumberOfPlanes(); plane++) {
    size_bytes += IOSurfaceGetBytesPerRowOfPlane(io_surface_.get(), plane) *
                  IOSurfaceGetHeightOfPlane(io_surface_.get(), plane);
  }

  dump->AddScalar(base::trace_event::MemoryAllocatorDump::kNameSize,
                  base::trace_event::MemoryAllocatorDump::kUnitsBytes,
                  static_cast<uint64_t>(size_bytes));

  // The client tracing id is to identify the GpuMemoryBuffer client that
  // created the allocation. For CVPixelBufferRefs, there is no corresponding
  // GpuMemoryBuffer, so use an invalid client id.
  if (usage().Has(SHARED_IMAGE_USAGE_MACOS_VIDEO_TOOLBOX)) {
    client_tracing_id =
        base::trace_event::MemoryDumpManager::kInvalidTracingProcessId;
  }

  // Create an edge using the GMB GenericSharedMemoryId if the image is not
  // anonymous. Otherwise, add another nested node to account for the anonymous
  // IOSurface.
  if (io_surface_id_.is_valid()) {
    auto guid = GetGenericSharedGpuMemoryGUIDForTracing(client_tracing_id,
                                                        io_surface_id_);
    pmd->CreateSharedGlobalAllocatorDump(guid);
    pmd->AddOwnershipEdge(dump->guid(), guid);
  } else {
    std::string anonymous_dump_name = dump_name + "/anonymous-iosurface";
    base::trace_event::MemoryAllocatorDump* anonymous_dump =
        pmd->CreateAllocatorDump(anonymous_dump_name);
    anonymous_dump->AddScalar(
        base::trace_event::MemoryAllocatorDump::kNameSize,
        base::trace_event::MemoryAllocatorDump::kUnitsBytes,
        static_cast<uint64_t>(size_bytes));
    anonymous_dump->AddScalar("width", "pixels", size().width());
    anonymous_dump->AddScalar("height", "pixels", size().height());
  }

  return dump;
}

SharedImageBackingType IOSurfaceImageBacking::GetType() const {
  return SharedImageBackingType::kIOSurface;
}

std::unique_ptr<GLTextureImageRepresentation>
IOSurfaceImageBacking::ProduceGLTexture(SharedImageManager* manager,
                                        MemoryTypeTracker* tracker) {
  return nullptr;
}

std::unique_ptr<GLTexturePassthroughImageRepresentation>
IOSurfaceImageBacking::ProduceGLTexturePassthrough(SharedImageManager* manager,
                                                   MemoryTypeTracker* tracker) {
  scoped_refptr<IOSurfaceBackingEGLState> egl_state;
  egl_state = RetainGLTexture();

  // The corresponding release will be done when the returned representation is
  // destroyed, in GLTextureImageRepresentationBeingDestroyed.
  return std::make_unique<GLTextureIRepresentation>(
      manager, this, std::move(egl_state), tracker);
}

std::unique_ptr<OverlayImageRepresentation>
IOSurfaceImageBacking::ProduceOverlay(SharedImageManager* manager,
                                      MemoryTypeTracker* tracker) {
  return std::make_unique<OverlayRepresentation>(manager, this, tracker,
                                                 io_surface_);
}

int IOSurfaceImageBacking::TrackBeginAccessToWGPUTexture(
    wgpu::Texture texture) {
  AssertLockAcquired();

  return wgpu_texture_ongoing_accesses_[texture.Get()]++;
}

int IOSurfaceImageBacking::TrackEndAccessToWGPUTexture(wgpu::Texture texture) {
  AssertLockAcquired();

  if (!wgpu_texture_ongoing_accesses_.contains(texture.Get())) {
    return 0;
  }

  int num_outstanding_accesses =
      --wgpu_texture_ongoing_accesses_[texture.Get()];
  CHECK_GE(num_outstanding_accesses, 0);

  if (num_outstanding_accesses == 0) {
    wgpu_texture_ongoing_accesses_.erase(texture.Get());
  }

  return num_outstanding_accesses;
}

const scoped_refptr<DawnSharedTextureCache>&
IOSurfaceImageBacking::GetDawnTextureCache() {
  AssertLockAcquired();
  return dawn_texture_cache_;
}

void IOSurfaceImageBacking::AddWGPUDeviceWithPendingCommands(
    wgpu::Device device) {
  AssertLockAcquired();
  wgpu_devices_pending_flush_.insert(std::move(device));
}

void IOSurfaceImageBacking::WaitForCommandsToBeScheduled(
    id<MTLDevice> waiting_device) {
  AssertLockAcquired();
  TRACE_EVENT0("gpu", "IOSurfaceImageBacking::WaitForCommandsToBeScheduled");

  std::vector<wgpu::Device> wgpu_devices_to_keep;
  for (const auto& device : wgpu_devices_pending_flush_) {
    // Only Metal backed devices are added to `wgpu_devices_pending_flush_`.
    id<MTLDevice> mtl_device = dawn::native::metal::GetMTLDevice(device.Get());
    if (mtl_device && mtl_device == waiting_device) {
      wgpu_devices_to_keep.push_back(device);
      continue;
    }
    TRACE_EVENT0("gpu",
                 "IOSurfaceImageBacking::WaitForCommandsToBeScheduled::Dawn");
    dawn::native::metal::WaitForCommandsToBeScheduled(device.Get());
  }
  wgpu_devices_pending_flush_ = std::move(wgpu_devices_to_keep);

  std::vector<gl::GLDisplayEGL*> egl_displays_to_keep;
  for (auto* display : egl_displays_pending_flush_) {
    // Always flush work for any ANGLE-OpenGL EGLDisplays.
    if (gl::GetANGLEImplementation() == gl::ANGLEImplementation::kMetal &&
        QueryMetalDeviceFromANGLE(display) == waiting_device) {
      egl_displays_to_keep.push_back(display);
      continue;
    }
    TRACE_EVENT0("gpu",
                 "IOSurfaceImageBacking::WaitForCommandsToBeScheduled::ANGLE");
    eglWaitUntilWorkScheduledANGLE(display->GetDisplay());
  }
  egl_displays_pending_flush_ = std::move(egl_displays_to_keep);
}

void IOSurfaceImageBacking::AddEGLDisplayWithPendingCommands(
    gl::GLDisplayEGL* display) {
  AssertLockAcquired();
  egl_displays_pending_flush_.insert(display);
}

void IOSurfaceImageBacking::ClearEGLDisplaysWithPendingCommands(
    gl::GLDisplayEGL* display_to_keep) {
  AssertLockAcquired();

  if (std::move(egl_displays_pending_flush_).contains(display_to_keep)) {
    egl_displays_pending_flush_.insert(display_to_keep);
  }
}

std::unique_ptr<DawnImageRepresentation> IOSurfaceImageBacking::ProduceDawn(
    SharedImageManager* manager,
    MemoryTypeTracker* tracker,
    const wgpu::Device& device,
    wgpu::BackendType backend_type,
    std::vector<wgpu::TextureFormat> view_formats,
    scoped_refptr<SharedContextState> context_state) {
  wgpu::TextureFormat wgpu_format = ToDawnFormat(format());
  // See comments in IOSurfaceImageBackingFactory::CreateSharedImage about
  // RGBA versus BGRA when using Skia Ganesh GL backend or ANGLE.
  if (io_surface_format_ == 'BGRA') {
    wgpu_format = wgpu::TextureFormat::BGRA8Unorm;
  }
  if (wgpu_format == wgpu::TextureFormat::Undefined) {
    LOG(ERROR) << "Unsupported format for Dawn: " << format().ToString();
    return nullptr;
  }

  if (backend_type == wgpu::BackendType::Metal) {
    wgpu::SharedTextureMemory shared_texture_memory;
    {
      AutoLock auto_lock(this);

      // Clear out any cached SharedTextureMemory instances for which the
      // associated Device has been lost - this both saves memory and more
      // importantly ensures that a new SharedTextureMemory instance will be
      // created if another Device occupies the same memory as a
      // previously-used, now-lost Device.
      dawn_texture_cache_->EraseDataIfDeviceLost();

      CHECK(device.HasFeature(wgpu::FeatureName::SharedTextureMemoryIOSurface));

      shared_texture_memory =
          dawn_texture_cache_->GetSharedTextureMemory(device);
      if (!shared_texture_memory) {
        // NOTE: `shared_dawn_context` may be null if Graphite is not being
        // used.
        const auto* shared_dawn_context =
            context_state->dawn_context_provider();
        const bool is_graphite_device =
            shared_dawn_context &&
            shared_dawn_context->GetDevice().Get() == device.Get();

        wgpu::SharedTextureMemoryIOSurfaceDescriptor io_surface_desc;
        io_surface_desc.ioSurface = io_surface_.get();
        // Set storage binding usage only if explicitly needed for WebGPU - this
        // forces the MTLTexture wrapping the IOSurface to have ShaderWrite
        // usage which in turn prevents texture compression. It's possible this
        // doesn't have any effect given that IOSurfaces have linear layout, but
        // it might if the kernel chooses to create a separate allocation for
        // the GPU.
        io_surface_desc.allowStorageBinding =
            (usage() & SHARED_IMAGE_USAGE_WEBGPU_STORAGE_TEXTURE) &&
            !is_graphite_device;

        wgpu::SharedTextureMemoryDescriptor desc = {};
        desc.nextInChain = &io_surface_desc;

        shared_texture_memory = device.ImportSharedTextureMemory(&desc);
        // If ImportSharedTextureMemory is not successful and the device is not
        // lost, an error SharedTextureMemory object will be returned, which
        // will cause an error upon usage.
        if (shared_texture_memory.IsDeviceLost()) {
          LOG(ERROR)
              << "Failed to create shared texture memory due to device loss.";
          return nullptr;
        }

        // We cache the SharedTextureMemory instance that is associated with the
        // Graphite device.
        // TODO(crbug.com/345674550): Extend caching to WebGPU devices as well.
        if (is_graphite_device) {
          // This is the Graphite device, so we cache its SharedTextureMemory
          // instance.
          dawn_texture_cache_->MaybeCacheSharedTextureMemory(
              device, shared_texture_memory);
        }
      }
    }

    // SharedImageRepresentation handles lock.
    return std::make_unique<DawnRepresentation>(
        manager, this, tracker, wgpu::Device(device),
        std::move(shared_texture_memory), io_surface_size_, wgpu_format,
        std::move(view_formats));
  }

  CHECK_EQ(backend_type, wgpu::BackendType::Vulkan);
  return std::make_unique<DawnFallbackImageRepresentation>(
      manager, this, tracker, wgpu::Device(device), wgpu_format,
      std::move(view_formats));
}

std::unique_ptr<SkiaGaneshImageRepresentation>
IOSurfaceImageBacking::ProduceSkiaGanesh(
    SharedImageManager* manager,
    MemoryTypeTracker* tracker,
    scoped_refptr<SharedContextState> context_state) {
  scoped_refptr<IOSurfaceBackingEGLState> egl_state;
  std::vector<sk_sp<GrPromiseImageTexture>> promise_textures;

  if (context_state->GrContextIsGL()) {
    egl_state = RetainGLTexture();
  }

  {
    AutoLock auto_lock(this);
    for (int plane_index = 0; plane_index < format().NumberOfPlanes();
         plane_index++) {
      GLFormatDesc format_desc =
          context_state->GetGLFormatCaps().ToGLFormatDesc(format(),
                                                          plane_index);
      GrBackendTexture backend_texture;
      auto plane_size = format().GetPlaneSize(plane_index, size());
      GetGrBackendTexture(
          context_state->feature_info(), egl_state->GetGLTarget(), plane_size,
          egl_state->GetGLServiceId(plane_index),
          format_desc.storage_internal_format,
          context_state->gr_context()->threadSafeProxy(), &backend_texture);
      sk_sp<GrPromiseImageTexture> promise_texture =
          GrPromiseImageTexture::Make(backend_texture);
      if (!promise_texture) {
        return nullptr;
      }
      promise_textures.push_back(std::move(promise_texture));
    }
  }

  return std::make_unique<SkiaGaneshRepresentation>(manager, this, egl_state,
                                                    std::move(context_state),
                                                    promise_textures, tracker);
}

std::unique_ptr<SkiaGraphiteImageRepresentation>
IOSurfaceImageBacking::ProduceSkiaGraphite(
    SharedImageManager* manager,
    MemoryTypeTracker* tracker,
    scoped_refptr<SharedContextState> context_state) {
  CHECK(context_state);
  if (context_state->IsGraphiteDawn()) {
#if BUILDFLAG(SKIA_USE_DAWN)
    // No AutoLock here. Lock is handled in ProduceDawn().
    auto device = context_state->dawn_context_provider()->GetDevice();
    auto backend_type = context_state->dawn_context_provider()->backend_type();
    auto dawn_representation =
        ProduceDawn(manager, tracker, device, backend_type, /*view_formats=*/{},
                    context_state);
    if (!dawn_representation) {
      LOG(ERROR) << "Could not create Dawn Representation";
      return nullptr;
    }

    // Use GPU main recorder since this should only be called for
    // fulfilling Graphite promise images on GPU main thread.
    if (backend_type == wgpu::BackendType::Metal) {
      return std::make_unique<SkiaGraphiteDawnMetalRepresentation>(
          std::move(dawn_representation), context_state,
          context_state->gpu_main_graphite_recorder(), manager, this, tracker);
    }

    // Use default skia representation
    CHECK_EQ(backend_type, wgpu::BackendType::Vulkan);
    return std::make_unique<SkiaGraphiteDawnImageRepresentation>(
        std::move(dawn_representation), context_state,
        context_state->gpu_main_graphite_recorder(), manager, this, tracker);
#else
    NOTREACHED();
#endif
  } else {
    CHECK(context_state->IsGraphiteMetal());
#if BUILDFLAG(SKIA_USE_METAL)
    std::vector<base::apple::scoped_nsprotocol<id<MTLTexture>>> mtl_textures;
    mtl_textures.reserve(format().NumberOfPlanes());

    for (int plane = 0; plane < format().NumberOfPlanes(); plane++) {
      auto plane_size = format().GetPlaneSize(plane, size());
      base::apple::scoped_nsprotocol<id<MTLTexture>> mtl_texture =
          CreateMetalTexture(
              context_state->metal_context_provider()->GetMTLDevice(),
              io_surface_.get(), plane_size, format(), plane);
      if (!mtl_texture) {
        LOG(ERROR) << "Failed to create MTLTexture from IOSurface";
        return nullptr;
      }
      mtl_textures.push_back(std::move(mtl_texture));
    }

    // Use GPU main recorder since this should only be called for
    // fulfilling Graphite promise images on GPU main thread.
    return std::make_unique<SkiaGraphiteMetalRepresentation>(
        manager, this, tracker, context_state->gpu_main_graphite_recorder(),
        std::move(mtl_textures));
#else
    NOTREACHED();
#endif
  }
}

void IOSurfaceImageBacking::SetPurgeable(bool purgeable) {
  AutoLock auto_lock(this);
  if (purgeable_ == purgeable)
    return;
  purgeable_ = purgeable;

  if (purgeable) {
    // It is in error to purge the surface while reading or writing to it.
    DCHECK(!ongoing_write_access_);
    DCHECK(!num_ongoing_read_accesses_);

    SetClearedRectInternal(gfx::Rect());
  }

  uint32_t old_state;
  IOSurfaceSetPurgeable(io_surface_.get(), purgeable, &old_state);
}

bool IOSurfaceImageBacking::IsPurgeable() const {
  AutoLock auto_lock(this);
  return purgeable_;
}

void IOSurfaceImageBacking::Update(std::unique_ptr<gfx::GpuFence> in_fence) {
  AutoLock auto_lock(this);
#if BUILDFLAG(IS_IOS)
  {
    // On iOS, we can't use IOKit to access IOSurfaces in the renderer process,
    // so we share the memory segment backing the IOSurface as shared memory
    // which is then mapped in the renderer process. We need to signal that the
    // IOSurface was updated on the CPU so we do an IOSurfaceLock+Unlock here in
    // case there are other consumers of the IOSurface that rely on its internal
    // seed value to detect updates - the lock+unlock updates the seed value.
    // TODO(crbug.com/40254930): Assert that we have CPU_WRITE_ONLY usage so
    // that we never have the client's CPU-written data overwritten due to a
    // shadow copy from the GPU - we can also use kIOSurfaceLockAvoidSync then.
    ScopedIOSurfaceLock io_surface_lock(io_surface_.get(), /*options=*/0);
  }
#endif
  for (auto iter : egl_state_map_) {
    iter.second->set_bind_pending();
  }
}

gfx::GpuMemoryBufferHandle IOSurfaceImageBacking::GetGpuMemoryBufferHandle() {
  gfx::GpuMemoryBufferHandle handle;
  handle.type = gfx::IO_SURFACE_BUFFER;
  handle.io_surface = io_surface_;
  return handle;
}

bool IOSurfaceImageBacking::BeginAccess(bool readonly) {
  AssertLockAcquired();

  CHECK_GE(num_ongoing_read_accesses_, 0);

  if (!readonly && ongoing_write_access_) {
    DLOG(ERROR) << "Unable to begin write access because another "
                   "write access is in progress";
    return false;
  }
  // Track reads and writes if not being used for concurrent read/writes.
  if (!(usage().Has(SHARED_IMAGE_USAGE_CONCURRENT_READ_WRITE))) {
    if (readonly && ongoing_write_access_) {
      DLOG(ERROR) << "Unable to begin read access because another "
                     "write access is in progress";
      return false;
    }
    if (!readonly && num_ongoing_read_accesses_ > 0) {
      DLOG(ERROR) << "Unable to begin write access because a read access is in "
                     "progress";
      return false;
    }
  }

  if (readonly) {
    num_ongoing_read_accesses_++;
  } else {
    ongoing_write_access_ = true;
  }

  return true;
}

void IOSurfaceImageBacking::EndAccess(bool readonly) {
  AssertLockAcquired();

  if (readonly) {
    CHECK_GT(num_ongoing_read_accesses_, 0);
    if (!(usage().Has(SHARED_IMAGE_USAGE_CONCURRENT_READ_WRITE))) {
      CHECK(!ongoing_write_access_);
    }
    num_ongoing_read_accesses_--;
  } else {
    CHECK(ongoing_write_access_);
    if (!(usage().Has(SHARED_IMAGE_USAGE_CONCURRENT_READ_WRITE))) {
      CHECK_EQ(num_ongoing_read_accesses_, 0);
    }
    ongoing_write_access_ = false;
  }
}

bool IOSurfaceImageBacking::IOSurfaceBackingEGLStateBeginAccess(
    IOSurfaceBackingEGLState* egl_state,
    bool readonly) {
  AssertLockAcquired();

  // It is in error to read or write an IOSurface while it is purgeable.
  CHECK(!purgeable_);
  if (!BeginAccess(readonly)) {
    return false;
  }

  CHECK_GE(egl_state->num_ongoing_accesses_, 0);

  gl::GLDisplayEGL* display = gl::GLDisplayEGL::GetDisplayForCurrentContext();
  CHECK(display);
  CHECK_EQ(display->GetDisplay(), egl_state->egl_display_);

  // Note that we don't need to call WaitForCommandsToBeScheduled for other
  // EGLDisplays because it is already done when the previous GL context is made
  // uncurrent. We can simply remove the other EGLDisplays from the list.
  ClearEGLDisplaysWithPendingCommands(/*display_to_keep=*/display);

  // IOSurface might be written on a different queue. So we have to wait for the
  // previous Dawn and ANGLE commands to be scheduled first so that the kernel
  // knows about the pending update to the IOSurface.
  WaitForCommandsToBeScheduled(QueryMetalDeviceFromANGLE(display));

  if (gl::GetANGLEImplementation() == gl::ANGLEImplementation::kMetal) {
    // If this image could potentially be shared with another Metal device,
    // it's necessary to synchronize between the two devices. If any Metal
    // shared events have been enqueued (the assumption is that this was done by
    // for a Dawn device or another ANGLE Metal EGLDisplay), wait on them.
    ProcessSharedEventsForBeginAccess(
        readonly,
        [display](id<MTLSharedEvent> shared_event, uint64_t signaled_value) {
          display->WaitForMetalSharedEvent(shared_event, signaled_value);
        });
  }

  // If the GL texture is already bound (the bind is not marked as pending),
  // then early-out.
  if (!egl_state->is_bind_pending()) {
    CHECK(!egl_state->egl_surfaces_.empty());
    egl_state->num_ongoing_accesses_++;
    return true;
  }

  if (egl_state->egl_surfaces_.empty()) {
    std::vector<std::unique_ptr<gl::ScopedEGLSurfaceIOSurface>> egl_surfaces;
    for (int plane_index = 0; plane_index < format().NumberOfPlanes();
         plane_index++) {
      gfx::BufferFormat buffer_format;
      if (format().is_single_plane()) {
        buffer_format = ToBufferFormat(format());
        // See comments in IOSurfaceImageBackingFactory::CreateSharedImage about
        // RGBA versus BGRA when using Skia Ganesh GL backend or ANGLE.
        if (io_surface_format_ == 'BGRA') {
          if (buffer_format == gfx::BufferFormat::RGBA_8888) {
            buffer_format = gfx::BufferFormat::BGRA_8888;
          } else if (buffer_format == gfx::BufferFormat::RGBX_8888) {
            buffer_format = gfx::BufferFormat::BGRX_8888;
          }
        }
      } else {
        // For multiplanar formats (without external sampler) get planar buffer
        // format.
        buffer_format = GetBufferFormatForPlane(format(), plane_index);
      }

      auto egl_surface = gl::ScopedEGLSurfaceIOSurface::Create(
          egl_state->egl_display_, egl_state->GetGLTarget(), io_surface_.get(),
          plane_index, buffer_format);
      if (!egl_surface) {
        LOG(ERROR) << "Failed to create ScopedEGLSurfaceIOSurface.";
        EndAccess(readonly);
        return false;
      }

      egl_surfaces.push_back(std::move(egl_surface));
    }
    egl_state->egl_surfaces_ = std::move(egl_surfaces);
  }

  CHECK_EQ(static_cast<int>(egl_state->gl_textures_.size()),
           format().NumberOfPlanes());
  CHECK_EQ(static_cast<int>(egl_state->egl_surfaces_.size()),
           format().NumberOfPlanes());
  for (int plane_index = 0; plane_index < format().NumberOfPlanes();
       plane_index++) {
    gl::ScopedRestoreTexture scoped_restore(
        gl::g_current_gl_context, egl_state->GetGLTarget(),
        egl_state->GetGLServiceId(plane_index));
    // Un-bind the IOSurface from the GL texture (this will be a no-op if it is
    // not yet bound).
    egl_state->egl_surfaces_[plane_index]->ReleaseTexImage();

    // Bind the IOSurface to the GL texture.
    if (!egl_state->egl_surfaces_[plane_index]->BindTexImage()) {
      LOG(ERROR) << "Failed to bind ScopedEGLSurfaceIOSurface to target.";
      EndAccess(readonly);
      return false;
    }
  }
  egl_state->clear_bind_pending();
  egl_state->num_ongoing_accesses_++;

  return true;
}

void IOSurfaceImageBacking::IOSurfaceBackingEGLStateEndAccess(
    IOSurfaceBackingEGLState* egl_state,
    bool readonly) {
  AssertLockAcquired();

  // Early out if BeginAccess didn't succeed and we didn't bind any surfaces.
  if (egl_state->is_bind_pending()) {
    return;
  }

  CHECK_GT(egl_state->num_ongoing_accesses_, 0);
  egl_state->num_ongoing_accesses_--;

  EndAccess(readonly);

  gl::GLDisplayEGL* display = gl::GLDisplayEGL::GetDisplayForCurrentContext();
  CHECK(display);
  CHECK_EQ(display->GetDisplay(), egl_state->egl_display_);

  const bool is_angle_metal =
      gl::GetANGLEImplementation() == gl::ANGLEImplementation::kMetal;
  if (is_angle_metal) {
    id<MTLSharedEvent> shared_event = nil;
    uint64_t signal_value = 0;
    if (display->CreateMetalSharedEvent(&shared_event, &signal_value)) {
      AddSharedEventForEndAccess(shared_event, signal_value, readonly);
    } else {
      LOG(DFATAL) << "Failed to create Metal shared event";
    }
  }

  // We have to call eglWaitUntilWorkScheduledANGLE for IOSurface
  // synchronization by the kernel e.g. using waitUntilScheduled on Metal or
  // glFlush on OpenGL. Defer the call until CoreAnimation, Dawn, or another
  // ANGLE EGLDisplay needs to access to avoid unnecessary overhead. This also
  // ensures that the Metal shared event enqueued above is eventually flushed.
  if (is_thread_safe()) {
    // With DrDC and Graphite enabled, don't call
    // AddEGLDisplayWithPendingCommands to avoid the GL context flush on
    // the Viz thread.
    eglWaitUntilWorkScheduledANGLE(display->GetDisplay());
  } else {
    AddEGLDisplayWithPendingCommands(display);
  }

  // When SwANGLE is used as the GL implementation, it holds an internal
  // texture. We have to call ReleaseTexImage here to trigger a copy from that
  // internal texture to the IOSurface (the next Bind() will then trigger an
  // IOSurface->internal texture copy). We do this only when there are no
  // ongoing reads in order to ensure that it does not result in the GLES2
  // decoders needing to perform on-demand binding (rather, the binding will be
  // performed at the next BeginAccess()). Note that it is not sufficient to
  // release the image only at the end of a write: the CPU can write directly to
  // the IOSurface when the GPU is not accessing the internal texture (in the
  // case of zero-copy raster), and any such IOSurface-side modifications need
  // to be copied to the internal texture via a Bind() when the GPU starts a
  // subsequent read. Note also that this logic assumes that writes are
  // serialized with respect to reads (so that the end of a write always
  // triggers a release and copy). By design, IOSurfaceImageBackingFactory
  // enforces this property for this use case.
  //
  // For ANGLE Metal, we need to rebind the texture for two reasons:
  // 1) ReleaseTexImage flushes the command buffer which contains the shared
  //    event signal above, otherwise the shared event might never be signaled
  //    since we skip calling eglWaitUntilWorkScheduledANGLE in single GPU case.
  // 2) BindTexImage adds a synchronization dependency on the command buffer
  //    which contains the shared event wait before the next ANGLE access.
  //    Otherwise, ANGLE might skip waiting on the command buffer and hence the
  //    shared event and do a CPU readback from the IOSurface in some cases.
  const bool is_swangle =
      gl::GetANGLEImplementation() == gl::ANGLEImplementation::kSwiftShader;
  if ((is_swangle || is_angle_metal) && egl_state->num_ongoing_accesses_ == 0) {
    CHECK_EQ(static_cast<int>(egl_state->gl_textures_.size()),
             format().NumberOfPlanes());
    CHECK_EQ(static_cast<int>(egl_state->egl_surfaces_.size()),
             format().NumberOfPlanes());
    for (int plane_index = 0; plane_index < format().NumberOfPlanes();
         plane_index++) {
      gl::ScopedRestoreTexture scoped_restore(
          gl::g_current_gl_context, egl_state->GetGLTarget(),
          egl_state->GetGLServiceId(plane_index));
      egl_state->egl_surfaces_[plane_index]->ReleaseTexImage();
    }
    egl_state->set_bind_pending();
  }
}

void IOSurfaceImageBacking::IOSurfaceBackingEGLStateBeingCreated(
    IOSurfaceBackingEGLState* egl_state) {
  AssertLockAcquired();

  auto key =
      std::make_pair(egl_state->egl_display_, egl_state->created_task_runner());
  auto insert_result = egl_state_map_.insert(std::make_pair(key, egl_state));
  CHECK(insert_result.second);
}

void IOSurfaceImageBacking::IOSurfaceBackingEGLStateBeingDestroyed(
    IOSurfaceBackingEGLState* egl_state,
    bool has_context) {
  AssertLockAcquired();
  ReleaseGLTexture(egl_state, has_context);

  egl_state->egl_surfaces_.clear();

  // Remove `egl_state` from `egl_state_map_`.
  auto key =
      std::make_pair(egl_state->egl_display_, egl_state->created_task_runner());
  auto found = egl_state_map_.find(key);
  CHECK(found != egl_state_map_.end());
  CHECK(found->second == egl_state);
  egl_state_map_.erase(found);
}

bool IOSurfaceImageBacking::InitializePixels(
    base::span<const uint8_t> pixel_data) {
  AutoLock auto_lock(this);
  CHECK(format().is_single_plane());
  ScopedIOSurfaceLock io_surface_lock(io_surface_.get(),
                                      kIOSurfaceLockAvoidSync);

  uint8_t* dst_data = reinterpret_cast<uint8_t*>(
      IOSurfaceGetBaseAddressOfPlane(io_surface_.get(), 0));
  size_t dst_stride = IOSurfaceGetBytesPerRowOfPlane(io_surface_.get(), 0);

  const uint8_t* src_data = pixel_data.data();
  const size_t src_stride = (format().BitsPerPixel() / 8) * size().width();
  const size_t height = size().height();

  if (pixel_data.size() != src_stride * height) {
    DLOG(ERROR) << "Invalid initial pixel data size";
    return false;
  }

  for (size_t y = 0; y < height; ++y) {
    memcpy(dst_data, src_data, src_stride);
    dst_data += dst_stride;
    src_data += src_stride;
  }

  return true;
}

void IOSurfaceImageBacking::AddSharedEventForEndAccess(
    id<MTLSharedEvent> shared_event,
    uint64_t signal_value,
    bool readonly) {
  AssertLockAcquired();

  SharedEventMap& shared_events =
      readonly ? non_exclusive_shared_events_ : exclusive_shared_events_;
  auto [it, _] = shared_events.insert(
      {ScopedSharedEvent(shared_event, base::scoped_policy::RETAIN), 0});
  it->second = std::max(it->second, signal_value);
}

template <typename Fn>
void IOSurfaceImageBacking::ProcessSharedEventsForBeginAccess(bool readonly,
                                                              const Fn& fn) {
  AssertLockAcquired();

  // Always need wait on exclusive access end events.
  for (const auto& [shared_event, signal_value] : exclusive_shared_events_) {
    fn(shared_event.get(), signal_value);
  }

  if (!readonly) {
    // For read-write (exclusive) access, non execlusive access end events
    // should be waited on as well.
    for (const auto& [shared_event, signal_value] :
         non_exclusive_shared_events_) {
      fn(shared_event.get(), signal_value);
    }

    // Clear events, since this read-write (exclusive) access will provide an
    // event when the access is finished.
    exclusive_shared_events_.clear();
    non_exclusive_shared_events_.clear();
  }
}

}  // namespace gpu