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
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
//! Video messages played in the terminal itself. In Pepper, Pepper's own
//! player draws the video straight into a box of cells and plays the sound
//! (`crate::pepper`). Elsewhere ffmpeg decodes frames to raw RGBA in a folder
//! of the player's own, at the video's own pace, the corners outside the
//! round frame take the bubble's color, kitty's protocol puts each where the
//! overlay's blank area is, and mpv plays the sound; and where pepper-play
//! can't play one, it plays that way too. Zooming restarts the decoder at
//! the same position with a bigger frame. Everything but the few calls
//! app.rs makes lives here.

use std::io::Read;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::Relaxed};
use std::thread::JoinHandle;

use anyhow::{Context, Result};
use ratatui::Frame;
use ratatui::layout::Rect;
use ratatui::style::Color;
use ratatui::text::Span;
use ratatui::widgets::Paragraph;
use ratatui_image::FontSize;
use ratatui_image::picker::cap_parser::Parser;
use tdlib_rs::types::VideoNote;
use tokio::sync::mpsc::UnboundedSender;

use crate::lang;
use crate::messages::{MediaFile, Msg};
use crate::term::{self, Terminal};
use crate::theme::Colors;
use crate::viewer::SIZES;

/// The biggest video message played in the terminal: they top out near a
/// minute, a few MB, so this leaves room to spare.
pub const MAX_FILE: u64 = 256 << 20;

/// Frames a second the decoder puts out, whatever the video's own rate, so
/// the frames shown tell where it is.
const FPS: f64 = 30.0;

/// The biggest side a video message is decoded at, in pixels. The sender
/// says how big theirs is, and each frame takes side × side × 4 bytes;
/// Telegram's apps record a few hundred.
const MAX_SIDE: i32 = 1024;

/// A video message, as TDLib describes it.
#[derive(Clone)]
pub struct Note {
    pub file_id: i32,
    pub size: u64,
    pub duration: i32,
    /// Diameter in pixels: video notes are square. At most [`MAX_SIDE`].
    pub length: u32,
}

impl Note {
    pub fn new(note: &VideoNote) -> Self {
        let size = note.video.size.max(note.video.expected_size);
        Self {
            file_id: note.video.id,
            size: u64::try_from(size).unwrap_or(0),
            duration: note.duration.max(0),
            length: note.length.clamp(1, MAX_SIDE) as u32,
        }
    }
}

/// Word from a decoder thread: the player it serves ([`TAG_VIEW`] or
/// [`TAG_INLINE`], which share the channel) and which run of it, since one
/// restarted at another size can leave the last run's word on the way.
pub struct VideoEvent {
    pub tag: u8,
    run: u64,
    pub news: News,
}

pub enum News {
    /// A new frame waits in the player's frame file.
    Frame,
    /// Another second went by: the time shown is drawn again.
    Moved,
    /// The video played out.
    Ended,
    Failed(String),
}

/// Tag of the fullscreen player's decoder.
pub const TAG_VIEW: u8 = 0;
/// Tag of the inline player's decoder.
pub const TAG_INLINE: u8 = 1;

/// Numbers every decoder run: see [`VideoEvent`].
static RUNS: AtomicU64 = AtomicU64::new(0);

/// The number kitty knows a video's frames by: outside the range images
/// take, so one's deletions never touch the other's.
const KITTY_ID: u32 = 0x7000_0000;

/// Where players make their folders: tmpfs, so kitty reads frames at memory
/// speed; the system temp dir where there is no /dev/shm (macOS, Windows).
fn frames_parent() -> PathBuf {
    let shm = PathBuf::from("/dev/shm");
    if shm.is_dir() {
        shm
    } else {
        std::env::temp_dir()
    }
}

/// One run of a video: as kitty frames this program sends, or through
/// Pepper's own player.
enum Run {
    Frames(Player),
    #[cfg(unix)]
    Pepper(PepperPlayer),
}

impl Run {
    fn run(&self) -> u64 {
        match self {
            Run::Frames(p) => p.run,
            #[cfg(unix)]
            Run::Pepper(p) => p.run,
        }
    }

    fn paused(&self) -> bool {
        match self {
            Run::Frames(p) => p.paused,
            #[cfg(unix)]
            Run::Pepper(p) => p.paused,
        }
    }

    fn toggle(&mut self) {
        match self {
            Run::Frames(p) => p.toggle(),
            #[cfg(unix)]
            Run::Pepper(p) => p.toggle(),
        }
    }

    /// Where it is, in seconds, for a run that started `start` in.
    fn position(&self, start: f64) -> f64 {
        match self {
            Run::Frames(p) => start + p.frames.load(Relaxed) as f64 / FPS,
            #[cfg(unix)]
            Run::Pepper(p) => f64::from_bits(p.seconds.load(Relaxed)),
        }
    }

    fn frames(&self) -> Option<&Player> {
        match self {
            Run::Frames(p) => Some(p),
            #[cfg(unix)]
            Run::Pepper(_) => None,
        }
    }
}

/// Pepper's player, pepper-play, on one video, driven over a socket pair
/// only it and tuigram hold (its fd 3). It quits once the video played or
/// the socket closes.
#[cfg(unix)]
struct PepperPlayer {
    child: Child,
    control: std::os::unix::net::UnixStream,
    /// The thread reading what pepper-play says.
    reader: Option<JoinHandle<()>>,
    /// The box's token: see [`crate::pepper`].
    token: String,
    /// Seconds into the video, as pepper-play last said, as `f64` bits.
    seconds: Arc<AtomicU64>,
    /// Where the box was last placed; `None` while it's taken away.
    placed: Option<Rect>,
    run: u64,
    paused: bool,
}

#[cfg(unix)]
impl PepperPlayer {
    /// Sends mpv's JSON IPC `command`.
    fn send(&mut self, command: serde_json::Value) {
        use std::io::Write;
        let line = serde_json::json!({ "command": command }).to_string();
        let _ = writeln!(self.control, "{line}");
    }

    fn toggle(&mut self) {
        self.paused = !self.paused;
        let pause = self.paused;
        self.send(serde_json::json!(["set_property", "pause", pause]));
    }

    /// Puts the picture over `area`, or takes it away for `None`: only when
    /// that changed, as each place is drawn again.
    fn place(&mut self, terminal: &mut Terminal, area: Option<Rect>) {
        if self.placed == area {
            return;
        }
        let code = match area {
            Some(area) => crate::pepper::place(&self.token, area),
            None => crate::pepper::remove(&self.token),
        };
        let _ = term::send(terminal, [code]);
        self.placed = area;
    }
}

#[cfg(unix)]
impl Drop for PepperPlayer {
    fn drop(&mut self) {
        // Its end of the socket closing ends pepper-play; killed too, in case
        // it hangs, and reaped.
        let _ = self.control.shutdown(std::net::Shutdown::Both);
        let _ = self.child.kill();
        let _ = self.child.wait();
        if let Some(reader) = self.reader.take() {
            let _ = reader.join();
        }
        if self.placed.is_some() {
            use std::io::Write;
            let _ = std::io::stdout().write_all(crate::pepper::remove(&self.token).as_bytes());
            let _ = std::io::stdout().flush();
        }
    }
}

/// Kitty frames: ffmpeg feeding frames into a folder of the player's own,
/// mpv on the sound. Both pause and resume together (SIGSTOP/SIGCONT), and
/// die with the player, the folder with them.
struct Player {
    ffmpeg: Child,
    audio: Option<Child>,
    /// The thread copying ffmpeg's frames into `dir`.
    pump: Option<JoinHandle<()>>,
    /// Made new for this run and only the user's
    /// ([`crate::config::new_private_dir`]): someone else's frames folder in
    /// a shared /dev/shm could read the frames or plant links to write through.
    dir: PathBuf,
    run: u64,
    /// Frames written to the file this run.
    frames: Arc<AtomicU64>,
    stop: Arc<AtomicBool>,
    paused: bool,
}

impl Player {
    /// Where the newest frame waits for the terminal to read it.
    fn frame_file(&self) -> PathBuf {
        self.dir.join("frame.rgb")
    }

    /// Play or pause: the decoder and the sound freeze together. Unix
    /// signals do it; Windows has nothing like them, so there pause just
    /// isn't there.
    #[cfg(unix)]
    fn toggle(&mut self) {
        let signal = if self.paused {
            libc::SIGCONT
        } else {
            libc::SIGSTOP
        };
        for child in std::iter::once(&self.ffmpeg).chain(&self.audio) {
            let pid: i32 = match child.id().try_into() {
                Ok(pid) if pid > 0 => pid,
                _ => continue,
            };
            unsafe { libc::kill(pid, signal) };
        }
        self.paused = !self.paused;
    }

    #[cfg(not(unix))]
    fn toggle(&mut self) {}
}

impl Drop for Player {
    fn drop(&mut self) {
        self.stop.store(true, Relaxed);
        let _ = self.ffmpeg.kill();
        // Reaped too: killed or finished, a child whose exit no one waits
        // for stays a zombie until tuigram itself exits.
        let _ = self.ffmpeg.wait();
        if let Some(audio) = &mut self.audio {
            let _ = audio.kill();
            let _ = audio.wait();
        }
        // The pump ends with ffmpeg's pipe; after it nothing writes there.
        if let Some(pump) = self.pump.take() {
            let _ = pump.join();
        }
        let _ = std::fs::remove_dir_all(&self.dir);
    }
}

