audio.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. // Copyright 2011 Dmitry Chestnykh. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package captcha
  5. import (
  6. "bytes"
  7. "encoding/binary"
  8. "math"
  9. "os"
  10. "rand"
  11. "io"
  12. )
  13. const sampleRate = 8000 // Hz
  14. var (
  15. endingBeepSound []byte
  16. )
  17. func init() {
  18. endingBeepSound = changeSpeed(beepSound, 1.4)
  19. }
  20. // BUG(dchest): [Not our bug] Google Chrome 10 plays unsigned 8-bit PCM WAVE
  21. // audio on Mac with horrible distortions. Issue:
  22. // http://code.google.com/p/chromium/issues/detail?id=70730.
  23. // This has been fixed, and version 12 will play them properly.
  24. type Audio struct {
  25. body *bytes.Buffer
  26. digitSounds [][]byte
  27. }
  28. // NewImage returns a new audio captcha with the given digits, where each digit
  29. // must be in range 0-9. Digits are pronounced in the given language. If there
  30. // are no sounds for the given language, English is used.
  31. func NewAudio(digits []byte, lang string) *Audio {
  32. a := new(Audio)
  33. if sounds, ok := digitSounds[lang]; ok {
  34. a.digitSounds = sounds
  35. } else {
  36. a.digitSounds = digitSounds["en"]
  37. }
  38. numsnd := make([][]byte, len(digits))
  39. nsdur := 0
  40. for i, n := range digits {
  41. snd := a.randomizedDigitSound(n)
  42. nsdur += len(snd)
  43. numsnd[i] = snd
  44. }
  45. // Random intervals between digits (including beginning).
  46. intervals := make([]int, len(digits)+1)
  47. intdur := 0
  48. for i := range intervals {
  49. dur := rnd(sampleRate, sampleRate*3) // 1 to 3 seconds
  50. intdur += dur
  51. intervals[i] = dur
  52. }
  53. // Generate background sound.
  54. bg := a.makeBackgroundSound(a.longestDigitSndLen()*len(digits) + intdur)
  55. // Create buffer and write audio to it.
  56. sil := makeSilence(sampleRate / 5)
  57. bufcap := 3*len(beepSound) + 2*len(sil) + len(bg) + len(endingBeepSound)
  58. a.body = bytes.NewBuffer(make([]byte, 0, bufcap))
  59. // Write prelude, three beeps.
  60. a.body.Write(beepSound)
  61. a.body.Write(sil)
  62. a.body.Write(beepSound)
  63. a.body.Write(sil)
  64. a.body.Write(beepSound)
  65. // Write digits.
  66. pos := intervals[0]
  67. for i, v := range numsnd {
  68. mixSound(bg[pos:], v)
  69. pos += len(v) + intervals[i+1]
  70. }
  71. a.body.Write(bg)
  72. // Write ending (one beep).
  73. a.body.Write(endingBeepSound)
  74. return a
  75. }
  76. // WriteTo writes captcha audio in WAVE format into the given io.Writer, and
  77. // returns the number of bytes written and an error if any.
  78. func (a *Audio) WriteTo(w io.Writer) (n int64, err os.Error) {
  79. // Calculate padded length of PCM chunk data.
  80. bodyLen := uint32(a.body.Len())
  81. paddedBodyLen := bodyLen
  82. if bodyLen%2 != 0 {
  83. paddedBodyLen++
  84. }
  85. totalLen := uint32(len(waveHeader)) - 4 + paddedBodyLen
  86. // Header.
  87. header := make([]byte, len(waveHeader)+4) // includes 4 bytes for chunk size
  88. copy(header, waveHeader)
  89. // Put the length of whole RIFF chunk.
  90. binary.LittleEndian.PutUint32(header[4:], totalLen)
  91. // Put the length of WAVE chunk.
  92. binary.LittleEndian.PutUint32(header[len(waveHeader):], bodyLen)
  93. // Write header.
  94. nn, err := w.Write(header)
  95. n = int64(nn)
  96. if err != nil {
  97. return
  98. }
  99. // Write data.
  100. n, err = a.body.WriteTo(w)
  101. n += int64(nn)
  102. if err != nil {
  103. return
  104. }
  105. // Pad byte if chunk length is odd.
  106. // (As header has even length, we can check if n is odd, not chunk).
  107. if bodyLen != paddedBodyLen {
  108. w.Write([]byte{0})
  109. n++
  110. }
  111. return
  112. }
  113. // EncodedLen returns the length of WAV-encoded audio captcha.
  114. func (a *Audio) EncodedLen() int {
  115. return len(waveHeader) + 4 + a.body.Len()
  116. }
  117. func (a *Audio) makeBackgroundSound(length int) []byte {
  118. b := makeWhiteNoise(length, 4)
  119. for i := 0; i < length/(sampleRate/10); i++ {
  120. snd := reversedSound(a.digitSounds[rand.Intn(10)])
  121. snd = changeSpeed(snd, rndf(0.8, 1.4))
  122. place := rand.Intn(len(b) - len(snd))
  123. setSoundLevel(snd, rndf(0.2, 0.5))
  124. mixSound(b[place:], snd)
  125. }
  126. return b
  127. }
  128. func (a *Audio) randomizedDigitSound(n byte) []byte {
  129. s := randomSpeed(a.digitSounds[n])
  130. setSoundLevel(s, rndf(0.75, 1.2))
  131. return s
  132. }
  133. func (a *Audio) longestDigitSndLen() int {
  134. n := 0
  135. for _, v := range a.digitSounds {
  136. if n < len(v) {
  137. n = len(v)
  138. }
  139. }
  140. return n
  141. }
  142. // mixSound mixes src into dst. Dst must have length equal to or greater than
  143. // src length.
  144. func mixSound(dst, src []byte) {
  145. for i, v := range src {
  146. av := int(v)
  147. bv := int(dst[i])
  148. if av < 128 && bv < 128 {
  149. dst[i] = byte(av * bv / 128)
  150. } else {
  151. dst[i] = byte(2*(av+bv) - av*bv/128 - 256)
  152. }
  153. }
  154. }
  155. func setSoundLevel(a []byte, level float64) {
  156. for i, v := range a {
  157. av := float64(v)
  158. switch {
  159. case av > 128:
  160. if av = (av-128)*level + 128; av < 128 {
  161. av = 128
  162. }
  163. case av < 128:
  164. if av = 128 - (128-av)*level; av > 128 {
  165. av = 128
  166. }
  167. default:
  168. continue
  169. }
  170. a[i] = byte(av)
  171. }
  172. }
  173. // changeSpeed returns new PCM bytes from the bytes with the speed and pitch
  174. // changed to the given value that must be in range [0, x].
  175. func changeSpeed(a []byte, speed float64) []byte {
  176. b := make([]byte, int(math.Floor(float64(len(a))*speed)))
  177. var p float64
  178. for _, v := range a {
  179. for i := int(p); i < int(p+speed); i++ {
  180. b[i] = v
  181. }
  182. p += speed
  183. }
  184. return b
  185. }
  186. func randomSpeed(a []byte) []byte {
  187. pitch := rndf(0.9, 1.2)
  188. return changeSpeed(a, pitch)
  189. }
  190. func makeSilence(length int) []byte {
  191. b := make([]byte, length)
  192. for i := range b {
  193. b[i] = 128
  194. }
  195. return b
  196. }
  197. func makeWhiteNoise(length int, level uint8) []byte {
  198. noise := randomBytes(length)
  199. adj := 128 - level/2
  200. for i, v := range noise {
  201. v %= level
  202. v += adj
  203. noise[i] = v
  204. }
  205. return noise
  206. }
  207. func reversedSound(a []byte) []byte {
  208. n := len(a)
  209. b := make([]byte, n)
  210. for i, v := range a {
  211. b[n-1-i] = v
  212. }
  213. return b
  214. }