cidre 0.15.2

Apple frameworks bindings for rust
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
use crate::{api, arc, cf, cg, cm, cv, define_cls, define_obj_type, dispatch, ns, objc, sc};

#[cfg(feature = "blocks")]
use crate::blocks;

/// Denotes the status of frame sample buffer.
#[doc(alias = "SCFrameStatus")]
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
#[repr(isize)]
pub enum FrameStatus {
    Complete,
    Idle,
    Blank,
    Suspended,
    Started,
    Stopped,
}

define_obj_type!(
    /// Keys you use to retrieve metadata from a frame the system captures.
    #[doc(alias = "SCStreamFrameInfo")]
    pub FrameInfo(ns::String)
);

impl FrameInfo {
    /// The key for the [`cf::Dictionary`] attached to the [`cm::SampleBuf`] that denotes the frames [`sc::FrameStatus`]
    #[doc(alias = "SCStreamFrameInfoStatus")]
    #[inline]
    #[api::available(macos = 12.3)]
    pub fn status() -> &'static Self {
        unsafe { SCStreamFrameInfoStatus }
    }

    /// The key for the [`cf::Dictionary`] attached to the [`cm::SampleBuf`] for the mach absolute
    /// time when the event occurred. For a frame event, this is when the frame was displayed by the window server.
    #[doc(alias = "SCStreamFrameInfoDisplayTime")]
    #[inline]
    #[api::available(macos = 12.3)]
    pub fn display_time() -> &'static Self {
        unsafe { SCStreamFrameInfoDisplayTime }
    }

    /// The key for the [`cf::Dictionary`] attached to the [`cm::SampleBuf`] for the display resolution
    /// associated with the frame. Display resolution is the pixel to point scaling factor.
    /// It should be in the range of \[1, 4\].
    #[doc(alias = "SCStreamFrameInfoScaleFactor")]
    #[inline]
    #[api::available(macos = 12.3)]
    pub fn scale_factor() -> &'static Self {
        unsafe { SCStreamFrameInfoScaleFactor }
    }

    /// The key for the [`cf::Dictionary`] attached to the [`cm::SampleBuf`] for the content scale
    /// associated with the frame. Content scale is the scaling factor from original content
    /// size to its size in surface.
    #[doc(alias = "SCStreamFrameInfoContentScale")]
    #[inline]
    #[api::available(macos = 12.3)]
    pub fn content_scale() -> &'static Self {
        unsafe { SCStreamFrameInfoContentScale }
    }

    /// The key for the [`cf::Dictionary`] attached to the [`cm::SampleBuf`] for the content rect
    /// associated with the frame. Content rect is the size and location of content in points in surface.
    #[doc(alias = "SCStreamFrameInfoContentRect")]
    #[inline]
    #[api::available(macos = 12.3)]
    pub fn content_rect() -> &'static Self {
        unsafe { SCStreamFrameInfoContentRect }
    }

    /// The key for the [`cf::Dictionary`] attached to the [`cm::SampleBuf`] for an array of rectangles
    /// that is the union of both rectangles that were redrawn and rectangles that were moved.
    /// This is an array of [`cg::Rect`] in [`ns::Value`]. The [`cg::Rect`]s elements are specified in pixels.
    #[doc(alias = "SCStreamFrameInfoDirtyRects")]
    #[inline]
    #[api::available(macos = 12.3)]
    pub fn dirty_rects() -> &'static Self {
        unsafe { SCStreamFrameInfoDirtyRects }
    }

    /// The key for the [`cf::Dictionary`] attached to the [`cm::SampleBuf`] for the onscreen location
    /// of the captured content
    #[doc(alias = "SCStreamFrameInfoScreenRect")]
    #[inline]
    #[api::available(macos = 13.1)]
    pub fn screen_rect() -> &'static Self {
        unsafe { SCStreamFrameInfoScreenRect }
    }

    /// The key for the [`cf::Dictionary`] attached to the [`cm::SampleBuf`] for the bounding rect
    /// associated with the frame. Bounding rect is the size and location of smallest bounding box
    /// containing all captured windows in points and in surface coordinates.
    #[doc(alias = "SCStreamFrameInfoBoundingRect")]
    #[inline]
    #[api::available(macos = 14.0)]
    pub fn bounding_rect() -> &'static Self {
        unsafe { SCStreamFrameInfoBoundingRect }
    }

    /// The key for the [`cf::Dictionary`] attached to the [`cm::SampleBuf`] for the content rect associated
    /// with the frame while in presenter overlay.  In presenter overlay small, this content rect is the size
    /// and location of smallest bounding box containing all captured windows plus small overlay window
    /// in points and in surface coordinates. If presenter overlay large, this content rect is the size and
    /// location of shared content in points and in surface coordinates.
    #[doc(alias = "SCStreamFrameInfoPresenterOverlayContentRect")]
    #[inline]
    #[api::available(macos = 14.2)]
    pub fn presenter_overlay_content_rect() -> &'static Self {
        unsafe { SCStreamFrameInfoPresenterOverlayContentRect }
    }
}

