screencapturekit 9.0.1

Safe Rust bindings for Apple's ScreenCaptureKit framework - screen and audio capture on macOS
Documentation
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
//! Async API tests
//!
//! These tests verify the async API types and traits work correctly.
//! Note: Tests that require screen capture permission are marked `no_run`.

#![cfg(feature = "async")]
#![allow(clippy::match_same_arms)]

use screencapturekit::async_api::*;
use screencapturekit::stream::output_type::SCStreamOutputType;
use std::time::Duration;

async fn live_shareable_content() -> Option<screencapturekit::shareable_content::SCShareableContent>
{
    match tokio::time::timeout(Duration::from_secs(5), AsyncSCShareableContent::get()).await {
        Ok(Ok(content)) => Some(content),
        Ok(Err(error)) => {
            eprintln!("skip: shareable content unavailable: {error}");
            None
        }
        Err(_) => {
            eprintln!("skip: shareable content query did not complete within 5 seconds");
            None
        }
    }
}

#[test]
fn test_async_shareable_content_options_builder() {
    let options = AsyncSCShareableContentOptions::default()
        .with_exclude_desktop_windows(true)
        .with_on_screen_windows_only(true);

    // Test that builder pattern works (options are consumed)
    assert_eq!(
        options,
        AsyncSCShareableContentOptions::default()
            .with_exclude_desktop_windows(true)
            .with_on_screen_windows_only(true)
    );
}

#[test]
fn test_async_shareable_content_options_default() {
    let options = AsyncSCShareableContentOptions::default();
    let default = AsyncSCShareableContentOptions::default();
    assert_eq!(options, default);
}

#[test]
fn test_async_shareable_content_options_clone() {
    let options = AsyncSCShareableContentOptions::default().with_exclude_desktop_windows(true);
    let cloned = options.clone();
    assert_eq!(options, cloned);
}

#[test]
fn test_async_shareable_content_options_debug() {
    let options = AsyncSCShareableContentOptions::default();
    let debug_str = format!("{options:?}");
    assert!(debug_str.contains("AsyncSCShareableContentOptions"));
}

#[test]
fn test_async_shareable_content_options_builder_chain() {
    // Test all builder methods
    let options = AsyncSCShareableContentOptions::default()
        .with_exclude_desktop_windows(false)
        .with_on_screen_windows_only(false)
        .with_exclude_desktop_windows(true)
        .with_on_screen_windows_only(true);

    // Each call should update the value
    let expected = AsyncSCShareableContentOptions::default()
        .with_exclude_desktop_windows(true)
        .with_on_screen_windows_only(true);

    assert_eq!(options, expected);
}

#[test]
fn test_async_shareable_content_debug() {
    let content = AsyncSCShareableContent;
    let debug_str = format!("{content:?}");
    assert!(debug_str.contains("AsyncSCShareableContent"));
}

#[test]
fn test_async_shareable_content_clone() {
    let content = AsyncSCShareableContent;
    let cloned = content;
    // Both are unit structs, should be equal
    let _ = cloned;
}

#[test]
fn test_async_shareable_content_copy() {
    let content = AsyncSCShareableContent;
    let copied = content;
    // Copy trait test
    let _ = (content, copied);
}

#[test]
fn test_async_shareable_content_with_options() {
    // Test that with_options returns the options builder
    let options = AsyncSCShareableContent::create();
    let debug_str = format!("{options:?}");
    assert!(debug_str.contains("AsyncSCShareableContentOptions"));
}

#[test]
fn test_async_shareable_content_future_debug() {
    // Create a future and verify it has Debug
    fn assert_debug<T: std::fmt::Debug>() {}
    assert_debug::<AsyncShareableContentFuture>();
}

#[test]
fn test_async_stream_creation() {
    use screencapturekit::shareable_content::SCShareableContent;
    use screencapturekit::stream::configuration::SCStreamConfiguration;
    use screencapturekit::stream::content_filter::SCContentFilter;

    // This may fail if no permission, that's OK - we're testing the API surface
    if let Ok(content) = SCShareableContent::get() {
        if let Some(display) = content.displays().first() {
            let filter = SCContentFilter::create()
                .with_display(display)
                .with_excluding_windows(&[])
                .build();
            let config = SCStreamConfiguration::new()
                .with_width(100)
                .with_height(100);

            let stream = AsyncSCStream::new(&filter, &config, 10, SCStreamOutputType::Screen);

            // Test basic methods
            assert!(!stream.is_closed());
            assert_eq!(stream.buffered_count(), 0);

            // Test try_next on empty buffer
            let sample = stream.try_next();
            assert!(sample.is_none());

            // Test clear_buffer
            stream.clear_buffer();
            assert_eq!(stream.buffered_count(), 0);

            // Test inner() accessor
            let _inner = stream.inner();

            // Test debug
            let debug_str = format!("{stream:?}");
            assert!(debug_str.contains("AsyncSCStream"));
            assert!(debug_str.contains("buffered_count"));
            assert!(debug_str.contains("is_closed"));
        }
    }
}

#[test]
fn test_async_stream_with_audio() {
    use screencapturekit::shareable_content::SCShareableContent;
    use screencapturekit::stream::configuration::SCStreamConfiguration;
    use screencapturekit::stream::content_filter::SCContentFilter;

    if let Ok(content) = SCShareableContent::get() {
        if let Some(display) = content.displays().first() {
            let filter = SCContentFilter::create()
                .with_display(display)
                .with_excluding_windows(&[])
                .build();
            let config = SCStreamConfiguration::new()
                .with_width(100)
                .with_height(100);

            // Create with Audio output type
            let stream = AsyncSCStream::new(&filter, &config, 5, SCStreamOutputType::Audio);
            assert!(!stream.is_closed());
            assert_eq!(stream.buffered_count(), 0);
        }
    }
}

