hdrshot-gui 2.4.0

HDR image tool: desktop app for converting HDR screenshots and images
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
//! HDR screenshots on Windows. A shortcut that works in games, or the
//! tray menu or the window's camera button, saves what a screen shows as
//! a JPEG XR file, like Game Bar does, which the app then converts with the
//! current settings.
//!
//! The picture comes from DXGI desktop duplication in 16-bit float
//! (scRGB), the format Windows composes an HDR desktop in, so nothing is
//! lost: it is the same data as in a Game Bar screenshot. The mouse pointer
//! isn't part of it.

use std::path::PathBuf;
#[cfg(windows)]
use std::sync::{Arc, Mutex};
use std::time::Duration;

use serde::{Deserialize, Serialize};

/// Whether this platform can take HDR screenshots.
pub(crate) const SUPPORTED: bool = cfg!(windows);

/// The keyboard shortcut that takes a screenshot, from any app.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) enum Shortcut {
    Off,
    CtrlShiftPrintScreen,
    CtrlPrintScreen,
    ShiftPrintScreen,
    CtrlAltPrintScreen,
}

impl Shortcut {
    /// The choices, in the order the Settings page offers them.
    pub(crate) const ALL: [Self; 5] = [
        Self::CtrlShiftPrintScreen,
        Self::CtrlPrintScreen,
        Self::ShiftPrintScreen,
        Self::CtrlAltPrintScreen,
        Self::Off,
    ];

    pub(crate) fn label(self) -> &'static str {
        match self {
            Self::Off => "Off",
            Self::CtrlShiftPrintScreen => "Ctrl+Shift+PrtScn",
            Self::CtrlPrintScreen => "Ctrl+PrtScn",
            Self::ShiftPrintScreen => "Shift+PrtScn",
            Self::CtrlAltPrintScreen => "Ctrl+Alt+PrtScn",
        }
    }
}

/// Which screen to capture.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Target {
    /// The one showing the window in front, e.g. the game.
    Foreground,
    /// The one with the mouse pointer, as after choosing the tray menu.
    Pointer,
}

/// The screenshot saved, or why not.
pub(crate) type Taken = Result<PathBuf, String>;

/// Where screenshots go unless the user picked a folder: `hdrshot` in the
/// Pictures folder.
pub(crate) fn default_folder() -> Option<PathBuf> {
    #[cfg(windows)]
    return imp::pictures().map(|p| p.join("hdrshot"));
    #[cfg(not(windows))]
    None
}

/// The shortcut, registered with the system while this exists. Each press
/// saves a screenshot into the folder it shares with the app and sends
/// the outcome.
pub(crate) struct Hotkey {
    #[cfg(windows)]
    thread: imp::HotkeyThread,
}

impl Hotkey {
    /// Registers `shortcut`; fails when another app has it already.
    #[cfg(windows)]
    pub(crate) fn register(
        shortcut: Shortcut,
        folder: Arc<Mutex<PathBuf>>,
        taken: std::sync::mpsc::Sender<Taken>,
        ctx: egui::Context,
    ) -> Result<Self, String> {
        imp::HotkeyThread::start(shortcut, folder, taken, ctx).map(|thread| Self { thread })
    }
}

#[cfg(windows)]
impl Drop for Hotkey {
    fn drop(&mut self) {
        self.thread.stop();
    }
}

/// Takes a screenshot of `target` after `delay`, on a thread of its own,
/// and sends the outcome.
#[cfg_attr(not(windows), allow(unused_variables))]
pub(crate) fn take_later(
    delay: Duration,
    target: Target,
    folder: PathBuf,
    taken: std::sync::mpsc::Sender<Taken>,
    ctx: egui::Context,
) {
    std::thread::spawn(move || {
        std::thread::sleep(delay);
        #[cfg(windows)]
        let outcome = imp::take(target, &folder);
        #[cfg(not(windows))]
        let outcome = Err("Screenshots need Windows".to_owned());
        if taken.send(outcome).is_ok() {
            ctx.request_repaint();
        }
    });
}

