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
//! DXGI Desktop Duplication API wrapper.
//!
//! This module provides [`DxgiDuplicationApi`] to capture a monitor using the
//! Windows DXGI Desktop Duplication API. It integrates with [`crate::monitor::Monitor`]
//! to select the target output and exposes CPU-readable frames via [`crate::frame::FrameBuffer`].
//!
//! # Example
//! ```no_run
//! use windows_capture::dxgi_duplication_api::DxgiDuplicationApi;
//! use windows_capture::encoder::ImageFormat;
//! use windows_capture::monitor::Monitor;
//!
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Select the primary monitor
//! let monitor = Monitor::primary()?;
//!
//! // Create a duplication session for this monitor
//! let mut dup = DxgiDuplicationApi::new(monitor)?;
//!
//! // Try to grab one frame within ~33ms (about 30 FPS budget)
//! let mut frame = dup.acquire_next_frame(33)?;
//!
//! // Map the GPU image into CPU memory and save a PNG
//! let mut buffer = frame.buffer()?;
//! buffer.save_as_image("dup.png", ImageFormat::Png)?;
//! Ok(())
//! }
//! ```
use std::path::Path;
use std::{fs, io, slice};
use rayon::iter::{IntoParallelIterator, ParallelIterator};
use windows::Win32::Foundation::E_ACCESSDENIED;
use windows::Win32::Graphics::Direct3D11::{
D3D11_BOX, D3D11_CPU_ACCESS_READ, D3D11_CPU_ACCESS_WRITE, D3D11_MAP_READ_WRITE, D3D11_MAPPED_SUBRESOURCE,
D3D11_TEXTURE2D_DESC, D3D11_USAGE_STAGING, ID3D11Device, ID3D11DeviceContext, ID3D11Texture2D,
};
use windows::Win32::Graphics::Dxgi::Common::{
DXGI_FORMAT, DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_B8G8R8A8_UNORM_SRGB, DXGI_FORMAT_R8G8B8A8_UNORM,
DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM, DXGI_FORMAT_R10G10B10A2_UNORM,
DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_SAMPLE_DESC,
};
use windows::Win32::Graphics::Dxgi::{
DXGI_ERROR_ACCESS_LOST, DXGI_ERROR_WAIT_TIMEOUT, DXGI_OUTDUPL_DESC, DXGI_OUTDUPL_FRAME_INFO, IDXGIDevice4,
IDXGIOutput6, IDXGIOutputDuplication,
};
use windows::Win32::UI::HiDpi::{DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2, SetProcessDpiAwarenessContext};
use windows::core::Interface;
use crate::d3d11::{StagingTexture, create_d3d_device};
use crate::encoder::{ImageEncoder, ImageEncoderError, ImageEncoderPixelFormat, ImageFormat};
use crate::monitor::Monitor;
/// Errors that can occur while using the DXGI Desktop Duplication API wrapper.
#[derive(thiserror::Error, Debug)]
pub enum Error {
/// The crop rectangle is invalid (start >= end on either axis).
#[error("Invalid crop size")]
InvalidSize,
/// Failed to find a DXGI output that corresponds to the provided monitor.
#[error("Failed to find DXGI output for the specified monitor")]
OutputNotFound,
/// AcquireNextFrame timed out without a new frame becoming available.
#[error("AcquireNextFrame timed out")]
Timeout,
/// The duplication access was lost and must be recreated.
#[error("Duplication access lost; the duplication must be recreated")]
AccessLost,
/// DirectX device creation or related error.
#[error("DirectX error: {0}")]
DirectXError(#[from] crate::d3d11::Error),
/// Invalid or mismatched staging texture supplied to [`DxgiDuplicationFrame::buffer_with`].
#[error("Invalid staging texture: {0}")]
InvalidStagingTexture(&'static str),
/// Image encoding failed.
///
/// Wraps [`crate::encoder::ImageEncoderError`].
#[error("Failed to encode the image buffer to image bytes with the specified format: {0}")]
ImageEncoderError(#[from] crate::encoder::ImageEncoderError),
/// An I/O error occurred while writing the image to disk.
///
/// Wraps [`std::io::Error`].
#[error("I/O error: {0}")]
IoError(#[from] io::Error),
/// Windows API error.
#[error("Windows API error: {0}")]
WindowsError(#[from] windows::core::Error),
}
/// Supported DXGI formats for duplication.
#[derive(Eq, PartialEq, Clone, Copy, Debug)]
pub enum DxgiDuplicationFormat {
/// 16-bit float RGBA format.
Rgba16F,
/// 10-bit RGB with 2-bit alpha format.
Rgb10A2,
/// 10-bit RGB with 2-bit alpha format (biased).
Rgb10XrA2,
/// 8-bit RGBA format.
Rgba8,
/// 8-bit RGBA format (sRGB).
Rgba8Srgb,
/// 8-bit BGRA format.
Bgra8,
/// 8-bit BGRA format (sRGB).
Bgra8Srgb,
}
/// A minimal, ergonomic wrapper around the DXGI Desktop Duplication API for capturing a monitor.
///
/// This wrapper focuses on staying close to the native API while providing a simple Rust interface.
/// It integrates with [`crate::monitor::Monitor`] to select the target output.
pub struct DxgiDuplicationApi {
/// Direct3D 11 device used for duplication operations.
d3d_device: ID3D11Device,
/// Direct3D 11 device context used for copy/map operations.
d3d_device_context: ID3D11DeviceContext,
/// The duplication interface used to acquire frames.
duplication: IDXGIOutputDuplication,
/// Description of the duplication, including format and dimensions.
duplication_desc: DXGI_OUTDUPL_DESC,
/// The DXGI device associated with the Direct3D device.
dxgi_device: IDXGIDevice4,
/// The DXGI output associated with this duplication.
output: IDXGIOutput6,
/// Whether the internal staging texture is currently holding a frame.
is_holding_frame: bool,
}
impl DxgiDuplicationApi {
/// Constructs a new duplication session for the specified monitor.
///
/// Internally creates a Direct3D 11 device and immediate context using the crate's d3d11
/// module.
pub fn new(monitor: Monitor) -> Result<Self, Error> {
// Create D3D11 device and context.
let (d3d_device, d3d_device_context) = create_d3d_device()?;
// Get the adapter used by the created device.
let dxgi_device = d3d_device.cast::<IDXGIDevice4>()?;
let adapter = unsafe { dxgi_device.GetAdapter()? };
// Find the DXGI output that corresponds to the provided HMONITOR.
let found_output;
let mut index = 0u32;
loop {
let output = unsafe { adapter.EnumOutputs(index) }?;
let desc = unsafe { output.GetDesc()? };
if desc.Monitor.0 == monitor.as_raw_hmonitor() {
found_output = Some(output);
break;
}
index += 1;
}
let Some(output) = found_output else {
return Err(Error::OutputNotFound);
};
// Get IDXGIOutput6 for DuplicateOutput.
let output = output.cast::<IDXGIOutput6>()?;
// Set the process to be per-monitor DPI aware to handle high-DPI monitors correctly.
match unsafe { SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2) } {
Ok(()) => (),
Err(e) => {
// returns E_ACCESSDENIED when the default API awareness mode for the process has already been set
// (via a previous API call or within the application manifest)
if e.code() != E_ACCESSDENIED {
return Err(Error::WindowsError(e));
}
}
}
// Create the duplication for this output using the supplied D3D11 device.
let duplication = unsafe { output.DuplicateOutput(&d3d_device)? };
// Get the duplication description to determine the format for our internal texture.
let duplication_desc = unsafe { duplication.GetDesc() };
Ok(Self {
d3d_device,
d3d_device_context,
duplication,
duplication_desc,
dxgi_device,
output,
is_holding_frame: false,
})
}
/// Constructs a new duplication session for the specified monitor, using a custom list of
/// supported DXGI formats.
///
/// This method allows directly receiving the original back buffer format used by a running
/// fullscreen application.
///
/// Bgra8 is inserted because it is widely supported and serves as a reliable fallback.
pub fn new_options(monitor: Monitor, supported_formats: &[DxgiDuplicationFormat]) -> Result<Self, Error> {
// Create D3D11 device and context.
let (d3d_device, d3d_device_context) = create_d3d_device()?;
// Get the adapter used by the created device.
let dxgi_device = d3d_device.cast::<IDXGIDevice4>()?;
let adapter = unsafe { dxgi_device.GetAdapter()? };
// Find the DXGI output that corresponds to the provided HMONITOR.
let found_output;
let mut index = 0u32;
loop {
let output = unsafe { adapter.EnumOutputs(index) }?;
let desc = unsafe { output.GetDesc()? };
if desc.Monitor.0 == monitor.as_raw_hmonitor() {
found_output = Some(output);
break;
}
index += 1;
}
let Some(output) = found_output else {
return Err(Error::OutputNotFound);
};
// Get IDXGIOutput6 for DuplicateOutput1.
let output = output.cast::<IDXGIOutput6>()?;
// Map the supported formats to DXGI_FORMAT values.
let mut supported_formats = supported_formats
.iter()
.map(|f| match f {
DxgiDuplicationFormat::Rgba16F => DXGI_FORMAT_R16G16B16A16_FLOAT,
DxgiDuplicationFormat::Rgb10A2 => DXGI_FORMAT_R10G10B10A2_UNORM,
DxgiDuplicationFormat::Rgb10XrA2 => DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM,
DxgiDuplicationFormat::Rgba8 => DXGI_FORMAT_R8G8B8A8_UNORM,
DxgiDuplicationFormat::Rgba8Srgb => DXGI_FORMAT_R8G8B8A8_UNORM_SRGB,
DxgiDuplicationFormat::Bgra8 => DXGI_FORMAT_B8G8R8A8_UNORM,
DxgiDuplicationFormat::Bgra8Srgb => DXGI_FORMAT_B8G8R8A8_UNORM_SRGB,
})
.collect::<Vec<DXGI_FORMAT>>();
if !supported_formats.contains(&DXGI_FORMAT_B8G8R8A8_UNORM) {
supported_formats.push(DXGI_FORMAT_B8G8R8A8_UNORM);
}
// Set the process to be per-monitor DPI aware to handle high-DPI monitors correctly.
match unsafe { SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2) } {
Ok(()) => (),
Err(e) => {
// returns E_ACCESSDENIED when the default API awareness mode for the process has already been set
// (via a previous API call or within the application manifest)
if e.code() != E_ACCESSDENIED {
return Err(Error::WindowsError(e));
}
}
}
// Create the duplication for this output using the supplied D3D11 device.
let duplication = unsafe { output.DuplicateOutput1(&d3d_device, 0, &supported_formats)? };
// Get the duplication description to determine the format for our internal texture.
let duplication_desc = unsafe { duplication.GetDesc() };
Ok(Self {
d3d_device,
d3d_device_context,
duplication,
duplication_desc,
dxgi_device,
output,
is_holding_frame: false,
})
}
/// Recreates the duplication interface, mostly used after receiving an [`Error::AccessLost`]
/// error from [`DxgiDuplicationApi::acquire_next_frame`].
pub fn recreate(self) -> Result<Self, Error> {
let Self {
d3d_device,
d3d_device_context,
duplication,
duplication_desc: _,
dxgi_device,
output,
is_holding_frame: _,
} = self;
drop(duplication);
let duplication = unsafe { output.DuplicateOutput(&d3d_device)? };
let duplication_desc = unsafe { duplication.GetDesc() };
Ok(Self {
d3d_device,
d3d_device_context,
duplication,
duplication_desc,
dxgi_device,
output,
is_holding_frame: false,
})
}
/// Recreates the duplication interface with a custom list of supported DXGI formats, mostly
/// used after receiving an [`Error::AccessLost`] error from
/// [`DxgiDuplicationApi::acquire_next_frame`].
pub fn recreate_options(self, supported_formats: &[DxgiDuplicationFormat]) -> Result<Self, Error> {
// Map the supported formats to DXGI_FORMAT values.
let mut supported_formats = supported_formats
.iter()
.map(|f| match f {
DxgiDuplicationFormat::Rgba16F => DXGI_FORMAT_R16G16B16A16_FLOAT,
DxgiDuplicationFormat::Rgb10A2 => DXGI_FORMAT_R10G10B10A2_UNORM,
DxgiDuplicationFormat::Rgb10XrA2 => DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM,
DxgiDuplicationFormat::Rgba8 => DXGI_FORMAT_R8G8B8A8_UNORM,
DxgiDuplicationFormat::Rgba8Srgb => DXGI_FORMAT_R8G8B8A8_UNORM_SRGB,
DxgiDuplicationFormat::Bgra8 => DXGI_FORMAT_B8G8R8A8_UNORM,
DxgiDuplicationFormat::Bgra8Srgb => DXGI_FORMAT_B8G8R8A8_UNORM_SRGB,
})
.collect::<Vec<DXGI_FORMAT>>();
if !supported_formats.contains(&DXGI_FORMAT_B8G8R8A8_UNORM) {
supported_formats.push(DXGI_FORMAT_B8G8R8A8_UNORM);
}
let Self {
d3d_device,
d3d_device_context,
duplication,
duplication_desc: _,
dxgi_device,
output,
is_holding_frame: _,
} = self;
drop(duplication);
let duplication = unsafe { output.DuplicateOutput1(&d3d_device, 0, &supported_formats)? };
let duplication_desc = unsafe { duplication.GetDesc() };
Ok(Self {
d3d_device,
d3d_device_context,
duplication,
duplication_desc,
dxgi_device,
output,
is_holding_frame: false,
})
}
/// Gets the underlying [`windows::Win32::Graphics::Direct3D11::ID3D11Device`] associated with
/// this object.
#[inline]
#[must_use]
pub const fn device(&self) -> &ID3D11Device {
&self.d3d_device
}
/// Gets the underlying [`windows::Win32::Graphics::Direct3D11::ID3D11DeviceContext`] used for
/// GPU operations.
#[inline]
#[must_use]
pub const fn device_context(&self) -> &ID3D11DeviceContext {
&self.d3d_device_context
}
/// Gets the underlying [`windows::Win32::Graphics::Dxgi::IDXGIOutputDuplication`] interface.
#[inline]
#[must_use]
pub const fn duplication(&self) -> &IDXGIOutputDuplication {
&self.duplication
}
/// Gets the [`windows::Win32::Graphics::Dxgi::DXGI_OUTDUPL_DESC`] of the duplication.
#[inline]
#[must_use]
pub const fn duplication_desc(&self) -> &DXGI_OUTDUPL_DESC {
&self.duplication_desc
}
/// Gets the underlying [`windows::Win32::Graphics::Dxgi::IDXGIDevice4`] interface.
#[inline]
#[must_use]
pub const fn dxgi_device(&self) -> &IDXGIDevice4 {
&self.dxgi_device
}
/// Gets the underlying [`windows::Win32::Graphics::Dxgi::IDXGIOutput6`] interface.
#[inline]
#[must_use]
pub const fn output(&self) -> &IDXGIOutput6 {
&self.output
}
/// Gets the width of the duplication.
#[inline]
#[must_use]
pub const fn width(&self) -> u32 {
self.duplication_desc.ModeDesc.Width
}
/// Gets the height of the duplication.
#[inline]
#[must_use]
pub const fn height(&self) -> u32 {
self.duplication_desc.ModeDesc.Height
}
/// Gets the pixel format of the duplication.
#[inline]
#[must_use]
pub const fn format(&self) -> DxgiDuplicationFormat {
match self.duplication_desc.ModeDesc.Format {
DXGI_FORMAT_R16G16B16A16_FLOAT => DxgiDuplicationFormat::Rgba16F,
DXGI_FORMAT_R10G10B10A2_UNORM => DxgiDuplicationFormat::Rgb10A2,
DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM => DxgiDuplicationFormat::Rgb10XrA2,
DXGI_FORMAT_R8G8B8A8_UNORM => DxgiDuplicationFormat::Rgba8,
DXGI_FORMAT_R8G8B8A8_UNORM_SRGB => DxgiDuplicationFormat::Rgba8Srgb,
DXGI_FORMAT_B8G8R8A8_UNORM => DxgiDuplicationFormat::Bgra8,
DXGI_FORMAT_B8G8R8A8_UNORM_SRGB => DxgiDuplicationFormat::Bgra8Srgb,
_ => unreachable!(),
}
}
/// Gets the refresh rate of the duplication as (numerator, denominator).
#[inline]
#[must_use]
pub const fn refresh_rate(&self) -> (u32, u32) {
(self.duplication_desc.ModeDesc.RefreshRate.Numerator, self.duplication_desc.ModeDesc.RefreshRate.Denominator)
}
/// Acquires the next frame and updates the internal texture.
///
/// This call will block up to `timeout_ms` milliseconds. If no new frame arrives within
/// the timeout, [`Error::Timeout`] is returned. If duplication access is lost,
/// [`Error::AccessLost`] is returned and a new duplication should be recreated.
///
/// Main reasons for [`Error::AccessLost`] include:
/// - The display mode of the output changed (e.g. resolution or color format change).
/// - The user switched to a different desktop (e.g. via Ctrl+Alt+Del or Fast User Switching).
/// - Switch from DWM on, DWM off, or other full-screen application
///
/// The returned [`DxgiDuplicationFrame`] allows you to map the current full desktop image via
/// [`DxgiDuplicationFrame::buffer`]. It contains the list of dirty rectangles reported for this
/// frame.
///
/// # Errors
/// - [`Error::Timeout`] when no frame arrives within `timeout_ms`
/// - [`Error::AccessLost`] when duplication access is lost and must be recreated
/// - [`Error::WindowsError`] for other Windows API failures during frame acquisition
#[inline]
pub fn acquire_next_frame(&mut self, timeout_ms: u32) -> Result<DxgiDuplicationFrame<'_>, Error> {
let mut frame_info = DXGI_OUTDUPL_FRAME_INFO::default();
let mut resource = None;
// Release the previous frame if we were holding one
if self.is_holding_frame {
match unsafe { self.duplication.ReleaseFrame() } {
Ok(()) => (),
Err(e) => {
if e.code() == DXGI_ERROR_ACCESS_LOST {
return Err(Error::AccessLost);
} else {
return Err(Error::WindowsError(e));
}
}
}
self.is_holding_frame = false;
}
// Acquire frame
match unsafe { self.duplication.AcquireNextFrame(timeout_ms, &mut frame_info, &mut resource) } {
Ok(()) => (),
Err(e) => {
if e.code() == DXGI_ERROR_WAIT_TIMEOUT {
return Err(Error::Timeout);
} else if e.code() == DXGI_ERROR_ACCESS_LOST {
return Err(Error::AccessLost);
} else {
return Err(Error::WindowsError(e));
}
}
}
self.is_holding_frame = true;
let resource = resource.unwrap();
// Convert the resource to an ID3D11Texture2D.
let frame_texture = resource.cast::<ID3D11Texture2D>()?;
// Obtain texture description to get size/format details.
let mut frame_desc = D3D11_TEXTURE2D_DESC::default();
unsafe { frame_texture.GetDesc(&mut frame_desc) };
Ok(DxgiDuplicationFrame {
d3d_device: &self.d3d_device,
d3d_device_context: &self.d3d_device_context,
duplication: &self.duplication,
texture: frame_texture,
texture_desc: frame_desc,
frame_info,
})
}
}
/// Represents a pre-assembled full desktop image for the current frame,
/// backed by the internal GPU texture.
/// Call [`DxgiDuplicationFrame::buffer`] to obtain a CPU-readable [`crate::frame::FrameBuffer`].
pub struct DxgiDuplicationFrame<'a> {
d3d_device: &'a ID3D11Device,
d3d_device_context: &'a ID3D11DeviceContext,
duplication: &'a IDXGIOutputDuplication,
texture: ID3D11Texture2D,
texture_desc: D3D11_TEXTURE2D_DESC,
frame_info: DXGI_OUTDUPL_FRAME_INFO,
}
impl<'a> DxgiDuplicationFrame<'a> {
/// Gets the width of the frame.
#[inline]
#[must_use]
pub const fn width(&self) -> u32 {
self.texture_desc.Width
}
/// Gets the height of the frame.
#[inline]
#[must_use]
pub const fn height(&self) -> u32 {
self.texture_desc.Height
}
/// Gets the pixel format of the frame.
#[inline]
#[must_use]
pub const fn format(&self) -> DxgiDuplicationFormat {
match self.texture_desc.Format {
DXGI_FORMAT_R16G16B16A16_FLOAT => DxgiDuplicationFormat::Rgba16F,
DXGI_FORMAT_R10G10B10A2_UNORM => DxgiDuplicationFormat::Rgb10A2,
DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM => DxgiDuplicationFormat::Rgb10XrA2,
DXGI_FORMAT_R8G8B8A8_UNORM => DxgiDuplicationFormat::Rgba8,
DXGI_FORMAT_R8G8B8A8_UNORM_SRGB => DxgiDuplicationFormat::Rgba8Srgb,
DXGI_FORMAT_B8G8R8A8_UNORM => DxgiDuplicationFormat::Bgra8,
DXGI_FORMAT_B8G8R8A8_UNORM_SRGB => DxgiDuplicationFormat::Bgra8Srgb,
_ => unreachable!(),
}
}
/// Gets the underlying Direct3D device associated with this frame.
#[inline]
#[must_use]
pub const fn device(&self) -> &ID3D11Device {
self.d3d_device
}
/// Gets the underlying Direct3D device context used for GPU operations.
#[inline]
#[must_use]
pub const fn device_context(&self) -> &ID3D11DeviceContext {
self.d3d_device_context
}
/// Gets the underlying IDXGIOutputDuplication interface.
#[inline]
#[must_use]
pub const fn duplication(&self) -> &IDXGIOutputDuplication {
self.duplication
}
/// Gets the underlying [`windows::Win32::Graphics::Direct3D11::ID3D11Texture2D`] interface.
#[inline]
#[must_use]
pub const fn texture(&self) -> &ID3D11Texture2D {
&self.texture
}
/// Gets the [`windows::Win32::Graphics::Direct3D11::D3D11_TEXTURE2D_DESC`] of the underlying
/// texture.
#[inline]
#[must_use]
pub const fn texture_desc(&self) -> &D3D11_TEXTURE2D_DESC {
&self.texture_desc
}
/// Gets the frame information for the current frame.
#[inline]
#[must_use]
pub const fn frame_info(&self) -> &DXGI_OUTDUPL_FRAME_INFO {
&self.frame_info
}
/// Maps the internal frame into CPU accessible memory and returns a
/// [`crate::frame::FrameBuffer`].
///
/// This creates a staging texture, copies the internal texture into it,
/// and maps it for CPU read/write. The returned buffer may include row padding;
/// you can use [`crate::frame::FrameBuffer::as_nopadding_buffer`] to obtain a packed
/// representation.
#[inline]
pub fn buffer<'b>(&'b mut self) -> Result<DxgiDuplicationFrameBuffer<'b>, Error> {
// Staging texture settings
let texture_desc = D3D11_TEXTURE2D_DESC {
Width: self.texture_desc.Width,
Height: self.texture_desc.Height,
MipLevels: 1,
ArraySize: 1,
Format: self.texture_desc.Format,
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
Usage: D3D11_USAGE_STAGING,
BindFlags: 0,
CPUAccessFlags: D3D11_CPU_ACCESS_READ.0 as u32 | D3D11_CPU_ACCESS_WRITE.0 as u32,
MiscFlags: 0,
};
// Create a CPU-readable staging texture
let mut staging = None;
unsafe {
self.d3d_device.CreateTexture2D(&texture_desc, None, Some(&mut staging))?;
};
let staging = staging.unwrap();
// Copy from the internal GPU texture into the staging texture
unsafe {
self.d3d_device_context.CopyResource(&staging, &self.texture);
};
// Map the staging texture for CPU access
let mut mapped = D3D11_MAPPED_SUBRESOURCE::default();
unsafe {
self.d3d_device_context.Map(&staging, 0, D3D11_MAP_READ_WRITE, 0, Some(&mut mapped))?;
};
// SAFETY: The staging texture remains alive for the scope of this function.
let mapped_frame_data = unsafe {
slice::from_raw_parts_mut(mapped.pData.cast(), (self.texture_desc.Height * mapped.RowPitch) as usize)
};
let format = match self.texture_desc.Format {
DXGI_FORMAT_R16G16B16A16_FLOAT => DxgiDuplicationFormat::Rgba16F,
DXGI_FORMAT_R10G10B10A2_UNORM => DxgiDuplicationFormat::Rgb10A2,
DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM => DxgiDuplicationFormat::Rgb10XrA2,
DXGI_FORMAT_R8G8B8A8_UNORM => DxgiDuplicationFormat::Rgba8,
DXGI_FORMAT_R8G8B8A8_UNORM_SRGB => DxgiDuplicationFormat::Rgba8Srgb,
DXGI_FORMAT_B8G8R8A8_UNORM => DxgiDuplicationFormat::Bgra8,
DXGI_FORMAT_B8G8R8A8_UNORM_SRGB => DxgiDuplicationFormat::Bgra8Srgb,
_ => unreachable!(),
};
Ok(DxgiDuplicationFrameBuffer::new(
mapped_frame_data,
self.texture_desc.Width,
self.texture_desc.Height,
mapped.RowPitch,
mapped.DepthPitch,
format,
))
}
/// Gets a cropped frame buffer of the duplication frame.
#[inline]
pub fn buffer_crop<'b>(
&'b mut self,
start_x: u32,
start_y: u32,
end_x: u32,
end_y: u32,
) -> Result<DxgiDuplicationFrameBuffer<'b>, Error> {
if start_x >= end_x || start_y >= end_y {
return Err(Error::InvalidSize);
}
let texture_width = end_x - start_x;
let texture_height = end_y - start_y;
// Staging texture settings for the cropped region
let texture_desc = D3D11_TEXTURE2D_DESC {
Width: texture_width,
Height: texture_height,
MipLevels: 1,
ArraySize: 1,
Format: self.texture_desc.Format,
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
Usage: D3D11_USAGE_STAGING,
BindFlags: 0,
CPUAccessFlags: D3D11_CPU_ACCESS_READ.0 as u32 | D3D11_CPU_ACCESS_WRITE.0 as u32,
MiscFlags: 0,
};
// Create a CPU-readable staging texture of the crop size
let mut staging = None;
unsafe {
self.d3d_device.CreateTexture2D(&texture_desc, None, Some(&mut staging))?;
};
let staging = staging.unwrap();
// Define the source box to copy from the duplication texture
let src_box = D3D11_BOX { left: start_x, top: start_y, front: 0, right: end_x, bottom: end_y, back: 1 };
// Copy the selected region into the staging texture at (0,0)
unsafe {
self.d3d_device_context.CopySubresourceRegion(&staging, 0, 0, 0, 0, &self.texture, 0, Some(&src_box));
}
// Map the staging texture for CPU access
let mut mapped = D3D11_MAPPED_SUBRESOURCE::default();
unsafe {
self.d3d_device_context.Map(&staging, 0, D3D11_MAP_READ_WRITE, 0, Some(&mut mapped))?;
}
// SAFETY: staging remains alive for the scope of this function.
let mapped_frame_data =
unsafe { slice::from_raw_parts_mut(mapped.pData.cast(), (texture_height * mapped.RowPitch) as usize) };
let format = match self.texture_desc.Format {
DXGI_FORMAT_R16G16B16A16_FLOAT => DxgiDuplicationFormat::Rgba16F,
DXGI_FORMAT_R10G10B10A2_UNORM => DxgiDuplicationFormat::Rgb10A2,
DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM => DxgiDuplicationFormat::Rgb10XrA2,
DXGI_FORMAT_R8G8B8A8_UNORM => DxgiDuplicationFormat::Rgba8,
DXGI_FORMAT_R8G8B8A8_UNORM_SRGB => DxgiDuplicationFormat::Rgba8Srgb,
DXGI_FORMAT_B8G8R8A8_UNORM => DxgiDuplicationFormat::Bgra8,
DXGI_FORMAT_B8G8R8A8_UNORM_SRGB => DxgiDuplicationFormat::Bgra8Srgb,
_ => unreachable!(),
};
Ok(DxgiDuplicationFrameBuffer::new(
mapped_frame_data,
texture_width,
texture_height,
mapped.RowPitch,
mapped.DepthPitch,
format,
))
}
/// Advanced: reuse your own CPU staging texture ([`crate::d3d11::StagingTexture`]).
///
/// This avoids per-frame allocations and lets you manage the texture’s lifetime.
/// The `staging` texture must be a `D3D11_USAGE_STAGING` 2D texture with CPU read/write access,
/// matching the frame’s width/height/format.
#[inline]
pub fn buffer_with<'s>(
&'s mut self,
staging: &'s mut StagingTexture,
) -> Result<DxgiDuplicationFrameBuffer<'s>, Error> {
// Validate geometry/format match.
let desc = staging.desc();
if desc.Width != self.texture_desc.Width || desc.Height != self.texture_desc.Height {
return Err(Error::InvalidStagingTexture("geometry must match the frame"));
}
if desc.Format != self.texture_desc.Format {
return Err(Error::InvalidStagingTexture("format must match the frame"));
}
// Unmap if was previously mapped
if staging.is_mapped() {
unsafe { self.d3d_device_context.Unmap(staging.texture(), 0) };
staging.set_mapped(false);
}
// Copy the acquired duplication texture into the provided staging texture
unsafe {
self.d3d_device_context.CopyResource(staging.texture(), &self.texture);
}
// Map the staging texture for CPU access
let mut mapped = D3D11_MAPPED_SUBRESOURCE::default();
unsafe {
self.d3d_device_context.Map(staging.texture(), 0, D3D11_MAP_READ_WRITE, 0, Some(&mut mapped))?;
}
staging.set_mapped(true);
// SAFETY: staging lives for 's and remains alive while the FrameBuffer is borrowed.
let mapped_frame_data = unsafe {
slice::from_raw_parts_mut(mapped.pData.cast(), (self.texture_desc.Height * mapped.RowPitch) as usize)
};
let format = match self.texture_desc.Format {
DXGI_FORMAT_R16G16B16A16_FLOAT => DxgiDuplicationFormat::Rgba16F,
DXGI_FORMAT_R10G10B10A2_UNORM => DxgiDuplicationFormat::Rgb10A2,
DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM => DxgiDuplicationFormat::Rgb10XrA2,
DXGI_FORMAT_R8G8B8A8_UNORM => DxgiDuplicationFormat::Rgba8,
DXGI_FORMAT_R8G8B8A8_UNORM_SRGB => DxgiDuplicationFormat::Rgba8Srgb,
DXGI_FORMAT_B8G8R8A8_UNORM => DxgiDuplicationFormat::Bgra8,
DXGI_FORMAT_B8G8R8A8_UNORM_SRGB => DxgiDuplicationFormat::Bgra8Srgb,
_ => unreachable!(),
};
Ok(DxgiDuplicationFrameBuffer::new(
mapped_frame_data,
self.texture_desc.Width,
self.texture_desc.Height,
mapped.RowPitch,
mapped.DepthPitch,
format,
))
}
/// Advanced: cropped buffer using a preallocated staging texture.
/// The provided staging texture must be a D3D11_USAGE_STAGING 2D texture with CPU read/write
/// access, of the same format as the duplication frame, and large enough to contain the
/// crop region.
#[inline]
pub fn buffer_crop_with<'s>(
&'s mut self,
staging: &'s mut StagingTexture,
start_x: u32,
start_y: u32,
end_x: u32,
end_y: u32,
) -> Result<DxgiDuplicationFrameBuffer<'s>, Error> {
// Validate crop rectangle
if start_x >= end_x || start_y >= end_y {
return Err(Error::InvalidSize);
}
let crop_width = end_x - start_x;
let crop_height = end_y - start_y;
// Validate format and capacity
let desc = staging.desc();
if desc.Format != self.texture_desc.Format {
return Err(Error::InvalidStagingTexture("format must match the frame"));
}
if desc.Width < crop_width || desc.Height < crop_height {
return Err(Error::InvalidStagingTexture("staging texture too small for crop region"));
}
// Unmap if was previously mapped
if staging.is_mapped() {
unsafe { self.d3d_device_context.Unmap(staging.texture(), 0) };
staging.set_mapped(false);
}
// Define the source region to copy
let src_box = D3D11_BOX { left: start_x, top: start_y, front: 0, right: end_x, bottom: end_y, back: 1 };
// Copy the selected region to the top-left of the staging texture
unsafe {
self.d3d_device_context.CopySubresourceRegion(
staging.texture(),
0,
0,
0,
0,
&self.texture,
0,
Some(&src_box),
);
}
// Map the staging texture
let mut mapped = D3D11_MAPPED_SUBRESOURCE::default();
unsafe {
self.d3d_device_context.Map(staging.texture(), 0, D3D11_MAP_READ_WRITE, 0, Some(&mut mapped))?;
}
staging.set_mapped(true);
// SAFETY: staging lives for 's and remains alive while the FrameBuffer is borrowed.
let mapped_frame_data =
unsafe { slice::from_raw_parts_mut(mapped.pData.cast(), (crop_height * mapped.RowPitch) as usize) };
let format = match self.texture_desc.Format {
DXGI_FORMAT_R16G16B16A16_FLOAT => DxgiDuplicationFormat::Rgba16F,
DXGI_FORMAT_R10G10B10A2_UNORM => DxgiDuplicationFormat::Rgb10A2,
DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM => DxgiDuplicationFormat::Rgb10XrA2,
DXGI_FORMAT_R8G8B8A8_UNORM => DxgiDuplicationFormat::Rgba8,
DXGI_FORMAT_R8G8B8A8_UNORM_SRGB => DxgiDuplicationFormat::Rgba8Srgb,
DXGI_FORMAT_B8G8R8A8_UNORM => DxgiDuplicationFormat::Bgra8,
DXGI_FORMAT_B8G8R8A8_UNORM_SRGB => DxgiDuplicationFormat::Bgra8Srgb,
_ => unreachable!(),
};
Ok(DxgiDuplicationFrameBuffer::new(
mapped_frame_data,
crop_width,
crop_height,
mapped.RowPitch,
mapped.DepthPitch,
format,
))
}
/// Saves the frame buffer as an image to the specified path.
#[inline]
pub fn save_as_image<T: AsRef<Path>>(&mut self, path: T, format: ImageFormat) -> Result<(), Error> {
let mut frame_buffer = self.buffer()?;
frame_buffer.save_as_image(path, format)?;
Ok(())
}
}
/// Represents a frame buffer containing pixel data.
///
/// # Example
/// ```ignore
/// // Get a frame from the capture session
/// let mut buffer = frame.buffer()?;
/// buffer.save_as_image("screenshot.png", ImageFormat::Png)?;
/// ```
pub struct DxgiDuplicationFrameBuffer<'a> {
raw_buffer: &'a mut [u8],
width: u32,
height: u32,
row_pitch: u32,
depth_pitch: u32,
format: DxgiDuplicationFormat,
}
impl<'a> DxgiDuplicationFrameBuffer<'a> {
/// Constructs a new `FrameBuffer`.
#[inline]
#[must_use]
pub const fn new(
raw_buffer: &'a mut [u8],
width: u32,
height: u32,
row_pitch: u32,
depth_pitch: u32,
format: DxgiDuplicationFormat,
) -> Self {
Self { raw_buffer, width, height, row_pitch, depth_pitch, format }
}
/// Gets the width of the frame buffer.
#[inline]
#[must_use]
pub const fn width(&self) -> u32 {
self.width
}
/// Gets the height of the frame buffer.
#[inline]
#[must_use]
pub const fn height(&self) -> u32 {
self.height
}
/// Gets the row pitch of the frame buffer.
#[inline]
#[must_use]
pub const fn row_pitch(&self) -> u32 {
self.row_pitch
}
/// Gets the depth pitch of the frame buffer.
#[inline]
#[must_use]
pub const fn depth_pitch(&self) -> u32 {
self.depth_pitch
}
/// Gets the color format of the frame buffer.
#[inline]
#[must_use]
pub const fn format(&self) -> DxgiDuplicationFormat {
self.format
}
/// Checks if the buffer has padding.
#[inline]
#[must_use]
pub const fn has_padding(&self) -> bool {
self.width * 4 != self.row_pitch
}
/// Gets the pixel data without padding.
#[inline]
#[must_use]
pub fn as_nopadding_buffer<'b>(&'b self, buffer: &'b mut Vec<u8>) -> &'b [u8] {
if !self.has_padding() {
return self.raw_buffer;
}
let multiplier = match self.format {
DxgiDuplicationFormat::Rgba16F => 8,
DxgiDuplicationFormat::Rgb10A2 => 4,
DxgiDuplicationFormat::Rgb10XrA2 => 4,
DxgiDuplicationFormat::Rgba8 => 4,
DxgiDuplicationFormat::Rgba8Srgb => 4,
DxgiDuplicationFormat::Bgra8 => 4,
DxgiDuplicationFormat::Bgra8Srgb => 4,
};
let frame_size = (self.width * self.height * multiplier) as usize;
if buffer.capacity() < frame_size {
buffer.resize(frame_size, 0);
}
let width_size = (self.width * multiplier) as usize;
let buffer_address = buffer.as_mut_ptr() as isize;
(0..self.height).into_par_iter().for_each(|y| {
let index = (y * self.row_pitch) as usize;
let ptr = buffer_address as *mut u8;
unsafe {
std::ptr::copy_nonoverlapping(
self.raw_buffer.as_ptr().add(index),
ptr.add(y as usize * width_size),
width_size,
);
}
});
&buffer[0..frame_size]
}
/// Gets the raw pixel data, which may include padding.
#[inline]
#[must_use]
pub const fn as_raw_buffer(&mut self) -> &mut [u8] {
self.raw_buffer
}
/// Saves the frame buffer as an image to the specified path.
#[inline]
pub fn save_as_image<T: AsRef<Path>>(&mut self, path: T, format: ImageFormat) -> Result<(), Error> {
let width = self.width;
let height = self.height;
let pixel_format = match self.format {
DxgiDuplicationFormat::Rgba8 => ImageEncoderPixelFormat::Rgba8,
DxgiDuplicationFormat::Bgra8 => ImageEncoderPixelFormat::Bgra8,
_ => return Err(ImageEncoderError::UnsupportedFormat.into()),
};
let mut buffer = Vec::new();
let bytes =
ImageEncoder::new(format, pixel_format)?.encode(self.as_nopadding_buffer(&mut buffer), width, height)?;
fs::write(path, bytes)?;
Ok(())
}
}