all repos — captcha @ 6a29415a8364ec2971fdc62d9e415ed53fc20410

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

audio.go (view raw)

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