#[tokio::test]
async fn test_async_stream_start_stop_capture() {
    use screencapturekit::shareable_content::SCShareableContent;
    use screencapturekit::stream::configuration::SCStreamConfiguration;
    use screencapturekit::stream::content_filter::SCContentFilter;

    if let Ok(content) = SCShareableContent::get() {
        if let Some(display) = content.displays().first() {
            let filter = SCContentFilter::create()
                .with_display(display)
                .with_excluding_windows(&[])
                .build();
            let config = SCStreamConfiguration::new()
                .with_width(100)
                .with_height(100);

            let stream = AsyncSCStream::new(&filter, &config, 10, SCStreamOutputType::Screen);

            // Start capture
            let start_result = stream.start_capture().await;
            assert!(start_result.is_ok(), "Should start capture");

            // Small delay to let capture initialize
            std::thread::sleep(std::time::Duration::from_millis(100));

            // Stop capture
            let stop_result = stream.stop_capture().await;
            assert!(stop_result.is_ok(), "Should stop capture");
        }
    }
}

#[tokio::test]
#[cfg(feature = "macos_14_0")]
async fn test_async_stream_update_configuration() {
    use screencapturekit::shareable_content::SCShareableContent;
    use screencapturekit::stream::configuration::SCStreamConfiguration;
    use screencapturekit::stream::content_filter::SCContentFilter;

    if let Ok(content) = SCShareableContent::get() {
        if let Some(display) = content.displays().first() {
            let filter = SCContentFilter::create()
                .with_display(display)
                .with_excluding_windows(&[])
                .build();
            let config = SCStreamConfiguration::new()
                .with_width(100)
                .with_height(100);

            let stream = AsyncSCStream::new(&filter, &config, 10, SCStreamOutputType::Screen);

            // Start capture first
            let _ = stream.start_capture().await;
            std::thread::sleep(std::time::Duration::from_millis(100));

            // Update configuration
            let new_config = SCStreamConfiguration::new()
                .with_width(200)
                .with_height(200);

            let update_result = stream.update_configuration(&new_config).await;
            // This may fail if stream is not running, that's ok
            let _ = update_result;

            let _ = stream.stop_capture().await;
        }
    }
}

#[tokio::test]
async fn test_async_stream_update_content_filter() {
    use screencapturekit::shareable_content::SCShareableContent;
    use screencapturekit::stream::configuration::SCStreamConfiguration;
    use screencapturekit::stream::content_filter::SCContentFilter;

    if let Ok(content) = SCShareableContent::get() {
        if let Some(display) = content.displays().first() {
            let filter = SCContentFilter::create()
                .with_display(display)
                .with_excluding_windows(&[])
                .build();
            let config = SCStreamConfiguration::new()
                .with_width(100)
                .with_height(100);

            let stream = AsyncSCStream::new(&filter, &config, 10, SCStreamOutputType::Screen);

            // Start capture first
            let _ = stream.start_capture().await;
            std::thread::sleep(std::time::Duration::from_millis(100));

            // Update content filter
            let new_filter = SCContentFilter::create()
                .with_display(display)
                .with_excluding_windows(&[])
                .build();

            let update_result = stream.update_content_filter(&new_filter).await;
            // This may fail if stream is not running, that's ok
            let _ = update_result;

            let _ = stream.stop_capture().await;
        }
    }
}

#[test]
fn test_async_stream_next_future() {
    use screencapturekit::shareable_content::SCShareableContent;
    use screencapturekit::stream::configuration::SCStreamConfiguration;
    use screencapturekit::stream::content_filter::SCContentFilter;

    if let Ok(content) = SCShareableContent::get() {
        if let Some(display) = content.displays().first() {
            let filter = SCContentFilter::create()
                .with_display(display)
                .with_excluding_windows(&[])
                .build();
            let config = SCStreamConfiguration::new()
                .with_width(100)
                .with_height(100);

            let stream = AsyncSCStream::new(&filter, &config, 10, SCStreamOutputType::Screen);

            // Get the next future (tests the next() method)
            let next_future = stream.next();
            let debug_str = format!("{next_future:?}");
            assert!(debug_str.contains("NextSample"));
        }
    }
}

#[test]
fn test_async_stream_debug() {
    fn assert_debug<T: std::fmt::Debug>() {}
    assert_debug::<AsyncSCStream>();
}

#[test]
fn test_next_sample_debug() {
    fn assert_debug<T: std::fmt::Debug>() {}
    assert_debug::<NextSample<'_>>();
}

#[test]
fn test_next_sample_typed_debug() {
    fn assert_debug<T: std::fmt::Debug>() {}
    assert_debug::<NextSampleTyped<'_>>();
}

#[test]
fn test_sample_stream_types_debug_and_stream() {
    fn assert_debug<T: std::fmt::Debug>() {}
    fn assert_stream<T: futures_util::Stream>() {}

    assert_debug::<SampleStream<'_>>();
    assert_debug::<TypedSampleStream<'_>>();
    // Compile-time proof the adapters implement `futures_core::Stream`.
    assert_stream::<SampleStream<'_>>();
    assert_stream::<TypedSampleStream<'_>>();
}

#[test]
fn test_stream_control_future_is_send_and_debug() {
    // The lifecycle control futures must be `Send` so they can be driven on
    // multi-threaded executors and moved across `tokio::spawn` boundaries, and
    // `Debug` for ergonomic logging. This is a compile-time guarantee.
    fn assert_send<T: Send>() {}
    fn assert_debug<T: std::fmt::Debug>() {}
    assert_send::<StreamControlFuture>();
    assert_debug::<StreamControlFuture>();
}

#[test]
fn test_async_stream_output_type() {
    // Test SCStreamOutputType enum values
    assert_ne!(SCStreamOutputType::Screen, SCStreamOutputType::Audio);

    let screen = SCStreamOutputType::Screen;
    let audio = SCStreamOutputType::Audio;

    let debug_screen = format!("{screen:?}");
    let debug_audio = format!("{audio:?}");

    assert!(debug_screen.contains("Screen"));
    assert!(debug_audio.contains("Audio"));
}

#[test]
fn test_async_stream_take_error_initially_none() {
    use screencapturekit::shareable_content::SCShareableContent;
    use screencapturekit::stream::configuration::SCStreamConfiguration;
    use screencapturekit::stream::content_filter::SCContentFilter;

    if let Ok(content) = SCShareableContent::get() {
        if let Some(display) = content.displays().first() {
            let filter = SCContentFilter::create()
                .with_display(display)
                .with_excluding_windows(&[])
                .build();
            let config = SCStreamConfiguration::new()
                .with_width(100)
                .with_height(100);
            let stream = AsyncSCStream::new(&filter, &config, 4, SCStreamOutputType::Screen);

            // A freshly created stream is open and has no stop error.
            assert!(!stream.is_closed());
            assert!(stream.take_error().is_none());
        }
    }
}

