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
14
15var (
16 // Length of the longest number sound
17 longestNumSndLen int
18 endingBeepSound []byte
19)
20
21func init() {
22 for _, v := range numberSounds {
23 if longestNumSndLen < len(v) {
24 longestNumSndLen = 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 slice of numbers, where
35// each number must be in range 0-9.
36func NewAudio(numbers []byte) *Audio {
37 numsnd := make([][]byte, len(numbers))
38 nsdur := 0
39 for i, n := range numbers {
40 snd := randomizedNumSound(n)
41 nsdur += len(snd)
42 numsnd[i] = snd
43 }
44 // Intervals between numbers (including beginning)
45 intervals := make([]int, len(numbers)+1)
46 intdur := 0
47 for i := range intervals {
48 // 1 to 3 seconds
49 dur := rnd(sampleRate, sampleRate*3)
50 intdur += dur
51 intervals[i] = dur
52 }
53 // Background noise
54 bg := makeBackgroundSound(longestNumSndLen*len(numbers) + intdur)
55 // --
56 a := new(Audio)
57 a.body = bytes.NewBuffer(nil)
58 // Prelude, three beeps
59 sil := makeSilence(sampleRate / 5)
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 // Numbers
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 // Ending
73 a.body.Write(endingBeepSound)
74 return a
75}
76
77// NewRandomAudio generates a sequence of random numbers with the given length,
78// and returns a new audio captcha with this numbers, and the sequence of
79// numbers itself.
80func NewRandomAudio(length int) (a *Audio, numbers []byte) {
81 numbers = randomNumbers(length)
82 a = NewAudio(numbers)
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, pitch float64) []byte {
140 b := make([]byte, int(math.Floor(float64(len(a))*pitch)))
141 var p float64
142 for _, v := range a {
143 for i := int(p); i < int(p+pitch); i++ {
144 b[i] = v
145 }
146 p += pitch
147 }
148 return b
149}
150
151// rndFloat64n returns a random float64 number in range [from, to].
152func rndFloat64n(from, to float64) float64 {
153 return (to-from)*rand.Float64() + from
154}
155
156func randomSpeed(a []byte) []byte {
157 pitch := rndFloat64n(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 makeStaticNoise(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 ln := len(a)
184 b := make([]byte, ln)
185 for i, v := range a {
186 b[ln-1-i] = v
187 }
188 return b
189}
190
191func makeBackgroundSound(length int) []byte {
192 b := makeStaticNoise(length, 8)
193 for i := 0; i < length/(sampleRate/10); i++ {
194 snd := numberSounds[rand.Intn(10)]
195 snd = changeSpeed(reversedSound(snd), rndFloat64n(0.8, 1.4))
196 place := rand.Intn(len(b) - len(snd))
197 setSoundLevel(snd, rndFloat64n(0.5, 1.2))
198 mixSound(b[place:], snd)
199 }
200 setSoundLevel(b, rndFloat64n(0.2, 0.3))
201 return b
202}
203
204func randomizedNumSound(n byte) []byte {
205 s := randomSpeed(numberSounds[n])
206 setSoundLevel(s, rndFloat64n(0.7, 1.3))
207 return s
208}