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 nn, err := w.Write(waveHeader)
90 n = int64(nn)
91 if err != nil {
92 return
93 }
94 err = binary.Write(w, binary.LittleEndian, uint32(a.body.Len()))
95 if err != nil {
96 return
97 }
98 nn += 4
99 n, err = a.body.WriteTo(w)
100 n += int64(nn)
101 return
102}
103
104// EncodedLen returns the length of WAV-encoded audio captcha.
105func (a *Audio) EncodedLen() int {
106 return len(waveHeader) + 4 + a.body.Len()
107}
108
109// mixSound mixes src into dst. Dst must have length equal to or greater than
110// src length.
111func mixSound(dst, src []byte) {
112 for i, v := range src {
113 av := int(v)
114 bv := int(dst[i])
115 if av < 128 && bv < 128 {
116 dst[i] = byte(av * bv / 128)
117 } else {
118 dst[i] = byte(2*(av+bv) - av*bv/128 - 256)
119 }
120 }
121}
122
123func setSoundLevel(a []byte, level float64) {
124 for i, v := range a {
125 av := float64(v)
126 switch {
127 case av > 128:
128 if av = (av-128)*level + 128; av < 128 {
129 av = 128
130 }
131 case av < 128:
132 if av = 128 - (128-av)*level; av > 128 {
133 av = 128
134 }
135 default:
136 continue
137 }
138 a[i] = byte(av)
139 }
140}
141
142// changeSpeed returns new PCM bytes from the bytes with the speed and pitch
143// changed to the given value that must be in range [0, x].
144func changeSpeed(a []byte, speed float64) []byte {
145 b := make([]byte, int(math.Floor(float64(len(a))*speed)))
146 var p float64
147 for _, v := range a {
148 for i := int(p); i < int(p+speed); i++ {
149 b[i] = v
150 }
151 p += speed
152 }
153 return b
154}
155
156func randomSpeed(a []byte) []byte {
157 pitch := rndf(0.9, 1.2)
158 return changeSpeed(a, pitch)
159}
160
161func makeSilence(length int) []byte {
162 b := make([]byte, length)
163 for i := range b {
164 b[i] = 128
165 }
166 return b
167}
168
169func makeWhiteNoise(length int, level uint8) []byte {
170 noise := randomBytes(length)
171 adj := 128 - level/2
172 for i, v := range noise {
173 v %= level
174 v += adj
175 noise[i] = v
176 }
177 return noise
178}
179
180func reversedSound(a []byte) []byte {
181 n := len(a)
182 b := make([]byte, n)
183 for i, v := range a {
184 b[n-1-i] = v
185 }
186 return b
187}
188
189func makeBackgroundSound(length int) []byte {
190 b := makeWhiteNoise(length, 4)
191 for i := 0; i < length/(sampleRate/10); i++ {
192 snd := reverseDigitSounds[rand.Intn(10)]
193 snd = changeSpeed(snd, rndf(0.8, 1.4))
194 place := rand.Intn(len(b) - len(snd))
195 setSoundLevel(snd, rndf(0.2, 0.3))
196 mixSound(b[place:], snd)
197 }
198 return b
199}
200
201func randomizedDigitSound(n byte) []byte {
202 s := randomSpeed(digitSounds[n])
203 setSoundLevel(s, rndf(0.7, 1.3))
204 return s
205}