2021-01-05 09:21:25 +08:00
|
|
|
package webrtc
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"encoding/base64"
|
|
|
|
"errors"
|
2021-01-06 06:56:00 +08:00
|
|
|
"log"
|
2021-01-05 09:21:25 +08:00
|
|
|
"time"
|
|
|
|
|
2022-03-14 03:16:09 +08:00
|
|
|
"github.com/deepch/vdk/codec/h264parser"
|
2021-01-05 09:21:25 +08:00
|
|
|
|
|
|
|
"github.com/deepch/vdk/av"
|
2022-03-14 03:16:09 +08:00
|
|
|
"github.com/pion/interceptor"
|
|
|
|
"github.com/pion/webrtc/v3"
|
2021-01-05 09:21:25 +08:00
|
|
|
"github.com/pion/webrtc/v3/pkg/media"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
2021-01-06 06:56:00 +08:00
|
|
|
ErrorNotFound = errors.New("WebRTC Stream Not Found")
|
|
|
|
ErrorCodecNotSupported = errors.New("WebRTC Codec Not Supported")
|
|
|
|
ErrorClientOffline = errors.New("WebRTC Client Offline")
|
|
|
|
ErrorNotTrackAvailable = errors.New("WebRTC Not Track Available")
|
2021-01-08 12:23:06 +08:00
|
|
|
ErrorIgnoreAudioTrack = errors.New("WebRTC Ignore Audio Track codec not supported WebRTC support only PCM_ALAW or PCM_MULAW")
|
2021-01-05 09:21:25 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
type Muxer struct {
|
2021-01-06 06:56:00 +08:00
|
|
|
streams map[int8]*Stream
|
|
|
|
status webrtc.ICEConnectionState
|
|
|
|
stop bool
|
|
|
|
pc *webrtc.PeerConnection
|
|
|
|
ClientACK *time.Timer
|
|
|
|
StreamACK *time.Timer
|
2021-01-15 23:26:23 +08:00
|
|
|
Options Options
|
2021-01-05 09:21:25 +08:00
|
|
|
}
|
|
|
|
type Stream struct {
|
|
|
|
codec av.CodecData
|
|
|
|
track *webrtc.TrackLocalStaticSample
|
|
|
|
}
|
2021-01-15 23:26:23 +08:00
|
|
|
type Options struct {
|
2021-03-30 07:49:53 +08:00
|
|
|
// ICEServers is a required array of ICE server URLs to connect to (e.g., STUN or TURN server URLs)
|
2021-01-15 23:26:23 +08:00
|
|
|
ICEServers []string
|
2021-03-30 07:49:53 +08:00
|
|
|
// ICEUsername is an optional username for authenticating with the given ICEServers
|
|
|
|
ICEUsername string
|
|
|
|
// ICECredential is an optional credential (i.e., password) for authenticating with the given ICEServers
|
|
|
|
ICECredential string
|
2021-11-17 18:21:01 +08:00
|
|
|
// ICECandidates sets a list of external IP addresses of 1:1
|
|
|
|
ICECandidates []string
|
2021-03-30 07:49:53 +08:00
|
|
|
// PortMin is an optional minimum (inclusive) ephemeral UDP port range for the ICEServers connections
|
|
|
|
PortMin uint16
|
|
|
|
// PortMin is an optional maximum (inclusive) ephemeral UDP port range for the ICEServers connections
|
|
|
|
PortMax uint16
|
2021-01-15 23:26:23 +08:00
|
|
|
}
|
2021-01-05 09:21:25 +08:00
|
|
|
|
2021-01-15 23:26:23 +08:00
|
|
|
func NewMuxer(options Options) *Muxer {
|
|
|
|
tmp := Muxer{Options: options, ClientACK: time.NewTimer(time.Second * 20), StreamACK: time.NewTimer(time.Second * 20), streams: make(map[int8]*Stream)}
|
2021-04-23 15:48:39 +08:00
|
|
|
//go tmp.WaitCloser()
|
2021-01-05 09:21:25 +08:00
|
|
|
return &tmp
|
|
|
|
}
|
2021-01-15 23:26:23 +08:00
|
|
|
func (element *Muxer) NewPeerConnection(configuration webrtc.Configuration) (*webrtc.PeerConnection, error) {
|
|
|
|
if len(element.Options.ICEServers) > 0 {
|
|
|
|
log.Println("Set ICEServers", element.Options.ICEServers)
|
2021-03-30 07:49:53 +08:00
|
|
|
configuration.ICEServers = append(configuration.ICEServers, webrtc.ICEServer{
|
|
|
|
URLs: element.Options.ICEServers,
|
|
|
|
Username: element.Options.ICEUsername,
|
|
|
|
Credential: element.Options.ICECredential,
|
|
|
|
CredentialType: webrtc.ICECredentialTypePassword,
|
|
|
|
})
|
2021-01-15 23:26:23 +08:00
|
|
|
}
|
|
|
|
m := &webrtc.MediaEngine{}
|
|
|
|
if err := m.RegisterDefaultCodecs(); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
i := &interceptor.Registry{}
|
|
|
|
if err := webrtc.RegisterDefaultInterceptors(m, i); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
s := webrtc.SettingEngine{}
|
|
|
|
if element.Options.PortMin > 0 && element.Options.PortMax > 0 && element.Options.PortMax > element.Options.PortMin {
|
|
|
|
s.SetEphemeralUDPPortRange(element.Options.PortMin, element.Options.PortMax)
|
|
|
|
log.Println("Set UDP ports to", element.Options.PortMin, "..", element.Options.PortMax)
|
|
|
|
}
|
2021-11-17 18:21:01 +08:00
|
|
|
if len(element.Options.ICECandidates) > 0 {
|
|
|
|
s.SetNAT1To1IPs(element.Options.ICECandidates, webrtc.ICECandidateTypeHost)
|
|
|
|
log.Println("Set ICECandidates", element.Options.ICECandidates)
|
|
|
|
}
|
2021-01-15 23:26:23 +08:00
|
|
|
api := webrtc.NewAPI(webrtc.WithMediaEngine(m), webrtc.WithInterceptorRegistry(i), webrtc.WithSettingEngine(s))
|
|
|
|
return api.NewPeerConnection(configuration)
|
|
|
|
}
|
2021-01-05 09:21:25 +08:00
|
|
|
func (element *Muxer) WriteHeader(streams []av.CodecData, sdp64 string) (string, error) {
|
2021-01-06 06:56:00 +08:00
|
|
|
var WriteHeaderSuccess bool
|
2021-01-05 09:21:25 +08:00
|
|
|
if len(streams) == 0 {
|
|
|
|
return "", ErrorNotFound
|
|
|
|
}
|
|
|
|
sdpB, err := base64.StdEncoding.DecodeString(sdp64)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
offer := webrtc.SessionDescription{
|
|
|
|
Type: webrtc.SDPTypeOffer,
|
|
|
|
SDP: string(sdpB),
|
|
|
|
}
|
2021-07-28 21:50:21 +08:00
|
|
|
peerConnection, err := element.NewPeerConnection(webrtc.Configuration{
|
|
|
|
SDPSemantics: webrtc.SDPSemanticsUnifiedPlanWithFallback,
|
|
|
|
})
|
2021-01-05 09:21:25 +08:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
2021-01-06 06:56:00 +08:00
|
|
|
defer func() {
|
|
|
|
if !WriteHeaderSuccess {
|
|
|
|
err = element.Close()
|
|
|
|
if err != nil {
|
|
|
|
log.Println(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
2021-01-05 09:21:25 +08:00
|
|
|
for i, i2 := range streams {
|
|
|
|
var track *webrtc.TrackLocalStaticSample
|
|
|
|
if i2.Type().IsVideo() {
|
2021-01-06 06:56:00 +08:00
|
|
|
if i2.Type() == av.H264 {
|
|
|
|
track, err = webrtc.NewTrackLocalStaticSample(webrtc.RTPCodecCapability{
|
|
|
|
MimeType: "video/h264",
|
|
|
|
}, "pion-rtsp-video", "pion-rtsp-video")
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
if _, err = peerConnection.AddTrack(track); err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
2021-01-05 09:21:25 +08:00
|
|
|
}
|
|
|
|
} else if i2.Type().IsAudio() {
|
2021-01-09 12:37:19 +08:00
|
|
|
AudioCodecString := webrtc.MimeTypePCMA
|
2021-01-05 09:21:25 +08:00
|
|
|
switch i2.Type() {
|
|
|
|
case av.PCM_ALAW:
|
2021-01-09 12:37:19 +08:00
|
|
|
AudioCodecString = webrtc.MimeTypePCMA
|
2021-01-05 09:21:25 +08:00
|
|
|
case av.PCM_MULAW:
|
2021-01-09 12:37:19 +08:00
|
|
|
AudioCodecString = webrtc.MimeTypePCMU
|
|
|
|
case av.OPUS:
|
|
|
|
AudioCodecString = webrtc.MimeTypeOpus
|
2021-01-05 09:21:25 +08:00
|
|
|
default:
|
2021-01-06 06:56:00 +08:00
|
|
|
log.Println(ErrorIgnoreAudioTrack)
|
2021-01-05 09:21:25 +08:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
track, err = webrtc.NewTrackLocalStaticSample(webrtc.RTPCodecCapability{
|
2021-01-09 12:37:19 +08:00
|
|
|
MimeType: AudioCodecString,
|
|
|
|
Channels: uint16(i2.(av.AudioCodecData).ChannelLayout().Count()),
|
|
|
|
ClockRate: uint32(i2.(av.AudioCodecData).SampleRate()),
|
2021-01-05 09:21:25 +08:00
|
|
|
}, "pion-rtsp-audio", "pion-rtsp-audio")
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
if _, err = peerConnection.AddTrack(track); err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
element.streams[int8(i)] = &Stream{track: track, codec: i2}
|
|
|
|
}
|
2021-01-06 06:56:00 +08:00
|
|
|
if len(element.streams) == 0 {
|
|
|
|
return "", ErrorNotTrackAvailable
|
|
|
|
}
|
2021-01-05 09:21:25 +08:00
|
|
|
peerConnection.OnICEConnectionStateChange(func(connectionState webrtc.ICEConnectionState) {
|
|
|
|
element.status = connectionState
|
|
|
|
if connectionState == webrtc.ICEConnectionStateDisconnected {
|
2021-01-06 06:56:00 +08:00
|
|
|
element.Close()
|
2021-01-05 09:21:25 +08:00
|
|
|
}
|
|
|
|
})
|
|
|
|
peerConnection.OnDataChannel(func(d *webrtc.DataChannel) {
|
|
|
|
d.OnMessage(func(msg webrtc.DataChannelMessage) {
|
2021-01-06 06:56:00 +08:00
|
|
|
element.ClientACK.Reset(5 * time.Second)
|
2021-01-05 09:21:25 +08:00
|
|
|
})
|
|
|
|
})
|
|
|
|
|
|
|
|
if err = peerConnection.SetRemoteDescription(offer); err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
gatherCompletePromise := webrtc.GatheringCompletePromise(peerConnection)
|
|
|
|
answer, err := peerConnection.CreateAnswer(nil)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
if err = peerConnection.SetLocalDescription(answer); err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
element.pc = peerConnection
|
2021-01-06 06:56:00 +08:00
|
|
|
waitT := time.NewTimer(time.Second * 10)
|
2021-01-05 09:21:25 +08:00
|
|
|
select {
|
|
|
|
case <-waitT.C:
|
|
|
|
return "", errors.New("gatherCompletePromise wait")
|
|
|
|
case <-gatherCompletePromise:
|
2021-01-06 06:56:00 +08:00
|
|
|
//Connected
|
2021-01-05 09:21:25 +08:00
|
|
|
}
|
|
|
|
resp := peerConnection.LocalDescription()
|
2021-01-06 06:56:00 +08:00
|
|
|
WriteHeaderSuccess = true
|
2021-01-05 09:21:25 +08:00
|
|
|
return base64.StdEncoding.EncodeToString([]byte(resp.SDP)), nil
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
func (element *Muxer) WritePacket(pkt av.Packet) (err error) {
|
2021-01-09 12:37:19 +08:00
|
|
|
//log.Println("WritePacket", pkt.Time, element.stop, webrtc.ICEConnectionStateConnected, pkt.Idx, element.streams[pkt.Idx])
|
2021-01-06 06:56:00 +08:00
|
|
|
var WritePacketSuccess bool
|
|
|
|
defer func() {
|
|
|
|
if !WritePacketSuccess {
|
|
|
|
element.Close()
|
|
|
|
}
|
|
|
|
}()
|
2021-01-05 09:21:25 +08:00
|
|
|
if element.stop {
|
|
|
|
return ErrorClientOffline
|
|
|
|
}
|
2021-01-09 22:24:48 +08:00
|
|
|
if element.status == webrtc.ICEConnectionStateChecking {
|
|
|
|
WritePacketSuccess = true
|
|
|
|
return nil
|
|
|
|
}
|
2021-01-05 09:21:25 +08:00
|
|
|
if element.status != webrtc.ICEConnectionStateConnected {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
if tmp, ok := element.streams[pkt.Idx]; ok {
|
2021-01-06 06:56:00 +08:00
|
|
|
element.StreamACK.Reset(10 * time.Second)
|
2021-02-09 09:27:04 +08:00
|
|
|
if len(pkt.Data) < 5 {
|
|
|
|
return nil
|
|
|
|
}
|
2021-01-05 09:21:25 +08:00
|
|
|
switch tmp.codec.Type() {
|
|
|
|
case av.H264:
|
2022-03-14 03:16:09 +08:00
|
|
|
nalus, _ := h264parser.SplitNALUs(pkt.Data)
|
|
|
|
for _, nalu := range nalus {
|
|
|
|
naltype := nalu[0] & 0x1f
|
|
|
|
if naltype == 5 {
|
|
|
|
codec := tmp.codec.(h264parser.CodecData)
|
|
|
|
err = tmp.track.WriteSample(media.Sample{Data: append([]byte{0, 0, 0, 1}, bytes.Join([][]byte{codec.SPS(), codec.PPS(), nalu}, []byte{0, 0, 0, 1})...), Duration: pkt.Duration})
|
2022-03-14 03:18:18 +08:00
|
|
|
|
2022-03-14 06:28:42 +08:00
|
|
|
} else if naltype == 1 {
|
2022-03-14 03:16:09 +08:00
|
|
|
err = tmp.track.WriteSample(media.Sample{Data: append([]byte{0, 0, 0, 1}, nalu...), Duration: pkt.Duration})
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2021-01-05 09:21:25 +08:00
|
|
|
}
|
2022-03-14 03:16:09 +08:00
|
|
|
WritePacketSuccess = true
|
|
|
|
return
|
|
|
|
/*
|
2022-03-14 03:18:18 +08:00
|
|
|
|
2022-03-14 03:16:09 +08:00
|
|
|
if pkt.IsKeyFrame {
|
|
|
|
pkt.Data = append([]byte{0, 0, 0, 1}, bytes.Join([][]byte{codec.SPS(), codec.PPS(), pkt.Data[4:]}, []byte{0, 0, 0, 1})...)
|
|
|
|
} else {
|
|
|
|
pkt.Data = pkt.Data[4:]
|
|
|
|
}
|
2022-03-14 03:18:18 +08:00
|
|
|
|
2022-03-14 03:16:09 +08:00
|
|
|
*/
|
2021-01-05 09:21:25 +08:00
|
|
|
case av.PCM_ALAW:
|
2021-01-09 12:37:19 +08:00
|
|
|
case av.OPUS:
|
2021-02-16 06:46:01 +08:00
|
|
|
case av.PCM_MULAW:
|
2021-01-15 23:26:23 +08:00
|
|
|
case av.AAC:
|
|
|
|
//TODO: NEED ADD DECODER AND ENCODER
|
|
|
|
return ErrorCodecNotSupported
|
|
|
|
case av.PCM:
|
|
|
|
//TODO: NEED ADD ENCODER
|
|
|
|
return ErrorCodecNotSupported
|
2021-01-05 09:21:25 +08:00
|
|
|
default:
|
|
|
|
return ErrorCodecNotSupported
|
|
|
|
}
|
2021-01-15 23:26:23 +08:00
|
|
|
err = tmp.track.WriteSample(media.Sample{Data: pkt.Data, Duration: pkt.Duration})
|
2021-01-06 06:56:00 +08:00
|
|
|
if err == nil {
|
|
|
|
WritePacketSuccess = true
|
|
|
|
}
|
2021-01-05 09:21:25 +08:00
|
|
|
return err
|
2021-01-06 06:56:00 +08:00
|
|
|
} else {
|
|
|
|
WritePacketSuccess = true
|
|
|
|
return nil
|
2021-01-05 09:21:25 +08:00
|
|
|
}
|
|
|
|
}
|
2021-04-23 15:48:39 +08:00
|
|
|
|
2021-01-05 09:21:25 +08:00
|
|
|
func (element *Muxer) Close() error {
|
2021-01-06 06:56:00 +08:00
|
|
|
element.stop = true
|
2021-01-05 09:21:25 +08:00
|
|
|
if element.pc != nil {
|
|
|
|
err := element.pc.Close()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|