/// Reads frames from `pipe` (width × height × 4 bytes each, RGBA) into
/// `dir`'s frame file, atomically: a half-written one never reaches the
/// terminal. At the video's own pace, since ffmpeg runs with `-re`, and
/// already round ([`round_graph`]).
fn pump_frames(
    mut pipe: impl Read,
    (width, height): (u32, u32),
    dir: &Path,
    frames: &AtomicU64,
    stop: &AtomicBool,
    (tag, run): (u8, u64),
    tx: &UnboundedSender<VideoEvent>,
) {
    let send = |news| tx.send(VideoEvent { tag, run, news }).is_ok();
    let size = width as usize * height as usize * 4;
    let tmp = dir.join("frame.tmp");
    let out = dir.join("frame.rgb");
    let mut buf = vec![0u8; size];
    loop {
        if stop.load(Relaxed) {
            return;
        }
        if let Err(e) = pipe.read_exact(&mut buf) {
            if !stop.load(Relaxed) {
                send(match e.kind() {
                    std::io::ErrorKind::UnexpectedEof => News::Ended,
                    _ => News::Failed(format!("{}: {e}", lang::t("decoding broke"))),
                });
            }
            return;
        }
        let written = std::fs::write(&tmp, &buf).and_then(|()| std::fs::rename(&tmp, &out));
        if let Err(e) = written {
            send(News::Failed(format!(
                "{}: {e}",
                lang::t("the frame file can't be written")
            )));
            return;
        }
        frames.fetch_add(1, Relaxed);
        if !send(News::Frame) {
            return;
        }
    }
}

/// How a video message is cut round: a square of `side` pixels, with what's
/// outside the circle painted `backdrop`.
#[derive(Clone, Copy)]
struct Round {
    side: u32,
    backdrop: [u8; 3],
}

impl Round {
    /// `note` on `bubble`; on black where that's a color the terminal picks,
    /// which has no RGB to read.
    fn of(note: &Note, bubble: Color) -> Self {
        let backdrop = match bubble {
            Color::Rgb(r, g, b) => [r, g, b],
            _ => [0, 0, 0],
        };
        Self {
            side: note.length,
            backdrop,
        }
    }
}

/// What the decoder's frames come out as: a video message cut round, or a
/// video sticker's own rectangle, which loops until it's stopped.
#[derive(Clone, Copy)]
enum Cut {
    Round(Round),
    Sticker { width: u32, height: u32 },
}

impl Cut {
    /// The frame's size: the reader counts bytes by it, kitty's transmit
    /// says it.
    fn size(&self) -> (u32, u32) {
        match self {
            Cut::Round(round) => (round.side, round.side),
            Cut::Sticker { width, height } => (*width, *height),
        }
    }
}

/// The size a video sticker is decoded at: its own, capped so a big one
/// doesn't flood the pipe — its slot is a dozen cells anyway.
fn sticker_side(width: u32, height: u32) -> (u32, u32) {
    const MAX: u32 = 256;
    let (w, h) = (width.max(1), height.max(1));
    let side = w.max(h);
    if side <= MAX {
        return (w, h);
    }
    // In u64: a sticker can claim any size.
    let scaled = |n: u32| (u64::from(n) * u64::from(MAX) / u64::from(side)).max(1) as u32;
    (scaled(w), scaled(h))
}

/// ffmpeg's arguments to decode `path` from `start` seconds through
/// `filter`. The file is a sender's: it's read only as the MP4 a video
/// message is, from the file alone, since one that's really a playlist
/// would have older ffmpegs fetch what it lists.
fn ffmpeg_args(path: &Path, start: &str, filter: &str) -> Vec<String> {
    let input = format!("file:{}", path.to_string_lossy());
    [
        "-v",
        "error",
        "-nostdin",
        "-re",
        "-protocol_whitelist",
        "file",
        "-f",
        "mov",
        "-ss",
        start,
        "-i",
        &input,
        "-an",
        "-vf",
        filter,
        "-f",
        "rawvideo",
        "-pix_fmt",
        "rgba",
        "pipe:1",
    ]
    .map(String::from)
    .to_vec()
}

/// ffmpeg's arguments to decode the WebM at `path` over and over through
/// `filter`: a video sticker loops until the cursor leaves it, and `-re`
/// paces the frames. As strict as [`ffmpeg_args`]: the file is a sender's,
/// read only as the WebM a video sticker is, from the file alone.
fn ffmpeg_loop_args(path: &Path, filter: &str, libvpx: bool) -> Vec<String> {
    let input = format!("file:{}", path.to_string_lossy());
    let mut args: Vec<String> = [
        "-v",
        "error",
        "-nostdin",
        "-re",
        "-protocol_whitelist",
        "file",
        "-f",
        "matroska,webm",
        "-stream_loop",
        "-1",
    ]
    .map(String::from)
    .to_vec();
    args.extend(sticker_decoder(libvpx));
    args.extend(
        [
            "-i", &input, "-an", "-vf", filter, "-f", "rawvideo", "-pix_fmt", "rgba", "pipe:1",
        ]
        .map(String::from),
    );
    args
}

/// The biggest side a video sticker's still is taken at: stickers are
/// 512px, and a sender's file may say it's any size.
const STILL_SIDE: u32 = 512;

/// ffmpeg's arguments to take the first frame of the WebM at `path` as a
/// PNG on stdout, no bigger than [`STILL_SIDE`]. As strict as
/// [`ffmpeg_args`]: the file is a sender's, read only as the WebM a video
/// sticker is, from the file alone.
pub fn ffmpeg_still_args(path: &Path, libvpx: bool) -> Vec<String> {
    let input = format!("file:{}", path.to_string_lossy());
    let scale = format!(
        "scale=w='min(iw,{STILL_SIDE})':h='min(ih,{STILL_SIDE})':force_original_aspect_ratio=decrease"
    );
    let mut args: Vec<String> = [
        "-v",
        "error",
        "-nostdin",
        "-protocol_whitelist",
        "file",
        "-f",
        "matroska,webm",
    ]
    .map(String::from)
    .to_vec();
    args.extend(sticker_decoder(libvpx));
    args.extend(
        [
            "-i",
            &input,
            "-an",
            "-vf",
            &scale,
            "-frames:v",
            "1",
            "-f",
            "image2pipe",
            "-c:v",
            "png",
            "pipe:1",
        ]
        .map(String::from),
    );
    args
}

/// The decoder for a video sticker: ffmpeg's own VP9 decoder drops its
/// transparency, which libvpx's keeps, where ffmpeg has it.
fn sticker_decoder(libvpx: bool) -> impl Iterator<Item = String> {
    libvpx
        .then_some(["-c:v", "libvpx-vp9"].map(String::from))
        .into_iter()
        .flatten()
}

/// What the ffmpeg on `PATH` can do, asked once; `None` without one.
pub struct Ffmpeg {
    /// It decodes VP9 with libvpx, keeping a sticker's transparency.
    pub libvpx: bool,
}

static FFMPEG: std::sync::OnceLock<Option<Ffmpeg>> = std::sync::OnceLock::new();

/// The ffmpeg on `PATH`, if there's one. Asked once, the first time:
/// [`crate::app::App::run`] asks on a thread of its own as it starts. Waits
/// for that answer, so the UI thread takes [`ffmpeg_if_known`] instead.
pub fn ffmpeg() -> Option<&'static Ffmpeg> {
    FFMPEG
        .get_or_init(|| {
            let out = Command::new("ffmpeg")
                .args(["-hide_banner", "-decoders"])
                .stdin(Stdio::null())
                .stderr(Stdio::null())
                .output()
                .ok()?;
            out.status.success().then(|| Ffmpeg {
                libvpx: String::from_utf8_lossy(&out.stdout).contains(" libvpx-vp9 "),
            })
        })
        .as_ref()
}

/// [`ffmpeg`] without waiting for its answer, for the UI thread: `None`
/// until it has come.
pub fn ffmpeg_if_known() -> Option<&'static Ffmpeg> {
    FFMPEG.get().and_then(Option::as_ref)
}

/// mpv's options for a sender's file, in mpv or pepper-play: read only as
/// the MP4 a video message is, from the file alone (mpv takes a playlist for
/// one by its contents and plays what it lists), with no config, scripts,
/// yt-dlp or output on the terminal.
const STRICT: [&str; 7] = [
    "--no-config",
    "--load-scripts=no",
    "--terminal=no",
    "--ytdl=no",
    "--demuxer=lavf",
    "--demuxer-lavf-format=mov",
    "--demuxer-lavf-o=protocol_whitelist=file",
];

/// mpv's arguments to play `path`'s sound from `start` seconds.
fn mpv_args(path: &Path, start: &str) -> Vec<String> {
    let mut args: Vec<String> = STRICT.map(String::from).into();
    args.extend(["--no-video".into(), format!("--start={start}")]);
    args.extend(["--".into(), path.to_string_lossy().into_owned()]);
    args
}

