why2-chat 2.0.1

Lightweight, fast and secure chat application powered by WHY2 encryption.
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
/*
This is part of WHY2
Copyright (C) 2022-2026 Václav Šmejkal

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
*/

use std::
{
    env,
    thread,
    time::{ Duration, Instant },
    sync::
    {
        Arc,
        RwLock,
        atomic::{ AtomicBool, Ordering },
        mpsc::Receiver,
    },
};

#[cfg(not(target_os = "macos"))]
use std::sync::mpsc;

use std::sync::mpsc::RecvTimeoutError;

use tokio::sync::mpsc::Sender;

use xcap::{ Frame, Monitor, VideoRecorder };

use openh264::
{
    OpenH264API,
    formats::{ RgbaSliceU8, YUVBuffer },
    encoder::
    {
        Encoder,
        EncoderConfig,
        BitRate,
        FrameRate,
        IntraFramePeriod,
        Complexity,
        UsageType,
        RateControlMode,
    },
};

use crate::network::screen::
{
    consts,
    client::{ gpu::GpuConverter, options },
};

fn monitor_name(monitor: &Monitor) -> String
{
    monitor.name().unwrap_or_else(|_| "unknown".to_owned())
}

fn monitor_list(monitors: &[Monitor]) -> String //THE MONITORS AS THE USER MAY NAME THEM, FOR THE ERROR THAT LISTS THEM
{
    monitors.iter().enumerate()
        .map(|(index, monitor)| format!("{} ({})", index + 1, monitor_name(monitor)))
        .collect::<Vec<String>>()
        .join(", ")
}

//THE MONITOR THE USER ASKED FOR, BY 1-BASED INDEX OR BY NAME. AN UNKNOWN ONE IS AN ERROR RATHER THAN
//A SILENT FALL BACK TO THE PRIMARY: SHARING A SCREEN THE USER DID NOT PICK IS THE WORSE OUTCOME.
fn select_monitor(monitors: Vec<Monitor>, selection: &str) -> Result<Monitor, String>
{
    if let Ok(index) = selection.parse::<usize>()
        && let Some(monitor) = index.checked_sub(1).and_then(|index| monitors.get(index))
    {
        return Ok(monitor.clone());
    }

    monitors.iter()
        .find(|monitor| monitor_name(monitor).eq_ignore_ascii_case(selection))
        .cloned()
        .ok_or_else(|| format!("no monitor called '{selection}' - available: {}", monitor_list(&monitors)))
}

fn get_target_monitor() -> Result<Monitor, String> //THE MONITOR TO SHARE: THE PICKED ONE, OTHERWISE THE PRIMARY
{
    let monitors = Monitor::all().map_err(|e| format!("failed to enumerate monitors ({e})"))?;

    if monitors.is_empty() { return Err("no monitors found".to_owned()); }

    match options::get_monitor()
    {
        Some(selection) => select_monitor(monitors, &selection),

        None => Ok(monitors.iter()
            .find(|m| m.is_primary().unwrap_or(false))
            .cloned()
            .unwrap_or_else(|| monitors.into_iter().next().unwrap())),
    }
}

//THE NAME OF THE MONITOR `selection` ASKS FOR. THE COMMAND RESOLVES BEFORE IT STORES ANYTHING, SO A
//MONITOR THAT DOES NOT EXIST IS REFUSED WHILE THE USER IS STILL LOOKING AT WHAT THEY TYPED - AND SO
//WHAT IS STORED IS THE MONITOR ITSELF RATHER THAN ONE OF THE WAYS OF SPELLING IT
pub fn resolve_monitor(selection: &str) -> Result<String, String>
{
    let monitors = Monitor::all().map_err(|e| format!("failed to enumerate monitors ({e})"))?;

    select_monitor(monitors, selection).map(|monitor| monitor_name(&monitor))
}

pub fn current_monitor() -> Option<String> //WHAT A SHARE WOULD CAPTURE RIGHT NOW, BY NAME
{
    get_target_monitor().ok().map(|monitor| monitor_name(&monitor))
}

