heatsync-tui 0.4.0

heat-sorted live multichat in the terminal — twitch, kick + youtube (read-only), real emotes, vim keys
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
//! emote image layer — lazy background load (fetch → decode → scale → encode
//! protocols off the render thread), a shared animation clock, and visible-only
//! draw. the render thread only ever blits already-built frames; a raid can't
//! stall it.
//!
//! tier: ratatui-image auto-detects (sixel on foot, kitty where present, else
//! half-blocks). we hand it decoded frames, so no image codecs pulled here.
//!
//! three properties this module is responsible for:
//!   * DIMENSIONS — every emote is scaled to exactly its cell block in pixels and
//!     centred, so nothing is letterboxed into a corner, stretched, or upscaled
//!     from a too-small source. width is per-emote (real aspect), height uniform.
//!   * NO FLASH — frames of one emote share a single quantised palette, so the
//!     sixel encoder's error diffusion has nothing to diffuse and static regions
//!     encode byte-identically frame to frame (that shimmer IS the flashing).
//!     the draw budget freezes animation instead of blanking an emote.
//!   * FULL FPS — the event loop sleeps until the next frame boundary of the
//!     soonest-flipping emote, so playback runs at the emote's authored rate.

use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use std::sync::mpsc::{self, Receiver, Sender};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant};

use super::blit::Blitter;
use image::imageops::FilterType;
use image::{DynamicImage, RgbaImage};
use ratatui::layout::Rect;
use ratatui_image::picker::{Picker, ProtocolType};
use ratatui_image::protocol::Protocol;
use ratatui_image::Resize;

use super::decode;
use crate::http;

/// inline emote height in cells. 2 rows so emotes read big; messages containing
/// a ready emote get EMOTE_H rows in the layout. WIDTH is per-emote — derived
/// from the emote's real aspect and the terminal's cell aspect — so a square
/// emote renders square and a wide one isn't crushed into a square hole.
pub const EMOTE_H: u16 = 2;
/// widest an emote may get, in cells. a hostile 20:1 image can't eat the row.
const MAX_W: u16 = 8;
/// frames kept per emote. longer animations are resampled onto this many slots
/// at the same total duration — bounds memory and terminal-side image handles
/// without changing playback speed.
pub(crate) const MAX_FRAMES: usize = 120;
/// total encoded frames held across all emotes; the LRU trims past this. also
/// caps how many image ids live in a kitty terminal at once.
const MAX_LIVE_FRAMES: usize = 6000;
/// graphics blits per draw. exceeding it FREEZES animation on the frames already
/// shown — it never blanks an emote (a blank frame is exactly the flash we're
/// removing). a raid still can't firehose the pty.
const DRAW_BUDGET: usize = 96;
/// per-frame delay floor (50fps ceiling) — matches decode's floor so a malformed
/// emote can't spin the animator.
pub(crate) const MIN_DELAY_MS: u32 = 20;
/// colors in the shared per-emote palette. under sixel's 256 with headroom.
const PALETTE_COLORS: u32 = 200;

struct FrameProto {
    proto: Protocol,
    delay_ms: u32,
}

/// a fully built emote: its frames, its cell footprint, and its loop length.
struct Anim {
    frames: Vec<FrameProto>,
    w_cells: u16,
    total_ms: u64,
    /// last index actually drawn — what we freeze on when the budget runs out.
    shown: Cell<usize>,
    /// LRU stamp, bumped whenever the draw path touches this emote.
    used: Cell<u64>,
}

enum Entry {
    Loading,
    Ready(Anim),
    Failed,
}

struct Job {
    key: String, // one url, or base+overlay urls joined by '\n' (a stack)
}
struct Done {
    key: String,
    built: Option<Built>,
}
struct Built {
    frames: Vec<FrameProto>,
    w_cells: u16,
    total_ms: u64,
}

pub struct EmoteStore {
    proto: ProtocolType, // the detected inline-graphics protocol (for the tier readout)
    /// inside tmux the attached client can change at any time — detach from
    /// foot, reattach over mosh from a phone — and our frames are encoded for
    /// the protocol probed at startup. a watcher THREAD re-asks tmux every 2s
    /// and stores the answer here; the render thread only ever reads the flag,
    /// so the subprocess spawn can never hitch a frame.
    tmux: bool,
    /// tmux draws sixel itself (raw sixel in, tmux's own grid owns the pixels).
    native: bool,
    outer_ok: Arc<AtomicBool>,
    /// where this pane's top-left cell sits on the OUTER terminal, packed
    /// (col << 16 | row); `NO_OFFSET` when unknown or the pane isn't visible.
    /// kept fresh by the watcher thread, which a resize wakes at once.
    pane_off: Arc<AtomicU32>,
    watcher: Option<thread::Thread>,
    /// the frame size the last blit saw — a change means the offset is stale.
    last_area: Cell<Rect>,
    /// footprint of a 1:1 emote in cells. the layout reserves this BEFORE an
    /// emote finishes loading, so nothing reflows when the image lands.
    square_w: u16,
    cache: HashMap<String, Entry>,
    jobs: Sender<Job>,
    done: Receiver<Done>,
    start: Instant,
    /// animation clock snapshotted once per draw, so every emote in a frame is
    /// sampled at the SAME instant (deterministic frame, exact flip scheduling).
    now_ms: Cell<u64>,
    /// soonest ms-to-flip among the animated emotes ACTUALLY DRAWN this frame,
    /// recorded by frame() as a free by-product of picking the frame index. this
    /// is what the event loop sleeps on — off-screen animations never wake it.
    next_flip_ms: Cell<u64>,
    // interior-mutable so frame() can run inside ratatui's immutable draw pass.
    budget_left: Cell<usize>,
    lru: Cell<u64>,
    /// LRU watermark at the start of the previous frame — anything touched
    /// since then was ON SCREEN, and eviction must never take it (reloading a
    /// visible emote is exactly the name↔image flicker we removed).
    frame_mark: Cell<u64>,
    live_frames: usize,
    /// sixel placements queued by this draw (see blit.rs).
    blit: RefCell<Blitter>,
}

