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