//THE NAMES THE PALETTE OFFERS. IT ASKS ON EVERY KEYSTROKE OF THE PARAMETER, AND ENUMERATING MONITORS
//IS A ROUND TRIP TO THE DISPLAY SERVER, SO THE ANSWER IS HELD FOR A MOMENT - LONG ENOUGH TO COVER
//TYPING, SHORT ENOUGH THAT A MONITOR PLUGGED IN MID-SESSION SHOWS UP WITHOUT A RESTART
pub fn monitor_names() -> Vec<String>
{
    static CACHE: RwLock<Option<(Instant, Vec<String>)>> = RwLock::new(None);

    if let Some((taken, names)) = CACHE.read().unwrap().as_ref()
        && taken.elapsed() < consts::MONITOR_LIST_TTL
    {
        return names.clone();
    }

    let names = Monitor::all().map(|monitors| monitors.iter().map(monitor_name).collect::<Vec<String>>())
        .unwrap_or_default();

    *CACHE.write().unwrap() = Some((Instant::now(), names.clone()));

    names
}

//SET BY THE BACKGROUND PROBE THE MOMENT THE OS-NATIVE RECORDER HAS PROVEN ITSELF, AND OBSERVED BY
//THE POLLING LOOPS SO THEY STAND DOWN. IT IS DELIBERATELY *NOT* `running`: standing the legacy path
//down is not ending the share, and clearing `running` would end it.
static UPGRADING: AtomicBool = AtomicBool::new(false);

fn upgrading() -> bool
{
    UPGRADING.load(Ordering::Relaxed)
}

#[cfg(target_os = "linux")]
fn wayland() -> bool
{
    env::var("WAYLAND_DISPLAY").is_ok() || env::var("XDG_SESSION_TYPE").unwrap_or_default() == "wayland"
}

fn legacy_capture_loop //THE PRE-RECORDER POLLING PATH, KEPT AS THE LAST FALLBACK
(
    frame_tx: Sender<Vec<u8>>,
    running: Arc<AtomicBool>,
    fps: u32,
) -> Result<(), String>
{
    #[cfg(target_os = "linux")]
    if wayland()
    {
        return capture_loop_wayshot(frame_tx, running, fps);
    }

    capture_loop_xcap(get_target_monitor()?, frame_tx, running, fps)
}

pub fn capture_loop //CAPTURE LOOP
(
    frame_tx: Sender<Vec<u8>>,
    running: Arc<AtomicBool>,
    fps: u32,
) -> Result<(), String>
{
    loop
    {
        let generation = options::monitor_generation();

        let outcome = capture_backend(frame_tx.clone(), running.clone(), fps);

        //THE BACKEND STOOD DOWN BECAUSE THE MONITOR CHANGED UNDER IT, NOT BECAUSE THE SHARE ENDED:
        //START OVER ON THE NEW ONE. THE VIEWER PAYS ONE KEYFRAME FOR IT (THE ENCODER IS NEW) AND
        //NOTHING ELSE - THE SOCKET, THE TOKEN AND THE SERVER'S IDEA OF WHO IS SHARING ALL SURVIVE
        if !switched(generation) || !running.load(Ordering::Relaxed) || !options::get_use_screen()
        {
            return outcome;
        }
    }
}

fn switched(generation: usize) -> bool //THE MONITOR WAS PICKED AGAIN WHILE WE WERE CAPTURING
{
    options::monitor_generation() != generation
}

