all repos — captcha @ 9d0ab4e0254bd6f8ce9aa950ebb90956b1764fc9

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	endingBeepSound []byte
 16)
 17
 18func init() {
 19	endingBeepSound = changeSpeed(beepSound, 1.4)
 20}
 21
 22// BUG(dchest): [Not our bug] Google Chrome 10 plays unsigned 8-bit PCM WAVE
 23// audio on Mac with horrible distortions.  Issue:
 24// http://code.google.com/p/chromium/issues/detail?id=70730.
 25// This has been fixed, and version 12 will play them properly.
 26
 27type Audio struct {
 28	body *bytes.Buffer
 29	digitSounds [][]byte
 30}
 31
 32// NewImage returns a new audio captcha with the given digits, where each digit
 33// must be in range 0-9. Digits are pronounced in the given language. If there
 34// are no sounds for the given language, English is used.
 35func NewAudio(digits []byte, lang string) *Audio {
 36	a := new(Audio)
 37	if sounds, ok := digitSounds[lang]; ok {
 38		a.digitSounds = sounds
 39	} else {
 40		a.digitSounds = digitSounds["en"]
 41	}
 42	numsnd := make([][]byte, len(digits))
 43	nsdur := 0
 44	for i, n := range digits {
 45		snd := a.randomizedDigitSound(n)
 46		nsdur += len(snd)
 47		numsnd[i] = snd
 48	}
 49	// Random intervals between digits (including beginning).
 50	intervals := make([]int, len(digits)+1)
 51	intdur := 0
 52	for i := range intervals {
 53		dur := rnd(sampleRate, sampleRate*3) // 1 to 3 seconds
 54		intdur += dur
 55		intervals[i] = dur
 56	}
 57	// Generate background sound.
 58	bg := a.makeBackgroundSound(a.longestDigitSndLen()*len(digits) + intdur)
 59	// Create buffer and write audio to it.
 60	sil := makeSilence(sampleRate / 5)
 61	bufcap := 3*len(beepSound) + 2*len(sil) + len(bg) + len(endingBeepSound)
 62	a.body = bytes.NewBuffer(make([]byte, 0, bufcap))
 63	// Write prelude, three beeps.
 64	a.body.Write(beepSound)
 65	a.body.Write(sil)
 66	a.body.Write(beepSound)
 67	a.body.Write(sil)
 68	a.body.Write(beepSound)
 69	// Write digits.
 70	pos := intervals[0]
 71	for i, v := range numsnd {
 72		mixSound(bg[pos:], v)
 73		pos += len(v) + intervals[i+1]
 74	}
 75	a.body.Write(bg)
 76	// Write ending (one beep).
 77	a.body.Write(endingBeepSound)
 78	return a
 79}
 80
 81// WriteTo writes captcha audio in WAVE format into the given io.Writer, and
 82// returns the number of bytes written and an error if any.
 83func (a *Audio) WriteTo(w io.Writer) (n int64, err os.Error) {
 84	// Calculate padded length of PCM chunk data.
 85	bodyLen := uint32(a.body.Len())
 86	paddedBodyLen := bodyLen
 87	if bodyLen%2 != 0 {
 88		paddedBodyLen++
 89	}
 90	totalLen := uint32(len(waveHeader)) - 4 + paddedBodyLen
 91	// Header.
 92	header := make([]byte, len(waveHeader)+4) // includes 4 bytes for chunk size
 93	copy(header, waveHeader)
 94	// Put the length of whole RIFF chunk.
 95	binary.LittleEndian.PutUint32(header[4:], totalLen)
 96	// Put the length of WAVE chunk.
 97	binary.LittleEndian.PutUint32(header[len(waveHeader):], bodyLen)
 98	// Write header.
 99	nn, err := w.Write(header)
100	n = int64(nn)
101	if err != nil {
102		return
103	}
104	// Write data.
105	n, err = a.body.WriteTo(w)
106	n += int64(nn)
107	if err != nil {
108		return
109	}
110	// Pad byte if chunk length is odd.
111	// (As header has even length, we can check if n is odd, not chunk).
112	if bodyLen != paddedBodyLen {
113		w.Write([]byte{0})
114		n++
115	}
116	return
117}
118
119// EncodedLen returns the length of WAV-encoded audio captcha.
120func (a *Audio) EncodedLen() int {
121	return len(waveHeader) + 4 + a.body.Len()
122}
123
124func (a *Audio) makeBackgroundSound(length int) []byte {
125	b := makeWhiteNoise(length, 4)
126	for i := 0; i < length/(sampleRate/10); i++ {
127		snd := reversedSound(a.digitSounds[rand.Intn(10)])
128		snd = changeSpeed(snd, rndf(0.8, 1.4))
129		place := rand.Intn(len(b) - len(snd))
130		setSoundLevel(snd, rndf(0.2, 0.5))
131		mixSound(b[place:], snd)
132	}
133	return b
134}
135
136func (a *Audio) randomizedDigitSound(n byte) []byte {
137	s := randomSpeed(a.digitSounds[n])
138	setSoundLevel(s, rndf(0.75, 1.2))
139	return s
140}
141
142func (a *Audio) longestDigitSndLen() int {
143	n := 0
144	for _, v := range a.digitSounds {
145		if n < len(v) {
146			n = len(v)
147		}
148	}
149	return n
150}
151
152// mixSound mixes src into dst. Dst must have length equal to or greater than
153// src length.
154func mixSound(dst, src []byte) {
155	for i, v := range src {
156		av := int(v)
157		bv := int(dst[i])
158		if av < 128 && bv < 128 {
159			dst[i] = byte(av * bv / 128)
160		} else {
161			dst[i] = byte(2*(av+bv) - av*bv/128 - 256)
162		}
163	}
164}
165
166func setSoundLevel(a []byte, level float64) {
167	for i, v := range a {
168		av := float64(v)
169		switch {
170		case av > 128:
171			if av = (av-128)*level + 128; av < 128 {
172				av = 128
173			}
174		case av < 128:
175			if av = 128 - (128-av)*level; av > 128 {
176				av = 128
177			}
178		default:
179			continue
180		}
181		a[i] = byte(av)
182	}
183}
184
185// changeSpeed returns new PCM bytes from the bytes with the speed and pitch
186// changed to the given value that must be in range [0, x].
187func changeSpeed(a []byte, speed float64) []byte {
188	b := make([]byte, int(math.Floor(float64(len(a))*speed)))
189	var p float64
190	for _, v := range a {
191		for i := int(p); i < int(p+speed); i++ {
192			b[i] = v
193		}
194		p += speed
195	}
196	return b
197}
198
199func randomSpeed(a []byte) []byte {
200	pitch := rndf(0.9, 1.2)
201	return changeSpeed(a, pitch)
202}
203
204func makeSilence(length int) []byte {
205	b := make([]byte, length)
206	for i := range b {
207		b[i] = 128
208	}
209	return b
210}
211
212func makeWhiteNoise(length int, level uint8) []byte {
213	noise := randomBytes(length)
214	adj := 128 - level/2
215	for i, v := range noise {
216		v %= level
217		v += adj
218		noise[i] = v
219	}
220	return noise
221}
222
223func reversedSound(a []byte) []byte {
224	n := len(a)
225	b := make([]byte, n)
226	for i, v := range a {
227		b[n-1-i] = v
228	}
229	return b
230}