forked from pion/mediadevices
-
Notifications
You must be signed in to change notification settings - Fork 0
/
speaker.go
311 lines (261 loc) · 6.67 KB
/
speaker.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
package speaker
import (
"encoding/binary"
"errors"
"fmt"
"io"
"log"
"strings"
"sync"
"time"
"unsafe"
"github.com/gen2brain/malgo"
"github.com/pion/mediadevices/pkg/driver"
"github.com/pion/mediadevices/pkg/io/audio"
"github.com/pion/mediadevices/pkg/prop"
"github.com/pion/mediadevices/pkg/wave"
)
const (
maxDeviceIDLength = 20
// TODO: should replace this with a more flexible approach
sampleRateStep = 1000
initialBufferSize = 1024
)
var ctx *malgo.AllocatedContext
var hostEndian binary.ByteOrder
var (
errUnsupportedFormat = errors.New("the provided audio format is not supported")
)
type speaker struct {
malgo.DeviceInfo
chunkChan chan []byte
deviceCloseFunc func()
device *malgo.Device
inputProp prop.Media
muted bool
}
func init() {
// NOTICE: this driver support windows only!
backends := []malgo.Backend{
malgo.BackendWasapi,
}
var err error
ctx, err = malgo.InitContext(backends, malgo.ContextConfig{}, func(message string) {
log.Printf("Playback device message: %s\n", message)
})
if err != nil {
panic(err)
}
devices, err := ctx.Devices(malgo.Playback)
if err != nil {
panic(err)
}
for _, device := range devices {
info, err := ctx.DeviceInfo(malgo.Capture, device.ID, malgo.Shared)
if err == nil {
priority := driver.PriorityNormal
name := device.Name()
name = strings.Trim(name, "\x00")
driver.GetManager().Register(newSpeaker(info), driver.Info{
Label: device.ID.String(),
DeviceType: driver.Speaker,
Priority: priority,
Name: name,
Manufacturer: "",
ModelID: "",
})
}
}
// Decide which endian
switch v := *(*uint16)(unsafe.Pointer(&([]byte{0x12, 0x34}[0]))); v {
case 0x1234:
hostEndian = binary.BigEndian
case 0x3412:
hostEndian = binary.LittleEndian
default:
panic(fmt.Sprintf("failed to determine host endianness: %x", v))
}
}
func newSpeaker(info malgo.DeviceInfo) *speaker {
return &speaker{
DeviceInfo: info,
}
}
func (m *speaker) Open() error {
m.chunkChan = make(chan []byte, 1)
return nil
}
func (m *speaker) Close() error {
if m.deviceCloseFunc != nil {
m.deviceCloseFunc()
}
return nil
}
func (m *speaker) Mute() bool {
if m.device == nil {
return false
}
m.muted = true
err := m.device.Stop()
if err != nil {
log.Println("Mute device failed:", err)
m.muted = false
return false
}
return true
}
func (m *speaker) Unmute() bool {
if m.device == nil {
return false
}
m.muted = false
err := m.device.Start()
if err != nil {
log.Println("Unmute device failed:", err)
return false
}
return true
}
// restart
func (m *speaker) Restart() {
log.Println("Restarting...")
// close current device
m.closePlaybackDevice()
device, err := m.defaultPlaybackDevice(m.inputProp)
if err != nil {
log.Println("Init default playback device failed with error:", err)
return
}
m.device = device
log.Println("Restarted")
}
func (m *speaker) closePlaybackDevice() {
if m.device != nil {
// destory playback device
m.device.Uninit()
m.device = nil
}
}
func (m *speaker) defaultPlaybackDevice(inputProp prop.Media) (*malgo.Device, error) {
config := malgo.DefaultDeviceConfig(malgo.Loopback)
var callbacks malgo.DeviceCallbacks
config.PerformanceProfile = malgo.LowLatency
config.Capture.Channels = uint32(inputProp.ChannelCount)
config.SampleRate = uint32(inputProp.SampleRate)
config.PeriodSizeInMilliseconds = uint32(inputProp.Latency.Milliseconds())
if inputProp.SampleSize == 4 && inputProp.IsFloat {
config.Capture.Format = malgo.FormatF32
} else if inputProp.SampleSize == 2 && !inputProp.IsFloat {
config.Capture.Format = malgo.FormatS16
} else {
return nil, errUnsupportedFormat
}
onRecvChunk := func(_, chunk []byte, framecount uint32) {
m.chunkChan <- chunk
}
callbacks.Data = onRecvChunk
onDeviceStop := func() {
go func() {
if !m.muted {
m.Restart()
}
}()
}
callbacks.Stop = onDeviceStop
device, err := malgo.InitDevice(ctx.Context, config, callbacks)
if err != nil {
return nil, err
}
err = device.Start()
if err != nil {
return nil, err
}
device.SetAllowPlaybackAutoStreamRouting(true)
r := device.ChangeVolume(1.0)
log.Println("ChangeVolume result:", r)
return device, nil
}
func (m *speaker) AudioRecord(inputProp prop.Media) (audio.Reader, error) {
m.inputProp = inputProp
decoder, err := wave.NewDecoder(&wave.RawFormat{
SampleSize: inputProp.SampleSize,
IsFloat: inputProp.IsFloat,
Interleaved: inputProp.IsInterleaved,
})
if err != nil {
return nil, err
}
device, err := m.defaultPlaybackDevice(inputProp)
if err != nil {
log.Println("Init default playback device failed with error:", err)
return nil, err
}
m.device = device
var closeDeviceOnce sync.Once
m.deviceCloseFunc = func() {
closeDeviceOnce.Do(func() {
m.closePlaybackDevice()
if m.chunkChan != nil {
close(m.chunkChan)
m.chunkChan = nil
}
})
}
var reader audio.Reader = audio.ReaderFunc(func() (wave.Audio, func(), error) {
chunk, ok := <-m.chunkChan
if !ok {
m.deviceCloseFunc()
return nil, func() {}, io.EOF
}
decodedChunk, err := decoder.Decode(hostEndian, chunk, inputProp.ChannelCount)
// FIXME: the decoder should also fill this information
switch decodedChunk := decodedChunk.(type) {
case *wave.Float32Interleaved:
decodedChunk.Size.SamplingRate = inputProp.SampleRate
case *wave.Int16Interleaved:
decodedChunk.Size.SamplingRate = inputProp.SampleRate
default:
panic("unsupported format")
}
return decodedChunk, func() {}, err
})
return reader, nil
}
func (m *speaker) Properties() []prop.Media {
var supportedProps []prop.Media
var isBigEndian bool
// miniaudio only uses the host endian
if hostEndian == binary.BigEndian {
isBigEndian = true
}
for ch := m.MinChannels; ch <= m.MaxChannels; ch++ {
// FIXME: Currently support 48kHz only. We need to implement a resampler first.
// for sampleRate := m.MinSampleRate; sampleRate <= m.MaxSampleRate; sampleRate += sampleRateStep {
sampleRate := 48000
for i := 0; i < int(m.FormatCount); i++ {
format := m.Formats[i]
supportedProp := prop.Media{
Audio: prop.Audio{
ChannelCount: int(ch),
SampleRate: int(sampleRate),
IsBigEndian: isBigEndian,
// miniaudio only supports interleaved at the moment
IsInterleaved: true,
// FIXME: should change this to a less discrete value
Latency: time.Millisecond * 20,
},
}
switch malgo.FormatType(format) {
case malgo.FormatF32:
supportedProp.SampleSize = 4
supportedProp.IsFloat = true
case malgo.FormatS16:
supportedProp.SampleSize = 2
supportedProp.IsFloat = false
}
supportedProps = append(supportedProps, supportedProp)
}
// }
}
return supportedProps
}