termmd 0.1.4

A best-in-class Markdown viewer for the terminal: real typography, real tables, real images.
Documentation
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
//! A DEC sixel encoder, including colour quantisation.
//!
//! Sixel encodes six vertically stacked pixels per character, one bit each, and
//! addresses colour through a palette of at most 256 registers. So an encoder is
//! really two problems: reducing an arbitrary image to 256 colours without it
//! looking like 1987, and packing the result compactly.
//!
//! * Quantisation uses median cut over a 15-bit colour histogram, which keeps
//!   the work proportional to the number of distinct colours rather than the
//!   number of pixels.
//! * Floyd-Steinberg dithering spreads the residual error into neighbouring
//!   pixels, which is what stops gradients from banding.
//! * Output is run-length encoded, because a photograph's background is mostly
//!   long runs of the same sixel.
//!
//! Written against the DEC sixel specification; no code was taken from libsixel
//! or any other implementation.

use image::RgbaImage;

/// Sixel supports 256 colour registers; some terminals have fewer, but 256 is
//  the value they all accept.
const MAX_COLORS: usize = 256;
/// Alpha below this is treated as fully transparent and left undrawn.
const ALPHA_THRESHOLD: u8 = 128;
/// A run shorter than this costs more to encode than to repeat.
const MIN_RUN: usize = 4;

/// Encodes an image as a sixel escape sequence.
pub fn encode(image: &RgbaImage) -> Option<String> {
    let (width, height) = image.dimensions();
    if width == 0 || height == 0 {
        return None;
    }
    let quantized = quantize(image, MAX_COLORS);
    Some(emit(&quantized, width as usize, height as usize))
}

/// An image reduced to a palette, with `None` marking transparent pixels.
struct Quantized {
    palette: Vec<[u8; 3]>,
    /// One entry per pixel, row-major.
    indices: Vec<Option<u8>>,
}

/// Builds the escape sequence from quantised pixels.
fn emit(q: &Quantized, width: usize, height: usize) -> String {
    let mut out = String::with_capacity(width * height / 4 + 256);

    // DCS with P2=1: bit-zero pixels leave the background untouched, which is
    // what makes transparency work.
    out.push_str("\x1bP0;1;0q");
    // Raster attributes: 1:1 pixel aspect, and the image's true size, so the
    // terminal reserves the right area before drawing.
    out.push_str(&format!("\"1;1;{width};{height}"));

    for (i, c) in q.palette.iter().enumerate() {
        // Colour components are percentages in sixel, not 0-255.
        out.push_str(&format!(
            "#{};2;{};{};{}",
            i,
            to_percent(c[0]),
            to_percent(c[1]),
            to_percent(c[2])
        ));
    }

    let bands = height.div_ceil(6);
    let mut used = vec![false; q.palette.len()];
    for band in 0..bands {
        let y0 = band * 6;
        let rows = 6.min(height - y0);

        used.iter_mut().for_each(|u| *u = false);
        for row in 0..rows {
            for x in 0..width {
                if let Some(i) = q.indices[(y0 + row) * width + x] {
                    used[i as usize] = true;
                }
            }
        }

        let mut first = true;
        for (color, _) in used.iter().enumerate().filter(|(_, u)| **u) {
            if !first {
                // Carriage return: draw the next colour over the same band.
                out.push('$');
            }
            first = false;
            out.push_str(&format!("#{color}"));
            emit_band(&mut out, q, width, height, y0, rows, color as u8);
        }
        if band + 1 < bands {
            out.push('-');
        }
    }

    out.push_str("\x1b\\");
    out
}

