tuigram-cli 1.10.0

Telegram in your terminal: a fast, vim-style Telegram client built on TDLib
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
//! Voice messages recorded in tuigram: what the microphone hears becomes
//! Opus in an Ogg file, which Telegram takes as a voice note. Recording
//! runs on a thread of its own, into a file only you can read in the
//! outbox, deleted once Telegram has the message it was sent as, or at once
//! if it's dropped unsent. One Telegram refused stays for Enter to send
//! again, until [`clean_stale`] finds it an hour old at a later start.

use std::fs::File;
use std::io::Write as _;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::Relaxed};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

use anyhow::{Context, Result, bail};

use crate::lang;

/// Samples a second: the rate Opus encodes at, which voice.rs plays at.
pub const RATE: u32 = crate::voice::RATE;

/// Samples an Opus frame holds: 20 ms, as Telegram's own voice notes.
const FRAME: usize = RATE as usize / 50;

/// A peak per window of this many samples (10 ms) is kept for the
/// waveform: a hundred buckets a second, little to keep.
const WINDOW: usize = RATE as usize / 100;

/// The levels of the waveform sent; Telegram's own come as 63, a hundred
/// fit the field.
const LEVELS: usize = 100;

/// The loudest level: five bits.
const LOUDEST: u32 = 31;

/// The bitrate asked for: what Telegram's apps send a voice note at.
const BITRATE: i32 = 32_000;

/// How long a leftover recording is kept by [`clean_stale`]: any newer one
/// may be a live tuigram's.
const KEEP: Duration = Duration::from_secs(3600);

/// A voice message being recorded, to send to the chat it was started in.
pub struct Recorder {
    shared: Arc<Shared>,
    thread: Option<std::thread::JoinHandle<Result<Take>>>,
    /// The temporary file being written; [`Recorder::stop`] hands it to
    /// the [`Take`], and dropping before that deletes it.
    path: PathBuf,
}

#[derive(Default)]
struct Shared {
    stop: AtomicBool,
    /// The microphone is open: until then nothing's recorded, and opening
    /// it can take seconds that `V` and Esc don't wait for.
    opened: AtomicBool,
    /// Samples written to the file so far, for the length on screen.
    captured: AtomicU64,
    /// Why the thread ended early, if it did: a device gone, say.
    failed: Mutex<Option<String>>,
}

/// A finished recording, to send: its file (deleted on drop unless taken
/// with [`Take::into_path`]), its length and its waveform.
#[derive(Debug)]
pub struct Take {
    path: PathBuf,
    /// Seconds, as Telegram shows them.
    pub duration: i32,
    /// Base64 of 5-bit levels packed lowest bits first, as TDLib takes it.
    pub waveform: String,
}

impl Take {
    /// The file, to keep: the [`Take`] then leaves it alone. The caller
    /// deletes it once Telegram has the message it was sent as.
    pub fn into_path(mut self) -> PathBuf {
        std::mem::take(&mut self.path)
    }
}

impl Drop for Take {
    fn drop(&mut self) {
        if !self.path.as_os_str().is_empty() {
            let _ = std::fs::remove_file(&self.path);
        }
    }
}

fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
    mutex.lock().unwrap_or_else(PoisonError::into_inner)
}

impl Recorder {
    /// Starts recording to a new file in `outbox`. Fails, without
    /// recording, if there's no microphone to use.
    pub fn start(outbox: &Path) -> Result<Recorder> {
        let path = new_path(outbox);
        crate::clipboard::private_folder(outbox).context(lang::t("the file can't be made"))?;
        let file = crate::clipboard::new_file(&path).context(lang::t("the file can't be made"))?;
        let shared = Arc::new(Shared::default());
        let (ours, theirs) = (Arc::clone(&shared), Arc::clone(&shared));
        let temp = path.clone();
        let spawned = std::thread::Builder::new()
            .name("record".into())
            .spawn(move || {
                let result = record(&ours, file, temp.clone());
                if let Err(e) = &result {
                    *lock(&theirs.failed) = Some(format!("{e:#}"));
                    // Left to end on its own, nobody else deletes it.
                    let _ = std::fs::remove_file(&temp);
                }
                result
            });
        match spawned.context(lang::t("there's no thread to record on")) {
            Ok(thread) => Ok(Recorder {
                shared,
                thread: Some(thread),
                path,
            }),
            Err(e) => {
                let _ = std::fs::remove_file(&path);
                Err(e)
            }
        }
    }

    /// A recorder that records nothing, for tests of what holds one.
    #[cfg(test)]
    pub fn idle() -> Recorder {
        Recorder {
            shared: Arc::default(),
            thread: Some(std::thread::spawn(|| bail!("nothing was recorded"))),
            path: PathBuf::new(),
        }
    }

    /// How much has been recorded, for the length on screen.
    pub fn duration(&self) -> Duration {
        Duration::from_secs_f64(self.shared.captured.load(Relaxed) as f64 / f64::from(RATE))
    }

    /// Why the recording ended early, if it did.
    pub fn failed(&self) -> Option<String> {
        lock(&self.shared.failed).clone()
    }

