forked from g3n/engine
/
player.go
365 lines (283 loc) · 8.6 KB
/
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
// Copyright 2016 The G3N Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package audio
// #include <stdlib.h>
import "C"
import (
"github.com/g3n/engine/audio/al"
"github.com/g3n/engine/core"
"github.com/g3n/engine/gls"
"github.com/g3n/engine/math32"
"io"
"time"
"unsafe"
)
const (
playerBufferCount = 2
playerBufferSize = 32 * 1024
)
// Player is a 3D (spatial) audio file player
// It embeds a core.Node so it can be inserted as a child in any other 3D object.
type Player struct {
core.Node // Embedded node
af *AudioFile // Pointer to media audio file
buffers []uint32 // OpenAL buffer names
source uint32 // OpenAL source name
nextBuf int // Index of next buffer to fill
pdata unsafe.Pointer // Pointer to C allocated storage
disposed bool // Disposed flag
gchan chan (string) // Channel for informing of goroutine end
}
// NewPlayer creates and returns a pointer to a new audio player object
// which will play the audio encoded in the specified file.
// Currently it supports wave and Ogg Vorbis formats.
func NewPlayer(filename string) (*Player, error) {
// Try to open audio file
af, err := NewAudioFile(filename)
if err != nil {
return nil, err
}
// Creates player
p := new(Player)
p.Node.Init()
p.af = af
// Generate buffers names
p.buffers = al.GenBuffers(playerBufferCount)
// Generate source name
p.source = al.GenSource()
// Allocates C memory buffer
p.pdata = C.malloc(playerBufferSize)
// Initialize channel for communication with internal goroutine
p.gchan = make(chan string, 1)
return p, nil
}
// Dispose disposes of this player resources
func (p *Player) Dispose() {
p.Stop()
// Close file
p.af.Close()
// Release OpenAL resources
al.DeleteSource(p.source)
al.DeleteBuffers(p.buffers)
// Release C memory
C.free(p.pdata)
p.pdata = nil
p.disposed = true
}
// State returns the current state of this player
func (p *Player) State() int {
return int(al.GetSourcei(p.source, al.SourceState))
}
// Play starts playing this player
func (p *Player) Play() error {
state := p.State()
// Already playing, nothing to do
if state == al.Playing {
return nil
}
// If paused, goroutine should be running, just starts playing
if state == al.Paused {
al.SourcePlay(p.source)
return nil
}
// Inactive or Stopped state
if state == al.Initial || state == al.Stopped {
// Sets file pointer to the beginning
err := p.af.Seek(0)
if err != nil {
return err
}
// Fill buffers with decoded data
for i := 0; i < playerBufferCount; i++ {
err = p.fillBuffer(p.buffers[i])
if err != nil {
if err != io.EOF {
return err
}
break
}
}
p.nextBuf = 0
// Clear previous goroutine response channel
select {
case _ = <-p.gchan:
default:
}
// Starts playing and starts goroutine to fill buffers
al.SourcePlay(p.source)
go p.run()
return nil
}
return nil
}
// Pause sets the player in the pause state
func (p *Player) Pause() {
if p.State() == al.Paused {
return
}
al.SourcePause(p.source)
}
// Stop stops the player
func (p *Player) Stop() {
state := p.State()
if state == al.Stopped || state == al.Initial {
return
}
al.SourceStop(p.source)
// Waits for goroutine to finish
<-p.gchan
}
// CurrentTime returns the current time in seconds spent in the stream
func (p *Player) CurrentTime() float64 {
return p.af.CurrentTime()
}
// TotalTime returns the total time in seconds to play this stream
func (p *Player) TotalTime() float64 {
return p.af.info.TotalTime
}
// Gain returns the current gain (volume) of this player
func (p *Player) Gain() float32 {
return al.GetSourcef(p.source, al.Gain)
}
// SetGain sets the gain (volume) of this player
func (p *Player) SetGain(gain float32) {
al.Sourcef(p.source, al.Gain, gain)
}
// MinGain returns the current minimum gain of this player
func (p *Player) MinGain() float32 {
return al.GetSourcef(p.source, al.MinGain)
}
// SetMinGain sets the minimum gain (volume) of this player
func (p *Player) SetMinGain(gain float32) {
al.Sourcef(p.source, al.MinGain, gain)
}
// MaxGain returns the current maximum gain of this player
func (p *Player) MaxGain() float32 {
return al.GetSourcef(p.source, al.MaxGain)
}
// SetMaxGain sets the maximum gain (volume) of this player
func (p *Player) SetMaxGain(gain float32) {
al.Sourcef(p.source, al.MaxGain, gain)
}
// Pitch returns the current pitch factor of this player
func (p *Player) Pitch() float32 {
return al.GetSourcef(p.source, al.Pitch)
}
// SetPitch sets the pitch factor of this player
func (p *Player) SetPitch(pitch float32) {
al.Sourcef(p.source, al.Pitch, pitch)
}
// Looping returns the current looping state of this player
func (p *Player) Looping() bool {
return p.af.Looping()
}
// SetLooping sets the looping state of this player
func (p *Player) SetLooping(looping bool) {
p.af.SetLooping(looping)
}
// InnerCone returns the inner cone angle in degrees
func (p *Player) InnerCone() float32 {
return al.GetSourcef(p.source, al.ConeInnerAngle)
}
// SetInnerCone sets the inner cone angle in degrees
func (p *Player) SetInnerCone(inner float32) {
al.Sourcef(p.source, al.ConeInnerAngle, inner)
}
// OuterCone returns the outer cone angle in degrees
func (p *Player) OuterCone() float32 {
return al.GetSourcef(p.source, al.ConeOuterAngle)
}
// SetOuterCone sets the outer cone angle in degrees
func (p *Player) SetOuterCone(outer float32) {
al.Sourcef(p.source, al.ConeOuterAngle, outer)
}
// SetVelocity sets the velocity of this player
// It is used to calculate Doppler effects
func (p *Player) SetVelocity(vx, vy, vz float32) {
al.Source3f(p.source, al.Velocity, vx, vy, vz)
}
// SetVelocityVec sets the velocity of this player from the specified vector
// It is used to calculate Doppler effects
func (p Player) SetVelocityVec(v *math32.Vector3) {
al.Source3f(p.source, al.Velocity, v.X, v.Y, v.Z)
}
// Velocity returns this player velocity
func (p *Player) Velocity() (float32, float32, float32) {
return al.GetSource3f(p.source, al.Velocity)
}
// VelocityVec returns this player velocity vector
func (p *Player) VelocityVec() math32.Vector3 {
vx, vy, vz := al.GetSource3f(p.source, al.Velocity)
return math32.Vector3{vx, vy, vz}
}
// SetRolloffFactor sets this player rolloff factor user to calculate
// the gain attenuation by distance
func (p *Player) SetRolloffFactor(rfactor float32) {
al.Sourcef(p.source, al.RolloffFactor, rfactor)
}
// Render satisfies the INode interface.
// It is called by renderer at every frame and is used to
// update the audio source position and direction
func (p *Player) Render(gl *gls.GLS) {
// Sets the player source world position
var wpos math32.Vector3
p.WorldPosition(&wpos)
al.Source3f(p.source, al.Position, wpos.X, wpos.Y, wpos.Z)
// Sets the player source world direction
var wdir math32.Vector3
p.WorldDirection(&wdir)
al.Source3f(p.source, al.Direction, wdir.X, wdir.Y, wdir.Z)
}
// Goroutine to fill PCM buffers with decoded data for OpenAL
func (p *Player) run() {
for {
// Get current state of player source
state := al.GetSourcei(p.source, al.SourceState)
processed := al.GetSourcei(p.source, al.BuffersProcessed)
queued := al.GetSourcei(p.source, al.BuffersQueued)
//log.Debug("state:%x processed:%v queued:%v", state, processed, queued)
// If stopped, unqueues all buffer before exiting
if state == al.Stopped {
if queued == 0 {
break
}
// Unqueue buffers
if processed > 0 {
al.SourceUnqueueBuffers(p.source, uint32(processed), nil)
}
continue
}
// If no buffers processed, sleeps and try again
if processed == 0 {
time.Sleep(20 * time.Millisecond)
continue
}
// Remove processed buffers from the queue
al.SourceUnqueueBuffers(p.source, uint32(processed), nil)
// Fill and enqueue buffers with new data
for i := 0; i < int(processed); i++ {
err := p.fillBuffer(p.buffers[p.nextBuf])
if err != nil {
break
}
p.nextBuf = (p.nextBuf + 1) % playerBufferCount
}
}
// Sends indication of goroutine end
p.gchan <- "end"
}
// fillBuffer fills the specified OpenAL buffer with next decoded data
// and queues the buffer to this player source
func (p *Player) fillBuffer(buf uint32) error {
// Reads next decoded data
n, err := p.af.Read(p.pdata, playerBufferSize)
if err != nil {
return err
}
// Sends data to buffer
//log.Debug("BufferData:%v format:%x n:%v rate:%v", buf, p.af.info.Format, n, p.af.info.SampleRate)
al.BufferData(buf, uint32(p.af.info.Format), p.pdata, uint32(n), uint32(p.af.info.SampleRate))
al.SourceQueueBuffers(p.source, buf)
return nil
}