impl EmoteStore {
    /// probe the terminal for graphics support. `None` → no protocol (text only).
    /// must be called BEFORE raw mode / alt screen.
    ///
    /// we ONLY run the stdin capability query on terminals we know will answer
    /// it. Picker's query spawns a reader thread that, on a terminal that never
    /// responds (linux tty, dumb ssh, plain xterm), lingers blocked on stdin and
    /// steals our keypresses → a hang. env-gating sidesteps that entirely: any
    /// terminal we can't positively identify as graphics-capable gets text mode.
    pub fn new() -> Option<EmoteStore> {
        // build a Picker for the terminal's inline-graphics protocol. inside tmux
        // we must NOT run the stdio capability query: its reader thread lingers on
        // stdin and steals keypresses (dead keyboard). instead we learn the OUTER
        // terminal from tmux and the cell pixel size from an ioctl — both stdin-
        // free — and force the matching protocol. from_fontsize still reads the
        // env-detected is_tmux, so output is wrapped in tmux passthrough and
        // reaches the outer terminal intact.
        let picker = if std::env::var_os("TMUX").is_some() {
            let (proto, _) = tmux_outer_protocol()?;
            let mut p = Picker::from_fontsize(cell_pixels()?);
            p.set_protocol_type(proto);
            p
        } else {
            if !graphics_capable_env() {
                return None;
            }
            Picker::from_query_stdio().ok()?
        };
        let proto = picker.protocol_type();
        // a terminal that only offers halfblocks renders emotes as blocky mush;
        // clean text names read better, so fall back to text in that case.
        if proto == ProtocolType::Halfblocks {
            return None;
        }
        let (cw, ch) = picker.font_size();
        let square_w = width_cells(1.0, cw, ch);
        let (jobs_tx, jobs_rx) = mpsc::channel::<Job>();
        let (done_tx, done_rx) = mpsc::channel::<Done>();
        // a small loader pool: fetch + decode + scale + encode off the render
        // thread. joining a channel drops ~30 jobs at once; one thread built
        // them serially and emotes trickled in — a few threads (network-bound
        // work) make the whole set land near-simultaneously. capped low so a
        // passive-cooled box never spins every core on decode.
        let jobs_rx = Arc::new(Mutex::new(jobs_rx));
        let workers = thread::available_parallelism()
            .map(|n| n.get())
            .unwrap_or(2)
            .clamp(2, 4);
        let tmux = std::env::var_os("TMUX").is_some();
        // sixel through tmux needs its passthrough wrapper re-escaped before it
        // is a legal escape sequence at all — see fix_tmux_passthrough.
        // unless tmux owns sixel itself (see tmux_outer_protocol_now): then the
        // crate's wrapper is peeled off and tmux gets the plain sixel.
        let native = tmux
            && proto == ProtocolType::Sixel
            && tmux_outer_protocol_now().is_some_and(|o| o.is_some_and(|(_, n)| n));
        let wrap = match (tmux && proto == ProtocolType::Sixel, native) {
            (true, true) => SixelWrap::Native,
            (true, false) => SixelWrap::Passthrough,
            _ => SixelWrap::Bare,
        };
        for _ in 0..workers {
            let rx = Arc::clone(&jobs_rx);
            let tx = done_tx.clone();
            let p = picker.clone();
            thread::spawn(move || loader(p, rx, tx, wrap));
        }
        let outer_ok = Arc::new(AtomicBool::new(true));
        let pane_off = Arc::new(AtomicU32::new(NO_OFFSET));
        let mut watcher = None;
        if tmux {
            // the attached-client watcher. asking tmux means fork+exec — done on
            // the render thread that was a guaranteed frame hitch every TTL.
            let flag = Arc::clone(&outer_ok);
            let off = Arc::clone(&pane_off);
            let h = thread::spawn(move || loop {
                // no client attached → keep the last answer (nobody is looking).
                if let Some(o) = tmux_outer_protocol_now() {
                    let same = o.is_some_and(|(p, n)| {
                        p == proto && (n == native || proto != ProtocolType::Sixel)
                    });
                    flag.store(same, Ordering::Relaxed);
                }
                off.store(
                    pane_offset().map_or(NO_OFFSET, |(x, y)| u32::from(x) << 16 | u32::from(y)),
                    Ordering::Relaxed,
                );
                thread::park_timeout(Duration::from_secs(2));
            });
            watcher = Some(h.thread().clone());
        }
        Some(EmoteStore {
            proto,
            tmux,
            native,
            outer_ok,
            pane_off,
            watcher,
            last_area: Cell::new(Rect::default()),
            square_w,
            cache: HashMap::new(),
            jobs: jobs_tx,
            done: done_rx,
            start: Instant::now(),
            now_ms: Cell::new(0),
            next_flip_ms: Cell::new(u64::MAX),
            budget_left: Cell::new(DRAW_BUDGET),
            lru: Cell::new(0),
            frame_mark: Cell::new(0),
            live_frames: 0,
            blit: RefCell::new(Blitter::default()),
        })
    }

    /// the footprint a not-yet-loaded emote is laid out at: square, since most
    /// emotes are. reserving space up front is what stops the chat from jumping
    /// (and every sixel below from being re-emitted) as images arrive.
    pub fn square_cells(&self) -> u16 {
        self.square_w
    }

    /// can the terminal that is on screen RIGHT NOW display our frames?
    /// outside tmux the terminal can't change under us — always true. inside
    /// tmux the session outlives any one client: started from foot, later
    /// reattached over mosh from termux, the sixel/kitty escapes we emit reach
    /// a terminal that silently drops them and every emote is a blank hole.
    /// the watcher thread re-asks tmux every 2s and reports false while the
    /// outer terminal can't render the protocol our frames are encoded in —
    /// the caller then draws the text tier (emote names) instead. this read is
    /// a single atomic load: nothing here can stall a frame.
    pub fn usable(&self) -> bool {
        !self.tmux || self.outer_ok.load(Ordering::Relaxed)
    }

    /// is it safe to wrap frames in synchronized output? bare terminals: yes.
    /// tmux repaints the whole pane when a sync frame ends, which wipes passthrough
    /// images tmux can't see — but images tmux owns survive its own repaint.
    pub fn sync_ok(&self) -> bool {
        !self.tmux || self.native
    }

