-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrtaudio.go
562 lines (490 loc) · 14.8 KB
/
rtaudio.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
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
package rtaudio
/*
#cgo CXXFLAGS: -g
#cgo LDFLAGS: -lstdc++ -g
#cgo linux CXXFLAGS: -D__LINUX_ALSA__
#cgo linux LDFLAGS: -lm -lasound -pthread
#cgo linux,pulseaudio CXXFLAGS: -D__LINUX_PULSE__
#cgo linux,pulseaudio LDFLAGS: -lpulse -lpulse-simple
#cgo jack CXXFLAGS: -D__UNIX_JACK__
#cgo jack LDFLAGS: -ljack
#cgo windows pkg-config: rtaudio
#cgo windows CXXFLAGS: -D__WINDOWS_WASAPI__ -D__WINDOWS_ASIO__
#cgo darwin CXXFLAGS: -D__MACOSX_CORE__
#cgo darwin LDFLAGS: -framework CoreAudio -framework CoreFoundation
#include <stdlib.h>
#include <stdint.h>
#include "rtaudio_stub.h"
extern int goCallback(void *out, void *in, unsigned int nFrames,
double stream_time, rtaudio_stream_status_t status, void *userdata);
static inline void cgoRtAudioOpenStream(rtaudio_t audio,
rtaudio_stream_parameters_t *output_params,
rtaudio_stream_parameters_t *input_params,
rtaudio_format_t format,
unsigned int sample_rate,
unsigned int *buffer_frames,
int cb_id,
rtaudio_stream_options_t *options) {
rtaudio_open_stream(audio, output_params, input_params,
format, sample_rate, buffer_frames,
goCallback, (void *)(uintptr_t)cb_id, options, NULL);
}*/
import "C"
import (
"errors"
"sync"
"time"
"unsafe"
)
// API is an enumeration of available compiled APIs. Supported API include
// Alsa/PulseAudio/OSS, Jack, CoreAudio, WASAPI/ASIO/DS and dummy API.
type API C.rtaudio_api_t
const (
// APIUnspecified looks for a working compiled API.
APIUnspecified API = C.RTAUDIO_API_UNSPECIFIED
// APILinuxALSA uses the Advanced Linux Sound Architecture API.
APILinuxALSA = C.RTAUDIO_API_LINUX_ALSA
// APILinuxPulse uses the Linux PulseAudio API.
APILinuxPulse = C.RTAUDIO_API_LINUX_PULSE
// APILinuxOSS uses the Linux Open Sound System API.
APILinuxOSS = C.RTAUDIO_API_LINUX_OSS
// APIUnixJack uses the Jack Low-Latency Audio Server API.
APIUnixJack = C.RTAUDIO_API_UNIX_JACK
// APIMacOSXCore uses Macintosh OS-X Core Audio API.
APIMacOSXCore = C.RTAUDIO_API_MACOSX_CORE
// APIWindowsWASAPI uses the Microsoft WASAPI API.
APIWindowsWASAPI = C.RTAUDIO_API_WINDOWS_WASAPI
// APIWindowsASIO uses the Steinberg Audio Stream I/O API.
APIWindowsASIO = C.RTAUDIO_API_WINDOWS_ASIO
// APIWindowsDS uses the Microsoft Direct Sound API.
APIWindowsDS = C.RTAUDIO_API_WINDOWS_DS
// APIDummy is a compilable but non-functional API.
APIDummy = C.RTAUDIO_API_DUMMY
)
func (api API) String() string {
switch api {
case APIUnspecified:
return "unspecified"
case APILinuxALSA:
return "alsa"
case APILinuxPulse:
return "pulse"
case APILinuxOSS:
return "oss"
case APIUnixJack:
return "jack"
case APIMacOSXCore:
return "coreaudio"
case APIWindowsWASAPI:
return "wasapi"
case APIWindowsASIO:
return "asio"
case APIWindowsDS:
return "directsound"
case APIDummy:
return "dummy"
}
return "?"
}
// StreamStatus defines over- or underflow flags in the audio callback.
type StreamStatus C.rtaudio_stream_status_t
const (
// StatusInputOverflow indicates that data was discarded because of an
// overflow condition at the driver.
StatusInputOverflow StreamStatus = C.RTAUDIO_STATUS_INPUT_OVERFLOW
// StatusOutputUnderflow indicates that the output buffer ran low, likely
// producing a break in the output sound.
StatusOutputUnderflow StreamStatus = C.RTAUDIO_STATUS_OUTPUT_UNDERFLOW
)
// Version returns current RtAudio library version string.
func Version() string {
return C.GoString(C.rtaudio_version())
}
// CompiledAPI determines the available compiled audio APIs.
func CompiledAPI() (apis []API) {
capis := (*[1 << 27]C.rtaudio_api_t)(unsafe.Pointer(C.rtaudio_compiled_api()))
for i := 0; ; i++ {
api := capis[i]
if api == C.RTAUDIO_API_UNSPECIFIED {
break
}
apis = append(apis, API(api))
}
return apis
}
// DeviceInfo is the public device information structure for returning queried values.
type DeviceInfo struct {
Name string
Probed bool
NumOutputChannels int
NumInputChannels int
NumDuplexChannels int
IsDefaultOutput bool
IsDefaultInput bool
//rtaudio_format_t native_formats;
PreferredSampleRate uint
SampleRates []int
}
// StreamParams is the structure for specifying input or output stream parameters.
type StreamParams struct {
DeviceID uint
NumChannels uint
FirstChannel uint
}
// StreamFlags is a set of RtAudio stream option flags.
type StreamFlags C.rtaudio_stream_flags_t
const (
// FlagsNoninterleaved is set to use non-interleaved buffers (default = interleaved).
FlagsNoninterleaved = C.RTAUDIO_FLAGS_NONINTERLEAVED
// FlagsMinimizeLatency when set attempts to configure stream parameters for lowest possible latency.
FlagsMinimizeLatency = C.RTAUDIO_FLAGS_MINIMIZE_LATENCY
// FlagsHogDevice when set attempts to grab device for exclusive use.
FlagsHogDevice = C.RTAUDIO_FLAGS_HOG_DEVICE
// FlagsScheduleRealtime is set in attempt to select realtime scheduling (round-robin) for the callback thread.
FlagsScheduleRealtime = C.RTAUDIO_FLAGS_SCHEDULE_REALTIME
// FlagsAlsaUseDefault is set to use the "default" PCM device (ALSA only).
FlagsAlsaUseDefault = C.RTAUDIO_FLAGS_ALSA_USE_DEFAULT
)
// StreamOptions is the structure for specifying stream options.
type StreamOptions struct {
Flags StreamFlags
NumBuffers uint
Priotity int
Name string
}
// RtAudio is a "controller" used to select an available audio i/o interface.
type RtAudio interface {
Destroy()
CurrentAPI() API
Devices() ([]DeviceInfo, error)
DefaultOutputDevice() int
DefaultInputDevice() int
Open(out, in *StreamParams, format Format, sampleRate uint, frames uint, cb Callback, opts *StreamOptions) error
Close()
Start() error
Stop() error
Abort() error
IsOpen() bool
IsRunning() bool
Latency() (int, error)
SampleRate() (uint, error)
Time() (time.Duration, error)
SetTime(time.Duration) error
ShowWarnings(bool)
}
type rtaudio struct {
audio C.rtaudio_t
cb Callback
inputChannels int
outputChannels int
format Format
}
var _ RtAudio = &rtaudio{}
// Create a new RtAudio instance using the given API.
func Create(api API) (RtAudio, error) {
audio := C.rtaudio_create(C.rtaudio_api_t(api))
if C.rtaudio_error(audio) != nil {
return nil, errors.New(C.GoString(C.rtaudio_error(audio)))
}
return &rtaudio{audio: audio}, nil
}
func (audio *rtaudio) Destroy() {
C.rtaudio_destroy(audio.audio)
}
func (audio *rtaudio) CurrentAPI() API {
return API(C.rtaudio_current_api(audio.audio))
}
func (audio *rtaudio) DefaultInputDevice() int {
return int(C.rtaudio_get_default_input_device(audio.audio))
}
func (audio *rtaudio) DefaultOutputDevice() int {
return int(C.rtaudio_get_default_output_device(audio.audio))
}
func (audio *rtaudio) Devices() ([]DeviceInfo, error) {
n := C.rtaudio_device_count(audio.audio)
devices := []DeviceInfo{}
for i := C.int(0); i < n; i++ {
cinfo := C.rtaudio_get_device_info(audio.audio, i)
if C.rtaudio_error(audio.audio) != nil {
return nil, errors.New(C.GoString(C.rtaudio_error(audio.audio)))
}
sr := []int{}
for _, r := range cinfo.sample_rates {
if r == 0 {
break
}
sr = append(sr, int(r))
}
devices = append(devices, DeviceInfo{
Name: C.GoString(&cinfo.name[0]),
Probed: cinfo.probed != 0,
NumInputChannels: int(cinfo.input_channels),
NumOutputChannels: int(cinfo.output_channels),
NumDuplexChannels: int(cinfo.duplex_channels),
IsDefaultOutput: cinfo.is_default_output != 0,
IsDefaultInput: cinfo.is_default_input != 0,
PreferredSampleRate: uint(cinfo.preferred_sample_rate),
SampleRates: sr,
})
// TODO: formats
}
return devices, nil
}
// Format defines RtAudio data format type.
type Format int
const (
// FormatInt8 uses 8-bit signed integer.
FormatInt8 Format = C.RTAUDIO_FORMAT_SINT8
// FormatInt16 uses 16-bit signed integer.
FormatInt16 = C.RTAUDIO_FORMAT_SINT16
// FormatInt24 uses 24-bit signed integer.
FormatInt24 = C.RTAUDIO_FORMAT_SINT24
// FormatInt32 uses 32-bit signed integer.
FormatInt32 = C.RTAUDIO_FORMAT_SINT32
// FormatFloat32 uses 32-bit floating point values normalized between (-1..1).
FormatFloat32 = C.RTAUDIO_FORMAT_FLOAT32
// FormatFloat64 uses 64-bit floating point values normalized between (-1..1).
FormatFloat64 = C.RTAUDIO_FORMAT_FLOAT64
)
// Buffer is a common interface for audio buffers of various data format types.
type Buffer interface {
Len() int
Int8() []int8
Int16() []int16
Int24() []Int24
Int32() []int32
Float32() []float32
Float64() []float64
}
// Int24 is a helper type to convert int32 values to int24 and back.
type Int24 [3]byte
// Set Int24 value using the least significant bytes of the given number n.
func (i *Int24) Set(n int32) {
(*i)[0], (*i)[1], (*i)[2] = byte(n&0xff), byte((n&0xff00)>>8), byte((n&0xff0000)>>16)
}
// Get Int24 value as int32.
func (i Int24) Get() int32 {
n := int32(i[0]) | int32(i[1])<<8 | int32(i[2])<<16
if n&0x800000 != 0 {
n |= ^0xffffff
}
return n
}
type buffer struct {
format Format
length int
numChannels int
ptr unsafe.Pointer
}
func (b *buffer) Len() int {
if b.ptr == nil {
return 0
}
return b.length
}
func (b *buffer) Int8() []int8 {
if b.format != FormatInt8 {
return nil
}
if b.ptr == nil {
return nil
}
return (*[1 << 30]int8)(b.ptr)[: b.length*b.numChannels : b.length*b.numChannels]
}
func (b *buffer) Int16() []int16 {
if b.format != FormatInt16 {
return nil
}
if b.ptr == nil {
return nil
}
return (*[1 << 29]int16)(b.ptr)[: b.length*b.numChannels : b.length*b.numChannels]
}
func (b *buffer) Int24() []Int24 {
if b.format != FormatInt24 {
return nil
}
if b.ptr == nil {
return nil
}
return (*[1 << 28]Int24)(b.ptr)[: b.length*b.numChannels : b.length*b.numChannels]
}
func (b *buffer) Int32() []int32 {
if b.format != FormatInt32 {
return nil
}
if b.ptr == nil {
return nil
}
return (*[1 << 27]int32)(b.ptr)[: b.length*b.numChannels : b.length*b.numChannels]
}
func (b *buffer) Float32() []float32 {
if b.format != FormatFloat32 {
return nil
}
if b.ptr == nil {
return nil
}
return (*[1 << 27]float32)(b.ptr)[: b.length*b.numChannels : b.length*b.numChannels]
}
func (b *buffer) Float64() []float64 {
if b.format != FormatFloat64 {
return nil
}
if b.ptr == nil {
return nil
}
return (*[1 << 23]float64)(b.ptr)[: b.length*b.numChannels : b.length*b.numChannels]
}
// Callback is a client-defined function that will be invoked when input data
// is available and/or output data is needed.
type Callback func(out Buffer, in Buffer, dur time.Duration, status StreamStatus) int
var (
mu sync.Mutex
audios = map[int]*rtaudio{}
)
func registerAudio(a *rtaudio) int {
mu.Lock()
defer mu.Unlock()
for i := 0; ; i++ {
if _, ok := audios[i]; !ok {
audios[i] = a
return i
}
}
}
func unregisterAudio(a *rtaudio) {
mu.Lock()
defer mu.Unlock()
for i := 0; i < len(audios); i++ {
if audios[i] == a {
delete(audios, i)
return
}
}
}
func findAudio(k int) *rtaudio {
mu.Lock()
defer mu.Unlock()
return audios[k]
}
//export goCallback
func goCallback(out, in unsafe.Pointer, frames C.uint, sec C.double,
status C.rtaudio_stream_status_t, userdata unsafe.Pointer) C.int {
k := int(uintptr(userdata))
audio := findAudio(k)
dur := time.Duration(time.Microsecond * time.Duration(sec*1000000.0))
inbuf := &buffer{audio.format, int(frames), audio.inputChannels, in}
outbuf := &buffer{audio.format, int(frames), audio.outputChannels, out}
return C.int(audio.cb(outbuf, inbuf, dur, StreamStatus(status)))
}
func (audio *rtaudio) Open(out, in *StreamParams, format Format, sampleRate uint,
frames uint, cb Callback, opts *StreamOptions) error {
var (
cInPtr *C.rtaudio_stream_parameters_t
cOutPtr *C.rtaudio_stream_parameters_t
cOptsPtr *C.rtaudio_stream_options_t
cIn C.rtaudio_stream_parameters_t
cOut C.rtaudio_stream_parameters_t
cOpts C.rtaudio_stream_options_t
)
audio.inputChannels = 0
audio.outputChannels = 0
if out != nil {
audio.outputChannels = int(out.NumChannels)
cOut.device_id = C.uint(out.DeviceID)
cOut.num_channels = C.uint(out.NumChannels)
cOut.first_channel = C.uint(out.FirstChannel)
cOutPtr = &cOut
}
if in != nil {
audio.inputChannels = int(in.NumChannels)
cIn.device_id = C.uint(in.DeviceID)
cIn.num_channels = C.uint(in.NumChannels)
cIn.first_channel = C.uint(in.FirstChannel)
cInPtr = &cIn
}
if opts != nil {
cOpts.flags = C.rtaudio_stream_flags_t(opts.Flags)
cOpts.num_buffers = C.uint(opts.NumBuffers)
cOpts.priority = C.int(opts.Priotity)
cOptsPtr = &cOpts
}
framesCount := C.uint(frames)
audio.format = format
audio.cb = cb
k := registerAudio(audio)
C.cgoRtAudioOpenStream(audio.audio, cOutPtr, cInPtr,
C.rtaudio_format_t(format), C.uint(sampleRate), &framesCount, C.int(k), cOptsPtr)
if C.rtaudio_error(audio.audio) != nil {
return errors.New(C.GoString(C.rtaudio_error(audio.audio)))
}
return nil
}
func (audio *rtaudio) Close() {
unregisterAudio(audio)
C.rtaudio_close_stream(audio.audio)
}
func (audio *rtaudio) Start() error {
C.rtaudio_start_stream(audio.audio)
if C.rtaudio_error(audio.audio) != nil {
return errors.New(C.GoString(C.rtaudio_error(audio.audio)))
}
return nil
}
func (audio *rtaudio) Stop() error {
C.rtaudio_stop_stream(audio.audio)
if C.rtaudio_error(audio.audio) != nil {
return errors.New(C.GoString(C.rtaudio_error(audio.audio)))
}
return nil
}
func (audio *rtaudio) Abort() error {
C.rtaudio_abort_stream(audio.audio)
if C.rtaudio_error(audio.audio) != nil {
return errors.New(C.GoString(C.rtaudio_error(audio.audio)))
}
return nil
}
func (audio *rtaudio) IsOpen() bool {
return C.rtaudio_is_stream_open(audio.audio) != 0
}
func (audio *rtaudio) IsRunning() bool {
return C.rtaudio_is_stream_running(audio.audio) != 0
}
func (audio *rtaudio) Latency() (int, error) {
latency := C.rtaudio_get_stream_latency(audio.audio)
if C.rtaudio_error(audio.audio) != nil {
return 0, errors.New(C.GoString(C.rtaudio_error(audio.audio)))
}
return int(latency), nil
}
func (audio *rtaudio) SampleRate() (uint, error) {
sampleRate := C.rtaudio_get_stream_sample_rate(audio.audio)
if C.rtaudio_error(audio.audio) != nil {
return 0, errors.New(C.GoString(C.rtaudio_error(audio.audio)))
}
return uint(sampleRate), nil
}
func (audio *rtaudio) Time() (time.Duration, error) {
sec := C.rtaudio_get_stream_time(audio.audio)
if C.rtaudio_error(audio.audio) != nil {
return 0, errors.New(C.GoString(C.rtaudio_error(audio.audio)))
}
return time.Duration(time.Microsecond * time.Duration(sec*1000000.0)), nil
}
func (audio *rtaudio) SetTime(t time.Duration) error {
sec := float64(t) * 1000000.0 / float64(time.Microsecond)
C.rtaudio_set_stream_time(audio.audio, C.double(sec))
if C.rtaudio_error(audio.audio) != nil {
return errors.New(C.GoString(C.rtaudio_error(audio.audio)))
}
return nil
}
func (audio *rtaudio) ShowWarnings(show bool) {
if show {
C.rtaudio_show_warnings(audio.audio, 1)
} else {
C.rtaudio_show_warnings(audio.audio, 0)
}
}