all repos — captcha @ dab967324bac3f9d55fb1664840f86df7643ec5a

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

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// EncodedLen returns the length of WAV-encoded audio captcha.
 95func (a *Audio) EncodedLen() int {
 96	return len(waveHeader) + 4 + a.body.Len()
 97}
 98
 99// mixSound mixes src into dst. Dst must have length equal to or greater than
100// src length.
101func mixSound(dst, src []byte) {
102	for i, v := range src {
103		av := int(v)
104		bv := int(dst[i])
105		if av < 128 && bv < 128 {
106			dst[i] = byte(av * bv / 128)
107		} else {
108			dst[i] = byte(2*(av+bv) - av*bv/128 - 256)
109		}
110	}
111}
112
113func setSoundLevel(a []byte, level float64) {
114	for i, v := range a {
115		av := float64(v)
116		switch {
117		case av > 128:
118			if av = (av-128)*level + 128; av < 128 {
119				av = 128
120			}
121		case av < 128:
122			if av = 128 - (128-av)*level; av > 128 {
123				av = 128
124			}
125		default:
126			continue
127		}
128		a[i] = byte(av)
129	}
130}
131
132// changeSpeed returns new PCM bytes from the bytes with the speed and pitch
133// changed to the given value that must be in range [0, x].
134func changeSpeed(a []byte, speed float64) []byte {
135	b := make([]byte, int(math.Floor(float64(len(a))*speed)))
136	var p float64
137	for _, v := range a {
138		for i := int(p); i < int(p+speed); i++ {
139			b[i] = v
140		}
141		p += speed
142	}
143	return b
144}
145
146// rndf returns a random float64 number in range [from, to].
147func rndf(from, to float64) float64 {
148	return (to-from)*rand.Float64() + from
149}
150
151func randomSpeed(a []byte) []byte {
152	pitch := rndf(0.9, 1.2)
153	return changeSpeed(a, pitch)
154}
155
156func makeSilence(length int) []byte {
157	b := make([]byte, length)
158	for i := 0; i < length; i++ {
159		b[i] = 128
160	}
161	return b
162}
163
164func makeWhiteNoise(length int, level uint8) []byte {
165	noise := make([]byte, length)
166	_, err := io.ReadFull(crand.Reader, noise)
167	if err != nil {
168		panic("error reading from random source: " + err.String())
169	}
170	for i := 0; i < len(noise); i++ {
171		noise[i] %= level
172		noise[i] += 128 - level/2
173	}
174	return noise
175}
176
177func reversedSound(a []byte) []byte {
178	n := len(a)
179	b := make([]byte, n)
180	for i, v := range a {
181		b[n-1-i] = v
182	}
183	return b
184}
185
186func makeBackgroundSound(length int) []byte {
187	b := makeWhiteNoise(length, 8)
188	for i := 0; i < length/(sampleRate/10); i++ {
189		snd := digitSounds[rand.Intn(10)]
190		snd = changeSpeed(reversedSound(snd), rndf(0.8, 1.4))
191		place := rand.Intn(len(b) - len(snd))
192		setSoundLevel(snd, rndf(0.5, 1.2))
193		mixSound(b[place:], snd)
194	}
195	setSoundLevel(b, rndf(0.2, 0.3))
196	return b
197}
198
199func randomizedDigitSound(n byte) []byte {
200	s := randomSpeed(digitSounds[n])
201	setSoundLevel(s, rndf(0.7, 1.3))
202	return s
203}