audio.go 5.1 KB

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