#[test]
fn test_async_stream_multi_output_typed() {
    use screencapturekit::shareable_content::SCShareableContent;
    use screencapturekit::stream::configuration::SCStreamConfiguration;
    use screencapturekit::stream::content_filter::SCContentFilter;

    if let Ok(content) = SCShareableContent::get() {
        if let Some(display) = content.displays().first() {
            let filter = SCContentFilter::create()
                .with_display(display)
                .with_excluding_windows(&[])
                .build();
            let config = SCStreamConfiguration::new()
                .with_width(160)
                .with_height(120)
                .with_captures_audio(true);

            let mut stream = AsyncSCStream::new(&filter, &config, 16, SCStreamOutputType::Screen);

            // Nothing is buffered before capture starts.
            assert!(stream.try_next_typed().is_none());

            // Add audio as a second output type so one stream carries A/V.
            let _registered = stream.add_output_type(SCStreamOutputType::Audio);

            if stream.inner().start_capture().is_ok() {
                std::thread::sleep(std::time::Duration::from_millis(300));

                // Every delivered sample must be correctly tagged with its type.
                while let Some((_buf, ty)) = stream.try_next_typed() {
                    assert!(matches!(
                        ty,
                        SCStreamOutputType::Screen
                            | SCStreamOutputType::Audio
                            | SCStreamOutputType::Microphone
                    ));
                }

                let _ = stream.inner().stop_capture();
            }
        }
    }
}

#[tokio::test]
async fn test_async_stream_frames_streamext_combinators() {
    use futures_util::StreamExt;
    use screencapturekit::shareable_content::SCShareableContent;
    use screencapturekit::stream::configuration::SCStreamConfiguration;
    use screencapturekit::stream::content_filter::SCContentFilter;

    let Ok(content) = SCShareableContent::get() else {
        return;
    };
    let displays = content.displays();
    let Some(display) = displays.first() else {
        return;
    };

    let filter = SCContentFilter::create()
        .with_display(display)
        .with_excluding_windows(&[])
        .build();
    let config = SCStreamConfiguration::new()
        .with_width(160)
        .with_height(120)
        .with_shows_cursor(true);

    let stream = AsyncSCStream::new(&filter, &config, 16, SCStreamOutputType::Screen);

    if stream.start_capture().await.is_ok() {
        // Drive the `futures_core::Stream` impl through `StreamExt`: take at most
        // 3 frames, mapping each to a unit so we exercise a combinator chain.
        // A timeout keeps a static screen from hanging the test.
        let collected = tokio::time::timeout(
            std::time::Duration::from_secs(3),
            stream
                .frames()
                .map(|_frame| ())
                .take(3)
                .collect::<Vec<()>>(),
        )
        .await;

        // Either we collected up to 3 frames, or we timed out — both are fine on
        // CI; the point is the StreamExt chain type-checks and drives the stream.
        if let Ok(frames) = collected {
            assert!(frames.len() <= 3);
        }

        let _ = stream.stop_capture().await;
    }
}

#[cfg(feature = "macos_14_0")]
mod macos_14_tests {
    use super::*;

    #[test]
    fn test_async_screenshot_manager_exists() {
        // Just verify the type exists and is accessible
        let _ = AsyncSCScreenshotManager;
    }

    #[test]
    fn test_async_screenshot_manager_debug() {
        let manager = AsyncSCScreenshotManager;
        let debug_str = format!("{manager:?}");
        assert!(debug_str.contains("AsyncSCScreenshotManager"));
    }

    #[test]
    fn test_async_screenshot_future_debug() {
        fn assert_debug<T: std::fmt::Debug>() {}
        assert_debug::<AsyncScreenshotFuture<()>>();
    }

    #[test]
    fn test_async_picker_future_debug() {
        fn assert_debug<T: std::fmt::Debug>() {}
        assert_debug::<AsyncPickerFuture>();
        assert_debug::<AsyncPickerFilterFuture>();
    }

    #[test]
    fn test_async_content_sharing_picker_exists() {
        let _ = AsyncSCContentSharingPicker;
    }

    #[test]
    fn test_async_content_sharing_picker_debug() {
        let picker = AsyncSCContentSharingPicker;
        let debug_str = format!("{picker:?}");
        assert!(debug_str.contains("AsyncSCContentSharingPicker"));
    }
}

#[cfg(feature = "macos_15_0")]
mod macos_15_tests {
    use super::*;

    #[test]
    fn test_recording_event_variants() {
        let started = RecordingEvent::Started;
        let finished = RecordingEvent::Finished;
        let failed = RecordingEvent::Failed("test error".to_string());

        assert_eq!(started, RecordingEvent::Started);
        assert_eq!(finished, RecordingEvent::Finished);
        assert_ne!(started, finished);

        if let RecordingEvent::Failed(msg) = failed {
            assert_eq!(msg, "test error");
        } else {
            panic!("Expected Failed variant");
        }
    }

    #[test]
    fn test_recording_event_debug() {
        let event = RecordingEvent::Started;
        let debug_str = format!("{event:?}");
        assert!(debug_str.contains("Started"));

        let event = RecordingEvent::Failed("error".to_string());
        let debug_str = format!("{event:?}");
        assert!(debug_str.contains("Failed"));
        assert!(debug_str.contains("error"));
    }

    #[test]
    fn test_recording_event_clone() {
        let event = RecordingEvent::Failed("clone test".to_string());
        let cloned = event.clone();
        assert_eq!(event, cloned);
    }

    #[test]
    fn test_recording_event_equality() {
        assert_eq!(RecordingEvent::Started, RecordingEvent::Started);
        assert_eq!(RecordingEvent::Finished, RecordingEvent::Finished);
        assert_ne!(RecordingEvent::Started, RecordingEvent::Finished);

        let failed1 = RecordingEvent::Failed("error".to_string());
        let failed2 = RecordingEvent::Failed("error".to_string());
        let failed3 = RecordingEvent::Failed("different".to_string());

        assert_eq!(failed1, failed2);
        assert_ne!(failed1, failed3);
    }

