audio.go 5.4 KB

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