#[doc(alias = "SCStreamOutputType")]
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
#[repr(isize)]
pub enum OutputType {
    #[doc(alias = "SCStreamOutputTypeScreen")]
    Screen,
    #[doc(alias = "SCStreamOutputTypeAudio")]
    Audio,
    #[doc(alias = "SCStreamOutputTypeMicrophone")]
    Mic,
}

/// Denotes the setting that can be set to determine when to show the presenter overlay
/// alert for any stream
#[doc(alias = "SCPresenterOverlayAlertSetting")]
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
#[repr(isize)]
pub enum PresenterOverlayAlertSetting {
    /// Allow the system to determine when to show the presenter overlay privacy alert.
    System,

    /// Never show the presenter overlay privacy alert.
    Never,

    /// Always show the presenter overlay privacy alert.
    Always,
}

#[doc(alias = "SCCaptureResolutionType")]
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
#[repr(isize)]
pub enum CaptureResolution {
    Automatic,
    Best,
    Nominal,
}

define_obj_type!(
    #[doc(alias = "SCStreamConfiguration")]
    pub Cfg(ns::Id),
    SC_STREAM_CONFIGURATION
);

/// Client can use sc::StreamCfgPreset to create sc::StreamCfg with suggested values of properties for various use cases
#[doc(alias = "SCStreamConfigurationPreset")]
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
#[repr(isize)]
pub enum CfgPreset {
    #[doc(alias = "SCStreamConfigurationPresetCaptureHDRStreamLocalDisplay")]
    CaptureHdrStreamLocalDisplay,
    #[doc(alias = "SCStreamConfigurationPresetCaptureHDRStreamCanonicalDisplay")]
    CaptureHdrStreamCanoncalDisplay,
    #[doc(alias = "SCStreamConfigurationPresetCaptureHDRScreenshotLocalDisplay")]
    CaptureHdrScreenshotLocalDisplay,
    #[doc(alias = "SCStreamConfigurationPresetCaptureHDRScreenshotCanonicalDisplay")]
    CaptureHdrScreenshotCanoncalDisplay,
}

impl Cfg {
    /// ```
    /// use cidre::{sc, cm, cv};
    ///
    /// let mut cfg = sc::StreamCfg::new();
    ///
    /// cfg.set_width(200);
    /// assert_eq!(200, cfg.width());
    /// cfg.set_height(300);
    /// assert_eq!(300, cfg.height());
    ///
    /// cfg.set_minimum_frame_interval(cm::Time::new(1, 60));
    /// cfg.set_pixel_format(cv::PixelFormat::_32_BGRA);
    /// cfg.set_scales_to_fit(false);
    /// cfg.set_shows_cursor(false);
    ///
    /// ```
    #[objc::msg_send(width)]
    pub fn width(&self) -> usize;

    #[objc::msg_send(setWidth:)]
    pub fn set_width(&mut self, val: usize);

    #[objc::msg_send(height)]
    pub fn height(&self) -> usize;

    #[objc::msg_send(setHeight:)]
    pub fn set_height(&mut self, val: usize);

    #[objc::msg_send(minimumFrameInterval)]
    pub fn minimum_frame_interval(&self) -> cm::Time;

    #[objc::msg_send(setMinimumFrameInterval:)]
    pub fn set_minimum_frame_interval(&mut self, val: cm::Time);

    /// 'BGRA': Packed Little Endian ARGB8888
    /// 'l10r': Packed Little Endian ARGB2101010
    /// '420v': 2-plane "video" range YCbCr 4:2:0
    /// '420f': 2-plane "full" range YCbCr 4:2:0
    /// Since macos 15.0
    /// 'xf44': 2 plane "full" range YCbCr10 4:4:4
    /// 'RGhA': 64 bit RGBA IEEE half-precision float, 16-bit little-endian
    #[objc::msg_send(pixelFormat)]
    pub fn pixel_format(&self) -> cv::PixelFormat;

    #[objc::msg_send(setPixelFormat:)]
    pub fn set_pixel_format(&mut self, val: cv::PixelFormat);

    #[objc::msg_send(scalesToFit)]
    pub fn scales_to_fit(&self) -> bool;

    #[objc::msg_send(setScalesToFit:)]
    pub fn set_scales_to_fit(&mut self, val: bool);

    #[objc::msg_send(preservesAspectRatio)]
    #[api::available(macos = 14.0)]
    pub fn preserves_aspect_ratio(&self) -> bool;

    #[objc::msg_send(setPreservesAspectRatio:)]
    #[api::available(macos = 14.0)]
    pub fn set_preserves_aspect_ratio(&self, val: bool) -> bool;

    #[objc::msg_send(showsCursor)]
    pub fn shows_cursor(&self) -> bool;

    #[objc::msg_send(setShowsCursor:)]
    pub fn set_shows_cursor(&mut self, val: bool);

    /// SCStreamProperty that specifies whether to draw a circle around the cursor
    /// click, default is false. This property will not be affected by shows_cursor.
    /// This property currently applies when pixelFormat is set to BGRA.
    #[objc::msg_send(showMouseClicks)]
    #[api::available(macos = 15.0)]
    pub fn show_mouse_clicks(&self) -> bool;

