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