-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
347 lines (289 loc) · 7.73 KB
/
main.go
File metadata and controls
347 lines (289 loc) · 7.73 KB
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
// spank detects slaps/hits on the laptop and plays audio responses.
// It reads the Apple Silicon accelerometer directly via IOKit HID —
// no separate sensor daemon required. Needs sudo.
//
// Cross-platform support:
// - macOS: Uses Apple Silicon accelerometer (IOKit HID)
// - Linux: Uses microphone to detect loud sounds (slaps)
// - Windows: Uses microphone to detect loud sounds (slaps)
//go:build darwin || linux || windows
// +build darwin linux windows
package main
import (
"bytes"
"context"
"embed"
"fmt"
"io"
"math/rand"
"os"
"os/signal"
"sort"
"sync"
"syscall"
"time"
"github.com/charmbracelet/fang"
"github.com/gopxl/beep/v2"
"github.com/gopxl/beep/v2/mp3"
"github.com/gopxl/beep/v2/speaker"
"github.com/spf13/cobra"
)
var version = "dev"
//go:embed audio/pain/*.mp3
var painAudio embed.FS
//go:embed audio/sexy/*.mp3
var sexyAudio embed.FS
//go:embed audio/halo/*.mp3
var haloAudio embed.FS
var (
sexyMode bool
haloMode bool
threshold int // Linux only: microphone threshold
)
// platformSensor is the interface for platform-specific sensor implementations
type platformSensor interface {
// Read returns (eventDetected, severity, amplitude, error)
Read() (bool, string, float64, error)
Close() error
}
// newPlatformSensor creates a platform-specific sensor with optional threshold (Linux only)
var newPlatformSensor func(threshold int) (platformSensor, error)
type playMode int
const (
modeRandom playMode = iota
modeEscalation
)
type soundPack struct {
name string
fs embed.FS
dir string
mode playMode
files []string
}
func (sp *soundPack) loadFiles() error {
entries, err := sp.fs.ReadDir(sp.dir)
if err != nil {
return err
}
sp.files = make([]string, 0, len(entries))
for _, e := range entries {
if !e.IsDir() {
sp.files = append(sp.files, sp.dir+"/"+e.Name())
}
}
sort.Strings(sp.files)
return nil
}
type slapTracker struct {
mu sync.Mutex
times []time.Time
window time.Duration
pack *soundPack
altIdx int
}
func newSlapTracker(pack *soundPack) *slapTracker {
return &slapTracker{
window: 5 * time.Minute,
pack: pack,
}
}
func (st *slapTracker) record(t time.Time) int {
st.mu.Lock()
defer st.mu.Unlock()
cutoff := t.Add(-st.window)
newTimes := make([]time.Time, 0, len(st.times)+1)
for _, tt := range st.times {
if tt.After(cutoff) {
newTimes = append(newTimes, tt)
}
}
newTimes = append(newTimes, t)
st.times = newTimes
return len(st.times)
}
func (st *slapTracker) getFile(count int) string {
st.mu.Lock()
defer st.mu.Unlock()
if len(st.pack.files) == 0 {
return ""
}
if st.pack.mode == modeRandom {
return st.pack.files[rand.Intn(len(st.pack.files))]
}
// Escalation mode
maxIdx := len(st.pack.files) - 1
topTwo := maxIdx - 1
if topTwo < 0 {
topTwo = 0
}
var idx int
if count >= 20 {
st.altIdx = 1 - st.altIdx
idx = topTwo + st.altIdx
} else {
ratio := float64(count) / 20.0
if ratio > 1 {
ratio = 1
}
idx = int(ratio * float64(topTwo))
}
if idx > maxIdx {
idx = maxIdx
}
return st.pack.files[idx]
}
func main() {
cmd := &cobra.Command{
Use: "spank",
Short: "Yells 'ow!' when you slap the laptop",
Long: `spank detects slaps/hits on the laptop and plays audio responses.
Platform-specific behavior:
macOS: Uses Apple Silicon accelerometer (IOKit HID) - requires root
Linux: Uses microphone to detect loud sounds (slaps) - no root needed
Use --sexy for a different experience. In sexy mode, the more you slap
within a minute, the more intense the sounds become.
Use --halo to play random audio clips from Halo soundtracks on each slap.`,
Version: version,
RunE: func(cmd *cobra.Command, args []string) error {
return run(cmd.Context())
},
SilenceUsage: true,
}
cmd.Flags().BoolVarP(&sexyMode, "sexy", "s", false, "Enable sexy mode")
cmd.Flags().BoolVarP(&haloMode, "halo", "H", false, "Enable halo mode")
cmd.Flags().IntVar(&threshold, "threshold", 0, "Microphone detection threshold (Linux only, default: 2000)")
if err := fang.Execute(context.Background(), cmd); err != nil {
os.Exit(1)
}
}
func run(ctx context.Context) error {
// Platform-specific requirements check
if err := checkPlatformRequirements(); err != nil {
return err
}
if sexyMode && haloMode {
return fmt.Errorf("--sexy and --halo are mutually exclusive; pick one")
}
var pack *soundPack
switch {
case sexyMode:
pack = &soundPack{name: "sexy", fs: sexyAudio, dir: "audio/sexy", mode: modeEscalation}
case haloMode:
pack = &soundPack{name: "halo", fs: haloAudio, dir: "audio/halo", mode: modeRandom}
default:
pack = &soundPack{name: "pain", fs: painAudio, dir: "audio/pain", mode: modeRandom}
}
if err := pack.loadFiles(); err != nil {
return fmt.Errorf("loading %s audio: %w", pack.name, err)
}
ctx, cancel := signal.NotifyContext(ctx, syscall.SIGINT, syscall.SIGTERM)
defer cancel()
// Create platform-specific sensor
sensor, err := newPlatformSensor(threshold)
if err != nil {
return fmt.Errorf("initializing sensor: %w", err)
}
defer sensor.Close()
tracker := newSlapTracker(pack)
lastYell := time.Time{}
cooldown := 1500 * time.Millisecond // Increased to avoid multiple triggers for single slap
fmt.Printf("spank: listening for slaps in %s mode... (ctrl+c to quit)\n", pack.name)
ticker := time.NewTicker(10 * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
fmt.Println("\nbye!")
return nil
case <-ticker.C:
}
now := time.Now()
// Platform-specific sensor read
eventDetected, severity, amplitude, err := sensor.Read()
if err != nil {
return fmt.Errorf("sensor error: %w", err)
}
if eventDetected {
if time.Since(lastYell) > cooldown {
lastYell = now
count := tracker.record(now)
file := tracker.getFile(count)
fmt.Printf("slap #%d [%s amp=%.5fg] -> %s\n", count, severity, amplitude, file)
queueAudio(pack.fs, file)
}
}
}
}
var speakerMu sync.Mutex
var currentSampleRate beep.SampleRate
// audioQueue is a channel for queuing audio files to be played sequentially
var audioQueue = make(chan queuedAudio, 10)
// audioQueueCount tracks number of audio files queued or playing
var audioQueueCount int
type queuedAudio struct {
fs embed.FS
path string
}
// audioPlayerStarted tracks if the background audio player goroutine is running
var audioPlayerStarted bool
func startAudioPlayer() {
speakerMu.Lock()
defer speakerMu.Unlock()
if audioPlayerStarted {
return
}
audioPlayerStarted = true
// Initialize speaker with a default sample rate (will be reinitialized on first play if needed)
defaultRate := beep.SampleRate(48000)
speaker.Init(defaultRate, defaultRate.N(time.Second/10))
go func() {
for qa := range audioQueue {
playAudioSync(qa.fs, qa.path)
}
}()
}
func playAudioSync(fs embed.FS, path string) {
data, err := fs.ReadFile(path)
if err != nil {
speakerMu.Lock()
audioQueueCount--
speakerMu.Unlock()
return
}
streamer, format, err := mp3.Decode(io.NopCloser(bytes.NewReader(data)))
if err != nil {
speakerMu.Lock()
audioQueueCount--
speakerMu.Unlock()
return
}
defer streamer.Close()
speakerMu.Lock()
if currentSampleRate != format.SampleRate {
currentSampleRate = format.SampleRate
speaker.Clear()
speaker.Init(currentSampleRate, currentSampleRate.N(time.Second/10))
}
speakerMu.Unlock()
done := make(chan bool)
speaker.Play(beep.Seq(streamer, beep.Callback(func() {
done <- true
})))
<-done
speakerMu.Lock()
audioQueueCount--
speakerMu.Unlock()
}
func queueAudio(fs embed.FS, path string) {
startAudioPlayer()
speakerMu.Lock()
audioQueueCount++
speakerMu.Unlock()
audioQueue <- queuedAudio{fs: fs, path: path}
}
// isAudioPlaying returns true if there are audio files queued or playing
func isAudioPlaying() bool {
speakerMu.Lock()
defer speakerMu.Unlock()
return audioQueueCount > 0
}