    /// Ends the recording; its file, length and waveform. Too short to
    /// hear counts as nothing, and the file is deleted.
    pub fn stop(mut self) -> Result<Take> {
        self.shared.stop.store(true, Relaxed);
        // Dropping it leaves the thread to end on its own.
        if !self.shared.opened.load(Relaxed) {
            bail!(lang::t("nothing was recorded"));
        }
        let thread = self.thread.take().expect("a recorder stops once");
        let result = thread
            .join()
            .map_err(|_| anyhow::anyhow!(lang::t("the recording couldn't be made")))?;
        let take = result?;
        if take.duration == 0 {
            bail!(lang::t("nothing was recorded"));
        }
        // The Take owns the file now.
        self.path = PathBuf::new();
        Ok(take)
    }
}

impl Drop for Recorder {
    fn drop(&mut self) {
        self.shared.stop.store(true, Relaxed);
        // A thread still opening the microphone isn't waited for: its take,
        // or its error, deletes the file when it ends.
        if let Some(thread) = self.thread.take()
            && self.shared.opened.load(Relaxed)
        {
            let _ = thread.join();
        }
        if !self.path.as_os_str().is_empty() {
            let _ = std::fs::remove_file(&self.path);
        }
    }
}

/// Records until `shared` says stop, writing `file`, and sums the take up.
fn record(shared: &Shared, file: File, path: PathBuf) -> Result<Take> {
    let mut source = source::open()?;
    shared.opened.store(true, Relaxed);
    // Stopped while it opened, which can't be cut short: closed at once, unread.
    if shared.stop.load(Relaxed) {
        drop(source);
        bail!(lang::t("nothing was recorded"));
    }
    let mut encoder = ::opus::Encoder::new(RATE, ::opus::Channels::Mono, ::opus::Application::Voip)
        .context(lang::t("the microphone can't be used"))?;
    let _ = encoder.set_bitrate(::opus::Bitrate::Bits(BITRATE));
    let preskip = encoder.get_lookahead().unwrap_or(0).max(0) as u64;
    let mut ogg = Ogg::new(file);
    ogg.head(preskip as u16)?;
    let mut pcm = vec![0i16; FRAME];
    let mut peaks: Vec<u16> = Vec::new();
    let mut peak = 0u16;
    let mut window = 0usize;
    let mut samples = 0u64;
    // The last packet waits, so the page that closes the stream can say so.
    let mut pending: Option<(Vec<u8>, u64)> = None;
    while !shared.stop.load(Relaxed) {
        let mut patience = Patience::new(samples > 0, &shared.stop);
        if !source.read(&mut pcm, &mut patience)? {
            break;
        }
        for &s in &pcm {
            peak = peak.max(s.unsigned_abs());
            window += 1;
            if window == WINDOW {
                peaks.push(peak);
                peak = 0;
                window = 0;
            }
        }
        let packet = encoder.encode_vec(&pcm, 4000)?;
        samples += pcm.len() as u64;
        shared.captured.store(samples, Relaxed);
        if let Some((last, end)) = pending.replace((packet, samples)) {
            ogg.packet(&last, end, false)?;
        }
    }
    if let Some((last, end)) = pending.take() {
        ogg.packet(&last, end, true)?;
    }
    let seconds = (samples - preskip.min(samples)) / u64::from(RATE);
    Ok(Take {
        path,
        duration: i32::try_from(seconds).unwrap_or(i32::MAX),
        waveform: waveform(&peaks),
    })
}

/// The peaks as Telegram's waveform field: 100 levels of 5 bits, packed
/// lowest bits first, base64.
fn waveform(peaks: &[u16]) -> String {
    if peaks.is_empty() {
        return String::new();
    }
    let loud = u32::from(peaks.iter().copied().max().unwrap_or(0).max(1));
    let n = peaks.len();
    let levels: Vec<u8> = (0..LEVELS)
        .map(|c| {
            let from = c * n / LEVELS;
            let to = ((c + 1) * n / LEVELS).clamp(from + 1, n);
            let peak = u32::from(peaks[from..to].iter().copied().max().unwrap_or(0));
            ((peak * LOUDEST + loud / 2) / loud) as u8
        })
        .collect();
    use base64::Engine;
    base64::engine::general_purpose::STANDARD.encode(pack(&levels))
}

/// The levels packed as Telegram's apps pack them: 5 bits each, lowest
/// bits of the first byte first. The inverse of voice.rs's `unpack`.
fn pack(levels: &[u8]) -> Vec<u8> {
    let mut bytes = vec![0; (levels.len() * 5).div_ceil(8)];
    for (i, &level) in levels.iter().enumerate() {
        let (byte, shift) = (i * 5 / 8, i * 5 % 8);
        let bits = u16::from(level.min(31)) << shift;
        bytes[byte] |= bits as u8;
        if let Some(next) = bytes.get_mut(byte + 1) {
            *next |= (bits >> 8) as u8;
        }
    }
    bytes
}

/// The start of a recording's file name; the rest is the process and the
/// time, then `.ogg`.
const PREFIX: &str = "tuigram-voice-";

/// Where a new recording goes: a name of its own in `outbox`.
fn new_path(outbox: &Path) -> PathBuf {
    let nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |d| d.as_nanos());
    outbox.join(format!("{PREFIX}{}-{nanos}.ogg", std::process::id()))
}

