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 longestDigitSndLen int
17 endingBeepSound []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}
28
29type Audio struct {
30 body *bytes.Buffer
31}
32
33// NewImage returns a new audio captcha with the given digits, where each digit
34// must be in range 0-9.
35func NewAudio(digits []byte) *Audio {
36 numsnd := make([][]byte, len(digits))
37 nsdur := 0
38 for i, n := range digits {
39 snd := randomizedDigitSound(n)
40 nsdur += len(snd)
41 numsnd[i] = snd
42 }
43 // Random intervals between digits (including beginning).
44 intervals := make([]int, len(digits)+1)
45 intdur := 0
46 for i := range intervals {
47 dur := rnd(sampleRate, sampleRate*3) // 1 to 3 seconds
48 intdur += dur
49 intervals[i] = dur
50 }
51 // Generate background sound.
52 bg := makeBackgroundSound(longestDigitSndLen*len(digits) + intdur)
53 // Create buffer and write audio to it.
54 a := new(Audio)
55 sil := makeSilence(sampleRate / 5)
56 bufcap := 3*len(beepSound) + 2*len(sil) + len(bg) + len(endingBeepSound)
57 a.body = bytes.NewBuffer(make([]byte, 0, bufcap))
58 // Write prelude, three beeps.
59 a.body.Write(beepSound)
60 a.body.Write(sil)
61 a.body.Write(beepSound)
62 a.body.Write(sil)
63 a.body.Write(beepSound)
64 // Write digits.
65 pos := intervals[0]
66 for i, v := range numsnd {
67 mixSound(bg[pos:], v)
68 pos += len(v) + intervals[i+1]
69 }
70 a.body.Write(bg)
71 // Write ending (one beep).
72 a.body.Write(endingBeepSound)
73 return a
74}
75
76// WriteTo writes captcha audio in WAVE format into the given io.Writer, and
77// returns the number of bytes written and an error if any.
78func (a *Audio) WriteTo(w io.Writer) (n int64, err os.Error) {
79 nn, err := w.Write(waveHeader)
80 n = int64(nn)
81 if err != nil {
82 return
83 }
84 err = binary.Write(w, binary.LittleEndian, uint32(a.body.Len()))
85 if err != nil {
86 return
87 }
88 nn += 4
89 n, err = a.body.WriteTo(w)
90 n += int64(nn)
91 return
92}
93
94// mixSound mixes src into dst. Dst must have length equal to or greater than
95// src length.
96func mixSound(dst, src []byte) {
97 for i, v := range src {
98 av := int(v)
99 bv := int(dst[i])
100 if av < 128 && bv < 128 {
101 dst[i] = byte(av * bv / 128)
102 } else {
103 dst[i] = byte(2*(av+bv) - av*bv/128 - 256)
104 }
105 }
106}
107
108func setSoundLevel(a []byte, level float64) {
109 for i, v := range a {
110 av := float64(v)
111 switch {
112 case av > 128:
113 if av = (av-128)*level + 128; av < 128 {
114 av = 128
115 }
116 case av < 128:
117 if av = 128 - (128-av)*level; av > 128 {
118 av = 128
119 }
120 default:
121 continue
122 }
123 a[i] = byte(av)
124 }
125}
126
127// changeSpeed returns new PCM bytes from the bytes with the speed and pitch
128// changed to the given value that must be in range [0, x].
129func changeSpeed(a []byte, speed float64) []byte {
130 b := make([]byte, int(math.Floor(float64(len(a))*speed)))
131 var p float64
132 for _, v := range a {
133 for i := int(p); i < int(p+speed); i++ {
134 b[i] = v
135 }
136 p += speed
137 }
138 return b
139}
140
141// rndf returns a random float64 number in range [from, to].
142func rndf(from, to float64) float64 {
143 return (to-from)*rand.Float64() + from
144}
145
146func randomSpeed(a []byte) []byte {
147 pitch := rndf(0.9, 1.2)
148 return changeSpeed(a, pitch)
149}
150
151func makeSilence(length int) []byte {
152 b := make([]byte, length)
153 for i := 0; i < length; i++ {
154 b[i] = 128
155 }
156 return b
157}
158
159func makeWhiteNoise(length int, level uint8) []byte {
160 noise := make([]byte, length)
161 _, err := io.ReadFull(crand.Reader, noise)
162 if err != nil {
163 panic("error reading from random source: " + err.String())
164 }
165 for i := 0; i < len(noise); i++ {
166 noise[i] %= level
167 noise[i] += 128 - level/2
168 }
169 return noise
170}
171
172func reversedSound(a []byte) []byte {
173 n := len(a)
174 b := make([]byte, n)
175 for i, v := range a {
176 b[n-1-i] = v
177 }
178 return b
179}
180
181func makeBackgroundSound(length int) []byte {
182 b := makeWhiteNoise(length, 8)
183 for i := 0; i < length/(sampleRate/10); i++ {
184 snd := digitSounds[rand.Intn(10)]
185 snd = changeSpeed(reversedSound(snd), rndf(0.8, 1.4))
186 place := rand.Intn(len(b) - len(snd))
187 setSoundLevel(snd, rndf(0.5, 1.2))
188 mixSound(b[place:], snd)
189 }
190 setSoundLevel(b, rndf(0.2, 0.3))
191 return b
192}
193
194func randomizedDigitSound(n byte) []byte {
195 s := randomSpeed(digitSounds[n])
196 setSoundLevel(s, rndf(0.7, 1.3))
197 return s
198}