forked from talkkonnect/talkkonnect
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstream.go
322 lines (283 loc) · 9.1 KB
/
stream.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
/*
* talkkonnect headless mumble client/gateway with lcd screen and channel control
* Copyright (C) 2018-2019, Suvir Kumar <[email protected]>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* talkkonnect is the based on talkiepi and barnard by Daniel Chote and Tim Cooper
*
* The Initial Developer of the Original Code is
* Suvir Kumar <[email protected]>
* Portions created by the Initial Developer are Copyright (C) Suvir Kumar. All Rights Reserved.
*
* Contributor(s):
*
* Suvir Kumar <[email protected]>
*
* My Blog is at www.talkkonnect.com
* The source code is hosted at github.com/talkkonnect
*
* stream.go part of mumble openal client modified to work with talkkonnect
*/
package talkkonnect
import (
"encoding/binary"
"errors"
"fmt"
"log"
"strconv"
"time"
"github.com/talkkonnect/go-openal/openal"
"github.com/talkkonnect/gumble/gumble"
"github.com/talkkonnect/gumble/gumbleffmpeg"
)
var (
errState = errors.New("gumbleopenal: invalid state")
lcdtext = [4]string{"nil", "nil", "nil", ""}
now = time.Now()
TotalStreams int
NeedToKill int
)
// MumbleDuplex - listenera and outgoing
type MumbleDuplex struct{}
type Stream struct {
client *gumble.Client
link gumble.Detacher
deviceSource *openal.CaptureDevice
sourceFrameSize int
sourceStop chan bool
deviceSink *openal.Device
contextSink *openal.Context
}
func (b *Talkkonnect) New(client *gumble.Client) (*Stream, error) {
s := &Stream{
client: client,
sourceFrameSize: client.Config.AudioFrameSize(),
}
s.deviceSource = openal.CaptureOpenDevice("", gumble.AudioSampleRate, openal.FormatMono16, uint32(s.sourceFrameSize))
s.deviceSink = openal.OpenDevice("")
s.contextSink = s.deviceSink.CreateContext()
s.contextSink.Activate()
s.link = client.Config.AttachAudio(s)
return s, nil
}
func (b *Talkkonnect) Destroy() {
b.Stream.link.Detach()
if b.Stream.deviceSource != nil {
b.Stream.deviceSource.CaptureStop()
b.Stream.deviceSource.CaptureCloseDevice()
b.Stream.deviceSource = nil
}
if b.Stream.deviceSink != nil {
b.Stream.contextSink.Destroy()
b.Stream.deviceSink.CloseDevice()
b.Stream.contextSink = nil
b.Stream.deviceSink = nil
}
}
func (b *Talkkonnect) StartSource() error {
var eventSound EventSoundStruct = findEventSound("incommingbeep")
if eventSound.Enabled {
if v, err := strconv.ParseFloat(eventSound.Volume, 32); err == nil {
time.Sleep(300 * time.Millisecond)
log.Println("alert: Playing Incomming into Stream")
b.splayIntoStream(eventSound.FileName, float32(v))
}
}
b.Stream.deviceSource.CaptureStart()
b.Stream.sourceStop = make(chan bool)
go b.sourceRoutine()
return nil
}
func (b *Talkkonnect) StopSource() error {
if b.Stream.sourceStop == nil {
return errState
}
close(b.Stream.sourceStop)
b.Stream.sourceStop = nil
b.Stream.deviceSource.CaptureStop()
b.Stream.deviceSource.CaptureCloseDevice()
var eventSound EventSoundStruct = findEventSound("rogerbeep")
if eventSound.Enabled {
GPIOOutPin("transmit", "on")
MyLedStripTransmitLEDOn()
log.Println("debug: Rogerbeep Playing")
if v, err := strconv.ParseFloat(eventSound.Volume, 32); err == nil {
b.splayIntoStream(eventSound.FileName, float32(v))
}
GPIOOutPin("transmit", "off")
MyLedStripTransmitLEDOff()
}
b.Stream.deviceSource = openal.CaptureOpenDevice("", gumble.AudioSampleRate, openal.FormatMono16, uint32(b.Stream.sourceFrameSize))
return nil
}
func (s *Stream) OnAudioStream(e *gumble.AudioStreamEvent) {
TotalStreams++
if _, userexists := StreamTracker[e.User.UserID]; userexists {
log.Printf("info: Stale GoRoutine Detected For UserID=%v UserName=%v Session=%v AudioStreamChannel=%v", e.User.UserID, e.User.Name, e.User.Session, e.C)
NeedToKill++
}
StreamTracker[e.User.UserID] = streamTrackerStruct{UserID: e.User.UserID, UserName: e.User.Name, UserSession: e.User.Session, C: e.C}
goStreamStats()
go func() {
source := openal.NewSource()
emptyBufs := openal.NewBuffers(24)
reclaim := func() {
if n := source.BuffersProcessed(); n > 0 {
reclaimedBufs := make(openal.Buffers, n)
source.UnqueueBuffers(reclaimedBufs)
emptyBufs = append(emptyBufs, reclaimedBufs...)
}
}
var raw [gumble.AudioMaximumFrameSize * 2]byte
for packet := range e.C {
TalkedTicker.Reset(Config.Global.Hardware.VoiceActivityTimermsecs * time.Millisecond)
if Config.Global.Software.IgnoreUser.IgnoreUserEnabled {
if len(Config.Global.Software.IgnoreUser.IgnoreUserRegex) > 0 {
if checkRegex(Config.Global.Software.IgnoreUser.IgnoreUserRegex, e.User.Name) {
continue
}
}
}
if Config.Global.Software.Settings.CancellableStream && NowStreaming {
IsPlayStream = !IsPlayStream
NowStreaming = IsPlayStream
pstream.Stop()
IsPlayStream = !IsPlayStream
NowStreaming = IsPlayStream
}
Talking <- talkingStruct{true, e.User.Name}
samples := len(packet.AudioBuffer)
if samples > cap(raw) {
continue
}
for i, value := range packet.AudioBuffer {
binary.LittleEndian.PutUint16(raw[i*2:], uint16(value))
}
reclaim()
if len(emptyBufs) == 0 {
continue
}
last := len(emptyBufs) - 1
buffer := emptyBufs[last]
emptyBufs = emptyBufs[:last]
buffer.SetData(openal.FormatMono16, raw[:samples*2], gumble.AudioSampleRate)
source.QueueBuffer(buffer)
if source.State() != openal.Playing {
source.Play()
}
Talking <- talkingStruct{false, e.User.Name}
}
reclaim()
emptyBufs.Delete()
source.Delete()
}()
}
func (b *Talkkonnect) sourceRoutine() {
interval := b.Stream.client.Config.AudioInterval
frameSize := b.Stream.client.Config.AudioFrameSize()
if frameSize != b.Stream.sourceFrameSize {
log.Println("error: FrameSize Error!")
b.Stream.deviceSource.CaptureCloseDevice()
b.Stream.sourceFrameSize = frameSize
b.Stream.deviceSource = openal.CaptureOpenDevice("", gumble.AudioSampleRate, openal.FormatMono16, uint32(b.Stream.sourceFrameSize))
}
ticker := time.NewTicker(interval)
defer ticker.Stop()
stop := b.Stream.sourceStop
outgoing := b.Stream.client.AudioOutgoing()
defer close(outgoing)
for {
select {
case <-stop:
return
case <-ticker.C:
//this is for encoding (transmitting)
buff := b.Stream.deviceSource.CaptureSamples(uint32(frameSize))
if len(buff) != frameSize*2 {
continue
}
int16Buffer := make([]int16, frameSize)
for i := range int16Buffer {
int16Buffer[i] = int16(binary.LittleEndian.Uint16(buff[i*2 : (i+1)*2]))
}
outgoing <- gumble.AudioBuffer(int16Buffer)
}
}
}
func (b *Talkkonnect) playIntoStream(filepath string, vol float32) {
if !IsPlayStream {
log.Println(fmt.Sprintf("info: File %s Stopped!", filepath))
pstream.Stop()
GPIOOutPin("transmit", "off")
MyLedStripTransmitLEDOff()
return
}
var eventSound EventSoundStruct = findEventSound("stream")
if eventSound.Enabled {
if pstream != nil && pstream.State() == gumbleffmpeg.StatePlaying {
pstream.Stop()
return
}
GPIOOutPin("transmit", "on")
MyLedStripTransmitLEDOn()
IsPlayStream = true
pstream = gumbleffmpeg.New(b.Client, gumbleffmpeg.SourceFile(filepath), vol/100)
if err := pstream.Play(); err != nil {
log.Println(fmt.Sprintf("error: Can't play %s error %s", filepath, err))
} else {
log.Println(fmt.Sprintf("info: File %s Playing!", filepath))
pstream.Wait()
pstream.Stop()
GPIOOutPin("transmit", "off")
MyLedStripTransmitLEDOff()
}
} else {
log.Println("warn: Sound Disabled by Config")
}
}
func (b *Talkkonnect) splayIntoStream(filepath string, vol float32) {
pstream = gumbleffmpeg.New(b.Stream.client, gumbleffmpeg.SourceFile(filepath), vol/100)
if err := pstream.Play(); err != nil {
log.Println(fmt.Sprintf("error: Can't play %s error %s", filepath, err))
} else {
log.Println(fmt.Sprintf("info: File %s Playing!", filepath))
pstream.Wait()
pstream.Stop()
}
}
func (b *Talkkonnect) OpenStream() {
if stream, err := b.New(b.Client); err != nil {
if Config.Global.Hardware.TargetBoard == "rpi" {
if LCDEnabled {
LcdText = [4]string{"Stream Error!", "nil", "nil", "nil"}
LcdDisplay(LcdText, LCDRSPin, LCDEPin, LCDD4Pin, LCDD5Pin, LCDD6Pin, LCDD7Pin, LCDInterfaceType, LCDI2CAddress)
}
if OLEDEnabled {
oledDisplay(false, 2, 1, "Stream Error!!")
}
}
FatalCleanUp("Stream Open Error " + err.Error())
} else {
b.Stream = stream
}
}
func (b *Talkkonnect) ResetStream() {
b.Stream.contextSink.Destroy()
time.Sleep(50 * time.Millisecond)
b.OpenStream()
}
func goStreamStats() {
log.Println("info: Active Streams")
for item, value := range StreamTracker {
log.Printf("info: Item=%v UserID=%v UserName=%v Session=%v AudioStreamChannel=%v", item, value.UserID, value.UserName, value.UserSession, value.C)
}
log.Printf("Total GoRoutines Open=%v, Total GoRoutines Wasted=%v \n", TotalStreams, NeedToKill)
}