fn capture_backend //PICK A BACKEND AND CAPTURE ON IT UNTIL IT STOPS
(
    frame_tx: Sender<Vec<u8>>,
    running: Arc<AtomicBool>,
    fps: u32,
) -> Result<(), String>
{
    //AN EXPLICIT OVERRIDE SKIPS THE PROBE ENTIRELY - THIS IS WHAT PINS A BACKEND ON HARDWARE
    //WHERE THE PREFERRED ONE MISBEHAVES
    match env::var(consts::BACKEND_OVERRIDE_VAR).unwrap_or_default().to_lowercase().as_str()
    {
        "recorder" => return capture_loop_recorder(frame_tx, running, fps),
        "legacy" | "xcap" | "wayshot" => return legacy_capture_loop(frame_tx, running, fps),
        _ => {},
    }

    //A PICKED MONITOR IS THE ONE THING THE PORTAL RECORDER CANNOT BE TOLD: ON WAYLAND IT IS THE USER'S
    //OWN PICKER THAT CHOOSES THE OUTPUT, SO UPGRADING TO IT WOULD QUIETLY THROW THE SELECTION AWAY -
    //AND ASK AGAIN ON TOP OF IT. THE POLLING PATH HONOURS THE CHOICE, SO IT KEEPS THE SHARE.
    #[cfg(target_os = "linux")]
    if wayland() && options::get_monitor().is_some()
    {
        return legacy_capture_loop(frame_tx, running, fps);
    }

    //SOME OBJECTIVE-C BULLSHIT ON MAC
    #[cfg(target_os = "macos")]
    return match open_recorder()
    {
        Ok(session) => run_recorder(session, frame_tx, running, fps),
        Err(_) => legacy_capture_loop(frame_tx, running, fps),
    };

    #[cfg(not(target_os = "macos"))]
    {
        UPGRADING.store(false, Ordering::Relaxed);

        let (probe_tx, probe_rx) = mpsc::channel();

        thread::spawn(move ||
        {
            let session = open_recorder();

            //THE FLAG GOES UP BEFORE THE SEND: IT IS WHAT MAKES THE POLLING LOOP STAND DOWN, AND ONLY
            //ONCE IT HAS STOOD DOWN IS ANYBODY WAITING ON THE CHANNEL
            if session.is_ok() { UPGRADING.store(true, Ordering::Relaxed); }

            probe_tx.send(session).ok();
        });

        let outcome = legacy_capture_loop(frame_tx.clone(), running.clone(), fps);

        //ENDED ON ITS OWN TERMS - STOPPED, OR THE SCREEN OPTION WENT OFF
        if !upgrading() && (outcome.is_ok() || !running.load(Ordering::Relaxed)) { return outcome; }

        let probed = if upgrading()
        {
            probe_rx.recv().ok()
        } else
        {
            //THE POLLING PATH COULD NOT RUN AT ALL
            probe_rx.recv_timeout(probe_timeout()).ok()
        };

        UPGRADING.store(false, Ordering::Relaxed);

        match probed
        {
            //A PROVEN RECORDER IS WORTH TAKING EVEN IF THE POLLING PATH ERRORED ON ITS WAY OUT
            Some(Ok(session)) if running.load(Ordering::Relaxed) => run_recorder(session, frame_tx, running, fps),
            _ => outcome,
        }
    }
}

fn create_encoder(fps: f32) -> Result<Encoder, String>
{
    let config = EncoderConfig::new()
        .max_frame_rate(FrameRate::from_hz(fps))
        .rate_control_mode(RateControlMode::Bitrate)
        .bitrate(BitRate::from_bps(consts::H264_BITRATE))
        .intra_frame_period(IntraFramePeriod::from_num_frames((fps * 2.0) as u32))
        .complexity(Complexity::Low)
        .usage_type(UsageType::ScreenContentRealTime)
        .skip_frames(true)
        .adaptive_quantization(false)
        .background_detection(false);

    Encoder::with_api_config(OpenH264API::from_source(), config)
        .map_err(|e| format!("failed to create H.264 encoder ({e})"))
}

struct YuvScratch //REUSABLE I420 SCRATCH BUFFER
{
    buffer: YUVBuffer,
    width: u32,
    height: u32,
}

impl YuvScratch
{
    fn new() -> Self
    {
        Self { buffer: YUVBuffer::new(0, 0), width: 0, height: 0 }
    }

    fn fill(&mut self, width: u32, height: u32, rgba: &[u8]) -> &YUVBuffer
    {
        //RESIZE ONLY WHEN THE MONITOR RESOLUTION ACTUALLY CHANGED
        if self.width != width || self.height != height
        {
            self.buffer = YUVBuffer::new(width as usize, height as usize);
            self.width = width;
            self.height = height;
        }

        self.buffer.read_rgb(RgbaSliceU8::new(rgba, (width as usize, height as usize)));

        &self.buffer
    }
}

enum Converter //RGBA -> I420, ON THE GPU WHERE THAT IS POSSIBLE
{
    Gpu(Box<GpuConverter>),
    Cpu(YuvScratch),
}

