This repository has been archived by the owner on Jul 22, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdevice_directsound.go
305 lines (266 loc) · 6.59 KB
/
device_directsound.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
// +build windows,directsound
package gosound
import (
"context"
"errors"
"io"
"github.com/gotracker/gomixing/mixing"
directsound "github.com/heucuva/go-directsound"
win32 "github.com/heucuva/go-win32"
winmm "github.com/heucuva/go-winmm"
"golang.org/x/sys/windows"
)
const dsoundName = "directsound"
type dsoundDevice struct {
device
ds *directsound.DirectSound
lpdsbPrimary *directsound.Buffer
wfx *winmm.WAVEFORMATEX
mix mixing.Mixer
}
func (d *dsoundDevice) GetKind() Kind {
return KindSoundCard
}
func newDSoundDevice(settings Settings) (Device, error) {
d := dsoundDevice{
device: device{
onRowOutput: settings.OnRowOutput,
},
mix: mixing.Mixer{
Channels: settings.Channels,
BitsPerSample: settings.BitsPerSample,
},
}
preferredDeviceName := ""
ds, err := directsound.NewDSound(preferredDeviceName)
if err != nil {
return nil, err
}
d.ds = ds
if d.ds == nil {
return nil, errors.New("could not create directsound device")
}
lpdsbPrimary, wfx, err := ds.CreateSoundBufferPrimary(settings.Channels, settings.SamplesPerSecond, settings.BitsPerSample)
if err != nil {
ds.Close()
return nil, err
}
d.lpdsbPrimary = lpdsbPrimary
d.wfx = wfx
return &d, nil
}
// Name returns the device name
func (d *dsoundDevice) Name() string {
return dsoundName
}
// Play starts the wave output device playing
func (d *dsoundDevice) Play(in <-chan *PremixData) error {
return d.PlayWithCtx(context.Background(), in)
}
type playbackData struct {
event windows.Handle
row *PremixData
pos int
}
type playbackBuffer struct {
buffer *directsound.Buffer
notify *directsound.Notify
rows []playbackData
maxSamples int
writePos int
}
func (p *playbackBuffer) Add(mix *mixing.Mixer, row *PremixData, pos int, size int, blockAlign int, panmixer mixing.PanMixer) (int, error) {
remaining := p.maxSamples - p.writePos
samples := row.SamplesLen - pos
if samples >= remaining {
samples = remaining
}
bufPos := p.writePos * blockAlign
segments, err := p.buffer.Lock(bufPos, samples*blockAlign)
if err != nil {
return 0, err
}
writeSegs := [][]byte{}
if pos > 0 {
front := make([]byte, pos*blockAlign)
writeSegs = append(writeSegs, front)
}
writeSegs = append(writeSegs, segments...)
if samples < row.SamplesLen {
rem := row.SamplesLen - samples
rear := make([]byte, rem*blockAlign)
writeSegs = append(writeSegs, rear)
}
mix.FlattenTo(writeSegs, panmixer, row.SamplesLen, row.Data, row.MixerVolume)
if err := p.buffer.Unlock(segments); err != nil {
return 0, err
}
p.writePos += samples
remaining -= samples
if remaining <= 0 {
err = io.EOF
}
return samples, err
}
// PlayWithCtx starts the wave output device playing
func (d *dsoundDevice) PlayWithCtx(ctx context.Context, in <-chan *PremixData) error {
maxOutstanding := 3
maxOutstandingEvents := 1000
panmixer := mixing.GetPanMixer(d.mix.Channels)
if panmixer == nil {
return errors.New("invalid pan mixer - check channel count")
}
done := make(chan struct{}, 1)
defer close(done)
myCtx, cancel := context.WithCancel(ctx)
defer cancel()
events := []windows.Handle{}
availableEvents := make(chan windows.Handle, maxOutstandingEvents)
defer func() {
for _, event := range events {
win32.CloseHandle(event)
}
}()
playbackBuffers := make([]playbackBuffer, maxOutstanding)
playbackBufferSize := int(float64(d.wfx.NSamplesPerSec) * 0.5)
availableBuffers := make(chan *playbackBuffer, len(playbackBuffers))
defer close(availableBuffers)
for i := range playbackBuffers {
lpdsb, err := d.ds.CreateSoundBufferSecondary(d.wfx, playbackBufferSize*int(d.wfx.NBlockAlign))
if err != nil {
return err
}
playbackBuffers[i] = playbackBuffer{
buffer: lpdsb,
maxSamples: playbackBufferSize,
}
availableBuffers <- &playbackBuffers[i]
}
defer func() {
for _, pb := range playbackBuffers {
pb.buffer.Release()
}
}()
getAvailableEvent := func() (windows.Handle, error) {
select {
case event := <-availableEvents:
return event, nil
default:
event, err := win32.CreateEvent(nil, false, false, "")
if err != nil {
return event, err
}
events = append(events, event)
return event, nil
}
}
currentBuffer := <-availableBuffers
out := make(chan *playbackBuffer, maxOutstanding)
go func() {
defer close(out)
defer cancel()
for {
select {
case <-myCtx.Done():
return
case row, ok := <-in:
if !ok {
return
}
size := row.SamplesLen
pos := 0
blockAlign := int(d.wfx.NBlockAlign)
if size > 0 {
event, err := getAvailableEvent()
if err != nil {
panic(err)
}
currentBuffer.rows = append(currentBuffer.rows, playbackData{
event: event,
row: row,
pos: currentBuffer.writePos * blockAlign,
})
}
for size > 0 {
n, err := currentBuffer.Add(&d.mix, row, pos, row.SamplesLen, blockAlign, panmixer)
size -= n
pos += n
if err != nil {
if !errors.Is(err, io.EOF) {
panic(err)
}
currentBuffer.writePos = 0
out <- currentBuffer
currentBuffer = <-availableBuffers
}
}
}
}
}()
for buffer := range out {
endEvent, err := getAvailableEvent()
if err != nil {
return err
}
if err := d.playWaveBuffer(buffer, endEvent); err != nil {
return err
}
for _, n := range buffer.rows {
availableEvents <- n.event
}
availableEvents <- endEvent
buffer.rows = []playbackData{}
availableBuffers <- buffer
}
done <- struct{}{}
return nil
}
func (d *dsoundDevice) playWaveBuffer(p *playbackBuffer, endEvent windows.Handle) error {
notify, err := p.buffer.GetNotify()
if err != nil {
return err
}
defer notify.Release()
pn := []directsound.PositionNotify{}
for _, n := range p.rows {
pn = append(pn, directsound.PositionNotify{
Offset: uint32(n.pos),
EventNotify: n.event,
})
}
pn = append(pn, directsound.PositionNotify{
Offset: directsound.DSBPN_OFFSETSTOP,
EventNotify: endEvent,
})
if err := notify.SetNotificationPositions(pn); err != nil {
return err
}
// play (non-looping)
if err := p.buffer.Play(false); err != nil {
return err
}
for _, n := range p.rows {
if d.onRowOutput != nil {
d.onRowOutput(KindSoundCard, n.row)
}
if err := win32.WaitForSingleObjectInfinite(n.event); err != nil {
return err
}
}
return win32.WaitForSingleObjectInfinite(endEvent)
}
// Close closes the wave output device
func (d *dsoundDevice) Close() {
if d.lpdsbPrimary != nil {
d.lpdsbPrimary.Release()
}
if d.ds != nil {
d.ds.Close()
}
}
func init() {
Map[dsoundName] = deviceDetails{
create: newDSoundDevice,
Kind: KindSoundCard,
}
}