audio.go (view raw)
1package captcha
2
3import (
4 "bytes"
5 crand "crypto/rand"
6 "encoding/binary"
7 "math"
8 "os"
9 "rand"
10 "io"
11)
12
13const sampleRate = 8000 // Hz
14
15var (
16 // Length of the longest digit sound.
17 longestDigitSndLen int
18 endingBeepSound []byte
19)
20
21func init() {
22 for _, v := range digitSounds {
23 if longestDigitSndLen < len(v) {
24 longestDigitSndLen = len(v)
25 }
26 }
27 endingBeepSound = changeSpeed(beepSound, 1.4)
28}
29
30type Audio struct {
31 body *bytes.Buffer
32}
33
34// NewImage returns a new audio captcha with the given digits, where each digit
35// must be in range 0-9.
36func NewAudio(digits []byte) *Audio {
37 numsnd := make([][]byte, len(digits))
38 nsdur := 0
39 for i, n := range digits {
40 snd := randomizedDigitSound(n)
41 nsdur += len(snd)
42 numsnd[i] = snd
43 }
44 // Random intervals between digits (including beginning).
45 intervals := make([]int, len(digits)+1)
46 intdur := 0
47 for i := range intervals {
48 dur := rnd(sampleRate, sampleRate*3) // 1 to 3 seconds
49 intdur += dur
50 intervals[i] = dur
51 }
52 // Generate background sound.
53 bg := makeBackgroundSound(longestDigitSndLen*len(digits) + intdur)
54 // Create buffer and write audio to it.
55 a := new(Audio)
56 sil := makeSilence(sampleRate / 5)
57 bufcap := 3*len(beepSound) + 2*len(sil) + len(bg) + len(endingBeepSound)
58 a.body = bytes.NewBuffer(make([]byte, 0, bufcap))
59 // Write prelude, three beeps.
60 a.body.Write(beepSound)
61 a.body.Write(sil)
62 a.body.Write(beepSound)
63 a.body.Write(sil)
64 a.body.Write(beepSound)
65 // Write digits.
66 pos := intervals[0]
67 for i, v := range numsnd {
68 mixSound(bg[pos:], v)
69 pos += len(v) + intervals[i+1]
70 }
71 a.body.Write(bg)
72 // Write ending (one beep).
73 a.body.Write(endingBeepSound)
74 return a
75}
76
77// NewRandomAudio generates a sequence of random digits with the given length,
78// and returns a new audio captcha with these digits, and the sequence of
79// digits itself.
80func NewRandomAudio(length int) (a *Audio, digits []byte) {
81 digits = randomDigits(length)
82 a = NewAudio(digits)
83 return
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// mixSound mixes src into dst. Dst must have length equal to or greater than
105// src length.
106func mixSound(dst, src []byte) {
107 for i, v := range src {
108 av := int(v)
109 bv := int(dst[i])
110 if av < 128 && bv < 128 {
111 dst[i] = byte(av * bv / 128)
112 } else {
113 dst[i] = byte(2*(av+bv) - av*bv/128 - 256)
114 }
115 }
116}
117
118func setSoundLevel(a []byte, level float64) {
119 for i, v := range a {
120 av := float64(v)
121 switch {
122 case av > 128:
123 if av = (av-128)*level + 128; av < 128 {
124 av = 128
125 }
126 case av < 128:
127 if av = 128 - (128-av)*level; av > 128 {
128 av = 128
129 }
130 default:
131 continue
132 }
133 a[i] = byte(av)
134 }
135}
136
137// changeSpeed returns new PCM bytes from the bytes with the speed and pitch
138// changed to the given value that must be in range [0, x].
139func changeSpeed(a []byte, speed float64) []byte {
140 b := make([]byte, int(math.Floor(float64(len(a))*speed)))
141 var p float64
142 for _, v := range a {
143 for i := int(p); i < int(p+speed); i++ {
144 b[i] = v
145 }
146 p += speed
147 }
148 return b
149}
150
151// rndf returns a random float64 number in range [from, to].
152func rndf(from, to float64) float64 {
153 return (to-from)*rand.Float64() + from
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 := 0; i < length; i++ {
164 b[i] = 128
165 }
166 return b
167}
168
169func makeWhiteNoise(length int, level uint8) []byte {
170 noise := make([]byte, length)
171 _, err := io.ReadFull(crand.Reader, noise)
172 if err != nil {
173 panic("error reading from random source: " + err.String())
174 }
175 for i := 0; i < len(noise); i++ {
176 noise[i] %= level
177 noise[i] += 128 - level/2
178 }
179 return noise
180}
181
182func reversedSound(a []byte) []byte {
183 n := len(a)
184 b := make([]byte, n)
185 for i, v := range a {
186 b[n-1-i] = v
187 }
188 return b
189}
190
191func makeBackgroundSound(length int) []byte {
192 b := makeWhiteNoise(length, 8)
193 for i := 0; i < length/(sampleRate/10); i++ {
194 snd := digitSounds[rand.Intn(10)]
195 snd = changeSpeed(reversedSound(snd), rndf(0.8, 1.4))
196 place := rand.Intn(len(b) - len(snd))
197 setSoundLevel(snd, rndf(0.5, 1.2))
198 mixSound(b[place:], snd)
199 }
200 setSoundLevel(b, rndf(0.2, 0.3))
201 return b
202}
203
204func randomizedDigitSound(n byte) []byte {
205 s := randomSpeed(digitSounds[n])
206 setSoundLevel(s, rndf(0.7, 1.3))
207 return s
208}