Fix so opusSender exits better on close, closes #123

This commit is contained in:
Bruce Marriner 2016-02-19 16:09:16 -06:00
parent bb612a0e8b
commit f832d3da4a

View file

@ -314,6 +314,10 @@ func (v *Voice) udpOpen() (err error) {
return fmt.Errorf("nil voice websocket") return fmt.Errorf("nil voice websocket")
} }
if v.UDPConn != nil {
return fmt.Errorf("udp connection already open")
}
if v.close == nil { if v.close == nil {
return fmt.Errorf("nil close channel") return fmt.Errorf("nil close channel")
} }
@ -408,7 +412,6 @@ func (v *Voice) udpKeepAlive(UDPConn *net.UDPConn, close <-chan struct{}, i time
ticker := time.NewTicker(i) ticker := time.NewTicker(i)
for { for {
// TODO: Add a way to break from loop
binary.LittleEndian.PutUint64(packet, sequence) binary.LittleEndian.PutUint64(packet, sequence)
sequence++ sequence++
@ -441,12 +444,12 @@ func (v *Voice) opusSender(UDPConn *net.UDPConn, close <-chan struct{}, opus <-c
// Voice is now ready to receive audio packets // Voice is now ready to receive audio packets
// TODO: this needs reviewed as I think there must be a better way. // TODO: this needs reviewed as I think there must be a better way.
v.Ready = true v.Ready = true
defer func() { defer func() { v.Ready = false }()
v.Ready = false
}()
var sequence uint16 var sequence uint16
var timestamp uint32 var timestamp uint32
var recvbuf []byte
var ok bool
udpHeader := make([]byte, 12) udpHeader := make([]byte, 12)
// build the parts that don't change in the udpHeader // build the parts that don't change in the udpHeader
@ -459,10 +462,15 @@ func (v *Voice) opusSender(UDPConn *net.UDPConn, close <-chan struct{}, opus <-c
for { for {
// Get data from chan. If chan is closed, return. // Get data from chan. If chan is closed, return.
recvbuf, ok := <-opus select {
case <-close:
return
case recvbuf, ok = <-opus:
if !ok { if !ok {
return return
} }
// else, continue loop
}
// Add sequence and timestamp to udpPacket // Add sequence and timestamp to udpPacket
binary.BigEndian.PutUint16(udpHeader[2:], sequence) binary.BigEndian.PutUint16(udpHeader[2:], sequence)
@ -474,10 +482,10 @@ func (v *Voice) opusSender(UDPConn *net.UDPConn, close <-chan struct{}, opus <-c
// block here until we're exactly at the right time :) // block here until we're exactly at the right time :)
// Then send rtp audio packet to Discord over UDP // Then send rtp audio packet to Discord over UDP
select { select {
case <-ticker.C:
// continue
case <-close: case <-close:
return return
case <-ticker.C:
// continue
} }
_, err := UDPConn.Write(sendbuf) _, err := UDPConn.Write(sendbuf)