-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdetector.go
73 lines (60 loc) · 1.72 KB
/
detector.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package goertzel
import (
"context"
"io"
"log"
"math"
"time"
)
func detectTone(pCtx context.Context, freq, sampleRate float64, minDuration time.Duration, in io.Reader) (sufficient bool, err error) {
var findingAbsence bool
if freq < 0 {
findingAbsence = true
freq = -freq
}
t := NewTarget(freq, sampleRate, minDuration)
defer t.Stop()
ctx, cancel := context.WithCancel(pCtx)
defer cancel()
go func() {
defer cancel()
if rErr := t.Read(in); rErr != nil {
if rErr == io.EOF {
return
}
log.Println("detectTone: failure reading input:", err)
}
}()
// Figure out the time-size of each block to determine the blocks required to constitute detection
timeSize := float64(t.blockSize) / sampleRate
reqBlocks := int(math.Ceil(minDuration.Seconds() / float64(timeSize)))
var count int
var found bool
for b := range t.Blocks() {
if findingAbsence {
found = !b.Present
} else {
found = b.Present
}
if found {
count++
} else {
count = 0
}
if count >= reqBlocks {
return true, nil
}
if ctx.Err() != nil {
return
}
}
return
}
// DetectTone waits for the given tone to be found, returning with `true` when it is. `false` will be returned if canceled by context or by a stream error/completion.
func DetectTone(ctx context.Context, freq, sampleRate float64, minDuration time.Duration, in io.Reader) (found bool, err error) {
return detectTone(ctx, freq, sampleRate, minDuration, in)
}
// DetectToneAbsence waits for the given frequency to go away for the requested amount of time
func DetectToneAbsence(ctx context.Context, freq, sampleRate float64, minDuration time.Duration, in io.Reader) (found bool, err error) {
return detectTone(ctx, -freq, sampleRate, minDuration, in)
}