/// Writes one colour's contribution to one band, run-length encoded.
fn emit_band(
    out: &mut String,
    q: &Quantized,
    width: usize,
    _height: usize,
    y0: usize,
    rows: usize,
    color: u8,
) {
    let mut run_char = 0u8;
    let mut run_len = 0usize;
    // Trailing empty sixels need not be written at all, so they are held back
    // until something visible follows.
    let mut pending_empty = 0usize;

    let flush = |out: &mut String, ch: u8, len: usize| {
        if len == 0 {
            return;
        }
        let c = (0x3f + ch) as char;
        if len >= MIN_RUN {
            out.push_str(&format!("!{len}{c}"));
        } else {
            for _ in 0..len {
                out.push(c);
            }
        }
    };

    for x in 0..width {
        let mut bits = 0u8;
        for row in 0..rows {
            if q.indices[(y0 + row) * width + x] == Some(color) {
                bits |= 1 << row;
            }
        }
        if bits == 0 {
            if run_char == 0 {
                run_len += 1;
            } else {
                flush(out, run_char, run_len);
                run_char = 0;
                run_len = 1;
            }
            continue;
        }
        // Something visible: any empty run we were holding must be written now.
        if run_char == 0 && run_len > 0 {
            pending_empty = run_len;
            run_len = 0;
        }
        if pending_empty > 0 {
            flush(out, 0, pending_empty);
            pending_empty = 0;
        }
        if bits == run_char {
            run_len += 1;
        } else {
            flush(out, run_char, run_len);
            run_char = bits;
            run_len = 1;
        }
    }
    if run_char != 0 {
        flush(out, run_char, run_len);
    }
}

fn to_percent(v: u8) -> u32 {
    (v as u32 * 100 + 127) / 255
}

/// A histogram entry: one 15-bit colour bucket and the pixels that fell in it.
#[derive(Clone, Copy)]
struct Entry {
    count: u32,
    sum: [u32; 3],
}

impl Entry {
    fn channel(&self, c: usize) -> u8 {
        // Reconstruct the bucket's representative channel value.
        (self.sum[c] / self.count.max(1)) as u8
    }
}

/// Reduces an image to at most `max_colors` colours.
fn quantize(image: &RgbaImage, max_colors: usize) -> Quantized {
    let entries = histogram(image);
    if entries.is_empty() {
        return Quantized {
            palette: vec![[0, 0, 0]],
            indices: vec![None; image.pixels().len()],
        };
    }
    let palette = median_cut(entries, max_colors.max(1));
    let indices = map_pixels(image, &palette);
    Quantized { palette, indices }
}

/// Buckets colours to 5 bits per channel and counts them.
///
/// 32768 buckets is a big enough net to keep distinct colours apart and small
/// enough that the median cut below is cheap regardless of image size.
fn histogram(image: &RgbaImage) -> Vec<Entry> {
    let mut table: Vec<Option<Entry>> = vec![None; 1 << 15];
    for px in image.pixels() {
        let [r, g, b, a] = px.0;
        if a < ALPHA_THRESHOLD {
            continue;
        }
        let slot = &mut table[key555(r, g, b) as usize];
        match slot {
            Some(e) => {
                e.count += 1;
                e.sum[0] += r as u32;
                e.sum[1] += g as u32;
                e.sum[2] += b as u32;
            }
            None => {
                *slot = Some(Entry {
                    count: 1,
                    sum: [r as u32, g as u32, b as u32],
                });
            }
        }
    }
    table.into_iter().flatten().collect()
}

fn key555(r: u8, g: u8, b: u8) -> u16 {
    ((r as u16 >> 3) << 10) | ((g as u16 >> 3) << 5) | (b as u16 >> 3)
}

/// Median cut: repeatedly split the most promising box along its widest channel.
fn median_cut(mut entries: Vec<Entry>, max_colors: usize) -> Vec<[u8; 3]> {
    if entries.len() <= max_colors {
        return entries.iter().map(average_of_one).collect();
    }

    // Boxes are contiguous ranges of `entries`, which lets a split be a sort
    // plus an index rather than a reallocation.
    let mut boxes: Vec<(usize, usize)> = vec![(0, entries.len())];

    while boxes.len() < max_colors {
        // Split the box with the largest colour volume weighted by population:
        // a wide box holding one pixel matters less than a narrow, busy one.
        let target = boxes
            .iter()
            .enumerate()
            .filter(|(_, (s, e))| e - s > 1)
            .max_by_key(|(_, (s, e))| {
                let slice = &entries[*s..*e];
                let (_, range) = widest_channel(slice);
                let count: u32 = slice.iter().map(|x| x.count).sum();
                (range as u64) * (count as u64).max(1)
            })
            .map(|(i, _)| i);

        let Some(i) = target else { break };
        let (start, end) = boxes[i];
        let slice = &mut entries[start..end];
        let (channel, _) = widest_channel(slice);
        slice.sort_unstable_by_key(|e| e.channel(channel));

        // Cut at the population median so both halves carry similar weight.
        let total: u32 = slice.iter().map(|e| e.count).sum();
        let mut acc = 0u32;
        let mut split = 1;
        for (j, e) in slice.iter().enumerate() {
            acc += e.count;
            if acc * 2 >= total {
                split = (j + 1).clamp(1, slice.len() - 1);
                break;
            }
        }

        boxes[i] = (start, start + split);
        boxes.push((start + split, end));
    }

    boxes
        .iter()
        .map(|(s, e)| average(&entries[*s..*e]))
        .collect()
}

