Skip to content

Instantly share code, notes, and snippets.

@Gictorbit
Created February 7, 2022 06:04
Show Gist options
  • Save Gictorbit/8c6e0cfab707fe7acadffb908060b0cd to your computer and use it in GitHub Desktop.
Save Gictorbit/8c6e0cfab707fe7acadffb908060b0cd to your computer and use it in GitHub Desktop.
func (w *WebRtcServer) CreateNewPeerConnection(offer webrtc.SessionDescription, userID uint32, sessionKey string) (
*ClientConnection, webrtc.SessionDescription, error) {
answer := webrtc.SessionDescription{}
if len(offer.SDP) == 0 || offer.Type != webrtc.SDPTypeOffer {
return nil, answer, errors.New("invalid offer")
}
if len(sessionKey) == 0 {
return nil, answer, errors.New("invalid user token")
}
peerConnection, err := webrtc.NewPeerConnection(webrtc.Configuration{
ICEServers: []webrtc.ICEServer{
{
URLs: []string{"stun:stun.l.google.com:19302"},
},
},
})
if err != nil {
return nil, answer, errors.New("error creating peer connection")
}
videoTrack, err := webrtc.NewTrackLocalStaticSample(webrtc.RTPCodecCapability{MimeType: "video/h264"}, "video", "pion")
if err != nil {
return nil, answer, errors.New("error create video track")
}
_, err = peerConnection.AddTrack(videoTrack)
if err != nil {
return nil, answer, errors.New("error add video track")
}
audioTrack, err := webrtc.NewTrackLocalStaticSample(webrtc.RTPCodecCapability{MimeType: "audio/opus"}, "audio", "pion")
if err != nil {
return nil, answer, errors.New("error create audio track")
}
_, err = peerConnection.AddTrack(audioTrack)
if err != nil {
return nil, answer, errors.New("error add audio track")
}
if err := peerConnection.SetRemoteDescription(offer); err != nil {
return nil, answer, errors.New("error set remote Description")
}
answer, err = peerConnection.CreateAnswer(nil)
if err != nil {
return nil, answer, errors.New("error create answer")
} else if err = peerConnection.SetLocalDescription(answer); err != nil {
return nil, answer, errors.New("error set local Description")
}
clientConn := &ClientConnection{
PeerConnection: peerConnection,
VideoTrack: videoTrack,
AudioTrack: audioTrack,
SessionKey: sessionKey,
}
peerConnection.OnConnectionStateChange(func(connectionState webrtc.PeerConnectionState) {
switch connectionState {
case webrtc.PeerConnectionStateDisconnected:
peerConnection.Close()
w.log.Info("peer connection disconnected",
zap.Uint32("userID", userID),
)
case webrtc.PeerConnectionStateClosed:
peerConnection.Close()
w.log.Info("peer connection closed",
zap.Uint32("userID", userID),
)
case webrtc.PeerConnectionStateConnected:
w.log.Info("peer connection connected",
zap.Uint32("userID", userID),
)
case webrtc.PeerConnectionStateFailed:
w.log.Info("peer connection failed",
zap.Uint32("userID", userID),
)
}
})
return clientConn, answer, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment