Moved decode per client to a goroutine so dropped packets can be accounted for

live
noah metz 2024-04-08 18:13:19 -06:00
parent 8b697a13ae
commit 65c82ef3f4
1 changed files with 43 additions and 16 deletions

@ -4,6 +4,7 @@ import (
"encoding/binary" "encoding/binary"
"fmt" "fmt"
"os" "os"
"time"
"git.metznet.ca/MetzNet/pnyx" "git.metznet.ca/MetzNet/pnyx"
"github.com/gen2brain/malgo" "github.com/gen2brain/malgo"
@ -11,7 +12,7 @@ import (
) )
func main() { func main() {
decoders := map[pnyx.PeerID]*opus.Decoder{} decoders := map[pnyx.PeerID]chan[]byte{}
encoder, err := opus.NewEncoder(48000, 1, opus.AppVoIP) encoder, err := opus.NewEncoder(48000, 1, opus.AppVoIP)
if err != nil { if err != nil {
panic(err) panic(err)
@ -179,23 +180,49 @@ func main() {
} }
peer := pnyx.PeerID(packet.Data[0:16]) peer := pnyx.PeerID(packet.Data[0:16])
if packet.Channel == pnyx.ChannelID(1) { if packet.Channel == pnyx.ChannelID(1) {
decoder, exists := decoders[peer] decode_chan, exists := decoders[peer]
if exists == false { if exists == false {
decoder, err = opus.NewDecoder(48000, 1) decode_chan = make(chan[]byte, 1000)
if err != nil { decoders[peer] = decode_chan
panic(err)
} 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) decode_chan <- packet.Data[16:]
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
} }
} }
}() }()