网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!
return self.ctx.Err()
}
func (self *Stream) Stop() bool {
self.cancel()
if self.hasAudioTrack {
<-self.audioFinish
}
if self.hasVideoTrack {
<-self.videoFinish
}
if self.hasVideoTrack && self.hasAudioTrack {
audiopath := self.savePath + self.Display + "\_audio.ogg"
videopath := self.savePath + self.Display + "\_video.h264"
cmd := exec.Command("ffmpeg",
"-i",
audiopath,
"-i",
videopath,
self.savePath+self.Display+".ts",
"-y")
if err := cmd.Run(); err != nil {
logrus.Errorf("拼接音频和视频失败:%v", err)
return false
}
return true
}
return false
}
func NewStream(host, room, display, savePath string) (*Stream, error) {
var err error
stream := &Stream{
Host: host,
Room: room,
Display: display,
rtcUrl: “webrtc://” + host + “/” + room + “/” + display,
savePath: savePath,
hasAudioTrack: false,
hasVideoTrack: false,
videoFinish: make(chan struct{}, 1),
audioFinish: make(chan struct{}, 1),
}
stream.ctx, stream.cancel = context.WithCancel(context.Background())
//创建PeerConncetion
stream.pc, err = newPeerConnection(webrtc.Configuration{})
if err != nil {
return nil, errors.Wrapf(err, "创建PeerConnection失败")
}
//设置方向
stream.pc.AddTransceiverFromKind(webrtc.RTPCodecTypeAudio, webrtc.RTPTransceiverInit{
Direction: webrtc.RTPTransceiverDirectionRecvonly,
})
stream.pc.AddTransceiverFromKind(webrtc.RTPCodecTypeVideo, webrtc.RTPTransceiverInit{
Direction: webrtc.RTPTransceiverDirectionRecvonly,
})
//创建offer
offer, err := stream.pc.CreateOffer(nil)
if err != nil {
return nil, errors.Wrap(err, "创建Local offer失败")
}
// 设置本地sdp
if err = stream.pc.SetLocalDescription(offer); err != nil {
return nil, errors.Wrap(err, "设置Local SDP失败")
}
// 设置远端SDP
answer, err := apiRtcRequest(stream.ctx, "/rtc/v1/play", stream.rtcUrl, offer.SDP)
if err != nil {
return nil, errors.Wrap(err, "SDP协商失败")
}
if err = stream.pc.SetRemoteDescription(webrtc.SessionDescription{
Type: webrtc.SDPTypeAnswer, SDP: answer,
}); err != nil {
return nil, errors.Wrap(err, "设置Remote SDP失败")
}
stream.pc.OnTrack(func(track \*webrtc.TrackRemote, receiver \*webrtc.RTPReceiver) {
fmt.Println("------------------")
err = stream.onTrack(track, receiver)
if err != nil {
codec := track.Codec()
logrus.Errorf("Handle track %v, pt=%v\nerr %v", codec.MimeType, codec.PayloadType, err)
stream.cancel()
}
stream.pc.Close()
})
stream.pc.OnICEConnectionStateChange(func(state webrtc.ICEConnectionState) {
logrus.Infof("ICE state %v", state)
if state == webrtc.ICEConnectionStateFailed || state == webrtc.ICEConnectionStateClosed {
if stream.ctx.Err() != nil {
return
}
logrus.Warnf("Close for ICE state %v", state)
stream.cancel()
stream.pc.Close()
}
})
key := "webrtc://" + host + "/" + room
Streams.Store(key, stream)
return stream, nil
}
func newPeerConnection(configuration webrtc.Configuration) (*webrtc.PeerConnection, error) {
m := &webrtc.MediaEngine{}
if err := m.RegisterDefaultCodecs(); err != nil {
return nil, err
}
for _, extension := range []string{sdp.SDESMidURI, sdp.SDESRTPStreamIDURI, sdp.TransportCCURI} {
if extension == sdp.TransportCCURI {
continue
}
if err := m.RegisterHeaderExtension(webrtc.RTPHeaderExtensionCapability{URI: extension}, webrtc.RTPCodecTypeVideo); err != nil {
return nil, err
}
}
// https://github.com/pion/ion/issues/130
// https://github.com/pion/ion-sfu/pull/373/files#diff-6f42c5ac6f8192dd03e5a17e9d109e90cb76b1a4a7973be6ce44a89ffd1b5d18R73
for _, extension := range []string{sdp.SDESMidURI, sdp.SDESRTPStreamIDURI, sdp.AudioLevelURI} {
if extension == sdp.AudioLevelURI {
continue
}
if err := m.RegisterHeaderExtension(webrtc.RTPHeaderExtensionCapability{URI: extension}, webrtc.RTPCodecTypeAudio); err != nil {
return nil, err
}
}
i := &interceptor.Registry{}
if err := webrtc.RegisterDefaultInterceptors(m, i); err != nil {
return nil, err
}
api := webrtc.NewAPI(webrtc.WithMediaEngine(m), webrtc.WithInterceptorRegistry(i))
return api.NewPeerConnection(configuration)
}
api.go
package stream
import (
“context”
“encoding/json”
“fmt”
“github.com/pkg/errors”
“github.com/sirupsen/logrus”
“io/ioutil”
“net/http”
“net/url”
“strings”
)
// Request SRS RTC API, the apiPath like “/rtc/v1/play”, the r is WebRTC url like
// “webrtc://localhost/live/livestream”, and the offer is SDP in string.
//
// Return the response of answer SDP in string.
func apiRtcRequest(ctx context.Context, apiPath, rtcurl, offer string) (string, error) {
u, err := url.Parse(rtcurl)
if err != nil {
return “”, errors.Wrapf(err, “Parse url %v”, rtcurl)
}
// Build api url.
host := u.Host
if !strings.Contains(host, ":") {
host += ":1985"
}
api := fmt.Sprintf("http://%v", host)
if !strings.HasPrefix(apiPath, "/") {
api += "/"
}
api += apiPath
if !strings.HasSuffix(apiPath, "/") {
api += "/"
}
if u.RawQuery != "" {
api += "?" + u.RawQuery
}
// Build JSON body.
reqBody := struct {
Api string `json:"api"`
ClientIP string `json:"clientip"`
SDP string `json:"sdp"`
StreamURL string `json:"streamurl"`
}{
api, "", offer, rtcurl,
}
resBody := struct {
Code int `json:"code"`
Session string `json:"sessionid"`
SDP string `json:"sdp"`
}{}
if err := apiRequest(ctx, api, reqBody, &resBody); err != nil {
return "", errors.Wrapf(err, "request api=%v", api)
}
if resBody.Code != 0 {
return "", errors.Errorf("Server fail code=%v", resBody.Code)
}
logrus.Infof("Parse response to code=%v, session=%v, sdp=%v",
resBody.Code, resBody.Session, escapeSDP(resBody.SDP))
logrus.Infof("Parse response to code=%v, session=%v, sdp=%v bytes",
resBody.Code, resBody.Session, len(resBody.SDP))
return resBody.SDP, nil
}
func escapeSDP(sdp string) string {
return strings.ReplaceAll(strings.ReplaceAll(sdp, “\r”, “\r”), “\n”, “\n”)
}
// Request SRS API and got response, both in JSON.
// The r is HTTP API to request, like “http://localhost:1985/rtc/v1/play”.
// The req is the HTTP request body, will be marshal to JSON object. nil is no body
// The res is the HTTP response body, already unmarshal to JSON object.
func apiRequest(ctx context.Context, r string, req interface{}, res interface{}) error {
var b []byte
if req != nil {
if b0, err := json.Marshal(req); err != nil {
return errors.Wrapf(err, “Marshal body %v”, req)
} else {
b = b0
}
}
logrus.Infof(“Request url api=%v with %v”, r, string(b))
logrus.Infof(“Request url api=%v with %v bytes”, r, len(b))
method := "POST"
if req == nil {
method = "GET"
}
reqObj, err := http.NewRequest(method, r, strings.NewReader(string(b)))
if err != nil {
return errors.Wrapf(err, "HTTP request %v", string(b))
}
resObj, err := http.DefaultClient.Do(reqObj.WithContext(ctx))
if err != nil {
return errors.Wrapf(err, "Do HTTP request %v", string(b))
}
b2, err := ioutil.ReadAll(resObj.Body)
if err != nil {
return errors.Wrapf(err, "Read response for %v", string(b))
}
logrus.Infof("Response from %v is %v", r, string(b2))
logrus.Infof("Response from %v is %v bytes", r, len(b2))
errorCode := struct {
Code int `json:"code"`
网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!
85200417)]
[外链图片转存中…(img-flXnBVUP-1715885200417)]
网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!