/// The channel with the widest spread in a box, and that spread.
fn widest_channel(entries: &[Entry]) -> (usize, u8) {
    let mut best = (0usize, 0u8);
    for c in 0..3 {
        let mut lo = u8::MAX;
        let mut hi = 0u8;
        for e in entries {
            let v = e.channel(c);
            lo = lo.min(v);
            hi = hi.max(v);
        }
        let range = hi.saturating_sub(lo);
        if range > best.1 {
            best = (c, range);
        }
    }
    best
}

fn average(entries: &[Entry]) -> [u8; 3] {
    let mut sum = [0u64; 3];
    let mut count = 0u64;
    for e in entries {
        for (c, total) in sum.iter_mut().enumerate() {
            *total += e.sum[c] as u64;
        }
        count += e.count as u64;
    }
    let count = count.max(1);
    [
        (sum[0] / count) as u8,
        (sum[1] / count) as u8,
        (sum[2] / count) as u8,
    ]
}

fn average_of_one(e: &Entry) -> [u8; 3] {
    [e.channel(0), e.channel(1), e.channel(2)]
}

/// Maps every pixel to a palette entry, diffusing the error as it goes.
fn map_pixels(image: &RgbaImage, palette: &[[u8; 3]]) -> Vec<Option<u8>> {
    let (w, h) = (image.width() as usize, image.height() as usize);
    let mut out = vec![None; w * h];
    // Working copy in i32 so diffused error can push a channel out of range
    // temporarily without wrapping.
    let mut buf: Vec<[i32; 3]> = image
        .pixels()
        .map(|p| [p.0[0] as i32, p.0[1] as i32, p.0[2] as i32])
        .collect();
    let mut cache = LookupCache::new(palette.len());

    for y in 0..h {
        for x in 0..w {
            let i = y * w + x;
            if image.as_raw()[i * 4 + 3] < ALPHA_THRESHOLD {
                continue;
            }
            let want = buf[i];
            let clamped = [
                want[0].clamp(0, 255) as u8,
                want[1].clamp(0, 255) as u8,
                want[2].clamp(0, 255) as u8,
            ];
            let index = cache.nearest(palette, clamped);
            out[i] = Some(index as u8);

            let chosen = palette[index];
            let error = [
                want[0] - chosen[0] as i32,
                want[1] - chosen[1] as i32,
                want[2] - chosen[2] as i32,
            ];
            // Floyd-Steinberg weights: 7/16 right, 3/16 down-left, 5/16 down,
            // 1/16 down-right.
            let mut spread = |dx: isize, dy: usize, num: i32| {
                let nx = x as isize + dx;
                let ny = y + dy;
                if nx < 0 || nx >= w as isize || ny >= h {
                    return;
                }
                let j = ny * w + nx as usize;
                for (c, channel) in buf[j].iter_mut().enumerate() {
                    *channel += error[c] * num / 16;
                }
            };
            spread(1, 0, 7);
            spread(-1, 1, 3);
            spread(0, 1, 5);
            spread(1, 1, 1);
        }
    }
    out
}

/// Caches nearest-palette lookups on 15-bit colour keys.
///
/// Without this, every pixel costs a linear scan of 256 palette entries; with
/// it, all but the first pixel of each colour bucket costs an array read.
struct LookupCache {
    table: Vec<u16>,
    palette_len: usize,
}

impl LookupCache {
    const EMPTY: u16 = u16::MAX;

    fn new(palette_len: usize) -> Self {
        Self {
            table: vec![Self::EMPTY; 1 << 15],
            palette_len,
        }
    }