    /// a short label for the detected graphics protocol (startup tier readout).
    pub fn tier_label(&self) -> &'static str {
        match self.proto {
            ProtocolType::Sixel => "sixel",
            ProtocolType::Kitty => "kitty",
            ProtocolType::Iterm2 => "iterm2",
            ProtocolType::Halfblocks => "halfblocks",
        }
    }

    /// ensure an emote (or overlay stack) is being loaded (idempotent). `key` is a
    /// single url or base+overlay urls joined by '\n'. called during the tick.
    pub fn request(&mut self, key: &str) {
        if self.cache.contains_key(key) {
            return;
        }
        self.cache.insert(key.to_string(), Entry::Loading);
        // if the loader thread died the send fails — mark failed, fall to text.
        if self
            .jobs
            .send(Job {
                key: key.to_string(),
            })
            .is_err()
        {
            self.cache.insert(key.to_string(), Entry::Failed);
        }
    }

    /// drain finished loads into the cache. called on the data tick. returns true
    /// if ≥1 emote finished loading (the caller forces a full re-emit — see below).
    pub fn pump(&mut self) -> bool {
        let mut loaded = false;
        let stamp = self.lru.get();
        while let Ok(d) = self.done.try_recv() {
            let entry = match d.built {
                Some(b) if !b.frames.is_empty() => {
                    self.live_frames += b.frames.len();
                    Entry::Ready(Anim {
                        frames: b.frames,
                        w_cells: b.w_cells,
                        total_ms: b.total_ms,
                        shown: Cell::new(0),
                        used: Cell::new(stamp),
                    })
                }
                _ => Entry::Failed,
            };
            if let Some(Entry::Ready(old)) = self.cache.insert(d.key, entry) {
                self.live_frames -= old.frames.len(); // a re-request replacing itself
            }
            loaded = true;
        }
        if loaded {
            self.evict();
        }
        loaded
    }

    /// trim least-recently-drawn emotes until the live frame count is back under
    /// budget. bounds our memory AND the number of images the terminal holds.
    /// emotes drawn since the last frame are exempt — evicting one would force
    /// a reload of something the user is looking at, which flashes its name
    /// while the image rebuilds. the soft cap can therefore be exceeded by at
    /// most one screenful.
    fn evict(&mut self) {
        if self.live_frames <= MAX_LIVE_FRAMES {
            return;
        }
        let mark = self.frame_mark.get();
        let mut aged: Vec<(u64, String)> = self
            .cache
            .iter()
            .filter_map(|(k, e)| match e {
                Entry::Ready(a) if a.used.get() < mark => Some((a.used.get(), k.clone())),
                _ => None,
            })
            .collect();
        aged.sort_unstable_by_key(|(used, _)| *used);
        for (_, key) in aged {
            if self.live_frames <= MAX_LIVE_FRAMES {
                break;
            }
            if let Some(Entry::Ready(a)) = self.cache.remove(&key) {
                self.live_frames -= a.frames.len();
            }
        }
    }

    /// start a draw: snapshot the animation clock and reset the blit budget. every
    /// emote in this frame is then sampled at the same instant. the LRU watermark
    /// taken here is what marks "touched since last frame" = on screen.
    pub fn begin_frame(&self) {
        self.now_ms.set(self.start.elapsed().as_millis() as u64);
        self.budget_left.set(DRAW_BUDGET);
        self.next_flip_ms.set(u64::MAX);
        self.frame_mark.set(self.lru.get());
    }

    /// how long until the soonest-flipping emote DRAWN LAST FRAME changes frame.
    /// the event loop sleeps exactly this long, so on-screen animations run at
    /// their authored fps — while animated emotes in unfocused channels (still
    /// cached, never drawn) schedule nothing and cost nothing.
    pub fn next_flip_in(&self) -> Option<Duration> {
        let soonest = self.next_flip_ms.get();
        (soonest != u64::MAX).then(|| Duration::from_millis(soonest.max(1)))
    }

    /// this emote/stack's width in cells, or None if it isn't loaded yet. doubles
    /// as the readiness check — a caller that gets a width can lay it out.
    pub fn cells(&self, key: &str) -> Option<u16> {
        match self.cache.get(key) {
            Some(Entry::Ready(a)) => {
                self.touch(a);
                Some(a.w_cells)
            }
            _ => None,
        }
    }

    /// the protocol for this emote/stack's current animation frame. a ready emote
    /// ALWAYS yields a frame — when the blit budget is spent it yields the one
    /// already on screen (a frozen emote, never a blank hole).
    pub fn frame(&self, key: &str) -> Option<&Protocol> {
        let Some(Entry::Ready(a)) = self.cache.get(key) else {
            return None;
        };
        self.touch(a);
        let idx = if a.frames.len() == 1 {
            0
        } else {
            let left = self.budget_left.get();
            if left == 0 {
                // frozen, not skipped: retry at the fps floor so a burst that
                // exhausts the budget can't park animations on the data tick.
                self.next_flip_ms
                    .set(self.next_flip_ms.get().min(MIN_DELAY_MS as u64));
                a.shown.get().min(a.frames.len() - 1)
            } else {
                self.budget_left.set(left - 1);
                let (idx, flip_in) = frame_at(&a.frames, self.now_ms.get(), a.total_ms);
                self.next_flip_ms.set(self.next_flip_ms.get().min(flip_in));
                idx
            }
        };
        a.shown.set(idx);
        Some(&a.frames[idx].proto)
    }

    /// is this emote's current frame a sixel? those skip the widget path: draw
    /// reserves NBSP cells and queues the image for `blit` instead.
    pub fn is_sixel(&self, key: &str) -> bool {
        matches!(self.cache.get(key), Some(Entry::Ready(a))
            if matches!(a.frames[a.shown.get().min(a.frames.len() - 1)].proto, Protocol::Sixel(_)))
    }

    /// can rows of this pane be scrolled for real? sixel only, and only where
    /// the terminal (or tmux, which keeps sixel in its own grid) owns the
    /// pixels — passthrough images are invisible to tmux's scroll.
    pub fn scroll_ok(&self) -> bool {
        self.proto == ProtocolType::Sixel && self.sync_ok()
    }

    /// the terminal scrolled rows `top..top+h` up by `k` (see blit.rs).
    pub fn shift_blits(&self, top: u16, h: u16, k: u16) -> bool {
        self.blit.borrow_mut().shift_up(top, h, k)
    }

    /// queue the emote's current frame (the one `frame` just picked) at `rect`.
    pub fn queue_blit(&self, rect: Rect, key: &str) {
        if let Some(Entry::Ready(a)) = self.cache.get(key) {
            self.blit.borrow_mut().push(rect, key, a.shown.get());
        }
    }

    /// after the text of a draw has flushed: write the queued sixels that
    /// changed, and only those. `area` is the frame size (a resize repaints
    /// everything, so everything is re-emitted).
    pub fn blit(&self, area: Rect, out: &mut impl std::io::Write) -> std::io::Result<()> {
        if self.last_area.replace(area) != area {
            // resized or moved: the offset is stale until the watcher re-asks.
            self.pane_off.store(NO_OFFSET, Ordering::Relaxed);
            if let Some(w) = &self.watcher {
                w.unpark();
            }
        }
        let emits = self.blit.borrow_mut().take_emits(area);
        let off = self.pane_off.load(Ordering::Relaxed);
        let off = (off != NO_OFFSET).then_some(((off >> 16) as u16, off as u16));
        if emits.is_empty() {
            return Ok(());
        }
        for q in emits {
            let Some(Entry::Ready(a)) = self.cache.get(&q.key) else {
                continue;
            };
            let Some(f) = a.frames.get(q.idx) else {
                continue;
            };
            if let Protocol::Sixel(s) = &f.proto {
                // under tmux-native sixel a fresh image over tmux's stored one
                // makes tmux delete and repaint it — a flash per animation
                // frame. frames that only replace the previous one in place go
                // around tmux as passthrough instead: foot paints over the
                // old pixels, tmux never sees an overlap.
                // passthrough lands at the OUTER cursor, so it carries its own
                // absolute position; with the pane offset unknown (stale after
                // a resize, pane hidden) the frame goes native instead.
                let wrapped = off
                    .filter(|_| q.in_place && self.tmux && self.native)
                    .map(|o| passthrough_in_place(&s.data, o, (q.rect.x, q.rect.y)));
                if let Some(w) = &wrapped {
                    crossterm::queue!(out, crossterm::style::Print(w))?;
                } else {
                    crossterm::queue!(
                        out,
                        crossterm::cursor::MoveTo(q.rect.x, q.rect.y),
                        crossterm::style::Print(&s.data)
                    )?;
                }
            }
        }
        out.flush()
    }

    fn touch(&self, a: &Anim) {
        let t = self.lru.get() + 1;
        self.lru.set(t);
        a.used.set(t);
    }
}

/// cell size in pixels via TIOCGWINSZ (crossterm reads the tty geometry, never
/// stdin). None when the terminal reports no pixel dimensions to divide by.
fn cell_pixels() -> Option<(u16, u16)> {
    let ws = crossterm::terminal::window_size().ok()?;
    if ws.width == 0 || ws.height == 0 || ws.columns == 0 || ws.rows == 0 {
        return None;
    }
    Some((ws.width / ws.columns, ws.height / ws.rows))
}

/// inside tmux, ask tmux for the attached client's terminal (the OUTER emulator,
/// which tmux masks behind TERM=tmux-256color) and map it to a forced graphics
/// protocol: kitty for kitty/ghostty, sixel for foot/wezterm/mlterm/contour.
/// None → the outer terminal isn't a known graphics-capable one → text tier.
/// this is how we get inline emotes in tmux without a stdin-stealing query.
fn tmux_outer_protocol() -> Option<(ProtocolType, bool)> {
    tmux_outer_protocol_now().flatten()
}

/// like [`tmux_outer_protocol`], but keeps "couldn't ask tmux / no client
/// attached" (outer None) apart from "a client is attached and it has no
/// graphics" (Some(None)) — the runtime re-check must not flip the tier on a
/// momentary detach.
///
/// the bool is "tmux draws sixel itself": tmux >= 3.4 built with sixel lists
/// `sixel` in the client's termfeatures, parses sixel an app prints into the
/// pane, keeps it in its own grid and re-emits it on every redraw. raw sixel
/// then survives pane repaints; passthrough sixel (invisible to tmux) doesn't.
fn tmux_outer_protocol_now() -> Option<Option<(ProtocolType, bool)>> {
    let out = std::process::Command::new("tmux")
        .args([
            "display-message",
            "-p",
            "#{client_termname}|#{client_termfeatures}",
        ])
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    let text = String::from_utf8_lossy(&out.stdout).trim().to_lowercase();
    let (term, feats) = text.split_once('|').unwrap_or((&text, ""));
    let native = feats.split(',').any(|f| f == "sixel");
    // prefer kitty (flicker-free, in-place image updates) wherever the outer
    // terminal supports it; sixel only where that's the terminal's best option.
    Some(
        if term.contains("kitty") || term.contains("ghostty") || term.contains("wezterm") {
            Some((ProtocolType::Kitty, false))
        } else if term.starts_with("foot") || term.contains("mlterm") || term.contains("contour") {
            Some((ProtocolType::Sixel, native))
        } else {
            None
        },
    )
}

/// how a frame's sixel reaches the outer terminal.
#[derive(Clone, Copy)]
enum SixelWrap {
    /// no tmux: the crate's output as is.
    Bare,
    /// tmux without sixel support: DCS passthrough, re-escaped (see below).
    Passthrough,
    /// tmux that draws sixel itself: plain sixel, tmux owns the pixels.
    Native,
}

/// peel the crate's passthrough wrapper off a sixel so tmux sees the plain
/// sixel and keeps it in its own grid (redrawn with the pane, never torn by a
/// repaint). cleared cells first, same as the passthrough path, so a loading
/// placeholder name can't show through. non-matching shapes are left alone.
fn unwrap_tmux_passthrough(proto: &mut Protocol) {
    let Protocol::Sixel(s) = proto else {
        return;
    };
    let Some(sixel) = s
        .data
        .strip_prefix("\x1bPtmux;\x1b\x1b")
        .and_then(|d| d.strip_suffix("\x1b\\"))
        .filter(|d| d.starts_with("\x1bP") && d.ends_with("\x1b\\"))
    else {
        return;
    };
    s.data = format!("{}{sixel}", erase_block(s.area.width, s.area.height));
    s.is_tmux = false;
}