/// A file name for a screenshot of the window titled `title` (a game's
/// name, usually) taken at `time` (year, month, day, hour, minute,
/// second), like Game Bar's: "Game 2026-11-28 13-45-02".
#[cfg_attr(not(windows), allow(dead_code))]
pub(crate) fn file_stem(title: &str, time: [u16; 6]) -> String {
    let mut name: String = title
        .chars()
        .map(|c| match c {
            '<' | '>' | ':' | '"' | '/' | '\\' | '|' | '?' | '*' => ' ',
            c if c.is_control() => ' ',
            c => c,
        })
        .collect::<String>()
        .split_whitespace()
        .collect::<Vec<_>>()
        .join(" ");
    if name.chars().count() > 60 {
        name = name
            .chars()
            .take(60)
            .collect::<String>()
            .trim_end()
            .to_owned();
    }
    // Windows doesn't allow names ending in a dot.
    let name = name.trim_end_matches('.');
    let name = if name.is_empty() { "Screenshot" } else { name };
    let [y, mo, d, h, mi, s] = time;
    format!("{name} {y:04}-{mo:02}-{d:02} {h:02}-{mi:02}-{s:02}")
}

/// How the desktop image is turned relative to the screen, as DXGI
/// reports for a monitor in portrait or upside down.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(not(windows), allow(dead_code))]
pub(crate) enum Rotation {
    None,
    /// The screen shows the image turned 90 degrees clockwise.
    Cw90,
    Cw180,
    Cw270,
}

/// Turns `pixels`, `width` by `height`, the way the screen shows them.
/// Returns the new width and height.
#[cfg_attr(not(windows), allow(dead_code))]
pub(crate) fn rotate<T: Copy>(
    pixels: &mut Vec<T>,
    width: usize,
    height: usize,
    rotation: Rotation,
) -> (usize, usize) {
    let (w, h) = match rotation {
        Rotation::None => return (width, height),
        Rotation::Cw180 => (width, height),
        Rotation::Cw90 | Rotation::Cw270 => (height, width),
    };
    // Where the pixel shown at `x`, `y` is in `pixels`.
    let source = |x: usize, y: usize| {
        let (sx, sy) = match rotation {
            Rotation::Cw90 => (y, height - 1 - x),
            Rotation::Cw180 => (width - 1 - x, height - 1 - y),
            _ => (width - 1 - y, x),
        };
        sy * width + sx
    };
    let turned = (0..h)
        .flat_map(|y| (0..w).map(move |x| (x, y)))
        .map(|(x, y)| pixels[source(x, y)])
        .collect();
    *pixels = turned;
    (w, h)
}

#[cfg(windows)]
mod imp {
    use std::path::{Path, PathBuf};
    use std::sync::mpsc::{Sender, sync_channel};
    use std::sync::{Arc, Mutex};
    use std::thread::JoinHandle;

    use windows::Win32::Foundation::{
        E_ACCESSDENIED, GENERIC_WRITE, HMODULE, HWND, LPARAM, POINT, WPARAM,
    };
    use windows::Win32::Graphics::Direct3D::D3D_DRIVER_TYPE_UNKNOWN;
    use windows::Win32::Graphics::Direct3D11::{
        D3D11_CPU_ACCESS_READ, D3D11_CREATE_DEVICE_BGRA_SUPPORT, D3D11_MAP_READ,
        D3D11_MAPPED_SUBRESOURCE, D3D11_SDK_VERSION, D3D11_TEXTURE2D_DESC, D3D11_USAGE_STAGING,
        D3D11CreateDevice, ID3D11Device, ID3D11DeviceContext, ID3D11Texture2D,
    };
    use windows::Win32::Graphics::Dxgi::Common::{
        DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_MODE_ROTATION_ROTATE90, DXGI_MODE_ROTATION_ROTATE180,
        DXGI_MODE_ROTATION_ROTATE270,
    };
    use windows::Win32::Graphics::Dxgi::{
        CreateDXGIFactory1, DXGI_ERROR_ACCESS_LOST, DXGI_ERROR_NOT_CURRENTLY_AVAILABLE,
        DXGI_ERROR_SESSION_DISCONNECTED, DXGI_ERROR_UNSUPPORTED, DXGI_ERROR_WAIT_TIMEOUT,
        DXGI_OUTDUPL_FRAME_INFO, IDXGIAdapter1, IDXGIFactory1, IDXGIOutput, IDXGIOutput5,
        IDXGIOutputDuplication, IDXGIResource,
    };
    use windows::Win32::Graphics::Gdi::{
        HMONITOR, MONITOR_DEFAULTTOPRIMARY, MonitorFromPoint, MonitorFromWindow,
    };
    use windows::Win32::Graphics::Imaging::{
        CLSID_WICImagingFactory, GUID_ContainerFormatWmp, GUID_WICPixelFormat64bppRGBAHalf,
        IWICBitmapFrameEncode, IWICImagingFactory, WICBitmapEncoderNoCache,
    };
    use windows::Win32::System::Com::StructuredStorage::{IPropertyBag2, PROPBAG2};
    use windows::Win32::System::Com::{
        CLSCTX_INPROC_SERVER, COINIT_MULTITHREADED, CoCreateInstance, CoInitializeEx, CoTaskMemFree,
    };
    use windows::Win32::System::SystemInformation::GetLocalTime;
    use windows::Win32::System::Threading::GetCurrentThreadId;
    use windows::Win32::System::Variant::VARIANT;
    use windows::Win32::UI::Input::KeyboardAndMouse::{
        HOT_KEY_MODIFIERS, MOD_ALT, MOD_CONTROL, MOD_NOREPEAT, MOD_SHIFT, RegisterHotKey,
        UnregisterHotKey, VK_SNAPSHOT,
    };
    use windows::Win32::UI::Shell::{FOLDERID_Pictures, KF_FLAG_DEFAULT, SHGetKnownFolderPath};
    use windows::Win32::UI::WindowsAndMessaging::{
        GetCursorPos, GetForegroundWindow, GetMessageW, GetWindowTextW, MSG, PM_NOREMOVE,
        PeekMessageW, PostThreadMessageW, WM_HOTKEY, WM_QUIT, WM_USER,
    };
    use windows::core::{GUID, HSTRING, Interface, PCWSTR, w};

    use super::{Rotation, Shortcut, Taken, Target, file_stem, rotate};

    /// The hotkey's id for the thread.
    const HOTKEY_ID: i32 = 1;

    /// A thread that owns the registered hotkey and waits for presses.
    pub struct HotkeyThread {
        id: u32,
        handle: Option<JoinHandle<()>>,
    }

    impl HotkeyThread {
        pub fn start(
            shortcut: Shortcut,
            folder: Arc<Mutex<PathBuf>>,
            taken: Sender<Taken>,
            ctx: egui::Context,
        ) -> Result<Self, String> {
            let modifiers = match shortcut {
                Shortcut::Off => return Err("No shortcut".to_owned()),
                Shortcut::CtrlShiftPrintScreen => MOD_CONTROL | MOD_SHIFT,
                Shortcut::CtrlPrintScreen => MOD_CONTROL,
                Shortcut::ShiftPrintScreen => MOD_SHIFT,
                Shortcut::CtrlAltPrintScreen => MOD_CONTROL | MOD_ALT,
            };
            let (ready, registered) = sync_channel(1);
            let handle = std::thread::spawn(move || {
                // SAFETY: plain Win32 calls on this thread's own queue and
                // hotkey.
                unsafe {
                    // Makes the thread's message queue, so a quit message
                    // can't arrive before there is one.
                    let mut msg = MSG::default();
                    let _ = PeekMessageW(&mut msg, None, WM_USER, WM_USER, PM_NOREMOVE);
                    let modifiers = HOT_KEY_MODIFIERS(modifiers.0 | MOD_NOREPEAT.0);
                    let result =
                        RegisterHotKey(None, HOTKEY_ID, modifiers, u32::from(VK_SNAPSHOT.0));
                    let ok = result.is_ok();
                    let _ = ready.send(result.map(|()| GetCurrentThreadId()));
                    if !ok {
                        return;
                    }
                    while GetMessageW(&mut msg, None, 0, 0).as_bool() {
                        if msg.message == WM_HOTKEY {
                            let dir = folder.lock().map(|d| d.clone()).unwrap_or_default();
                            if taken.send(take(Target::Foreground, &dir)).is_ok() {
                                ctx.request_repaint();
                            }
                        }
                    }
                    let _ = UnregisterHotKey(None, HOTKEY_ID);
                }
            });
            match registered.recv() {
                Ok(Ok(id)) => Ok(Self {
                    id,
                    handle: Some(handle),
                }),
                _ => {
                    let _ = handle.join();
                    Err(format!(
                        "{} is taken by another app. Choose another shortcut.",
                        shortcut.label()
                    ))
                }
            }
        }