    #[test]
    fn test_next_recording_event_debug() {
        fn assert_debug<T: std::fmt::Debug>() {}
        assert_debug::<NextRecordingEvent<'_>>();
    }

    #[test]
    fn test_async_recording_output_debug() {
        fn assert_debug<T: std::fmt::Debug>() {}
        assert_debug::<AsyncSCRecordingOutput>();
    }
}

// ============================================================================
// Real capture tests (require screen capture permission)
// ============================================================================

mod capture_tests {
    use screencapturekit::async_api::*;
    use screencapturekit::shareable_content::SCShareableContent;
    use screencapturekit::stream::configuration::SCStreamConfiguration;
    use screencapturekit::stream::content_filter::SCContentFilter;
    use screencapturekit::stream::output_type::SCStreamOutputType;
    use std::time::Duration;

    #[test]
    fn test_async_stream_capture_frames() {
        if let Ok(content) = SCShareableContent::get() {
            if let Some(display) = content.displays().first() {
                let filter = SCContentFilter::create()
                    .with_display(display)
                    .with_excluding_windows(&[])
                    .build();

                let config = SCStreamConfiguration::new()
                    .with_width(320)
                    .with_height(240)
                    .with_shows_cursor(true);

                let stream = AsyncSCStream::new(&filter, &config, 5, SCStreamOutputType::Screen);

                // Start capture
                if stream.inner().start_capture().is_ok() {
                    // Wait a bit for frames to arrive
                    std::thread::sleep(Duration::from_millis(300));

                    // Check if we got any frames
                    let count = stream.buffered_count();
                    // May or may not have frames depending on timing
                    let _ = count;

                    // Try to get a frame using try_next
                    let sample = stream.try_next();
                    if let Some(sample) = sample {
                        // Verify the sample has data
                        assert!(!sample.is_valid() || sample.is_valid());
                    }

                    let _ = stream.inner().stop_capture();
                }
            }
        }
    }

    #[test]
    fn test_async_stream_buffer_capacity() {
        if let Ok(content) = SCShareableContent::get() {
            if let Some(display) = content.displays().first() {
                let filter = SCContentFilter::create()
                    .with_display(display)
                    .with_excluding_windows(&[])
                    .build();

                let config = SCStreamConfiguration::new()
                    .with_width(160)
                    .with_height(120)
                    .with_shows_cursor(true);

                // Small buffer capacity
                let stream = AsyncSCStream::new(&filter, &config, 2, SCStreamOutputType::Screen);

                if stream.inner().start_capture().is_ok() {
                    // Wait for buffer to potentially fill
                    std::thread::sleep(Duration::from_millis(200));

                    // Buffer should not exceed capacity
                    assert!(stream.buffered_count() <= 2);

                    let _ = stream.inner().stop_capture();
                }
            }
        }
    }

    #[test]
    fn test_async_stream_clear_buffer() {
        if let Ok(content) = SCShareableContent::get() {
            if let Some(display) = content.displays().first() {
                let filter = SCContentFilter::create()
                    .with_display(display)
                    .with_excluding_windows(&[])
                    .build();

                let config = SCStreamConfiguration::new()
                    .with_width(160)
                    .with_height(120)
                    .with_shows_cursor(true);

                let stream = AsyncSCStream::new(&filter, &config, 10, SCStreamOutputType::Screen);

                if stream.inner().start_capture().is_ok() {
                    std::thread::sleep(Duration::from_millis(200));

                    // Clear the buffer
                    stream.clear_buffer();
                    assert_eq!(stream.buffered_count(), 0);

                    let _ = stream.inner().stop_capture();
                }
            }
        }
    }

    #[test]
    fn test_async_stream_is_closed_after_stop() {
        if let Ok(content) = SCShareableContent::get() {
            if let Some(display) = content.displays().first() {
                let filter = SCContentFilter::create()
                    .with_display(display)
                    .with_excluding_windows(&[])
                    .build();

                let config = SCStreamConfiguration::new()
                    .with_width(160)
                    .with_height(120);

                let stream = AsyncSCStream::new(&filter, &config, 5, SCStreamOutputType::Screen);

                assert!(!stream.is_closed());

                if stream.inner().start_capture().is_ok() {
                    assert!(!stream.is_closed());

                    let _ = stream.inner().stop_capture();
                    // Note: is_closed may or may not be true immediately after stop
                    // depending on implementation
                }
            }
        }
    }

    #[test]
    fn test_async_stream_multiple_try_next() {
        if let Ok(content) = SCShareableContent::get() {
            if let Some(display) = content.displays().first() {
                let filter = SCContentFilter::create()
                    .with_display(display)
                    .with_excluding_windows(&[])
                    .build();

                let config = SCStreamConfiguration::new()
                    .with_width(160)
                    .with_height(120)
                    .with_shows_cursor(true);

                let stream = AsyncSCStream::new(&filter, &config, 10, SCStreamOutputType::Screen);

                if stream.inner().start_capture().is_ok() {
                    std::thread::sleep(Duration::from_millis(200));

                    // Try to get multiple frames
                    let mut frame_count = 0;
                    while let Some(_sample) = stream.try_next() {
                        frame_count += 1;
                        if frame_count >= 3 {
                            break;
                        }
                    }

                    let _ = stream.inner().stop_capture();
                }
            }
        }
    }
}

// ============================================================================
// Async future polling tests
// ============================================================================