    /// SCStreamProperty that specifies whether to draw a circle around the cursor
    /// click, default is false. This property will not be affected by shows_cursor.
    /// This property currently applies when pixelFormat is set to BGRA.
    #[objc::msg_send(setShowMouseClicks:)]
    #[api::available(macos = 15.0)]
    pub fn set_show_mouse_clicks(&mut self, val: bool);

    #[objc::msg_send(backgroundColor)]
    pub fn background_color(&self) -> &cg::Color;

    #[objc::msg_send(setBackgroundColor:)]
    pub fn set_background_color(&mut self, val: &cg::Color);

    #[objc::msg_send(sourceRect)]
    pub fn src_rect(&self) -> cg::Rect;

    #[objc::msg_send(setSourceRect:)]
    pub fn set_src_rect(&mut self, val: cg::Rect);

    #[objc::msg_send(destinationRect)]
    pub fn dst_rect(&self) -> cg::Rect;

    #[objc::msg_send(setDestinationRect:)]
    pub fn set_dst_rect(&self, val: cg::Rect);

    #[objc::msg_send(queueDepth)]
    pub fn queue_depth(&self) -> isize;

    #[objc::msg_send(setQueueDepth:)]
    pub fn set_queue_depth(&mut self, val: isize);

    /// Specifies the YCbCr matrix applied to the output surface.
    /// The value must be one of the strings specified
    /// [in](https://developer.apple.com/documentation/coregraphics/quartz_display_services/display_stream_ycbcr_to_rgb_conversion_matrix_options)
    /// Should only be used if your pixel format is 420v or 420f.
    #[objc::msg_send(colorMatrix)]
    pub fn color_matrix(&self) -> &cf::String;

    #[objc::msg_send(setColorMatrix:)]
    pub fn set_color_matrix(&self, val: &cf::String);

    /// The color space of the output buffer.  If not set the output buffer uses the same color
    /// space as the display. The value must be one of the strings specified
    /// [in](https://developer.apple.com/documentation/coregraphics/cgcolorspace/color_space_names)
    #[objc::msg_send(colorSpaceName)]
    pub fn color_space_name(&self) -> &cf::String;

    #[objc::msg_send(setColorSpaceName:)]
    pub fn set_color_space_name(&mut self, val: &cf::String);

    /// Specifies whether the audio will be captured.  By default audio is not captured.
    #[objc::msg_send(capturesAudio)]
    #[api::available(macos = 13.0)]
    pub fn captures_audio(&self) -> bool;

    #[objc::msg_send(setCapturesAudio:)]
    #[api::available(macos = 13.0)]
    pub fn set_captures_audio(&mut self, val: bool);

    /// The sample rate for audio. Default is set to 48000.
    #[objc::msg_send(sampleRate)]
    #[api::available(macos = 13.0)]
    pub fn sample_rate(&self) -> i64;

    #[objc::msg_send(setSampleRate:)]
    #[api::available(macos = 13.0)]
    pub fn set_sample_rate(&mut self, val: i64);

    /// Channel count. Default is set to two.
    #[objc::msg_send(channelCount)]
    #[api::available(macos = 13.0)]
    pub fn channel_count(&self) -> i64;

    #[objc::msg_send(setChannelCount:)]
    #[api::available(macos = 13.0)]
    pub fn set_channel_count(&mut self, val: i64);

    /// Whether to exclude audio from current process. Default is set to false.
    #[objc::msg_send(excludesCurrentProcessAudio)]
    #[api::available(macos = 13.0)]
    pub fn excludes_current_process_audio(&self) -> bool;

    #[objc::msg_send(setExcludesCurrentProcessAudio:)]
    #[api::available(macos = 13.0)]
    pub fn set_excludes_current_process_audio(&mut self, val: bool);

    /// Ignore framing on windows in the display sharing case (will ignore shadows).
    #[objc::msg_send(ignoreShadowsDisplay)]
    #[api::available(macos = 14.0)]
    pub fn ignore_shadows_display(&self) -> bool;

    #[objc::msg_send(setIgnoreShadowsDisplay:)]
    #[api::available(macos = 14.0)]
    pub fn set_ignore_shadows_display(&mut self, val: bool);

    /// Ignore framing on windows in the single window sharing case (will ignore shadows).
    #[objc::msg_send(ignoreShadowsSingleWindow)]
    #[api::available(macos = 14.0)]
    pub fn ignore_shadows_single_window(&self) -> bool;

    #[objc::msg_send(setIgnoreShadowsSingleWindow:)]
    #[api::available(macos = 14.0)]
    pub fn set_ignore_shadows_single_window(&mut self, val: bool);

    #[objc::msg_send(captureResolution)]
    #[api::available(macos = 14.0)]
    pub fn capture_resolution(&self) -> sc::CaptureResolution;

    #[objc::msg_send(setCaptureResolution:)]
    #[api::available(macos = 14.0)]
    pub fn set_capture_resolution(&mut self, val: sc::CaptureResolution);