impl Converter
{
    fn select() -> Self
    {
        //AN EXPLICIT "cpu" PINS THE OLD PATH; ANYTHING ELSE MERELY *PREFERS* THE GPU, WHICH STILL
        //HAS TO INITIALISE SUCCESSFULLY BEFORE IT IS USED
        if env::var(consts::CONVERTER_OVERRIDE_VAR).unwrap_or_default().eq_ignore_ascii_case("cpu")
        {
            return Converter::Cpu(YuvScratch::new());
        }

        match GpuConverter::new()
        {
            Ok(converter) => Converter::Gpu(Box::new(converter)),

            //NO ADAPTER, NO DRIVER, A HEADLESS BOX - THE CPU PATH IS ALWAYS THERE
            Err(_) => Converter::Cpu(YuvScratch::new()),
        }
    }
}

struct FrameEncoder
{
    encoder: Encoder,
    converter: Converter,
    fps: f32,
    dimensions: Option<(u32, u32)>,
}

impl FrameEncoder
{
    fn new(fps: f32) -> Result<Self, String>
    {
        Ok(Self { encoder: create_encoder(fps)?, converter: Converter::select(), fps, dimensions: None })
    }

    fn force_intra_frame(&mut self)
    {
        self.encoder.force_intra_frame();
    }

    fn encode(&mut self, width: u32, height: u32, rgba: &[u8]) -> Result<Option<Vec<u8>>, String>
    {
        //I420 CONVERSION PANICS ON ODD DIMENSIONS - FAIL CLEANLY INSTEAD
        if width % 2 != 0 || height % 2 != 0
        {
            return Err(format!("unsupported capture resolution {width}x{height} (must be even)"));
        }

        //openh264 FIXES ITS RESOLUTION ON THE FIRST FRAME, SO A MONITOR RECONFIGURED MID-SHARE
        //NEEDS A FRESH ENCODER RATHER THAN A CORRUPT STREAM
        if self.dimensions.is_some_and(|previous| previous != (width, height))
        {
            self.encoder = create_encoder(self.fps)?;
        }

        self.dimensions = Some((width, height));

        //A GPU THAT FAILS MID-SESSION (DEVICE LOST, A RESOLUTION THE PACKING CANNOT EXPRESS) DROPS
        //BACK TO THE CPU FOR GOOD RATHER THAN RETRYING EVERY FRAME
        if let Converter::Gpu(_) = &self.converter
            && !GpuConverter::supports(width, height)
        {
            self.converter = Converter::Cpu(YuvScratch::new());
        }

        let mut fallback = None;

        let bitstream = match &mut self.converter
        {
            Converter::Gpu(converter) => match converter.convert(width, height, rgba)
            {
                Ok(frame) =>
                {
                    let bitstream = self.encoder.encode(frame)
                        .map_err(|e| format!("H.264 encode failed ({e})"))?;

                    Some(bitstream.to_vec())
                },

                Err(reason) =>
                {
                    fallback = Some(reason);
                    None
                },
            },

            Converter::Cpu(scratch) =>
            {
                let yuv = scratch.fill(width, height, rgba);

                let bitstream = self.encoder.encode(yuv)
                    .map_err(|e| format!("H.264 encode failed ({e})"))?;

                Some(bitstream.to_vec())
            },
        };

        //THE GPU REFUSED THIS FRAME - SWITCH PERMANENTLY AND REDO IT ON THE CPU, SO THE VIEWER
        //NEVER SEES A GAP IN THE PREDICTED STREAM
        let data = match bitstream
        {
            Some(result) => result,

            None =>
            {
                debug_assert!(fallback.is_some(), "the GPU path only yields None after refusing a frame");

                self.converter = Converter::Cpu(YuvScratch::new());

                let Converter::Cpu(scratch) = &mut self.converter else { unreachable!() };

                let yuv = scratch.fill(width, height, rgba);

                let bitstream = self.encoder.encode(yuv)
                    .map_err(|e| format!("H.264 encode failed ({e})"))?;

                bitstream.to_vec()
            },
        };

        //SKIP EMPTY FRAMES (ENCODER MAY DECIDE NO DATA IS NEEDED)
        if data.is_empty()
        {
            return Ok(None);
        }

        Ok(Some(data))
    }

