Debian Codegraph @

ansi/sixel/encoder.go

raw
1 package sixel
2
3 import (
4 "fmt"
5 "image"
6 "image/color"
7 "io"
8 "strconv"
9 "strings"
10
11 "github.com/bits-and-blooms/bitset"
12 )
13
14 // Sixels are a protocol for writing images to the terminal by writing a large blob of ANSI-escaped data.
15 // They function by encoding columns of 6 pixels into a single character (in much the same way base64
16 // encodes data 6 bits at a time). Sixel images are paletted, with a palette established at the beginning
17 // of the image blob and pixels identifying palette entires by index while writing the pixel data.
18 //
19 // Sixels are written one 6-pixel-tall band at a time, one color at a time. For each band, a single
20 // color's pixels are written, then a carriage return is written to bring the "cursor" back to the
21 // beginning of a band where a new color is selected and pixels written. This continues until the entire
22 // band has been drawn, at which time a line break is written to begin the next band.
23
24 // Sixel control functions.
25 const (
26 LineBreak byte = '-'
27 CarriageReturn byte = '$'
28 RepeatIntroducer byte = '!'
29 ColorIntroducer byte = '#'
30 RasterAttribute byte = '"'
31 )
32
33 // Encoder is a Sixel encoder. It encodes an image to Sixel data format.
34 type Encoder struct{}
35
36 // Encode will accept an Image and write sixel data to a Writer. The sixel data
37 // will be everything after the 'q' that ends the DCS parameters and before the ST
38 // that ends the sequence. That means it includes the pixel metrics and color
39 // palette.
40 func (e *Encoder) Encode(w io.Writer, img image.Image) error {
41 if img == nil {
42 return nil
43 }
44
45 imageBounds := img.Bounds()
46
47 // Set the default raster 1:1 aspect ratio if it's not set
48 if _, err := WriteRaster(w, 1, 1, imageBounds.Dx(), imageBounds.Dy()); err != nil {
49 return fmt.Errorf("error encoding raster: %w", err)
50 }
51
52 palette := newSixelPalette(img, MaxColors)
53
54 for paletteIndex, color := range palette.PaletteColors {
55 e.encodePaletteColor(w, paletteIndex, color)
56 }
57
58 scratch := newSixelBuilder(imageBounds.Dx(), imageBounds.Dy(), palette)
59
60 for y := range imageBounds.Dy() {
61 for x := range imageBounds.Dx() {
62 scratch.SetColor(x, y, img.At(x, y))
63 }
64 }
65
66 pixels := scratch.GeneratePixels()
67 io.WriteString(w, pixels) //nolint:errcheck,gosec
68
69 return nil
70 }
71
72 func (e *Encoder) encodePaletteColor(w io.Writer, paletteIndex int, c sixelColor) {
73 // Initializing palette entries
74 // #<a>;<b>;<c>;<d>;<e>
75 // a = palette index
76 // b = color type, 2 is RGB
77 // c = R
78 // d = G
79 // e = B
80
81 w.Write([]byte{ColorIntroducer}) //nolint:errcheck,gosec
82 io.WriteString(w, strconv.Itoa(paletteIndex)) //nolint:errcheck,gosec
83 io.WriteString(w, ";2;") //nolint:errcheck,gosec
84 io.WriteString(w, strconv.Itoa(int(c.Red))) //nolint:errcheck,gosec
85 w.Write([]byte{';'}) //nolint:errcheck,gosec
86 io.WriteString(w, strconv.Itoa(int(c.Green))) //nolint:errcheck,gosec
87 w.Write([]byte{';'}) //nolint:errcheck,gosec
88 io.WriteString(w, strconv.Itoa(int(c.Blue))) //nolint:errcheck,gosec
89 }
90
91 // sixelBuilder is a temporary structure used to create a SixelImage. It handles
92 // breaking pixels out into bits, and then encoding them into a sixel data string. RLE
93 // handling is included.
94 //
95 // Making use of a sixelBuilder is done in two phases. First, SetColor is used to write all
96 // pixels to the internal BitSet data. Then, GeneratePixels is called to retrieve a string
97 // representing the pixel data encoded in the sixel format.
98 type sixelBuilder struct {
99 SixelPalette sixelPalette
100
101 imageHeight int
102 imageWidth int
103
104 pixelBands bitset.BitSet
105
106 imageData strings.Builder
107 repeatByte byte
108 repeatCount int
109 }
110
111 // newSixelBuilder creates a sixelBuilder and prepares it for writing.
112 func newSixelBuilder(width, height int, palette sixelPalette) sixelBuilder {
113 scratch := sixelBuilder{
114 imageWidth: width,
115 imageHeight: height,
116 SixelPalette: palette,
117 }
118
119 return scratch
120 }
121
122 // BandHeight returns the number of six-pixel bands this image consists of.
123 func (s *sixelBuilder) BandHeight() int {
124 bandHeight := s.imageHeight / 6
125 if s.imageHeight%6 != 0 {
126 bandHeight++
127 }
128
129 return bandHeight
130 }
131
132 // SetColor will write a single pixel to sixelBuilder's internal bitset data to be used by
133 // GeneratePixels.
134 func (s *sixelBuilder) SetColor(x int, y int, color color.Color) {
135 bandY := y / 6
136 paletteIndex := s.SixelPalette.ColorIndex(sixelConvertColor(color))
137
138 bit := s.BandHeight()*s.imageWidth*6*paletteIndex + bandY*s.imageWidth*6 + (x * 6) + (y % 6)
139 s.pixelBands.Set(uint(bit)) //nolint:gosec
140 }
141
142 // GeneratePixels is used to write the pixel data to the internal imageData string builder.
143 // All pixels in the image must be written to the sixelBuilder using SetColor before this method is
144 // called. This method returns a string that represents the pixel data. Sixel strings consist of five parts:
145 // ISC <header> <palette> <pixels> ST
146 // The header contains some arbitrary options indicating how the sixel image is to be drawn.
147 // The palette maps palette indices to RGB colors
148 // The pixels indicates which pixels are to be drawn with which palette colors.
149 //
150 // GeneratePixels only produces the <pixels> part of the string. The rest is written by
151 // Style.RenderSixelImage.
152 func (s *sixelBuilder) GeneratePixels() string {
153 s.imageData = strings.Builder{}
154 bandHeight := s.BandHeight()
155
156 for bandY := range bandHeight {
157 if bandY > 0 {
158 s.writeControlRune(LineBreak)
159 }
160
161 hasWrittenAColor := false
162
163 for paletteIndex := range s.SixelPalette.PaletteColors {
164 if s.SixelPalette.PaletteColors[paletteIndex].Alpha < 1 {
165 // Don't draw anything for purely transparent pixels
166 continue
167 }
168
169 firstColorBit := uint(s.BandHeight()*s.imageWidth*6*paletteIndex + bandY*s.imageWidth*6) //nolint:gosec
170 nextColorBit := firstColorBit + uint(s.imageWidth*6) //nolint:gosec
171
172 firstSetBitInBand, anySet := s.pixelBands.NextSet(firstColorBit)
173 if !anySet || firstSetBitInBand >= nextColorBit {
174 // Color not appearing in this row
175 continue
176 }
177
178 if hasWrittenAColor {
179 s.writeControlRune(CarriageReturn)
180 }
181 hasWrittenAColor = true
182
183 s.writeControlRune(ColorIntroducer)
184 s.imageData.WriteString(strconv.Itoa(paletteIndex))
185 for x := 0; x < s.imageWidth; x += 4 {
186 bit := firstColorBit + uint(x*6) //nolint:gosec
187 word := s.pixelBands.GetWord64AtBit(bit)
188
189 pixel1 := byte((word & 63) + '?')
190 pixel2 := byte(((word >> 6) & 63) + '?')
191 pixel3 := byte(((word >> 12) & 63) + '?')
192 pixel4 := byte(((word >> 18) & 63) + '?')
193
194 s.writeImageRune(pixel1)
195
196 if x+1 >= s.imageWidth {
197 continue
198 }
199 s.writeImageRune(pixel2)
200
201 if x+2 >= s.imageWidth {
202 continue
203 }
204 s.writeImageRune(pixel3)
205
206 if x+3 >= s.imageWidth {
207 continue
208 }
209 s.writeImageRune(pixel4)
210 }
211 }
212 }
213
214 s.writeControlRune('-')
215 return s.imageData.String()
216 }
217
218 // writeImageRune will write a single line of six pixels to pixel data. The data
219 // doesn't get written to the imageData, it gets buffered for the purposes of RLE.
220 func (s *sixelBuilder) writeImageRune(r byte) {
221 if r == s.repeatByte {
222 s.repeatCount++
223 return
224 }
225
226 s.flushRepeats()
227 s.repeatByte = r
228 s.repeatCount = 1
229 }
230
231 // writeControlRune will write a special rune such as a new line or carriage return
232 // rune. It will call flushRepeats first, if necessary.
233 func (s *sixelBuilder) writeControlRune(r byte) {
234 if s.repeatCount > 0 {
235 s.flushRepeats()
236 s.repeatCount = 0
237 s.repeatByte = 0
238 }
239
240 s.imageData.WriteByte(r)
241 }
242
243 // flushRepeats is used to actually write the current repeatByte to the imageData when
244 // it is about to change. This buffering is used to manage RLE in the sixelBuilder.
245 func (s *sixelBuilder) flushRepeats() {
246 if s.repeatCount == 0 {
247 return
248 }
249
250 // Only write using the RLE form if it's actually providing space savings
251 if s.repeatCount > 3 {
252 WriteRepeat(&s.imageData, s.repeatCount, s.repeatByte) //nolint:errcheck,gosec
253 return
254 }
255
256 for range s.repeatCount {
257 s.imageData.WriteByte(s.repeatByte)
258 }
259 }