paeth_test.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. // Copyright 2012 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package png
  5. import (
  6. "bytes"
  7. "math/rand"
  8. "testing"
  9. )
  10. func slowAbs(x int) int {
  11. if x < 0 {
  12. return -x
  13. }
  14. return x
  15. }
  16. // slowPaeth is a slow but simple implementation of the Paeth function.
  17. // It is a straight port of the sample code in the PNG spec, section 9.4.
  18. func slowPaeth(a, b, c uint8) uint8 {
  19. p := int(a) + int(b) - int(c)
  20. pa := slowAbs(p - int(a))
  21. pb := slowAbs(p - int(b))
  22. pc := slowAbs(p - int(c))
  23. if pa <= pb && pa <= pc {
  24. return a
  25. } else if pb <= pc {
  26. return b
  27. }
  28. return c
  29. }
  30. // slowFilterPaeth is a slow but simple implementation of func filterPaeth.
  31. func slowFilterPaeth(cdat, pdat []byte, bytesPerPixel int) {
  32. for i := 0; i < bytesPerPixel; i++ {
  33. cdat[i] += paeth(0, pdat[i], 0)
  34. }
  35. for i := bytesPerPixel; i < len(cdat); i++ {
  36. cdat[i] += paeth(cdat[i-bytesPerPixel], pdat[i], pdat[i-bytesPerPixel])
  37. }
  38. }
  39. func TestPaeth(t *testing.T) {
  40. for a := 0; a < 256; a += 15 {
  41. for b := 0; b < 256; b += 15 {
  42. for c := 0; c < 256; c += 15 {
  43. got := paeth(uint8(a), uint8(b), uint8(c))
  44. want := slowPaeth(uint8(a), uint8(b), uint8(c))
  45. if got != want {
  46. t.Errorf("a, b, c = %d, %d, %d: got %d, want %d", a, b, c, got, want)
  47. }
  48. }
  49. }
  50. }
  51. }
  52. func BenchmarkPaeth(b *testing.B) {
  53. for i := 0; i < b.N; i++ {
  54. paeth(uint8(i>>16), uint8(i>>8), uint8(i))
  55. }
  56. }
  57. func TestPaethDecode(t *testing.T) {
  58. pdat0 := make([]byte, 32)
  59. pdat1 := make([]byte, 32)
  60. pdat2 := make([]byte, 32)
  61. cdat0 := make([]byte, 32)
  62. cdat1 := make([]byte, 32)
  63. cdat2 := make([]byte, 32)
  64. r := rand.New(rand.NewSource(1))
  65. for bytesPerPixel := 1; bytesPerPixel <= 8; bytesPerPixel++ {
  66. for i := 0; i < 100; i++ {
  67. for j := range pdat0 {
  68. pdat0[j] = uint8(r.Uint32())
  69. cdat0[j] = uint8(r.Uint32())
  70. }
  71. copy(pdat1, pdat0)
  72. copy(pdat2, pdat0)
  73. copy(cdat1, cdat0)
  74. copy(cdat2, cdat0)
  75. filterPaeth(cdat1, pdat1, bytesPerPixel)
  76. slowFilterPaeth(cdat2, pdat2, bytesPerPixel)
  77. if !bytes.Equal(cdat1, cdat2) {
  78. t.Errorf("bytesPerPixel: %d\npdat0: % x\ncdat0: % x\ngot: % x\nwant: % x", bytesPerPixel, pdat0, cdat0, cdat1, cdat2)
  79. break
  80. }
  81. }
  82. }
  83. }