all repos — captcha @ 7b585d44e115cb4e46a6d033adaba32fb0fddd31

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