Browse Source

add surport metaRTC p2p signaling

m7s
superxxd 2 years ago
parent
commit
83497ed972
  1. 231
      test/http.js
  2. 6
      test/jquery-1.10.2.min.js
  3. 1
      test/jquery-1.10.2.min.map
  4. 2
      test/main.html
  5. 74
      test/metaRTC.js
  6. 124
      test/miniAjax.js
  7. 10
      test/mqtt.js
  8. 12
      test/parameter.js
  9. 590
      test/srs.sdk.p2p.js
  10. 2
      test/start.js
  11. 2
      test/video.js

231
test/http.js

@ -1,207 +1,50 @@
// https://qxbjz-20210528.blog.csdn.net/article/details/101430551
// 常用工具函数
var tools = {
/* ajaxget
* @param url string 请求的路径
* @param query object 请求的参数query
* @param succCb function 请求成功之后的回调
* @param failCb function 请求失败的回调
* @param isJson boolean true 解析json false文本请求 默认值true
*/
ajaxGet: function (url, query, succCb, failCb, isJson) {
// 拼接url加query
if (query) {
var parms = tools.formatParams(query);
url += '?' + parms;
// console.log('-------------',url);
}
// 1、创建对象
var ajax = new XMLHttpRequest();
// 2、建立连接
// true:请求为异步 false:同步
ajax.open("GET", url, true);
// ajax.setRequestHeader("Origin",STATIC_PATH);
// ajax.setRequestHeader("Access-Control-Allow-Origin","*");
// // 响应类型
// ajax.setRequestHeader('Access-Control-Allow-Methods', '*');
// // 响应头设置
// ajax.setRequestHeader('Access-Control-Allow-Headers', 'x-requested-with,content-type');
// ajax.withCredentials = true;
// 3、发送请求
ajax.send(null);
// 4、监听状态的改变
ajax.onreadystatechange = function () {
if (ajax.readyState === 4) {
if (ajax.status === 200) {
// 用户传了回调才执行
// isJson默认值为true,要解析json
if (isJson === undefined) {
isJson = true;
}
var res = isJson ? JSON.parse(ajax.responseText == "" ? '{}' : ajax.responseText) : ajax.responseText;
succCb && succCb(res);
} else {
// 请求失败
failCb && failCb();
}
}
}
},
/* ajaxpost
* @param url string 请求的路径
* @param data object 请求的参数query
* @param succCb function 请求成功之后的回调
* @param failCb function 请求失败的回调
* @param isJson boolean true 解析json false文本请求 默认值true
*/
ajaxPost: function (url, data, succCb, failCb, isJson) {
var formData = new FormData();
for (var i in data) {
formData.append(i, data[i]);
}
//得到xhr对象
var xhr = null;
if (XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("post", url, true);
// 设置请求头 需在open后send前
// 这里的CSRF需自己取后端获取,下面给出获取代码
// xhr.setRequestHeader("X-CSRFToken", CSRF);
xhr.setRequestHeader('Content-Type','application/json');
xhr.send(formData);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
// 判断isJson是否传进来了
isJson = isJson === undefined ? true : isJson;
succCb && succCb(isJson ? JSON.parse(xhr.responseText) : xhr.responseText);
function ajax(){
var ajaxData = {
type:arguments[0].type || "GET",
url:arguments[0].url || "",
async:arguments[0].async || "true",
data:arguments[0].data || null,
dataType:arguments[0].dataType || "text",
contentType:arguments[0].contentType || "application/x-www-form-urlencoded",
beforeSend:arguments[0].beforeSend || function(){},
success:arguments[0].success || function(){},
error:arguments[0].error || function(){}
}
ajaxData.beforeSend()
var xhr = createxmlHttpRequest();
xhr.responseType=ajaxData.dataType;
xhr.open(ajaxData.type,ajaxData.url,ajaxData.async);
xhr.setRequestHeader("Content-Type",ajaxData.contentType);
xhr.send(convertData(ajaxData.data));
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if(xhr.status == 200){
ajaxData.success(xhr.response)
}else{
isJson = isJson === undefined ? true : isJson;
failCb && failCb(isJson ? JSON.parse(xhr.responseText) : xhr.responseText);
}
ajaxData.error()
}
}
},
formatParams: function (data) {
var arr = [];
for (var name in data) {
arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name]));
}
arr.push(("v=" + Math.random()).replace(".", ""));
return arr.join("&");
}
}
// // 调用
// // 接口地址
// let url = ""
// // 传输数据 为object
// let data = {}
// tools.ajaxGet(url, data, function(res){
// console.log('返回的数据:',res)
// // ....
// })
var Ajax = {
get: function(url,callback){
// XMLHttpRequest对象用于在后台与服务器交换数据
var xhr=new XMLHttpRequest();
xhr.open('GET',url,false);
xhr.onreadystatechange=function(){
// readyState == 4说明请求已完成
if(xhr.readyState==4){
if(xhr.status==200 || xhr.status==304){
console.log(xhr.responseText);
callback(xhr.responseText);
}
function createxmlHttpRequest() {
if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
} else if (window.XMLHttpRequest) {
return new XMLHttpRequest();
}
}
xhr.send();
},
// data应为'a=a1&b=b1'这种字符串格式,在jq里如果data为对象会自动将对象转成这种字符串格式
post: function(url,data,callback){
var xhr=new XMLHttpRequest();
xhr.open('POST',url,false);
// 添加http头,发送信息至服务器时内容编码类型
//xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); ////text/plain application/json
xhr.setRequestHeader('Content-Type','application/json');
xhr.onreadystatechange=function(){
if (xhr.readyState==4){
if (xhr.status==200 || xhr.status==304){
// console.log(xhr.responseText);
callback(xhr.responseText);
}
}
}
xhr.send(data);
function convertData(data){
if( typeof data === 'object' ){
var convertResult = "" ;
for(var c in data){
convertResult+= c + "=" + data[c] + "&";
}
}
const getJSON = function(url) {
const promise = new Promise(function(resolve, reject){
const handler = function() {
if (this.readyState !== 4) {
return;
convertResult=convertResult.substring(0,convertResult.length-1)
return convertResult;
}else{
return data;
}
if (this.status === 200) {
resolve(this.response);
} else {
reject(new Error(this.statusText));
}
};
const client = new XMLHttpRequest();
client.open("GET", url);
client.onreadystatechange = handler;
client.responseType = "json";
client.setRequestHeader("Accept", "application/json");
client.send();
});
return promise;
};
getJSON("promise.json").then(function(json) {
console.log('Data: ', json);
}, function(error) {
console.error('err', error);
});
function initXMLhttp(){
var e;
return e=window.XMLHttpRequest?new XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP")
}
function minAjax(e){
if(!e.url)return
void(1==e.debugLog&&console.log("No Url!"));
if(!e.type)return
void(1==e.debugLog&&console.log("No Default type (GET/POST) given!"));
e.method||(e.method=!0),e.debugLog||(e.debugLog=!1);
var o=initXMLhttp();
o.onreadystatechange=function(){
4==o.readyState&&200==o.status?(e.success&&e.success(o.responseText,o.readyState),1==e.debugLog&&console.log("SuccessResponse"),1==e.debugLog&&console.log("Response Data:"+o.responseText)):1==e.debugLog&&console.log("FailureResponse --> State:"+o.readyState+"Status:"+o.status)
};
var t=[],n=e.data;
if("string"==typeof n)for(var s=String.prototype.split.call(n,"&"),r=0,a=s.length;a>r;r++){var c=s[r].split("=");t.push(encodeURIComponent(c[0])+"="+encodeURIComponent(c[1]))}else if("object"==typeof n&&!(n instanceof String||FormData&&n instanceof FormData))for(var p in n){var c=n[p];if("[object Array]"==Object.prototype.toString.call(c))for(var r=0,a=c.length;a>r;r++)t.push(encodeURIComponent(p)+"[]="+encodeURIComponent(c[r]));else t.push(encodeURIComponent(p)+"="+encodeURIComponent(c))}t=t.join("&"),"GET"==e.type&&(o.open("GET",e.url+"?"+t,e.method),o.send(),1==e.debugLog&&console.log("GET fired at:"+e.url+"?"+t)),"POST"==e.type&&(o.open("POST",e.url,e.method),o.setRequestHeader("Content-type","application/x-www-form-urlencoded"),o.send(t),1==e.debugLog&&console.log("POST fired at:"+e.url+" || Data:"+t))}

6
test/jquery-1.10.2.min.js

File diff suppressed because one or more lines are too long

1
test/jquery-1.10.2.min.map

File diff suppressed because one or more lines are too long

2
test/main.html

@ -35,7 +35,7 @@
<option value="ws">WS</option>
<option value="httpFlv">HTTP-FLV</option>
</select>
<input type="text" id="inputUrl" value="webrtc://192.168.0.4:1988/live/livestream" style="width:300px"/>
<input type="text" id="inputUrl" value="webrtc://192.168.0.18:1988/live/livestream" style="width:300px"/>
设 备 名 称: <input type="text" name="devicename" id="deviceId" value="4E:7B:BF:71:D6:B4" style="width:100px"/>
拉 流 名 称: <input type="text" name="streamname" id="streamId" value="metartc" style="width:100px"/>
</div>

74
test/metaRTC.js

@ -134,33 +134,28 @@
}
}
};
function StartMetaRTC(url,player){
var datachannel=null;
function StartMetaRTC(url){
var conf = __internal.prepareUrl(url);
pc = new RTCPeerConnection({
iceServers: ICEServerkvm,//ICEServer
iceServers: ICEServermetaRTC
});
if(bVideo) {
if(bAudio) {
const { receivervideo } = pc.addTransceiver('video', { direction: 'recvonly' });
const { receiveraudio } = pc.addTransceiver('audio', { direction: 'recvonly' });
OnTrack(pc)
}
if(bAudio) {
if(bVideo) {
const { receiveraudio } = pc.addTransceiver('audio', { direction: 'recvonly' });
const { receivervideo } = pc.addTransceiver('video', { direction: 'recvonly' });
OnTrack(pc)
}
// Populate SDP field when finished gathering
pc.oniceconnectionstatechange = e => {
log(pc.iceConnectionState)
var state ={
t: kconnectStatusResponse,
s: pc.connectionState
}
player.postMessage(state)
}
pc.onicecandidate = event => {
@ -171,32 +166,41 @@ pc.onicecandidate = event => {
clientip: null, sdp: offer.sdp
};
console.log("Generated offer: ", data);
Ajax.post(conf.apiUrl, offer.sdp+"}", function(res){
console.log('返回的数据:',res)
pc.setRemoteDescription(new RTCSessionDescription({type: 'answer', sdp: res.sdp}));
// await self.pc.setRemoteDescription(
// new RTCSessionDescription({type: 'answer', sdp: session.sdp})
// );
// ....
})
// ajax({
// type: "POST", url: conf.apiUrl, data: offer.sdp+"}",
// contentType:'text/plain', dataType: 'json',
// crossDomain:true
// }).done(function(data) {
// if (data.code) {
// reject(data); return;
// }
// console.log("Got sdp: ", data.sdp);
// resolve(data);
ajax({
type:"POST",
url:conf.apiUrl,
dataType:"json",
data:offer.sdp+"}",
beforeSend:function(){
//some js code
},
success:function(msg){
console.log(msg)
pc.setRemoteDescription(new RTCSessionDescription({type: 'answer', sdp: msg.sdp}));
},
error:function(){
console.log("error")
}
})
// }).fail(function(reason){
// reject(reason);
// });
}
}
datachannel=self.pc.createDataChannel('chat');
datachannel.onopen = function(event) {
console.log("datachannel onopen: ", event);
}
datachannel.onmessage = function(event) {
console.log("receive message: ", event.data);
// $('#datachannel_recv').val(event.data);
}
datachannel.onerror=function(event) {
console.log("datachannel error: ", event.data);
}
datachannel.onclose=function(event) {
console.log("datachannel close: ");
}
pc.createOffer().then(d => pc.setLocalDescription(d)).catch(log)
}

124
test/miniAjax.js

@ -1,124 +0,0 @@
/*|--minAjax.js--|
|--(A Minimalistic Pure JavaScript Header for Ajax POST/GET Request )--|
|--Author : flouthoc (gunnerar7@gmail.com)(http://github.com/flouthoc)--|
|--Contributers : Add Your Name Below--|
*/
function initXMLhttp() {
var xmlhttp;
if (window.XMLHttpRequest) {
//code for IE7,firefox chrome and above
xmlhttp = new XMLHttpRequest();
} else {
//code for Internet Explorer
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlhttp;
}
function minAjax(config) {
/*Config Structure
url:"reqesting URL"
type:"GET or POST"
method: "(OPTIONAL) True for async and False for Non-async | By default its Async"
debugLog: "(OPTIONAL)To display Debug Logs | By default it is false"
data: "(OPTIONAL) another Nested Object which should contains reqested Properties in form of Object Properties"
success: "(OPTIONAL) Callback function to process after response | function(data,status)"
*/
if (!config.url) {
if (config.debugLog == true)
console.log("No Url!");
return;
}
if (!config.type) {
if (config.debugLog == true)
console.log("No Default type (GET/POST) given!");
return;
}
if (!config.method) {
config.method = true;
}
if (!config.debugLog) {
config.debugLog = false;
}
var xmlhttp = initXMLhttp();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
if (config.success) {
config.success(xmlhttp.responseText, xmlhttp.readyState);
}
if (config.debugLog == true)
console.log("SuccessResponse");
if (config.debugLog == true)
console.log("Response Data:" + xmlhttp.responseText);
} else {
if (config.debugLog == true)
console.log("FailureResponse --> State:" + xmlhttp.readyState + "Status:" + xmlhttp.status);
if(config.errorCallback){
console.log("Calling Error Callback");
config.errorCallback();
}
}
}
var sendString = [],
sendData = config.data;
if( typeof sendData === "string" ){
var tmpArr = String.prototype.split.call(sendData,'&');
for(var i = 0, j = tmpArr.length; i < j; i++){
var datum = tmpArr[i].split('=');
sendString.push(encodeURIComponent(datum[0]) + "=" + encodeURIComponent(datum[1]));
}
}else if( typeof sendData === 'object' && !( sendData instanceof String || (FormData && sendData instanceof FormData) ) ){
for (var k in sendData) {
var datum = sendData[k];
if( Object.prototype.toString.call(datum) == "[object Array]" ){
for(var i = 0, j = datum.length; i < j; i++) {
sendString.push(encodeURIComponent(k) + "[]=" + encodeURIComponent(datum[i]));
}
}else{
sendString.push(encodeURIComponent(k) + "=" + encodeURIComponent(datum));
}
}
}
sendString = sendString.join('&');
if (config.type == "GET") {
xmlhttp.open("GET", config.url + "?" + sendString, config.method);
xmlhttp.send();
if (config.debugLog == true)
console.log("GET fired at:" + config.url + "?" + sendString);
}
if (config.type == "POST") {
xmlhttp.open("POST", config.url, config.method);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(sendString);
if (config.debugLog == true)
console.log("POST fired at:" + config.url + " || Data:" + sendString);
}
}

10
test/mqtt.js

@ -28,6 +28,11 @@ function getStreamWebrtc(player) {
iceServers: ICEServerkvm,//ICEServer
});
// initH265Transfer(pc,player);
if(bAudio) {
// initAudioDC(pc);
const { receiveraudio } = pc.addTransceiver('audio', { direction: 'recvonly' });
OnTrack(pc)
}
if(bVideo) {
if(!bDecodeH264){
initH265DC(pc,player);
@ -35,11 +40,6 @@ function getStreamWebrtc(player) {
const { receivervideo } = pc.addTransceiver('video', { direction: 'recvonly' });
OnTrack(pc)
}
}
if(bAudio) {
// initAudioDC(pc);
const { receiveraudio } = pc.addTransceiver('audio', { direction: 'recvonly' });
OnTrack(pc)
}
// Populate SDP field when finished gathering
pc.oniceconnectionstatechange = e => {

12
test/parameter.js

@ -91,3 +91,15 @@ var ICEServerkvm = [
credential: "123456"
}
];
var ICEServermetaRTC = [
{
//urls:["stun:stun.l.google.com:19302"]
urls: ["stun:192.168.0.18:3478"]
//urls: ["stun:192.168.0.20:3478"]
}, {
urls: ["turn:192.168.0.18:3478"],
//urls: ["turn:192.168.0.20:3478"],
username: "media",
credential: "123456"
}
];

590
test/srs.sdk.p2p.js

@ -1,590 +0,0 @@
//
// Copyright (c) 2013-2021 Winlin
//
// SPDX-License-Identifier: MIT
//
'use strict';
// Depends on adapter-7.4.0.min.js from https://github.com/webrtc/adapter
// Async-awat-prmise based SRS RTC Publisher.
function SrsRtcPublisherAsync() {
var self = {};
// https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia
self.constraints = {
audio: true,
video: {
width: {ideal: 320, max: 576}
}
};
// @see https://github.com/rtcdn/rtcdn-draft
// @url The WebRTC url to play with, for example:
// webrtc://r.ossrs.net/live/livestream
// or specifies the API port:
// webrtc://r.ossrs.net:11985/live/livestream
// or autostart the publish:
// webrtc://r.ossrs.net/live/livestream?autostart=true
// or change the app from live to myapp:
// webrtc://r.ossrs.net:11985/myapp/livestream
// or change the stream from livestream to mystream:
// webrtc://r.ossrs.net:11985/live/mystream
// or set the api server to myapi.domain.com:
// webrtc://myapi.domain.com/live/livestream
// or set the candidate(eip) of answer:
// webrtc://r.ossrs.net/live/livestream?candidate=39.107.238.185
// or force to access https API:
// webrtc://r.ossrs.net/live/livestream?schema=https
// or use plaintext, without SRTP:
// webrtc://r.ossrs.net/live/livestream?encrypt=false
// or any other information, will pass-by in the query:
// webrtc://r.ossrs.net/live/livestream?vhost=xxx
// webrtc://r.ossrs.net/live/livestream?token=xxx
self.publish = async function (url) {
var conf = self.__internal.prepareUrl(url);
self.pc.addTransceiver("audio", {direction: "sendonly"});
self.pc.addTransceiver("video", {direction: "sendonly"});
var stream = await navigator.mediaDevices.getUserMedia(self.constraints);
// @see https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/addStream#Migrating_to_addTrack
stream.getTracks().forEach(function (track) {
self.pc.addTrack(track);
// Notify about local track when stream is ok.
self.ontrack && self.ontrack({track: track});
});
var offer = await self.pc.createOffer();
await self.pc.setLocalDescription(offer);
var session = await new Promise(function (resolve, reject) {
// @see https://github.com/rtcdn/rtcdn-draft
var data = {
api: conf.apiUrl, tid: conf.tid, streamurl: conf.streamUrl,
clientip: null, sdp: offer.sdp
};
console.log("Generated offer: ", data);
$.ajax({
type: "POST", url: conf.apiUrl, data: JSON.stringify(data),
contentType: 'application/json', dataType: 'json'
}).done(function (data) {
console.log("Got answer: ", data);
if (data.code) {
reject(data);
return;
}
resolve(data);
}).fail(function (reason) {
reject(reason);
});
});
await self.pc.setRemoteDescription(
new RTCSessionDescription({type: 'answer', sdp: session.sdp})
);
session.simulator = conf.schema + '//' + conf.urlObject.server + ':' + conf.port + '/rtc/v1/nack/';
return session;
};
// Close the publisher.
self.close = function () {
self.pc && self.pc.close();
self.pc = null;
};
// The callback when got local stream.
// @see https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/addStream#Migrating_to_addTrack
self.ontrack = function (event) {
// Add track to stream of SDK.
// self.stream.addTrack(event.track);
console.log("ontrack", event.track.kind)
var el = document.createElement(event.track.kind);
el.srcObject = event.streams[0];
el.autoplay = true;
// document.getElementById("remote-video").appendChild(el);
el.controls = false; // 显示
};
// Internal APIs.
self.__internal = {
defaultPath: '/rtc/v1/publish/',
prepareUrl: function (webrtcUrl) {
var urlObject = self.__internal.parse(webrtcUrl);
// If user specifies the schema, use it as API schema.
var schema = urlObject.user_query.schema;
schema = schema ? schema + ':' : window.location.protocol;
var port = urlObject.port || 1985;
if (schema === 'https:') {
port = urlObject.port || 443;
}
// @see https://github.com/rtcdn/rtcdn-draft
var api = urlObject.user_query.play || self.__internal.defaultPath;
if (api.lastIndexOf('/') !== api.length - 1) {
api += '/';
}
apiUrl = schema + '//' + urlObject.server + ':' + port + api;
for (var key in urlObject.user_query) {
if (key !== 'api' && key !== 'play') {
apiUrl += '&' + key + '=' + urlObject.user_query[key];
}
}
// Replace /rtc/v1/play/&k=v to /rtc/v1/play/?k=v
var apiUrl = apiUrl.replace(api + '&', api + '?');
var streamUrl = urlObject.url;
return {
apiUrl: apiUrl, streamUrl: streamUrl, schema: schema, urlObject: urlObject, port: port,
tid: Number(parseInt(new Date().getTime()*Math.random()*100)).toString(16).substr(0, 7)
};
},
parse: function (url) {
// @see: http://stackoverflow.com/questions/10469575/how-to-use-location-object-to-parse-url-without-redirecting-the-page-in-javascri
var a = document.createElement("a");
a.href = url.replace("rtmp://", "http://")
.replace("webrtc://", "http://")
.replace("rtc://", "http://");
var vhost = a.hostname;
var app = a.pathname.substr(1, a.pathname.lastIndexOf("/") - 1);
var stream = a.pathname.substr(a.pathname.lastIndexOf("/") + 1);
// parse the vhost in the params of app, that srs supports.
app = app.replace("...vhost...", "?vhost=");
if (app.indexOf("?") >= 0) {
var params = app.substr(app.indexOf("?"));
app = app.substr(0, app.indexOf("?"));
if (params.indexOf("vhost=") > 0) {
vhost = params.substr(params.indexOf("vhost=") + "vhost=".length);
if (vhost.indexOf("&") > 0) {
vhost = vhost.substr(0, vhost.indexOf("&"));
}
}
}
// when vhost equals to server, and server is ip,
// the vhost is __defaultVhost__
if (a.hostname === vhost) {
var re = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/;
if (re.test(a.hostname)) {
vhost = "__defaultVhost__";
}
}
// parse the schema
var schema = "rtmp";
if (url.indexOf("://") > 0) {
schema = url.substr(0, url.indexOf("://"));
}
var port = a.port;
if (!port) {
if (schema === 'http') {
port = 80;
} else if (schema === 'https') {
port = 443;
} else if (schema === 'rtmp') {
port = 1935;
}
}
var ret = {
url: url,
schema: schema,
server: a.hostname, port: port,
vhost: vhost, app: app, stream: stream
};
self.__internal.fill_query(a.search, ret);
// For webrtc API, we use 443 if page is https, or schema specified it.
if (!ret.port) {
if (schema === 'webrtc' || schema === 'rtc') {
if (ret.user_query.schema === 'https') {
ret.port = 443;
} else if (window.location.href.indexOf('https://') === 0) {
ret.port = 443;
} else {
// For WebRTC, SRS use 1985 as default API port.
ret.port = 1985;
}
}
}
return ret;
},
fill_query: function (query_string, obj) {
// pure user query object.
obj.user_query = {};
if (query_string.length === 0) {
return;
}
// split again for angularjs.
if (query_string.indexOf("?") >= 0) {
query_string = query_string.split("?")[1];
}
var queries = query_string.split("&");
for (var i = 0; i < queries.length; i++) {
var elem = queries[i];
var query = elem.split("=");
obj[query[0]] = query[1];
obj.user_query[query[0]] = query[1];
}
// alias domain for vhost.
if (obj.domain) {
obj.vhost = obj.domain;
}
}
};
self.pc = new RTCPeerConnection(null);
// To keep api consistent between player and publisher.
// @see https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/addStream#Migrating_to_addTrack
// @see https://webrtc.org/getting-started/media-devices
self.stream = new MediaStream();
return self;
}
var datachannel=null;
// Depends on adapter-7.4.0.min.js from https://github.com/webrtc/adapter
// Async-await-promise based SRS RTC Player.
function SrsRtcPlayerAsync() {
var self = {};
/**
const config = {
bundlePolicy: 'balanced',
// certificates?: RTCCertificate[];
// iceCandidatePoolSize?: number;
iceTransportPolicy: "relay",// all
rtcpMuxPolicy : 'negotiate',
iceServers: [
{
urls: "turn:192.168.1.102:3478",
username: "metartc",
credential: "metartc"
}
]
};
self.pc = new RTCPeerConnection(config);
* */
self.pc = new RTCPeerConnection(null);
self.pc.onconnectionstatechange=function(event){
console.log("connection state change: ", self.pc.connectionState);
}
self.pc.onicecandidate = async (ev) => {
console.log('=======>' + JSON.stringify(ev.candidate));
};
datachannel=self.pc.createDataChannel('chat');
datachannel.onopen = function(event) {
console.log("datachannel onopen: ", event.data);
}
datachannel.onmessage = function(event) {
console.log("receive message: ", event.data);
// $('#datachannel_recv').val(event.data);
}
datachannel.onerror=function(event) {
console.log("datachannel error: ", event.data);
}
datachannel.onclose=function(event) {
console.log("datachannel close: ");
}
// @see https://github.com/rtcdn/rtcdn-draft
// @url The WebRTC url to play with, for example:
// webrtc://r.ossrs.net/live/livestream
// or specifies the API port:
// webrtc://r.ossrs.net:11985/live/livestream
// or autostart the play:
// webrtc://r.ossrs.net/live/livestream?autostart=true
// or change the app from live to myapp:
// webrtc://r.ossrs.net:11985/myapp/livestream
// or change the stream from livestream to mystream:
// webrtc://r.ossrs.net:11985/live/mystream
// or set the api server to myapi.domain.com:
// webrtc://myapi.domain.com/live/livestream
// or set the candidate(eip) of answer:
// webrtc://r.ossrs.net/live/livestream?candidate=39.107.238.185
// or force to access https API:
// webrtc://r.ossrs.net/live/livestream?schema=https
// or use plaintext, without SRTP:
// webrtc://r.ossrs.net/live/livestream?encrypt=false
// or any other information, will pass-by in the query:
// webrtc://r.ossrs.net/live/livestream?vhost=xxx
// webrtc://r.ossrs.net/live/livestream?token=xxx
self.play = async function(url) {
var conf = self.__internal.prepareUrl(url);
console.log("conf.apiUrl: ", conf.apiUrl);
self.pc.addTransceiver("audio", {direction: "recvonly"});
self.pc.addTransceiver("video", {direction: "recvonly"});
var offer = await self.pc.createOffer();
await self.pc.setLocalDescription(offer);
var session = await new Promise(function(resolve, reject) {
// @see https://github.com/rtcdn/rtcdn-draft
var data = {
api: conf.apiUrl, tid: conf.tid, streamurl: conf.streamUrl,
clientip: null, sdp: offer.sdp
};
console.log("Generated offer: ", data);
//text/plain application/json
// tools.ajaxPost(conf.apiUrl, offer.sdp+"}", function(res){
// console.log('返回的数据:',res)
// if (res.code) {
// reject(daresta); return;
// }
// console.log("Got sdp: ", res.sdp);
// resolve(res);
// })
// let data = {
// data: offer.sdp+"}"
// }
// Ajax.post(conf.apiUrl, data, function(res){
// console.log('返回的数据:',res)
// // ....
// })
// $.ajax({
// type: "POST", url: conf.apiUrl, data: offer.sdp+"}",
// contentType:'text/plain', dataType: 'json',
// crossDomain:true
// }).done(function(data) {
// if (data.code) {
// reject(data); return;
// }
// console.log("Got sdp: ", data.sdp);
// resolve(data);
// }).fail(function(reason){
// reject(reason);
// });
});
await self.pc.setRemoteDescription(
new RTCSessionDescription({type: 'answer', sdp: session.sdp})
);
session.simulator = conf.schema + '//' + conf.urlObject.server + ':' + conf.port + '/rtc/v1/nack/';
return session;
};
// Close the player.
self.close = function() {
if(datachannel) {
datachannel.close();
datachannel=null;
}
self.pc && self.pc.close();
self.pc = null;
};
// The callback when got remote track.
// Note that the onaddstream is deprecated, @see https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/onaddstream
self.ontrack = function (event) {
// https://webrtc.org/getting-started/remote-streams
self.stream.addTrack(event.track);
};
// Internal APIs.
self.__internal = {
defaultPath: '/rtc/v1/play/',
prepareUrl: function (webrtcUrl) {
var urlObject = self.__internal.parse(webrtcUrl);
var schema="http:";
var port = urlObject.port || 1985;
if (schema === 'https:') {
port = urlObject.port || 443;
}
// @see https://github.com/rtcdn/rtcdn-draft
var api = urlObject.user_query.play || self.__internal.defaultPath;
if (api.lastIndexOf('/') !== api.length - 1) {
api += '/';
}
apiUrl = schema + '//' + urlObject.server + ':' + port + api;
for (var key in urlObject.user_query) {
if (key !== 'api' && key !== 'play') {
apiUrl += '&' + key + '=' + urlObject.user_query[key];
}
}
// Replace /rtc/v1/play/&k=v to /rtc/v1/play/?k=v
var apiUrl = apiUrl.replace(api + '&', api + '?');
var streamUrl = urlObject.url;
return {
apiUrl: apiUrl, streamUrl: streamUrl, schema: schema, urlObject: urlObject, port: port,
tid: Number(parseInt(new Date().getTime()*Math.random()*100)).toString(16).substr(0, 7)
};
},
parse: function (url) {
// @see: http://stackoverflow.com/questions/10469575/how-to-use-location-object-to-parse-url-without-redirecting-the-page-in-javascri
var a = document.createElement("a");
a.href = url.replace("rtmp://", "http://")
.replace("webrtc://", "http://")
.replace("rtc://", "http://");
var vhost = a.hostname;
var app = a.pathname.substr(1, a.pathname.lastIndexOf("/") - 1);
var stream = a.pathname.substr(a.pathname.lastIndexOf("/") + 1);
// parse the vhost in the params of app, that srs supports.
app = app.replace("...vhost...", "?vhost=");
if (app.indexOf("?") >= 0) {
var params = app.substr(app.indexOf("?"));
app = app.substr(0, app.indexOf("?"));
if (params.indexOf("vhost=") > 0) {
vhost = params.substr(params.indexOf("vhost=") + "vhost=".length);
if (vhost.indexOf("&") > 0) {
vhost = vhost.substr(0, vhost.indexOf("&"));
}
}
}
// when vhost equals to server, and server is ip,
// the vhost is __defaultVhost__
if (a.hostname === vhost) {
var re = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/;
if (re.test(a.hostname)) {
vhost = "__defaultVhost__";
}
}
// parse the schema
var schema = "rtmp";
if (url.indexOf("://") > 0) {
schema = url.substr(0, url.indexOf("://"));
}
var port = a.port;
if (!port) {
if (schema === 'http') {
port = 80;
} else if (schema === 'https') {
port = 443;
} else if (schema === 'rtmp') {
port = 1935;
}
}
var ret = {
url: url,
schema: schema,
server: a.hostname, port: port,
vhost: vhost, app: app, stream: stream
};
self.__internal.fill_query(a.search, ret);
// For webrtc API, we use 443 if page is https, or schema specified it.
if (!ret.port) {
if (schema === 'webrtc' || schema === 'rtc') {
if (ret.user_query.schema === 'https') {
ret.port = 443;
} else if (window.location.href.indexOf('https://') === 0) {
ret.port = 443;
} else {
// For WebRTC, SRS use 1985 as default API port.
ret.port = 1985;
}
}
}
return ret;
},
fill_query: function (query_string, obj) {
// pure user query object.
obj.user_query = {};
if (query_string.length === 0) {
return;
}
// split again for angularjs.
if (query_string.indexOf("?") >= 0) {
query_string = query_string.split("?")[1];
}
var queries = query_string.split("&");
for (var i = 0; i < queries.length; i++) {
var elem = queries[i];
var query = elem.split("=");
obj[query[0]] = query[1];
obj.user_query[query[0]] = query[1];
}
// alias domain for vhost.
if (obj.domain) {
obj.vhost = obj.domain;
}
}
};
// Create a stream to add track to the stream, @see https://webrtc.org/getting-started/remote-streams
self.stream = new MediaStream();
// https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/ontrack
self.pc.ontrack = function(event) {
if (self.ontrack) {
self.ontrack(event);
}
};
return self;
}
// Format the codec of RTCRtpSender, kind(audio/video) is optional filter.
// https://developer.mozilla.org/en-US/docs/Web/Media/Formats/WebRTC_codecs#getting_the_supported_codecs
function SrsRtcFormatSenders(senders, kind) {
var codecs = [];
senders.forEach(function (sender) {
var params = sender.getParameters();
params && params.codecs && params.codecs.forEach(function(c) {
if (kind && sender.track.kind !== kind) {
return;
}
if (c.mimeType.indexOf('/red') > 0 || c.mimeType.indexOf('/rtx') > 0 || c.mimeType.indexOf('/fec') > 0) {
return;
}
var s = '';
s += c.mimeType.replace('audio/', '').replace('video/', '');
s += ', ' + c.clockRate + 'HZ';
if (sender.track.kind === "audio") {
s += ', channels: ' + c.channels;
}
s += ', pt: ' + c.payloadType;
codecs.push(s);
});
});
return codecs.join(", ");
}

2
test/start.js

@ -17,7 +17,7 @@ importScripts("./audiodc.js")
importScripts("./h265dc.js")
importScripts("https://cdn.bootcdn.net/ajax/libs/mqtt/2.18.8/mqtt.min.js")
importScripts("adapter-7.4.0.min.js")
importScripts("srs.sdk.p2p.js")
// importScripts("srs.sdk.p2p.js")
importScripts("http.js")
importScripts("metaRTC.js")
// importScripts("miniAjax.js")

2
test/video.js

@ -10,7 +10,7 @@ function startPlay(url) {
alert("url is null")
return;
}
StartMetaRTC(url,player)
StartMetaRTC(url)
// // Close PC when user replay.
// if (sdk) {
// sdk.close();

Loading…
Cancel
Save