forked from ebitengine/oto
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdriver_darwin.go
244 lines (207 loc) · 6.44 KB
/
driver_darwin.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
// Copyright 2019 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.
// +build !js
package oto
// #cgo LDFLAGS: -framework AudioToolbox
//
// #import <AudioToolbox/AudioToolbox.h>
//
// void oto_render(void* inUserData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffer);
import "C"
import (
"fmt"
"runtime"
"sync"
"time"
"unsafe"
)
const baseQueueBufferSize = 1024
type audioInfo struct {
channelNum int
bitDepthInBytes int
}
type driver struct {
audioQueue C.AudioQueueRef
buf []byte
bufSize int
sampleRate int
audioInfo *audioInfo
buffers []C.AudioQueueBufferRef
err error
chWrite chan []byte
chWritten chan int
}
var (
theDriver *driver
driverM sync.Mutex
)
func setDriver(d *driver) {
driverM.Lock()
defer driverM.Unlock()
if theDriver != nil && d != nil {
panic("oto: at most one driver object can exist")
}
theDriver = d
setNotificationHandler(d)
}
func getDriver() *driver {
driverM.Lock()
defer driverM.Unlock()
return theDriver
}
// TOOD: Convert the error code correctly.
// See https://stackoverflow.com/questions/2196869/how-do-you-convert-an-iphone-osstatus-code-to-something-useful
func newDriver(sampleRate, channelNum, bitDepthInBytes, bufferSizeInBytes int) (tryWriteCloser, error) {
flags := C.kAudioFormatFlagIsPacked
if bitDepthInBytes != 1 {
flags |= C.kAudioFormatFlagIsSignedInteger
}
desc := C.AudioStreamBasicDescription{
mSampleRate: C.double(sampleRate),
mFormatID: C.kAudioFormatLinearPCM,
mFormatFlags: C.UInt32(flags),
mBytesPerPacket: C.UInt32(channelNum * bitDepthInBytes),
mFramesPerPacket: 1,
mBytesPerFrame: C.UInt32(channelNum * bitDepthInBytes),
mChannelsPerFrame: C.UInt32(channelNum),
mBitsPerChannel: C.UInt32(8 * bitDepthInBytes),
}
audioInfo := &audioInfo{
channelNum: channelNum,
bitDepthInBytes: bitDepthInBytes,
}
var audioQueue C.AudioQueueRef
if osstatus := C.AudioQueueNewOutput(
&desc,
(C.AudioQueueOutputCallback)(C.oto_render),
unsafe.Pointer(audioInfo),
(C.CFRunLoopRef)(0),
(C.CFStringRef)(0),
0,
&audioQueue); osstatus != C.noErr {
return nil, fmt.Errorf("oto: AudioQueueNewFormat with StreamFormat failed: %d", osstatus)
}
queueBufferSize := baseQueueBufferSize * channelNum * bitDepthInBytes
nbuf := bufferSizeInBytes / queueBufferSize
if nbuf <= 1 {
nbuf = 2
}
d := &driver{
audioQueue: audioQueue,
sampleRate: sampleRate,
audioInfo: audioInfo,
bufSize: nbuf * queueBufferSize,
buffers: make([]C.AudioQueueBufferRef, nbuf),
chWrite: make(chan []byte),
chWritten: make(chan int),
}
runtime.SetFinalizer(d, (*driver).Close)
// Set the driver before setting the rendering callback.
setDriver(d)
for i := 0; i < len(d.buffers); i++ {
if osstatus := C.AudioQueueAllocateBuffer(audioQueue, C.UInt32(queueBufferSize), &d.buffers[i]); osstatus != C.noErr {
return nil, fmt.Errorf("oto: AudioQueueAllocateBuffer failed: %d", osstatus)
}
d.buffers[i].mAudioDataByteSize = C.UInt32(queueBufferSize)
for j := 0; j < queueBufferSize; j++ {
*(*byte)(unsafe.Pointer(uintptr(unsafe.Pointer(d.buffers[i].mAudioData)) + uintptr(j))) = 0
}
if osstatus := C.AudioQueueEnqueueBuffer(audioQueue, d.buffers[i], 0, nil); osstatus != C.noErr {
return nil, fmt.Errorf("oto: AudioQueueEnqueueBuffer failed: %d", osstatus)
}
}
if osstatus := C.AudioQueueStart(audioQueue, nil); osstatus != C.noErr {
return nil, fmt.Errorf("oto: AudioQueueStart failed: %d", osstatus)
}
return d, nil
}
//export oto_render
func oto_render(inUserData unsafe.Pointer, inAQ C.AudioQueueRef, inBuffer C.AudioQueueBufferRef) {
audioInfo := (*audioInfo)(inUserData)
queueBufferSize := baseQueueBufferSize * audioInfo.channelNum * audioInfo.bitDepthInBytes
d := getDriver()
var buf []byte
// Set the timer. When the application is in background or being switched, the driver's buffer is not
// updated and it is needed to fill the buffer with zeros.
s := time.Second * time.Duration(queueBufferSize) / time.Duration(d.sampleRate*d.audioInfo.channelNum*d.audioInfo.bitDepthInBytes)
t := time.NewTicker(s)
defer t.Stop()
ch := t.C
paused := false
for len(buf) < queueBufferSize {
select {
case dbuf := <-d.chWrite:
if paused {
C.AudioQueueStart(inAQ, nil)
paused = false
}
n := queueBufferSize - len(buf)
if n > len(dbuf) {
n = len(dbuf)
}
buf = append(buf, dbuf[:n]...)
d.chWritten <- n
case <-ch:
if !paused {
C.AudioQueuePause(inAQ)
paused = true
}
ch = nil
}
}
for i := 0; i < queueBufferSize; i++ {
*(*byte)(unsafe.Pointer(uintptr(inBuffer.mAudioData) + uintptr(i))) = buf[i]
}
// Do not update mAudioDataByteSize, or the buffer is not used correctly any more.
if osstatus := C.AudioQueueEnqueueBuffer(inAQ, inBuffer, 0, nil); osstatus != C.noErr {
if d.err != nil {
d.err = fmt.Errorf("oto: AudioQueueEnqueueBuffer at oto_render failed: %d", d.err)
}
}
}
func (d *driver) TryWrite(data []byte) (int, error) {
if d.err != nil {
return 0, d.err
}
n := d.bufSize - len(d.buf)
if n > len(data) {
n = len(data)
}
d.buf = append(d.buf, data[:n]...)
// Use the buffer only when the buffer length is enough to avoid choppy sound.
queueBufferSize := baseQueueBufferSize * d.audioInfo.channelNum * d.audioInfo.bitDepthInBytes
for len(d.buf) >= queueBufferSize {
d.chWrite <- d.buf
n := <-d.chWritten
d.buf = d.buf[n:]
}
return n, nil
}
func (d *driver) Close() error {
runtime.SetFinalizer(d, nil)
for _, b := range d.buffers {
if osstatus := C.AudioQueueFreeBuffer(d.audioQueue, b); osstatus != C.noErr {
return fmt.Errorf("oto: AudioQueueFreeBuffer failed: %d", osstatus)
}
}
if osstatus := C.AudioQueueStop(d.audioQueue, C.false); osstatus != C.noErr {
return fmt.Errorf("oto: AudioQueueStop failed: %d", osstatus)
}
if osstatus := C.AudioQueueDispose(d.audioQueue, C.false); osstatus != C.noErr {
return fmt.Errorf("oto: AudioQueueDispose failed: %d", osstatus)
}
d.audioQueue = nil
setDriver(nil)
return nil
}