        pub fn stop(&mut self) {
            // SAFETY: posts to the thread started above, which then ends.
            unsafe {
                let _ = PostThreadMessageW(self.id, WM_QUIT, WPARAM(0), LPARAM(0));
            }
            if let Some(handle) = self.handle.take() {
                let _ = handle.join();
            }
        }
    }

    /// The user's Pictures folder, wherever it was moved, e.g. to OneDrive.
    pub fn pictures() -> Option<PathBuf> {
        // SAFETY: the returned string is copied, then freed as documented.
        unsafe {
            let path = SHGetKnownFolderPath(&FOLDERID_Pictures, KF_FLAG_DEFAULT, None).ok()?;
            let text = path.to_string().ok();
            CoTaskMemFree(Some(path.0 as *const _));
            text.map(PathBuf::from)
        }
    }

    /// Takes a screenshot of `target` and saves it into `folder` as JPEG XR.
    pub fn take(target: Target, folder: &Path) -> Taken {
        // SAFETY: Win32 calls on handles that are only read.
        let (monitor, title) = unsafe {
            let _ = CoInitializeEx(None, COINIT_MULTITHREADED);
            match target {
                Target::Foreground => {
                    let window = GetForegroundWindow();
                    (
                        MonitorFromWindow(window, MONITOR_DEFAULTTOPRIMARY),
                        window_title(window),
                    )
                }
                Target::Pointer => {
                    let mut point = POINT::default();
                    let _ = GetCursorPos(&mut point);
                    (
                        MonitorFromPoint(point, MONITOR_DEFAULTTOPRIMARY),
                        String::new(),
                    )
                }
            }
        };
        let frame = capture(monitor).map_err(|e| describe(&e))?;
        std::fs::create_dir_all(folder)
            .map_err(|e| format!("Can't make {}: {e}", folder.display()))?;
        // SAFETY: fills a plain struct.
        let now = unsafe { GetLocalTime() };
        let stem = file_stem(
            &title,
            [
                now.wYear,
                now.wMonth,
                now.wDay,
                now.wHour,
                now.wMinute,
                now.wSecond,
            ],
        );
        let mut path = folder.join(format!("{stem}.jxr"));
        let mut n = 2;
        while path.exists() {
            path = folder.join(format!("{stem} ({n}).jxr"));
            n += 1;
        }
        // Written under another name first, so a watch folder or the app
        // never sees half a file.
        let partial = path.with_extension("jxr.partial");
        let written = save_jxr(&frame, &partial);
        if let Err(e) = written {
            let _ = std::fs::remove_file(&partial);
            return Err(format!("Couldn't save the screenshot: {}", e.message()));
        }
        std::fs::rename(&partial, &path).map_err(|e| {
            let _ = std::fs::remove_file(&partial);
            format!("Couldn't save the screenshot: {e}")
        })?;
        Ok(path)
    }

    fn window_title(window: HWND) -> String {
        let mut text = [0u16; 256];
        // SAFETY: the buffer's length is passed with it.
        let len = unsafe { GetWindowTextW(window, &mut text) };
        let title = String::from_utf16_lossy(&text[..len.max(0) as usize]);
        // The desktop itself.
        if title == "Program Manager" {
            String::new()
        } else {
            title
        }
    }