    fn dispatch(&mut self, frame_tx: &Sender<Vec<u8>>, frame: Vec<u8>) //HAND A FRAME TO THE NETWORK TASK
    {
        //A FULL CHANNEL MEANS THE NETWORK FELL BEHIND AND THIS FRAME IS GONE, SO THE NEXT ONE
        //CANNOT BE A PREDICTED ONE
        if frame_tx.try_send(frame).is_err()
        {
            self.force_intra_frame();
        }
    }
}

fn sleep_until_next_tick(next_tick: &mut Instant, target_interval: Duration)
{
    let now = Instant::now();
    if *next_tick > now
    {
        thread::sleep(*next_tick - now);
    } else
    {
        *next_tick = now;
    }

    *next_tick += target_interval;
}

fn capture_loop_xcap
(
    monitor: Monitor,
    frame_tx: Sender<Vec<u8>>,
    running: Arc<AtomicBool>,
    fps: u32,
) -> Result<(), String>
{
    let target_interval = Duration::from_secs_f64(1.0 / fps as f64);
    let mut next_tick = Instant::now() + target_interval;

    let generation = options::monitor_generation();

    let mut encoder = FrameEncoder::new(fps as f32)?;

    //PREVIOUS FRAME, KEPT BY MOVE - COPYING ITS BYTES OUT WOULD COST A FULL-FRAME memcpy EVERY TICK
    let mut last_image: Option<xcap::image::RgbaImage> = None;
    let mut last_encode_time = Instant::now();

    while running.load(Ordering::Relaxed) && !upgrading() && !switched(generation)
    {
        //EXIT ON DISABLED SCREEN
        if !options::get_use_screen()
        {
            running.store(false, Ordering::Relaxed);
            return Ok(());
        }

        if let Ok(image) = monitor.capture_image()
        {
            let force_encode = last_encode_time.elapsed() >= consts::FORCED_INTRA_INTERVAL;

            //memcmp EARLY-EXITS ON THE FIRST DIFFERING BYTE, SO THIS IS CHEAP WHEN THE SCREEN MOVED
            let changed = last_image.as_ref().is_none_or(|previous| previous.as_raw() != image.as_raw());

            if force_encode || changed
            {
                if let Some(compressed) = encoder.encode(image.width(), image.height(), image.as_raw())?
                {
                    encoder.dispatch(&frame_tx, compressed);
                }

                last_image = Some(image);
                last_encode_time = Instant::now();
            }
        }

        sleep_until_next_tick(&mut next_tick, target_interval);
    }

    Ok(())
}

#[cfg(target_os = "linux")]
fn select_output(wayshot: &libwayshot::WayshotConnection) -> Result<libwayshot::output::OutputInfo, String> //PICK THE OUTPUT TO SHARE
{
    let outputs = wayshot.get_all_outputs();

    if outputs.is_empty() { return Err("compositor reported no outputs".to_owned()); }

    //A PICKED MONITOR IS RESOLVED HERE TOO, AND IS THE ONE CASE THAT MAY FAIL: THE COMPOSITOR AND xcap
    //NUMBER THEIR OUTPUTS INDEPENDENTLY, SO THE SELECTION IS TURNED INTO A NAME FIRST AND THE NAME IS
    //WHAT THE OUTPUT IS FOUND BY. FALLING BACK TO ANOTHER SCREEN HERE WOULD SHARE ONE NOBODY ASKED FOR.
    let picked = options::get_monitor().is_some();

    match get_target_monitor().and_then(|m| m.name().map_err(|e| e.to_string()))
    {
        Ok(name) => match outputs.iter().find(|o| o.name == name)
        {
            Some(output) => return Ok(output.clone()),
            None if picked => return Err(format!("the compositor knows no output called '{name}'")),
            None => {},
        },

        Err(reason) if picked => return Err(reason),
        Err(_) => {},
    }

    //FALLBACK: THE OUTPUT AT THE ORIGIN OF THE LAYOUT, OTHERWISE THE FIRST ONE
    Ok(outputs.iter()
        .find(|o| o.logical_region.inner.position.x == 0 && o.logical_region.inner.position.y == 0)
        .unwrap_or(&outputs[0])
        .clone())
}

