neko/internal/webrtc/peer.go

85 lines
2.0 KiB
Go
Raw Normal View History

package webrtc
2021-06-28 08:02:05 +12:00
import (
"time"
"github.com/pion/webrtc/v3"
"github.com/rs/zerolog/log"
)
// how long is can take between sending offer and connecting
const offerTimeout = 10 * time.Second
2020-11-26 06:41:40 +13:00
type WebRTCPeerCtx struct {
2021-02-15 02:40:17 +13:00
api *webrtc.API
connection *webrtc.PeerConnection
dataChannel *webrtc.DataChannel
changeVideo func(videoID string) error
iceTrickle bool
}
func (peer *WebRTCPeerCtx) CreateOffer(ICERestart bool) (*webrtc.SessionDescription, error) {
2021-06-28 08:02:05 +12:00
// offer timeout
go func() {
time.Sleep(offerTimeout)
// already disconnected
if peer.connection.ConnectionState() == webrtc.PeerConnectionStateClosed {
return
}
// not connected
if peer.connection.ConnectionState() != webrtc.PeerConnectionStateConnected {
log.Warn().Msg("connection timeouted, closing")
peer.connection.Close()
}
}()
offer, err := peer.connection.CreateOffer(&webrtc.OfferOptions{
ICERestart: ICERestart,
})
if err != nil {
return nil, err
}
if !peer.iceTrickle {
2021-06-28 08:02:05 +12:00
// Create channel that is blocked until ICE Gathering is complete
gatherComplete := webrtc.GatheringCompletePromise(peer.connection)
if err := peer.connection.SetLocalDescription(offer); err != nil {
return nil, err
}
<-gatherComplete
} else {
if err := peer.connection.SetLocalDescription(offer); err != nil {
return nil, err
}
}
return peer.connection.LocalDescription(), nil
}
2021-02-15 05:11:21 +13:00
func (peer *WebRTCPeerCtx) SignalAnswer(sdp string) error {
return peer.connection.SetRemoteDescription(webrtc.SessionDescription{
2021-02-15 02:40:17 +13:00
SDP: sdp,
2020-11-02 04:09:48 +13:00
Type: webrtc.SDPTypeAnswer,
})
}
2021-02-15 05:11:21 +13:00
func (peer *WebRTCPeerCtx) SignalCandidate(candidate webrtc.ICECandidateInit) error {
return peer.connection.AddICECandidate(candidate)
2021-02-03 08:43:33 +13:00
}
2021-02-15 05:11:21 +13:00
func (peer *WebRTCPeerCtx) SetVideoID(videoID string) error {
return peer.changeVideo(videoID)
}
2021-02-15 05:11:21 +13:00
func (peer *WebRTCPeerCtx) Destroy() error {
if peer.connection == nil || peer.connection.ConnectionState() != webrtc.PeerConnectionStateConnected {
2020-11-02 04:09:48 +13:00
return nil
}
2021-02-03 06:28:32 +13:00
2021-02-15 05:11:21 +13:00
return peer.connection.Close()
}