mod future_polling_tests {
    use screencapturekit::async_api::*;
    use screencapturekit::shareable_content::SCShareableContent;
    use screencapturekit::stream::configuration::SCStreamConfiguration;
    use screencapturekit::stream::content_filter::SCContentFilter;
    use screencapturekit::stream::output_type::SCStreamOutputType;
    use std::future::Future;
    use std::pin::Pin;
    use std::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};
    use std::time::Duration;

    // Simple waker that does nothing (for single poll tests)
    fn dummy_waker() -> Waker {
        fn clone(_: *const ()) -> RawWaker {
            RawWaker::new(std::ptr::null(), &VTABLE)
        }
        const fn wake(_: *const ()) {}
        const fn wake_by_ref(_: *const ()) {}
        const fn drop(_: *const ()) {}

        static VTABLE: RawWakerVTable = RawWakerVTable::new(clone, wake, wake_by_ref, drop);
        let raw = RawWaker::new(std::ptr::null(), &VTABLE);
        unsafe { Waker::from_raw(raw) }
    }

    #[test]
    fn test_next_sample_future_poll_pending() {
        if let Ok(content) = SCShareableContent::get() {
            if let Some(display) = content.displays().first() {
                let filter = SCContentFilter::create()
                    .with_display(display)
                    .with_excluding_windows(&[])
                    .build();

                let config = SCStreamConfiguration::new()
                    .with_width(160)
                    .with_height(120);

                let stream = AsyncSCStream::new(&filter, &config, 5, SCStreamOutputType::Screen);

                // Create future but don't start capture - should poll Pending or None
                let mut future = stream.next();
                let waker = dummy_waker();
                let mut cx = Context::from_waker(&waker);

                // Poll the future
                let result = Pin::new(&mut future).poll(&mut cx);
                // Either Pending (waiting for frames) or Ready(None) if closed
                match result {
                    Poll::Pending => (),        // Expected when buffer empty
                    Poll::Ready(None) => (),    // Expected if stream not started
                    Poll::Ready(Some(_)) => (), // Possible if there's buffered data
                }
            }
        }
    }

    #[test]
    fn test_next_sample_future_poll_with_data() {
        if let Ok(content) = SCShareableContent::get() {
            if let Some(display) = content.displays().first() {
                let filter = SCContentFilter::create()
                    .with_display(display)
                    .with_excluding_windows(&[])
                    .build();

                let config = SCStreamConfiguration::new()
                    .with_width(160)
                    .with_height(120);

                let stream = AsyncSCStream::new(&filter, &config, 5, SCStreamOutputType::Screen);

                if stream.inner().start_capture().is_ok() {
                    // Wait for frames
                    std::thread::sleep(Duration::from_millis(200));

                    // Now poll the future
                    let mut future = stream.next();
                    let waker = dummy_waker();
                    let mut cx = Context::from_waker(&waker);

                    let result = Pin::new(&mut future).poll(&mut cx);
                    // Should have data or be pending
                    match result {
                        Poll::Ready(Some(sample)) => {
                            // Got a frame!
                            assert!(sample.is_valid() || !sample.is_valid());
                        }
                        Poll::Ready(None) => (),
                        Poll::Pending => (),
                    }

                    let _ = stream.inner().stop_capture();
                }
            }
        }
    }

    #[test]
    fn test_next_sample_after_close() {
        if let Ok(content) = SCShareableContent::get() {
            if let Some(display) = content.displays().first() {
                let filter = SCContentFilter::create()
                    .with_display(display)
                    .with_excluding_windows(&[])
                    .build();

                let config = SCStreamConfiguration::new()
                    .with_width(160)
                    .with_height(120);

                let stream = AsyncSCStream::new(&filter, &config, 5, SCStreamOutputType::Screen);

                if stream.inner().start_capture().is_ok() {
                    let _ = stream.inner().stop_capture();

                    // Clear any buffered data
                    stream.clear_buffer();

                    // Poll after stop - should return None eventually
                    let mut future = stream.next();
                    let waker = dummy_waker();
                    let mut cx = Context::from_waker(&waker);

                    // May take multiple polls
                    for _ in 0..5 {
                        let result = Pin::new(&mut future).poll(&mut cx);
                        if result == Poll::Ready(None) {
                            break;
                        }
                    }
                }
            }
        }
    }
}

// ============================================================================
// macOS 14.0+ Screenshot tests
// ============================================================================

#[cfg(feature = "macos_14_0")]
mod screenshot_tests {
    use screencapturekit::shareable_content::SCShareableContent;
    use screencapturekit::stream::configuration::SCStreamConfiguration;
    use screencapturekit::stream::content_filter::SCContentFilter;

    #[test]
    fn test_screenshot_capture_sample_buffer() {
        use screencapturekit::screenshot_manager::SCScreenshotManager;

        if let Ok(content) = SCShareableContent::get() {
            if let Some(display) = content.displays().first() {
                let filter = SCContentFilter::create()
                    .with_display(display)
                    .with_excluding_windows(&[])
                    .build();

                let config = SCStreamConfiguration::new()
                    .with_width(640)
                    .with_height(480);

                if let Ok(sample) = SCScreenshotManager::capture_sample_buffer(&filter, &config) {
                    assert!(sample.is_valid());
                } else {
                    // May fail without permission
                }
            }
        }
    }

    #[test]
    fn test_screenshot_capture_image() {
        use screencapturekit::screenshot_manager::SCScreenshotManager;

        if let Ok(content) = SCShareableContent::get() {
            if let Some(display) = content.displays().first() {
                let filter = SCContentFilter::create()
                    .with_display(display)
                    .with_excluding_windows(&[])
                    .build();

                let config = SCStreamConfiguration::new()
                    .with_width(640)
                    .with_height(480);

                if let Ok(image) = SCScreenshotManager::capture_image(&filter, &config) {
                    assert!(image.width() > 0);
                    assert!(image.height() > 0);
                } else {
                    // May fail without permission
                }
            }
        }
    }
}

// ============================================================================
// macOS 15.0+ Recording tests
// ============================================================================

#[cfg(feature = "macos_15_0")]
mod recording_tests {
    use screencapturekit::recording_output::{
        SCRecordingOutputCodec, SCRecordingOutputConfiguration, SCRecordingOutputFileType,
    };

    #[test]
    fn test_recording_output_configuration() {
        let temp_dir = std::env::temp_dir();
        let output_path = temp_dir.join("test_recording.mov");

        let config = SCRecordingOutputConfiguration::new()
            .with_output_url(&output_path)
            .with_output_file_type(SCRecordingOutputFileType::MOV)
            .with_video_codec(SCRecordingOutputCodec::H264);

        // Verify configuration was created
        let _ = config;
    }

    #[test]
    fn test_file_type_values() {
        assert_eq!(SCRecordingOutputFileType::MP4.identifier(), "public.mpeg-4");
        assert_eq!(
            SCRecordingOutputFileType::MOV.identifier(),
            "com.apple.quicktime-movie"
        );
        assert_eq!(
            SCRecordingOutputFileType::default(),
            SCRecordingOutputFileType::MP4
        );
    }

