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