all repos — captcha @ ebb75a0b6ca0591c2ca8898fa0d60c5e6adfa548

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