all repos — captcha @ c833d164be8ae91753e83315c2d9f1a347cf9af8

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
 29// BUG(dchest): [Not our bug] Google Chrome 10 plays unsigned 8-bit PCM WAVE
 30// audio on Mac with horrible distortions.  Issue:
 31// http://code.google.com/p/chromium/issues/detail?id=70730.
 32// This has been fixed, and version 12 will play them properly.
 33
 34type Audio struct {
 35	body *bytes.Buffer
 36}
 37
 38// NewImage returns a new audio captcha with the given digits, where each digit
 39// must be in range 0-9.
 40func NewAudio(digits []byte) *Audio {
 41	numsnd := make([][]byte, len(digits))
 42	nsdur := 0
 43	for i, n := range digits {
 44		snd := randomizedDigitSound(n)
 45		nsdur += len(snd)
 46		numsnd[i] = snd
 47	}
 48	// Random intervals between digits (including beginning).
 49	intervals := make([]int, len(digits)+1)
 50	intdur := 0
 51	for i := range intervals {
 52		dur := rnd(sampleRate, sampleRate*3) // 1 to 3 seconds
 53		intdur += dur
 54		intervals[i] = dur
 55	}
 56	// Generate background sound.
 57	bg := makeBackgroundSound(longestDigitSndLen*len(digits) + intdur)
 58	// Create buffer and write audio to it.
 59	a := new(Audio)
 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	nn, err := w.Write(waveHeader)
 85	n = int64(nn)
 86	if err != nil {
 87		return
 88	}
 89	err = binary.Write(w, binary.LittleEndian, uint32(a.body.Len()))
 90	if err != nil {
 91		return
 92	}
 93	nn += 4
 94	n, err = a.body.WriteTo(w)
 95	n += int64(nn)
 96	return
 97}
 98
 99// EncodedLen returns the length of WAV-encoded audio captcha.
100func (a *Audio) EncodedLen() int {
101	return len(waveHeader) + 4 + a.body.Len()
102}
103
104// mixSound mixes src into dst. Dst must have length equal to or greater than
105// src length.
106func mixSound(dst, src []byte) {
107	for i, v := range src {
108		av := int(v)
109		bv := int(dst[i])
110		if av < 128 && bv < 128 {
111			dst[i] = byte(av * bv / 128)
112		} else {
113			dst[i] = byte(2*(av+bv) - av*bv/128 - 256)
114		}
115	}
116}
117
118func setSoundLevel(a []byte, level float64) {
119	for i, v := range a {
120		av := float64(v)
121		switch {
122		case av > 128:
123			if av = (av-128)*level + 128; av < 128 {
124				av = 128
125			}
126		case av < 128:
127			if av = 128 - (128-av)*level; av > 128 {
128				av = 128
129			}
130		default:
131			continue
132		}
133		a[i] = byte(av)
134	}
135}
136
137// changeSpeed returns new PCM bytes from the bytes with the speed and pitch
138// changed to the given value that must be in range [0, x].
139func changeSpeed(a []byte, speed float64) []byte {
140	b := make([]byte, int(math.Floor(float64(len(a))*speed)))
141	var p float64
142	for _, v := range a {
143		for i := int(p); i < int(p+speed); i++ {
144			b[i] = v
145		}
146		p += speed
147	}
148	return b
149}
150
151// rndf returns a random float64 number in range [from, to].
152func rndf(from, to float64) float64 {
153	return (to-from)*rand.Float64() + from
154}
155
156func randomSpeed(a []byte) []byte {
157	pitch := rndf(0.9, 1.2)
158	return changeSpeed(a, pitch)
159}
160
161func makeSilence(length int) []byte {
162	b := make([]byte, length)
163	for i := 0; i < length; i++ {
164		b[i] = 128
165	}
166	return b
167}
168
169func makeWhiteNoise(length int, level uint8) []byte {
170	noise := make([]byte, length)
171	_, err := io.ReadFull(crand.Reader, noise)
172	if err != nil {
173		panic("error reading from random source: " + err.String())
174	}
175	for i := 0; i < len(noise); i++ {
176		noise[i] %= level
177		noise[i] += 128 - level/2
178	}
179	return noise
180}
181
182func reversedSound(a []byte) []byte {
183	n := len(a)
184	b := make([]byte, n)
185	for i, v := range a {
186		b[n-1-i] = v
187	}
188	return b
189}
190
191func makeBackgroundSound(length int) []byte {
192	b := makeWhiteNoise(length, 8)
193	for i := 0; i < length/(sampleRate/10); i++ {
194		snd := digitSounds[rand.Intn(10)]
195		snd = changeSpeed(reversedSound(snd), rndf(0.8, 1.4))
196		place := rand.Intn(len(b) - len(snd))
197		setSoundLevel(snd, rndf(0.5, 1.2))
198		mixSound(b[place:], snd)
199	}
200	setSoundLevel(b, rndf(0.2, 0.3))
201	return b
202}
203
204func randomizedDigitSound(n byte) []byte {
205	s := randomSpeed(digitSounds[n])
206	setSoundLevel(s, rndf(0.7, 1.3))
207	return s
208}