/// re-escape ratatui-image's tmux passthrough wrapper. THIS is the flicker.
///
/// passthrough is `ESC Ptmux;` + payload + `ESC \`, and every ESC inside the
/// payload must be DOUBLED — tmux halves them again and forwards the result to
/// the outer terminal, ending the sequence at the first undoubled `ESC \`.
/// ratatui-image 8.1.1 only doubles the sixel's LEADING escape; the `ESC \`
/// that terminates the sixel itself is left single. so tmux ends the
/// passthrough on the sixel's own terminator and forwards a sixel with NO
/// string terminator. foot then sits in sixel-parsing state consuming whatever
/// tmux writes next — our chat text — as image data, until the next emote's
/// stray terminator finally closes it. text disappears into images, images land
/// a frame late: that's the flicker.
///
/// so unwrap what the crate built and re-wrap it correctly. anything that
/// doesn't match the crate's exact shape is left untouched, so a future encoder
/// change degrades to today's behaviour instead of emitting a mangled escape.
///
/// the sixel is also prefixed with an ERASE of its own cell block, because a
/// second thing goes wrong under tmux. while an emote loads, the layout parks
/// the truncated name in the cells it reserved; the frame it turns ready, the
/// layout writes spaces there instead — but ratatui-image marks every cell of
/// an image `skip`, so ratatui never EMITS those spaces and the name is never
/// erased. in a bare terminal the pixels simply cover the stale glyphs. tmux is
/// not a bare terminal: passthrough pixels are invisible to it, its own screen
/// still holds the name, and it repaints that name over the emote. erasing the
/// block from inside the same string fixes the ordering for good — one cursor
/// save, `ECH` per row, restore, then the pixels land on cleared cells.
fn fix_tmux_passthrough(proto: &mut Protocol) {
    let Protocol::Sixel(s) = proto else {
        return;
    };
    if !s.is_tmux {
        return;
    }
    let Some(sixel) = s
        .data
        .strip_prefix("\x1bPtmux;\x1b\x1b")
        .and_then(|d| d.strip_suffix("\x1b\\"))
    else {
        return;
    };
    s.data = format!(
        "{}\x1bPtmux;{}\x1b\\",
        erase_block(s.area.width, s.area.height),
        sixel.replace('\x1b', "\x1b\x1b")
    );
}

/// packed pane offset meaning "unknown".
const NO_OFFSET: u32 = u32::MAX;

/// tmux format: visible flag, pane left/top, and rows a top status line takes.
const PANE_FMT: &str = "#{&&:#{window_active},#{pane_active}} #{pane_left} #{pane_top} \
#{?#{==:#{status-position},top},#{?#{==:#{status},off},0,#{?#{==:#{status},on},1,#{status}}},0}";

/// where this pane's top-left cell is on the outer terminal, None when the pane
/// isn't the visible one (tmux with `allow-passthrough on` drops hidden panes'
/// passthrough, `all` forwards it — to the wrong place).
fn pane_offset() -> Option<(u16, u16)> {
    let pane = std::env::var("TMUX_PANE").ok()?;
    let out = std::process::Command::new("tmux")
        .args(["display-message", "-p", "-t", &pane, PANE_FMT])
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    parse_pane_offset(&String::from_utf8_lossy(&out.stdout))
}

fn parse_pane_offset(s: &str) -> Option<(u16, u16)> {
    let mut f = s.split_whitespace();
    let visible = f.next()? == "1";
    let left: u16 = f.next()?.parse().ok()?;
    let top: u16 = f.next()?.parse().ok()?;
    let status: u16 = f.next()?.parse().ok()?;
    visible.then_some((left, top + status))
}

/// a native-mode sixel (erase block + plain sixel) as tmux passthrough: the
/// erase is dropped (the cells are already blank, the opaque frame covers the
/// old one). tmux forwards the payload to the outer terminal at the OUTER
/// cursor, so it saves that cursor, jumps to the absolute cell (pane offset +
/// rect, 1-based), paints, and restores — all inside the passthrough. every ESC
/// is doubled so tmux forwards the sixel intact.
fn passthrough_in_place(native: &str, off: (u16, u16), at: (u16, u16)) -> String {
    let sixel = native.find("\x1bP").map_or(native, |i| &native[i..]);
    let payload = format!(
        "\x1b7\x1b[{};{}H{sixel}\x1b8",
        off.1 + at.1 + 1,
        off.0 + at.0 + 1
    );
    format!("\x1bPtmux;{}\x1b\\", payload.replace('\x1b', "\x1b\x1b"))
}

/// blank a `w`x`h` cell block at the cursor and leave the cursor exactly where
/// it started. DECSC/DECRC rather than cursor-up: at the bottom of the screen a
/// cursor-down is clamped and the matching cursor-up would land a row high,
/// dropping the image one row off its cells.
fn erase_block(w: u16, h: u16) -> String {
    if w == 0 || h == 0 {
        return String::new();
    }
    let mut out = String::from("\x1b7"); // DECSC — save cursor
    for row in 0..h {
        out.push_str(&format!("\x1b[{w}X")); // ECH — erase w cells, cursor stays
        if row + 1 < h {
            out.push_str("\x1b[B"); // CUD — next row of the block
        }
    }
    out.push_str("\x1b8"); // DECRC — restore cursor
    out
}

/// heuristic: is this terminal known to support (and answer a query for) an
/// inline-graphics protocol? conservative — false for anything unrecognized,
/// including the linux tty (`TERM=linux`), which has no graphics and only 16
/// colors. detection is env-only; we never touch stdin here.
fn graphics_capable_env() -> bool {
    let e = |k: &str| std::env::var(k).ok().filter(|v| !v.is_empty());
    let term = e("TERM").unwrap_or_default();
    let prog = e("TERM_PROGRAM").unwrap_or_default();

    // kitty graphics protocol
    if e("KITTY_WINDOW_ID").is_some() || term.contains("kitty") || term.contains("ghostty") {
        return true;
    }
    // foot (sixel)
    if term.starts_with("foot") {
        return true;
    }
    // wezterm (sixel/kitty/iterm2)
    if prog == "WezTerm" || e("WEZTERM_EXECUTABLE").is_some() {
        return true;
    }
    // iterm2 / mintty (iterm2 inline images)
    if prog == "iTerm.app" || e("ITERM_SESSION_ID").is_some() || term.contains("mintty") {
        return true;
    }
    // other sixel-capable emulators
    if term.contains("mlterm") || term.contains("contour") || term.contains("st-") {
        return true;
    }
    // VTE (gnome-terminal etc.) gained sixel in 0.78 → VTE_VERSION >= 7800
    if let Some(v) = e("VTE_VERSION") {
        if v.parse::<u32>().map(|n| n >= 7800).unwrap_or(false) {
            return true;
        }
    }
    false
}

/// the frame showing at `now_ms` (cumulative-delay window, looping) and how many
/// ms remain before it flips. `(0, u64::MAX)` for a static image — nothing to
/// schedule.
fn frame_at(frames: &[FrameProto], now_ms: u64, total_ms: u64) -> (usize, u64) {
    if frames.len() <= 1 || total_ms == 0 {
        return (0, u64::MAX);
    }
    let mut t = now_ms % total_ms;
    for (i, f) in frames.iter().enumerate() {
        let d = f.delay_ms.max(MIN_DELAY_MS) as u64;
        if t < d {
            return (i, d - t);
        }
        t -= d;
    }
    (0, 1)
}

/// how wide, in cells, an emote of this aspect ratio should be so that it renders
/// at its true proportions in a terminal whose cells are `cw`×`ch` pixels. this is
/// the whole fix for "square emotes look squashed": cells are ~1:2, so a square
/// emote spanning EMOTE_H rows needs ≈ EMOTE_H·ch/cw columns, not a fixed 3.
pub(crate) fn width_cells(aspect: f32, cw: u16, ch: u16) -> u16 {
    let block_h = (EMOTE_H as f32) * (ch.max(1) as f32);
    let want_px = block_h * aspect.max(0.01);
    ((want_px / cw.max(1) as f32).round() as i64).clamp(1, MAX_W as i64) as u16
}