/// `path` is a recording tuigram made in `outbox`: named as it names
/// them, since the data folder can be set from a `.env` file, and so might
/// not be tuigram's own.
pub fn is_recording(path: &Path, outbox: &Path) -> bool {
    let named = path
        .file_name()
        .and_then(|n| n.to_str())
        .is_some_and(|name| {
            name.strip_prefix(PREFIX)
                .and_then(|n| n.strip_suffix(".ogg"))
                .and_then(|n| n.split_once('-'))
                .is_some_and(|(pid, nanos)| {
                    [pid, nanos]
                        .iter()
                        .all(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
                })
        });
    // TDLib names a file by its real path, which the data folder's may not be.
    named
        && path.parent().is_some_and(|dir| {
            dir == outbox
                || matches!(
                    (std::fs::canonicalize(dir), std::fs::canonicalize(outbox)),
                    (Ok(dir), Ok(outbox)) if dir == outbox
                )
        })
}

/// Deletes recordings a killed tuigram left in `outbox`: sent ones go once
/// Telegram has the message (`updateMessageSendSucceeded`), and a `Take`
/// dropped unsent deletes its own, so only a crash or a send that failed
/// leaves any. Fresh ones are kept:
/// they may be a live tuigram's, still recording or sending, or a failed
/// one's that Enter would send again; past [`KEEP`], that has no file.
pub fn clean_stale(outbox: &Path, now: SystemTime) {
    let Ok(entries) = std::fs::read_dir(outbox) else {
        return;
    };
    for entry in entries.flatten() {
        if !is_recording(&entry.path(), outbox) {
            continue;
        }
        // The entry itself, not what a link points to.
        let stale = entry
            .metadata()
            .ok()
            .filter(std::fs::Metadata::is_file)
            .and_then(|m| m.modified().ok())
            .is_some_and(|t| now.duration_since(t).is_ok_and(|age| age > KEEP));
        if stale {
            let _ = std::fs::remove_file(entry.path());
        }
    }
}

/// An Ogg stream (RFC 3533) written page by page: Opus in Ogg, as a
/// Telegram voice note.
struct Ogg {
    out: File,
    serial: u32,
    seq: u32,
}

impl Ogg {
    fn new(out: File) -> Self {
        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map_or(0, |d| d.as_nanos());
        Self {
            out,
            serial: nanos as u32,
            seq: 0,
        }
    }

    /// The OpusHead and OpusTags packets, each on a page of its own, as
    /// RFC 7845 asks. `preskip` is the encoder's warm-up, in samples.
    fn head(&mut self, preskip: u16) -> Result<()> {
        let mut head = Vec::with_capacity(19);
        head.extend_from_slice(b"OpusHead");
        head.push(1); // version
        head.push(1); // one channel
        head.extend_from_slice(&preskip.to_le_bytes());
        head.extend_from_slice(&RATE.to_le_bytes());
        head.extend_from_slice(&0i16.to_le_bytes()); // no gain change
        head.push(0); // channel mapping family 0: mono
        self.page(2, 0, &[&head])?; // 2: the stream's first page
        let vendor = b"tuigram";
        let mut tags = Vec::with_capacity(16 + vendor.len());
        tags.extend_from_slice(b"OpusTags");
        tags.extend_from_slice(&(vendor.len() as u32).to_le_bytes());
        tags.extend_from_slice(vendor);
        tags.extend_from_slice(&0u32.to_le_bytes()); // no comments
        self.page(0, 0, &[&tags])?;
        Ok(())
    }

    /// A sound packet on a page of its own; `granule` is samples decoded up
    /// to it, the encoder's warm-up included (RFC 7845), and `last` closes
    /// the stream.
    fn packet(&mut self, packet: &[u8], granule: u64, last: bool) -> Result<()> {
        self.page(u8::from(last) << 2, granule, &[packet])
    }

    /// One page: its packets' lacing values (a 255 means the packet goes
    /// on), then the header and data with the checksum filled in.
    fn page(&mut self, flags: u8, granule: u64, packets: &[&[u8]]) -> Result<()> {
        let mut lacing = Vec::new();
        for packet in packets {
            let mut left = packet.len();
            loop {
                let part = left.min(255);
                lacing.push(part as u8);
                left -= part;
                // A whole number of 255s still ends with a 0.
                if part < 255 {
                    break;
                }
            }
        }
        let mut page = Vec::with_capacity(27 + lacing.len() + 4000);
        page.extend_from_slice(b"OggS");
        page.push(0); // stream structure version
        page.push(flags);
        page.extend_from_slice(&granule.to_le_bytes());
        page.extend_from_slice(&self.serial.to_le_bytes());
        page.extend_from_slice(&self.seq.to_le_bytes());
        self.seq += 1;
        page.extend_from_slice(&0u32.to_le_bytes()); // the checksum, below
        page.push(lacing.len() as u8);
        page.extend_from_slice(&lacing);
        for packet in packets {
            page.extend_from_slice(packet);
        }
        let sum = crc(&page);
        page[22..26].copy_from_slice(&sum.to_le_bytes());
        self.out
            .write_all(&page)
            .context(lang::t("the file can't be written"))
    }
}

/// Ogg's CRC-32: no reflection, no final xor, the MPEG polynomial without
/// its preset.
fn crc(bytes: &[u8]) -> u32 {
    const fn table() -> [u32; 256] {
        let mut table = [0u32; 256];
        let mut i = 0;
        while i < 256 {
            let mut r = (i as u32) << 24;
            let mut b = 0;
            while b < 8 {
                r = if r & 0x8000_0000 != 0 {
                    (r << 1) ^ 0x04c1_1db7
                } else {
                    r << 1
                };
                b += 1;
            }
            table[i] = r;
            i += 1;
        }
        table
    }
    const TABLE: [u32; 256] = table();
    let mut sum = 0u32;
    for &byte in bytes {
        sum = (sum << 8) ^ TABLE[((sum >> 24) as u8 ^ byte) as usize];
    }
    sum
}

/// How long a read waits for the microphone: a device can take seconds to
/// start (a Bluetooth headset changing profiles), but one that has given
/// sound and then gives none for [`STALLED`] is gone.
const STARTING: Duration = Duration::from_secs(15);
const STALLED: Duration = Duration::from_secs(3);

/// A read waiting for the device, which the recording's stop ends at once:
/// `V` and Esc wait for the thread.
struct Patience<'a> {
    since: Instant,
    wait: Duration,
    stop: &'a AtomicBool,
}