    #[objc::msg_send(capturesShadowsOnly)]
    #[api::available(macos = 14.0)]
    pub fn captures_shadows_only(&self) -> bool;

    #[objc::msg_send(setCapturesShadowsOnly:)]
    #[api::available(macos = 14.0)]
    pub fn set_captures_shadows_only(&mut self, val: bool);

    /// Ensure partially transparent areas on windows are backed by
    /// a solid white color so that the resulting image is fully opaque.
    #[objc::msg_send(shouldBeOpaque)]
    #[api::available(macos = 14.0)]
    pub fn should_be_opaque(&self) -> bool;

    #[objc::msg_send(setShouldBeOpaque:)]
    #[api::available(macos = 14.0)]
    pub fn set_should_be_opaque(&mut self, val: bool);

    #[objc::msg_send(ignoreGlobalClipDisplay)]
    #[api::available(macos = 14.0)]
    pub fn ignore_global_clip_display(&self) -> bool;

    #[objc::msg_send(setIgnoreGlobalClipDisplay:)]
    #[api::available(macos = 14.0)]
    pub fn set_ignore_global_clip_display(&mut self, val: bool);

    /// Ignore framing on windows in the single window sharing case (will ignore shadows).
    #[objc::msg_send(ignoreGlobalClipSingleWindow)]
    #[api::available(macos = 14.0)]
    pub fn ignore_global_clip_single_window(&self) -> bool;

    #[objc::msg_send(setIgnoreGlobalClipSingleWindow:)]
    #[api::available(macos = 14.0)]
    pub fn set_ignore_global_clip_single_window(&mut self, val: bool);

    /// Informs the system if a privacy alert should be shown when using presenter overlay
    /// for a stream. Defaults to 'sc::PresenterOverlayAlertSetting::System';
    #[objc::msg_send(presenterOverlayPrivacyAlertSetting)]
    #[api::available(macos = 14.0)]
    pub fn presenter_overlay_privacy_alert_setting(&self) -> PresenterOverlayAlertSetting;

    #[objc::msg_send(setPresenterOverlayPrivacyAlertSetting:)]
    #[api::available(macos = 14.0)]
    pub fn set_presenter_overlay_privacy_alert_setting(
        &mut self,
        val: PresenterOverlayAlertSetting,
    );

    /// Show the child windows in display bound windows and applications sharing.
    /// Child windows are included by default.
    #[objc::msg_send(includeChildWindows)]
    #[api::available(macos = 14.2)]
    pub fn include_child_windows(&self) -> bool;

    #[objc::msg_send(setIncludeChildWindows:)]
    #[api::available(macos = 14.2)]
    pub fn set_include_child_windows(&mut self, val: bool);

    #[objc::msg_send(captureMicrophone)]
    #[api::available(macos = 15.0)]
    pub fn capture_mic(&self) -> bool;

    #[objc::msg_send(setCaptureMicrophone:)]
    #[api::available(macos = 15.0)]
    pub fn set_capture_mic(&mut self, val: bool);

    #[objc::msg_send(microphoneCaptureDeviceID)]
    #[api::available(macos = 15.0)]
    pub fn mic_capture_device_id(&self) -> Option<arc::R<ns::String>>;

    #[objc::msg_send(setMicrophoneCaptureDeviceID:)]
    #[api::available(macos = 15.0)]
    pub fn set_mic_capture_device_id(&mut self, val: Option<&ns::String>);

    #[objc::msg_send(captureDynamicRange)]
    #[api::available(macos = 15.0)]
    pub fn capture_dynamic_range(&self) -> CaptureDynamicRange;

    #[objc::msg_send(setCaptureDynamicRange:)]
    #[api::available(macos = 15.0)]
    pub fn set_capture_dynamic_range(&mut self, val: CaptureDynamicRange);

    #[objc::msg_send(streamConfigurationWithPreset:)]
    #[api::available(macos = 15.0)]
    pub fn with_preset(preset: CfgPreset) -> arc::R<Self>;
}

unsafe extern "C" {
    static SC_STREAM_CONFIGURATION: &'static objc::Class<Cfg>;
    static SC_CONTENT_FILTER: &'static objc::Class<ContentFilter>;
    static SC_STREAM: &'static objc::Class<Stream>;
}

#[api::weak]
unsafe extern "C" {
    #[api::available(macos = 12.3)]
    static SCStreamFrameInfoStatus: &'static FrameInfo;
    #[api::available(macos = 12.3)]
    static SCStreamFrameInfoDisplayTime: &'static FrameInfo;
    #[api::available(macos = 12.3)]
    static SCStreamFrameInfoScaleFactor: &'static FrameInfo;
    #[api::available(macos = 12.3)]
    static SCStreamFrameInfoContentScale: &'static FrameInfo;
    #[api::available(macos = 12.3)]
    static SCStreamFrameInfoContentRect: &'static FrameInfo;
    #[api::available(macos = 12.3)]
    static SCStreamFrameInfoDirtyRects: &'static FrameInfo;
    #[api::available(macos = 13.1)]
    static SCStreamFrameInfoScreenRect: &'static FrameInfo;
    #[api::available(macos = 14.0)]
    static SCStreamFrameInfoBoundingRect: &'static FrameInfo;
    #[api::available(macos = 14.2)]
    static SCStreamFrameInfoPresenterOverlayContentRect: &'static FrameInfo;
}