/// pepper-play's arguments to play `path` from `start` seconds, driven over
/// the socket it gets as fd 3, cut as `round` says.
#[cfg(unix)]
fn pepper_args(path: &Path, start: &str, round: Round) -> Vec<String> {
    let [r, g, b] = round.backdrop;
    let graph = round_graph(round);
    let mut args: Vec<String> = STRICT.map(String::from).into();
    args.extend([
        "--keep-open=no".into(),
        "--input-ipc-client=fd://3".into(),
        format!("--start={start}"),
        // The filter takes frames in memory, not on the graphics chip.
        "--hwdec=no".into(),
        // Length-prefixed, as mpv takes a value with brackets and commas in it.
        format!("--vf=lavfi=graph=%{}%{graph}", graph.len()),
        // Where the box isn't the picture's shape, the bars on its sides.
        format!("--background-color=#{r:02x}{g:02x}{b:02x}"),
    ]);
    args.extend(["--".into(), path.to_string_lossy().into_owned()]);
    args
}

/// The filter, for ffmpeg and mpv alike, scaling the picture to a square of
/// `round.side` pixels and cutting it round: a sender's video can come with
/// its corners white. The circle is drawn once and laid on each frame, over
/// the backdrop, and the edge is a shade, not a step. It ends with the video.
fn round_graph(
    Round {
        side,
        backdrop: [r, g, b],
    }: Round,
) -> String {
    let cover = "clip(min(W,H)/2-hypot(X-(W-1)/2,Y-(H-1)/2)+0.5,0,1)";
    format!(
        "scale={side}:{side},split[a][b];\
         [b]drawbox=c=0x{r:02x}{g:02x}{b:02x}:t=fill[back];\
         color=black:s={side}x{side}:r=1:d=1,format=gray,geq=lum='255*{cover}',loop=-1:1[circle];\
         [a]format=rgba[video];\
         [video][circle]alphamerge=shortest=1[cut];\
         [back][cut]overlay"
    )
}

/// Starts playing `path` from `start` seconds, cut as `cut` says: a video
/// message through Pepper's player `pepper` where there's one and it
/// starts, else as kitty frames. A video sticker is kitty frames only:
/// Pepper's player reads videos as MP4, which a WebM sticker isn't.
fn spawn(
    path: &Path,
    start: f64,
    cut: Cut,
    tag: u8,
    tx: UnboundedSender<VideoEvent>,
    pepper: Option<&Path>,
) -> Result<Run> {
    #[cfg(unix)]
    if let (Some(play), Cut::Round(round)) = (pepper, cut)
        && let Ok(player) = spawn_pepper(play, path, start, round, tag, tx.clone())
    {
        return Ok(Run::Pepper(player));
    }
    #[cfg(not(unix))]
    let _ = pepper;
    spawn_frames(path, start, cut, tag, tx).map(Run::Frames)
}

/// Starts pepper-play on `path` from `start` seconds. Its words come back
/// as decoder words ([`read_pepper`]), so the app can't tell the two apart.
#[cfg(unix)]
fn spawn_pepper(
    play: &Path,
    path: &Path,
    start: f64,
    round: Round,
    tag: u8,
    tx: UnboundedSender<VideoEvent>,
) -> Result<PepperPlayer> {
    use std::os::fd::AsRawFd;
    use std::os::unix::process::CommandExt;
    let token = crate::pepper::new_token().context("no randomness for Pepper's token")?;
    let (ours, theirs) = std::os::unix::net::UnixStream::pair()?;
    let reading = ours.try_clone()?;
    let fd = theirs.as_raw_fd();
    let mut command = Command::new(play);
    command
        .args(pepper_args(path, &format!("{start:.3}"), round))
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null());
    // SAFETY: only dup2 or fcntl runs between fork and exec, both
    // async-signal-safe. dup2 also clears close-on-exec on fd 3.
    unsafe {
        command.pre_exec(move || {
            let ok = if fd == 3 {
                libc::fcntl(3, libc::F_SETFD, 0) != -1
            } else {
                libc::dup2(fd, 3) != -1
            };
            if ok {
                Ok(())
            } else {
                Err(std::io::Error::last_os_error())
            }
        });
    }
    let child = command.spawn().context("pepper-play can't start")?;
    drop(theirs);
    let run = RUNS.fetch_add(1, Relaxed);
    let seconds = Arc::new(AtomicU64::new(start.to_bits()));
    let reader = {
        let seconds = Arc::clone(&seconds);
        std::thread::spawn(move || read_pepper(reading, &seconds, (tag, run), &tx))
    };
    let mut player = PepperPlayer {
        child,
        control: ours,
        reader: Some(reader),
        token,
        seconds,
        placed: None,
        run,
        paused: false,
    };
    let token = player.token.clone();
    player.send(serde_json::json!([
        "script-message-to",
        "main",
        "pepper-token",
        token
    ]));
    player.send(serde_json::json!(["observe_property", 1, "time-pos"]));
    Ok(player)
}

/// What pepper-play said, of what's heard.
#[cfg(unix)]
#[derive(Debug, PartialEq)]
enum Said {
    /// The picture started (mpv's `playback-restart`).
    Started,
    /// Seconds into the video.
    At(f64),
    Ended,
    Failed(String),
}

/// One line of mpv's JSON IPC from pepper-play, read as [`Said`].
#[cfg(unix)]
fn said(line: &str) -> Option<Said> {
    let said: serde_json::Value = serde_json::from_str(line).ok()?;
    match said.get("event")?.as_str()? {
        "playback-restart" => Some(Said::Started),
        "property-change" if said.get("name")? == "time-pos" => {
            said.get("data")?.as_f64().map(Said::At)
        }
        "end-file" if said.get("reason")? == "error" => {
            let why = said.get("file_error").and_then(|e| e.as_str());
            Some(Said::Failed(crate::text::clean(
                why.unwrap_or(lang::t("it can't be played")),
            )))
        }
        "end-file" => Some(Said::Ended),
        _ => None,
    }
}

/// Reads what pepper-play says on `stream` until it closes, keeping where it
/// is in `seconds` and sending the rest on as decoder words: a frame once
/// the picture started, the end, or why it couldn't play.
#[cfg(unix)]
fn read_pepper(
    stream: impl Read,
    seconds: &AtomicU64,
    (tag, run): (u8, u64),
    tx: &UnboundedSender<VideoEvent>,
) {
    use std::io::BufRead;
    let send = |news| tx.send(VideoEvent { tag, run, news }).is_ok();
    let mut started = false;
    for line in std::io::BufReader::new(stream).lines() {
        let Ok(line) = line else {
            break;
        };
        match said(&line) {
            Some(Said::Started) if !started => {
                started = true;
                if !send(News::Frame) {
                    return;
                }
            }
            Some(Said::At(at)) => {
                let before = f64::from_bits(seconds.swap(at.to_bits(), Relaxed));
                if at.floor() != before.floor() && !send(News::Moved) {
                    return;
                }
            }
            Some(Said::Ended) => {
                send(News::Ended);
                return;
            }
            Some(Said::Failed(why)) => {
                send(News::Failed(why));
                return;
            }
            _ => {}
        }
    }
    // The socket closed with no end said: pepper-play quit, or was stopped.
    send(if started {
        News::Ended
    } else {
        News::Failed("pepper-play stopped".into())
    });
}

/// Starts decoding `path` from `start` seconds into frames cut as `cut`
/// says; a video message also gets its sound in mpv, a video sticker loops
/// silently. No audio rather than no video when mpv is missing.
fn spawn_frames(
    path: &Path,
    start: f64,
    cut: Cut,
    tag: u8,
    tx: UnboundedSender<VideoEvent>,
) -> Result<Player> {
    // Always the same size: the frame's size never changes, so the reader
    // can count bytes.
    let start = format!("{start:.3}");
    let args = match cut {
        Cut::Round(round) => {
            let filter = format!("fps={FPS},{}", round_graph(round));
            ffmpeg_args(path, &start, &filter)
        }
        // Until ffmpeg has said whether it keeps transparency, the sticker
        // keeps its still.
        Cut::Sticker { width, height } => {
            let ffmpeg = ffmpeg_if_known().context("ffmpeg hasn't answered yet")?;
            let filter = format!("scale={width}:{height},fps={FPS}");
            ffmpeg_loop_args(path, &filter, ffmpeg.libvpx)
        }
    };
    let dir = crate::config::new_private_dir(&frames_parent(), "tuigram-video")?;
    let ffmpeg = Command::new("ffmpeg")
        .args(args)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .spawn();
    let ffmpeg = match ffmpeg {
        Ok(ffmpeg) => ffmpeg,
        Err(e) => {
            let _ = std::fs::remove_dir_all(&dir);
            return Err(e).context(lang::t("ffmpeg isn't installed"));
        }
    };
    // From here on, dropping the player cleans up after it.
    let mut player = Player {
        ffmpeg,
        audio: None,
        pump: None,
        dir,
        run: RUNS.fetch_add(1, Relaxed),
        frames: Arc::new(AtomicU64::new(0)),
        stop: Arc::new(AtomicBool::new(false)),
        paused: false,
    };
    let pipe = player
        .ffmpeg
        .stdout
        .take()
        .context("ffmpeg's frames are piped")?;
    // A video sticker is silent: nothing for mpv to play.
    if matches!(cut, Cut::Round(_)) {
        player.audio = Command::new("mpv")
            .args(mpv_args(path, &start))
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn()
            .ok();
    }
    let (frames, stop) = (Arc::clone(&player.frames), Arc::clone(&player.stop));
    let (dir, run) = (player.dir.clone(), player.run);
    player.pump = Some(std::thread::spawn(move || {
        pump_frames(pipe, cut.size(), &dir, &frames, &stop, (tag, run), &tx);
    }));
    Ok(player)
}

