-
Notifications
You must be signed in to change notification settings - Fork 151
Expand file tree
/
Copy pathdriver_darwin.go
More file actions
393 lines (344 loc) · 10.7 KB
/
driver_darwin.go
File metadata and controls
393 lines (344 loc) · 10.7 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
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
// Copyright 2021 The Oto Authors
//
// 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 oto
import (
"fmt"
"runtime"
"sync"
"time"
"unsafe"
"github.com/ebitengine/oto/v3/internal/mux"
)
const (
float32SizeInBytes = 4
bufferCount = 4
noErr = 0
// maxAudioQueueRebuildCount caps how many times we will rebuild the AudioQueue in
// response to kAudioQueueErr_QueueInvalidated before giving up. A handful is
// enough: a transient mediaserverd reset only invalidates the queue once.
maxAudioQueueRebuildCount = 5
)
func newAudioQueue(sampleRate, channelCount int, oneBufferSizeInBytes int) (_AudioQueueRef, []_AudioQueueBufferRef, error) {
desc := _AudioStreamBasicDescription{
mSampleRate: float64(sampleRate),
mFormatID: uint32(kAudioFormatLinearPCM),
mFormatFlags: uint32(kAudioFormatFlagIsFloat),
mBytesPerPacket: uint32(channelCount * float32SizeInBytes),
mFramesPerPacket: 1,
mBytesPerFrame: uint32(channelCount * float32SizeInBytes),
mChannelsPerFrame: uint32(channelCount),
mBitsPerChannel: uint32(8 * float32SizeInBytes),
}
var audioQueue _AudioQueueRef
if osstatus := _AudioQueueNewOutput(
&desc,
render,
nil,
0, //CFRunLoopRef
0, //CFStringRef
0,
&audioQueue); osstatus != noErr {
return 0, nil, fmt.Errorf("oto: AudioQueueNewFormat with StreamFormat failed: %d", osstatus)
}
bufs := make([]_AudioQueueBufferRef, 0, bufferCount)
for len(bufs) < cap(bufs) {
var buf _AudioQueueBufferRef
if osstatus := _AudioQueueAllocateBuffer(audioQueue, uint32(oneBufferSizeInBytes), &buf); osstatus != noErr {
return 0, nil, fmt.Errorf("oto: AudioQueueAllocateBuffer failed: %d", osstatus)
}
buf.mAudioDataByteSize = uint32(oneBufferSizeInBytes)
bufs = append(bufs, buf)
}
return audioQueue, bufs, nil
}
type context struct {
audioQueue _AudioQueueRef
unqueuedBuffers []_AudioQueueBufferRef
sampleRate int
channelCount int
oneBufferSizeInBytes int
cond *sync.Cond
toPause bool
toResume bool
mux *mux.Mux
err atomicError
}
// TODO: Convert the error code correctly.
// See https://stackoverflow.com/questions/2196869/how-do-you-convert-an-iphone-osstatus-code-to-something-useful
var theContext *context
func newContext(sampleRate int, channelCount int, format mux.Format, bufferSizeInBytes int, _ string) (*context, chan struct{}, error) {
// defaultOneBufferSizeInBytes is the default buffer size in bytes.
//
// 12288 seems necessary at least on iPod touch (7th) and MacBook Pro 2020.
// With 48000[Hz] stereo, the maximum delay is (12288*4[buffers] / 4 / 2)[samples] / 48000 [Hz] = 100[ms].
// '4' is float32 size in bytes. '2' is a number of channels for stereo.
const defaultOneBufferSizeInBytes = 12288
var oneBufferSizeInBytes int
if bufferSizeInBytes != 0 {
oneBufferSizeInBytes = bufferSizeInBytes / bufferCount
} else {
oneBufferSizeInBytes = defaultOneBufferSizeInBytes
}
bytesPerSample := channelCount * 4
oneBufferSizeInBytes = oneBufferSizeInBytes / bytesPerSample * bytesPerSample
ready := make(chan struct{})
c := &context{
cond: sync.NewCond(&sync.Mutex{}),
mux: mux.New(sampleRate, channelCount, format),
sampleRate: sampleRate,
channelCount: channelCount,
oneBufferSizeInBytes: oneBufferSizeInBytes,
}
theContext = c
if err := initializeAPI(); err != nil {
return nil, nil, err
}
go func() {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
var readyClosed bool
defer func() {
if !readyClosed {
close(ready)
}
}()
q, bs, err := newAudioQueue(c.sampleRate, c.channelCount, c.oneBufferSizeInBytes)
if err != nil {
c.err.TryStore(err)
return
}
c.audioQueue = q
c.unqueuedBuffers = bs
var retryCount int
var rebuildCount int
try:
if osstatus := _AudioQueueStart(c.audioQueue, nil); osstatus != noErr {
if osstatus == kAudioQueueErr_QueueInvalidated && rebuildCount < maxAudioQueueRebuildCount {
if err := c.rebuildAudioQueue(); err != nil {
c.err.TryStore(err)
return
}
rebuildCount++
retryCount = 0
goto try
}
maxRetry := 0
switch osstatus {
case avAudioSessionErrorCodeCannotStartPlaying:
maxRetry = 100
case avAudioSessionErrorCodeUnspecified:
maxRetry = 30
}
if retryCount < maxRetry {
time.Sleep(sleepTime(retryCount))
retryCount++
goto try
}
c.err.TryStore(fmt.Errorf("oto: AudioQueueStart failed at newContext: %d", osstatus))
return
}
close(ready)
readyClosed = true
c.loop()
}()
return c, ready, nil
}
func (c *context) wait() bool {
c.cond.L.Lock()
defer c.cond.L.Unlock()
for len(c.unqueuedBuffers) == 0 && c.err.Load() == nil && !c.toPause && !c.toResume {
c.cond.Wait()
}
return c.err.Load() == nil
}
func (c *context) loop() {
buf32 := make([]float32, c.oneBufferSizeInBytes/4)
for {
if !c.wait() {
return
}
c.appendBuffer(buf32)
}
}
func (c *context) appendBuffer(buf32 []float32) {
c.cond.L.Lock()
defer c.cond.L.Unlock()
if c.err.Load() != nil {
return
}
if c.toPause {
if err := c.pause(); err != nil {
c.err.TryStore(err)
}
c.toPause = false
return
}
if c.toResume {
if err := c.resume(); err != nil {
c.err.TryStore(err)
}
c.toResume = false
return
}
buf := c.unqueuedBuffers[0]
copy(c.unqueuedBuffers, c.unqueuedBuffers[1:])
c.unqueuedBuffers = c.unqueuedBuffers[:len(c.unqueuedBuffers)-1]
c.mux.ReadFloat32s(buf32)
copy(unsafe.Slice((*float32)(unsafe.Pointer(buf.mAudioData)), buf.mAudioDataByteSize/float32SizeInBytes), buf32)
if osstatus := _AudioQueueEnqueueBuffer(c.audioQueue, buf, 0, nil); osstatus != noErr {
if osstatus == kAudioQueueErr_QueueInvalidated {
// The queue was invalidated under us (typically a mediaserverd reset).
// Rebuild a fresh queue and start it. The audio we just rendered into
// `buf` is dropped — at most one buffer of glitch.
if err := c.rebuildAudioQueue(); err != nil {
c.err.TryStore(err)
return
}
if err := c.resume(); err != nil {
c.err.TryStore(err)
}
return
}
c.err.TryStore(fmt.Errorf("oto: AudioQueueEnqueueBuffer failed: %d", osstatus))
}
}
// Suspend returns immediately. The actual AudioQueuePause runs on a
// background goroutine so the calling thread (typically the platform UI
// thread) is never blocked on cond.L — which can be held for several seconds
// while resume() retries transient AVAudioSession errors. Errors from the
// asynchronous transition surface via Err.
func (c *context) Suspend() error {
err := c.err.Load()
go func() {
c.cond.L.Lock()
defer c.cond.L.Unlock()
c.toPause = true
c.toResume = false
c.cond.Signal()
}()
return err
}
// Resume returns immediately. See Suspend for the rationale; AudioQueueStart
// (with retries on transient AVAudioSession errors on iOS) runs on a
// background goroutine.
func (c *context) Resume() error {
err := c.err.Load()
go func() {
c.cond.L.Lock()
defer c.cond.L.Unlock()
c.toPause = false
c.toResume = true
c.cond.Signal()
}()
return err
}
func (c *context) pause() error {
if osstatus := _AudioQueuePause(c.audioQueue); osstatus != noErr {
if osstatus == kAudioQueueErr_QueueInvalidated {
// Rebuild a fresh stopped queue so a subsequent Resume can start it.
return c.rebuildAudioQueue()
}
return fmt.Errorf("oto: AudioQueuePause failed: %d", osstatus)
}
return nil
}
func (c *context) resume() error {
var retryCount int
var rebuildCount int
try:
if osstatus := _AudioQueueStart(c.audioQueue, nil); osstatus != noErr {
if osstatus == kAudioQueueErr_QueueInvalidated && rebuildCount < maxAudioQueueRebuildCount {
if err := c.rebuildAudioQueue(); err != nil {
return err
}
rebuildCount++
retryCount = 0
goto try
}
maxRetry := 0
switch osstatus {
case avAudioSessionErrorCodeCannotStartPlaying:
maxRetry = 100
case avAudioSessionErrorCodeCannotInterruptOthers,
avAudioSessionErrorCodeUnspecified:
maxRetry = 30
}
if retryCount < maxRetry {
// It is uncertain that this error is temporary or not. Then let's use exponential-time sleeping.
time.Sleep(sleepTime(retryCount))
retryCount++
goto try
}
if osstatus == avAudioSessionErrorCodeSiriIsRecording {
// As this error should be temporary, it should be OK to use a short time for sleep anytime.
time.Sleep(10 * time.Millisecond)
goto try
}
return fmt.Errorf("oto: AudioQueueStart failed at Resume: %d", osstatus)
}
return nil
}
// rebuildAudioQueue disposes the current AudioQueue (which may already be invalid)
// and creates a fresh queue with new buffers. The new queue is left in the stopped
// state — the caller is responsible for any subsequent _AudioQueueStart.
//
// The caller must serialize access to c.audioQueue and c.unqueuedBuffers (i.e. hold
// c.cond.L, or be the newContext goroutine before `ready` has been closed).
func (c *context) rebuildAudioQueue() error {
if c.audioQueue != 0 {
// kAudioQueueErr_QueueInvalidated is expected here — that's the very case
// we're recovering from. Anything else is unexpected and worth surfacing.
osstatus := _AudioQueueDispose(c.audioQueue, true)
c.audioQueue = 0
if osstatus != noErr && osstatus != kAudioQueueErr_QueueInvalidated {
c.unqueuedBuffers = nil
return fmt.Errorf("oto: AudioQueueDispose failed during rebuild: %d", osstatus)
}
}
c.unqueuedBuffers = nil
q, bs, err := newAudioQueue(c.sampleRate, c.channelCount, c.oneBufferSizeInBytes)
if err != nil {
return fmt.Errorf("oto: rebuilding AudioQueue failed: %w", err)
}
c.audioQueue = q
c.unqueuedBuffers = bs
return nil
}
func (c *context) Err() error {
return c.err.Load()
}
func render(inUserData unsafe.Pointer, inAQ _AudioQueueRef, inBuffer _AudioQueueBufferRef) {
theContext.cond.L.Lock()
defer theContext.cond.L.Unlock()
// Drop callbacks from a previously-disposed queue: after rebuildAudioQueue,
// late-delivered callbacks for the old queue would otherwise inject stale
// buffer pointers into c.unqueuedBuffers.
if inAQ != theContext.audioQueue {
return
}
theContext.unqueuedBuffers = append(theContext.unqueuedBuffers, inBuffer)
theContext.cond.Signal()
}
func sleepTime(count int) time.Duration {
switch count {
case 0:
return 10 * time.Millisecond
case 1:
return 20 * time.Millisecond
case 2:
return 50 * time.Millisecond
default:
return 100 * time.Millisecond
}
}