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
//! One window that shows every way to composite pixels GPUI did not draw.
//!
//! ```sh
//! cargo run -p gpui --example surface
//! ```
//!
//! The window is a labelled grid of solid olive-green tiles. Each tile is one combination of an
//! **authoring layer** and a **payload**, and the grid is the point: the same colour reaches the
//! window whether it arrives through the `surface()` element or through a `gpu_canvas()` callback,
//! and whichever payload the host renderer can composite.
//!
//! # The two layers
//!
//! - `surface(source)` is an ordinary element. It lays out and stacks like any other child, and the
//! renderer samples `source` while it composites the frame.
//! - `gpu_canvas(..)` is a box whose content a paint-time callback supplies: it receives a
//! `GpuCanvasContext` and either paints a surface source into the canvas, or paints a texture the
//! producer rendered on the window's own device.
//!
//! # The payloads, by renderer
//!
//! Only the combinations the host renderer supports are built and shown; each is labelled in place.
//!
//! - **wgpu** (Linux): `surface()` carries a dma-buf handle in each of `Bgra8`, `Rgba8` and `Nv12`;
//! `gpu_canvas(..)` paints a `wgpu` texture view.
//! - **Direct3D 11** (Windows): `surface()` carries a `B8G8R8A8_UNORM` texture, and separately a
//! shader-resource view the producer made; `gpu_canvas(..)` paints a surface source.
//! - **Metal** (macOS): `surface()` carries a CoreVideo pixel buffer; `gpu_canvas(..)` paints the same
//! buffer and an `id<MTLTexture>`.
//!
//! # One colour, in each payload's own format
//!
//! Every tile is the same olive green. A single-plane payload stores it directly, in that format's
//! byte order; the two-plane `Nv12` payload stores the luma and chroma bytes the renderer's BT.601
//! conversion maps back to that green, and that conversion is worked out and commented where the
//! bytes are made.
//!
//! The producers are the platform's own: a bare Vulkan device exports the Linux dma-bufs, and the
//! window's device (or one the platform hands every creator) backs the textures. This is a working
//! application, not a sketch.
#[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
fn main() {
eprintln!(
"surface is a desktop example: it produces a GPU texture or dma-buf and composites it \
through the window's renderer. Run it on Linux, Windows or macOS."
);
}
#[cfg(any(target_os = "linux", target_os = "windows", target_os = "macos"))]
fn main() {
demo::run();
}
#[cfg(any(target_os = "linux", target_os = "windows", target_os = "macos"))]
mod demo {
use gpui::{
AnyElement, App, Bounds, Context, IntoElement, Render, Window, WindowBounds, WindowOptions,
div, prelude::*, px, rgb, size,
};
/// The produced surface size, in pixels; each element scales it into its tile.
const TILE: u32 = 128;
/// The demo's payload: SMPTE 75% colour bars, in the byte layout each format carries.
///
/// A card rather than a flat colour, because each bar is a known triple: a wrong channel order,
/// a transfer function applied the wrong way, or a mis-set row stride shows up as the wrong bar,
/// where a solid fill would look plausible. The card is the seven vertical bars of SMPTE RP 219
/// at 75% amplitude — grey, yellow, cyan, green, magenta, red, blue.
mod test_card {
/// The bars, left to right, as sRGB-encoded `u8` RGB.
const BARS: [[u8; 3]; 7] = [
[191, 191, 191],
[191, 191, 0],
[0, 191, 191],
[0, 191, 0],
[191, 0, 191],
[191, 0, 0],
[0, 0, 191],
];
/// The bar at column `x` of `width`, as an sRGB RGB triple.
fn bar(x: u32, width: u32) -> [u8; 3] {
BARS[(x * BARS.len() as u32 / width).min(BARS.len() as u32 - 1) as usize]
}
/// The card's pixel at `(x, y)` of a `width`-square image, as an sRGB RGB triple.
///
/// The top three quarters are the colour bars. The bottom quarter is fine detail in two
/// halves: left, one-pixel red/blue columns — colour detail a 4:2:0 chroma plane cannot
/// carry, so it smears toward purple; right, one-pixel black/white columns — luma detail,
/// which NV12 keeps. The pair shows what subsampling costs and what it does not.
pub fn pixel(x: u32, y: u32, width: u32) -> [u8; 3] {
if y < width * 3 / 4 {
return bar(x, width);
}
if x < width / 2 {
if x.is_multiple_of(2) {
[255, 0, 0]
} else {
[0, 0, 255]
}
} else if x.is_multiple_of(2) {
[0, 0, 0]
} else {
[255, 255, 255]
}
}
/// The card as 4-byte `Bgra8` pixels, row-major.
pub fn bgra8(width: u32) -> Vec<u8> {
let mut bytes = Vec::with_capacity((width * width * 4) as usize);
for y in 0..width {
for x in 0..width {
let [r, g, b] = pixel(x, y, width);
bytes.extend_from_slice(&[b, g, r, 255]);
}
}
bytes
}
/// The card as 4-byte `Rgba8` pixels, row-major.
#[cfg(target_os = "linux")]
pub fn rgba8(width: u32) -> Vec<u8> {
let mut bytes = Vec::with_capacity((width * width * 4) as usize);
for y in 0..width {
for x in 0..width {
let [r, g, b] = pixel(x, y, width);
bytes.extend_from_slice(&[r, g, b, 255]);
}
}
bytes
}
/// The card's full-resolution luma plane, `width`-square, full-range BT.601.
#[cfg(any(target_os = "linux", target_os = "macos"))]
pub fn luma(width: u32) -> Vec<u8> {
let mut bytes = Vec::with_capacity((width * width) as usize);
for y in 0..width {
for x in 0..width {
bytes.push(super::nv12_from_rgb(to_rgba(pixel(x, y, width))).0);
}
}
bytes
}
/// The card's half-resolution interleaved chroma plane, Cb then Cr per sample.
#[cfg(any(target_os = "linux", target_os = "macos"))]
pub fn chroma(width: u32) -> Vec<u8> {
let mut bytes = Vec::with_capacity(((width / 2) * (width / 2) * 2) as usize);
for row in 0..width / 2 {
for x in 0..width / 2 {
// A chroma sample is the average of its 2x2 block, as an encoder's box filter
// makes it. Over the fine red/blue columns that average is the murky purple the
// subsampling bleeds — the point of the patch.
let (_, cb, cr) = super::nv12_from_rgb(block_average(x * 2, row * 2, width));
bytes.push(cb);
bytes.push(cr);
}
}
bytes
}
/// The average of the 2x2 block at `(x, y)`, as the RGBA the conversion takes.
#[cfg(any(target_os = "linux", target_os = "macos"))]
fn block_average(x: u32, y: u32, width: u32) -> [u8; 4] {
let mut sums = [0u32; 3];
for dy in 0..2 {
for dx in 0..2 {
let [r, g, b] = pixel((x + dx).min(width - 1), (y + dy).min(width - 1), width);
sums[0] += u32::from(r);
sums[1] += u32::from(g);
sums[2] += u32::from(b);
}
}
[
(sums[0] / 4) as u8,
(sums[1] / 4) as u8,
(sums[2] / 4) as u8,
255,
]
}
/// The card as one NV12 buffer: the luma plane, then the chroma plane.
#[cfg(any(target_os = "linux", target_os = "macos"))]
pub fn nv12(width: u32) -> Vec<u8> {
let mut bytes = luma(width);
bytes.extend_from_slice(&chroma(width));
bytes
}
/// An sRGB triple widened to the RGBA the conversion takes.
#[cfg(any(target_os = "linux", target_os = "macos"))]
fn to_rgba(rgb: [u8; 3]) -> [u8; 4] {
[rgb[0], rgb[1], rgb[2], 255]
}
}
#[cfg(target_os = "linux")]
const BACKEND: &str =
"Linux · wgpu — dma-buf Bgra8, Rgba8 and Nv12, and an imported texture view";
#[cfg(target_os = "windows")]
const BACKEND: &str =
"Windows · Direct3D 11 — a texture payload, a view payload, and a canvas surface";
#[cfg(target_os = "macos")]
const BACKEND: &str = "macOS · Metal — a CoreVideo buffer and an imported Metal texture";
pub fn run() {
gpui::application().run(|cx: &mut App| {
let bounds = Bounds::centered(None, size(px(780.), px(680.)), cx);
cx.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(bounds)),
..Default::default()
},
|_, cx| cx.new(|_| Showcase::new()),
)
.expect("a window to composite into");
cx.activate(true);
});
}
/// The window's view. The producers live here so their resources outlive every frame, and the
/// selected tab names the format dimension the grid is showing.
struct Showcase {
tab: usize,
#[cfg(target_os = "linux")]
producer: Option<wgpu_backend::Producer>,
#[cfg(target_os = "windows")]
producer: Option<directx_backend::Producer>,
#[cfg(target_os = "macos")]
producer: Option<metal_backend::Producer>,
}
impl Showcase {
fn new() -> Self {
Self {
tab: 0,
producer: None,
}
}
}
impl Render for Showcase {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
#[cfg(target_os = "linux")]
let (formats, tiles) = (
wgpu_backend::FORMATS,
wgpu_backend::tiles(&mut self.producer, self.tab, window),
);
#[cfg(target_os = "windows")]
let (formats, tiles) = (
directx_backend::FORMATS,
directx_backend::tiles(&mut self.producer, self.tab, window),
);
#[cfg(target_os = "macos")]
let (formats, tiles) = (
metal_backend::FORMATS,
metal_backend::tiles(&mut self.producer, self.tab, window),
);
let selected = self.tab;
let tabs = div().flex().flex_wrap().justify_center().gap_2().children(
formats.iter().enumerate().map(|(index, name)| {
let active = index == selected;
div()
.id(("format-tab", index))
.px_3()
.py_1()
.rounded_md()
.cursor_pointer()
.text_sm()
.bg(if active { rgb(0x3a3a44) } else { rgb(0x1c1c22) })
.text_color(if active { rgb(0xffffff) } else { rgb(0x9a9aa2) })
.child(*name)
.on_click(cx.listener(move |this, _, _, cx| {
this.tab = index;
cx.notify();
}))
}),
);
div()
.size_full()
.bg(rgb(0x101014))
.flex()
.flex_col()
.items_center()
.gap_6()
.p_8()
.child(
div()
.flex()
.flex_col()
.items_center()
.gap_1()
.child(
div()
.text_2xl()
.text_color(rgb(0xffffff))
.child("External surfaces"),
)
.child(div().text_sm().text_color(rgb(0x9a9aa2)).child(BACKEND)),
)
.child(tabs)
.child(
div()
.flex()
.flex_wrap()
.justify_center()
.gap_6()
.children(tiles),
)
}
}
/// A square tile with a caption under it, so each combination is labelled the way it was made.
fn panel(content: impl IntoElement, caption: impl IntoElement) -> AnyElement {
div()
.flex()
.flex_col()
.items_center()
.gap_2()
.w(px(220.))
.child(div().w(px(170.)).h(px(170.)).child(content))
.child(div().text_color(rgb(0xd8d8d8)).text_center().child(caption))
.into_any_element()
}
/// A tile that stands in for one the host could not produce, so the grid still explains itself.
fn error_panel(message: String) -> AnyElement {
panel(
div()
.size_full()
.bg(rgb(0x2a1518))
.flex()
.items_center()
.justify_center()
.p_3()
.child(div().text_color(rgb(0xffaaaa)).text_center().child(message)),
"unavailable on this host",
)
}
/// The Y, Cb and Cr bytes the renderer's BT.601 surface conversion maps back to `rgb`.
///
/// The surface fragment of a two-plane payload converts with this matrix:
///
/// ```text
/// R = y + 1.4020*cr - 0.7010
/// G = y - 0.3441*cb - 0.7141*cr + 0.5291
/// B = y + 1.7720*cb - 0.8860
/// ```
///
/// which is BT.601, full range — the same matrix the wgpu and Metal shaders carry. Inverting it
/// (move the offsets to the source side, then apply the luma/chroma rows of the inverse) gives the
/// bytes to store for a target colour.
#[cfg(any(target_os = "linux", target_os = "macos"))]
fn nv12_from_rgb(rgb: [u8; 4]) -> (u8, u8, u8) {
let r = f32::from(rgb[0]) / 255.0;
let g = f32::from(rgb[1]) / 255.0;
let b = f32::from(rgb[2]) / 255.0;
let (r, g, b) = (r + 0.7010, g - 0.5291, b + 0.8860);
let y = 0.299 * r + 0.587 * g + 0.114 * b;
let cb = -0.168736 * r - 0.331264 * g + 0.5 * b;
let cr = 0.5 * r - 0.418688 * g - 0.081312 * b;
(
(y.clamp(0.0, 1.0) * 255.0).round() as u8,
(cb.clamp(0.0, 1.0) * 255.0).round() as u8,
(cr.clamp(0.0, 1.0) * 255.0).round() as u8,
)
}
/// Linux's producer: a bare Vulkan device exports the dma-bufs, and the window's own wgpu device
/// backs the imported texture.
#[cfg(target_os = "linux")]
mod wgpu_backend {
use std::cell::RefCell;
use std::os::fd::{FromRawFd, OwnedFd};
use std::rc::Rc;
use std::sync::Arc;
use super::{TILE, error_panel, panel, test_card};
use anyhow::{Context as _, Result};
use ash::vk;
use gpui::{
AnyElement, ChromaReconstruction, Corners, DmaBufHandle, DmaBufPlane,
ImportedTextureExt as _, ImportedTextureHandle, SurfaceFormatKind, Window, gpu_canvas,
prelude::*, surface,
};
/// The format dimension: one tab per payload the platform can carry, plus the same NV12
/// buffer sampled both ways so the chroma reconstruction can be compared.
pub const FORMATS: &[&str] = &[
"Bgra8",
"Rgba8",
"Nv12 · bilinear",
"Nv12 · luma-guided",
"wgpu texture",
];
pub struct Producer {
/// The device the dma-bufs are exported from. It must outlive every handle made from it.
_vulkan: Vulkan,
/// `surface()` with a dma-buf in each of the three formats.
bgra: DmaBufHandle,
rgba: DmaBufHandle,
nv12: DmaBufHandle,
/// The same NV12 buffer, asking the renderer for luma-guided chroma.
nv12_sharp: DmaBufHandle,
/// The imported-texture tile. Built at paint time, when the window's device exists; the
/// `Rc` is shared with the callback so the tile survives across frames instead of being
/// rebuilt every paint.
imported: Rc<RefCell<Option<ImportedTile>>>,
}
impl Producer {
fn new() -> Result<Self> {
let mut vulkan = Vulkan::new()?;
// A single plane per format, each holding the test card in its own byte order.
let bgra_fd = vulkan.allocate(&test_card::bgra8(TILE))?;
let bgra = DmaBufHandle::new(
TILE,
TILE,
SurfaceFormatKind::bgra8(),
DmaBufHandle::LINEAR,
[DmaBufPlane::new(bgra_fd, 0, TILE * 4)],
None,
);
let rgba_fd = vulkan.allocate(&test_card::rgba8(TILE))?;
let rgba = DmaBufHandle::new(
TILE,
TILE,
SurfaceFormatKind::rgba8(),
DmaBufHandle::LINEAR,
[DmaBufPlane::new(rgba_fd, 0, TILE * 4)],
None,
);
// Two planes in one allocation: full-resolution luma, then half-resolution interleaved
// chroma. Both planes are written whole, padding included.
let luma_size = TILE * TILE;
let content = test_card::nv12(TILE);
let fd = vulkan.allocate(&content)?;
let chroma_fd = fd
.try_clone()
.context("duplicate the dma-buf for the chroma plane")?;
let nv12 = DmaBufHandle::new(
TILE,
TILE,
SurfaceFormatKind::nv12(),
DmaBufHandle::LINEAR,
[
DmaBufPlane::new(fd, 0, TILE),
DmaBufPlane::new(chroma_fd, luma_size as u64, TILE),
],
None,
);
// A second NV12 buffer over the same card, asking for luma-guided chroma: the same
// bytes the renderer would otherwise sample bilinearly, reconstructed against the
// sharp luma plane instead.
let sharp_fd = vulkan.allocate(&content)?;
let sharp_chroma_fd = sharp_fd
.try_clone()
.context("duplicate the dma-buf for the guided chroma plane")?;
let nv12_sharp = DmaBufHandle::new(
TILE,
TILE,
SurfaceFormatKind::nv12(),
DmaBufHandle::LINEAR,
[
DmaBufPlane::new(sharp_fd, 0, TILE),
DmaBufPlane::new(sharp_chroma_fd, luma_size as u64, TILE),
],
None,
)
.with_chroma(ChromaReconstruction::LumaGuided);
Ok(Self {
_vulkan: vulkan,
bgra,
rgba,
nv12,
nv12_sharp,
imported: Rc::new(RefCell::new(None)),
})
}
}
/// The imported-texture tile: a wgpu texture the window's own device draws through.
struct ImportedTile {
/// Held so the device outlives the view taken from the texture.
_device: Arc<wgpu::Device>,
_texture: wgpu::Texture,
handle: ImportedTextureHandle,
}
impl ImportedTile {
fn new(device: Arc<wgpu::Device>, queue: Arc<wgpu::Queue>) -> Result<Self> {
let texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some("surface_showcase"),
size: wgpu::Extent3d {
width: TILE,
height: TILE,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
// sRGB, matching the renderer's imported-texture path: the sampler decodes to
// linear and the fragment re-encodes, so these sRGB-encoded bytes come back
// unchanged rather than double-encoded.
format: wgpu::TextureFormat::Bgra8UnormSrgb,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture: &texture,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
&test_card::bgra8(TILE),
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(TILE * 4),
rows_per_image: Some(TILE),
},
wgpu::Extent3d {
width: TILE,
height: TILE,
depth_or_array_layers: 1,
},
);
let handle = texture
.create_view(&wgpu::TextureViewDescriptor::default())
.to_imported_handle()?;
Ok(Self {
_device: device,
_texture: texture,
handle,
})
}
}
pub fn tiles(
slot: &mut Option<Producer>,
format: usize,
_window: &mut Window,
) -> Vec<AnyElement> {
if slot.is_none() {
match Producer::new() {
Ok(producer) => *slot = Some(producer),
Err(error) => {
log::error!("surface: cannot produce a dma-buf: {error:#}");
return vec![error_panel(format!(
"dma-buf producer unavailable: {error:#}"
))];
}
}
}
let producer = slot.as_ref().expect("the producer was just built");
match format {
0..=3 => {
let (handle, surface_caption, canvas_caption) = match format {
0 => (
producer.bgra.clone(),
"surface() · SurfaceFormatKind::bgra8()",
"gpu_canvas(..) · SurfaceFormatKind::bgra8()",
),
1 => (
producer.rgba.clone(),
"surface() · SurfaceFormatKind::rgba8()",
"gpu_canvas(..) · SurfaceFormatKind::rgba8()",
),
2 => (
producer.nv12.clone(),
"surface() · Nv12 · bilinear chroma",
"gpu_canvas(..) · Nv12 · bilinear chroma",
),
_ => (
producer.nv12_sharp.clone(),
"surface() · Nv12 · luma-guided chroma",
"gpu_canvas(..) · Nv12 · luma-guided chroma",
),
};
let canvas = handle.clone();
vec![
panel(surface(handle).size_full(), surface_caption),
panel(
gpu_canvas(move |gpu| gpu.paint_surface(canvas)).size_full(),
canvas_caption,
),
]
}
_ => {
let imported = producer.imported.clone();
vec![panel(
gpu_canvas(move |gpu| {
let mut tile = imported.borrow_mut();
if tile.is_none() {
let Some((device, queue)) =
gpu.try_device::<gpui_wgpu::WgpuRenderer>()
else {
log::error!(
"surface: the window's renderer lends no wgpu device"
);
return;
};
match ImportedTile::new(device, queue) {
Ok(built) => *tile = Some(built),
Err(error) => {
log::error!(
"surface: cannot produce the imported texture: {error:#}"
);
return;
}
}
}
let handle = tile
.as_ref()
.expect("the tile was just built")
.handle
.clone();
gpu.paint_texture(handle, Corners::default(), 1.0, false);
})
.size_full(),
"gpu_canvas(..) · wgpu texture view",
)]
}
}
}
/// A minimal Vulkan "producer": the loader, instance and device that keep the exported
/// dma-bufs alive for as long as the renderer samples them.
///
/// The `Entry` must outlive the device it made — dropping it unloads the loader the device's
/// calls go through — so it is a field and the device is destroyed explicitly first.
struct Vulkan {
_entry: ash::Entry,
instance: ash::Instance,
device: ash::Device,
external_memory_fd: ash::khr::external_memory_fd::Device,
/// Every allocation ever exported; kept alive, not read.
memories: Vec<vk::DeviceMemory>,
/// A host-visible, host-coherent memory type the allocations are made in.
memory_type_index: u32,
}
impl Vulkan {
fn new() -> Result<Self> {
let entry = unsafe { ash::Entry::load() }
.map_err(|error| anyhow::anyhow!("load vulkan: {error}"))?;
let app_info =
vk::ApplicationInfo::default().api_version(vk::make_api_version(0, 1, 1, 0));
let instance = unsafe {
entry.create_instance(
&vk::InstanceCreateInfo::default().application_info(&app_info),
None,
)
}
.context("create the producer instance")?;
let devices = unsafe { instance.enumerate_physical_devices() }
.context("enumerate physical devices")?;
// Prefer the integrated GPU, the one a renderer is usually steered to; fall back to
// whatever the driver lists first.
let physical = devices
.iter()
.copied()
.find(|device| {
let properties =
unsafe { instance.get_physical_device_properties(*device) };
properties.device_type == vk::PhysicalDeviceType::INTEGRATED_GPU
})
.or_else(|| devices.first().copied())
.context("no Vulkan device for the producer")?;
let properties =
unsafe { instance.get_physical_device_memory_properties(physical) };
let memory_type_index = properties
.memory_types
.iter()
.enumerate()
.find(|(_, memory_type)| {
memory_type.property_flags.contains(
vk::MemoryPropertyFlags::HOST_VISIBLE
| vk::MemoryPropertyFlags::HOST_COHERENT,
)
})
.map(|(index, _)| index as u32)
.context("no host-visible memory for the producer")?;
let extensions = [
vk::KHR_EXTERNAL_MEMORY_FD_NAME.as_ptr(),
vk::EXT_EXTERNAL_MEMORY_DMA_BUF_NAME.as_ptr(),
];
let device = unsafe {
instance.create_device(
physical,
&vk::DeviceCreateInfo::default().enabled_extension_names(&extensions),
None,
)
}
.context("create the producer device")?;
let external_memory_fd =
ash::khr::external_memory_fd::Device::new(&instance, &device);
Ok(Self {
_entry: entry,
instance,
device,
external_memory_fd,
memories: Vec::new(),
memory_type_index,
})
}
/// Allocate `content` in a host-visible buffer and export it as a linear dma-buf.
fn allocate(&mut self, content: &[u8]) -> Result<OwnedFd> {
let size = content.len() as u64;
let mut export_info = vk::ExportMemoryAllocateInfo::default()
.handle_types(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT);
let memory = unsafe {
self.device.allocate_memory(
&vk::MemoryAllocateInfo::default()
.allocation_size(size)
.memory_type_index(self.memory_type_index)
.push_next(&mut export_info),
None,
)
}
.context("allocate the producer buffer")?;
unsafe {
let mapped =
self.device
.map_memory(memory, 0, size, vk::MemoryMapFlags::empty())
.context("map the producer buffer")? as *mut u8;
std::ptr::copy_nonoverlapping(content.as_ptr(), mapped, content.len());
self.device.unmap_memory(memory);
}
let fd = unsafe {
self.external_memory_fd.get_memory_fd(
&vk::MemoryGetFdInfoKHR::default()
.memory(memory)
.handle_type(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT),
)
}
.context("export the producer's dma-buf")?;
let owned = unsafe { OwnedFd::from_raw_fd(fd) };
self.memories.push(memory);
Ok(owned)
}
}
impl Drop for Vulkan {
fn drop(&mut self) {
unsafe {
self.device.destroy_device(None);
self.instance.destroy_instance(None);
}
}
}
}
/// Windows' producer: Direct3D 11 on the device the window's renderer lends — the route a
/// hardware decoder or a Direct3D engine takes.
#[cfg(target_os = "windows")]
mod directx_backend {
use std::cell::RefCell;
use std::rc::Rc;
use anyhow::{Context as _, Result};
use gpui::{
AnyElement, DirectXRenderer, DirectXSource, GpuCanvasContext, SharedDirectXFence,
SharedDirectXSurface, SurfaceSource, Window, gpu_canvas, prelude::*, surface,
};
use windows::Win32::Foundation::{HANDLE, HMODULE};
use windows::Win32::Graphics::Direct3D::{
D3D_DRIVER_TYPE_HARDWARE, D3D_FEATURE_LEVEL_11_0, D3D_SRV_DIMENSION_TEXTURE2D,
};
use windows::Win32::Graphics::Direct3D11::{
D3D11_BIND_SHADER_RESOURCE, D3D11_CREATE_DEVICE_BGRA_SUPPORT, D3D11_FENCE_FLAG_SHARED,
D3D11_RESOURCE_MISC_SHARED_NTHANDLE, D3D11_SDK_VERSION,
D3D11_SHADER_RESOURCE_VIEW_DESC, D3D11_SHADER_RESOURCE_VIEW_DESC_0, D3D11_TEX2D_SRV,
D3D11_TEXTURE2D_DESC, D3D11_USAGE_DEFAULT, D3D11CreateDevice, ID3D11Device,
ID3D11Device5, ID3D11DeviceContext, ID3D11DeviceContext4, ID3D11Fence, ID3D11Resource,
ID3D11ShaderResourceView, ID3D11Texture2D,
};
use windows::Win32::Graphics::Dxgi::Common::{
DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_SAMPLE_DESC,
};
use windows::Win32::Graphics::Dxgi::{
DXGI_SHARED_RESOURCE_READ, DXGI_SHARED_RESOURCE_WRITE, IDXGIResource1,
};
use windows::core::{Interface as _, PCWSTR};
use super::{TILE, error_panel, panel, test_card};
/// The format dimension: one tab per payload this backend carries.
pub const FORMATS: &[&str] = &["Texture", "View", "Shared"];
/// `GENERIC_ALL`, the access a shared fence handle is created with.
const GENERIC_ALL: u32 = 0x1000_0000;
/// The two device-made payloads. They are built on the first paint, when the renderer's
/// device exists, and shared with every canvas callback.
struct Payloads {
texture_variant: ID3D11Texture2D,
view_variant: ID3D11ShaderResourceView,
}
pub struct Producer {
payloads: Rc<RefCell<Option<Payloads>>>,
/// The device-independent payload: a shared texture (and fence) made on the producer's
/// *own* device at construction — no window involved.
shared: Option<SharedProducer>,
}
impl Producer {
fn new() -> Self {
Self {
payloads: Rc::new(RefCell::new(None)),
shared: match SharedProducer::new() {
Ok(shared) => Some(shared),
Err(error) => {
log::error!(
"surface: cannot produce a shared Direct3D texture: {error:#}"
);
None
}
},
}
}
}
/// A shared Direct3D texture made on the producer's *own* device.
///
/// This is the payload `surface()` exists for on Windows: the NT handle is
/// device-independent, so the element carries it before the window's renderer has a device,
/// and the renderer opens and views it at draw. The handle is same-adapter, so the producer
/// device is created on the default adapter — the one the window renderer uses by default.
struct SharedProducer {
/// Held so the device that made the texture and the fence outlives them.
_device: ID3D11Device,
_texture: ID3D11Texture2D,
_fence: ID3D11Fence,
/// The texture's NT handle, for `DirectXSource::Shared`.
handle: HANDLE,
/// The fence's NT handle, and the value the renderer waits for before it samples.
fence: HANDLE,
value: u64,
}
impl SharedProducer {
fn new() -> Result<Self> {
let mut device = None;
let mut context = None;
unsafe {
D3D11CreateDevice(
None,
D3D_DRIVER_TYPE_HARDWARE,
HMODULE::default(),
D3D11_CREATE_DEVICE_BGRA_SUPPORT,
Some(&[D3D_FEATURE_LEVEL_11_0]),
D3D11_SDK_VERSION,
Some(&mut device),
None,
Some(&mut context),
)
}
.context("creating the shared producer's Direct3D 11 device")?;
let device: ID3D11Device =
device.context("D3D11CreateDevice returned no device")?;
let context: ID3D11DeviceContext =
context.context("D3D11CreateDevice returned no context")?;
let texture: ID3D11Texture2D = unsafe {
let mut texture = None;
device
.CreateTexture2D(
&D3D11_TEXTURE2D_DESC {
Width: TILE,
Height: TILE,
MipLevels: 1,
ArraySize: 1,
Format: DXGI_FORMAT_B8G8R8A8_UNORM,
SampleDesc: DXGI_SAMPLE_DESC {
Count: 1,
Quality: 0,
},
Usage: D3D11_USAGE_DEFAULT,
BindFlags: D3D11_BIND_SHADER_RESOURCE.0 as u32,
CPUAccessFlags: 0,
MiscFlags: D3D11_RESOURCE_MISC_SHARED_NTHANDLE.0 as u32,
},
None,
Some(&mut texture),
)
.context("creating the shared texture")?;
texture.context("CreateTexture2D returned no texture")?
};
let fence: ID3D11Fence = unsafe {
let device5: ID3D11Device5 =
device.cast().context("not a Direct3D 11.5 device")?;
let mut fence = None;
device5
.CreateFence(0, D3D11_FENCE_FLAG_SHARED, &mut fence)
.context("creating the shared fence")?;
fence.context("CreateFence returned no fence")?
};
// Upload the card on the producer's own context and signal the fence, so the
// renderer's first sample is ordered behind the upload.
upload_card(&device, &texture)?;
unsafe {
let context4: ID3D11DeviceContext4 =
context.cast().context("not a Direct3D 11.4 context")?;
context4
.Signal(&fence, 1)
.context("signalling the shared fence")?;
context.Flush();
}
let resource: IDXGIResource1 = texture
.cast()
.context("the texture is not a DXGI resource")?;
let handle = unsafe {
resource
.CreateSharedHandle(
None,
(DXGI_SHARED_RESOURCE_READ | DXGI_SHARED_RESOURCE_WRITE).0,
PCWSTR::null(),
)
.context("sharing the texture")?
};
let fence_handle = unsafe {
fence
.CreateSharedHandle(None, GENERIC_ALL, PCWSTR::null())
.context("sharing the fence")?
};
Ok(Self {
_device: device,
_texture: texture,
_fence: fence,
handle,
fence: fence_handle,
value: 1,
})
}
}
/// Build the payloads on the window renderer's own device.
///
/// The device is reachable only at paint, so this runs inside a `gpu_canvas` callback: a
/// `surface()` element takes its source before painting, which a same-device source cannot
/// satisfy.
fn build(gpu: &mut GpuCanvasContext) -> Result<Payloads> {
let device = gpu
.try_device::<DirectXRenderer>()
.context("the window's renderer is not Direct3D")?;
let texture_variant = card_texture(&device)?;
let view_texture = card_texture(&device)?;
let view_variant = shader_resource_view(&device, &view_texture)?;
Ok(Payloads {
texture_variant,
view_variant,
})
}
/// Build the shared payloads (once) and paint one of them through `source`.
fn paint(
payloads: &Rc<RefCell<Option<Payloads>>>,
gpu: &mut GpuCanvasContext,
source: impl FnOnce(&Payloads) -> SurfaceSource,
) {
let mut built = payloads.borrow_mut();
if built.is_none() {
match build(gpu) {
Ok(payloads) => *built = Some(payloads),
Err(error) => {
log::error!("surface: cannot produce a Direct3D texture: {error:#}");
return;
}
}
}
let built = built.as_ref().expect("the payloads were just built");
gpu.paint_surface(source(built));
}
pub fn tiles(
slot: &mut Option<Producer>,
format: usize,
_window: &mut Window,
) -> Vec<AnyElement> {
let producer = slot.get_or_insert_with(Producer::new);
let payloads = producer.payloads.clone();
let shared = producer.shared.as_ref().map(|shared| SharedDirectXSurface {
texture: shared.handle,
fence: Some(SharedDirectXFence {
handle: shared.fence,
value: shared.value,
}),
width: TILE,
height: TILE,
});
match format {
0 => vec![panel(
gpu_canvas({
let payloads = payloads.clone();
move |gpu| {
paint(&payloads, gpu, |payloads| {
SurfaceSource::DirectX(DirectXSource::Texture(
payloads.texture_variant.clone(),
))
});
}
})
.size_full(),
"gpu_canvas(..) · DirectXSource::Texture",
)],
1 => vec![panel(
gpu_canvas({
let payloads = payloads.clone();
move |gpu| {
paint(&payloads, gpu, |payloads| {
SurfaceSource::DirectX(DirectXSource::View(
payloads.view_variant.clone(),
))
});
}
})
.size_full(),
"gpu_canvas(..) · DirectXSource::View",
)],
_ => match shared {
Some(source) => {
let canvas_source = source.clone();
vec![
panel(
surface(SurfaceSource::DirectX(DirectXSource::Shared(source)))
.size_full(),
"surface() · DirectXSource::Shared",
),
panel(
gpu_canvas(move |gpu| {
gpu.paint_surface(SurfaceSource::DirectX(
DirectXSource::Shared(canvas_source),
));
})
.size_full(),
"gpu_canvas(..) · DirectXSource::Shared",
),
]
}
None => vec![error_panel("no shared Direct3D producer".to_string())],
},
}
}
/// An offscreen texture on `device`, holding the test card.
///
/// `SHADER_RESOURCE` because both layers sample it. The format is the renderer's own target
/// format, `B8G8R8A8_UNORM`: the renderer views the texture as non-sRGB and the fragment
/// samples its bytes straight through.
fn card_texture(device: &ID3D11Device) -> Result<ID3D11Texture2D> {
let desc = D3D11_TEXTURE2D_DESC {
Width: TILE,
Height: TILE,
MipLevels: 1,
ArraySize: 1,
Format: DXGI_FORMAT_B8G8R8A8_UNORM,
SampleDesc: DXGI_SAMPLE_DESC {
Count: 1,
Quality: 0,
},
Usage: D3D11_USAGE_DEFAULT,
BindFlags: D3D11_BIND_SHADER_RESOURCE.0 as u32,
CPUAccessFlags: 0,
MiscFlags: 0,
};
let mut texture = None;
unsafe { device.CreateTexture2D(&desc, None, Some(&mut texture))? };
let texture = texture.context("CreateTexture2D returned no texture")?;
upload_card(device, &texture)?;
Ok(texture)
}
/// Writes the test card into `texture` through the device's immediate context.
///
/// A `DEFAULT` texture cannot be mapped, so the card is uploaded with `UpdateSubresource`,
/// which writes a whole subresource: one row pitch, no depth pitch, no destination box.
fn upload_card(device: &ID3D11Device, texture: &ID3D11Texture2D) -> Result<()> {
let bytes = test_card::bgra8(TILE);
let context = unsafe { device.GetImmediateContext() }
.context("the device has no immediate context")?;
let resource: ID3D11Resource = texture
.cast()
.context("the texture is not a Direct3D resource")?;
unsafe {
context.UpdateSubresource(
&resource,
0,
None,
bytes.as_ptr() as *const core::ffi::c_void,
TILE * 4,
0,
);
}
Ok(())
}
/// A non-sRGB `B8G8R8A8_UNORM` view of `texture`, the payload of a view tile.
fn shader_resource_view(
device: &ID3D11Device,
texture: &ID3D11Texture2D,
) -> Result<ID3D11ShaderResourceView> {
unsafe {
let desc = D3D11_SHADER_RESOURCE_VIEW_DESC {
Format: DXGI_FORMAT_B8G8R8A8_UNORM,
ViewDimension: D3D_SRV_DIMENSION_TEXTURE2D,
Anonymous: D3D11_SHADER_RESOURCE_VIEW_DESC_0 {
Texture2D: D3D11_TEX2D_SRV {
MostDetailedMip: 0,
MipLevels: 1,
},
},
};
let mut view = None;
device.CreateShaderResourceView(texture, Some(&desc), Some(&mut view))?;
view.context("CreateShaderResourceView returned no view")
}
}
}
/// macOS' producer: a CoreVideo buffer for two tiles, and a wgpu texture resolved to its
/// `id<MTLTexture>` for the third.
#[cfg(target_os = "macos")]
mod metal_backend {
use std::sync::Arc;
use anyhow::{Context as _, Result, ensure};
use core_foundation::base::{CFType, TCFType as _};
use core_foundation::boolean::CFBoolean;
use core_foundation::dictionary::CFDictionary;
use core_foundation::string::CFString;
use core_video::pixel_buffer::{
CVPixelBuffer, kCVPixelBufferIOSurfacePropertiesKey,
kCVPixelBufferMetalCompatibilityKey, kCVPixelFormatType_420YpCbCr8BiPlanarFullRange,
};
use gpui::{
AnyElement, Corners, ImportedTextureHandle, SurfaceSource, Window, gpu_canvas,
prelude::*, surface,
};
use super::{TILE, error_panel, panel, test_card};
/// The format dimension: one tab per payload this backend carries.
pub const FORMATS: &[&str] = &["CoreVideo", "Metal texture"];
pub struct Producer {
/// The CoreVideo buffer, for `surface()` and `gpu_canvas(..)`.
buffer: CVPixelBuffer,
/// Held so the device outlives the view taken from the texture.
_device: Arc<wgpu::Device>,
_texture: wgpu::Texture,
/// The imported-texture tile's handle.
imported: ImportedTextureHandle,
}
impl Producer {
fn new() -> Result<Self> {
// A decoder's frame: an IOSurface-backed, two-plane NV12 buffer at full range,
// holding the test card made from the renderer's own BT.601 conversion.
let buffer = new_nv12_buffer(TILE, TILE)?;
fill_card(&buffer)?;
// The imported-texture tile: a wgpu texture on the one Metal device macOS hands every
// creator, so it is the device the renderer samples on.
let (device, queue) = device()?;
let texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some("surface_showcase"),
size: wgpu::Extent3d {
width: TILE,
height: TILE,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
// sRGB, the format the imported-texture path requires: the sampler decodes to
// linear and the fragment re-encodes, so the card's bytes come back unchanged.
format: wgpu::TextureFormat::Bgra8UnormSrgb,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture: &texture,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
&test_card::bgra8(TILE),
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(TILE * 4),
rows_per_image: Some(TILE),
},
wgpu::Extent3d {
width: TILE,
height: TILE,
depth_or_array_layers: 1,
},
);
let imported = metal_handle(&texture)?;
Ok(Self {
buffer,
_device: device,
_texture: texture,
imported,
})
}
}
pub fn tiles(
slot: &mut Option<Producer>,
format: usize,
_window: &mut Window,
) -> Vec<AnyElement> {
if slot.is_none() {
match Producer::new() {
Ok(producer) => *slot = Some(producer),
Err(error) => {
log::error!("surface: cannot produce the macOS payloads: {error:#}");
return vec![error_panel(format!("producer unavailable: {error:#}"))];
}
}
}
let producer = slot.as_ref().expect("the producer was just built");
match format {
0 => {
let surface_buffer = producer.buffer.clone();
let canvas_buffer = producer.buffer.clone();
vec![
panel(
surface(SurfaceSource::CoreVideo(surface_buffer)).size_full(),
"surface() · CoreVideo CVPixelBuffer",
),
panel(
gpu_canvas(move |gpu| {
gpu.paint_surface(SurfaceSource::CoreVideo(canvas_buffer));
})
.size_full(),
"gpu_canvas(..) · CoreVideo",
),
]
}
_ => {
let imported = producer.imported.clone();
vec![panel(
gpu_canvas(move |gpu| {
gpu.paint_texture(imported, Corners::default(), 1.0, false);
})
.size_full(),
"gpu_canvas(..) · id<MTLTexture>",
)]
}
}
}
/// An `IOSurface`-backed, two-plane `NV12` full-range buffer — the layout a hardware decoder
/// produces and the renderer expects.
fn new_nv12_buffer(width: u32, height: u32) -> Result<CVPixelBuffer> {
// A `CVPixelBuffer` is IOSurface-backed only when its attributes ask for it; the renderer's
// texture cache needs the IOSurface behind it. Metal compatibility is declared alongside.
let iosurface_properties: CFDictionary<CFString, CFType> =
CFDictionary::from_CFType_pairs(&[]);
let iosurface_key: CFString =
unsafe { CFString::wrap_under_get_rule(kCVPixelBufferIOSurfacePropertiesKey) };
let metal_key: CFString =
unsafe { CFString::wrap_under_get_rule(kCVPixelBufferMetalCompatibilityKey) };
let attributes = CFDictionary::from_CFType_pairs(&[
(iosurface_key, iosurface_properties.as_CFType()),
(metal_key, CFBoolean::true_value().as_CFType()),
]);
CVPixelBuffer::new(
kCVPixelFormatType_420YpCbCr8BiPlanarFullRange,
width as usize,
height as usize,
Some(&attributes),
)
.map_err(|code| anyhow::anyhow!("CVPixelBuffer::new returned CVReturn {code}"))
}
/// Fill both planes with the test card, padding included, so no stale bytes are sampled.
fn fill_card(buffer: &CVPixelBuffer) -> Result<()> {
let width = buffer.get_width() as u32;
let height = buffer.get_height();
let luma = test_card::luma(width);
let chroma = test_card::chroma(width);
// 0 is the read-write lock: the CPU fills the planes, the GPU samples them.
let lock = 0u64;
let result = buffer.lock_base_address(lock);
ensure!(
result == 0,
"CVPixelBufferLockBaseAddress returned CVReturn {result}"
);
// Safety: the buffer is locked, so both planes' base addresses are valid for the plane's
// height and stride, and the source rows are `width` bytes of the card.
unsafe {
let luma_base = buffer.get_base_address_of_plane(0) as *mut u8;
let luma_stride = buffer.get_bytes_per_row_of_plane(0);
let chroma_base = buffer.get_base_address_of_plane(1) as *mut u8;
let chroma_stride = buffer.get_bytes_per_row_of_plane(1);
let chroma_height = buffer.get_height_of_plane(1);
for row in 0..height {
let source = &luma[row * width as usize..(row + 1) * width as usize];
std::ptr::copy_nonoverlapping(
source.as_ptr(),
luma_base.add(row * luma_stride),
width as usize,
);
}
// Cb and Cr are interleaved, two bytes a sample, so a row of `width/2` samples is
// `width` bytes.
for row in 0..chroma_height {
let source = &chroma[row * width as usize..(row + 1) * width as usize];
std::ptr::copy_nonoverlapping(
source.as_ptr(),
chroma_base.add(row * chroma_stride),
width as usize,
);
}
}
let result = buffer.unlock_base_address(lock);
ensure!(
result == 0,
"CVPixelBufferUnlockBaseAddress returned CVReturn {result}"
);
Ok(())
}
/// wgpu's own Metal device, which is the one the window's Metal renderer also draws through.
fn device() -> Result<(Arc<wgpu::Device>, Arc<wgpu::Queue>)> {
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
backends: wgpu::Backends::METAL,
flags: wgpu::InstanceFlags::default(),
backend_options: wgpu::BackendOptions::default(),
memory_budget_thresholds: wgpu::MemoryBudgetThresholds::default(),
display: None,
});
let adapter =
pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::LowPower,
compatible_surface: None,
force_fallback_adapter: false,
}))
.map_err(|error| anyhow::anyhow!("no Metal adapter: {error}"))?;
let (device, queue) =
pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
label: Some("surface_showcase"),
required_features: wgpu::Features::empty(),
required_limits: wgpu::Limits::downlevel_defaults(),
memory_hints: wgpu::MemoryHints::MemoryUsage,
trace: wgpu::Trace::Off,
experimental_features: wgpu::ExperimentalFeatures::disabled(),
}))
.map_err(|error| anyhow::anyhow!("no wgpu device: {error}"))?;
Ok((Arc::new(device), Arc::new(queue)))
}
/// The texture's own `id<MTLTexture>`, the handle the renderer resolves.
fn metal_handle(texture: &wgpu::Texture) -> Result<ImportedTextureHandle> {
use foreign_types::ForeignTypeRef as _;
use gpui::MetalTextureExt as _;
unsafe {
let hal = texture
.as_hal::<wgpu::hal::api::Metal>()
.context("the texture has no Metal handle")?;
let texture = metal::TextureRef::from_ptr(hal.raw_handle() as *const _ as *mut _);
texture.to_imported_handle()
}
}
}
}