/// A video message playing in the terminal, over everything but the status
/// bar, as the photo viewer shows photos.
pub struct VideoView {
    pub chat_id: i64,
    /// The message it's in.
    pub message_id: i64,
    /// What `o` opens in another app.
    pub file: MediaFile,
    pub note: Note,
    /// Why `o` doesn't hand the file to another app: Telegram says it
    /// can't be saved.
    pub cant_copy: Option<&'static str>,
    /// How the picture is cut: on the color of others' bubbles.
    round: Round,
    /// Playing it is to tell its sender, once a frame of it shows: see
    /// [`VideoView::tell_now`].
    pub tell: bool,
    /// The downloaded file, once TDLib brings it.
    path: Option<PathBuf>,
    player: Option<Run>,
    /// Pepper's player, while it's the one to try: see [`crate::pepper`].
    pepper: Option<PathBuf>,
    tx: UnboundedSender<VideoEvent>,
    /// Seconds into the video the current run started at.
    start: f64,
    /// The size `j` or `k` picked, in [`SIZES`]. `None` until then: filling
    /// the window.
    zoom: Option<usize>,
    /// The cells the picture filled last frame.
    rect: Option<Rect>,
    /// The square the running player decodes at, in pixels: a change (zoomed
    /// or resized below the video's own size) restarts it at the same position.
    side: Option<u32>,
    /// A frame waits to be sent to the terminal.
    pending: bool,
    /// A frame of it came from the decoder.
    framed: bool,
    /// It played out: video messages play once, then the app closes the view.
    done: bool,
    /// Why it can't play, once: the app shows it and closes the view.
    pub error: Option<String>,
    /// Escapes go through tmux's passthrough when detected.
    tmux: bool,
}

impl VideoView {
    /// The video message of message `message_id`, `msg`, if it has one the
    /// terminal can play.
    pub fn of(
        chat_id: i64,
        message_id: i64,
        msg: &Msg,
        tx: UnboundedSender<VideoEvent>,
        tmux: bool,
        pepper: Option<PathBuf>,
        colors: &Colors,
    ) -> Option<Self> {
        let note = msg.video.clone()?;
        let file = msg.file.clone().filter(|f| f.id == note.file_id)?;
        Some(Self {
            chat_id,
            message_id,
            file,
            round: Round::of(&note, colors.other_bubble),
            note,
            cant_copy: crate::viewer::cant_copy(msg),
            tell: false,
            path: None,
            player: None,
            pepper,
            tx,
            start: 0.0,
            zoom: None,
            rect: None,
            side: None,
            pending: false,
            framed: false,
            done: false,
            error: None,
            tmux,
        })
    }

    /// The file Enter was on.
    pub fn waits_for(&self, file_id: i32) -> bool {
        self.path.is_none() && self.note.file_id == file_id
    }

    /// The file is downloaded: played from the next frame drawn.
    pub fn downloaded(&mut self, path: PathBuf) {
        self.path = Some(path);
    }

    /// True once, when a frame of it has come and playing it is to tell
    /// its sender: the app tells them then, as Telegram's apps do.
    pub fn tell_now(&mut self) -> bool {
        let now = self.tell && self.framed;
        if now {
            self.tell = false;
        }
        now
    }

    /// Where it is, in seconds.
    fn position(&self) -> f64 {
        self.player
            .as_ref()
            .map_or(self.start, |p| p.position(self.start))
    }

    /// Playing; paused; waiting for the file.
    pub fn status(&self) -> &'static str {
        match &self.player {
            None => lang::t("loading…"),
            Some(p) if p.paused() => lang::t("paused"),
            Some(_) => lang::t("playing"),
        }
    }

    /// Continue from `secs` in: a video message playing inline grows to the
    /// view where it is.
    pub fn resume_at(&mut self, secs: f64) {
        self.start = secs;
    }

    /// Message `message_id` of chat `chat_id`, now `msg`, no longer has the
    /// video message shown.
    pub fn lost(&self, chat_id: i64, message_id: i64, msg: Option<&Msg>) -> bool {
        chat_id == self.chat_id
            && message_id == self.message_id
            && msg.and_then(|m| m.video.as_ref()).map(|v| v.file_id) != Some(self.note.file_id)
    }

    /// Play or pause.
    pub fn toggle(&mut self) {
        if let Some(player) = &mut self.player {
            player.toggle();
        }
    }

    /// Bigger, as in the photo viewer; the decoder restarts at the same
    /// position on the next frame drawn, at the new size.
    pub fn zoom_in(&mut self) {
        let now = self.share();
        if let Some(i) = SIZES.iter().position(|&s| s > now + 0.001) {
            self.zoom = Some(i);
        }
    }

    /// Smaller.
    pub fn zoom_out(&mut self) {
        let now = self.share();
        if let Some(i) = SIZES.iter().rposition(|&s| s < now - 0.001) {
            self.zoom = Some(i);
        }
    }

    fn share(&self) -> f64 {
        self.zoom.map_or(1.0, |i| SIZES[i])
    }

    /// Word from the decoder: a frame to send, the end (it plays once, then
    /// the app closes the view), or why it can't play — `Err` closes the
    /// view too. A run stopped for another, at a new size, is no longer heard.
    pub fn on_event(&mut self, event: VideoEvent) -> Result<(), String> {
        if self.player.as_ref().is_none_or(|p| p.run() != event.run) {
            return Ok(());
        }
        match event.news {
            News::Frame => {
                self.pending = true;
                self.framed = true;
                Ok(())
            }
            News::Moved => Ok(()),
            News::Ended => {
                self.player = None;
                self.done = true;
                Ok(())
            }
            // pepper-play couldn't play it at all: kitty frames play it
            // instead, from the next frame drawn.
            News::Failed(_)
                if !self.framed && self.player.as_ref().is_some_and(|p| p.frames().is_none()) =>
            {
                self.pepper = None;
                self.player = None;
                Ok(())
            }
            News::Failed(why) => Err(why),
        }
    }

    /// It played to the end.
    pub fn finished(&self) -> bool {
        self.done
    }

    /// The picture's cells within `inner`, centered and square, as video
    /// messages are, at the zoom picked. Font cells are about twice as tall
    /// as wide: the pixel box accounts for it.
    fn layout(&self, inner: Rect, font: FontSize) -> (Rect, (u32, u32)) {
        let share = self.share();
        let (fw, fh) = (
            f64::from(font.width).max(1.0),
            f64::from(font.height).max(1.0),
        );
        let mut cols = f64::from(inner.width) * share;
        let mut rows = f64::from(inner.height) * share;
        if cols * fw > rows * fh {
            cols = rows * fh / fw;
        } else {
            rows = cols * fw / fh;
        }
        let cols = cols.max(1.0) as u16;
        let rows = rows.max(1.0) as u16;
        let rect = Rect {
            x: inner.x + inner.width.saturating_sub(cols) / 2,
            y: inner.y + inner.height.saturating_sub(rows) / 2,
            width: cols,
            height: rows,
        };
        let pixels = ((f64::from(cols) * fw) as u32, (f64::from(rows) * fh) as u32);
        (rect, pixels)
    }

    /// The square kitty frames are decoded at for a picture of `pixels`: no
    /// bigger than the video, since the terminal scales a frame to its cells,
    /// and a bigger one only costs, each frame, to make, write and read.
    fn frame_side(&self, (w, h): (u32, u32)) -> u32 {
        self.round.side.min(w).min(h).max(1)
    }

    /// The overlay: a blank board the frames land on, with a title. The
    /// player (re)starts once the picture's size is known or it changed.
    pub fn draw(&mut self, frame: &mut Frame, area: Rect, font: FontSize, colors: &Colors) {
        let block = crate::ui::bordered(colors);
        let inner = block.inner(area);
        let (at, pixels) = self.layout(inner, font);
        let side = self.frame_side(pixels);
        self.rect = Some(at);
        let now = self.position().min(f64::from(self.note.duration)) as u32;
        let of = self.note.duration.max(0) as u32;
        let mut title = format!(
            " {} · {} · {}:{:02} {} {}:{:02}",
            self.file.label,
            self.status(),
            now / 60,
            now % 60,
            lang::t("of"),
            of / 60,
            of % 60
        );
        if let Some(i) = self.zoom {
            title.push_str(&format!(" · {:.0}%", SIZES[i] * 100.0));
        }
        frame.render_widget(crate::ui::Cover, area);
        frame.render_widget(Paragraph::new(Span::from(title)).block(block), area);
        frame.render_widget(crate::ui::Cover, at);

        // Pepper scales the picture to its box itself: only kitty frames are
        // made again at a new size.
        let needs_restart = self.path.is_some()
            && !self.done
            && self
                .player
                .as_ref()
                .is_none_or(|p| p.frames().is_some() && self.side != Some(side));
        if needs_restart && self.error.is_none() {
            let position = if self.player.is_some() {
                self.position()
            } else {
                self.start
            };
            let was_paused = self.player.as_ref().is_some_and(Run::paused);
            self.player = None;
            match spawn(
                &self.path.clone().unwrap(),
                position,
                Cut::Round(Round { side, ..self.round }),
                TAG_VIEW,
                self.tx.clone(),
                self.pepper.as_deref(),
            ) {
                Ok(mut player) => {
                    if was_paused {
                        player.toggle();
                    }
                    self.player = Some(player);
                    self.start = position;
                    self.side = Some(side);
                }
                Err(e) => self.error = Some(format!("{e:#}")),
            }
        }
    }

    /// Sends the newest frame to the terminal, if one waits and the picture
    /// has a place; in Pepper, places the box where the picture goes. Called
    /// after each frame ratatui draws, so the picture lands over the board's
    /// blank cells.
    pub fn send_frame(&mut self, terminal: &mut Terminal) {
        #[cfg(unix)]
        if let Some(Run::Pepper(player)) = &mut self.player {
            player.place(terminal, self.rect);
            return;
        }
        let Some(player) = self.player.as_ref().and_then(Run::frames) else {
            return;
        };
        let (Some(at), Some(side)) = (self.rect, self.side) else {
            return;
        };
        if !self.pending {
            return;
        }
        self.pending = false;
        let path = kitty_path(&player.frame_file());
        let (start, escape, end) = Parser::tmux_start_escape_end(self.tmux);
        let codes = [
            // The picture goes at its cell, whatever ratatui left under the
            // cursor.
            format!("\x1b[{};{}H", at.y + 1, at.x + 1),
            format!(
                "{start}{escape}_Ga=T,t=f,f=32,s={side},v={side},i={KITTY_ID},q=2,c={},r={};{path}{escape}\\{end}",
                at.width, at.height
            ),
        ];
        let _ = term::send(terminal, codes);
    }
}