#[doc(alias = "SCCaptureDynamicRange")]
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
#[repr(isize)]
pub enum CaptureDynamicRange {
    #[doc(alias = "SCCaptureDynamicRangeSDR")]
    Sdr,
    #[doc(alias = "SCCaptureDynamicRangeHDRLocalDisplay")]
    HdrLocalDisplay,
    #[doc(alias = "SCCaptureDynamicRangeHDRCanonicalDisplay")]
    HdrCanonicalDisplay,
}

define_obj_type!(
    #[doc(alias = "SCContentFilter")]
    pub ContentFilter(ns::Id)
);

impl arc::A<ContentFilter> {
    #[objc::msg_send(initWithDesktopIndependentWindow:)]
    pub fn init_with_desktop_independent_window(
        self,
        window: &sc::Window,
    ) -> arc::Retained<ContentFilter>;

    #[objc::msg_send(initWithDisplay:excludingWindows:)]
    pub fn init_with_display_excluding_windows(
        self,
        display: &sc::Display,
        windows: &ns::Array<sc::Window>,
    ) -> arc::Retained<ContentFilter>;

    /// Creates a content filter that includes only the specified windows on the given display.
    ///
    /// Use this initializer to capture specific windows from a display. Unlike
    /// `init_with_desktop_independent_window`, this method works reliably for all
    /// window types including regular application windows.
    #[objc::msg_send(initWithDisplay:includingWindows:)]
    #[api::available(macos = 12.3)]
    pub fn init_with_display_including_windows(
        self,
        display: &sc::Display,
        windows: &ns::Array<sc::Window>,
    ) -> arc::Retained<ContentFilter>;

    /// Creates a content filter that includes content from the specified applications,
    /// optionally excluding specific windows.
    #[objc::msg_send(initWithDisplay:includingApplications:exceptingWindows:)]
    #[api::available(macos = 12.3)]
    pub fn init_with_display_including_apps_excepting_windows(
        self,
        display: &sc::Display,
        apps: &ns::Array<sc::RunningApp>,
        excepting_windows: &ns::Array<sc::Window>,
    ) -> arc::Retained<ContentFilter>;

    /// Creates a content filter that excludes content from the specified applications,
    /// optionally excepting specific windows that should still be included.
    #[objc::msg_send(initWithDisplay:excludingApplications:exceptingWindows:)]
    #[api::available(macos = 12.3)]
    pub fn init_with_display_excluding_apps_excepting_windows(
        self,
        display: &sc::Display,
        apps: &ns::Array<sc::RunningApp>,
        excepting_windows: &ns::Array<sc::Window>,
    ) -> arc::Retained<ContentFilter>;
}

impl ContentFilter {
    define_cls!(SC_CONTENT_FILTER);

    /// Creates a content filter that captures just the independent window passed in.
    ///
    /// Note: This is intended for "desktop independent" windows like overlays or HUDs.
    /// For regular application windows, use `with_display_including_windows` instead.
    pub fn with_desktop_independent_window(window: &sc::Window) -> arc::R<ContentFilter> {
        Self::alloc().init_with_desktop_independent_window(window)
    }

    /// Creates a content filter for a display, excluding the specified windows.
    pub fn with_display_excluding_windows(
        display: &sc::Display,
        windows: &ns::Array<sc::Window>,
    ) -> arc::R<Self> {
        Self::alloc().init_with_display_excluding_windows(display, windows)
    }

    /// Creates a content filter that includes only the specified windows on the given display.
    ///
    /// This is the recommended method for capturing specific application windows.
    /// Unlike `with_desktop_independent_window`, this works reliably for all window types.
    ///
    /// # Example
    /// ```no_run
    /// use cidre::{arc, ns, sc};
    ///
    /// async fn capture_window() {
    ///     let content = sc::ShareableContent::current().await.unwrap();
    ///     let displays = content.displays();
    ///     let windows = content.windows();
    ///
    ///     if let (Some(display), Some(window)) = (displays.first(), windows.first()) {
    ///         let window_array = ns::Array::from_slice_retained(&[window.retained()]);
    ///         let filter = sc::ContentFilter::with_display_including_windows(display, &window_array);
    ///         // Use filter with SCStream or SCScreenshotManager
    ///     }
    /// }
    /// ```
    #[api::available(macos = 12.3)]
    pub fn with_display_including_windows(
        display: &sc::Display,
        windows: &ns::Array<sc::Window>,
    ) -> arc::R<Self> {
        Self::alloc().init_with_display_including_windows(display, windows)
    }

    /// Creates a content filter that includes content from the specified applications,
    /// optionally excluding specific windows.
    ///
    /// Use this to capture all windows from specific applications while optionally
    /// excluding certain windows.
    #[api::available(macos = 12.3)]
    pub fn with_display_including_apps_excepting_windows(
        display: &sc::Display,
        apps: &ns::Array<sc::RunningApp>,
        excepting_windows: &ns::Array<sc::Window>,
    ) -> arc::R<Self> {
        Self::alloc().init_with_display_including_apps_excepting_windows(
            display,
            apps,
            excepting_windows,
        )
    }