//A FRESH CONNECTION ONTO THE SAME OUTPUT. USED BOTH WHEN CAPTURE BREAKS AND, ROUTINELY, TO HAND THE
//COMPOSITOR BACK THE MEMORY EVERY CAPTURE STRANDS (SEE THE LEAK NOTE IN capture_loop_wayshot).
#[cfg(target_os = "linux")]
fn reconnect_wayshot(name: &str) -> Option<(libwayshot::WayshotConnection, libwayshot::output::OutputInfo)>
{
    let connection = libwayshot::WayshotConnection::new().ok()?;
    let output = connection.get_all_outputs().iter().find(|output| output.name == name).cloned()?;

    Some((connection, output))
}

#[cfg(target_os = "linux")]
fn capture_loop_wayshot
(
    frame_tx: Sender<Vec<u8>>,
    running: Arc<AtomicBool>,
    fps: u32,
) -> Result<(), String>
{
    let target_interval = Duration::from_secs_f64(1.0 / fps as f64);

    let generation = options::monitor_generation();

    let mut wayshot = libwayshot::WayshotConnection::new()
        .map_err(|e| format!("wayland screen capture is unavailable ({e})"))?;

    let mut target_output = select_output(&wayshot)?;

    let mut encoder = FrameEncoder::new(fps as f32)?;

    //PROBE ONCE UP FRONT SO AN UNSUPPORTED COMPOSITOR REPORTS A USEFUL ERROR RATHER THAN A BLANK SHARE
    let first_image = wayshot.screenshot_single_output(&target_output, true)
        .map_err(|e| format!("capturing {} failed ({e}) - your compositor must support \
            ext-image-copy-capture-v1 or wlr-screencopy-v1", target_output.name))?
        .into_rgba8();

    //ENCODE AND SEND FIRST FRAME
    if let Some(compressed) = encoder.encode(first_image.width(), first_image.height(), first_image.as_raw())?
    {
        encoder.dispatch(&frame_tx, compressed);
    }

    //PREVIOUS FRAME, KEPT BY MOVE (SEE capture_loop_xcap) - THIS PATH USED TO ENCODE EVERY TICK UNCONDITIONALLY
    let mut last_image = Some(first_image);

    let mut last_encode_time = Instant::now();

    let mut failures = 0u32;
    let mut next_tick = Instant::now() + target_interval;

    //libwayshot BINDS A FRESH wl_shm PER CAPTURE AND NEVER RELEASES IT, SO THE COMPOSITOR HOLDS ON TO ONE
    //FULL-SCREEN BUFFER FOR EVERY FRAME WE TAKE - MEASURED AT ~5.5 MB A FRAME, WHICH IS ~10 GB A MINUTE AT
    //30 FPS AND TAKES THE WHOLE MACHINE DOWN WITH IT. IT IS ALL HANDED BACK WHEN THE CLIENT DISCONNECTS,
    //AND RECONNECTING COSTS 0.4 ms, SO THE SHARE SIMPLY RECYCLES ITS CONNECTION BEFORE THE BILL GETS BIG.
    let mut stranded = 0u64;

    while running.load(Ordering::Relaxed) && !upgrading() && !switched(generation)
    {
        //EXIT ON DISABLED SCREEN
        if !options::get_use_screen()
        {
            running.store(false, Ordering::Relaxed);
            return Ok(());
        }

        match wayshot.screenshot_single_output(&target_output, true)
        {
            Ok(image) =>
            {
                failures = 0;

                let image = image.into_rgba8();

                stranded += image.as_raw().len() as u64;

                let force_encode = last_encode_time.elapsed() >= consts::FORCED_INTRA_INTERVAL;

                let changed = last_image.as_ref().is_none_or(|previous| previous.as_raw() != image.as_raw());

                if force_encode || changed
                {
                    if let Some(compressed) = encoder.encode(image.width(), image.height(), image.as_raw())?
                    {
                        encoder.dispatch(&frame_tx, compressed);
                    }

                    last_image = Some(image);
                    last_encode_time = Instant::now();
                }

                //NOTHING WAS MISSED AND THE PICTURE HAS NOT MOVED, SO THIS COSTS NEITHER A KEYFRAME NOR THE
                //CHANGE DETECTION - ONLY THE RECONNECT ITSELF
                if stranded >= consts::WAYLAND_LEAK_BUDGET
                {
                    if let Some((connection, output)) = reconnect_wayshot(&target_output.name)
                    {
                        wayshot = connection;
                        target_output = output;
                    }

                    stranded = 0;
                }
            },

            //RECONNECT ONLY WHEN CAPTURE ACTUALLY BREAKS (E.G. THE OUTPUT WAS HOTPLUGGED)
            Err(_) =>
            {
                failures += 1;

                if failures >= consts::WAYLAND_RECONNECT_FAILURES
                {
                    if let Some((connection, output)) = reconnect_wayshot(&target_output.name)
                    {
                        wayshot = connection;
                        target_output = output;

                        //FORCE A KEYFRAME - THE VIEWER HAS MISSED FRAMES WHILE WE WERE DOWN
                        encoder.force_intra_frame();
                        last_image = None;
                    }

                    stranded = 0;
                    failures = 0;
                }
            },
        }

        sleep_until_next_tick(&mut next_tick, target_interval);
    }

    Ok(())
}

