-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathsixel.go
523 lines (496 loc) · 11.6 KB
/
sixel.go
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
package sixel
import (
"bufio"
"bytes"
"errors"
"fmt"
"image"
"image/color"
"image/draw"
"io"
"os"
"github.com/soniakeys/quant/median"
)
// Encoder encode image to sixel format
type Encoder struct {
w io.Writer
// Dither, if true, will dither the image when generating a paletted version
// using the Floyd–Steinberg dithering algorithm.
Dither bool
// Width is the maximum width to draw to.
Width int
// Height is the maximum height to draw to.
Height int
// Colors sets the number of colors for the encoder to quantize if needed.
// If the value is below 2 (e.g. the zero value), then 255 is used.
// A color is always reserved for alpha, so 2 colors give you 1 color.
Colors int
}
// NewEncoder return new instance of Encoder
func NewEncoder(w io.Writer) *Encoder {
return &Encoder{w: w}
}
const (
specialChNr = byte(0x6d)
specialChCr = byte(0x64)
)
// Encode do encoding
func (e *Encoder) Encode(img image.Image) error {
nc := e.Colors // (>= 2, 8bit, index 0 is reserved for transparent key color)
if nc < 2 {
nc = 255
}
width, height := img.Bounds().Dx(), img.Bounds().Dy()
if width == 0 || height == 0 {
return nil
}
if e.Width > 0 {
width = e.Width
}
if e.Height > 0 {
height = e.Height
}
var paletted *image.Paletted
// fast path for paletted images
if p, ok := img.(*image.Paletted); ok && len(p.Palette) < int(nc) {
paletted = p
} else {
// make adaptive palette using median cut alogrithm
q := median.Quantizer(nc - 1)
paletted = q.Paletted(img)
if e.Dither {
// copy source image to new image with applying floyd-stenberg dithering
draw.FloydSteinberg.Draw(paletted, img.Bounds(), img, image.Point{})
} else {
draw.Draw(paletted, img.Bounds(), img, image.Point{}, draw.Over)
}
}
// use on-memory output buffer for improving the performance
var w io.Writer
if _, ok := e.w.(*os.File); ok {
w = bytes.NewBuffer(make([]byte, 0, 1024*32))
} else {
w = e.w
}
// DECSIXEL Introducer(\033P0;0;8q) + DECGRA ("1;1): Set Raster Attributes
w.Write([]byte{0x1b, 0x50, 0x30, 0x3b, 0x30, 0x3b, 0x38, 0x71, 0x22, 0x31, 0x3b, 0x31})
for n, v := range paletted.Palette {
r, g, b, _ := v.RGBA()
r = r * 100 / 0xFFFF
g = g * 100 / 0xFFFF
b = b * 100 / 0xFFFF
// DECGCI (#): Graphics Color Introducer
fmt.Fprintf(w, "#%d;2;%d;%d;%d", n+1, r, g, b)
}
buf := make([]byte, width*nc)
cset := make([]bool, nc)
ch0 := specialChNr
for z := 0; z < (height+5)/6; z++ {
// DECGNL (-): Graphics Next Line
if z > 0 {
w.Write([]byte{0x2d})
}
for p := 0; p < 6; p++ {
y := z*6 + p
for x := 0; x < width; x++ {
_, _, _, alpha := img.At(x, y).RGBA()
if alpha != 0 {
idx := paletted.ColorIndexAt(x, y) + 1
cset[idx] = false // mark as used
buf[width*int(idx)+x] |= 1 << uint(p)
}
}
}
for n := 1; n < nc; n++ {
if cset[n] {
continue
}
cset[n] = true
// DECGCR ($): Graphics Carriage Return
if ch0 == specialChCr {
w.Write([]byte{0x24})
}
// select color (#%d)
if n >= 100 {
digit1 := n / 100
digit2 := (n - digit1*100) / 10
digit3 := n % 10
c1 := byte(0x30 + digit1)
c2 := byte(0x30 + digit2)
c3 := byte(0x30 + digit3)
w.Write([]byte{0x23, c1, c2, c3})
} else if n >= 10 {
c1 := byte(0x30 + n/10)
c2 := byte(0x30 + n%10)
w.Write([]byte{0x23, c1, c2})
} else {
w.Write([]byte{0x23, byte(0x30 + n)})
}
cnt := 0
for x := 0; x < width; x++ {
// make sixel character from 6 pixels
ch := buf[width*n+x]
buf[width*n+x] = 0
if ch0 < 0x40 && ch != ch0 {
// output sixel character
s := 63 + ch0
for ; cnt > 255; cnt -= 255 {
w.Write([]byte{0x21, 0x32, 0x35, 0x35, s})
}
if cnt == 1 {
w.Write([]byte{s})
} else if cnt == 2 {
w.Write([]byte{s, s})
} else if cnt == 3 {
w.Write([]byte{s, s, s})
} else if cnt >= 100 {
digit1 := cnt / 100
digit2 := (cnt - digit1*100) / 10
digit3 := cnt % 10
c1 := byte(0x30 + digit1)
c2 := byte(0x30 + digit2)
c3 := byte(0x30 + digit3)
// DECGRI (!): - Graphics Repeat Introducer
w.Write([]byte{0x21, c1, c2, c3, s})
} else if cnt >= 10 {
c1 := byte(0x30 + cnt/10)
c2 := byte(0x30 + cnt%10)
// DECGRI (!): - Graphics Repeat Introducer
w.Write([]byte{0x21, c1, c2, s})
} else if cnt > 0 {
// DECGRI (!): - Graphics Repeat Introducer
w.Write([]byte{0x21, byte(0x30 + cnt), s})
}
cnt = 0
}
ch0 = ch
cnt++
}
if ch0 != 0 {
// output sixel character
s := 63 + ch0
for ; cnt > 255; cnt -= 255 {
w.Write([]byte{0x21, 0x32, 0x35, 0x35, s})
}
if cnt == 1 {
w.Write([]byte{s})
} else if cnt == 2 {
w.Write([]byte{s, s})
} else if cnt == 3 {
w.Write([]byte{s, s, s})
} else if cnt >= 100 {
digit1 := cnt / 100
digit2 := (cnt - digit1*100) / 10
digit3 := cnt % 10
c1 := byte(0x30 + digit1)
c2 := byte(0x30 + digit2)
c3 := byte(0x30 + digit3)
// DECGRI (!): - Graphics Repeat Introducer
w.Write([]byte{0x21, c1, c2, c3, s})
} else if cnt >= 10 {
c1 := byte(0x30 + cnt/10)
c2 := byte(0x30 + cnt%10)
// DECGRI (!): - Graphics Repeat Introducer
w.Write([]byte{0x21, c1, c2, s})
} else if cnt > 0 {
// DECGRI (!): - Graphics Repeat Introducer
w.Write([]byte{0x21, byte(0x30 + cnt), s})
}
}
ch0 = specialChCr
}
}
// string terminator(ST)
w.Write([]byte{0x1b, 0x5c})
// copy to given buffer
if _, ok := e.w.(*os.File); ok {
w.(*bytes.Buffer).WriteTo(e.w)
}
return nil
}
// Decoder decode sixel format into image
type Decoder struct {
r io.Reader
}
// NewDecoder return new instance of Decoder
func NewDecoder(r io.Reader) *Decoder {
return &Decoder{r}
}
// Decode do decoding from image
func (e *Decoder) Decode(img *image.Image) error {
buf := bufio.NewReader(e.r)
_, err := buf.ReadBytes('\x1B')
if err != nil {
if err == io.EOF {
err = nil
}
return err
}
c, err := buf.ReadByte()
if err != nil {
return err
}
switch c {
case 'P':
_, err := buf.ReadString('q')
if err != nil {
return err
}
default:
return errors.New("Invalid format: illegal header")
}
colors := map[uint]color.Color{
// 16 predefined color registers of VT340
0: sixelRGB(0, 0, 0),
1: sixelRGB(20, 20, 80),
2: sixelRGB(80, 13, 13),
3: sixelRGB(20, 80, 20),
4: sixelRGB(80, 20, 80),
5: sixelRGB(20, 80, 80),
6: sixelRGB(80, 80, 20),
7: sixelRGB(53, 53, 53),
8: sixelRGB(26, 26, 26),
9: sixelRGB(33, 33, 60),
10: sixelRGB(60, 26, 26),
11: sixelRGB(33, 60, 33),
12: sixelRGB(60, 33, 60),
13: sixelRGB(33, 60, 60),
14: sixelRGB(60, 60, 33),
15: sixelRGB(80, 80, 80),
}
dx, dy := 0, 0
dw, dh, w, h := 0, 0, 200, 200
pimg := image.NewNRGBA(image.Rect(0, 0, w, h))
var cn uint
data:
for {
c, err = buf.ReadByte()
if err != nil {
if err == io.EOF {
err = nil
}
return err
}
if c == '\r' || c == '\n' || c == '\b' {
continue
}
switch {
case c == '\x1b':
c, err = buf.ReadByte()
if err != nil {
return err
}
if c == '\\' {
break data
}
case c == '"':
params := []int{}
for {
var i int
n, err := fmt.Fscanf(buf, "%d", &i)
if err == io.EOF {
return err
}
if n == 0 {
i = 0
}
params = append(params, i)
c, err = buf.ReadByte()
if err != nil {
return err
}
if c != ';' {
break
}
}
if len(params) >= 4 {
if w < params[2] {
w = params[2]
}
if h < params[3]+6 {
h = params[3] + 6
}
pimg = expandImage(pimg, w, h)
}
err = buf.UnreadByte()
if err != nil {
return err
}
case c == '$':
dx = 0
case c == '!':
err = buf.UnreadByte()
if err != nil {
return err
}
var nc uint
var c byte
n, err := fmt.Fscanf(buf, "!%d%c", &nc, &c)
if err != nil {
return err
}
if n != 2 || c < '?' || c > '~' {
return fmt.Errorf("invalid format: illegal repeating data tokens '!%d%c'", nc, c)
}
if w <= dx+int(nc)-1 {
w *= 2
pimg = expandImage(pimg, w, h)
}
m := byte(1)
c -= '?'
for p := 0; p < 6; p++ {
if c&m != 0 {
for q := 0; q < int(nc); q++ {
pimg.Set(dx+q, dy+p, colors[cn])
}
if dh < dy+p+1 {
dh = dy + p + 1
}
}
m <<= 1
}
dx += int(nc)
if dw < dx {
dw = dx
}
case c == '-':
dx = 0
dy += 6
if h <= dy+6 {
h *= 2
pimg = expandImage(pimg, w, h)
}
case c == '#':
err = buf.UnreadByte()
if err != nil {
return err
}
var nc, csys uint
var r, g, b uint
var c byte
n, err := fmt.Fscanf(buf, "#%d%c", &nc, &c)
if err != nil {
return err
}
if n != 2 {
return fmt.Errorf("invalid format: illegal color specifier '#%d%c'", nc, c)
}
if c == ';' {
n, err := fmt.Fscanf(buf, "%d;%d;%d;%d", &csys, &r, &g, &b)
if err != nil {
return err
}
if n != 4 {
return fmt.Errorf("invalid format: illegal color specifier '#%d;%d;%d;%d;%d'", nc, csys, r, g, b)
}
if csys == 1 {
colors[nc] = sixelHLS(r, g, b)
} else {
colors[nc] = sixelRGB(r, g, b)
}
} else {
err = buf.UnreadByte()
if err != nil {
return err
}
}
cn = nc
if _, ok := colors[cn]; !ok {
return fmt.Errorf("invalid format: undefined color number %d", cn)
}
default:
if c >= '?' && c <= '~' {
if w <= dx {
w *= 2
pimg = expandImage(pimg, w, h)
}
m := byte(1)
c -= '?'
for p := 0; p < 6; p++ {
if c&m != 0 {
pimg.Set(dx, dy+p, colors[cn])
if dh < dy+p+1 {
dh = dy + p + 1
}
}
m <<= 1
}
dx++
if dw < dx {
dw = dx
}
break
}
return errors.New("invalid format: illegal data tokens")
}
}
rect := image.Rect(0, 0, dw, dh)
tmp := image.NewNRGBA(rect)
draw.Draw(tmp, rect, pimg, image.Point{0, 0}, draw.Src)
*img = tmp
return nil
}
func sixelRGB(r, g, b uint) color.Color {
return color.NRGBA{uint8(r * 0xFF / 100), uint8(g * 0xFF / 100), uint8(b * 0xFF / 100), 0xFF}
}
func sixelHLS(h, l, s uint) color.Color {
var r, g, b, max, min float64
/* https://wikimedia.org/api/rest_v1/media/math/render/svg/17e876f7e3260ea7fed73f69e19c71eb715dd09d */
/* https://wikimedia.org/api/rest_v1/media/math/render/svg/f6721b57985ad83db3d5b800dc38c9980eedde1d */
if l > 50 {
max = float64(l) + float64(s)*(1.0-float64(l)/100.0)
min = float64(l) - float64(s)*(1.0-float64(l)/100.0)
} else {
max = float64(l) + float64(s*l)/100.0
min = float64(l) - float64(s*l)/100.0
}
/* sixel hue color ring is roteted -120 degree from nowdays general one. */
h = (h + 240) % 360
/* https://wikimedia.org/api/rest_v1/media/math/render/svg/937e8abdab308a22ff99de24d645ec9e70f1e384 */
switch h / 60 {
case 0: /* 0 <= hue < 60 */
r = max
g = min + (max-min)*(float64(h)/60.0)
b = min
break
case 1: /* 60 <= hue < 120 */
r = min + (max-min)*(float64(120-h)/60.0)
g = max
b = min
break
case 2: /* 120 <= hue < 180 */
r = min
g = max
b = min + (max-min)*(float64(h-120)/60.0)
break
case 3: /* 180 <= hue < 240 */
r = min
g = min + (max-min)*(float64(240-h)/60.0)
b = max
break
case 4: /* 240 <= hue < 300 */
r = min + (max-min)*(float64(h-240)/60.0)
g = min
b = max
break
case 5: /* 300 <= hue < 360 */
r = max
g = min
b = min + (max-min)*(float64(360-h)/60.0)
break
default:
}
return sixelRGB(uint(r), uint(g), uint(b))
}
func expandImage(pimg *image.NRGBA, w, h int) *image.NRGBA {
b := pimg.Bounds()
if w < b.Max.X {
w = b.Max.X
}
if h < b.Max.Y {
h = b.Max.Y
}
tmp := image.NewNRGBA(image.Rect(0, 0, w, h))
draw.Draw(tmp, b, pimg, image.Point{0, 0}, draw.Src)
return tmp
}