/// A frame file's path as kitty's protocol takes it, in base64.
fn kitty_path(file: &Path) -> String {
    use base64::Engine;
    base64::engine::general_purpose::STANDARD.encode(file.as_os_str().as_encoded_bytes())
}

/// The video's frames go away with the view: kitty's image is deleted, the
/// decoder and the sound die with the player, its folder with them.
impl Drop for VideoView {
    fn drop(&mut self) {
        let (start, escape, end) = Parser::tmux_start_escape_end(self.tmux);
        let code = format!("{start}{escape}_Ga=d,d=I,i={KITTY_ID},q=2{escape}\\{end}");
        use std::io::Write;
        let _ = std::io::stdout().write_all(code.as_bytes());
        let _ = std::io::stdout().flush();
    }
}

/// The number kitty knows an inline player's frames by: beside the view's,
/// outside the range images take.
const INLINE_KITTY_ID: u32 = 0x7000_0001;

/// A video message playing where its thumbnail sits in the chat, as in
/// Telegram's apps. Space starts (and pauses) it, z blows it up to twice
/// the cells each way, pushing the messages around it apart; it stops once
/// its bubble isn't drawn — scrolled away, or the chat left — and plays
/// once, then the still is back. Enter grows it to the whole terminal
/// (see [`VideoView`]). A video sticker is the same player the cursor
/// starts and stops instead (see [`Inline::of_sticker`]): it loops until
/// the cursor moves on, silently.
pub struct Inline {
    pub chat_id: i64,
    /// The message it's in.
    pub message_id: i64,
    pub note: Note,
    /// Playing it is to tell its sender, once a frame of it shows: see
    /// [`Inline::tell_now`].
    pub tell: bool,
    /// The downloaded file, once TDLib brings it.
    path: Option<PathBuf>,
    /// How the frames are cut: a video message's circle, or a video
    /// sticker's own rectangle.
    cut: Cut,
    player: Option<Run>,
    /// Pepper's player, while it's the one to try: see [`crate::pepper`].
    pepper: Option<PathBuf>,
    tx: UnboundedSender<VideoEvent>,
    /// A frame waits to be sent to the terminal.
    pending: bool,
    /// A frame of it came from the decoder.
    framed: bool,
    /// z blew it up to twice the thumbnail's cells each way.
    medium: bool,
    /// The bubble's picture cells were drawn this frame; ui sets it, the
    /// app stops the player when a whole frame went by without it.
    pub seen: bool,
    /// A video sticker [`Inline::stop_unseen`] stopped, to play again once
    /// its bubble is drawn: see [`Inline::resume`].
    stopped: bool,
    /// The slot's size in cells, set by the ui when it draws the
    /// placeholder cells: kitty's virtual placement is made exactly that
    /// big (`c`/`r` on the transmit), or it guesses a size from the cells
    /// it has seen — a guess a partial redraw breaks, cutting the picture.
    pub placement: Option<(u16, u16)>,
    /// In Pepper, the cells the ui left blank for the picture this frame:
    /// `None` while a popup is over them, which Pepper's box would cover.
    pub area: Option<Rect>,
    tmux: bool,
}

impl Inline {
    /// The video message of message `message_id`, `msg`, if it has one the
    /// terminal can play inline: it needs a thumbnail's cells to play in.
    pub fn of(
        chat_id: i64,
        message_id: i64,
        msg: &Msg,
        tx: UnboundedSender<VideoEvent>,
        tmux: bool,
        pepper: Option<PathBuf>,
        colors: &Colors,
    ) -> Option<Self> {
        let note = msg.video.clone()?;
        msg.preview.as_ref()?;
        Some(Self {
            chat_id,
            message_id,
            cut: Cut::Round(Round::of(
                &note,
                if msg.outgoing {
                    colors.own_bubble
                } else {
                    colors.other_bubble
                },
            )),
            note,
            tell: false,
            path: None,
            player: None,
            pepper,
            tx,
            pending: false,
            framed: false,
            medium: false,
            seen: false,
            stopped: false,
            placement: None,
            area: None,
            tmux,
        })
    }

    /// The video sticker of message `message_id`, `msg`, if it is one and
    /// has a thumbnail's cells to play in. It loops while the cursor stays
    /// on the message; Telegram has nothing to be told about it playing.
    pub fn of_sticker(
        chat_id: i64,
        message_id: i64,
        msg: &Msg,
        tx: UnboundedSender<VideoEvent>,
        tmux: bool,
    ) -> Option<Self> {
        let file_id = msg.video_sticker?;
        let preview = msg.preview.as_ref()?;
        let (width, height) = sticker_side(preview.width, preview.height);
        Some(Self {
            chat_id,
            message_id,
            note: Note {
                file_id,
                size: 0,
                duration: 0,
                length: width.max(height),
            },
            tell: false,
            path: None,
            cut: Cut::Sticker { width, height },
            player: None,
            pepper: None,
            tx,
            pending: false,
            framed: false,
            medium: false,
            seen: false,
            stopped: false,
            placement: None,
            area: None,
            tmux,
        })
    }

    /// A video sticker, which the cursor's coming and going starts and
    /// stops, not Space.
    pub fn is_sticker(&self) -> bool {
        matches!(self.cut, Cut::Sticker { .. })
    }

    /// It plays the video message of this chat's this message, which Space
    /// and `z` act on; never a video sticker.
    pub fn plays_note(&self, chat_id: i64, message_id: i64) -> bool {
        !self.is_sticker() && self.is_on(chat_id, message_id)
    }

    /// It's this chat's this message's player.
    pub fn is_on(&self, chat_id: i64, message_id: i64) -> bool {
        self.chat_id == chat_id && self.message_id == message_id
    }

    /// The file Space was on.
    pub fn waits_for(&self, file_id: i32) -> bool {
        self.path.is_none() && self.note.file_id == file_id
    }

    /// The file is downloaded: played from the first frame, square as the
    /// note is.
    pub fn downloaded(&mut self, path: PathBuf) -> Result<(), String> {
        self.path = Some(path);
        self.start_over()
    }

    /// Plays it from the start.
    fn start_over(&mut self) -> Result<(), String> {
        let Some(path) = &self.path else {
            return Ok(());
        };
        let pepper = self.pepper.as_deref();
        let run = spawn(path, 0.0, self.cut, TAG_INLINE, self.tx.clone(), pepper);
        self.player = Some(run.map_err(|e| format!("{e:#}"))?);
        self.framed = false;
        Ok(())
    }

    /// Its bubble wasn't drawn for a whole frame: it stops. A video sticker
    /// stays, showing its still, so the cursor still on it doesn't start it
    /// over every frame; false says to drop a video message's player.
    pub fn stop_unseen(&mut self) -> bool {
        self.player = None;
        self.stopped = self.is_sticker();
        self.is_sticker()
    }

    /// Stopped while out of sight, to play again once its bubble is drawn.
    pub fn resumes(&self) -> bool {
        self.stopped
    }

    /// Plays a video sticker [`Inline::stop_unseen`] stopped again: its
    /// bubble is back in sight. One that can't start keeps its still.
    pub fn resume(&mut self) {
        if std::mem::take(&mut self.stopped) {
            let _ = self.start_over();
        }
    }

    /// True once, when a frame of it has come and playing it is to tell
    /// its sender: the app tells them then, as Telegram's apps do.
    pub fn tell_now(&mut self) -> bool {
        let now = self.tell && self.framed;
        if now {
            self.tell = false;
        }
        now
    }

    /// The decoder is up: the bubble can show frames instead of the still.
    pub fn started(&self) -> bool {
        self.player.is_some()
    }

