Debian Codegraph @

img.go

raw symbols SCIP
1 // Package qart generates a pretty qr img
2 /**
3 * Copyright ©2014-04-07 Alex <[email protected]>
4 */
5 package qart
6
7 import (
8 "bytes"
9 "fmt"
10 "github.com/vitrun/qart/coding"
11 "github.com/vitrun/qart/gf256"
12 "github.com/vitrun/qart/qr"
13 "image"
14 "image/png"
15 _ "image/jpeg"
16 "math/rand"
17 "sort"
18 )
19
20 type pixinfo struct {
21 X int
22 Y int
23 Pix coding.Pixel
24 Targ byte
25 DTarg int
26 Contrast int
27 HardZero bool
28 Block *bitBlock
29 Bit uint
30 }
31
32 type bitBlock struct {
33 DataBytes int
34 CheckBytes int
35 B []byte
36 M [][]byte
37 Tmp []byte
38 RS *gf256.RSEncoder
39 bdata []byte
40 cdata []byte
41 }
42
43 func (b *bitBlock) check() {
44 b.RS.ECC(b.B[:b.DataBytes], b.Tmp)
45 if !bytes.Equal(b.B[b.DataBytes:], b.Tmp) {
46 fmt.Printf("ecc mismatch\n%x\n%x\n", b.B[b.DataBytes:], b.Tmp)
47 panic("mismatch")
48 }
49 }
50
51 func (b *bitBlock) reset(bi uint, bval byte) {
52 if (b.B[bi/8]>>(7-bi&7))&1 == bval {
53 // already has desired bit
54 return
55 }
56 // rows that have already been set
57 m := b.M[len(b.M):cap(b.M)]
58 for _, row := range m {
59 if row[bi/8]&(1<<(7-bi&7)) != 0 {
60 // Found it.
61 for j, v := range row {
62 b.B[j] ^= v
63 }
64 return
65 }
66 }
67 panic("reset of unset bit")
68 }
69
70 func (b *bitBlock) canSet(bi uint, bval byte) bool {
71 found := false
72 m := b.M
73 for j, row := range m {
74 if row[bi/8]&(1<<(7-bi&7)) == 0 {
75 continue
76 }
77 if !found {
78 found = true
79 if j != 0 {
80 m[0], m[j] = m[j], m[0]
81 }
82 continue
83 }
84 for k := range row {
85 row[k] ^= m[0][k]
86 }
87 }
88 if !found {
89 return false
90 }
91
92 targ := m[0]
93
94 // Subtract from saved-away rows too.
95 for _, row := range m[len(m):cap(m)] {
96 if row[bi/8]&(1<<(7-bi&7)) == 0 {
97 continue
98 }
99 for k := range row {
100 row[k] ^= targ[k]
101 }
102 }
103
104 // Found a row with bit #bi == 1 and cut that bit from all the others.
105 // Apply to data and remove from m.
106 if (b.B[bi/8]>>(7-bi&7))&1 != bval {
107 for j, v := range targ {
108 b.B[j] ^= v
109 }
110 }
111 b.check()
112 n := len(m) - 1
113 m[0], m[n] = m[n], m[0]
114 b.M = m[:n]
115
116 for _, row := range b.M {
117 if row[bi/8]&(1<<(7-bi&7)) != 0 {
118 panic("did not reduce")
119 }
120 }
121
122 return true
123 }
124
125 func (b *bitBlock) copyOut() {
126 b.check()
127 copy(b.bdata, b.B[:b.DataBytes])
128 copy(b.cdata, b.B[b.DataBytes:])
129 }
130
131 type pixOrder struct {
132 Off int
133 Priority int
134 }
135
136 type byPriority []pixOrder
137
138 func (x byPriority) Len() int { return len(x) }
139 func (x byPriority) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
140 func (x byPriority) Less(i, j int) bool { return x[i].Priority > x[j].Priority }
141
142 func loadSize(data []byte, max int) *image.RGBA {
143 i, _, err := image.Decode(bytes.NewBuffer(data))
144 if err != nil {
145 panic(err)
146 }
147 // switch i := i.(type) {
148 // case *image.RGBA64:
149 // i = i.RGBA()
150 // }
151
152 b := i.Bounds()
153 dx, dy := max, max
154 if b.Dx() > b.Dy() {
155 dy = b.Dy() * dx / b.Dx()
156 } else {
157 dx = b.Dx() * dy / b.Dy()
158 }
159 var irgba *image.RGBA
160 switch i := i.(type) {
161 case *image.RGBA:
162 irgba = qr.ResizeRGBA(i, i.Bounds(), dx, dy)
163 case *image.NRGBA:
164 irgba = qr.ResizeNRGBA(i, i.Bounds(), dx, dy)
165 }
166 return irgba
167 }
168
169 func makeTarg(data []byte, max int) [][]int {
170 i := loadSize(data, max)
171 b := i.Bounds()
172 dx, dy := b.Dx(), b.Dy()
173 targ := make([][]int, dy)
174 arr := make([]int, dx*dy)
175 for y := 0; y < dy; y++ {
176 targ[y], arr = arr[:dx], arr[dx:]
177 row := targ[y]
178 for x := 0; x < dx; x++ {
179 p := i.Pix[y*i.Stride+4*x:]
180 r, g, b, a := p[0], p[1], p[2], p[3]
181 if a == 0 {
182 row[x] = -1
183 } else {
184 row[x] = int((299*uint32(r) + 587*uint32(g) + 114*uint32(b) + 500) / 1000)
185 }
186 }
187 }
188 return targ
189 }
190
191 func newBlock(nd, nc int, rs *gf256.RSEncoder, dat, cdata []byte) *bitBlock {
192 b := &bitBlock{
193 DataBytes: nd,
194 CheckBytes: nc,
195 B: make([]byte, nd+nc),
196 Tmp: make([]byte, nc),
197 RS: rs,
198 bdata: dat,
199 cdata: cdata,
200 }
201 copy(b.B, dat)
202 rs.ECC(b.B[:nd], b.B[nd:])
203 b.check()
204 if !bytes.Equal(b.Tmp, cdata) {
205 panic("cdata")
206 }
207
208 b.M = make([][]byte, nd*8)
209 for i := range b.M {
210 row := make([]byte, nd+nc)
211 b.M[i] = row
212 for j := range row {
213 row[j] = 0
214 }
215 row[i/8] = 1 << (7 - uint(i%8))
216 rs.ECC(row[:nd], row[nd:])
217 }
218 return b
219 }
220
221 func pngEncode(c image.Image) []byte {
222 var b bytes.Buffer
223 png.Encode(&b, c)
224 return b.Bytes()
225 }
226
227 func addDither(pixByOff []pixinfo, pix coding.Pixel, err int) {
228 if pix.Role() != coding.Data && pix.Role() != coding.Check {
229 return
230 }
231 pinfo := &pixByOff[pix.Offset()]
232 println("add", pinfo.X, pinfo.Y, pinfo.DTarg, err)
233 pinfo.DTarg += err
234 }
235
236 // Image generates the pretty qr code
237 type Image struct {
238 Target [][]int
239 Dx int
240 Dy int
241 URL string
242 Tag string
243 Version int
244 Mask int
245 Scale int
246 Rotation int
247 Size int
248
249 // RandControl says to pick the pixels randomly.
250 RandControl bool
251 Seed int64
252
253 // Dither says to dither instead of using threshold pixel layout.
254 Dither bool
255
256 // OnlyDataBits says to use only data bits, not check bits.
257 OnlyDataBits bool
258
259 // Code is the final QR code.
260 Code *qr.Code
261
262 // Control is a PNG showing the pixels that we controlled.
263 // Pixels we don't control are grayed out.
264 SaveControl bool
265 Control []byte
266 }
267
268 func (m *Image) target(x, y int) (targ byte, contrast int) {
269 tx := x + m.Dx
270 ty := y + m.Dy
271 if ty < 0 || ty >= len(m.Target) || tx < 0 || tx >= len(m.Target[ty]) {
272 return 255, -1
273 }
274
275 v0 := m.Target[ty][tx]
276 if v0 < 0 {
277 return 255, -1
278 }
279 targ = byte(v0)
280
281 n := 0
282 sum := 0
283 sumsq := 0
284 const del = 5
285 for dy := -del; dy <= del; dy++ {
286 for dx := -del; dx <= del; dx++ {
287 if 0 <= ty+dy && ty+dy < len(m.Target) && 0 <= tx+dx && tx+dx < len(m.Target[ty+dy]) {
288 v := m.Target[ty+dy][tx+dx]
289 sum += v
290 sumsq += v * v
291 n++
292 }
293 }
294 }
295
296 avg := sum / n
297 contrast = sumsq/n - avg*avg
298 return
299 }
300
301 func (m *Image) rotate(p *coding.Plan, rot int) {
302 if rot == 0 {
303 return
304 }
305
306 N := len(p.Pixel)
307 pix := make([][]coding.Pixel, N)
308 apix := make([]coding.Pixel, N*N)
309 for i := range pix {
310 pix[i], apix = apix[:N], apix[N:]
311 }
312
313 switch rot {
314 case 0:
315 // ok
316 case 1:
317 for y := 0; y < N; y++ {
318 for x := 0; x < N; x++ {
319 pix[y][x] = p.Pixel[x][N-1-y]
320 }
321 }
322 case 2:
323 for y := 0; y < N; y++ {
324 for x := 0; x < N; x++ {
325 pix[y][x] = p.Pixel[N-1-y][N-1-x]
326 }
327 }
328 case 3:
329 for y := 0; y < N; y++ {
330 for x := 0; x < N; x++ {
331 pix[y][x] = p.Pixel[N-1-x][y]
332 }
333 }
334 }
335
336 p.Pixel = pix
337 }
338
339 // Encode encodes
340 func (m *Image) Encode() error {
341 p, err := coding.NewPlan(coding.Version(m.Version), coding.L, coding.Mask(m.Mask))
342 if err != nil {
343 return err
344 }
345
346 m.rotate(p, m.Rotation)
347
348 // QR parameters.
349 nd := p.DataBytes / p.Blocks
350 nc := p.CheckBytes / p.Blocks
351 extra := p.DataBytes - nd*p.Blocks
352 rs := gf256.NewRSEncoder(coding.Field, nc)
353
354 // Build information about pixels, indexed by data/check bit number.
355 pixByOff := make([]pixinfo, (p.DataBytes+p.CheckBytes)*8)
356 expect := make([][]bool, len(p.Pixel))
357 for y, row := range p.Pixel {
358 expect[y] = make([]bool, len(row))
359 for x, pix := range row {
360 targ, contrast := m.target(x, y)
361 if m.RandControl && contrast >= 0 {
362 contrast = rand.Intn(128) + 64*((x+y)%2) + 64*((x+y)%3%2)
363 }
364 expect[y][x] = pix&coding.Black != 0
365 if r := pix.Role(); r == coding.Data || r == coding.Check {
366 pixByOff[pix.Offset()] = pixinfo{X: x, Y: y, Pix: pix, Targ: targ, Contrast: contrast}
367 }
368 }
369 }
370
371 Again:
372 // Count fixed initial data bits, prepare template URL.
373 url := m.URL + "#"
374 var b coding.Bits
375 coding.String(url).Encode(&b, p.Version)
376 coding.Num("").Encode(&b, p.Version)
377 bbit := b.Bits()
378 dbit := p.DataBytes*8 - bbit
379 if dbit < 0 {
380 return fmt.Errorf("cannot encode URL into available bits")
381 }
382 num := make([]byte, dbit/10*3)
383 for i := range num {
384 num[i] = '0'
385 }
386 b.Pad(dbit)
387 b.Reset()
388 coding.String(url).Encode(&b, p.Version)
389 coding.Num(num).Encode(&b, p.Version)
390 b.AddCheckBytes(p.Version, p.Level)
391 data := b.Bytes()
392
393 doff := 0 // data offset
394 coff := 0 // checksum offset
395 mbit := bbit + dbit/10*10
396
397 // Choose pixels.
398 bitblocks := make([]*bitBlock, p.Blocks)
399 for blocknum := 0; blocknum < p.Blocks; blocknum++ {
400 if blocknum == p.Blocks-extra {
401 nd++
402 }
403
404 bdata := data[doff/8 : doff/8+nd]
405 cdata := data[p.DataBytes+coff/8 : p.DataBytes+coff/8+nc]
406 bb := newBlock(nd, nc, rs, bdata, cdata)
407 bitblocks[blocknum] = bb
408
409 // Determine which bits in this block we can try to edit.
410 lo, hi := 0, nd*8
411 if lo < bbit-doff {
412 lo = bbit - doff
413 if lo > hi {
414 lo = hi
415 }
416 }
417 if hi > mbit-doff {
418 hi = mbit - doff
419 if hi < lo {
420 hi = lo
421 }
422 }
423
424 // Preserve [0, lo) and [hi, nd*8).
425 for i := 0; i < lo; i++ {
426 if !bb.canSet(uint(i), (bdata[i/8]>>uint(7-i&7))&1) {
427 return fmt.Errorf("cannot preserve required bits")
428 }
429 }
430 for i := hi; i < nd*8; i++ {
431 if !bb.canSet(uint(i), (bdata[i/8]>>uint(7-i&7))&1) {
432 return fmt.Errorf("cannot preserve required bits")
433 }
434 }
435
436 // Can edit [lo, hi) and checksum bits to hit target.
437 // Determine which ones to try first.
438 order := make([]pixOrder, (hi-lo)+nc*8)
439 for i := lo; i < hi; i++ {
440 order[i-lo].Off = doff + i
441 }
442 for i := 0; i < nc*8; i++ {
443 order[hi-lo+i].Off = p.DataBytes*8 + coff + i
444 }
445 if m.OnlyDataBits {
446 order = order[:hi-lo]
447 }
448 for i := range order {
449 po := &order[i]
450 po.Priority = pixByOff[po.Off].Contrast<<8 | rand.Intn(256)
451 }
452 sort.Sort(byPriority(order))
453
454 const mark = false
455 for i := range order {
456 po := &order[i]
457 pinfo := &pixByOff[po.Off]
458 bval := pinfo.Targ
459 if bval < 128 {
460 bval = 1
461 } else {
462 bval = 0
463 }
464 pix := pinfo.Pix
465 if pix&coding.Invert != 0 {
466 bval ^= 1
467 }
468 if pinfo.HardZero {
469 bval = 0
470 }
471
472 var bi int
473 if pix.Role() == coding.Data {
474 bi = po.Off - doff
475 } else {
476 bi = po.Off - p.DataBytes*8 - coff + nd*8
477 }
478 if bb.canSet(uint(bi), bval) {
479 pinfo.Block = bb
480 pinfo.Bit = uint(bi)
481 if mark {
482 p.Pixel[pinfo.Y][pinfo.X] = coding.Black
483 }
484 } else {
485 if pinfo.HardZero {
486 panic("hard zero")
487 }
488 if mark {
489 p.Pixel[pinfo.Y][pinfo.X] = 0
490 }
491 }
492 }
493 bb.copyOut()
494
495 const cheat = false
496 for i := 0; i < nd*8; i++ {
497 pinfo := &pixByOff[doff+i]
498 pix := p.Pixel[pinfo.Y][pinfo.X]
499 if bb.B[i/8]&(1<<uint(7-i&7)) != 0 {
500 pix ^= coding.Black
501 }
502 expect[pinfo.Y][pinfo.X] = pix&coding.Black != 0
503 if cheat {
504 p.Pixel[pinfo.Y][pinfo.X] = pix & coding.Black
505 }
506 }
507 for i := 0; i < nc*8; i++ {
508 pinfo := &pixByOff[p.DataBytes*8+coff+i]
509 pix := p.Pixel[pinfo.Y][pinfo.X]
510 if bb.B[nd+i/8]&(1<<uint(7-i&7)) != 0 {
511 pix ^= coding.Black
512 }
513 expect[pinfo.Y][pinfo.X] = pix&coding.Black != 0
514 if cheat {
515 p.Pixel[pinfo.Y][pinfo.X] = pix & coding.Black
516 }
517 }
518 doff += nd * 8
519 coff += nc * 8
520 }
521
522 // Pass over all pixels again, dithering.
523 if m.Dither {
524 for i := range pixByOff {
525 pinfo := &pixByOff[i]
526 pinfo.DTarg = int(pinfo.Targ)
527 }
528 for y, row := range p.Pixel {
529 for x, pix := range row {
530 if pix.Role() != coding.Data && pix.Role() != coding.Check {
531 continue
532 }
533 pinfo := &pixByOff[pix.Offset()]
534 if pinfo.Block == nil {
535 // did not choose this pixel
536 continue
537 }
538
539 pix := pinfo.Pix
540
541 pval := byte(1) // pixel value (black)
542 v := 0 // gray value (black)
543 targ := pinfo.DTarg
544 if targ >= 128 {
545 // want white
546 pval = 0
547 v = 255
548 }
549
550 bval := pval // bit value
551 if pix&coding.Invert != 0 {
552 bval ^= 1
553 }
554 if pinfo.HardZero && bval != 0 {
555 bval ^= 1
556 pval ^= 1
557 v ^= 255
558 }
559
560 // Set pixel value as we want it.
561 pinfo.Block.reset(pinfo.Bit, bval)
562
563 _, _ = x, y
564
565 err := targ - v
566 if x+1 < len(row) {
567 addDither(pixByOff, row[x+1], err*7/16)
568 }
569 if false && y+1 < len(p.Pixel) {
570 if x > 0 {
571 addDither(pixByOff, p.Pixel[y+1][x-1], err*3/16)
572 }
573 addDither(pixByOff, p.Pixel[y+1][x], err*5/16)
574 if x+1 < len(row) {
575 addDither(pixByOff, p.Pixel[y+1][x+1], err*1/16)
576 }
577 }
578 }
579 }
580
581 for _, bb := range bitblocks {
582 bb.copyOut()
583 }
584 }
585
586 noops := 0
587 // Copy numbers back out.
588 for i := 0; i < dbit/10; i++ {
589 // Pull out 10 bits.
590 v := 0
591 for j := 0; j < 10; j++ {
592 bi := uint(bbit + 10*i + j)
593 v <<= 1
594 v |= int((data[bi/8] >> (7 - bi&7)) & 1)
595 }
596 // Turn into 3 digits.
597 if v >= 1000 {
598 // Oops - too many 1 bits.
599 // We know the 512, 256, 128, 64, 32 bits are all set.
600 // Pick one at random to clear. This will break some
601 // checksum bits, but so be it.
602 // println("oops", i, v)
603 pinfo := &pixByOff[bbit+10*i+3] // TODO random
604 pinfo.Contrast = 1e9 >> 8
605 pinfo.HardZero = true
606 noops++
607 }
608 num[i*3+0] = byte(v/100 + '0')
609 num[i*3+1] = byte(v/10%10 + '0')
610 num[i*3+2] = byte(v%10 + '0')
611 }
612 if noops > 0 {
613 goto Again
614 }
615
616 var b1 coding.Bits
617 coding.String(url).Encode(&b1, p.Version)
618 coding.Num(num).Encode(&b1, p.Version)
619 b1.AddCheckBytes(p.Version, p.Level)
620 if !bytes.Equal(b.Bytes(), b1.Bytes()) {
621 fmt.Printf("mismatch\n%d %x\n%d %x\n", len(b.Bytes()), b.Bytes(), len(b1.Bytes()), b1.Bytes())
622 panic("byte mismatch")
623 }
624
625 cc, err := p.Encode(coding.String(url), coding.Num(num))
626 if err != nil {
627 return err
628 }
629
630 if !m.Dither {
631 for y, row := range expect {
632 for x, pix := range row {
633 if cc.Black(x, y) != pix {
634 println("mismatch", x, y, p.Pixel[y][x].String())
635 }
636 }
637 }
638 }
639
640 m.Code = &qr.Code{Bitmap: cc.Bitmap, Size: cc.Size, Stride: cc.Stride, Scale: m.Scale}
641
642 if m.SaveControl {
643 // m.Control = pngEncode(makeImage(req, "", "", 0, cc.Size, 4, m.Scale, func(x, y int) (rgba uint32) {
644 // pix := p.Pixel[y][x]
645 // if pix.Role() == coding.Data || pix.Role() == coding.Check {
646 // pinfo := &pixByOff[pix.Offset()]
647 // if pinfo.Block != nil {
648 // if cc.Black(x, y) {
649 // return 0x000000ff
650 // }
651 // return 0xffffffff
652 // }
653 // }
654 // if cc.Black(x, y) {
655 // return 0x3f3f3fff
656 // }
657 // return 0xbfbfbfff
658 // }))
659 }
660
661 return nil
662 }