合并修改

This commit is contained in:
langhuihui
2020-07-27 21:31:34 +08:00
parent bf1430f0df
commit 694c05ec8e
8 changed files with 259 additions and 250 deletions

116
main.go
View File

@@ -48,10 +48,6 @@ var config struct {
// port int
// }
var m MediaEngine
var api *API
var SSRC uint32
var SSRCMap = make(map[string]uint32)
var ssrcLock sync.Mutex
var playWaitList WaitList
@@ -75,15 +71,7 @@ func (wl *WaitList) Get(k string) *WebRTC {
return wl.m[k]
}
func init() {
m.RegisterCodec(NewRTPCodec(RTPCodecTypeVideo,
H264,
90000,
0,
"level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42001f",
DefaultPayloadTypeH264,
new(avformat.H264)))
//m.RegisterCodec(NewRTPPCMUCodec(DefaultPayloadTypePCMU, 8000))
api = NewAPI(WithMediaEngine(m))
InstallPlugin(&PluginConfig{
Config: &config,
Name: "WebRTC",
@@ -97,19 +85,13 @@ type WebRTC struct {
*PeerConnection
RemoteAddr string
videoTrack *Track
m MediaEngine
api *API
// codecs.H264Packet
// *os.File
}
func (rtc *WebRTC) Play(streamPath string) bool {
rtc.OnICEConnectionStateChange(func(connectionState ICEConnectionState) {
Printf("%s Connection State has changed %s ", streamPath, connectionState.String())
switch connectionState {
case ICEConnectionStateDisconnected:
if rtc.Stream != nil {
rtc.Stream.Close()
}
case ICEConnectionStateConnected:
var sub Subscriber
sub.ID = rtc.RemoteAddr
sub.Type = "WebRTC"
@@ -148,13 +130,32 @@ func (rtc *WebRTC) Play(streamPath string) bool {
lastTimeStamp = packet.Timestamp
return nil
}
go sub.Subscribe(streamPath)
// go sub.Subscribe(streamPath)
rtc.OnICEConnectionStateChange(func(connectionState ICEConnectionState) {
Printf("%s Connection State has changed %s ", streamPath, connectionState.String())
switch connectionState {
case ICEConnectionStateDisconnected:
if rtc.Stream != nil {
rtc.Stream.Close()
}
case ICEConnectionStateConnected:
//rtc.videoTrack = rtc.GetSenders()[0].Track()
sub.Subscribe(streamPath)
}
})
return true
}
func (rtc *WebRTC) Publish(streamPath string) bool {
peerConnection, err := api.NewPeerConnection(Configuration{
rtc.m.RegisterCodec(NewRTPCodec(RTPCodecTypeVideo,
H264,
90000,
0,
"level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42001f",
DefaultPayloadTypeH264,
new(avformat.H264)))
//m.RegisterCodec(NewRTPPCMUCodec(DefaultPayloadTypePCMU, 8000))
rtc.api = NewAPI(WithMediaEngine(rtc.m))
peerConnection, err := rtc.api.NewPeerConnection(Configuration{
ICEServers: []ICEServer{
{
URLs: config.ICEServers,
@@ -233,79 +234,84 @@ func (rtc *WebRTC) GetAnswer(localSdp SessionDescription) ([]byte, error) {
func run() {
http.HandleFunc("/webrtc/play", func(w http.ResponseWriter, r *http.Request) {
streamPath := r.URL.Query().Get("streamPath")
offer := SessionDescription{}
var offer SessionDescription
bytes, err := ioutil.ReadAll(r.Body)
err = json.Unmarshal(bytes, &offer)
defer func() {
if err != nil {
Println(err)
fmt.Fprint(w, err)
return
}
}()
if err != nil {
return
}
if rtc := playWaitList.Get(streamPath); rtc != nil {
if err := rtc.SetRemoteDescription(offer); err != nil {
Println(err)
return
}
if rtc.Play(streamPath) {
w.Write([]byte(`success`))
rtc.Play(streamPath)
} else {
w.Write([]byte(`{"errmsg":"bad name"}`))
}
} else {
w.Write([]byte(`{"errmsg":"bad name"}`))
w.Write([]byte("bad name"))
}
})
http.HandleFunc("/webrtc/preparePlay", func(w http.ResponseWriter, r *http.Request) {
streamPath := r.URL.Query().Get("streamPath")
pli := "42001f"
if stream := FindStream(streamPath); stream != nil {
pli = fmt.Sprintf("%x", stream.SPS[1:4])
}
rtc := new(WebRTC)
peerConnection, err := api.NewPeerConnection(Configuration{
rtc.m.RegisterCodec(NewRTPCodec(RTPCodecTypeVideo,
H264,
90000,
0,
"level-asymmetry-allowed=1;packetization-mode=1;profile-level-id="+pli,
DefaultPayloadTypeH264,
new(avformat.H264)))
//m.RegisterCodec(NewRTPPCMUCodec(DefaultPayloadTypePCMU, 8000))
rtc.api = NewAPI(WithMediaEngine(rtc.m))
peerConnection, err := rtc.api.NewPeerConnection(Configuration{
ICEServers: []ICEServer{
{
URLs: config.ICEServers,
},
},
})
if _, err = peerConnection.AddTransceiverFromKind(RTPCodecTypeVideo); err != nil {
if err != nil {
Println(err)
return
}
}
if err != nil {
return
}
rtc.PeerConnection = peerConnection
// Create a video track, using the same SSRC as the incoming RTP Packet
ssrcLock.Lock()
if _, ok := SSRCMap[streamPath]; !ok {
SSRC++
SSRCMap[streamPath] = SSRC
rtc.OnICECandidate(func(ice *ICECandidate) {
if ice != nil {
println(ice.ToJSON().Candidate)
}
ssrcLock.Unlock()
videoTrack, err := rtc.NewTrack(DefaultPayloadTypeH264, SSRC, "video", "monibuca")
})
if r, err := peerConnection.AddTransceiverFromKind(RTPCodecTypeVideo); err == nil {
rtc.videoTrack = r.Sender().Track()
} else {
Println(err)
}
defer func() {
if err != nil {
Println(err)
fmt.Fprintf(w, `{"errmsg":"%s"}`, err.Error())
return
}
if _, err = rtc.AddTrack(videoTrack); err != nil {
Println(err)
}()
if err != nil {
return
}
rtc.videoTrack = videoTrack
playWaitList.Set(streamPath, rtc)
rtc.RemoteAddr = r.RemoteAddr
offer, err := rtc.CreateOffer(nil)
if err != nil {
Println(err)
return
}
if bytes, err := rtc.GetAnswer(offer); err == nil {
w.Write(bytes)
} else {
Println(err)
w.Write([]byte(err.Error()))
return
}
})
http.HandleFunc("/webrtc/publish", func(w http.ResponseWriter, r *http.Request) {
streamPath := r.URL.Query().Get("streamPath")

View File

@@ -221,12 +221,12 @@ var staticRenderFns = []
// CONCATENATED MODULE: ./src/App.vue?vue&type=template&id=50fea0bc&scoped=true&
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"7d106341-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/components/Player.vue?vue&type=template&id=edf62584&
var Playervue_type_template_id_edf62584_render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('Modal',_vm._g(_vm._b({attrs:{"draggable":"","title":_vm.streamPath},on:{"on-ok":_vm.onClosePreview,"on-cancel":_vm.onClosePreview}},'Modal',_vm.$attrs,false),_vm.$listeners),[_c('video',{ref:"webrtc",attrs:{"width":"488","height":"275","autoplay":"","muted":"","controls":""},domProps:{"srcObject":_vm.stream,"muted":true}}),_c('div',{attrs:{"slot":"footer"},slot:"footer"},[(_vm.remoteSDP)?_c('mu-badge',[_c('a',{attrs:{"slot":"content","href":_vm.remoteSDPURL,"download":"remoteSDP.txt"},slot:"content"},[_vm._v("remoteSDP")])]):_vm._e(),(_vm.localSDP)?_c('mu-badge',[_c('a',{attrs:{"slot":"content","href":_vm.localSDPURL,"download":"localSDP.txt"},slot:"content"},[_vm._v("localSDP")])]):_vm._e()],1)])}
var Playervue_type_template_id_edf62584_staticRenderFns = []
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"7d106341-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/components/Player.vue?vue&type=template&id=6aea3512&
var Playervue_type_template_id_6aea3512_render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('Modal',_vm._g(_vm._b({attrs:{"draggable":"","title":_vm.streamPath},on:{"on-ok":_vm.onClosePreview,"on-cancel":_vm.onClosePreview}},'Modal',_vm.$attrs,false),_vm.$listeners),[_c('video',{ref:"webrtc",attrs:{"width":"488","height":"275","autoplay":"","muted":"","controls":""},domProps:{"srcObject":_vm.stream,"muted":true}}),_c('div',{attrs:{"slot":"footer"},slot:"footer"},[(_vm.remoteSDP)?_c('mu-badge',[_c('a',{attrs:{"slot":"content","href":_vm.remoteSDPURL,"download":"remoteSDP.txt"},slot:"content"},[_vm._v("remoteSDP")])]):_vm._e(),(_vm.localSDP)?_c('mu-badge',[_c('a',{attrs:{"slot":"content","href":_vm.localSDPURL,"download":"localSDP.txt"},slot:"content"},[_vm._v("localSDP")])]):_vm._e()],1)])}
var Playervue_type_template_id_6aea3512_staticRenderFns = []
// CONCATENATED MODULE: ./src/components/Player.vue?vue&type=template&id=edf62584&
// CONCATENATED MODULE: ./src/components/Player.vue?vue&type=template&id=6aea3512&
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/components/Player.vue?vue&type=script&lang=js&
//
@@ -263,19 +263,22 @@ let pc = null;
streamPath: ""
};
},
methods: {
async play(streamPath) {
pc = new RTCPeerConnection();
this.streamPath = streamPath;
pc.onsignalingstatechange = e => {
console.log(e);
//console.log(e);
};
pc.oniceconnectionstatechange = e => {
this.$toast.info(pc.iceConnectionState);
this.iceConnectionState = pc.iceConnectionState;
};
pc.onicecandidate = event => {};
const result = await this.ajax({
pc.onicecandidate = event => {
console.log(event)
};
let result = await this.ajax({
url: "/webrtc/preparePlay?streamPath=" + this.streamPath,
dataType: "json"
});
@@ -284,13 +287,12 @@ let pc = null;
return;
} else {
this.remoteSDP = result.sdp;
this.remoteSDPURL = URL.createObjectURL(
new Blob([this.remoteSDP], { type: "text/plain" })
);
this.remoteSDPURL = URL.createObjectURL(new Blob([this.remoteSDP], { type: "text/plain" }));
}
pc.ontrack = event => {
console.log(event);
if (event.streams[0].id == "monibuca") this.stream = event.streams[0];
// console.log(event);
if (event.track.kind == "video")
this.stream = event.streams[0];
};
await pc.setRemoteDescription(new RTCSessionDescription(result));
await pc.setLocalDescription(await pc.createAnswer());
@@ -301,12 +303,11 @@ let pc = null;
result = await this.ajax({
type: "POST",
processData: false,
data: JSON.stringify(pc.localDescription),
data: JSON.stringify(pc.localDescription.toJSON()),
url: "/webrtc/play?streamPath=" + this.streamPath,
dataType: "json"
});
if (result != "success") {
this.$toast.error(result.errmsg || result);
this.$toast.error(result);
}
},
onClosePreview() {
@@ -427,8 +428,8 @@ function normalizeComponent (
var component = normalizeComponent(
components_Playervue_type_script_lang_js_,
Playervue_type_template_id_edf62584_render,
Playervue_type_template_id_edf62584_staticRenderFns,
Playervue_type_template_id_6aea3512_render,
Playervue_type_template_id_6aea3512_staticRenderFns,
false,
null,
null,

File diff suppressed because one or more lines are too long

View File

@@ -230,12 +230,12 @@ var staticRenderFns = []
// CONCATENATED MODULE: ./src/App.vue?vue&type=template&id=50fea0bc&scoped=true&
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"7d106341-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/components/Player.vue?vue&type=template&id=edf62584&
var Playervue_type_template_id_edf62584_render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('Modal',_vm._g(_vm._b({attrs:{"draggable":"","title":_vm.streamPath},on:{"on-ok":_vm.onClosePreview,"on-cancel":_vm.onClosePreview}},'Modal',_vm.$attrs,false),_vm.$listeners),[_c('video',{ref:"webrtc",attrs:{"width":"488","height":"275","autoplay":"","muted":"","controls":""},domProps:{"srcObject":_vm.stream,"muted":true}}),_c('div',{attrs:{"slot":"footer"},slot:"footer"},[(_vm.remoteSDP)?_c('mu-badge',[_c('a',{attrs:{"slot":"content","href":_vm.remoteSDPURL,"download":"remoteSDP.txt"},slot:"content"},[_vm._v("remoteSDP")])]):_vm._e(),(_vm.localSDP)?_c('mu-badge',[_c('a',{attrs:{"slot":"content","href":_vm.localSDPURL,"download":"localSDP.txt"},slot:"content"},[_vm._v("localSDP")])]):_vm._e()],1)])}
var Playervue_type_template_id_edf62584_staticRenderFns = []
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"7d106341-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/components/Player.vue?vue&type=template&id=6aea3512&
var Playervue_type_template_id_6aea3512_render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('Modal',_vm._g(_vm._b({attrs:{"draggable":"","title":_vm.streamPath},on:{"on-ok":_vm.onClosePreview,"on-cancel":_vm.onClosePreview}},'Modal',_vm.$attrs,false),_vm.$listeners),[_c('video',{ref:"webrtc",attrs:{"width":"488","height":"275","autoplay":"","muted":"","controls":""},domProps:{"srcObject":_vm.stream,"muted":true}}),_c('div',{attrs:{"slot":"footer"},slot:"footer"},[(_vm.remoteSDP)?_c('mu-badge',[_c('a',{attrs:{"slot":"content","href":_vm.remoteSDPURL,"download":"remoteSDP.txt"},slot:"content"},[_vm._v("remoteSDP")])]):_vm._e(),(_vm.localSDP)?_c('mu-badge',[_c('a',{attrs:{"slot":"content","href":_vm.localSDPURL,"download":"localSDP.txt"},slot:"content"},[_vm._v("localSDP")])]):_vm._e()],1)])}
var Playervue_type_template_id_6aea3512_staticRenderFns = []
// CONCATENATED MODULE: ./src/components/Player.vue?vue&type=template&id=edf62584&
// CONCATENATED MODULE: ./src/components/Player.vue?vue&type=template&id=6aea3512&
// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/components/Player.vue?vue&type=script&lang=js&
//
@@ -272,19 +272,22 @@ let pc = null;
streamPath: ""
};
},
methods: {
async play(streamPath) {
pc = new RTCPeerConnection();
this.streamPath = streamPath;
pc.onsignalingstatechange = e => {
console.log(e);
//console.log(e);
};
pc.oniceconnectionstatechange = e => {
this.$toast.info(pc.iceConnectionState);
this.iceConnectionState = pc.iceConnectionState;
};
pc.onicecandidate = event => {};
const result = await this.ajax({
pc.onicecandidate = event => {
console.log(event)
};
let result = await this.ajax({
url: "/webrtc/preparePlay?streamPath=" + this.streamPath,
dataType: "json"
});
@@ -293,13 +296,12 @@ let pc = null;
return;
} else {
this.remoteSDP = result.sdp;
this.remoteSDPURL = URL.createObjectURL(
new Blob([this.remoteSDP], { type: "text/plain" })
);
this.remoteSDPURL = URL.createObjectURL(new Blob([this.remoteSDP], { type: "text/plain" }));
}
pc.ontrack = event => {
console.log(event);
if (event.streams[0].id == "monibuca") this.stream = event.streams[0];
// console.log(event);
if (event.track.kind == "video")
this.stream = event.streams[0];
};
await pc.setRemoteDescription(new RTCSessionDescription(result));
await pc.setLocalDescription(await pc.createAnswer());
@@ -310,12 +312,11 @@ let pc = null;
result = await this.ajax({
type: "POST",
processData: false,
data: JSON.stringify(pc.localDescription),
data: JSON.stringify(pc.localDescription.toJSON()),
url: "/webrtc/play?streamPath=" + this.streamPath,
dataType: "json"
});
if (result != "success") {
this.$toast.error(result.errmsg || result);
this.$toast.error(result);
}
},
onClosePreview() {
@@ -436,8 +437,8 @@ function normalizeComponent (
var component = normalizeComponent(
components_Playervue_type_script_lang_js_,
Playervue_type_template_id_edf62584_render,
Playervue_type_template_id_edf62584_staticRenderFns,
Playervue_type_template_id_6aea3512_render,
Playervue_type_template_id_6aea3512_staticRenderFns,
false,
null,
null,

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -32,19 +32,22 @@ export default {
streamPath: ""
};
},
methods: {
async play(streamPath) {
pc = new RTCPeerConnection();
this.streamPath = streamPath;
pc.onsignalingstatechange = e => {
console.log(e);
//console.log(e);
};
pc.oniceconnectionstatechange = e => {
this.$toast.info(pc.iceConnectionState);
this.iceConnectionState = pc.iceConnectionState;
};
pc.onicecandidate = event => {};
const result = await this.ajax({
pc.onicecandidate = event => {
console.log(event)
};
let result = await this.ajax({
url: "/webrtc/preparePlay?streamPath=" + this.streamPath,
dataType: "json"
});
@@ -53,13 +56,12 @@ export default {
return;
} else {
this.remoteSDP = result.sdp;
this.remoteSDPURL = URL.createObjectURL(
new Blob([this.remoteSDP], { type: "text/plain" })
);
this.remoteSDPURL = URL.createObjectURL(new Blob([this.remoteSDP], { type: "text/plain" }));
}
pc.ontrack = event => {
console.log(event);
if (event.streams[0].id == "monibuca") this.stream = event.streams[0];
// console.log(event);
if (event.track.kind == "video")
this.stream = event.streams[0];
};
await pc.setRemoteDescription(new RTCSessionDescription(result));
await pc.setLocalDescription(await pc.createAnswer());
@@ -70,12 +72,11 @@ export default {
result = await this.ajax({
type: "POST",
processData: false,
data: JSON.stringify(pc.localDescription),
data: JSON.stringify(pc.localDescription.toJSON()),
url: "/webrtc/play?streamPath=" + this.streamPath,
dataType: "json"
});
if (result != "success") {
this.$toast.error(result.errmsg || result);
this.$toast.error(result);
}
},
onClosePreview() {