impl<'a> Patience<'a> {
    fn new(heard_before: bool, stop: &'a AtomicBool) -> Self {
        Self {
            since: Instant::now(),
            wait: if heard_before { STALLED } else { STARTING },
            stop,
        }
    }

    /// The device gave something.
    #[cfg_attr(
        not(any(target_os = "linux", target_os = "macos", target_os = "windows")),
        allow(dead_code)
    )]
    fn heard(&mut self) {
        self.since = Instant::now();
    }

    /// The device has nothing yet: true to read again in a moment, false
    /// once the recording stopped, Err once it gave nothing for too long.
    #[cfg_attr(
        not(any(target_os = "linux", target_os = "macos", target_os = "windows")),
        allow(dead_code)
    )]
    fn wait(&self) -> Result<bool> {
        if self.stop.load(Relaxed) {
            return Ok(false);
        }
        if self.since.elapsed() > self.wait {
            bail!(lang::t("the microphone stopped"));
        }
        std::thread::sleep(Duration::from_millis(5));
        Ok(true)
    }
}

/// Where the samples come from.
trait Source {
    /// Fills `buf`: true once it's full, false if the recording stopped
    /// first. Err: the device failed or went away.
    fn read(&mut self, buf: &mut [i16], patience: &mut Patience) -> Result<bool>;
}

#[cfg(target_os = "linux")]
mod source {
    use std::ffi::{CStr, c_char, c_int, c_long, c_uint, c_ulong, c_void};
    use std::ptr::null_mut;
    use std::sync::OnceLock;

    use anyhow::{Result, bail};

    use super::{Patience, RATE, Source};
    use crate::lang;

    /// ALSA's `snd_pcm_t`, only ever behind a pointer.
    type Pcm = c_void;

    /// Capture, where playback (sound.rs) is 0.
    const CAPTURE: c_int = 1;
    /// Reads return at once with nothing heard, rather than wait: a device
    /// that stops delivering would hold the thread `V` and Esc wait for.
    const NONBLOCK: c_int = 1;
    #[cfg(target_endian = "little")]
    const S16: c_int = 2;
    #[cfg(target_endian = "big")]
    const S16: c_int = 3;
    const RW_INTERLEAVED: c_int = 3;
    /// How much ALSA buffers, in microseconds.
    const LATENCY: c_uint = 100_000;

    /// ALSA calls this with its errors, which it would otherwise print over
    /// the screen. It's declared variadic in C; on the platforms here a
    /// function ignoring the extra arguments takes such a call fine.
    type ErrorHandler =
        unsafe extern "C" fn(*const c_char, c_int, *const c_char, c_int, *const c_char);

    unsafe extern "C" fn quiet(
        _: *const c_char,
        _: c_int,
        _: *const c_char,
        _: c_int,
        _: *const c_char,
    ) {
    }

    // Their C signatures, from alsa/pcm.h and alsa/error.h.
    type SetHandler = unsafe extern "C" fn(Option<ErrorHandler>) -> c_int;
    type Open = unsafe extern "C" fn(*mut *mut Pcm, *const c_char, c_int, c_int) -> c_int;
    type SetParams =
        unsafe extern "C" fn(*mut Pcm, c_int, c_int, c_uint, c_uint, c_int, c_uint) -> c_int;
    type Read = unsafe extern "C" fn(*mut Pcm, *mut c_void, c_ulong) -> c_long;
    type Recover = unsafe extern "C" fn(*mut Pcm, c_int, c_int) -> c_int;
    type Close = unsafe extern "C" fn(*mut Pcm) -> c_int;
    type StrError = unsafe extern "C" fn(c_int) -> *const c_char;

