all repos — captcha @ e6fb73402841aa4835165d9402634587e948de8e

Go package captcha implements generation and verification of image and audio CAPTCHAs.

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