//STRUCTS
struct RecorderSession //A STARTED OS-NATIVE RECORDER, ITS FRAME CHANNEL, AND ITS PROVEN FIRST FRAME
{
    recorder: VideoRecorder,
    frames: Receiver<Frame>,
    first: Frame,
}

fn open_recorder() -> Result<RecorderSession, String> //THE BLOCKING HALF OF THE PROBE
{
    let monitor = get_target_monitor()?;

    let (recorder, frames) = monitor.video_recorder()
        .map_err(|e| format!("the OS screen recorder is unavailable ({e})"))?;

    recorder.start()
        .map_err(|e| format!("starting the OS screen recorder failed ({e})"))?;

    //A RECORDER THAT STARTS IS NOT A RECORDER THAT WORKS. xcap's X11 RECORDER, FOR ONE, REPORTS
    //SUCCESS AND THEN NEVER DELIVERS A SINGLE FRAME - ACCEPTING IT ON THE STRENGTH OF `start()`
    //WOULD HAND THE VIEWER A PERMANENTLY BLANK SHARE THAT NO FALLBACK COULD EVER RESCUE, BECAUSE
    //NOTHING WOULD HAVE FAILED. SO THE PROBE IS ONLY SATISFIED BY AN ACTUAL FRAME.
    let first = frames.recv_timeout(consts::RECORDER_FIRST_FRAME)
        .map_err(|_| "the OS screen recorder started but delivered no frames".to_owned())?;

    Ok(RecorderSession { recorder, frames, first })
}

#[cfg(not(target_os = "macos"))]
fn probe_timeout() -> Duration
{
    env::var(consts::PROBE_TIMEOUT_VAR).ok()
        .and_then(|value| value.parse().ok())
        .map(Duration::from_secs)
        .unwrap_or(consts::RECORDER_PROBE_TIMEOUT)
}

//SEE `capture_loop`: A macOS SESSION CANNOT CROSS A THREAD, AND HAS NO PORTAL TO WAIT ON EITHER,
//SO THE BOUND IT WOULD BUY IS THE ONE `open_recorder` ALREADY IMPOSES ON THE FIRST FRAME
#[cfg(target_os = "macos")]
fn start_recorder() -> Result<RecorderSession, String>
{
    open_recorder()
}

#[cfg(not(target_os = "macos"))]
fn start_recorder() -> Result<RecorderSession, String> //PROBE THE OS-NATIVE RECORDER, BOUNDED
{
    //THE PROBE RUNS ON A THREAD OF ITS OWN BECAUSE IT CAN BLOCK FOR AN UNBOUNDED TIME: ON WAYLAND
    //IT IS AN xdg-desktop-portal SCREENCAST REQUEST, WHICH SITS THERE UNTIL SOMEBODY ANSWERS THE
    //PICKER - AND NEVER RETURNS AT ALL IF NO PORTAL IMPLEMENTATION IS LISTENING. RUNNING IT INLINE
    //WOULD WEDGE THE WHOLE CAPTURE THREAD WITH NO WAY BACK TO THE FALLBACK PATH.
    let (probe_tx, probe_rx) = mpsc::channel();

    thread::spawn(move ||
    {
        //A LATE ANSWER FINDS THE RECEIVER GONE; THE SESSION IS THEN DROPPED HERE, WHICH STOPS THE
        //RECORDER AND RELEASES THE PORTAL SESSION RATHER THAN LEAKING IT
        probe_tx.send(open_recorder()).ok();
    });

    match probe_rx.recv_timeout(probe_timeout())
    {
        Ok(result) => result,
        Err(RecvTimeoutError::Timeout) => Err("the OS screen recorder did not answer in time".to_owned()),
        Err(RecvTimeoutError::Disconnected) => Err("the OS screen recorder probe died".to_owned()),
    }
}

