From 65c82ef3f4f3df2da301e649ca269a8df78c82ef Mon Sep 17 00:00:00 2001 From: Noah Metz Date: Mon, 8 Apr 2024 18:13:19 -0600 Subject: [PATCH] Moved decode per client to a goroutine so dropped packets can be accounted for --- cmd/client/main.go | 59 +++++++++++++++++++++++++++++++++------------- 1 file changed, 43 insertions(+), 16 deletions(-) diff --git a/cmd/client/main.go b/cmd/client/main.go index 5e0c20f..4b8255e 100644 --- a/cmd/client/main.go +++ b/cmd/client/main.go @@ -4,6 +4,7 @@ import ( "encoding/binary" "fmt" "os" + "time" "git.metznet.ca/MetzNet/pnyx" "github.com/gen2brain/malgo" @@ -11,7 +12,7 @@ import ( ) func main() { - decoders := map[pnyx.PeerID]*opus.Decoder{} + decoders := map[pnyx.PeerID]chan[]byte{} encoder, err := opus.NewEncoder(48000, 1, opus.AppVoIP) if err != nil { panic(err) @@ -179,23 +180,49 @@ func main() { } peer := pnyx.PeerID(packet.Data[0:16]) if packet.Channel == pnyx.ChannelID(1) { - decoder, exists := decoders[peer] + decode_chan, exists := decoders[peer] if exists == false { - decoder, err = opus.NewDecoder(48000, 1) - if err != nil { - panic(err) - } + decode_chan = make(chan[]byte, 1000) + decoders[peer] = decode_chan + + go func(decode_chan chan[]byte){ + decoder, err := opus.NewDecoder(48000, 1) + if err != nil { + panic(err) + } + + for true { + select { + case <-time.After(20*time.Millisecond): + pcm := make([]int16, 960) + err := decoder.DecodePLC(pcm) + if err != nil { + panic(err) + } + + pcm_bytes := make([]byte, 960*2) + for i := 0; i < 960; i++ { + binary.LittleEndian.PutUint16(pcm_bytes[i*2:], uint16(pcm[i])) + } + speaker <- pcm_bytes + case data := <-decode_chan: + pcm := make([]int16, 960) + written, err := decoder.Decode(data, pcm) + if err != nil { + panic(err) + } + + pcm_bytes := make([]byte, written*2) + for i := 0; i < written; i++ { + binary.LittleEndian.PutUint16(pcm_bytes[i*2:], uint16(pcm[i])) + } + speaker <- pcm_bytes + } + } + + }(decoders[peer]) } - pcm := make([]int16, 1000) - written, err := decoder.Decode(packet.Data[16:], pcm) - if err != nil { - panic(err) - } - data := make([]byte, written*2) - for i := 0; i < written; i++ { - binary.LittleEndian.PutUint16(data[i*2:], uint16(pcm[i])) - } - speaker <- data + decode_chan <- packet.Data[16:] } } }()