    /// Says what went wrong in words.
    fn describe(e: &windows::core::Error) -> String {
        let code = e.code();
        if code == E_ACCESSDENIED {
            "Windows doesn't allow screenshots right now, e.g. while a UAC prompt or \
             the lock screen shows"
                .to_owned()
        } else if code == DXGI_ERROR_UNSUPPORTED {
            "Windows can't capture this screen with this graphics driver".to_owned()
        } else if code == DXGI_ERROR_NOT_CURRENTLY_AVAILABLE {
            "Too many apps are capturing the screen right now".to_owned()
        } else if code == DXGI_ERROR_SESSION_DISCONNECTED || code == DXGI_ERROR_ACCESS_LOST {
            "The screen changed while taking the screenshot. Try again.".to_owned()
        } else {
            format!("Couldn't capture the screen: {}", e.message())
        }
    }

    /// A screen's picture: half floats, red, green, blue and alpha.
    struct Frame {
        width: usize,
        height: usize,
        pixels: Vec<[u16; 4]>,
    }

    /// One in half float.
    const HALF_ONE: u16 = 0x3c00;

    /// How long to wait for the screen to show a new frame. A game shows
    /// one every few milliseconds; a still desktop may show none.
    const FRAME_WAIT_MS: u32 = 250;

    fn capture(monitor: HMONITOR) -> windows::core::Result<Frame> {
        // SAFETY: COM calls on objects made here; the mapped memory is
        // read within its row pitch and unmapped before it's released.
        unsafe {
            let (adapter, output) = find_output(monitor)?;
            let output: IDXGIOutput5 = output.cast().map_err(|_| {
                windows::core::Error::new(
                    DXGI_ERROR_UNSUPPORTED,
                    "HDR screenshots need Windows 10 version 1703 or later",
                )
            })?;
            let mut device: Option<ID3D11Device> = None;
            let mut context: Option<ID3D11DeviceContext> = None;
            D3D11CreateDevice(
                &adapter,
                D3D_DRIVER_TYPE_UNKNOWN,
                HMODULE::default(),
                D3D11_CREATE_DEVICE_BGRA_SUPPORT,
                None,
                D3D11_SDK_VERSION,
                Some(&mut device),
                None,
                Some(&mut context),
            )?;
            let device = device.expect("D3D11CreateDevice made a device");
            let context = context.expect("D3D11CreateDevice made a context");
            // Float even when HDR is off: Windows converts the desktop.
            let duplication =
                output.DuplicateOutput1(&device, 0, &[DXGI_FORMAT_R16G16B16A16_FLOAT])?;
            let rotation = match duplication.GetDesc().Rotation {
                DXGI_MODE_ROTATION_ROTATE90 => Rotation::Cw90,
                DXGI_MODE_ROTATION_ROTATE180 => Rotation::Cw180,
                DXGI_MODE_ROTATION_ROTATE270 => Rotation::Cw270,
                _ => Rotation::None,
            };
            let staging = newest_frame(&duplication, &device, &context)?;
            let mut desc = D3D11_TEXTURE2D_DESC::default();
            staging.GetDesc(&mut desc);
            if desc.Format != DXGI_FORMAT_R16G16B16A16_FLOAT {
                return Err(windows::core::Error::new(
                    DXGI_ERROR_UNSUPPORTED,
                    "Windows gave the screen in a format other than 16-bit float",
                ));
            }
            let (width, height) = (desc.Width as usize, desc.Height as usize);
            let mut mapped = D3D11_MAPPED_SUBRESOURCE::default();
            context.Map(&staging, 0, D3D11_MAP_READ, 0, Some(&mut mapped))?;
            let mut pixels = Vec::with_capacity(width * height);
            for y in 0..height {
                let row = (mapped.pData as *const u8).add(y * mapped.RowPitch as usize);
                let row = std::slice::from_raw_parts(row as *const [u16; 4], width);
                // The alpha channel means nothing on a screen.
                pixels.extend(row.iter().map(|&[r, g, b, _]| [r, g, b, HALF_ONE]));
            }
            context.Unmap(&staging, 0);
            let (width, height) = rotate(&mut pixels, width, height, rotation);
            Ok(Frame {
                width,
                height,
                pixels,
            })
        }
    }

