-
Notifications
You must be signed in to change notification settings - Fork 97
/
beep_player.go
489 lines (432 loc) · 10.4 KB
/
beep_player.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
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
package player
import (
"context"
"io"
"log/slog"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/gopxl/beep"
"github.com/gopxl/beep/effects"
"github.com/gopxl/beep/speaker"
"github.com/go-musicfox/go-musicfox/internal/configs"
"github.com/go-musicfox/go-musicfox/internal/types"
"github.com/go-musicfox/go-musicfox/utils/app"
"github.com/go-musicfox/go-musicfox/utils/errorx"
"github.com/go-musicfox/go-musicfox/utils/filex"
"github.com/go-musicfox/go-musicfox/utils/iox"
"github.com/go-musicfox/go-musicfox/utils/slogx"
"github.com/go-musicfox/go-musicfox/utils/timex"
)
const (
sampleRate = beep.SampleRate(44100)
resampleQuiality = 4
)
type beepPlayer struct {
l sync.Mutex
curMusic URLMusic
timer *timex.Timer
cacheReader *os.File
cacheWriter *os.File
cacheDownloaded bool
curStreamer beep.StreamSeekCloser
curFormat beep.Format
state types.State
ctrl *beep.Ctrl
volume *effects.Volume
timeChan chan time.Duration
stateChan chan types.State
musicChan chan URLMusic
httpClient *http.Client
close chan struct{}
}
func NewBeepPlayer() *beepPlayer {
p := &beepPlayer{
state: types.Stopped,
timeChan: make(chan time.Duration),
stateChan: make(chan types.State),
musicChan: make(chan URLMusic),
ctrl: &beep.Ctrl{
Paused: false,
},
volume: &effects.Volume{
Base: 2,
Silent: false,
},
httpClient: &http.Client{},
close: make(chan struct{}),
}
errorx.WaitGoStart(p.listen)
return p
}
// listen 开始监听
func (p *beepPlayer) listen() {
var (
done = make(chan struct{})
resp *http.Response
reader io.ReadCloser
err error
ctx context.Context
cancel context.CancelFunc
prevSongId int64
doneHandle = func() {
select {
case done <- struct{}{}:
case <-p.close:
}
}
)
if err = speaker.Init(sampleRate, sampleRate.N(time.Millisecond*200)); err != nil {
panic(err)
}
cacheFile := filepath.Join(app.DataRootDir(), "music_cache")
for {
select {
case <-p.close:
if cancel != nil {
cancel()
}
return
case <-done:
p.Stop()
case p.curMusic = <-p.musicChan:
p.l.Lock()
p.pausedNoLock()
if p.timer != nil {
p.timer.SetPassed(0)
}
// 清理上一轮
if cancel != nil {
cancel()
}
p.reset()
ctx, cancel = context.WithCancel(context.Background())
if prevSongId != p.curMusic.Id || !filex.FileOrDirExists(cacheFile) {
// FIXME: 先这样处理,暂时没想到更好的办法
if p.cacheReader, err = os.OpenFile(cacheFile, os.O_CREATE|os.O_TRUNC|os.O_RDONLY, 0666); err != nil {
panic(err)
}
if p.cacheWriter, err = os.OpenFile(cacheFile, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666); err != nil {
panic(err)
}
if strings.HasPrefix(p.curMusic.URL, "file://") {
reader, err = os.Open(strings.TrimPrefix(p.curMusic.URL, "file://"))
if err != nil {
panic(err)
}
} else if resp, err = p.httpClient.Get(p.curMusic.URL); err != nil {
p.stopNoLock()
goto nextLoop
} else {
reader = resp.Body
}
// 边下载边播放
go func(ctx context.Context, cacheWFile *os.File, read io.ReadCloser) {
defer func() {
if errorx.Recover(true) {
p.Stop()
}
}()
_, _ = iox.CopyClose(ctx, cacheWFile, read)
p.cacheDownloaded = true
p.l.Lock()
defer p.l.Unlock()
if p.curStreamer == nil {
// nil说明外层解析还没开始或解析失败,这里直接退出
return
}
// 除了MP3格式,其他格式无需重载
if p.curMusic.Type == Mp3 && configs.ConfigRegistry.Player.BeepMp3Decoder != types.BeepMiniMp3Decoder {
// 需再开一次文件,保证其指针变化,否则将概率导致 p.ctrl.Streamer = beep.Seq(……) 直接停止播放
cacheReader, _ := os.OpenFile(cacheFile, os.O_RDONLY, 0666)
// 使用新的文件后需手动Seek到上次播放处
lastStreamer := p.curStreamer
defer func() { _ = lastStreamer.Close() }()
pos := lastStreamer.Position()
if p.curStreamer, p.curFormat, err = DecodeSong(p.curMusic.Type, cacheReader); err != nil {
p.stopNoLock()
return
}
if pos >= p.curStreamer.Len() {
pos = p.curStreamer.Len() - 1
}
if pos < 0 {
pos = 1
}
_ = p.curStreamer.Seek(pos)
p.ctrl.Streamer = beep.Seq(p.resampleStreamer(p.curFormat.SampleRate), beep.Callback(doneHandle))
}
}(ctx, p.cacheWriter, reader)
N := 512
if p.curMusic.Type == Flac {
N *= 4
}
if err = iox.WaitForNBytes(p.cacheReader, N, time.Millisecond*100, 50); err != nil {
slog.Error("WaitForNBytes err", slogx.Error(err))
p.stopNoLock()
goto nextLoop
}
} else {
// 单曲循环以及歌单只有一首歌时不再请求网络
if p.cacheReader, err = os.OpenFile(cacheFile, os.O_RDONLY, 0666); err != nil {
panic(err)
}
}
if p.curStreamer, p.curFormat, err = DecodeSong(p.curMusic.Type, p.cacheReader); err != nil {
p.stopNoLock()
goto nextLoop
}
slog.Info("current song sample rate", slog.Int("sample_rate", int(p.curFormat.SampleRate)))
p.ctrl.Streamer = beep.Seq(p.resampleStreamer(p.curFormat.SampleRate), beep.Callback(doneHandle))
p.volume.Streamer = p.ctrl
speaker.Play(p.volume)
// 计时器
p.timer = timex.NewTimer(timex.Options{
Duration: 8760 * time.Hour,
TickerInternal: 200 * time.Millisecond,
OnRun: func(started bool) {},
OnPaused: func() {},
OnDone: func(stopped bool) {},
OnTick: func() {
select {
case p.timeChan <- p.timer.Passed():
default:
}
},
})
p.resumeNoLock()
prevSongId = p.curMusic.Id
nextLoop:
p.l.Unlock()
}
}
}
// Play 播放音乐
func (p *beepPlayer) Play(music URLMusic) {
timer := time.NewTimer(time.Second)
defer timer.Stop()
select {
case p.musicChan <- music:
case <-timer.C:
}
}
func (p *beepPlayer) CurMusic() URLMusic {
return p.curMusic
}
func (p *beepPlayer) setState(state types.State) {
p.state = state
select {
case p.stateChan <- state:
case <-time.After(time.Second * 2):
}
}
// State 当前状态
func (p *beepPlayer) State() types.State {
return p.state
}
// StateChan 状态发生变更
func (p *beepPlayer) StateChan() <-chan types.State {
return p.stateChan
}
func (p *beepPlayer) PassedTime() time.Duration {
if p.timer == nil {
return 0
}
return p.timer.Passed()
}
// TimeChan 获取定时器
func (p *beepPlayer) TimeChan() <-chan time.Duration {
return p.timeChan
}
func (p *beepPlayer) Seek(duration time.Duration) {
if duration < 0 {
return
}
// FIXME: 暂时仅对MP3格式提供跳转功能
// FLAC格式(其他未测)跳转会占用大量CPU资源,比特率越高占用越高
// 导致Seek方法卡住20-40秒的时间,之后方可随意跳转
// minimp3未实现Seek
if p.curStreamer == nil || p.curMusic.Type != Mp3 || configs.ConfigRegistry.Player.BeepMp3Decoder == types.BeepMiniMp3Decoder {
return
}
if p.state == types.Playing || p.state == types.Paused {
speaker.Lock()
newPos := sampleRate.N(duration)
if newPos < 0 {
newPos = 0
}
if newPos >= p.curStreamer.Len() {
newPos = p.curStreamer.Len() - 1
}
if p.curStreamer != nil {
err := p.curStreamer.Seek(newPos)
if err != nil {
slog.Error("seek error", slogx.Error(err))
}
}
if p.timer != nil {
p.timer.SetPassed(duration)
}
speaker.Unlock()
}
}
// UpVolume 调大音量
func (p *beepPlayer) UpVolume() {
if p.volume.Volume >= 0 {
return
}
p.l.Lock()
defer p.l.Unlock()
p.volume.Silent = false
p.volume.Volume += 0.25
}
// DownVolume 调小音量
func (p *beepPlayer) DownVolume() {
if p.volume.Volume <= -5 {
return
}
p.l.Lock()
defer p.l.Unlock()
p.volume.Volume -= 0.25
if p.volume.Volume <= -5 {
p.volume.Silent = true
}
}
func (p *beepPlayer) Volume() int {
return int((p.volume.Volume + 5) * 100 / 5) // 转为0~100存储
}
func (p *beepPlayer) SetVolume(volume int) {
if volume > 100 {
volume = 100
}
if volume < 0 {
volume = 0
}
p.l.Lock()
defer p.l.Unlock()
p.volume.Volume = float64(volume)*5/100 - 5
}
func (p *beepPlayer) pausedNoLock() {
if p.state != types.Playing {
return
}
p.ctrl.Paused = true
p.timer.Pause()
p.setState(types.Paused)
}
// Paused 暂停播放
func (p *beepPlayer) Paused() {
p.l.Lock()
defer p.l.Unlock()
p.pausedNoLock()
}
func (p *beepPlayer) resumeNoLock() {
if p.state == types.Playing {
return
}
p.ctrl.Paused = false
go p.timer.Run()
p.setState(types.Playing)
}
// Resume 继续播放
func (p *beepPlayer) Resume() {
p.l.Lock()
defer p.l.Unlock()
p.resumeNoLock()
}
func (p *beepPlayer) stopNoLock() {
if p.state == types.Stopped {
return
}
p.ctrl.Paused = true
p.timer.Pause()
p.setState(types.Stopped)
}
// Stop 停止
func (p *beepPlayer) Stop() {
p.l.Lock()
defer p.l.Unlock()
p.stopNoLock()
}
// Toggle 切换状态
func (p *beepPlayer) Toggle() {
switch p.State() {
case types.Paused, types.Stopped:
p.Resume()
case types.Playing:
p.Paused()
default:
p.Resume()
}
}
// Close 关闭
func (p *beepPlayer) Close() {
p.l.Lock()
defer p.l.Unlock()
if p.timer != nil {
p.timer.Stop()
}
close(p.close)
speaker.Clear()
speaker.Close()
}
func (p *beepPlayer) reset() {
// 关闭旧计时器
if p.timer != nil {
p.timer.Stop()
}
if p.cacheReader != nil {
_ = p.cacheReader.Close()
}
if p.cacheWriter != nil {
_ = p.cacheWriter.Close()
}
if p.curStreamer != nil {
_ = p.curStreamer.Close()
p.curStreamer = nil
}
p.cacheDownloaded = false
speaker.Clear()
}
func (p *beepPlayer) streamer(samples [][2]float64) (n int, ok bool) {
defer func() {
if err := recover(); err != nil {
slog.Error("streamer panic", slogx.Error(err))
p.Stop()
}
}()
pos := p.curStreamer.Position()
n, ok = p.curStreamer.Stream(samples)
err := p.curStreamer.Err()
if err == nil && (ok || p.cacheDownloaded) {
return
}
p.pausedNoLock()
retry := 4
for !ok && retry > 0 {
if p.curMusic.Type == Flac {
if err = p.curStreamer.Seek(pos); err != nil {
return
}
}
errorx.ResetError(p.curStreamer)
select {
case <-time.After(time.Second * 5):
n, ok = p.curStreamer.Stream(samples)
case <-p.close:
return
}
retry--
}
p.resumeNoLock()
return
}
func (p *beepPlayer) resampleStreamer(old beep.SampleRate) beep.Streamer {
if old == sampleRate {
return beep.StreamerFunc(p.streamer)
}
return beep.Resample(resampleQuiality, old, sampleRate, beep.StreamerFunc(p.streamer))
}