    /// Creates a content filter that excludes content from the specified applications,
    /// optionally excepting specific windows that should still be included.
    ///
    /// Use this to capture a display while hiding content from certain applications.
    #[api::available(macos = 12.3)]
    pub fn with_display_excluding_apps_excepting_windows(
        display: &sc::Display,
        apps: &ns::Array<sc::RunningApp>,
        excepting_windows: &ns::Array<sc::Window>,
    ) -> arc::R<Self> {
        Self::alloc().init_with_display_excluding_apps_excepting_windows(
            display,
            apps,
            excepting_windows,
        )
    }

    #[objc::msg_send(style)]
    #[api::available(macos = 14.0)]
    pub fn style(&self) -> sc::ShareableContentStyle;

    #[objc::msg_send(pointPixelScale)]
    #[api::available(macos = 14.0)]
    pub fn point_pixel_scale(&self) -> f32;

    #[objc::msg_send(contentRect)]
    #[api::available(macos = 14.0)]
    pub fn content_rect(&self) -> cg::Rect;

    #[objc::msg_send(includeMenuBar)]
    #[api::available(macos = 14.2)]
    pub fn include_menu_bar(&self) -> bool;

    /// To include menu bar as part of the capture. This property has no effect for the
    /// desktop independent window filter. For content filters created with initWithDisplay:excluding,
    /// the default value is 'true'. Display excluding content filters contains the desktop
    /// and dock. For content filters created with initWithDisplay:including, the default
    /// value is 'false'. Display including content filters do not contain the desktop and dock
    #[objc::msg_send(setIncludeMenuBar:)]
    #[api::available(macos = 14.2)]
    pub fn set_include_menu_bar(&mut self, val: bool);

    /// sc::Displays that are included in the content filter
    #[objc::msg_send(includedDisplays)]
    #[api::available(macos = 15.2)]
    pub fn included_displays(&self) -> arc::R<ns::Array<sc::Display>>;

    /// Applications that are included in the content filter
    #[objc::msg_send(includedApplications)]
    #[api::available(macos = 15.2)]
    pub fn included_apps(&self) -> arc::R<ns::Array<sc::RunningApp>>;

    /// Windows that are included in the content filter
    #[objc::msg_send(includedWindows)]
    #[api::available(macos = 15.2)]
    pub fn included_windows(&self) -> arc::R<ns::Array<sc::Window>>;
}

define_obj_type!(
    /// An object that represents a stream of shareable content.
    #[doc(alias = "SCStream")]
    pub Stream(ns::Id)
);

unsafe impl Send for Stream {}
unsafe impl Sync for Stream {}

#[objc::protocol(SCStreamOutput)]
pub trait Output: objc::Obj {
    #[objc::optional]
    #[objc::msg_send(stream:didOutputSampleBuffer:ofType:)]
    fn stream_did_output_sample_buf(
        &mut self,
        stream: &Stream,
        sample_buf: &mut cm::SampleBuf,
        kind: OutputType,
    );
}

#[objc::protocol(SCStreamDelegate)]
pub trait Delegate: objc::Obj {
    #[objc::optional]
    #[objc::msg_send(stream:didStopWithError:)]
    fn stream_did_stop_with_err(&mut self, stream: &Stream, error: &ns::Error);

    #[objc::optional]
    #[objc::msg_send(userDidStopStream:)]
    fn user_did_stop_stream(&mut self, stream: &Stream);

    #[objc::optional]
    #[objc::msg_send(outputVideoEffectDidStartForStream:)]
    fn output_video_effect_did_start_for_stream(&mut self, stream: &Stream);

    #[objc::optional]
    #[objc::msg_send(outputVideoEffectDidStopForStream:)]
    fn output_video_effect_did_stop_for_stream(&mut self, stream: &Stream);

    #[objc::optional]
    #[objc::msg_send(streamDidBecomeActive:)]
    fn stream_did_become_active(&mut self, stream: &Stream);

    #[objc::optional]
    #[objc::msg_send(streamDidBecomeInactive:)]
    fn stream_did_become_inactive(&mut self, stream: &Stream);
}

define_obj_type!(pub AnyDelegate(ns::Id));

impl Delegate for AnyDelegate {}

impl arc::A<Stream> {
    #[objc::msg_send(initWithFilter:configuration:delegate:)]
    pub fn init_with_filter_configuration_delegate<D: Delegate>(
        self,
        filter: &ContentFilter,
        configuration: &Cfg,
        delegate: Option<&D>,
    ) -> arc::Retained<Stream>;
}

impl Stream {
    define_cls!(SC_STREAM);

    pub fn with_delegate<D: Delegate>(
        filter: &ContentFilter,
        configuration: &Cfg,
        delegate: &D,
    ) -> arc::R<Self> {
        Self::alloc().init_with_filter_configuration_delegate(filter, configuration, Some(delegate))
    }