/// scale `src` to fit inside `tw`×`th` preserving aspect, then CENTRE it on a
/// fully transparent canvas of exactly that size. two things matter here:
/// the output is always exactly the cell block in pixels (so the encoder does no
/// resizing of its own and the cell footprint is deterministic), and the image is
/// centred rather than shoved into the top-left with dead space below it.
pub(crate) fn fit_center(src: &RgbaImage, tw: u32, th: u32) -> RgbaImage {
    let (sw, sh) = src.dimensions();
    let mut canvas = RgbaImage::new(tw.max(1), th.max(1));
    if sw == 0 || sh == 0 {
        return canvas;
    }
    let ratio = (tw as f32 / sw as f32).min(th as f32 / sh as f32);
    let nw = ((sw as f32 * ratio).round() as u32).clamp(1, tw.max(1));
    let nh = ((sh as f32 * ratio).round() as u32).clamp(1, th.max(1));
    // Lanczos3 for downscales (crisp, and — unlike Nearest — stable frame to
    // frame, so a moving edge doesn't pop pixels on and off); Triangle when
    // enlarging, which stays smooth instead of ringing.
    let filter = if ratio < 1.0 {
        FilterType::Lanczos3
    } else {
        FilterType::Triangle
    };
    let scaled = if (nw, nh) == (sw, sh) {
        src.clone()
    } else {
        image::imageops::resize(src, nw, nh, filter)
    };
    // replace, not overlay — copy alpha verbatim onto the empty canvas.
    image::imageops::replace(
        &mut canvas,
        &scaled,
        ((tw - nw) / 2) as i64,
        ((th - nh) / 2) as i64,
    );
    canvas
}

/// alpha-composite an rgba frame onto black (premultiply), making it opaque so
/// sixel renders no transparent fringe and each animation frame fully overwrites.
pub(crate) fn flatten_onto_black(img: &mut RgbaImage) {
    for px in img.pixels_mut() {
        let a = px[3] as u16;
        px[0] = (px[0] as u16 * a / 255) as u8;
        px[1] = (px[1] as u16 * a / 255) as u8;
        px[2] = (px[2] as u16 * a / 255) as u8;
        px[3] = 255;
    }
}

/// pixels NeuQuant should see before it is allowed to start skipping any.
const TRAIN_PX: usize = 20_000;

/// NeuQuant's sampling factor: it learns the palette from a 1-in-N pixel
/// sample, so N trades quality for speed. a FIXED factor is the trap — it reads
/// as cheap on a photo and ruinous here, because an emote block is tiny (a 4x2
/// cell block is ~1.4k pixels, so a two-frame animation at 1-in-10 trains a
/// 200-colour palette on ~280 pixels and comes back banded and muddy). scale
/// the factor to the pixel count instead: small emotes train on everything,
/// long animations still get the order-of-magnitude skip they were given it for.
fn train_factor(px: usize) -> i32 {
    (px / TRAIN_PX).clamp(1, 10) as i32
}

/// collapse every frame of ONE emote onto a single shared palette.
///
/// this is the anti-flash fix. sixel encoders pick a palette per image and
/// error-diffuse (dither) into it; run that independently on consecutive frames
/// of an animation and identical regions come out with different dither noise
/// every frame — the emote boils/shimmers even where nothing moves. quantising
/// all frames against one palette up front leaves the encoder with ≤256 exact
/// colors and ~zero diffusion error, so unchanged pixels encode identically and
/// only real motion changes on screen.
pub(crate) fn stabilize_palette(frames: &mut [RgbaImage]) {
    if frames.len() < 2 {
        return;
    }
    let total: usize = frames.iter().map(|f| f.as_raw().len()).sum();
    let mut sample: Vec<u8> = Vec::with_capacity(total);
    for f in frames.iter() {
        sample.extend_from_slice(f.as_raw());
    }
    if sample.is_empty() {
        return;
    }
    let nq = color_quant::NeuQuant::new(
        train_factor(sample.len() / 4),
        PALETTE_COLORS as usize,
        &sample,
    );
    let map = nq.color_map_rgba();
    // memoize color→palette lookups: index_of is a search per call, and an
    // animation repeats the same few hundred distinct colors across every
    // frame. one lookup per distinct color instead of one per pixel.
    let mut memo: HashMap<[u8; 4], [u8; 3]> = HashMap::new();
    for f in frames.iter_mut() {
        for px in f.pixels_mut() {
            let key = px.0;
            let rgb = *memo.entry(key).or_insert_with(|| {
                let i = nq.index_of(&key) * 4;
                if i + 2 < map.len() {
                    [map[i], map[i + 1], map[i + 2]]
                } else {
                    [key[0], key[1], key[2]]
                }
            });
            px.0 = [rgb[0], rgb[1], rgb[2], key[3]];
        }
    }
}

/// alpha-composite `over` onto `base` in place (standard src-over). both must be
/// the same dimensions. used to stack zero-width (overlay) emotes on their base.
fn alpha_over(base: &mut RgbaImage, over: &RgbaImage) {
    for (b, o) in base.pixels_mut().zip(over.pixels()) {
        let oa = o[3] as u16;
        let ia = 255 - oa;
        for c in 0..3 {
            b[c] = ((o[c] as u16 * oa + b[c] as u16 * ia) / 255) as u8;
        }
        b[3] = (oa + b[3] as u16 * ia / 255) as u8;
    }
}

/// which frame of a decoded layer is showing at `t_ms` (cumulative-delay window,
/// looping) — lets overlay layers be sampled against the driver's timeline.
fn sample_frame(frames: &[decode::Frame], t_ms: u64) -> usize {
    if frames.len() <= 1 {
        return 0;
    }
    let total: u64 = frames
        .iter()
        .map(|f| f.delay_ms.max(MIN_DELAY_MS) as u64)
        .sum();
    if total == 0 {
        return 0;
    }
    let mut t = t_ms % total;
    for (i, f) in frames.iter().enumerate() {
        let d = f.delay_ms.max(MIN_DELAY_MS) as u64;
        if t < d {
            return i;
        }
        t -= d;
    }
    0
}

/// emote CDNs serve fixed size tiers and the emote set hands us the smallest
/// (1x = 32px). that's pixel-perfect on an 8×16 cell but has to be UPSCALED —
/// i.e. blurred — on terminals with larger cells. pick the smallest tier that
/// covers `min_px`. None → the url shape is unknown, or 1x already covers it.
fn source_url(url: &str, min_px: u32) -> Option<String> {
    if min_px <= 34 {
        return None; // 1x is 32px — already at or above the target
    }
    let swap = |from: &str, to: &str| {
        let s = url.replacen(from, to, 1);
        (s != url).then_some(s)
    };
    if url.contains("cdn.7tv.app") {
        let t = if min_px > 96 {
            "/4x"
        } else if min_px > 64 {
            "/3x"
        } else {
            "/2x"
        };
        return swap("/1x", t);
    }
    if url.contains("betterttv.net") {
        return swap("/1x", if min_px > 64 { "/3x" } else { "/2x" });
    }
    if url.contains("frankerfacez.com") {
        // ffz publishes 1, 2 and 4 only.
        let t = if min_px > 64 { "4" } else { "2" };
        return url.strip_suffix("/1").map(|s| format!("{s}/{t}"));
    }
    if url.contains("jtvnw.net") {
        let t = if min_px > 64 { "3.0" } else { "2.0" };
        return url.strip_suffix("/1.0").map(|s| format!("{s}/{t}"));
    }
    None
}

/// fetch an emote at a resolution that covers `min_px`, falling back to the url
/// we were given if the higher tier 404s or the host is unknown.
fn fetch_at(url: &str, min_px: u32) -> Option<Vec<u8>> {
    if let Some(alt) = source_url(url, min_px) {
        if let Some(bytes) = http::image_bytes(&alt) {
            return Some(bytes);
        }
    }
    http::image_bytes(url)
}

/// resample a long animation onto at most `max` frames, preserving total loop
/// duration — a 150-frame emote plays at the same speed on a third the handles.
pub(crate) fn subsample(frames: Vec<(RgbaImage, u32)>, max: usize) -> Vec<(RgbaImage, u32)> {
    if frames.len() <= max || max == 0 {
        return frames;
    }
    let total: u64 = frames.iter().map(|f| f.1.max(MIN_DELAY_MS) as u64).sum();
    let per = ((total / max as u64) as u32).max(MIN_DELAY_MS);
    let last = frames.len() - 1;
    let step = frames.len() as f64 / max as f64;
    let keep: Vec<usize> = (0..max)
        .map(|i| ((i as f64 * step).round() as usize).min(last))
        .collect();
    frames
        .into_iter()
        .enumerate()
        .filter(|(i, _)| keep.binary_search(i).is_ok())
        .map(|(_, f)| (f.0, per))
        .collect()
}