    /// The few functions of libasound recording uses. As for playing, the
    /// library is loaded when something first records, not linked: a
    /// headless server must still start tuigram.
    struct Alsa {
        open: Open,
        set_params: SetParams,
        readi: Read,
        recover: Recover,
        close: Close,
        strerror: StrError,
    }

    fn alsa() -> Result<&'static Alsa> {
        static ALSA: OnceLock<Option<Alsa>> = OnceLock::new();
        match ALSA.get_or_init(load) {
            Some(alsa) => Ok(alsa),
            None => bail!(lang::t(
                "there's no sound here (ALSA's libasound.so.2 isn't installed)"
            )),
        }
    }

    fn load() -> Option<Alsa> {
        // SAFETY: the names are NUL-terminated, each symbol has its C
        // signature, and the library is never closed.
        unsafe {
            let lib = libc::dlopen(
                c"libasound.so.2".as_ptr(),
                libc::RTLD_NOW | libc::RTLD_LOCAL,
            );
            if lib.is_null() {
                return None;
            }
            macro_rules! function {
                ($name:literal as $signature:ty) => {{
                    let f = libc::dlsym(lib, $name.as_ptr());
                    if f.is_null() {
                        return None;
                    }
                    std::mem::transmute::<*mut c_void, $signature>(f)
                }};
            }
            let set_handler = function!(c"snd_lib_error_set_handler" as SetHandler);
            set_handler(Some(quiet));
            Some(Alsa {
                open: function!(c"snd_pcm_open" as Open),
                set_params: function!(c"snd_pcm_set_params" as SetParams),
                readi: function!(c"snd_pcm_readi" as Read),
                recover: function!(c"snd_pcm_recover" as Recover),
                close: function!(c"snd_pcm_close" as Close),
                strerror: function!(c"snd_strerror" as StrError),
            })
        }
    }

    pub struct Mic {
        alsa: &'static Alsa,
        pcm: *mut Pcm,
    }

    pub fn open() -> Result<Box<dyn Source>> {
        let alsa = alsa()?;
        // ALSA's PulseAudio and JACK plugins print over the screen, opening
        // the device and setting it up alike.
        let pcm = crate::sound::quietly(|| open_with(alsa))?;
        Ok(Box::new(Mic { alsa, pcm }))
    }

    fn open_with(alsa: &Alsa) -> Result<*mut Pcm> {
        let mut pcm = null_mut();
        // SAFETY: `pcm` is written by ALSA; "default" is NUL-terminated.
        let e = unsafe { (alsa.open)(&mut pcm, c"default".as_ptr(), CAPTURE, NONBLOCK) };
        if e < 0 {
            bail!(
                "{}: {}",
                lang::t("the microphone can't be opened"),
                message(alsa, e)
            );
        }
        // ALSA converts to what recording takes: mono at 48 kHz.
        // SAFETY: `pcm` is open.
        let e = unsafe { (alsa.set_params)(pcm, S16, RW_INTERLEAVED, 1, RATE, 1, LATENCY) };
        if e < 0 {
            // SAFETY: `pcm` is open, and not used after this.
            unsafe { (alsa.close)(pcm) };
            bail!(
                "{}: {}",
                lang::t("the microphone can't be used"),
                message(alsa, e)
            );
        }
        Ok(pcm)
    }

    fn message(alsa: &Alsa, e: c_int) -> String {
        // SAFETY: snd_strerror returns a static string for any code.
        let text = unsafe { (alsa.strerror)(e) };
        if text.is_null() {
            return format!("{} {e}", lang::t("error"));
        }
        // SAFETY: not null, and NUL-terminated.
        unsafe { CStr::from_ptr(text) }
            .to_string_lossy()
            .into_owned()
    }

    impl Source for Mic {
        fn read(&mut self, buf: &mut [i16], patience: &mut Patience) -> Result<bool> {
            let mut filled = 0;
            while filled < buf.len() {
                // SAFETY: `pcm` is open and `buf`'s tail is written: one
                // 16-bit sample per frame.
                let n = unsafe {
                    (self.alsa.readi)(
                        self.pcm,
                        buf[filled..].as_mut_ptr().cast(),
                        (buf.len() - filled) as c_ulong,
                    )
                };
                if n == 0 || n == -c_long::from(libc::EAGAIN) {
                    if !patience.wait()? {
                        return Ok(false);
                    }
                    continue;
                }
                if n < 0 {
                    // Mostly an overrun: what was heard meanwhile is lost.
                    // SAFETY: `pcm` is open.
                    let e = unsafe { (self.alsa.recover)(self.pcm, n as c_int, 1) };
                    if e < 0 {
                        bail!(
                            "{}: {}",
                            lang::t("the microphone stopped"),
                            message(self.alsa, e)
                        );
                    }
                    continue;
                }
                filled += n as usize;
                patience.heard();
            }
            Ok(true)
        }
    }

    impl Drop for Mic {
        fn drop(&mut self) {
            // SAFETY: `pcm` is open, and not used after this.
            unsafe { (self.alsa.close)(self.pcm) };
        }
    }
}

#[cfg(any(target_os = "macos", target_os = "windows"))]
mod source {
    use std::collections::VecDeque;
    use std::sync::{Arc, Mutex, MutexGuard, PoisonError};