    #[test]
    fn test_video_codec_type_values() {
        assert_eq!(SCRecordingOutputCodec::H264.identifier(), "avc1");
        assert_eq!(SCRecordingOutputCodec::HEVC.identifier(), "hvc1");
        assert_eq!(
            SCRecordingOutputCodec::default(),
            SCRecordingOutputCodec::H264
        );
    }
}

// ============================================================================
// macOS 14.0+ Content Sharing Picker tests
// ============================================================================

#[cfg(feature = "macos_14_0")]
mod content_picker_tests {
    use screencapturekit::content_sharing_picker::*;

    #[test]
    fn test_picker_configuration_new() {
        let config = SCContentSharingPickerConfiguration::new();
        // Default should allow changing content
        let _ = config;
    }

    #[test]
    fn test_picker_configuration_allows_changing_content() {
        let mut config = SCContentSharingPickerConfiguration::new();

        config.set_allows_changing_selected_content(true);
        assert!(config.allows_changing_selected_content());

        config.set_allows_changing_selected_content(false);
        assert!(!config.allows_changing_selected_content());
    }

    #[test]
    fn test_picker_configuration_allowed_modes() {
        let mut config = SCContentSharingPickerConfiguration::new();

        config.set_allowed_picker_modes(&[
            SCContentSharingPickerMode::SingleWindow,
            SCContentSharingPickerMode::MultipleWindows,
        ]);

        // Just verify it doesn't crash
        let _ = config;
    }

    #[test]
    fn test_picker_configuration_excluded_bundle_ids() {
        let mut config = SCContentSharingPickerConfiguration::new();

        config.set_excluded_bundle_ids(&["com.apple.finder", "com.apple.dock"]);
        let excluded = config.excluded_bundle_ids();
        assert_eq!(excluded.len(), 2);
        assert!(excluded.contains(&"com.apple.finder".to_string()));
        assert!(excluded.contains(&"com.apple.dock".to_string()));
    }

    #[test]
    fn test_picker_configuration_excluded_window_ids() {
        let mut config = SCContentSharingPickerConfiguration::new();

        config.set_excluded_window_ids(&[123, 456, 789]);
        let excluded = config.excluded_window_ids();
        assert_eq!(excluded.len(), 3);
        assert!(excluded.contains(&123));
        assert!(excluded.contains(&456));
        assert!(excluded.contains(&789));
    }

    #[test]
    fn test_picker_mode_values() {
        assert_eq!(SCContentSharingPickerMode::SingleWindow as i32, 0);
        assert_eq!(SCContentSharingPickerMode::MultipleWindows as i32, 1);
        assert_eq!(SCContentSharingPickerMode::SingleDisplay as i32, 2);
        assert_eq!(SCContentSharingPickerMode::SingleApplication as i32, 3);
        assert_eq!(SCContentSharingPickerMode::MultipleApplications as i32, 4);
    }

    #[test]
    fn test_picker_mode_debug() {
        let mode = SCContentSharingPickerMode::SingleWindow;
        let debug_str = format!("{mode:?}");
        assert!(debug_str.contains("SingleWindow"));
    }

    #[test]
    fn test_picker_mode_clone() {
        let mode1 = SCContentSharingPickerMode::MultipleWindows;
        let mode2 = mode1;
        assert_eq!(mode1, mode2);
    }

    #[test]
    fn test_picked_source_variants() {
        let window_source = SCPickedSource::Window("Test Window".to_string());
        let display_source = SCPickedSource::Display(1);
        let app_source = SCPickedSource::Application("Test App".to_string());
        let unknown_source = SCPickedSource::Unknown;

        // Just verify they can be created
        let _ = (window_source, display_source, app_source, unknown_source);
    }

    #[test]
    fn test_picked_source_debug() {
        let source = SCPickedSource::Display(1);
        let debug_str = format!("{source:?}");
        assert!(debug_str.contains("Display"));
    }

    #[test]
    fn test_picker_outcome_debug() {
        let outcome = SCPickerOutcome::Cancelled;
        let debug_str = format!("{outcome:?}");
        assert!(debug_str.contains("Cancelled"));
    }

    #[test]
    fn test_picker_filter_outcome_debug() {
        let outcome = SCPickerFilterOutcome::Cancelled;
        let debug_str = format!("{outcome:?}");
        assert!(debug_str.contains("Cancelled"));
    }

    #[test]
    fn test_set_maximum_stream_count() {
        // Just verify it doesn't crash
        SCContentSharingPicker::set_maximum_stream_count(5);
        SCContentSharingPicker::set_maximum_stream_count(1);
    }
}

// ============================================================================
// Async/await tests using tokio runtime
// ============================================================================

#[cfg(feature = "async")]
mod tokio_async_tests {
    use screencapturekit::async_api::*;
    use screencapturekit::stream::configuration::SCStreamConfiguration;
    use screencapturekit::stream::content_filter::SCContentFilter;
    use screencapturekit::stream::output_type::SCStreamOutputType;
    use std::time::Duration;

    #[tokio::test]
    async fn test_async_shareable_content_get() {
        let Some(content) = super::live_shareable_content().await else {
            return;
        };
        if content.displays().is_empty() {
            eprintln!("skip: no displays available");
        }
    }

    #[tokio::test]
    async fn test_async_shareable_content_with_options() {
        let result = tokio::time::timeout(
            Duration::from_secs(5),
            AsyncSCShareableContent::create()
                .with_exclude_desktop_windows(true)
                .with_on_screen_windows_only(true)
                .get(),
        )
        .await;
        if !matches!(result, Ok(Ok(_))) {
            eprintln!("skip: filtered shareable content unavailable");
        }
    }

    #[cfg(feature = "macos_14_4")]
    #[tokio::test]
    async fn test_async_shareable_content_current_process() {
        let result = tokio::time::timeout(
            Duration::from_secs(5),
            AsyncSCShareableContent::current_process(),
        )
        .await;
        // May or may not succeed depending on permissions
        let _ = result;
    }