    /// The graphics adapter and output that show `monitor`.
    unsafe fn find_output(
        monitor: HMONITOR,
    ) -> windows::core::Result<(IDXGIAdapter1, IDXGIOutput)> {
        // SAFETY: plain DXGI enumeration.
        unsafe {
            let factory: IDXGIFactory1 = CreateDXGIFactory1()?;
            let mut first = None;
            let mut a = 0;
            while let Ok(adapter) = factory.EnumAdapters1(a) {
                let mut o = 0;
                while let Ok(output) = adapter.EnumOutputs(o) {
                    if output.GetDesc()?.Monitor == monitor {
                        return Ok((adapter, output));
                    }
                    if first.is_none() {
                        first = Some((adapter.clone(), output));
                    }
                    o += 1;
                }
                a += 1;
            }
            first
                .ok_or_else(|| windows::core::Error::new(DXGI_ERROR_UNSUPPORTED, "No screen found"))
        }
    }

    /// Copies the screen's picture into a texture the CPU can read. The
    /// first frame may be from before the latest one shown, so this waits
    /// briefly for one the screen actually presented.
    unsafe fn newest_frame(
        duplication: &IDXGIOutputDuplication,
        device: &ID3D11Device,
        context: &ID3D11DeviceContext,
    ) -> windows::core::Result<ID3D11Texture2D> {
        // SAFETY: each acquired frame is released before the next.
        unsafe {
            let mut staging: Option<ID3D11Texture2D> = None;
            for _ in 0..4 {
                let mut info = DXGI_OUTDUPL_FRAME_INFO::default();
                let mut resource: Option<IDXGIResource> = None;
                match duplication.AcquireNextFrame(FRAME_WAIT_MS, &mut info, &mut resource) {
                    Ok(()) => {}
                    Err(e) if e.code() == DXGI_ERROR_WAIT_TIMEOUT => {
                        if staging.is_some() {
                            break;
                        }
                        continue;
                    }
                    Err(e) => return Err(e),
                }
                let presented = info.LastPresentTime != 0;
                if let Some(resource) = resource
                    && (presented || staging.is_none())
                {
                    let texture: ID3D11Texture2D = resource.cast()?;
                    if staging.is_none() {
                        let mut desc = D3D11_TEXTURE2D_DESC::default();
                        texture.GetDesc(&mut desc);
                        desc.Usage = D3D11_USAGE_STAGING;
                        desc.BindFlags = 0;
                        desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ.0 as u32;
                        desc.MiscFlags = 0;
                        desc.MipLevels = 1;
                        desc.ArraySize = 1;
                        device.CreateTexture2D(&desc, None, Some(&mut staging))?;
                    }
                    context.CopyResource(staging.as_ref().expect("made above"), &texture);
                }
                duplication.ReleaseFrame()?;
                if presented && staging.is_some() {
                    break;
                }
            }
            staging.ok_or_else(|| {
                windows::core::Error::new(
                    DXGI_ERROR_WAIT_TIMEOUT,
                    "The screen didn't show a picture in time",
                )
            })
        }
    }

    /// Saves `frame` as a lossless JPEG XR file with Windows' own encoder,
    /// the format Game Bar saves HDR screenshots in.
    fn save_jxr(frame: &Frame, path: &Path) -> windows::core::Result<()> {
        // SAFETY: COM calls on objects made here; the pixels outlive them.
        unsafe {
            let factory: IWICImagingFactory =
                CoCreateInstance(&CLSID_WICImagingFactory, None, CLSCTX_INPROC_SERVER)?;
            let stream = factory.CreateStream()?;
            let name = HSTRING::from(path.as_os_str());
            stream.InitializeFromFilename(PCWSTR(name.as_ptr()), GENERIC_WRITE.0)?;
            let encoder = factory.CreateEncoder(&GUID_ContainerFormatWmp, std::ptr::null())?;
            encoder.Initialize(&stream, WICBitmapEncoderNoCache)?;
            let mut encode: Option<IWICBitmapFrameEncode> = None;
            let mut options: Option<IPropertyBag2> = None;
            encoder.CreateNewFrame(&mut encode, &mut options)?;
            let encode = encode.expect("CreateNewFrame made a frame");
            if let Some(options) = &options {
                // 1.0 is lossless.
                let name = PROPBAG2 {
                    pstrName: windows::core::PWSTR(w!("ImageQuality").as_ptr() as *mut u16),
                    ..Default::default()
                };
                options.Write(1, &name, &VARIANT::from(1.0f32))?;
            }
            encode.Initialize(options.as_ref())?;
            encode.SetSize(frame.width as u32, frame.height as u32)?;
            let wanted: GUID = GUID_WICPixelFormat64bppRGBAHalf;
            let mut format = wanted;
            encode.SetPixelFormat(&mut format)?;
            if format != wanted {
                return Err(windows::core::Error::new(
                    DXGI_ERROR_UNSUPPORTED,
                    "Windows' JPEG XR encoder doesn't take 16-bit float pixels",
                ));
            }
            let bytes = std::slice::from_raw_parts(
                frame.pixels.as_ptr() as *const u8,
                frame.pixels.len() * 8,
            );
            let stride = frame.width as u32 * 8;
            // In bands, as WIC limits the size of one call.
            let band = (16 * 1024 * 1024 / stride as usize).max(1);
            for rows in bytes.chunks(band * stride as usize) {
                encode.WritePixels(rows.len() as u32 / stride, stride, rows)?;
            }
            encode.Commit()?;
            encoder.Commit()?;
            Ok(())
        }
    }

