forked from hajimehoshi/ebiten
/
audio.go
622 lines (547 loc) · 14.5 KB
/
audio.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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
// Copyright 2015 Hajime Hoshi
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package audio provides audio players.
//
// The stream format must be 16-bit little endian and 2 channels. The format is as follows:
// [data] = [sample 1] [sample 2] [sample 3] ...
// [sample *] = [channel 1] ...
// [channel *] = [byte 1] [byte 2] ...
//
// An audio context (audio.Context object) has a sample rate you can specify and all streams you want to play must have the same
// sample rate. However, decoders in e.g. audio/mp3 package adjust sample rate automatically,
// and you don't have to care about it as long as you use those decoders.
//
// An audio context can generate 'players' (audio.Player objects),
// and you can play sound by calling Play function of players.
// When multiple players play, mixing is automatically done.
// Note that too many players may cause distortion.
//
// Ebiten's game progress tries to synchronizes with audio progress, but
// delay can happen if, e.g., decoding an audio source takes long.
//
// For the simplest example to play sound, see wav package in the examples.
package audio
import (
"bytes"
"errors"
"fmt"
"io"
"runtime"
"time"
"github.com/hajimehoshi/oto"
"github.com/hajimehoshi/ebiten/internal/audiobinding"
"github.com/hajimehoshi/ebiten/internal/clock"
"github.com/hajimehoshi/ebiten/internal/sync"
"github.com/hajimehoshi/ebiten/internal/web"
)
type players struct {
players map[*Player]struct{}
sync.RWMutex
}
const (
channelNum = 2
bytesPerSample = 2
// TODO: This assumes that channelNum is a power of 2.
mask = ^(channelNum*bytesPerSample - 1)
)
func (p *players) Read(b []byte) (int, error) {
p.Lock()
defer p.Unlock()
if len(p.players) == 0 {
l := len(b)
l &= mask
copy(b, make([]byte, l))
return l, nil
}
l := len(b)
l &= mask
b16s := [][]int16{}
for player := range p.players {
buf, err := player.bufferToInt16(l)
if err != nil {
return 0, err
}
b16s = append(b16s, buf)
}
for i := 0; i < l/2; i++ {
x := 0
for _, b16 := range b16s {
x += int(b16[i])
}
if x > (1<<15)-1 {
x = (1 << 15) - 1
}
if x < -(1 << 15) {
x = -(1 << 15)
}
b[2*i] = byte(x)
b[2*i+1] = byte(x >> 8)
}
closed := []*Player{}
for player := range p.players {
if player.eof() {
closed = append(closed, player)
}
}
for _, player := range closed {
delete(p.players, player)
}
return l, nil
}
func (p *players) addPlayer(player *Player) {
p.Lock()
p.players[player] = struct{}{}
p.Unlock()
}
func (p *players) removePlayer(player *Player) {
p.Lock()
delete(p.players, player)
p.Unlock()
}
func (p *players) hasPlayer(player *Player) bool {
p.RLock()
_, ok := p.players[player]
p.RUnlock()
return ok
}
func (p *players) hasSource(src ReadSeekCloser) bool {
p.RLock()
defer p.RUnlock()
for player := range p.players {
if player.src == src {
return true
}
}
return false
}
// A Context represents a current state of audio.
//
// At most one Context object can exist in one process.
// This means only one constant sample rate is valid in your one application.
//
// For a typical usage example, see examples/wav/main.go.
type Context struct {
players *players
initCh chan struct{}
initedCh chan struct{}
pingCount int
sampleRate int
m sync.Mutex
}
var (
theContext *Context
theContextLock sync.Mutex
)
// NewContext creates a new audio context with the given sample rate.
//
// The sample rate is also used for decoding MP3 with audio/mp3 package
// or other formats as the target sample rate.
//
// sampleRate should be 44100 or 48000.
// Other values might not work.
// For example, 22050 causes error on Safari when decoding MP3.
//
// Error returned by NewContext is always nil as of 1.5.0-alpha.
//
// NewContext panics when an audio context is already created.
func NewContext(sampleRate int) (*Context, error) {
theContextLock.Lock()
defer theContextLock.Unlock()
if theContext != nil {
panic("audio: context is already created")
}
c := &Context{
sampleRate: sampleRate,
}
theContext = c
c.players = &players{
players: map[*Player]struct{}{},
}
go c.loop()
return c, nil
}
// CurrentContext returns the current context or nil if there is no context.
func CurrentContext() *Context {
theContextLock.Lock()
c := theContext
theContextLock.Unlock()
return c
}
func (c *Context) ping() {
if c.initCh != nil {
close(c.initCh)
c.initCh = nil
}
<-c.initedCh
c.m.Lock()
c.pingCount = 5
c.m.Unlock()
}
func (c *Context) loop() {
c.initCh = make(chan struct{})
c.initedCh = make(chan struct{})
// Copy the channel since c.initCh can be set as nil after clock.RegisterPing.
initCh := c.initCh
clock.RegisterPing(c.ping)
// Initialize oto.Player lazily to enable calling NewContext in an 'init' function.
// Accessing oto.Player functions requires the environment to be already initialized,
// but if Ebiten is used for a shared library, the timing when init functions are called
// is unexpectable.
// e.g. a variable for JVM on Android might not be set.
<-initCh
// On most desktop environments, 4096 [bytes] is enough
// but there are some known environment that is too short (e.g. Windows on Parallels, iOS).
p, err := oto.NewPlayer(c.sampleRate, channelNum, bytesPerSample, 8192)
if err != nil {
audiobinding.SetError(err)
return
}
defer p.Close()
close(c.initedCh)
bytesPerFrame := c.sampleRate * bytesPerSample * channelNum / clock.FPS
written := int64(0)
prevWritten := int64(0)
for {
c.m.Lock()
if c.pingCount == 0 {
c.m.Unlock()
time.Sleep(10 * time.Millisecond)
continue
}
c.pingCount--
c.m.Unlock()
const n = 4096
if _, err := io.CopyN(p, c.players, n); err != nil {
audiobinding.SetError(err)
return
}
written += int64(n)
fs := written/int64(bytesPerFrame) - prevWritten/int64(bytesPerFrame)
clock.ProceedAudioTimer(fs)
prevWritten = written
}
}
// Update is deprecated as of 1.6.0-alpha.
//
// As of 1.6.0-alpha, Update always returns nil and does nothing related to updating the state.
// You don't have to call this function any longer.
// The internal audio error is returned at ebiten.Run instead.
func (c *Context) Update() error {
return nil
}
// SampleRate returns the sample rate.
func (c *Context) SampleRate() int {
return c.sampleRate
}
// ReadSeekCloser is an io.ReadSeeker and io.Closer.
type ReadSeekCloser interface {
io.ReadSeeker
io.Closer
}
type bytesReadSeekCloser struct {
reader *bytes.Reader
}
func (b *bytesReadSeekCloser) Read(buf []byte) (int, error) {
return b.reader.Read(buf)
}
func (b *bytesReadSeekCloser) Seek(offset int64, whence int) (int64, error) {
return b.reader.Seek(offset, whence)
}
func (b *bytesReadSeekCloser) Close() error {
b.reader = nil
return nil
}
// BytesReadSeekCloser creates ReadSeekCloser from bytes.
func BytesReadSeekCloser(b []byte) ReadSeekCloser {
return &bytesReadSeekCloser{reader: bytes.NewReader(b)}
}
// Player is an audio player which has one stream.
type Player struct {
players *players
src ReadSeekCloser
srcEOF bool
sampleRate int
buf []byte
pos int64
volume float64
closeCh chan struct{}
closedCh chan struct{}
readLoopEndedCh chan struct{}
seekCh chan seekArgs
seekedCh chan error
proceedCh chan []int16
proceededCh chan proceededValues
syncCh chan func()
}
type seekArgs struct {
offset int64
whence int
}
type proceededValues struct {
buf []int16
err error
}
// NewPlayer creates a new player with the given stream.
//
// src's format must be linear PCM (16bits little endian, 2 channel stereo)
// without a header (e.g. RIFF header).
// The sample rate must be same as that of the audio context.
//
// Note that the given src can't be shared with other Player objects.
//
// NewPlayer tries to call Seek of src to get the current position.
// NewPlayer returns error when the Seek returns error.
func NewPlayer(context *Context, src ReadSeekCloser) (*Player, error) {
if context.players.hasSource(src) {
return nil, errors.New("audio: src cannot be shared with another Player")
}
p := &Player{
players: context.players,
src: src,
sampleRate: context.sampleRate,
buf: []byte{},
volume: 1,
closeCh: make(chan struct{}),
closedCh: make(chan struct{}),
readLoopEndedCh: make(chan struct{}),
seekCh: make(chan seekArgs),
seekedCh: make(chan error),
proceedCh: make(chan []int16),
proceededCh: make(chan proceededValues),
syncCh: make(chan func()),
}
// Get the current position of the source.
pos, err := p.src.Seek(0, io.SeekCurrent)
if err != nil {
return nil, err
}
p.pos = pos
runtime.SetFinalizer(p, (*Player).Close)
go func() {
p.readLoop()
}()
return p, nil
}
// NewPlayerFromBytes creates a new player with the given bytes.
//
// As opposed to NewPlayer, you don't have to care if src is already used by another player or not.
// src can be shared by multiple players.
//
// The format of src should be same as noted at NewPlayer.
//
// NewPlayerFromBytes's error is always nil as of 1.5.0-alpha.
func NewPlayerFromBytes(context *Context, src []byte) (*Player, error) {
b := BytesReadSeekCloser(src)
p, err := NewPlayer(context, b)
if err != nil {
// Errors should never happen.
panic(err)
}
return p, nil
}
// Close closes the stream.
//
// When closing, the stream owned by the player will also be closed by calling its Close.
// This means that the source stream passed via NewPlayer will also be closed.
//
// Close returns error when closing the source returns error.
func (p *Player) Close() error {
runtime.SetFinalizer(p, nil)
p.players.removePlayer(p)
select {
case p.closeCh <- struct{}{}:
<-p.closedCh
return nil
case <-p.readLoopEndedCh:
return fmt.Errorf("audio: the player is already closed")
}
}
func (p *Player) bufferToInt16(lengthInBytes int) ([]int16, error) {
select {
case p.proceedCh <- make([]int16, lengthInBytes/2):
r := <-p.proceededCh
return r.buf, r.err
case <-p.readLoopEndedCh:
return nil, fmt.Errorf("audio: the player is already closed")
}
}
// Play plays the stream.
//
// Play always returns nil.
func (p *Player) Play() error {
p.players.addPlayer(p)
return nil
}
func (p *Player) readLoop() {
defer func() {
// Note: the error is ignored
p.src.Close()
// Receiving from a closed channel returns quickly
// i.e. `case <-p.readLoopEndedCh:` can check if this loops is ended.
close(p.readLoopEndedCh)
}()
t := time.After(0)
var readErr error
for {
select {
case <-p.closeCh:
p.closedCh <- struct{}{}
return
case s := <-p.seekCh:
pos, err := p.src.Seek(s.offset, s.whence)
p.buf = nil
p.pos = pos
p.srcEOF = false
p.seekedCh <- err
t = time.After(time.Millisecond)
break
case <-t:
// If the buffer has 1 second, that's enough.
if len(p.buf) >= p.sampleRate*bytesPerSample*channelNum {
t = time.After(100 * time.Millisecond)
break
}
// Try to read the buffer for 1/60[s].
s := 60
if web.IsAndroidChrome() {
s = 10
} else if web.IsBrowser() {
s = 20
}
l := p.sampleRate * bytesPerSample * channelNum / s
l &= mask
buf := make([]byte, l)
n, err := p.src.Read(buf)
p.buf = append(p.buf, buf[:n]...)
if err == io.EOF {
p.srcEOF = true
}
if p.srcEOF && len(p.buf) == 0 {
t = nil
break
}
if err != nil && err != io.EOF {
readErr = err
t = nil
break
}
if web.IsBrowser() {
t = time.After(10 * time.Millisecond)
} else {
t = time.After(time.Millisecond)
}
case buf := <-p.proceedCh:
if readErr != nil {
p.proceededCh <- proceededValues{buf, readErr}
return
}
lengthInBytes := len(buf) * 2
l := lengthInBytes
if len(p.buf) < lengthInBytes && !p.srcEOF {
p.proceededCh <- proceededValues{buf, nil}
break
}
if l > len(p.buf) {
l = len(p.buf)
}
for i := 0; i < l/2; i++ {
buf[i] = int16(p.buf[2*i]) | (int16(p.buf[2*i+1]) << 8)
buf[i] = int16(float64(buf[i]) * p.volume)
}
p.pos += int64(l)
p.buf = p.buf[l:]
p.proceededCh <- proceededValues{buf, nil}
case f := <-p.syncCh:
f()
}
}
}
func (p *Player) sync(f func()) bool {
ch := make(chan struct{})
ff := func() {
f()
close(ch)
}
select {
case p.syncCh <- ff:
<-ch
return true
case <-p.readLoopEndedCh:
return false
}
}
func (p *Player) eof() bool {
r := false
p.sync(func() {
r = p.srcEOF && len(p.buf) == 0
})
return r
}
// IsPlaying returns boolean indicating whether the player is playing.
func (p *Player) IsPlaying() bool {
return p.players.hasPlayer(p)
}
// Rewind rewinds the current position to the start.
//
// Rewind returns error when seeking the source stream returns error.
func (p *Player) Rewind() error {
return p.Seek(0)
}
// Seek seeks the position with the given offset.
//
// Seek returns error when seeking the source stream returns error.
func (p *Player) Seek(offset time.Duration) error {
o := int64(offset) * bytesPerSample * channelNum * int64(p.sampleRate) / int64(time.Second)
o &= mask
select {
case p.seekCh <- seekArgs{o, io.SeekStart}:
return <-p.seekedCh
case <-p.readLoopEndedCh:
return fmt.Errorf("audio: the player is already closed")
}
}
// Pause pauses the playing.
//
// Pause always returns nil.
func (p *Player) Pause() error {
p.players.removePlayer(p)
return nil
}
// Current returns the current position.
func (p *Player) Current() time.Duration {
sample := int64(0)
p.sync(func() {
sample = p.pos / bytesPerSample / channelNum
})
return time.Duration(sample) * time.Second / time.Duration(p.sampleRate)
}
// Volume returns the current volume of this player [0-1].
func (p *Player) Volume() float64 {
v := 0.0
p.sync(func() {
v = p.volume
})
return v
}
// SetVolume sets the volume of this player.
// volume must be in between 0 and 1. This function panics otherwise.
func (p *Player) SetVolume(volume float64) {
// The condition must be true when volume is NaN.
if !(0 <= volume && volume <= 1) {
panic("audio: volume must be in between 0 and 1")
}
p.sync(func() {
p.volume = volume
})
}