    #[tokio::test]
    async fn test_async_stream_next_await() {
        let Some(content) = super::live_shareable_content().await else {
            return;
        };
        if let Some(display) = content.displays().first() {
            let filter = SCContentFilter::create()
                .with_display(display)
                .with_excluding_windows(&[])
                .build();

            let config = SCStreamConfiguration::new()
                .with_width(160)
                .with_height(120);

            let stream = AsyncSCStream::new(&filter, &config, 5, SCStreamOutputType::Screen);

            if stream.start_capture().await.is_ok() {
                // Use tokio timeout to avoid hanging
                let timeout_result =
                    tokio::time::timeout(std::time::Duration::from_millis(500), stream.next())
                        .await;

                match timeout_result {
                    Ok(Some(_sample)) => {
                        // Got a frame via async/await path
                    }
                    Ok(None) => {
                        // Stream closed
                    }
                    Err(_) => {
                        // Timeout - that's okay for this test
                    }
                }

                let _ = stream.stop_capture().await;
            }
        }
    }

    #[tokio::test]
    async fn test_async_stream_multiple_next_await() {
        let Some(content) = super::live_shareable_content().await else {
            return;
        };
        if let Some(display) = content.displays().first() {
            let filter = SCContentFilter::create()
                .with_display(display)
                .with_excluding_windows(&[])
                .build();

            let config = SCStreamConfiguration::new()
                .with_width(160)
                .with_height(120);

            let stream = AsyncSCStream::new(&filter, &config, 10, SCStreamOutputType::Screen);

            if stream.start_capture().await.is_ok() {
                // Try to get multiple frames with timeout
                for _ in 0..3 {
                    let timeout_result =
                        tokio::time::timeout(std::time::Duration::from_millis(200), stream.next())
                            .await;

                    if timeout_result.is_err() {
                        break; // Timeout is fine
                    }
                }

                let _ = stream.stop_capture().await;
            }
        }
    }

    #[cfg(feature = "macos_14_0")]
    #[tokio::test]
    async fn test_async_screenshot_capture_image() {
        use screencapturekit::async_api::AsyncSCScreenshotManager;

        let Some(content) = super::live_shareable_content().await else {
            return;
        };
        if let Some(display) = content.displays().first() {
            let filter = SCContentFilter::create()
                .with_display(display)
                .with_excluding_windows(&[])
                .build();

            let config = SCStreamConfiguration::new()
                .with_width(320)
                .with_height(240);

            let result = AsyncSCScreenshotManager::capture_image(&filter, &config).await;
            if let Ok(image) = result {
                assert!(image.width() > 0);
                assert!(image.height() > 0);
            } else {
                // Permission error is okay
            }
        }
    }

    #[cfg(feature = "macos_14_0")]
    #[tokio::test]
    async fn test_async_screenshot_capture_sample_buffer() {
        use screencapturekit::async_api::AsyncSCScreenshotManager;

        let Some(content) = super::live_shareable_content().await else {
            return;
        };
        if let Some(display) = content.displays().first() {
            let filter = SCContentFilter::create()
                .with_display(display)
                .with_excluding_windows(&[])
                .build();

            let config = SCStreamConfiguration::new()
                .with_width(320)
                .with_height(240);

            let result = AsyncSCScreenshotManager::capture_sample_buffer(&filter, &config).await;
            if let Ok(sample) = result {
                assert!(sample.is_valid());
            } else {
                // Permission error is okay
            }
        }
    }
}

// ============================================================================
// Additional async coverage tests
// ============================================================================

#[cfg(feature = "async")]
mod additional_async_tests {
    use screencapturekit::async_api::*;
    use std::time::Duration;

    #[tokio::test]
    async fn test_async_shareable_content_below_window() {
        let Some(content) = super::live_shareable_content().await else {
            return;
        };
        if let Some(window) = content.windows().first() {
            let result = tokio::time::timeout(
                Duration::from_secs(5),
                AsyncSCShareableContent::create()
                    .with_exclude_desktop_windows(true)
                    .below_window(window),
            )
            .await;
            // May succeed or fail depending on window state
            let _ = result;
        }
    }

    #[tokio::test]
    async fn test_async_shareable_content_above_window() {
        let Some(content) = super::live_shareable_content().await else {
            return;
        };
        if let Some(window) = content.windows().first() {
            let result = tokio::time::timeout(
                Duration::from_secs(5),
                AsyncSCShareableContent::create()
                    .with_exclude_desktop_windows(false)
                    .above_window(window),
            )
            .await;
            // May succeed or fail depending on window state
            let _ = result;
        }
    }
}

/// Assertive frame-delivery test.
///
/// Unlike the API-shape tests above, this drives a real capture and asserts
/// that frames are actually delivered through the async iterator. It requires
/// screen-recording permission and an attached display, so it is `#[ignore]`d
/// by default. Run it manually with:
///
/// ```text
/// cargo test --features async --test async_api_tests -- --ignored frame_delivery
/// ```
#[tokio::test]
#[ignore = "requires screen-recording permission and an attached display"]
async fn test_async_frame_delivery_assertive() {
    use screencapturekit::shareable_content::SCShareableContent;
    use screencapturekit::stream::configuration::SCStreamConfiguration;
    use screencapturekit::stream::content_filter::SCContentFilter;
    use std::time::Duration;

    let content = SCShareableContent::get().expect("screen-recording permission required");
    let displays = content.displays();
    let display = displays.first().expect("an attached display is required");

    let filter = SCContentFilter::create()
        .with_display(display)
        .with_excluding_windows(&[])
        .build();
    let config = SCStreamConfiguration::new()
        .with_width(320)
        .with_height(240);

    let stream = AsyncSCStream::new(&filter, &config, 16, SCStreamOutputType::Screen);
    stream.start_capture().await.expect("start_capture failed");

    // A real frame must be delivered within a reasonable window.
    let first = tokio::time::timeout(Duration::from_secs(5), stream.next())
        .await
        .expect("timed out waiting for the first frame");
    assert!(first.is_some(), "stream closed before delivering a frame");

    // next() must keep yielding frames (continuous delivery).
    let second = tokio::time::timeout(Duration::from_secs(5), stream.next())
        .await
        .expect("timed out waiting for the second frame");
    assert!(second.is_some(), "expected continuous frame delivery");

    stream.stop_capture().await.expect("stop_capture failed");

    // A clean stop must not surface a stop error.
    assert!(
        stream.take_error().is_none(),
        "clean capture should leave no stop error"
    );
}