fn loader(picker: Picker, jobs: Arc<Mutex<Receiver<Job>>>, done: Sender<Done>, wrap: SixelWrap) {
    // sixel drops the alpha channel (to_rgb8) so a transparent pixel falls back to
    // its raw rgb — often a colored fringe or box. flatten onto black first so
    // emotes sit cleanly on a dark terminal. kitty/iterm2 keep true transparency.
    let flatten = picker.protocol_type() == ProtocolType::Sixel;
    loop {
        // hold the lock only while receiving: the holder blocks on recv, takes
        // one job, releases, and works — its siblings then take the next jobs.
        let job = match jobs.lock() {
            Ok(rx) => match rx.recv() {
                Ok(j) => j,
                Err(_) => return, // store dropped → app closed
            },
            Err(_) => return,
        };
        let built = build(&picker, &job.key, flatten, wrap);
        if done
            .send(Done {
                key: job.key,
                built,
            })
            .is_err()
        {
            return; // store dropped → app closed
        }
    }
}

/// fetch + decode + composite a stack into RGBA frames (base at the bottom,
/// overlays on top), driven by the longest-animating layer, each layer with
/// the effects its key line carries (`#codes@hue` — see core's stack keys).
/// `key` is layer urls joined by '\n'; `min_px` is the pixel size the caller
/// will render at, used to pick a CDN size tier that never needs upscaling. no
/// encoding — shared by build(), the framebuffer tier, and the render-test
/// harness. any fetch/decode failure → None.
pub fn composite_frames(key: &str, min_px: u32) -> Option<Vec<(RgbaImage, u32)>> {
    let mut layers: Vec<decode::Decoded> = Vec::new();
    for spec in heatsync_core::emote::split_key(key) {
        let bytes = fetch_at(&spec.url, min_px)?;
        let mut layer = decode::decode(&bytes).ok()?;
        // each layer carries its own effects — applied BEFORE compositing, so
        // `Kappa RainTime ffzX` flips the overlay and leaves the base alone.
        // geometry on an overlay is undone by the resize onto the base canvas.
        if !spec.fx.is_empty() || spec.hue.is_some() {
            let frames = layer
                .frames
                .into_iter()
                .map(|f| (f.img, f.delay_ms))
                .collect();
            layer.frames = super::fx::apply(frames, &spec.fx, spec.hue)
                .into_iter()
                .map(|(img, delay_ms)| decode::Frame { img, delay_ms })
                .collect();
            if layer.frames.is_empty() {
                return None;
            }
        }
        layers.push(layer);
    }
    if layers.is_empty() {
        return None;
    }
    // canvas = base (first layer) native size; overlays resize onto it.
    let (tw, th) = layers[0].frames.first()?.img.dimensions();
    let single = layers.len() == 1;
    let driver = layers
        .iter()
        .max_by_key(|l| l.frames.len())
        .expect("≥1 layer");
    let mut out = Vec::with_capacity(driver.frames.len());
    let mut t = 0u64;
    for df in &driver.frames {
        let canvas = if single {
            layers[0].frames[sample_frame(&layers[0].frames, t)]
                .img
                .clone()
        } else {
            let mut c = RgbaImage::new(tw, th);
            for layer in &layers {
                let f = &layer.frames[sample_frame(&layer.frames, t)];
                if f.img.dimensions() == (tw, th) {
                    alpha_over(&mut c, &f.img);
                } else {
                    let r = image::imageops::resize(&f.img, tw, th, FilterType::Lanczos3);
                    alpha_over(&mut c, &r);
                }
            }
            c
        };
        out.push((canvas, df.delay_ms));
        t += df.delay_ms.max(MIN_DELAY_MS) as u64;
    }
    if out.is_empty() {
        None
    } else {
        Some(out)
    }
}