    #[cfg(test)]
    mod tests {
        use super::*;

        /// Windows' encoder writes a file that hdrshot reads back as the
        /// same HDR picture.
        #[test]
        fn jxr_round_trip() {
            // SAFETY: initializes COM for this test thread.
            let _ = unsafe { CoInitializeEx(None, COINIT_MULTITHREADED) };
            let half = |v: f32| {
                // Exact for these values: 0.5, 1, 4.
                match v {
                    0.5 => 0x3800,
                    1.0 => 0x3c00,
                    _ => 0x4400,
                }
            };
            let (width, height) = (16, 8);
            let pixels = (0..width * height)
                .map(|i| {
                    let v = [0.5, 1.0, 4.0][i % 3];
                    [half(v), half(1.0), half(0.5), HALF_ONE]
                })
                .collect();
            let frame = Frame {
                width,
                height,
                pixels,
            };
            let path =
                std::env::temp_dir().join(format!("hdrshot-shot-{}.jxr", std::process::id()));
            save_jxr(&frame, &path).unwrap();
            let bytes = std::fs::read(&path).unwrap();
            let image = hdrshot_core::decode::decode(&bytes).unwrap();
            let _ = std::fs::remove_file(&path);
            assert_eq!((image.width, image.height), (16, 8));
            for (i, p) in image.pixels.iter().enumerate() {
                let v = [0.5, 1.0, 4.0][i % 3];
                assert!((p[0] - v).abs() < 1e-3, "{p:?} at {i}");
                assert!((p[1] - 1.0).abs() < 1e-3 && (p[2] - 0.5).abs() < 1e-3);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn names_like_game_bar() {
        let time = [2026, 11, 28, 9, 5, 2];
        assert_eq!(
            file_stem("Some Game", time),
            "Some Game 2026-11-28 09-05-02"
        );
        assert_eq!(
            file_stem("  A: B / C?  ", time),
            "A B C 2026-11-28 09-05-02"
        );
        assert_eq!(file_stem("", time), "Screenshot 2026-11-28 09-05-02");
        assert_eq!(file_stem("...", time), "Screenshot 2026-11-28 09-05-02");
        let long = "x".repeat(100);
        assert_eq!(file_stem(&long, time).len(), 60 + 20);
    }

    #[test]
    fn rotations() {
        // 3 by 2:
        // a b c
        // d e f
        let image = vec!['a', 'b', 'c', 'd', 'e', 'f'];
        let turned = |rotation| {
            let mut pixels = image.clone();
            let size = rotate(&mut pixels, 3, 2, rotation);
            (size, pixels.into_iter().collect::<String>())
        };
        assert_eq!(turned(Rotation::None), ((3, 2), "abcdef".into()));
        // Turned clockwise: d a / e b / f c.
        assert_eq!(turned(Rotation::Cw90), ((2, 3), "daebfc".into()));
        assert_eq!(turned(Rotation::Cw180), ((3, 2), "fedcba".into()));
        // Counterclockwise: c f / b e / a d.
        assert_eq!(turned(Rotation::Cw270), ((2, 3), "cfbead".into()));
    }
}