fn run_recorder //EVENT-DRIVEN CAPTURE LOOP
(
    session: RecorderSession,
    frame_tx: Sender<Vec<u8>>,
    running: Arc<AtomicBool>,
    fps: u32,
) -> Result<(), String>
{
    let RecorderSession { recorder, frames, first } = session;

    let mut encoder = FrameEncoder::new(fps as f32)?;

    let min_interval = Duration::from_secs_f64(1.0 / fps as f64);

    let mut last_encode_time = Instant::now();

    //SET BACK BY ONE INTERVAL SO THE VERY FIRST FRAME IS NOT HELD FOR THE FPS BUDGET
    let mut last_dispatch = Instant::now() - min_interval;

    //THE PREVIOUS FRAME'S BYTES. UNLIKE THE POLLING PATHS THIS BACKEND ONLY SPEAKS WHEN THE SCREEN
    //CHANGED ON MOST PLATFORMS, SO THE COMPARISON USUALLY EARLY-EXITS ON THE FIRST BYTE
    let mut last_raw: Option<Vec<u8>> = None;

    //THE FRAME THE PROBE ALREADY PAID FOR GOES OUT RATHER THAN BEING THROWN AWAY
    let mut pending = Some(first);

    let generation = options::monitor_generation();

    let outcome = loop
    {
        if !running.load(Ordering::Relaxed) { break Ok(()); }

        //THE MONITOR WAS PICKED AGAIN - HAND THE RECORDER BACK SO capture_loop CAN OPEN THE NEW ONE
        if switched(generation) { break Ok(()); }

        //EXIT ON DISABLED SCREEN
        if !options::get_use_screen()
        {
            running.store(false, Ordering::Relaxed);
            break Ok(());
        }

        //THE TIMEOUT IS ONLY THERE SO `running` IS STILL OBSERVED ON A PERFECTLY IDLE SCREEN -
        //AN IDLE DESKTOP COSTS US NOTHING BUT THIS WAKEUP, WHERE THE POLLING PATHS GRABBED A FULL FRAME
        let mut frame = match pending.take()
        {
            Some(frame) => frame,

            None => match frames.recv_timeout(consts::RECORDER_POLL_INTERVAL)
            {
                Ok(frame) => frame,
                Err(RecvTimeoutError::Timeout) => continue,
                Err(RecvTimeoutError::Disconnected) => break Err("the OS screen recorder stopped delivering frames".to_owned()),
            },
        };

        //A COMPOSITOR MAY DELIVER FASTER THAN WE ENCODE; KEEP THE NEWEST FRAME AND DROP THE REST
        while let Ok(newer) = frames.try_recv()
        {
            frame = newer;
        }

        let force_encode = last_encode_time.elapsed() >= consts::FORCED_INTRA_INTERVAL;

        //FPS BUDGET
        if !force_encode && last_dispatch.elapsed() < min_interval
        {
            continue;
        }

        let changed = last_raw.as_ref().is_none_or(|previous| previous != &frame.raw);

        if !(force_encode || changed)
        {
            continue;
        }

        if let Some(compressed) = encoder.encode(frame.width, frame.height, &frame.raw)?
        {
            encoder.dispatch(&frame_tx, compressed);
        }

        last_dispatch = Instant::now();
        last_encode_time = last_dispatch;
        last_raw = Some(frame.raw);
    };

    recorder.stop().ok();

    outcome
}

fn capture_loop_recorder //OS-NATIVE STREAMING CAPTURE, WITHOUT THE FALLBACK CHAIN
(
    frame_tx: Sender<Vec<u8>>,
    running: Arc<AtomicBool>,
    fps: u32,
) -> Result<(), String>
{
    run_recorder(start_recorder()?, frame_tx, running, fps)
}