    use anyhow::{Context, Result, anyhow, bail};
    use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
    use cpal::{FromSample, SampleFormat, SizedSample, StreamConfig};

    use super::{Patience, RATE, Resampler, Source};
    use crate::lang;

    /// What the device hears, shared with its callback: mono samples at
    /// its own rate, and why it failed if it did.
    #[derive(Default)]
    struct Heard {
        samples: VecDeque<f32>,
        failed: Option<String>,
    }

    pub struct Mic {
        /// Captures while it's kept.
        _stream: cpal::Stream,
        heard: Arc<Mutex<Heard>>,
        resampler: Resampler,
        scratch: Vec<i16>,
    }

    fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
        mutex.lock().unwrap_or_else(PoisonError::into_inner)
    }

    pub fn open() -> Result<Box<dyn Source>> {
        let device = cpal::default_host()
            .default_input_device()
            .context(lang::t("no microphone found"))?;
        let supported = device
            .default_input_config()
            .map_err(|e| anyhow!("{}: {e}", lang::t("the microphone can't be used")))?;
        let format = supported.sample_format();
        let config: StreamConfig = supported.into();
        let heard = Arc::new(Mutex::new(Heard::default()));
        let stream = match format {
            SampleFormat::F32 => stream::<f32>(&device, &config, &heard)?,
            SampleFormat::I16 => stream::<i16>(&device, &config, &heard)?,
            SampleFormat::U16 => stream::<u16>(&device, &config, &heard)?,
            SampleFormat::I32 => stream::<i32>(&device, &config, &heard)?,
            other => bail!(lang::f(
                "the microphone gives {format} samples, which tuigram can't take",
                &[("format", &other)],
            )),
        };
        stream
            .play()
            .map_err(|e| anyhow!("{}: {e}", lang::t("the microphone didn't start")))?;
        Ok(Box::new(Mic {
            _stream: stream,
            heard,
            resampler: Resampler::new(config.sample_rate, RATE),
            scratch: Vec::new(),
        }))
    }

    fn stream<T: SizedSample>(
        device: &cpal::Device,
        config: &StreamConfig,
        heard: &Arc<Mutex<Heard>>,
    ) -> Result<cpal::Stream>
    where
        f32: FromSample<T>,
    {
        let channels = usize::from(config.channels).max(1);
        let fill = Arc::clone(heard);
        let failed = Arc::clone(heard);
        device
            .build_input_stream(
                *config,
                move |data: &[T], _: &cpal::InputCallbackInfo| {
                    let mut heard = lock(&fill);
                    for frame in data.chunks(channels) {
                        // The channels averaged, as one.
                        let sum: f32 = frame.iter().map(|s| s.to_sample::<f32>()).sum();
                        heard.samples.push_back(sum / channels as f32);
                    }
                },
                // Not printed: the screen is tuigram's.
                move |e| lock(&failed).failed = Some(e.to_string()),
                None,
            )
            .map_err(|e| anyhow!("{}: {e}", lang::t("the microphone can't be used")))
    }

    impl Source for Mic {
        fn read(&mut self, buf: &mut [i16], patience: &mut Patience) -> Result<bool> {
            let mut filled = 0;
            while filled < buf.len() {
                {
                    let mut heard = lock(&self.heard);
                    if let Some(e) = &heard.failed {
                        bail!("{}: {e}", lang::t("the microphone stopped"));
                    }
                    let mut input = Vec::new();
                    while let Some(s) = heard.samples.pop_front() {
                        input.push(s);
                    }
                    drop(heard);
                    self.resampler.run(&input, &mut self.scratch);
                }
                let take = self.scratch.len().min(buf.len() - filled);
                buf[filled..filled + take].copy_from_slice(&self.scratch[..take]);
                self.scratch.drain(..take);
                filled += take;
                if take > 0 {
                    patience.heard();
                }
                if filled < buf.len() && !patience.wait()? {
                    return Ok(false);
                }
            }
            Ok(true)
        }
    }
}

#[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))]
mod source {
    use anyhow::{Result, bail};

    use super::Source;

    pub fn open() -> Result<Box<dyn Source>> {
        bail!(crate::lang::t("tuigram can't record on this system yet"))
    }
}

/// Changes the sample rate, drawing a straight line between samples:
/// plenty for a voice, as sound.rs does for playing. Used by the cpal
/// source; ALSA converts itself.
#[cfg(any(test, any(target_os = "macos", target_os = "windows")))]
pub struct Resampler {
    /// Input samples per output sample.
    step: f64,
    /// Where the next output sample falls, in input samples from the start
    /// of the next input; -1 is `last`.
    at: f64,
    /// The previous input's last sample.
    last: f32,
}

#[cfg(any(test, any(target_os = "macos", target_os = "windows")))]
impl Resampler {
    pub fn new(from: u32, to: u32) -> Self {
        Self {
            step: f64::from(from) / f64::from(to.max(1)),
            at: 0.0,
            last: 0.0,
        }
    }