/// composite a stack (see [`composite_frames`]), scale every frame to exactly its
/// cell block, share one palette across the animation, and encode to the
/// terminal's inline-graphics protocol. any failure → None.
fn build(picker: &Picker, key: &str, flatten: bool, wrap: SixelWrap) -> Option<Built> {
    let (cw, ch) = picker.font_size();
    let block_h = EMOTE_H as u32 * ch.max(1) as u32;
    let frames = subsample(composite_frames(key, block_h)?, MAX_FRAMES);
    let (sw, sh) = frames[0].0.dimensions();
    if sw == 0 || sh == 0 {
        return None;
    }
    let w_cells = width_cells(sw as f32 / sh as f32, cw, ch);
    let (tw, th) = (w_cells as u32 * cw.max(1) as u32, block_h);

    let mut canvases: Vec<RgbaImage> = frames.iter().map(|(f, _)| fit_center(f, tw, th)).collect();
    if flatten {
        for c in &mut canvases {
            flatten_onto_black(c);
        }
        // sixel dithers per image — without a shared palette the static parts of
        // an animation shimmer. see stabilize_palette.
        stabilize_palette(&mut canvases);
    }

    let size = Rect::new(0, 0, w_cells, EMOTE_H);
    let mut out = Vec::with_capacity(canvases.len());
    let mut total_ms = 0u64;
    for (canvas, (_, delay_ms)) in canvases.into_iter().zip(frames.iter()) {
        // the canvas is ALREADY exactly `size` in pixels, so this encodes without
        // resizing and the protocol's footprint is exactly `size` — no letterbox,
        // no surprise cell count.
        let mut proto = picker
            .new_protocol(DynamicImage::ImageRgba8(canvas), size, Resize::Fit(None))
            .ok()?;
        match wrap {
            SixelWrap::Passthrough => fix_tmux_passthrough(&mut proto),
            SixelWrap::Native => unwrap_tmux_passthrough(&mut proto),
            SixelWrap::Bare => {}
        }
        let delay_ms = (*delay_ms).max(MIN_DELAY_MS);
        total_ms += delay_ms as u64;
        out.push(FrameProto { proto, delay_ms });
    }
    if out.is_empty() {
        None
    } else {
        Some(Built {
            frames: out,
            w_cells,
            total_ms,
        })
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn in_place_frame_is_absolute_doubled_passthrough_without_the_erase() {
        let native = format!("{}\x1bPq#0;2;0;0;0~\x1b\\", super::erase_block(2, 2));
        // pane at outer col 29, row 1 (top status); emote at pane cell (3, 4)
        let got = super::passthrough_in_place(&native, (29, 1), (3, 4));
        assert_eq!(
            got,
            "\x1bPtmux;\x1b\x1b7\x1b\x1b[6;33H\x1b\x1bPq#0;2;0;0;0~\x1b\x1b\\\x1b\x1b8\x1b\\"
        );
    }

    #[test]
    fn pane_offset_needs_a_visible_pane() {
        assert_eq!(super::parse_pane_offset("1 29 0 1\n"), Some((29, 1)));
        assert_eq!(super::parse_pane_offset("0 29 0 1"), None);
        assert_eq!(super::parse_pane_offset("garbage"), None);
    }

    use super::*;
    use image::{Rgba, RgbaImage};

    /// what tmux forwards to the outer terminal: strip the wrapper, halve every
    /// doubled ESC, and stop at the first ESC that ISN'T doubled (that one ends
    /// the passthrough). this is tmux's own rule — the test asserts against it
    /// rather than against our formatting.
    fn tmux_forwards(data: &str) -> String {
        let at = data.find("\x1bPtmux;").expect("passthrough prefix");
        let body = data[at + "\x1bPtmux;".len()..]
            .strip_suffix("\x1b\\")
            .expect("passthrough terminator");
        let mut out = String::new();
        let mut it = body.chars();
        while let Some(c) = it.next() {
            if c != '\x1b' {
                out.push(c);
                continue;
            }
            // a lone ESC (not doubled) terminates the passthrough early.
            match it.next() {
                Some('\x1b') => out.push('\x1b'),
                _ => break,
            }
        }
        out
    }

    /// native tmux sixel: the wrapper is gone, the sixel is intact and
    /// ST-terminated, and the block is cleared first.
    #[test]
    fn native_unwrap_yields_plain_sixel() {
        use ratatui_image::protocol::sixel::Sixel;
        let img = DynamicImage::ImageRgba8(RgbaImage::from_pixel(8, 8, Rgba([255, 135, 0, 255])));
        let area = Rect::new(0, 0, 2, 2);
        let plain = Sixel::new(img.clone(), area, false).expect("encode");
        let mut p = Protocol::Sixel(Sixel::new(img, area, true).expect("encode"));
        unwrap_tmux_passthrough(&mut p);
        let Protocol::Sixel(s) = &p else {
            unreachable!()
        };
        assert!(!s.is_tmux);
        assert!(!s.data.contains("tmux;"));
        assert_eq!(s.data, format!("{}{}", erase_block(2, 2), plain.data));
    }

    /// the whole bug in one assertion: what tmux hands the outer terminal must
    /// be the COMPLETE sixel, terminator included. before the fix the crate's
    /// wrapper leaked the sixel's own `ESC \` as the passthrough terminator, so
    /// foot got an unterminated sixel and swallowed the chat text after it.
    #[test]
    fn passthrough_forwards_a_complete_terminated_sixel() {
        use ratatui_image::protocol::sixel::Sixel;
        let img = DynamicImage::ImageRgba8(RgbaImage::from_pixel(8, 8, Rgba([255, 135, 0, 255])));
        let area = Rect::new(0, 0, 2, 2);
        let plain = Sixel::new(img.clone(), area, false).expect("encode");
        assert!(plain.data.ends_with("\x1b\\"), "sixel is ST-terminated");

        // the crate's own tmux output loses the terminator.
        let raw_wrap = Sixel::new(img.clone(), area, true).expect("encode");
        assert!(!tmux_forwards(&raw_wrap.data).ends_with("\x1b\\"));

        let mut fixed = Protocol::Sixel(Sixel::new(img, area, true).expect("encode"));
        fix_tmux_passthrough(&mut fixed);
        let Protocol::Sixel(s) = &fixed else {
            unreachable!()
        };
        assert_eq!(tmux_forwards(&s.data), plain.data);
        assert!(s.is_tmux, "still passthrough — tmux stays blind by design");

        // and the pixels must land on cells we cleared first, or tmux keeps
        // repainting the loading placeholder over the emote.
        let head = &s.data[..s.data.find("\x1bPtmux;").unwrap()];
        assert_eq!(head, "\x1b7\x1b[2X\x1b[B\x1b[2X\x1b8");
    }

    /// two frames of a real emote block: a smooth gradient, which is exactly
    /// what a starved palette turns into bands.
    fn gradient_frames() -> Vec<RgbaImage> {
        (0..2)
            .map(|f| {
                RgbaImage::from_fn(40, 36, |x, y| {
                    let s = (f * 7) as u32;
                    Rgba([
                        ((x * 6 + s) % 256) as u8,
                        ((y * 7 + s) % 256) as u8,
                        ((x * 3 + y * 4 + s) % 256) as u8,
                        255,
                    ])
                })
            })
            .collect()
    }

    /// mean per-channel error of quantising `frames` through one NeuQuant
    /// palette trained at sampling factor `fac`.
    fn quantise_err(frames: &[RgbaImage], fac: i32) -> f64 {
        let mut sample: Vec<u8> = Vec::new();
        for f in frames {
            sample.extend_from_slice(f.as_raw());
        }
        let nq = color_quant::NeuQuant::new(fac, PALETTE_COLORS as usize, &sample);
        let map = nq.color_map_rgba();
        let (mut sum, mut n) = (0.0f64, 0.0f64);
        for f in frames {
            for px in f.pixels() {
                let i = nq.index_of(&px.0) * 4;
                for c in 0..3 {
                    sum += (px.0[c] as f64 - map[i + c] as f64).abs();
                    n += 1.0;
                }
            }
        }
        sum / n
    }

    #[test]
    fn train_factor_never_starves_a_small_emote() {
        assert_eq!(train_factor(1_440 * 2), 1); // two frames of a 4x2 cell block
        assert_eq!(train_factor(43_000), 2);
        assert_eq!(train_factor(5_000_000), 10); // capped — long animations stay fast
    }

    /// the regression this guards: a FIXED 1-in-10 sample trains the palette on
    /// a few hundred pixels at emote size and the result is visibly worse. our
    /// factor must stay close to full quality on frames this small.
    #[test]
    fn small_emotes_quantise_near_full_quality() {
        let frames = gradient_frames();
        let px = frames.iter().map(|f| f.as_raw().len() / 4).sum::<usize>();
        let ours = quantise_err(&frames, train_factor(px));
        let starved = quantise_err(&frames, 10);
        let best = quantise_err(&frames, 1);
        assert_eq!(ours, best, "an emote-sized stack must train on every pixel");
        assert!(
            ours < starved,
            "ours {ours:.2} should beat the fixed 1-in-10 sample {starved:.2}"
        );
    }

    /// the erase must cover every row of the block and put the cursor back
    /// where it was, or the sixel paints at the wrong place.
    #[test]
    fn erase_block_clears_each_row_and_restores_the_cursor() {
        assert_eq!(erase_block(4, 1), "\x1b7\x1b[4X\x1b8");
        assert_eq!(
            erase_block(3, 3),
            "\x1b7\x1b[3X\x1b[B\x1b[3X\x1b[B\x1b[3X\x1b8"
        );
        assert_eq!(erase_block(0, 2), "");
        assert_eq!(erase_block(2, 0), "");
    }

    /// a sixel that was never wrapped (outside tmux, or a wrapper shape we
    /// don't recognise) must pass through untouched, never half-rewritten.
    #[test]
    fn fix_leaves_unwrapped_sixel_alone() {
        use ratatui_image::protocol::sixel::Sixel;
        let mut p = Protocol::Sixel(Sixel {
            data: "\x1bP0;1;0q#0;2;100;50;0#0~~\x1b\\".into(),
            area: Rect::new(0, 0, 2, 2),
            is_tmux: false,
        });
        let Protocol::Sixel(orig) = &p else {
            unreachable!()
        };
        let orig = orig.data.clone();
        fix_tmux_passthrough(&mut p);
        let Protocol::Sixel(after) = &p else {
            unreachable!()
        };
        assert_eq!(after.data, orig);
    }

    #[test]
    fn alpha_over_opaque_replaces() {
        let mut base = RgbaImage::from_pixel(2, 2, Rgba([255, 0, 0, 255])); // red
        let over = RgbaImage::from_pixel(2, 2, Rgba([0, 0, 255, 255])); // opaque blue
        alpha_over(&mut base, &over);
        assert_eq!(base.get_pixel(0, 0), &Rgba([0, 0, 255, 255])); // fully covered → blue
    }

    #[test]
    fn alpha_over_transparent_keeps_base() {
        let mut base = RgbaImage::from_pixel(2, 2, Rgba([255, 0, 0, 255])); // red
        let over = RgbaImage::from_pixel(2, 2, Rgba([0, 0, 255, 0])); // transparent blue
        alpha_over(&mut base, &over);
        assert_eq!(base.get_pixel(0, 0), &Rgba([255, 0, 0, 255])); // untouched → red
    }

    #[test]
    fn alpha_over_half_blends() {
        let mut base = RgbaImage::from_pixel(1, 1, Rgba([0, 0, 0, 255])); // black
        let over = RgbaImage::from_pixel(1, 1, Rgba([255, 255, 255, 128])); // ~50% white
        alpha_over(&mut base, &over);
        let p = base.get_pixel(0, 0);
        assert!((120..=136).contains(&p[0]), "blended ~half: {}", p[0]);
        assert_eq!(p[3], 255); // base was opaque → stays opaque
    }

    #[test]
    fn sample_frame_walks_timeline() {
        let f = |ms: u32| decode::Frame {
            img: RgbaImage::new(1, 1),
            delay_ms: ms,
        };
        let frames = vec![f(100), f(100), f(100)];
        assert_eq!(sample_frame(&frames, 0), 0);
        assert_eq!(sample_frame(&frames, 150), 1);
        assert_eq!(sample_frame(&frames, 250), 2);
        assert_eq!(sample_frame(&frames, 300), 0); // loops
    }

    // ---- dimensions ------------------------------------------------------

    #[test]
    fn square_emote_gets_square_cell_block() {
        // 8x16 cells: 2 rows = 32px tall, so a 1:1 emote needs 4 columns to be
        // square. the old fixed width of 3 made every emote 25% too narrow.
        assert_eq!(width_cells(1.0, 8, 16), 4);
        // 10x20 cells: 2 rows = 40px → 4 columns.
        assert_eq!(width_cells(1.0, 10, 20), 4);
        // a square cell (rare, but valid) → 2 columns for 2 rows.
        assert_eq!(width_cells(1.0, 10, 10), 2);
    }

    #[test]
    fn wide_emote_gets_more_columns() {
        assert_eq!(width_cells(2.0, 8, 16), 8); // 2:1 → 64px → 8 cols
        assert_eq!(width_cells(0.5, 8, 16), 2); // 1:2 (tall) → 16px → 2 cols
    }

    #[test]
    fn absurd_aspect_is_clamped_not_unbounded() {
        assert_eq!(width_cells(50.0, 8, 16), MAX_W);
        assert_eq!(width_cells(0.0001, 8, 16), 1);
        // a terminal reporting a degenerate cell size must still yield a sane,
        // in-range footprint rather than panicking or dividing by zero.
        assert!((1..=MAX_W).contains(&width_cells(1.0, 0, 0)));
        assert!((1..=MAX_W).contains(&width_cells(f32::NAN, 8, 16)));
        assert!((1..=MAX_W).contains(&width_cells(f32::INFINITY, 8, 16)));
    }

    #[test]
    fn fit_center_fills_exact_block_and_centres() {
        // 32x32 source into a 64x32 block → scaled to 32x32, centred with 16px
        // of transparent padding each side. never stretched.
        let src = RgbaImage::from_pixel(32, 32, Rgba([255, 135, 0, 255]));
        let out = fit_center(&src, 64, 32);
        assert_eq!(out.dimensions(), (64, 32)); // exactly the block
        assert_eq!(out.get_pixel(0, 16)[3], 0); // left pad transparent
        assert_eq!(out.get_pixel(63, 16)[3], 0); // right pad transparent
        assert_eq!(out.get_pixel(32, 16), &Rgba([255, 135, 0, 255])); // centred
    }

    #[test]
    fn fit_center_preserves_aspect_when_downscaling() {
        // a 4:1 source into a square block must letterbox, never squash.
        let src = RgbaImage::from_pixel(128, 32, Rgba([255, 255, 255, 255]));
        let out = fit_center(&src, 32, 32);
        assert_eq!(out.dimensions(), (32, 32));
        assert_eq!(out.get_pixel(16, 0)[3], 0); // top pad
        assert_eq!(out.get_pixel(16, 31)[3], 0); // bottom pad
        assert_eq!(out.get_pixel(16, 16)[3], 255); // image band through the middle
    }

    #[test]
    fn fit_center_upscales_small_sources_to_the_block() {
        let src = RgbaImage::from_pixel(16, 16, Rgba([1, 2, 3, 255]));
        let out = fit_center(&src, 48, 48);
        assert_eq!(out.dimensions(), (48, 48));
        assert_eq!(out.get_pixel(24, 24)[3], 255); // fills, not a 16px speck
    }

    // ---- animation clock -------------------------------------------------

    fn protos(delays: &[u32]) -> Vec<FrameProto> {
        // Protocol has no cheap constructor; Halfblocks::default() is the one
        // variant we can build without a terminal.
        delays
            .iter()
            .map(|&delay_ms| FrameProto {
                proto: Protocol::Halfblocks(Default::default()),
                delay_ms,
            })
            .collect()
    }

    #[test]
    fn frame_at_reports_index_and_time_to_flip() {
        let f = protos(&[100, 100, 100]);
        assert_eq!(frame_at(&f, 0, 300), (0, 100));
        assert_eq!(frame_at(&f, 40, 300), (0, 60));
        assert_eq!(frame_at(&f, 150, 300), (1, 50));
        assert_eq!(frame_at(&f, 300, 300), (0, 100)); // loops
    }

    #[test]
    fn static_image_never_schedules_a_redraw() {
        assert_eq!(frame_at(&protos(&[0]), 12_345, 0).1, u64::MAX);
    }

    // ---- resampling ------------------------------------------------------

    #[test]
    fn subsample_caps_frames_and_keeps_duration() {
        let frames: Vec<(RgbaImage, u32)> = (0..300).map(|_| (RgbaImage::new(1, 1), 20)).collect();
        let out = subsample(frames, MAX_FRAMES);
        assert_eq!(out.len(), MAX_FRAMES);
        let total: u64 = out.iter().map(|f| f.1 as u64).sum();
        assert!(
            (5500..=6500).contains(&total),
            "loop length preserved: {total}"
        );
    }

    #[test]
    fn subsample_leaves_short_animations_alone() {
        let frames: Vec<(RgbaImage, u32)> = (0..10).map(|_| (RgbaImage::new(1, 1), 40)).collect();
        assert_eq!(subsample(frames, MAX_FRAMES).len(), 10);
    }

    // ---- palette stability (the anti-flash property) ----------------------

    #[test]
    fn stabilize_palette_makes_unchanged_regions_byte_identical() {
        // two frames sharing a large static region, differing only in one corner.
        let mut a = RgbaImage::new(32, 32);
        for (x, y, px) in a.enumerate_pixels_mut() {
            *px = Rgba([(x * 7 % 256) as u8, (y * 5 % 256) as u8, 90, 255]);
        }
        let mut b = a.clone();
        for x in 0..8 {
            for y in 0..8 {
                b.put_pixel(x, y, Rgba([255, 0, 0, 255]));
            }
        }
        let mut frames = vec![a, b];
        stabilize_palette(&mut frames);
        // the shared region must quantise identically in both frames — that is
        // exactly what stops the sixel dither from boiling between frames.
        let (qa, qb) = (&frames[0], &frames[1]);
        for y in 8..32 {
            for x in 8..32 {
                assert_eq!(qa.get_pixel(x, y), qb.get_pixel(x, y), "drift at {x},{y}");
            }
        }
    }

    #[test]
    fn stabilize_palette_collapses_to_at_most_the_palette_size() {
        let mut f = RgbaImage::new(64, 64);
        for (x, y, px) in f.enumerate_pixels_mut() {
            *px = Rgba([x as u8 * 4, y as u8 * 4, (x + y) as u8, 255]);
        }
        let mut frames = vec![f.clone(), f];
        stabilize_palette(&mut frames);
        let mut seen = std::collections::HashSet::new();
        for px in frames[0].pixels() {
            seen.insert([px[0], px[1], px[2]]);
        }
        assert!(
            seen.len() <= PALETTE_COLORS as usize,
            "{} colors",
            seen.len()
        );
    }

    #[test]
    fn stabilize_palette_noop_on_single_frame() {
        let f = RgbaImage::from_pixel(4, 4, Rgba([1, 2, 3, 255]));
        let mut frames = vec![f.clone()];
        stabilize_palette(&mut frames);
        assert_eq!(frames[0], f);
    }

    // ---- cdn size tiers --------------------------------------------------

    #[test]
    fn source_url_upgrades_only_when_the_block_needs_it() {
        let u = "https://cdn.7tv.app/emote/ABC/1x.webp";
        assert_eq!(source_url(u, 32), None); // 1x already covers a 32px block
        assert_eq!(
            source_url(u, 40).as_deref(),
            Some("https://cdn.7tv.app/emote/ABC/2x.webp")
        );
        assert_eq!(
            source_url(u, 100).as_deref(),
            Some("https://cdn.7tv.app/emote/ABC/4x.webp")
        );
    }

    #[test]
    fn source_url_handles_each_cdn_shape() {
        assert_eq!(
            source_url("https://cdn.betterttv.net/emote/ID/1x", 40).as_deref(),
            Some("https://cdn.betterttv.net/emote/ID/2x")
        );
        assert_eq!(
            source_url("https://cdn.frankerfacez.com/emote/1234/1", 40).as_deref(),
            Some("https://cdn.frankerfacez.com/emote/1234/2")
        );
        assert_eq!(
            source_url(
                "https://static-cdn.jtvnw.net/emoticons/v2/25/default/dark/1.0",
                40
            )
            .as_deref(),
            Some("https://static-cdn.jtvnw.net/emoticons/v2/25/default/dark/2.0")
        );
    }

    #[test]
    fn source_url_leaves_unknown_hosts_alone() {
        assert_eq!(source_url("https://example.com/emote.png", 64), None);
    }
}