    fn nearest(&mut self, palette: &[[u8; 3]], color: [u8; 3]) -> usize {
        let key = key555(color[0], color[1], color[2]) as usize;
        let cached = self.table[key];
        if cached != Self::EMPTY && (cached as usize) < self.palette_len {
            return cached as usize;
        }
        let mut best = 0usize;
        let mut best_d = i32::MAX;
        for (i, c) in palette.iter().enumerate() {
            let dr = color[0] as i32 - c[0] as i32;
            let dg = color[1] as i32 - c[1] as i32;
            let db = color[2] as i32 - c[2] as i32;
            // Green-weighted distance: the eye is most sensitive to it.
            let d = 2 * dr * dr + 4 * dg * dg + 3 * db * db;
            if d < best_d {
                best_d = d;
                best = i;
            }
        }
        self.table[key] = best as u16;
        best
    }
}

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

    fn gradient(w: u32, h: u32) -> RgbaImage {
        let mut img = RgbaImage::new(w, h);
        for (x, y, px) in img.enumerate_pixels_mut() {
            *px = Rgba([
                (x * 255 / w.max(1)) as u8,
                (y * 255 / h.max(1)) as u8,
                90,
                255,
            ]);
        }
        img
    }

    #[test]
    fn produces_a_well_formed_sequence() {
        let out = encode(&gradient(12, 12)).unwrap();
        assert!(out.starts_with("\x1bP"), "must open with a DCS");
        assert!(out.ends_with("\x1b\\"), "must close with ST");
        assert!(
            out.contains("\"1;1;12;12"),
            "raster attributes should state the size"
        );
        assert!(
            out.contains("#0;2;"),
            "at least one colour register must be defined"
        );
    }

    #[test]
    fn colour_components_are_percentages() {
        let img = RgbaImage::from_pixel(2, 2, Rgba([255, 0, 0, 255]));
        let out = encode(&img).unwrap();
        assert!(out.contains(";2;100;0;0"), "255 should become 100%: {out}");
    }

    #[test]
    fn every_data_byte_is_a_legal_sixel_character() {
        let out = encode(&gradient(20, 14)).unwrap();
        // Strip the header and terminator, then check the payload alphabet.
        let body = out
            .trim_start_matches("\x1bP0;1;0q")
            .trim_end_matches("\x1b\\");
        let body = &body[body.find('#').unwrap_or(0)..];
        for c in body.chars() {
            let ok = ('?'..='~').contains(&c)
                || c == '#'
                || c == '$'
                || c == '-'
                || c == '!'
                || c == ';'
                || c == '"'
                || c.is_ascii_digit();
            assert!(ok, "illegal sixel byte {c:?} in output");
        }
    }

    #[test]
    fn bands_are_separated_by_newlines() {
        // 13 rows spans three bands of six, so there should be two separators.
        let out = encode(&gradient(4, 13)).unwrap();
        assert_eq!(out.matches('-').count(), 2, "expected two band separators");
    }

    #[test]
    fn run_length_encodes_long_runs() {
        let img = RgbaImage::from_pixel(200, 6, Rgba([10, 200, 30, 255]));
        let out = encode(&img).unwrap();
        assert!(
            out.contains("!200"),
            "a uniform row should compress to one run: {out}"
        );
        assert!(
            out.len() < 400,
            "output should be compact, got {} bytes",
            out.len()
        );
    }

    #[test]
    fn transparent_pixels_are_left_undrawn() {
        let mut img = RgbaImage::from_pixel(8, 6, Rgba([255, 255, 255, 255]));
        for x in 0..4 {
            for y in 0..6 {
                img.put_pixel(x, y, Rgba([0, 0, 0, 0]));
            }
        }
        let out = encode(&img).unwrap();
        // The left half contributes no set bits, so it appears as empty sixels.
        assert!(
            out.contains('?'),
            "expected empty sixels for the transparent half: {out}"
        );
    }

    #[test]
    fn quantisation_stays_within_the_palette_limit() {
        let img = gradient(64, 64);
        let q = quantize(&img, 16);
        assert!(q.palette.len() <= 16, "got {} colours", q.palette.len());
        assert!(
            q.indices
                .iter()
                .flatten()
                .all(|&i| (i as usize) < q.palette.len())
        );
    }

    #[test]
    fn a_small_palette_is_preserved_exactly() {
        let mut img = RgbaImage::new(4, 1);
        img.put_pixel(0, 0, Rgba([255, 0, 0, 255]));
        img.put_pixel(1, 0, Rgba([0, 255, 0, 255]));
        img.put_pixel(2, 0, Rgba([0, 0, 255, 255]));
        img.put_pixel(3, 0, Rgba([255, 0, 0, 255]));
        let q = quantize(&img, 256);
        assert_eq!(
            q.palette.len(),
            3,
            "three distinct colours, three registers"
        );
    }

    #[test]
    fn quantisation_keeps_colours_close_to_the_original() {
        let img = gradient(48, 48);
        let q = quantize(&img, 256);
        let mut worst = 0i32;
        for (i, px) in img.pixels().enumerate() {
            let chosen = q.palette[q.indices[i].unwrap() as usize];
            for (actual, want) in chosen.iter().zip(px.0.iter()) {
                worst = worst.max((*want as i32 - *actual as i32).abs());
            }
        }
        // Dithering trades per-pixel accuracy for perceived accuracy, so this is
        // a sanity bound rather than a tight one.
        assert!(worst < 96, "quantisation drifted too far: {worst}");
    }

    #[test]
    fn handles_a_single_pixel() {
        let img = RgbaImage::from_pixel(1, 1, Rgba([1, 2, 3, 255]));
        assert!(encode(&img).is_some());
    }

    #[test]
    fn handles_a_fully_transparent_image() {
        let img = RgbaImage::from_pixel(4, 4, Rgba([0, 0, 0, 0]));
        let out = encode(&img).unwrap();
        assert!(out.starts_with("\x1bP") && out.ends_with("\x1b\\"));
    }

    #[test]
    fn empty_images_encode_to_nothing() {
        assert!(encode(&RgbaImage::new(0, 0)).is_none());
    }
    // -- round trip ----------------------------------------------------------
    //
    // The tests above assert on the bytes we emit. That catches malformed
    // output, but not output that is well formed and wrong: a repeat count one
    // too high, a band that paints below the picture, a colour selected before
    // it is defined. The only way to know an encoder works is to receive from
    // it, so the rest of this module is a decoder -- the DCS header, the
    // palette, `!` runs, `$` carriage returns and `-` newlines, read the way a
    // terminal reads them -- and images pushed through both halves.

    /// A sixel sequence decoded back into pixels.
    struct Decoded {
        /// The size the raster attributes declared.
        width: usize,
        height: usize,
        /// Row-major over a canvas larger than the declared raster, so that
        /// anything painted outside it shows up instead of being clipped.
        canvas: Vec<Option<[u8; 3]>>,
        canvas_w: usize,
        canvas_h: usize,
    }

    impl Decoded {
        fn at(&self, x: usize, y: usize) -> Option<[u8; 3]> {
            self.canvas[y * self.canvas_w + x]
        }

        /// Pixels painted beyond the size the sequence declared.
        fn painted_outside(&self) -> Vec<(usize, usize)> {
            let mut out = Vec::new();
            for y in 0..self.canvas_h {
                for x in 0..self.canvas_w {
                    if (x >= self.width || y >= self.height)
                        && self.canvas[y * self.canvas_w + x].is_some()
                    {
                        out.push((x, y));
                    }
                }
            }
            out
        }
    }

    /// Reads a decimal parameter, returning it and the index after it.
    fn number(bytes: &[u8], mut i: usize) -> (u32, usize) {
        let mut n = 0u32;
        while let Some(d) = bytes.get(i).filter(|b| b.is_ascii_digit()) {
            n = n * 10 + u32::from(d - b'0');
            i += 1;
        }
        (n, i)
    }

    /// Sets the pixels one sixel character stands for.
    fn paint(d: &mut Decoded, x: usize, band: usize, bits: u8, rgb: [u8; 3]) {
        for row in 0..6 {
            if bits & (1 << row) == 0 {
                continue;
            }
            let y = band * 6 + row;
            assert!(
                x < d.canvas_w && y < d.canvas_h,
                "sixel data ran off the canvas at ({x}, {y})"
            );
            d.canvas[y * d.canvas_w + x] = Some(rgb);
        }
    }

    fn decode(seq: &str) -> Decoded {
        let body = seq
            .strip_prefix("\x1bP")
            .and_then(|s| s.strip_suffix("\x1b\\"))
            .expect("a sixel image is a DCS terminated by ST");
        let (_, data) = body
            .split_once('q')
            .expect("the sixel data follows a `q` introducer");
        let bytes = data.as_bytes();
        let mut i = 0;

        // Raster attributes: "Pan;Pad;Ph;Pv, of which the last two are the size.
        let (mut width, mut height) = (0usize, 0usize);
        if bytes.first() == Some(&b'"') {
            i = 1;
            let mut params = Vec::new();
            loop {
                let (n, next) = number(bytes, i);
                params.push(n);
                i = next;
                if bytes.get(i) == Some(&b';') {
                    i += 1;
                } else {
                    break;
                }
            }
            assert_eq!(params.len(), 4, "raster attributes take four parameters");
            width = params[2] as usize;
            height = params[3] as usize;
        }

        // Room to spare on both axes. A terminal would clip; we would rather
        // see the mistake.
        let (canvas_w, canvas_h) = (width + 8, height + 12);
        let mut d = Decoded {
            width,
            height,
            canvas: vec![None; canvas_w * canvas_h],
            canvas_w,
            canvas_h,
        };

        let mut palette = [None; 256];
        let mut color = 0usize;
        let mut x = 0usize;
        let mut band = 0usize;

        while i < bytes.len() {
            match bytes[i] {
                b'#' => {
                    let (n, next) = number(bytes, i + 1);
                    color = n as usize;
                    assert!(color < 256, "colour register {color} is out of range");
                    i = next;
                    if bytes.get(i) == Some(&b';') {
                        // A definition rather than a selection.
                        let mut params = Vec::new();
                        while bytes.get(i) == Some(&b';') {
                            let (n, next) = number(bytes, i + 1);
                            params.push(n);
                            i = next;
                        }
                        assert_eq!(
                            params.len(),
                            4,
                            "a colour takes a space and three components"
                        );
                        assert_eq!(params[0], 2, "components should be declared as RGB");
                        // Components are percentages on the wire.
                        let byte = |p: u32| {
                            assert!(p <= 100, "a component of {p}% is out of range");
                            ((p * 255 + 50) / 100) as u8
                        };
                        palette[color] = Some([byte(params[1]), byte(params[2]), byte(params[3])]);
                    }
                }
                b'!' => {
                    let (count, next) = number(bytes, i + 1);
                    let ch = *bytes.get(next).expect("a run must be followed by a sixel");
                    assert!(
                        (0x3f..=0x7e).contains(&ch),
                        "a run repeats a sixel, not {:?}",
                        ch as char
                    );
                    let rgb = palette[color].expect("a colour must be defined before it is used");
                    for _ in 0..count {
                        paint(&mut d, x, band, ch - 0x3f, rgb);
                        x += 1;
                    }
                    i = next + 1;
                }
                // Graphics carriage return: back to the left of the same band.
                b'$' => {
                    x = 0;
                    i += 1;
                }
                // Graphics newline: down to the next band.
                b'-' => {
                    x = 0;
                    band += 1;
                    i += 1;
                }
                ch @ 0x3f..=0x7e => {
                    let rgb = palette[color].expect("a colour must be defined before it is used");
                    paint(&mut d, x, band, ch - 0x3f, rgb);
                    x += 1;
                    i += 1;
                }
                other => panic!("unexpected byte {:?} in sixel data", other as char),
            }
        }
        d
    }

    /// Asserts that every pixel came back, within the one step of drift the
    /// wire format imposes: colour components travel as percentages, and
    /// rounding a byte to the nearest of a hundred steps and back moves it by
    /// at most one. Anything looser would stop policing the rounding itself.
    const DRIFT: i32 = 1;

    #[track_caller]
    fn assert_same(image: &RgbaImage, decoded: &Decoded) {
        assert_eq!(
            (decoded.width, decoded.height),
            (image.width() as usize, image.height() as usize),
            "the raster attributes should state the image's size"
        );
        for (x, y, px) in image.enumerate_pixels() {
            let got = decoded
                .at(x as usize, y as usize)
                .unwrap_or_else(|| panic!("pixel ({x}, {y}) was never drawn"));
            for c in 0..3 {
                let drift = i32::from(got[c]) - i32::from(px.0[c]);
                assert!(
                    drift.abs() <= DRIFT,
                    "pixel ({x}, {y}) came back {got:?}, not {:?}",
                    &px.0[..3]
                );
            }
        }
    }

    /// Six colours far enough apart to survive quantisation untouched.
    fn patchwork(w: u32, h: u32) -> RgbaImage {
        const COLORS: [[u8; 3]; 6] = [
            [220, 40, 40],
            [40, 200, 80],
            [60, 90, 230],
            [240, 220, 40],
            [20, 20, 20],
            [250, 250, 250],
        ];
        let mut img = RgbaImage::new(w, h);
        for (x, y, px) in img.enumerate_pixels_mut() {
            let c = COLORS[(x as usize / 3 + y as usize / 2) % COLORS.len()];
            *px = Rgba([c[0], c[1], c[2], 255]);
        }
        img
    }

    #[test]
    fn a_decoded_image_matches_the_one_encoded() {
        // Colours from a small, well separated palette are reproduced exactly:
        // median cut keeps them, and dithering has no error to spread.
        let img = patchwork(17, 13);
        assert_same(&img, &decode(&encode(&img).unwrap()));
    }

    #[test]
    fn nothing_is_painted_below_the_last_row() {
        // Thirteen rows is two full bands and a third holding a single row. A
        // sixel is six pixels tall whatever the picture does, so the five bits
        // under that last row must be left clear -- a terminal would paint them.
        let img = patchwork(9, 13);
        let decoded = decode(&encode(&img).unwrap());
        assert_eq!(
            decoded.painted_outside(),
            Vec::new(),
            "pixels were painted outside the declared raster"
        );
        assert_same(&img, &decoded);
    }

    #[test]
    fn transparency_survives_the_round_trip() {
        let mut img = RgbaImage::from_pixel(10, 8, Rgba([30, 160, 220, 255]));
        for y in 0..8 {
            for x in 0..10 {
                if (x + y) % 3 == 0 {
                    img.put_pixel(x, y, Rgba([0, 0, 0, 0]));
                }
            }
        }
        let decoded = decode(&encode(&img).unwrap());
        for (x, y, px) in img.enumerate_pixels() {
            assert_eq!(
                decoded.at(x as usize, y as usize).is_some(),
                px.0[3] >= ALPHA_THRESHOLD,
                "pixel ({x}, {y}) was not left as it should be"
            );
        }
    }

    #[test]
    fn runs_expand_to_the_columns_they_came_from() {
        // One odd column in a long uniform run: a repeat count out by one moves
        // the stripe, which the shape of the output cannot show.
        let mut img = RgbaImage::from_pixel(120, 6, Rgba([15, 15, 15, 255]));
        for y in 0..6 {
            img.put_pixel(73, y, Rgba([240, 240, 240, 255]));
        }
        let seq = encode(&img).unwrap();
        assert!(seq.contains('!'), "a run of 73 should have been compressed");
        assert_same(&img, &decode(&seq));
    }

    #[test]
    fn a_gradient_round_trips_within_tolerance() {
        // More distinct colours than registers, so this exercises median cut
        // and dithering as well as the wire format. Dithering deliberately
        // trades per-pixel accuracy for the look of the whole, so the bound is
        // on the average.
        let img = gradient(64, 40);
        let decoded = decode(&encode(&img).unwrap());
        let (mut total, mut count) = (0u64, 0u64);
        for (x, y, px) in img.enumerate_pixels() {
            let got = decoded
                .at(x as usize, y as usize)
                .unwrap_or_else(|| panic!("pixel ({x}, {y}) was never drawn"));
            for (got, want) in got.iter().zip(px.0.iter()) {
                total += (i32::from(*got) - i32::from(*want)).unsigned_abs() as u64;
                count += 1;
            }
        }
        let mean = total / count;
        assert!(mean <= 4, "mean channel error of {mean} is too high");
    }

    #[test]
    fn a_single_row_image_round_trips() {
        // One row in a band of six: the other five bits stay clear.
        let img = patchwork(24, 1);
        let decoded = decode(&encode(&img).unwrap());
        assert_eq!(decoded.painted_outside(), Vec::new());
        assert_same(&img, &decoded);
    }
}