    /// A video message that played to its end, or couldn't start: kept for
    /// `z` and Space, but nothing's playing.
    pub fn played_out(&self) -> bool {
        !self.is_sticker() && self.path.is_some() && self.player.is_none()
    }

    #[cfg(test)]
    pub fn play_out_for_test(&mut self) {
        self.path = Some(PathBuf::from("/nowhere/note.mp4"));
        self.player = None;
    }

    /// The picture plays through Pepper's player, in a box over the cells
    /// the ui leaves blank, not in kitty's placeholder cells.
    pub fn in_pepper(&self) -> bool {
        self.player.as_ref().is_some_and(|p| p.frames().is_none())
    }

    /// Where it is, in seconds: where [`VideoView`] takes over on Enter.
    pub fn position(&self) -> f64 {
        self.player.as_ref().map_or(0.0, |p| p.position(0.0))
    }

    /// Play or pause; after it played out, play it again from the start.
    pub fn toggle(&mut self) {
        match &mut self.player {
            Some(player) => player.toggle(),
            None => {
                let _ = self.start_over();
            }
        }
    }

    /// Twice as big in the chat, pushing the messages around it apart, or
    /// back to the thumbnail's size. The decoder is untouched: kitty scales
    /// the placement.
    pub fn toggle_zoom(&mut self) {
        self.medium = !self.medium;
    }

    /// It takes twice the thumbnail's cells each way.
    pub fn medium(&self) -> bool {
        self.medium
    }

    /// Message `message_id` of chat `chat_id`, now `msg`, no longer has the
    /// video message or video sticker shown.
    pub fn lost(&self, chat_id: i64, message_id: i64, msg: Option<&Msg>) -> bool {
        chat_id == self.chat_id
            && message_id == self.message_id
            && msg.and_then(|m| match self.cut {
                Cut::Round(_) => m.video.as_ref().map(|v| v.file_id),
                Cut::Sticker { .. } => m.video_sticker,
            }) != Some(self.note.file_id)
    }

    /// Word from the decoder: a frame to send, or the end — it plays once,
    /// then the bubble shows the still again until Space starts it over. A
    /// run stopped for another is no longer heard.
    pub fn on_event(&mut self, event: VideoEvent) -> Result<(), String> {
        if self.player.as_ref().is_none_or(|p| p.run() != event.run) {
            return Ok(());
        }
        match event.news {
            News::Frame => {
                self.pending = true;
                self.framed = true;
                Ok(())
            }
            News::Moved => Ok(()),
            News::Ended => {
                self.player = None;
                Ok(())
            }
            // pepper-play couldn't play it at all: kitty frames play it
            // instead.
            News::Failed(_) if !self.framed && self.in_pepper() => {
                self.pepper = None;
                self.start_over()
            }
            // A video sticker that can't play just shows its still: the
            // cursor staying on it isn't an error to report.
            News::Failed(_) if self.is_sticker() => {
                self.player = None;
                Ok(())
            }
            News::Failed(why) => Err(why),
        }
    }

    /// Sends the newest frame to the terminal as a virtual placement sized
    /// to the slot's cells (`c`/`r`): kitty fits the frame into it, keeping
    /// the aspect. The bubble's placeholder cells (see [`InlineImage`]) say
    /// where it shows, so it follows the text as it scrolls. In Pepper, places
    /// the box over [`Inline::area`] instead. Called after each frame ratatui
    /// draws.
    pub fn send_frame(&mut self, terminal: &mut Terminal) {
        #[cfg(unix)]
        if let Some(Run::Pepper(player)) = &mut self.player {
            player.place(terminal, self.area);
            return;
        }
        let Some(player) = self.player.as_ref().and_then(Run::frames) else {
            return;
        };
        let Some((c, r)) = self.placement else {
            return;
        };
        if !self.pending {
            return;
        }
        self.pending = false;
        let path = kitty_path(&player.frame_file());
        let (start, escape, end) = Parser::tmux_start_escape_end(self.tmux);
        let (s, v) = self.cut.size();
        let code = format!(
            "{start}{escape}_Gq=2,i={INLINE_KITTY_ID},a=T,U=1,f=32,t=f,s={s},v={v},c={c},r={r};{path}{escape}\\{end}"
        );
        let _ = term::send(terminal, [code]);
    }
}

/// The video's frames go away with the player: kitty's image is deleted,
/// the decoder and the sound die with it.
impl Drop for Inline {
    fn drop(&mut self) {
        let (start, escape, end) = Parser::tmux_start_escape_end(self.tmux);
        let code = format!("{start}{escape}_Ga=d,d=I,i={INLINE_KITTY_ID},q=2{escape}\\{end}");
        use std::io::Write;
        let _ = std::io::stdout().write_all(code.as_bytes());
        let _ = std::io::stdout().flush();
    }
}

/// The placeholder cells kitty's protocol draws an inline player's frames
/// at: U+10EEEE with the image's number as the cell's foreground color, and
/// the row, column and the number's high byte as diacritics on each row's
/// first cell. Mirrored from ratatui-image's kitty backend, which can't be
/// used here: it transmits the image's bytes itself, while a playing
/// video's frames go as files ([`Inline::send_frame`]).
pub struct InlineImage {
    /// Rows scrolled off the top: the first visible row's number.
    pub skip: u16,
}

impl ratatui::widgets::Widget for InlineImage {
    fn render(self, area: Rect, buf: &mut ratatui::buffer::Buffer) {
        use ratatui::buffer::CellDiffOption;
        use std::num::NonZeroU16;
        let [id_extra, r, g, b] = INLINE_KITTY_ID.to_be_bytes();
        let fg = ratatui::style::Color::Rgb(r, g, b);
        let max = DIACRITICS.len() as u16;
        // Cells the diacritic table can't number are left alone rather than
        // shown at the wrong offset.
        let mut symbol = String::with_capacity(8);
        for y in 0..area.height.min(max) {
            let row = y + self.skip;
            if row >= max {
                break;
            }
            for x in 0..area.width.min(max) {
                let Some(cell) = buf.cell_mut((area.x + x, area.y + y)) else {
                    continue;
                };
                symbol.clear();
                symbol.push(crate::images::PLACEHOLDER);
                if x == 0 {
                    symbol.push(diacritic(row));
                    symbol.push(diacritic(0));
                    symbol.push(diacritic(u16::from(id_extra)));
                }
                cell.set_symbol(&symbol)
                    .set_fg(fg)
                    .set_diff_option(CellDiffOption::ForcedWidth(NonZeroU16::new(1).unwrap()));
            }
        }
    }
}