// ============================================================================
// AsyncSCStream lifecycle / sender-accounting regressions
// ============================================================================

/// Skip-aware fixture: a 320×240 video-only filter and configuration.
fn async_live_fixture() -> Option<(
    screencapturekit::stream::content_filter::SCContentFilter,
    screencapturekit::stream::configuration::SCStreamConfiguration,
)> {
    use screencapturekit::shareable_content::SCShareableContent;
    use screencapturekit::stream::configuration::SCStreamConfiguration;
    use screencapturekit::stream::content_filter::SCContentFilter;

    let content = match SCShareableContent::get() {
        Ok(c) => c,
        Err(e) => {
            eprintln!("skip: screen-recording permission required (error: {e:?})");
            return None;
        }
    };
    let displays = content.displays();
    let display = displays.first().or_else(|| {
        eprintln!("skip: no displays available");
        None
    })?;

    let filter = SCContentFilter::create()
        .with_display(display)
        .with_excluding_windows(&[])
        .build();
    let config = SCStreamConfiguration::new()
        .with_width(320)
        .with_height(240);
    Some((filter, config))
}

/// Regression test: every extra output type gets its own sender, and each
/// sender used to close the whole queue on drop. Registering a second type —
/// whether `ScreenCaptureKit` accepts it or rejects it (in which case the
/// freshly created sender is dropped straight away) — must leave the original
/// output delivering frames.
#[tokio::test]
async fn test_extra_output_type_registration_never_closes_the_stream() {
    use std::time::Duration;

    let Some((filter, config)) = async_live_fixture() else {
        return;
    };

    let mut stream = AsyncSCStream::new(&filter, &config, 8, SCStreamOutputType::Screen);
    assert!(!stream.is_closed(), "stream closed before it was used");

    // Either outcome exercises the sender accounting: on success the queue has
    // two senders, on failure the second sender is created and immediately
    // dropped — which used to mark the queue closed.
    let added = stream.add_output_type(SCStreamOutputType::Audio);
    eprintln!("add_output_type(Audio) -> {added}");

    assert!(
        !stream.is_closed(),
        "registering an extra output type closed the whole stream"
    );
    assert!(
        stream.take_error().is_none(),
        "registering an extra output type must not record a stop error"
    );

    if let Err(e) = stream.start_capture().await {
        eprintln!("skip: stream failed to start: {e:?}");
        return;
    }
    let frame = tokio::time::timeout(Duration::from_secs(5), stream.next())
        .await
        .expect("timed out waiting for a frame after the extra registration");
    assert!(
        frame.is_some(),
        "the original output stopped delivering after a second registration"
    );

    stream.stop_capture().await.expect("stop_capture failed");
}

/// Regression test: a clean stop is never reported through the delegate, so
/// `stop_capture()` must close the queue itself — otherwise `next()` pends
/// forever after the last buffered frame.
#[tokio::test]
async fn test_clean_stop_closes_the_sample_queue() {
    use std::time::Duration;

    let Some((filter, config)) = async_live_fixture() else {
        return;
    };

    let stream = AsyncSCStream::new(&filter, &config, 8, SCStreamOutputType::Screen);
    if let Err(e) = stream.start_capture().await {
        eprintln!("skip: stream failed to start: {e:?}");
        return;
    }

    let first = tokio::time::timeout(Duration::from_secs(5), stream.next())
        .await
        .expect("timed out waiting for the first frame");
    assert!(first.is_some(), "stream closed before delivering a frame");

    stream.stop_capture().await.expect("stop_capture failed");
    assert!(stream.is_closed(), "a successful stop must close the queue");

    // Drain whatever was already buffered, then the iterator must terminate
    // rather than hang.
    loop {
        let next = tokio::time::timeout(Duration::from_secs(2), stream.next())
            .await
            .expect("next() hung after a clean stop");
        if next.is_none() {
            break;
        }
    }

    assert!(
        stream.take_error().is_none(),
        "a clean stop must not record a stop error"
    );
}

/// `ScreenCaptureKit` cannot restart a stopped `SCStream`; the async wrapper
/// must say so explicitly instead of pending or surfacing an opaque error.
#[tokio::test]
async fn test_restart_after_stop_is_rejected() {
    let Some((filter, config)) = async_live_fixture() else {
        return;
    };

    let stream = AsyncSCStream::new(&filter, &config, 4, SCStreamOutputType::Screen);
    if let Err(e) = stream.start_capture().await {
        eprintln!("skip: stream failed to start: {e:?}");
        return;
    }
    stream.stop_capture().await.expect("stop_capture failed");

    let restart = stream.start_capture().await;
    let err = restart.expect_err("restarting a stopped stream must fail");
    assert!(
        err.to_string().contains("cannot be restarted"),
        "unexpected restart error: {err}"
    );
}

/// Regression test: the queue used to hold a single `Option<Waker>`, so a
/// second concurrent consumer silently evicted the first one's waker and that
/// task never woke. Both consumers must make progress.
#[tokio::test]
async fn test_two_concurrent_consumers_both_get_woken() {
    use std::time::Duration;

    let Some((filter, config)) = async_live_fixture() else {
        return;
    };

    let stream = std::sync::Arc::new(AsyncSCStream::new(
        &filter,
        &config,
        16,
        SCStreamOutputType::Screen,
    ));
    if let Err(e) = stream.start_capture().await {
        eprintln!("skip: stream failed to start: {e:?}");
        return;
    }

    // Park both consumers before any frame arrives, so each has to be woken by
    // the capture callback rather than finding a frame already buffered.
    let a = {
        let stream = stream.clone();
        tokio::spawn(async move { stream.next().await.is_some() })
    };
    let b = {
        let stream = stream.clone();
        tokio::spawn(async move { stream.next().await.is_some() })
    };

    let got_a = tokio::time::timeout(Duration::from_secs(5), a)
        .await
        .expect("first consumer was never woken")
        .expect("first consumer task panicked");
    let got_b = tokio::time::timeout(Duration::from_secs(5), b)
        .await
        .expect("second consumer was never woken")
        .expect("second consumer task panicked");

    assert!(got_a && got_b, "both consumers must receive a frame");

    stream.stop_capture().await.expect("stop_capture failed");
}