audio: Refactoring

This commit is contained in:
Hajime Hoshi 2016-04-16 00:52:07 +09:00
parent 4dc4cf55d0
commit e5609f06d6
2 changed files with 90 additions and 89 deletions

View File

@ -35,12 +35,8 @@ import (
"github.com/hajimehoshi/ebiten/exp/audio/internal/driver" "github.com/hajimehoshi/ebiten/exp/audio/internal/driver"
) )
type mixingStream struct { type players struct {
sampleRate int players map[*Player]struct{}
players map[*Player]struct{}
// Note that Read (and other methods) need to be concurrent safe
// because Read is called from another groutine (see NewContext).
sync.RWMutex sync.RWMutex
} }
@ -52,10 +48,6 @@ const (
mask = ^(channelNum*bytesPerSample - 1) mask = ^(channelNum*bytesPerSample - 1)
) )
func (s *mixingStream) SampleRate() int {
return s.sampleRate
}
func min(a, b int) int { func min(a, b int) int {
if a < b { if a < b {
return a return a
@ -63,11 +55,11 @@ func min(a, b int) int {
return b return b
} }
func (s *mixingStream) Read(b []byte) (int, error) { func (p *players) Read(b []byte) (int, error) {
s.Lock() p.Lock()
defer s.Unlock() defer p.Unlock()
if len(s.players) == 0 { if len(p.players) == 0 {
l := len(b) l := len(b)
l &= mask l &= mask
copy(b, make([]byte, l)) copy(b, make([]byte, l))
@ -75,7 +67,7 @@ func (s *mixingStream) Read(b []byte) (int, error) {
} }
closed := []*Player{} closed := []*Player{}
l := len(b) l := len(b)
for p := range s.players { for p := range p.players {
err := p.readToBuffer(l) err := p.readToBuffer(l)
if err == io.EOF { if err == io.EOF {
closed = append(closed, p) closed = append(closed, p)
@ -86,7 +78,7 @@ func (s *mixingStream) Read(b []byte) (int, error) {
} }
l &= mask l &= mask
b16s := [][]int16{} b16s := [][]int16{}
for p := range s.players { for p := range p.players {
b16s = append(b16s, p.bufferToInt16(l)) b16s = append(b16s, p.bufferToInt16(l))
} }
for i := 0; i < l/2; i++ { for i := 0; i < l/2; i++ {
@ -103,73 +95,45 @@ func (s *mixingStream) Read(b []byte) (int, error) {
b[2*i] = byte(x) b[2*i] = byte(x)
b[2*i+1] = byte(x >> 8) b[2*i+1] = byte(x >> 8)
} }
for p := range s.players { for p := range p.players {
p.proceed(l) p.proceed(l)
} }
for _, p := range closed { for _, pl := range closed {
delete(s.players, p) delete(p.players, pl)
} }
return l, nil return l, nil
} }
func (s *mixingStream) newPlayer(src ReadSeekCloser) (*Player, error) { func (p *players) addPlayer(player *Player) {
s.Lock() p.Lock()
defer s.Unlock() defer p.Unlock()
p := &Player{ p.players[player] = struct{}{}
stream: s,
src: src,
buf: []byte{},
volume: 1,
}
// Get the current position of the source.
pos, err := p.src.Seek(0, 1)
if err != nil {
return nil, err
}
p.pos = pos
runtime.SetFinalizer(p, (*Player).Close)
return p, nil
} }
func (s *mixingStream) closePlayer(player *Player) error { func (p *players) removePlayer(player *Player) {
s.Lock() p.Lock()
defer s.Unlock() defer p.Unlock()
runtime.SetFinalizer(player, nil) delete(p.players, player)
return player.src.Close()
} }
func (s *mixingStream) addPlayer(player *Player) { func (p *players) hasPlayer(player *Player) bool {
s.Lock() p.RLock()
defer s.Unlock() defer p.RUnlock()
s.players[player] = struct{}{} _, ok := p.players[player]
}
func (s *mixingStream) removePlayer(player *Player) {
s.Lock()
defer s.Unlock()
delete(s.players, player)
}
func (s *mixingStream) hasPlayer(player *Player) bool {
s.RLock()
defer s.RUnlock()
_, ok := s.players[player]
return ok return ok
} }
func (s *mixingStream) seekPlayer(player *Player, offset time.Duration) error { func (p *players) seekPlayer(player *Player, offset int64) error {
s.Lock() p.Lock()
defer s.Unlock() defer p.Unlock()
o := int64(offset) * bytesPerSample * channelNum * int64(s.sampleRate) / int64(time.Second) return player.seek(offset)
o &= mask
return player.seek(o)
} }
func (s *mixingStream) playerCurrent(player *Player) time.Duration { func (p *players) playerCurrent(player *Player, sampleRate int) time.Duration {
s.RLock() p.RLock()
defer s.RUnlock() defer p.RUnlock()
sample := player.pos / bytesPerSample / channelNum sample := player.pos / bytesPerSample / channelNum
return time.Duration(sample) * time.Second / time.Duration(s.sampleRate) return time.Duration(sample) * time.Second / time.Duration(sampleRate)
} }
// TODO: Enable to specify the format like Mono8? // TODO: Enable to specify the format like Mono8?
@ -200,8 +164,9 @@ func (s *mixingStream) playerCurrent(player *Player) time.Duration {
// You can also call Update independently from the game loop as 'async mode'. // You can also call Update independently from the game loop as 'async mode'.
// In this case, audio goes on even when the game stops e.g. by diactivating the screen. // In this case, audio goes on even when the game stops e.g. by diactivating the screen.
type Context struct { type Context struct {
stream *mixingStream players *players
driver *driver.Player driver *driver.Player
sampleRate int
frames int frames int
writtenBytes int writtenBytes int
} }
@ -209,10 +174,11 @@ type Context struct {
// NewContext creates a new audio context with the given sample rate (e.g. 44100). // NewContext creates a new audio context with the given sample rate (e.g. 44100).
func NewContext(sampleRate int) (*Context, error) { func NewContext(sampleRate int) (*Context, error) {
// TODO: Panic if one context exists. // TODO: Panic if one context exists.
c := &Context{} c := &Context{
c.stream = &mixingStream{
sampleRate: sampleRate, sampleRate: sampleRate,
players: map[*Player]struct{}{}, }
c.players = &players{
players: map[*Player]struct{}{},
} }
// TODO: Rename this other than player // TODO: Rename this other than player
p, err := driver.NewPlayer(sampleRate, channelNum, bytesPerSample) p, err := driver.NewPlayer(sampleRate, channelNum, bytesPerSample)
@ -232,12 +198,12 @@ func NewContext(sampleRate int) (*Context, error) {
// In async mode, the audio never stops even when the game stops. // In async mode, the audio never stops even when the game stops.
func (c *Context) Update() error { func (c *Context) Update() error {
c.frames++ c.frames++
bytesPerFrame := c.stream.sampleRate * bytesPerSample * channelNum / ebiten.FPS bytesPerFrame := c.sampleRate * bytesPerSample * channelNum / ebiten.FPS
l := (c.frames * bytesPerFrame) - c.writtenBytes l := (c.frames * bytesPerFrame) - c.writtenBytes
l &= mask l &= mask
c.writtenBytes += l c.writtenBytes += l
buf := make([]byte, l) buf := make([]byte, l)
n, err := io.ReadFull(c.stream, buf) n, err := io.ReadFull(c.players, buf)
if err != nil { if err != nil {
return err return err
} }
@ -256,8 +222,10 @@ func (c *Context) Update() error {
// SampleRate returns the sample rate. // SampleRate returns the sample rate.
// All audio source must have the same sample rate. // All audio source must have the same sample rate.
//
// This function is concurrent-safe.
func (c *Context) SampleRate() int { func (c *Context) SampleRate() int {
return c.stream.SampleRate() return c.sampleRate
} }
// ReadSeekCloser is an io.ReadSeeker and io.Closer. // ReadSeekCloser is an io.ReadSeeker and io.Closer.
@ -268,11 +236,12 @@ type ReadSeekCloser interface {
// Player is an audio player which has one stream. // Player is an audio player which has one stream.
type Player struct { type Player struct {
stream *mixingStream players *players
src ReadSeekCloser src ReadSeekCloser
buf []byte buf []byte
pos int64 sampleRate int
volume float64 pos int64
volume float64
} }
// NewPlayer creates a new player with the given stream. // NewPlayer creates a new player with the given stream.
@ -280,13 +249,33 @@ type Player struct {
// src's format must be linear PCM (16bits little endian, 2 channel stereo) // src's format must be linear PCM (16bits little endian, 2 channel stereo)
// without a header (e.g. RIFF header). // without a header (e.g. RIFF header).
// The sample rate must be same as that of the audio context. // The sample rate must be same as that of the audio context.
//
// This function is concurrent-safe.
func (c *Context) NewPlayer(src ReadSeekCloser) (*Player, error) { func (c *Context) NewPlayer(src ReadSeekCloser) (*Player, error) {
return c.stream.newPlayer(src) p := &Player{
players: c.players,
src: src,
sampleRate: c.sampleRate,
buf: []byte{},
volume: 1,
}
// Get the current position of the source.
pos, err := p.src.Seek(0, 1)
if err != nil {
return nil, err
}
p.pos = pos
runtime.SetFinalizer(p, (*Player).Close)
return p, nil
} }
// Close closes the stream. Ths source stream passed by NewPlayer will also be closed. // Close closes the stream. Ths source stream passed by NewPlayer will also be closed.
//
// This function is concurrent-safe.
func (p *Player) Close() error { func (p *Player) Close() error {
return p.stream.closePlayer(p) p.players.removePlayer(p)
runtime.SetFinalizer(p, nil)
return p.src.Close()
} }
func (p *Player) readToBuffer(length int) error { func (p *Player) readToBuffer(length int) error {
@ -317,24 +306,34 @@ func (p *Player) bufferLength() int {
} }
// Play plays the stream. // Play plays the stream.
//
// This function is concurrent-safe.
func (p *Player) Play() error { func (p *Player) Play() error {
p.stream.addPlayer(p) p.players.addPlayer(p)
return nil return nil
} }
// IsPlaying returns boolean indicating whether the player is playing. // IsPlaying returns boolean indicating whether the player is playing.
//
// This function is concurrent-safe.
func (p *Player) IsPlaying() bool { func (p *Player) IsPlaying() bool {
return p.stream.hasPlayer(p) return p.players.hasPlayer(p)
} }
// Rewind rewinds the current position to the start. // Rewind rewinds the current position to the start.
//
// This function is concurrent-safe.
func (p *Player) Rewind() error { func (p *Player) Rewind() error {
return p.Seek(0) return p.Seek(0)
} }
// Seek seeks the position with the given offset. // Seek seeks the position with the given offset.
//
// This function is concurrent-safe.
func (p *Player) Seek(offset time.Duration) error { func (p *Player) Seek(offset time.Duration) error {
return p.stream.seekPlayer(p, offset) o := int64(offset) * bytesPerSample * channelNum * int64(p.sampleRate) / int64(time.Second)
o &= mask
return p.players.seekPlayer(p, o)
} }
func (p *Player) seek(offset int64) error { func (p *Player) seek(offset int64) error {
@ -348,14 +347,18 @@ func (p *Player) seek(offset int64) error {
} }
// Pause pauses the playing. // Pause pauses the playing.
//
// This function is concurrent-safe.
func (p *Player) Pause() error { func (p *Player) Pause() error {
p.stream.removePlayer(p) p.players.removePlayer(p)
return nil return nil
} }
// Current returns the current position. // Current returns the current position.
//
// This function is concurrent-safe.
func (p *Player) Current() time.Duration { func (p *Player) Current() time.Duration {
return p.stream.playerCurrent(p) return p.players.playerCurrent(p, p.sampleRate)
} }
// Volume returns the current volume of this player [0-1]. // Volume returns the current volume of this player [0-1].
@ -372,5 +375,3 @@ func (p *Player) SetVolume(volume float64) {
} }
p.volume = volume p.volume = volume
} }
// TODO: Panning

View File

@ -23,7 +23,7 @@ type Loop struct {
size int64 size int64
} }
func NewLoop(stream ReadSeekCloser, size int64) ReadSeekCloser { func NewLoop(stream ReadSeekCloser, size int64) *Loop {
return &Loop{ return &Loop{
stream: stream, stream: stream,
size: size, size: size,