blob: 8cadd9413866df3d701fb47a4be637e231c7a56f [file] [log] [blame]
Nigel Tao981bf192018-05-23 12:17:55 +10001// Copyright 2018 The Wuffs Authors.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15// +build ignore
16
17package main
18
19// make-artificial.go makes test data in various formats.
20//
21// See test/data/artificial/*.make.txt for examples.
22//
23// Usage: go run make-artificial.go < foo.make.txt
24
25import (
26 "bytes"
27 "compress/lzw"
28 "fmt"
29 "io/ioutil"
30 "os"
31 "strconv"
32 "strings"
33)
34
35type stateFunc func(line string) (stateFunc, error)
36
37type repeat struct {
38 count uint32
39 remaining string
40}
41
42var (
43 state stateFunc
44 repeats []repeat
45 out []byte
46 formats = map[string]stateFunc{}
47)
48
49func main() {
50 if err := main1(); err != nil {
51 os.Stderr.WriteString(err.Error() + "\n")
52 os.Exit(1)
53 }
54}
55
56func main1() error {
57 stdin, err := ioutil.ReadAll(os.Stdin)
58 if err != nil {
59 return err
60 }
61 s := string(stdin)
62 for remaining := ""; len(s) > 0; s, remaining = remaining, "" {
63 if i := strings.IndexByte(s, '\n'); i >= 0 {
64 s, remaining = s[:i], s[i+1:]
65 }
66 s = strings.TrimSpace(s)
67 if s == "" || s[0] == '#' {
68 continue
69 }
70
71 if state == nil {
72 const m = "make "
73 if !strings.HasPrefix(s, m) {
74 return fmt.Errorf(`input must start with "make foo"`)
75 }
76 s = s[len(m):]
77 state = formats[s]
78 if state == nil {
79 return fmt.Errorf("unsupported format %q", s)
80 }
81 continue
82 }
83
84 const rep = "repeat "
85 if strings.HasPrefix(s, rep) {
86 args := s[len(rep):]
87 count, args, ok := parseNum(args)
88 if !ok || count <= 0 || args != "[" {
89 return fmt.Errorf("bad repeat command: %q", s)
90 }
91 repeats = append(repeats, repeat{
92 count: count,
93 remaining: remaining,
94 })
95 continue
96 }
97
98 if s == "]" {
99 if len(repeats) <= 0 {
100 return fmt.Errorf(`unbalanced close-repeat command: "]"`)
101 }
102 i := len(repeats) - 1
103 repeats[i].count--
104 if repeats[i].count == 0 {
105 repeats = repeats[:i]
106 } else {
107 remaining = repeats[i].remaining
108 }
109 continue
110 }
111
112 state, err = state(s)
113 if err != nil {
114 return err
115 }
116 if state == nil {
117 return fmt.Errorf("bad state transition")
118 }
119 }
120
121 _, err = os.Stdout.Write(out)
122 return err
123}
124
125// ----
126
127func appendU16LE(b []byte, u uint16) []byte {
128 return append(b, uint8(u), uint8(u>>8))
129}
130
131func log2(u uint32) (i int32) {
132 for i, pow := uint32(0), uint32(1); i < 32; i, pow = i+1, pow<<1 {
133 if u == pow {
134 return int32(i)
135 }
136 if u < pow {
137 break
138 }
139 }
140 return -1
141}
142
143func parseHex(s string) (num uint32, remaining string, ok bool) {
144 if i := strings.IndexByte(s, ' '); i >= 0 {
145 s, remaining = s[:i], s[i+1:]
146 for len(remaining) > 0 && remaining[0] == ' ' {
147 remaining = remaining[1:]
148 }
149 }
150
151 if len(s) < 2 || s[0] != '0' || s[1] != 'x' {
152 return 0, "", false
153 }
154 s = s[2:]
155
156 u, err := strconv.ParseUint(s, 16, 32)
157 if err != nil {
158 return 0, "", false
159 }
160 return uint32(u), remaining, true
161}
162
163func parseNum(s string) (num uint32, remaining string, ok bool) {
164 if i := strings.IndexByte(s, ' '); i >= 0 {
165 s, remaining = s[:i], s[i+1:]
166 for len(remaining) > 0 && remaining[0] == ' ' {
167 remaining = remaining[1:]
168 }
169 }
170
171 u, err := strconv.ParseUint(s, 10, 32)
172 if err != nil {
173 return 0, "", false
174 }
175 return uint32(u), remaining, true
176}
177
178func reverse(x uint32, n uint32) uint32 {
179 x = uint32(reverse8[0xFF&(x>>0)])<<24 |
180 uint32(reverse8[0xFF&(x>>8)])<<16 |
181 uint32(reverse8[0xFF&(x>>16)])<<8 |
182 uint32(reverse8[0xFF&(x>>24)])<<0
183 return x >> (32 - n)
184}
185
186var reverse8 = [256]byte{
187 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0, // 0x00 - 0x07
188 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0, // 0x08 - 0x0F
189 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8, // 0x10 - 0x17
190 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8, // 0x18 - 0x1F
191 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4, // 0x20 - 0x27
192 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4, // 0x28 - 0x2F
193 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC, // 0x30 - 0x37
194 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC, // 0x38 - 0x3F
195 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2, // 0x40 - 0x47
196 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2, // 0x48 - 0x4F
197 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA, // 0x50 - 0x57
198 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA, // 0x58 - 0x5F
199 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6, // 0x60 - 0x67
200 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6, // 0x68 - 0x6F
201 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE, // 0x70 - 0x77
202 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE, // 0x78 - 0x7F
203 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1, // 0x80 - 0x87
204 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1, // 0x88 - 0x8F
205 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9, // 0x90 - 0x97
206 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9, // 0x98 - 0x9F
207 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5, // 0xA0 - 0xA7
208 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5, // 0xA8 - 0xAF
209 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED, // 0xB0 - 0xB7
210 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD, // 0xB8 - 0xBF
211 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3, // 0xC0 - 0xC7
212 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3, // 0xC8 - 0xCF
213 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB, // 0xD0 - 0xD7
214 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB, // 0xD8 - 0xDF
215 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7, // 0xE0 - 0xE7
216 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7, // 0xE8 - 0xEF
217 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF, // 0xF0 - 0xF7
218 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF, // 0xF8 - 0xFF
219}
220
221// ----
222
223func init() {
224 formats["deflate"] = stateDeflate
225}
226
227var deflateGlobals struct {
228 bncData []byte
229 stream deflateBitStream
230}
231
232func stateDeflate(line string) (stateFunc, error) {
233 g := &deflateGlobals
234 const (
235 cmdBNC = "blockNoCompression "
236 cmdBFH = "blockFixedHuffman "
237 )
238 bits := uint32(0)
239 s := ""
240
241 retState := stateFunc(nil)
242 switch {
243 case strings.HasPrefix(line, cmdBNC):
244 s = line[len(cmdBNC):]
245 retState = stateDeflateNoCompression
246 bits |= 0 << 1
247 case strings.HasPrefix(line, cmdBFH):
248 s = line[len(cmdBFH):]
249 retState = stateDeflateFixedHuffman
250 bits |= 1 << 1
251 default:
252 return nil, fmt.Errorf("bad stateDeflate command: %q", line)
253 }
254
255 switch s {
256 case "(final) {":
257 bits |= 1
258 case "(nonFinal) {":
259 // No-op.
260 default:
261 return nil, fmt.Errorf("bad stateDeflate command: %q", line)
262 }
263
264 g.stream.writeBits(bits, 3)
265 return retState, nil
266}
267
268func stateDeflateNoCompression(line string) (stateFunc, error) {
269 g := &deflateGlobals
270 if line == "}" {
271 if len(g.bncData) > 0xFFFF {
272 return nil, fmt.Errorf("bncData is too long")
273 }
274 n := uint32(len(g.bncData))
275 g.stream.flush()
276 g.stream.writeBits(n, 16)
277 g.stream.writeBits(0xFFFF-n, 16)
278 g.stream.writeBytes(g.bncData)
279 g.bncData = g.bncData[:0]
280 return stateDeflate, nil
281 }
282
283 if lit, ok := deflateParseLiteral(line); ok {
284 g.bncData = append(g.bncData, lit...)
285 return stateDeflateNoCompression, nil
286 }
287
288 return nil, fmt.Errorf("bad blockNoCompression command: %q", line)
289}
290
291func stateDeflateFixedHuffman(line string) (stateFunc, error) {
292 g := &deflateGlobals
293 if line == "}" {
294 g.stream.flush()
295 return stateDeflate, nil
296 }
297
298 if line == "endOfBlock" {
299 g.stream.writeBits(0, 7)
300 return stateDeflateFixedHuffman, nil
301 }
302
303 if lit, ok := deflateParseLiteral(line); ok {
304 // TODO: support "\xAB" escape codes in the script?
305 for i := 0; i < len(lit); i++ {
306 g.stream.writeLCode(uint32(lit[i]))
307 }
308 return stateDeflateFixedHuffman, nil
309 }
310
311 if l, d, ok := deflateParseLenDist(line); ok {
312 lCode, lExtra, lNExtra := deflateEncodeLength(l)
313 g.stream.writeLCode(lCode)
314 g.stream.writeBits(lExtra, lNExtra)
315 dCode, dExtra, dNExtra := deflateEncodeDistance(d)
316 g.stream.writeBits(reverse(dCode, 5), 5)
317 g.stream.writeBits(dExtra, dNExtra)
318 return stateDeflateFixedHuffman, nil
319 }
320
321 return nil, fmt.Errorf("bad stateDeflateFixedHuffman command: %q", line)
322}
323
324type deflateBitStream struct {
325 bits uint32
326 nBits uint32 // Always within [0, 7].
327}
328
329// writeBits writes the low n bits of b to z.
330func (z *deflateBitStream) writeBits(b uint32, n uint32) {
331 if n > 24 {
332 panic("writeBits: n is too large")
333 }
334 z.bits |= b << z.nBits
335 z.nBits += n
336 for z.nBits >= 8 {
337 out = append(out, uint8(z.bits))
338 z.bits >>= 8
339 z.nBits -= 8
340 }
341}
342
343func (z *deflateBitStream) writeBytes(b []byte) {
344 z.flush()
345 out = append(out, b...)
346}
347
348func (z *deflateBitStream) writeLCode(lCode uint32) {
349 switch {
350 case lCode < 144: // 0b._0011_0000 through 0b._1011_1111
351 lCode += 0x030
352 z.writeBits(reverse(lCode, 8), 8)
353 case lCode < 256: // 0b1_1001_0000 through 0b1_1111_1111
354 lCode += 0x190 - 144
355 z.writeBits(reverse(lCode, 9), 9)
356 case lCode < 280: // 0b._.000_0000 through 0b._.001_0111
357 lCode -= 256 - 0x000
358 z.writeBits(reverse(lCode, 7), 7)
359 default: // 0b._1100_0000 through 0b._1100_0111
360 lCode -= 280 - 0x0C0
361 z.writeBits(reverse(lCode, 8), 8)
362 }
363}
364
365func (z *deflateBitStream) flush() {
366 if z.nBits > 0 {
367 out = append(out, uint8(z.bits))
368 z.bits = 0
369 z.nBits = 0
370 }
371}
372
373func deflateEncodeLength(l uint32) (code uint32, extra uint32, nExtra uint32) {
374 switch {
375 case l < 3:
376 // No-op.
377 case l < 11:
378 l -= 3
379 return (l >> 0) + 257, l & 0x0000, 0
380 case l < 19:
381 l -= 11
382 return (l >> 1) + 265, l & 0x0001, 1
383 case l < 35:
384 l -= 19
385 return (l >> 2) + 269, l & 0x0003, 2
386 case l < 67:
387 l -= 35
388 return (l >> 3) + 273, l & 0x0007, 3
389 case l < 131:
390 l -= 67
391 return (l >> 4) + 277, l & 0x000F, 4
392 case l < 258:
393 l -= 131
394 return (l >> 5) + 281, l & 0x001F, 5
395 case l == 258:
396 return 285, 0, 0
397 }
398 panic(fmt.Sprintf("deflateEncodeLength: l=%d", l))
399}
400
401func deflateEncodeDistance(d uint32) (code uint32, extra uint32, nExtra uint32) {
402 switch {
403 case d < 1:
404 // No-op.
405 case d < 5:
406 d -= 1
407 return (d >> 0) + 0, d & 0x0000, 0
408 case d < 9:
409 d -= 5
410 return (d >> 1) + 4, d & 0x0001, 1
411 case d < 17:
412 d -= 9
413 return (d >> 2) + 6, d & 0x0003, 2
414 case d < 33:
415 d -= 17
416 return (d >> 3) + 8, d & 0x0007, 3
417 case d < 65:
418 d -= 33
419 return (d >> 4) + 10, d & 0x000F, 4
420 case d < 129:
421 d -= 65
422 return (d >> 5) + 12, d & 0x001F, 5
423 case d < 257:
424 d -= 129
425 return (d >> 6) + 14, d & 0x003F, 6
426 case d < 513:
427 d -= 257
428 return (d >> 7) + 16, d & 0x007F, 7
429 case d < 1025:
430 d -= 513
431 return (d >> 8) + 18, d & 0x00FF, 8
432 case d < 2049:
433 d -= 1025
434 return (d >> 9) + 20, d & 0x01FF, 9
435 case d < 4097:
436 d -= 2049
437 return (d >> 10) + 22, d & 0x03FF, 10
438 case d < 8193:
439 d -= 4097
440 return (d >> 11) + 24, d & 0x07FF, 11
441 case d < 16385:
442 d -= 8193
443 return (d >> 12) + 26, d & 0x0FFF, 12
444 case d < 32769:
445 d -= 16385
446 return (d >> 13) + 28, d & 0x1FFF, 13
447 }
448 panic(fmt.Sprintf("deflateEncodeDistance: d=%d", d))
449}
450
451func deflateParseLiteral(s string) (lit string, ok bool) {
452 const (
453 prefix = `literal "`
454 suffix = `"`
455 )
456 if strings.HasPrefix(s, prefix) {
457 s = s[len(prefix):]
458 if strings.HasSuffix(s, suffix) {
459 return s[:len(s)-len(suffix)], true
460 }
461 }
462 return "", false
463}
464
465func deflateParseLenDist(line string) (l uint32, d uint32, ok bool) {
466 const (
467 lStr = "len "
468 dStr = "dist "
469 )
470 s := line
471 if strings.HasPrefix(s, lStr) {
472 s = s[len(lStr):]
473 if l, s, ok := parseNum(s); ok && 3 <= l && l <= 258 {
474 if strings.HasPrefix(s, dStr) {
475 s = s[len(dStr):]
476 if d, s, ok := parseNum(s); ok && 1 <= d && d <= 32768 && s == "" {
477 return l, d, true
478 }
479 }
480 }
481 }
482 return 0, 0, false
483}
484
485// ----
486
487func init() {
488 formats["gif"] = stateGif
489}
490
491var gifGlobals struct {
492 imageWidth uint32
493 imageHeight uint32
494
495 frameLeft uint32
496 frameTop uint32
497 frameWidth uint32
498 frameHeight uint32
499
500 globalPalette [][4]uint8
501}
502
503func stateGif(line string) (stateFunc, error) {
504 const (
Nigel Tao7be9c392018-10-13 17:00:45 +1100505 cmdL = "lzw "
506 cmdLC = "loopCount "
Nigel Tao981bf192018-05-23 12:17:55 +1000507 )
508outer:
509 switch {
510 case line == "frame {":
511 out = append(out, 0x2C)
512 return stateGifFrame, nil
513
514 case line == "header":
515 out = append(out, "GIF89a"...)
516 return stateGif, nil
517
518 case line == "image {":
519 return stateGifImage, nil
520
521 case line == "trailer":
522 out = append(out, 0x3B)
523 return stateGif, nil
524
525 case strings.HasPrefix(line, cmdL):
526 s := line[len(cmdL):]
527 litWidth, s, ok := parseNum(s)
528 if !ok || litWidth < 2 || 8 < litWidth {
529 break
530 }
531 out = append(out, uint8(litWidth))
532
533 uncompressed := []byte(nil)
534 for s != "" {
535 x := uint32(0)
536 x, s, ok = parseHex(s)
537 if !ok {
538 break outer
539 }
540 uncompressed = append(uncompressed, uint8(x))
541 }
542
543 buf := bytes.NewBuffer(nil)
544 w := lzw.NewWriter(buf, lzw.LSB, int(litWidth))
545 if _, err := w.Write(uncompressed); err != nil {
546 return nil, err
547 }
548 if err := w.Close(); err != nil {
549 return nil, err
550 }
551 compressed := buf.Bytes()
552
553 for len(compressed) > 0 {
554 if len(compressed) <= 0xFF {
555 out = append(out, uint8(len(compressed)))
556 out = append(out, compressed...)
557 compressed = nil
558 } else {
559 out = append(out, 0xFF)
560 out = append(out, compressed[:0xFF]...)
561 compressed = compressed[0xFF:]
562 }
563 }
564 out = append(out, 0x00)
565 return stateGif, nil
Nigel Tao7be9c392018-10-13 17:00:45 +1100566
567 case strings.HasPrefix(line, cmdLC):
568 s := line[len(cmdLC):]
569 loopCount, _, ok := parseNum(s)
570 if !ok || 0xFFFF < loopCount {
571 break
572 }
573 out = append(out,
574 0x21, // Extension Introducer.
575 0xFF, // Application Extension Label.
576 0x0B, // Block Size.
577 )
578 out = append(out, "NETSCAPE2.0"...)
579 out = append(out,
580 0x03, // Block Size.
581 0x01, // Magic Number.
582 byte(loopCount),
583 byte(loopCount>>8),
584 0x00, // Block Terminator.
585 )
586 return stateGif, nil
Nigel Tao981bf192018-05-23 12:17:55 +1000587 }
588
589 return nil, fmt.Errorf("bad stateGif command: %q", line)
590}
591
592func stateGifImage(line string) (stateFunc, error) {
593 g := &gifGlobals
594 if line == "}" {
595 out = appendU16LE(out, uint16(g.imageWidth))
596 out = appendU16LE(out, uint16(g.imageHeight))
597 if g.globalPalette == nil {
598 out = append(out, 0x00)
599 } else if n := log2(uint32(len(g.globalPalette))); n < 2 || 8 < n {
600 return nil, fmt.Errorf("bad len(g.globalPalette): %d", len(g.globalPalette))
601 } else {
602 out = append(out, 0x80|uint8(n-1))
603 }
604 out = append(out, 0x00) // TODO: background index.
605 out = append(out, 0x00)
606 for _, x := range g.globalPalette {
607 out = append(out, x[0], x[1], x[2])
608 }
609 return stateGif, nil
610 }
611
612 const (
613 cmdIWH = "imageWidthHeight "
614 cmdP = "palette {"
615 )
616 switch {
617 case strings.HasPrefix(line, cmdIWH):
618 s := line[len(cmdIWH):]
619 if w, s, ok := parseNum(s); ok {
620 if h, _, ok := parseNum(s); ok {
621 g.imageWidth = w
622 g.imageHeight = h
623 return stateGifImage, nil
624 }
625 }
626
627 case strings.HasPrefix(line, cmdP):
628 return stateGifImagePalette, nil
629 }
630
631 return nil, fmt.Errorf("bad stateGifImage command: %q", line)
632}
633
634func stateGifFrame(line string) (stateFunc, error) {
635 g := &gifGlobals
636 if line == "}" {
637 out = appendU16LE(out, uint16(g.frameLeft))
638 out = appendU16LE(out, uint16(g.frameTop))
639 out = appendU16LE(out, uint16(g.frameWidth))
640 out = appendU16LE(out, uint16(g.frameHeight))
641 out = append(out, 0x00) // TODO: flags.
642 return stateGif, nil
643 }
644
645 const (
646 cmdFLTWH = "frameLeftTopWidthHeight "
647 )
648 switch {
649 case strings.HasPrefix(line, cmdFLTWH):
650 s := line[len(cmdFLTWH):]
651 if l, s, ok := parseNum(s); ok {
652 if t, s, ok := parseNum(s); ok {
653 if w, s, ok := parseNum(s); ok {
654 if h, _, ok := parseNum(s); ok {
655 g.frameLeft = l
656 g.frameTop = t
657 g.frameWidth = w
658 g.frameHeight = h
659 return stateGifFrame, nil
660 }
661 }
662 }
663 }
664 }
665
666 return nil, fmt.Errorf("bad stateGifFrame command: %q", line)
667}
668
669func stateGifImagePalette(line string) (stateFunc, error) {
670 g := &gifGlobals
671 if line == "}" {
672 return stateGifImage, nil
673 }
674
675 s := line
676 if rgb0, s, ok := parseHex(s); ok {
677 if rgb1, s, ok := parseHex(s); ok {
678 if rgb2, _, ok := parseHex(s); ok {
679 g.globalPalette = append(g.globalPalette,
680 [4]uint8{uint8(rgb0), uint8(rgb1), uint8(rgb2), 0xFF})
681 return stateGifImagePalette, nil
682 }
683 }
684 }
685
686 return nil, fmt.Errorf("bad stateGifImagePalette command: %q", line)
687}