ace/lib/webrtcconnection/connection.go
2022-09-26 06:54:32 +00:00

126 lines
2.8 KiB
Go

package webrtcconnection
import (
"github.com/pion/mediadevices"
"github.com/pion/mediadevices/pkg/codec/opus"
"github.com/pion/mediadevices/pkg/codec/x264"
"github.com/pion/webrtc/v3"
"github.com/sirupsen/logrus"
)
const DefaultStreamID = "ace-server"
type Connection struct {
option *Options
}
func New(o *Options) *Connection {
return &Connection{
option: o,
}
}
func (c *Connection) Regist(offer *webrtc.SessionDescription) (*webrtc.SessionDescription, error) {
logrus.Debug("received offer ", offer.Type.String())
codecSelector, err := setupCodec(c.option.Video.BPS, c.option.Audio.BPS)
if err != nil {
return nil, err
}
me := &webrtc.MediaEngine{}
codecSelector.Populate(me)
api := webrtc.NewAPI(webrtc.WithMediaEngine(me))
rtc, err := api.NewPeerConnection(webrtc.Configuration{
ICEServers: []webrtc.ICEServer{
{
URLs: c.option.STUNServers,
},
},
})
if err != nil {
return nil, err
}
rtc.OnICEConnectionStateChange(func(connectionState webrtc.ICEConnectionState) {
logrus.Debug("connection state has changed: ", connectionState.String())
switch connectionState {
case webrtc.ICEConnectionStateFailed:
fallthrough
case webrtc.ICEConnectionStateClosed:
rtc.Close()
}
})
s, err := mediadevices.GetUserMedia(mediadevices.MediaStreamConstraints{
Video: func(mtc *mediadevices.MediaTrackConstraints) {
/*
mtc.Height = prop.IntExact(c.option.Video.Height)
mtc.Width = prop.IntExact(c.option.Video.Width)
*/
},
Audio: func(mtc *mediadevices.MediaTrackConstraints) {},
Codec: codecSelector,
})
if err != nil {
return nil, err
}
for _, track := range s.GetTracks() {
track.OnEnded(func(err error) {
logrus.Errorf("Track (ID: %s) ended with error: %v", track.ID(), err)
})
_, err := rtc.AddTransceiverFromTrack(track, webrtc.RTPTransceiverInit{
Direction: webrtc.RTPTransceiverDirectionSendonly,
})
if err != nil {
logrus.Error(err)
}
}
rtc.OnDataChannel(dataChannel)
if err := rtc.SetRemoteDescription(*offer); err != nil {
return nil, err
}
logrus.Debug("offer set")
answer, err := rtc.CreateAnswer(nil)
if err != nil {
return nil, err
}
gatherComplete := webrtc.GatheringCompletePromise(rtc)
if err := rtc.SetLocalDescription(answer); err != nil {
return nil, err
}
logrus.Debug("answer set")
<-gatherComplete
defer logrus.Debug("regist complete")
return rtc.LocalDescription(), nil
}
func setupCodec(videoBPS, audioBPS int) (*mediadevices.CodecSelector, error) {
x264Prarm, err := x264.NewParams()
if err != nil {
return nil, err
}
x264Prarm.BitRate = videoBPS
opusParam, err := opus.NewParams()
if err != nil {
return nil, err
}
opusParam.BitRate = audioBPS
codecSelector := mediadevices.NewCodecSelector(
mediadevices.WithAudioEncoders(&opusParam),
mediadevices.WithVideoEncoders(&x264Prarm),
)
return codecSelector, nil
}