/// Row/column diacritics for kitty's unicode placeholders.
/// From https://sw.kovidgoyal.net/kitty/_downloads/1792bad15b12979994cd6ecc54c967a6/rowcolumn-diacritics.txt
/// See https://sw.kovidgoyal.net/kitty/graphics-protocol/#unicode-placeholders for further explanation.
static DIACRITICS: [char; 297] = [
    '\u{305}',
    '\u{30D}',
    '\u{30E}',
    '\u{310}',
    '\u{312}',
    '\u{33D}',
    '\u{33E}',
    '\u{33F}',
    '\u{346}',
    '\u{34A}',
    '\u{34B}',
    '\u{34C}',
    '\u{350}',
    '\u{351}',
    '\u{352}',
    '\u{357}',
    '\u{35B}',
    '\u{363}',
    '\u{364}',
    '\u{365}',
    '\u{366}',
    '\u{367}',
    '\u{368}',
    '\u{369}',
    '\u{36A}',
    '\u{36B}',
    '\u{36C}',
    '\u{36D}',
    '\u{36E}',
    '\u{36F}',
    '\u{483}',
    '\u{484}',
    '\u{485}',
    '\u{486}',
    '\u{487}',
    '\u{592}',
    '\u{593}',
    '\u{594}',
    '\u{595}',
    '\u{597}',
    '\u{598}',
    '\u{599}',
    '\u{59C}',
    '\u{59D}',
    '\u{59E}',
    '\u{59F}',
    '\u{5A0}',
    '\u{5A1}',
    '\u{5A8}',
    '\u{5A9}',
    '\u{5AB}',
    '\u{5AC}',
    '\u{5AF}',
    '\u{5C4}',
    '\u{610}',
    '\u{611}',
    '\u{612}',
    '\u{613}',
    '\u{614}',
    '\u{615}',
    '\u{616}',
    '\u{617}',
    '\u{657}',
    '\u{658}',
    '\u{659}',
    '\u{65A}',
    '\u{65B}',
    '\u{65D}',
    '\u{65E}',
    '\u{6D6}',
    '\u{6D7}',
    '\u{6D8}',
    '\u{6D9}',
    '\u{6DA}',
    '\u{6DB}',
    '\u{6DC}',
    '\u{6DF}',
    '\u{6E0}',
    '\u{6E1}',
    '\u{6E2}',
    '\u{6E4}',
    '\u{6E7}',
    '\u{6E8}',
    '\u{6EB}',
    '\u{6EC}',
    '\u{730}',
    '\u{732}',
    '\u{733}',
    '\u{735}',
    '\u{736}',
    '\u{73A}',
    '\u{73D}',
    '\u{73F}',
    '\u{740}',
    '\u{741}',
    '\u{743}',
    '\u{745}',
    '\u{747}',
    '\u{749}',
    '\u{74A}',
    '\u{7EB}',
    '\u{7EC}',
    '\u{7ED}',
    '\u{7EE}',
    '\u{7EF}',
    '\u{7F0}',
    '\u{7F1}',
    '\u{7F3}',
    '\u{816}',
    '\u{817}',
    '\u{818}',
    '\u{819}',
    '\u{81B}',
    '\u{81C}',
    '\u{81D}',
    '\u{81E}',
    '\u{81F}',
    '\u{820}',
    '\u{821}',
    '\u{822}',
    '\u{823}',
    '\u{825}',
    '\u{826}',
    '\u{827}',
    '\u{829}',
    '\u{82A}',
    '\u{82B}',
    '\u{82C}',
    '\u{82D}',
    '\u{951}',
    '\u{953}',
    '\u{954}',
    '\u{F82}',
    '\u{F83}',
    '\u{F86}',
    '\u{F87}',
    '\u{135D}',
    '\u{135E}',
    '\u{135F}',
    '\u{17DD}',
    '\u{193A}',
    '\u{1A17}',
    '\u{1A75}',
    '\u{1A76}',
    '\u{1A77}',
    '\u{1A78}',
    '\u{1A79}',
    '\u{1A7A}',
    '\u{1A7B}',
    '\u{1A7C}',
    '\u{1B6B}',
    '\u{1B6D}',
    '\u{1B6E}',
    '\u{1B6F}',
    '\u{1B70}',
    '\u{1B71}',
    '\u{1B72}',
    '\u{1B73}',
    '\u{1CD0}',
    '\u{1CD1}',
    '\u{1CD2}',
    '\u{1CDA}',
    '\u{1CDB}',
    '\u{1CE0}',
    '\u{1DC0}',
    '\u{1DC1}',
    '\u{1DC3}',
    '\u{1DC4}',
    '\u{1DC5}',
    '\u{1DC6}',
    '\u{1DC7}',
    '\u{1DC8}',
    '\u{1DC9}',
    '\u{1DCB}',
    '\u{1DCC}',
    '\u{1DD1}',
    '\u{1DD2}',
    '\u{1DD3}',
    '\u{1DD4}',
    '\u{1DD5}',
    '\u{1DD6}',
    '\u{1DD7}',
    '\u{1DD8}',
    '\u{1DD9}',
    '\u{1DDA}',
    '\u{1DDB}',
    '\u{1DDC}',
    '\u{1DDD}',
    '\u{1DDE}',
    '\u{1DDF}',
    '\u{1DE0}',
    '\u{1DE1}',
    '\u{1DE2}',
    '\u{1DE3}',
    '\u{1DE4}',
    '\u{1DE5}',
    '\u{1DE6}',
    '\u{1DFE}',
    '\u{20D0}',
    '\u{20D1}',
    '\u{20D4}',
    '\u{20D5}',
    '\u{20D6}',
    '\u{20D7}',
    '\u{20DB}',
    '\u{20DC}',
    '\u{20E1}',
    '\u{20E7}',
    '\u{20E9}',
    '\u{20F0}',
    '\u{2CEF}',
    '\u{2CF0}',
    '\u{2CF1}',
    '\u{2DE0}',
    '\u{2DE1}',
    '\u{2DE2}',
    '\u{2DE3}',
    '\u{2DE4}',
    '\u{2DE5}',
    '\u{2DE6}',
    '\u{2DE7}',
    '\u{2DE8}',
    '\u{2DE9}',
    '\u{2DEA}',
    '\u{2DEB}',
    '\u{2DEC}',
    '\u{2DED}',
    '\u{2DEE}',
    '\u{2DEF}',
    '\u{2DF0}',
    '\u{2DF1}',
    '\u{2DF2}',
    '\u{2DF3}',
    '\u{2DF4}',
    '\u{2DF5}',
    '\u{2DF6}',
    '\u{2DF7}',
    '\u{2DF8}',
    '\u{2DF9}',
    '\u{2DFA}',
    '\u{2DFB}',
    '\u{2DFC}',
    '\u{2DFD}',
    '\u{2DFE}',
    '\u{2DFF}',
    '\u{A66F}',
    '\u{A67C}',
    '\u{A67D}',
    '\u{A6F0}',
    '\u{A6F1}',
    '\u{A8E0}',
    '\u{A8E1}',
    '\u{A8E2}',
    '\u{A8E3}',
    '\u{A8E4}',
    '\u{A8E5}',
    '\u{A8E6}',
    '\u{A8E7}',
    '\u{A8E8}',
    '\u{A8E9}',
    '\u{A8EA}',
    '\u{A8EB}',
    '\u{A8EC}',
    '\u{A8ED}',
    '\u{A8EE}',
    '\u{A8EF}',
    '\u{A8F0}',
    '\u{A8F1}',
    '\u{AAB0}',
    '\u{AAB2}',
    '\u{AAB3}',
    '\u{AAB7}',
    '\u{AAB8}',
    '\u{AABE}',
    '\u{AABF}',
    '\u{AAC1}',
    '\u{FE20}',
    '\u{FE21}',
    '\u{FE22}',
    '\u{FE23}',
    '\u{FE24}',
    '\u{FE25}',
    '\u{FE26}',
    '\u{10A0F}',
    '\u{10A38}',
    '\u{1D185}',
    '\u{1D186}',
    '\u{1D187}',
    '\u{1D188}',
    '\u{1D189}',
    '\u{1D1AA}',
    '\u{1D1AB}',
    '\u{1D1AC}',
    '\u{1D1AD}',
    '\u{1D242}',
    '\u{1D243}',
    '\u{1D244}',
];

