forked from ebitengine/oto
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdriver_darwin.go
223 lines (184 loc) · 5.47 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
// 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
// #cgo LDFLAGS: -framework AudioToolbox
//
// #import <AudioToolbox/AudioToolbox.h>
//
// void oto_render(void* inUserData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffer);
//
// void oto_setNotificationHandler();
import "C"
import (
"fmt"
"sync"
"time"
"unsafe"
)
const (
float32SizeInBytes = 4
)
func newAudioQueue(sampleRate, channelNum, bitDepthInBytes int) (C.AudioQueueRef, []C.AudioQueueBufferRef, error) {
desc := C.AudioStreamBasicDescription{
mSampleRate: C.double(sampleRate),
mFormatID: C.kAudioFormatLinearPCM,
mFormatFlags: C.kAudioFormatFlagIsFloat,
mBytesPerPacket: C.UInt32(channelNum * float32SizeInBytes),
mFramesPerPacket: 1,
mBytesPerFrame: C.UInt32(channelNum * float32SizeInBytes),
mChannelsPerFrame: C.UInt32(channelNum),
mBitsPerChannel: C.UInt32(8 * float32SizeInBytes),
}
var audioQueue C.AudioQueueRef
if osstatus := C.AudioQueueNewOutput(
&desc,
(C.AudioQueueOutputCallback)(C.oto_render),
nil,
(C.CFRunLoopRef)(0),
(C.CFStringRef)(0),
0,
&audioQueue); osstatus != C.noErr {
return nil, nil, fmt.Errorf("oto: AudioQueueNewFormat with StreamFormat failed: %d", osstatus)
}
bufs := make([]C.AudioQueueBufferRef, 0, 4)
for len(bufs) < cap(bufs) {
var buf C.AudioQueueBufferRef
if osstatus := C.AudioQueueAllocateBuffer(audioQueue, bufferSizeInBytes, &buf); osstatus != C.noErr {
return nil, nil, fmt.Errorf("oto: AudioQueueAllocateBuffer failed: %d", osstatus)
}
buf.mAudioDataByteSize = bufferSizeInBytes
bufs = append(bufs, buf)
}
return audioQueue, bufs, nil
}
type context struct {
sampleRate int
channelNum int
bitDepthInBytes int
audioQueue C.AudioQueueRef
unqueuedBuffers []C.AudioQueueBufferRef
cond *sync.Cond
players *players
err atomicError
}
// TOOD: 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, channelNum, bitDepthInBytes int) (*context, chan struct{}, error) {
ready := make(chan struct{})
close(ready)
c := &context{
sampleRate: sampleRate,
channelNum: channelNum,
bitDepthInBytes: bitDepthInBytes,
cond: sync.NewCond(&sync.Mutex{}),
players: newPlayers(),
}
theContext = c
q, bs, err := newAudioQueue(sampleRate, channelNum, bitDepthInBytes)
if err != nil {
return nil, nil, err
}
c.audioQueue = q
c.unqueuedBuffers = bs
C.oto_setNotificationHandler()
if osstatus := C.AudioQueueStart(c.audioQueue, nil); osstatus != C.noErr {
return nil, nil, fmt.Errorf("oto: AudioQueueStart failed: %d", osstatus)
}
go 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.cond.Wait()
}
return c.err.Load() == nil
}
func (c *context) loop() {
buf32 := make([]float32, bufferSizeInBytes/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
}
buf := c.unqueuedBuffers[0]
copy(c.unqueuedBuffers, c.unqueuedBuffers[1:])
c.unqueuedBuffers = c.unqueuedBuffers[:len(c.unqueuedBuffers)-1]
c.players.read(buf32)
for i, f := range buf32 {
*(*float32)(unsafe.Pointer(uintptr(buf.mAudioData) + uintptr(i)*float32SizeInBytes)) = f
}
if osstatus := C.AudioQueueEnqueueBuffer(c.audioQueue, buf, 0, nil); osstatus != C.noErr {
c.err.TryStore(fmt.Errorf("oto: AudioQueueEnqueueBuffer failed: %d", osstatus))
}
}
func (c *context) Suspend() error {
c.cond.L.Lock()
defer c.cond.L.Unlock()
if err := c.err.Load(); err != nil {
return err.(error)
}
if osstatus := C.AudioQueuePause(c.audioQueue); osstatus != C.noErr {
return fmt.Errorf("oto: AudioQueuePause failed: %d", osstatus)
}
return nil
}
func (c *context) Resume() error {
c.cond.L.Lock()
defer c.cond.L.Unlock()
if err := c.err.Load(); err != nil {
return err.(error)
}
try:
if osstatus := C.AudioQueueStart(c.audioQueue, nil); osstatus != C.noErr {
const AVAudioSessionErrorCodeSiriIsRecording = 0x73697269 // 'siri'
if osstatus == AVAudioSessionErrorCodeSiriIsRecording {
time.Sleep(10 * time.Millisecond)
goto try
}
return fmt.Errorf("oto: AudioQueueStart failed: %d", osstatus)
}
return nil
}
func (c *context) Err() error {
if err := c.err.Load(); err != nil {
return err.(error)
}
return nil
}
//export oto_render
func oto_render(inUserData unsafe.Pointer, inAQ C.AudioQueueRef, inBuffer C.AudioQueueBufferRef) {
theContext.cond.L.Lock()
defer theContext.cond.L.Unlock()
theContext.unqueuedBuffers = append(theContext.unqueuedBuffers, inBuffer)
theContext.cond.Signal()
}
//export oto_setGlobalPause
func oto_setGlobalPause() {
theContext.Suspend()
}
//export oto_setGlobalResume
func oto_setGlobalResume() {
theContext.Resume()
}