-
Notifications
You must be signed in to change notification settings - Fork 13
/
catnip.go
98 lines (76 loc) · 1.93 KB
/
catnip.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package catnip
import (
"context"
"sync"
"github.com/noriah/catnip/input"
"github.com/noriah/catnip/processor"
"github.com/pkg/errors"
)
const MaxChannelCount = 2
const MaxSampleSize = 2048
type SetupFunc func() error
type StartFunc func(ctx context.Context) (context.Context, error)
type CleanupFunc func() error
func Run(cfg *Config, ctx context.Context) error {
if err := cfg.Validate(); err != nil {
return err
}
inputBuffers := input.MakeBuffers(cfg.ChannelCount, cfg.SampleSize)
procConfig := processor.Config{
SampleRate: cfg.SampleRate,
SampleSize: cfg.SampleSize,
ChannelCount: cfg.ChannelCount,
ProcessRate: cfg.ProcessRate,
Buffers: inputBuffers,
Analyzer: cfg.Analyzer,
Output: cfg.Output,
Smoother: cfg.Smoother,
Windower: cfg.Windower,
}
var vis processor.Processor
if cfg.UseThreaded {
vis = processor.NewThreaded(procConfig)
} else {
vis = processor.New(procConfig)
}
backend, err := input.InitBackend(cfg.Backend)
if err != nil {
return err
}
sessConfig := input.SessionConfig{
FrameSize: cfg.ChannelCount,
SampleSize: cfg.SampleSize,
SampleRate: cfg.SampleRate,
}
if sessConfig.Device, err = input.GetDevice(backend, cfg.Device); err != nil {
return err
}
audio, err := backend.Start(sessConfig)
defer backend.Close()
if err != nil {
return errors.Wrap(err, "failed to start the input backend")
}
if cfg.SetupFunc != nil {
if err := cfg.SetupFunc(); err != nil {
return err
}
}
if cfg.CleanupFunc != nil {
defer cfg.CleanupFunc()
}
if cfg.StartFunc != nil {
if ctx, err = cfg.StartFunc(ctx); err != nil {
return err
}
}
kickChan := make(chan bool, 1)
mu := &sync.Mutex{}
ctx = vis.Start(ctx, kickChan, mu)
defer vis.Stop()
if err := audio.Start(ctx, inputBuffers, kickChan, mu); err != nil {
if !errors.Is(ctx.Err(), context.Canceled) {
return errors.Wrap(err, "failed to start input session")
}
}
return nil
}