#[inline]
fn diacritic(y: u16) -> char {
    *DIACRITICS
        .get(usize::from(y))
        .unwrap_or_else(|| &DIACRITICS[0])
}

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

    /// A message with a video message `length` pixels wide.
    fn note_msg(length: u32) -> Msg {
        let (_, mut msg) = crate::messages::tests::page([1]).remove(0);
        msg.file = Some(MediaFile {
            id: 5,
            label: "Video message".into(),
            photo: false,
            downloaded: true,
        });
        msg.video = Some(Note {
            file_id: 5,
            size: 10,
            duration: 1,
            length,
        });
        msg
    }

    #[test]
    fn the_whole_window_plays_frames_no_bigger_than_the_video() {
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        let msg = note_msg(400);
        let view = VideoView::of(1, 1, &msg, tx, false, None, &Colors::default()).unwrap();
        // The terminal scales them to the cells.
        assert_eq!(view.frame_side((1400, 1380)), 400);
        assert_eq!(view.frame_side((300, 320)), 300, "smaller ones shrink");
    }

    #[test]
    fn the_circle_is_drawn_once_on_the_bubbles_color_and_ends_with_the_video() {
        let graph = round_graph(Round {
            side: 400,
            backdrop: [0x31, 0x32, 0x44],
        });
        assert!(graph.starts_with("scale=400:400,"), "{graph}");
        assert!(graph.contains("drawbox=c=0x313244:t=fill"), "{graph}");
        assert!(graph.contains("r=1:d=1,"), "one circle: {graph}");
        assert!(graph.contains("loop=-1:1"), "laid on every frame: {graph}");
        assert!(graph.contains("alphamerge=shortest=1"), "{graph}");
    }

    #[test]
    fn a_video_stickers_frame_is_read_only_as_a_local_webm() {
        let path = Path::new("/files/stickers/file_9.webm");
        let args = ffmpeg_still_args(path, false);
        let input = args.iter().position(|a| a == "-i").unwrap();
        let before = &args[..input];
        assert!(
            before
                .windows(2)
                .any(|w| w == ["-protocol_whitelist", "file"]),
            "{args:?}"
        );
        assert!(
            before.windows(2).any(|w| w == ["-f", "matroska,webm"]),
            "{args:?}"
        );
        assert!(!args.iter().any(|a| a == "-re"), "a still, not a stream");
        assert_eq!(args[input + 1], "file:/files/stickers/file_9.webm");
        let scale = &args[args.iter().position(|a| a == "-vf").unwrap() + 1];
        assert!(
            scale.contains("min(iw,512)") && scale.contains("min(ih,512)"),
            "no bigger than a sticker, whatever the file says: {scale}"
        );
        assert!(!before.iter().any(|a| a == "libvpx-vp9"));
    }

    #[test]
    fn a_video_sticker_keeps_its_transparency_where_ffmpeg_can() {
        let path = Path::new("/files/stickers/file_9.webm");
        for args in [
            ffmpeg_still_args(path, true),
            ffmpeg_loop_args(path, "scale=256:256,fps=30", true),
        ] {
            let input = args.iter().position(|a| a == "-i").unwrap();
            assert!(
                args[..input]
                    .windows(2)
                    .any(|w| w == ["-c:v", "libvpx-vp9"]),
                "decoded by libvpx, before the input: {args:?}"
            );
        }
        let plain = ffmpeg_loop_args(path, "scale=256:256,fps=30", false);
        assert!(!plain.iter().any(|a| a == "libvpx-vp9"), "{plain:?}");
    }

    #[test]
    fn a_video_sticker_loops_read_only_as_a_local_webm() {
        let path = Path::new("/files/stickers/file_9.webm");
        let args = ffmpeg_loop_args(path, "scale=256:256,fps=30", false);
        let input = args.iter().position(|a| a == "-i").unwrap();
        let before = &args[..input];
        assert!(
            before
                .windows(2)
                .any(|w| w == ["-protocol_whitelist", "file"]),
            "{args:?}"
        );
        assert!(
            before.windows(2).any(|w| w == ["-f", "matroska,webm"]),
            "{args:?}"
        );
        assert!(
            before.windows(2).any(|w| w == ["-stream_loop", "-1"]),
            "loops until it's stopped: {args:?}"
        );
        assert!(before.iter().any(|a| a == "-re"), "paced: {args:?}");
        assert!(!args.iter().any(|a| a == "-ss"), "always from the start");
        assert_eq!(args[input + 1], "file:/files/stickers/file_9.webm");
    }

    #[test]
    fn a_video_sticker_is_decoded_no_bigger_than_its_slot_needs() {
        assert_eq!(sticker_side(512, 512), (256, 256));
        assert_eq!(sticker_side(512, 256), (256, 128));
        assert_eq!(sticker_side(100, 200), (100, 200), "small as it is");
        assert_eq!(sticker_side(0, 0), (1, 1), "never nothing");
        assert_eq!(sticker_side(u32::MAX, 512), (256, 1), "whatever it claims");
    }

    #[test]
    fn a_video_sticker_plays_inline_without_telling_its_sender() {
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        let (_, mut msg) = crate::messages::tests::page([1]).remove(0);
        msg.preview = Some(crate::messages::Preview {
            file_id: 9,
            width: 512,
            height: 512,
            thumbnail: None,
            sticker: true,
        });
        msg.video_sticker = Some(9);
        let inline = Inline::of_sticker(1, 1, &msg, tx, false).unwrap();
        assert!(inline.is_sticker());
        assert!(!inline.tell, "nothing to tell");
        assert_eq!(inline.cut.size(), (256, 256));
        assert!(!inline.lost(1, 1, Some(&msg)));

        // The message edited into anything else loses it.
        msg.video_sticker = None;
        assert!(inline.lost(1, 1, Some(&msg)));
        assert!(inline.lost(1, 1, None), "deleted");

        // A message that isn't a video sticker has no inline sticker.
        let (_, msg) = crate::messages::tests::page([1]).remove(0);
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        assert!(Inline::of_sticker(1, 1, &msg, tx, false).is_none());
    }

    #[test]
    fn a_senders_file_is_read_only_as_a_local_mp4() {
        let path = Path::new("/files/video_notes/file_3.mp4");
        let args = ffmpeg_args(path, "0.000", "fps=30");
        let input = args.iter().position(|a| a == "-i").unwrap();
        let before = &args[..input];
        assert!(
            before
                .windows(2)
                .any(|w| w == ["-protocol_whitelist", "file"]),
            "{args:?}"
        );
        assert!(before.windows(2).any(|w| w == ["-f", "mov"]), "{args:?}");
        assert_eq!(args[input + 1], "file:/files/video_notes/file_3.mp4");

        let mut players = vec![mpv_args(path, "0.000")];
        #[cfg(unix)]
        players.push(pepper_args(
            path,
            "0.000",
            Round {
                side: 400,
                backdrop: [0, 0, 0],
            },
        ));
        for args in players {
            for wanted in [
                "--no-config",
                "--load-scripts=no",
                "--ytdl=no",
                "--demuxer=lavf",
                "--demuxer-lavf-format=mov",
                "--demuxer-lavf-o=protocol_whitelist=file",
            ] {
                assert!(args.iter().any(|a| a == wanted), "{wanted}: {args:?}");
            }
            assert_eq!(
                args[args.len() - 2..],
                ["--", "/files/video_notes/file_3.mp4"]
            );
        }
    }

    #[cfg(unix)]
    #[test]
    fn pepper_play_cuts_the_picture_round_on_the_bubbles_color() {
        let round = Round {
            side: 400,
            backdrop: [0x31, 0x32, 0x44],
        };
        let args = pepper_args(Path::new("/f.mp4"), "0.000", round);
        assert!(args.iter().any(|a| a == "--hwdec=no"), "{args:?}");
        assert!(
            args.iter().any(|a| a == "--background-color=#313244"),
            "{args:?}"
        );
        let vf = args
            .iter()
            .find_map(|a| a.strip_prefix("--vf=lavfi=graph=%"));
        let (len, graph) = vf.and_then(|v| v.split_once('%')).unwrap();
        // mpv reads as many bytes as the prefix says.
        assert_eq!(len.parse::<usize>().unwrap(), graph.len());
        assert_eq!(graph, round_graph(round));
    }

    #[test]
    fn a_senders_word_on_its_videos_size_is_kept_within_reason() {
        let note = |length| {
            Note::new(&VideoNote {
                duration: 8,
                waveform: String::new(),
                length,
                minithumbnail: None,
                thumbnail: None,
                speech_recognition_result: None,
                video: tdlib_rs::types::File::default(),
            })
        };
        assert_eq!(note(400).length, 400);
        // Each frame takes side × side × 4 bytes.
        assert_eq!(note(60_000).length, MAX_SIDE as u32);
        assert_eq!(note(-5).length, 1);
    }

    #[test]
    fn frames_go_into_the_players_own_folder_tagged_with_its_run() {
        let dir = crate::config::new_private_dir(&std::env::temp_dir(), "tuigram-test").unwrap();
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
        // Two frames of 2 × 2 pixels, then the end.
        let pipe = [255u8; 2 * 2 * 4 * 2];
        let stop = AtomicBool::new(false);
        pump_frames(
            &pipe[..],
            (2, 2),
            &dir,
            &AtomicU64::new(0),
            &stop,
            (TAG_INLINE, 7),
            &tx,
        );
        let events: Vec<VideoEvent> = std::iter::from_fn(|| rx.try_recv().ok()).collect();
        assert!(events.iter().all(|e| e.tag == TAG_INLINE && e.run == 7));
        let news: Vec<&News> = events.iter().map(|e| &e.news).collect();
        assert!(matches!(news[..], [News::Frame, News::Frame, News::Ended]));
        assert_eq!(std::fs::read(dir.join("frame.rgb")).unwrap().len(), 16);
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[cfg(unix)]
    #[test]
    fn what_pepper_play_says_is_read_as_decoder_words() {
        // As pepper-play 0.4.0 said it, playing a clip.
        let lines = [
            r#"{"data": null, "request_id": 0, "error": "success"}"#,
            r#"{"event": "start-file", "playlist_entry_id": 1}"#,
            r#"{"event": "property-change", "id": 1, "name": "time-pos", "data": null}"#,
            r#"{"event": "file-loaded"}"#,
            r#"{"event": "property-change", "id": 1, "name": "time-pos", "data": 0.5}"#,
            r#"{"event": "playback-restart"}"#,
            r#"{"event": "property-change", "id": 1, "name": "time-pos", "data": 1.92}"#,
            r#"{"event": "property-change", "id": 1, "name": "time-pos", "data": 1.95}"#,
            r#"{"event": "playback-restart"}"#,
            r#"{"event": "end-file", "reason": "eof", "playlist_entry_id": 1}"#,
        ];
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
        let seconds = AtomicU64::new(0);
        read_pepper(lines.join("\n").as_bytes(), &seconds, (TAG_VIEW, 3), &tx);
        let events: Vec<VideoEvent> = std::iter::from_fn(|| rx.try_recv().ok()).collect();
        assert!(events.iter().all(|e| e.tag == TAG_VIEW && e.run == 3));
        let news: Vec<&News> = events.iter().map(|e| &e.news).collect();
        // The time shown is drawn again each second, not each frame.
        assert!(
            matches!(news[..], [News::Frame, News::Moved, News::Ended]),
            "one start, one second"
        );
        assert_eq!(f64::from_bits(seconds.load(Relaxed)), 1.95);

        let failed = r#"{"event": "end-file", "reason": "error", "file_error": "loading failed"}"#;
        assert_eq!(said(failed), Some(Said::Failed("loading failed".into())));
        // It quit before the picture started: it couldn't play it.
        read_pepper(&b""[..], &seconds, (TAG_VIEW, 4), &tx);
        assert!(matches!(rx.try_recv().unwrap().news, News::Failed(_)));
    }

    #[cfg(unix)]
    #[test]
    fn a_video_message_pepper_play_cant_play_plays_as_kitty_frames() {
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
        let msg = note_msg(240);
        // A pepper-play that quits at once, as one without libmpv does.
        let quits = PathBuf::from("/bin/sh");
        let colors = Colors::default();
        let mut view = VideoView::of(1, 1, &msg, tx.clone(), false, Some(quits), &colors).unwrap();
        let path = Path::new("/nowhere/file_5.mp4");
        let run = spawn(
            path,
            0.0,
            Cut::Round(view.round),
            TAG_VIEW,
            tx,
            view.pepper.as_deref(),
        )
        .unwrap();
        assert!(run.frames().is_none(), "Pepper's player first");
        view.player = Some(run);
        let event = rx.blocking_recv().unwrap();
        assert!(view.on_event(event).is_ok(), "not an error to show");
        assert!(
            view.player.is_none() && view.pepper.is_none(),
            "kitty frames next"
        );
    }
}