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