    pub fn run(&mut self, input: &[f32], out: &mut Vec<i16>) {
        let Some(&end) = input.last() else {
            return;
        };
        let sample = |i: isize| match i {
            -1 => self.last,
            i => input[i as usize],
        };
        let len = input.len() as f64;
        while self.at < len - 1.0 {
            let i = self.at.floor();
            let (a, b) = (sample(i as isize), sample(i as isize + 1));
            let s = a + (b - a) * (self.at - i) as f32;
            out.push((s * 32768.0).clamp(-32768.0, 32767.0) as i16);
            self.at += self.step;
        }
        self.at -= len;
        self.last = end;
    }
}

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

    #[test]
    fn esc_and_v_never_wait_for_a_microphone_still_opening() {
        // An audio server that doesn't answer keeps the device opening.
        let opening = || Recorder {
            shared: Arc::default(),
            thread: Some(std::thread::spawn(|| {
                std::thread::sleep(Duration::from_secs(2));
                bail!("opened too late")
            })),
            path: PathBuf::new(),
        };
        let at = std::time::Instant::now();
        drop(opening());
        assert!(at.elapsed() < Duration::from_secs(1), "Esc waited");
        let at = std::time::Instant::now();
        assert!(opening().stop().is_err(), "nothing was recorded");
        assert!(at.elapsed() < Duration::from_secs(1), "V waited");
    }

    #[test]
    fn ogg_crc_matches_the_known_value() {
        // The CRC catalogue's value for Ogg's parameters ("123456789").
        assert_eq!(crc(b"123456789"), 0x89a1_897f);
    }

    #[test]
    fn a_written_page_carries_its_checksum() {
        let path = std::env::temp_dir().join(format!(
            "tuigram-record-test-{}-page.ogg",
            std::process::id()
        ));
        let file = File::create(&path).unwrap();
        let mut ogg = Ogg::new(file);
        ogg.packet(b"a packet", 960, true).unwrap();
        drop(ogg);
        let page = std::fs::read(&path).unwrap();
        std::fs::remove_file(&path).unwrap();
        assert!(page.starts_with(b"OggS\0\x04"), "the last page says so");
        let stored = u32::from_le_bytes(page[22..26].try_into().unwrap());
        let mut zeroed = page.clone();
        zeroed[22..26].fill(0);
        assert_eq!(crc(&zeroed), stored, "the page's checksum is its own");
        // Its granule and lacing.
        assert_eq!(u64::from_le_bytes(page[6..14].try_into().unwrap()), 960);
        assert_eq!(page[26], 1, "one packet");
        assert_eq!(page[27], 8, "of 8 bytes");
    }

    #[test]
    fn waveform_levels_pack_as_voice_rs_reads_them() {
        let levels: Vec<u8> = (0..100usize).map(|i| ((i * 7) % 32) as u8).collect();
        let packed = pack(&levels);
        // Voice.rs's unpacking, written out here to test against.
        let unpacked: Vec<u8> = (0..packed.len() * 8 / 5)
            .map(|i| {
                let (byte, shift) = (i * 5 / 8, i * 5 % 8);
                let next = packed.get(byte + 1).copied().unwrap_or(0);
                let pair = u16::from(packed[byte]) | u16::from(next) << 8;
                (pair >> shift & 0x1f) as u8
            })
            .collect();
        assert_eq!(unpacked[..100], levels[..]);
    }

    #[test]
    fn a_waveform_scales_to_the_loudest_peak() {
        let mut peaks = vec![0u16; 100];
        peaks[50] = 1000;
        let levels_b64 = waveform(&peaks);
        use base64::Engine;
        let bytes = base64::engine::general_purpose::STANDARD
            .decode(&levels_b64)
            .unwrap();
        assert_eq!(bytes.len(), 63, "100 levels of 5 bits");
        // The bucket with the peak is loudest.
        let loud = (0..bytes.len() * 8 / 5)
            .map(|i| {
                let (byte, shift) = (i * 5 / 8, i * 5 % 8);
                let next = bytes.get(byte + 1).copied().unwrap_or(0);
                ((u16::from(bytes[byte]) | u16::from(next) << 8) >> shift & 0x1f) as u8
            })
            .max()
            .unwrap();
        assert_eq!(loud, 31);
        assert!(waveform(&[]).is_empty(), "nothing heard, no waveform");
    }

    #[test]
    fn a_recording_written_is_one_voice_rs_reads() {
        // A sine through record()'s Ogg writer and Opus encoding, read back
        // by the player.
        let mut encoder =
            ::opus::Encoder::new(RATE, ::opus::Channels::Mono, ::opus::Application::Voip).unwrap();
        let preskip = encoder.get_lookahead().unwrap_or(0).max(0) as u64;
        let path =
            std::env::temp_dir().join(format!("tuigram-record-test-{}.ogg", std::process::id()));
        let file = File::create(&path).unwrap();
        let mut ogg = Ogg::new(file);
        ogg.head(preskip as u16).unwrap();
        let mut samples = 0u64;
        let mut pending: Option<(Vec<u8>, u64)> = None;
        for frame in 0..50 {
            let pcm: Vec<i16> = (0..FRAME)
                .map(|i| {
                    let t = (frame * FRAME + i) as f64 / f64::from(RATE);
                    (f64::sin(t * 440.0 * std::f64::consts::TAU) * 8000.0) as i16
                })
                .collect();
            let packet = encoder.encode_vec(&pcm, 4000).unwrap();
            samples += FRAME as u64;
            if let Some((last, end)) = pending.replace((packet, samples)) {
                ogg.packet(&last, end, false).unwrap();
            }
        }
        let (last, end) = pending.take().unwrap();
        ogg.packet(&last, end, true).unwrap();
        drop(ogg);

        let file = File::open(&path).unwrap();
        let mut sound = crate::voice::OggOpus::new(std::io::BufReader::new(file)).unwrap();
        let mut heard = Vec::new();
        let mut out = Vec::new();
        while sound.next(&mut out).unwrap() {
            heard.extend_from_slice(&out);
        }
        std::fs::remove_file(&path).unwrap();
        // The second of sound, less the warm-up a player skips: a page's
        // granule counts it in (RFC 7845), or the end is cut short too.
        let expect = 50 * FRAME - preskip as usize;
        assert_eq!(heard.len(), expect);
        // And it is the sine, not silence.
        assert!(heard.iter().any(|&s| s.unsigned_abs() > 4000));
    }

    #[test]
    fn resampling_keeps_the_length_in_time() {
        let mut resampler = Resampler::new(44_100, 48_000);
        let mut out = Vec::new();
        let second: Vec<f32> = (0..44_100)
            .map(|i| f32::sin(i as f32 / 44_100.0 * 440.0 * std::f32::consts::TAU))
            .collect();
        for chunk in second.chunks(441) {
            resampler.run(chunk, &mut out);
        }
        assert!(
            (47_990..=48_000).contains(&out.len()),
            "a second stays a second: {}",
            out.len()
        );
    }

    #[test]
    fn a_device_has_longer_to_start_than_to_go_quiet_and_a_stop_ends_the_wait() {
        let stop = AtomicBool::new(false);
        let quiet_for = STALLED + Duration::from_secs(1);
        let mut starting = Patience::new(false, &stop);
        starting.since -= quiet_for;
        assert!(starting.wait().unwrap(), "still starting: read again");
        let mut going = Patience::new(true, &stop);
        going.since -= quiet_for;
        assert!(going.wait().is_err(), "it gave sound, then none");
        going.heard();
        assert!(going.wait().unwrap(), "it gave some again");

        stop.store(true, Relaxed);
        starting.since -= STARTING;
        assert!(!starting.wait().unwrap(), "stopped: no error, no waiting");
    }

    #[test]
    fn stale_recordings_are_removed_but_fresh_ones_kept() {
        let dir =
            std::env::temp_dir().join(format!("tuigram-record-test-{}-stale", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let old = dir.join("tuigram-voice-1-2.ogg");
        let other = dir.join("other.ogg");
        let lookalike = dir.join("tuigram-voice-notes.ogg");
        for file in [&old, &other, &lookalike] {
            std::fs::write(file, b"x").unwrap();
        }
        let now = SystemTime::now();
        // An hour ago is stale.
        for file in [&old, &lookalike] {
            File::options()
                .write(true)
                .open(file)
                .unwrap()
                .set_modified(now - KEEP - Duration::from_secs(60))
                .unwrap();
        }
        clean_stale(&dir, now);
        assert!(!old.exists(), "an hour-old recording is removed");
        assert!(other.exists(), "other files are left alone");
        assert!(
            lookalike.exists(),
            "named otherwise than tuigram names them"
        );
        let fresh = dir.join("tuigram-voice-3-4.ogg");
        std::fs::write(&fresh, b"x").unwrap();
        clean_stale(&dir, now);
        assert!(fresh.exists(), "a fresh one may be a live tuigram's");
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn a_recording_is_a_file_only_you_can_read_in_the_outbox() {
        let outbox =
            std::env::temp_dir().join(format!("tuigram-record-test-{}-outbox", std::process::id()));
        let path = new_path(&outbox);
        assert!(is_recording(&path, &outbox), "{path:?}");
        assert!(
            !is_recording(&path, &std::env::temp_dir()),
            "only in the outbox"
        );
        assert!(!is_recording(&outbox.join("pasted-1.png"), &outbox));
        crate::clipboard::private_folder(&outbox).unwrap();
        drop(crate::clipboard::new_file(&path).unwrap());
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mode = |p: &Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777;
            assert_eq!(mode(&outbox), 0o700);
            assert_eq!(mode(&path), 0o600);
        }
        assert!(
            crate::clipboard::new_file(&path).is_err(),
            "never one that's there already"
        );
        std::fs::remove_dir_all(&outbox).unwrap();
    }

    #[test]
    fn a_take_deletes_its_file_unless_taken() {
        let path = new_path(&std::env::temp_dir());
        std::fs::write(&path, b"x").unwrap();
        {
            let take = Take {
                path: path.clone(),
                duration: 1,
                waveform: String::new(),
            };
            assert_eq!(take.path, path);
        }
        assert!(!path.exists(), "dropped, the file is gone");
        std::fs::write(&path, b"x").unwrap();
        let take = Take {
            path: path.clone(),
            duration: 1,
            waveform: String::new(),
        };
        let kept = take.into_path();
        assert!(kept.exists(), "taken, the file stays");
        std::fs::remove_file(&kept).unwrap();
    }
}