kappanhang/audiostream.go

83 lines
1.7 KiB
Go
Raw Normal View History

2020-10-18 10:33:47 +02:00
package main
2020-10-18 15:40:25 +02:00
import (
"bytes"
"encoding/binary"
"time"
"github.com/nonoo/kappanhang/log"
)
const audioTimeoutDuration = 3 * time.Second
2020-10-18 10:33:47 +02:00
type audioStream struct {
2020-10-18 11:01:53 +02:00
common streamCommon
2020-10-18 15:40:25 +02:00
timeoutTimer *time.Timer
receivedAudio bool
2020-10-18 15:40:25 +02:00
lastReceivedAudioSeq uint16
2020-10-18 10:33:47 +02:00
}
2020-10-18 13:19:52 +02:00
func (s *audioStream) sendDisconnect() {
s.common.sendDisconnect()
}
2020-10-18 15:40:25 +02:00
func (s *audioStream) handleAudioPacket(r []byte) {
if s.timeoutTimer != nil {
s.timeoutTimer.Stop()
s.timeoutTimer.Reset(audioTimeoutDuration)
}
gotSeq := binary.LittleEndian.Uint16(r[6:8])
if s.receivedAudio {
expectedSeq := s.lastReceivedAudioSeq + 1
if expectedSeq != gotSeq {
var missingPkts int
if gotSeq > expectedSeq {
missingPkts = int(gotSeq) - int(expectedSeq)
} else {
missingPkts = int(gotSeq) + 65536 - int(expectedSeq)
}
log.Error("lost ", missingPkts, " audio packets")
2020-10-18 15:40:25 +02:00
}
}
s.lastReceivedAudioSeq = gotSeq
s.receivedAudio = true
2020-10-18 15:40:25 +02:00
// log.Print("got audio packet ", len(r[24:]), " bytes")
}
2020-10-18 13:52:38 +02:00
func (s *audioStream) handleRead(r []byte) {
2020-10-18 15:40:25 +02:00
if len(r) >= 580 && (bytes.Equal(r[:6], []byte{0x6c, 0x05, 0x00, 0x00, 0x00, 0x00}) || bytes.Equal(r[:6], []byte{0x44, 0x02, 0x00, 0x00, 0x00, 0x00})) {
s.handleAudioPacket(r)
}
2020-10-18 13:52:38 +02:00
}
func (s *audioStream) init() {
2020-10-18 11:17:40 +02:00
s.common.open("audio", 50003)
}
2020-10-18 10:33:47 +02:00
func (s *audioStream) start() {
2020-10-18 11:01:53 +02:00
s.common.sendPkt3()
2020-10-18 13:52:38 +02:00
s.common.waitForPkt4Answer()
2020-10-18 11:01:53 +02:00
s.common.sendPkt6()
2020-10-18 13:52:38 +02:00
s.common.waitForPkt6Answer()
log.Print("stream started")
2020-10-18 13:52:38 +02:00
2020-10-18 15:40:25 +02:00
s.timeoutTimer = time.NewTimer(audioTimeoutDuration)
2020-10-18 14:21:58 +02:00
s.common.pkt7.sendSeq = 1
s.common.pkt7.startPeriodicSend(&s.common)
2020-10-18 13:52:38 +02:00
var r []byte
for {
select {
case r = <-s.common.readChan:
s.handleRead(r)
2020-10-18 15:40:25 +02:00
case <-s.timeoutTimer.C:
log.Fatal("timeout")
2020-10-18 13:52:38 +02:00
}
}
2020-10-18 10:33:47 +02:00
}