    pub fn new(filter: &ContentFilter, configuration: &Cfg) -> arc::R<Self> {
        Self::alloc().init_with_filter_configuration_delegate::<AnyDelegate>(
            filter,
            configuration,
            None,
        )
    }

    #[objc::msg_send(addStreamOutput:type:sampleHandlerQueue:error:)]
    unsafe fn add_stream_output_type_sample_handler_queue_err<D: Output>(
        &self,
        output: &D,
        output_type: OutputType,
        queue: Option<&dispatch::Queue>,
        error: *mut Option<&ns::Error>,
    ) -> bool;

    pub fn add_stream_output<'ear, D: Output>(
        &self,
        output: &D,
        output_type: OutputType,
        queue: Option<&dispatch::Queue>,
    ) -> ns::Result<'ear> {
        ns::if_false(|err| unsafe {
            self.add_stream_output_type_sample_handler_queue_err(output, output_type, queue, err)
        })
    }

    #[objc::msg_send(removeStreamOutput:type:error:)]
    unsafe fn remove_stream_output_err<'ear, D: Output>(
        &self,
        output: &D,
        output_type: OutputType,
        error: *mut Option<&'ear ns::Error>,
    ) -> bool;

    pub fn remove_stream_output<'ear, D: Output>(
        &self,
        output: &D,
        output_type: OutputType,
    ) -> ns::Result<'ear> {
        ns::if_false(|err| unsafe { self.remove_stream_output_err(output, output_type, err) })
    }

    #[cfg(feature = "blocks")]
    #[objc::msg_send(updateContentFilter:completionHandler:)]
    pub fn update_content_filter_ch_block(
        &self,
        filter: &ContentFilter,
        ch: Option<&mut blocks::ErrCh>,
    );

    #[cfg(feature = "blocks")]
    pub fn update_content_filter_ch(
        &self,
        filter: &ContentFilter,
        ch: impl FnMut(Option<&ns::Error>) + 'static,
    ) {
        let mut block = blocks::ErrCh::new1(ch);
        self.update_content_filter_ch_block(filter, Some(&mut block));
    }

    #[cfg(all(feature = "blocks", feature = "async"))]
    pub async fn update_content_filter(
        &self,
        filter: &ContentFilter,
    ) -> Result<(), arc::R<ns::Error>> {
        let (future, mut block) = blocks::ok();
        self.update_content_filter_ch_block(filter, Some(&mut block));
        future.await
    }

    #[cfg(feature = "blocks")]
    #[objc::msg_send(updateConfiguration:completionHandler:)]
    pub fn update_cfg_ch_block(&self, cfg: &Cfg, ch: Option<&mut blocks::ErrCh>);

    #[cfg(feature = "blocks")]
    pub fn update_cfg_ch(&self, cfg: &Cfg, ch: impl FnMut(Option<&ns::Error>) + 'static) {
        let mut block = blocks::ErrCh::new1(ch);
        self.update_cfg_ch_block(cfg, Some(&mut block));
    }

    #[cfg(all(feature = "blocks", feature = "async"))]
    pub async fn update_cfg(&self, cfg: &Cfg) -> Result<(), arc::R<ns::Error>> {
        let (future, mut block) = blocks::ok();
        self.update_cfg_ch_block(cfg, Some(&mut block));
        future.await
    }

    #[cfg(feature = "blocks")]
    #[objc::msg_send(startCaptureWithCompletionHandler:)]
    pub fn start_with_ch_block(&self, ch: Option<&mut blocks::ErrCh>);

    #[cfg(feature = "blocks")]
    pub fn start_with_ch(&self, ch: impl FnMut(Option<&ns::Error>) + 'static) {
        let mut block = blocks::ErrCh::new1(ch);
        self.start_with_ch_block(Some(&mut block));
    }

    #[cfg(feature = "blocks")]
    #[objc::msg_send(stopCaptureWithCompletionHandler:)]
    pub fn stop_with_ch_block(&self, ch: Option<&mut blocks::ErrCh>);

    #[cfg(feature = "blocks")]
    pub fn stop_with_ch(&self, ch: impl FnMut(Option<&ns::Error>) + 'static) {
        let mut block = blocks::ErrCh::new1(ch);
        self.stop_with_ch_block(Some(&mut block));
    }

    #[cfg(all(feature = "blocks", feature = "async"))]
    pub async fn start(&self) -> Result<(), arc::R<ns::Error>> {
        let (future, mut block) = blocks::ok();
        self.start_with_ch_block(Some(&mut block));
        future.await
    }

    #[cfg(all(feature = "blocks", feature = "async"))]
    pub async fn stop(&self) -> Result<(), arc::R<ns::Error>> {
        let (future, mut block) = blocks::ok();
        self.stop_with_ch_block(Some(&mut block));
        future.await
    }

    #[objc::msg_send(addRecordingOutput:error:)]
    #[api::available(macos = 15.0)]
    pub unsafe fn add_recording_output_err<'ar>(
        &mut self,
        val: &sc::RecordingOutput,
        error: *mut Option<&'ar ns::Error>,
    ) -> bool;

    #[api::available(macos = 15.0)]
    pub fn add_recording_output<'ear>(&mut self, val: &sc::RecordingOutput) -> ns::Result<'ear> {
        ns::if_false(|err| unsafe { self.add_recording_output_err(val, err) })
    }

    #[objc::msg_send(removeRecordingOutput:error:)]
    #[api::available(macos = 15.0)]
    pub unsafe fn remove_recording_output_err<'ar>(
        &mut self,
        val: &sc::RecordingOutput,
        error: *mut Option<&'ar ns::Error>,
    ) -> bool;

    #[api::available(macos = 15.0)]
    pub fn remove_recording_output<'ear>(&mut self, val: &sc::RecordingOutput) -> ns::Result<'ear> {
        ns::if_false(|err| unsafe { self.remove_recording_output_err(val, err) })
    }
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    use crate::{
        cm, cv, define_obj_type, dispatch, ns, objc, sc, sc::stream::Output, sc::stream::OutputImpl,
    };

    define_obj_type!(
        FrameCounter + sc::stream::OutputImpl,
        usize,
        FRAME_COUNTER_CLS
    );

    impl Output for FrameCounter {}

    #[objc::add_methods]
    impl OutputImpl for FrameCounter {}

    #[test]
    fn basics() {
        let mut cfg = sc::StreamCfg::new();

        cfg.set_width(200);
        assert_eq!(200, cfg.width());
        cfg.set_height(300);
        assert_eq!(300, cfg.height());

        cfg.set_minimum_frame_interval(cm::Time::new(1, 60));
        cfg.set_pixel_format(cv::PixelFormat::_32_BGRA);
        cfg.set_scales_to_fit(false);
        cfg.set_shows_cursor(true);
    }

    #[tokio::test]
    async fn start_fails() {
        let q = dispatch::Queue::serial_with_ar_pool();
        let content = sc::ShareableContent::current().await.expect("content");
        let display = content.displays().get(0).unwrap();
        let mut cfg = sc::StreamCfg::new();
        cfg.set_width(display.width() as usize * 2);
        cfg.set_height(display.height() as usize * 2);

        let windows = ns::Array::new();
        let filter = sc::ContentFilter::with_display_excluding_windows(&display, &windows);
        let stream = sc::Stream::new(&filter, &cfg);
        let delegate = FrameCounter::with(0);
        stream
            .add_stream_output(delegate.as_ref(), sc::OutputType::Screen, Some(&q))
            .unwrap();
        stream.start().await.expect("started");
        stream.start().await.expect_err("already started");

        stream
            .update_content_filter(&filter)
            .await
            .expect("Failed to update filter");
        stream.update_cfg(&cfg).await.expect("Failed to update cfg");

        tokio::time::sleep(Duration::from_secs(2)).await;

        stream
            .remove_stream_output(delegate.as_ref(), sc::OutputType::Screen)
            .unwrap();

        stream.stop().await.expect("stopped");
        stream.stop().await.expect_err("already stopped");
        // println!(
        //     "------- {:?} {:?}",
        //     d.obj.as_type_ref(),
        //     d.delegate.counter()
        // );

        // assert!(d.delegate.counter() > 10, "{:?}", d.delegate.counter);
    }

    #[tokio::test]
    async fn content_filter_with_display_including_windows() {
        let content = sc::ShareableContent::current().await.expect("content");
        let displays = content.displays();
        let windows = content.windows();

        let display = displays.first().expect("at least one display");

        // Test with empty window array
        let empty_windows = ns::Array::<sc::Window>::new();
        let filter = sc::ContentFilter::with_display_including_windows(&display, &empty_windows);
        // Filter should be created successfully
        let _ = filter.content_rect();

        // Test with actual windows if available
        if let Some(window) = windows.first() {
            let window_array = ns::Array::from_slice_retained(&[window.retained()]);
            let filter = sc::ContentFilter::with_display_including_windows(&display, &window_array);
            // Filter should be created successfully and have valid content rect
            let rect = filter.content_rect();
            assert!(rect.size.width > 0.0 || rect.size.height > 0.0);
        }
    }

    #[tokio::test]
    async fn content_filter_with_apps() {
        let content = sc::ShareableContent::current().await.expect("content");
        let displays = content.displays();
        let apps = content.apps();

        let display = displays.first().expect("at least one display");
        let empty_windows = ns::Array::<sc::Window>::new();

        // Test including apps
        if let Some(app) = apps.first() {
            let app_array = ns::Array::from_slice_retained(&[app.retained()]);
            let filter = sc::ContentFilter::with_display_including_apps_excepting_windows(
                &display,
                &app_array,
                &empty_windows,
            );
            // Filter should be created successfully
            let _ = filter.content_rect();
        }

        // Test excluding apps
        if let Some(app) = apps.first() {
            let app_array = ns::Array::from_slice_retained(&[app.retained()]);
            let filter = sc::ContentFilter::with_display_excluding_apps_excepting_windows(
                &display,
                &app_array,
                &empty_windows,
            );
            // Filter should be created successfully
            let _ = filter.content_rect();
        }
    }
}